VirtualBox

Changeset 3140 in kBuild


Ignore:
Timestamp:
Mar 14, 2018 9:28:10 PM (7 years ago)
Author:
bird
Message:

kmk: Merged in changes from GNU make 4.2.1 (2e55f5e4abdc0e38c1d64be703b446695e70b3b6 / https://git.savannah.gnu.org/git/make.git).

Location:
trunk/src
Files:
7 deleted
182 edited
49 copied
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/src/kmk

  • trunk/src/kmk/AUTHORS

    r2591 r3140  
    3838      DJ Delorie <[email protected]>
    3939      Rob Tulloh <[email protected]>
    40       Eli Zaretskii <eliz@is.elta.co.il>
     40      Eli Zaretskii <eliz@gnu.org>
    4141      Jonathan Grant <[email protected]>
    4242      Andreas Beuning <[email protected]>
    4343      Earnie Boyd <[email protected]>
     44      Troy Runkel <[email protected]>
    4445
    4546-----------------------------------
     
    4849  Janet Carson <[email protected]>
    4950  Howard Chu <[email protected]>
     51  Ludovic Courtès <[email protected]>
    5052  Paul Eggert <[email protected]>
     53  Ramon Garcia Fernandez <[email protected]>
    5154  Klaus Heinz <[email protected]>
    5255  Michael Joosten
     
    5659  Markus Mauhart <[email protected]>
    5760  Greg McGary <[email protected]>
     61  Thien-Thi Nguyen <[email protected]>
    5862  Thomas Riedl <[email protected]>
    5963  Han-Wen Nienhuys <[email protected]>
     
    6165  Carl Staelin (Princeton University)
    6266  Ian Stewartson (Data Logic Limited)
    63   Ramon Garcia Fernandez <[email protected]>
     67  David A. Wheeler <[email protected]>
     68  David Boyce <[email protected]>
     69  Frank Heckenbach <[email protected]>
    6470
    6571With suggestions/comments/bug reports from a cast of ... well ...
     
    6773
    6874-------------------------------------------------------------------------------
    69 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
    70 2008, 2009, 2010 Free Software Foundation, Inc.
     75Copyright (C) 1997-2016 Free Software Foundation, Inc.
    7176This file is part of GNU Make.
    7277
  • trunk/src/kmk/ChangeLog.1

    r2591 r3140  
    17041704
    17051705        * load.c: Use the symbol KERNEL_FILE_NAME instead of KERNEL_FILE.
    1706         * compatMakefile: Changed the comment for `LOAD_AVG' accordinly.
     1706        * compatMakefile: Changed the comment for `LOAD_AVG' accordingly.
    17071707
    17081708Thu Sep  7 16:46:26 1989  Roland McGrath  (mcgrath at paris.Berkeley.EDU)
     
    32193219        `shell_function_completed'.  Block children before forking and
    32203220        unblock after `shell_function_pid' is set properly and
    3221         `shell_functon_completed' is reset to 0.
     3221        `shell_function_completed' is reset to 0.
    32223222
    32233223        * commands.c (child_handler): When the child of the `shell' function
     
    44664466
    44674467        * rule.c (pattern_search): If an existent (non-intermediate)
    4468         dependendency was found via a terminal rule, set its
     4468        dependency was found via a terminal rule, set its
    44694469        `tried_implicit' flag, so it will never have implicit rule search done.
    44704470
     
    48274827
    48284828        * dir.c: Re-indented the `struct dir' definition to be right.
    4829         (dir_load): Cleaned up slighty.
     4829        (dir_load): Cleaned up slightly.
    48304830        (file_exists_p): Removed comment saying we could use `access', since
    48314831        that is a bad idea (except for setuid programs).  Cleaned up slightly.
     
    49834983
    49844984
    4985 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    4986 1998, 1999, 2000, 2001, 2002, 2003, 2005, 2006, 2007, 2008, 2009 Free
    4987 Software Foundation, Inc.
     4985Copyright (C) 1988-2009 Free Software Foundation, Inc.
    49884986This file is part of GNU Make.
    49894987
  • trunk/src/kmk/ChangeLog.2

    r1993 r3140  
    30813081        stores now the names of the variables only and reads their contents
    30823082        when they are accessed to reflect that these variables are really
    3083         global (ie. they CAN change WHILE make runs !) This handling is
     3083        global (i.e., they CAN change WHILE make runs !) This handling is
    30843084        made in lookup_variable()
    30853085
     
    66326632
    66336633
    6634 See ChangeLog.1, available in the CVS repository at:
    6635 
    6636         http://savannah.gnu.org/cvs/?group=make
     6634See ChangeLog.1, available in the Git repository at:
     6635
     6636        http://git.savannah.gnu.org/cgit/make.git/tree/
    66376637
    66386638for earlier changes.
    66396639
    66406640
    6641 Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
    6642 2001, 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc.
     6641Copyright (C) 1991-2007 Free Software Foundation, Inc.
    66436642This file is part of GNU Make.
    66446643
  • trunk/src/kmk/Makefile.DOS.template

    r2591 r3140  
    22# Makefile.in generated automatically by automake 1.2 from Makefile.am
    33#
    4 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
    5 # 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     4# Copyright (C) 1994-2016 Free Software Foundation, Inc.
    65# This file is part of GNU Make.
    76#
     
    9089BUILT_SOURCES = README build.sh-in
    9190
    92 EXTRA_DIST =    $(BUILT_SOURCES) $(man_MANS) README.customs remote-cstms.c  make-stds.texi texinfo.tex SCOPTIONS SMakefile  Makefile.ami README.Amiga config.ami amiga.c amiga.h  NMakefile README.DOS configh.dos configure.bat makefile.com  README.W32 build_w32.bat config.h-W32 subproc.bat make.lnk  config.h-vms makefile.vms readme.vms vmsdir.h vmsfunctions.c  vmsify.c
     91EXTRA_DIST =    $(BUILT_SOURCES) $(man_MANS) README.customs remote-cstms.c  make-stds.texi texinfo.tex SCOPTIONS SMakefile  Makefile.ami README.Amiga config.ami amiga.c amiga.h  NMakefile README.DOS configh.dos configure.bat makefile.com  README.W32 build_w32.bat config.h-W32 subproc.bat make.lnk  config.h-vms makefile.vms README.VMS vmsdir.h vmsfunctions.c  vmsify.c gmk-default.scm gmk-default.h
    9392
    9493SUBDIRS =       glob doc
     
    124123
    125124NROFF = nroff
    126 DIST_COMMON =  README ABOUT-NLS AUTHORS COPYING ChangeLog INSTALL Makefile.am  Makefile.in NEWS acconfig.h aclocal.m4 alloca.c build.sh-in config.h-in  configure configure.in getloadavg.c
     125DIST_COMMON =  README ABOUT-NLS AUTHORS COPYING ChangeLog INSTALL Makefile.am  Makefile.in NEWS acconfig.h aclocal.m4 alloca.c build.sh-in config.h-in  configure configure.ac getloadavg.c
    127126
    128127DISTFILES = $(DIST_COMMON) $(SOURCES) $(HEADERS) $(TEXINFOS) $(EXTRA_DIST)
     
    508507dist-hook:
    509508        (cd $(srcdir); \
    510          w32=`find w32 -follow \( -name CVS -prune \) -o -type f -print`; \
     509         w32=`find w32 -follow \( -name .git -prune \) -o -type f -print`; \
    511510         tar chf - $$w32) \
    512511        | (cd $(distdir); tar xfBp -)
  • trunk/src/kmk/Makefile.am

    r3114 r3140  
    11# This is a -*-Makefile-*-, or close enough
    22#
    3 # Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    4 # 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     3# Copyright (C) 1997-2016 Free Software Foundation, Inc.
    54# This file is part of GNU Make.
    65#
     
    1817# this program.  If not, see <http://www.gnu.org/licenses/>.
    1918
    20 AUTOMAKE_OPTIONS = 1.8 dist-bzip2 check-news
    21 ACLOCAL_AMFLAGS = -I config
     19AUTOMAKE_OPTIONS = dist-bzip2 silent-rules std-options
     20ACLOCAL_AMFLAGS = -I config
    2221
    2322MAKE_HOST =     @MAKE_HOST@
     
    2827  W32INC =      -I $(top_srcdir)/w32/include
    2928  W32LIB =      -Lw32 -lw32
     29  ossrc =
     30else
     31  ossrc =       posixos.c
    3032endif
    3133
     
    3537
    3638bin_PROGRAMS =  kmk kmk_redirect
     39include_HEADERS = gnumake.h
    3740
    3841if USE_CUSTOMS
     
    4245endif
    4346
    44 
    4547kmk_SOURCES =   ar.c arscan.c commands.c default.c dir.c expand.c file.c \
    46                 function.c getopt.c getopt1.c implicit.c job.c main.c \
    47                 misc.c read.c remake.c $(remote) rule.c signame.c \
    48                 strcache.c variable.c version.c vpath.c hash.c \
     48                function.c getopt.c getopt1.c guile.c implicit.c job.c load.c \
     49                loadapi.c main.c misc.c $(ossrc) output.c read.c remake.c \
     50                rule.c signame.c strcache.c variable.c version.c vpath.c \
     51                hash.c $(remote) \
    4952                \
    5053                expreval.c \
     
    101104kmk_redirect_CFLAGS = -UKMK
    102105
    103 
    104106EXTRA_kmk_SOURCES = vmsjobs.c remote-stub.c remote-cstms.c
    105107
    106 noinst_HEADERS = commands.h dep.h filedef.h job.h make.h rule.h variable.h \
    107                 debug.h getopt.h gettext.h hash.h
     108noinst_HEADERS = commands.h dep.h filedef.h job.h makeint.h rule.h variable.h \
     109                debug.h getopt.h gettext.h hash.h output.h os.h
    108110
    109111#kmk_LDADD =    @LIBOBJS@ @ALLOCA@ $(GLOBLIB) @GETLOADAVG_LIBS@ @LIBINTL@
    110 kmk_LDADD =     @LIBOBJS@ @ALLOCA@ $(GLOBLIB) @GETLOADAVG_LIBS@
     112kmk_LDADD =     @LIBOBJS@ @ALLOCA@ $(GLOBLIB) @GETLOADAVG_LIBS@ \
     113                $(GUILE_LIBS)
    111114# Only process if target is MS-Windows
    112115if WINDOWSENV
     
    184187
    185188AM_CPPFLAGS =   $(GLOBINC) -I$(srcdir)/../lib -I$(srcdir)/../lib/kStuff/include
     189AM_CFLAGS =     $(GUILE_CFLAGS)
    186190# Only process if target is MS-Windows
    187191if WINDOWSENV
     
    192196# Extra stuff to include in the distribution.
    193197
    194 EXTRA_DIST =    README build.sh.in $(man_MANS) \
     198EXTRA_DIST =    ChangeLog README build.sh.in $(man_MANS) \
    195199                README.customs README.OS2 \
    196200                SCOPTIONS SMakefile \
     
    199203                README.W32 NMakefile config.h.W32 build_w32.bat subproc.bat \
    200204                make_msvc_net2003.sln make_msvc_net2003.vcproj \
    201                 readme.vms makefile.vms makefile.com config.h-vms \
    202                 vmsdir.h vmsfunctions.c vmsify.c
     205                README.VMS makefile.vms makefile.com config.h-vms \
     206                vmsdir.h vmsfunctions.c vmsify.c vms_exit.c vms_progname.c \
     207                vms_export_symbol.c vms_export_symbol_test.com \
     208                gmk-default.scm gmk-default.h
    203209
    204210# This is built during configure, but behind configure's back
     
    206212DISTCLEANFILES = build.sh
    207213
    208 # Forward targets
    209 
    210 html:
    211         cd doc && $(MAKE) $(AM_MAKEFLAGS) $@
    212 
    213 .PHONY: html
    214 
    215214# --------------- Internationalization Section
    216215
     
    223222
    224223# Whether or not make needs to be installed setgid.
    225 # The value should be either `true' or `false'.
    226 # On many systems, the getloadavg function (used to implement the `-l'
     224# The value should be either 'true' or 'false'.
     225# On many systems, the getloadavg function (used to implement the '-l'
    227226# switch) will not work unless make is installed setgid kmem.
    228227#
     
    240239           else \
    241240             echo "$$app needs to be owned by group $(inst_group) and setgid;"; \
    242              echo "otherwise the \`-l' option will probably not work."; \
     241             echo "otherwise the '-l' option will probably not work."; \
    243242             echo "You may need special privileges to complete the installation"; \
    244243             echo "of $$app."; \
     
    246245         else true; fi
    247246
     247# --------------- Generate the Guile default module content
     248
     249guile.$(OBJEXT): gmk-default.h
     250gmk-default.h: $(srcdir)/gmk-default.scm
     251        (echo 'static const char *const GUILE_module_defn = " '\\ \
     252          && sed -e 's/;.*//' -e '/^[ \t]*$$/d' -e 's/"/\\"/g' -e 's/$$/ \\/' \
     253                 $(srcdir)/gmk-default.scm \
     254          && echo '";') > $@
     255
    248256# --------------- Local DIST Section
    249257
     
    252260dist-hook:
    253261        (cd $(srcdir); \
    254          sub=`find w32 tests -follow \( -name CVS -prune -o -name .cvsignore -o -name work -prune \) -o \( -name \*.orig -o -name \*.rej -o -name \*~ -prune \) -o -type f -print`; \
     262         sub=`find w32 tests -follow \( -name .git -o -name .deps -o -name work -o -name .gitignore -o -name \*.orig -o -name \*.rej -o -name \*~ -o -name Makefile \) -prune -o -type f -print`; \
    255263         tar chf - $$sub) \
    256264        | (cd $(distdir); tar xfBp -)
     
    290298MAKETESTFLAGS =
    291299
    292 check-regression:
    293         @if test -f "$(srcdir)/tests/run_make_tests"; then \
     300check-regression: tests/config-flags.pm
     301        @if test -f '$(srcdir)/tests/run_make_tests'; then \
     302          ulimit -n 128; \
    294303          if $(PERL) -v >/dev/null 2>&1; then \
    295             case `cd $(srcdir); pwd` in `pwd`) : ;; \
     304            case `cd '$(srcdir)'; pwd` in `pwd`) : ;; \
    296305              *) test -d tests || mkdir tests; \
    297306                 rm -f srctests; \
    298                  if ln -s "$(srcdir)/tests" srctests; then \
     307                 if ln -s '$(srcdir)/tests' srctests; then \
    299308                   for f in run_make_tests run_make_tests.pl test_driver.pl scripts; do \
    300309                     rm -f tests/$$f; ln -s ../srctests/$$f tests; \
    301310                   done; fi ;; \
    302311            esac; \
    303             echo "cd tests && $(PERL) ./run_make_tests.pl -make ../make$(EXEEXT) $(MAKETESTFLAGS)"; \
    304             cd tests && $(PERL) ./run_make_tests.pl -make ../make$(EXEEXT) $(MAKETESTFLAGS); \
     312            echo "cd tests && $(PERL) ./run_make_tests.pl -srcdir $(abs_srcdir) -make ../make$(EXEEXT) $(MAKETESTFLAGS)"; \
     313            cd tests && $(PERL) ./run_make_tests.pl -srcdir '$(abs_srcdir)' -make '../make$(EXEEXT)' $(MAKETESTFLAGS); \
    305314          else \
    306315            echo "Can't find a working Perl ($(PERL)); the test suite requires Perl."; \
    307316          fi; \
    308          else \
     317        else \
    309318          echo "Can't find the GNU Make test suite ($(srcdir)/tests)."; \
    310          fi
     319        fi
    311320
    312321
     
    314323
    315324# Tell automake that I haven't forgotten about this file and it will be
    316 # created before we build a distribution (see maintMakefile in the CVS
     325# created before we build a distribution (see maintMakefile in the Git
    317326# distribution).
    318327
  • trunk/src/kmk/Makefile.ami

    r2591 r3140  
    11# -*-Makefile-*- for GNU make on Amiga
    22#
    3 # NOTE: If you have no `make' program at all to process this makefile, run
    4 # `build.sh' instead.
    5 #
    6 # Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
    7 # 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     3# NOTE: If you have no 'make' program at all to process this makefile, run
     4# 'build.sh' instead.
     5#
     6# Copyright (C) 1995-2016 Free Software Foundation, Inc.
    87# This file is part of GNU Make.
    98#
     
    3332
    3433# Define these for your system as follows:
    35 #       -DNO_ARCHIVES           To disable `ar' archive support.
     34#       -DNO_ARCHIVES           To disable 'ar' archive support.
    3635#       -DNO_FLOAT              To avoid using floating-point numbers.
    3736#       -DENUM_BITFIELDS        If the compiler isn't GCC but groks enum foo:2.
     
    4039#                               so beware.
    4140# NeXT 1.0a uses an old version of GCC, which required -D__inline=inline.
    42 # See also `config.h'.
     41# See also 'config.h'.
    4342defines =
    4443
    4544# Which flavor of remote job execution support to use.
    46 # The code is found in `remote-$(REMOTE).c'.
     45# The code is found in 'remote-$(REMOTE).c'.
    4746REMOTE = stub
    4847
     
    7877exec_prefix =
    7978
    80 # Directory to install `make' in.
     79# Directory to install 'make' in.
    8180bindir = sc:c
    82 # Directory to find libraries in for `-lXXX'.
     81# Directory to find libraries in for '-lXXX'.
    8382libdir = lib:
    8483# Directory to search by default for included makefiles.
     
    9089# Number to put on the man page filename.
    9190manext = 1
    92 # Prefix to put on installed `make' binary file name.
     91# Prefix to put on installed 'make' binary file name.
    9392binprefix =
    94 # Prefix to put on installed `make' man page file name.
     93# Prefix to put on installed 'make' man page file name.
    9594manprefix = $(binprefix)
    9695
    9796# Whether or not make needs to be installed setgid.
    98 # The value should be either `true' or `false'.
    99 # On many systems, the getloadavg function (used to implement the `-l'
     97# The value should be either 'true' or 'false'.
     98# On many systems, the getloadavg function (used to implement the '-l'
    10099# switch) will not work unless make is installed setgid kmem.
    101100install_setgid = false
     
    103102group = sys
    104103
    105 # Program to install `make'.
     104# Program to install 'make'.
    106105INSTALL_PROGRAM = copy
    107106# Program to install the man page.
     
    119118CTAGS = ctags -w
    120119
    121 objs = commands.o job.o dir.o file.o misc.o main.o read.o remake.o      \
    122        rule.o implicit.o default.o variable.o expand.o function.o       \
    123        vpath.o version.o ar.o arscan.o signame.o strcache.o hash.o      \
    124        remote-$(REMOTE).o $(GETOPT) $(ALLOCA) $(extras)
     120#guile = guile.o
     121
     122objs = commands.o job.o dir.o file.o misc.o main.o read.o remake.o   \
     123       rule.o implicit.o default.o variable.o expand.o function.o    \
     124       vpath.o version.o ar.o arscan.o signame.o strcache.o hash.o   \
     125       remote-$(REMOTE).o $(GETOPT) $(ALLOCA) $(extras) $(guile)
     126
    125127srcs = $(srcdir)commands.c $(srcdir)job.c $(srcdir)dir.c             \
    126128       $(srcdir)file.c $(srcdir)getloadavg.c $(srcdir)misc.c         \
     
    129131       $(srcdir)variable.c $(srcdir)expand.c $(srcdir)function.c     \
    130132       $(srcdir)vpath.c $(srcdir)version.c $(srcdir)hash.c           \
    131        $(srcdir)remote-$(REMOTE).c                                     \
    132        $(srcdir)ar.c $(srcdir)arscan.c $(srcdir)strcache.c              \
    133        $(srcdir)signame.c $(srcdir)signame.h $(GETOPT_SRC)            \
    134        $(srcdir)commands.h $(srcdir)dep.h $(srcdir)filedep.h            \
    135        $(srcdir)job.h $(srcdir)make.h $(srcdir)rule.h                \
     133       $(srcdir)guile.c $(srcdir)remote-$(REMOTE).c                  \
     134       $(srcdir)ar.c $(srcdir)arscan.c $(srcdir)strcache.c           \
     135       $(srcdir)signame.c $(srcdir)signame.h $(GETOPT_SRC)           \
     136       $(srcdir)commands.h $(srcdir)dep.h $(srcdir)filedep.h         \
     137       $(srcdir)job.h $(srcdir)makeint.h $(srcdir)rule.h             \
    136138       $(srcdir)variable.h $(ALLOCA_SRC) $(srcdir)config.h.in
    137139
     
    143145info: make.info
    144146dvi: make.dvi
    145 # Some makes apparently use .PHONY as the default goal if it is before `all'.
     147# Some makes apparently use .PHONY as the default goal if it is before 'all'.
    146148.PHONY: all check info dvi
    147149
     
    179181        cd glob; $(MAKE) libglob.a
    180182FORCE:
    181 
    182 tagsrcs = $(srcs) $(srcdir)remote-*.c
    183183
    184184.PHONY: install installdirs
     
    197197           else \
    198198             echo "$@ needs to be owned by group $(group) and setgid;"; \
    199              echo "otherwise the \`-l' option will probably not work."; \
     199             echo "otherwise the '-l' option will probably not work."; \
    200200             echo "You may need special privileges to install $@."; \
    201201           fi; \
     
    214214        done
    215215# Run install-info only if it exists.
    216 # Use `if' instead of just prepending `-' to the
     216# Use 'if' instead of just prepending '-' to the
    217217# line so we notice real errors from install-info.
    218 # We use `$(SHELL) -c' because some shells do not
     218# We use '$(SHELL) -c' because some shells do not
    219219# fail gracefully when there is an unknown command.
    220220        if $(SHELL) -c 'install-info --version' >/dev/null 2>&1; then \
     
    267267
    268268# The automatically generated dependencies below may omit config.h
    269 # because it is included with ``#include <config.h>'' rather than
    270 # ``#include "config.h"''.  So we add the explicit dependency to make sure.
     269# because it is included with '#include <config.h>' rather than
     270# '#include "config.h"'.  So we add the explicit dependency to make sure.
    271271$(objs): config.h
    272272
     
    274274
    275275# Automatically generated dependencies.
    276 commands.o: commands.c make.h dep.h filedef.h variable.h job.h \
     276commands.o: commands.c makeint.h dep.h filedef.h variable.h job.h \
    277277 commands.h
    278 job.o: job.c make.h job.h filedef.h commands.h variable.h
    279 dir.o: dir.c make.h
    280 file.o: file.c make.h dep.h filedef.h job.h commands.h variable.h
    281 misc.o: misc.c make.h dep.h
    282 main.o: main.c make.h dep.h filedef.h variable.h job.h commands.h \
     278job.o: job.c makeint.h job.h filedef.h commands.h variable.h
     279dir.o: dir.c makeint.h
     280file.o: file.c makeint.h dep.h filedef.h job.h commands.h variable.h
     281misc.o: misc.c makeint.h dep.h
     282main.o: main.c makeint.h dep.h filedef.h variable.h job.h commands.h \
    283283 getopt.h
    284 read.o: read.c make.h dep.h filedef.h job.h commands.h variable.h \
     284guile.o: guile.c makeint.h dep.h debug.h variable.h gmk-default.h
     285read.o: read.c makeint.h dep.h filedef.h job.h commands.h variable.h \
    285286 glob/glob.h
    286 remake.o: remake.c make.h filedef.h job.h commands.h dep.h
    287 rule.o: rule.c make.h dep.h filedef.h job.h commands.h variable.h \
     287remake.o: remake.c makeint.h filedef.h job.h commands.h dep.h
     288rule.o: rule.c makeint.h dep.h filedef.h job.h commands.h variable.h \
    288289 rule.h
    289 implicit.o: implicit.c make.h rule.h dep.h filedef.h
    290 default.o: default.c make.h rule.h dep.h filedef.h job.h commands.h \
     290implicit.o: implicit.c makeint.h rule.h dep.h filedef.h
     291default.o: default.c makeint.h rule.h dep.h filedef.h job.h commands.h \
    291292 variable.h
    292 variable.o: variable.c make.h dep.h filedef.h job.h commands.h \
     293variable.o: variable.c makeint.h dep.h filedef.h job.h commands.h \
    293294 variable.h
    294 expand.o: expand.c make.h filedef.h job.h commands.h variable.h
    295 function.o: function.c make.h filedef.h variable.h dep.h job.h \
     295expand.o: expand.c makeint.h filedef.h job.h commands.h variable.h
     296function.o: function.c makeint.h filedef.h variable.h dep.h job.h \
    296297 commands.h amiga.h
    297 vpath.o: vpath.c make.h filedef.h variable.h
    298 strcache.o: strcache.c make.h hash.h
     298vpath.o: vpath.c makeint.h filedef.h variable.h
     299strcache.o: strcache.c makeint.h hash.h
    299300version.o: version.c
    300 ar.o: ar.c make.h filedef.h dep.h
    301 arscan.o: arscan.c make.h
     301ar.o: ar.c makeint.h filedef.h dep.h
     302arscan.o: arscan.c makeint.h
    302303signame.o: signame.c signame.h
    303 remote-stub.o: remote-stub.c make.h filedef.h job.h commands.h
     304remote-stub.o: remote-stub.c makeint.h filedef.h job.h commands.h
    304305getopt.o: getopt.c
    305306getopt1.o : getopt1.c getopt.h
    306307getloadavg.o: getloadavg.c
    307 amiga.o: amiga.c make.h variable.h amiga.h
     308amiga.o: amiga.c makeint.h variable.h amiga.h
  • trunk/src/kmk/Makefile.kmk

    r3110 r3140  
    5454TEMPLATE_BIN-KMK_CFLAGS.win.amd64 = $(TEMPLATE_BIN-THREADED_CFLAGS.win.amd64) -wd4244 -wd4267
    5555TEMPLATE_BIN-KMK_CLEAN.win = $(TEMPLATE_BIN-KMK_DEPS.win)
     56TEMPLATE_BIN-KMK_DEFS.debug = $(TEMPLATE_BIN-KMK_DEPS.debug) MAKE_MAINTAINER_MODE
    5657TEMPLATE_BIN-KMK_INCS = $(kmk_0_OUTDIR) . $(TEMPLATE_BIN-THREADED_INCS)
    5758ifneq ($(KBUILD_TARGET),os2)
     
    144145        w32/subproc/w32err.c \
    145146        w32/pathstuff.c \
    146         w32/imagecache.c
     147        w32/imagecache.c \
     148        w32/compat/posixfcn.c
    147149
    148150#
     
    213215kmk_DEFS.x86 = CONFIG_WITH_OPTIMIZATION_HACKS
    214216kmk_DEFS.amd64 = CONFIG_WITH_OPTIMIZATION_HACKS
    215 kmk_DEFS.win = CONFIG_NEW_WIN32_CTRL_EVENT CONFIG_WITH_FAST_IS_SPACE
     217kmk_DEFS.win = CONFIG_NEW_WIN32_CTRL_EVENT
    216218kmk_DEFS.debug = CONFIG_WITH_MAKE_STATS
    217219ifdef CONFIG_WITH_MAKE_STATS
     
    241243        job.c \
    242244        misc.c \
     245        output.c \
    243246        remake.c \
    244247        rule.c \
     
    247250        vpath.c \
    248251        remote-stub.c \
     252        guile.c \
     253        load.c \
    249254       \
    250255        alloccache.c \
     
    256261        kbuild-object.c
    257262ifeq ($(KBUILD_TARGET),win)
    258  kmk_SOURCES += dir-nt-bird.c
     263 kmk_SOURCES += \
     264        dir-nt-bird.c \
     265        w32/w32os.c
    259266else
    260  kmk_SOURCES += dir.c
     267 kmk_SOURCES += \
     268        dir.c \
     269        posixos.c
    261270endif
    262271
     
    481490        job.c \
    482491        misc.c \
     492        output.c \
    483493        remake.c \
    484494        rule.c \
     
    486496        version.c \
    487497        vpath.c \
    488         remote-stub.c
     498        remote-stub.c \
     499        guile.c \
     500        load.c
     501ifeq ($(KBUILD_TARGET),win)
     502 kmk_gmake_SOURCES += \
     503        w32/w32os.c
     504else
     505 kmk_gmake_SOURCES += \
     506        posixos.c
     507endif
    489508
    490509kmk_gmake_SOURCES.win = \
     
    533552        job.c \
    534553        misc.c \
     554        output.c \
    535555        alloccache.c \
    536556        remake.c \
     
    539559        version.c \
    540560        vpath.c \
    541         remote-stub.c
     561        remote-stub.c \
     562        guile.c \
     563        load.c
     564ifeq ($(KBUILD_TARGET),win)
     565 kmk_fgmake_SOURCES += \
     566        w32/w32os.c
     567# @todo: dir-nt-bird.c for fgmake
     568else
     569 kmk_fgmake_SOURCES += \
     570        posixos.c
     571endif
    542572
    543573kmk_fgmake_SOURCES.win = \
  • trunk/src/kmk/NEWS

    r2591 r3140  
    11GNU make NEWS                                               -*-indented-text-*-
    22  History of user-visible changes.
    3   28 July 2010
     3  10 June 2016
    44
    55See the end of this file for copyrights and conditions.
     
    1111
    1212
    13 Version 3.82
     13Version 4.2.1 (10 Jun 2016)
     14
     15A complete list of bugs fixed in this version is available here:
     16h
     17ttp://sv.gnu.org/bugs/index.php?group=make&report_id=111&fix_release_id=107&set=custom
     18
     19This release is a bug-fix release.
     20
     21
     22
     23Version 4.2 (22 May 2016)
     24
     25A complete list of bugs fixed in this version is available here:
     26
     27http://sv.gnu.org/bugs/index.php?group=make&report_id=111&fix_release_id=106&set=custom
     28
     29* New variable: $(.SHELLSTATUS) is set to the exit status of the last != or
     30  $(shell ...) function invoked in this instance of make.  This will be "0" if
     31  successful or not "0" if not successful.  The variable value is unset if no
     32  != or $(shell ...) function has been invoked.
     33
     34* The $(file ...) function can now read from a file with $(file <FILE).
     35  The function is expanded to the contents of the file.  The contents are
     36  expanded verbatim except that the final newline, if any, is stripped.
     37
     38* The makefile line numbers shown by GNU make now point directly to the
     39  specific line in the recipe where the failure or warning occurred.
     40  Sample changes suggested by Brian Vandenberg <[email protected]>
     41
     42* The interface to GNU make's "jobserver" is stable as documented in the
     43  manual, for tools which may want to access it.
     44
     45  WARNING: Backward-incompatibility! The internal-only command line option
     46  --jobserver-fds has been renamed for publishing, to --jobserver-auth.
     47
     48* The amount of parallelism can be determined by querying MAKEFLAGS, even when
     49  the job server is enabled (previously MAKEFLAGS would always contain only
     50  "-j", with no number, when job server was enabled).
     51
     52* VMS-specific changes:
     53
     54  * Perl test harness now works.
     55
     56  * Full support for converting Unix exit status codes to VMS exit status
     57    codes.  BACKWARD INCOMPATIBILITY Notice: On a child failure the VMS exit
     58    code is now the encoded Unix exit status that Make usually generates, not
     59    the VMS exit status of the child.
     60
     61
     62
     63Version 4.1 (05 Oct 2014)
     64
     65A complete list of bugs fixed in this version is available here:
     66
     67http://sv.gnu.org/bugs/index.php?group=make&report_id=111&fix_release_id=105&set=custom
     68
     69* New variables: $(MAKE_TERMOUT) and $(MAKE_TERMERR) are set to non-empty
     70  values if stdout or stderr, respectively, are believed to be writing to a
     71  terminal.  These variables are exported by default.
     72
     73* Allow a no-text-argument form of the $(file ...) function.  Without a text
     74  argument nothing is written to the file: it is simply opened in the
     75  requested mode, then closed again.
     76
     77* Change the fatal error for mixed explicit and implicit rules, that was
     78  introduced in GNU make 3.82, to a non-fatal error.  However, this syntax is
     79  still deprecated and may return to being illegal in a future version of GNU
     80  make.  Makefiles that rely on this syntax should be fixed.
     81  See https://savannah.gnu.org/bugs/?33034
     82
     83* VMS-specific changes:
     84
     85  * Support for library files added, including support for using the GNV ar
     86    utility.
     87
     88  * Partial support for properly encoding Unix exit status codes into VMS exit
     89    status codes.
     90
     91    WARNING: Backward-incompatibility! These are different exit status codes
     92    than Make exited with in the past.
     93
     94  * Macros to hold the current make command are set up to translate the
     95    argv[0] string to a VMS format path name and prefix it with "MCR " so that
     96    the macro has a space in it.
     97
     98    WARNING: Backward-incompatibility!  This may break complex makefiles that
     99    do processing on those macros.  This is unlikely because so much in that
     100    area was not and is still not currently working on VMS, it is unlikely to
     101    find such a complex makefile, so this is more likely to impact
     102    construction of a future makefile.
     103
     104  * A command file is always used to run the commands for a recipe.
     105
     106    WARNING: Backward-incompatibility!  Running the make self tests has
     107    exposed that there are significant differences in behavior when running
     108    with the command file mode.  It is unknown if this will be noticed by most
     109    existing VMS makefiles.
     110
     111
     112Version 4.0 (09 Oct 2013)
     113
     114A complete list of bugs fixed in this version is available here:
     115
     116http://sv.gnu.org/bugs/index.php?group=make&report_id=111&fix_release_id=101&set=custom
     117
     118* WARNING: Backward-incompatibility!
     119  If .POSIX is specified, then make adheres to the POSIX backslash/newline
     120  handling requirements, which introduces the following changes to the
     121  standard backslash/newline handling in non-recipe lines:
     122  * Any trailing space before the backslash is preserved
     123  * Each backslash/newline (plus subsequent whitespace) is converted to a
     124    single space
     125
     126* New feature: GNU Guile integration
     127  This version of GNU make can be compiled with GNU Guile integration.
     128  GNU Guile serves as an embedded extension language for make.
     129  See the "Guile Function" section in the GNU Make manual for details.
     130  Currently GNU Guile 1.8 and 2.0+ are supported.  In Guile 1.8 there is no
     131  support for internationalized character sets.  In Guile 2.0+, scripts can be
     132  encoded in UTF-8.
     133
     134* New command line option: --output-sync (-O) enables grouping of output by
     135  target or by recursive make.  This is useful during parallel builds to avoid
     136  mixing output from different jobs together giving hard-to-understand
     137  results.  Original implementation by David Boyce <[email protected]>.
     138  Reworked and enhanced by Frank Heckenbach <[email protected]>.
     139  Windows support by Eli Zaretskii <[email protected]>.
     140
     141* New command line option: --trace enables tracing of targets.  When enabled
     142  the recipe to be invoked is printed even if it would otherwise be suppressed
     143  by .SILENT or a "@" prefix character.  Also before each recipe is run the
     144  makefile name and linenumber where it was defined are shown as well as the
     145  prerequisites that caused the target to be considered out of date.
     146
     147* New command line option argument: --debug now accepts a "n" (none) flag
     148  which disables all debugging settings that are currently enabled.
     149
     150* New feature: The "job server" capability is now supported on Windows.
     151  Implementation contributed by Troy Runkel <[email protected]>
     152
     153* New feature: The .ONESHELL capability is now supported on Windows.  Support
     154  added by Eli Zaretskii <[email protected]>.
     155
     156* New feature: "!=" shell assignment operator as an alternative to the
     157  $(shell ...) function.  Implemented for compatibility with BSD makefiles.
     158  Note there are subtle differences between "!=" and $(shell ...).  See the
     159  description in the GNU make manual.
     160  WARNING: Backward-incompatibility!
     161  Variables ending in "!" previously defined as "variable!= value" will now be
     162  interpreted as shell assignment.  Change your assignment to add whitespace
     163  between the "!" and "=": "variable! = value"
     164
     165* New feature: "::=" simple assignment operator as defined by POSIX in 2012.
     166  This operator has identical functionality to ":=" in GNU make, but will be
     167  portable to any implementation of make conforming to a sufficiently new
     168  version of POSIX (see http://austingroupbugs.net/view.php?id=330).  It is
     169  not necessary to define the .POSIX target to access this operator.
     170
     171* New feature: Loadable objects
     172  This version of GNU make contains a "technology preview": the ability to
     173  load dynamic objects into the make runtime.  These objects can be created by
     174  the user and can add extended functionality, usable by makefiles.
     175
     176* New function: $(file ...) writes to a file.
     177
     178* New variable: $(GNUMAKEFLAGS) will be parsed for make flags, just like
     179  MAKEFLAGS is.  It can be set in the environment or the makefile, containing
     180  GNU make-specific flags to allow your makefile to be portable to other
     181  versions of make.  Once this variable is parsed, GNU make will set it to the
     182  empty string so that flags will not be duplicated on recursion.
     183
     184* New variable: `MAKE_HOST' gives the name of the host architecture
     185  make was compiled for.  This is the same value you see after 'Built for'
     186  when running 'make --version'.
     187
     188* Behavior of MAKEFLAGS and MFLAGS is more rigorously defined.  All simple
     189  flags are grouped together in the first word of MAKEFLAGS.  No options that
     190  accept arguments appear in the first word.  If no simple flags are present
     191  MAKEFLAGS begins with a space.  Flags with both short and long versions
     192  always use the short versions in MAKEFLAGS.  Flags are listed in
     193  alphabetical order using ASCII ordering.  MFLAGS never begins with "- ".
     194
     195* Setting the -r and -R options in MAKEFLAGS inside a makefile now works as
     196  expected, removing all built-in rules and variables, respectively.
     197
     198* If a recipe fails, the makefile name and linenumber of the recipe are shown.
     199
     200* A .RECIPEPREFIX setting is remembered per-recipe and variables expanded
     201  in that recipe also use that recipe prefix setting.
     202
     203* In -p output, .RECIPEPREFIX settings are shown and all target-specific
     204  variables are output as if in a makefile, instead of as comments.
     205
     206* On MS-Windows, recipes that use ".." quoting will no longer force
     207  invocation of commands via temporary batch files and stock Windows
     208  shells, they will be short-circuited and invoked directly.  (In
     209  other words, " is no longer a special character for stock Windows
     210  shells.)  This avoids hitting shell limits for command length when
     211  quotes are used, but nothing else in the command requires the shell.
     212  This change could potentially mean some minor incompatibilities in
     213  behavior when the recipe uses quoted string on shell command lines.
     214
     215
     216
     217Version 3.82 (28 Jul 2010)
    14218
    15219A complete list of bugs fixed in this version is available here:
     
    19223* Compiling GNU make now requires a conforming ISO C 1989 compiler and
    20224  standard runtime library.
    21 
    22 * WARNING: Future backward-incompatibility!
    23   Wildcards are not documented as returning sorted values, but up to and
    24   including this release the results have been sorted and some makefiles are
    25   apparently depending on that.  In the next release of GNU make, for
    26   performance reasons, we may remove that sorting.  If your makefiles
    27   require sorted results from wildcard expansions, use the $(sort ...)
    28   function to request it explicitly.
    29225
    30226* WARNING: Backward-incompatibility!
     
    44240
    45241* WARNING: Backward-incompatibility!
     242  Wildcards were not documented as returning sorted values, but the results
     243  have been sorted up until this release..  If your makefiles require sorted
     244  results from wildcard expansions, use the $(sort ...)  function to request
     245  it explicitly.
     246
     247* WARNING: Backward-incompatibility!
    46248  As a result of parser enhancements, three backward-compatibility issues
    47249  exist: first, a prerequisite containing an "=" cannot be escaped with a
     
    116318  multi-line variable assignment.
    117319
    118 
    119 
    120 Version 3.81
     320* VMS-specific changes:
     321
     322  * Michael Gehre (at VISTEC-SEMI dot COM) supplied a fix for a problem with
     323    timestamps of object modules in OLBs. The timestamps were not correctly
     324    adjusted to GMT based time, if the local VMS time was using a daylight
     325    saving algorithm and if daylight saving was switched off.
     326
     327  * John Eisenbraun (at HP dot COM) supplied fixes and and an enhancement to
     328    append output redirection in action lines.
     329
     330  * Rework of ctrl+c and ctrl+y handling.
     331
     332  * Fix a problem with cached strings, which showed on case-insensitive file
     333    systems.
     334
     335  * Build fixes for const-ified code in VMS specific sources.
     336
     337  * A note on appending the redirected output. With this change, a simple
     338    mechanism is implemented to make ">>" work in action lines. In VMS
     339    there is no simple feature like ">>" to have DCL command or program
     340    output redirected and appended to a file. GNU make for VMS already
     341    implements the redirection of output. If such a redirection is detected,
     342    an ">" on the action line, GNU make creates a DCL command procedure to
     343    execute the action and to redirect its output. Based on that, now ">>"
     344    is also recognized and a similar but different command procedure is
     345    created to implement the append. The main idea here is to create a
     346    temporary file which collects the output and which is appended to the
     347    wanted output file. Then the temporary file is deleted. This is all done
     348    in the command procedure to keep changes in make small and simple. This
     349    obviously has some limitations but it seems good enough compared with
     350    the current ">" implementation. (And in my opinion, redirection is not
     351    really what GNU make has to do.) With this approach, it may happen that
     352    the temporary file is not yet appended and is left in SYS$SCRATCH.
     353    The temporary file names look like "CMDxxxxx.". Any time the created
     354    command procedure can not complete, this happens. Pressing Ctrl+Y to
     355    abort make is one case. In case of Ctrl+Y the associated command
     356    procedure is left in SYS$SCRATCH as well. Its name is CMDxxxxx.COM.
     357
     358  * Change in the Ctrl+Y handling. The CtrlY handler now uses $delprc to
     359    delete all children. This way also actions with DCL commands will be
     360    stopped. As before the CtrlY handler then sends SIGQUIT to itself,
     361    which is handled in common code.
     362
     363  * Change in deleteing temporary command files. Temporary command files
     364    are now deleted in the vms child termination handler. That deletes
     365    them even if a Ctrl+C was pressed.
     366
     367  * The behavior of pressing Ctrl+C is not changed. It still has only an
     368    effect, after the current action is terminated. If that doesn't happen
     369    or takes too long, Ctrl+Y should be used instead.
     370
     371
     372
     373Version 3.81 (01 Apr 2006)
    121374
    122375* GNU make is ported to OS/2.
     
    131384  might have caused the target to rebuild.  Starting with the _next_
    132385  release of GNU make, '$?' will contain all prerequisites that caused
    133   the target to be considered out of date.  See this Savannah bug:
    134   http://savannah.gnu.org/bugs/index.php?func=detailitem&item_id=16051
     386  the target to be considered out of date.
     387  See http://savannah.gnu.org/bugs/?16051
    135388
    136389* WARNING: Backward-incompatibility!
     
    241494
    242495* On VMS there is now support for case-sensitive filesystems such as ODS5.
    243   See the readme.vms file for information.
     496  See the README.VMS file for information.
    244497
    245498* Parallel builds (-jN) no longer require a working Bourne shell on
     
    260513
    261514
    262 Version 3.80
     515Version 3.80 (03 Oct 2002)
    263516
    264517* A new feature exists: order-only prerequisites.  These prerequisites
     
    337590* Updated to autoconf 2.54 and automake 1.7.  Users should not be impacted.
    338591
     592* VMS-specific changes:
     593
     594  * In default.c define variable ARCH as IA64 for VMS on Itanium systems.
     595
     596  * In makefile.vms avoid name collision for glob and globfree.
     597
     598  * This is the VMS port of GNU Make done by [email protected].
     599
     600    It is based on the specific version 3.77k and on 3.78.1. 3.77k was done
     601    by Klaus Kämpf <[email protected]>, the code was based on the VMS port of
     602    GNU Make 3.60 by Mike Moretti.
     603
     604    It was ported on OpenVMS/Alpha V7.1, DECC V5.7-006. It was re-build and
     605    tested on OpenVMS/Alpha V7.2, OpenVMS/VAX 7.1 and 5.5-2. Different
     606    versions of DECC were used. VAXC was tried: it fails; but it doesn't
     607    seem worth to get it working. There are still some PTRMISMATCH warnings
     608    during the compile. Although perl is working on VMS the test scripts
     609    don't work. The function $shell is still missing.
     610
     611    There is a known bug in some of the VMS CRTLs. It is in the shipped
     612    versions of VMS V7.2 and V7.2-1 and in the currently (October 1999)
     613    available ECOs for VMS V7.1 and newer versions. It is fixed in versions
     614    shipped with newer VMS versions and all ECO kits after October 1999. It
     615    only shows up during the daylight saving time period (DST): stat()
     616    returns a modification time 1 hour ahead. This results in GNU make
     617    warning messages. For a just created source you will see:
     618
     619     $ gmake x.exe
     620     gmake.exe;1: *** Warning: File 'x.c' has modification time in the future
     621     (940582863 > 940579269)
     622     cc    /obj=x.obj x.c
     623     link  x.obj    /exe=x.exe
     624     gmake.exe;1: *** Warning:  Clock skew detected.  Your build may be
     625     incomplete.
     626
     627
    339628A complete list of bugs fixed in this version is available here:
    340629
     
    343632
    344633
    345 Version 3.79.1
     634Version 3.79.1 (23 Jun 2000)
    346635
    347636* .SECONDARY with no prerequisites now prevents any target from being
     
    353642
    354643
    355 Version 3.79
     644Version 3.79 (04 Apr 2000)
    356645
    357646* GNU make optionally supports internationalization and locales via the
     
    394683
    395684* Hartmut Becker provided many updates for the VMS port of GNU make.
    396   See the readme.vms file for more details.
    397 
    398 
    399 Version 3.78
     685  See the README.VMS file for more details.
     686
     687* VMS-specific changes:
     688
     689  * Fix a problem with automatically remaking makefiles. GNU make uses an
     690    execve to restart itself after a successful remake of the makefile. On
     691    UNIX systems execve replaces the running program with a new one and
     692    resets all signal handling to the default. On VMS execve creates a child
     693    process, signal and exit handlers of the parent are still active, and,
     694    unfortunately, corrupt the exit code from the child. Fix in job.c:
     695    ignore SIGCHLD.
     696
     697  * Added some switches to reflect latest features of DECC. Modifications in
     698    makefile.vms.
     699
     700  * Set some definitions to reflect latest features of DECC. Modifications in
     701    config.h-vms (which is copied to config.h).
     702
     703  * Added extern strcmpi declaration to avoid 'implicitly declared' messages.
     704    Modification in make.h.
     705
     706  * Default rule for C++, conditionals for gcc (GCC_IS_NATIVE) or DEC/Digital/
     707    Compaq c/c++ compilers. Modifications in default.c.
     708
     709  * Usage of opendir() and friends, suppress file version. Modifications in
     710    dir.c.
     711
     712  * Added VMS specific code to handle ctrl+c and ctrl+y to abort make.
     713    Modifications in job.c.
     714
     715  * Added support to have case sensitive targets and dependencies but to
     716    still use case blind file names. This is especially useful for Java
     717    makefiles on VMS:
     718
     719        .SUFFIXES :
     720        .SUFFIXES : .class .java
     721        .java.class :
     722                javac "$<
     723        HelloWorld.class :      HelloWorld.java
     724
     725  * A new macro WANT_CASE_SENSITIVE_TARGETS in config.h-vms was introduced.
     726    It needs to be enabled to get this feature; default is disabled.  The
     727    macro HAVE_CASE_INSENSITIVE_FS must not be touched: it is still enabled.
     728    Modifications in file.c and config.h-vms.
     729
     730  * Bootstrap make to start building make is still makefile.com, but make
     731    needs to be re-made with a make to make a correct version: ignore all
     732    possible warnings, delete all objects, rename make.exe to a different
     733    name and run it.
     734
     735  * Made some minor modifications to the bootstrap build makefile.com.
     736
     737
     738Version 3.78 (22 Sep 1999)
    400739
    401740* Two new functions, $(error ...) and $(warning ...) are available.  The
     
    454793
    455794
    456 Version 3.77
     795Version 3.77 (28 Jul 1998)
    457796
    458797* Implement BSD make's "?=" variable assignment operator.  The variable
     
    500839  and to the DOS port from Eli Zaretski (see README.DOS).
    501840
    502 
    503 Version 3.76.1
     841* VMS-specific changes:
     842
     843  * This is the VMS port of GNU Make.
     844    It is based on the VMS port of GNU Make 3.60 by Mike Moretti.
     845    This port was done by Klaus Kämpf <[email protected]>
     846
     847  * There is first-level support available from proGIS Software, Germany.
     848    Visit their web-site at http://www.progis.de to get information
     849    about other vms software and forthcoming updates to gnu make.
     850
     851  * /bin/sh style I/O redirection is supported. You can now write lines like
     852        mcr sys$disk:[]program.exe < input.txt > output.txt &> error.txt
     853
     854  * Makefile variables are looked up in the current environment. You can set
     855    symbols or logicals in DCL and evaluate them in the Makefile via
     856    $(<name-of-symbol-or-logical>).  Variables defined in the Makefile
     857    override VMS symbols/logicals !
     858
     859  * Functions for file names are working now. See the GNU Make manual for
     860    $(dir ...)  and $(wildcard ...).  Unix-style and VMS-style names are
     861    supported as arguments.
     862
     863  * The default rules are set up for GNU C. Building an executable from a
     864    single source file is as easy as 'make file.exe'.
     865
     866  * The variable $(ARCH) is predefined as ALPHA or VAX resp. Makefiles for
     867    different VMS systems can now be written by checking $(ARCH) as in
     868      ifeq ($(ARCH),ALPHA)
     869        $(ECHO) "On the Alpha"
     870      else
     871        $(ECHO) "On the VAX"
     872      endif
     873
     874  * Command lines of excessive length are correctly broken and written to a
     875    batch file in sys$scratch for later execution. There's no limit to the
     876    lengths of commands (and no need for .opt files :-) any more.
     877
     878  * Empty commands are handled correctly and don't end in a new DCL process.
     879
     880
     881Version 3.76.1 (19 Sep 1997)
    504882
    505883* Small (but serious) bug fix.  Quick rollout to get into the GNU source CD.
    506884
    507885
    508 Version 3.76
     886Version 3.76 (16 Sep 1997)
    509887
    510888* GNU make now uses automake to control Makefile.in generation.  This
     
    549927  Delorie <[email protected]>.
    550928
    551 * John W. Eaton has updated the VMS port to support libraries and VPATH.
    552 
    553 
    554 Version 3.75
     929* VMS-specific changes:
     930
     931  * John W. Eaton has updated the VMS port to support libraries and VPATH.
     932
     933  * The cd command is supported if it's called as $(CD). This invokes
     934    the 'builtin_cd' command which changes the directory.
     935    Calling 'set def' doesn't do the trick, since a sub-shell is
     936    spawned for this command, the directory is changed *in this sub-shell*
     937    and the sub-shell ends.
     938
     939  * Libraries are not supported. They were in GNU Make 3.60 but somehow I
     940    didn't care porting the code. If there is enough interest, I'll do it at
     941    some later time.
     942
     943  * The variable $^ separates files with commas instead of spaces (It's the
     944    natural thing to do for VMS).
     945
     946  * See defaults.c for VMS default suffixes and my definitions for default
     947    rules and variables.
     948
     949  * The shell function is not implemented yet.
     950
     951  * Load average routines haven't been implemented for VMS yet.
     952
     953  * The default include directory for including other makefiles is
     954    SYS$SYSROOT:[SYSLIB] (I don't remember why I didn't just use
     955    SYS$LIBRARY: instead; maybe it wouldn't work that way).
     956
     957  * The default makefiles make looks for are: makefile.vms, gnumakefile,
     958    makefile., and gnumakefile. .
     959
     960  * The stat() function and handling of time stamps in VMS is broken, so I
     961    replaced it with a hack in vmsfunctions.c. I will provide a full rewrite
     962    somewhere in the future. Be warned, the time resolution inside make is
     963    less than what vms provides. This might be a problem on the faster Alphas.
     964
     965  * You can use a : in a filename only if you precede it with a backslash ('\').
     966    E.g.- hobbes\:[bogas.files]
     967
     968  * Make ignores success, informational, or warning errors (-S-, -I-, or -W-).
     969    But it will stop on -E- and -F- errors. (unless you do something
     970    to override this in your makefile, or whatever).
     971
     972  * Remote stuff isn't implemented yet.
     973
     974  * Multiple line DCL commands, such as "if" statements, must be put inside
     975    command files.  You can run a command file by using \@.
     976
     977Version 3.75 (27 Aug 1996)
    555978
    556979* The directory messages printed by `-w' and implicitly in sub-makes,
     
    573996  <[email protected]>.
    574997
    575 
    576 Version 3.73
     998* VMS-specific changes:
     999
     1000  * Lots of default settings are adapted for VMS. See default.c.
     1001
     1002  * Long command lines are now converted to command files.
     1003
     1004  * Comma (',') as a separator is now allowed. See makefile.vms for an example.
     1005
     1006
     1007Version 3.73 (05 Apr 1995)
    5771008
    5781009* Converted to use Autoconf version 2, so `configure' has some new options.
     
    5831014
    5841015
    585 Version 3.72
     1016Version 3.72 (04 Nov 1994)
    5861017
    5871018* DJ Delorie has ported Make to MS-DOS using the GO32 extender.
     
    6181049
    6191050
    620 Version 3.71
     1051Version 3.71 (21 May 1994)
    6211052
    6221053* The automatic variables `$(@D)', `$(%D)', `$(*D)', `$(<D)', `$(?D)', and
     
    6411072
    6421073
    643 Version 3.70
     1074Version 3.70 (03 Jan 1994)
    6441075
    6451076* It is no longer a fatal error to have a NUL character in a makefile.
     
    6531084
    6541085
    655 Version 3.69
     1086Version 3.69 (07 Nov 1993)
    6561087
    6571088* Implicit rule search for archive member references is now done in the
     
    6721103  cause a paradoxical situation in cases like:
    6731104
    674         export variable = $(shell echo value)
     1105        export variable = $(shell echo value)
    6751106
    6761107  When Make attempted to put this variable in the environment for a
     
    6841115
    6851116
    686 Version 3.68
     1117Version 3.68 (28 Jul 1993)
    6871118
    6881119* You can list several archive member names inside parenthesis:
     
    6961127
    6971128* A suffix rule `.X.a' now produces two pattern rules:
    698         (%.o): %.X      # Previous versions produced only this.
    699         %.a: %.X        # Now produces this as well, just like other suffixes.
     1129        (%.o): %.X      # Previous versions produced only this.
     1130        %.a: %.X        # Now produces this as well, just like other suffixes.
    7001131
    7011132* The new flag `--warn-undefined-variables' says to issue a warning message
     
    7111142
    7121143
    713 Version 3.66
     1144Version 3.66 (21 May 1993)
    7141145
    7151146* `make --version' (or `make -v') now exits immediately after printing
     
    7171148
    7181149
    719 Version 3.65
     1150Version 3.65 (09 May 1993)
    7201151
    7211152* Make now supports long-named members in `ar' archive files.
    7221153
    7231154
    724 Version 3.64
     1155Version 3.64 (21 Apr 1993)
    7251156
    7261157* Make now supports the `+=' syntax for a variable definition which appends
     
    7371168
    7381169
    739 Version 3.63
     1170Version 3.63 (22 Jan 1993)
    7401171
    7411172* Make now uses a standard GNU `configure' script.  See the new file
     
    7711202  Make runs.  Instead, only variables specified on the command line or in
    7721203  the environment are exported by default.  To export others, use:
    773         export VARIABLE
     1204        export VARIABLE
    7741205  or you can define variables with:
    775         export VARIABLE = VALUE
     1206        export VARIABLE = VALUE
    7761207  or:
    777         export VARIABLE := VALUE
     1208        export VARIABLE := VALUE
    7781209  You can use just:
    779         export
     1210        export
    7801211  or:
    781         .EXPORT_ALL_VARIABLES:
     1212        .EXPORT_ALL_VARIABLES:
    7821213  to get the old behavior.  See the node `Variables/Recursion' in the manual
    7831214  for a full description.
     
    7991230* A single `include' directive can now specify more than one makefile to
    8001231  include, like this:
    801         include file1 file2
     1232        include file1 file2
    8021233  You can also use shell file name patterns in an `include' directive:
    803         include *.mk
     1234        include *.mk
    8041235
    8051236* The default directories to search for included makefiles, and for
     
    9461377
    9471378* Messages indicating failed recipe lines now contain the target name:
    948         make: *** [target] Error 1
     1379        make: *** [target] Error 1
    9491380
    9501381* The `-p' output format has been changed somewhat to look more like
     
    11501581
    11511582-------------------------------------------------------------------------------
    1152 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    1153 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    1154 2010 Free Software Foundation, Inc.  This file is part of GNU Make.
     1583Copyright (C) 1988-2016 Free Software Foundation, Inc.
     1584This file is part of GNU Make.
    11551585
    11561586GNU Make is free software; you can redistribute it and/or modify it under the
  • trunk/src/kmk/NMakefile.template

    r2591 r3140  
    44# run 'build_w32.bat' instead.
    55#
    6 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    7 # 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     6# Copyright (C) 1996-2016 Free Software Foundation, Inc.
    87# This file is part of GNU Make.
    98#
     
    3433
    3534LDFLAGS_debug = w32\subproc\WinDebug\subproc.lib /NOLOGO /SUBSYSTEM:console\
    36         /INCREMENTAL:no /PDB:WinDebug/make.pdb /OUT:WinDebug/make.exe /DEBUG
     35        /STACK:0x400000 /INCREMENTAL:no /PDB:WinDebug/make.pdb /OUT:WinDebug/make.exe /DEBUG
    3736LDFLAGS_release = w32\subproc\WinRel\subproc.lib /NOLOGO /SUBSYSTEM:console\
    38         /INCREMENTAL:no /OUT:WinRel/make.exe
     37        /STACK:0x400000 /INCREMENTAL:no /OUT:WinRel/make.exe
    3938
    4039all: config.h subproc Release Debug
     
    7473LIBS = kernel32.lib user32.lib advapi32.lib
    7574
     75guile = $(OUTDIR)/guile.obj
     76
    7677OBJS = \
    7778        $(OUTDIR)/ar.obj \
     
    8990        $(OUTDIR)/implicit.obj \
    9091        $(OUTDIR)/job.obj \
     92        $(OUTDIR)/load.obj \
    9193        $(OUTDIR)/main.obj \
    9294        $(OUTDIR)/misc.obj \
     95        $(OUTDIR)/output.obj \
    9396        $(OUTDIR)/read.obj \
    9497        $(OUTDIR)/remake.obj \
     
    103106        $(OUTDIR)/fnmatch.obj \
    104107        $(OUTDIR)/dirent.obj \
    105         $(OUTDIR)/pathstuff.obj
     108        $(OUTDIR)/pathstuff.obj \
     109        $(OUTDIR)/posixfcn.obj \
     110        $(OUTDIR)/w32os.obj \
     111        $(guile)
    106112
    107113$(OUTDIR)/make.exe: $(OUTDIR) $(OBJS)
     
    119125$(OUTDIR)/dirent.obj : w32/compat/dirent.c
    120126        $(CC) $(CFLAGS) /c $?
     127$(OUTDIR)/posixfcn.obj : w32/compat/posixfcn.c
     128        $(CC) $(CFLAGS) /c $?
    121129$(OUTDIR)/pathstuff.obj : w32/pathstuff.c
    122130        $(CC) $(CFLAGS) /c $?
     131$(OUTDIR)/w32os.obj : w32/w32os.c
     132        $(CC) $(CFLAGS) /c $?
  • trunk/src/kmk/README.Amiga

    r2591 r3140  
    1212- Allows to use Device-Names in targets:
    1313
    14         c:make : make.o
     14        c:make : make.o
    1515
    1616    is ok. To distinguish between device-names and target : or ::, MAKE
     
    2020- Replaces @@ by a newline in any command line:
    2121
    22         if exists make @@\
    23             delete make.bak quiet @@\
    24             rename make make.bak @@\
    25         endif @@\
    26         $(CC) Link Make.o To make
     22        if exists make @@\
     23            delete make.bak quiet @@\
     24            rename make make.bak @@\
     25        endif @@\
     26        $(CC) Link Make.o To make
    2727
    28     works. Note that the @@ must stand alone (ie. "make@@\" is illegal).
    29     Also be carefull that there is a space after the "\" (ie, at the
     28    works. Note that the @@ must stand alone (i.e., "make@@\" is illegal).
     29    Also be careful that there is a space after the "\" (i.e., at the
    3030    beginning of the next line).
    3131- Can be made resident to save space and time
     
    3737    dummy.h : src/*.c
    3838
    39 tries to make dummy.h from "src/*.c" (ie. no wildcard-expansion takes
     39tries to make dummy.h from "src/*.c" (i.e., no wildcard-expansion takes
    4040place). You have to use "$(wildcard src/*.c)" instead.
    4141
     
    4343----------------------
    4444
    45 To recompile, you need SAS/C 6.51. make itself is not neccessary, there
     45To recompile, you need SAS/C 6.51. make itself is not necessary, there
    4646is an smakefile.
    4747
    48481. Copy config.ami to config.h
    49 2. If you use make to compie, copy Makefile.ami to Makefile and
     492. If you use make to compile, copy Makefile.ami to Makefile and
    5050    glob/Makefile.ami to glob/Makefile. Copy make into the current
    5151    directory.
     
    5555INSTALLATION
    5656
    57 Copy make somewhere in your search path (eg. sc:c or sc:bin).
     57Copy make somewhere in your search path (e.g., sc:c or sc:bin).
    5858If you plan to use recursive makes, install make resident:
    5959
     
    6363
    6464-------------------------------------------------------------------------------
    65 Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
    66 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     65Copyright (C) 1995-2016 Free Software Foundation, Inc.
    6766This file is part of GNU Make.
    6867
  • trunk/src/kmk/README.DOS.template

    r2591 r3140  
    99
    1010   2. Supports both stock DOS COMMAND.COM and Unix-style shells
    11       (details in ``Notes'' below).
     11      (details in 'Notes' below).
    1212
    1313   3. Supports DOS drive letters in dependencies and pattern rules.
    1414
    1515   4. Better support for DOS-style backslashes in pathnames (but see
    16       ``Notes'' below).
     16      'Notes' below).
    1717
    1818   5. The $(shell) built-in can run arbitrary complex commands,
     
    5656      environment), or the DJGPP port of GNU Tar.
    5757
    58    2. Invoke the `configure.bat' batch file.
     58   2. Invoke the 'configure.bat' batch file.
    5959
    6060      If you are building Make in-place, i.e. in the same directory
     
    6363      directory as an argument to the batch file, like this:
    6464
    65         c:\djgpp\gnu\make-%VERSION%\configure.bat c:/djgpp/gnu/make-%VERSION%
     65        c:\djgpp\gnu\make-%VERSION%\configure.bat c:/djgpp/gnu/make-%VERSION%
    6666
    6767      Note the forward slashes in the source path argument: you MUST
     
    6969
    7070   3. If configure.bat doesn't find a working Make, it will suggest to
    71       use the `dosbuild.bat' batch file to build Make.  Either do as it
     71      use the 'dosbuild.bat' batch file to build Make.  Either do as it
    7272      suggests or install another Make program (a pre-compiled binary
    7373      should be available from the usual DJGPP sites) and rerun
     
    8585      need to tell Make where the sources are, like this:
    8686
    87                 make srcdir=c:/djgpp/gnu/make-%VERSION%
     87                make srcdir=c:/djgpp/gnu/make-%VERSION%
    8888
    8989      (configure.bat will tell you this when it finishes).  You MUST
     
    9292
    9393   6. After Make finishes, if you have a Unix-style shell installed,
    94       you can use the `install' target to install the package.  You
     94      you can use the 'install' target to install the package.  You
    9595      will also need GNU Fileutils and GNU Sed for this (they should
    9696      be available from the DJGPP sites).
     
    100100      DESTDIR variable when invoking "make install", like this:
    101101
    102                 make install DESTDIR=c:/other/dir
     102                make install DESTDIR=c:/other/dir
    103103
    104104      This causes the make executable to be placed in c:/other/dir/bin,
     
    108108      and the docs manually.  Copy make.exe to a directory on your
    109109      PATH, make.i* info files to your Info directory, and update the
    110       file `dir' in your Info directory by adding the following item
     110      file 'dir' in your Info directory by adding the following item
    111111      to the main menu:
    112112
    113         * Make: (make.info).           The GNU make utility.
    114 
    115       If you have the `install-info' program (from the GNU Texinfo
     113        * Make: (make.info).           The GNU make utility.
     114
     115      If you have the 'install-info' program (from the GNU Texinfo
    116116      package), it will do that for you if you invoke it like this:
    117117
    118         install-info --info-dir=c:/djgpp/info c:/djgpp/info/make.info
     118        install-info --info-dir=c:/djgpp/info c:/djgpp/info/make.info
    119119
    120120      (If your Info directory is other than C:\DJGPP\INFO, change this
    121121      command accordingly.)
    122122
    123    7. The `clean' targets also require Unix-style shell, and GNU Sed
    124       and `rm' programs (the latter from Fileutils).
     123   7. The 'clean' targets also require Unix-style shell, and GNU Sed
     124      and 'rm' programs (the latter from Fileutils).
    125125
    126126   8. To run the test suite, type "make check".  This requires a Unix
     
    145145      This port supports both DOS shells (the stock COMMAND.COM and its
    146146      4DOS/NDOS replacements), and Unix-style shells (tested with the
    147       venerable Stewartson's `ms_sh' 2.3 and the DJGPP port of `bash' by
     147      venerable Stewartson's 'ms_sh' 2.3 and the DJGPP port of 'bash' by
    148148      Daisuke Aoyama <[email protected]>).
    149149
     
    167167      batch file or a command internal to the shell is invoked.  (Even
    168168      when a command is an internal shell command, Make will first
    169       search the $PATH for it, so that if a Makefile calls `mkdir',
    170       you can install, say, a port of GNU `mkdir' and have it called
     169      search the $PATH for it, so that if a Makefile calls 'mkdir',
     170      you can install, say, a port of GNU 'mkdir' and have it called
    171171      in that case.)
    172172
    173       The key to all this is the extended functionality of `spawn' and
    174       `system' functions from the DJGPP library; this port just calls
    175       `system' where it would invoke the shell on Unix.  The most
     173      The key to all this is the extended functionality of 'spawn' and
     174      'system' functions from the DJGPP library; this port just calls
     175      'system' where it would invoke the shell on Unix.  The most
    176176      important aspect of these functions is that they use a special
    177177      mechanism to pass long (up to 16KB) command lines to DJGPP
    178       programs.  In addition, `system' emulates some internal
    179       commands, like `cd' (so that you can now use forward slashes
     178      programs.  In addition, 'system' emulates some internal
     179      commands, like 'cd' (so that you can now use forward slashes
    180180      with it, and can also change the drive if the directory is on
    181181      another drive).  Another aspect worth mentioning is that you can
     
    187187
    188188      The $(shell) built-in is implemented in this port by calling
    189       `popen'.  Since `popen' calls `system', the above considerations
     189      'popen'.  Since 'popen' calls 'system', the above considerations
    190190      are valid for $(shell) as well.  In particular, you can put
    191191      arbitrary complex commands, including pipes and redirection,
     
    198198      Many Unix Makefiles include a line which sets the SHELL, for
    199199      those versions of Make which don't have this as the default.
    200       Since many DOS systems don't have `sh' installed (in fact, most
    201       of them don't even have a `/bin' directory), this port takes
     200      Since many DOS systems don't have 'sh' installed (in fact, most
     201      of them don't even have a '/bin' directory), this port takes
    202202      such directives with a grain of salt.  It will only honor such a
    203       directive if the basename of the shell name (like `sh' in the
     203      directive if the basename of the shell name (like 'sh' in the
    204204      above example) can indeed be found in the directory that is
    205       mentioned in the SHELL= line (`/bin' in the above example), or
     205      mentioned in the SHELL= line ('/bin' in the above example), or
    206206      in the current working directory, or anywhere on the $PATH (in
    207207      that order).  If the basename doesn't include a filename
     
    238238      Makefiles to MSDOS and leave the line which sets the shell
    239239      intact, so that people who do have Unixy shell could use it for
    240       targets which aren't converted to DOS (like `install' and
    241       `uninstall', for example).
     240      targets which aren't converted to DOS (like 'install' and
     241      'uninstall', for example).
    242242
    243243
     
    259259      letter-case issue.  Make is internally case-sensitive, but all
    260260      file operations are case-insensitive on Windows 9x, so
    261       e.g. files `FAQ', `faq' and `Faq' all refer to the same file, as
     261      e.g. files 'FAQ', 'faq' and 'Faq' all refer to the same file, as
    262262      far as Windows is concerned.  The underlying DJGPP C library
    263263      functions honor the letter-case of the filenames they get from
     
    266266      many Makefiles otherwise.  (The details of which filenames are
    267267      converted to lower case are explained in the DJGPP libc docs,
    268       under the `_preserve_fncase' and `_lfn_gen_short_fname'
     268      under the '_preserve_fncase' and '_lfn_gen_short_fname'
    269269      functions, but as a thumb rule, any filename that is stored in
    270270      upper case in the directory, is a valid DOS 8+3 filename and
     
    283283      There are a lot of places throughout the program sources which
    284284      make implicit assumptions about the pathname syntax.  In
    285       particular, the directories are assumed to be separated by `/',
    286       and any pathname which doesn't begin with a `/' is assumed to be
     285      particular, the directories are assumed to be separated by '/',
     286      and any pathname which doesn't begin with a '/' is assumed to be
    287287      relative to the current directory.  This port attempts to
    288288      support DOS-style pathnames which might include the drive letter
     
    297297      are advised to stay away from backslashes whenever possible.  In
    298298      particular, filename globbing won't work on pathnames with
    299       backslashes, because the GNU `glob' library doesn't support them
     299      backslashes, because the GNU 'glob' library doesn't support them
    300300      (backslash is special in filename wildcards, and I didn't want
    301301      to break that).
     
    316316   group).  For other bugs, please follow the procedure explained in
    317317   the "Bugs" chapter of the Info docs.  If you don't have an Info
    318    reader, look up that chapter in the `make.i1' file with any text
     318   reader, look up that chapter in the 'make.i1' file with any text
    319319   browser/editor.
    320320
    321321
    322322   Enjoy,
    323                         Eli Zaretskii <[email protected]>
     323                        Eli Zaretskii <[email protected]>
    324324
    325325
    326326
    327327-------------------------------------------------------------------------------
    328 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    329 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     328Copyright (C) 1996-2016 Free Software Foundation, Inc.
    330329This file is part of GNU Make.
    331330
  • trunk/src/kmk/README.OS2.template

    r2591 r3140  
    141141_getcwd2() are NOT used).  The testsuite interpretes the whole output of
    142142make, especially statements like make[1]: Entering directory
    143 `C:/somewhere/make-3.79.1/tests' where the testsuite does not expect the
     143'C:/somewhere/make-3.79.1/tests' where the testsuite does not expect the
    144144drive letter. This would be interpreted as an error even if there is
    145145none.
     
    162162
    163163-------------------------------------------------------------------------------
    164 Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
    165 Foundation, Inc.
     164Copyright (C) 2003-2016 Free Software Foundation, Inc.
    166165This file is part of GNU Make.
    167166
  • trunk/src/kmk/README.W32.template

    r2591 r3140  
    1 This version of GNU make has been tested on Microsoft Windows 2000/XP/2003.
     1This version of GNU make has been tested on:
     2  Microsoft Windows 2000/XP/2003/Vista/7/8/10
    23It has also been used on Windows 95/98/NT, and on OS/2.
    34
    4 It builds with the MinGW port of GCC (tested with GCC 3.4.2).
    5 
    6 It also builds with MSVC 2.x, 4.x, 5.x, 6.x, and 2003 as well as
    7 with .NET 7.x and .NET 2003.
    8 
    9 The Windows 32-bit port of GNU make is maintained jointly by various
    10 people.  It was originally made by Rob Tulloh.
     5It builds with the MinGW port of GCC (tested with GCC 3.4.2, 4.8.1,
     6and 4.9.3).
     7
     8It also builds with MSVC 2.x, 4.x, 5.x, 6.x, 2003, and 14 (2015) as
     9well as with .NET 7.x and .NET 2003.
     10
     11As of version 4.0, a build with Guile is supported (tested with Guile
     122.0.3).  To build with Guile, you will need, in addition to Guile
     13itself, its dependency libraries and the pkg-config program.  The
     14latter is used to figure out which compilation and link switches and
     15libraries need to be mentioned on the compiler command lines to
     16correctly link with Guile.  A Windows port of pkg-config can be found
     17on ezwinports site:
     18
     19  http://sourceforge.net/projects/ezwinports/
     20
     21The libraries on which Guile depends can vary depending on your
     22version and build of Guile.  At the very least, the Boehm's GC library
     23will be needed, and typically also GNU MP, libffi, libunistring, and
     24libtool's libltdl.  Whoever built the port of Guile you have should
     25also provide you with these dependencies or a URL where to download
     26them.  A precompiled 32-bit Windows build of Guile is available from
     27the ezwinports site mentioned above.
     28
     29The Windows port of GNU make is maintained jointly by various people.
     30It was originally made by Rob Tulloh.
     31It is currently maintained by Eli Zaretskii.
    1132
    1233
     
    1435---------------------------------------------------------
    1536
    16  1. At the Windows command prompt run:
    17 
    18       if not exist NMakefile copy NMakefile.template NMakefile
    19       if not exist config.h copy config.h.W32 config.h
    20 
    21     Then edit config.h to your liking (especially the few shell-related
     37 1. Edit config.h.W32 to your liking (especially the few shell-related
    2238    defines near the end, or HAVE_CASE_INSENSITIVE_FS which corresponds
    23     to './configure --enable-case-insensitive-file-system').
     39    to './configure --enable-case-insensitive-file-system').  (We don't
     40    recommend to define HAVE_CASE_INSENSITIVE_FS, but you may wish to
     41    consider that if you have a lot of files whose names are in upper
     42    case, while Makefile rules are written for lower-case versions.)
    2443
    2544
     
    3857    correct PATH and other environment variables for it, then execute ...
    3958
    40         build_w32.bat gcc
    41 
    42     This produces gnumake.exe in the current directory.
     59        build_w32.bat gcc
     60
     61    This produces gnumake.exe in the GccRel directory.
     62    If you want a version of GNU make built with debugging enabled,
     63    add the --debug option.
     64
     65    The batch file will probe for Guile installation, and will build
     66    gnumake.exe with Guile if it finds it.  If you have Guile
     67    installed, but want to build Make without Guile support, type
     68
     69        build_w32.bat --without-guile gcc
    4370
    4471
     
    5279    menue entry from the cl-installation), then execute EITHER ...
    5380
    54         build_w32.bat
    55 
    56     (this produces WinDebug/gnumake.exe and WinRel/gnumake.exe)
     81        build_w32.bat
     82
     83    This produces gnumake.exe in the WinRel directory.
     84    If you want a version of GNU make built with debugging enabled,
     85    add the --debug option.
    5786
    5887    ... OR ...
    5988
    60         nmake /f NMakefile
     89        nmake /f NMakefile
    6190
    6291    (this produces WinDebug/make.exe and WinRel/make.exe).
    6392
     93    The batch file will probe for Guile installation, and will build
     94    gnumake.exe with Guile if it finds it.  If you have Guile
     95    installed, but want to build Make without Guile support, type
     96
     97        build_w32.bat --without-guile
    6498
    6599-------------------
     
    69103GNU make on Windows 32-bit platforms:
    70104
    71         This version of make is ported natively to Windows32 platforms
    72         (Windows NT 3.51, Windows NT 4.0, Windows 2000, Windows XP,
    73         Windows 95, and Windows 98). It does not rely on any 3rd party
    74         software or add-on packages for building. The only thing
    75         needed is a Windows compiler.  Two compilers supported
    76         officially are the MinGW port of GNU GCC, and the various
    77         versions of the Microsoft C compiler.
    78 
    79         Do not confuse this port of GNU make with other Windows32 projects
    80         which provide a GNU make binary. These are separate projects
    81         and are not connected to this port effort.
     105        This version of make is ported natively to Windows32 platforms
     106        (Windows NT 3.51, Windows NT 4.0, Windows 2000, Windows XP,
     107        Windows 95, and Windows 98). It does not rely on any 3rd party
     108        software or add-on packages for building. The only thing
     109        needed is a Windows compiler.  Two compilers supported
     110        officially are the MinGW port of GNU GCC, and the various
     111        versions of the Microsoft C compiler.
     112
     113        Do not confuse this port of GNU make with other Windows32 projects
     114        which provide a GNU make binary. These are separate projects
     115        and are not connected to this port effort.
    82116
    83117GNU make and sh.exe:
    84118
    85         This port prefers if you have a working sh.exe somewhere on
    86         your system. If you don't have sh.exe, the port falls back to
    87         MSDOS mode for launching programs (via a batch file).  The
    88         MSDOS mode style execution has not been tested that carefully
    89         though (The author uses GNU bash as sh.exe).
    90 
    91         There are very few true ports of Bourne shell for NT right now.
    92         There is a version of GNU bash available from Cygnus "Cygwin"
    93         porting effort (http://www.cygwin.com/).
    94         Other possibilities are the MKS version of sh.exe, or building
     119        This port prefers if you have a working sh.exe somewhere on
     120        your system. If you don't have sh.exe, the port falls back to
     121        MSDOS mode for launching programs (via a batch file).  The
     122        MSDOS mode style execution has not been tested that carefully
     123        though (The author uses GNU bash as sh.exe).
     124
     125        There are very few true ports of Bourne shell for NT right now.
     126        There is a version of GNU bash available from Cygnus "Cygwin"
     127        porting effort (http://www.cygwin.com/).
     128        Other possibilities are the MKS version of sh.exe, or building
    95129        your own with a package like NutCracker (DataFocus) or Portage
    96130        (Consensys).  Also MinGW includes sh (http://mingw.org/).
     
    98132GNU make and brain-dead shells (BATCH_MODE_ONLY_SHELL):
    99133
    100         Some versions of Bourne shell do not behave well when invoked
    101         as 'sh -c' from CreateProcess().  The main problem is they seem
    102         to have a hard time handling quoted strings correctly. This can
    103         be circumvented by writing commands to be executed to a batch
    104         file and then executing the command by calling 'sh file'.
    105 
    106         To work around this difficulty, this version of make supports
    107         a batch mode.  When BATCH_MODE_ONLY_SHELL is defined at compile
    108         time, make forces all command lines to be executed via script
    109         files instead of by command line.  In this mode you must have a
    110         working sh.exe in order to use parallel builds (-j).
    111 
    112         A native Windows32 system with no Bourne shell will also run
    113         in batch mode.  All command lines will be put into batch files
    114         and executed via $(COMSPEC) (%COMSPEC%).  However, parallel
    115         builds ARE supported with Windows shells (cmd.exe and
    116         command.com).  See the next section about some peculiarities
    117         of parallel builds on Windows.
     134        Some versions of Bourne shell do not behave well when invoked
     135        as 'sh -c' from CreateProcess().  The main problem is they seem
     136        to have a hard time handling quoted strings correctly. This can
     137        be circumvented by writing commands to be executed to a batch
     138        file and then executing the command by calling 'sh file'.
     139
     140        To work around this difficulty, this version of make supports
     141        a batch mode.  When BATCH_MODE_ONLY_SHELL is defined at compile
     142        time, make forces all command lines to be executed via script
     143        files instead of by command line.  In this mode you must have a
     144        working sh.exe in order to use parallel builds (-j).
     145
     146        A native Windows32 system with no Bourne shell will also run
     147        in batch mode.  All command lines will be put into batch files
     148        and executed via $(COMSPEC) (%COMSPEC%).  However, parallel
     149        builds ARE supported with Windows shells (cmd.exe and
     150        command.com).  See the next section about some peculiarities
     151        of parallel builds on Windows.
    118152
    119153Support for parallel builds
    120154
    121         Parallel builds (-jN) are supported in this port, with 2
    122         limitations:
    123 
    124           - The number of concurrent processes has a hard limit of 64,
    125             due to the way this port implements waiting for its
    126             subprocesses;
    127 
    128           - The job server method (available when Make runs on Posix
    129             platforms) is not supported, which means you must pass an
    130             explicit -jN switch to sub-Make's in a recursive Makefile.
    131             If a sub-Make does not receive an explicit -jN switch, it
    132             will default to -j1, i.e. no parallelism in sub-Make's.
     155        Parallel builds (-jN) are supported in this port, with 1
     156        limitation: The number of concurrent processes has a hard
     157        limit of 64, due to the way this port implements waiting for
     158        its subprocesses.
    133159
    134160GNU make and Cygnus GNU Windows32 tools:
    135161
    136         Good news! Make now has native support for Cygwin sh. To enable,
    137         define the HAVE_CYGWIN_SHELL in config.h and rebuild make
    138         from scratch. This version of make tested with B20.1 of Cygwin.
    139         Do not define BATCH_MODE_ONLY_SHELL if you use HAVE_CYGWIN_SHELL.
     162        Good news! Make now has native support for Cygwin sh. To enable,
     163        define the HAVE_CYGWIN_SHELL in config.h and rebuild make
     164        from scratch. This version of make tested with B20.1 of Cygwin.
     165        Do not define BATCH_MODE_ONLY_SHELL if you use HAVE_CYGWIN_SHELL.
    140166
    141167GNU make and the MKS shell:
    142168
    143         There is now semi-official support for the MKS shell. To turn this
    144         support on, define HAVE_MKS_SHELL in the config.h.W32 before you
    145         build make.  Do not define BATCH_MODE_ONLY_SHELL if you turn
    146         on HAVE_MKS_SHELL.
     169        There is now semi-official support for the MKS shell. To turn this
     170        support on, define HAVE_MKS_SHELL in the config.h.W32 before you
     171        build make.  Do not define BATCH_MODE_ONLY_SHELL if you turn
     172        on HAVE_MKS_SHELL.
    147173
    148174GNU make handling of drive letters in pathnames (PATH, vpath, VPATH):
    149175
    150         There is a caveat that should be noted with respect to handling
    151         single character pathnames on Windows systems.  When colon is
    152         used in PATH variables, make tries to be smart about knowing when
    153         you are using colon as a separator versus colon as a drive
    154         letter. Unfortunately, something as simple as the string 'x:/'
    155         could be interpreted 2 ways: (x and /) or (x:/).
    156 
    157         Make chooses to interpret a letter plus colon (e.g. x:/) as a
    158         drive letter pathname.  If it is necessary to use single
    159         character directories in paths (VPATH, vpath, Path, PATH), the
    160         user must do one of two things:
    161 
    162         a. Use semicolon as the separator to disambiguate colon. For
    163             example use 'x;/' if you want to say 'x' and '/' are
    164             separate components.
    165 
    166         b. Qualify the directory name so that there is more than
    167             one character in the path(s) used. For example, none
    168             of these settings are ambiguous:
    169 
    170               ./x:./y
    171               /some/path/x:/some/path/y
    172               x:/some/path/x:x:/some/path/y
    173 
    174         Please note that you are free to mix colon and semi-colon in the
    175         specification of paths. Make is able to figure out the intended
    176         result and convert the paths internally to the format needed
    177         when interacting with the operating system, providing the path
    178         is not within quotes, e.g. "x:/test/test.c".
    179 
    180         You are encouraged to use colon as the separator character.
    181         This should ease the pain of deciding how to handle various path
    182         problems which exist between platforms. If colon is used on
    183         both Unix and Windows systems, then no ifdef'ing will be
    184         necessary in the makefile source.
     176        There is a caveat that should be noted with respect to handling
     177        single character pathnames on Windows systems.  When colon is
     178        used in PATH variables, make tries to be smart about knowing when
     179        you are using colon as a separator versus colon as a drive
     180        letter. Unfortunately, something as simple as the string 'x:/'
     181        could be interpreted 2 ways: (x and /) or (x:/).
     182
     183        Make chooses to interpret a letter plus colon (e.g. x:/) as a
     184        drive letter pathname.  If it is necessary to use single
     185        character directories in paths (VPATH, vpath, Path, PATH), the
     186        user must do one of two things:
     187
     188        a. Use semicolon as the separator to disambiguate colon. For
     189            example use 'x;/' if you want to say 'x' and '/' are
     190            separate components.
     191
     192        b. Qualify the directory name so that there is more than
     193            one character in the path(s) used. For example, none
     194            of these settings are ambiguous:
     195
     196              ./x:./y
     197              /some/path/x:/some/path/y
     198              x:/some/path/x:x:/some/path/y
     199
     200        Please note that you are free to mix colon and semi-colon in the
     201        specification of paths. Make is able to figure out the intended
     202        result and convert the paths internally to the format needed
     203        when interacting with the operating system, providing the path
     204        is not within quotes, e.g. "x:/test/test.c".
     205
     206        You are encouraged to use colon as the separator character.
     207        This should ease the pain of deciding how to handle various path
     208        problems which exist between platforms. If colon is used on
     209        both Unix and Windows systems, then no ifdef'ing will be
     210        necessary in the makefile source.
    185211
    186212GNU make test suite:
    187213
    188         I verified all functionality with a slightly modified version
    189         of make-test-%VERSION% (modifications to get test suite to run
    190         on Windows NT). All tests pass in an environment that includes
    191         sh.exe.  Tests were performed on both Windows NT and Windows 95.
     214        I verified all functionality with a slightly modified version
     215        of make-test-%VERSION% (modifications to get test suite to run
     216        on Windows NT). All tests pass in an environment that includes
     217        sh.exe.  Tests were performed on both Windows NT and Windows 95.
    192218
    193219Pathnames and white space:
    194220
    195         Unlike Unix, Windows 95/NT systems encourage pathnames which
    196         contain white space (e.g. C:\Program Files\). These sorts of
    197         pathnames are valid on Unix too, but are never encouraged.
    198         There is at least one place in make (VPATH/vpath handling) where
    199         paths containing white space will simply not work. There may be
    200         others too. I chose to not try and port make in such a way so
    201         that these sorts of paths could be handled. I offer these
    202         suggestions as workarounds:
    203 
    204                 1. Use 8.3 notation. i.e. "x:/long~1/", which is actually
    205                    "x:\longpathtest".  Type "dir /x" to view these filenames
    206                    within the cmd.exe shell.
    207                 2. Rename the directory so it does not contain white space.
    208 
    209         If you are unhappy with this choice, this is free software
    210         and you are free to take a crack at making this work. The code
    211         in w32/pathstuff.c and vpath.c would be the places to start.
     221        Unlike Unix, Windows 95/NT systems encourage pathnames which
     222        contain white space (e.g. C:\Program Files\). These sorts of
     223        pathnames are valid on Unix too, but are never encouraged.
     224        There is at least one place in make (VPATH/vpath handling) where
     225        paths containing white space will simply not work. There may be
     226        others too. I chose to not try and port make in such a way so
     227        that these sorts of paths could be handled. I offer these
     228        suggestions as workarounds:
     229
     230                1. Use 8.3 notation. i.e. "x:/long~1/", which is actually
     231                   "x:\longpathtest".  Type "dir /x" to view these filenames
     232                   within the cmd.exe shell.
     233                2. Rename the directory so it does not contain white space.
     234
     235        If you are unhappy with this choice, this is free software
     236        and you are free to take a crack at making this work. The code
     237        in w32/pathstuff.c and vpath.c would be the places to start.
    212238
    213239Pathnames and Case insensitivity:
    214240
    215         Unlike Unix, Windows 95/NT systems are case insensitive but case
    216         preserving.  For example if you tell the file system to create a
    217         file named "Target", it will preserve the case.  Subsequent access to
    218         the file with other case permutations will succeed (i.e. opening a
    219         file named "target" or "TARGET" will open the file "Target").
    220 
    221         By default, GNU make retains its case sensitivity when comparing
    222         target names and existing files or directories.  It can be
    223         configured, however, into a case preserving and case insensitive
    224         mode by adding a define for HAVE_CASE_INSENSITIVE_FS to
    225         config.h.W32.
    226 
    227         For example, the following makefile will create a file named
    228         Target in the directory subdir which will subsequently be used
    229         to satisfy the dependency of SUBDIR/DepTarget on SubDir/TARGET.
    230         Without HAVE_CASE_INSENSITIVE_FS configured, the dependency link
    231         will not be made:
    232 
    233         subdir/Target:
    234                 touch $@
    235 
    236         SUBDIR/DepTarget: SubDir/TARGET
    237                 cp $^ $@
    238 
    239         Reliance on this behavior also eliminates the ability of GNU make
    240         to use case in comparison of matching rules.  For example, it is
    241         not possible to set up a C++ rule using %.C that is different
    242         than a C rule using %.c.  GNU make will consider these to be the
    243         same rule and will issue a warning.
     241        Unlike Unix, Windows 95/NT systems are case insensitive but case
     242        preserving.  For example if you tell the file system to create a
     243        file named "Target", it will preserve the case.  Subsequent access to
     244        the file with other case permutations will succeed (i.e. opening a
     245        file named "target" or "TARGET" will open the file "Target").
     246
     247        By default, GNU make retains its case sensitivity when comparing
     248        target names and existing files or directories.  It can be
     249        configured, however, into a case preserving and case insensitive
     250        mode by adding a define for HAVE_CASE_INSENSITIVE_FS to
     251        config.h.W32.
     252
     253        For example, the following makefile will create a file named
     254        Target in the directory subdir which will subsequently be used
     255        to satisfy the dependency of SUBDIR/DepTarget on SubDir/TARGET.
     256        Without HAVE_CASE_INSENSITIVE_FS configured, the dependency link
     257        will not be made:
     258
     259        subdir/Target:
     260                touch $@
     261
     262        SUBDIR/DepTarget: SubDir/TARGET
     263                cp $^ $@
     264
     265        Reliance on this behavior also eliminates the ability of GNU make
     266        to use case in comparison of matching rules.  For example, it is
     267        not possible to set up a C++ rule using %.C that is different
     268        than a C rule using %.c.  GNU make will consider these to be the
     269        same rule and will issue a warning.
    244270
    245271SAMBA/NTFS/VFAT:
    246272
    247         I have not had any success building the debug version of this
    248         package using SAMBA as my file server. The reason seems to be
    249         related to the way VC++ 4.0 changes the case name of the pdb
    250         filename it is passed on the command line. It seems to change
    251         the name always to to lower case. I contend that the VC++
    252         compiler should not change the casename of files that are passed
    253         as arguments on the command line. I don't think this was a
    254         problem in MSVC 2.x, but I know it is a problem in MSVC 4.x.
    255 
    256         The package builds fine on VFAT and NTFS filesystems.
    257 
    258         Most all of the development I have done to date has been using
    259         NTFS and long file names. I have not done any considerable work
    260         under VFAT. VFAT users may wish to be aware that this port of
    261         make does respect case sensitivity.
     273        I have not had any success building the debug version of this
     274        package using SAMBA as my file server. The reason seems to be
     275        related to the way VC++ 4.0 changes the case name of the pdb
     276        filename it is passed on the command line. It seems to change
     277        the name always to to lower case. I contend that the VC++
     278        compiler should not change the casename of files that are passed
     279        as arguments on the command line. I don't think this was a
     280        problem in MSVC 2.x, but I know it is a problem in MSVC 4.x.
     281
     282        The package builds fine on VFAT and NTFS filesystems.
     283
     284        Most all of the development I have done to date has been using
     285        NTFS and long file names. I have not done any considerable work
     286        under VFAT. VFAT users may wish to be aware that this port of
     287        make does respect case sensitivity.
    262288
    263289FAT:
    264290
    265         Version 3.76 added support for FAT filesystems. Make works
    266         around some difficulties with stat'ing of files and caching of
    267         filenames and directories internally.
     291        Version 3.76 added support for FAT filesystems. Make works
     292        around some difficulties with stat'ing of files and caching of
     293        filenames and directories internally.
    268294
    269295Bug reports:
    270296
    271         Please submit bugs via the normal bug reporting mechanism which
    272         is described in the GNU make manual and the base README.
     297        Please submit bugs via the normal bug reporting mechanism which
     298        is described in the GNU make manual and the base README.
    273299
    274300
    275301-------------------------------------------------------------------------------
    276 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    277 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     302Copyright (C) 1996-2016 Free Software Foundation, Inc.
    278303This file is part of GNU Make.
    279304
  • trunk/src/kmk/README.customs

    r2591 r3140  
    3636documentation.  You should also install the man pages (contrary to
    3737comments in the documentation, they weren't installed automatically for
    38 me; I had to cd to the ``pmake-2.1.33/doc'' directory and run ``pmake
    39 install'' there directly).
     38me; I had to cd to the 'pmake-2.1.33/doc' directory and run 'pmake
     39install' there directly).
    4040
    4141
     
    4444
    4545Once you've installed Customs, you can build GNU make to use it.  When
    46 configuring GNU make, merely use the ``--with-customs=DIR'' option.
    47 Provide the directory containing the ``lib'' and ``include/customs''
     46configuring GNU make, merely use the '--with-customs=DIR' option.
     47Provide the directory containing the 'lib' and 'include/customs'
    4848subdirectories as DIR.  For example, if you installed the customs
    4949library in /usr/local/lib and the headers in /usr/local/include/customs,
    50 then you'd pass ``--with-customs=/usr/local'' as an option to configure.
     50then you'd pass '--with-customs=/usr/local' as an option to configure.
    5151
    5252Run make (or use build.sh) normally to build GNU make as described in
     
    9898
    9999-------------------------------------------------------------------------------
    100 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
    101 2009, 2010 Free Software Foundation, Inc.
     100Copyright (C) 1998-2016 Free Software Foundation, Inc.
    102101This file is part of GNU Make.
    103102
  • trunk/src/kmk/README.template

    r2591 r3140  
    99For general building and installation instructions, see the file INSTALL.
    1010
    11 If you need to build GNU Make and have no other `make' program to use,
    12 you can use the shell script `build.sh' instead.  To do this, first run
    13 `configure' as described in INSTALL.  Then, instead of typing `make' to
    14 build the program, type `sh build.sh'.  This should compile the program
     11If you need to build GNU Make and have no other 'make' program to use,
     12you can use the shell script 'build.sh' instead.  To do this, first run
     13'configure' as described in INSTALL.  Then, instead of typing 'make' to
     14build the program, type 'sh build.sh'.  This should compile the program
    1515in the current directory.  Then you will have a Make program that you can
    16 use for `./make install', or whatever else.
     16use for './make install', or whatever else.
    1717
    1818Some systems' Make programs are broken and cannot process the Makefile for
    1919GNU Make.  If you get errors from your system's Make when building GNU
    20 Make, try using `build.sh' instead.
     20Make, try using 'build.sh' instead.
    2121
    2222
    2323GNU Make is free software.  See the file COPYING for copying conditions.
    24 
     24GNU Make is copyright by the Free Software Foundation.  Copyright notices
     25condense sequential years into a range; e.g. "1987-1994" means all years
     26from 1987 to 1994 inclusive.
    2527
    2628Downloading
     
    6567
    6668You can send GNU make bug reports to <[email protected]>.  Please see the
    67 section of the GNU make manual entitled `Problems and Bugs' for
     69section of the GNU make manual entitled 'Problems and Bugs' for
    6870information on submitting useful and complete bug reports.
    6971
     
    8082  news:gnu.utils.bug
    8183
    82   http://savannah.gnu.org/support/?group=make
    8384
    84 You may also find interesting patches to GNU Make available here:
    85 
    86   http://savannah.gnu.org/patch/?group=make
    87 
    88 Note these patches are provided by our users as a service and we make no
    89 statements regarding their correctness.  Please contact the authors
    90 directly if you have a problem or suggestion for a patch available on
    91 this page.
    92 
    93 
    94 CVS Access
     85Git Access
    9586----------
    9687
    97 The GNU make source repository is available via anonymous CVS from the
    98 GNU Subversions CVS server; look here for details:
     88The GNU make source repository is available via Git from the
     89GNU Savannah Git server; look here for details:
    9990
    100   http://savannah.gnu.org/cvs/?group=make
     91  http://savannah.gnu.org/git/?group=make
    10192
    102 Please note: you won't be able to build GNU make from CVS without
     93Please note: you won't be able to build GNU make from Git without
    10394installing appropriate maintainer's tools, such as GNU m4, automake,
    104 autoconf, Perl, GNU make, and GCC.  See the README.cvs file for hints on
     95autoconf, Perl, GNU make, and GCC.  See the README.git file for hints on
    10596how to build GNU make once these tools are available.  We make no
    106 guarantees about the contents or quality of the latest code in the CVS
     97guarantees about the contents or quality of the latest code in the Git
    10798repository: it is not unheard of for code that is known to be broken to
    10899be checked in.  Use at your own risk.
     
    113104
    114105It has been reported that the XLC 1.2 compiler on AIX 3.2 is buggy such
    115 that if you compile make with `cc -O' on AIX 3.2, it will not work
    116 correctly.  It is said that using `cc' without `-O' does work.
     106that if you compile make with 'cc -O' on AIX 3.2, it will not work
     107correctly.  It is said that using 'cc' without '-O' does work.
    117108
    118109The standard /bin/sh on SunOS 4.1.3_U1 and 4.1.4 is broken and cannot be
     
    124115One area that is often a problem in configuration and porting is the code
    125116to check the system's current load average.  To make it easier to test and
    126 debug this code, you can do `make check-loadavg' to see if it works
    127 properly on your system.  (You must run `configure' beforehand, but you
     117debug this code, you can do 'make check-loadavg' to see if it works
     118properly on your system.  (You must run 'configure' beforehand, but you
    128119need not build Make itself to run this test.)
    129120
     
    132123Please report any bugs that you find in this area.  If you run into
    133124difficulties, then as a workaround you should be able to disable LFS by
    134 adding the `--disable-largefile' option to the `configure' script.
     125adding the '--disable-largefile' option to the 'configure' script.
    135126
    136127On systems that support micro- and nano-second timestamp values and
     
    152143    Customs distributed build environment from the Pmake distribution.
    153144
    154   - See readme.vms for details about GNU Make on OpenVMS.
     145  - See README.VMS for details about GNU Make on OpenVMS.
    155146
    156147  - See README.Amiga for details about GNU Make on AmigaDOS.
     
    173164
    174165-------------------------------------------------------------------------------
    175 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    176 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    177 2010 Free Software Foundation, Inc.
     166Copyright (C) 1988-2016 Free Software Foundation, Inc.
    178167This file is part of GNU Make.
    179168
  • trunk/src/kmk/SMakefile.template

    r2591 r3140  
    44# run 'build.sh' instead.
    55#
    6 # Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
    7 # 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     6# Copyright (C) 1995-2016 Free Software Foundation, Inc.
    87# This file is part of GNU Make.
    98#
     
    2726# Ultrix 2.2 make doesn't expand the value of VPATH.
    2827VPATH = /make-%VERSION%/
    29 # This must repeat the value, because configure will remove `VPATH = .'.
     28# This must repeat the value, because configure will remove 'VPATH = .'.
    3029srcdir = /make-%VERSION%/
    3130
     
    3938
    4039# Define these for your system as follows:
    41 #       -DNO_ARCHIVES           To disable `ar' archive support.
     40#       -DNO_ARCHIVES           To disable 'ar' archive support.
    4241#       -DNO_FLOAT              To avoid using floating-point numbers.
    4342#       -DENUM_BITFIELDS        If the compiler isn't GCC but groks enum foo:2.
     
    4645#                               so beware.
    4746# NeXT 1.0a uses an old version of GCC, which required -D__inline=inline.
    48 # See also `config.h'.
     47# See also 'config.h'.
    4948defines =
    5049
    5150# Which flavor of remote job execution support to use.
    52 # The code is found in `remote-$(REMOTE).c'.
     51# The code is found in 'remote-$(REMOTE).c'.
    5352REMOTE = stub
    5453
     
    8483exec_prefix =
    8584
    86 # Directory to install `make' in.
     85# Directory to install 'make' in.
    8786bindir = sc:c
    88 # Directory to find libraries in for `-lXXX'.
     87# Directory to find libraries in for '-lXXX'.
    8988libdir = lib:
    9089# Directory to search by default for included makefiles.
     
    9695# Number to put on the man page filename.
    9796manext = 1
    98 # Prefix to put on installed `make' binary file name.
     97# Prefix to put on installed 'make' binary file name.
    9998binprefix =
    100 # Prefix to put on installed `make' man page file name.
     99# Prefix to put on installed 'make' man page file name.
    101100manprefix = $(binprefix)
    102101
    103102# Whether or not make needs to be installed setgid.
    104 # The value should be either `true' or `false'.
    105 # On many systems, the getloadavg function (used to implement the `-l'
     103# The value should be either 'true' or 'false'.
     104# On many systems, the getloadavg function (used to implement the '-l'
    106105# switch) will not work unless make is installed setgid kmem.
    107106install_setgid = false
     
    109108group = sys
    110109
    111 # Program to install `make'.
     110# Program to install 'make'.
    112111INSTALL_PROGRAM = copy
    113112# Program to install the man page.
     
    125124CTAGS = ctags -w
    126125
    127 objs = commands.o job.o dir.o file.o misc.o main.o read.o remake.o      \
    128        rule.o implicit.o default.o variable.o expand.o function.o       \
    129        vpath.o version.o ar.o arscan.o signame.o strcache.o hash.o      \
    130        remote-$(REMOTE).o $(GLOB) $(GETOPT) $(ALLOCA) $(extras)
     126#guile = guile.o
     127
     128objs = commands.o job.o dir.o file.o misc.o main.o read.o remake.o   \
     129       rule.o implicit.o default.o variable.o expand.o function.o    \
     130       vpath.o version.o ar.o arscan.o signame.o strcache.o hash.o   \
     131       output.o remote-$(REMOTE).o $(GLOB) $(GETOPT) $(ALLOCA)       \
     132       $(extras) $(guile)
     133
    131134srcs = $(srcdir)commands.c $(srcdir)job.c $(srcdir)dir.c             \
    132135       $(srcdir)file.c $(srcdir)getloadavg.c $(srcdir)misc.c         \
     
    135138       $(srcdir)variable.c $(srcdir)expand.c $(srcdir)function.c     \
    136139       $(srcdir)vpath.c $(srcdir)version.c $(srcdir)hash.c           \
    137        $(srcdir)remote-$(REMOTE).c                                     \
    138        $(srcdir)ar.c $(srcdir)arscan.c $(srcdir)strcache.c              \
    139        $(srcdir)signame.c $(srcdir)signame.h $(GETOPT_SRC)            \
     140       $(srcdir)guile.c $(srcdir)remote-$(REMOTE).c                  \
     141       $(srcdir)ar.c $(srcdir)arscan.c $(srcdir)strcache.c           \
     142       $(srcdir)signame.c $(srcdir)signame.h $(GETOPT_SRC)           \
    140143       $(srcdir)commands.h $(srcdir)dep.h $(srcdir)file.h            \
    141        $(srcdir)job.h $(srcdir)make.h $(srcdir)rule.h                \
     144       $(srcdir)job.h $(srcdir)makeint.h $(srcdir)rule.h             \
     145       $(srcdir)output.c $(srcdir)output.h                           \
    142146       $(srcdir)variable.h $(ALLOCA_SRC) $(srcdir)config.h.in
    143147
     
    149153info: make.info
    150154dvi: make.dvi
    151 # Some makes apparently use .PHONY as the default goal if it is before `all'.
     155# Some makes apparently use .PHONY as the default goal if it is before 'all'.
    152156.PHONY: all check info dvi
    153157
  • trunk/src/kmk/TODO.private

    r2591 r3140  
    77They are listed in no particular order!
    88
    9 Also, I don't gaurantee that all of them will be ultimately deemed "good
     9Also, I don't guarantee that all of them will be ultimately deemed "good
    1010ideas" and implemented.  These are just the ones that, at first blush,
    1111seem to have some merit (and that I can remember).
     
    100100    means this isn't 100% trivial, but it probably won't be hard.
    101101
    102  8) Integration of Guile as an embedded scripting language.  This means:
    103     allowing Guile functions to be declared in makefiles somehow, then
    104     providing a syntax for invoking them.  At least one formulation of
    105     that would have the function resolve to a string which would be
    106     substituted in the makefile, kind of like $(shell ...) does now, but
    107     using the embedded interpreter so there's no process forked of
    108     course.  Obviously this is an optional add-on feature.
    109 
    110     It could be more advanced than that, even, who knows?  Maybe make
    111     could provide Guile functions that allow Guile scripts more direct
    112     access to internal make structures, somehow.  This kind of thing
    113     needs a lot of thought.
    114 
    115     Also there's always the flip side: in some very fundamental ways
    116     make isn't the best choice right now for a complex build tool.  It's
    117     great for simple-to-medium tasks, but there are already other tools
    118     available for the really tough situations.  Ask yourself,
    119     realistically, how much work is worthwhile to add to make, given the
    120     fundamentals you can't really overcome without significantly
    121     affecting backward compatibility--and then why not use another tool
    122     in the first place?
    123 
    124     Something to think about.
    125 
    126102
    127103
    128104-------------------------------------------------------------------------------
    129 Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    130 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     105Copyright (C) 1997-2016 Free Software Foundation, Inc.
    131106This file is part of GNU Make.
    132107
  • trunk/src/kmk/acinclude.m4

    r2591 r3140  
    22dnl
    33dnl Automake will incorporate this into its generated aclocal.m4.
    4 dnl Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
    5 dnl 2008, 2009, 2010 Free Software Foundation, Inc.
     4dnl Copyright (C) 1998-2016 Free Software Foundation, Inc.
    65dnl This file is part of GNU Make.
    76dnl
     
    101100dnl ---------------------------------------------------------------------------
    102101dnl From Paul Eggert <[email protected]>
     102dnl Update for Darwin by Troy Runkel <[email protected]>
     103dnl Update for AIX by Olexiy Buyanskyy (Savannah bug 32485)
    103104
    104105AC_DEFUN([AC_STRUCT_ST_MTIM_NSEC],
    105  [AC_CACHE_CHECK([for nanoseconds field of struct stat.st_mtim],
     106 [AC_CACHE_CHECK([for nanoseconds field of struct stat],
    106107   ac_cv_struct_st_mtim_nsec,
    107108   [ac_save_CPPFLAGS="$CPPFLAGS"
    108109    ac_cv_struct_st_mtim_nsec=no
    109     # tv_nsec -- the usual case
    110     # _tv_nsec -- Solaris 2.6, if
     110    # st_mtim.tv_nsec -- the usual case
     111    # st_mtim._tv_nsec -- Solaris 2.6, if
    111112    #   (defined _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED == 1
    112113    #    && !defined __EXTENSIONS__)
    113     # st__tim.tv_nsec -- UnixWare 2.1.2
    114     for ac_val in tv_nsec _tv_nsec st__tim.tv_nsec; do
     114    # st_mtim.st__tim.tv_nsec -- UnixWare 2.1.2
     115    # st_mtime_n -- AIX 5.2 and above
     116    # st_mtimespec.tv_nsec -- Darwin (Mac OSX)
     117    for ac_val in st_mtim.tv_nsec st_mtim._tv_nsec st_mtim.st__tim.tv_nsec st_mtime_n st_mtimespec.tv_nsec; do
    115118      CPPFLAGS="$ac_save_CPPFLAGS -DST_MTIM_NSEC=$ac_val"
    116119      AC_TRY_COMPILE([#include <sys/types.h>
    117120#include <sys/stat.h>
    118         ], [struct stat s; s.st_mtim.ST_MTIM_NSEC;],
     121        ], [struct stat s; s.ST_MTIM_NSEC;],
    119122        [ac_cv_struct_st_mtim_nsec=$ac_val; break])
    120123    done
  • trunk/src/kmk/alloca.c

    r53 r3140  
    117117find_stack_direction (void)
    118118{
    119   static char *addr = NULL;     /* Address of first `dummy', once known.  */
     119  static char *addr = NULL;     /* Address of first 'dummy', once known.  */
    120120  auto char dummy;              /* To get stack address.  */
    121121
  • trunk/src/kmk/alloccache.c

    r2633 r3140  
    3838*   Header Files                                                               *
    3939*******************************************************************************/
    40 #include "make.h"
     40#include "makeint.h"
    4141#include "dep.h"
    4242#include "debug.h"
     
    6767  cache->free_head = f;
    6868  MAKE_STATS(cache->free_count++;);
    69 #else
    70   free(item);
    71 #endif
     69#else  /* CONFIG_WITH_ALLOCCACHE_DEBUG */
     70
     71  struct alloccache **ppcache = (struct alloccache **)item - 1;
     72  MY_ASSERT_MSG (*ppcache == cache, ("*ppcache=%p cache=%p item=%p\n", *ppcache, cache, item));
     73  *ppcache = NULL;
     74  free(ppcache);
     75#endif /* CONFIG_WITH_ALLOCCACHE_DEBUG */
    7276}
    7377
     
    99103  /* caller counts */
    100104  return (struct alloccache_free_ent *)item;
    101 #else
    102   return (struct alloccache_free_ent *)xmalloc(cache->size);
    103 #endif
     105#else  /* CONFIG_WITH_ALLOCCACHE_DEBUG */
     106
     107  /* Prefix the allocation with a cache pointer so alloccahce_free can better
     108     catch incorrect calls. */
     109  struct alloccache **ppcache = (struct alloccache **)xmalloc(sizeof(*ppcache) + cache->size);
     110  *ppcache = cache;
     111  return (struct alloccache_free_ent *)(ppcache + 1);
     112#endif /* CONFIG_WITH_ALLOCCACHE_DEBUG */
    104113}
    105114
  • trunk/src/kmk/amiga.c

    r2591 r3140  
    11/* Running commands on Amiga
    2 Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
    3 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1995-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    1615this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1716
    18 #include "make.h"
     17#include "makeint.h"
    1918#include "variable.h"
    2019#include "amiga.h"
     
    2625
    2726static const char Amiga_version[] = "$VER: Make 3.74.3 (12.05.96) \n"
    28                     "Amiga Port by A. Digulla ([email protected])";
     27                    "Amiga Port by A. Digulla ([email protected])";
    2928
    3029int
     
    3837    for (aptr=argv; *aptr; aptr++)
    3938    {
    40         len += strlen (*aptr) + 4;
     39        len += strlen (*aptr) + 4;
    4140    }
    4241
     
    4443
    4544    if (!buffer)
    46       fatal (NILF, "MyExecute: Cannot allocate space for calling a command");
     45      O (fatal, NILF, "MyExecute: Cannot allocate space for calling a command\n");
    4746
    4847    ptr = buffer;
     
    5049    for (aptr=argv; *aptr; aptr++)
    5150    {
    52         if (((*aptr)[0] == ';' && !(*aptr)[1]))
    53         {
    54             *ptr ++ = '"';
    55             strcpy (ptr, *aptr);
    56             ptr += strlen (ptr);
    57             *ptr ++ = '"';
    58         }
    59         else if ((*aptr)[0] == '@' && (*aptr)[1] == '@' && !(*aptr)[2])
    60         {
    61             *ptr ++ = '\n';
    62             continue;
    63         }
    64         else
    65         {
    66             strcpy (ptr, *aptr);
    67             ptr += strlen (ptr);
    68         }
    69         *ptr ++ = ' ';
    70         *ptr = 0;
     51        if (((*aptr)[0] == ';' && !(*aptr)[1]))
     52        {
     53            *ptr ++ = '"';
     54            strcpy (ptr, *aptr);
     55            ptr += strlen (ptr);
     56            *ptr ++ = '"';
     57        }
     58        else if ((*aptr)[0] == '@' && (*aptr)[1] == '@' && !(*aptr)[2])
     59        {
     60            *ptr ++ = '\n';
     61            continue;
     62        }
     63        else
     64        {
     65            strcpy (ptr, *aptr);
     66            ptr += strlen (ptr);
     67        }
     68        *ptr ++ = ' ';
     69        *ptr = 0;
    7170    }
    7271
     
    7473
    7574    status = SystemTags (buffer,
    76         SYS_UserShell, TRUE,
    77         TAG_END);
     75        SYS_UserShell, TRUE,
     76        TAG_END);
    7877
    7978    FreeMem (buffer, len);
    8079
    81     if (SetSignal(0L,0L) & SIGBREAKF_CTRL_C)
    82         status = 20;
     80    if (SetSignal (0L,0L) & SIGBREAKF_CTRL_C)
     81        status = 20;
    8382
    8483    /* Warnings don't count */
    8584    if (status == 5)
    86         status = 0;
     85        status = 0;
    8786
    8887    return status;
     
    9291wildcard_expansion (char *wc, char *o)
    9392{
    94 #   define PATH_SIZE    1024
     93#   define PATH_SIZE    1024
    9594    struct AnchorPath * apath;
    9695
    9796    if ( (apath = AllocMem (sizeof (struct AnchorPath) + PATH_SIZE,
    98             MEMF_CLEAR))
    99         )
     97            MEMF_CLEAR))
     98        )
    10099    {
    101         apath->ap_Strlen = PATH_SIZE;
     100        apath->ap_Strlen = PATH_SIZE;
    102101
    103         if (MatchFirst (wc, apath) == 0)
    104         {
    105             do
    106             {
    107                 o = variable_buffer_output (o, apath->ap_Buf,
    108                         strlen (apath->ap_Buf));
    109                 o = variable_buffer_output (o, " ",1);
    110             } while (MatchNext (apath) == 0);
    111         }
     102        if (MatchFirst (wc, apath) == 0)
     103        {
     104            do
     105            {
     106                o = variable_buffer_output (o, apath->ap_Buf,
     107                        strlen (apath->ap_Buf));
     108                o = variable_buffer_output (o, " ",1);
     109            } while (MatchNext (apath) == 0);
     110        }
    112111
    113         MatchEnd (apath);
    114         FreeMem (apath, sizeof (struct AnchorPath) + PATH_SIZE);
     112        MatchEnd (apath);
     113        FreeMem (apath, sizeof (struct AnchorPath) + PATH_SIZE);
    115114    }
    116115
  • trunk/src/kmk/amiga.h

    r2591 r3140  
    11/* Definitions for amiga specific things
    2 Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
    3 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1995-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
  • trunk/src/kmk/ar.c

    r2591 r3140  
    1 /* Interface to `ar' archives for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     1/* Interface to 'ar' archives for GNU Make.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53
    64This file is part of GNU Make.
     
    1816this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1917
    20 #include "make.h"
    21 
    22 #ifndef NO_ARCHIVES
     18#include "makeint.h"
     19
     20#ifndef NO_ARCHIVES
    2321
    2422#include "filedef.h"
     
    2725
    2826/* Return nonzero if NAME is an archive-member reference, zero if not.  An
    29    archive-member reference is a name like `lib(member)' where member is a
     27   archive-member reference is a name like 'lib(member)' where member is a
    3028   non-empty string.
    31    If a name like `lib((entry))' is used, a fatal error is signaled at
     29   If a name like 'lib((entry))' is used, a fatal error is signaled at
    3230   the attempt to use this unsupported feature.  */
    3331
     
    4644
    4745  if (p[1] == '(' && end[-1] == ')')
    48     fatal (NILF, _("attempt to use unsupported feature: `%s'"), name);
     46    OS (fatal, NILF, _("attempt to use unsupported feature: '%s'"), name);
    4947
    5048  return 1;
     
    6462  p = strchr (*arname_p, '(');
    6563  *(p++) = '\0';
    66   p[strlen(p) - 1] = '\0';
     64  p[strlen (p) - 1] = '\0';
    6765  *memname_p = p;
    6866}
     
    7068
    7169
    72 /* This function is called by `ar_scan' to find which member to look at.  */
     70/* This function is called by 'ar_scan' to find which member to look at.  */
    7371
    7472/* ARGSUSED */
    7573static long int
    7674ar_member_date_1 (int desc UNUSED, const char *mem, int truncated,
    77                   long int hdrpos UNUSED, long int datapos UNUSED,
     75                  long int hdrpos UNUSED, long int datapos UNUSED,
    7876                  long int size UNUSED, long int date,
    79                   int uid UNUSED, int gid UNUSED, int mode UNUSED,
    80                   const void *name)
     77                  int uid UNUSED, int gid UNUSED, unsigned int mode UNUSED,
     78                  const void *name)
    8179{
    8280  return ar_name_equal (name, mem, truncated) ? date : 0;
     
    125123ar_touch (const char *name)
    126124{
    127   error (NILF, _("touch archive member is not available on VMS"));
     125  O (error, NILF, _("touch archive member is not available on VMS"));
    128126  return -1;
    129127}
     
    149147    {
    150148    case -1:
    151       error (NILF, _("touch: Archive `%s' does not exist"), arname);
     149      OS (error, NILF, _("touch: Archive '%s' does not exist"), arname);
    152150      break;
    153151    case -2:
    154       error (NILF, _("touch: `%s' is not a valid archive"), arname);
     152      OS (error, NILF, _("touch: '%s' is not a valid archive"), arname);
    155153      break;
    156154    case -3:
     
    158156      break;
    159157    case 1:
    160       error (NILF,
    161              _("touch: Member `%s' does not exist in `%s'"), memname, arname);
     158      OSS (error, NILF,
     159           _("touch: Member '%s' does not exist in '%s'"), memname, arname);
    162160      break;
    163161    case 0:
     
    165163      break;
    166164    default:
    167       error (NILF,
    168              _("touch: Bad return code from ar_member_touch on `%s'"), name);
     165      OS (error, NILF,
     166          _("touch: Bad return code from ar_member_touch on '%s'"), name);
    169167    }
    170168
     
    176174
    177175
    178 /* State of an `ar_glob' run, passed to `ar_glob_match'.  */
     176/* State of an 'ar_glob' run, passed to 'ar_glob_match'.  */
     177
     178/* On VMS, (object) modules in libraries do not have suffixes. That is, to
     179   find a match for a pattern, the pattern must not have any suffix. So the
     180   suffix of the pattern is saved and the pattern is stripped (ar_glob).
     181   If there is a match and the match, which is a module name, is added to
     182   the chain, the saved suffix is added back to construct a source filename
     183   (ar_glob_match). */
    179184
    180185struct ar_glob_state
     
    182187    const char *arname;
    183188    const char *pattern;
     189#ifdef VMS
     190    char *suffix;
     191#endif
    184192    unsigned int size;
    185193    struct nameseq *chain;
     
    187195  };
    188196
    189 /* This function is called by `ar_scan' to match one archive
     197/* This function is called by 'ar_scan' to match one archive
    190198   element against the pattern in STATE.  */
    191199
    192200static long int
    193201ar_glob_match (int desc UNUSED, const char *mem, int truncated UNUSED,
    194                long int hdrpos UNUSED, long int datapos UNUSED,
     202               long int hdrpos UNUSED, long int datapos UNUSED,
    195203               long int size UNUSED, long int date UNUSED, int uid UNUSED,
    196                int gid UNUSED, int mode UNUSED, const void *arg)
     204               int gid UNUSED, unsigned int mode UNUSED, const void *arg)
    197205{
    198206  struct ar_glob_state *state = (struct ar_glob_state *)arg;
     
    202210      /* We have a match.  Add it to the chain.  */
    203211      struct nameseq *new = xcalloc (state->size);
    204       new->name = strcache_add (concat (4, state->arname, "(", mem, ")"));
     212#ifdef VMS
     213      if (state->suffix)
     214        new->name = strcache_add(
     215            concat(5, state->arname, "(", mem, state->suffix, ")"));
     216      else
     217#endif
     218        new->name = strcache_add(concat(4, state->arname, "(", mem, ")"));
    205219      new->next = state->chain;
    206220      state->chain = new;
     
    214228   Metacharacters can be quoted with backslashes if QUOTE is nonzero.  */
    215229static int
    216 glob_pattern_p (const char *pattern, int quote)
     230ar_glob_pattern_p (const char *pattern, int quote)
    217231{
    218232  const char *p;
     
    224238      case '?':
    225239      case '*':
    226         return 1;
     240        return 1;
    227241
    228242      case '\\':
    229         if (quote)
    230           ++p;
    231         break;
     243        if (quote)
     244          ++p;
     245        break;
    232246
    233247      case '[':
    234         opened = 1;
    235         break;
     248        opened = 1;
     249        break;
    236250
    237251      case ']':
    238         if (opened)
    239           return 1;
    240         break;
     252        if (opened)
     253          return 1;
     254        break;
    241255      }
    242256
     
    254268  const char **names;
    255269  unsigned int i;
    256 
    257   if (! glob_pattern_p (member_pattern, 1))
     270#ifdef VMS
     271  char *vms_member_pattern;
     272#endif
     273  if (! ar_glob_pattern_p (member_pattern, 1))
    258274    return 0;
    259275
     
    262278  state.arname = arname;
    263279  state.pattern = member_pattern;
     280#ifdef VMS
     281    {
     282      /* In a copy of the pattern, find the suffix, save it and  remove it from
     283         the pattern */
     284      char *lastdot;
     285      vms_member_pattern = xstrdup(member_pattern);
     286      lastdot = strrchr(vms_member_pattern, '.');
     287      state.suffix = lastdot;
     288      if (lastdot)
     289        {
     290          state.suffix = xstrdup(lastdot);
     291          *lastdot = 0;
     292        }
     293      state.pattern = vms_member_pattern;
     294    }
     295#endif
    264296  state.size = size;
    265297  state.chain = 0;
    266298  state.n = 0;
    267299  ar_scan (arname, ar_glob_match, &state);
     300
     301#ifdef VMS
     302  /* Deallocate any duplicated string */
     303  free(vms_member_pattern);
     304  if (state.suffix)
     305    {
     306      free(state.suffix);
     307    }
     308#endif
    268309
    269310  if (state.chain == 0)
     
    288329}
    289330
    290 #endif  /* Not NO_ARCHIVES.  */
     331#endif  /* Not NO_ARCHIVES.  */
  • trunk/src/kmk/arscan.c

    r2591 r3140  
    11/* Library function for scanning an archive file.
    2 Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1987-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
     18
     19#ifdef TEST
     20/* Hack, the real error() routine eventually pulls in die from main.c */
     21#define error(a, b, c, d)
     22#endif
    2023
    2124#ifdef HAVE_FCNTL_H
     
    2528#endif
    2629
    27 #ifndef NO_ARCHIVES
     30#ifndef NO_ARCHIVES
    2831
    2932#ifdef VMS
     
    3336#include <descrip.h>
    3437#include <ctype.h>
    35 #if __DECC
     38#include <ssdef.h>
     39#include <stsdef.h>
     40#include <rmsdef.h>
     41
     42/* This symbol should be present in lbrdef.h. */
     43#ifndef LBR$_HDRTRUNC
     44#pragma extern_model save
     45#pragma extern_model globalvalue
     46extern unsigned int LBR$_HDRTRUNC;
     47#pragma extern_model restore
     48#endif
     49
    3650#include <unixlib.h>
    3751#include <lbr$routines.h>
    38 #endif
    39 
     52
     53const char *
     54vmsify (const char *name, int type);
     55
     56/* Time conversion from VMS to Unix
     57   Conversion from local time (stored in library) to GMT (needed for gmake)
     58   Note: The tm_gmtoff element is a VMS extension to the ANSI standard. */
     59static time_t
     60vms_time_to_unix(void *vms_time)
     61{
     62  struct tm *tmp;
     63  time_t unix_time;
     64
     65  unix_time = decc$fix_time(vms_time);
     66  tmp = localtime(&unix_time);
     67  unix_time -= tmp->tm_gmtoff;
     68
     69  return unix_time;
     70}
     71
     72
     73/* VMS library routines need static variables for callback */
    4074static void *VMS_lib_idx;
    4175
    42 static char *VMS_saved_memname;
    43 
    44 static time_t VMS_member_date;
     76static const void *VMS_saved_arg;
    4577
    4678static long int (*VMS_function) ();
    4779
     80static long int VMS_function_ret;
     81
     82
     83/* This is a callback procedure for lib$get_index */
    4884static int
    49 VMS_get_member_info (struct dsc$descriptor_s *module, unsigned long *rfa)
     85VMS_get_member_info(struct dsc$descriptor_s *module, unsigned long *rfa)
    5086{
    5187  int status, i;
    52   long int fnval;
    53 
    54   time_t val;
     88  const int truncated = 0; /* Member name may be truncated */
     89  time_t member_date; /* Member date */
     90  char *filename;
     91  unsigned int buffer_length; /* Actual buffer length */
     92
     93  /* Unused constants - Make does not actually use most of these */
     94  const int file_desc = -1; /* archive file descriptor for reading the data */
     95  const int header_position = 0; /* Header position */
     96  const int data_position = 0; /* Data position in file */
     97  const int data_size = 0; /* Data size */
     98  const int uid = 0; /* member gid */
     99  const int gid = 0; /* member gid */
     100  const int mode = 0; /* member protection mode */
     101  /* End of unused constants */
    55102
    56103  static struct dsc$descriptor_s bufdesc =
    57104    { 0, DSC$K_DTYPE_T, DSC$K_CLASS_S, NULL };
    58105
     106  /* Only need the module definition */
    59107  struct mhddef *mhd;
    60   char filename[128];
    61 
    62   bufdesc.dsc$a_pointer = filename;
    63   bufdesc.dsc$w_length = sizeof (filename);
    64 
    65   status = lbr$set_module (&VMS_lib_idx, rfa, &bufdesc,
    66                            &bufdesc.dsc$w_length, 0);
    67   if (! (status & 1))
     108
     109  /* If a previous callback is non-zero, just return that status */
     110  if (VMS_function_ret)
    68111    {
    69       error (NILF, _("lbr$set_module() failed to extract module info, status = %d"),
    70              status);
    71 
    72       lbr$close (&VMS_lib_idx);
    73 
    74       return 0;
     112      return SS$_NORMAL;
    75113    }
    76114
    77   mhd = (struct mhddef *) filename;
    78 
    79 #ifdef __DECC
    80   /* John Fowler <[email protected]> writes this is needed in his environment,
    81    * but that decc$fix_time() isn't documented to work this way.  Let me
    82    * know if this causes problems in other VMS environments.
    83    */
    84   {
    85     /* Modified by M. Gehre at 11-JAN-2008 because old formula is wrong:
    86      * val = decc$fix_time (&mhd->mhd$l_datim) + timezone - daylight*3600;
    87      * a) daylight specifies, if the timezone has daylight saving enabled, not
    88      *    if it is active
    89      * b) what we need is the information, if daylight saving was active, if
    90      *    the library module was replaced. This information we get using the
    91      *    localtime function
    92      */
    93 
    94     struct tm *tmp;
    95 
    96     /* Conversion from VMS time to C time */
    97     val = decc$fix_time (&mhd->mhd$l_datim);
    98 
    99     /*
    100      * Conversion from local time (stored in library) to GMT (needed for gmake)
    101      * Note: The tm_gmtoff element is a VMS extension to the ANSI standard.
    102      */
    103     tmp = localtime (&val);
    104     val -= tmp->tm_gmtoff;
    105   }
    106 #endif
    107 
     115  /* lbr_set_module returns more than just the module header. So allocate
     116     a buffer which is big enough: the maximum LBR$C_MAXHDRSIZ. That's at
     117     least bigger than the size of struct mhddef.
     118     If the request is too small, a buffer truncated warning is issued so
     119     it can be reissued with a larger buffer.
     120     We do not care if the buffer is truncated, so that is still a success. */
     121  mhd = xmalloc(LBR$C_MAXHDRSIZ);
     122  bufdesc.dsc$a_pointer = (char *) mhd;
     123  bufdesc.dsc$w_length = LBR$C_MAXHDRSIZ;
     124
     125  status = lbr$set_module(&VMS_lib_idx, rfa, &bufdesc, &buffer_length, 0);
     126
     127  if ((status != LBR$_HDRTRUNC) && !$VMS_STATUS_SUCCESS(status))
     128    {
     129      ON(error, NILF,
     130          _("lbr$set_module() failed to extract module info, status = %d"),
     131          status);
     132
     133      lbr$close(&VMS_lib_idx);
     134
     135      return status;
     136    }
     137
     138#ifdef TEST
     139  /* When testing this code, it is useful to know the length returned */
     140  printf("Input length = %d, actual = %d\n",
     141      bufdesc.dsc$w_length, buffer_length);
     142#endif
     143
     144  /* Conversion from VMS time to C time.
     145     VMS defectlet - mhddef is sub-optimal, for the time, it has a 32 bit
     146     longword, mhd$l_datim, and a 32 bit fill instead of two longwords, or
     147     equivalent. */
     148  member_date = vms_time_to_unix(&mhd->mhd$l_datim);
     149  free(mhd);
     150
     151  /* Here we have a problem.  The module name on VMS does not have
     152     a file type, but the filename pattern in the "VMS_saved_arg"
     153     may have one.
     154     But only the method being called knows how to interpret the
     155     filename pattern.
     156     There are currently two different formats being used.
     157     This means that we need a VMS specific code in those methods
     158     to handle it. */
     159  filename = xmalloc(module->dsc$w_length + 1);
     160
     161  /* TODO: We may need an option to preserve the case of the module
     162     For now force the module name to lower case */
    108163  for (i = 0; i < module->dsc$w_length; i++)
    109     filename[i] = _tolower ((unsigned char)module->dsc$a_pointer[i]);
     164    filename[i] = _tolower((unsigned char )module->dsc$a_pointer[i]);
    110165
    111166  filename[i] = '\0';
    112167
    113   VMS_member_date = (time_t) -1;
    114 
    115   fnval =
    116     (*VMS_function) (-1, filename, 0, 0, 0, 0, val, 0, 0, 0,
    117                      VMS_saved_memname);
    118 
    119   if (fnval)
    120     {
    121       VMS_member_date = fnval;
    122       return 0;
    123     }
    124   else
    125     return 1;
     168  VMS_function_ret = (*VMS_function)(file_desc, filename, truncated,
     169      header_position, data_position, data_size, member_date, uid, gid, mode,
     170      VMS_saved_arg);
     171
     172  free(filename);
     173  return SS$_NORMAL;
    126174}
     175
    127176
    128177/* Takes three arguments ARCHIVE, FUNCTION and ARG.
     
    156205
    157206long int
    158 ar_scan (const char *archive, ar_member_func_t function, const void *arg)
     207ar_scan (const char *archive, ar_member_func_t function, const void *varg)
    159208{
    160   char *p;
     209  char *vms_archive;
    161210
    162211  static struct dsc$descriptor_s libdesc =
    163212    { 0, DSC$K_DTYPE_T, DSC$K_CLASS_S, NULL };
    164213
    165   unsigned long func = LBR$C_READ;
    166   unsigned long type = LBR$C_TYP_UNK;
    167   unsigned long index = 1;
    168 
     214  const unsigned long func = LBR$C_READ;
     215  const unsigned long type = LBR$C_TYP_UNK;
     216  const unsigned long index = 1;
     217  unsigned long lib_idx;
    169218  int status;
    170219
    171   status = lbr$ini_control (&VMS_lib_idx, &func, &type, 0);
    172 
    173   if (! (status & 1))
     220  VMS_saved_arg = varg;
     221
     222  /* Null archive string can show up in test and cause an access violation */
     223  if (archive == NULL)
    174224    {
    175       error (NILF, _("lbr$ini_control() failed with status = %d"), status);
     225      /* Null filenames do not exist */
     226      return -1;
     227    }
     228
     229  /* archive path name must be in VMS format */
     230  vms_archive = (char *) vmsify(archive, 0);
     231
     232  status = lbr$ini_control(&VMS_lib_idx, &func, &type, 0);
     233
     234  if (!$VMS_STATUS_SUCCESS(status))
     235    {
     236      ON(error, NILF, _("lbr$ini_control() failed with status = %d"), status);
    176237      return -2;
    177238    }
    178239
    179   /* there is no such descriptor with "const char *dsc$a_pointer" */
    180   libdesc.dsc$a_pointer = (char *)archive;
    181   libdesc.dsc$w_length = strlen (archive);
    182 
    183   status = lbr$open (&VMS_lib_idx, &libdesc, 0, 0, 0, 0, 0);
    184 
    185   if (! (status & 1))
     240  libdesc.dsc$a_pointer = vms_archive;
     241  libdesc.dsc$w_length = strlen(vms_archive);
     242
     243  status = lbr$open(&VMS_lib_idx, &libdesc, 0, NULL, 0, NULL, 0);
     244
     245  if (!$VMS_STATUS_SUCCESS(status))
    186246    {
    187       error (NILF, _("unable to open library `%s' to lookup member `%s'"),
    188              archive, (char *)arg);
    189       return -1;
     247
     248      /* TODO: A library format failure could mean that this is a file
     249         generated by the GNU AR utility and in that case, we need to
     250         take the UNIX codepath.  This will also take a change to the
     251         GNV AR wrapper program. */
     252
     253      switch (status)
     254        {
     255      case RMS$_FNF:
     256        /* Archive does not exist */
     257        return -1;
     258      default:
     259#ifndef TEST
     260        OSN(error, NILF,
     261            _("unable to open library '%s' to lookup member status %d"),
     262            archive, status);
     263#endif
     264        /* For library format errors, specification says to return -2 */
     265        return -2;
     266        }
    190267    }
    191268
    192   VMS_saved_memname = (char *)arg;
    193 
    194   /* For comparison, delete .obj from arg name.  */
    195 
    196   p = strrchr (VMS_saved_memname, '.');
    197   if (p)
    198     *p = '\0';
    199 
    200269  VMS_function = function;
    201270
    202   VMS_member_date = (time_t) -1;
    203   lbr$get_index (&VMS_lib_idx, &index, VMS_get_member_info, 0);
    204 
    205   /* Undo the damage.  */
    206   if (p)
    207     *p = '.';
    208 
    209   lbr$close (&VMS_lib_idx);
    210 
    211   return VMS_member_date > 0 ? VMS_member_date : 0;
     271  /* Clear the return status, as we are supposed to stop calling the
     272     callback function if it becomes non-zero, and this is a static
     273     variable. */
     274  VMS_function_ret = 0;
     275
     276  status = lbr$get_index(&VMS_lib_idx, &index, VMS_get_member_info, NULL, 0);
     277
     278  lbr$close(&VMS_lib_idx);
     279
     280  /* Unless a failure occurred in the lbr$ routines, return the
     281     the status from the 'function' routine. */
     282  if ($VMS_STATUS_SUCCESS(status))
     283    {
     284      return VMS_function_ret;
     285    }
     286
     287  /* This must be something wrong with the library and an error
     288     message should already have been printed. */
     289  return -2;
    212290}
    213291
     
    215293
    216294/* SCO Unix's compiler defines both of these.  */
    217 #ifdef  M_UNIX
    218 #undef  M_XENIX
     295#ifdef  M_UNIX
     296#undef  M_XENIX
    219297#endif
    220298
     
    225303
    226304#if (!defined (PORTAR) || PORTAR == 0) && (!defined (PORT5AR) || PORT5AR == 0)
    227 #undef  PORTAR
     305#undef  PORTAR
    228306#ifdef M_XENIX
    229307/* According to Jim Sievert <[email protected]>, for SCO XENIX defining
     
    254332
    255333#ifndef WINDOWS32
    256 # if !defined(__BEOS__) && !defined(__HAIKU__)
     334# if !defined (__ANDROID__) && !defined (__BEOS__) && !defined (__HAIKU__) /* bird: exclude haiku */
    257335#  include <ar.h>
    258336# else
    259    /* BeOS 5 doesn't have <ar.h> but has archives in the same format
     337   /* These platforms don't have <ar.h> but have archives in the same format
    260338    * as many other Unices.  This was taken from GNU binutils for BeOS.
    261339    */
    262 #  define ARMAG "!<arch>\n"     /* String that begins an archive file.  */
    263 #  define SARMAG 8              /* Size of that string.  */
    264 #  define ARFMAG "`\n"          /* String in ar_fmag at end of each header.  */
     340#  define ARMAG "!<arch>\n"     /* String that begins an archive file.  */
     341#  define SARMAG 8              /* Size of that string.  */
     342#  define ARFMAG "`\n"          /* String in ar_fmag at end of each header.  */
    265343struct ar_hdr
    266344  {
    267     char ar_name[16];           /* Member file name, sometimes / terminated. */
    268     char ar_date[12];           /* File date, decimal seconds since Epoch.  */
    269     char ar_uid[6], ar_gid[6];  /* User and group IDs, in ASCII decimal.  */
    270     char ar_mode[8];            /* File mode, in ASCII octal.  */
    271     char ar_size[10];           /* File size, in ASCII decimal.  */
    272     char ar_fmag[2];            /* Always contains ARFMAG.  */
     345    char ar_name[16];           /* Member file name, sometimes / terminated. */
     346    char ar_date[12];           /* File date, decimal seconds since Epoch.  */
     347    char ar_uid[6], ar_gid[6];  /* User and group IDs, in ASCII decimal.  */
     348    char ar_mode[8];            /* File mode, in ASCII octal.  */
     349    char ar_size[10];           /* File size, in ASCII decimal.  */
     350    char ar_fmag[2];            /* Always contains ARFMAG.  */
    273351  };
    274352# endif
     
    295373
    296374/* Cray's <ar.h> apparently defines this.  */
    297 #ifndef AR_HDR_SIZE
    298 # define   AR_HDR_SIZE  (sizeof (struct ar_hdr))
     375#ifndef AR_HDR_SIZE
     376# define   AR_HDR_SIZE  (sizeof (struct ar_hdr))
    299377#endif
    300378
     
    332410#ifdef AIAMAG
    333411  FL_HDR fl_header;
    334 #ifdef AIAMAGBIG
     412# ifdef AIAMAGBIG
    335413  int big_archive = 0;
    336414  FL_HDR_BIG fl_header_big;
    337 #endif
    338 #else
    339   int long_name = 0;
     415# endif
    340416#endif
    341417  char *namemap = 0;
     
    346422  {
    347423    char buf[SARMAG];
    348     register int nread = read (desc, buf, SARMAG);
     424    int nread;
     425    EINTRLOOP (nread, read (desc, buf, SARMAG));
    349426    if (nread != SARMAG || memcmp (buf, ARMAG, SARMAG))
    350427      {
    351         (void) close (desc);
    352         return -2;
     428        (void) close (desc);
     429        return -2;
    353430      }
    354431  }
     
    356433#ifdef AIAMAG
    357434  {
    358     register int nread = read (desc, &fl_header, FL_HSZ);
    359 
     435    int nread;
     436    EINTRLOOP (nread, read (desc, &fl_header, FL_HSZ));
    360437    if (nread != FL_HSZ)
    361438      {
    362         (void) close (desc);
    363         return -2;
     439        (void) close (desc);
     440        return -2;
    364441      }
    365442#ifdef AIAMAGBIG
     
    368445    if (!memcmp (fl_header.fl_magic, AIAMAGBIG, SAIAMAG))
    369446      {
    370         big_archive = 1;
    371 
    372         /* seek back to beginning of archive */
    373         if (lseek (desc, 0, 0) < 0)
    374           {
    375             (void) close (desc);
    376             return -2;
    377           }
    378 
    379         /* re-read the header into the "big" structure */
    380         nread = read (desc, &fl_header_big, FL_HSZ_BIG);
    381         if (nread != FL_HSZ_BIG)
    382           {
    383             (void) close (desc);
    384             return -2;
    385           }
     447        off_t o;
     448
     449        big_archive = 1;
     450
     451        /* seek back to beginning of archive */
     452        EINTRLOOP (o, lseek (desc, 0, 0));
     453        if (o < 0)
     454          {
     455            (void) close (desc);
     456            return -2;
     457          }
     458
     459        /* re-read the header into the "big" structure */
     460        EINTRLOOP (nread, read (desc, &fl_header_big, FL_HSZ_BIG));
     461        if (nread != FL_HSZ_BIG)
     462          {
     463            (void) close (desc);
     464            return -2;
     465          }
    386466      }
    387467    else
     
    389469       /* Check to make sure this is a "normal" archive. */
    390470      if (memcmp (fl_header.fl_magic, AIAMAG, SAIAMAG))
    391         {
     471        {
    392472          (void) close (desc);
    393473          return -2;
    394         }
     474        }
    395475  }
    396476#else
     
    401481    unsigned short int buf;
    402482#endif
    403     register int nread = read(desc, &buf, sizeof (buf));
     483    int nread;
     484    EINTRLOOP (nread, read (desc, &buf, sizeof (buf)));
    404485    if (nread != sizeof (buf) || buf != ARMAG)
    405486      {
    406         (void) close (desc);
    407         return -2;
     487        (void) close (desc);
     488        return -2;
    408489      }
    409490  }
     
    423504    if ( big_archive )
    424505      {
    425         sscanf (fl_header_big.fl_fstmoff, "%20ld", &member_offset);
    426         sscanf (fl_header_big.fl_lstmoff, "%20ld", &last_member_offset);
     506        sscanf (fl_header_big.fl_fstmoff, "%20ld", &member_offset);
     507        sscanf (fl_header_big.fl_lstmoff, "%20ld", &last_member_offset);
    427508      }
    428509    else
    429510#endif
    430511      {
    431         sscanf (fl_header.fl_fstmoff, "%12ld", &member_offset);
    432         sscanf (fl_header.fl_lstmoff, "%12ld", &last_member_offset);
     512        sscanf (fl_header.fl_fstmoff, "%12ld", &member_offset);
     513        sscanf (fl_header.fl_lstmoff, "%12ld", &last_member_offset);
    433514      }
    434515
    435516    if (member_offset == 0)
    436517      {
    437         /* Empty archive.  */
    438         close (desc);
    439         return 0;
     518        /* Empty archive.  */
     519        close (desc);
     520        return 0;
    440521      }
    441522#else
    442 #ifndef M_XENIX
     523#ifndef M_XENIX
    443524    register long int member_offset = sizeof (int);
    444 #else   /* Xenix.  */
     525#else   /* Xenix.  */
    445526    register long int member_offset = sizeof (unsigned short int);
    446 #endif  /* Not Xenix.  */
     527#endif  /* Not Xenix.  */
    447528#endif
    448529#endif
     
    450531    while (1)
    451532      {
    452         register int nread;
    453         struct ar_hdr member_header;
     533        register int nread;
     534        struct ar_hdr member_header;
    454535#ifdef AIAMAGBIG
    455         struct ar_hdr_big member_header_big;
     536        struct ar_hdr_big member_header_big;
    456537#endif
    457538#ifdef AIAMAG
    458         char name[256];
    459         int name_len;
    460         long int dateval;
    461         int uidval, gidval;
    462         long int data_offset;
    463 #else
    464         char namebuf[sizeof member_header.ar_name + 1];
    465         char *name;
    466         int is_namemap;         /* Nonzero if this entry maps long names.  */
    467 #endif
    468         long int eltsize;
    469         int eltmode;
    470         long int fnval;
    471 
    472         if (lseek (desc, member_offset, 0) < 0)
    473           {
    474             (void) close (desc);
    475             return -2;
    476           }
     539        char name[256];
     540        int name_len;
     541        long int dateval;
     542        int uidval, gidval;
     543        long int data_offset;
     544#else
     545        char namebuf[sizeof member_header.ar_name + 1];
     546        char *name;
     547        int is_namemap;         /* Nonzero if this entry maps long names.  */
     548        int long_name = 0;
     549#endif
     550        long int eltsize;
     551        unsigned int eltmode;
     552        long int fnval;
     553        off_t o;
     554
     555        EINTRLOOP (o, lseek (desc, member_offset, 0));
     556        if (o < 0)
     557          {
     558            (void) close (desc);
     559            return -2;
     560          }
    477561
    478562#ifdef AIAMAG
     
    480564
    481565#ifdef AIAMAGBIG
    482         if (big_archive)
    483           {
    484             nread = read (desc, &member_header_big,
    485                           AR_MEMHDR_SZ(member_header_big) );
    486 
    487             if (nread != AR_MEMHDR_SZ(member_header_big))
    488               {
    489                 (void) close (desc);
    490                 return -2;
    491               }
    492 
    493             sscanf (member_header_big.ar_namlen, "%4d", &name_len);
    494             nread = read (desc, name, name_len);
    495 
    496             if (nread != name_len)
    497               {
    498                 (void) close (desc);
    499                 return -2;
    500               }
    501 
    502             name[name_len] = 0;
    503 
    504             sscanf (member_header_big.ar_date, "%12ld", &dateval);
    505             sscanf (member_header_big.ar_uid, "%12d", &uidval);
    506             sscanf (member_header_big.ar_gid, "%12d", &gidval);
    507             sscanf (member_header_big.ar_mode, "%12o", &eltmode);
    508             sscanf (member_header_big.ar_size, "%20ld", &eltsize);
    509 
    510             data_offset = (member_offset + AR_MEMHDR_SZ(member_header_big)
    511                            + name_len + 2);
    512           }
    513         else
    514 #endif
    515           {
    516             nread = read (desc, &member_header,
    517                           AR_MEMHDR_SZ(member_header) );
    518 
    519             if (nread != AR_MEMHDR_SZ(member_header))
    520               {
    521                 (void) close (desc);
    522                 return -2;
    523               }
    524 
    525             sscanf (member_header.ar_namlen, "%4d", &name_len);
    526             nread = read (desc, name, name_len);
    527 
    528             if (nread != name_len)
    529               {
    530                 (void) close (desc);
    531                 return -2;
    532               }
    533 
    534             name[name_len] = 0;
    535 
    536             sscanf (member_header.ar_date, "%12ld", &dateval);
    537             sscanf (member_header.ar_uid, "%12d", &uidval);
    538             sscanf (member_header.ar_gid, "%12d", &gidval);
    539             sscanf (member_header.ar_mode, "%12o", &eltmode);
    540             sscanf (member_header.ar_size, "%12ld", &eltsize);
    541 
    542             data_offset = (member_offset + AR_MEMHDR_SZ(member_header)
    543                            + name_len + 2);
    544           }
    545         data_offset += data_offset % 2;
    546 
    547         fnval =
    548           (*function) (desc, name, 0,
    549                        member_offset, data_offset, eltsize,
    550                        dateval, uidval, gidval,
    551                        eltmode, arg);
    552 
    553 #else   /* Not AIAMAG.  */
    554         nread = read (desc, &member_header, AR_HDR_SIZE);
    555         if (nread == 0)
    556           /* No data left means end of file; that is OK.  */
    557           break;
    558 
    559         if (nread != AR_HDR_SIZE
     566        if (big_archive)
     567          {
     568            EINTRLOOP (nread, read (desc, &member_header_big,
     569                                    AR_MEMHDR_SZ(member_header_big)));
     570
     571            if (nread != AR_MEMHDR_SZ(member_header_big))
     572              {
     573                (void) close (desc);
     574                return -2;
     575              }
     576
     577            sscanf (member_header_big.ar_namlen, "%4d", &name_len);
     578            EINTRLOOP (nread, read (desc, name, name_len));
     579
     580            if (nread != name_len)
     581              {
     582                (void) close (desc);
     583                return -2;
     584              }
     585
     586            name[name_len] = 0;
     587
     588            sscanf (member_header_big.ar_date, "%12ld", &dateval);
     589            sscanf (member_header_big.ar_uid, "%12d", &uidval);
     590            sscanf (member_header_big.ar_gid, "%12d", &gidval);
     591            sscanf (member_header_big.ar_mode, "%12o", &eltmode);
     592            sscanf (member_header_big.ar_size, "%20ld", &eltsize);
     593
     594            data_offset = (member_offset + AR_MEMHDR_SZ(member_header_big)
     595                           + name_len + 2);
     596          }
     597        else
     598#endif
     599          {
     600            EINTRLOOP (nread, read (desc, &member_header,
     601                                    AR_MEMHDR_SZ(member_header)));
     602
     603            if (nread != AR_MEMHDR_SZ(member_header))
     604              {
     605                (void) close (desc);
     606                return -2;
     607              }
     608
     609            sscanf (member_header.ar_namlen, "%4d", &name_len);
     610            EINTRLOOP (nread, read (desc, name, name_len));
     611
     612            if (nread != name_len)
     613              {
     614                (void) close (desc);
     615                return -2;
     616              }
     617
     618            name[name_len] = 0;
     619
     620            sscanf (member_header.ar_date, "%12ld", &dateval);
     621            sscanf (member_header.ar_uid, "%12d", &uidval);
     622            sscanf (member_header.ar_gid, "%12d", &gidval);
     623            sscanf (member_header.ar_mode, "%12o", &eltmode);
     624            sscanf (member_header.ar_size, "%12ld", &eltsize);
     625
     626            data_offset = (member_offset + AR_MEMHDR_SZ(member_header)
     627                           + name_len + 2);
     628          }
     629        data_offset += data_offset % 2;
     630
     631        fnval =
     632          (*function) (desc, name, 0,
     633                       member_offset, data_offset, eltsize,
     634                       dateval, uidval, gidval,
     635                       eltmode, arg);
     636
     637#else   /* Not AIAMAG.  */
     638        EINTRLOOP (nread, read (desc, &member_header, AR_HDR_SIZE));
     639        if (nread == 0)
     640          /* No data left means end of file; that is OK.  */
     641          break;
     642
     643        if (nread != AR_HDR_SIZE
    560644#if defined(ARFMAG) || defined(ARFZMAG)
    561             || (
     645            || (
    562646# ifdef ARFMAG
    563647                memcmp (member_header.ar_fmag, ARFMAG, 2)
     
    573657               )
    574658#endif
    575             )
    576           {
    577             (void) close (desc);
    578             return -2;
    579           }
    580 
    581         name = namebuf;
    582         memcpy (name, member_header.ar_name, sizeof member_header.ar_name);
    583         {
    584           register char *p = name + sizeof member_header.ar_name;
    585           do
    586             *p = '\0';
    587           while (p > name && *--p == ' ');
     659            )
     660          {
     661            (void) close (desc);
     662            return -2;
     663          }
     664
     665        name = namebuf;
     666        memcpy (name, member_header.ar_name, sizeof member_header.ar_name);
     667        {
     668          register char *p = name + sizeof member_header.ar_name;
     669          do
     670            *p = '\0';
     671          while (p > name && *--p == ' ');
    588672
    589673#ifndef AIAMAG
    590           /* If the member name is "//" or "ARFILENAMES/" this may be
    591              a list of file name mappings.  The maximum file name
    592              length supported by the standard archive format is 14
    593              characters.  This member will actually always be the
    594              first or second entry in the archive, but we don't check
    595              that.  */
    596           is_namemap = (!strcmp (name, "//")
    597                         || !strcmp (name, "ARFILENAMES/"));
    598 #endif  /* Not AIAMAG. */
    599           /* On some systems, there is a slash after each member name.  */
    600           if (*p == '/')
    601             *p = '\0';
     674          /* If the member name is "//" or "ARFILENAMES/" this may be
     675             a list of file name mappings.  The maximum file name
     676             length supported by the standard archive format is 14
     677             characters.  This member will actually always be the
     678             first or second entry in the archive, but we don't check
     679             that.  */
     680          is_namemap = (!strcmp (name, "//")
     681                        || !strcmp (name, "ARFILENAMES/"));
     682#endif  /* Not AIAMAG. */
     683          /* On some systems, there is a slash after each member name.  */
     684          if (*p == '/')
     685            *p = '\0';
    602686
    603687#ifndef AIAMAG
    604           /* If the member name starts with a space or a slash, this
    605              is an index into the file name mappings (used by GNU ar).
    606              Otherwise if the member name looks like #1/NUMBER the
    607              real member name appears in the element data (used by
    608              4.4BSD).  */
    609           if (! is_namemap
    610               && (name[0] == ' ' || name[0] == '/')
    611               && namemap != 0)
    612             {
    613               name = namemap + atoi (name + 1);
    614               long_name = 1;
    615             }
    616           else if (name[0] == '#'
    617                    && name[1] == '1'
    618                    && name[2] == '/')
    619             {
    620               int namesize = atoi (name + 3);
    621 
    622               name = alloca (namesize + 1);
    623               nread = read (desc, name, namesize);
    624               if (nread != namesize)
    625                 {
    626                   close (desc);
    627                   return -2;
    628                 }
    629               name[namesize] = '\0';
    630 
    631               long_name = 1;
    632             }
     688          /* If the member name starts with a space or a slash, this
     689             is an index into the file name mappings (used by GNU ar).
     690             Otherwise if the member name looks like #1/NUMBER the
     691             real member name appears in the element data (used by
     692             4.4BSD).  */
     693          if (! is_namemap
     694              && (name[0] == ' ' || name[0] == '/')
     695              && namemap != 0)
     696            {
     697              name = namemap + atoi (name + 1);
     698              long_name = 1;
     699            }
     700          else if (name[0] == '#'
     701                   && name[1] == '1'
     702                   && name[2] == '/')
     703            {
     704              int namesize = atoi (name + 3);
     705
     706              name = alloca (namesize + 1);
     707              EINTRLOOP (nread, read (desc, name, namesize));
     708              if (nread != namesize)
     709                {
     710                  close (desc);
     711                  return -2;
     712                }
     713              name[namesize] = '\0';
     714
     715              long_name = 1;
     716            }
    633717#endif /* Not AIAMAG. */
    634         }
    635 
    636 #ifndef M_XENIX
    637         sscanf (TOCHAR (member_header.ar_mode), "%o", &eltmode);
    638         eltsize = atol (TOCHAR (member_header.ar_size));
    639 #else   /* Xenix.  */
    640         eltmode = (unsigned short int) member_header.ar_mode;
    641         eltsize = member_header.ar_size;
    642 #endif  /* Not Xenix.  */
    643 
    644         fnval =
    645           (*function) (desc, name, ! long_name, member_offset,
    646                        member_offset + AR_HDR_SIZE, eltsize,
    647 #ifndef M_XENIX
    648                        atol (TOCHAR (member_header.ar_date)),
    649                        atoi (TOCHAR (member_header.ar_uid)),
    650                        atoi (TOCHAR (member_header.ar_gid)),
    651 #else   /* Xenix.  */
    652                        member_header.ar_date,
    653                        member_header.ar_uid,
    654                        member_header.ar_gid,
    655 #endif  /* Not Xenix.  */
    656                        eltmode, arg);
     718        }
     719
     720#ifndef M_XENIX
     721        sscanf (TOCHAR (member_header.ar_mode), "%o", &eltmode);
     722        eltsize = atol (TOCHAR (member_header.ar_size));
     723#else   /* Xenix.  */
     724        eltmode = (unsigned short int) member_header.ar_mode;
     725        eltsize = member_header.ar_size;
     726#endif  /* Not Xenix.  */
     727
     728        fnval =
     729          (*function) (desc, name, ! long_name, member_offset,
     730                       member_offset + AR_HDR_SIZE, eltsize,
     731#ifndef M_XENIX
     732                       atol (TOCHAR (member_header.ar_date)),
     733                       atoi (TOCHAR (member_header.ar_uid)),
     734                       atoi (TOCHAR (member_header.ar_gid)),
     735#else   /* Xenix.  */
     736                       member_header.ar_date,
     737                       member_header.ar_uid,
     738                       member_header.ar_gid,
     739#endif  /* Not Xenix.  */
     740                       eltmode, arg);
    657741
    658742#endif  /* AIAMAG.  */
    659743
    660         if (fnval)
    661           {
    662             (void) close (desc);
    663             return fnval;
    664           }
     744        if (fnval)
     745          {
     746            (void) close (desc);
     747            return fnval;
     748          }
    665749
    666750#ifdef AIAMAG
    667         if (member_offset == last_member_offset)
    668           /* End of the chain.  */
    669           break;
     751        if (member_offset == last_member_offset)
     752          /* End of the chain.  */
     753          break;
    670754
    671755#ifdef AIAMAGBIG
    672         if (big_archive)
     756        if (big_archive)
    673757         sscanf (member_header_big.ar_nxtmem, "%20ld", &member_offset);
    674         else
    675 #endif
    676           sscanf (member_header.ar_nxtmem, "%12ld", &member_offset);
    677 
    678         if (lseek (desc, member_offset, 0) != member_offset)
    679           {
    680             (void) close (desc);
    681             return -2;
    682           }
    683 #else
    684 
    685         /* If this member maps archive names, we must read it in.  The
    686            name map will always precede any members whose names must
    687            be mapped.  */
    688         if (is_namemap)
    689           {
    690             char *clear;
    691             char *limit;
    692 
    693             namemap = alloca (eltsize);
    694             nread = read (desc, namemap, eltsize);
    695             if (nread != eltsize)
    696               {
    697                 (void) close (desc);
    698                 return -2;
    699               }
    700 
    701             /* The names are separated by newlines.  Some formats have
    702                a trailing slash.  Null terminate the strings for
    703                convenience.  */
    704             limit = namemap + eltsize;
    705             for (clear = namemap; clear < limit; clear++)
    706               {
    707                 if (*clear == '\n')
    708                   {
    709                     *clear = '\0';
    710                     if (clear[-1] == '/')
    711                       clear[-1] = '\0';
    712                   }
    713               }
    714 
    715             is_namemap = 0;
    716           }
    717 
    718         member_offset += AR_HDR_SIZE + eltsize;
    719         if (member_offset % 2 != 0)
    720           member_offset++;
     758        else
     759#endif
     760          sscanf (member_header.ar_nxtmem, "%12ld", &member_offset);
     761
     762        if (lseek (desc, member_offset, 0) != member_offset)
     763          {
     764            (void) close (desc);
     765            return -2;
     766          }
     767#else
     768
     769        /* If this member maps archive names, we must read it in.  The
     770           name map will always precede any members whose names must
     771           be mapped.  */
     772        if (is_namemap)
     773          {
     774            char *clear;
     775            char *limit;
     776
     777            namemap = alloca (eltsize);
     778            EINTRLOOP (nread, read (desc, namemap, eltsize));
     779            if (nread != eltsize)
     780              {
     781                (void) close (desc);
     782                return -2;
     783              }
     784
     785            /* The names are separated by newlines.  Some formats have
     786               a trailing slash.  Null terminate the strings for
     787               convenience.  */
     788            limit = namemap + eltsize;
     789            for (clear = namemap; clear < limit; clear++)
     790              {
     791                if (*clear == '\n')
     792                  {
     793                    *clear = '\0';
     794                    if (clear[-1] == '/')
     795                      clear[-1] = '\0';
     796                  }
     797              }
     798
     799            is_namemap = 0;
     800          }
     801
     802        member_offset += AR_HDR_SIZE + eltsize;
     803        if (member_offset % 2 != 0)
     804          member_offset++;
    721805#endif
    722806      }
     
    751835      struct ar_hdr hdr;
    752836#if !defined (__hpux) && !defined (cray)
    753       return strneq (name, mem, sizeof(hdr.ar_name) - 1);
    754 #else
    755       return strneq (name, mem, sizeof(hdr.ar_name) - 2);
     837      return strneq (name, mem, sizeof (hdr.ar_name) - 1);
     838#else
     839      return strneq (name, mem, sizeof (hdr.ar_name) - 2);
    756840#endif /* !__hpux && !cray */
    757841#endif /* !AIAMAG */
    758842    }
     843
     844  return !strcmp (name, mem);
     845#else
     846  /* VMS members do not have suffixes, but the filenames usually
     847     have.
     848     Do we need to strip VMS disk/directory format paths?
     849
     850     Most VMS compilers etc. by default are case insensitive
     851     but produce uppercase external names, incl. module names.
     852     However the VMS librarian (ar) and the linker by default
     853     are case sensitive: they take what they get, usually
     854     uppercase names. So for the non-default settings of the
     855     compilers etc. there is a need to have a case sensitive
     856     mode. */
     857  {
     858    int len;
     859    len = strlen(mem);
     860    int match;
     861    char *dot;
     862    if ((dot=strrchr(name,'.')))
     863      match = (len == dot - name) && !strncasecmp(name, mem, len);
     864    else
     865      match = !strcasecmp (name, mem);
     866    return match;
     867  }
    759868#endif /* !VMS */
    760 
    761   return !strcmp (name, mem);
    762869}
    763870
     
    767874static long int
    768875ar_member_pos (int desc UNUSED, const char *mem, int truncated,
    769                long int hdrpos, long int datapos UNUSED, long int size UNUSED,
     876               long int hdrpos, long int datapos UNUSED, long int size UNUSED,
    770877               long int date UNUSED, int uid UNUSED, int gid UNUSED,
    771                int mode UNUSED, const void *name)
     878               unsigned int mode UNUSED, const void *name)
    772879{
    773880  if (!ar_name_equal (name, mem, truncated))
     
    789896  int fd;
    790897  struct ar_hdr ar_hdr;
    791   int i;
     898  off_t o;
     899  int r;
    792900  unsigned int ui;
    793901  struct stat statbuf;
     
    798906    return 1;
    799907
    800   fd = open (arname, O_RDWR, 0666);
     908  EINTRLOOP (fd, open (arname, O_RDWR, 0666));
    801909  if (fd < 0)
    802910    return -3;
    803911  /* Read in this member's header */
    804   if (lseek (fd, pos, 0) < 0)
     912  EINTRLOOP (o, lseek (fd, pos, 0));
     913  if (o < 0)
    805914    goto lose;
    806   if (AR_HDR_SIZE != read (fd, &ar_hdr, AR_HDR_SIZE))
     915  EINTRLOOP (r, read (fd, &ar_hdr, AR_HDR_SIZE));
     916  if (r != AR_HDR_SIZE)
    807917    goto lose;
    808918  /* Write back the header, thus touching the archive file.  */
    809   if (lseek (fd, pos, 0) < 0)
     919  EINTRLOOP (o, lseek (fd, pos, 0));
     920  if (o < 0)
    810921    goto lose;
    811   if (AR_HDR_SIZE != write (fd, &ar_hdr, AR_HDR_SIZE))
     922  EINTRLOOP (r, write (fd, &ar_hdr, AR_HDR_SIZE));
     923  if (r != AR_HDR_SIZE)
    812924    goto lose;
    813925  /* The file's mtime is the time we we want.  */
    814   EINTRLOOP (i, fstat (fd, &statbuf));
    815   if (i < 0)
     926  EINTRLOOP (r, fstat (fd, &statbuf));
     927  if (r < 0)
    816928    goto lose;
    817929#if defined(ARFMAG) || defined(ARFZMAG) || defined(AIAMAG) || defined(WINDOWS32)
     
    819931  for (ui = 0; ui < sizeof ar_hdr.ar_date; ui++)
    820932    ar_hdr.ar_date[ui] = ' ';
    821   sprintf (TOCHAR (ar_hdr.ar_date), "%ld", (long int) statbuf.st_mtime);
     933  sprintf (TOCHAR (ar_hdr.ar_date), "%lu", (long unsigned) statbuf.st_mtime);
    822934#ifdef AIAMAG
    823   ar_hdr.ar_date[strlen(ar_hdr.ar_date)] = ' ';
     935  ar_hdr.ar_date[strlen (ar_hdr.ar_date)] = ' ';
    824936#endif
    825937#else
     
    827939#endif
    828940  /* Write back this member's header */
    829   if (lseek (fd, pos, 0) < 0)
     941  EINTRLOOP (o, lseek (fd, pos, 0));
     942  if (o < 0)
    830943    goto lose;
    831   if (AR_HDR_SIZE != write (fd, &ar_hdr, AR_HDR_SIZE))
     944  EINTRLOOP (r, write (fd, &ar_hdr, AR_HDR_SIZE));
     945  if (r != AR_HDR_SIZE)
    832946    goto lose;
    833947  close (fd);
     
    835949
    836950 lose:
    837   i = errno;
     951  r = errno;
    838952  close (fd);
    839   errno = i;
     953  errno = r;
    840954  return -3;
    841955}
     
    847961long int
    848962describe_member (int desc, const char *name, int truncated,
    849                  long int hdrpos, long int datapos, long int size,
    850                  long int date, int uid, int gid, int mode, const void *arg)
     963                 long int hdrpos, long int datapos, long int size,
     964                 long int date, int uid, int gid, unsigned int mode,
     965                 const void *arg)
    851966{
    852967  extern char *ctime ();
    853968
    854   printf (_("Member `%s'%s: %ld bytes at %ld (%ld).\n"),
    855           name, truncated ? _(" (name might be truncated)") : "",
    856           size, hdrpos, datapos);
     969  printf (_("Member '%s'%s: %ld bytes at %ld (%ld).\n"),
     970          name, truncated ? _(" (name might be truncated)") : "",
     971          size, hdrpos, datapos);
    857972  printf (_("  Date %s"), ctime (&date));
    858973  printf (_("  uid = %d, gid = %d, mode = 0%o.\n"), uid, gid, mode);
     
    868983}
    869984
    870 #endif  /* TEST.  */
    871 #endif  /* NO_ARCHIVES.  */
     985#endif  /* TEST.  */
     986#endif  /* NO_ARCHIVES.  */
  • trunk/src/kmk/build.template

    r2591 r3140  
    11#!/bin/sh
    2 # Shell script to build GNU Make in the absence of any `make' program.
     2# Shell script to build GNU Make in the absence of any 'make' program.
    33# @configure_input@
    44
    5 # Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
    6 # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     5# Copyright (C) 1993-2016 Free Software Foundation, Inc.
    76# This file is part of GNU Make.
    87#
     
    2423srcdir='@srcdir@'
    2524CC='@CC@'
    26 CFLAGS='@CFLAGS@'
     25CFLAGS='@CFLAGS@ @GUILE_CFLAGS@'
    2726CPPFLAGS='@CPPFLAGS@'
    28 LDFLAGS='@LDFLAGS@'
     27LDFLAGS='@AM_LDFLAGS@ @LDFLAGS@'
    2928ALLOCA='@ALLOCA@'
    30 LOADLIBES='@LIBS@ @LIBINTL@'
     29LOADLIBES='@LIBS@ @GUILE_LIBS@ @LIBINTL@'
    3130eval extras=\'@LIBOBJS@\'
    3231REMOTE='@REMOTE@'
     
    4039# Common prefix for machine-dependent installed files.
    4140exec_prefix=`eval echo @exec_prefix@`
    42 # Directory to find libraries in for `-lXXX'.
     41# Directory to find libraries in for '-lXXX'.
    4342libdir=${exec_prefix}/lib
    4443# Directory to search by default for included makefiles.
     
    4847aliaspath=${localedir}${PATH_SEPARATOR}.
    4948
    50 defines="-DALIASPATH=\"${aliaspath}\" -DLOCALEDIR=\"${localedir}\" -DLIBDIR=\"${libdir}\" -DINCLUDEDIR=\"${includedir}\""' @DEFS@'
     49defines="-DLOCALEDIR=\"${localedir}\" -DLIBDIR=\"${libdir}\" -DINCLUDEDIR=\"${includedir}\""' @DEFS@'
    5150
    5251# Exit as soon as any command fails.
  • trunk/src/kmk/build_w32.bat

    r2591 r3140  
    11@echo off
    2 rem Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 rem 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2rem Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43rem This file is part of GNU Make.
    54rem
     
    1716rem with this program.  If not, see <http://www.gnu.org/licenses/>.
    1817
    19 if exist config.h.W32 GoTo NotCVS
    20 sed -n "s/^AC_INIT(\[GNU make\],\[\([^]]\+\)\].*/s,%%VERSION%%,\1,g/p" configure.in > config.h.W32.sed
    21 echo s,%%PACKAGE%%,make,g >> config.h.W32.sed
    22 sed -f config.h.W32.sed config.h.W32.template > config.h.W32
    23 :NotCVS
    24 if not exist config.h copy config.h.W32 config.h
    25 cd w32\subproc
    26 echo "Creating the subproc library"
    27 %ComSpec% /c build.bat %1
    28 cd ..\..
    29 
    30 if exist link.dbg del link.dbg
    31 if exist link.rel del link.rel
    32 echo "Creating GNU Make for Windows 9X/NT/2K/XP"
    33 if "%1" == "gcc" GoTo GCCBuild
    34 set make=gnumake
    35 echo on
    36 if not exist .\WinDebug\nul mkdir .\WinDebug
    37 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D TIVOLI /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c variable.c
    38 echo WinDebug\variable.obj >>link.dbg
    39 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c rule.c
    40 echo WinDebug\rule.obj >>link.dbg
    41 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c remote-stub.c
    42 echo WinDebug\remote-stub.obj >>link.dbg
    43 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c commands.c
    44 echo WinDebug\commands.obj >>link.dbg
    45 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c file.c
    46 echo WinDebug\file.obj >>link.dbg
    47 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c getloadavg.c
    48 echo WinDebug\getloadavg.obj >>link.dbg
    49 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c default.c
    50 echo WinDebug\default.obj >>link.dbg
    51 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c signame.c
    52 echo WinDebug\signame.obj >>link.dbg
    53 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c expand.c
    54 echo WinDebug\expand.obj >>link.dbg
    55 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c dir.c
    56 echo WinDebug\dir.obj >>link.dbg
    57 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c main.c
    58 echo WinDebug\main.obj >>link.dbg
    59 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c getopt1.c
    60 echo WinDebug\getopt1.obj >>link.dbg
    61 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c job.c
    62 echo WinDebug\job.obj >>link.dbg
    63 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c read.c
    64 echo WinDebug\read.obj >>link.dbg
    65 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c version.c
    66 echo WinDebug\version.obj >>link.dbg
    67 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c getopt.c
    68 echo WinDebug\getopt.obj >>link.dbg
    69 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c arscan.c
    70 echo WinDebug\arscan.obj >>link.dbg
    71 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c hash.c
    72 echo WinDebug\hash.obj >>link.dbg
    73 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c strcache.c
    74 echo WinDebug\strcache.obj >>link.dbg
    75 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c remake.c
    76 echo WinDebug\remake.obj >>link.dbg
    77 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c misc.c
    78 echo WinDebug\misc.obj >>link.dbg
    79 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c ar.c
    80 echo WinDebug\ar.obj >>link.dbg
    81 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c function.c
    82 echo WinDebug\function.obj >>link.dbg
    83 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c vpath.c
    84 echo WinDebug\vpath.obj >>link.dbg
    85 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c implicit.c
    86 echo WinDebug\implicit.obj >>link.dbg
    87 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c  .\w32\compat\dirent.c
    88 echo WinDebug\dirent.obj >>link.dbg
    89 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c  .\glob\glob.c
    90 echo WinDebug\glob.obj >>link.dbg
    91 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c  .\glob\fnmatch.c
    92 echo WinDebug\fnmatch.obj >>link.dbg
    93 cl.exe /nologo /MT /W4 /GX /Zi /YX /Od /I . /I glob /I w32/include /D _DEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinDebug/ /Fp.\WinDebug/%make%.pch /Fo.\WinDebug/ /Fd.\WinDebug/%make%.pdb /c  .\w32\pathstuff.c
    94 echo WinDebug\pathstuff.obj >>link.dbg
    95 echo off
    96 echo "Linking WinDebug/%make%.exe"
    97 rem link.exe kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib w32\subproc\windebug\subproc.lib /NOLOGO /SUBSYSTEM:console /INCREMENTAL:yes /PDB:.\WinDebug/%make%.pdb /DEBUG /OUT:.\WinDebug/%make%.exe .\WinDebug/variable.obj  .\WinDebug/rule.obj  .\WinDebug/remote-stub.obj  .\WinDebug/commands.obj  .\WinDebug/file.obj  .\WinDebug/getloadavg.obj  .\WinDebug/default.obj  .\WinDebug/signame.obj  .\WinDebug/expand.obj  .\WinDebug/dir.obj  .\WinDebug/main.obj  .\WinDebug/getopt1.obj  .\WinDebug/job.obj  .\WinDebug/read.obj  .\WinDebug/version.obj  .\WinDebug/getopt.obj  .\WinDebug/arscan.obj  .\WinDebug/remake.obj  .\WinDebug/hash.obj  .\WinDebug/strcache.obj  .\WinDebug/misc.obj  .\WinDebug/ar.obj  .\WinDebug/function.obj  .\WinDebug/vpath.obj  .\WinDebug/implicit.obj  .\WinDebug/dirent.obj  .\WinDebug/glob.obj  .\WinDebug/fnmatch.obj  .\WinDebug/pathstuff.obj
    98 echo kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib w32\subproc\windebug\subproc.lib >>link.dbg
    99 link.exe /NOLOGO /SUBSYSTEM:console /INCREMENTAL:yes /PDB:.\WinDebug/%make%.pdb /DEBUG /OUT:.\WinDebug/%make%.exe @link.dbg
    100 if not exist .\WinDebug/%make%.exe echo "WinDebug build failed"
    101 if exist .\WinDebug/%make%.exe echo "WinDebug build succeeded!"
    102 if not exist .\WinRel\nul mkdir .\WinRel
    103 echo on
    104 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /D TIVOLI /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c variable.c
    105 echo WinRel\variable.obj >>link.rel
    106 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c rule.c
    107 echo WinRel\rule.obj >>link.rel
    108 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c remote-stub.c
    109 echo WinRel\remote-stub.obj >>link.rel
    110 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c commands.c
    111 echo WinRel\commands.obj >>link.rel
    112 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c file.c
    113 echo WinRel\file.obj >>link.rel
    114 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c getloadavg.c
    115 echo WinRel\getloadavg.obj >>link.rel
    116 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c default.c
    117 echo WinRel\default.obj >>link.rel
    118 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c signame.c
    119 echo WinRel\signame.obj >>link.rel
    120 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c expand.c
    121 echo WinRel\expand.obj >>link.rel
    122 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c dir.c
    123 echo WinRel\dir.obj >>link.rel
    124 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c main.c
    125 echo WinRel\main.obj >>link.rel
    126 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c getopt1.c
    127 echo WinRel\getopt1.obj >>link.rel
    128 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c job.c
    129 echo WinRel\job.obj >>link.rel
    130 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c read.c
    131 echo WinRel\read.obj >>link.rel
    132 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c version.c
    133 echo WinRel\version.obj >>link.rel
    134 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c getopt.c
    135 echo WinRel\getopt.obj >>link.rel
    136 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c arscan.c
    137 echo WinRel\arscan.obj >>link.rel
    138 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c remake.c
    139 echo WinRel\remake.obj >>link.rel
    140 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c hash.c
    141 echo WinRel\hash.obj >>link.rel
    142 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c strcache.c
    143 echo WinRel\strcache.obj >>link.rel
    144 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c misc.c
    145 echo WinRel\misc.obj >>link.rel
    146 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c ar.c
    147 echo WinRel\ar.obj >>link.rel
    148 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c function.c
    149 echo WinRel\function.obj >>link.rel
    150 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c vpath.c
    151 echo WinRel\vpath.obj >>link.rel
    152 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c implicit.c
    153 echo WinRel\implicit.obj >>link.rel
    154 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c  .\w32\compat\dirent.c
    155 echo WinRel\dirent.obj >>link.rel
    156 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c  .\glob\glob.c
    157 echo WinRel\glob.obj >>link.rel
    158 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c  .\glob\fnmatch.c
    159 echo WinRel\fnmatch.obj >>link.rel
    160 cl.exe /nologo /MT /W4 /GX /YX /O2 /I . /I glob /I w32/include /D NDEBUG /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR.\WinRel/ /Fp.\WinRel/%make%.pch /Fo.\WinRel/ /c  .\w32\pathstuff.c
    161 echo WinRel\pathstuff.obj >>link.rel
    162 echo off
    163 echo "Linking WinRel/%make%.exe"
    164 rem link.exe kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib w32\subproc\winrel\subproc.lib /NOLOGO /SUBSYSTEM:console /INCREMENTAL:no /PDB:.\WinRel/%make%.pdb /OUT:.\WinRel/%make%.exe .\WinRel/variable.obj  .\WinRel/rule.obj  .\WinRel/remote-stub.obj  .\WinRel/commands.obj  .\WinRel/file.obj  .\WinRel/getloadavg.obj  .\WinRel/default.obj  .\WinRel/signame.obj  .\WinRel/expand.obj  .\WinRel/dir.obj  .\WinRel/main.obj  .\WinRel/getopt1.obj  .\WinRel/job.obj  .\WinRel/read.obj  .\WinRel/version.obj  .\WinRel/getopt.obj  .\WinRel/arscan.obj  .\WinRel/remake.obj  .\WinRel/misc.obj  .\WinRel/hash.obj  .\WinRel/strcache.obj  .\WinRel/ar.obj  .\WinRel/function.obj  .\WinRel/vpath.obj  .\WinRel/implicit.obj  .\WinRel/dirent.obj  .\WinRel/glob.obj  .\WinRel/fnmatch.obj  .\WinRel/pathstuff.obj
    165 echo kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib w32\subproc\winrel\subproc.lib >>link.rel
    166 link.exe /NOLOGO /SUBSYSTEM:console /INCREMENTAL:no /PDB:.\WinRel/%make%.pdb /OUT:.\WinRel/%make%.exe @link.rel
    167 if not exist .\WinRel/%make%.exe echo "WinRel build failed"
    168 if exist .\WinRel/%make%.exe echo "WinRel build succeeded!"
    169 set make=
    170 GoTo BuildEnd
    171 :GCCBuild
    172 echo on
    173 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c variable.c
    174 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c rule.c
    175 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c remote-stub.c
    176 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c commands.c
    177 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c file.c
    178 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c getloadavg.c
    179 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c default.c
    180 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c signame.c
    181 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c expand.c
    182 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c dir.c
    183 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c main.c
    184 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c getopt1.c
    185 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c job.c
    186 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c read.c
    187 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c version.c
    188 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c getopt.c
    189 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c arscan.c
    190 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c remake.c
    191 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c hash.c
    192 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c strcache.c
    193 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c misc.c
    194 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c ar.c
    195 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c function.c
    196 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c vpath.c
    197 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c implicit.c
    198 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c ./glob/glob.c -o glob.o
    199 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c ./glob/fnmatch.c -o fnmatch.o
    200 gcc -mthreads -Wall -gdwarf-2 -g3 -O2 -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H -c ./w32/pathstuff.c -o pathstuff.o
    201 gcc -mthreads -gdwarf-2 -g3 -o gnumake.exe variable.o rule.o remote-stub.o commands.o file.o getloadavg.o default.o signame.o expand.o dir.o main.o getopt1.o job.o read.o version.o getopt.o arscan.o remake.o misc.o hash.o strcache.o ar.o function.o vpath.o implicit.o glob.o fnmatch.o pathstuff.o w32_misc.o sub_proc.o w32err.o -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32
    202 :BuildEnd
    203 echo on
     18call :Reset
     19
     20if "%1" == "-h" goto Usage
     21if "%1" == "--help" goto Usage
     22
     23set MAKE=gnumake
     24set GUILE=Y
     25set COMPILER=msvc
     26
     27:ParseSW
     28if "%1" == "--debug" goto SetDebug
     29if "%1" == "--without-guile" goto NoGuile
     30if "%1" == "gcc" goto SetCC
     31if "%1" == "" goto DoneSW
     32
     33:SetDebug
     34set DEBUG=Y
     35shift
     36goto ParseSW
     37
     38:NoGuile
     39set GUILE=N
     40echo Building without Guile
     41shift
     42goto ParseSW
     43
     44:SetCC
     45set COMPILER=gcc
     46echo Building with GCC
     47shift
     48goto ParseSW
     49
     50rem Build with Guile is supported only on NT and later versions
     51:DoneSW
     52echo.
     53echo Creating GNU Make for Windows 9X/NT/2K/XP/Vista/7/8
     54if "%DEBUG%" == "Y" echo Building without compiler optimizations
     55
     56if "%COMPILER%" == "gcc" goto GccBuild
     57
     58set OUTDIR=.\WinRel
     59set "OPTS=/O2 /D NDEBUG"
     60set LINKOPTS=
     61if "%DEBUG%" == "Y" set OUTDIR=.\WinDebug
     62if "%DEBUG%" == "Y" set "OPTS=/Zi /Od /D _DEBUG"
     63if "%DEBUG%" == "Y" set LINKOPTS=/DEBUG
     64call :Build
     65goto Done
     66
     67:GccBuild
     68set OUTDIR=.\GccRel
     69set OPTS=-O2
     70if "%DEBUG%" == "Y" set OPTS=-O0
     71if "%DEBUG%" == "Y" set OUTDIR=.\GccDebug
     72call :Build
     73goto Done
     74
     75:Done
     76call :Reset
     77goto :EOF
     78
     79:Build
     80:: Clean the directory if it exists
     81if exist %OUTDIR%\nul rmdir /S /Q %OUTDIR%
     82
     83:: Recreate it
     84mkdir %OUTDIR%
     85mkdir %OUTDIR%\glob
     86mkdir %OUTDIR%\w32
     87mkdir %OUTDIR%\w32\compat
     88mkdir %OUTDIR%\w32\subproc
     89
     90if "%GUILE%" == "Y" call :ChkGuile
     91
     92echo.
     93echo Compiling %OUTDIR% version
     94
     95if exist config.h.W32.template call :ConfigSCM
     96copy config.h.W32 %OUTDIR%\config.h
     97
     98call :Compile ar
     99call :Compile arscan
     100call :Compile commands
     101call :Compile default
     102call :Compile dir
     103call :Compile expand
     104call :Compile file
     105call :Compile function
     106call :Compile getloadavg
     107call :Compile getopt
     108call :Compile getopt1
     109call :Compile glob\fnmatch
     110call :Compile glob\glob
     111call :Compile guile GUILE
     112call :Compile hash
     113call :Compile implicit
     114call :Compile job
     115call :Compile load
     116call :Compile loadapi
     117call :Compile main GUILE
     118call :Compile misc
     119call :Compile output
     120call :Compile read
     121call :Compile remake
     122call :Compile remote-stub
     123call :Compile rule
     124call :Compile signame
     125call :Compile strcache
     126call :Compile variable
     127call :Compile version
     128call :Compile vpath
     129call :Compile w32\compat\posixfcn
     130call :Compile w32\pathstuff
     131call :Compile w32\subproc\misc
     132call :Compile w32\subproc\sub_proc
     133call :Compile w32\subproc\w32err
     134call :Compile w32\w32os
     135
     136if not "%COMPILER%" == "gcc" call :Compile w32\compat\dirent
     137
     138call :Link
     139
     140echo.
     141if not exist %OUTDIR%\%MAKE%.exe echo %OUTDIR% build FAILED!
     142if exist %OUTDIR%\%MAKE%.exe echo %OUTDIR% build succeeded.
     143goto :EOF
     144
     145:Compile
     146set EXTRAS=
     147if "%2" == "GUILE" set "EXTRAS=%GUILECFLAGS%"
     148if "%COMPILER%" == "gcc" goto GccCompile
     149
     150:: MSVC Compile
     151echo on
     152cl.exe /nologo /MT /W4 /EHsc %OPTS% /I %OUTDIR% /I . /I glob /I w32/include /D WINDOWS32 /D WIN32 /D _CONSOLE /D HAVE_CONFIG_H /FR%OUTDIR% /Fp%OUTDIR%\%MAKE%.pch /Fo%OUTDIR%\%1.obj /Fd%OUTDIR%\%MAKE%.pdb %EXTRAS% /c %1.c
     153@echo off
     154echo %OUTDIR%\%1.obj >>%OUTDIR%\link.sc
     155goto :EOF
     156
     157:GccCompile
     158:: GCC Compile
     159echo on
     160gcc -mthreads -Wall -std=gnu99 -gdwarf-2 -g3 %OPTS% -I%OUTDIR% -I. -I./glob -I./w32/include -DWINDOWS32 -DHAVE_CONFIG_H %EXTRAS% -o %OUTDIR%\%1.o -c %1.c
     161@echo off
     162goto :EOF
     163
     164:Link
     165echo Linking %OUTDIR%/%MAKE%.exe
     166if "%COMPILER%" == "gcc" goto GccLink
     167
     168:: MSVC Link
     169echo %GUILELIBS% kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib >>%OUTDIR%\link.sc
     170echo on
     171link.exe /NOLOGO /SUBSYSTEM:console /PDB:%OUTDIR%\%MAKE%.pdb %LINKOPTS% /OUT:%OUTDIR%\%MAKE%.exe @%OUTDIR%\link.sc
     172@echo off
     173goto :EOF
     174
     175:GccLink
     176:: GCC Link
     177echo on
     178gcc -mthreads -gdwarf-2 -g3 -o %OUTDIR%\%MAKE%.exe %OUTDIR%\variable.o %OUTDIR%\rule.o %OUTDIR%\remote-stub.o %OUTDIR%\commands.o %OUTDIR%\file.o %OUTDIR%\getloadavg.o %OUTDIR%\default.o %OUTDIR%\signame.o %OUTDIR%\expand.o %OUTDIR%\dir.o %OUTDIR%\main.o %OUTDIR%\getopt1.o %OUTDIR%\guile.o %OUTDIR%\job.o %OUTDIR%\output.o %OUTDIR%\read.o %OUTDIR%\version.o %OUTDIR%\getopt.o %OUTDIR%\arscan.o %OUTDIR%\remake.o %OUTDIR%\misc.o %OUTDIR%\hash.o %OUTDIR%\strcache.o %OUTDIR%\ar.o %OUTDIR%\function.o %OUTDIR%\vpath.o %OUTDIR%\implicit.o %OUTDIR%\loadapi.o %OUTDIR%\load.o %OUTDIR%\glob\glob.o %OUTDIR%\glob\fnmatch.o %OUTDIR%\w32\pathstuff.o %OUTDIR%\w32\compat\posixfcn.o %OUTDIR%\w32\w32os.o %OUTDIR%\w32\subproc\misc.o %OUTDIR%\w32\subproc\sub_proc.o %OUTDIR%\w32\subproc\w32err.o %GUILELIBS% -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 -Wl,--out-implib=%OUTDIR%\libgnumake-1.dll.a
     179@echo off
     180goto :EOF
     181
     182:ConfigSCM
     183echo Generating config from SCM templates
     184sed -n "s/^AC_INIT(\[GNU make\],\[\([^]]\+\)\].*/s,%%VERSION%%,\1,g/p" configure.ac > %OUTDIR%\config.h.W32.sed
     185echo s,%%PACKAGE%%,make,g >> %OUTDIR%\config.h.W32.sed
     186sed -f %OUTDIR%\config.h.W32.sed config.h.W32.template > config.h.W32
     187echo static const char *const GUILE_module_defn = ^" \> gmk-default.h
     188sed -e "s/;.*//" -e "/^[ \t]*$/d" -e "s/\"/\\\\\"/g" -e "s/$/ \\\/" gmk-default.scm >> gmk-default.h
     189echo ^";>> gmk-default.h
     190goto :EOF
     191
     192:ChkGuile
     193if not "%OS%" == "Windows_NT" goto NoGuile
     194pkg-config --help > %OUTDIR%\guile.tmp 2> NUL
     195if ERRORLEVEL 1 goto NoPkgCfg
     196
     197echo Checking for Guile 2.0
     198if not "%COMPILER%" == "gcc" set PKGMSC=--msvc-syntax
     199pkg-config --cflags --short-errors "guile-2.0" > %OUTDIR%\guile.tmp
     200if not ERRORLEVEL 1 set /P GUILECFLAGS= < %OUTDIR%\guile.tmp
     201
     202pkg-config --libs --static --short-errors %PKGMSC% "guile-2.0" > %OUTDIR%\guile.tmp
     203if not ERRORLEVEL 1 set /P GUILELIBS= < %OUTDIR%\guile.tmp
     204
     205if not "%GUILECFLAGS%" == "" goto GuileDone
     206
     207echo Checking for Guile 1.8
     208pkg-config --cflags --short-errors "guile-1.8" > %OUTDIR%\guile.tmp
     209if not ERRORLEVEL 1 set /P GUILECFLAGS= < %OUTDIR%\guile.tmp
     210
     211pkg-config --libs --static --short-errors %PKGMSC% "guile-1.8" > %OUTDIR%\guile.tmp
     212if not ERRORLEVEL 1 set /P GUILELIBS= < %OUTDIR%\guile.tmp
     213
     214if not "%GUILECFLAGS%" == "" goto GuileDone
     215
     216echo No Guile found, building without Guile
     217goto GuileDone
     218
     219:NoPkgCfg
     220echo pkg-config not found, building without Guile
     221
     222:GuileDone
     223if "%GUILECFLAGS%" == "" goto :EOF
     224
     225echo Guile found, building with Guile
     226set "GUILECFLAGS=%GUILECFLAGS% -DHAVE_GUILE"
     227goto :EOF
     228
     229:Usage
     230echo Usage: %0 [options] [gcc]
     231echo Options:
     232echo.  --debug           For GCC only, make a debug build
     233echo.                    (MSVC build always makes both debug and release)
     234echo.  --without-guile   Do not compile Guile support even if found
     235echo.  --help            Display these instructions and exit
     236goto :EOF
     237
     238:Reset
     239set COMPILER=
     240set DEBUG=
     241set GUILE=
     242set GUILECFLAGS=
     243set GUILELIBS=
     244set LINKOPTS=
     245set MAKE=
     246set NOGUILE=
     247set OPTS=
     248set OUTDIR=
     249set PKGMSC=
     250goto :EOF
  • trunk/src/kmk/commands.c

    r2754 r3140  
    11/* Command processing for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
     18#include "filedef.h"
    2019#include "dep.h"
    21 #include "filedef.h"
    2220#include "variable.h"
    2321#include "job.h"
     
    3230
    3331#if VMS
    34 # define FILE_LIST_SEPARATOR ','
     32# define FILE_LIST_SEPARATOR (vms_comma_separator ? ',' : ' ')
    3533#else
    3634# define FILE_LIST_SEPARATOR ' '
    3735#endif
    3836
    39 int remote_kill (int id, int sig);
    40 
    41 #ifndef HAVE_UNISTD_H
     37#ifndef HAVE_UNISTD_H
    4238int getpid ();
    4339#endif
     
    176172#endif
    177173
    178 #ifndef NO_ARCHIVES
    179   /* If the target is an archive member `lib(member)',
    180      then $@ is `lib' and $% is `member'.  */
     174#ifndef NO_ARCHIVES
     175  /* If the target is an archive member 'lib(member)',
     176     then $@ is 'lib' and $% is 'member'.  */
    181177
    182178  if (ar_name (file->name))
     
    198194    }
    199195  else
    200 #endif  /* NO_ARCHIVES.  */
     196#endif  /* NO_ARCHIVES.  */
    201197    {
    202198      at = file->name;
     
    208204    {
    209205      /* In Unix make, $* is set to the target name with
    210         any suffix in the .SUFFIXES list stripped off for
    211          explicit rules.  We store this in the `stem' member.  */
     206        any suffix in the .SUFFIXES list stripped off for
     207         explicit rules.  We store this in the 'stem' member.  */
    212208      const char *name;
    213209      unsigned int len;
    214210
    215 #ifndef NO_ARCHIVES
     211#ifndef NO_ARCHIVES
    216212      if (ar_name (file->name))
     213        {
     214          name = strchr (file->name, '(') + 1;
     215          len = strlen (name) - 1;
     216        }
     217      else
     218#endif
    217219        {
    218           name = strchr (file->name, '(') + 1;
    219           len = strlen (name) - 1;
    220         }
    221       else
    222 #endif
    223         {
    224           name = file->name;
     220          name = file->name;
    225221#ifndef CONFIG_WITH_STRCACHE2
    226           len = strlen (name);
    227 #else
    228           len = strcache2_get_len (&file_strcache, name);
    229 #endif
    230         }
     222          len = strlen (name);
     223#else
     224          len = strcache2_get_len (&file_strcache, name);
     225#endif
     226        }
    231227
    232228#ifndef CONFIG_WITH_STRCACHE2
    233229      for (d = enter_file (strcache_add (".SUFFIXES"))->deps; d ; d = d->next)
    234         {
    235           unsigned int slen = strlen (dep_name (d));
     230        {
     231          unsigned int slen = strlen (dep_name (d));
    236232#else
    237233      for (d = enter_file (suffixes_strcached)->deps; d ; d = d->next)
    238234        {
    239           unsigned int slen = strcache2_get_len (&file_strcache, dep_name (d));
    240 #endif
    241           if (len > slen && strneq (dep_name (d), name + (len - slen), slen))
    242             {
    243               file->stem = strcache_add_len (name, len - slen);
    244               break;
    245             }
    246         }
     235          unsigned int slen = strcache2_get_len (&file_strcache, dep_name (d));
     236#endif
     237          if (len > slen && strneq (dep_name (d), name + (len - slen), slen))
     238            {
     239              file->stem = strcache_add_len (name, len - slen);
     240              break;
     241            }
     242        }
    247243      if (d == 0)
    248         file->stem = "";
     244        file->stem = "";
    249245    }
    250246  star = file->stem;
     
    265261    less = at;
    266262
    267 #define DEFINE_VARIABLE(name, len, value) \
     263#define DEFINE_VARIABLE(name, len, value) \
    268264  (void) define_variable_for_file (name,len,value,o_automatic,0,file)
    269265
     
    369365    cp = plus_value;
    370366
    371     qmark_len = plus_len + 1;   /* Will be this or less.  */
     367    qmark_len = plus_len + 1;   /* Will be this or less.  */
    372368    for (d = file->deps; d != 0; d = d->next)
    373369      if (! d->ignore_mtime && ! d->need_2nd_expansion)
     
    375371          const char *c = dep_name (d);
    376372
    377 #ifndef NO_ARCHIVES
     373#ifndef NO_ARCHIVES
    378374          if (ar_name (c))
    379375            {
     
    393389          *cp++ = FILE_LIST_SEPARATOR;
    394390          if (! (d->changed || always_make_flag))
    395             qmark_len -= len + 1;       /* Don't space in $? for this one.  */
     391            qmark_len -= len + 1;       /* Don't space in $? for this one.  */
    396392        }
    397393
     
    448444
    449445        c = dep_name (d);
    450 #ifndef NO_ARCHIVES
     446#ifndef NO_ARCHIVES
    451447        if (ar_name (c))
    452           {
    453             c = strchr (c, '(') + 1;
    454             len = strlen (c) - 1;
    455           }
    456         else
     448          {
     449            c = strchr (c, '(') + 1;
     450            len = strlen (c) - 1;
     451          }
     452        else
    457453#endif
    458454#ifndef CONFIG_WITH_STRCACHE2
    459           len = strlen (c);
    460 #else
    461           len = strcache2_get_len (&file_strcache, c);
     455          len = strlen (c);
     456#else
     457          len = strcache2_get_len (&file_strcache, c);
    462458#endif
    463459
     
    465461          {
    466462            memcpy (bp, c, len);
    467             bp += len;
    468             *bp++ = FILE_LIST_SEPARATOR;
    469           }
    470         else
     463            bp += len;
     464            *bp++ = FILE_LIST_SEPARATOR;
     465          }
     466        else
    471467          {
    472468            memcpy (cp, c, len);
     
    495491    DEFINE_VARIABLE ("|", 1, bar_value);
    496492  }
    497 #undef  DEFINE_VARIABLE
     493#undef  DEFINE_VARIABLE
    498494}
    499495
    500496
    501497/* Chop CMDS up into individual command lines if necessary.
    502    Also set the `lines_flags' and `any_recurse' members.  */
     498   Also set the 'lines_flags' and 'any_recurse' members.  */
    503499
    504500void
     
    577573     CMDS->any_recurse flag.  */
    578574
     575  if (nlines > USHRT_MAX)
     576    ON (fatal, &cmds->fileinfo, _("Recipe has too many lines (%ud)"), nlines);
     577
    579578  cmds->ncommand_lines = nlines;
    580579  cmds->command_lines = lines;
     
    589588  for (idx = 0; idx < nlines; ++idx)
    590589    {
    591       int flags = 0;
     590      unsigned char flags = 0;
    592591      const char *p = lines[idx];
    593592
    594       while (isblank (*p) || *p == '-' || *p == '@' || *p == '+' IF_WITH_COMMANDS_FUNC(|| *p == '%'))
     593      while (ISBLANK (*p) || *p == '-' || *p == '@' || *p == '+' IF_WITH_COMMANDS_FUNC(|| *p == '%'))
    595594        switch (*(p++))
    596595          {
     
    628627
    629628      cmds->lines_flags[idx] = flags;
    630       cmds->any_recurse |= flags & COMMANDS_RECURSE;
     629      cmds->any_recurse |= flags & COMMANDS_RECURSE ? 1 : 0;
    631630    }
    632631}
     
    668667
    669668  for (p = file->cmds->commands; *p != '\0'; ++p)
    670     if (!isspace ((unsigned char)*p) && *p != '-' && *p != '@')
     669    if (!ISSPACE (*p) && *p != '-' && *p != '@' && *p != '+')
    671670      break;
    672671  if (*p == '\0')
     
    677676#endif
    678677      set_command_state (file, cs_running);
    679       file->update_status = 0;
     678      file->update_status = us_success;
    680679      notice_finished_file (file);
    681680      return;
     
    691690  set_file_variables (file);
    692691#endif
     692
     693  /* If this is a loaded dynamic object, unload it before remaking.
     694     Some systems don't support overwriting a loaded object.  */
     695  if (file->loaded)
     696    unload_file (file->name);
    693697
    694698  /* Start the commands running.  */
     
    737741
    738742      if (susp_count != 0)
    739         fprintf (stderr, "SuspendThread: suspend count = %ld\n", susp_count);
     743        fprintf (stderr, "SuspendThread: suspend count = %ld\n", susp_count);
    740744      else if (susp_count == (DWORD)-1)
    741         {
    742           DWORD ierr = GetLastError ();
    743 
    744           fprintf (stderr, "SuspendThread: error %ld: %s\n",
    745                    ierr, map_windows32_error_to_string (ierr));
    746         }
     745        {
     746          DWORD ierr = GetLastError ();
     747
     748          fprintf (stderr, "SuspendThread: error %ld: %s\n",
     749                   ierr, map_windows32_error_to_string (ierr));
     750        }
    747751    }
    748752#endif
     
    760764      struct child *c;
    761765      for (c = children; c != 0; c = c->next)
    762         if (!c->remote)
    763           (void) kill (c->pid, SIGTERM);
     766        if (!c->remote)
     767          (void) kill (c->pid, SIGTERM);
    764768    }
    765769
     
    779783
    780784      /* Remote children won't automatically get signals sent
    781         to the process group, so we must send them.  */
     785        to the process group, so we must send them.  */
    782786      for (c = children; c != 0; c = c->next)
    783         if (c->remote)
    784           (void) remote_kill (c->pid, sig);
     787        if (c->remote)
     788          (void) remote_kill (c->pid, sig);
    785789
    786790      for (c = children; c != 0; c = c->next)
    787         delete_child_targets (c);
     791        delete_child_targets (c);
    788792
    789793      /* Clean up the children.  We don't just use the call below because
    790         we don't want to print the "Waiting for children" message.  */
     794        we don't want to print the "Waiting for children" message.  */
    791795      while (job_slots_used > 0)
    792         reap_children (1, 0);
     796        reap_children (1, 0);
    793797    }
    794798  else
     
    804808    /* We don't want to send ourselves SIGQUIT, because it will
    805809       cause a core dump.  Just exit instead.  */
    806     exit (EXIT_FAILURE);
     810    exit (MAKE_TROUBLE);
    807811#endif
    808812
     
    845849    {
    846850      time_t file_date = (file->last_mtime == NONEXISTENT_MTIME
    847                           ? (time_t) -1
    848                           : (time_t) FILE_TIMESTAMP_S (file->last_mtime));
     851                          ? (time_t) -1
     852                          : (time_t) FILE_TIMESTAMP_S (file->last_mtime));
    849853      if (ar_member_date (file->name) != file_date)
    850         {
    851           if (on_behalf_of)
    852             error (NILF, _("*** [%s] Archive member `%s' may be bogus; not deleted"),
    853                    on_behalf_of, file->name);
    854           else
    855             error (NILF, _("*** Archive member `%s' may be bogus; not deleted"),
    856                    file->name);
    857         }
     854        {
     855          if (on_behalf_of)
     856            OSS (error, NILF,
     857                 _("*** [%s] Archive member '%s' may be bogus; not deleted"),
     858                 on_behalf_of, file->name);
     859          else
     860            OS (error, NILF,
     861                _("*** Archive member '%s' may be bogus; not deleted"),
     862                file->name);
     863        }
    858864      return;
    859865    }
     
    866872    {
    867873      if (on_behalf_of)
    868         error (NILF, _("*** [%s] Deleting file `%s'"), on_behalf_of, file->name);
     874        OSS (error, NILF,
     875             _("*** [%s] Deleting file '%s'"), on_behalf_of, file->name);
    869876      else
    870         error (NILF, _("*** Deleting file `%s'"), file->name);
     877        OS (error, NILF, _("*** Deleting file '%s'"), file->name);
    871878      if (unlink (file->name) < 0
    872           && errno != ENOENT)   /* It disappeared; so what.  */
    873         perror_with_name ("unlink: ", file->name);
     879          && errno != ENOENT)   /* It disappeared; so what.  */
     880        perror_with_name ("unlink: ", file->name);
    874881    }
    875882}
     
    890897  delete_target (child->file, NULL);
    891898
    892   /* Also remove any non-precious targets listed in the `also_make' member.  */
     899  /* Also remove any non-precious targets listed in the 'also_make' member.  */
    893900  for (d = child->file->also_make; d != 0; d = d->next)
    894901    delete_target (d->file, child->file->name);
     
    923930    puts (_(" (built-in):"));
    924931  else
    925     printf (_(" (from `%s', line %lu):\n"),
     932    printf (_(" (from '%s', line %lu):\n"),
    926933            cmds->fileinfo.filenm, cmds->fileinfo.lineno);
    927934
     
    930937    {
    931938      const char *end;
    932 
    933       end = strchr (s, '\n');
    934       if (end == 0)
    935         end = s + strlen (s);
     939      int bs;
     940
     941      /* Print one full logical recipe line: find a non-escaped newline.  */
     942      for (end = s, bs = 0; *end != '\0'; ++end)
     943        {
     944          if (*end == '\n' && !bs)
     945            break;
     946
     947          bs = *end == '\\' ? !bs : 0;
     948        }
    936949
    937950      printf ("%c%.*s\n", cmd_prefix, (int) (end - s), s);
  • trunk/src/kmk/commands.h

    r2754 r3140  
    11/* Definition of data structures describing shell commands for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    2220struct commands
    2321  {
    24     struct floc fileinfo;       /* Where commands were defined.  */
    25     char *commands;             /* Commands text.  */
    26     unsigned int ncommand_lines;/* Number of command lines.  */
    27     char **command_lines;       /* Commands chopped up into lines.  */
     22    floc fileinfo;              /* Where commands were defined.  */
     23    char *commands;             /* Commands text.  */
     24    char **command_lines;       /* Commands chopped up into lines.  */
    2825#ifdef CONFIG_WITH_COMMANDS_FUNC
    29     short *lines_flags;         /* One set of flag bits for each line.  */
     26    unsigned short *lines_flags;/* One set of flag bits for each line.  */
    3027#else
    31     char *lines_flags;          /* One set of flag bits for each line.  */
     28    unsigned char *lines_flags; /* One set of flag bits for each line.  */
    3229#endif
    33     int any_recurse;            /* Nonzero if any `lines_recurse' elt has */
    34                                 /* the COMMANDS_RECURSE bit set.  */
     30    unsigned short ncommand_lines;/* Number of command lines.  */
     31    char recipe_prefix;         /* Recipe prefix for this command set.  */
     32    unsigned int any_recurse:1; /* Nonzero if any 'lines_flags' elt has */
     33                                /* the COMMANDS_RECURSE bit set.  */
    3534#ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
    3635    int refs;                   /* References.  */
     
    3837  };
    3938
    40 /* Bits in `lines_flags'.  */
    41 #define COMMANDS_RECURSE        1 /* Recurses: + or $(MAKE).  */
    42 #define COMMANDS_SILENT         2 /* Silent: @.  */
    43 #define COMMANDS_NOERROR        4 /* No errors: -.  */
     39/* Bits in 'lines_flags'.  */
     40#define COMMANDS_RECURSE        1 /* Recurses: + or $(MAKE).  */
     41#define COMMANDS_SILENT         2 /* Silent: @.  */
     42#define COMMANDS_NOERROR        4 /* No errors: -.  */
    4443#ifdef CONFIG_WITH_EXTENDED_NOTPARALLEL
    4544# define COMMANDS_NOTPARALLEL   32  /* kmk: The commands must be executed alone. */
     
    5352#endif
    5453
     54RETSIGTYPE fatal_error_signal (int sig);
    5555void execute_file_commands (struct file *file);
    5656void print_commands (const struct commands *cmds);
  • trunk/src/kmk/config.ami.template

    r2591 r3140  
    11/* config.h -- hand-massaged for Amiga                                  -*-C-*-
    2 Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
    3 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1995-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    1817/* Define if on AIX 3.
    1918   System headers sometimes define this.
    20    We just want to avoid a redefinition error message.  */
     19   We just want to avoid a redefinition error message.  */
    2120#ifndef _ALL_SOURCE
    2221/* #undef _ALL_SOURCE */
     
    3938/* #undef DGUX */
    4039
    41 /* Define if the `getloadavg' function needs to be run setuid or setgid.  */
     40/* Define if the 'getloadavg' function needs to be run setuid or setgid.  */
    4241/* #undef GETLOADAVG_PRIVILEGED */
    4342
    44 /* Define to `unsigned long' or `unsigned long long'
     43/* Define to 'unsigned long' or 'unsigned long long'
    4544   if <inttypes.h> doesn't define.  */
    4645#define uintmax_t unsigned long
    4746
    48 /* Define to `int' if <sys/types.h> doesn't define.  */
     47/* Define to 'int' if <sys/types.h> doesn't define.  */
    4948#define gid_t int
    5049
     
    5554/* #undef HAVE_ALLOCA_H */
    5655
    57 /* Define if you don't have vprintf but do have _doprnt.  */
    58 /* #undef HAVE_DOPRNT */
    59 
    6056/* Define if your system has a working fnmatch function.  */
    6157/* #undef HAVE_FNMATCH */
    6258
    63 /* Define if your system has its own `getloadavg' function.  */
     59/* Define if your system has its own 'getloadavg' function.  */
    6460/* #undef HAVE_GETLOADAVG */
    6561
     
    6763/* #undef HAVE_GETMNTENT */
    6864
    69 /* Define if the `long double' type works.  */
     65/* Embed GNU Guile support */
     66/* #undef HAVE_GUILE */
     67
     68/* Define if the 'long double' type works.  */
    7069/* #undef HAVE_LONG_DOUBLE */
    7170
    72 /* Define if you support file names longer than 14 characters.  */
     71/* Define if you support file names longer than 14 characters.  */
    7372#define HAVE_LONG_FILE_NAMES 1
    7473
    75 /* Define if you have a working `mmap' system call.  */
     74/* Define if you have a working 'mmap' system call.  */
    7675/* #undef HAVE_MMAP */
    7776
     
    8685/* #undef HAVE_ST_BLOCKS */
    8786
    88 /* Define if you have the strcoll function and it is properly defined.  */
     87/* Define if you have the strcoll function and it is properly defined.  */
    8988#define HAVE_STRCOLL 1
    9089
     
    9594#define HAVE_STRFTIME 1
    9695
    97 /* Define if you have <sys/wait.h> that is POSIX.1 compatible.  */
     96/* Define if you have <sys/wait.h> that is POSIX.1 compatible.  */
    9897/* #undef HAVE_SYS_WAIT_H */
    9998
     
    111110/* #undef HAVE_UTIME_NULL */
    112111
    113 /* Define if you have <vfork.h>.  */
    114 /* #undef HAVE_VFORK_H */
    115 
    116 /* Define if you have the vprintf function.  */
    117 #define HAVE_VPRINTF 1
    118 
    119112/* Define if you have the wait3 system call.  */
    120113/* #undef HAVE_WAIT3 */
    121114
    122 /* Define if on MINIX.  */
     115/* Define if on MINIX.  */
    123116/* #undef _MINIX */
    124117
     
    132125/* #undef NO_MINUS_C_MINUS_O */
    133126
    134 /* Define to `int' if <sys/types.h> doesn't define.  */
     127/* Define to 'int' if <sys/types.h> doesn't define.  */
    135128#define pid_t int
    136129
     
    153146   direction of stack growth for your system; otherwise it will be
    154147   automatically deduced at run-time.
    155         STACK_DIRECTION > 0 => grows toward higher addresses
    156         STACK_DIRECTION < 0 => grows toward lower addresses
    157         STACK_DIRECTION = 0 => direction of growth unknown
     148        STACK_DIRECTION > 0 => grows toward higher addresses
     149        STACK_DIRECTION < 0 => grows toward lower addresses
     150        STACK_DIRECTION = 0 => direction of growth unknown
    158151 */
    159152#define STACK_DIRECTION -1
    160153
    161 /* Define if the `S_IS*' macros in <sys/stat.h> do not work properly.  */
     154/* Define if the 'S_IS*' macros in <sys/stat.h> do not work properly.  */
    162155/* #undef STAT_MACROS_BROKEN */
    163156
    164 /* Define if your compiler conforms to the ANSI C standard. */
    165 #define HAVE_ANSI_COMPILER 1
    166 
    167 /* Define if you have the ANSI C header files.  */
     157/* Define if you have the ANSI C header files.  */
    168158#define STDC_HEADERS
    169159
     
    171161/* #undef SVR4 */
    172162
    173 /* Define if `sys_siglist' is declared by <signal.h>.  */
     163/* Define if 'sys_siglist' is declared by <signal.h>.  */
    174164/* #undef SYS_SIGLIST_DECLARED */
    175165
    176 /* Define to `int' if <sys/types.h> doesn't define.  */
     166/* Define to 'int' if <sys/types.h> doesn't define.  */
    177167#define uid_t int
    178168
     
    184174/* #undef UMAX4_3 */
    185175
    186 /* Define vfork as fork if vfork does not work.  */
    187 /* #undef vfork */
    188 
    189176/* Name of this package (needed by automake) */
    190177#define PACKAGE "%PACKAGE%"
     
    193180#define VERSION "%VERSION%"
    194181
    195 /* Define to the name of the SCCS `get' command.  */
     182/* Define to the name of the SCCS 'get' command.  */
    196183#define SCCS_GET "get"
    197184
    198 /* Define this if the SCCS `get' command understands the `-G<file>' option.  */
     185/* Define this if the SCCS 'get' command understands the '-G<file>' option.  */
    199186/* #undef SCCS_GET_MINUS_G */
    200187
     
    206193/* #undef ST_MTIM_NSEC */
    207194
    208 /* Define this if the C library defines the variable `sys_siglist'.  */
     195/* Define this if the C library defines the variable 'sys_siglist'.  */
    209196/* #undef HAVE_SYS_SIGLIST */
    210197
    211 /* Define this if the C library defines the variable `_sys_siglist'.  */
     198/* Define this if the C library defines the variable '_sys_siglist'.  */
    212199/* #undef HAVE__SYS_SIGLIST */
    213200
    214 /* Define this if you have the `union wait' type in <sys/wait.h>.  */
     201/* Define this if you have the 'union wait' type in <sys/wait.h>.  */
    215202/* #undef HAVE_UNION_WAIT */
    216203
     
    248235/* #undef HAVE_SETEUID */
    249236
    250 /* Define if you have the setlinebuf function.  */
     237/* Define if you have the setlinebuf function.  */
    251238/* #undef HAVE_SETLINEBUF */
    252239
     
    257244/* #undef HAVE_SETREUID */
    258245
    259 /* Define if you have the sigsetmask function.  */
     246/* Define if you have the sigsetmask function.  */
    260247/* #undef HAVE_SIGSETMASK */
    261248
     
    302289/* #undef HAVE_NDIR_H */
    303290
    304 /* Define to 1 if you have the <stdarg.h> header file. */
    305 #define HAVE_STDARG_H 1
    306 
    307291/* Define if you have the <stdlib.h> header file.  */
    308292/* #undef HAVE_STDLIB_H */
     
    335319/* #undef HAVE_LIBKSTAT */
    336320
     321/* Define to 1 if you have the `isatty' function. */
     322/* #undef HAVE_ISATTY */
     323
     324/* Define to 1 if you have the `ttyname' function. */
     325/* #undef HAVE_TTYNAME */
     326
    337327/* Define if you have the sun library (-lsun).  */
    338328/* #undef HAVE_LIBSUN */
    339329
     330/* Output sync sypport */
     331#define NO_OUTPUT_SYNC
     332
    340333/* Define for Case Insensitve behavior */
    341334#define HAVE_CASE_INSENSITIVE_FS
  • trunk/src/kmk/config.h-vms.template

    r2591 r3140  
    11/* config.h-vms. Generated by hand by Klaus Kämpf <[email protected]>      -*-C-*-
    22
    3 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    4 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     3Copyright (C) 1996-2016 Free Software Foundation, Inc.
    54This file is part of GNU Make.
    65
     
    1817
    1918/* config.h.  Generated automatically by configure.  */
    20 /* config.h.in.  Generated automatically from configure.in by autoheader.  */
     19/* config.h.in.  Generated automatically from configure.ac by autoheader.  */
     20
     21/* Pull in types.h here to get __CRTL_VER defined for old versions of the
     22   compiler which don't define it. */
     23#ifdef __DECC
     24# include <types.h>
     25#endif
    2126
    2227/* Define to 1 if on AIX 3.
     
    3641/* #undef HAVE_GETTEXT */
    3742
     43/* Embed GNU Guile support */
     44/* #undef HAVE_GUILE */
     45
    3846/* Define to 1 if your locale.h file contains LC_MESSAGES.  */
    3947/* #undef HAVE_LC_MESSAGES */
     
    5866/* #undef DGUX */
    5967
    60 /* Define to 1 if the `getloadavg' function needs to be run setuid or setgid.  */
     68/* Define to 1 if the 'getloadavg' function needs to be run setuid or setgid.  */
    6169/* #undef GETLOADAVG_PRIVILEGED */
    6270
    63 /* Define to `unsigned long' or `unsigned long long'
     71/* Define to 'unsigned long' or 'unsigned long long'
    6472   if <inttypes.h> doesn't define.  */
    6573#define uintmax_t unsigned long
    6674
    67 /* Define to `int' if <sys/types.h> doesn't define.  */
     75/* Define to 'int' if <sys/types.h> doesn't define.  */
    6876/* #undef gid_t */
    6977
     
    7482/* #undef HAVE_ALLOCA_H */
    7583
    76 /* Define to 1 if you don't have vprintf but do have _doprnt.  */
    77 /* #undef HAVE_DOPRNT */
    78 
    7984/* Define to 1 if you have the fdopen function.  */
    8085#define HAVE_FDOPEN 1
     
    8388/* #undef HAVE_FNMATCH */
    8489
    85 /* Define to 1 if your system has its own `getloadavg' function.  */
     90/* Define to 1 if your system has its own 'getloadavg' function.  */
    8691/* #undef HAVE_GETLOADAVG */
    8792
     
    8994/* #undef HAVE_GETMNTENT */
    9095
    91 /* Define to 1 if the `long double' type works.  */
     96/* Define to 1 if the 'long double' type works.  */
    9297/* #undef HAVE_LONG_DOUBLE */
    9398
     
    95100#define HAVE_LONG_FILE_NAMES 1
    96101
    97 /* Define to 1 if you have a working `mmap' system call.  */
     102/* Define to 1 if you have a working 'mmap' system call.  */
    98103/* #undef HAVE_MMAP */
    99104
     
    111116/* #undef HAVE_STRCOLL */
    112117
     118/* Define to 1 if you have the strncasecmp' function. */
     119#if __CRTL_VER >= 70000000
     120#define HAVE_STRNCASECMP 1
     121#endif
     122
    113123/* Define to 1 if your struct stat has st_rdev.  */
    114124/* #undef HAVE_ST_RDEV */
     
    135145/* #undef HAVE_UTIME_NULL */
    136146
    137 /* Define to 1 if you have <vfork.h>.  */
    138 /* #undef HAVE_VFORK_H */
    139 
    140 /* Define to 1 if you have the vprintf function.  */
    141 #define HAVE_VPRINTF 1
    142 
    143147/* Define to 1 if you have the wait3 system call.  */
    144148/* #undef HAVE_WAIT3 */
     
    156160/* #undef NO_MINUS_C_MINUS_O */
    157161
    158 /* Define to `int' if <sys/types.h> doesn't define.  */
     162/* Define to 'int' if <sys/types.h> doesn't define.  */
    159163/* I assume types.h is available for all 5.0 cc/cxx compilers */
    160164#if __DECC_VER < 50090000
     
    180184   direction of stack growth for your system; otherwise it will be
    181185   automatically deduced at run-time.
    182         STACK_DIRECTION > 0 => grows toward higher addresses
    183         STACK_DIRECTION < 0 => grows toward lower addresses
    184         STACK_DIRECTION = 0 => direction of growth unknown
     186        STACK_DIRECTION > 0 => grows toward higher addresses
     187        STACK_DIRECTION < 0 => grows toward lower addresses
     188        STACK_DIRECTION = 0 => direction of growth unknown
    185189 */
    186190/* #undef STACK_DIRECTION */
    187191
    188 /* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly.  */
     192/* Define to 1 if the 'S_IS*' macros in <sys/stat.h> do not work properly.  */
    189193/* #undef STAT_MACROS_BROKEN */
    190194
     
    195199/* #undef SVR4 */
    196200
    197 /* Define to 1 if `sys_siglist' is declared by <signal.h>.  */
     201/* Define to 1 if 'sys_siglist' is declared by <signal.h>.  */
    198202/* #undef SYS_SIGLIST_DECLARED */
    199203
    200 /* Define to `int' if <sys/types.h> doesn't define.  */
     204/* Define to 'int' if <sys/types.h> doesn't define.  */
    201205#if __DECC_VER < 50090000
    202206#define uid_t int
     
    210214/* #undef UMAX4_3 */
    211215
    212 /* Define vfork as fork if vfork does not work.  */
    213 /* #undef vfork */
    214 
    215216/* Name of this package (needed by automake) */
    216217#define PACKAGE "%PACKAGE%"
     
    219220#define VERSION "%VERSION%"
    220221
    221 /* Define to the name of the SCCS `get' command.  */
     222/* Define to the name of the SCCS 'get' command.  */
    222223/* #undef SCCS_GET */
    223224
    224 /* Define this if the SCCS `get' command understands the `-G<file>' option.  */
     225/* Define this if the SCCS 'get' command understands the '-G<file>' option.  */
    225226/* #undef SCCS_GET_MINUS_G */
    226227
     
    232233/* #undef ST_MTIM_NSEC */
    233234
    234 /* Define to 1 if the C library defines the variable `sys_siglist'.  */
     235/* Define to 1 if the C library defines the variable 'sys_siglist'.  */
    235236/* #undefine HAVE_SYS_SIGLIST */
    236237
    237 /* Define to 1 if the C library defines the variable `_sys_siglist'.  */
     238/* Define to 1 if the C library defines the variable '_sys_siglist'.  */
    238239/* #undef HAVE__SYS_SIGLIST */
    239240
    240 /* Define to 1 if you have the `union wait' type in <sys/wait.h>.  */
     241/* Define to 1 if you have the 'union wait' type in <sys/wait.h>.  */
    241242/* #undef HAVE_UNION_WAIT */
    242243
     
    255256/* Define to 1 if you have the gethostname function.  */
    256257/* #undef HAVE_GETHOSTNAME */
    257 
    258 /* Define to 1 if you have the getloadavg function.  */
    259 /* #undef HAVE_GETLOADAVG */
    260258
    261259/* Define to 1 if you have the memmove function.  */
     
    333331/* #undef HAVE_NDIR_H */
    334332
    335 /* Define to 1 if your compiler conforms to the ANSI C standard. */
    336 #define HAVE_ANSI_COMPILER 1
    337 
    338 /* Define to 1 if you have the <stdarg.h> header file. */
    339 #define HAVE_STDARG_H 1
    340 
    341333/* Define to 1 if you have the <stdlib.h> header file.  */
    342334#define HAVE_STDLIB_H 1
     
    370362/* Define to 1 if you have the sun library (-lsun).  */
    371363/* #undef HAVE_LIBSUN */
     364
     365/* Define to 1 if you have the `isatty' function. */
     366/* #undef HAVE_ISATTY */
     367
     368/* Define to 1 if you have the `ttyname' function. */
     369/* #undef HAVE_TTYNAME */
    372370
    373371/* Use high resolution file timestamps if nonzero. */
     
    387385/* #undef _DIRENT_HAVE_D_NAMLEN */
    388386
    389 /* On older systems without 7.0 backport of CRTL the first one is defined */
    390 #ifdef __CRTL_VER
    391 # if __CRTL_VER < 70000000
    392 #  define HAVE_VMSDIR_H 1
    393 # endif
    394 #else
    395 # if __VMS_VER < 70000000
    396 #  define HAVE_VMSDIR_H 1
    397 # endif
     387/* On older systems without 7.0 backport of CRTL use non-VMS code for opendir() etc. */
     388#if __CRTL_VER < 70000000
     389# define HAVE_VMSDIR_H 1
    398390#endif
    399391
     
    421413/* Define if using alloca.c.  */
    422414/* #undef C_ALLOCA */
    423 /* maybe this should be placed into make.h */
    424 #if     defined(__VAX) && defined(__DECC)
    425 #define alloca(n)       __ALLOCA(n)
    426 #endif
     415/* maybe this should be placed into makeint.h */
     416#if     defined(__VAX) && defined(__DECC)
     417#define alloca(n)       __ALLOCA(n)
     418#endif
     419
     420/* Output sync sypport */
     421#define NO_OUTPUT_SYNC
     422
     423/* Define to 1 to write even short single-line actions into a VMS/DCL command
     424   file; this also enables exporting make environment variables into the
     425   (sub-)process, which executes the action.
     426   The usual make rules apply whether a shell variable - here a DCL symbol or
     427   VMS logical [see CRTL getenv()] - is added to the make environment and
     428   is exported. */
     429#define USE_DCL_COM_FILE 1
    427430
    428431/* Build host information. */
  • trunk/src/kmk/config.h.W32.template

    r2591 r3140  
    11/* config.h.W32 -- hand-massaged config.h file for Windows builds       -*-C-*-
    22
    3 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    4 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     3Copyright (C) 1996-2016 Free Software Foundation, Inc.
    54This file is part of GNU Make.
    65
     
    2928#endif
    3029
    31 /* Define to 1 if the `closedir' function returns void instead of `int'. */
     30/* Define to 1 if the 'closedir' function returns void instead of 'int'. */
    3231/* #undef CLOSEDIR_VOID */
    3332
    34 /* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
    35    systems. This function is required for `alloca.c' support on those systems.
     33/* Define to one of '_getb67', 'GETB67', 'getb67' for Cray-2 and Cray-YMP
     34   systems. This function is required for 'alloca.c' support on those systems.
    3635   */
    3736/* #undef CRAY_STACKSEG_END */
    3837
    39 /* Define to 1 if using `alloca.c'. */
     38/* Define to 1 if using 'alloca.c'. */
    4039/* #undef C_ALLOCA */
    4140
    42 /* Define to 1 if using `getloadavg.c'. */
    43 /*#define C_GETLOADAVG 1*/
     41/* Define to 1 if using 'getloadavg.c'. */
     42#define C_GETLOADAVG 1
    4443
    4544/* Define to 1 for DGUX with <sys/dg_sys_info.h>. */
     
    5352#define FILE_TIMESTAMP_HI_RES 0
    5453
    55 /* Define to 1 if the `getloadavg' function needs to be run setuid or setgid.
     54/* Define to 1 if the 'getloadavg' function needs to be run setuid or setgid.
    5655   */
    5756/* #undef GETLOADAVG_PRIVILEGED */
    5857
    59 /* Define to 1 if you have `alloca', as a function or macro. */
     58/* Define to 1 if you have 'alloca', as a function or macro. */
    6059#define HAVE_ALLOCA 1
    6160
     
    6463/* #undef HAVE_ALLOCA_H */
    6564
    66 /* Define if your compiler conforms to the ANSI C standard. */
    67 #define HAVE_ANSI_COMPILER 1
    68 
    69 /* Define to 1 if you have the `bsd_signal' function. */
    70 /* #undef HAVE_BSD_SIGNAL */
     65/* Define to 1 if you have the 'atexit' function. */
     66#define HAVE_ATEXIT 1
    7167
    7268/* Use case insensitive file names */
    7369/* #undef HAVE_CASE_INSENSITIVE_FS */
    7470
    75 /* Define if you have the clock_gettime function. */
     71/* Define to 1 if you have the clock_gettime function. */
    7672/* #undef HAVE_CLOCK_GETTIME */
    7773
     74/* Embed GNU Guile support.  Windows build sets this on the
     75   compilation command line.  */
     76/* #undef HAVE_GUILE */
     77
    7878/* Define if the GNU dcgettext() function is already present or preinstalled.
    7979   */
    8080/* #undef HAVE_DCGETTEXT */
    8181
    82 /* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
     82/* Define to 1 if you have the declaration of 'bsd_signal', and to 0 if you
     83   don't. */
     84#define HAVE_DECL_BSD_SIGNAL 0
     85
     86/* Define to 1 if you have the declaration of 'sys_siglist', and to 0 if you
     87   don't. */
     88#define HAVE_DECL_SYS_SIGLIST 0
     89
     90/* Define to 1 if you have the declaration of '_sys_siglist', and to 0 if you
     91   don't. */
     92#define HAVE_DECL__SYS_SIGLIST 0
     93
     94/* Define to 1 if you have the declaration of '__sys_siglist', and to 0 if you
     95   don't. */
     96#define HAVE_DECL___SYS_SIGLIST 0
     97
     98/* Define to 1 if you have the <dirent.h> header file, and it defines 'DIR'.
    8399   */
    84100#define HAVE_DIRENT_H 1
     
    91107#endif
    92108
    93 /* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
    94 /* #undef HAVE_DOPRNT */
    95 
    96109/* Use platform specific coding */
    97110#define HAVE_DOS_PATHS 1
    98111
    99 /* Define to 1 if you have the `dup2' function. */
     112/* Define to 1 if you have the 'dup2' function. */
    100113#define HAVE_DUP2 1
    101114
     
    103116#define HAVE_FCNTL_H 1
    104117
    105 /* Define to 1 if you have the `fdopen' function. */
    106 /*#define HAVE_FDOPEN 1*/
    107 
    108 /* Define to 1 if you have the `fork' function. */
    109 /* #undef HAVE_FORK */
    110 
    111 /* Define to 1 if you have the `getcwd' function.  */
     118/* Define to 1 if you have the 'fdopen' function. */
     119#ifdef __MINGW32__
     120#define HAVE_FDOPEN 1
     121#endif
     122
     123/* Define to 1 if you have the 'fileno' function. */
     124#define HAVE_FILENO 1
     125
     126/* Define to 1 if you have the 'getcwd' function.  */
    112127#define HAVE_GETCWD 1
    113128
    114 /* Define to 1 if you have the `getgroups' function. */
     129/* Define to 1 if you have the 'getgroups' function. */
    115130/* #undef HAVE_GETGROUPS */
    116131
    117 /* Define to 1 if you have the `gethostbyname' function. */
     132/* Define to 1 if you have the 'gethostbyname' function. */
    118133/* #undef HAVE_GETHOSTBYNAME */
    119134
    120 /* Define to 1 if you have the `gethostname' function. */
     135/* Define to 1 if you have the 'gethostname' function. */
    121136/* #undef HAVE_GETHOSTNAME */
    122137
    123 /* Define to 1 if you have the `getloadavg' function. */
     138/* Define to 1 if you have the 'getloadavg' function. */
    124139/* #undef HAVE_GETLOADAVG */
    125140
    126 /* Define to 1 if you have the `getrlimit' function. */
     141/* Define to 1 if you have the 'getrlimit' function. */
    127142/* #undef HAVE_GETRLIMIT */
    128143
     
    130145/* #undef HAVE_GETTEXT */
    131146
    132 /* Define if you have a standard gettimeofday function */
    133 /* #undef HAVE_GETTIMEOFDAY */
     147/* Define to 1 if you have a standard gettimeofday function */
     148#ifdef __MINGW32__
     149#define HAVE_GETTIMEOFDAY 1
     150#endif
    134151
    135152/* Define if you have the iconv() function. */
     
    137154
    138155/* Define to 1 if you have the <inttypes.h> header file. */
    139 /*#define HAVE_INTTYPES_H 1*/
    140 
    141 /* Define to 1 if you have the `dgc' library (-ldgc). */
     156#ifdef __MINGW32__
     157#define HAVE_INTTYPES_H 1
     158#endif
     159
     160/* Define to 1 if you have the 'dgc' library (-ldgc). */
    142161/* #undef HAVE_LIBDGC */
    143162
    144 /* Define to 1 if you have the `kstat' library (-lkstat). */
     163/* Define to 1 if you have the 'kstat' library (-lkstat). */
    145164/* #undef HAVE_LIBKSTAT */
    146165
     
    151170/*#define HAVE_LOCALE_H 1*/
    152171
     172/* Define to 1 if you have the 'lstat' function. */
     173/* #undef HAVE_LSTAT */
     174
    153175/* Define to 1 if you have the <mach/mach.h> header file. */
    154176/* #undef HAVE_MACH_MACH_H */
    155177
    156 /* Define to 1 if you have the `memmove' function. */
    157 #define HAVE_MEMMOVE 1
    158 
    159178/* Define to 1 if you have the <memory.h> header file. */
    160179#define HAVE_MEMORY_H 1
    161180
    162 /* Define to 1 if you have the `mkstemp' function. */
     181/* Define to 1 if you have the 'mkstemp' function. */
    163182/* #undef HAVE_MKSTEMP */
    164183
    165 /* Define to 1 if you have the `mktemp' function. */
     184/* Define to 1 if you have the 'mktemp' function. */
    166185#define HAVE_MKTEMP 1
    167186
    168 /* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
     187/* Define to 1 if you have the <ndir.h> header file, and it defines 'DIR'. */
    169188/* #undef HAVE_NDIR_H */
    170189
     
    172191/* #undef HAVE_NLIST_H */
    173192
    174 /* Define to 1 if you have the `pipe' function. */
     193/* Define to 1 if you have the 'pipe' function. */
    175194/* #undef HAVE_PIPE */
    176195
    177 /* Define to 1 if you have the `pstat_getdynamic' function. */
     196/* Define to 1 if you have the 'pstat_getdynamic' function. */
    178197/* #undef HAVE_PSTAT_GETDYNAMIC */
    179198
    180 /* Define to 1 if you have the `realpath' function. */
     199/* Define to 1 if you have the 'readlink' function. */
     200/* #undef HAVE_READLINK */
     201
     202/* Define to 1 if you have the 'realpath' function. */
    181203/* #undef HAVE_REALPATH */
    182204
    183 /* Define if <signal.h> defines the SA_RESTART constant. */
     205/* Define to 1 if <signal.h> defines the SA_RESTART constant. */
    184206/* #undef HAVE_SA_RESTART */
    185207
    186 /* Define to 1 if you have the `setegid' function. */
     208/* Define to 1 if you have the 'setegid' function. */
    187209/* #undef HAVE_SETEGID */
    188210
    189 /* Define to 1 if you have the `seteuid' function. */
     211/* Define to 1 if you have the 'seteuid' function. */
    190212/* #undef HAVE_SETEUID */
    191213
    192 /* Define to 1 if you have the `setlinebuf' function. */
     214/* Define to 1 if you have the 'setlinebuf' function. */
    193215/* #undef HAVE_SETLINEBUF */
    194216
    195 /* Define to 1 if you have the `setlocale' function. */
     217/* Define to 1 if you have the 'setlocale' function. */
    196218/*#define HAVE_SETLOCALE 1*/
    197219
    198 /* Define to 1 if you have the `setregid' function. */
     220/* Define to 1 if you have the 'setregid' function. */
    199221/* #undef HAVE_SETREGID */
    200222
    201 /* Define to 1 if you have the `setreuid' function. */
     223/* Define to 1 if you have the 'setreuid' function. */
    202224/* #undef HAVE_SETREUID */
    203225
    204 /* Define to 1 if you have the `setrlimit' function. */
     226/* Define to 1 if you have the 'setrlimit' function. */
    205227/* #undef HAVE_SETRLIMIT */
    206228
    207 /* Define to 1 if you have the `setvbuf' function. */
    208 /*#define HAVE_SETVBUF 1 */
    209 
    210 /* Define to 1 if you have the `sigaction' function. */
     229/* Define to 1 if you have the 'setvbuf' function. */
     230#define HAVE_SETVBUF 1
     231
     232/* Define to 1 if you have the 'sigaction' function. */
    211233/* #undef HAVE_SIGACTION */
    212234
    213 /* Define to 1 if you have the `sigsetmask' function. */
     235/* Define to 1 if you have the 'sigsetmask' function. */
    214236/* #undef HAVE_SIGSETMASK */
    215237
    216 /* Define to 1 if you have the `socket' function. */
     238/* Define to 1 if you have the 'socket' function. */
    217239/* #undef HAVE_SOCKET */
    218240
    219 /* Define to 1 if you have the <stdarg.h> header file. */
    220 #define HAVE_STDARG_H 1
    221 
    222241/* Define to 1 if you have the <stdint.h> header file. */
    223 /*#define HAVE_STDINT_H 1*/
     242#ifdef __MINGW32__
     243#define HAVE_STDINT_H 1
     244#endif
    224245
    225246/* Define to 1 if you have the <stdlib.h> header file. */
    226247#define HAVE_STDLIB_H 1
    227248
    228 /* Define to 1 if you have the `strcasecmp' function. */
    229 /* #undef HAVE_STRCASECMP */
    230 
    231 /* Define to 1 if you have the `strcmpi' function. */
    232 /* #undef HAVE_STRCMPI */
    233 
    234 /* Define to 1 if you have the `stricmp' function. */
     249/* Define to 1 if you have the 'strcasecmp' function. */
     250#ifdef __MINGW32__
     251#define HAVE_STRCASECMP 1
     252#endif
     253
     254/* Define to 1 if you have the 'strcmpi' function. */
     255#define HAVE_STRCMPI 1
     256
     257/* Define to 1 if you have the 'strcoll' function and it is properly defined.
     258   */
     259#define HAVE_STRCOLL 1
     260
     261/* Define to 1 if you have the 'strdup' function. */
     262#define HAVE_STRDUP 1
     263
     264/* Define to 1 if you have the 'strerror' function. */
     265#define HAVE_STRERROR 1
     266
     267/* Define to 1 if you have the 'stricmp' function. */
    235268#define HAVE_STRICMP 1
    236 
    237 /* Define to 1 if you have the `strncasecmp' function. */
    238 /* #undef HAVE_STRNCASECMP */
    239 
    240 /* Define to 1 if you have the `strncmpi' function. */
    241 /* #undef HAVE_STRNCMPI */
    242 
    243 /* Define to 1 if you have the `strnicmp' function. */
    244 #define HAVE_STRNICMP 1
    245 
    246 /* Define to 1 if you have the `strchr' function. */
    247 #define HAVE_STRCHR 1
    248 
    249 /* Define to 1 if you have the `strcoll' function and it is properly defined.
    250    */
    251 #define HAVE_STRCOLL 1
    252 
    253 /* Define to 1 if you have the `strdup' function. */
    254 #define HAVE_STRDUP 1 /* bird */
    255 
    256 /* Define to 1 if you have the `strerror' function. */
    257 #define HAVE_STRERROR 1
    258269
    259270/* Define to 1 if you have the <strings.h> header file. */
     
    263274#define HAVE_STRING_H 1
    264275
    265 /* Define to 1 if you have the `strsignal' function. */
     276/* Define to 1 if you have the 'strncasecmp' function. */
     277#ifdef __MINGW32__
     278#define HAVE_STRNCASECMP 1
     279#endif
     280
     281/* Define to 1 if you have the 'strncmpi' function. */
     282/* #undef HAVE_STRNCMPI */
     283
     284/* Define to 1 if you have the 'strndup' function. */
     285/* #undef HAVE_STRNDUP */
     286
     287/* Define to 1 if you have the 'strnicmp' function. */
     288#ifdef __MINGW32__
     289#define HAVE_STRNICMP 1
     290#endif
     291
     292/* Define to 1 if you have the 'strsignal' function. */
    266293/* #undef HAVE_STRSIGNAL */
    267294
    268 /* Define to 1 if `n_un.n_name' is member of `struct nlist'. */
     295/* Define to 1 if you have the `isatty' function. */
     296#define HAVE_ISATTY 1
     297
     298/* Define to 1 if you have the `ttyname' function. */
     299#define HAVE_TTYNAME 1
     300char *ttyname (int);
     301
     302/* Define to 1 if 'n_un.n_name' is a member of 'struct nlist'. */
    269303/* #undef HAVE_STRUCT_NLIST_N_UN_N_NAME */
    270304
    271 /* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
     305/* Define to 1 if you have the <sys/dir.h> header file, and it defines 'DIR'.
    272306   */
    273307/* #undef HAVE_SYS_DIR_H */
    274308
    275 /* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
     309/* Define to 1 if you have the <sys/ndir.h> header file, and it defines 'DIR'.
    276310   */
    277311/* #undef HAVE_SYS_NDIR_H */
    278312
    279313/* Define to 1 if you have the <sys/param.h> header file. */
    280 /* #define HAVE_SYS_PARAM_H 1 */
     314#ifdef __MINGW32__
     315#define HAVE_SYS_PARAM_H 1
     316#endif
    281317
    282318/* Define to 1 if you have the <sys/resource.h> header file. */
     
    284320
    285321/* Define to 1 if you have the <sys/stat.h> header file. */
    286 /* #define HAVE_SYS_STAT_H 1 */
     322#define HAVE_SYS_STAT_H 1
    287323
    288324/* Define to 1 if you have the <sys/timeb.h> header file. */
    289 /*#define HAVE_SYS_TIMEB_H 1*/
     325#define HAVE_SYS_TIMEB_H 1
    290326
    291327/* Define to 1 if you have the <sys/time.h> header file. */
    292 /*#define HAVE_SYS_TIME_H 1*/
     328#ifdef __MINGW32__
     329#define HAVE_SYS_TIME_H 1
     330#endif
    293331
    294332/* Define to 1 if you have the <sys/types.h> header file. */
    295 /*#define HAVE_SYS_TYPES_H 1*/
     333#define HAVE_SYS_TYPES_H 1
    296334
    297335/* Define to 1 if you have the <sys/wait.h> header file. */
    298336/* #undef HAVE_SYS_WAIT_H */
    299337
    300 /* Define this if you have the \`union wait' type in <sys/wait.h>. */
     338/* Define to 1 if you have the \'union wait' type in <sys/wait.h>. */
    301339/* #undef HAVE_UNION_WAIT */
    302340
    303341/* Define to 1 if you have the <unistd.h> header file. */
    304 /* #define HAVE_UNISTD_H 1*/
    305 
    306 /* Define to 1 if you have the <varargs.h> header file. */
    307 /* #undef HAVE_VARARGS_H */
    308 
    309 /* Define to 1 if you have the `vfork' function. */
    310 /* #undef HAVE_VFORK */
    311 
    312 /* Define to 1 if you have the <vfork.h> header file. */
    313 /* #undef HAVE_VFORK_H */
    314 
    315 /* Define to 1 if you have the `vprintf' function. */
    316 #define HAVE_VPRINTF 1
    317 
    318 
    319 /* Define to 1 if you have the `wait3' function. */
     342#ifdef __MINGW32__
     343#define HAVE_UNISTD_H 1
     344#endif
     345
     346/* Define to 1 if you have the 'wait3' function. */
    320347/* #undef HAVE_WAIT3 */
    321348
    322 /* Define to 1 if you have the `waitpid' function. */
     349/* Define to 1 if you have the 'waitpid' function. */
    323350/* #undef HAVE_WAITPID */
    324 
    325 /* Define to 1 if `fork' works. */
    326 /* #undef HAVE_WORKING_FORK */
    327 
    328 /* Define to 1 if `vfork' works. */
    329 /* #undef HAVE_WORKING_VFORK */
    330351
    331352/* Build host information. (not used by kmk) */
    332353#define MAKE_HOST "Windows32"
    333354
    334 /* Define this to enable job server support in GNU make. */
    335 /* #undef MAKE_JOBSERVER */
    336 
    337 /* Define to 1 if your `struct nlist' has an `n_un' member. Obsolete, depend
    338    on `HAVE_STRUCT_NLIST_N_UN_N_NAME */
     355/* Define to 1 to enable job server support in GNU make. */
     356#define MAKE_JOBSERVER 1
     357
     358/* Define to 1 to enable 'load' support in GNU make. */
     359#define MAKE_LOAD 1
     360
     361/* Define to 1 to enable symbolic link timestamp checking. */
     362/* #undef MAKE_SYMLINKS */
     363
     364/* Define to 1 if your 'struct nlist' has an 'n_un' member. Obsolete, depend
     365   on 'HAVE_STRUCT_NLIST_N_UN_N_NAME */
    339366/* #undef NLIST_NAME_UNION */
    340367
    341 /* Define if struct nlist.n_name is a pointer rather than an array. */
     368/* Define to 1 if struct nlist.n_name is a pointer rather than an array. */
    342369/* #undef NLIST_STRUCT */
    343370
     
    348375#define PACKAGE "%PACKAGE%"
    349376
    350 /* Define to 1 if the C compiler supports function prototypes. */
    351 #define PROTOTYPES 1
    352 
    353 /* Define as the return type of signal handlers (`int' or `void'). */
     377/* Define to the address where bug reports for this package should be sent. */
     378#define PACKAGE_BUGREPORT "[email protected]"
     379
     380/* Define to the full name of this package. */
     381#define PACKAGE_NAME "GNU make"
     382
     383/* Define to the home page for this package. */
     384#define PACKAGE_URL "http://www.gnu.org/software/make/"
     385
     386/* Define to the version of this package. */
     387#define PACKAGE_VERSION "%VERSION%"
     388
     389/* Define to the character that separates directories in PATH. */
     390#define PATH_SEPARATOR_CHAR ';'
     391
     392/* Define as the return type of signal handlers ('int' or 'void'). */
    354393#define RETSIGTYPE void
    355394
     
    360399/* #undef SCCS_GET_MINUS_G */
    361400
    362 /* Define to 1 if the `setvbuf' function takes the buffering type as its
     401/* Define to 1 if the 'setvbuf' function takes the buffering type as its
    363402   second argument and the buffer pointer as the third, as on System V before
    364403   release 3. */
     
    367406/* If using the C implementation of alloca, define if you know the
    368407   direction of stack growth for your system; otherwise it will be
    369    automatically deduced at run-time.
    370         STACK_DIRECTION > 0 => grows toward higher addresses
    371         STACK_DIRECTION < 0 => grows toward lower addresses
    372         STACK_DIRECTION = 0 => direction of growth unknown */
     408   automatically deduced at run time.
     409        STACK_DIRECTION > 0 => grows toward higher addresses
     410        STACK_DIRECTION < 0 => grows toward lower addresses
     411        STACK_DIRECTION = 0 => direction of growth unknown */
    373412/* #undef STACK_DIRECTION */
    374413
    375 /* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
     414/* Define to 1 if the 'S_IS*' macros in <sys/stat.h> do not work properly. */
    376415/* #undef STAT_MACROS_BROKEN */
    377416
     
    386425
    387426/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
    388 /* #define TIME_WITH_SYS_TIME 1 */
     427#ifdef __MINGW32__
     428#define TIME_WITH_SYS_TIME 1
     429#endif
    389430
    390431/* Define to 1 for Encore UMAX. */
     
    421462/* #undef _POSIX_1_SOURCE */
    422463
    423 /* Define to 1 if you need to in order for `stat' and other things to work. */
    424 #define _POSIX_SOURCE 1
    425 
    426 /* Define like PROTOTYPES; this can be used by system headers. */
    427 /*#define __PROTOTYPES 1*/
    428 
    429 /* Define to empty if `const' does not conform to ANSI C. */
     464/* Define to 1 if you need to in order for 'stat' and other things to work. */
     465/* #undef _POSIX_SOURCE */
     466
     467/* Define to empty if 'const' does not conform to ANSI C. */
    430468/* #undef const */
    431469
    432470#include <sys/types.h>
    433471
    434 /* Define to `int' if <sys/types.h> doesn't define. */
     472/* Define to 'int' if <sys/types.h> doesn't define. */
    435473#define gid_t int
    436474
    437 /* Define to `int' if <sys/types.h> does not define. */
     475/* Define to 'int' if <sys/types.h> does not define. */
    438476/* GCC 4.x reportedly defines pid_t.  */
    439477#ifndef _PID_T_
     
    445483#endif
    446484
    447 /* Define to `int' if <sys/types.h> doesn't define. */
     485/* Define to 'int' if <sys/types.h> doesn't define. */
    448486#define uid_t int
    449487
    450488/* Define uintmax_t if not defined in <stdint.h> or <inttypes.h>. */
     489#if !HAVE_STDINT_H && !HAVE_INTTYPES_H
    451490#define uintmax_t unsigned long
    452 
    453 /* Define as `fork' if `vfork' does not work. */
    454 /*#define vfork fork*/
    455 
    456 /* Define to `unsigned long' or `unsigned long long'
    457    if <inttypes.h> doesn't define.  */
    458 #define uintmax_t unsigned long
    459 
    460 /* Define if you support file names longer than 14 characters.  */
    461 #define HAVE_LONG_FILE_NAMES 1
    462 
    463 /* Define if your struct stat has st_rdev.  */
    464 #undef HAVE_ST_RDEV
    465 #define HAVE_ST_RDEV 1
    466 
    467 /* Define if you have the strftime function.  */
    468 #undef HAVE_STRFTIME
    469 #define HAVE_STRFTIME 1
     491#endif
    470492
    471493/* Define if you have <sys/wait.h> that is POSIX.1 compatible.  */
    472494/* #undef HAVE_SYS_WAIT_H */
    473 
    474 /* Define if your struct tm has tm_zone.  */
    475 /* #undef HAVE_TM_ZONE */
    476 
    477 /* Define if you don't have tm_zone but do have the external array
    478    tzname.  */
    479 #undef HAVE_TZNAME
    480 #define HAVE_TZNAME 1
    481 
    482 /* Define if utime(file, NULL) sets file's timestamp to the present.  */
    483 #undef HAVE_UTIME_NULL
    484 #define HAVE_UTIME_NULL 1
    485495
    486496/* Define to the installation directory for locales.  */
  • trunk/src/kmk/config.h.linux

    r2671 r3140  
    377377
    378378/* Define if struct stat contains a nanoseconds field */
    379 #define ST_MTIM_NSEC tv_nsec
     379#ifdef __USE_XOPEN2K8
     380# define ST_MTIM_NSEC st_mtim.tv_nsec
     381#else
     382# define ST_MTIM_NSEC st_mtimensec
     383#endif
    380384
    381385/* Define to 1 on System V Release 4. */
  • trunk/src/kmk/config.h.win

    r2843 r3140  
    11/* config.h.W32 -- hand-massaged config.h file for Windows builds       -*-C-*-
    22
    3 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    4 2006 Free Software Foundation, Inc.
     3Copyright (C) 1996-2016 Free Software Foundation, Inc.
    54This file is part of GNU Make.
    65
    76GNU Make is free software; you can redistribute it and/or modify it under the
    87terms of the GNU General Public License as published by the Free Software
    9 Foundation; either version 2, or (at your option) any later version.
     8Foundation; either version 3 of the License, or (at your option) any later
     9version.
    1010
    1111GNU Make is distributed in the hope that it will be useful, but WITHOUT ANY
     
    1414
    1515You should have received a copy of the GNU General Public License along with
    16 GNU Make; see the file COPYING.  If not, write to the Free Software
    17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.  */
     16this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1817
    1918#ifndef ___config_h_win
     
    2827# pragma warning(disable:4131) /* uses old-style declarator */
    2928# pragma warning(disable:4702) /* unreachable code */
    30 #endif
    31 
    32 /* Define to 1 if the `closedir' function returns void instead of `int'. */
     29# ifndef _CRT_SECURE_NO_WARNINGS
     30#  define _CRT_SECURE_NO_WARNINGS  /* function or variable may be unsafe */
     31# endif
     32# ifndef _CRT_NONSTDC_NO_WARNINGS
     33#  define _CRT_NONSTDC_NO_WARNINGS /* functions w/o a leading underscore */
     34# endif
     35#endif
     36
     37/* Define to 1 if the 'closedir' function returns void instead of 'int'. */
    3338/* #undef CLOSEDIR_VOID */
    3439
    35 /* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
    36    systems. This function is required for `alloca.c' support on those systems.
     40/* Define to one of '_getb67', 'GETB67', 'getb67' for Cray-2 and Cray-YMP
     41   systems. This function is required for 'alloca.c' support on those systems.
    3742   */
    3843/* #undef CRAY_STACKSEG_END */
    3944
    40 /* Define to 1 if using `alloca.c'. */
     45/* Define to 1 if using 'alloca.c'. */
    4146/* #undef C_ALLOCA */
    4247
    43 /* Define to 1 if using `getloadavg.c'. */
    44 /*#define C_GETLOADAVG 1*/
     48/* Define to 1 if using 'getloadavg.c'. */
     49#define C_GETLOADAVG 1
    4550
    4651/* Define to 1 for DGUX with <sys/dg_sys_info.h>. */
     
    5459#define FILE_TIMESTAMP_HI_RES 0
    5560
    56 /* Define to 1 if the `getloadavg' function needs to be run setuid or setgid.
     61/* Define to 1 if the 'getloadavg' function needs to be run setuid or setgid.
    5762   */
    5863/* #undef GETLOADAVG_PRIVILEGED */
    5964
    60 /* Define to 1 if you have `alloca', as a function or macro. */
     65/* Define to 1 if you have 'alloca', as a function or macro. */
    6166#define HAVE_ALLOCA 1
    6267
     
    6469   */
    6570/* #undef HAVE_ALLOCA_H */
     71
     72/* Define to 1 if you have the 'atexit' function. */
     73#define HAVE_ATEXIT 1
    6674
    6775/* Define if your compiler conforms to the ANSI C standard. */
    6876#define HAVE_ANSI_COMPILER 1
    6977
    70 /* Define to 1 if you have the `bsd_signal' function. */
    71 /* #undef HAVE_BSD_SIGNAL */
    72 
    7378/* Use case insensitive file names */
    7479/* #undef HAVE_CASE_INSENSITIVE_FS */
    7580
    76 /* Define if you have the clock_gettime function. */
     81/* Define to 1 if you have the clock_gettime function. */
    7782/* #undef HAVE_CLOCK_GETTIME */
    7883
     84/* Embed GNU Guile support.  Windows build sets this on the
     85   compilation command line.  */
     86/* #undef HAVE_GUILE */
     87
    7988/* Define if the GNU dcgettext() function is already present or preinstalled.
    8089   */
    8190/* #undef HAVE_DCGETTEXT */
    8291
    83 /* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
     92/* Define to 1 if you have the declaration of 'bsd_signal', and to 0 if you
     93   don't. */
     94#define HAVE_DECL_BSD_SIGNAL 0
     95
     96/* Define to 1 if you have the declaration of 'sys_siglist', and to 0 if you
     97   don't. */
     98#define HAVE_DECL_SYS_SIGLIST 0
     99
     100/* Define to 1 if you have the declaration of '_sys_siglist', and to 0 if you
     101   don't. */
     102#define HAVE_DECL__SYS_SIGLIST 0
     103
     104/* Define to 1 if you have the declaration of '__sys_siglist', and to 0 if you
     105   don't. */
     106#define HAVE_DECL___SYS_SIGLIST 0
     107
     108/* Define to 1 if you have the <dirent.h> header file, and it defines 'DIR'.
    84109   */
    85110#define HAVE_DIRENT_H 1
     
    92117#endif
    93118
    94 /* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
    95 /* #undef HAVE_DOPRNT */
    96 
    97119/* Use platform specific coding */
    98120#define HAVE_DOS_PATHS 1
    99121
    100 /* Define to 1 if you have the `dup2' function. */
     122/* Define to 1 if you have the 'dup2' function. */
    101123#define HAVE_DUP2 1
    102124
     
    104126#define HAVE_FCNTL_H 1
    105127
    106 /* Define to 1 if you have the `fdopen' function. */
    107 /*#define HAVE_FDOPEN 1*/
    108 
    109 /* Define to 1 if you have the `fork' function. */
    110 /* #undef HAVE_FORK */
    111 
    112 /* Define to 1 if you have the `getcwd' function.  */
     128/* Define to 1 if you have the 'fdopen' function. */
     129#ifdef __MINGW32__
     130#define HAVE_FDOPEN 1
     131#endif
     132
     133/* Define to 1 if you have the 'fileno' function. */
     134#define HAVE_FILENO 1
     135
     136/* Define to 1 if you have the 'getcwd' function.  */
    113137#define HAVE_GETCWD 1
    114138
    115 /* Define to 1 if you have the `getgroups' function. */
     139/* Define to 1 if you have the 'getgroups' function. */
    116140/* #undef HAVE_GETGROUPS */
    117141
    118 /* Define to 1 if you have the `gethostbyname' function. */
     142/* Define to 1 if you have the 'gethostbyname' function. */
    119143/* #undef HAVE_GETHOSTBYNAME */
    120144
    121 /* Define to 1 if you have the `gethostname' function. */
     145/* Define to 1 if you have the 'gethostname' function. */
    122146/* #undef HAVE_GETHOSTNAME */
    123147
    124 /* Define to 1 if you have the `getloadavg' function. */
     148/* Define to 1 if you have the 'getloadavg' function. */
    125149/* #undef HAVE_GETLOADAVG */
    126150
    127 /* Define to 1 if you have the `getrlimit' function. */
     151/* Define to 1 if you have the 'getrlimit' function. */
    128152/* #undef HAVE_GETRLIMIT */
    129153
     
    131155/* #undef HAVE_GETTEXT */
    132156
    133 /* Define if you have a standard gettimeofday function */
    134 /* #undef HAVE_GETTIMEOFDAY */
     157/* Define to 1 if you have a standard gettimeofday function */
     158#ifdef __MINGW32__
     159#define HAVE_GETTIMEOFDAY 1
     160#endif
    135161
    136162/* Define if you have the iconv() function. */
     
    138164
    139165/* Define to 1 if you have the <inttypes.h> header file. */
    140 /*#define HAVE_INTTYPES_H 1*/
    141 
    142 /* Define to 1 if you have the `dgc' library (-ldgc). */
     166#ifdef __MINGW32__
     167#define HAVE_INTTYPES_H 1
     168#endif
     169
     170/* Define to 1 if you have the 'dgc' library (-ldgc). */
    143171/* #undef HAVE_LIBDGC */
    144172
    145 /* Define to 1 if you have the `kstat' library (-lkstat). */
     173/* Define to 1 if you have the 'kstat' library (-lkstat). */
    146174/* #undef HAVE_LIBKSTAT */
    147175
     
    150178
    151179/* Define to 1 if you have the <locale.h> header file. */
    152 #define HAVE_LOCALE_H 1
     180#define HAVE_LOCALE_H 1 /* bird: differs */
     181
     182/* Define to 1 if you have the 'lstat' function. */
     183/* #undef HAVE_LSTAT */
    153184
    154185/* Define to 1 if you have the <mach/mach.h> header file. */
    155186/* #undef HAVE_MACH_MACH_H */
    156187
    157 /* Define to 1 if you have the `memmove' function. */
    158 #define HAVE_MEMMOVE 1
    159 
    160188/* Define to 1 if you have the <memory.h> header file. */
    161189#define HAVE_MEMORY_H 1
    162190
    163 /* Define to 1 if you have the `mkstemp' function. */
     191/* Define to 1 if you have the 'mkstemp' function. */
    164192/* #undef HAVE_MKSTEMP */
    165193
    166 /* Define to 1 if you have the `mktemp' function. */
     194/* Define to 1 if you have the 'mktemp' function. */
    167195#define HAVE_MKTEMP 1
    168196
    169 /* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
     197/* Define to 1 if you have the <ndir.h> header file, and it defines 'DIR'. */
    170198/* #undef HAVE_NDIR_H */
    171199
     
    173201/* #undef HAVE_NLIST_H */
    174202
    175 /* Define to 1 if you have the `pipe' function. */
     203/* Define to 1 if you have the 'pipe' function. */
    176204/* #undef HAVE_PIPE */
    177205
    178 /* Define to 1 if you have the `pstat_getdynamic' function. */
     206/* Define to 1 if you have the 'pstat_getdynamic' function. */
    179207/* #undef HAVE_PSTAT_GETDYNAMIC */
    180208
    181 /* Define to 1 if you have the `realpath' function. */
     209/* Define to 1 if you have the 'readlink' function. */
     210/* #undef HAVE_READLINK */
     211
     212/* Define to 1 if you have the 'realpath' function. */
    182213/* #undef HAVE_REALPATH */
    183214
    184 /* Define if <signal.h> defines the SA_RESTART constant. */
     215/* Define to 1 if <signal.h> defines the SA_RESTART constant. */
    185216/* #undef HAVE_SA_RESTART */
    186217
    187 /* Define to 1 if you have the `setegid' function. */
     218/* Define to 1 if you have the 'setegid' function. */
    188219/* #undef HAVE_SETEGID */
    189220
    190 /* Define to 1 if you have the `seteuid' function. */
     221/* Define to 1 if you have the 'seteuid' function. */
    191222/* #undef HAVE_SETEUID */
    192223
    193 /* Define to 1 if you have the `setlinebuf' function. */
     224/* Define to 1 if you have the 'setlinebuf' function. */
    194225/* #undef HAVE_SETLINEBUF */
    195226
    196 /* Define to 1 if you have the `setlocale' function. */
     227/* Define to 1 if you have the 'setlocale' function. */
    197228/*#define HAVE_SETLOCALE 1*/
    198229
    199 /* Define to 1 if you have the `setregid' function. */
     230/* Define to 1 if you have the 'setregid' function. */
    200231/* #undef HAVE_SETREGID */
    201232
    202 /* Define to 1 if you have the `setreuid' function. */
     233/* Define to 1 if you have the 'setreuid' function. */
    203234/* #undef HAVE_SETREUID */
    204235
    205 /* Define to 1 if you have the `setrlimit' function. */
     236/* Define to 1 if you have the 'setrlimit' function. */
    206237/* #undef HAVE_SETRLIMIT */
    207238
    208 /* Define to 1 if you have the `setvbuf' function. */
    209 /*#define HAVE_SETVBUF 1 */
    210 
    211 /* Define to 1 if you have the `sigaction' function. */
     239/* Define to 1 if you have the 'setvbuf' function. */
     240#define HAVE_SETVBUF 1
     241
     242/* Define to 1 if you have the 'sigaction' function. */
    212243/* #undef HAVE_SIGACTION */
    213244
    214 /* Define to 1 if you have the `sigsetmask' function. */
     245/* Define to 1 if you have the 'sigsetmask' function. */
    215246/* #undef HAVE_SIGSETMASK */
    216247
    217 /* Define to 1 if you have the `socket' function. */
     248/* Define to 1 if you have the 'socket' function. */
    218249/* #undef HAVE_SOCKET */
    219250
    220 /* Define to 1 if you have the <stdarg.h> header file. */
    221 #define HAVE_STDARG_H 1
    222 
    223251/* Define to 1 if you have the <stdint.h> header file. */
    224 #if _MSC_VER >= 1600
     252#if defined(__MINGW32__) || _MSC_VER >= 1600 /* bird: added latter */
    225253# define HAVE_STDINT_H 1
    226254#endif
     
    229257#define HAVE_STDLIB_H 1
    230258
    231 /* Define to 1 if you have the `strcasecmp' function. */
    232 /* #undef HAVE_STRCASECMP */
    233 
    234 /* Define to 1 if you have the `strcmpi' function. */
     259/* Define to 1 if you have the 'strcasecmp' function. */
     260#ifdef __MINGW32__
     261#define HAVE_STRCASECMP 1
     262#endif
     263
     264/* Define to 1 if you have the 'strcmpi' function. */
    235265#define HAVE_STRCMPI 1
    236266
    237 /* Define to 1 if you have the `stricmp' function. */
    238 /* #undef HAVE_STRICMP */
    239 
    240 /* Define to 1 if you have the `strchr' function. */
    241 #define HAVE_STRCHR 1
    242 
    243 /* Define to 1 if you have the `strcoll' function and it is properly defined.
     267/* Define to 1 if you have the 'strcoll' function and it is properly defined.
    244268   */
    245269#define HAVE_STRCOLL 1
    246270
    247 /* Define to 1 if you have the `strdup' function. */
    248 #define HAVE_STRDUP 1 /* bird */
    249 
    250 /* Define to 1 if you have the `strerror' function. */
     271/* Define to 1 if you have the 'strdup' function. */
     272#define HAVE_STRDUP 1
     273
     274/* Define to 1 if you have the 'strerror' function. */
    251275#define HAVE_STRERROR 1
     276
     277/* Define to 1 if you have the 'stricmp' function. */
     278#define HAVE_STRICMP 1
    252279
    253280/* Define to 1 if you have the <strings.h> header file. */
     
    257284#define HAVE_STRING_H 1
    258285
    259 /* Define to 1 if you have the `strsignal' function. */
     286/* Define to 1 if you have the 'strncasecmp' function. */
     287#ifdef __MINGW32__
     288#define HAVE_STRNCASECMP 1
     289#endif
     290
     291/* Define to 1 if you have the 'strncmpi' function. */
     292/* #undef HAVE_STRNCMPI */
     293
     294/* Define to 1 if you have the 'strndup' function. */
     295/* #undef HAVE_STRNDUP */
     296
     297/* Define to 1 if you have the 'strnicmp' function. */
     298/*#ifdef __MINGW32__ - bird */
     299#define HAVE_STRNICMP 1
     300/* #endif - bird */
     301
     302/* Define to 1 if you have the 'strsignal' function. */
    260303/* #undef HAVE_STRSIGNAL */
    261304
    262 /* Define to 1 if `n_un.n_name' is member of `struct nlist'. */
     305/* Define to 1 if you have the `isatty' function. */
     306#define HAVE_ISATTY 1
     307
     308/* Define to 1 if you have the `ttyname' function. */
     309#define HAVE_TTYNAME 1
     310char *ttyname (int);
     311
     312/* Define to 1 if 'n_un.n_name' is a member of 'struct nlist'. */
    263313/* #undef HAVE_STRUCT_NLIST_N_UN_N_NAME */
    264314
    265 /* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
     315/* Define to 1 if you have the <sys/dir.h> header file, and it defines 'DIR'.
    266316   */
    267317/* #undef HAVE_SYS_DIR_H */
    268318
    269 /* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
     319/* Define to 1 if you have the <sys/ndir.h> header file, and it defines 'DIR'.
    270320   */
    271321/* #undef HAVE_SYS_NDIR_H */
    272322
    273323/* Define to 1 if you have the <sys/param.h> header file. */
    274 /* #define HAVE_SYS_PARAM_H 1 */
     324#ifdef __MINGW32__
     325#define HAVE_SYS_PARAM_H 1
     326#endif
    275327
    276328/* Define to 1 if you have the <sys/resource.h> header file. */
     
    281333
    282334/* Define to 1 if you have the <sys/timeb.h> header file. */
    283 /*#define HAVE_SYS_TIMEB_H 1*/
     335#define HAVE_SYS_TIMEB_H 1
    284336
    285337/* Define to 1 if you have the <sys/time.h> header file. */
    286 /*#define HAVE_SYS_TIME_H 1*/
     338#ifdef __MINGW32__
     339#define HAVE_SYS_TIME_H 1
     340#endif
    287341
    288342/* Define to 1 if you have the <sys/types.h> header file. */
    289 /*#define HAVE_SYS_TYPES_H 1*/
     343#define HAVE_SYS_TYPES_H 1
    290344
    291345/* Define to 1 if you have the <sys/wait.h> header file. */
    292346/* #undef HAVE_SYS_WAIT_H */
    293347
    294 /* Define this if you have the \`union wait' type in <sys/wait.h>. */
     348/* Define to 1 if you have the \'union wait' type in <sys/wait.h>. */
    295349/* #undef HAVE_UNION_WAIT */
    296350
    297351/* Define to 1 if you have the <unistd.h> header file. */
    298 /* #define HAVE_UNISTD_H 1*/
    299 
    300 /* Define to 1 if you have the <varargs.h> header file. */
    301 /* #undef HAVE_VARARGS_H */
    302 
    303 /* Define to 1 if you have the `vfork' function. */
    304 /* #undef HAVE_VFORK */
    305 
    306 /* Define to 1 if you have the <vfork.h> header file. */
    307 /* #undef HAVE_VFORK_H */
    308 
    309 /* Define to 1 if you have the `vprintf' function. */
    310 #define HAVE_VPRINTF 1
    311 
    312 
    313 /* Define to 1 if you have the `wait3' function. */
     352#ifdef __MINGW32__
     353#define HAVE_UNISTD_H 1
     354#endif
     355
     356/* Define to 1 if you have the 'wait3' function. */
    314357/* #undef HAVE_WAIT3 */
    315358
    316 /* Define to 1 if you have the `waitpid' function. */
     359/* Define to 1 if you have the 'waitpid' function. */
    317360/* #undef HAVE_WAITPID */
    318 
    319 /* Define to 1 if `fork' works. */
    320 /* #undef HAVE_WORKING_FORK */
    321 
    322 /* Define to 1 if `vfork' works. */
    323 /* #undef HAVE_WORKING_VFORK */
    324361
    325362/* Build host information. (not used by kmk) */
    326363#define MAKE_HOST "Windows32"
    327364
    328 /* Define this to enable job server support in GNU make. */
    329 /* #undef MAKE_JOBSERVER */
    330 
    331 /* Define to 1 if your `struct nlist' has an `n_un' member. Obsolete, depend
    332    on `HAVE_STRUCT_NLIST_N_UN_N_NAME */
     365/* Define to 1 to enable job server support in GNU make. */
     366#define MAKE_JOBSERVER 1
     367
     368/* Define to 1 to enable 'load' support in GNU make. */
     369#define MAKE_LOAD 1
     370
     371/* Define to 1 to enable symbolic link timestamp checking. */
     372/* #undef MAKE_SYMLINKS */
     373
     374/* Define to 1 if your 'struct nlist' has an 'n_un' member. Obsolete, depend
     375   on 'HAVE_STRUCT_NLIST_N_UN_N_NAME */
    333376/* #undef NLIST_NAME_UNION */
    334377
    335 /* Define if struct nlist.n_name is a pointer rather than an array. */
     378/* Define to 1 if struct nlist.n_name is a pointer rather than an array. */
    336379/* #undef NLIST_STRUCT */
    337380
     
    346389
    347390/* Define to the full name of this package. */
    348 #define PACKAGE_NAME "GNU make"
    349 
    350 /* Define to the full name and version of this package. */
    351 #define PACKAGE_STRING "GNU make 3.82"
    352 
    353 /* Define to the one symbol short name of this package. */
    354 #define PACKAGE_TARNAME "make"
     391#define PACKAGE_NAME "kmk"
     392
     393/* Define to the home page for this package. */
     394#define PACKAGE_URL "http://kbuild.org/"
    355395
    356396/* Define to the version of this package. */
    357 #define PACKAGE_VERSION "3.82"
    358 
    359 /* Define to 1 if the C compiler supports function prototypes. */
    360 #define PROTOTYPES 1
    361 
    362 /* Define as the return type of signal handlers (`int' or `void'). */
     397#define PACKAGE_VERSION "4.2.1"
     398
     399/* Define to the character that separates directories in PATH. */
     400#define PATH_SEPARATOR_CHAR ';'
     401
     402/* Define as the return type of signal handlers ('int' or 'void'). */
    363403#define RETSIGTYPE void
    364404
     
    369409/* #undef SCCS_GET_MINUS_G */
    370410
    371 /* Define to 1 if the `setvbuf' function takes the buffering type as its
     411/* Define to 1 if the 'setvbuf' function takes the buffering type as its
    372412   second argument and the buffer pointer as the third, as on System V before
    373413   release 3. */
     
    376416/* If using the C implementation of alloca, define if you know the
    377417   direction of stack growth for your system; otherwise it will be
    378    automatically deduced at run-time.
    379         STACK_DIRECTION > 0 => grows toward higher addresses
    380         STACK_DIRECTION < 0 => grows toward lower addresses
    381         STACK_DIRECTION = 0 => direction of growth unknown */
     418   automatically deduced at run time.
     419        STACK_DIRECTION > 0 => grows toward higher addresses
     420        STACK_DIRECTION < 0 => grows toward lower addresses
     421        STACK_DIRECTION = 0 => direction of growth unknown */
    382422/* #undef STACK_DIRECTION */
    383423
    384 /* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
     424/* Define to 1 if the 'S_IS*' macros in <sys/stat.h> do not work properly. */
    385425/* #undef STAT_MACROS_BROKEN */
    386426
     
    389429
    390430/* Define if struct stat contains a nanoseconds field */
    391 #define ST_MTIM_NSEC tv_nsec
     431#define ST_MTIM_NSEC tv_nsec /* bird */
    392432
    393433/* Define to 1 on System V Release 4. */
     
    395435
    396436/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
    397 /* #define TIME_WITH_SYS_TIME 1 */
     437#ifdef __MINGW32__
     438#define TIME_WITH_SYS_TIME 1
     439#endif
    398440
    399441/* Define to 1 for Encore UMAX. */
     
    405447
    406448/* Version number of package */
    407 #define VERSION "3.82"
     449#define VERSION "4.2.1"
    408450
    409451/* Define if using the dmalloc debugging malloc package */
     
    430472/* #undef _POSIX_1_SOURCE */
    431473
    432 /* Define to 1 if you need to in order for `stat' and other things to work. */
    433 #define _POSIX_SOURCE 1
    434 
    435 /* Define like PROTOTYPES; this can be used by system headers. */
    436 /*#define __PROTOTYPES 1*/
    437 
    438 /* Define to empty if `const' does not conform to ANSI C. */
     474/* Define to 1 if you need to in order for 'stat' and other things to work. */
     475/* #undef _POSIX_SOURCE */
     476
     477/* Define to empty if 'const' does not conform to ANSI C. */
    439478/* #undef const */
    440479
    441 /* Define to `int' if <sys/types.h> doesn't define. */
     480/* Define to 'int' if <sys/types.h> doesn't define. */
    442481#define gid_t int
    443482
    444 /* Define to `int' if <sys/types.h> does not define. */
     483/* Define to 'int' if <sys/types.h> does not define. */
    445484/* Note (bird)! sub_proc.c needs this to be pointer sized. */
    446485#define pid_t intptr_t
    447486
    448 /* Define to `int' if <sys/types.h> doesn't define. */
     487/* Define to 'int' if <sys/types.h> doesn't define. */
    449488#define uid_t int
    450489
    451490/* Define uintmax_t if not defined in <stdint.h> or <inttypes.h>. */
    452 #if _MSC_VER < 1600
     491#if !HAVE_STDINT_H && !HAVE_INTTYPES_H
    453492# if 0
    454493#  define uintmax_t unsigned long
     
    458497#endif
    459498
    460 /* Define as `fork' if `vfork' does not work. */
    461 /*#define vfork fork*/
    462 
    463 #if 0/* see above */
    464 /* Define to `unsigned long' or `unsigned long long'
    465    if <inttypes.h> doesn't define.  */
    466 #define uintmax_t unsigned long
    467 #endif
    468 
    469 /* Define if you support file names longer than 14 characters.  */
    470 #define HAVE_LONG_FILE_NAMES 1
    471 
    472 /* Define if your struct stat has st_rdev.  */
    473 #undef HAVE_ST_RDEV
    474 #define HAVE_ST_RDEV 1
    475 
    476 /* Define if you have the strftime function.  */
    477 #undef HAVE_STRFTIME
    478 #define HAVE_STRFTIME 1
    479 
    480499/* Define if you have <sys/wait.h> that is POSIX.1 compatible.  */
    481500/* #undef HAVE_SYS_WAIT_H */
    482 
    483 /* Define if your struct tm has tm_zone.  */
    484 /* #undef HAVE_TM_ZONE */
    485 
    486 /* Define if you don't have tm_zone but do have the external array
    487    tzname.  */
    488 #undef HAVE_TZNAME
    489 #define HAVE_TZNAME 1
    490 
    491 /* Define if utime(file, NULL) sets file's timestamp to the present.  */
    492 #undef HAVE_UTIME_NULL
    493 #define HAVE_UTIME_NULL 1
    494501
    495502/* Define to the installation directory for locales.  */
     
    547554#include "inlined_memchr.h"
    548555
    549 #ifdef CONFIG_WITH_FAST_IS_SPACE
    550 # include <ctype.h>
    551 # if _MSC_VER >= 1400
    552 #  include <intrin.h>
    553 #  pragma intrinsic(_bittest)
    554 #  pragma intrinsic(_bittestandset)
    555 #  define space_map_size          32
    556 #  define set_space_map_entry(ch) _bittestandset((long *)&space_map[0], (unsigned char)(ch))
    557 #  define isspace(ch)             _bittest((long *)&space_map[0], (unsigned char)(ch))
    558 # else
    559 #  define space_map_size          256
    560 #  define set_space_map_entry(ch) (space_map[(unsigned char)(ch)] = 1)
    561 #  define isspace(ch)             (space_map[(unsigned char)(ch)])
    562 # endif
    563 extern char space_map[space_map_size];
    564 #endif
    565 
    566556/* bird: Include mscfakes.h to make sure we have all it's tricks applied. */
    567557#ifndef ___mscfakes_h
     
    569559#endif
    570560
     561/*
     562 * Map posixfcn.c stuff to non-conflicting names.
     563 */
     564#include <stdio.h>
     565#include <io.h>
     566
     567#define tmpfile posixfcn_tmpfile
     568FILE *posixfcn_tmpfile(void);
     569
     570#define isatty posixfcn_isatty
     571int posixfcn_isatty(int fd);
     572
    571573#endif /* bird */
    572574
  • trunk/src/kmk/config/Makefile.am

    r2591 r3140  
    11# -*-Makefile-*-, or close enough
    2 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free
    3 # Software Foundation, Inc.
     2# Copyright (C) 2002-2016 Free Software Foundation, Inc.
    43# This file is part of GNU Make.
    54#
     
    1716# this program.  If not, see <http://www.gnu.org/licenses/>.
    1817
    19 EXTRA_DIST =    codeset.m4 gettext.m4 glibc21.m4 iconv.m4 isc-posix.m4 nls.m4 \
    20                 intdiv0.m4 inttypes-pri.m4 inttypes.m4 inttypes_h.m4 \
    21                 isc-posix.m4 lcmessage.m4 lib-ld.m4 lib-link.m4 lib-prefix.m4 \
    22                 progtest.m4 stdint_h.m4 uintmax_t.m4 ulonglong.m4 longlong.m4 \
    23                 dospaths.m4 po.m4 signed.m4 longdouble.m4 wchar_t.m4 \
    24                 wint_t.m4 intmax.m4 printf-posix.m4 xsize.m4 size_max.m4
     18# Autoconf / automake know how to handle this directory.
  • trunk/src/kmk/config/dospaths.m4

    r2591 r3140  
    22# By Paul Smith <[email protected]>.  Based on dos.m4 by Jim Meyering.
    33#
    4 # Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
    5 # 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     4# Copyright (C) 1993-2016 Free Software Foundation, Inc.
    65# This file is part of GNU Make.
    76#
     
    1918# this program.  If not, see <http://www.gnu.org/licenses/>.
    2019
    21 AC_DEFUN([pds_AC_DOS_PATHS],
    22   [
    23     AC_CACHE_CHECK([whether system uses MSDOS-style paths], [ac_cv_dos_paths],
    24       [
    25         AC_COMPILE_IFELSE([
     20AC_DEFUN([pds_AC_DOS_PATHS], [
     21  AC_CACHE_CHECK([whether system uses MSDOS-style paths], [ac_cv_dos_paths], [
     22    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
    2623#if !defined _WIN32 && !defined __WIN32__ && !defined __MSDOS__ && !defined __EMX__ && !defined __MSYS__ && !defined __CYGWIN__
    2724neither MSDOS nor Windows nor OS2
    2825#endif
    29 ],
     26]])],
    3027        [ac_cv_dos_paths=yes],
    31         [ac_cv_dos_paths=no])
    32       ])
     28        [ac_cv_dos_paths=no])])
    3329
    34     if test x"$ac_cv_dos_paths" = xyes; then
    35       AC_DEFINE_UNQUOTED([HAVE_DOS_PATHS], 1,
    36                          [Define if the system uses DOS-style pathnames.])
    37     fi
    38   ])
     30  AS_IF([test x"$ac_cv_dos_paths" = xyes],
     31  [ AC_DEFINE_UNQUOTED([HAVE_DOS_PATHS], 1,
     32                       [Define if the system uses DOS-style pathnames.])])
     33])
  • trunk/src/kmk/configh.dos.template

    r2591 r3140  
    11/* configh.dos -- hand-massaged config.h file for MS-DOS builds         -*-C-*-
    22
    3 Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
    4 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     3Copyright (C) 1994-2016 Free Software Foundation, Inc.
    54This file is part of GNU Make.
    65
     
    2625#if __DJGPP__ > 2 || __DJGPP_MINOR__ > 1
    2726
    28 /* Define to 1 if `sys_siglist' is declared by <signal.h> or <unistd.h>. */
     27/* Define to 1 if 'sys_siglist' is declared by <signal.h> or <unistd.h>. */
    2928# define SYS_SIGLIST_DECLARED 1
    3029
    31 /* Define to 1 if the C library defines the variable `_sys_siglist'.  */
     30/* Define to 1 if the C library defines the variable '_sys_siglist'.  */
    3231# define HAVE_DECL_SYS_SIGLIST 1
    3332
     
    4241#define FILE_TIMESTAMP_HI_RES 0
    4342
    44 /* Define to 1 if you have `alloca', as a function or macro. */
     43/* Define to 1 if you have 'alloca', as a function or macro. */
    4544#define HAVE_ALLOCA 1
    4645
     
    4847#define HAVE_FDOPEN 1
    4948
    50 /* Define to 1 if you have the `getgroups' function. */
     49/* Define to 1 if you have the 'getgroups' function. */
    5150#define HAVE_GETGROUPS 1
    5251
     
    5756#define HAVE_MKSTEMP 1
    5857
    59 /* Define to 1 if you have the `mktemp' function. */
     58/* Define to 1 if you have the 'mktemp' function. */
    6059#define HAVE_MKTEMP 1
    6160
    62 /* Define to 1 if you have the `setlinebuf' function. */
     61/* Define to 1 if you have the 'setlinebuf' function. */
    6362#define HAVE_SETLINEBUF 1
    6463
    65 /* Define to 1 if you have the `setvbuf' function. */
     64/* Define to 1 if you have the 'setvbuf' function. */
    6665#define HAVE_SETVBUF 1
    6766
    6867#define SCCS_GET "get"
    6968
    70 /* Define to `unsigned long' or `unsigned long long'
     69/* Define to 'unsigned long' or 'unsigned long long'
    7170   if <inttypes.h> doesn't define.  */
    7271#define uintmax_t unsigned long long
     
    7877#define HAVE_SELECT 1
    7978
    80 /* Define to 1 if your compiler conforms to the ANSI C standard. */
    81 #define HAVE_ANSI_COMPILER 1
    82 
    83 /* Define to 1 if you have the <stdarg.h> header file. */
    84 #define HAVE_STDARG_H 1
    85 
    86 /* Define to 1 if you have the vprintf library function.  */
    87 #undef HAVE_VPRINTF
    88 #define HAVE_VPRINTF 1
    89 
    9079/* Define to 1 if you have the stricmp function.  */
    9180#define HAVE_STRICMP 1
     81
     82/* Define to 1 if you have the 'strncasecmp' function. */
     83#define HAVE_STRNCASECMP 1
    9284
    9385/* Name of the package */
     
    109101#define PACKAGE_VERSION "%VERSION%"
    110102
    111 /* Define to 1 if the C compiler supports function prototypes. */
    112 #define PROTOTYPES 1
     103/* Output sync sypport */
     104#define NO_OUTPUT_SYNC
    113105
    114106/* Version number of package */
  • trunk/src/kmk/configure.bat

    r2591 r3140  
    11@echo off
    2 rem Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
    3 rem 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2rem Copyright (C) 1994-2016 Free Software Foundation, Inc.
    43rem This file is part of GNU Make.
    54rem
  • trunk/src/kmk/debug.h

    r2591 r3140  
    11/* Debugging macros and interface.
    2 Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
    3 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1999-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
  • trunk/src/kmk/default.c

    r2591 r3140  
    11/* Data base of default implicit rules for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
     18
     19#include <assert.h>
     20
    2021#include "filedef.h"
    2122#include "variable.h"
     
    3334
    3435/* This is the default list of suffixes for suffix rules.
    35    `.s' must come last, so that a `.o' file will be made from
    36    a `.c' or `.p' or ... file rather than from a .s file.  */
     36   '.s' must come last, so that a '.o' file will be made from
     37   a '.c' or '.p' or ... file rather than from a .s file.  */
    3738
    3839static char default_suffixes[]
    3940#ifndef CONFIG_NO_DEFAULT_SUFFIXES
    4041#ifdef VMS
    41   = ".exe .olb .ln .obj .c .cxx .cc .pas .p .for .f .r .y .l .mar \
    42 .s .ss .i .ii .mod .sym .def .h .info .dvi .tex .texinfo .texi .txinfo \
    43 .w .ch .cweb .web .com .sh .elc .el";
     42  /* VMS should include all UNIX/POSIX + some VMS extensions */
     43  = ".out .exe .a .olb .hlb .tlb .mlb .ln .o .obj .c .cxx .cc .cpp .pas .p \
     44.for .f .r .y .l .ym .yl .mar .s .ss .i .ii .mod .sym .def .h .info .dvi \
     45.tex .texinfo .texi .txinfo .mem .hlp .brn .rnh .rno .rnt .rnx .w .ch .cweb \
     46.web .com .sh .elc .el";
    4447#elif defined(__EMX__)
    4548  = ".out .a .ln .o .c .cc .C .cpp .p .f .F .m .r .y .l .ym .yl .s .S \
     
    5861  {
    5962#ifndef CONFIG_NO_DEFAULT_PATTERN_RULES
     63#ifdef VMS
    6064    { "(%)", "%",
    61         "$(AR) $(ARFLAGS) $@ $<" },
    62 
     65        "@if f$$search(\"$@\") .eqs. \"\" then $(LIBRARY)/CREATE/"
     66         "$(or "
     67          "$(patsubst %,TEXT,$(filter %.tlb %.TLB,$@)),"
     68          "$(patsubst %,HELP,$(filter %.hlb %.HLB,$@)),"
     69          "$(patsubst %,MACRO,$(filter %.mlb %.MLB,$@)),"
     70          "$(and "
     71           "$(patsubst %,SHARE,$(filter %.olb %.OLB,$@)),"
     72           "$(patsubst %,SHARE,$(filter %.exe %.EXE,$<))),"
     73          "OBJECT)"
     74         " $@\n"
     75        "$(AR) $(ARFLAGS) $@ $<" },
     76
     77#else
     78    { "(%)", "%",
     79        "$(AR) $(ARFLAGS) $@ $<" },
     80#endif
    6381    /* The X.out rules are only in BSD's default set because
    64        BSD Make has no null-suffix rules, so `foo.out' and
    65        `foo' are the same thing.  */
     82       BSD Make has no null-suffix rules, so 'foo.out' and
     83       'foo' are the same thing.  */
    6684#ifdef VMS
    6785    { "%.exe", "%",
    68         "copy $< $@" },
    69 #else
     86        "$(CP) $< $@" },
     87
     88#endif
    7089    { "%.out", "%",
    71         "@rm -f $@ \n cp $< $@" },
    72 #endif
     90        "@rm -f $@ \n cp $< $@" },
     91
    7392    /* Syntax is "ctangle foo.w foo.ch foo.c".  */
    7493    { "%.c", "%.w %.ch",
    75         "$(CTANGLE) $^ $@" },
     94        "$(CTANGLE) $^ $@" },
    7695    { "%.tex", "%.w %.ch",
    77         "$(CWEAVE) $^ $@" },
     96        "$(CWEAVE) $^ $@" },
    7897#endif /* !CONFIG_NO_DEFAULT_PATTERN_RULES */
    7998    { 0, 0, 0 }
     
    84103#ifndef CONFIG_NO_DEFAULT_TERMINAL_RULES
    85104#ifdef VMS
     105
    86106    /* RCS.  */
    87107    { "%", "%$$5lv", /* Multinet style */
    88         "if f$$search($@) .nes. \"\" then +$(CHECKOUT,v)" },
     108        "if f$$search(\"$@\") .nes. \"\" then +$(CHECKOUT,v)" },
    89109    { "%", "[.$$rcs]%$$5lv", /* Multinet style */
    90         "if f$$search($@) .nes. \"\" then +$(CHECKOUT,v)" },
     110        "if f$$search(\"$@\") .nes. \"\" then +$(CHECKOUT,v)" },
    91111    { "%", "%_v", /* Normal style */
    92         "if f$$search($@) .nes. \"\" then +$(CHECKOUT,v)" },
     112        "if f$$search(\"$@\") .nes. \"\" then +$(CHECKOUT,v)" },
    93113    { "%", "[.rcs]%_v", /* Normal style */
    94         "if f$$search($@) .nes. \"\" then +$(CHECKOUT,v)" },
     114        "if f$$search(\"$@\") .nes. \"\" then +$(CHECKOUT,v)" },
    95115
    96116    /* SCCS.  */
    97         /* ain't no SCCS on vms */
     117        /* ain't no SCCS on vms */
     118
    98119#else
    99120    /* RCS.  */
    100121    { "%", "%,v",
    101         "$(CHECKOUT,v)" },
     122        "$(CHECKOUT,v)" },
    102123    { "%", "RCS/%,v",
    103         "$(CHECKOUT,v)" },
     124        "$(CHECKOUT,v)" },
    104125    { "%", "RCS/%",
    105         "$(CHECKOUT,v)" },
     126        "$(CHECKOUT,v)" },
    106127
    107128    /* SCCS.  */
    108129    { "%", "s.%",
    109         "$(GET) $(GFLAGS) $(SCCS_OUTPUT_OPTION) $<" },
     130        "$(GET) $(GFLAGS) $(SCCS_OUTPUT_OPTION) $<" },
    110131    { "%", "SCCS/s.%",
    111         "$(GET) $(GFLAGS) $(SCCS_OUTPUT_OPTION) $<" },
     132        "$(GET) $(GFLAGS) $(SCCS_OUTPUT_OPTION) $<" },
    112133#endif /* !VMS */
    113134#endif /* !CONFIG_NO_DEFAULT_TERMINAL_RULES */
     
    115136  };
    116137
    117 static char *default_suffix_rules[] =
     138static const char *default_suffix_rules[] =
    118139  {
    119140#ifndef CONFIG_NO_DEFAULT_SUFFIX_RULES
    120141#ifdef VMS
     142    ".o",
     143    "$(LINK.obj) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     144    ".obj",
     145    "$(LINK.obj) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     146    ".s",
     147    "$(LINK.s) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     148    ".S",
     149    "$(LINK.S) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     150    ".c",
     151    "$(LINK.c) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     152    ".cc",
     153    "$(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     154    ".C",
     155    "$(LINK.C) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     156    ".cpp",
     157    "$(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     158    ".f",
     159    "$(LINK.f) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     160    ".m",
     161    "$(LINK.m) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     162    ".p",
     163    "$(LINK.p) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     164    ".F",
     165    "$(LINK.F) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     166    ".r",
     167    "$(LINK.r) $^ $(LOADLIBES) $(LDLIBS) -o $@",
     168    ".mod",
     169    "$(COMPILE.mod) -o $@ -e $@ $^",
     170
     171    ".def.sym",
     172    "$(COMPILE.def) -o $@ $<",
     173
     174    ".sh",
     175    "copy $< >$@",
     176
    121177    ".obj.exe",
    122178    "$(LINK.obj) $^ $(LOADLIBES) $(LDLIBS) $(CRT0) /exe=$@",
    123179    ".mar.exe",
    124180    "$(COMPILE.mar) $^ \n $(LINK.obj) $(subst .mar,.obj,$^) $(LOADLIBES) $(LDLIBS) $(CRT0) /exe=$@",
     181    ".s.o",
     182    "$(COMPILE.s) -o $@ $<",
    125183    ".s.exe",
    126184    "$(COMPILE.s) $^ \n $(LINK.obj) $(subst .s,.obj,$^) $(LOADLIBES) $(LDLIBS) $(CRT0) /exe=$@",
     
    157215    ".c.obj",
    158216    "$(COMPILE.c) /obj=$@ $<",
     217    ".c.o",
     218    "$(COMPILE.c) /obj=$@ $<",
    159219    ".cc.ii",
    160220    "$(COMPILE.cc)/prep /list=$@ $<",
     
    165225    ".cc.obj",
    166226    "$(COMPILE.cc) /obj=$@ $<",
     227    ".cc.o",
     228    "$(COMPILE.cc) /obj=$@ $<",
    167229    ".cxx.obj",
     230    "$(COMPILE.cxx) /obj=$@ $<",
     231    ".cxx.o",
    168232    "$(COMPILE.cxx) /obj=$@ $<",
    169233    ".for.obj",
    170234    "$(COMPILE.for) /obj=$@ $<",
     235    ".for.o",
     236    "$(COMPILE.for) /obj=$@ $<",
    171237    ".pas.obj",
     238    "$(COMPILE.pas) /obj=$@ $<",
     239    ".pas.o",
    172240    "$(COMPILE.pas) /obj=$@ $<",
    173241
     
    182250    ".tex.dvi",
    183251    "$(TEX) $<",
     252
     253    ".cpp.o",
     254    "$(COMPILE.cpp) $(OUTPUT_OPTION) $<",
     255    ".f.o",
     256    "$(COMPILE.f) $(OUTPUT_OPTION) $<",
     257    ".m.o",
     258    "$(COMPILE.m) $(OUTPUT_OPTION) $<",
     259    ".p.o",
     260    "$(COMPILE.p) $(OUTPUT_OPTION) $<",
     261    ".r.o",
     262    "$(COMPILE.r) $(OUTPUT_OPTION) $<",
     263    ".mod.o",
     264    "$(COMPILE.mod) -o $@ $<",
     265
     266    ".c.ln",
     267    "$(LINT.c) -C$* $<",
     268    ".y.ln",
     269    "$(YACC.y) $< \n rename y_tab.c $@",
     270
     271    ".l.ln",
     272    "@$(RM) $*.c\n $(LEX.l) $< > $*.c\n$(LINT.c) -i $*.c -o $@\n $(RM) $*.c",
    184273
    185274#else /* ! VMS */
     
    302391
    303392    ".w.c",
    304     "$(CTANGLE) $< - $@",       /* The `-' says there is no `.ch' file.  */
     393    "$(CTANGLE) $< - $@",       /* The '-' says there is no '.ch' file.  */
    305394
    306395    ".web.p",
     
    308397
    309398    ".w.tex",
    310     "$(CWEAVE) $< - $@",        /* The `-' says there is no `.ch' file.  */
     399    "$(CWEAVE) $< - $@",        /* The '-' says there is no '.ch' file.  */
    311400
    312401    ".web.tex",
     
    331420    "ARCH", "VAX",
    332421#endif
    333     "AR", "library/obj",
     422    "AR", "library",
     423    "LIBRARY", "library",
    334424    "ARFLAGS", "/replace",
    335425    "AS", "macro",
     
    341431#endif
    342432    "CD", "builtin_cd",
    343     "MAKE", "make",
    344     "ECHO", "write sys$$output \"",
     433    "ECHO", "builtin_echo",
    345434#ifdef GCC_IS_NATIVE
    346435    "C++", "gcc/plus",
     
    349438    "C++", "cxx",
    350439    "CXX", "cxx",
     440#ifndef __ia64
    351441    "CXXLD", "cxxlink",
     442    "CXXLINK", "cxxlink",
     443#else
     444    /* CXXLINK is not used on VMS/IA64 */
     445    "CXXLD", "link",
     446    "CXXLINK", "link",
     447#endif
    352448#endif
    353449    "CO", "co",
     
    385481#endif
    386482
     483    "LINK.o", "$(LD) $(LDFLAGS)",
    387484    "LINK.obj", "$(LD) $(LDFLAGS)",
    388485#ifndef GCC_IS_NATIVE
     
    391488#endif
    392489    "COMPILE.c", "$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH)",
     490    "LINK.c", "$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH)",
     491    "COMPILE.m", "$(OBJC) $(OBJCFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
     492    "LINK.m", "$(OBJC) $(OBJCFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
    393493    "COMPILE.cc", "$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH)",
     494    "COMPILE.C", "$(COMPILE.cc)",
     495    "COMPILE.cpp", "$(COMPILE.cc)",
     496    "LINK.C", "$(LINK.cc)",
     497    "LINK.cpp", "$(LINK.cc)",
    394498    "YACC.y", "$(YACC) $(YFLAGS)",
    395499    "LEX.l", "$(LEX) $(LFLAGS)",
     500    "YACC.m", "$(YACC) $(YFLAGS)",
     501    "LEX.m", "$(LEX) $(LFLAGS) -t",
    396502    "COMPILE.for", "$(FC) $(FFLAGS) $(TARGET_ARCH)",
     503    "COMPILE.f", "$(FC) $(FFLAGS) $(TARGET_ARCH) -c",
     504    "LINK.f", "$(FC) $(FFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
     505    "COMPILE.F", "$(FC) $(FFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
     506    "LINK.F", "$(FC) $(FFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
     507    "COMPILE.r", "$(FC) $(FFLAGS) $(RFLAGS) $(TARGET_ARCH) -c",
     508    "LINK.r", "$(FC) $(FFLAGS) $(RFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
    397509    "COMPILE.pas", "$(PC) $(PFLAGS) $(CPPFLAGS) $(TARGET_ARCH)",
     510    "COMPILE.def", "$(M2C) $(M2FLAGS) $(DEFFLAGS) $(TARGET_ARCH)",
     511    "COMPILE.mod", "$(M2C) $(M2FLAGS) $(MODFLAGS) $(TARGET_ARCH)",
     512    "COMPILE.p", "$(PC) $(PFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
     513    "LINK.p", "$(PC) $(PFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
    398514    "COMPILE.mar", "$(MACRO) $(MACROFLAGS)",
    399515    "COMPILE.s", "$(AS) $(ASFLAGS) $(TARGET_MACH)",
     516    "LINK.S", "$(CC) $(ASFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_MACH)",
     517    "COMPILE.S", "$(CC) $(ASFLAGS) $(CPPFLAGS) $(TARGET_MACH) -c",
     518    "PREPROCESS.S", "$(CC) -E $(CPPFLAGS)",
     519    "PREPROCESS.F", "$(FC) $(FFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -F",
     520    "PREPROCESS.r", "$(FC) $(FFLAGS) $(RFLAGS) $(TARGET_ARCH) -F",
    400521    "LINT.c", "$(LINT) $(LINTFLAGS) $(CPPFLAGS) $(TARGET_ARCH)",
    401522
    402523    "MV", "rename/new_version",
    403524    "CP", "copy",
     525    ".LIBPATTERNS", "%.olb lib%.a",
    404526
    405527#else /* !VMS */
     
    411533    "CC", "gcc",
    412534# ifdef __MSDOS__
    413     "CXX", "gpp",       /* g++ is an invalid name on MSDOS */
     535    "CXX", "gpp",       /* g++ is an invalid name on MSDOS */
    414536# else
    415537    "CXX", "gcc",
     
    429551
    430552    "CPP", "$(CC) -E",
    431 #ifdef  CRAY
     553#ifdef  CRAY
    432554    "CF77PPFLAGS", "-P",
    433555    "CF77PP", "/lib/cpp",
     
    435557    "CF", "cf77",
    436558    "FC", "$(CF)",
    437 #else   /* Not CRAY.  */
    438 #ifdef  _IBMR2
     559#else   /* Not CRAY.  */
     560#ifdef  _IBMR2
    439561    "FC", "xlf",
    440562#else
    441 #ifdef  __convex__
     563#ifdef  __convex__
    442564    "FC", "fc",
    443565#else
     
    449571    "F77", "$(FC)",
    450572    "F77FLAGS", "$(FFLAGS)",
    451 #endif  /* Cray.  */
     573#endif  /* Cray.  */
    452574    "GET", SCCS_GET,
    453575    "LD", "ld",
     
    459581    "LINT", "lint",
    460582    "M2C", "m2c",
    461 #ifdef  pyr
     583#ifdef  pyr
    462584    "PC", "pascal",
    463585#else
    464 #ifdef  CRAY
     586#ifdef  CRAY
    465587    "PC", "PASCAL",
    466588    "SEGLDR", "segldr",
    467589#else
    468590    "PC", "pc",
    469 #endif  /* CRAY.  */
    470 #endif  /* pyr.  */
     591#endif  /* CRAY.  */
     592#endif  /* pyr.  */
    471593#ifdef GCC_IS_NATIVE
    472594    "YACC", "bison -y",
    473595#else
    474     "YACC", "yacc",     /* Or "bison -y"  */
     596    "YACC", "yacc",     /* Or "bison -y"  */
    475597#endif
    476598    "MAKEINFO", "makeinfo",
     
    490612    "LINK.m", "$(OBJC) $(OBJCFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
    491613    "COMPILE.cc", "$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c",
     614#ifndef HAVE_CASE_INSENSITIVE_FS
     615    /* On case-insensitive filesystems, treat *.C files as *.c files,
     616       to avoid erroneously compiling C sources as C++, which will
     617       probably fail.  */
    492618    "COMPILE.C", "$(COMPILE.cc)",
     619#else
     620    "COMPILE.C", "$(COMPILE.c)",
     621#endif
    493622    "COMPILE.cpp", "$(COMPILE.cc)",
    494623    "LINK.cc", "$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)",
     624#ifndef HAVE_CASE_INSENSITIVE_FS
    495625    "LINK.C", "$(LINK.cc)",
     626#else
     627    "LINK.C", "$(LINK.c)",
     628#endif
    496629    "LINK.cpp", "$(LINK.cc)",
    497630    "YACC.y", "$(YACC) $(YFLAGS)",
     
    518651    "LINT.c", "$(LINT) $(LINTFLAGS) $(CPPFLAGS) $(TARGET_ARCH)",
    519652
    520 #ifndef NO_MINUS_C_MINUS_O
     653#ifndef NO_MINUS_C_MINUS_O
    521654    "OUTPUT_OPTION", "-o $@",
    522655#endif
    523656
    524 #ifdef  SCCS_GET_MINUS_G
     657#ifdef  SCCS_GET_MINUS_G
    525658    "SCCS_OUTPUT_OPTION", "-G$@",
    526659#endif
    527660
    528 #ifdef _AMIGA
     661#if defined(_AMIGA)
    529662    ".LIBPATTERNS", "%.lib",
    530 #else
    531 #ifdef __MSDOS__
     663#elif defined(__MSDOS__)
    532664    ".LIBPATTERNS", "lib%.a $(DJDIR)/lib/lib%.a",
     665#elif defined(__APPLE__)
     666    ".LIBPATTERNS", "lib%.dylib lib%.a",
     667#elif defined(__CYGWIN__) || defined(WINDOWS32)
     668    ".LIBPATTERNS", "lib%.dll.a %.dll.a lib%.a %.lib lib%.dll %.dll",
    533669#else
    534670    ".LIBPATTERNS", "lib%.so lib%.a",
    535 #endif
    536671#endif
    537672
    538673#endif /* !VMS */
    539674#endif /* !CONFIG_NO_DEFAULT_VARIABLES */
     675    /* Make this assignment to avoid undefined variable warnings.  */
     676    "GNUMAKEFLAGS", "",
    540677    0, 0
    541678  };
     
    548685{
    549686  suffix_file = enter_file (strcache_add (".SUFFIXES"));
     687  suffix_file->builtin = 1;
    550688
    551689  if (no_builtin_rules_flag)
     
    553691  else
    554692    {
    555       char *p = default_suffixes;
    556       suffix_file->deps = enter_prereqs(PARSE_FILE_SEQ (&p, struct dep, '\0',
    557                                                         NULL, 0),
    558                                         NULL);
     693      struct dep *d;
     694      const char *p = default_suffixes;
     695      suffix_file->deps = enter_prereqs (PARSE_SIMPLE_SEQ ((char **)&p, struct dep),
     696                                         NULL);
     697      for (d = suffix_file->deps; d; d = d->next)
     698        d->file->builtin = 1;
     699
    559700      define_variable_cname ("SUFFIXES", default_suffixes, o_default, 0);
    560701    }
     
    569710install_default_suffix_rules (void)
    570711{
    571   char **s;
     712  const char **s;
    572713
    573714  if (no_builtin_rules_flag)
     
    577718    {
    578719      struct file *f = enter_file (strcache_add (s[0]));
    579       /* Don't clobber cmds given in a makefile if there were any.  */
    580       if (f->cmds == 0)
    581         {
     720      /* This function should run before any makefile is parsed.  */
     721      assert (f->cmds == 0);
    582722#ifndef CONFIG_WITH_ALLOC_CACHES
    583           f->cmds = xmalloc (sizeof (struct commands));
    584 #else
    585           f->cmds = alloccache_alloc (&commands_cache);
    586 #endif
    587           f->cmds->fileinfo.filenm = 0;
    588           f->cmds->commands = s[1];
    589           f->cmds->command_lines = 0;
     723      f->cmds = xmalloc (sizeof (struct commands));
     724#else
     725      f->cmds = alloccache_alloc (&commands_cache);
     726#endif
     727      f->cmds->fileinfo.filenm = 0;
     728      f->cmds->commands = xstrdup (s[1]);
     729      f->cmds->command_lines = 0;
     730      f->cmds->recipe_prefix = RECIPEPREFIX_DEFAULT;
    590731#ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
    591           f->cmds->refs = 1000;
    592 #endif
    593         }
     732      f->cmds->refs = 1000;
     733#endif
     734      f->builtin = 1;
    594735    }
    595736}
     
    624765    define_variable (s[0], strlen (s[0]), s[1], o_default, 1);
    625766}
     767
     768void
     769undefine_default_variables (void)
     770{
     771  const char **s;
     772
     773  for (s = default_variables; *s != 0; s += 2)
     774    undefine_variable_global (s[0], strlen (s[0]), o_default);
     775}
  • trunk/src/kmk/dep.h

    r2591 r3140  
    11/* Definitions of dependency data structures for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 /* Flag bits for the second argument to `read_makefile'.
    20    These flags are saved in the `changed' field of each
    21    `struct dep' in the chain returned by `read_all_makefiles'.  */
    2217
    23 #define RM_NO_DEFAULT_GOAL      (1 << 0) /* Do not set default goal.  */
    24 #define RM_INCLUDED             (1 << 1) /* Search makefile search path.  */
    25 #define RM_DONTCARE             (1 << 2) /* No error if it doesn't exist.  */
    26 #define RM_NO_TILDE             (1 << 3) /* Don't expand ~ in file name.  */
    27 #define RM_NOFLAG               0
     18/* Structure used in chains of names, for parsing and globbing.  */
     19
     20#define NAMESEQ(_t)     \
     21    _t *next;           \
     22    const char *name
     23
     24struct nameseq
     25  {
     26    NAMESEQ (struct nameseq);
     27  };
     28
     29/* Flag bits for the second argument to 'read_makefile'.
     30   These flags are saved in the 'flags' field of each
     31   'struct goaldep' in the chain returned by 'read_all_makefiles'.  */
     32
     33#define RM_NO_DEFAULT_GOAL      (1 << 0) /* Do not set default goal.  */
     34#define RM_INCLUDED             (1 << 1) /* Search makefile search path.  */
     35#define RM_DONTCARE             (1 << 2) /* No error if it doesn't exist.  */
     36#define RM_NO_TILDE             (1 << 3) /* Don't expand ~ in file name.  */
     37#define RM_NOFLAG               0
    2838
    2939/* Structure representing one dependency of a file.
    30    Each struct file's `deps' points to a chain of these,
    31    chained through the `next'. `stem' is the stem for this
    32    dep line of static pattern rule or NULL.
     40   Each struct file's 'deps' points to a chain of these, through 'next'.
     41   'stem' is the stem for this dep line of static pattern rule or NULL.  */
    3342
    34    Note that the first two words of this match a struct nameseq.  */
     43#ifndef CONFIG_WITH_INCLUDEDEP
     44#define DEP(_t)                                 \
     45    NAMESEQ (_t);                               \
     46    struct file *file;                          \
     47    const char *stem;                           \
     48    unsigned short flags : 8;                   \
     49    unsigned short changed : 1;                 \
     50    unsigned short ignore_mtime : 1;            \
     51    unsigned short staticpattern : 1;           \
     52    unsigned short need_2nd_expansion : 1
     53#else
     54# define DEP(_t)                                \
     55    NAMESEQ (_t);                               \
     56    struct file *file;                          \
     57    const char *stem;                           \
     58    unsigned short flags : 8;                   \
     59    unsigned short changed : 1;                 \
     60    unsigned short ignore_mtime : 1;            \
     61    unsigned short staticpattern : 1;           \
     62    unsigned short need_2nd_expansion : 1;      \
     63    unsigned short includedep : 1
     64#endif
    3565
    3666struct dep
    3767  {
    38     struct dep *next;
    39     const char *name;
    40     const char *stem;
    41     struct file *file;
    42     unsigned int changed : 8;
    43     unsigned int ignore_mtime : 1;
    44     unsigned int staticpattern : 1;
    45     unsigned int need_2nd_expansion : 1;
    46     unsigned int dontcare : 1;
    47 
    48 #ifdef CONFIG_WITH_INCLUDEDEP
    49     unsigned int includedep : 1;
    50 #endif
     68    DEP (struct dep);
    5169  };
    5270
     71/* Structure representing one goal.
     72   The goals to be built constitute a chain of these, chained through 'next'.
     73   'stem' is not used, but it's simpler to include and ignore it.  */
    5374
    54 /* Structure used in chains of names, for parsing and globbing.  */
    55 
    56 struct nameseq
     75struct goaldep
    5776  {
    58     struct nameseq *next;
    59     const char *name;
     77    DEP (struct goaldep);
     78    unsigned short error;
     79    floc floc;
    6080  };
    6181
     82/* Options for parsing lists of filenames.  */
    6283
    63 #define PARSEFS_NONE    (0x0000)
    64 #define PARSEFS_NOSTRIP (0x0001)
    65 #define PARSEFS_NOAR    (0x0002)
    66 #define PARSEFS_NOGLOB  (0x0004)
    67 #define PARSEFS_EXISTS  (0x0008)
    68 #define PARSEFS_NOCACHE (0x0010)
     84#define PARSEFS_NONE    0x0000
     85#define PARSEFS_NOSTRIP 0x0001
     86#define PARSEFS_NOAR    0x0002
     87#define PARSEFS_NOGLOB  0x0004
     88#define PARSEFS_EXISTS  0x0008
     89#define PARSEFS_NOCACHE 0x0010
    6990
    7091#ifndef CONFIG_WITH_ALLOC_CACHES
    7192#define PARSE_FILE_SEQ(_s,_t,_c,_p,_f) \
    7293            (_t *)parse_file_seq ((_s),sizeof (_t),(_c),(_p),(_f))
     94#define PARSE_SIMPLE_SEQ(_s,_t) \
     95            (_t *)parse_file_seq ((_s),sizeof (_t),MAP_NUL,NULL,PARSEFS_NONE)
    7396#else
    7497# define PARSE_FILE_SEQ(_s,_t,_c,_p,_f) \
    7598            (_t *)parse_file_seq ((_s),sizeof (_t),(_c),(_p),(_f), \
    7699                                  &PARSE_FILE_SEQ_IGNORE_ ## _t ## _cache)
     100# define PARSE_SIMPLE_SEQ(_s,_t) \
     101            (_t *)parse_file_seq ((_s),sizeof (_t),MAP_NUL,NULL,PARSEFS_NONE, \
     102                                  &PARSE_FILE_SEQ_IGNORE_ ## _t ## _cache)
    77103# define PARSE_FILE_SEQ_IGNORE_struct
    78104#endif
     105
    79106
    80107#ifdef VMS
     
    82109#else
    83110void *parse_file_seq (char **stringp, unsigned int size,
    84                       int stopchar, const char *prefix, int flags
     111                      int stopmap, const char *prefix, int flags
    85112                      IF_WITH_ALLOC_CACHES_PARAM(struct alloccache *cache));
    86113#endif
     
    92119#endif
    93120
    94 #define dep_name(d)     ((d)->name == 0 ? (d)->file->name : (d)->name)
    95 
     121#define dep_name(d)        ((d)->name ? (d)->name : (d)->file->name)
    96122
    97123#ifndef CONFIG_WITH_ALLOC_CACHES
    98 #define alloc_dep()     (xcalloc (sizeof (struct dep)))
    99 #define free_ns(_n)     free (_n)
    100 #define free_dep(_d)    free_ns (_d)
     124
     125#define alloc_seq_elt(_t)   xcalloc (sizeof (_t))
     126void free_ns_chain (struct nameseq *n);
     127
     128#if defined(MAKE_MAINTAINER_MODE) && defined(__GNUC__)
     129/* Use inline to get real type-checking.  */
     130#define SI static inline
     131SI struct nameseq *alloc_ns()      { return alloc_seq_elt (struct nameseq); }
     132SI struct dep *alloc_dep()         { return alloc_seq_elt (struct dep); }
     133SI struct goaldep *alloc_goaldep() { return alloc_seq_elt (struct goaldep); }
     134
     135SI void free_ns(struct nameseq *n)      { free (n); }
     136SI void free_dep(struct dep *d)         { free_ns ((struct nameseq *)d); }
     137SI void free_goaldep(struct goaldep *g) { free_dep ((struct dep *)g); }
     138
     139SI void free_dep_chain(struct dep *d)      { free_ns_chain((struct nameseq *)d); }
     140SI void free_goal_chain(struct goaldep *g) { free_dep_chain((struct dep *)g); }
    101141#else
    102 #define alloc_dep()     alloccache_calloc (&dep_cache)
    103 #define free_ns(_n)     alloccache_free (&nameseq_cache, _n)
    104 #define free_dep(_d)    alloccache_free (&dep_cache, _d)
     142# define alloc_ns()          alloc_seq_elt (struct nameseq)
     143# define alloc_dep()         alloc_seq_elt (struct dep)
     144# define alloc_goaldep()     alloc_seq_elt (struct goaldep)
     145
     146# define free_ns(_n)         free (_n)
     147# define free_dep(_d)        free_ns (_d)
     148# define free_goaldep(_g)    free_dep (_g)
     149
     150# define free_dep_chain(_d)  free_ns_chain ((struct nameseq *)(_d))
     151# define free_goal_chain(_g) free_ns_chain ((struct nameseq *)(_g))
    105152#endif
    106153
     154#else /* CONFIG_WITH_ALLOC_CACHES */
     155
     156# include <k/kDefs.h>
     157
     158K_INLINE struct nameseq *alloc_ns (void)        { return (struct nameseq *)alloccache_calloc (&nameseq_cache); }
     159K_INLINE void free_ns (struct nameseq *n)       { alloccache_free (&nameseq_cache, n); }
     160void free_ns_chain (struct nameseq *n);
     161
     162K_INLINE struct dep *alloc_dep (void)           { return (struct dep *)alloccache_calloc (&dep_cache); }
     163K_INLINE void free_dep (struct dep *d)          { alloccache_free (&dep_cache, d); }
     164void free_dep_chain (struct dep *d);
     165
     166K_INLINE struct goaldep *alloc_goaldep (void)   { return (struct goaldep *)alloccache_calloc (&goaldep_cache); }
     167K_INLINE void free_goaldep (struct goaldep *g)  { alloccache_free (&goaldep_cache, g); }
     168void free_goal_chain (struct goaldep *g);
     169
     170#endif  /* CONFIG_WITH_ALLOC_CACHES */
     171
    107172struct dep *copy_dep_chain (const struct dep *d);
    108 void free_dep_chain (struct dep *d);
    109 void free_ns_chain (struct nameseq *n);
    110 struct dep *read_all_makefiles (const char **makefiles);
    111 void eval_buffer (char *buffer IF_WITH_VALUE_LENGTH(COMMA char *eos));
    112 int update_goal_chain (struct dep *goals);
     173
     174struct goaldep *read_all_makefiles (const char **makefiles);
     175void eval_buffer (char *buffer, const floc *floc IF_WITH_VALUE_LENGTH(COMMA char *eos));
     176enum update_status update_goal_chain (struct goaldep *goals);
    113177
    114178#ifdef CONFIG_WITH_INCLUDEDEP
    115179/* incdep.c */
    116180enum incdep_op { incdep_read_it, incdep_queue, incdep_flush };
    117 void eval_include_dep (const char *name, struct floc *f, enum incdep_op op);
     181void eval_include_dep (const char *name, floc *f, enum incdep_op op);
    118182void incdep_flush_and_term (void);
    119183#endif
  • trunk/src/kmk/dir-nt-bird.c

    r3024 r3140  
    3232*********************************************************************************************************************************/
    3333#include "nt/kFsCache.h"
    34 #include "make.h"
     34#include "makeint.h"
    3535#if defined(KMK) && !defined(__OS2__)
    3636# include "glob/glob.h"
     
    653653            return 0;
    654654        }
    655         error(reading_file, "failed to mark '%s' as volatile", pszDir);
     655        OS(error, reading_file, "failed to mark '%s' as volatile", pszDir);
    656656    }
    657657    else
    658         error(reading_file, "failed to mark '%s' as volatile (not found)", pszDir);
     658        OS(error, reading_file, "failed to mark '%s' as volatile (not found)", pszDir);
    659659    return -1;
    660660}
  • trunk/src/kmk/dir.c

    r3065 r3140  
    11/* Directory hashing for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018#include "hash.h"
    21 
    22 #ifdef  HAVE_DIRENT_H
     19#include "filedef.h"
     20#include "dep.h"
     21
     22#ifdef  HAVE_DIRENT_H
    2323# include <dirent.h>
    2424# define NAMLEN(dirent) strlen((dirent)->d_name)
     
    9797
    9898  /* First, transform the name part.  */
    99   for (i = 0; *filename != '\0' && i < 8 && *filename != '.'; ++i)
     99  for (i = 0; i < 8 && ! STOP_SET (*filename, MAP_DOT|MAP_NUL); ++i)
    100100    *df++ = tolower ((unsigned char)*filename++);
    101101
    102102  /* Now skip to the next dot.  */
    103   while (*filename != '\0' && *filename != '.')
     103  while (! STOP_SET (*filename, MAP_DOT|MAP_NUL))
    104104    ++filename;
    105105  if (*filename != '\0')
    106106    {
    107107      *df++ = *filename++;
    108       for (i = 0; *filename != '\0' && i < 3 && *filename != '.'; ++i)
    109         *df++ = tolower ((unsigned char)*filename++);
     108      for (i = 0; i < 3 && ! STOP_SET (*filename, MAP_DOT|MAP_NUL); ++i)
     109        *df++ = tolower ((unsigned char)*filename++);
    110110    }
    111111
    112112  /* Look for more dots.  */
    113   while (*filename != '\0' && *filename != '.')
     113  while (! STOP_SET (*filename, MAP_DOT|MAP_NUL))
    114114    ++filename;
    115115  if (*filename == '.')
     
    154154#ifdef VMS
    155155
     156static char *
     157downcase_inplace(char *filename)
     158{
     159  char *name;
     160  name = filename;
     161  while (*name != '\0')
     162    {
     163      *name = tolower ((unsigned char)*name);
     164      ++name;
     165    }
     166  return filename;
     167}
     168
     169#ifndef _USE_STD_STAT
     170/* VMS 8.2 fixed the VMS stat output to have unique st_dev and st_ino
     171   when _USE_STD_STAT is used on the compile line.
     172
     173   Prior to _USE_STD_STAT support, the st_dev is a pointer to thread
     174   static memory containing the device of the last filename looked up.
     175
     176   Todo: find out if the ino_t still needs to be faked on a directory.
     177 */
     178
     179/* Define this if the older VMS_INO_T is needed */
     180#define VMS_INO_T 1
     181
    156182static int
    157183vms_hash (const char *name)
    158184{
    159185  int h = 0;
    160   int g;
    161186
    162187  while (*name)
    163188    {
    164189      unsigned char uc = *name;
     190      int g;
    165191#ifdef HAVE_CASE_INSENSITIVE_FS
    166192      h = (h << 4) + (isupper (uc) ? tolower (uc) : uc);
     
    171197      g = h & 0xf0000000;
    172198      if (g)
    173         {
    174           h = h ^ (g >> 24);
    175           h = h ^ g;
    176         }
     199        {
     200          h = h ^ (g >> 24);
     201          h = h ^ g;
     202        }
    177203    }
    178204  return h;
     
    191217    return -1;
    192218  closedir (dir);
    193   s = strchr (name, ':');       /* find device */
     219  s = strchr (name, ':');       /* find device */
    194220  if (s)
    195221    {
     
    212238  return 0;
    213239}
     240
     241# define stat(__path, __sbuf) vmsstat_dir (__path, __sbuf)
     242
     243#endif /* _USE_STD_STAT */
    214244#endif /* VMS */
    215245
     
    217247/* Hash table of directories.  */
    218248
    219 #ifndef DIRECTORY_BUCKETS
     249#ifndef DIRECTORY_BUCKETS
    220250#ifdef KMK
    221251#  define DIRECTORY_BUCKETS 4096
     
    227257struct directory_contents
    228258  {
    229     dev_t dev;                  /* Device and inode numbers of this dir.  */
     259    dev_t dev;                  /* Device and inode numbers of this dir.  */
    230260#ifdef WINDOWS32
    231261    /* Inode means nothing on WINDOWS32. Even file key information is
     
    239269    char const *path_key; /* strcache'ed */
    240270# endif
    241     int  ctime;
    242     int  mtime;        /* controls check for stale directory cache */
    243     int   fs_flags;     /* FS_FAT, FS_NTFS, ... */
     271    time_t ctime;
     272    time_t mtime;        /* controls check for stale directory cache */
     273    int fs_flags;     /* FS_FAT, FS_NTFS, ... */
    244274# define FS_FAT      0x1
    245275# define FS_NTFS     0x2
     
    249279# endif
    250280#else
    251 # ifdef VMS
     281# ifdef VMS_INO_T
    252282    ino_t ino[3];
    253283# else
     
    255285# endif
    256286#endif /* WINDOWS32 */
    257     struct hash_table dirfiles; /* Files in this directory.  */
    258     DIR *dirstream;             /* Stream reading this directory.  */
     287    struct hash_table dirfiles; /* Files in this directory.  */
     288    DIR *dirstream;             /* Stream reading this directory.  */
    259289  };
    260290
     
    274304  hash ^= ((unsigned int) key->dev << 4) ^ (unsigned int) key->ctime;
    275305#else
    276 # ifdef VMS
     306# ifdef VMS_INO_T
    277307  hash = (((unsigned int) key->dev << 4)
    278           ^ ((unsigned int) key->ino[0]
    279              + (unsigned int) key->ino[1]
    280              + (unsigned int) key->ino[2]));
     308          ^ ((unsigned int) key->ino[0]
     309             + (unsigned int) key->ino[1]
     310             + (unsigned int) key->ino[2]));
    281311# else
    282312  hash = ((unsigned int) key->dev << 4) ^ (unsigned int) key->ino;
     
    301331  hash ^= ((unsigned int) key->dev << 4) ^ (unsigned int) ~key->ctime;
    302332#else
    303 # ifdef VMS
     333# ifdef VMS_INO_T
    304334  hash = (((unsigned int) key->dev << 4)
    305           ^ ~((unsigned int) key->ino[0]
    306               + (unsigned int) key->ino[1]
    307               + (unsigned int) key->ino[2]));
     335          ^ ~((unsigned int) key->ino[0]
     336              + (unsigned int) key->ino[1]
     337              + (unsigned int) key->ino[2]));
    308338# else
    309339  hash = ((unsigned int) key->dev << 4) ^ (unsigned int) ~key->ino;
     
    345375    return result;
    346376#else
    347 # ifdef VMS
     377# ifdef VMS_INO_T
    348378  result = MAKECMP(x->ino[0], y->ino[0]);
    349379  if (result)
     
    375405struct directory
    376406  {
    377     const char *name;                   /* Name of the directory.  */
     407    const char *name;                   /* Name of the directory.  */
    378408
    379409    /* The directory's contents.  This data may be shared by several
    380410       entries in the hash table, which refer to the same directory
    381        (identified uniquely by `dev' and `ino') under different names.  */
     411       (identified uniquely by 'dev' and 'ino') under different names.  */
    382412    struct directory_contents *contents;
    383413  };
     
    400430{
    401431  return_ISTRING_COMPARE (((const struct directory *) x)->name,
    402                           ((const struct directory *) y)->name);
     432                          ((const struct directory *) y)->name);
    403433}
    404434#endif /* !CONFIG_WITH_STRCACHE2 */
     
    423453struct dirfile
    424454  {
    425     const char *name;           /* Name of the file.  */
    426     short length;
    427     short impossible;           /* This file is impossible.  */
     455    const char *name;           /* Name of the file.  */
     456    size_t length;
     457    short impossible;           /* This file is impossible.  */
    428458  };
    429459
     
    453483#endif /* !CONFIG_WITH_STRCACHE2 */
    454484
    455 #ifndef DIRFILE_BUCKETS
     485#ifndef DIRFILE_BUCKETS
    456486#define DIRFILE_BUCKETS 107
    457487#endif
     
    468498static struct directory *find_directory (const char *name);
    469499
    470 /* Find the directory named NAME and return its `struct directory'.  */
     500/* Find the directory named NAME and return its 'struct directory'.  */
    471501
    472502static struct directory *
    473503find_directory (const char *name)
    474504{
    475   const char *p;
    476505  struct directory *dir;
    477506  struct directory **dir_slot;
    478507  struct directory dir_key;
    479   int r;
    480 #ifdef WINDOWS32
    481   char* w32_path;
    482   char  fs_label[BUFSIZ];
    483   char  fs_type[BUFSIZ];
    484   unsigned long  fs_serno;
    485   unsigned long  fs_flags;
    486   unsigned long  fs_len;
    487 #endif
    488 #ifdef VMS
    489   if ((*name == '.') && (*(name+1) == 0))
    490     name = "[]";
    491   else
    492     name = vmsify (name,1);
    493 #endif
    494508
    495509#ifndef CONFIG_WITH_STRCACHE2
     
    497511  dir_slot = (struct directory **) hash_find_slot (&directories, &dir_key);
    498512#else
    499   p = name + strlen (name);
     513  const char *p = name + strlen (name);
    500514# if defined(HAVE_CASE_INSENSITIVE_FS) && defined(VMS)
    501515  dir_key.name = strcache_add_len (downcase(name), p - name);
     
    509523  if (HASH_VACANT (dir))
    510524    {
     525      /* The directory was not found.  Create a new entry for it.  */
     526#ifndef CONFIG_WITH_STRCACHE2
     527      const char *p = name + strlen (name);
     528#endif
    511529      struct stat st;
    512 
    513       /* The directory was not found.  Create a new entry for it.  */
    514 
    515 #ifndef CONFIG_WITH_STRCACHE2
    516       p = name + strlen (name);
    517 #endif
     530      int r;
     531
    518532#ifndef CONFIG_WITH_ALLOC_CACHES
    519533      dir = xmalloc (sizeof (struct directory));
     
    523537#ifndef CONFIG_WITH_STRCACHE2
    524538#if defined(HAVE_CASE_INSENSITIVE_FS) && defined(VMS)
    525       dir->name = strcache_add_len (downcase(name), p - name);
     539      /* Todo: Why is this only needed on VMS? */
     540      {
     541        char *lname = downcase_inplace (xstrdup (name));
     542        dir->name = strcache_add_len (lname, p - name);
     543        free (lname);
     544      }
    526545#else
    527546      dir->name = strcache_add_len (name, p - name);
     
    532551      hash_insert_at (&directories, dir, dir_slot);
    533552      /* The directory is not in the name hash table.
    534          Find its device and inode numbers, and look it up by them.  */
    535 
    536 #ifdef VMS
    537       r = vmsstat_dir (name, &st);
    538 #elif defined(WINDOWS32)
     553         Find its device and inode numbers, and look it up by them.  */
     554
     555#if defined(WINDOWS32)
    539556      {
    540557        char tem[MAXPATHLEN], *tstart, *tend;
     
    559576      if (r < 0)
    560577        {
    561         /* Couldn't stat the directory.  Mark this by
    562            setting the `contents' member to a nil pointer.  */
    563           dir->contents = 0;
    564         }
     578        /* Couldn't stat the directory.  Mark this by
     579           setting the 'contents' member to a nil pointer.  */
     580          dir->contents = 0;
     581        }
    565582      else
    566         {
    567           /* Search the contents hash table; device and inode are the key.  */
    568 
    569           struct directory_contents *dc;
    570           struct directory_contents **dc_slot;
    571           struct directory_contents dc_key;
    572 
    573           dc_key.dev = st.st_dev;
     583        {
     584          /* Search the contents hash table; device and inode are the key.  */
     585
     586#ifdef WINDOWS32
     587          char *w32_path;
     588#endif
     589          struct directory_contents *dc;
     590          struct directory_contents **dc_slot;
     591          struct directory_contents dc_key;
     592
     593          dc_key.dev = st.st_dev;
    574594#ifdef WINDOWS32
    575595# ifndef CONFIG_WITH_STRCACHE2
     
    581601          dc_key.ctime = st.st_ctime;
    582602#else
    583 # ifdef VMS
    584           dc_key.ino[0] = st.st_ino[0];
    585           dc_key.ino[1] = st.st_ino[1];
    586           dc_key.ino[2] = st.st_ino[2];
     603# ifdef VMS_INO_T
     604          dc_key.ino[0] = st.st_ino[0];
     605          dc_key.ino[1] = st.st_ino[1];
     606          dc_key.ino[2] = st.st_ino[2];
    587607# else
    588           dc_key.ino = st.st_ino;
    589 # endif
    590 #endif
    591           dc_slot = (struct directory_contents **) hash_find_slot (&directory_contents, &dc_key);
    592           dc = *dc_slot;
    593 
    594           if (HASH_VACANT (dc))
    595             {
     608          dc_key.ino = st.st_ino;
     609# endif
     610#endif
     611          dc_slot = (struct directory_contents **) hash_find_slot (&directory_contents, &dc_key);
     612          dc = *dc_slot;
     613
     614          if (HASH_VACANT (dc))
     615            {
     616              /* Nope; this really is a directory we haven't seen before.  */
     617#ifdef WINDOWS32
     618              char  fs_label[BUFSIZ];
     619              char  fs_type[BUFSIZ];
     620              unsigned long  fs_serno;
     621              unsigned long  fs_flags;
     622              unsigned long  fs_len;
     623#endif
    596624#if defined(WINDOWS32) && defined(KMK)
    597625              static char s_last_volume[4];
    598626              static int  s_last_flags;
    599627#endif
    600               /* Nope; this really is a directory we haven't seen before.  */
    601628
    602629#ifndef CONFIG_WITH_ALLOC_CACHES
     
    608635#endif
    609636
    610               /* Enter it in the contents hash table.  */
    611               dc->dev = st.st_dev;
     637              /* Enter it in the contents hash table.  */
     638              dc->dev = st.st_dev;
    612639#ifdef WINDOWS32
    613640# ifndef CONFIG_WITH_STRCACHE2
     
    617644# endif /* CONFIG_WITH_STRCACHE2 */
    618645
    619               dc->ctime = st.st_ctime;
     646              dc->ctime = st.st_ctime;
    620647              dc->mtime = st.st_mtime;
    621648# ifdef KMK
     
    623650# endif
    624651
    625               /*
    626                * NTFS is the only WINDOWS32 filesystem that bumps mtime
    627                * on a directory when files are added/deleted from
    628                * a directory.
    629                */
     652              /* NTFS is the only WINDOWS32 filesystem that bumps mtime on a
     653                 directory when files are added/deleted from a directory.  */
    630654              w32_path[3] = '\0';
     655
    631656# ifdef KMK /* Need for speed: Cache the GetVolumeInformation result. */
    632657              if (   s_last_volume[0] == w32_path[0]
     
    638663                {
    639664# endif
    640               if (GetVolumeInformation(w32_path,
    641                      fs_label, sizeof (fs_label),
    642                      &fs_serno, &fs_len,
    643                      &fs_flags, fs_type, sizeof (fs_type)) == FALSE)
     665              if (GetVolumeInformation (w32_path, fs_label, sizeof (fs_label),
     666                                        &fs_serno, &fs_len, &fs_flags, fs_type,
     667                                        sizeof (fs_type)) == FALSE)
    644668                dc->fs_flags = FS_UNKNOWN;
    645               else if (!strcmp(fs_type, "FAT"))
     669              else if (!strcmp (fs_type, "FAT"))
    646670                dc->fs_flags = FS_FAT;
    647               else if (!strcmp(fs_type, "NTFS"))
     671              else if (!strcmp (fs_type, "NTFS"))
    648672                dc->fs_flags = FS_NTFS;
    649673              else
    650674                dc->fs_flags = FS_UNKNOWN;
    651675# ifdef KMK
    652                   s_last_volume[0] = w32_path[0];
    653                   s_last_volume[1] = w32_path[1];
    654                   s_last_volume[2] = w32_path[2];
    655                   s_last_volume[3] = w32_path[3];
    656                   s_last_flags     = dc->fs_flags;
    657                 }
    658 # endif
    659 #else
    660 # ifdef VMS
    661               dc->ino[0] = st.st_ino[0];
    662               dc->ino[1] = st.st_ino[1];
    663               dc->ino[2] = st.st_ino[2];
     676              s_last_volume[0] = w32_path[0];
     677              s_last_volume[1] = w32_path[1];
     678              s_last_volume[2] = w32_path[2];
     679              s_last_volume[3] = w32_path[3];
     680              s_last_flags     = dc->fs_flags;
     681# endif
     682#else
     683# ifdef VMS_INO_T
     684              dc->ino[0] = st.st_ino[0];
     685              dc->ino[1] = st.st_ino[1];
     686              dc->ino[2] = st.st_ino[2];
    664687# else
    665               dc->ino = st.st_ino;
     688              dc->ino = st.st_ino;
    666689# endif
    667690#endif /* WINDOWS32 */
    668               hash_insert_at (&directory_contents, dc, dc_slot);
    669               ENULLLOOP (dc->dirstream, opendir (name));
    670               if (dc->dirstream == 0)
     691              hash_insert_at (&directory_contents, dc, dc_slot);
     692              ENULLLOOP (dc->dirstream, opendir (name));
     693              if (dc->dirstream == 0)
    671694                /* Couldn't open the directory.  Mark this by setting the
    672                    `files' member to a nil pointer.  */
     695                   'files' member to a nil pointer.  */
    673696                dc->dirfiles.ht_vec = 0;
    674697              else
     
    682705#else
    683706# ifndef CONFIG_WITH_STRCACHE2
    684                   hash_init (&dc->dirfiles, DIRFILE_BUCKETS,
    685                              dirfile_hash_1, dirfile_hash_2, dirfile_hash_cmp);
     707                  hash_init (&dc->dirfiles, DIRFILE_BUCKETS,
     708                             dirfile_hash_1, dirfile_hash_2, dirfile_hash_cmp);
    686709# else  /* CONFIG_WITH_STRCACHE2 */
    687710                  hash_init_strcached (&dc->dirfiles, DIRFILE_BUCKETS,
     
    690713# endif /* CONFIG_WITH_STRCACHE2 */
    691714#endif
    692                   /* Keep track of how many directories are open.  */
    693                   ++open_directories;
    694                   if (open_directories == MAX_OPEN_DIRECTORIES)
    695                     /* We have too many directories open already.
    696                        Read the entire directory and then close it.  */
    697                     dir_contents_file_exists_p (dc, 0);
    698                 }
    699             }
    700 
    701           /* Point the name-hashed entry for DIR at its contents data.  */
    702           dir->contents = dc;
    703         }
     715                  ++open_directories;
     716                  if (open_directories == MAX_OPEN_DIRECTORIES)
     717                    /* We have too many directories open already.
     718                       Read the entire directory and then close it.  */
     719                    dir_contents_file_exists_p (dc, 0);
     720                }
     721            }
     722
     723          /* Point the name-hashed entry for DIR at its contents data.  */
     724          dir->contents = dc;
     725        }
    704726    }
    705727
     
    715737                            const char *filename)
    716738{
    717   /*unsigned int hash;*/
    718739  struct dirfile *df;
    719740  struct dirent *d;
     
    744765    _fnlwr (filename); /* lower case for FAT drives */
    745766#endif
    746 
    747 #ifdef VMS
    748   filename = vmsify (filename,0);
    749 #endif
    750 
    751   /*hash = 0;*/
    752767  if (filename != 0)
    753768    {
     
    755770
    756771      if (*filename == '\0')
    757         {
    758           /* Checking if the directory exists.  */
    759           return 1;
    760         }
     772        {
     773          /* Checking if the directory exists.  */
     774          return 1;
     775        }
    761776#ifndef CONFIG_WITH_STRCACHE2
    762777      dirfile_key.name = filename;
     
    789804      if (dir->path_key)
    790805# endif
    791         {
     806        {
    792807          if ((dir->fs_flags & FS_FAT) != 0)
    793808            {
     
    801816          else if (stat (dir->path_key, &st) == 0 && st.st_mtime > dir->mtime)
    802817# endif
    803             {
    804               /* reset date stamp to show most recent re-process.  */
    805               dir->mtime = st.st_mtime;
    806               rehash = 1;
    807             }
     818            {
     819              /* reset date stamp to show most recent re-process.  */
     820              dir->mtime = st.st_mtime;
     821              rehash = 1;
     822            }
    808823
    809824
    810825          /* If it has been already read in, all done.  */
    811           if (!rehash)
    812             return 0;
     826          if (!rehash)
     827            return 0;
    813828
    814829          /* make sure directory can still be opened; if not return.  */
     
    819834          dc->last_updated = time(NULL);
    820835# endif
    821         }
     836        }
    822837      else
    823838#endif
    824         /* The directory has been all read in.  */
    825         return 0;
     839        /* The directory has been all read in.  */
     840        return 0;
    826841    }
    827842
     
    857872/* bird: end */
    858873          if (errno)
    859             fatal (NILF, "INTERNAL: readdir(%p): %s (filename=%s)\n", (void *)dir, strerror (errno), filename);
     874            pfatal_with_name ("INTERNAL: readdir");
    860875          break;
    861876        }
    862877
    863878#if defined(VMS) && defined(HAVE_DIRENT_H)
    864       /* In VMS we get file versions too, which have to be stripped off */
     879      /* In VMS we get file versions too, which have to be stripped off.
     880         Some versions of VMS return versions on Unix files even when
     881         the feature option to strip them is set.  */
    865882      {
    866883        char *p = strrchr (d->d_name, ';');
     
    870887#endif
    871888      if (!REAL_DIR_ENTRY (d))
    872         continue;
     889        continue;
    873890
    874891      len = NAMLEN (d);
     
    895912        {
    896913#ifndef CONFIG_WITH_ALLOC_CACHES
    897           df = xmalloc (sizeof (struct dirfile));
     914          df = xmalloc (sizeof (struct dirfile));
    898915#else
    899916          df = alloccache_alloc (&dirfile_cache);
     
    901918#ifndef CONFIG_WITH_STRCACHE2
    902919#if defined(HAVE_CASE_INSENSITIVE_FS) && defined(VMS)
    903           df->name = strcache_add_len (downcase(d->d_name), len);
    904 #else
    905           df->name = strcache_add_len (d->d_name, len);
     920          /* TODO: Why is this only needed on VMS? */
     921          df->name = strcache_add_len (downcase_inplace (d->d_name), len);
     922#else
     923          df->name = strcache_add_len (d->d_name, len);
    906924#endif
    907925#else  /* CONFIG_WITH_STRCACHE2 */
    908926          df->name = dirfile_key.name;
    909927#endif /* CONFIG_WITH_STRCACHE2 */
    910           df->length = len;
    911           df->impossible = 0;
    912           hash_insert_at (&dir->dirfiles, df, dirfile_slot);
    913         }
     928          df->length = len;
     929          df->impossible = 0;
     930          hash_insert_at (&dir->dirfiles, df, dirfile_slot);
     931        }
    914932      /* Check if the name matches the one we're searching for.  */
    915933#ifndef CONFIG_WITH_STRCACHE2
     
    947965dir_file_exists_p (const char *dirname, const char *filename)
    948966{
     967#ifdef VMS
     968  if ((filename != NULL) && (dirname != NULL))
     969    {
     970      int want_vmsify;
     971      want_vmsify = (strpbrk (dirname, ":<[") != NULL);
     972      if (want_vmsify)
     973        filename = vmsify (filename, 0);
     974    }
     975#endif
    949976  return dir_contents_file_exists_p (find_directory (dirname)->contents,
    950                                      filename);
     977                                     filename);
    951978}
    952979
     
    961988  const char *slash;
    962989
    963 #ifndef NO_ARCHIVES
     990#ifndef NO_ARCHIVES
    964991  if (ar_name (name))
    965992    return ar_member_date (name) != (time_t) -1;
    966993#endif
    967994
     995  dirend = strrchr (name, '/');
    968996#ifdef VMS
    969   dirend = strrchr (name, ']');
    970997  if (dirend == 0)
    971     dirend = strrchr (name, ':');
     998    {
     999      dirend = strrchr (name, ']');
     1000      dirend == NULL ? dirend : dirend++;
     1001    }
    9721002  if (dirend == 0)
    973     return dir_file_exists_p ("[]", name);
    974 #else /* !VMS */
    975   dirend = strrchr (name, '/');
     1003    {
     1004      dirend = strrchr (name, '>');
     1005      dirend == NULL ? dirend : dirend++;
     1006    }
     1007  if (dirend == 0)
     1008    {
     1009      dirend = strrchr (name, ':');
     1010      dirend == NULL ? dirend : dirend++;
     1011    }
     1012#endif /* VMS */
    9761013#ifdef HAVE_DOS_PATHS
    9771014  /* Forward and backslashes might be mixed.  We need the rightmost one.  */
    9781015  {
    979     const char *bslash = strrchr(name, '\\');
     1016    const char *bslash = strrchr (name, '\\');
    9801017    if (!dirend || bslash > dirend)
    9811018      dirend = bslash;
     
    9881025#ifndef _AMIGA
    9891026    return dir_file_exists_p (".", name);
    990 #else /* !VMS && !AMIGA */
     1027#else /* !AMIGA */
    9911028    return dir_file_exists_p ("", name);
    9921029#endif /* AMIGA */
    993 #endif /* VMS */
    9941030
    9951031  slash = dirend;
     
    10021038  /* d:/ and d: are *very* different...  */
    10031039      if (dirend < name + 3 && name[1] == ':' &&
    1004           (*dirend == '/' || *dirend == '\\' || *dirend == ':'))
    1005         dirend++;
     1040          (*dirend == '/' || *dirend == '\\' || *dirend == ':'))
     1041        dirend++;
    10061042#endif
    10071043      p = alloca (dirend - name + 1);
     
    10101046      dirname = p;
    10111047    }
    1012   return dir_file_exists_p (dirname, slash + 1);
    1013 }
    1014 
    1015 
    1016 /* Mark FILENAME as `impossible' for `file_impossible_p'.
     1048#ifdef VMS
     1049  if (*slash == '/')
     1050    slash++;
     1051#else
     1052  slash++;
     1053#endif
     1054  return dir_file_exists_p (dirname, slash);
     1055}
     1056
     1057
     1058/* Mark FILENAME as 'impossible' for 'file_impossible_p'.
    10171059   This means an attempt has been made to search for FILENAME
    10181060   as an intermediate file, and it has failed.  */
     
    10261068  struct dirfile *new;
    10271069
     1070  dirend = strrchr (p, '/');
    10281071#ifdef VMS
    1029   dirend = strrchr (p, ']');
    1030   if (dirend == 0)
    1031     dirend = strrchr (p, ':');
    1032   dirend++;
    1033   if (dirend == (char *)1)
    1034     dir = find_directory ("[]");
    1035 #else
    1036   dirend = strrchr (p, '/');
    1037 # ifdef HAVE_DOS_PATHS
     1072  if (dirend == NULL)
     1073    {
     1074      dirend = strrchr (p, ']');
     1075      dirend == NULL ? dirend : dirend++;
     1076    }
     1077  if (dirend == NULL)
     1078    {
     1079      dirend = strrchr (p, '>');
     1080      dirend == NULL ? dirend : dirend++;
     1081    }
     1082  if (dirend == NULL)
     1083    {
     1084      dirend = strrchr (p, ':');
     1085      dirend == NULL ? dirend : dirend++;
     1086    }
     1087#endif
     1088#ifdef HAVE_DOS_PATHS
    10381089  /* Forward and backslashes might be mixed.  We need the rightmost one.  */
    10391090  {
    1040     const char *bslash = strrchr(p, '\\');
     1091    const char *bslash = strrchr (p, '\\');
    10411092    if (!dirend || bslash > dirend)
    10421093      dirend = bslash;
     
    10451096      dirend = p + 1;
    10461097  }
    1047 # endif /* HAVE_DOS_PATHS */
     1098#endif /* HAVE_DOS_PATHS */
    10481099  if (dirend == 0)
    1049 # ifdef _AMIGA
     1100#ifdef _AMIGA
    10501101    dir = find_directory ("");
    1051 # else /* !VMS && !AMIGA */
     1102#else /* !AMIGA */
    10521103    dir = find_directory (".");
    1053 # endif /* AMIGA */
    1054 #endif /* VMS */
     1104#endif /* AMIGA */
    10551105  else
    10561106    {
     
    10581108      const char *slash = dirend;
    10591109      if (dirend == p)
    1060         dirname = "/";
     1110        dirname = "/";
    10611111      else
    1062         {
     1112        {
    10631113          char *cp;
    10641114#ifdef HAVE_DOS_PATHS
    1065           /* d:/ and d: are *very* different...  */
    1066           if (dirend < p + 3 && p[1] == ':' &&
    1067               (*dirend == '/' || *dirend == '\\' || *dirend == ':'))
    1068             dirend++;
    1069 #endif
    1070           cp = alloca (dirend - p + 1);
    1071           memcpy (cp, p, dirend - p);
    1072           cp[dirend - p] = '\0';
     1115          /* d:/ and d: are *very* different...  */
     1116          if (dirend < p + 3 && p[1] == ':' &&
     1117              (*dirend == '/' || *dirend == '\\' || *dirend == ':'))
     1118            dirend++;
     1119#endif
     1120          cp = alloca (dirend - p + 1);
     1121          memcpy (cp, p, dirend - p);
     1122          cp[dirend - p] = '\0';
    10731123          dirname = cp;
    1074         }
     1124        }
    10751125      dir = find_directory (dirname);
     1126#ifdef VMS
     1127      if (*slash == '/')
     1128        filename = p = slash + 1;
     1129      else
     1130        filename = p = slash;
     1131#else
    10761132      filename = p = slash + 1;
     1133#endif
    10771134    }
    10781135
     
    10901147#ifndef CONFIG_WITH_STRCACHE2
    10911148      hash_init (&dir->contents->dirfiles, DIRFILE_BUCKETS,
    1092                 dirfile_hash_1, dirfile_hash_2, dirfile_hash_cmp);
     1149                dirfile_hash_1, dirfile_hash_2, dirfile_hash_cmp);
    10931150#else  /* CONFIG_WITH_STRCACHE2 */
    10941151      hash_init_strcached (&dir->contents->dirfiles, DIRFILE_BUCKETS,
     
    11061163  new->length = strlen (filename);
    11071164#if defined(HAVE_CASE_INSENSITIVE_FS) && defined(VMS)
    1108   new->name = strcache_add_len (downcase(filename), new->length);
     1165  /* todo: Why is this only needed on VMS? */
     1166  new->name = strcache_add_len (downcase (filename), new->length);
    11091167#else
    11101168  new->name = strcache_add_len (filename, new->length);
     
    11251183{
    11261184  const char *dirend;
    1127   const char *p = filename;
    11281185  struct directory_contents *dir;
    11291186  struct dirfile *dirfile;
    11301187  struct dirfile dirfile_key;
    1131 
    11321188#ifdef VMS
    1133   dirend = strrchr (filename, ']');
    1134   if (dirend == 0)
    1135     dir = find_directory ("[]")->contents;
    1136 #else
     1189  int want_vmsify = 0;
     1190#endif
     1191
    11371192  dirend = strrchr (filename, '/');
     1193#ifdef VMS
     1194  if (dirend == NULL)
     1195    {
     1196      want_vmsify = (strpbrk (filename, "]>:^") != NULL);
     1197      dirend = strrchr (filename, ']');
     1198    }
     1199  if (dirend == NULL && want_vmsify)
     1200    dirend = strrchr (filename, '>');
     1201  if (dirend == NULL && want_vmsify)
     1202    dirend = strrchr (filename, ':');
     1203#endif
    11381204#ifdef HAVE_DOS_PATHS
    11391205  /* Forward and backslashes might be mixed.  We need the rightmost one.  */
    11401206  {
    1141     const char *bslash = strrchr(filename, '\\');
     1207    const char *bslash = strrchr (filename, '\\');
    11421208    if (!dirend || bslash > dirend)
    11431209      dirend = bslash;
     
    11501216#ifdef _AMIGA
    11511217    dir = find_directory ("")->contents;
    1152 #else /* !VMS && !AMIGA */
     1218#else /* !AMIGA */
    11531219    dir = find_directory (".")->contents;
    11541220#endif /* AMIGA */
    1155 #endif /* VMS */
    11561221  else
    11571222    {
     
    11591224      const char *slash = dirend;
    11601225      if (dirend == filename)
    1161         dirname = "/";
     1226        dirname = "/";
    11621227      else
    1163         {
     1228        {
    11641229          char *cp;
    11651230#ifdef HAVE_DOS_PATHS
    1166           /* d:/ and d: are *very* different...  */
    1167           if (dirend < filename + 3 && filename[1] == ':' &&
    1168               (*dirend == '/' || *dirend == '\\' || *dirend == ':'))
    1169             dirend++;
    1170 #endif
    1171           cp = alloca (dirend - filename + 1);
    1172           memcpy (cp, p, dirend - p);
    1173           cp[dirend - p] = '\0';
     1231          /* d:/ and d: are *very* different...  */
     1232          if (dirend < filename + 3 && filename[1] == ':' &&
     1233              (*dirend == '/' || *dirend == '\\' || *dirend == ':'))
     1234            dirend++;
     1235#endif
     1236          cp = alloca (dirend - filename + 1);
     1237          memcpy (cp, filename, dirend - filename);
     1238          cp[dirend - filename] = '\0';
    11741239          dirname = cp;
    1175         }
     1240        }
    11761241      dir = find_directory (dirname)->contents;
    1177       p = filename = slash + 1;
     1242#ifdef VMS
     1243      if (*slash == '/')
     1244        filename = slash + 1;
     1245      else
     1246        filename = slash;
     1247#else
     1248      filename = slash + 1;
     1249#endif
    11781250    }
    11791251
     
    11831255
    11841256#ifdef __MSDOS__
    1185   filename = dosify (p);
     1257  filename = dosify (filename);
    11861258#endif
    11871259#ifdef HAVE_CASE_INSENSITIVE_FS
    1188   filename = downcase (p);
     1260  filename = downcase (filename);
    11891261#endif
    11901262#ifdef VMS
    1191   filename = vmsify (p, 1);
     1263  if (want_vmsify)
     1264    filename = vmsify (filename, 1);
    11921265#endif
    11931266
     
    12381311      struct directory *dir = *dir_slot;
    12391312      if (! HASH_VACANT (dir))
    1240         {
    1241           if (dir->contents == 0)
    1242             printf (_("# %s: could not be stat'd.\n"), dir->name);
    1243           else if (dir->contents->dirfiles.ht_vec == 0)
    1244             {
     1313        {
     1314          if (dir->contents == 0)
     1315            printf (_("# %s: could not be stat'd.\n"), dir->name);
     1316          else if (dir->contents->dirfiles.ht_vec == 0)
     1317            {
    12451318#ifdef WINDOWS32
    1246               printf (_("# %s (key %s, mtime %d): could not be opened.\n"),
    1247                       dir->name, dir->contents->path_key,dir->contents->mtime);
     1319              printf (_("# %s (key %s, mtime %I64u): could not be opened.\n"),
     1320                      dir->name, dir->contents->path_key,
     1321                      (unsigned long long)dir->contents->mtime);
    12481322#else  /* WINDOWS32 */
    1249 #ifdef VMS
    1250               printf (_("# %s (device %d, inode [%d,%d,%d]): could not be opened.\n"),
    1251                       dir->name, dir->contents->dev,
    1252                       dir->contents->ino[0], dir->contents->ino[1],
    1253                       dir->contents->ino[2]);
    1254 #else
    1255               printf (_("# %s (device %ld, inode %ld): could not be opened.\n"),
    1256                       dir->name, (long int) dir->contents->dev,
    1257                       (long int) dir->contents->ino);
     1323#ifdef VMS_INO_T
     1324              printf (_("# %s (device %d, inode [%d,%d,%d]): could not be opened.\n"),
     1325                      dir->name, dir->contents->dev,
     1326                      dir->contents->ino[0], dir->contents->ino[1],
     1327                      dir->contents->ino[2]);
     1328#else
     1329              printf (_("# %s (device %ld, inode %ld): could not be opened.\n"),
     1330                      dir->name, (long int) dir->contents->dev,
     1331                      (long int) dir->contents->ino);
    12581332#endif
    12591333#endif /* WINDOWS32 */
    1260             }
    1261           else
    1262             {
    1263               unsigned int f = 0;
    1264               unsigned int im = 0;
    1265               struct dirfile **files_slot;
    1266               struct dirfile **files_end;
    1267 
    1268               files_slot = (struct dirfile **) dir->contents->dirfiles.ht_vec;
    1269               files_end = files_slot + dir->contents->dirfiles.ht_size;
    1270               for ( ; files_slot < files_end; files_slot++)
    1271                 {
    1272                   struct dirfile *df = *files_slot;
    1273                   if (! HASH_VACANT (df))
    1274                     {
    1275                       if (df->impossible)
    1276                         ++im;
    1277                       else
    1278                         ++f;
    1279                     }
    1280                 }
     1334            }
     1335          else
     1336            {
     1337              unsigned int f = 0;
     1338              unsigned int im = 0;
     1339              struct dirfile **files_slot;
     1340              struct dirfile **files_end;
     1341
     1342              files_slot = (struct dirfile **) dir->contents->dirfiles.ht_vec;
     1343              files_end = files_slot + dir->contents->dirfiles.ht_size;
     1344              for ( ; files_slot < files_end; files_slot++)
     1345                {
     1346                  struct dirfile *df = *files_slot;
     1347                  if (! HASH_VACANT (df))
     1348                    {
     1349                      if (df->impossible)
     1350                        ++im;
     1351                      else
     1352                        ++f;
     1353                    }
     1354                }
    12811355#ifdef WINDOWS32
    1282               printf (_("# %s (key %s, mtime %d): "),
    1283                       dir->name, dir->contents->path_key, dir->contents->mtime);
     1356              printf (_("# %s (key %s, mtime %I64u): "),
     1357                      dir->name, dir->contents->path_key,
     1358                      (unsigned long long)dir->contents->mtime);
    12841359#else  /* WINDOWS32 */
    1285 #ifdef VMS
    1286               printf (_("# %s (device %d, inode [%d,%d,%d]): "),
    1287                       dir->name, dir->contents->dev,
    1288                       dir->contents->ino[0], dir->contents->ino[1],
    1289                       dir->contents->ino[2]);
    1290 #else
    1291               printf (_("# %s (device %ld, inode %ld): "),
    1292                       dir->name,
    1293                       (long)dir->contents->dev, (long)dir->contents->ino);
     1360#ifdef VMS_INO_T
     1361              printf (_("# %s (device %d, inode [%d,%d,%d]): "),
     1362                      dir->name, dir->contents->dev,
     1363                      dir->contents->ino[0], dir->contents->ino[1],
     1364                      dir->contents->ino[2]);
     1365#else
     1366              printf (_("# %s (device %ld, inode %ld): "),
     1367                      dir->name,
     1368                      (long)dir->contents->dev, (long)dir->contents->ino);
    12941369#endif
    12951370#endif /* WINDOWS32 */
    1296               if (f == 0)
    1297                 fputs (_("No"), stdout);
    1298               else
    1299                 printf ("%u", f);
    1300               fputs (_(" files, "), stdout);
    1301               if (im == 0)
    1302                 fputs (_("no"), stdout);
    1303               else
    1304                 printf ("%u", im);
    1305               fputs (_(" impossibilities"), stdout);
    1306               if (dir->contents->dirstream == 0)
    1307                 puts (".");
    1308               else
    1309                 puts (_(" so far."));
    1310               files += f;
    1311               impossible += im;
     1371              if (f == 0)
     1372                fputs (_("No"), stdout);
     1373              else
     1374                printf ("%u", f);
     1375              fputs (_(" files, "), stdout);
     1376              if (im == 0)
     1377                fputs (_("no"), stdout);
     1378              else
     1379                printf ("%u", im);
     1380              fputs (_(" impossibilities"), stdout);
     1381              if (dir->contents->dirstream == 0)
     1382                puts (".");
     1383              else
     1384                puts (_(" so far."));
     1385              files += f;
     1386              impossible += im;
    13121387#ifdef KMK
    13131388              fputs ("# ", stdout);
     
    13151390              fputs ("\n", stdout);
    13161391#endif
    1317             }
    1318         }
     1392            }
     1393        }
    13191394    }
    13201395
     
    13521427/* Hooks for globbing.  */
    13531428
    1354 #include <glob.h>
    1355 
    13561429/* Structure describing state of iterating through a directory hash table.  */
    13571430
     
    14031476      struct dirfile *df = *ds->dirfile_slot++;
    14041477      if (! HASH_VACANT (df) && !df->impossible)
    1405         {
    1406           /* The glob interface wants a `struct dirent', so mock one up.  */
    1407           struct dirent *d;
    1408           unsigned int len = df->length + 1;
     1478        {
     1479          /* The glob interface wants a 'struct dirent', so mock one up.  */
     1480          struct dirent *d;
     1481          unsigned int len = df->length + 1;
    14091482          unsigned int sz = sizeof (*d) - sizeof (d->d_name) + len;
    1410           if (sz > bufsz)
    1411             {
    1412               bufsz *= 2;
    1413               if (sz > bufsz)
    1414                 bufsz = sz;
    1415               buf = xrealloc (buf, bufsz);
    1416             }
    1417           d = (struct dirent *) buf;
     1483          if (sz > bufsz)
     1484            {
     1485              bufsz *= 2;
     1486              if (sz > bufsz)
     1487                bufsz = sz;
     1488              buf = xrealloc (buf, bufsz);
     1489            }
     1490          d = (struct dirent *) buf;
    14181491#ifdef __MINGW32__
    14191492# if __MINGW32_MAJOR_VERSION < 3 || (__MINGW32_MAJOR_VERSION == 3 && \
    1420                                      __MINGW32_MINOR_VERSION == 0)
    1421           d->d_name = xmalloc(len);
    1422 # endif
    1423 #endif
    1424           FAKE_DIR_ENTRY (d);
     1493                                     __MINGW32_MINOR_VERSION == 0)
     1494          d->d_name = xmalloc (len);
     1495# endif
     1496#endif
     1497          FAKE_DIR_ENTRY (d);
    14251498#ifdef _DIRENT_HAVE_D_NAMLEN
    1426           d->d_namlen = len - 1;
     1499          d->d_namlen = len - 1;
    14271500#endif
    14281501#ifdef _DIRENT_HAVE_D_TYPE
    1429           d->d_type = DT_UNKNOWN;
    1430 #endif
    1431           memcpy (d->d_name, df->name, len);
    1432           return d;
    1433         }
     1502          d->d_type = DT_UNKNOWN;
     1503#endif
     1504          memcpy (d->d_name, df->name, len);
     1505          return d;
     1506        }
    14341507    }
    14351508
    14361509  return 0;
    1437 }
    1438 
    1439 static void
    1440 ansi_free (void *p)
    1441 {
    1442   if (p)
    1443     free(p);
    14441510}
    14451511
     
    14471513 * macro for stat64().  If stat is a macro, make a local wrapper function to
    14481514 * invoke it.
     1515 *
     1516 * On MS-Windows, stat() "succeeds" for foo/bar/. where foo/bar is a
     1517 * regular file; fix that here.
    14491518 */
    1450 #ifndef stat
     1519#if !defined(stat) && !defined(WINDOWS32) || defined(VMS)
    14511520# ifndef VMS
     1521#  ifndef HAVE_SYS_STAT_H
    14521522int stat (const char *path, struct stat *sbuf);
     1523#  endif
     1524# else
     1525    /* We are done with the fake stat.  Go back to the real stat */
     1526#   ifdef stat
     1527#     undef stat
     1528#   endif
    14531529# endif
    14541530# define local_stat stat
     
    14581534{
    14591535  int e;
     1536#ifdef WINDOWS32
     1537  size_t plen = strlen (path);
     1538
     1539  /* Make sure the parent of "." exists and is a directory, not a
     1540     file.  This is because 'stat' on Windows normalizes the argument
     1541     foo/. => foo without checking first that foo is a directory.  */
     1542  if (plen > 1 && path[plen - 1] == '.'
     1543      && (path[plen - 2] == '/' || path[plen - 2] == '\\'))
     1544    {
     1545      char parent[MAXPATHLEN];
     1546
     1547      strncpy (parent, path, plen - 2);
     1548      parent[plen - 2] = '\0';
     1549      if (stat (parent, buf) < 0 || !_S_ISDIR (buf->st_mode))
     1550        return -1;
     1551    }
     1552#endif
    14601553
    14611554  EINTRLOOP (e, stat (path, buf));
     
    14821575  gl->gl_opendir = open_dirstream;
    14831576  gl->gl_readdir = read_dirstream;
    1484   gl->gl_closedir = ansi_free;
     1577  gl->gl_closedir = free;
    14851578  gl->gl_stat = local_stat;
    14861579#ifdef __EMX__ /* The FreeBSD implementation actually uses gl_lstat!! */
     
    15001593#ifndef CONFIG_WITH_STRCACHE2
    15011594  hash_init (&directories, DIRECTORY_BUCKETS,
    1502              directory_hash_1, directory_hash_2, directory_hash_cmp);
     1595             directory_hash_1, directory_hash_2, directory_hash_cmp);
    15031596#else  /* CONFIG_WITH_STRCACHE2 */
    15041597  hash_init_strcached (&directories, DIRECTORY_BUCKETS, &file_strcache,
     
    15061599#endif /* CONFIG_WITH_STRCACHE2 */
    15071600  hash_init (&directory_contents, DIRECTORY_BUCKETS,
    1508              directory_contents_hash_1, directory_contents_hash_2,
     1601             directory_contents_hash_1, directory_contents_hash_2,
    15091602             directory_contents_hash_cmp);
    15101603#ifdef CONFIG_WITH_ALLOC_CACHES
  • trunk/src/kmk/doc/Makefile.am

    r2591 r3140  
    11# -*-Makefile-*-, or close enough
    2 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    3 # 2010 Free Software Foundation, Inc.
     2# Copyright (C) 2000-2016 Free Software Foundation, Inc.
    43# This file is part of GNU Make.
    54#
     
    2423
    2524CLEANFILES = make*.html
    26 
    27 ## ----------------------------- ##
    28 ## Other documentation formats.  ##
    29 ## ----------------------------- ##
    30 
    31 html: make_1.html
    32 
    33 make_1.html: $(info_TEXINFOS) $(make_TEXINFOS)
    34         $(TEXI2HTML) $(TEXI2HTML_FLAGS) $(srcdir)/make.texi
    35 
    36 .PHONY: html
  • trunk/src/kmk/doc/make.texi

    r2591 r3140  
    44
    55@include version.texi
    6 @set EDITION 0.71
    7 @set RCSID $Id: make.texi,v 1.66 2010/07/19 07:10:54 psmith Exp $
     6@set EDITION 0.74
    87
    98@settitle GNU @code{make}
     
    2827Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
    29281996, 1997, 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007,
    30 2008, 2009, 2010 Free Software Foundation, Inc.
     292008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Free Software
     30Foundation, Inc.
    3131
    3232@quotation
    3333Permission is granted to copy, distribute and/or modify this document
    34 under the terms of the GNU Free Documentation License, Version 1.2 or
     34under the terms of the GNU Free Documentation License, Version 1.3 or
    3535any later version published by the Free Software Foundation; with no
    3636Invariant Sections, with the Front-Cover Texts being ``A GNU Manual,''
     
    101101                                  based on their file names.
    102102* Archives::                    How @code{make} can update library archives.
     103* Extending make::              Using extensions to @code{make}.
     104* Integrating make::            Integrating @code{make} with other tools.
    103105* Features::                    Features GNU @code{make} has over other @code{make}s.
    104106* Missing::                     What GNU @code{make} lacks from other @code{make}s.
     
    110112                                  but nontrivial, makefile.
    111113
    112 * GNU Free Documentation License::  License for copying this manual
    113 * Concept Index::               Index of Concepts
    114 * Name Index::                  Index of Functions, Variables, & Directives
     114* GNU Free Documentation License::  License for copying this manual.
     115* Concept Index::               Index of Concepts.
     116* Name Index::                  Index of Functions, Variables, & Directives.
    115117
    116118@detailmenu
     
    119121Overview of @code{make}
    120122
    121 * Preparing::                   Preparing and running make
    122 * Reading::                     On reading this text
    123 * Bugs::                        Problems and bugs
     123* Preparing::                   Preparing and running @code{make}.
     124* Reading::                     On reading this text.
     125* Bugs::                        Problems and bugs.
    124126
    125127An Introduction to Makefiles
    126128
    127129* Rule Introduction::           What a rule looks like.
    128 * Simple Makefile::             A simple makefile
    129 * How Make Works::              How @code{make} processes this makefile
    130 * Variables Simplify::          Variables make makefiles simpler
    131 * make Deduces::                Letting @code{make} deduce the recipe
    132 * Combine By Prerequisite::     Another style of makefile
    133 * Cleanup::                     Rules for cleaning the directory
     130* Simple Makefile::             A simple makefile.
     131* How Make Works::              How @code{make} processes this makefile.
     132* Variables Simplify::          Variables make makefiles simpler.
     133* make Deduces::                Letting @code{make} deduce the recipes.
     134* Combine By Prerequisite::     Another style of makefile.
     135* Cleanup::                     Rules for cleaning the directory.
    134136
    135137Writing Makefiles
     
    144146* Reading Makefiles::           How makefiles are parsed.
    145147* Secondary Expansion::         How and when secondary expansion is performed.
     148
     149What Makefiles Contain
     150
     151* Splitting Lines::             Splitting long lines in makefiles
    146152
    147153Writing Rules
     
    171177Using Wildcard Characters in File Names
    172178
    173 * Wildcard Examples::           Several examples
     179* Wildcard Examples::           Several examples.
    174180* Wildcard Pitfall::            Problems to avoid.
    175181* Wildcard Function::           How to cause wildcard expansion where
     
    207213Recipe Syntax
    208214
    209 * Splitting Lines::             Breaking long recipe lines for readability.
     215* Splitting Recipe Lines::      Breaking long recipe lines for readability.
    210216* Variables in Recipes::        Using @code{make} variables in recipes.
    211217
    212218Recipe Execution
    213219
     220* One Shell::                   One shell for all lines in a recipe.
    214221* Choosing the Shell::          How @code{make} chooses the shell used
    215222                                  to run recipes.
     223
     224Parallel Execution
     225
     226* Parallel Output::             Handling output during parallel execution
     227* Parallel Input::              Handling input during parallel execution
    216228
    217229Recursive Use of @code{make}
     
    236248* Multi-Line::                  An alternate way to set a variable
    237249                                  to a multi-line string.
     250* Undefine Directive::          How to undefine a variable so that it appears
     251                                  as if it was never set.
    238252* Environment::                 Variable values can come from the environment.
    239253* Target-specific::             Variable values can be defined on a per-target
     
    263277* Conditional Functions::       Functions that implement conditions.
    264278* Foreach Function::            Repeat some text with controlled variation.
     279* File Function::               Write text to a file.
    265280* Call Function::               Expand a user-defined function.
    266281* Value Function::              Return the un-expanded value of a variable.
     
    268283* Origin Function::             Find where a variable got its value.
    269284* Flavor Function::             Find out the flavor of a variable.
     285* Make Control Functions::      Functions that control how make runs.
    270286* Shell Function::              Substitute the output of a shell command.
    271 * Make Control Functions::      Functions that control how make runs.
     287* Guile Function::              Use GNU Guile embedded scripting language.
    272288
    273289How to Run @code{make}
     
    290306
    291307* Using Implicit::              How to use an existing implicit rule
    292                                   to get the recipe for updating a file.
    293 * Catalogue of Rules::          A list of built-in implicit rules.
     308                                  to get the recipes for updating a file.
     309* Catalogue of Rules::          A list of built-in rules.
    294310* Implicit Variables::          How to change what predefined rules do.
    295311* Chained Rules::               How to use a chain of implicit rules.
     
    325341* Archive Symbols::             How to update archive symbol directories.
    326342
     343Extending GNU @code{make}
     344
     345* Guile Integration::           Using Guile as an embedded scripting language.
     346* Loading Objects::             Loading dynamic objects as extensions.
     347
     348GNU Guile Integration
     349
     350* Guile Types::                 Converting Guile types to @code{make} strings.
     351* Guile Interface::             Invoking @code{make} functions from Guile.
     352* Guile Example::               Example using Guile in @code{make}.
     353
     354Loading Dynamic Objects
     355
     356* load Directive::              Loading dynamic objects as extensions.
     357* Remaking Loaded Objects::     How loaded objects get remade.
     358* Loaded Object API::           Programmatic interface for loaded objects.
     359* Loaded Object Example::       Example of a loaded object
     360
     361Integrating GNU @code{make}
     362
     363* Job Slots::                   Share job slots with GNU @code{make}.
     364* Terminal Output::             Control output to terminals.
     365
     366Sharing Job Slots with GNU @code{make}
     367
     368* POSIX Jobserver::             Using the jobserver on POSIX systems.
     369* Windows Jobserver::           Using the jobserver on Windows systems.
     370
    327371@end detailmenu
    328372@end menu
     
    351395
    352396@menu
    353 * Preparing::                   Preparing and Running Make
    354 * Reading::                     On Reading this Text
    355 * Bugs::                        Problems and Bugs
     397* Preparing::                   Preparing and running @code{make}.
     398* Reading::                     On reading this text.
     399* Bugs::                        Problems and bugs.
    356400@end menu
    357401
     
    487531@menu
    488532* Rule Introduction::           What a rule looks like.
    489 * Simple Makefile::             A Simple Makefile
    490 * How Make Works::              How @code{make} Processes This Makefile
    491 * Variables Simplify::          Variables Make Makefiles Simpler
    492 * make Deduces::                Letting @code{make} Deduce the Recipes
    493 * Combine By Prerequisite::     Another Style of Makefile
    494 * Cleanup::                     Rules for Cleaning the Directory
     533* Simple Makefile::             A simple makefile.
     534* How Make Works::              How @code{make} processes this makefile.
     535* Variables Simplify::          Variables make makefiles simpler.
     536* make Deduces::                Letting @code{make} deduce the recipes.
     537* Combine By Prerequisite::     Another style of makefile.
     538* Cleanup::                     Rules for cleaning the directory.
    495539@end menu
    496540
     
    592636
    593637@noindent
    594 We split each long line into two lines using backslash-newline; this is
    595 like using one long line, but is easier to read.
     638We split each long line into two lines using backslash/newline; this is
     639like using one long line, but is easier to read.  @xref{Splitting Lines,
     640, Splitting Long Lines}.
    596641@cindex continuation lines
    597642@cindex @code{\} (backslash), for continuation lines
     
    10271072@end itemize
    10281073
     1074@menu
     1075* Splitting Lines::             Splitting long lines in makefiles
     1076@end menu
     1077
     1078@node Splitting Lines,  , Makefile Contents, Makefile Contents
     1079@subsection Splitting Long Lines
     1080@cindex splitting long lines
     1081@cindex long lines, splitting
     1082@cindex backslash (@code{\}), to quote newlines
     1083
     1084Makefiles use a ``line-based'' syntax in which the newline character
     1085is special and marks the end of a statement.  GNU @code{make} has no
     1086limit on the length of a statement line, up to the amount of memory in
     1087your computer.
     1088
     1089However, it is difficult to read lines which are too long to display
     1090without wrapping or scrolling.  So, you can format your makefiles for
     1091readability by adding newlines into the middle of a statement: you do
     1092this by escaping the internal newlines with a backslash (@code{\})
     1093character.  Where we need to make a distinction we will refer to
     1094``physical lines'' as a single line ending with a newline (regardless
     1095of whether it is escaped) and a ``logical line'' being a complete
     1096statement including all escaped newlines up to the first non-escaped
     1097newline.
     1098
     1099The way in which backslash/newline combinations are handled depends on
     1100whether the statement is a recipe line or a non-recipe line.  Handling
     1101of backslash/newline in a recipe line is discussed later
     1102(@pxref{Splitting Recipe Lines}).
     1103
     1104Outside of recipe lines, backslash/newlines are converted into a
     1105single space character.  Once that is done, all whitespace around the
     1106backslash/newline is condensed into a single space: this includes all
     1107whitespace preceding the backslash, all whitespace at the beginning of
     1108the line after the backslash/newline, and any consecutive
     1109backslash/newline combinations.
     1110
     1111If the @code{.POSIX} special target is defined then backslash/newline
     1112handling is modified slightly to conform to POSIX.2: first, whitespace
     1113preceding a backslash is not removed and second, consecutive
     1114backslash/newlines are not condensed.
     1115
    10291116@node Makefile Names, Include, Makefile Contents, Makefiles
    10301117@section What Name to Give Your Makefile
     
    12201307@node Remaking Makefiles, Overriding Makefiles, MAKEFILES Variable, Makefiles
    12211308@section How Makefiles Are Remade
    1222 
    12231309@cindex updating makefiles
    12241310@cindex remaking makefiles
     
    12421328you want to keep @code{make} from performing an implicit rule search
    12431329on them, perhaps for efficiency reasons, you can use any normal method
    1244 of preventing implicit rule lookup to do so.  For example, you can
     1330of preventing implicit rule look-up to do so.  For example, you can
    12451331write an explicit rule with the makefile as the target, and an empty
    12461332recipe (@pxref{Empty Recipes, ,Using Empty Recipes}).
     
    13061392another makefile.  You can often use the @samp{include} directive to
    13071393include one in the other, and add more targets or variable definitions.
    1308 However, it is illegal for two makefiles to give different recipes for
     1394However, it is invalid for two makefiles to give different recipes for
    13091395the same target.  But there is another way.
    13101396
     
    13801466@cindex ?=, expansion
    13811467@cindex +=, expansion
     1468@cindex !=, expansion
    13821469@cindex define, expansion
    13831470
     
    13881475@var{immediate} ?= @var{deferred}
    13891476@var{immediate} := @var{immediate}
     1477@var{immediate} ::= @var{immediate}
    13901478@var{immediate} += @var{deferred} or @var{immediate}
     1479@var{immediate} != @var{immediate}
    13911480
    13921481define @var{immediate}
     
    14061495endef
    14071496
     1497define @var{immediate} ::=
     1498  @var{immediate}
     1499endef
     1500
    14081501define @var{immediate} +=
    14091502  @var{deferred} or @var{immediate}
    14101503endef
     1504
     1505define @var{immediate} !=
     1506  @var{immediate}
     1507endef
    14111508@end example
    14121509
    14131510For the append operator, @samp{+=}, the right-hand side is considered
    14141511immediate if the variable was previously set as a simple variable
    1415 (@samp{:=}), and deferred otherwise.
     1512(@samp{:=} or @samp{::=}), and deferred otherwise.
     1513
     1514For the shell assignment operator, @samp{!=}, the right-hand side is
     1515evaluated immediately and handed to the shell.  The result is stored in the
     1516variable named on the left, and that variable becomes a simple variable
     1517(and will thus be re-evaluated on each reference).
    14161518
    14171519@subheading Conditional Directives
     
    14391541@example
    14401542@var{immediate} : @var{immediate} ; @var{deferred}
    1441         @var{deferred}
     1543        @var{deferred}
    14421544@end example
    14431545
     
    14881590without being recognized as a variable reference.  Now during the
    14891591secondary expansion the first word is expanded again but since it
    1490 contains no variable or function references it remains the static
    1491 value @file{onefile}, while the second word is now a normal reference
    1492 to the variable @var{TWOVAR}, which is expanded to the value
    1493 @file{twofile}.  The final result is that there are two prerequisites,
    1494 @file{onefile} and @file{twofile}.
     1592contains no variable or function references it remains the value
     1593@file{onefile}, while the second word is now a normal reference to the
     1594variable @var{TWOVAR}, which is expanded to the value @file{twofile}.
     1595The final result is that there are two prerequisites, @file{onefile}
     1596and @file{twofile}.
    14951597
    14961598Obviously, this is not a very interesting case since the same result
     
    16341736Search, ,Implicit Rule Search Algorithm}, is appended (after
    16351737expansion) to all the patterns in the prerequisites list.  As an
    1636 example:
     1738example:@refill
    16371739
    16381740@example
     
    16421744
    16431745%.o: $$(addsuffix /%.c,foo bar) foo.h
    1644 @end example
    1645 
    1646 The prerequisite list after the secondary expansion and directory
    1647 prefix reconstruction will be @file{/tmp/foo/foo.c /tmp/var/bar/foo.c
    1648 foo.h}.  If you are not interested in this reconstruction, you can use
    1649 @code{$$*} instead of @code{%} in the prerequisites list.
     1746        @@echo $^
     1747@end example
     1748
     1749The prerequisite list printed, after the secondary expansion and
     1750directory prefix reconstruction, will be @file{/tmp/foo/foo.c
     1751/tmp/bar/foo.c foo.h}.  If you are not interested in this
     1752reconstruction, you can use @code{$$*} instead of @code{%} in the
     1753prerequisites list.
    16501754
    16511755@node Rules, Recipes, Makefiles, Top
     
    16851789* Directory Search::            Searching other directories for source files.
    16861790* Phony Targets::               Using a target that is not a real file's name.
    1687 * Force Targets::               You can use a target without recipes
     1791* Force Targets::               You can use a target without a recipe
    16881792                                  or prerequisites to mark other targets
    16891793                                  as phony.
     
    19222026
    19232027@menu
    1924 * Wildcard Examples::           Several examples
     2028* Wildcard Examples::           Several examples.
    19252029* Wildcard Pitfall::            Problems to avoid.
    19262030* Wildcard Function::           How to cause wildcard expansion where
     
    21202224                                  for a specified class of names.
    21212225* Search Algorithm::            When and how search paths are applied.
    2122 * Recipes/Search::             How to write recipes that work together
     2226* Recipes/Search::              How to write recipes that work together
    21232227                                  with search paths.
    21242228* Implicit/Search::             How search paths affect implicit rules.
     
    24562560@samp{-l@var{name}} is seen, @code{make} will replace the percent in
    24572561each pattern in the list with @var{name} and perform the above directory
    2458 searches using each library filename.
     2562searches using each library file name.
    24592563
    24602564The default value for @code{.LIBPATTERNS} is @samp{lib%.so lib%.a},
     
    24932597
    24942598@findex .PHONY
    2495 The phony target will cease to work if anything ever does create a file
    2496 named @file{clean} in this directory.  Since it has no prerequisites, the
    2497 file @file{clean} would inevitably be considered up to date, and its
    2498 recipe would not be executed.  To avoid this problem, you can explicitly
    2499 declare the target to be phony, using the special target @code{.PHONY}
     2599In this example, the @file{clean} target will not work properly if a
     2600file named @file{clean} is ever created in this directory.  Since it
     2601has no prerequisites, @file{clean} would always be considered up to
     2602date and its recipe would not be executed.  To avoid this problem you
     2603can explicitly declare the target to be phony by making it a
     2604prerequisite of the special target @code{.PHONY}
    25002605(@pxref{Special Targets, ,Special Built-in Target Names}) as follows:
    2501 
    2502 @example
    2503 .PHONY : clean
    2504 @end example
    2505 
    2506 @noindent
    2507 Once this is done, @samp{make clean} will run the recipe regardless of
    2508 whether there is a file named @file{clean}.
    2509 
    2510 Since it knows that phony targets do not name actual files that could be
    2511 remade from other files, @code{make} skips the implicit rule search for
    2512 phony targets (@pxref{Implicit Rules}).  This is why declaring a target
    2513 phony is good for performance, even if you are not worried about the
    2514 actual file existing.
    2515 
    2516 Thus, you first write the line that states that @code{clean} is a
    2517 phony target, then you write the rule, like this:
    25182606
    25192607@example
     
    25252613@end example
    25262614
    2527 Another example of the usefulness of phony targets is in conjunction
    2528 with recursive invocations of @code{make} (for more information, see
    2529 @ref{Recursion, ,Recursive Use of @code{make}}).  In this case the
    2530 makefile will often contain a variable which lists a number of
    2531 subdirectories to be built.  One way to handle this is with one rule
    2532 whose recipe is a shell loop over the subdirectories, like this:
     2615@noindent
     2616Once this is done, @samp{make clean} will run the recipe regardless of
     2617whether there is a file named @file{clean}.
     2618
     2619Phony targets are also useful in conjunction with recursive
     2620invocations of @code{make} (@pxref{Recursion, ,Recursive Use of @code{make}}).
     2621In this situation the makefile will often contain a variable which
     2622lists a number of sub-directories to be built.  A simplistic way to
     2623handle this is to define one rule with a recipe that loops over the
     2624sub-directories, like this:
    25332625
    25342626@example
     
    25442636
    25452637There are problems with this method, however.  First, any error
    2546 detected in a submake is ignored by this rule, so it will continue
     2638detected in a sub-make is ignored by this rule, so it will continue
    25472639to build the rest of the directories even when one fails.  This can be
    25482640overcome by adding shell commands to note the error and exit, but then
     
    25532645one rule.
    25542646
    2555 By declaring the subdirectories as phony targets (you must do this as
    2556 the subdirectory obviously always exists; otherwise it won't be built)
    2557 you can remove these problems:
     2647By declaring the sub-directories as @code{.PHONY} targets (you must do
     2648this as the sub-directory obviously always exists; otherwise it won't
     2649be built) you can remove these problems:
    25582650
    25592651@example
     
    25722664@end example
    25732665
    2574 Here we've also declared that the @file{foo} subdirectory cannot be
    2575 built until after the @file{baz} subdirectory is complete; this kind of
     2666Here we've also declared that the @file{foo} sub-directory cannot be
     2667built until after the @file{baz} sub-directory is complete; this kind of
    25762668relationship declaration is particularly important when attempting
    25772669parallel builds.
     2670
     2671The implicit rule search (@pxref{Implicit Rules}) is skipped for
     2672@code{.PHONY} targets.  This is why declaring a target as
     2673@code{.PHONY} is good for performance, even if you are not worried
     2674about the actual file existing.
    25782675
    25792676A phony target should not be a prerequisite of a real target file; if it
     
    28172914is up to date.  Unfortunately, some hosts do not provide a way to set a
    28182915high resolution file time stamp, so commands like @samp{cp -p} that
    2819 explicitly set a file's time stamp must discard its subsecond part.
     2916explicitly set a file's time stamp must discard its sub-second part.
    28202917If a file is created by such a command, you should list it as a
    28212918prerequisite of @code{.LOW_RESOLUTION_TIME} so that @command{make}
     
    28312928@end example
    28322929
    2833 Since @samp{cp -p} discards the subsecond part of @file{src}'s time
     2930Since @samp{cp -p} discards the sub-second part of @file{src}'s time
    28342931stamp, @file{dst} is typically slightly older than @file{src} even when
    28352932it is up to date.  The @code{.LOW_RESOLUTION_TIME} line causes
     
    31333230for each target that does not.  If you have a list of files, only some of
    31343231which will match the pattern, you can use the @code{filter} function to
    3135 remove nonmatching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
     3232remove non-matching file names (@pxref{Text Functions, ,Functions for String Substitution and Analysis}):
    31363233
    31373234@example
     
    32873384The compiler will do it for you.
    32883385
    3289 Note that such a prerequisite constitutes mentioning @file{main.o} in a
    3290 makefile, so it can never be considered an intermediate file by implicit
    3291 rule search.  This means that @code{make} won't ever remove the file
    3292 after using it; @pxref{Chained Rules, ,Chains of Implicit Rules}.
     3386Note that such a rule constitutes mentioning @file{main.o} in a
     3387makefile, so it can never be considered an intermediate file by
     3388implicit rule search.  This means that @code{make} won't ever remove
     3389the file after using it; @pxref{Chained Rules, ,Chains of Implicit
     3390Rules}.
    32933391
    32943392@cindex @code{make depend}
     
    33353433of @samp{-M}.  This omits prerequisites on system header files.
    33363434@xref{Preprocessor Options, , Options Controlling the Preprocessor,
    3337 gcc.info, Using GNU CC}, for details.
     3435gcc, Using GNU CC}, for details.
    33383436
    33393437@cindex @code{sed} (shell command)
     
    34643562
    34653563@menu
    3466 * Splitting Lines::             Breaking long recipe lines for readability.
     3564* Splitting Recipe Lines::      Breaking long recipe lines for readability.
    34673565* Variables in Recipes::        Using @code{make} variables in recipes.
    34683566@end menu
    34693567
    3470 @node Splitting Lines, Variables in Recipes, Recipe Syntax, Recipe Syntax
     3568@node Splitting Recipe Lines, Variables in Recipes, Recipe Syntax, Recipe Syntax
    34713569@subsection Splitting Recipe Lines
    34723570@cindex recipes, splitting
     
    34873585
    34883586However, in contrast to how they are treated in other places in a
    3489 makefile, backslash-newline pairs are @emph{not} removed from the
    3490 recipe.  Both the backslash and the newline characters are preserved
    3491 and passed to the shell.  How the backslash-newline is interpreted
    3492 depends on your shell.  If the first character of the next line after
    3493 the backslash-newline is the recipe prefix character (a tab by
    3494 default; @pxref{Special Variables}), then that character (and only
    3495 that character) is removed.  Whitespace is never added to the recipe.
     3587makefile (@pxref{Splitting Lines, , Splitting Long Lines}),
     3588backslash/newline pairs are @emph{not} removed from the recipe.  Both
     3589the backslash and the newline characters are preserved and passed to
     3590the shell.  How the backslash/newline is interpreted depends on your
     3591shell.  If the first character of the next line after the
     3592backslash/newline is the recipe prefix character (a tab by default;
     3593@pxref{Special Variables}), then that character (and only that
     3594character) is removed.  Whitespace is never added to the recipe.
    34963595
    34973596For example, the recipe for the all target in this makefile:
     
    35643663
    35653664Sometimes you want to split a long line inside of single quotes, but
    3566 you don't want the backslash-newline to appear in the quoted content.
     3665you don't want the backslash/newline to appear in the quoted content.
    35673666This is often the case when passing scripts to languages such as Perl,
    35683667where extraneous backslashes inside the script can change its meaning
     
    35713670@code{make} variable then use the variable in the recipe.  In this
    35723671situation the newline quoting rules for makefiles will be used, and
    3573 the backslash-newline will be removed.  If we rewrite our example
     3672the backslash/newline will be removed.  If we rewrite our example
    35743673above using this method:
    35753674
     
    35973696uses it.
    35983697
    3599 @node Variables in Recipes,  , Splitting Lines, Recipe Syntax
     3698@node Variables in Recipes,  , Splitting Recipe Lines, Recipe Syntax
    36003699@subsection Using Variables in Recipes
    36013700@cindex variable references in recipes
     
    37003799
    37013800When it is time to execute recipes to update a target, they are
    3702 executed by invoking a new subshell for each line of the recipe,
     3801executed by invoking a new sub-shell for each line of the recipe,
    37033802unless the @code{.ONESHELL} special target is in effect
    37043803(@pxref{One Shell, ,Using One Shell})  (In practice, @code{make} may
     
    37313830
    37323831@menu
    3733 * One Shell::                   One shell for all lines in a recipe
     3832* One Shell::                   One shell for all lines in a recipe.
    37343833* Choosing the Shell::          How @code{make} chooses the shell used
    37353834                                  to run recipes.
     
    39704069slots is one, which means serial execution (one thing at a time).
    39714070
    3972 One unpleasant consequence of running several recipes simultaneously is
    3973 that output generated by the recipes appears whenever each recipe
    3974 sends it, so messages from different recipes may be interspersed.
    3975 
    3976 Another problem is that two processes cannot both take input from the
    3977 same device; so to make sure that only one recipe tries to take input
    3978 from the terminal at once, @code{make} will invalidate the standard
    3979 input streams of all but one running recipe.  This means that
    3980 attempting to read from standard input will usually be a fatal error (a
    3981 @samp{Broken pipe} signal) for most child processes if there are
    3982 several.
    3983 @cindex broken pipe
    3984 @cindex standard input
    3985 
    3986 It is unpredictable which recipe will have a valid standard input stream
    3987 (which will come from the terminal, or wherever you redirect the standard
    3988 input of @code{make}).  The first recipe run will always get it first, and
    3989 the first recipe started after that one finishes will get it next, and so
    3990 on.
    3991 
    3992 We will change how this aspect of @code{make} works if we find a better
    3993 alternative.  In the mean time, you should not rely on any recipe using
    3994 standard input at all if you are using the parallel execution feature; but
    3995 if you are not using this feature, then standard input works normally in
    3996 all recipes.
    3997 
    3998 Finally, handling recursive @code{make} invocations raises issues.  For
    3999 more information on this, see
    4000 @ref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
     4071Handling recursive @code{make} invocations raises issues for parallel
     4072execution.  For more information on this, see @ref{Options/Recursion,
     4073,Communicating Options to a Sub-@code{make}}.
    40014074
    40024075If a recipe fails (is killed by a signal or exits with a nonzero
    4003 status), and errors are not ignored for that recipe
    4004 (@pxref{Errors, ,Errors in Recipes}),
    4005 the remaining recipe lines to remake the same target will not be run.
    4006 If a recipe fails and the @samp{-k} or @samp{--keep-going}
    4007 option was not given
    4008 (@pxref{Options Summary, ,Summary of Options}),
    4009 @code{make} aborts execution.  If make
     4076status), and errors are not ignored for that recipe (@pxref{Errors,
     4077,Errors in Recipes}), the remaining recipe lines to remake the same
     4078target will not be run.  If a recipe fails and the @samp{-k} or
     4079@samp{--keep-going} option was not given (@pxref{Options Summary,
     4080,Summary of Options}), @code{make} aborts execution.  If make
    40104081terminates for any reason (including a signal) with child processes
    40114082running, it waits for them to finish before actually exiting.@refill
     
    40394110
    40404111By default, there is no load limit.
     4112
     4113@menu
     4114* Parallel Output::             Handling output during parallel execution
     4115* Parallel Input::              Handling input during parallel execution
     4116@end menu
     4117
     4118@node Parallel Output, Parallel Input, Parallel, Parallel
     4119@subsection Output During Parallel Execution
     4120@cindex output during parallel execution
     4121@cindex parallel execution, output during
     4122
     4123When running several recipes in parallel the output from each
     4124recipe appears as soon as it is generated, with the result that
     4125messages from different recipes may be interspersed, sometimes even
     4126appearing on the same line.  This can make reading the output very
     4127difficult.
     4128
     4129@cindex @code{--output-sync}
     4130@cindex @code{-O}
     4131To avoid this you can use the @samp{--output-sync} (@samp{-O}) option.
     4132This option instructs @code{make} to save the output from the commands
     4133it invokes and print it all once the commands are completed.
     4134Additionally, if there are multiple recursive @code{make} invocations
     4135running in parallel, they will communicate so that only one of them is
     4136generating output at a time.
     4137
     4138If working directory printing is enabled (@pxref{-w Option, ,The
     4139@samp{--print-directory} Option}), the enter/leave messages are
     4140printed around each output grouping.  If you prefer not to see these
     4141messages add the @samp{--no-print-directory} option to @code{MAKEFLAGS}.
     4142
     4143There are four levels of granularity when synchronizing output,
     4144specified by giving an argument to the option (e.g.,  @samp{-Oline} or
     4145@samp{--output-sync=recurse}).
     4146
     4147@table @code
     4148@item none
     4149This is the default: all output is sent directly as it is generated and
     4150no synchronization is performed.
     4151
     4152@item line
     4153Output from each individual line of the recipe is grouped and printed
     4154as soon as that line is complete.  If a recipe consists of multiple
     4155lines, they may be interspersed with lines from other recipes.
     4156
     4157@item target
     4158Output from the entire recipe for each target is grouped and printed
     4159once the target is complete.  This is the default if the
     4160@code{--output-sync} or @code{-O} option is given with no argument.
     4161
     4162@item recurse
     4163Output from each recursive invocation of @code{make} is grouped and
     4164printed once the recursive invocation is complete.
     4165
     4166@end table
     4167
     4168Regardless of the mode chosen, the total build time will be the same.
     4169The only difference is in how the output appears.
     4170
     4171The @samp{target} and @samp{recurse} modes both collect the output of
     4172the entire recipe of a target and display it uninterrupted when the
     4173recipe completes.  The difference between them is in how recipes that
     4174contain recursive invocations of @code{make} are treated
     4175(@pxref{Recursion, ,Recursive Use of @code{make}}).  For all recipes
     4176which have no recursive lines, the @samp{target} and @samp{recurse}
     4177modes behave identically.
     4178
     4179If the @samp{recurse} mode is chosen, recipes that contain recursive
     4180@code{make} invocations are treated the same as other targets: the
     4181output from the recipe, including the output from the recursive
     4182@code{make}, is saved and printed after the entire recipe is complete.
     4183This ensures output from all the targets built by a given recursive
     4184@code{make} instance are grouped together, which may make the output
     4185easier to understand.  However it also leads to long periods of time
     4186during the build where no output is seen, followed by large bursts of
     4187output.  If you are not watching the build as it proceeds, but instead
     4188viewing a log of the build after the fact, this may be the best option
     4189for you.
     4190
     4191If you are watching the output, the long gaps of quiet during the
     4192build can be frustrating.  The @samp{target} output synchronization
     4193mode detects when @code{make} is going to be invoked recursively,
     4194using the standard methods, and it will not synchronize the output of
     4195those lines.  The recursive @code{make} will perform the
     4196synchronization for its targets and the output from each will be
     4197displayed immediately when it completes.  Be aware that output from
     4198recursive lines of the recipe are not synchronized (for example if
     4199the recursive line prints a message before running @code{make}, that
     4200message will not be synchronized).
     4201
     4202The @samp{line} mode can be useful for front-ends that are watching
     4203the output of @code{make} to track when recipes are started and
     4204completed.
     4205
     4206Some programs invoked by @code{make} may behave differently if they
     4207determine they're writing output to a terminal versus a file (often
     4208described as ``interactive'' vs. ``non-interactive'' modes).  For
     4209example, many programs that can display colorized output will not do
     4210so if they determine they are not writing to a terminal.  If your
     4211makefile invokes a program like this then using the output
     4212synchronization options will cause the program to believe it's running
     4213in ``non-interactive'' mode even though the output will ultimately go
     4214to the terminal.
     4215
     4216@node Parallel Input,  , Parallel Output, Parallel
     4217@subsection Input During Parallel Execution
     4218@cindex input during parallel execution
     4219@cindex parallel execution, input during
     4220@cindex standard input
     4221
     4222Two processes cannot both take input from the same device at the same
     4223time.  To make sure that only one recipe tries to take input from the
     4224terminal at once, @code{make} will invalidate the standard input
     4225streams of all but one running recipe.  If another recipe attempts to
     4226read from standard input it will usually incur a fatal error (a
     4227@samp{Broken pipe} signal).
     4228@cindex broken pipe
     4229
     4230It is unpredictable which recipe will have a valid standard input stream
     4231(which will come from the terminal, or wherever you redirect the standard
     4232input of @code{make}).  The first recipe run will always get it first, and
     4233the first recipe started after that one finishes will get it next, and so
     4234on.
     4235
     4236We will change how this aspect of @code{make} works if we find a better
     4237alternative.  In the mean time, you should not rely on any recipe using
     4238standard input at all if you are using the parallel execution feature; but
     4239if you are not using this feature, then standard input works normally in
     4240all recipes.
    40414241
    40424242@node Errors, Interrupts, Parallel, Recipes
     
    41794379makefile.  This technique is useful when you want separate makefiles for
    41804380various subsystems that compose a larger system.  For example, suppose you
    4181 have a subdirectory @file{subdir} which has its own makefile, and you would
     4381have a sub-directory @file{subdir} which has its own makefile, and you would
    41824382like the containing directory's makefile to run @code{make} on the
    4183 subdirectory.  You can do it by writing this:
     4383sub-directory.  You can do it by writing this:
    41844384
    41854385@example
     
    42934493Variable values of the top-level @code{make} can be passed to the
    42944494sub-@code{make} through the environment by explicit request.  These
    4295 variables are defined in the sub-@code{make} as defaults, but do not
    4296 override what is specified in the makefile used by the sub-@code{make}
    4297 makefile unless you use the @samp{-e} switch (@pxref{Options Summary,
    4298 ,Summary of Options}).@refill
     4495variables are defined in the sub-@code{make} as defaults, but they do
     4496not override variables defined in the makefile used by
     4497the sub-@code{make} unless you use the @samp{-e} switch (@pxref{Options
     4498Summary, ,Summary of Options}).@refill
    42994499
    43004500To pass down, or @dfn{export}, a variable, @code{make} adds the
     
    45224722
    45234723If your operating system doesn't support the above communication, then
    4524 @samp{-j 1} is always put into @code{MAKEFLAGS} instead of the value you
    4525 specified.  This is because if the @w{@samp{-j}} option were passed down
    4526 to sub-@code{make}s, you would get many more jobs running in parallel
     4724no @samp{-j} is added to @code{MAKEFLAGS}, so that sub-@code{make}s
     4725run in non-parallel mode.  If the @w{@samp{-j}} option were passed down
     4726to sub-@code{make}s you would get many more jobs running in parallel
    45274727than you asked for.  If you give @samp{-j} with no numeric argument,
    45284728meaning to run as many jobs as possible in parallel, this is passed
     
    45564756see the error message @samp{Arg list too long}, this may be the problem.
    45574757@findex .POSIX
    4558 @cindex POSIX.2
     4758@cindex POSIX
    45594759(For strict compliance with POSIX.2, changing @code{MAKEOVERRIDES} does
    45604760not affect @code{MAKEFLAGS} if the special target @samp{.POSIX} appears
     
    46084808put in one of these variables, could have disastrous consequences and would
    46094809certainly have at least surprising and probably annoying effects.@refill
     4810
     4811If you'd like to run other implementations of @code{make} in addition
     4812to GNU @code{make}, and hence do not want to add GNU
     4813@code{make}-specific flags to the @code{MAKEFLAGS} variable, you can
     4814add them to the @code{GNUMAKEFLAGS} variable instead.  This variable
     4815is parsed just before @code{MAKEFLAGS}, in the same way as
     4816@code{MAKEFLAGS}.  When @code{make} constructs @code{MAKEFLAGS} to
     4817pass to a recursive @code{make} it will include all flags, even those
     4818taken from @code{GNUMAKEFLAGS}.  As a result, after parsing
     4819@code{GNUMAKEFLAGS} GNU @code{make} sets this variable to the empty
     4820string to avoid duplicating flags during recursion.
     4821
     4822It's best to use @code{GNUMAKEFLAGS} only with flags which won't
     4823materially change the behavior of your makefiles.  If your makefiles
     4824require GNU make anyway then simply use @code{MAKEFLAGS}.  Flags such
     4825as @samp{--no-print-directory} or @samp{--output-sync} may be
     4826appropriate for @code{GNUMAKEFLAGS}.
    46104827
    46114828@node -w Option,  , Options/Recursion, Recursion
     
    47174934In recipe execution, each line of a canned sequence is treated just as
    47184935if the line appeared on its own in the rule, preceded by a tab.  In
    4719 particular, @code{make} invokes a separate subshell for each line.  You
     4936particular, @code{make} invokes a separate sub-shell for each line.  You
    47204937can use the special prefix characters that affect command lines
    47214938(@samp{@@}, @samp{-}, and @samp{+}) on each line of a canned sequence.
     
    47664983
    47674984@findex .DEFAULT@r{, and empty recipes}
    4768 You may be wondering why you would want to define a recipe that
    4769 does nothing.  The only reason this is useful is to prevent a target
    4770 from getting implicit recipes (from implicit rules or the
    4771 @code{.DEFAULT} special target; @pxref{Implicit Rules} and
    4772 @pxref{Last Resort, ,Defining Last-Resort Default Rules}).@refill
    4773 
    4774 @c !!! another reason is for canonical stamp files:
    4775 @ignore
    4776 @example
    4777 foo: stamp-foo ;
    4778 stamp-foo: foo.in
    4779         create foo frm foo.in
    4780         touch $@
    4781 @end example
    4782 @end ignore
    4783 
    4784 You may be inclined to define empty recipes for targets that are
    4785 not actual files, but only exist so that their prerequisites can be
     4985You may be wondering why you would want to define a recipe that does
     4986nothing.  One reason this is useful is to prevent a target from
     4987getting implicit recipes (from implicit rules or the @code{.DEFAULT}
     4988special target; @pxref{Implicit Rules} and @pxref{Last Resort,
     4989,Defining Last-Resort Default Rules}).@refill
     4990
     4991Empty recipes can also be used to avoid errors for targets that will
     4992be created as a side-effect of another recipe: if the target does not
     4993exist the empty recipe ensures that @code{make} won't complain that it
     4994doesn't know how to build the target, and @code{make} will assume the
     4995target is out of date.
     4996
     4997You may be inclined to define empty recipes for targets that are not
     4998actual files, but only exist so that their prerequisites can be
    47864999remade.  However, this is not the best way to do that, because the
    4787 prerequisites may not be remade properly if the target file actually does exist.
    4788 @xref{Phony Targets, ,Phony Targets}, for a better way to do this.
     5000prerequisites may not be remade properly if the target file actually
     5001does exist.  @xref{Phony Targets, ,Phony Targets}, for a better way to
     5002do this.
    47895003
    47905004@node Using Variables, Conditionals, Recipes, Top
     
    48115025write output in, or anything else you can imagine.
    48125026
    4813 A variable name may be any sequence of characters not containing @samp{:},
    4814 @samp{#}, @samp{=}, or leading or trailing whitespace.  However,
    4815 variable names containing characters other than letters, numbers, and
    4816 underscores should be avoided, as they may be given special meanings in the
    4817 future, and with some shells they cannot be passed through the environment to a
    4818 sub-@code{make}
    4819 (@pxref{Variables/Recursion, ,Communicating Variables to a Sub-@code{make}}).
     5027A variable name may be any sequence of characters not containing
     5028@samp{:}, @samp{#}, @samp{=}, or whitespace.  However, variable names
     5029containing characters other than letters, numbers, and underscores
     5030should be considered carefully, as in some shells they cannot be
     5031passed through the environment to a sub-@code{make}
     5032(@pxref{Variables/Recursion, ,Communicating Variables to a
     5033Sub-@code{make}}).  Variable names beginning with @samp{.} and an
     5034uppercase letter may be given special meaning in future versions of
     5035@code{make}.
    48205036
    48215037Variable names are case-sensitive.  The names @samp{foo}, @samp{FOO},
     
    49415157expands to @samp{$(ugh)} which finally expands to @samp{Huh?}.@refill
    49425158
    4943 This flavor of variable is the only sort supported by other versions of
    4944 @code{make}.  It has its advantages and its disadvantages.  An advantage
    4945 (most would say) is that:
     5159This flavor of variable is the only sort supported by most other
     5160versions of @code{make}.  It has its advantages and its disadvantages.
     5161An advantage (most would say) is that:
    49465162
    49475163@example
     
    49795195@cindex variables, simply expanded
    49805196@cindex :=
     5197@cindex ::=
    49815198@dfn{Simply expanded variables} are defined by lines using @samp{:=}
    4982 (@pxref{Setting, ,Setting Variables}).
     5199or @samp{::=} (@pxref{Setting, ,Setting Variables}).  Both forms are
     5200equivalent in GNU @code{make}; however only the @samp{::=} form is
     5201described by the POSIX standard (support for @samp{::=} was added to
     5202the POSIX standard in 2012, so older versions of @code{make} won't
     5203accept this form either).
     5204
    49835205The value of a simply expanded variable is scanned
    49845206once and for all, expanding any references to other variables and
     
    52205442
    52215443References to recursively-expanded variables within a variable name are
    5222 reexpanded in the usual fashion.  For example:
     5444re-expanded in the usual fashion.  For example:
    52235445
    52245446@example
     
    53995621@cindex =
    54005622@cindex :=
     5623@cindex ::=
    54015624@cindex ?=
     5625@cindex !=
    54025626
    54035627To set a variable from the makefile, write a line starting with the
    5404 variable name followed by @samp{=} or @samp{:=}.  Whatever follows the
    5405 @samp{=} or @samp{:=} on the line becomes the value.  For example,
     5628variable name followed by @samp{=}, @samp{:=}, or @samp{::=}.  Whatever
     5629follows the @samp{=}, @samp{:=}, or @samp{::=} on the line becomes the
     5630value.  For example,
    54065631
    54075632@example
     
    54135638name and immediately after the @samp{=} is ignored.
    54145639
    5415 Variables defined with @samp{=} are @dfn{recursively expanded} variables.
    5416 Variables defined with @samp{:=} are @dfn{simply expanded} variables; these
    5417 definitions can contain variable references which will be expanded before
    5418 the definition is made.  @xref{Flavors, ,The Two Flavors of Variables}.
     5640Variables defined with @samp{=} are @dfn{recursively expanded}
     5641variables.  Variables defined with @samp{:=} or @samp{::=} are
     5642@dfn{simply expanded} variables; these definitions can contain
     5643variable references which will be expanded before the definition is
     5644made.  @xref{Flavors, ,The Two Flavors of Variables}.
    54195645
    54205646The variable name may contain function and variable references, which
     
    54225648
    54235649There is no limit on the length of the value of a variable except the
    5424 amount of swapping space on the computer.  When a variable definition is
    5425 long, it is a good idea to break it into several lines by inserting
    5426 backslash-newline at convenient places in the definition.  This will not
    5427 affect the functioning of @code{make}, but it will make the makefile easier
    5428 to read.
     5650amount of memory on the computer.  You can split the value of a
     5651variable into multiple physical lines for readability
     5652(@pxref{Splitting Lines, ,Splitting Long Lines}).
    54295653
    54305654Most variable names are considered to have the empty string as a value if
     
    54545678@end example
    54555679
     5680The shell assignment operator @samp{!=} can be used to execute a
     5681shell script and set a variable to its output.  This operator first
     5682evaluates the right-hand side, then passes that result to the shell
     5683for execution.  If the result of the execution ends in a newline, that
     5684one newline is removed; all other newlines are replaced by spaces.
     5685The resulting string is then placed into the named
     5686recursively-expanded variable.  For example:
     5687
     5688@example
     5689hash != printf '\043'
     5690file_list != find . -name '*.c'
     5691@end example
     5692
     5693If the result of the execution could produce a @code{$}, and you don't
     5694intend what follows that to be interpreted as a make variable or
     5695function reference, then you must replace every @code{$} with
     5696@code{$$} as part of the execution.  Alternatively, you can set a
     5697simply expanded variable to the result of running a program using the
     5698@code{shell} function call.  @xref{Shell Function, , The @code{shell}
     5699Function}.  For example:
     5700
     5701@example
     5702hash := $(shell printf '\043')
     5703var := $(shell find . -name "*.c")
     5704@end example
     5705
     5706As with the @code{shell} function, the exit status of the just-invoked
     5707shell script is stored in the @code{.SHELLSTATUS} variable.
     5708
     5709
    54565710@node Appending, Override Directive, Setting, Using Variables
    54575711@section Appending More Text to Variables
     
    54985752When you add to a variable's value with @samp{+=}, @code{make} acts
    54995753essentially as if you had included the extra text in the initial
    5500 definition of the variable.  If you defined it first with @samp{:=},
    5501 making it a simply-expanded variable, @samp{+=} adds to that
    5502 simply-expanded definition, and expands the new text before appending it
    5503 to the old value just as @samp{:=} does
    5504 (see @ref{Setting, ,Setting Variables}, for a full explanation of @samp{:=}).
    5505 In fact,
     5754definition of the variable.  If you defined it first with @samp{:=} or
     5755@samp{::=}, making it a simply-expanded variable, @samp{+=} adds to
     5756that simply-expanded definition, and expands the new text before
     5757appending it to the old value just as @samp{:=} does (see
     5758@ref{Setting, ,Setting Variables}, for a full explanation of
     5759@samp{:=} or @samp{::=}).  In fact,
    55065760
    55075761@example
     
    55615815The first line defines the @code{CFLAGS} variable with a reference to another
    55625816variable, @code{includes}.  (@code{CFLAGS} is used by the rules for C
    5563 compilation; @pxref{Catalogue of Rules, ,Catalogue of Implicit Rules}.)
     5817compilation; @pxref{Catalogue of Rules, ,Catalogue of Built-In Rules}.)
    55645818Using @samp{=} for the definition makes @code{CFLAGS} a recursively-expanded
    55655819variable, meaning @w{@samp{$(includes) -O}} is @emph{not} expanded when
     
    57175971since two commands separated by semicolon behave much like two separate
    57185972shell commands.  However, note that using two separate lines means
    5719 @code{make} will invoke the shell twice, running an independent subshell
     5973@code{make} will invoke the shell twice, running an independent sub-shell
    57205974for each line.  @xref{Execution, ,Recipe Execution}.
    57215975
     
    58436097
    58446098The @var{variable-assignment} can be any valid form of assignment;
    5845 recursive (@samp{=}), static (@samp{:=}), appending (@samp{+=}), or
    5846 conditional (@samp{?=}).  All variables that appear within the
    5847 @var{variable-assignment} are evaluated within the context of the
    5848 target: thus, any previously-defined target-specific variable values
    5849 will be in effect.  Note that this variable is actually distinct from
    5850 any ``global'' value: the two variables do not have to have the same
    5851 flavor (recursive vs.@: static).
     6099recursive (@samp{=}), simple (@samp{:=} or @samp{::=}), appending
     6100(@samp{+=}), or conditional (@samp{?=}).  All variables that appear
     6101within the @var{variable-assignment} are evaluated within the context
     6102of the target: thus, any previously-defined target-specific variable
     6103values will be in effect.  Note that this variable is actually
     6104distinct from any ``global'' value: the two variables do not have to
     6105have the same flavor (recursive vs.@: simple).
    58526106
    58536107Target-specific variables have the same priority as any other makefile
     
    59746228Due to the @code{private} modifier, @code{a.o} and @code{b.o} will not
    59756229inherit the @code{EXTRA_CFLAGS} variable assignment from the
    5976 @code{progs} target.
     6230@code{prog} target.
    59776231
    59786232@node Special Variables,  , Suppressing Inheritance, Using Variables
     
    60706324
    60716325Note that assigning more than one target name to @code{.DEFAULT_GOAL} is
    6072 illegal and will result in an error.
     6326invalid and will result in an error.
    60736327
    60746328@vindex MAKE_RESTARTS @r{(number of times @code{make} has restarted)}
     
    60796333this is not the same as recursion (counted by the @code{MAKELEVEL}
    60806334variable).  You should not set, modify, or export this variable.
     6335
     6336@vindex MAKE_TERMOUT @r{(whether stdout is a terminal)}
     6337@vindex MAKE_TERMERR @r{(whether stderr is a terminal)}
     6338@item MAKE_TERMOUT
     6339@itemx MAKE_TERMERR
     6340When @code{make} starts it will check whether stdout and stderr will
     6341show their output on a terminal.  If so, it will set
     6342@code{MAKE_TERMOUT} and @code{MAKE_TERMERR}, respectively, to the name
     6343of the terminal device (or @code{true} if this cannot be determined).
     6344If set these variables will be marked for export.  These variables
     6345will not be changed by @code{make} and they will not be modified if
     6346already set.
     6347
     6348These values can be used (particularly in combination with output
     6349synchronization (@pxref{Parallel Output, ,Output During Parallel
     6350Execution}) to determine whether @code{make} itself is writing to a
     6351terminal; they can be tested to decide whether to force recipe
     6352commands to generate colorized output for example.
     6353
     6354If you invoke a sub-@code{make} and redirect its stdout or stderr it
     6355is your responsibility to reset or unexport these variables as well,
     6356if your makefiles rely on them.
    60816357
    60826358@vindex .RECIPEPREFIX @r{(change the recipe prefix character)}
     
    61216397@item .FEATURES
    61226398Expands to a list of special features supported by this version of
    6123 @code{make}.  Possible values include:
     6399@code{make}.  Possible values include, but are not limited to:
    61246400
    61256401@table @samp
    61266402
    61276403@item archives
    6128 Supports @code{ar} (archive) files using special filename syntax.
     6404Supports @code{ar} (archive) files using special file name syntax.
    61296405@xref{Archives, ,Using @code{make} to Update Archive Files}.
    61306406
     
    61416417,Parallel Execution}.
    61426418
    6143 @item second-expansion
    6144 Supports secondary expansion of prerequisite lists.
     6419@item oneshell
     6420Supports the @code{.ONESHELL} special target.  @xref{One Shell, ,Using
     6421One Shell}.
    61456422
    61466423@item order-only
     
    61486425of Prerequisites}.
    61496426
     6427@item second-expansion
     6428Supports secondary expansion of prerequisite lists.
     6429
     6430@item shortest-stem
     6431Uses the ``shortest stem'' method of choosing which pattern, of
     6432multiple applicable options, will be used.  @xref{Pattern Match, ,How
     6433Patterns Match}.
     6434
    61506435@item target-specific
    61516436Supports target-specific and pattern-specific variable assignments.
    61526437@xref{Target-specific, ,Target-specific Variable Values}.
    61536438
     6439@item undefine
     6440Supports the @code{undefine} directive.  @xref{Undefine Directive}.
     6441
     6442@item guile
     6443Has GNU Guile available as an embedded extension language.
     6444@xref{Guile Integration, ,GNU Guile Integration}.
     6445
     6446@item load
     6447Supports dynamically loadable objects for creating custom extensions.
     6448@xref{Loading Objects, ,Loading Dynamic Objects}.
    61546449@end table
    61556450
     
    62926587
    62936588@example
    6294 @var{conditional-directive}
     6589@var{conditional-directive-one}
    62956590@var{text-if-one-is-true}
    6296 else @var{conditional-directive}
    6297 @var{text-if-true}
     6591else @var{conditional-directive-two}
     6592@var{text-if-two-is-true}
    62986593else
    6299 @var{text-if-false}
     6594@var{text-if-one-and-two-are-false}
    63006595endif
    63016596@end example
     
    63546649@item ifdef @var{variable-name}
    63556650The @code{ifdef} form takes the @emph{name} of a variable as its
    6356 argument, not a reference to a variable.  The value of that variable
    6357 has a non-empty value, the @var{text-if-true} is effective; otherwise,
    6358 the @var{text-if-false}, if any, is effective.  Variables that have
    6359 never been defined have an empty value.  The text @var{variable-name}
    6360 is expanded, so it could be a variable or function that expands
    6361 to the name of a variable.  For example:
     6651argument, not a reference to a variable.  If the value of that
     6652variable has a non-empty value, the @var{text-if-true} is effective;
     6653otherwise, the @var{text-if-false}, if any, is effective.  Variables
     6654that have never been defined have an empty value.  The text
     6655@var{variable-name} is expanded, so it could be a variable or function
     6656that expands to the name of a variable.  For example:
    63626657
    63636658@example
     
    64936788* Conditional Functions::       Functions that implement conditions.
    64946789* Foreach Function::            Repeat some text with controlled variation.
     6790* File Function::               Write text to a file.
    64956791* Call Function::               Expand a user-defined function.
    64966792* Value Function::              Return the un-expanded value of a variable.
     
    64986794* Origin Function::             Find where a variable got its value.
    64996795* Flavor Function::             Find out the flavor of a variable.
     6796* Make Control Functions::      Functions that control how make runs.
    65006797* Shell Function::              Substitute the output of a shell command.
    6501 * Make Control Functions::      Functions that control how make runs.
     6798* Guile Function::              Use GNU Guile embedded scripting language.
    65026799@end menu
    65036800
     
    65096806@cindex functions, syntax of
    65106807
    6511 A function call resembles a variable reference.  It looks like this:
     6808A function call resembles a variable reference.  It can appear
     6809anywhere a variable reference can appear, and it is expanded using the
     6810same rules as variable references.  A function call looks like this:
    65126811
    65136812@example
     
    65246823Here @var{function} is a function name; one of a short list of names
    65256824that are part of @code{make}.  You can also essentially create your own
    6526 functions by using the @code{call} builtin function.
     6825functions by using the @code{call} built-in function.
    65276826
    65286827The @var{arguments} are the arguments of the function.  They are
     
    71417440@end table
    71427441
    7143 @node Foreach Function, Call Function, Conditional Functions, Functions
     7442@node Foreach Function, File Function, Conditional Functions, Functions
    71447443@section The @code{foreach} Function
    71457444@findex foreach
     
    72037502Here we use the variable @code{find_files} this way.  We use plain @samp{=}
    72047503to define a recursively-expanding variable, so that its value contains an
    7205 actual function call to be reexpanded under the control of @code{foreach};
     7504actual function call to be re-expanded under the control of @code{foreach};
    72067505a simply-expanded variable would not do, since @code{wildcard} would be
    72077506called only once at the time of defining @code{find_files}.
     
    72217520
    72227521@smallexample
    7223 files := $(foreach Esta escrito en espanol!,b c ch,$(find_files))
     7522files := $(foreach Esta-escrito-en-espanol!,b c ch,$(find_files))
    72247523@end smallexample
    72257524
    72267525@noindent
    72277526might be useful if the value of @code{find_files} references the variable
    7228 whose name is @samp{Esta escrito en espanol!} (es un nombre bastante largo,
     7527whose name is @samp{Esta-escrito-en-espanol!} (es un nombre bastante largo,
    72297528no?), but it is more likely to be a mistake.
    72307529
    7231 @node Call Function, Value Function, Foreach Function, Functions
     7530@node File Function, Call Function, Foreach Function, Functions
     7531@section The @code{file} Function
     7532@findex file
     7533@cindex writing to a file
     7534@cindex file, writing to
     7535@cindex reading from a file
     7536@cindex file, reading from
     7537
     7538The @code{file} function allows the makefile to write to or read from
     7539a file.  Two modes of writing are supported: overwrite, where the text
     7540is written to the beginning of the file and any existing content is
     7541lost, and append, where the text is written to the end of the file,
     7542preserving the existing content.  In both cases the file is created if
     7543it does not exist.  It is a fatal error if the file cannot be opened
     7544for writing, or if the write operation fails.  The @code{file}
     7545function expands to the empty string when writing to a file.
     7546
     7547When reading from a file, the @code{file} function expands to the
     7548verbatim contents of the file, except that the final newline (if there
     7549is one) will be stripped.  Attempting to read from a non-existent file
     7550expands to the empty string.
     7551
     7552The syntax of the @code{file} function is:
     7553
     7554@example
     7555$(file @var{op} @var{filename}[,@var{text}])
     7556@end example
     7557
     7558When the @code{file} function is evaluated all its arguments are
     7559expanded first, then the file indicated by @var{filename} will be
     7560opened in the mode described by @var{op}.
     7561
     7562The operator @var{op} can be @code{>} to indicate the file will be
     7563overwritten with new content, @code{>>} to indicate the current
     7564contents of the file will be appended to, or @code{<} to indicate the
     7565contents of the file will be read in.  The @var{filename} specifies
     7566the file to be written to or read from.  There may optionally be
     7567whitespace between the operator and the file name.
     7568
     7569When reading files, it is an error to provide a @var{text} value.
     7570
     7571When writing files, @var{text} will be written to the file.  If
     7572@var{text} does not already end in a newline a final newline will be
     7573written (even if @var{text} is the empty string).  If the @var{text}
     7574argument is not given at all, nothing will be written.
     7575
     7576For example, the @code{file} function can be useful if your build
     7577system has a limited command line size and your recipe runs a command
     7578that can accept arguments from a file as well.  Many commands use the
     7579convention that an argument prefixed with an @code{@@} specifies a
     7580file containing more arguments.  Then you might write your recipe in
     7581this way:
     7582
     7583@example
     7584@group
     7585program: $(OBJECTS)
     7586        $(file >$@@.in,$^)
     7587        $(CMD) $(CMDFLAGS) @@$@@.in
     7588        @@rm $@@.in
     7589@end group
     7590@end example
     7591
     7592If the command required each argument to be on a separate line of the
     7593input file, you might write your recipe like this:
     7594
     7595@example
     7596@group
     7597program: $(OBJECTS)
     7598        $(file >$@@.in) $(foreach O,$^,$(file >>$@@.in,$O))
     7599        $(CMD) $(CMDFLAGS) @@$@@.in
     7600        @@rm $@@.in
     7601@end group
     7602@end example
     7603
     7604@node Call Function, Value Function, File Function, Functions
    72327605@section The @code{call} Function
    72337606@findex call
     
    72637636constant.)
    72647637
    7265 If @var{variable} is the name of a builtin function, the builtin function
     7638If @var{variable} is the name of a built-in function, the built-in function
    72667639is always invoked (even if a @code{make} variable by that name also
    72677640exists).
     
    72697642The @code{call} function expands the @var{param} arguments before
    72707643assigning them to temporary variables.  This means that @var{variable}
    7271 values containing references to builtin functions that have special
     7644values containing references to built-in functions that have special
    72727645expansion rules, like @code{foreach} or @code{if}, may not work as you
    72737646expect.
     
    73417714@end example
    73427715
    7343 Note that @var{variable} is the @emph{name} of a variable; not a
     7716Note that @var{variable} is the @emph{name} of a variable, not a
    73447717@emph{reference} to that variable.  Therefore you would not normally
    73457718use a @samp{$} or parentheses when writing it.  (You can, however, use
     
    74527825@end example
    74537826
    7454 Note that @var{variable} is the @emph{name} of a variable to inquire about;
     7827Note that @var{variable} is the @emph{name} of a variable to inquire about,
    74557828not a @emph{reference} to that variable.  Therefore you would not normally
    74567829use a @samp{$} or parentheses when writing it.  (You can, however, use a
     
    75457918@xref{Text Functions, , Functions for String Substitution and Analysis}.
    75467919
    7547 @node Flavor Function, Shell Function, Origin Function, Functions
     7920@node Flavor Function, Make Control Functions, Origin Function, Functions
    75487921@section The @code{flavor} Function
    75497922@findex flavor
     
    75517924@cindex flavor of variable
    75527925
    7553 The @code{flavor} function is unlike most other functions (and like
    7554 @code{origin} function) in that it does not operate on the values of
    7555 variables; it tells you something @emph{about} a variable.
    7556 Specifically, it tells you the flavor of a variable (@pxref{Flavors,
    7557 ,The Two Flavors of Variables}).
     7926The @code{flavor} function, like the @code{origin} function, does not
     7927operate on the values of variables but rather it tells you something
     7928@emph{about} a variable.  Specifically, it tells you the flavor of a
     7929variable (@pxref{Flavors, ,The Two Flavors of Variables}).
    75587930
    75597931The syntax of the @code{flavor} function is:
     
    75637935@end example
    75647936
    7565 Note that @var{variable} is the @emph{name} of a variable to inquire about;
     7937Note that @var{variable} is the @emph{name} of a variable to inquire about,
    75667938not a @emph{reference} to that variable.  Therefore you would not normally
    75677939use a @samp{$} or parentheses when writing it.  (You can, however, use a
     
    75867958@end table
    75877959
    7588 
    7589 @node Shell Function, Make Control Functions, Flavor Function, Functions
    7590 @section The @code{shell} Function
    7591 @findex shell
    7592 @cindex command expansion
    7593 @cindex backquotes
    7594 @cindex shell command, function for
    7595 
    7596 The @code{shell} function is unlike any other function other than the
    7597 @code{wildcard} function
    7598 (@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
    7599 communicates with the world outside of @code{make}.
    7600 
    7601 The @code{shell} function performs the same function that backquotes
    7602 (@samp{`}) perform in most shells: it does @dfn{command expansion}.
    7603 This means that it takes as an argument a shell command and evaluates
    7604 to the output of the command.  The only processing @code{make} does on
    7605 the result is to convert each newline (or carriage-return / newline
    7606 pair) to a single space.  If there is a trailing (carriage-return
    7607 and) newline it will simply be removed.@refill
    7608 
    7609 The commands run by calls to the @code{shell} function are run when the
    7610 function calls are expanded (@pxref{Reading Makefiles, , How
    7611 @code{make} Reads a Makefile}).  Because this function involves
    7612 spawning a new shell, you should carefully consider the performance
    7613 implications of using the @code{shell} function within recursively
    7614 expanded variables vs.@: simply expanded variables (@pxref{Flavors, ,The
    7615 Two Flavors of Variables}).
    7616 
    7617 Here are some examples of the use of the @code{shell} function:
    7618 
    7619 @example
    7620 contents := $(shell cat foo)
    7621 @end example
    7622 
    7623 @noindent
    7624 sets @code{contents} to the contents of the file @file{foo}, with a space
    7625 (rather than a newline) separating each line.
    7626 
    7627 @example
    7628 files := $(shell echo *.c)
    7629 @end example
    7630 
    7631 @noindent
    7632 sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
    7633 using a very strange shell, this has the same result as
    7634 @w{@samp{$(wildcard *.c)}} (as long as at least one @samp{.c} file
    7635 exists).@refill
    7636 
    7637 @node Make Control Functions,  , Shell Function, Functions
     7960@node Make Control Functions, Shell Function, Flavor Function, Functions
    76387961@section Functions That Control Make
    76397962@cindex functions, for controlling make
     
    76968019result of the expansion of this function is the empty string.
    76978020@end table
     8021
     8022@node Shell Function, Guile Function, Make Control Functions, Functions
     8023@section The @code{shell} Function
     8024@findex shell
     8025@cindex command expansion
     8026@cindex backquotes
     8027@cindex shell command, function for
     8028
     8029The @code{shell} function is unlike any other function other than the
     8030@code{wildcard} function
     8031(@pxref{Wildcard Function, ,The Function @code{wildcard}}) in that it
     8032communicates with the world outside of @code{make}.
     8033
     8034The @code{shell} function performs the same function that backquotes
     8035(@samp{`}) perform in most shells: it does @dfn{command expansion}.
     8036This means that it takes as an argument a shell command and evaluates
     8037to the output of the command.  The only processing @code{make} does on
     8038the result is to convert each newline (or carriage-return / newline
     8039pair) to a single space.  If there is a trailing (carriage-return
     8040and) newline it will simply be removed.@refill
     8041
     8042The commands run by calls to the @code{shell} function are run when the
     8043function calls are expanded (@pxref{Reading Makefiles, , How
     8044@code{make} Reads a Makefile}).  Because this function involves
     8045spawning a new shell, you should carefully consider the performance
     8046implications of using the @code{shell} function within recursively
     8047expanded variables vs.@: simply expanded variables (@pxref{Flavors, ,The
     8048Two Flavors of Variables}).
     8049
     8050@vindex .SHELLSTATUS
     8051After the @code{shell} function or @samp{!=} assignment operator is
     8052used, its exit status is placed in the @code{.SHELLSTATUS} variable.
     8053
     8054Here are some examples of the use of the @code{shell} function:
     8055
     8056@example
     8057contents := $(shell cat foo)
     8058@end example
     8059
     8060@noindent
     8061sets @code{contents} to the contents of the file @file{foo}, with a space
     8062(rather than a newline) separating each line.
     8063
     8064@example
     8065files := $(shell echo *.c)
     8066@end example
     8067
     8068@noindent
     8069sets @code{files} to the expansion of @samp{*.c}.  Unless @code{make} is
     8070using a very strange shell, this has the same result as
     8071@w{@samp{$(wildcard *.c)}} (as long as at least one @samp{.c} file
     8072exists).@refill
     8073
     8074@node Guile Function,  , Shell Function, Functions
     8075@section The @code{guile} Function
     8076@findex guile
     8077@cindex Guile
     8078
     8079If GNU @code{make} is built with support for GNU Guile as an embedded
     8080extension language then the @code{guile} function will be available.
     8081The @code{guile} function takes one argument which is first expanded
     8082by @code{make} in the normal fashion, then passed to the GNU Guile
     8083evaluator.  The result of the evaluator is converted into a string and
     8084used as the expansion of the @code{guile} function in the makefile.
     8085See @ref{Guile Integration, ,GNU Guile Integration} for details on
     8086writing extensions to @code{make} in Guile.
     8087
     8088You can determine whether GNU Guile support is available by checking
     8089the @code{.FEATURES} variable for the word @var{guile}.
    76988090
    76998091@node Running, Implicit Rules, Functions, Top
     
    79198311@cindex @code{-n}
    79208312
    7921 ``No-op''.  The activity is to print what recipe would be used to make
    7922 the targets up to date, but not actually execute it.  Some recipes are
    7923 still executed, even with this flag (@pxref{MAKE Variable, ,How the @code{MAKE} Variable Works}).
     8313``No-op''.  Causes @code{make} to print the recipes that are needed to
     8314make the targets up to date, but not actually execute them.  Note that
     8315some recipes are still executed, even with this flag (@pxref{MAKE
     8316Variable, ,How the @code{MAKE} Variable Works}).  Also any recipes
     8317needed to update included makefiles are still executed
     8318(@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).
    79248319
    79258320@item -t
     
    79308325@cindex @code{-t}
    79318326
    7932 ``Touch''.  The activity is to mark the targets as up to date without
    7933 actually changing them.  In other words, @code{make} pretends to compile
    7934 the targets but does not really change their contents.
     8327``Touch''.  Marks targets as up to date without actually changing
     8328them.  In other words, @code{make} pretends to update the targets but
     8329does not really change their contents; instead only their modified
     8330times are updated.
    79358331
    79368332@item -q
     
    79408336@cindex question mode
    79418337
    7942 ``Question''.  The activity is to find out silently whether the targets
    7943 are up to date already; but execute no recipe in either case.  In other
    7944 words, neither compilation nor output will occur.
     8338``Question''.  Silently check whether the targets are up to date, but
     8339do not execute recipes; the exit code shows whether any updates are
     8340needed.
    79458341
    79468342@item -W @var{file}
     
    81168512define either a recursively-expanded variable or a simply-expanded
    81178513variable.  The examples shown above make a recursively-expanded
    8118 variable; to make a simply-expanded variable, write @samp{:=} instead
    8119 of @samp{=}.  But, unless you want to include a variable reference or
    8120 function call in the @emph{value} that you specify, it makes no
    8121 difference which kind of variable you create.
     8514variable; to make a simply-expanded variable, write @samp{:=} or
     8515@samp{::=} instead of @samp{=}.  But, unless you want to include a
     8516variable reference or function call in the @emph{value} that you
     8517specify, it makes no difference which kind of variable you create.
    81228518
    81238519There is one way that the makefile can change a variable that you have
     
    82438639
    82448640@item j (@i{jobs})
    8245 Prints messages giving details on the invocation of specific subcommands.
     8641Prints messages giving details on the invocation of specific sub-commands.
    82468642
    82478643@item m (@i{makefile})
     
    82508646too.  Note that the @samp{all} option does enable this option.  This
    82518647option also enables @samp{basic} messages.
     8648
     8649@item n (@i{none})
     8650Disable all debugging currently enabled.  If additional debugging
     8651flags are encountered after this they will still take effect.
    82528652@end table
    82538653
     
    83678767are ignored.  @xref{Avoiding Compilation, ,Avoiding Recompilation of
    83688768Some Files}.@refill
     8769
     8770@item -O[@var{type}]
     8771@cindex @code{-O}
     8772@itemx --output-sync[=@var{type}]
     8773@cindex @code{--output-sync}
     8774@cindex output during parallel execution
     8775@cindex parallel execution, output during
     8776Ensure that the complete output from each recipe is printed in one
     8777uninterrupted sequence.  This option is only useful when using the
     8778@code{--jobs} option to run multiple recipes simultaneously
     8779(@pxref{Parallel, ,Parallel Execution})  Without this option output
     8780will be displayed as it is generated by the recipes.@refill
     8781
     8782With no type or the type @samp{target}, output from the entire recipe
     8783of each target is grouped together.  With the type @samp{line}, output
     8784from each line in the recipe is grouped together.  With the type
     8785@samp{recurse}, the output from an entire recursive make is grouped
     8786together.  With the type @samp{none}, no output synchronization is
     8787performed.  @xref{Parallel Output, ,Output During Parallel Execution}.
    83698788
    83708789@item -p
     
    83808799to remake any files, use @w{@samp{make -qp}}.  To print the data base
    83818800of predefined rules and variables, use @w{@samp{make -p -f /dev/null}}.
    8382 The data base output contains filename and linenumber information for
     8801The data base output contains file name and line number information for
    83838802recipe and variable definitions, so it can be a useful debugging tool
    83848803in complex environments.
     
    84558874@code{make}.  @xref{Instead of Execution, ,Instead of Executing Recipes}.
    84568875
     8876@item --trace
     8877@cindex @code{--trace}
     8878Show tracing information for @code{make} execution.  Prints the entire
     8879recipe to be executed, even for recipes that are normally silent (due
     8880to @code{.SILENT} or @samp{@@}).  Also prints the makefile name and
     8881line number where the recipe was defined, and information on why the
     8882target is being rebuilt.
     8883
    84578884@item -v
    84588885@cindex @code{-v}
     
    84738900see @ref{-w Option, ,The @samp{--print-directory} Option}.)
    84748901
    8475 @itemx --no-print-directory
     8902@item --no-print-directory
    84768903@cindex @code{--no-print-directory}
    84778904Disable printing of the working directory under @code{-w}.
     
    85518978* Using Implicit::              How to use an existing implicit rule
    85528979                                  to get the recipes for updating a file.
    8553 * Catalogue of Rules::          A list of built-in implicit rules.
     8980* Catalogue of Rules::          A list of built-in rules.
    85548981* Implicit Variables::          How to change what predefined rules do.
    85558982* Chained Rules::               How to use a chain of implicit rules.
    85568983* Pattern Rules::               How to define new implicit rules.
    8557 * Last Resort::                 How to define recipes for rules which
     8984* Last Resort::                 How to define a recipe for rules which
    85588985                                  cannot find any.
    85598986* Suffix Rules::                The old-fashioned style of implicit rule.
     
    86039030want @code{make} to use, and you know it will choose that one because you
    86049031know which possible prerequisite files are supposed to exist.
    8605 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules},
     9032@xref{Catalogue of Rules, ,Catalogue of Built-In Rules},
    86069033for a catalogue of all the predefined implicit rules.
    86079034
     
    86339060rule to make an object file from a C source file is used instead,
    86349061because it appears before the Pascal rule in the list of predefined
    8635 implicit rules (@pxref{Catalogue of Rules, , Catalogue of Implicit
     9062implicit rules (@pxref{Catalogue of Rules, , Catalogue of Built-In
    86369063Rules}).
    86379064
     
    86419068
    86429069@node Catalogue of Rules, Implicit Variables, Using Implicit, Implicit Rules
    8643 @section Catalogue of Implicit Rules
     9070@section Catalogue of Built-In Rules
    86449071@cindex implicit rule, predefined
    86459072@cindex rule, implicit, predefined
     
    89879414Here is a table of some of the more common variables used as names of
    89889415programs in built-in rules:
    8989 makefiles.
    89909416
    89919417@table @code
     
    91429568@vindex LDFLAGS
    91439569Extra flags to give to compilers when they are supposed to invoke the linker,
    9144 @samp{ld}.
     9570@samp{ld}, such as @code{-L}.  Libraries (@code{-lfoo}) should be
     9571added to the @code{LDLIBS} variable instead.
     9572
     9573@item LDLIBS
     9574@vindex LDLIBS
     9575@vindex LOADLIBES
     9576Library flags or names given to compilers when they are supposed to
     9577invoke the linker, @samp{ld}.  @code{LOADLIBES} is a deprecated (but
     9578still supported) alternative to @code{LDLIBS}.  Non-library linker
     9579flags, such as @code{-L}, should go in the @code{LDFLAGS} variable.
    91459580
    91469581@item LFLAGS
     
    92759710* Pattern Examples::            Examples of pattern rules.
    92769711* Automatic Variables::         How to use automatic variables in the
    9277                                   recipes of implicit rules.
     9712                                  recipe of implicit rules.
    92789713* Pattern Match::               How patterns match.
    92799714* Match-Anything Rules::        Precautions you should take prior to
     
    93759810@noindent
    93769811defines a rule that can make any file @file{@var{x}} whatsoever from a
    9377 corresponding file @file{@var{x},v} in the subdirectory @file{RCS}.  Since
     9812corresponding file @file{@var{x},v} in the sub-directory @file{RCS}.  Since
    93789813the target is @samp{%}, this rule will apply to any file whatever, provided
    93799814the appropriate prerequisite file exists.  The double colon makes the rule
     
    974810183
    974910184If you do not mark the match-anything rule as terminal, then it is
    9750 nonterminal.  A nonterminal match-anything rule cannot apply to a file name
     10185non-terminal.  A non-terminal match-anything rule cannot apply to a file name
    975110186that indicates a specific type of data.  A file name indicates a specific
    975210187type of data if some non-match-anything implicit rule target matches it.
     
    975610191rule is actually applicable (which happens only if there is a file
    975710192@file{foo.y}), the fact that its target matches is enough to prevent
    9758 consideration of any nonterminal match-anything rules for the file
     10193consideration of any non-terminal match-anything rules for the file
    975910194@file{foo.c}.  Thus, @code{make} will not even consider trying to make
    976010195@file{foo.c} as an executable file from @file{foo.c.o}, @file{foo.c.c},
    976110196@file{foo.c.p}, etc.@refill
    976210197
    9763 The motivation for this constraint is that nonterminal match-anything
     10198The motivation for this constraint is that non-terminal match-anything
    976410199rules are used for making files containing specific types of data (such as
    976510200executable files) and a file name with a recognized suffix indicates some
     
    976710202
    976810203Special built-in dummy pattern rules are provided solely to recognize
    9769 certain file names so that nonterminal match-anything rules will not be
     10204certain file names so that non-terminal match-anything rules will not be
    977010205considered.  These dummy rules have no prerequisites and no recipes, and
    977110206they are ignored for all other purposes.  For example, the built-in
     
    998710422@item
    998810423If any rule in that list is @emph{not} a match-anything rule, then
    9989 remove all nonterminal match-anything rules from the list.
     10424remove all non-terminal match-anything rules from the list.
    999010425
    999110426@item
     
    1005610491prerequisites.  @xref{Automatic Variables}.
    1005710492
    10058 @node Archives, Features, Implicit Rules, Top
     10493@node Archives, Extending make, Implicit Rules, Top
    1005910494@chapter Using @code{make} to Update Archive Files
    1006010495@cindex archive
    1006110496
    10062 @dfn{Archive files} are files containing named subfiles called
     10497@dfn{Archive files} are files containing named sub-files called
    1006310498@dfn{members}; they are maintained with the program @code{ar} and their
    1006410499main use is as subroutine libraries for linking.
     
    1028310718@w{%.@var{x}}} and @samp{@w{%.a}: @w{%.@var{x}}}.@refill
    1028410719
    10285 @node Features, Missing, Archives, Top
     10720@node Extending make, Integrating make, Archives, Top
     10721@chapter Extending GNU @code{make}
     10722@cindex make extensions
     10723
     10724GNU @code{make} provides many advanced capabilities, including many
     10725useful functions.  However, it does not contain a complete programming
     10726language and so it has limitations.  Sometimes these limitations can be
     10727overcome through use of the @code{shell} function to invoke a separate
     10728program, although this can be inefficient.
     10729
     10730In cases where the built-in capabilities of GNU @code{make} are
     10731insufficient to your requirements there are two options for extending
     10732@code{make}.  On systems where it's provided, you can utilize GNU
     10733Guile as an embedded scripting language (@pxref{Guile Integration,,GNU
     10734Guile Integration}).  On systems which support dynamically loadable
     10735objects, you can write your own extension in any language (which can
     10736be compiled into such an object) and load it to provide extended
     10737capabilities (@pxref{load Directive, ,The @code{load} Directive}).
     10738
     10739@menu
     10740* Guile Integration::           Using Guile as an embedded scripting language.
     10741* Loading Objects::             Loading dynamic objects as extensions.
     10742@end menu
     10743
     10744@node Guile Integration, Loading Objects, Extending make, Extending make
     10745@section GNU Guile Integration
     10746@cindex Guile
     10747@cindex extensions, Guile
     10748
     10749GNU @code{make} may be built with support for GNU Guile as an embedded
     10750extension language.  Guile implements the Scheme language.  A review
     10751of GNU Guile and the Scheme language and its features is beyond the
     10752scope of this manual: see the documentation for GNU Guile and Scheme.
     10753
     10754You can determine if @code{make} contains support for Guile by
     10755examining the @code{.FEATURES} variable; it will contain the word
     10756@var{guile} if Guile support is available.
     10757
     10758The Guile integration provides one new @code{make} function: @code{guile}.
     10759The @code{guile} function takes one argument which is first expanded
     10760by @code{make} in the normal fashion, then passed to the GNU Guile
     10761evaluator.  The result of the evaluator is converted into a string and
     10762used as the expansion of the @code{guile} function in the makefile.
     10763
     10764In addition, GNU @code{make} exposes Guile procedures for use in Guile
     10765scripts.
     10766
     10767@menu
     10768* Guile Types::                 Converting Guile types to @code{make} strings.
     10769* Guile Interface::             Invoking @code{make} functions from Guile.
     10770* Guile Example::               Example using Guile in @code{make}.
     10771@end menu
     10772
     10773@node Guile Types, Guile Interface, Guile Integration, Guile Integration
     10774@subsection Conversion of Guile Types
     10775@cindex convert guile types
     10776@cindex guile, conversion of types
     10777@cindex types, conversion of
     10778
     10779There is only one ``data type'' in @code{make}: a string.  GNU Guile,
     10780on the other hand, provides a rich variety of different data types.
     10781An important aspect of the interface between @code{make} and GNU Guile
     10782is the conversion of Guile data types into @code{make} strings.
     10783
     10784This conversion is relevant in two places: when a makefile invokes the
     10785@code{guile} function to evaluate a Guile expression, the result of
     10786that evaluation must be converted into a make string so it can be
     10787further evaluated by @code{make}.  And secondly, when a Guile script
     10788invokes one of the procedures exported by @code{make} the argument
     10789provided to the procedure must be converted into a string.
     10790
     10791The conversion of Guile types into @code{make} strings is as below:
     10792
     10793@table @code
     10794@item #f
     10795False is converted into the empty string: in @code{make} conditionals
     10796the empty string is considered false.
     10797
     10798@item #t
     10799True is converted to the string @samp{#t}: in @code{make} conditionals
     10800any non-empty string is considered true.
     10801
     10802@item symbol
     10803@item number
     10804A symbol or number is converted into the string representation of that
     10805symbol or number.
     10806
     10807@item character
     10808A printable character is converted to the same character.
     10809
     10810@item string
     10811A string containing only printable characters is converted to the same
     10812string.
     10813
     10814@item list
     10815A list is converted recursively according to the above rules.  This
     10816implies that any structured list will be flattened (that is, a result
     10817of @samp{'(a b (c d) e)} will be converted to the @code{make} string
     10818@samp{a b c d e}).
     10819
     10820@item other
     10821Any other Guile type results in an error.  In future versions of
     10822@code{make}, other Guile types may be converted.
     10823
     10824@end table
     10825
     10826The translation of @samp{#f} (to the empty string) and @samp{#t} (to
     10827the non-empty string @samp{#t}) is designed to allow you to use Guile
     10828boolean results directly as @code{make} boolean conditions.  For
     10829example:
     10830
     10831@example
     10832$(if $(guile (access? "myfile" R_OK)),$(info myfile exists))
     10833@end example
     10834
     10835As a consequence of these conversion rules you must consider the
     10836result of your Guile script, as that result will be converted into a
     10837string and parsed by @code{make}.  If there is no natural result for
     10838the script (that is, the script exists solely for its side-effects),
     10839you should add @samp{#f} as the final expression in order to avoid
     10840syntax errors in your makefile.
     10841
     10842@node Guile Interface, Guile Example, Guile Types, Guile Integration
     10843@subsection Interfaces from Guile to @code{make}
     10844@cindex make interface to guile
     10845@cindex make procedures in guile
     10846
     10847In addition to the @code{guile} function available in makefiles,
     10848@code{make} exposes some procedures for use in your Guile scripts.  At
     10849startup @code{make} creates a new Guile module, @code{gnu make}, and
     10850exports these procedures as public interfaces from that module:
     10851
     10852@table @code
     10853@item gmk-expand
     10854@findex gmk-expand
     10855This procedure takes a single argument which is converted into a
     10856string.  The string is expanded by @code{make} using normal
     10857@code{make} expansion rules.  The result of the expansion is converted
     10858into a Guile string and provided as the result of the procedure.
     10859
     10860@item gmk-eval
     10861@findex gmk-eval
     10862This procedure takes a single argument which is converted into a
     10863string.  The string is evaluated by @code{make} as if it were a
     10864makefile.  This is the same capability available via the @code{eval}
     10865function (@pxref{Eval Function}).  The result of the @code{gmk-eval}
     10866procedure is always the empty string.
     10867
     10868Note that @code{gmk-eval} is not quite the same as using
     10869@code{gmk-expand} with the @code{eval} function: in the latter case
     10870the evaluated string will be expanded @emph{twice}; first by
     10871@code{gmk-expand}, then again by the @code{eval} function.
     10872
     10873@end table
     10874
     10875@node Guile Example,  , Guile Interface, Guile Integration
     10876@subsection Example Using Guile in @code{make}
     10877@cindex Guile example
     10878@cindex example using Guile
     10879
     10880Here is a very simple example using GNU Guile to manage writing to a
     10881file.  These Guile procedures simply open a file, allow writing to the
     10882file (one string per line), and close the file.  Note that because we
     10883cannot store complex values such as Guile ports in @code{make}
     10884variables, we'll keep the port as a global variable in the Guile
     10885interpreter.
     10886
     10887You can create Guile functions easily using @code{define}/@code{endef}
     10888to create a Guile script, then use the @code{guile} function to
     10889internalize it:
     10890
     10891@example
     10892@group
     10893define GUILEIO
     10894;; A simple Guile IO library for GNU make
     10895
     10896(define MKPORT #f)
     10897
     10898(define (mkopen name mode)
     10899  (set! MKPORT (open-file name mode))
     10900  #f)
     10901
     10902(define (mkwrite s)
     10903  (display s MKPORT)
     10904  (newline MKPORT)
     10905  #f)
     10906
     10907(define (mkclose)
     10908  (close-port MKPORT)
     10909  #f)
     10910
     10911#f
     10912endef
     10913
     10914# Internalize the Guile IO functions
     10915$(guile $(GUILEIO))
     10916@end group
     10917@end example
     10918
     10919If you have a significant amount of Guile support code, you might
     10920consider keeping it in a different file (e.g., @file{guileio.scm}) and
     10921then loading it in your makefile using the @code{guile} function:
     10922
     10923@example
     10924$(guile (load "guileio.scm"))
     10925@end example
     10926
     10927An advantage to this method is that when editing @file{guileio.scm},
     10928your editor will understand that this file contains Scheme syntax
     10929rather than makefile syntax.
     10930
     10931Now you can use these Guile functions to create files.  Suppose you
     10932need to operate on a very large list, which cannot fit on the command
     10933line, but the utility you're using accepts the list as input as well:
     10934
     10935@example
     10936@group
     10937prog: $(PREREQS)
     10938        @@$(guile (mkopen "tmp.out" "w")) \
     10939         $(foreach X,$^,$(guile (mkwrite "$(X)"))) \
     10940         $(guile (mkclose))
     10941        $(LINK) < tmp.out
     10942@end group
     10943@end example
     10944
     10945A more comprehensive suite of file manipulation procedures is possible
     10946of course.  You could, for example, maintain multiple output files at
     10947the same time by choosing a symbol for each one and using it as the
     10948key to a hash table, where the value is a port, then returning the
     10949symbol to be stored in a @code{make} variable.
     10950
     10951@node Loading Objects,  , Guile Integration, Extending make
     10952@section Loading Dynamic Objects
     10953@cindex loaded objects
     10954@cindex objects, loaded
     10955@cindex extensions, loading
     10956
     10957@cartouche
     10958@quotation Warning
     10959The @code{load} directive and extension capability is considered a
     10960``technology preview'' in this release of GNU make.  We encourage you
     10961to experiment with this feature and we appreciate any feedback on it.
     10962However we cannot guarantee to maintain backward-compatibility in the
     10963next release.  Consider using GNU Guile instead for extending GNU make
     10964(@pxref{Guile Function, ,The @code{guile} Function}).
     10965@end quotation
     10966@end cartouche
     10967
     10968Many operating systems provide a facility for dynamically loading
     10969compiled objects.  If your system provides this facility, GNU
     10970@code{make} can make use of it to load dynamic objects at runtime,
     10971providing new capabilities which may then be invoked by your makefile.
     10972
     10973The @code{load} directive is used to load a dynamic object.  Once the
     10974object is loaded, a ``setup'' function will be invoked to allow the
     10975object to initialize itself and register new facilities with GNU
     10976@code{make}.  A dynamic object might include new @code{make} functions,
     10977for example, and the ``setup'' function would register them with GNU
     10978@code{make}'s function handling system.
     10979
     10980@menu
     10981* load Directive::              Loading dynamic objects as extensions.
     10982* Remaking Loaded Objects::     How loaded objects get remade.
     10983* Loaded Object API::           Programmatic interface for loaded objects.
     10984* Loaded Object Example::       Example of a loaded object
     10985@end menu
     10986
     10987@node load Directive, Remaking Loaded Objects, Loading Objects, Loading Objects
     10988@subsection The @code{load} Directive
     10989@cindex load directive
     10990@cindex extensions, load directive
     10991
     10992Objects are loaded into GNU @code{make} by placing the @code{load}
     10993directive into your makefile.  The syntax of the @code{load} directive
     10994is as follows:
     10995
     10996@findex load
     10997@example
     10998load @var{object-file} @dots{}
     10999@end example
     11000
     11001or:
     11002
     11003@example
     11004load @var{object-file}(@var{symbol-name}) @dots{}
     11005@end example
     11006
     11007The file @var{object-file} is dynamically loaded by GNU @code{make}.
     11008If @var{object-file} does not include a directory path then it is
     11009first looked for in the current directory.  If it is not found there,
     11010or a directory path is included, then system-specific paths will be
     11011searched.  If the load fails for any reason, @code{make} will print a
     11012message and exit.
     11013
     11014If the load succeeds @code{make} will invoke an initializing function.
     11015
     11016If @var{symbol-name} is provided, it will be used as the name of the
     11017initializing function.
     11018
     11019If no @var{symbol-name} is provided, the initializing function name is
     11020created by taking the base file name of @var{object-file}, up to the
     11021first character which is not a valid symbol name character
     11022(alphanumerics and underscores are valid symbol name characters).  To
     11023this prefix will be appended the suffix @code{_gmk_setup}.
     11024
     11025More than one object file may be loaded with a single @code{load}
     11026directive, and both forms of @code{load} arguments may be used in the
     11027same directive.
     11028
     11029The initializing function will be provided the file name and line
     11030number of the invocation of the @code{load} operation.  It should
     11031return a value of type @code{int}, which must be @code{0} on failure
     11032and non-@code{0} on success.  If the return value is @code{-1}, then
     11033GNU make will @emph{not} attempt to rebuild the object file
     11034(@pxref{Remaking Loaded Objects, ,How Loaded Objects Are Remade}).
     11035
     11036For example:
     11037
     11038@example
     11039load ../mk_funcs.so
     11040@end example
     11041
     11042will load the dynamic object @file{../mk_funcs.so}.  After the object
     11043is loaded, @code{make} will invoke the function (assumed to be defined
     11044by the shared object) @code{mk_funcs_gmk_setup}.
     11045
     11046On the other hand:
     11047
     11048@example
     11049load ../mk_funcs.so(init_mk_func)
     11050@end example
     11051
     11052will load the dynamic object @file{../mk_funcs.so}.  After the object
     11053is loaded, @code{make} will invoke the function @code{init_mk_func}.
     11054
     11055Regardless of how many times an object file appears in a @code{load}
     11056directive, it will only be loaded (and its setup function will only
     11057be invoked) once.
     11058
     11059@vindex .LOADED
     11060After an object has been successfully loaded, its file name is
     11061appended to the @code{.LOADED} variable.
     11062
     11063@findex -load
     11064If you would prefer that failure to load a dynamic object not be
     11065reported as an error, you can use the @code{-load} directive instead
     11066of @code{load}.  GNU @code{make} will not fail and no message will be
     11067generated if an object fails to load.  The failed object is not added
     11068to the @code{.LOADED} variable, which can then be consulted to
     11069determine if the load was successful.
     11070
     11071@node Remaking Loaded Objects, Loaded Object API, load Directive, Loading Objects
     11072@subsection How Loaded Objects Are Remade
     11073@cindex updating loaded objects
     11074@cindex remaking loaded objects
     11075@cindex loaded objects, remaking of
     11076
     11077Loaded objects undergo the same re-make procedure as makefiles
     11078(@pxref{Remaking Makefiles, ,How Makefiles Are Remade}).  If any
     11079loaded object is recreated, then @code{make} will start from scratch
     11080and re-read all the makefiles, and reload the object files again.  It
     11081is not necessary for the loaded object to do anything special to
     11082support this.@refill
     11083
     11084It's up to the makefile author to provide the rules needed for
     11085rebuilding the loaded object.
     11086
     11087@node Loaded Object API, Loaded Object Example, Remaking Loaded Objects, Loading Objects
     11088@subsection Loaded Object Interface
     11089@cindex loaded object API
     11090@cindex interface for loaded objects
     11091
     11092@cartouche
     11093@quotation Warning
     11094For this feature to be useful your extensions will need to invoke
     11095various functions internal to GNU @code{make}.  The programming
     11096interfaces provided in this release should not be considered stable:
     11097functions may be added, removed, or change calling signatures or
     11098implementations in future versions of GNU @code{make}.
     11099@end quotation
     11100@end cartouche
     11101
     11102To be useful, loaded objects must be able to interact with GNU
     11103@code{make}.  This interaction includes both interfaces the loaded
     11104object provides to makefiles and also interfaces @code{make} provides
     11105to the loaded object to manipulate @code{make}'s operation.
     11106
     11107The interface between loaded objects and @code{make} is defined by the
     11108@file{gnumake.h} C header file.  All loaded objects written in C
     11109should include this header file.  Any loaded object not written in C
     11110will need to implement the interface defined in this header file.
     11111
     11112Typically, a loaded object will register one or more new GNU
     11113@code{make} functions using the @code{gmk_add_function} routine from
     11114within its setup function.  The implementations of these @code{make}
     11115functions may make use of the @code{gmk_expand} and @code{gmk_eval}
     11116routines to perform their tasks, then optionally return a string as
     11117the result of the function expansion.
     11118
     11119@subsubheading Loaded Object Licensing
     11120@cindex loaded object licensing
     11121@cindex plugin_is_GPL_compatible
     11122
     11123Every dynamic extension should define the global symbol
     11124@code{plugin_is_GPL_compatible} to assert that it has been licensed
     11125under a GPL-compatible license.  If this symbol does not exist,
     11126@code{make} emits a fatal error and exits when it tries to load your
     11127extension.
     11128
     11129The declared type of the symbol should be @code{int}. It does not need
     11130to be in any allocated section, though.  The code merely asserts that
     11131the symbol exists in the global scope. Something like this is enough:
     11132
     11133@example
     11134int plugin_is_GPL_compatible;
     11135@end example
     11136
     11137@subsubheading Data Structures
     11138
     11139@table @code
     11140@item gmk_floc
     11141This structure represents a filename/location pair.  It is provided
     11142when defining items, so GNU @code{make} can inform the user later
     11143where the definition occurred if necessary.
     11144@end table
     11145
     11146@subsubheading Registering Functions
     11147@findex gmk_add_function
     11148
     11149There is currently one way for makefiles to invoke operations provided
     11150by the loaded object: through the @code{make} function call
     11151interface.  A loaded object can register one or more new functions
     11152which may then be invoked from within the makefile in the same way as
     11153any other function.
     11154
     11155Use @code{gmk_add_function} to create a new @code{make} function.  Its
     11156arguments are as follows:
     11157
     11158@table @code
     11159@item name
     11160The function name.  This is what the makefile should use to invoke the
     11161function.  The name must be between 1 and 255 characters long and it
     11162may only contain alphanumeric, period (@samp{.}), dash (@samp{-}), and
     11163underscore (@samp{_}) characters.  It may not begin with a period.
     11164
     11165@item func_ptr
     11166A pointer to a function that @code{make} will invoke when it expands
     11167the function in a makefile.  This function must be defined by the
     11168loaded object.
     11169
     11170@item min_args
     11171The minimum number of arguments the function will accept.  Must be
     11172between 0 and 255.  GNU @code{make} will check this and fail before
     11173invoking @code{func_ptr} if the function was invoked with too few
     11174arguments.
     11175
     11176@item max_args
     11177The maximum number of arguments the function will accept.  Must be
     11178between 0 and 255.  GNU @code{make} will check this and fail before
     11179invoking @code{func_ptr} if the function was invoked with too few
     11180arguments.  If the value is 0, then any number of arguments is
     11181accepted.  If the value is greater than 0, then it must be greater
     11182than or equal to @code{min_args}.
     11183
     11184@item flags
     11185Flags that specify how this function will operate; the desired flags
     11186should be OR'd together.  If the @code{GMK_FUNC_NOEXPAND} flag is
     11187given then the function arguments will not be expanded before the
     11188function is called; otherwise they will be expanded first.
     11189@end table
     11190
     11191@subsubheading Registered Function Interface
     11192@findex gmk_func_ptr
     11193
     11194A function registered with @code{make} must match the
     11195@code{gmk_func_ptr} type.  It will be invoked with three parameters:
     11196@code{name} (the name of the function), @code{argc} (the number of
     11197arguments to the function), and @code{argv} (an array of pointers to
     11198arguments to the function).  The last pointer (that is,
     11199@code{argv[argc]}) will be null (@code{0}).
     11200
     11201The return value of the function is the result of expanding the
     11202function.  If the function expands to nothing the return value may be
     11203null.  Otherwise, it must be a pointer to a string created with
     11204@code{gmk_alloc}.  Once the function returns, @code{make} owns this
     11205string and will free it when appropriate; it cannot be accessed by the
     11206loaded object.
     11207
     11208@subsubheading GNU @code{make} Facilities
     11209
     11210There are some facilities exported by GNU @code{make} for use by
     11211loaded objects.  Typically these would be run from within the
     11212setup function and/or the functions registered via
     11213@code{gmk_add_function}, to retrieve or modify the data @code{make}
     11214works with.
     11215
     11216@table @code
     11217@item gmk_expand
     11218@findex gmk_expand
     11219This function takes a string and expands it using @code{make}
     11220expansion rules.  The result of the expansion is returned in a
     11221nil-terminated string buffer.  The caller is responsible for calling
     11222@code{gmk_free} with a pointer to the returned buffer when done.
     11223
     11224@item gmk_eval
     11225@findex gmk_eval
     11226This function takes a buffer and evaluates it as a segment of makefile
     11227syntax.  This function can be used to define new variables, new rules,
     11228etc.  It is equivalent to using the @code{eval} @code{make} function.
     11229@end table
     11230
     11231Note that there is a difference between @code{gmk_eval} and calling
     11232@code{gmk_expand} with a string using the @code{eval} function: in
     11233the latter case the string will be expanded @emph{twice}; once by
     11234@code{gmk_expand} and then again by the @code{eval} function.  Using
     11235@code{gmk_eval} the buffer is only expanded once, at most (as it's
     11236read by the @code{make} parser).
     11237
     11238@subsubheading Memory Management
     11239
     11240Some systems allow for different memory management schemes.  Thus you
     11241should never pass memory that you've allocated directly to any
     11242@code{make} function, nor should you attempt to directly free any
     11243memory returned to you by any @code{make} function.  Instead, use the
     11244@code{gmk_alloc} and @code{gmk_free} functions.
     11245
     11246In particular, the string returned to @code{make} by a function
     11247registered using @code{gmk_add_function} @emph{must} be allocated
     11248using @code{gmk_alloc}, and the string returned from the @code{make}
     11249@code{gmk_expand} function @emph{must} be freed (when no longer
     11250needed) using @code{gmk_free}.
     11251
     11252@table @code
     11253@item gmk_alloc
     11254@findex gmk_alloc
     11255Return a pointer to a newly-allocated buffer.  This function will
     11256always return a valid pointer; if not enough memory is available
     11257@code{make} will exit.
     11258
     11259@item gmk_free
     11260@findex gmk_free
     11261Free a buffer returned to you by @code{make}.  Once the
     11262@code{gmk_free} function returns the string will no longer be valid.
     11263@end table
     11264
     11265@node Loaded Object Example,  , Loaded Object API, Loading Objects
     11266@subsection Example Loaded Object
     11267@cindex loaded object example
     11268@cindex example of loaded objects
     11269
     11270Let's suppose we wanted to write a new GNU @code{make} function that
     11271would create a temporary file and return its name.  We would like our
     11272function to take a prefix as an argument.  First we can write the
     11273function in a file @file{mk_temp.c}:
     11274
     11275@example
     11276@group
     11277#include <stdlib.h>
     11278#include <stdlib.h>
     11279#include <stdio.h>
     11280#include <string.h>
     11281#include <unistd.h>
     11282#include <errno.h>
     11283
     11284#include <gnumake.h>
     11285
     11286int plugin_is_GPL_compatible;
     11287
     11288char *
     11289gen_tmpfile(const char *nm, int argc, char **argv)
     11290@{
     11291  int fd;
     11292
     11293  /* Compute the size of the filename and allocate space for it.  */
     11294  int len = strlen (argv[0]) + 6 + 1;
     11295  char *buf = gmk_alloc (len);
     11296
     11297  strcpy (buf, argv[0]);
     11298  strcat (buf, "XXXXXX");
     11299
     11300  fd = mkstemp(buf);
     11301  if (fd >= 0)
     11302    @{
     11303      /* Don't leak the file descriptor.  */
     11304      close (fd);
     11305      return buf;
     11306    @}
     11307
     11308  /* Failure.  */
     11309  fprintf (stderr, "mkstemp(%s) failed: %s\n", buf, strerror (errno));
     11310  gmk_free (buf);
     11311  return NULL;
     11312@}
     11313
     11314int
     11315mk_temp_gmk_setup ()
     11316@{
     11317  /* Register the function with make name "mk-temp".  */
     11318  gmk_add_function ("mk-temp", gen_tmpfile, 1, 1, 1);
     11319  return 1;
     11320@}
     11321@end group
     11322@end example
     11323
     11324Next, we will write a makefile that can build this shared object, load
     11325it, and use it:
     11326
     11327@example
     11328@group
     11329all:
     11330        @@echo Temporary file: $(mk-temp tmpfile.)
     11331
     11332load mk_temp.so
     11333
     11334mk_temp.so: mk_temp.c
     11335        $(CC) -shared -fPIC -o $@ $<
     11336@end group
     11337@end example
     11338
     11339On MS-Windows, due to peculiarities of how shared objects are
     11340produced, the compiler needs to scan the @dfn{import library} produced
     11341when building @code{make}, typically called
     11342@file{libgnumake-@var{version}.dll.a}, where @var{version} is the
     11343version of the load object API.  So the recipe to produce a shared
     11344object will look on Windows like this (assuming the API version is 1):
     11345
     11346@example
     11347@group
     11348mk_temp.dll: mk_temp.c
     11349        $(CC) -shared -o $@ $< -lgnumake-1
     11350@end group
     11351@end example
     11352
     11353Now when you run @code{make} you'll see something like:
     11354
     11355@example
     11356$ make
     11357cc -shared -fPIC -o mk_temp.so mk_temp.c
     11358Temporary filename: tmpfile.A7JEwd
     11359@end example
     11360
     11361@node Integrating make, Features, Extending make, Top
     11362@chapter Integrating GNU @code{make}
     11363@cindex make integration
     11364
     11365GNU @code{make} is often one component in a larger system of tools,
     11366including integrated development environments, compiler toolchains,
     11367and others.  The role of @code{make} is to start commands and
     11368determine whether they succeeded or not: no special integration is
     11369needed to accomplish that.  However, sometimes it is convenient to
     11370bind @code{make} more tightly with other parts of the system, both
     11371higher-level (tools that invoke @code{make}) and lower-level (tools
     11372that @code{make} invokes).
     11373
     11374@menu
     11375* Job Slots::                   Share job slots with GNU @code{make}.
     11376* Terminal Output::             Control output to terminals.
     11377@end menu
     11378
     11379@node Job Slots, Terminal Output, Integrating make, Integrating make
     11380@section Sharing Job Slots with GNU @code{make}
     11381@cindex job slots, sharing
     11382@cindex tools, sharing job slots
     11383
     11384GNU @code{make} has the ability to run multiple recipes in parallel
     11385(@pxref{Parallel, ,Parallel Execution}) and to cap the total number of
     11386parallel jobs even across recursive invocations of @code{make}
     11387(@pxref{Options/Recursion, ,Communicating Options to a
     11388Sub-@code{make}}).  Tools that @code{make} invokes which are also able
     11389to run multiple operations in parallel, either using multiple threads
     11390or multiple processes, can be enhanced to participate in GNU
     11391@code{make}'s job management facility to ensure that the total number
     11392of active threads/processes running on the system does not exceed the
     11393maximum number of slots provided to GNU @code{make}. @refill
     11394
     11395@cindex jobserver
     11396GNU @code{make} uses a method called the ``jobserver'' to control the
     11397number of active jobs across recursive invocations.  The actual
     11398implementation of the jobserver varies across different operating
     11399systems, but some fundamental aspects are always true.
     11400
     11401First, only command lines that @code{make} understands to be recursive
     11402invocations of @code{make} (@pxref{MAKE Variable, ,How the @code{MAKE}
     11403Variable Works}) will have access to the jobserver.  When writing
     11404makefiles you must be sure to mark the command as recursive (most
     11405commonly by prefixing the command line with the @code{+} indicator
     11406(@pxref{Recursion, ,Recursive Use of @code{make}}).
     11407
     11408Second, @code{make} will provide information necessary for accessing
     11409the jobserver through the environment to its children, in the
     11410@code{MAKEFLAGS} environment variable.  Tools which want to
     11411participate in the jobserver protocol will need to parse this
     11412environment variable, as described in subsequent sections.
     11413
     11414Third, every command @code{make} starts has one implicit job slot
     11415reserved for it before it starts.  Any tool which wants to participate
     11416in the jobserver protocol should assume it can always run one job
     11417without having to contact the jobserver at all.
     11418
     11419Finally, it's critical that tools that participate in the jobserver
     11420protocol return the exact number of slots they obtained from the
     11421jobserver back to the jobserver before they exit, even under error
     11422conditions.  Remember that the implicit job slot should @strong{not}
     11423be returned to the jobserver!  Returning too few slots means that
     11424those slots will be lost for the rest of the build process; returning
     11425too many slots means that extra slots will be available.  The
     11426top-level @code{make} command will print an error message at the end
     11427of the build if it detects an incorrect number of slots available in
     11428the jobserver.
     11429
     11430As an example, suppose you are implementing a linker which provides
     11431for multithreaded operation.  You would like to enhance the linker so
     11432that if it is invoked by GNU @code{make} it can participate in the
     11433jobserver protocol to control how many threads are used during link.
     11434First you will need to modify the linker to determine if the
     11435@code{MAKEFLAGS} environment variable is set.  Next you will need to
     11436parse the value of that variable to determine if the jobserver is
     11437available, and how to access it.  If it is available then you can
     11438access it to obtain job slots controlling how much parallelism your
     11439tool can use.  Once done your tool must return those job slots back to
     11440the jobserver.
     11441
     11442@menu
     11443* POSIX Jobserver::             Using the jobserver on POSIX systems.
     11444* Windows Jobserver::           Using the jobserver on Windows systems.
     11445@end menu
     11446
     11447@node POSIX Jobserver, Windows Jobserver, Job Slots, Job Slots
     11448@subsection POSIX Jobserver Interaction
     11449@cindex jobserver on POSIX
     11450
     11451On POSIX systems the jobserver is implemented as a simple UNIX pipe.
     11452The pipe will be pre-loaded with one single-character token for each
     11453available job.  To obtain an extra slot you must read a single
     11454character from the jobserver pipe; to release a slot you must write a
     11455single character back into the jobserver pipe.
     11456
     11457To access the pipe you must parse the @code{MAKEFLAGS} variable and
     11458look for the argument string @code{--jobserver-auth=R,W} where
     11459@samp{R} and @samp{W} are non-negative integers representing file
     11460descriptors: @samp{R} is the read file descriptor and @samp{W} is the
     11461write file descriptor.
     11462
     11463It's important that when you release the job slot, you write back the
     11464same character you read from the pipe for that slot.  Don't assume
     11465that all tokens are the same character; different characters may have
     11466different meanings to GNU @code{make}.  The order is not important,
     11467since @code{make} has no idea in what order jobs will complete anyway.
     11468
     11469There are various error conditions you must consider to ensure your
     11470implementation is robust:
     11471
     11472@itemize @bullet
     11473@item
     11474Usually you will have a command-line argument controlling the parallel
     11475operation of your tool.  Consider whether your tool should detect
     11476situations where both the jobserver and the command-line argument are
     11477specified, and how it should react.
     11478
     11479@item
     11480If your tool determines that the @code{--jobserver-auth} option is
     11481available in @code{MAKEFLAGS} but that the file descriptors specified
     11482are closed, this means that the calling @code{make} process did not
     11483think that your tool was a recursive @code{make} invocation (e.g., the
     11484command line was not prefixed with a @code{+} character).  You should
     11485notify your users of this situation.
     11486
     11487@item
     11488Your tool should also examine the first word of the @code{MAKEFLAGS}
     11489variable and look for the character @code{n}.  If this character is
     11490present then @code{make} was invoked with the @samp{-n} option and
     11491your tool should stop without performing any operations.
     11492
     11493@item
     11494Your tool should be sure to write back the tokens it read, even under
     11495error conditions.  This includes not only errors in your tool but also
     11496outside influences such as interrupts (@code{SIGINT}), etc.  You may
     11497want to install signal handlers to manage this write-back.
     11498@end itemize
     11499
     11500@node Windows Jobserver,  , POSIX Jobserver, Job Slots
     11501@subsection Windows Jobserver Interaction
     11502@cindex jobserver on Windows
     11503
     11504On Windows systems the jobserver is implemented as a named semaphore.
     11505The semaphore will be set with an initial count equal to the number of
     11506available slots; to obtain a slot you must wait on the semaphore (with
     11507or without a timeout).  To release a slot, release the semaphore.
     11508
     11509To access the semaphore you must parse the @code{MAKEFLAGS} variable and
     11510look for the argument string @code{--jobserver-auth=NAME} where
     11511@samp{NAME} is the name of the named semaphore.  Use this name with
     11512@code{OpenSemaphore} to create a handle to the semaphore.
     11513
     11514There are various error conditions you must consider to ensure your
     11515implementation is robust:
     11516
     11517@itemize @bullet
     11518@item
     11519Usually you will have a command-line argument controlling the parallel
     11520operation of your tool.  Consider whether your tool should detect
     11521situations where both the jobserver and the command-line argument are
     11522specified, and how it should react.
     11523
     11524@item
     11525Your tool should be sure to release the semaphore for the tokens it
     11526read, even under error conditions.  This includes not only errors in
     11527your tool but also outside influences such as interrupts
     11528(@code{SIGINT}), etc.  You may want to install signal handlers to
     11529manage this write-back.
     11530@end itemize
     11531
     11532@node Terminal Output,  , Job Slots, Integrating make
     11533@section Synchronized Terminal Output
     11534@cindex parallel output to terminal
     11535@cindex terminal, output to
     11536
     11537Normally GNU @code{make} will invoke all commands with access to the
     11538same standard and error outputs that @code{make} itself was started
     11539with.  A number of tools will detect whether the output is a terminal
     11540or not-a-terminal, and use this information to change the output
     11541style.  For example if the output goes to a terminal the tool may add
     11542control characters that set color, or even change the location of the
     11543cursor.  If the output is not going to a terminal then these special
     11544control characters are not emitted so that they don't corrupt log
     11545files, etc.
     11546
     11547The @code{--output-sync} (@pxref{Parallel Output, ,Output During
     11548Parallel Output}) option will defeat the terminal detection.  When
     11549output synchronization is enabled GNU @code{make} arranges for all
     11550command output to be written to a file, so that its output can be
     11551written as a block without interference from other commands.  This
     11552means that all tools invoked by @code{make} will believe that their
     11553output is not going to be displayed on a terminal, even when it will
     11554be (because @code{make} will display it there after the command is
     11555completed).
     11556
     11557In order to facilitate tools which would like to determine whether or
     11558not their output will be displayed on a terminal, GNU @code{make} will
     11559set the @code{MAKE_TERMOUT} and @code{MAKE_TERMERR} environment
     11560variables before invoking any commands.  Tools which would like to
     11561determine whether standard or error output (respectively) will be
     11562displayed on a terminal can check these environment variables to
     11563determine if they exist and contain a non-empty value.  If so the tool
     11564can assume that the output will (eventually) be displayed on a
     11565terminal.  If the variables are not set or have an empty value, then
     11566the tool should fall back to its normal methods of detecting whether
     11567output is going to a terminal or not.
     11568
     11569The content of the variables can be parsed to determine the type of
     11570terminal which will be used to display the output.
     11571
     11572Similarly, environments which invoke @code{make} and would like to
     11573capture the output and eventually display it on a terminal (or some
     11574display which can interpret terminal control characters) can set these
     11575variables before invoking @code{make}.  GNU @code{make} will not
     11576modify these environment variables if they already exist when it
     11577starts.
     11578
     11579@node Features, Missing, Integrating make, Top
    1028611580@chapter Features of GNU @code{make}
    1028711581@cindex features of GNU @code{make}
     
    1035011644
    1035111645@item
    10352 The arrangement of lines and backslash-newline combinations in
     11646The arrangement of lines and backslash/newline combinations in
    1035311647recipes is retained when the recipes are printed, so they appear as
    1035411648they do in the makefile, except for the stripping of initial
     
    1039311687
    1039411688@item
     11689A number of different build tools that support parallelism also
     11690support collecting output and displaying as a single block.
     11691@xref{Parallel Output, ,Output During Parallel Execution}.
     11692
     11693@item
    1039511694Modified variable references using pattern substitution come from
    1039611695SunOS 4.  @xref{Reference, ,Basics of Variable References}.
     
    1042111720@code{-include} directive.)  The same feature appears with the name
    1042211721@code{sinclude} in SGI @code{make} and perhaps others.
     11722
     11723@item
     11724The @code{!=} shell assignment operator exists in many BSD of
     11725@code{make} and is purposefully implemented here to behave identically
     11726to those implementations.
     11727
     11728@item
     11729Various build management tools are implemented using scripting
     11730languages such as Perl or Python and thus provide a natural embedded
     11731scripting language, similar to GNU @code{make}'s integration of GNU
     11732Guile.
    1042311733@end itemize
    1042411734
     
    1052411834@item
    1052511835Various new built-in implicit rules.
    10526 @xref{Catalogue of Rules, ,Catalogue of Implicit Rules}.
     11836@xref{Catalogue of Rules, ,Catalogue of Built-In Rules}.
    1052711837
    1052811838@item
    10529 The built-in variable @samp{MAKE_VERSION} gives the version number of
    10530 @code{make}.
    10531 @vindex MAKE_VERSION
     11839Load dynamic objects which can modify the behavior of @code{make}.
     11840@xref{Loading Objects, ,Loading Dynamic Objects}.
    1053211841@end itemize
    1053311842
     
    1055011859
    1055111860This feature was not put into GNU @code{make} because of the
    10552 nonmodularity of putting knowledge into @code{make} of the internal
     11861non-modularity of putting knowledge into @code{make} of the internal
    1055311862format of archive file symbol tables.
    1055411863@xref{Archive Symbols, ,Updating Archive Symbol Directories}.
     
    1064811957This appendix summarizes the directives, text manipulation functions,
    1064911958and special variables which GNU @code{make} understands.
    10650 @xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Implicit Rules},
     11959@xref{Special Targets}, @ref{Catalogue of Rules, ,Catalogue of Built-In Rules},
    1065111960and @ref{Options Summary, ,Summary of Options},
    1065211961for other summaries.
     
    1065811967@itemx define @var{variable} =
    1065911968@itemx define @var{variable} :=
     11969@itemx define @var{variable} ::=
    1066011970@itemx define @var{variable} +=
    1066111971@itemx define @var{variable} ?=
     
    1087212182@xref{Eval Function, ,The @code{eval} Function}.
    1087312183
     12184@item $(file @var{op} @var{filename},@var{text})
     12185Expand the arguments, then open the file @var{filename} using mode
     12186@var{op} and write @var{text} to that file.@*
     12187@xref{File Function, ,The @code{file} Function}.
     12188
    1087412189@item $(value @var{var})
    1087512190Evaluates to the contents of the variable @var{var}, with no expansion
     
    1097112286@code{MAKE} Variable Works}.
    1097212287
     12288@item MAKE_VERSION
     12289
     12290The built-in variable @samp{MAKE_VERSION} expands to the version
     12291number of the GNU @code{make} program.
     12292@vindex MAKE_VERSION
     12293
     12294@item MAKE_HOST
     12295
     12296The built-in variable @samp{MAKE_HOST} expands to a string
     12297representing the host that GNU @code{make} was built to run on.
     12298@vindex MAKE_HOST
     12299
    1097312300@item MAKELEVEL
    1097412301
     
    1098712314through the environment from its parent.
    1098812315
     12316@item GNUMAKEFLAGS
     12317
     12318Other flags parsed by @code{make}.  You can set this in the environment or
     12319a makefile to set @code{make} command-line flags.  GNU @code{make}
     12320never sets this variable itself.  This variable is only needed if
     12321you'd like to set GNU @code{make}-specific flags in a POSIX-compliant
     12322makefile.  This variable will be seen by GNU @code{make} and ignored
     12323by other @code{make} implementations.  It's not needed if you only use
     12324GNU @code{make}; just use @code{MAKEFLAGS} directly.
     12325@xref{Options/Recursion, ,Communicating Options to a Sub-@code{make}}.
     12326
    1098912327@item MAKECMDGOALS
    1099012328
     
    1099512333@item CURDIR
    1099612334
    10997 Set to the pathname of the current working directory (after all
    10998 @code{-C} options are processed, if any).  Setting this variable has no
    10999 effect on the operation of @code{make}.@*
     12335Set to the absolute pathname of the current working directory (after
     12336all @code{-C} options are processed, if any).  Setting this variable
     12337has no effect on the operation of @code{make}.@*
    1100012338@xref{Recursion, ,Recursive Use of @code{make}}.
    1100112339
     
    1102512363Error messages are all either prefixed with the name of the program
    1102612364(usually @samp{make}), or, if the error is found in a makefile, the name
    11027 of the file and linenumber containing the problem.
     12365of the file and line number containing the problem.
    1102812366
    1102912367In the table below, these common prefixes are left off.
     
    1103912377signal of some type).  @xref{Errors, ,Errors in Recipes}.
    1104012378
    11041 If no @code{***} is attached to the message, then the subprocess failed
     12379If no @code{***} is attached to the message, then the sub-process failed
    1104212380but the rule in the makefile was prefixed with the @code{-} special
    1104312381character, so @code{make} ignored the error.
     
    1107912417If you want that file to be built, you will need to add a rule to your
    1108012418makefile describing how that target can be built.  Other possible
    11081 sources of this problem are typos in the makefile (if that filename is
     12419sources of this problem are typos in the makefile (if that file name is
    1108212420wrong) or a corrupted source tree (if that file is not supposed to be
    1108312421built, but rather only a prerequisite).
     
    1111312451This means you've defined a normal (recursive) @code{make} variable
    1111412452@var{xxx} that, when it's expanded, will refer to itself (@var{xxx}).
    11115 This is not allowed; either use simply-expanded variables (@code{:=}) or
    11116 use the append operator (@code{+=}).  @xref{Using Variables, ,How to Use
    11117 Variables}.
     12453This is not allowed; either use simply-expanded variables (@samp{:=}
     12454or @samp{::=}) or use the append operator (@samp{+=}).  @xref{Using
     12455Variables, ,How to Use Variables}.
    1111812456
    1111912457@item Unterminated variable reference.  Stop.
     
    1113012468@itemx target pattern contains no `%'.  Stop.
    1113112469@itemx mixed implicit and static pattern rules.  Stop.
    11132 These are generated for malformed static pattern rules.  The first means
    11133 there's no pattern in the target section of the rule; the second means
    11134 there are multiple patterns in the target section; the third means
    11135 the target doesn't contain a pattern character (@code{%}); and the
    11136 fourth means that all three parts of the static pattern rule contain
    11137 pattern characters (@code{%})--only the first two parts should.
     12470These are generated for malformed static pattern rules.  The first
     12471means there's no pattern in the target section of the rule; the second
     12472means there are multiple patterns in the target section; the third
     12473means the target doesn't contain a pattern character (@code{%}); and
     12474the fourth means that all three parts of the static pattern rule
     12475contain pattern characters (@code{%})--only the first two parts
     12476should.  If you see these errors and you aren't trying to create a
     12477static pattern rule, check the value of any variables in your target
     12478and prerequisite lists to be sure they do not contain colons.
    1113812479@xref{Static Usage, ,Syntax of Static Pattern Rules}.
    1113912480
     
    1116812509
    1116912510Here is the makefile for the GNU @code{tar} program.  This is a
    11170 moderately complex makefile.
     12511moderately complex makefile.  The first line uses a @code{#!} setting
     12512to allow the makefile to be executed directly.
    1117112513
    1117212514Because it is the first target, the default goal is @samp{all}.  An
     
    1120412546@example
    1120512547@group
     12548#!/usr/bin/make -f
    1120612549# Generated automatically from Makefile.in by configure.
    1120712550# Un*x Makefile for GNU tar program.
  • trunk/src/kmk/dosbuild.bat

    r2591 r3140  
    11@echo off
    2 rem Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
    3 rem 2008, 2009, 2010 Free Software Foundation, Inc.
     2rem Copyright (C) 1998-2016 Free Software Foundation, Inc.
    43rem This file is part of GNU Make.
    54rem
     
    2221@echo on
    2322gcc  -c -I. -I./glob -DHAVE_CONFIG_H -O2 -g commands.c -o commands.o
     23gcc  -c -I. -I./glob -DHAVE_CONFIG_H -O2 -g output.c -o output.o
    2424gcc  -c -I. -I./glob -DHAVE_CONFIG_H -O2 -g job.c -o job.o
    2525gcc  -c -I. -I./glob -DHAVE_CONFIG_H -O2 -g dir.c -o dir.o
     
    5353cd ..
    5454echo commands.o > respf.$$$
    55 for %%f in (job dir file misc main read remake rule implicit default variable) do echo %%f.o >> respf.$$$
     55for %%f in (job output dir file misc main read remake rule implicit default variable) do echo %%f.o >> respf.$$$
    5656for %%f in (expand function vpath hash strcache version ar arscan signame remote-stub getopt getopt1) do echo %%f.o >> respf.$$$
    5757echo glob/libglob.a >> respf.$$$
     58rem gcc  -c -I. -I./glob -DHAVE_CONFIG_H -O2 -g guile.c -o guile.o
     59rem echo guile.o >> respf.$$$
    5860@echo Linking...
    5961@echo on
  • trunk/src/kmk/expand.c

    r2771 r3140  
    11/* Variable expansion functions for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018
    2119#include <assert.h>
     
    3230/* Initially, any errors reported when expanding strings will be reported
    3331   against the file where the error appears.  */
    34 const struct floc **expanding_var = &reading_file;
     32const floc **expanding_var = &reading_file;
    3533
    3634/* The next two describe the variable output buffer.
     
    8482      unsigned int offset = ptr - variable_buffer;
    8583      variable_buffer_length = (newlen + 100 > 2 * variable_buffer_length
    86                                 ? newlen + 100
    87                                 : 2 * variable_buffer_length);
     84                                ? newlen + 100
     85                                : 2 * variable_buffer_length);
    8886      variable_buffer = xrealloc (variable_buffer, variable_buffer_length);
    8987      ptr = variable_buffer + offset;
     
    145143{
    146144  char *value;
    147   const struct floc *this_var;
    148   const struct floc **saved_varp;
     145  const floc *this_var;
     146  const floc **saved_varp;
    149147  struct variable_set_list *save = 0;
    150148  int set_reading = 0;
     
    170168      if (!v->exp_count)
    171169        /* Expanding V causes infinite recursion.  Lose.  */
    172         fatal (*expanding_var,
    173                _("Recursive variable `%s' references itself (eventually)"),
    174                v->name);
     170        OS (fatal, *expanding_var,
     171            _("Recursive variable '%s' references itself (eventually)"),
     172            v->name);
    175173      --v->exp_count;
    176174    }
     
    231229reference_recursive_variable (char *o, struct variable *v)
    232230{
    233   const struct floc *this_var;
    234   const struct floc **saved_varp;
     231  const floc *this_var;
     232  const floc **saved_varp;
    235233  int set_reading = 0;
    236234
     
    255253      if (!v->exp_count)
    256254        /* Expanding V causes infinite recursion.  Lose.  */
    257         fatal (*expanding_var,
    258                _("Recursive variable `%s' references itself (eventually)"),
    259                v->name);
     255        OS (fatal, *expanding_var,
     256            _("Recursive variable `%s' references itself (eventually)"),
     257            v->name);
    260258      --v->exp_count;
    261259    }
     
    346344   a null byte is found.
    347345
    348    Write the results to LINE, which must point into `variable_buffer'.  If
     346   Write the results to LINE, which must point into 'variable_buffer'.  If
    349347   LINE is NULL, start at the beginning of the buffer.
    350348   Return a pointer to LINE, or to the beginning of the buffer if LINE is
     
    356354  struct variable *v;
    357355  const char *p, *p1;
    358   char *abuf = NULL;
     356  char *save;
    359357  char *o;
    360358  unsigned int line_offset;
    361359
    362360  if (!line)
    363     line = initialize_variable_output();
     361    line = initialize_variable_output ();
    364362  o = line;
    365363  line_offset = line - variable_buffer;
     
    371369    }
    372370
    373   /* If we want a subset of the string, allocate a temporary buffer for it.
    374      Most of the functions we use here don't work with length limits.  */
    375   if (length > 0 && string[length] != '\0')
    376     {
    377       abuf = xmalloc(length+1);
    378       memcpy(abuf, string, length);
    379       abuf[length] = '\0';
    380       string = abuf;
    381     }
    382   p = string;
     371  /* We need a copy of STRING: due to eval, it's possible that it will get
     372     freed as we process it (it might be the value of a variable that's reset
     373     for example).  Also having a nil-terminated string is handy.  */
     374  save = length < 0 ? xstrdup (string) : xstrndup (string, length);
     375  p = save;
    383376
    384377  while (1)
     
    386379      /* Copy all following uninteresting chars all at once to the
    387380         variable output buffer, and skip them.  Uninteresting chars end
    388         at the next $ or the end of the input.  */
     381        at the next $ or the end of the input.  */
    389382
    390383      p1 = strchr (p, '$');
     
    393386
    394387      if (p1 == 0)
    395         break;
     388        break;
    396389      p = p1 + 1;
    397390
     
    399392
    400393      switch (*p)
    401         {
    402         case '$':
    403           /* $$ seen means output one $ to the variable output buffer.  */
    404           o = variable_buffer_output (o, p, 1);
    405           break;
    406 
    407         case '(':
    408         case '{':
    409           /* $(...) or ${...} is the general case of substitution.  */
    410           {
    411             char openparen = *p;
    412             char closeparen = (openparen == '(') ? ')' : '}';
     394        {
     395        case '$':
     396        case '\0':
     397          /* $$ or $ at the end of the string means output one $ to the
     398             variable output buffer.  */
     399          o = variable_buffer_output (o, p1, 1);
     400          break;
     401
     402        case '(':
     403        case '{':
     404          /* $(...) or ${...} is the general case of substitution.  */
     405          {
     406            char openparen = *p;
     407            char closeparen = (openparen == '(') ? ')' : '}';
    413408            const char *begp;
    414             const char *beg = p + 1;
    415             char *op;
     409            const char *beg = p + 1;
     410            char *op;
    416411            char *abeg = NULL;
    417             const char *end, *colon;
    418 
    419             op = o;
    420             begp = p;
    421             if (handle_function (&op, &begp))
    422               {
    423                 o = op;
    424                 p = begp;
    425                 break;
    426               }
    427 
    428             /* Is there a variable reference inside the parens or braces?
    429                If so, expand it before expanding the entire reference.  */
    430 
    431             end = strchr (beg, closeparen);
    432             if (end == 0)
     412            const char *end, *colon;
     413
     414            op = o;
     415            begp = p;
     416            if (handle_function (&op, &begp))
     417              {
     418                o = op;
     419                p = begp;
     420                break;
     421              }
     422
     423            /* Is there a variable reference inside the parens or braces?
     424               If so, expand it before expanding the entire reference.  */
     425
     426            end = strchr (beg, closeparen);
     427            if (end == 0)
    433428              /* Unterminated variable reference.  */
    434               fatal (*expanding_var, _("unterminated variable reference"));
    435             p1 = lindex (beg, end, '$');
    436             if (p1 != 0)
    437               {
    438                 /* BEG now points past the opening paren or brace.
    439                    Count parens or braces until it is matched.  */
    440                 int count = 0;
    441                 for (p = beg; *p != '\0'; ++p)
    442                   {
    443                     if (*p == openparen)
    444                       ++count;
    445                     else if (*p == closeparen && --count < 0)
    446                       break;
    447                   }
    448                 /* If COUNT is >= 0, there were unmatched opening parens
    449                    or braces, so we go to the simple case of a variable name
    450                    such as `$($(a)'.  */
    451                 if (count < 0)
    452                   {
    453                     abeg = expand_argument (beg, p); /* Expand the name.  */
    454                     beg = abeg;
    455                     end = strchr (beg, '\0');
    456                   }
    457               }
    458             else
    459               /* Advance P to the end of this reference.  After we are
     429              O (fatal, *expanding_var, _("unterminated variable reference"));
     430            p1 = lindex (beg, end, '$');
     431            if (p1 != 0)
     432              {
     433                /* BEG now points past the opening paren or brace.
     434                   Count parens or braces until it is matched.  */
     435                int count = 0;
     436                for (p = beg; *p != '\0'; ++p)
     437                  {
     438                    if (*p == openparen)
     439                      ++count;
     440                    else if (*p == closeparen && --count < 0)
     441                      break;
     442                  }
     443                /* If COUNT is >= 0, there were unmatched opening parens
     444                   or braces, so we go to the simple case of a variable name
     445                   such as '$($(a)'.  */
     446                if (count < 0)
     447                  {
     448                    abeg = expand_argument (beg, p); /* Expand the name.  */
     449                    beg = abeg;
     450                    end = strchr (beg, '\0');
     451                  }
     452              }
     453            else
     454              /* Advance P to the end of this reference.  After we are
    460455                 finished expanding this one, P will be incremented to
    461456                 continue the scan.  */
    462               p = end;
    463 
    464             /* This is not a reference to a built-in function and
    465                any variable references inside are now expanded.
    466                Is the resultant text a substitution reference?  */
    467 
    468             colon = lindex (beg, end, ':');
    469             if (colon)
    470               {
    471                 /* This looks like a substitution reference: $(FOO:A=B).  */
    472                 const char *subst_beg, *subst_end, *replace_beg, *replace_end;
    473 
    474                 subst_beg = colon + 1;
    475                 subst_end = lindex (subst_beg, end, '=');
    476                 if (subst_end == 0)
    477                   /* There is no = in sight.  Punt on the substitution
    478                      reference and treat this as a variable name containing
    479                      a colon, in the code below.  */
    480                   colon = 0;
    481                 else
    482                   {
    483                     replace_beg = subst_end + 1;
    484                     replace_end = end;
    485 
    486                     /* Extract the variable name before the colon
    487                        and look up that variable.  */
    488                     v = lookup_variable (beg, colon - beg);
    489                     if (v == 0)
    490                       warn_undefined (beg, colon - beg);
     457              p = end;
     458
     459            /* This is not a reference to a built-in function and
     460               any variable references inside are now expanded.
     461               Is the resultant text a substitution reference?  */
     462
     463            colon = lindex (beg, end, ':');
     464            if (colon)
     465              {
     466                /* This looks like a substitution reference: $(FOO:A=B).  */
     467                const char *subst_beg = colon + 1;
     468                const char *subst_end = lindex (subst_beg, end, '=');
     469                if (subst_end == 0)
     470                  /* There is no = in sight.  Punt on the substitution
     471                     reference and treat this as a variable name containing
     472                     a colon, in the code below.  */
     473                  colon = 0;
     474                else
     475                  {
     476                    const char *replace_beg = subst_end + 1;
     477                    const char *replace_end = end;
     478
     479                    /* Extract the variable name before the colon
     480                       and look up that variable.  */
     481                    v = lookup_variable (beg, colon - beg);
     482                    if (v == 0)
     483                      warn_undefined (beg, colon - beg);
    491484
    492485                    /* If the variable is not empty, perform the
    493486                       substitution.  */
    494                     if (v != 0 && *v->value != '\0')
    495                       {
    496                         char *pattern, *replace, *ppercent, *rpercent;
    497                         char *value = (v->recursive
     487                    if (v != 0 && *v->value != '\0')
     488                      {
     489                        char *pattern, *replace, *ppercent, *rpercent;
     490                        char *value = (v->recursive
    498491                                       ? recursively_expand (v)
    499                                        : v->value);
     492                                       : v->value);
    500493
    501494                        /* Copy the pattern and the replacement.  Add in an
     
    515508                        /* Look for %.  Set the percent pointers properly
    516509                           based on whether we find one or not.  */
    517                         ppercent = find_percent (pattern);
    518                         if (ppercent)
     510                        ppercent = find_percent (pattern);
     511                        if (ppercent)
    519512                          {
    520513                            ++ppercent;
     
    523516                              ++rpercent;
    524517                          }
    525                         else
     518                        else
    526519                          {
    527520                            ppercent = pattern;
     
    534527                                                 ppercent, rpercent);
    535528
    536                         if (v->recursive)
    537                           free (value);
    538                       }
    539                   }
    540               }
    541 
    542             if (colon == 0)
    543               /* This is an ordinary variable reference.
    544                  Look up the value of the variable.  */
    545                 o = reference_variable (o, beg, end - beg);
    546 
    547           if (abeg)
    548             free (abeg);
    549           }
    550           break;
    551 
    552         case '\0':
    553           break;
    554 
    555         default:
    556           if (isblank ((unsigned char)p[-1]))
    557             break;
    558 
    559           /* A $ followed by a random char is a variable reference:
    560              $a is equivalent to $(a).  */
     529                        if (v->recursive)
     530                          free (value);
     531                      }
     532                  }
     533              }
     534
     535            if (colon == 0)
     536              /* This is an ordinary variable reference.
     537                 Look up the value of the variable.  */
     538                o = reference_variable (o, beg, end - beg);
     539
     540            free (abeg);
     541          }
     542          break;
     543
     544        default:
     545          if (ISSPACE (p[-1]))
     546            break;
     547
     548          /* A $ followed by a random char is a variable reference:
     549             $a is equivalent to $(a).  */
    561550          o = reference_variable (o, p, 1);
    562551
    563           break;
    564         }
     552          break;
     553        }
    565554
    566555      if (*p == '\0')
    567         break;
     556        break;
    568557
    569558      ++p;
    570559    }
    571560
    572   if (abuf)
    573     free (abuf);
     561  free (save);
    574562
    575563  variable_buffer_output (o, "", 1);
     
    682670            if (end == 0)
    683671              /* Unterminated variable reference.  */
    684               fatal (*expanding_var, _("unterminated variable reference"));
     672              O (fatal, *expanding_var, _("unterminated variable reference"));
    685673            p1 = lindex (beg, end, '$');
    686674            if (p1 != 0)
     
    812800
    813801        default:
    814           if (isblank ((unsigned char)p[-1])) /* XXX: This looks incorrect, previous is '$' */
     802          if (ISBLANK (p[-1])) /* XXX: This looks incorrect, previous is '$' */
    815803            break;
    816804
     
    839827
    840828/* Scan LINE for variable references and expansion-function calls.
    841    Build in `variable_buffer' the result of expanding the references and calls.
     829   Build in 'variable_buffer' the result of expanding the references and calls.
    842830   Return the address of the resulting string, which is null-terminated
    843831   and is valid only until the next time this function is called.  */
     
    847835{
    848836#ifndef CONFIG_WITH_VALUE_LENGTH
    849   return variable_expand_string(NULL, line, (long)-1);
     837  return variable_expand_string (NULL, line, (long)-1);
    850838#else  /* CONFIG_WITH_VALUE_LENGTH */
    851839  char *s;
     
    865853   The text starting at STR and ending at END is variable-expanded
    866854   into a null-terminated string that is returned as the value.
    867    This is done without clobbering `variable_buffer' or the current
     855   This is done without clobbering 'variable_buffer' or the current
    868856   variable-expansion that is in progress.  */
    869857
     
    877865
    878866  if (str == end)
    879     return xstrdup("");
     867    return xstrdup ("");
    880868
    881869#ifndef CONFIG_WITH_VALUE_LENGTH
     
    893881  r = allocated_variable_expand (tmp);
    894882
    895   if (alloc)
    896     free (alloc);
     883  free (alloc);
    897884
    898885  return r;
     
    913900  char *result;
    914901  struct variable_set_list *savev;
    915   const struct floc *savef;
     902  const floc *savef;
    916903
    917904  if (file == 0)
     
    950937  char *result;
    951938  struct variable_set_list *savev;
    952   const struct floc *savef;
     939  const floc *savef;
    953940  long len = length == ~0U ? (long)-1 : (long)length;
    954941  char *eol;
     
    990977static char *
    991978variable_append (const char *name, unsigned int length,
    992                  const struct variable_set_list *set)
     979                 const struct variable_set_list *set, int local)
    993980{
    994981  const struct variable *v;
    995982  char *buf = 0;
     983  /* If this set is local and the next is not a parent, then next is local.  */
     984  int nextlocal = local && set->next_is_parent == 0;
    996985
    997986  /* If there's nothing left to check, return the empty buffer.  */
     
    1002991  v = lookup_variable_in_set (name, length, set->set);
    1003992
    1004   /* If there isn't one, look to see if there's one in a set above us.  */
    1005   if (!v)
    1006     return variable_append (name, length, set->next);
     993  /* If there isn't one, or this one is private, try the set above us.  */
     994  if (!v || (!local && v->private_var))
     995    return variable_append (name, length, set->next, nextlocal);
    1007996
    1008997  /* If this variable type is append, first get any upper values.
    1009998     If not, initialize the buffer.  */
    1010999  if (v->append)
    1011     buf = variable_append (name, length, set->next);
     1000    buf = variable_append (name, length, set->next, nextlocal);
    10121001  else
    10131002    buf = initialize_variable_output ();
     
    11151104  variable_buffer = 0;
    11161105
    1117   assert ((unsigned int)v->length == strlen (v->name)); /* bird */
    1118   val = variable_append (v->name, strlen (v->name), current_variable_set_list);
     1106  assert ((unsigned int)v->length == strlen (v->name)); /* bird */
     1107  val = variable_append (v->name, strlen (v->name), /** @todo optimize by using v->length! */
     1108                         current_variable_set_list, 1);
    11191109  variable_buffer_output (val, "", 1);
    11201110  val = variable_buffer;
  • trunk/src/kmk/expreval.c

    r3065 r3140  
    2828*   Header Files                                                               *
    2929*******************************************************************************/
    30 #include "make.h"
     30#include "makeint.h"
    3131#include <assert.h>
    3232
     
    162162    const char *psz;
    163163    /** The current file location, used for errors. */
    164     const struct floc *pFileLoc;
     164    const floc *pFileLoc;
    165165    /** Pending binary operator. */
    166166    PCEXPROP pPending;
     
    213213    va_end(va);
    214214
    215     fatal(pThis->pFileLoc, "%s", szTmp);
     215    OS(fatal,pThis->pFileLoc, "%s", szTmp);
    216216}
    217217
     
    284284     * Skip blanks.
    285285     */
    286     while (isblank(*psz))
     286    while (ISBLANK(*psz))
    287287        psz++;
    288288
     
    305305     * Recognize some exsotic prefixes here in addition to the two standard ones.
    306306     */
    307     if (*psz != '0' || psz[1] == '\0' || isblank((unsigned int)psz[1]))
     307    if (*psz != '0' || psz[1] == '\0' || ISBLANK(psz[1]))
    308308        uBase = 10;
    309309    else if (psz[1] == 'x' || psz[1] == 'X')
     
    370370            default:
    371371                /* is the rest white space? */
    372                 while (isspace((unsigned int)*psz))
     372                while (ISSPACE(*psz))
    373373                    psz++;
    374374                if (*psz != '\0')
     
    745745            EXPRINT64 iVal;
    746746            char const *psz = pVar->uVal.psz;
    747             while (isblank((unsigned char)*psz))
     747            while (ISBLANK(*psz))
    748748                psz++;
    749749            if (    *psz
     
    17731773
    17741774        /* spaces */
    1775         while (isspace((unsigned int)*psz))
     1775        while (ISSPACE(*psz))
    17761776            psz++;
    17771777        /* see what we've got. */
     
    18371837     * Eat white space and make sure there is something after it.
    18381838     */
    1839     while (isspace((unsigned int)*psz))
     1839    while (ISSPACE(*psz))
    18401840        psz++;
    18411841    if (!*psz)
     
    19351935                            break;
    19361936                    }
    1937                     if (isspace((unsigned char)ch))
     1937                    if (ISSPACE(ch))
    19381938                        break;
    19391939                }
     
    20812081 * @param   flocp   The file location, used for errors.
    20822082 */
    2083 int expr_eval_if_conditionals(const char *line, const struct floc *flocp)
     2083int expr_eval_if_conditionals(const char *line, const floc *flocp)
    20842084{
    20852085    /*
  • trunk/src/kmk/file.c

    r2788 r3140  
    11/* Target file management for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018
    2119#include <assert.h>
    2220
     21#include "filedef.h"
    2322#include "dep.h"
    24 #include "filedef.h"
    2523#include "job.h"
    2624#include "commands.h"
     
    6361#ifndef CONFIG_WITH_STRCACHE2
    6462  return_ISTRING_COMPARE (((struct file const *) x)->hname,
    65                           ((struct file const *) y)->hname);
     63                          ((struct file const *) y)->hname);
    6664#else  /* CONFIG_WITH_STRCACHE2 */
    6765  return ((struct file const *) x)->hname
     
    7068}
    7169
    72 #ifndef FILE_BUCKETS
    73 #define FILE_BUCKETS    1007
    74 #endif
    7570static struct hash_table files;
    7671
     
    9388  struct file *f;
    9489  struct file file_key;
    95 #if defined(VMS) && !defined(WANT_CASE_SENSITIVE_TARGETS)
     90#ifdef VMS
     91  int want_vmsify;
     92#ifndef WANT_CASE_SENSITIVE_TARGETS
    9693  char *lname;
     94#endif
    9795#endif
    9896
     
    103101     on the command line.  */
    104102#ifdef VMS
     103   want_vmsify = (strpbrk (name, "]>:^") != NULL);
    105104# ifndef WANT_CASE_SENSITIVE_TARGETS
    106105  if (*name != '.')
     
    118117  while (name[0] == '[' && name[1] == ']' && name[2] != '\0')
    119118      name += 2;
     119  while (name[0] == '<' && name[1] == '>' && name[2] != '\0')
     120      name += 2;
    120121#endif
    121122  while (name[0] == '.'
    122123#ifdef HAVE_DOS_PATHS
    123         && (name[1] == '/' || name[1] == '\\')
     124        && (name[1] == '/' || name[1] == '\\')
    124125#else
    125         && name[1] == '/'
    126 #endif
    127         && name[2] != '\0')
     126        && name[1] == '/'
     127#endif
     128        && name[2] != '\0')
    128129    {
    129130      name += 2;
    130131      while (*name == '/'
    131132#ifdef HAVE_DOS_PATHS
    132              || *name == '\\'
    133 #endif
    134              )
    135         /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
    136         ++name;
     133             || *name == '\\'
     134#endif
     135             )
     136        /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
     137        ++name;
    137138    }
    138139
    139140  if (*name == '\0')
    140     /* It was all slashes after a dot.  */
     141    {
     142      /* It was all slashes after a dot.  */
     143#if defined(_AMIGA)
     144      name = "";
     145#else
     146      name = "./";
     147#endif
    141148#if defined(VMS)
    142     name = "[]";
    143 #elif defined(_AMIGA)
    144     name = "";
    145 #else
    146     name = "./";
    147 #endif
    148 
     149      /* TODO - This section is probably not needed. */
     150      if (want_vmsify)
     151        name = "[]";
     152#endif
     153    }
    149154#ifndef CONFIG_WITH_STRCACHE2
    150155  file_key.hname = name;
     
    209214
    210215  assert (*name != '\0');
    211   assert (strcache_iscached (name));
     216  assert (! verify_flag || strcache_iscached (name));
    212217
    213218#if defined(VMS) && !defined(WANT_CASE_SENSITIVE_TARGETS)
     
    237242  f = *file_slot;
    238243  if (! HASH_VACANT (f) && !f->double_colon)
    239     return f;
     244    {
     245      f->builtin = 0;
     246      return f;
     247    }
    240248
    241249#ifndef CONFIG_WITH_ALLOC_CACHES
     
    245253#endif
    246254  new->name = new->hname = name;
    247   new->update_status = -1;
     255  new->update_status = us_none;
    248256
    249257  if (HASH_VACANT (f))
     
    271279
    272280/* Rehash FILE to NAME.  This is not as simple as resetting
    273    the `hname' member, since it must be put in a new hash bucket,
     281   the 'hname' member, since it must be put in a new hash bucket,
    274282   and possibly merged with an existing file called NAME.  */
    275283
     
    289297
    290298  /* If it's already that name, we're done.  */
     299  from_file->builtin = 0;
    291300  file_key.hname = to_hname;
    292301  if (! file_hash_cmp (from_file, &file_key))
     
    341350      else if (from_file->cmds != to_file->cmds)
    342351        {
     352          size_t l = strlen (from_file->name);
    343353          /* We have two sets of commands.  We will go with the
    344354             one given in the rule explicitly mentioning this name,
     
    346356          if (to_file->cmds->fileinfo.filenm != 0)
    347357            error (&from_file->cmds->fileinfo,
    348                    _("Recipe was specified for file `%s' at %s:%lu,"),
     358                   l + strlen (to_file->cmds->fileinfo.filenm) + INTSTR_LENGTH,
     359                   _("Recipe was specified for file '%s' at %s:%lu,"),
    349360                   from_file->name, to_file->cmds->fileinfo.filenm,
    350361                   to_file->cmds->fileinfo.lineno);
    351362          else
    352             error (&from_file->cmds->fileinfo,
    353                    _("Recipe for file `%s' was found by implicit rule search,"),
     363            error (&from_file->cmds->fileinfo, l,
     364                   _("Recipe for file '%s' was found by implicit rule search,"),
    354365                   from_file->name);
    355           error (&from_file->cmds->fileinfo,
    356                  _("but `%s' is now considered the same file as `%s'."),
     366          l += strlen (to_hname);
     367          error (&from_file->cmds->fileinfo, l,
     368                 _("but '%s' is now considered the same file as '%s'."),
    357369                 from_file->name, to_hname);
    358           error (&from_file->cmds->fileinfo,
    359                  _("Recipe for `%s' will be ignored in favor of the one for `%s'."),
     370          error (&from_file->cmds->fileinfo, l,
     371                 _("Recipe for '%s' will be ignored in favor of the one for '%s'."),
    360372                 to_hname, from_file->name);
    361373        }
     
    367379    {
    368380      if (to_file->multi_head)
    369         fatal (NILF, _("can't rename/merge multi target '%s' with multi target '%s'"),
    370                from_file->name, to_hname);
     381        OSS (fatal, NILF, _("can't rename/merge multi target '%s' with multi target '%s'"),
     382             from_file->name, to_hname);
    371383
    372384      to_file->multi_maybe = from_file->multi_maybe;
     
    411423
    412424  if (to_file->double_colon && from_file->is_target && !from_file->double_colon)
    413     fatal (NILF, _("can't rename single-colon `%s' to double-colon `%s'"),
    414            from_file->name, to_hname);
     425    OSS (fatal, NILF, _("can't rename single-colon '%s' to double-colon '%s'"),
     426         from_file->name, to_hname);
    415427  if (!to_file->double_colon  && from_file->double_colon)
    416428    {
    417429      if (to_file->is_target)
    418         fatal (NILF, _("can't rename double-colon `%s' to single-colon `%s'"),
    419                from_file->name, to_hname);
     430        OSS (fatal, NILF,
     431             _("can't rename double-colon '%s' to single-colon '%s'"),
     432             from_file->name, to_hname);
    420433      else
    421434        to_file->double_colon = from_file->double_colon;
     
    436449  MERGE (cmd_target);
    437450  MERGE (phony);
     451  MERGE (loaded);
    438452  MERGE (ignore_vpath);
    439453#undef MERGE
    440454
     455  to_file->builtin = 0;
    441456  from_file->renamed = to_file;
    442457}
    443458
    444459/* Rename FILE to NAME.  This is not as simple as resetting
    445    the `name' member, since it must be put in a new hash bucket,
     460   the 'name' member, since it must be put in a new hash bucket,
    446461   and possibly merged with an existing file called NAME.  */
    447462
     
    498513    if (! HASH_VACANT (*file_slot))
    499514      {
    500         struct file *f = *file_slot;
     515        struct file *f = *file_slot;
    501516        /* Is this file eligible for automatic deletion?
    502517           Yes, IFF: it's marked intermediate, it's not secondary, it wasn't
    503518           given on the command line, and it's either a -include makefile or
    504519           it's not precious.  */
    505         if (f->intermediate && (f->dontcare || !f->precious)
    506             && !f->secondary && !f->cmd_target)
    507           {
    508             int status;
    509             if (f->update_status == -1)
    510               /* If nothing would have created this file yet,
    511                  don't print an "rm" command for it.  */
    512               continue;
    513             if (just_print_flag)
    514               status = 0;
    515             else
    516               {
    517                 status = unlink (f->name);
    518                 if (status < 0 && errno == ENOENT)
    519                   continue;
    520               }
    521             if (!f->dontcare)
    522               {
    523                 if (sig)
    524                   error (NILF, _("*** Deleting intermediate file `%s'"), f->name);
    525                 else
    526                   {
    527                     if (! doneany)
    528                       DB (DB_BASIC, (_("Removing intermediate files...\n")));
    529                     if (!silent_flag)
    530                       {
    531                         if (! doneany)
    532                           {
    533                             fputs ("rm ", stdout);
    534                             doneany = 1;
    535                           }
    536                         else
    537                           putchar (' ');
    538                         fputs (f->name, stdout);
    539                         fflush (stdout);
    540                       }
    541                   }
    542                 if (status < 0)
    543                   perror_with_name ("unlink: ", f->name);
    544               }
    545           }
     520        if (f->intermediate && (f->dontcare || !f->precious)
     521            && !f->secondary && !f->cmd_target)
     522          {
     523            int status;
     524            if (f->update_status == us_none)
     525              /* If nothing would have created this file yet,
     526                 don't print an "rm" command for it.  */
     527              continue;
     528            if (just_print_flag)
     529              status = 0;
     530            else
     531              {
     532                status = unlink (f->name);
     533                if (status < 0 && errno == ENOENT)
     534                  continue;
     535              }
     536            if (!f->dontcare)
     537              {
     538                if (sig)
     539                  OS (error, NILF,
     540                      _("*** Deleting intermediate file '%s'"), f->name);
     541                else
     542                  {
     543                    if (! doneany)
     544                      DB (DB_BASIC, (_("Removing intermediate files...\n")));
     545                    if (!silent_flag)
     546                      {
     547                        if (! doneany)
     548                          {
     549                            fputs ("rm ", stdout);
     550                            doneany = 1;
     551                          }
     552                        else
     553                          putchar (' ');
     554                        fputs (f->name, stdout);
     555                        fflush (stdout);
     556                      }
     557                  }
     558                if (status < 0)
     559                  perror_with_name ("unlink: ", f->name);
     560              }
     561          }
    546562      }
    547563
     
    560576split_prereqs (char *p)
    561577{
    562   struct dep *new = PARSE_FILE_SEQ (&p, struct dep, '|', NULL, 0);
     578  struct dep *new = PARSE_FILE_SEQ (&p, struct dep, MAP_PIPE, NULL,
     579                                    PARSEFS_NONE);
    563580
    564581  if (*p)
     
    569586
    570587      ++p;
    571       ood = PARSE_FILE_SEQ (&p, struct dep, '\0', NULL, 0);
     588      ood = PARSE_SIMPLE_SEQ (&p, struct dep);
    572589
    573590      if (! new)
     
    728745      if (d->staticpattern)
    729746        {
    730           char *o;
    731           d->name = o = variable_expand ("");
     747          char *o = variable_expand ("");
    732748          o = subst_expand (o, name, "%", "$*", 1, 2, 0);
    733749          *o = '\0';
     
    802818}
    803819
    804 /* For each dependency of each file, make the `struct dep' point
    805    at the appropriate `struct file' (which may have to be created).
     820/* For each dependency of each file, make the 'struct dep' point
     821   at the appropriate 'struct file' (which may have to be created).
    806822
    807823   Also mark the files depended on by .PRECIOUS, .PHONY, .SILENT,
     
    911927    for (d = f->deps; d != 0; d = d->next)
    912928      for (f2 = d->file; f2 != 0; f2 = f2->prev)
    913         f2->precious = 1;
     929        f2->precious = 1;
    914930
    915931  for (f = lookup_file (".LOW_RESOLUTION_TIME"); f != 0; f = f->prev)
    916932    for (d = f->deps; d != 0; d = d->next)
    917933      for (f2 = d->file; f2 != 0; f2 = f2->prev)
    918         f2->low_resolution_time = 1;
     934        f2->low_resolution_time = 1;
    919935
    920936  for (f = lookup_file (".PHONY"); f != 0; f = f->prev)
    921937    for (d = f->deps; d != 0; d = d->next)
    922938      for (f2 = d->file; f2 != 0; f2 = f2->prev)
    923         {
    924           /* Mark this file as phony nonexistent target.  */
    925           f2->phony = 1;
     939        {
     940          /* Mark this file as phony nonexistent target.  */
     941          f2->phony = 1;
    926942          f2->is_target = 1;
    927           f2->last_mtime = NONEXISTENT_MTIME;
    928           f2->mtime_before_update = NONEXISTENT_MTIME;
    929         }
     943          f2->last_mtime = NONEXISTENT_MTIME;
     944          f2->mtime_before_update = NONEXISTENT_MTIME;
     945        }
    930946
    931947  for (f = lookup_file (".INTERMEDIATE"); f != 0; f = f->prev)
     
    959975    {
    960976      if (f->deps == 0)
    961         ignore_errors_flag = 1;
     977        ignore_errors_flag = 1;
    962978      else
    963         for (d = f->deps; d != 0; d = d->next)
    964           for (f2 = d->file; f2 != 0; f2 = f2->prev)
    965             f2->command_flags |= COMMANDS_NOERROR;
     979        for (d = f->deps; d != 0; d = d->next)
     980          for (f2 = d->file; f2 != 0; f2 = f2->prev)
     981            f2->command_flags |= COMMANDS_NOERROR;
    966982    }
    967983
     
    970986    {
    971987      if (f->deps == 0)
    972         silent_flag = 1;
     988        silent_flag = 1;
    973989      else
    974         for (d = f->deps; d != 0; d = d->next)
    975           for (f2 = d->file; f2 != 0; f2 = f2->prev)
    976             f2->command_flags |= COMMANDS_SILENT;
     990        for (d = f->deps; d != 0; d = d->next)
     991          for (f2 = d->file; f2 != 0; f2 = f2->prev)
     992            f2->command_flags |= COMMANDS_SILENT;
    977993    }
    978994
     
    10051021
    10061022
    1007 /* Set the `command_state' member of FILE and all its `also_make's.  */
     1023/* Set the 'command_state' member of FILE and all its 'also_make's.  */
    10081024
    10091025void
     
    10281044
    10291045FILE_TIMESTAMP
    1030 file_timestamp_cons (const char *fname, time_t s, int ns)
     1046file_timestamp_cons (const char *fname, time_t stamp, long int ns)
    10311047{
    10321048  int offset = ORDINARY_MTIME_MIN + (FILE_TIMESTAMP_HI_RES ? ns : 0);
     1049  FILE_TIMESTAMP s = stamp;
    10331050  FILE_TIMESTAMP product = (FILE_TIMESTAMP) s << FILE_TIMESTAMP_LO_BITS;
    10341051  FILE_TIMESTAMP ts = product + offset;
    10351052
    10361053  if (! (s <= FILE_TIMESTAMP_S (ORDINARY_MTIME_MAX)
    1037         && product <= ts && ts <= ORDINARY_MTIME_MAX))
     1054        && product <= ts && ts <= ORDINARY_MTIME_MAX))
    10381055    {
    10391056      char buf[FILE_TIMESTAMP_PRINT_LEN_BOUND + 1];
     1057      const char *f = fname ? fname : _("Current time");
    10401058      ts = s <= OLD_MTIME ? ORDINARY_MTIME_MIN : ORDINARY_MTIME_MAX;
    10411059      file_timestamp_sprintf (buf, ts);
    1042       error (NILF, _("%s: Timestamp out of range; substituting %s"),
    1043              fname ? fname : _("Current time"), buf);
     1060      OSS (error, NILF,
     1061           _("%s: Timestamp out of range; substituting %s"), f, buf);
    10441062    }
    10451063
     
    10661084    if (clock_gettime (CLOCK_REALTIME, &timespec) == 0)
    10671085      {
    1068         r = 1;
    1069         s = timespec.tv_sec;
    1070         ns = timespec.tv_nsec;
    1071         goto got_time;
     1086        r = 1;
     1087        s = timespec.tv_sec;
     1088        ns = timespec.tv_nsec;
     1089        goto got_time;
    10721090      }
    10731091  }
     
    10781096    if (gettimeofday (&timeval, 0) == 0)
    10791097      {
    1080         r = 1000;
    1081         s = timeval.tv_sec;
    1082         ns = timeval.tv_usec * 1000;
    1083         goto got_time;
     1098        r = 1000;
     1099        s = timeval.tv_sec;
     1100        ns = timeval.tv_usec * 1000;
     1101        goto got_time;
    10841102      }
    10851103  }
     
    11081126  if (tm)
    11091127    sprintf (p, "%04d-%02d-%02d %02d:%02d:%02d",
    1110              tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
    1111              tm->tm_hour, tm->tm_min, tm->tm_sec);
     1128             tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
     1129             tm->tm_hour, tm->tm_min, tm->tm_sec);
    11121130  else if (t < 0)
    11131131    sprintf (p, "%ld", (long) t);
     
    11611179  const struct file *f = item;
    11621180
     1181  /* If we're not using builtin targets, don't show them.
     1182
     1183     Ideally we'd be able to delete them altogether but currently there's no
     1184     facility to ever delete a file once it's been added.  */
     1185  if (no_builtin_rules_flag && f->builtin)
     1186    return;
     1187
    11631188  putchar ('\n');
     1189
     1190  if (f->cmds && f->cmds->recipe_prefix != cmd_prefix)
     1191    {
     1192      fputs (".RECIPEPREFIX = ", stdout);
     1193      cmd_prefix = f->cmds->recipe_prefix;
     1194      if (cmd_prefix != RECIPEPREFIX_DEFAULT)
     1195        putchar (cmd_prefix);
     1196      putchar ('\n');
     1197    }
     1198
     1199  if (f->variables != 0)
     1200    print_target_variables (f);
     1201
    11641202  if (!f->is_target)
    11651203    puts (_("# Not a target:"));
     
    12281266    }
    12291267#endif
    1230 
     1268  if (f->builtin)
     1269    puts (_("#  Builtin rule"));
    12311270  puts (f->tried_implicit
    12321271        ? _("#  Implicit rule search has been done.")
    12331272        : _("#  Implicit rule search has not been done."));
    12341273  if (f->stem != 0)
    1235     printf (_("#  Implicit/static pattern stem: `%s'\n"), f->stem);
     1274    printf (_("#  Implicit/static pattern stem: '%s'\n"), f->stem);
    12361275  if (f->intermediate)
    12371276    puts (_("#  File is an intermediate prerequisite."));
     
    12411280      fputs (_("#  Also makes:"), stdout);
    12421281      for (d = f->also_make; d != 0; d = d->next)
    1243         printf (" %s", dep_name (d));
     1282        printf (" %s", dep_name (d));
    12441283      putchar ('\n');
    12451284    }
     
    12691308    case cs_finished:
    12701309      switch (f->update_status)
    1271         {
    1272         case -1:
    1273           break;
    1274         case 0:
    1275           puts (_("#  Successfully updated."));
    1276           break;
    1277         case 1:
    1278           assert (question_flag);
    1279           puts (_("#  Needs to be updated (-q is set)."));
    1280           break;
    1281         case 2:
    1282           puts (_("#  Failed to be updated."));
    1283           break;
    1284         default:
    1285           puts (_("#  Invalid value in `update_status' member!"));
    1286           fflush (stdout);
    1287           fflush (stderr);
    1288           abort ();
    1289         }
     1310        {
     1311        case us_none:
     1312          break;
     1313        case us_success:
     1314          puts (_("#  Successfully updated."));
     1315          break;
     1316        case us_question:
     1317          assert (question_flag);
     1318          puts (_("#  Needs to be updated (-q is set)."));
     1319          break;
     1320        case us_failed:
     1321          puts (_("#  Failed to be updated."));
     1322          break;
     1323        }
    12901324      break;
    12911325    default:
    1292       puts (_("#  Invalid value in `command_state' member!"));
     1326      puts (_("#  Invalid value in 'command_state' member!"));
    12931327      fflush (stdout);
    12941328      fflush (stderr);
     
    13311365
    13321366#define VERIFY_CACHED(_p,_n) \
    1333     do{\
    1334         if (_p->_n && _p->_n[0] && !strcache_iscached (_p->_n)) \
    1335           error (NULL, "%s: Field '%s' not cached: %s\n", _p->name, # _n, _p->_n); \
     1367    do{                                                                       \
     1368        if (_p->_n && _p->_n[0] && !strcache_iscached (_p->_n))               \
     1369          error (NULL, strlen (_p->name) + CSTRLEN (# _n) + strlen (_p->_n),  \
     1370                 _("%s: Field '%s' not cached: %s"), _p->name, # _n, _p->_n); \
    13361371    }while(0)
    13371372
  • trunk/src/kmk/filedef.h

    r2788 r3140  
    11/* Definition of target file data structures for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    2018/* Structure that represents the info on one file
    2119   that the makefile says how to make.
    22    All of these are chained together through `next'.  */
     20   All of these are chained together through 'next'.  */
    2321
    2422#include "hash.h"
     
    3432                                   demaned by func_deps. */
    3533#endif
    36     struct commands *cmds;      /* Commands to execute for this target.  */
    37     int command_flags;          /* Flags OR'd in for cmds; see commands.h.  */
    38     const char *stem;           /* Implicit stem, if an implicit
     34    struct commands *cmds;      /* Commands to execute for this target.  */
     35    const char *stem;           /* Implicit stem, if an implicit
    3936                                   rule has been used */
    40     struct dep *also_make;      /* Targets that are made by making this.  */
    41     FILE_TIMESTAMP last_mtime;  /* File's modtime, if already known.  */
    42     FILE_TIMESTAMP mtime_before_update; /* File's modtime before any updating
    43                                            has been performed.  */
    44     struct file *prev;          /* Previous entry for same file name;
    45                                    used when there are multiple double-colon
    46                                    entries for the same file.  */
     37    struct dep *also_make;      /* Targets that are made by making this.  */
     38    struct file *prev;          /* Previous entry for same file name;
     39                                   used when there are multiple double-colon
     40                                   entries for the same file.  */
    4741    struct file *last;          /* Last entry for the same file name.  */
    4842
    4943    /* File that this file was renamed to.  After any time that a
    50        file could be renamed, call `check_renamed' (below).  */
     44       file could be renamed, call 'check_renamed' (below).  */
    5145    struct file *renamed;
    5246
     
    7872#endif
    7973
    80     short int update_status;    /* Status of the last attempt to update,
    81                                    or -1 if none has been made.  */
    82 
    83     enum cmd_state              /* State of the commands.  */
    84       {         /* Note: It is important that cs_not_started be zero.  */
    85         cs_not_started,         /* Not yet started.  */
    86         cs_deps_running,        /* Dep commands running.  */
    87         cs_running,             /* Commands running.  */
    88         cs_finished             /* Commands finished.  */
     74    FILE_TIMESTAMP last_mtime;  /* File's modtime, if already known.  */
     75    FILE_TIMESTAMP mtime_before_update; /* File's modtime before any updating
     76                                           has been performed.  */
     77    unsigned int considered;    /* equal to 'considered' if file has been
     78                                   considered on current scan of goal chain */
     79    int command_flags;          /* Flags OR'd in for cmds; see commands.h.  */
     80    enum update_status          /* Status of the last attempt to update.  */
     81      {
     82        us_success = 0,         /* Successfully updated.  Must be 0!  */
     83        us_none,                /* No attempt to update has been made.  */
     84        us_question,            /* Needs to be updated (-q is is set).  */
     85        us_failed               /* Update failed.  */
     86      } update_status ENUM_BITFIELD (2);
     87    enum cmd_state              /* State of the commands.  */
     88      {
     89        cs_not_started = 0,     /* Not yet started.  Must be 0!  */
     90        cs_deps_running,        /* Dep commands running.  */
     91        cs_running,             /* Commands running.  */
     92        cs_finished             /* Commands finished.  */
    8993      } command_state ENUM_BITFIELD (2);
    9094
    91     unsigned int precious:1;    /* Non-0 means don't delete file on quit */
    92     unsigned int low_resolution_time:1; /* Nonzero if this file's time stamp
    93                                            has only one-second resolution.  */
     95    unsigned int builtin:1;     /* True if the file is a builtin rule. */
     96    unsigned int precious:1;    /* Non-0 means don't delete file on quit */
     97    unsigned int loaded:1;      /* True if the file is a loaded object. */
     98    unsigned int low_resolution_time:1; /* Nonzero if this file's time stamp
     99                                           has only one-second resolution.  */
    94100    unsigned int tried_implicit:1; /* Nonzero if have searched
    95                                       for implicit rule for making
    96                                       this file; don't search again.  */
    97     unsigned int updating:1;    /* Nonzero while updating deps of this file */
    98     unsigned int updated:1;     /* Nonzero if this file has been remade.  */
    99     unsigned int is_target:1;   /* Nonzero if file is described as target.  */
    100     unsigned int cmd_target:1;  /* Nonzero if file was given on cmd line.  */
    101     unsigned int phony:1;       /* Nonzero if this is a phony file
    102                                    i.e., a prerequisite of .PHONY.  */
     101                                      for implicit rule for making
     102                                      this file; don't search again.  */
     103    unsigned int updating:1;    /* Nonzero while updating deps of this file */
     104    unsigned int updated:1;     /* Nonzero if this file has been remade.  */
     105    unsigned int is_target:1;   /* Nonzero if file is described as target.  */
     106    unsigned int cmd_target:1;  /* Nonzero if file was given on cmd line.  */
     107    unsigned int phony:1;       /* Nonzero if this is a phony file
     108                                   i.e., a prerequisite of .PHONY.  */
    103109    unsigned int intermediate:1;/* Nonzero if this is an intermediate file.  */
    104110    unsigned int secondary:1;   /* Nonzero means remove_intermediates should
    105111                                   not delete it.  */
    106     unsigned int dontcare:1;    /* Nonzero if no complaint is to be made if
    107                                    this target cannot be remade.  */
     112    unsigned int dontcare:1;    /* Nonzero if no complaint is to be made if
     113                                   this target cannot be remade.  */
    108114    unsigned int ignore_vpath:1;/* Nonzero if we threw out VPATH name.  */
    109115    unsigned int pat_searched:1;/* Nonzero if we already searched for
    110116                                   pattern-specific variables.  */
    111     unsigned int considered:1;  /* equal to 'considered' if file has been
    112                                    considered on current scan of goal chain */
    113117    unsigned int no_diag:1;     /* True if the file failed to update and no
    114118                                   diagnostics has been issued (dontcare). */
     
    130134
    131135
    132 extern struct file *suffix_file, *default_file;
     136extern struct file *default_file;
    133137
    134138
     
    147151void notice_finished_file (struct file *file);
    148152void init_hash_files (void);
     153void verify_file_data_base (void);
    149154char *build_target_list (char *old_list);
    150155void print_prereqs (const struct dep *deps);
    151156void print_file_data_base (void);
     157int try_implicit_rule (struct file *file, unsigned int depth);
     158int stemlen_compare (const void *v1, const void *v2);
    152159
    153160#if FILE_TIMESTAMP_HI_RES
    154161# define FILE_TIMESTAMP_STAT_MODTIME(fname, st) \
    155     file_timestamp_cons (fname, (st).st_mtime, (st).st_mtim.ST_MTIM_NSEC)
     162    file_timestamp_cons (fname, (st).st_mtime, (st).ST_MTIM_NSEC)
    156163#else
    157164# define FILE_TIMESTAMP_STAT_MODTIME(fname, st) \
     
    168175
    169176#define FILE_TIMESTAMP_S(ts) (((ts) - ORDINARY_MTIME_MIN) \
    170                               >> FILE_TIMESTAMP_LO_BITS)
     177                              >> FILE_TIMESTAMP_LO_BITS)
    171178#define FILE_TIMESTAMP_NS(ts) ((int) (((ts) - ORDINARY_MTIME_MIN) \
    172                                       & ((1 << FILE_TIMESTAMP_LO_BITS) - 1)))
     179                                      & ((1 << FILE_TIMESTAMP_LO_BITS) - 1)))
    173180
    174181/* Upper bound on length of string "YYYY-MM-DD HH:MM:SS.NNNNNNNNN"
    175    representing a file timestamp.  The upper bound is not necessarily 19,
     182   representing a file timestamp.  The upper bound is not necessarily 29,
    176183   since the year might be less than -999 or greater than 9999.
    177184
     
    190197   + 1 + 1 + 4 + 25)
    191198
    192 FILE_TIMESTAMP file_timestamp_cons (char const *, time_t, int);
     199FILE_TIMESTAMP file_timestamp_cons (char const *, time_t, long int);
    193200FILE_TIMESTAMP file_timestamp_now (int *);
    194201void file_timestamp_sprintf (char *p, FILE_TIMESTAMP ts);
     
    225232#else
    226233#define ORDINARY_MTIME_MAX ((FILE_TIMESTAMP_S (NEW_MTIME) \
    227                              << FILE_TIMESTAMP_LO_BITS) \
    228                             + ORDINARY_MTIME_MIN + FILE_TIMESTAMPS_PER_S - 1)
    229 #endif
    230 
    231 /* Modtime value to use for `infinitely new'.  We used to get the current time
    232    from the system and use that whenever we wanted `new'.  But that causes
     234                             << FILE_TIMESTAMP_LO_BITS) \
     235                            + ORDINARY_MTIME_MIN + FILE_TIMESTAMPS_PER_S - 1)
     236#endif
     237
     238/* Modtime value to use for 'infinitely new'.  We used to get the current time
     239   from the system and use that whenever we wanted 'new'.  But that causes
    233240   trouble when the machine running make and the machine holding a file have
    234    different ideas about what time it is; and can also lose for `force'
     241   different ideas about what time it is; and can also lose for 'force'
    235242   targets, which need to be considered newer than anything that depends on
    236243   them, even if said dependents' modtimes are in the future.  */
  • trunk/src/kmk/function.c

    r2912 r3140  
    11/* Builtin function expansion for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018#include "filedef.h"
    2119#include "variable.h"
     
    9492struct function_table_entry
    9593  {
     94    union {
     95      char *(*func_ptr) (char *output, char **argv, const char *fname);
     96      gmk_func_ptr alloc_func_ptr;
     97    } fptr;
    9698    const char *name;
    9799    unsigned char len;
    98100    unsigned char minimum_args;
    99101    unsigned char maximum_args;
    100     char expand_args;
    101     char *(*func_ptr) (char *output, char **argv, const char *fname);
     102    unsigned char expand_args:1;
     103    unsigned char alloc_fn:1;
    102104  };
    103105
     
    157159      o = variable_buffer_output (o, t, strlen (t));
    158160      if (rlen > 0)
    159         o = variable_buffer_output (o, replace, rlen);
     161        o = variable_buffer_output (o, replace, rlen);
    160162      return o;
    161163    }
     
    164166    {
    165167      if (by_word && slen == 0)
    166         /* When matching by words, the empty string should match
    167            the end of each word, rather than the end of the whole text.  */
    168         p = end_of_token (next_token (t));
     168        /* When matching by words, the empty string should match
     169           the end of each word, rather than the end of the whole text.  */
     170        p = end_of_token (next_token (t));
    169171      else
    170         {
    171           p = strstr (t, subst);
    172           if (p == 0)
    173             {
    174               /* No more matches.  Output everything left on the end.  */
    175               o = variable_buffer_output (o, t, strlen (t));
    176               return o;
    177             }
    178         }
     172        {
     173          p = strstr (t, subst);
     174          if (p == 0)
     175            {
     176              /* No more matches.  Output everything left on the end.  */
     177              o = variable_buffer_output (o, t, strlen (t));
     178              return o;
     179            }
     180        }
    179181
    180182      /* Output everything before this occurrence of the string to replace.  */
    181183      if (p > t)
    182         o = variable_buffer_output (o, t, p - t);
     184        o = variable_buffer_output (o, t, p - t);
    183185
    184186      /* If we're substituting only by fully matched words,
    185         or only at the ends of words, check that this case qualifies.  */
     187        or only at the ends of words, check that this case qualifies.  */
    186188      if (by_word
    187           && ((p > text && !isblank ((unsigned char)p[-1]))
    188               || (p[slen] != '\0' && !isblank ((unsigned char)p[slen]))))
    189         /* Struck out.  Output the rest of the string that is
    190            no longer to be replaced.  */
    191         o = variable_buffer_output (o, subst, slen);
     189          && ((p > text && !ISSPACE (p[-1]))
     190              || ! STOP_SET (p[slen], MAP_SPACE|MAP_NUL)))
     191        /* Struck out.  Output the rest of the string that is
     192           no longer to be replaced.  */
     193        o = variable_buffer_output (o, subst, slen);
    192194      else if (rlen > 0)
    193         /* Output the replacement string.  */
    194         o = variable_buffer_output (o, replace, rlen);
     195        /* Output the replacement string.  */
     196        o = variable_buffer_output (o, replace, rlen);
    195197
    196198      /* Advance T past the string to be replaced.  */
     
    240242    /* With no % in the pattern, this is just a simple substitution.  */
    241243    return subst_expand (o, text, pattern, replace,
    242                         strlen (pattern), strlen (replace), 1);
     244                        strlen (pattern), strlen (replace), 1);
    243245
    244246  /* Record the length of PATTERN before and after the %
     
    253255      /* Is it big enough to match?  */
    254256      if (len < pattern_prepercent_len + pattern_postpercent_len)
    255         fail = 1;
     257        fail = 1;
    256258
    257259      /* Does the prefix match? */
    258260      if (!fail && pattern_prepercent_len > 0
    259           && (*t != *pattern
    260               || t[pattern_prepercent_len - 1] != pattern_percent[-2]
    261               || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
    262         fail = 1;
     261          && (*t != *pattern
     262              || t[pattern_prepercent_len - 1] != pattern_percent[-2]
     263              || !strneq (t + 1, pattern + 1, pattern_prepercent_len - 1)))
     264        fail = 1;
    263265
    264266      /* Does the suffix match? */
    265267      if (!fail && pattern_postpercent_len > 0
    266           && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
    267               || t[len - pattern_postpercent_len] != *pattern_percent
    268               || !strneq (&t[len - pattern_postpercent_len],
    269                           pattern_percent, pattern_postpercent_len - 1)))
    270         fail = 1;
     268          && (t[len - 1] != pattern_percent[pattern_postpercent_len - 1]
     269              || t[len - pattern_postpercent_len] != *pattern_percent
     270              || !strneq (&t[len - pattern_postpercent_len],
     271                          pattern_percent, pattern_postpercent_len - 1)))
     272        fail = 1;
    271273
    272274      if (fail)
    273         /* It didn't match.  Output the string.  */
    274         o = variable_buffer_output (o, t, len);
     275        /* It didn't match.  Output the string.  */
     276        o = variable_buffer_output (o, t, len);
    275277      else
    276         {
    277           /* It matched.  Output the replacement.  */
    278 
    279           /* Output the part of the replacement before the %.  */
    280           o = variable_buffer_output (o, replace, replace_prepercent_len);
    281 
    282           if (replace_percent != 0)
    283             {
    284               /* Output the part of the matched string that
    285                 matched the % in the pattern.  */
    286               o = variable_buffer_output (o, t + pattern_prepercent_len,
    287                                           len - (pattern_prepercent_len
    288                                                 + pattern_postpercent_len));
    289               /* Output the part of the replacement after the %.  */
    290               o = variable_buffer_output (o, replace_percent,
    291                                           replace_postpercent_len);
    292             }
    293         }
     278        {
     279          /* It matched.  Output the replacement.  */
     280
     281          /* Output the part of the replacement before the %.  */
     282          o = variable_buffer_output (o, replace, replace_prepercent_len);
     283
     284          if (replace_percent != 0)
     285            {
     286              /* Output the part of the matched string that
     287                matched the % in the pattern.  */
     288              o = variable_buffer_output (o, t + pattern_prepercent_len,
     289                                          len - (pattern_prepercent_len
     290                                                + pattern_postpercent_len));
     291              /* Output the part of the replacement after the %.  */
     292              o = variable_buffer_output (o, replace_percent,
     293                                          replace_postpercent_len);
     294            }
     295        }
    294296
    295297      /* Output a space, but not if the replacement is "".  */
    296298      if (fail || replace_prepercent_len > 0
    297           || (replace_percent != 0 && len + replace_postpercent_len > 0))
    298         {
    299           o = variable_buffer_output (o, " ", 1);
    300           doneany = 1;
    301         }
     299          || (replace_percent != 0 && len + replace_postpercent_len > 0))
     300        {
     301          o = variable_buffer_output (o, " ", 1);
     302          doneany = 1;
     303        }
    302304    }
    303305#ifndef CONFIG_WITH_VALUE_LENGTH
     
    376378        if (!func_char_map[ch = s[idx]]) \
    377379          { \
    378             if (isblank (ch)) \
     380            if (ISBLANK (ch)) \
    379381              return lookup_function_in_hash_tab (s, idx); \
    380382            return 0; \
     
    401403      case 12: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); Z(12);
    402404      case 13: X(0); X(1); X(2); X(3); X(4); X(5); X(6); X(7); X(8); X(9); X(10); X(11); X(12);
    403         if ((ch = s[12]) == '\0' || isblank (ch))
     405        if ((ch = s[12]) == '\0' || ISBLANK (ch))
    404406          return lookup_function_in_hash_tab (s, 12);
    405407        return 0;
     
    418420      e++;
    419421    }
    420   if (ch == '\0' || isblank (ch))
     422  if (ch == '\0' || ISBLANK (ch))
    421423    return lookup_function_in_hash_tab (s, e - s);
    422424  return 0;
     
    430432lookup_function (const char *s)
    431433{
     434  struct function_table_entry function_table_entry_key;
    432435  const char *e = s;
    433   while (*e && ( (*e >= 'a' && *e <= 'z') || *e == '-'))
     436  while (STOP_SET (*e, MAP_USERFUNC))
    434437    e++;
    435   if (*e == '\0' || isblank ((unsigned char) *e))
    436     {
    437       struct function_table_entry function_table_entry_key;
    438       function_table_entry_key.name = s;
    439       function_table_entry_key.len = e - s;
    440 
    441       return hash_find_item (&function_table, &function_table_entry_key);
    442     }
    443   return 0;
     438
     439  if (e == s || !STOP_SET(*e, MAP_NUL|MAP_SPACE))
     440    return NULL;
     441
     442  function_table_entry_key.name = s;
     443  function_table_entry_key.len = e - s;
     444
     445  return hash_find_item (&function_table, &function_table_entry_key);
    444446}
    445447#endif /* original code */
     
    461463      percent = find_percent (new_chars);
    462464      if (percent == 0)
    463         return streq (new_chars, str);
     465        return streq (new_chars, str);
    464466      pattern = new_chars;
    465467    }
     
    496498    else if (*ptr == endparen)
    497499      {
    498         --count;
    499         if (count < 0)
    500           return NULL;
     500        --count;
     501        if (count < 0)
     502          return NULL;
    501503      }
    502504
     
    521523  unsigned int idx;
    522524
    523   chain = PARSE_FILE_SEQ (&line, struct nameseq, '\0', NULL,
    524                           /* We do not want parse_file_seq to strip `./'s.
     525  chain = PARSE_FILE_SEQ (&line, struct nameseq, MAP_NUL, NULL,
     526                          /* We do not want parse_file_seq to strip './'s.
    525527                             That would break examples like:
    526528                             $(patsubst ./%.c,obj/%.o,$(wildcard ./?*.c)).  */
     
    599601      tp = find_next_token (&list1_iterator, &len1);
    600602      if (tp != 0)
    601         o = variable_buffer_output (o, tp, len1);
     603        o = variable_buffer_output (o, tp, len1);
    602604
    603605      pp = find_next_token (&list2_iterator, &len2);
    604606      if (pp != 0)
    605         o = variable_buffer_output (o, pp, len2);
     607        o = variable_buffer_output (o, pp, len2);
    606608
    607609      if (tp != 0 || pp != 0)
    608         {
    609           o = variable_buffer_output (o, " ", 1);
    610           doneany = 1;
    611         }
     610        {
     611          o = variable_buffer_output (o, " ", 1);
     612          doneany = 1;
     613        }
    612614    }
    613615  while (tp != 0 || pp != 0);
     
    632634      default:
    633635      case o_invalid:
    634         abort ();
    635         break;
     636        abort ();
     637        break;
    636638      case o_default:
    637         o = variable_buffer_output (o, "default", 7);
    638         break;
     639        o = variable_buffer_output (o, "default", 7);
     640        break;
    639641      case o_env:
    640         o = variable_buffer_output (o, "environment", 11);
    641         break;
     642        o = variable_buffer_output (o, "environment", 11);
     643        break;
    642644      case o_file:
    643         o = variable_buffer_output (o, "file", 4);
    644         break;
     645        o = variable_buffer_output (o, "file", 4);
     646        break;
    645647      case o_env_override:
    646         o = variable_buffer_output (o, "environment override", 20);
    647         break;
     648        o = variable_buffer_output (o, "environment override", 20);
     649        break;
    648650      case o_command:
    649         o = variable_buffer_output (o, "command line", 12);
    650         break;
     651        o = variable_buffer_output (o, "command line", 12);
     652        break;
    651653      case o_override:
    652         o = variable_buffer_output (o, "override", 8);
    653         break;
     654        o = variable_buffer_output (o, "override", 8);
     655        break;
    654656      case o_automatic:
    655         o = variable_buffer_output (o, "automatic", 9);
    656         break;
     657        o = variable_buffer_output (o, "automatic", 9);
     658        break;
    657659#ifdef CONFIG_WITH_LOCAL_VARIABLES
    658660      case o_local:
     
    704706#endif /* CONFIG_WITH_WHERE_FUNCTION */
    705707
    706 #ifdef VMS
    707 # define IS_PATHSEP(c) ((c) == ']')
    708 #else
    709 # ifdef HAVE_DOS_PATHS
    710 #  define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
    711 # else
    712 #  define IS_PATHSEP(c) ((c) == '/')
    713 # endif
    714 #endif
    715 
    716 
    717708static char *
    718709func_notdir_suffix (char *o, char **argv, const char *funcname)
     
    724715  unsigned int len=0;
    725716
    726   int is_suffix = streq (funcname, "suffix");
     717  int is_suffix = funcname[0] == 's';
    727718  int is_notdir = !is_suffix;
     719  int stop = MAP_DIRSEP | (is_suffix ? MAP_DOT : 0);
     720#ifdef VMS
     721  /* For VMS list_iterator points to a comma separated list. To use the common
     722     [find_]next_token, create a local copy and replace the commas with
     723     spaces. Obviously, there is a problem if there is a ',' in the VMS filename
     724     (can only happen on ODS5), the same problem as with spaces in filenames,
     725     which seems to be present in make on all platforms. */
     726  char *vms_list_iterator = alloca(strlen(list_iterator) + 1);
     727  int i;
     728  for (i = 0; list_iterator[i]; i++)
     729    if (list_iterator[i] == ',')
     730      vms_list_iterator[i] = ' ';
     731    else
     732      vms_list_iterator[i] = list_iterator[i];
     733  vms_list_iterator[i] = list_iterator[i];
     734  while ((p2 = find_next_token((const char**) &vms_list_iterator, &len)) != 0)
     735#else
    728736  while ((p2 = find_next_token (&list_iterator, &len)) != 0)
    729     {
    730       const char *p = p2 + len;
    731 
    732 
    733       while (p >= p2 && (!is_suffix || *p != '.'))
    734         {
    735           if (IS_PATHSEP (*p))
    736             break;
    737           --p;
    738         }
     737#endif
     738    {
     739      const char *p = p2 + len - 1;
     740
     741      while (p >= p2 && ! STOP_SET (*p, stop))
     742        --p;
    739743
    740744      if (p >= p2)
    741         {
    742           if (is_notdir)
    743             ++p;
    744           else if (*p != '.')
    745             continue;
    746           o = variable_buffer_output (o, p, len - (p - p2));
    747         }
     745        {
     746          if (is_notdir)
     747            ++p;
     748          else if (*p != '.')
     749            continue;
     750          o = variable_buffer_output (o, p, len - (p - p2));
     751        }
    748752#ifdef HAVE_DOS_PATHS
    749753      /* Handle the case of "d:foo/bar".  */
    750       else if (streq (funcname, "notdir") && p2[0] && p2[1] == ':')
    751         {
    752           p = p2 + 2;
    753           o = variable_buffer_output (o, p, len - (p - p2));
    754         }
     754      else if (is_notdir && p2[0] && p2[1] == ':')
     755        {
     756          p = p2 + 2;
     757          o = variable_buffer_output (o, p, len - (p - p2));
     758        }
    755759#endif
    756760      else if (is_notdir)
    757         o = variable_buffer_output (o, p2, len);
     761        o = variable_buffer_output (o, p2, len);
    758762
    759763      if (is_notdir || p >= p2)
    760         {
    761           o = variable_buffer_output (o, " ", 1);
    762           doneany = 1;
    763         }
     764        {
     765#ifdef VMS
     766          if (vms_comma_separator)
     767            o = variable_buffer_output (o, ",", 1);
     768          else
     769#endif
     770          o = variable_buffer_output (o, " ", 1);
     771
     772          doneany = 1;
     773        }
    764774    }
    765775
     
    778788  const char *p3 = argv[0];
    779789  const char *p2;
    780   int doneany=0;
    781   unsigned int len=0;
    782 
    783   int is_basename= streq (funcname, "basename");
    784   int is_dir= !is_basename;
    785 
     790  int doneany = 0;
     791  unsigned int len = 0;
     792
     793  int is_basename = funcname[0] == 'b';
     794  int is_dir = !is_basename;
     795  int stop = MAP_DIRSEP | (is_basename ? MAP_DOT : 0) | MAP_NUL;
     796#ifdef VMS
     797  /* As in func_notdir_suffix ... */
     798  char *vms_p3 = alloca (strlen(p3) + 1);
     799  int i;
     800  for (i = 0; p3[i]; i++)
     801    if (p3[i] == ',')
     802      vms_p3[i] = ' ';
     803    else
     804      vms_p3[i] = p3[i];
     805  vms_p3[i] = p3[i];
     806  while ((p2 = find_next_token((const char**) &vms_p3, &len)) != 0)
     807#else
    786808  while ((p2 = find_next_token (&p3, &len)) != 0)
    787     {
    788       const char *p = p2 + len;
    789       while (p >= p2 && (!is_basename  || *p != '.'))
    790         {
    791           if (IS_PATHSEP (*p))
    792             break;
    793           --p;
    794         }
     809#endif
     810    {
     811      const char *p = p2 + len - 1;
     812      while (p >= p2 && ! STOP_SET (*p, stop))
     813        --p;
    795814
    796815      if (p >= p2 && (is_dir))
     
    805824      else if (is_dir)
    806825#ifdef VMS
    807         o = variable_buffer_output (o, "[]", 2);
     826        {
     827          extern int vms_report_unix_paths;
     828          if (vms_report_unix_paths)
     829            o = variable_buffer_output (o, "./", 2);
     830          else
     831            o = variable_buffer_output (o, "[]", 2);
     832        }
    808833#else
    809834#ifndef _AMIGA
     
    817842        o = variable_buffer_output (o, p2, len);
    818843
    819       o = variable_buffer_output (o, " ", 1);
     844#ifdef VMS
     845      if (vms_comma_separator)
     846        o = variable_buffer_output (o, ",", 1);
     847      else
     848#endif
     849        o = variable_buffer_output (o, " ", 1);
    820850      doneany = 1;
    821851    }
     
    827857  return o;
    828858}
     859
     860#if 1 /* rewrite to new MAP stuff? */
     861# ifdef VMS
     862#  define IS_PATHSEP(c) ((c) == ']')
     863# else
     864#  ifdef HAVE_DOS_PATHS
     865#   define IS_PATHSEP(c) ((c) == '/' || (c) == '\\')
     866#  else
     867#   define IS_PATHSEP(c) ((c) == '/')
     868#  endif
     869# endif
     870#endif
    829871
    830872#ifdef CONFIG_WITH_ROOT_FUNC
     
    848890      const char *p2 = p;
    849891
    850 #ifdef HAVE_DOS_PATHS
     892# ifdef HAVE_DOS_PATHS
    851893      if (   len >= 2
    852894          && p2[1] == ':'
     
    889931        p2 = NULL;
    890932
    891 #elif defined (VMS) || defined (AMGIA)
     933# elif defined (VMS) || defined (AMGIA)
    892934      /* XXX: VMS and AMGIA */
    893       fatal (NILF, _("$(root ) is not implemented on this platform"));
    894 #else
     935      O (fatal, NILF, _("$(root ) is not implemented on this platform"));
     936# else
    895937      if (IS_PATHSEP(*p2))
    896938        {
     
    900942      else
    901943        p2 = NULL;
    902 #endif
     944# endif
    903945      if (p2 != NULL)
    904946        {
     
    938980      const char *p2 = p;
    939981
    940 #ifdef HAVE_DOS_PATHS
     982# ifdef HAVE_DOS_PATHS
    941983      if (   len >= 2
    942984          && p2[1] == ':'
     
    9761018        }
    9771019
    978 #elif defined (VMS) || defined (AMGIA)
     1020# elif defined (VMS) || defined (AMGIA)
    9791021      /* XXX: VMS and AMGIA */
    980       fatal (NILF, _("$(root ) is not implemented on this platform"));
    981 #endif
     1022      O (fatal, NILF, _("$(root ) is not implemented on this platform"));
     1023# endif
    9821024
    9831025      /* Exclude all subsequent / leading path separators. */
     
    10071049  int fixlen = strlen (argv[0]);
    10081050  const char *list_iterator = argv[1];
    1009   int is_addprefix = streq (funcname, "addprefix");
     1051  int is_addprefix = funcname[3] == 'p';
    10101052  int is_addsuffix = !is_addprefix;
    10111053
     
    10171059    {
    10181060      if (is_addprefix)
    1019         o = variable_buffer_output (o, argv[0], fixlen);
     1061        o = variable_buffer_output (o, argv[0], fixlen);
    10201062      o = variable_buffer_output (o, p, len);
    10211063      if (is_addsuffix)
    1022         o = variable_buffer_output (o, argv[0], fixlen);
     1064        o = variable_buffer_output (o, argv[0], fixlen);
    10231065      o = variable_buffer_output (o, " ", 1);
    10241066      doneany = 1;
     
    10361078{
    10371079  o = subst_expand (o, argv[2], argv[0], argv[1], strlen (argv[0]),
    1038                     strlen (argv[1]), 0);
     1080                    strlen (argv[1]), 0);
    10391081
    10401082  return o;
     
    10631105    rc = 1;
    10641106  else
    1065 #if 1 /* FIXME: later */
    1066     fatal (*expanding_var,
    1067            _("second argument to `%s' function must be `name' or `value', not `%s'"),
    1068            funcname, arg1);
    1069 #else
     1107# if 1 /* FIXME: later */
     1108    OSS (fatal, *expanding_var,
     1109         _("second argument to `%s' function must be `name' or `value', not `%s'"),
     1110         funcname, arg1);
     1111# else
    10701112    {
    10711113      /* check the expanded form */
     
    10801122        rc = 1;
    10811123      else
    1082         fatal (*expanding_var,
    1083                _("second argument to `%s' function must be `name' or `value', not `%s'"),
    1084                funcname, exp);
     1124        OSS (fatal, *expanding_var,
     1125             _("second argument to `%s' function must be `name' or `value', not `%s'"),
     1126             funcname, exp);
    10851127      free (exp);
    10861128    }
    1087 #endif
     1129# endif
    10881130
    10891131  return rc;
     
    11921234  char buf[20];
    11931235
    1194   while (find_next_token (&word_iterator, (unsigned int *) 0) != 0)
     1236  while (find_next_token (&word_iterator, NULL) != 0)
    11951237    ++i;
    11961238
     
    12091251strip_whitespace (const char **begpp, const char **endpp)
    12101252{
    1211   while (*begpp <= *endpp && isspace ((unsigned char)**begpp))
     1253  while (*begpp <= *endpp && ISSPACE (**begpp))
    12121254    (*begpp) ++;
    1213   while (*endpp >= *begpp && isspace ((unsigned char)**endpp))
     1255  while (*endpp >= *begpp && ISSPACE (**endpp))
    12141256    (*endpp) --;
    12151257  return (char *)*begpp;
     
    12241266
    12251267  for (; s <= end; ++s)
    1226     if (!ISDIGIT (*s))  /* ISDIGIT only evals its arg once: see make.h.  */
     1268    if (!ISDIGIT (*s))  /* ISDIGIT only evals its arg once: see makeint.h.  */
    12271269      break;
    12281270
    12291271  if (s <= end || end - beg < 0)
    1230     fatal (*expanding_var, "%s: '%s'", msg, beg);
     1272    OSS (fatal, *expanding_var, "%s: '%s'", msg, beg);
    12311273}
    12321274
     
    12411283
    12421284  /* Check the first argument.  */
    1243   check_numeric (argv[0], _("non-numeric first argument to `word' function"));
     1285  check_numeric (argv[0], _("non-numeric first argument to 'word' function"));
    12441286  i = atoi (argv[0]);
    12451287
    12461288  if (i == 0)
    1247     fatal (*expanding_var,
    1248            _("first argument to `word' function must be greater than 0"));
     1289    O (fatal, *expanding_var,
     1290       _("first argument to 'word' function must be greater than 0"));
    12491291
    12501292  end_p = argv[1];
     
    12661308  /* Check the arguments.  */
    12671309  check_numeric (argv[0],
    1268                  _("non-numeric first argument to `wordlist' function"));
     1310                 _("non-numeric first argument to 'wordlist' function"));
    12691311  check_numeric (argv[1],
    1270                  _("non-numeric second argument to `wordlist' function"));
     1312                 _("non-numeric second argument to 'wordlist' function"));
    12711313
    12721314  start = atoi (argv[0]);
    12731315  if (start < 1)
    1274     fatal (*expanding_var,
    1275            "invalid first argument to `wordlist' function: `%d'", start);
     1316    ON (fatal, *expanding_var,
     1317        "invalid first argument to 'wordlist' function: '%d'", start);
    12761318
    12771319  count = atoi (argv[1]) - start + 1;
     
    13271369  struct variable *var;
    13281370
     1371  /* Clean up the variable name by removing whitespace.  */
     1372  char *vp = next_token (varname);
     1373  end_of_token (vp)[0] = '\0';
     1374
    13291375  push_new_variable_scope ();
    1330   var = define_variable (varname, strlen (varname), "", o_automatic, 0);
     1376  var = define_variable (vp, strlen (vp), "", o_automatic, 0);
    13311377
    13321378  /* loop through LIST,  put the value in VAR and expand BODY */
     
    13901436
    13911437    install_variable_buffer (&buf, &buf_len);
    1392     eval_buffer (text, text + text_len);
     1438    eval_buffer (text, NULL, text + text_len);
    13931439    restore_variable_buffer (buf, buf_len);
    13941440}
     
    14971543    return result;
    14981544  return_STRING_COMPARE (((struct a_word const *) x)->str,
    1499                         ((struct a_word const *) y)->str);
     1545                        ((struct a_word const *) y)->str);
    15001546}
    15011547
     
    15061552  char *percent;
    15071553  int length;
    1508   int save_c;
    15091554};
    15101555
     
    15201565
    15211566  struct hash_table a_word_table;
    1522   int is_filter = streq (funcname, "filter");
     1567  int is_filter = funcname[CSTRLEN ("filter")] == '\0';
    15231568  const char *pat_iterator = argv[0];
    15241569  const char *word_iterator = argv[1];
     
    15291574  unsigned int len;
    15301575
    1531   /* Chop ARGV[0] up into patterns to match against the words.  */
     1576  /* Chop ARGV[0] up into patterns to match against the words.
     1577     We don't need to preserve it because our caller frees all the
     1578     argument memory anyway.  */
    15321579
    15331580  pattail = &pathead;
     
    15401587
    15411588      if (*pat_iterator != '\0')
    1542         ++pat_iterator;
     1589        ++pat_iterator;
    15431590
    15441591      pat->str = p;
    1545       pat->length = len;
    1546       pat->save_c = p[len];
    15471592      p[len] = '\0';
    15481593      pat->percent = find_percent (p);
    15491594      if (pat->percent == 0)
    1550         literals++;
     1595        literals++;
     1596
     1597      /* find_percent() might shorten the string so LEN is wrong.  */
     1598      pat->length = strlen (pat->str);
    15511599    }
    15521600  *pattail = 0;
     
    15631611
    15641612      if (*word_iterator != '\0')
    1565         ++word_iterator;
     1613        ++word_iterator;
    15661614
    15671615      p[len] = '\0';
     
    15811629                 a_word_hash_cmp);
    15821630      for (wp = wordhead; wp != 0; wp = wp->next)
    1583         {
    1584           struct a_word *owp = hash_insert (&a_word_table, wp);
    1585           if (owp)
    1586             wp->chain = owp;
    1587         }
     1631        {
     1632          struct a_word *owp = hash_insert (&a_word_table, wp);
     1633          if (owp)
     1634            wp->chain = owp;
     1635        }
    15881636    }
    15891637
     
    15941642      /* Run each pattern through the words, killing words.  */
    15951643      for (pp = pathead; pp != 0; pp = pp->next)
    1596         {
    1597           if (pp->percent)
    1598             for (wp = wordhead; wp != 0; wp = wp->next)
    1599               wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
    1600           else if (hashing)
    1601             {
    1602               struct a_word a_word_key;
    1603               a_word_key.str = pp->str;
    1604               a_word_key.length = pp->length;
    1605               wp = hash_find_item (&a_word_table, &a_word_key);
    1606               while (wp)
    1607                 {
    1608                   wp->matched |= 1;
    1609                   wp = wp->chain;
    1610                 }
    1611             }
    1612           else
    1613             for (wp = wordhead; wp != 0; wp = wp->next)
    1614               wp->matched |= (wp->length == pp->length
    1615                               && strneq (pp->str, wp->str, wp->length));
    1616         }
     1644        {
     1645          if (pp->percent)
     1646            for (wp = wordhead; wp != 0; wp = wp->next)
     1647              wp->matched |= pattern_matches (pp->str, pp->percent, wp->str);
     1648          else if (hashing)
     1649            {
     1650              struct a_word a_word_key;
     1651              a_word_key.str = pp->str;
     1652              a_word_key.length = pp->length;
     1653              wp = hash_find_item (&a_word_table, &a_word_key);
     1654              while (wp)
     1655                {
     1656                  wp->matched |= 1;
     1657                  wp = wp->chain;
     1658                }
     1659            }
     1660          else
     1661            for (wp = wordhead; wp != 0; wp = wp->next)
     1662              wp->matched |= (wp->length == pp->length
     1663                              && strneq (pp->str, wp->str, wp->length));
     1664        }
    16171665
    16181666      /* Output the words that matched (or didn't, for filter-out).  */
    16191667      for (wp = wordhead; wp != 0; wp = wp->next)
    1620         if (is_filter ? wp->matched : !wp->matched)
    1621           {
    1622             o = variable_buffer_output (o, wp->str, strlen (wp->str));
    1623             o = variable_buffer_output (o, " ", 1);
    1624             doneany = 1;
    1625           }
     1668        if (is_filter ? wp->matched : !wp->matched)
     1669          {
     1670            o = variable_buffer_output (o, wp->str, strlen (wp->str));
     1671            o = variable_buffer_output (o, " ", 1);
     1672            doneany = 1;
     1673          }
    16261674
    16271675      if (doneany)
    1628         /* Kill the last space.  */
    1629         --o;
    1630     }
    1631 
    1632   for (pp = pathead; pp != 0; pp = pp->next)
    1633     pp->str[pp->length] = pp->save_c;
     1676        /* Kill the last space.  */
     1677        --o;
     1678    }
    16341679
    16351680  if (hashing)
     
    16511696      const char *word_start;
    16521697
    1653       while (isspace ((unsigned char)*p))
    1654         ++p;
     1698      NEXT_TOKEN (p);
    16551699      word_start = p;
    1656       for (i=0; *p != '\0' && !isspace ((unsigned char)*p); ++p, ++i)
    1657         {}
     1700      for (i=0; *p != '\0' && !ISSPACE (*p); ++p, ++i)
     1701        {}
    16581702      if (!i)
    1659         break;
     1703        break;
    16601704      o = variable_buffer_output (o, word_start, i);
    16611705      o = variable_buffer_output (o, " ", 1);
     
    16971741  strcpy (p, *argvp);
    16981742
    1699   switch (*funcname) {
     1743  switch (*funcname)
     1744    {
    17001745    case 'e':
    1701       fatal (reading_file, "%s", msg);
     1746      OS (fatal, reading_file, "%s", msg);
    17021747
    17031748    case 'w':
    1704       error (reading_file, "%s", msg);
     1749      OS (error, reading_file, "%s", msg);
    17051750      break;
    17061751
    17071752    case 'i':
    1708       printf ("%s\n", msg);
    1709       fflush(stdout);
     1753      outputs (0, msg);
     1754      outputs (0, "\n");
    17101755      break;
    17111756
    17121757    default:
    1713       fatal (*expanding_var, "Internal error: func_error: '%s'", funcname);
    1714   }
     1758      OS (fatal, *expanding_var, "Internal error: func_error: '%s'", funcname);
     1759    }
    17151760
    17161761  /* The warning function expands to the empty string.  */
     
    17301775  char *p;
    17311776  unsigned int len;
    1732   int i;
    17331777
    17341778  /* Find the maximum number of words we'll have.  */
    17351779  t = argv[0];
    1736   wordi = 1;
    1737   while (*t != '\0')
    1738     {
    1739       char c = *(t++);
    1740 
    1741       if (! isspace ((unsigned char)c))
    1742         continue;
    1743 
     1780  wordi = 0;
     1781  while ((p = find_next_token (&t, NULL)) != 0)
     1782    {
     1783      ++t;
    17441784      ++wordi;
    1745 
    1746       while (isspace ((unsigned char)*t))
    1747         ++t;
    1748     }
    1749 
    1750   words = xmalloc (wordi * sizeof (char *));
     1785    }
     1786
     1787  words = xmalloc ((wordi == 0 ? 1 : wordi) * sizeof (char *));
    17511788
    17521789  /* Now assign pointers to each string in the array.  */
     
    17631800  if (wordi)
    17641801    {
     1802      int i;
     1803
    17651804      /* Now sort the list of words.  */
    17661805      qsort (words, wordi, sizeof (char *), alpha_compare);
     
    19291968{
    19301969  char *expansion;
    1931   int result;
    19321970
    19331971  while (1)
     
    19351973      const char *begp = *argv;
    19361974      const char *endp = begp + strlen (*argv) - 1;
     1975      int result;
    19371976
    19381977      /* An empty condition is always false.  */
     
    19972036
    19982037#ifndef CONFIG_WITH_VALUE_LENGTH
    1999   eval_buffer (argv[0]);
     2038  eval_buffer (argv[0], NULL);
    20002039#else
    2001   eval_buffer (argv[0], strchr (argv[0], '\0'));
     2040  eval_buffer (argv[0], NULL, strchr (argv[0], '\0'));
    20022041#endif
    20032042
     
    20242063  push_new_variable_scope ();
    20252064
    2026   eval_buffer (argv[0], strchr (argv[0], '\0'));
     2065  eval_buffer (argv[0], NULL, strchr (argv[0], '\0'));
    20272066
    20282067  pop_variable_scope ();
     
    20472086      int var_ctx;
    20482087      size_t off;
    2049       const struct floc *reading_file_saved = reading_file;
     2088      const floc *reading_file_saved = reading_file;
    20502089# ifdef CONFIG_WITH_MAKE_STATS
    20512090      unsigned long long uStartTick = CURRENT_CLOCK_TICK();
     
    20852124
    20862125        install_variable_buffer (&buf, &len); /* Really necessary? */
    2087         eval_buffer (o, o + v->value_length);
     2126        eval_buffer (o, NULL, o + v->value_length);
    20882127        restore_variable_buffer (buf, len);
    20892128      }
     
    21342173                    {
    21352174                      ch = (unsigned char)dst[-1];
    2136                       if (!isblank (ch))
     2175                      if (!ISBLANK (ch))
    21372176                        break;
    21382177                      dst--;
     
    21752214        }
    21762215      else if (v)
    2177         error (NILF, _("$(%s ): variable `%s' is of the wrong type\n"), funcname, v->name);
     2216        OSS (error, NILF, _("$(%s ): variable `%s' is of the wrong type\n"), funcname, v->name);
    21782217    }
    21792218
     
    21972236    }
    21982237#else
    2199     o = variable_buffer_output (o, v->value, strlen(v->value));
     2238    o = variable_buffer_output (o, v->value, strlen (v->value));
    22002239#endif
    22012240
     
    22042243
    22052244/*
    2206   \r  is replaced on UNIX as well. Is this desirable?
     2245  \r is replaced on UNIX as well. Is this desirable?
    22072246 */
    22082247static void
    2209 fold_newlines (char *buffer, unsigned int *length)
     2248fold_newlines (char *buffer, unsigned int *length, int trim_newlines)
    22102249{
    22112250  char *dst = buffer;
    22122251  char *src = buffer;
    2213   char *last_nonnl = buffer -1;
     2252  char *last_nonnl = buffer - 1;
    22142253  src[*length] = 0;
    22152254  for (; *src != '\0'; ++src)
    22162255    {
    22172256      if (src[0] == '\r' && src[1] == '\n')
    2218         continue;
     2257        continue;
    22192258      if (*src == '\n')
    2220         {
    2221           *dst++ = ' ';
    2222         }
     2259        {
     2260          *dst++ = ' ';
     2261        }
    22232262      else
    2224         {
    2225           last_nonnl = dst;
    2226           *dst++ = *src;
    2227         }
    2228     }
     2263        {
     2264          last_nonnl = dst;
     2265          *dst++ = *src;
     2266        }
     2267    }
     2268
     2269  if (!trim_newlines && (last_nonnl < (dst - 2)))
     2270    last_nonnl = dst - 2;
     2271
    22292272  *(++last_nonnl) = '\0';
    22302273  *length = last_nonnl - buffer;
    22312274}
    22322275
    2233 
    2234 
    2235 int shell_function_pid = 0, shell_function_completed;
    2236 
     2276pid_t shell_function_pid = 0;
     2277static int shell_function_completed;
     2278
     2279void
     2280shell_completed (int exit_code, int exit_sig)
     2281{
     2282  char buf[256];
     2283
     2284  shell_function_pid = 0;
     2285  if (exit_sig == 0 && exit_code == 127)
     2286    shell_function_completed = -1;
     2287  else
     2288    shell_function_completed = 1;
     2289
     2290  sprintf (buf, "%d", exit_code);
     2291  define_variable_cname (".SHELLSTATUS", buf, o_override, 0);
     2292}
    22372293
    22382294#ifdef WINDOWS32
     
    22442300
    22452301
    2246 void
    2247 windows32_openpipe (int *pipedes, pid_t *pid_p, char **command_argv, char **envp)
     2302int
     2303windows32_openpipe (int *pipedes, int errfd, pid_t *pid_p, char **command_argv, char **envp)
    22482304{
    22492305  SECURITY_ATTRIBUTES saAttr;
    2250   HANDLE hIn;
    2251   HANDLE hErr;
     2306  HANDLE hIn = INVALID_HANDLE_VALUE;
     2307  HANDLE hErr = INVALID_HANDLE_VALUE;
    22522308  HANDLE hChildOutRd;
    22532309  HANDLE hChildOutWr;
    2254   HANDLE hProcess;
    2255 
     2310  HANDLE hProcess, tmpIn, tmpErr;
     2311  DWORD e;
     2312
     2313  /* Set status for return.  */
     2314  pipedes[0] = pipedes[1] = -1;
     2315  *pid_p = (pid_t)-1;
    22562316
    22572317  saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
     
    22592319  saAttr.lpSecurityDescriptor = NULL;
    22602320
    2261   if (DuplicateHandle (GetCurrentProcess(),
    2262                       GetStdHandle(STD_INPUT_HANDLE),
    2263                       GetCurrentProcess(),
    2264                       &hIn,
    2265                       0,
    2266                       TRUE,
    2267                       DUPLICATE_SAME_ACCESS) == FALSE) {
    2268     fatal (NILF, _("windows32_openpipe(): DuplicateHandle(In) failed (e=%ld)\n"),
    2269            GetLastError());
    2270 
    2271   }
    2272   if (DuplicateHandle(GetCurrentProcess(),
    2273                       GetStdHandle(STD_ERROR_HANDLE),
    2274                       GetCurrentProcess(),
    2275                       &hErr,
    2276                       0,
    2277                       TRUE,
    2278                       DUPLICATE_SAME_ACCESS) == FALSE) {
    2279     fatal (NILF, _("windows32_open_pipe(): DuplicateHandle(Err) failed (e=%ld)\n"),
    2280            GetLastError());
    2281   }
    2282 
    2283   if (!CreatePipe(&hChildOutRd, &hChildOutWr, &saAttr, 0))
    2284     fatal (NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
    2285 
    2286   hProcess = process_init_fd(hIn, hChildOutWr, hErr);
     2321  /* Standard handles returned by GetStdHandle can be NULL or
     2322     INVALID_HANDLE_VALUE if the parent process closed them.  If that
     2323     happens, we open the null device and pass its handle to
     2324     process_begin below as the corresponding handle to inherit.  */
     2325  tmpIn = GetStdHandle (STD_INPUT_HANDLE);
     2326  if (DuplicateHandle (GetCurrentProcess (), tmpIn,
     2327                       GetCurrentProcess (), &hIn,
     2328                       0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     2329    {
     2330      e = GetLastError ();
     2331      if (e == ERROR_INVALID_HANDLE)
     2332        {
     2333          tmpIn = CreateFile ("NUL", GENERIC_READ,
     2334                              FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
     2335                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     2336          if (tmpIn != INVALID_HANDLE_VALUE
     2337              && DuplicateHandle (GetCurrentProcess (), tmpIn,
     2338                                  GetCurrentProcess (), &hIn,
     2339                                  0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     2340            CloseHandle (tmpIn);
     2341        }
     2342      if (hIn == INVALID_HANDLE_VALUE)
     2343        {
     2344          ON (error, NILF,
     2345              _("windows32_openpipe: DuplicateHandle(In) failed (e=%ld)\n"), e);
     2346          return -1;
     2347        }
     2348    }
     2349  tmpErr = (HANDLE)_get_osfhandle (errfd);
     2350  if (DuplicateHandle (GetCurrentProcess (), tmpErr,
     2351                       GetCurrentProcess (), &hErr,
     2352                       0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     2353    {
     2354      e = GetLastError ();
     2355      if (e == ERROR_INVALID_HANDLE)
     2356        {
     2357          tmpErr = CreateFile ("NUL", GENERIC_WRITE,
     2358                               FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
     2359                               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     2360          if (tmpErr != INVALID_HANDLE_VALUE
     2361              && DuplicateHandle (GetCurrentProcess (), tmpErr,
     2362                                  GetCurrentProcess (), &hErr,
     2363                                  0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE)
     2364            CloseHandle (tmpErr);
     2365        }
     2366      if (hErr == INVALID_HANDLE_VALUE)
     2367        {
     2368          ON (error, NILF,
     2369              _("windows32_openpipe: DuplicateHandle(Err) failed (e=%ld)\n"), e);
     2370          return -1;
     2371        }
     2372    }
     2373
     2374  if (! CreatePipe (&hChildOutRd, &hChildOutWr, &saAttr, 0))
     2375    {
     2376      ON (error, NILF, _("CreatePipe() failed (e=%ld)\n"), GetLastError());
     2377      return -1;
     2378    }
     2379
     2380  hProcess = process_init_fd (hIn, hChildOutWr, hErr);
    22872381
    22882382  if (!hProcess)
    2289     fatal (NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
     2383    {
     2384      O (error, NILF, _("windows32_openpipe(): process_init_fd() failed\n"));
     2385      return -1;
     2386    }
    22902387
    22912388  /* make sure that CreateProcess() has Path it needs */
    2292   sync_Path_environment();
    2293   /* `sync_Path_environment' may realloc `environ', so take note of
     2389  sync_Path_environment ();
     2390  /* 'sync_Path_environment' may realloc 'environ', so take note of
    22942391     the new value.  */
    22952392  envp = environ;
    22962393
    2297   if (!process_begin(hProcess, command_argv, envp, command_argv[0], NULL)) {
    2298     /* register process for wait */
    2299     process_register(hProcess);
    2300 
    2301     /* set the pid for returning to caller */
    2302     *pid_p = (pid_t) hProcess;
    2303 
    2304   /* set up to read data from child */
    2305   pipedes[0] = _open_osfhandle((intptr_t) hChildOutRd, O_RDONLY);
    2306 
    2307   /* this will be closed almost right away */
    2308   pipedes[1] = _open_osfhandle((intptr_t) hChildOutWr, O_APPEND);
    2309   } else {
    2310     /* reap/cleanup the failed process */
    2311         process_cleanup(hProcess);
    2312 
    2313     /* close handles which were duplicated, they weren't used */
    2314         CloseHandle(hIn);
    2315         CloseHandle(hErr);
    2316 
    2317         /* close pipe handles, they won't be used */
    2318         CloseHandle(hChildOutRd);
    2319         CloseHandle(hChildOutWr);
    2320 
    2321     /* set status for return */
    2322     pipedes[0] = pipedes[1] = -1;
    2323     *pid_p = (pid_t)-1;
    2324   }
     2394  if (! process_begin (hProcess, command_argv, envp, command_argv[0], NULL))
     2395    {
     2396      /* register process for wait */
     2397      process_register (hProcess);
     2398
     2399      /* set the pid for returning to caller */
     2400      *pid_p = (pid_t) hProcess;
     2401
     2402      /* set up to read data from child */
     2403      pipedes[0] = _open_osfhandle ((intptr_t) hChildOutRd, O_RDONLY);
     2404
     2405      /* this will be closed almost right away */
     2406      pipedes[1] = _open_osfhandle ((intptr_t) hChildOutWr, O_APPEND);
     2407      return 0;
     2408    }
     2409  else
     2410    {
     2411      /* reap/cleanup the failed process */
     2412      process_cleanup (hProcess);
     2413
     2414      /* close handles which were duplicated, they weren't used */
     2415      if (hIn != INVALID_HANDLE_VALUE)
     2416        CloseHandle (hIn);
     2417      if (hErr != INVALID_HANDLE_VALUE)
     2418        CloseHandle (hErr);
     2419
     2420      /* close pipe handles, they won't be used */
     2421      CloseHandle (hChildOutRd);
     2422      CloseHandle (hChildOutWr);
     2423
     2424      return -1;
     2425    }
    23252426}
    23262427#endif
     
    23322433{
    23332434  FILE *fpipe=0;
    2334   /* MSDOS can't fork, but it has `popen'.  */
     2435  /* MSDOS can't fork, but it has 'popen'.  */
    23352436  struct variable *sh = lookup_variable ("SHELL", 5);
    23362437  int e;
     
    23382439
    23392440  /* Make sure not to bother processing an empty line.  */
    2340   while (isblank ((unsigned char)*text))
    2341     ++text;
     2441  NEXT_TOKEN (text);
    23422442  if (*text == '\0')
    23432443    return 0;
     
    23472447      char buf[PATH_MAX + 7];
    23482448      /* This makes sure $SHELL value is used by $(shell), even
    2349         though the target environment is not passed to it.  */
     2449        though the target environment is not passed to it.  */
    23502450      sprintf (buf, "SHELL=%s", sh->value);
    23512451      putenv (buf);
     
    23662466      *pidp = -1;
    23672467      if (dos_status)
    2368         errno = EINTR;
     2468        errno = EINTR;
    23692469      else if (errno == 0)
    2370         errno = ENOMEM;
    2371       shell_function_completed = -1;
     2470        errno = ENOMEM;
     2471      if (fpipe)
     2472        pclose (fpipe);
     2473      shell_completed (127, 0);
    23722474    }
    23732475  else
     
    23762478      *pidp = 42; /* Yes, the Meaning of Life, the Universe, and Everything! */
    23772479      errno = e;
    2378       shell_function_completed = 1;
    23792480    }
    23802481  return fpipe;
     
    23892490
    23902491/* VMS can't do $(shell ...)  */
     2492
     2493char *
     2494func_shell_base (char *o, char **argv, int trim_newlines)
     2495{
     2496  fprintf (stderr, "This platform does not support shell\n");
     2497  die (MAKE_TROUBLE);
     2498  return NULL;
     2499}
     2500
    23912501#define func_shell 0
    23922502
    23932503#else
    23942504#ifndef _AMIGA
    2395 static char *
    2396 func_shell (char * volatile o, char **argv, const char *funcname UNUSED)
     2505char *
     2506func_shell_base (char *o, char **argv, int trim_newlines)
    23972507{
    23982508  char *batch_filename = NULL;
    2399 
     2509  int errfd;
    24002510#ifdef __MSDOS__
    24012511  FILE *fpipe;
    24022512#endif
    24032513  char **command_argv;
    2404   const char * volatile error_prefix; /* bird: this volatile and the 'o' one, is for shutting up gcc warnings */
     2514  const char * volatile error_prefix; /* bird: this volatile ~~and the 'o' one~~, is for shutting up gcc warnings */
    24052515  char **envp;
    24062516  int pipedes[2];
     
    24082518
    24092519#ifndef __MSDOS__
     2520#ifdef WINDOWS32
     2521  /* Reset just_print_flag.  This is needed on Windows when batch files
     2522     are used to run the commands, because we normally refrain from
     2523     creating batch files under -n.  */
     2524  int j_p_f = just_print_flag;
     2525  just_print_flag = 0;
     2526#endif
     2527
    24102528  /* Construct the argument list.  */
    24112529  command_argv = construct_command_argv (argv[0], NULL, NULL, 0,
    24122530                                         &batch_filename);
    24132531  if (command_argv == 0)
    2414     return o;
    2415 #endif
    2416 
    2417   /* Using a target environment for `shell' loses in cases like:
    2418      export var = $(shell echo foobie)
    2419      because target_environment hits a loop trying to expand $(var)
    2420      to put it in the environment.  This is even more confusing when
    2421      var was not explicitly exported, but just appeared in the
    2422      calling environment.
     2532    {
     2533#ifdef WINDOWS32
     2534      just_print_flag = j_p_f;
     2535#endif
     2536      return o;
     2537    }
     2538#endif /* !__MSDOS__ */
     2539
     2540  /* Using a target environment for 'shell' loses in cases like:
     2541       export var = $(shell echo foobie)
     2542       bad := $(var)
     2543     because target_environment hits a loop trying to expand $(var) to put it
     2544     in the environment.  This is even more confusing when 'var' was not
     2545     explicitly exported, but just appeared in the calling environment.
    24232546
    24242547     See Savannah bug #10593.
    24252548
    2426   envp = target_environment (NILF);
     2549  envp = target_environment (NULL);
    24272550  */
    24282551
     
    24332556    {
    24342557      char *p = alloca (strlen (reading_file->filenm)+11+4);
    2435       sprintf (p, "%s:%lu: ", reading_file->filenm, reading_file->lineno);
     2558      sprintf (p, "%s:%lu: ", reading_file->filenm,
     2559               reading_file->lineno + reading_file->offset);
    24362560      error_prefix = p;
    24372561    }
    24382562  else
    24392563    error_prefix = "";
     2564
     2565  /* Set up the output in case the shell writes something.  */
     2566  output_start ();
     2567
     2568  errfd = (output_context && output_context->err >= 0
     2569           ? output_context->err : FD_STDERR);
    24402570
    24412571#if defined(__MSDOS__)
     
    24462576      return o;
    24472577    }
     2578
    24482579#elif defined(WINDOWS32)
    2449   windows32_openpipe (pipedes, &pid, command_argv, envp);
     2580  windows32_openpipe (pipedes, errfd, &pid, command_argv, envp);
     2581  /* Restore the value of just_print_flag.  */
     2582  just_print_flag = j_p_f;
     2583
    24502584  if (pipedes[0] < 0)
    24512585    {
    2452       /* open of the pipe failed, mark as failed execution */
    2453       shell_function_completed = -1;
    2454 
     2586      /* Open of the pipe failed, mark as failed execution. */
     2587      shell_completed (127, 0);
     2588      perror_with_name (error_prefix, "pipe");
    24552589      return o;
    24562590    }
    2457   else
     2591
    24582592#else
    24592593  if (pipe (pipedes) < 0)
     
    24632597    }
    24642598
    2465 # ifdef __EMX__
    2466   /* close some handles that are unnecessary for the child process */
     2599  /* Close handles that are unnecessary for the child process.  */
    24672600  CLOSE_ON_EXEC(pipedes[1]);
    24682601  CLOSE_ON_EXEC(pipedes[0]);
    2469   /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
    2470   pid = child_execute_job (0, pipedes[1], command_argv, envp);
     2602
     2603  {
     2604    struct output out;
     2605    out.syncout = 1;
     2606    out.out = pipedes[1];
     2607    out.err = errfd;
     2608
     2609    pid = child_execute_job (&out, 1, command_argv, envp);
     2610  }
     2611
    24712612  if (pid < 0)
    2472     perror_with_name (error_prefix, "spawn");
    2473 # else /* ! __EMX__ */
    2474   pid = vfork ();
    2475   if (pid < 0)
    2476     perror_with_name (error_prefix, "fork");
    2477   else if (pid == 0)
    2478     child_execute_job (0, pipedes[1], command_argv, envp);
    2479   else
    2480 # endif
    2481 #endif
    2482     {
    2483       /* We are the parent.  */
    2484       char *buffer;
    2485       unsigned int maxlen, i;
    2486       int cc;
    2487 
    2488       /* Record the PID for reap_children.  */
    2489       shell_function_pid = pid;
     2613    {
     2614      perror_with_name (error_prefix, "fork");
     2615      return o;
     2616    }
     2617#endif
     2618
     2619  {
     2620    char *buffer;
     2621    unsigned int maxlen, i;
     2622    int cc;
     2623
     2624    /* Record the PID for reap_children.  */
     2625    shell_function_pid = pid;
    24902626#ifndef  __MSDOS__
    2491       shell_function_completed = 0;
    2492 
    2493       /* Free the storage only the child needed.  */
    2494       free (command_argv[0]);
    2495       free (command_argv);
    2496 
    2497       /* Close the write side of the pipe.  We test for -1, since
    2498         pipedes[1] is -1 on MS-Windows, and some versions of MS
    2499          libraries barf when `close' is called with -1.  */
    2500       if (pipedes[1] >= 0)
    2501         close (pipedes[1]);
    2502 #endif
    2503 
    2504       /* Set up and read from the pipe.  */
    2505 
    2506       maxlen = 200;
    2507       buffer = xmalloc (maxlen + 1);
    2508 
    2509       /* Read from the pipe until it gets EOF.  */
    2510       for (i = 0; ; i += cc)
    2511         {
    2512           if (i == maxlen)
    2513             {
    2514               maxlen += 512;
    2515               buffer = xrealloc (buffer, maxlen + 1);
    2516             }
    2517 
    2518           EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
    2519           if (cc <= 0)
    2520             break;
    2521         }
    2522       buffer[i] = '\0';
    2523 
    2524       /* Close the read side of the pipe.  */
     2627    shell_function_completed = 0;
     2628
     2629    /* Free the storage only the child needed.  */
     2630    free (command_argv[0]);
     2631    free (command_argv);
     2632
     2633    /* Close the write side of the pipe.  We test for -1, since
     2634      pipedes[1] is -1 on MS-Windows, and some versions of MS
     2635       libraries barf when 'close' is called with -1.  */
     2636    if (pipedes[1] >= 0)
     2637      close (pipedes[1]);
     2638#endif
     2639
     2640    /* Set up and read from the pipe.  */
     2641
     2642    maxlen = 200;
     2643    buffer = xmalloc (maxlen + 1);
     2644
     2645    /* Read from the pipe until it gets EOF.  */
     2646    for (i = 0; ; i += cc)
     2647      {
     2648        if (i == maxlen)
     2649          {
     2650            maxlen += 512;
     2651            buffer = xrealloc (buffer, maxlen + 1);
     2652          }
     2653
     2654        EINTRLOOP (cc, read (pipedes[0], &buffer[i], maxlen - i));
     2655        if (cc <= 0)
     2656          break;
     2657      }
     2658    buffer[i] = '\0';
     2659
     2660    /* Close the read side of the pipe.  */
    25252661#ifdef  __MSDOS__
    2526       if (fpipe)
    2527         (void) pclose (fpipe);
     2662    if (fpipe)
     2663      {
     2664        int st = pclose (fpipe);
     2665        shell_completed (st, 0);
     2666      }
    25282667#else
    25292668# ifdef _MSC_VER /* Avoid annoying msvcrt when debugging. (bird) */
    25302669      if (pipedes[0] != -1)
    25312670# endif
    2532       (void) close (pipedes[0]);
    2533 #endif
    2534 
    2535       /* Loop until child_handler or reap_children()  sets
    2536          shell_function_completed to the status of our child shell.  */
    2537       while (shell_function_completed == 0)
    2538         reap_children (1, 0);
    2539 
    2540       if (batch_filename) {
    2541         DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
    2542                        batch_filename));
    2543         remove (batch_filename);
    2544         free (batch_filename);
     2671        (void) close (pipedes[0]);
     2672#endif
     2673
     2674    /* Loop until child_handler or reap_children()  sets
     2675       shell_function_completed to the status of our child shell.  */
     2676    while (shell_function_completed == 0)
     2677      reap_children (1, 0);
     2678
     2679    if (batch_filename)
     2680      {
     2681        DB (DB_VERBOSE, (_("Cleaning up temporary batch file %s\n"),
     2682                         batch_filename));
     2683        remove (batch_filename);
     2684        free (batch_filename);
    25452685      }
    2546       shell_function_pid = 0;
    2547 
    2548       /* The child_handler function will set shell_function_completed
    2549          to 1 when the child dies normally, or to -1 if it
    2550          dies with status 127, which is most likely an exec fail.  */
    2551 
    2552       if (shell_function_completed == -1)
    2553         {
    2554           /* This likely means that the execvp failed, so we should just
    2555              write the error message in the pipe from the child.  */
    2556           fputs (buffer, stderr);
    2557           fflush (stderr);
    2558         }
    2559       else
    2560         {
    2561           /* The child finished normally.  Replace all newlines in its output
    2562              with spaces, and put that in the variable output buffer.  */
    2563           fold_newlines (buffer, &i);
    2564           o = variable_buffer_output (o, buffer, i);
    2565         }
    2566 
    2567       free (buffer);
    2568     }
    2569 
    2570   return o;
    2571 }
    2572 
    2573 #else   /* _AMIGA */
     2686    shell_function_pid = 0;
     2687
     2688    /* shell_completed() will set shell_function_completed to 1 when the
     2689       child dies normally, or to -1 if it dies with status 127, which is
     2690      most likely an exec fail.  */
     2691
     2692    if (shell_function_completed == -1)
     2693      {
     2694        /* This likely means that the execvp failed, so we should just
     2695           write the error message in the pipe from the child.  */
     2696        fputs (buffer, stderr);
     2697        fflush (stderr);
     2698      }
     2699    else
     2700      {
     2701        /* The child finished normally.  Replace all newlines in its output
     2702           with spaces, and put that in the variable output buffer.  */
     2703        fold_newlines (buffer, &i, trim_newlines);
     2704        o = variable_buffer_output (o, buffer, i);
     2705      }
     2706
     2707    free (buffer);
     2708  }
     2709
     2710  return o;
     2711}
     2712
     2713#else   /* _AMIGA */
    25742714
    25752715/* Do the Amiga version of func_shell.  */
    25762716
    2577 static char *
    2578 func_shell (char *o, char **argv, const char *funcname)
     2717char *
     2718func_shell_base (char *o, char **argv, int trim_newlines)
    25792719{
    25802720  /* Amiga can't fork nor spawn, but I can start a program with
     
    26062746
    26072747  /* Note the mktemp() is a security hole, but this only runs on Amiga.
    2608      Ideally we would use main.c:open_tmpfile(), but this uses a special
     2748     Ideally we would use output_tmpfile(), but this uses a special
    26092749     Open(), not fopen(), and I'm not familiar enough with the code to mess
    26102750     with it.  */
     
    26412781    {
    26422782      if (i == maxlen)
    2643         {
    2644           maxlen += 512;
    2645           buffer = xrealloc (buffer, maxlen + 1);
    2646         }
     2783        {
     2784          maxlen += 512;
     2785          buffer = xrealloc (buffer, maxlen + 1);
     2786        }
    26472787
    26482788      cc = Read (child_stdout, &buffer[i], maxlen - i);
    26492789      if (cc > 0)
    2650         i += cc;
     2790        i += cc;
    26512791    } while (cc > 0);
    26522792
    26532793  Close (child_stdout);
    26542794
    2655   fold_newlines (buffer, &i);
     2795  fold_newlines (buffer, &i, trim_newlines);
    26562796  o = variable_buffer_output (o, buffer, i);
    26572797  free (buffer);
     
    26592799}
    26602800#endif  /* _AMIGA */
     2801
     2802static char *
     2803func_shell (char *o, char **argv, const char *funcname UNUSED)
     2804{
     2805  return func_shell_base (o, argv, 1);
     2806}
    26612807#endif  /* !VMS */
    26622808
     
    26642810
    26652811/*
    2666   equality. Return is string-boolean, ie, the empty string is false.
     2812  equality. Return is string-boolean, i.e., the empty string is false.
    26672813 */
    26682814static char *
     
    26832829  const char *s = argv[0];
    26842830  int result = 0;
    2685   while (isspace ((unsigned char)*s))
    2686     s++;
     2831  NEXT_TOKEN (s);
    26872832  result = ! (*s);
    26882833  o = variable_buffer_output (o,  result ? "1" : "", result);
     
    26922837
    26932838
    2694 #ifdef CONFIG_WITH_STRING_FUNCTIONS
    2695 /*
    2696   $(length string)
    2697 
    2698   XXX: This doesn't take multibyte locales into account.
    2699  */
    2700 static char *
    2701 func_length (char *o, char **argv, const char *funcname UNUSED)
    2702 {
    2703   size_t len = strlen (argv[0]);
    2704   return math_int_to_variable_buffer (o, len);
    2705 }
    2706 
    2707 /*
    2708   $(length-var var)
    2709 
    2710   XXX: This doesn't take multibyte locales into account.
    2711  */
    2712 static char *
    2713 func_length_var (char *o, char **argv, const char *funcname UNUSED)
    2714 {
    2715   struct variable *var = lookup_variable (argv[0], strlen (argv[0]));
    2716   return math_int_to_variable_buffer (o, var ? var->value_length : 0);
    2717 }
    2718 
    2719 
    2720 /* func_insert and func_substr helper. */
    2721 static char *
    2722 helper_pad (char *o, size_t to_add, const char *pad, size_t pad_len)
    2723 {
    2724   while (to_add > 0)
    2725     {
    2726       size_t size = to_add > pad_len ? pad_len : to_add;
    2727       o = variable_buffer_output (o, pad, size);
    2728       to_add -= size;
    2729     }
    2730   return o;
    2731 }
    2732 
    2733 /*
    2734   $(insert in, str[, n[, length[, pad]]])
    2735 
    2736   XXX: This doesn't take multibyte locales into account.
    2737  */
    2738 static char *
    2739 func_insert (char *o, char **argv, const char *funcname UNUSED)
    2740 {
    2741   const char *in      = argv[0];
    2742   math_int    in_len  = (math_int)strlen (in);
    2743   const char *str     = argv[1];
    2744   math_int    str_len = (math_int)strlen (str);
    2745   math_int    n       = 0;
    2746   math_int    length  = str_len;
    2747   const char *pad     = "                ";
    2748   size_t      pad_len = 16;
    2749   size_t      i;
    2750 
    2751   if (argv[2] != NULL)
    2752     {
    2753       n = math_int_from_string (argv[2]);
    2754       if (n > 0)
    2755         n--;            /* one-origin */
    2756       else if (n == 0)
    2757         n = str_len;    /* append */
    2758       else
    2759         { /* n < 0: from the end */
    2760           n = str_len + n;
    2761           if (n < 0)
    2762             n = 0;
    2763         }
    2764       if (n > 16*1024*1024) /* 16MB */
    2765         fatal (NILF, _("$(insert ): n=%s is out of bounds\n"), argv[2]);
    2766 
    2767       if (argv[3] != NULL)
    2768         {
    2769           length = math_int_from_string (argv[3]);
    2770           if (length < 0 || length > 16*1024*1024 /* 16MB */)
    2771               fatal (NILF, _("$(insert ): length=%s is out of bounds\n"), argv[3]);
    2772 
    2773           if (argv[4] != NULL)
    2774             {
    2775               const char *tmp = argv[4];
    2776               for (i = 0; tmp[i] == ' '; i++)
    2777                 /* nothing */;
    2778               if (tmp[i] != '\0')
    2779                 {
    2780                   pad = argv[4];
    2781                   pad_len = strlen (pad);
    2782                 }
    2783               /* else: it was all default spaces. */
    2784             }
    2785         }
    2786     }
    2787 
    2788   /* the head of the original string */
    2789   if (n > 0)
    2790     {
    2791       if (n <= str_len)
    2792         o = variable_buffer_output (o, str, n);
    2793       else
    2794         {
    2795           o = variable_buffer_output (o, str, str_len);
    2796           o = helper_pad (o, n - str_len, pad, pad_len);
    2797         }
    2798     }
    2799 
    2800   /* insert the string */
    2801   if (length <= in_len)
    2802     o = variable_buffer_output (o, in, length);
    2803   else
    2804     {
    2805       o = variable_buffer_output (o, in, in_len);
    2806       o = helper_pad (o, length - in_len, pad, pad_len);
    2807     }
    2808 
    2809   /* the tail of the original string */
    2810   if (n < str_len)
    2811     o = variable_buffer_output (o, str + n, str_len - n);
    2812 
    2813   return o;
    2814 }
    2815 
    2816 
    2817 /*
    2818   $(pos needle, haystack[, start])
    2819   $(lastpos needle, haystack[, start])
    2820 
    2821   XXX: This doesn't take multibyte locales into account.
    2822  */
    2823 static char *
    2824 func_pos (char *o, char **argv, const char *funcname UNUSED)
    2825 {
    2826   const char *needle       = *argv[0] ? argv[0] : " ";
    2827   size_t      needle_len   = strlen (needle);
    2828   const char *haystack     = argv[1];
    2829   size_t      haystack_len = strlen (haystack);
    2830   math_int    start        = 0;
    2831   const char *hit;
    2832 
    2833   if (argv[2] != NULL)
    2834     {
    2835       start = math_int_from_string (argv[2]);
    2836       if (start > 0)
    2837         start--;            /* one-origin */
    2838       else if (start < 0)
    2839         start = haystack_len + start; /* from the end */
    2840       if (start < 0 || start + needle_len > haystack_len)
    2841         return math_int_to_variable_buffer (o, 0);
    2842     }
    2843   else if (funcname[0] == 'l')
    2844     start = haystack_len - 1;
    2845 
    2846   /* do the searching */
    2847   if (funcname[0] != 'l')
    2848     { /* pos */
    2849       if (needle_len == 1)
    2850         hit = strchr (haystack + start, *needle);
    2851       else
    2852         hit = strstr (haystack + start, needle);
    2853     }
    2854   else
    2855     { /* last pos */
    2856       int    ch  = *needle;
    2857       size_t off = start + 1;
    2858 
    2859       hit = NULL;
    2860       while (off-- > 0)
    2861         {
    2862           if (   haystack[off] == ch
    2863               && (   needle_len == 1
    2864                   || strncmp (&haystack[off], needle, needle_len) == 0))
    2865             {
    2866               hit = haystack + off;
    2867               break;
    2868             }
    2869         }
    2870     }
    2871 
    2872   return math_int_to_variable_buffer (o, hit ? hit - haystack + 1 : 0);
    2873 }
    2874 
    2875 
    2876 /*
    2877   $(substr str, start[, length[, pad]])
    2878 
    2879   XXX: This doesn't take multibyte locales into account.
    2880  */
    2881 static char *
    2882 func_substr (char *o, char **argv, const char *funcname UNUSED)
    2883 {
    2884   const char *str     = argv[0];
    2885   math_int    str_len = (math_int)strlen (str);
    2886   math_int    start   = math_int_from_string (argv[1]);
    2887   math_int    length  = 0;
    2888   const char *pad     = NULL;
    2889   size_t      pad_len = 0;
    2890 
    2891   if (argv[2] != NULL)
    2892     {
    2893       if (argv[3] != NULL)
    2894         {
    2895           pad = argv[3];
    2896           for (pad_len = 0; pad[pad_len] == ' '; pad_len++)
    2897             /* nothing */;
    2898           if (pad[pad_len] != '\0')
    2899               pad_len = strlen (pad);
    2900           else
    2901             {
    2902               pad = "                ";
    2903               pad_len = 16;
    2904             }
    2905         }
    2906       length = math_int_from_string (argv[2]);
    2907       if (pad != NULL && length > 16*1024*1024 /* 16MB */)
    2908         fatal (NILF, _("$(substr ): length=%s is out of bounds\n"), argv[2]);
    2909       if (pad != NULL && length < 0)
    2910         fatal (NILF, _("$(substr ): negative length (%s) and padding doesn't mix.\n"), argv[2]);
    2911       if (length == 0)
    2912         return o;
    2913     }
    2914 
    2915   /* Note that negative start is and length are used for referencing from the
    2916      end of the string. */
    2917   if (pad == NULL)
    2918     {
    2919       if (start > 0)
    2920         start--;      /* one-origin */
    2921       else
    2922         {
    2923           start = str_len + start;
    2924           if (start <= 0)
    2925             {
    2926               if (length < 0)
    2927                 return o;
    2928               start += length;
    2929               if (start <= 0)
    2930                 return o;
    2931               length = start;
    2932               start = 0;
    2933             }
    2934         }
    2935 
    2936       if (start >= str_len)
    2937         return o;
    2938       if (length == 0)
    2939         length = str_len - start;
    2940       else if (length < 0)
    2941         {
    2942           if (str_len <= -length)
    2943             return o;
    2944           length += str_len;
    2945           if (length <= start)
    2946             return o;
    2947           length -= start;
    2948         }
    2949       else if (start + length > str_len)
    2950         length = str_len - start;
    2951 
    2952       o = variable_buffer_output (o, str + start, length);
    2953     }
    2954   else
    2955     {
    2956       if (start > 0)
    2957         {
    2958           start--;      /* one-origin */
    2959           if (start >= str_len)
    2960             return length ? helper_pad (o, length, pad, pad_len) : o;
    2961           if (length == 0)
    2962             length = str_len - start;
    2963         }
    2964       else
    2965         {
    2966           start = str_len + start;
    2967           if (start <= 0)
    2968             {
    2969               if (start + length <= 0)
    2970                 return length ? helper_pad (o, length, pad, pad_len) : o;
    2971               o = helper_pad (o, -start, pad, pad_len);
    2972               return variable_buffer_output (o, str, length + start);
    2973             }
    2974           if (length == 0)
    2975             length = str_len - start;
    2976         }
    2977       if (start + length <= str_len)
    2978         o = variable_buffer_output (o, str + start, length);
    2979       else
    2980         {
    2981           o = variable_buffer_output (o, str + start, str_len - start);
    2982           o = helper_pad (o, start + length - str_len, pad, pad_len);
    2983         }
    2984     }
    2985 
    2986   return o;
    2987 }
    2988 
    2989 
    2990 /*
    2991   $(translate string, from-set[, to-set[, pad-char]])
    2992 
    2993   XXX: This doesn't take multibyte locales into account.
    2994  */
    2995 static char *
    2996 func_translate (char *o, char **argv, const char *funcname UNUSED)
    2997 {
    2998   const unsigned char *str      = (const unsigned char *)argv[0];
    2999   const unsigned char *from_set = (const unsigned char *)argv[1];
    3000   const char          *to_set   = argv[2] != NULL ? argv[2] : "";
    3001   char                 trans_tab[1 << CHAR_BIT];
    3002   int                  i;
    3003   char                 ch;
    3004 
    3005   /* init the array. */
    3006   for (i = 0; i < (1 << CHAR_BIT); i++)
    3007     trans_tab[i] = i;
    3008 
    3009   while (   (i = *from_set) != '\0'
    3010          && (ch = *to_set) != '\0')
    3011     {
    3012       trans_tab[i] = ch;
    3013       from_set++;
    3014       to_set++;
    3015     }
    3016 
    3017   if (i != '\0')
    3018     {
    3019       ch = '\0';                        /* no padding == remove char */
    3020       if (argv[2] != NULL && argv[3] != NULL)
    3021         {
    3022           ch = argv[3][0];
    3023           if (ch && argv[3][1])
    3024             fatal (NILF, _("$(translate ): pad=`%s' expected a single char\n"), argv[3]);
    3025           if (ch == '\0')               /* no char == space */
    3026             ch = ' ';
    3027         }
    3028       while ((i = *from_set++) != '\0')
    3029         trans_tab[i] = ch;
    3030     }
    3031 
    3032   /* do the translation */
    3033   while ((i = *str++) != '\0')
    3034     {
    3035       ch = trans_tab[i];
    3036       if (ch)
    3037         o = variable_buffer_output (o, &ch, 1);
    3038     }
    3039 
    3040   return o;
    3041 }
    3042 #endif /* CONFIG_WITH_STRING_FUNCTIONS */
    3043 
    3044 
    3045 #ifdef CONFIG_WITH_LAZY_DEPS_VARS
    3046 
    3047 /* This is also in file.c (bad).  */
    3048 # if VMS
    3049 #  define FILE_LIST_SEPARATOR ','
     2839
     2840#ifdef HAVE_DOS_PATHS
     2841# ifdef __CYGWIN__
     2842#  define IS_ABSOLUTE(n) ((n[0] && n[1] == ':') || STOP_SET (n[0], MAP_DIRSEP))
    30502843# else
    3051 #  define FILE_LIST_SEPARATOR ' '
     2844#  define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
    30522845# endif
    3053 
    3054 /* Implements $^ and $+.
    3055 
    3056    The first comes with FUNCNAME 'deps', the second as 'deps-all'.
    3057 
    3058    If no second argument is given, or if it's empty, or if it's zero,
    3059    all dependencies will be returned.  If the second argument is non-zero
    3060    the dependency at that position will be returned.  If the argument is
    3061    negative a fatal error is thrown.  */
    3062 static char *
    3063 func_deps (char *o, char **argv, const char *funcname)
    3064 {
    3065   unsigned int idx = 0;
    3066   struct file *file;
    3067 
    3068   /* Handle the argument if present. */
    3069 
    3070   if (argv[1])
    3071     {
    3072       char *p = argv[1];
    3073       while (isspace ((unsigned int)*p))
    3074         p++;
    3075       if (*p != '\0')
    3076         {
    3077           char *n;
    3078           long l = strtol (p, &n, 0);
    3079           while (isspace ((unsigned int)*n))
    3080             n++;
    3081           idx = l;
    3082           if (*n != '\0' || l < 0 || (long)idx != l)
    3083             fatal (NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
    3084         }
    3085     }
    3086 
    3087   /* Find the file and select the list corresponding to FUNCNAME. */
    3088 
    3089   file = lookup_file (argv[0]);
    3090   if (file)
    3091     {
    3092       struct dep *deps;
    3093       struct dep *d;
    3094       if (funcname[4] == '\0')
    3095         {
    3096           deps = file->deps_no_dupes;
    3097           if (!deps && file->deps)
    3098             deps = file->deps = create_uniqute_deps_chain (file->deps);
    3099         }
    3100       else
    3101         deps = file->deps;
    3102 
    3103       if (   file->double_colon
    3104           && (   file->double_colon != file
    3105               || file->last != file))
    3106           error (NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
    3107                  funcname, file->name);
    3108 
    3109       if (idx == 0 /* all */)
    3110         {
    3111           unsigned int total_len = 0;
    3112 
    3113           /* calc the result length. */
    3114 
    3115           for (d = deps; d; d = d->next)
    3116             if (!d->ignore_mtime)
    3117               {
    3118                 const char *c = dep_name (d);
    3119 
    3120 #ifndef NO_ARCHIVES
    3121                 if (ar_name (c))
    3122                   {
    3123                     c = strchr (c, '(') + 1;
    3124                     total_len += strlen (c);
    3125                   }
    3126                 else
    3127 #elif defined (CONFIG_WITH_STRCACHE2)
    3128                   total_len += strcache2_get_len (&file_strcache, c) + 1;
    3129 #else
    3130                   total_len += strlen (c) + 1;
    3131 #endif
    3132               }
    3133 
    3134           if (total_len)
    3135             {
    3136               /* prepare the variable buffer dude wrt to the output size and
    3137                  pass along the strings.  */
    3138 
    3139               o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
    3140 
    3141               for (d = deps; d; d = d->next)
    3142                 if (!d->ignore_mtime)
    3143                   {
    3144                     unsigned int len;
    3145                     const char *c = dep_name (d);
    3146 
    3147 #ifndef NO_ARCHIVES
    3148                     if (ar_name (c))
    3149                       {
    3150                         c = strchr (c, '(') + 1;
    3151                         len = strlen (c);
    3152                       }
    3153                     else
    3154 #elif defined (CONFIG_WITH_STRCACHE2)
    3155                       len = strcache2_get_len (&file_strcache, c) + 1;
    3156 #else
    3157                       len = strlen (c) + 1;
    3158 #endif
    3159                     o = variable_buffer_output (o, c, len);
    3160                     o[-1] = FILE_LIST_SEPARATOR;
    3161                   }
    3162 
    3163                 --o;        /* nuke the last list separator */
    3164                 *o = '\0';
    3165             }
    3166         }
    3167       else
    3168         {
    3169           /* Dependency given by index.  */
    3170 
    3171           for (d = deps; d; d = d->next)
    3172             if (!d->ignore_mtime)
    3173               {
    3174                 if (--idx == 0) /* 1 based indexing */
    3175                   {
    3176                     unsigned int len;
    3177                     const char *c = dep_name (d);
    3178 
    3179 #ifndef NO_ARCHIVES
    3180                     if (ar_name (c))
    3181                       {
    3182                         c = strchr (c, '(') + 1;
    3183                         len = strlen (c) - 1;
    3184                       }
    3185                     else
    3186 #elif defined (CONFIG_WITH_STRCACHE2)
    3187                       len = strcache2_get_len (&file_strcache, c);
    3188 #else
    3189                       len = strlen (c);
    3190 #endif
    3191                     o = variable_buffer_output (o, c, len);
    3192                     break;
    3193                   }
    3194               }
    3195         }
    3196     }
    3197 
    3198   return o;
    3199 }
    3200 
    3201 /* Implements $?.
    3202 
    3203    If no second argument is given, or if it's empty, or if it's zero,
    3204    all dependencies will be returned.  If the second argument is non-zero
    3205    the dependency at that position will be returned.  If the argument is
    3206    negative a fatal error is thrown.  */
    3207 static char *
    3208 func_deps_newer (char *o, char **argv, const char *funcname)
    3209 {
    3210   unsigned int idx = 0;
    3211   struct file *file;
    3212 
    3213   /* Handle the argument if present. */
    3214 
    3215   if (argv[1])
    3216     {
    3217       char *p = argv[1];
    3218       while (isspace ((unsigned int)*p))
    3219         p++;
    3220       if (*p != '\0')
    3221         {
    3222           char *n;
    3223           long l = strtol (p, &n, 0);
    3224           while (isspace ((unsigned int)*n))
    3225             n++;
    3226           idx = l;
    3227           if (*n != '\0' || l < 0 || (long)idx != l)
    3228             fatal (NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
    3229         }
    3230     }
    3231 
    3232   /* Find the file. */
    3233 
    3234   file = lookup_file (argv[0]);
    3235   if (file)
    3236     {
    3237       struct dep *deps = file->deps;
    3238       struct dep *d;
    3239 
    3240       if (   file->double_colon
    3241           && (   file->double_colon != file
    3242               || file->last != file))
    3243           error (NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
    3244                  funcname, file->name);
    3245 
    3246       if (idx == 0 /* all */)
    3247         {
    3248           unsigned int total_len = 0;
    3249 
    3250           /* calc the result length. */
    3251 
    3252           for (d = deps; d; d = d->next)
    3253             if (!d->ignore_mtime && d->changed)
    3254               {
    3255                 const char *c = dep_name (d);
    3256 
    3257 #ifndef NO_ARCHIVES
    3258                 if (ar_name (c))
    3259                   {
    3260                     c = strchr (c, '(') + 1;
    3261                     total_len += strlen (c);
    3262                   }
    3263                 else
    3264 #elif defined (CONFIG_WITH_STRCACHE2)
    3265                   total_len += strcache2_get_len (&file_strcache, c) + 1;
    3266 #else
    3267                   total_len += strlen (c) + 1;
    3268 #endif
    3269               }
    3270 
    3271           if (total_len)
    3272             {
    3273               /* prepare the variable buffer dude wrt to the output size and
    3274                  pass along the strings.  */
    3275 
    3276               o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
    3277 
    3278               for (d = deps; d; d = d->next)
    3279                 if (!d->ignore_mtime && d->changed)
    3280                   {
    3281                     unsigned int len;
    3282                     const char *c = dep_name (d);
    3283 
    3284 #ifndef NO_ARCHIVES
    3285                     if (ar_name (c))
    3286                       {
    3287                         c = strchr (c, '(') + 1;
    3288                         len = strlen (c);
    3289                       }
    3290                     else
    3291 #elif defined (CONFIG_WITH_STRCACHE2)
    3292                       len = strcache2_get_len (&file_strcache, c) + 1;
    3293 #else
    3294                       len = strlen (c) + 1;
    3295 #endif
    3296                     o = variable_buffer_output (o, c, len);
    3297                     o[-1] = FILE_LIST_SEPARATOR;
    3298                   }
    3299 
    3300                 --o;        /* nuke the last list separator */
    3301                 *o = '\0';
    3302             }
    3303         }
    3304       else
    3305         {
    3306           /* Dependency given by index.  */
    3307 
    3308           for (d = deps; d; d = d->next)
    3309             if (!d->ignore_mtime && d->changed)
    3310               {
    3311                 if (--idx == 0) /* 1 based indexing */
    3312                   {
    3313                     unsigned int len;
    3314                     const char *c = dep_name (d);
    3315 
    3316 #ifndef NO_ARCHIVES
    3317                     if (ar_name (c))
    3318                       {
    3319                         c = strchr (c, '(') + 1;
    3320                         len = strlen (c) - 1;
    3321                       }
    3322                     else
    3323 #elif defined (CONFIG_WITH_STRCACHE2)
    3324                       len = strcache2_get_len (&file_strcache, c);
    3325 #else
    3326                       len = strlen (c);
    3327 #endif
    3328                     o = variable_buffer_output (o, c, len);
    3329                     break;
    3330                   }
    3331               }
    3332         }
    3333     }
    3334 
    3335   return o;
    3336 }
    3337 
    3338 /* Implements $|, the order only dependency list.
    3339 
    3340    If no second argument is given, or if it's empty, or if it's zero,
    3341    all dependencies will be returned.  If the second argument is non-zero
    3342    the dependency at that position will be returned.  If the argument is
    3343    negative a fatal error is thrown.  */
    3344 static char *
    3345 func_deps_order_only (char *o, char **argv, const char *funcname)
    3346 {
    3347   unsigned int idx = 0;
    3348   struct file *file;
    3349 
    3350   /* Handle the argument if present. */
    3351 
    3352   if (argv[1])
    3353     {
    3354       char *p = argv[1];
    3355       while (isspace ((unsigned int)*p))
    3356         p++;
    3357       if (*p != '\0')
    3358         {
    3359           char *n;
    3360           long l = strtol (p, &n, 0);
    3361           while (isspace ((unsigned int)*n))
    3362             n++;
    3363           idx = l;
    3364           if (*n != '\0' || l < 0 || (long)idx != l)
    3365             fatal (NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
    3366         }
    3367     }
    3368 
    3369   /* Find the file. */
    3370 
    3371   file = lookup_file (argv[0]);
    3372   if (file)
    3373     {
    3374       struct dep *deps = file->deps;
    3375       struct dep *d;
    3376 
    3377       if (   file->double_colon
    3378           && (   file->double_colon != file
    3379               || file->last != file))
    3380           error (NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
    3381                  funcname, file->name);
    3382 
    3383       if (idx == 0 /* all */)
    3384         {
    3385           unsigned int total_len = 0;
    3386 
    3387           /* calc the result length. */
    3388 
    3389           for (d = deps; d; d = d->next)
    3390             if (d->ignore_mtime)
    3391               {
    3392                 const char *c = dep_name (d);
    3393 
    3394 #ifndef NO_ARCHIVES
    3395                 if (ar_name (c))
    3396                   {
    3397                     c = strchr (c, '(') + 1;
    3398                     total_len += strlen (c);
    3399                   }
    3400                 else
    3401 #elif defined (CONFIG_WITH_STRCACHE2)
    3402                   total_len += strcache2_get_len (&file_strcache, c) + 1;
    3403 #else
    3404                   total_len += strlen (c) + 1;
    3405 #endif
    3406               }
    3407 
    3408           if (total_len)
    3409             {
    3410               /* prepare the variable buffer dude wrt to the output size and
    3411                  pass along the strings.  */
    3412 
    3413               o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
    3414 
    3415               for (d = deps; d; d = d->next)
    3416                 if (d->ignore_mtime)
    3417                   {
    3418                     unsigned int len;
    3419                     const char *c = dep_name (d);
    3420 
    3421 #ifndef NO_ARCHIVES
    3422                     if (ar_name (c))
    3423                       {
    3424                         c = strchr (c, '(') + 1;
    3425                         len = strlen (c);
    3426                       }
    3427                     else
    3428 #elif defined (CONFIG_WITH_STRCACHE2)
    3429                       len = strcache2_get_len (&file_strcache, c) + 1;
    3430 #else
    3431                       len = strlen (c) + 1;
    3432 #endif
    3433                     o = variable_buffer_output (o, c, len);
    3434                     o[-1] = FILE_LIST_SEPARATOR;
    3435                   }
    3436 
    3437                 --o;        /* nuke the last list separator */
    3438                 *o = '\0';
    3439             }
    3440         }
    3441       else
    3442         {
    3443           /* Dependency given by index.  */
    3444 
    3445           for (d = deps; d; d = d->next)
    3446             if (d->ignore_mtime)
    3447               {
    3448                 if (--idx == 0) /* 1 based indexing */
    3449                   {
    3450                     unsigned int len;
    3451                     const char *c = dep_name (d);
    3452 
    3453 #ifndef NO_ARCHIVES
    3454                     if (ar_name (c))
    3455                       {
    3456                         c = strchr (c, '(') + 1;
    3457                         len = strlen (c) - 1;
    3458                       }
    3459                     else
    3460 #elif defined (CONFIG_WITH_STRCACHE2)
    3461                       len = strcache2_get_len (&file_strcache, c);
    3462 #else
    3463                       len = strlen (c);
    3464 #endif
    3465                     o = variable_buffer_output (o, c, len);
    3466                     break;
    3467                   }
    3468               }
    3469         }
    3470     }
    3471 
    3472   return o;
    3473 }
    3474 #endif /* CONFIG_WITH_LAZY_DEPS_VARS */
    3475 
    3476 
    3477 
    3478 #ifdef CONFIG_WITH_DEFINED
    3479 /* Similar to ifdef. */
    3480 static char *
    3481 func_defined (char *o, char **argv, const char *funcname UNUSED)
    3482 {
    3483   struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
    3484   int result = v != NULL && *v->value != '\0';
    3485   o = variable_buffer_output (o,  result ? "1" : "", result);
    3486   return o;
    3487 }
    3488 #endif /* CONFIG_WITH_DEFINED*/
    3489 
    3490 
    3491 
    3492 #ifdef HAVE_DOS_PATHS
    3493 #define IS_ABSOLUTE(n) (n[0] && n[1] == ':')
    3494 #define ROOT_LEN 3
     2846# define ROOT_LEN 3
    34952847#else
    34962848#define IS_ABSOLUTE(n) (n[0] == '/')
     
    34982850#endif
    34992851
    3500 /* Return the absolute name of file NAME which does not contain any `.',
    3501    `..' components nor any repeated path separators ('/').   */
     2852/* Return the absolute name of file NAME which does not contain any '.',
     2853   '..' components nor any repeated path separators ('/').   */
    35022854#ifdef KMK
    35032855char *
     
    35402892      /* It is unlikely we would make it until here but just to make sure. */
    35412893      if (!starting_directory)
    3542         return NULL;
     2894        return NULL;
    35432895
    35442896      strcpy (apath, starting_directory);
    35452897
    35462898#ifdef HAVE_DOS_PATHS
    3547       if (IS_PATHSEP(name[0]))
    3548         {
    3549           if (IS_PATHSEP(name[1]))
    3550             {
    3551               /* A UNC.  Don't prepend a drive letter.  */
    3552               apath[0] = name[0];
    3553               apath[1] = name[1];
    3554               root_len = 2;
    3555             }
    3556           /* We have /foo, an absolute file name except for the drive
    3557              letter.  Assume the missing drive letter is the current
    3558              drive, which we can get if we remove from starting_directory
    3559              everything past the root directory.  */
    3560           apath[root_len] = '\0';
    3561         }
     2899      if (STOP_SET (name[0], MAP_DIRSEP))
     2900        {
     2901          if (STOP_SET (name[1], MAP_DIRSEP))
     2902            {
     2903              /* A UNC.  Don't prepend a drive letter.  */
     2904              apath[0] = name[0];
     2905              apath[1] = name[1];
     2906              root_len = 2;
     2907            }
     2908          /* We have /foo, an absolute file name except for the drive
     2909             letter.  Assume the missing drive letter is the current
     2910             drive, which we can get if we remove from starting_directory
     2911             everything past the root directory.  */
     2912          apath[root_len] = '\0';
     2913        }
    35622914#endif
    35632915
     
    35662918  else
    35672919    {
     2920#if defined(__CYGWIN__) && defined(HAVE_DOS_PATHS)
     2921      if (STOP_SET (name[0], MAP_DIRSEP))
     2922        root_len = 1;
     2923#endif
    35682924      strncpy (apath, name, root_len);
    35692925      apath[root_len] = '\0';
     
    35722928      name += root_len;
    35732929#ifdef HAVE_DOS_PATHS
    3574       if (!IS_PATHSEP(apath[2]))
    3575         {
    3576           /* Convert d:foo into d:./foo and increase root_len.  */
    3577           apath[2] = '.';
    3578           apath[3] = '/';
    3579           dest++;
    3580           root_len++;
    3581           /* strncpy above copied one character too many.  */
    3582           name--;
    3583         }
     2930      if (! STOP_SET (apath[root_len - 1], MAP_DIRSEP))
     2931        {
     2932          /* Convert d:foo into d:./foo and increase root_len.  */
     2933          apath[2] = '.';
     2934          apath[3] = '/';
     2935          dest++;
     2936          root_len++;
     2937          /* strncpy above copied one character too many.  */
     2938          name--;
     2939        }
    35842940      else
    3585         apath[2] = '/'; /* make sure it's a forward slash */
     2941        apath[root_len - 1] = '/'; /* make sure it's a forward slash */
    35862942#endif
    35872943    }
     
    35922948
    35932949      /* Skip sequence of multiple path-separators.  */
    3594       while (IS_PATHSEP(*start))
    3595         ++start;
     2950      while (STOP_SET (*start, MAP_DIRSEP))
     2951        ++start;
    35962952
    35972953      /* Find end of path component.  */
    3598       for (end = start; *end != '\0' && !IS_PATHSEP(*end); ++end)
     2954      for (end = start; ! STOP_SET (*end, MAP_DIRSEP|MAP_NUL); ++end)
    35992955        ;
    36002956
     
    36022958
    36032959      if (len == 0)
    3604         break;
     2960        break;
    36052961      else if (len == 1 && start[0] == '.')
    3606         /* nothing */;
     2962        /* nothing */;
    36072963      else if (len == 2 && start[0] == '.' && start[1] == '.')
    3608         {
    3609           /* Back up to previous component, ignore if at root already.  */
    3610           if (dest > apath + root_len)
    3611             for (--dest; !IS_PATHSEP(dest[-1]); --dest);
    3612         }
     2964        {
     2965          /* Back up to previous component, ignore if at root already.  */
     2966          if (dest > apath + root_len)
     2967            for (--dest; ! STOP_SET (dest[-1], MAP_DIRSEP); --dest)
     2968              ;
     2969        }
    36132970      else
    3614         {
    3615           if (!IS_PATHSEP(dest[-1]))
     2971        {
     2972          if (! STOP_SET (dest[-1], MAP_DIRSEP))
    36162973            *dest++ = '/';
    36172974
    3618           if (dest + len >= apath_limit)
     2975          if (dest + len >= apath_limit)
    36192976            return NULL;
    36202977
    3621           dest = memcpy (dest, start, len);
     2978          dest = memcpy (dest, start, len);
    36222979          dest += len;
    3623           *dest = '\0';
    3624         }
     2980          *dest = '\0';
     2981        }
    36252982    }
    36262983#endif /* !WINDOWS32 && !__OS2__ */
    36272984
    36282985  /* Unless it is root strip trailing separator.  */
    3629   if (dest > apath + root_len && IS_PATHSEP(dest[-1]))
     2986  if (dest > apath + root_len && STOP_SET (dest[-1], MAP_DIRSEP))
    36302987    --dest;
    36312988
     
    36443001  int doneany = 0;
    36453002  unsigned int len = 0;
    3646 #ifndef HAVE_REALPATH
    3647   struct stat st;
    3648 #endif
    3649   PATH_VAR (in);
    3650   PATH_VAR (out);
    36513003
    36523004  while ((path = find_next_token (&p, &len)) != 0)
     
    36543006      if (len < GET_PATH_MAX)
    36553007        {
     3008          char *rp;
     3009          struct stat st;
     3010          PATH_VAR (in);
     3011          PATH_VAR (out);
     3012
    36563013          strncpy (in, path, len);
    36573014          in[len] = '\0';
    36583015
    3659           if (
    36603016#ifdef HAVE_REALPATH
    3661               realpath (in, out)
     3017          ENULLLOOP (rp, realpath (in, out));
    36623018#else
    3663               abspath (in, out) && stat (out, &st) == 0
    3664 #endif
    3665              )
     3019          rp = abspath (in, out);
     3020#endif
     3021
     3022          if (rp)
    36663023            {
    3667               o = variable_buffer_output (o, out, strlen (out));
    3668               o = variable_buffer_output (o, " ", 1);
    3669               doneany = 1;
     3024              int r;
     3025              EINTRLOOP (r, stat (out, &st));
     3026              if (r == 0)
     3027                {
     3028                  o = variable_buffer_output (o, out, strlen (out));
     3029                  o = variable_buffer_output (o, " ", 1);
     3030                  doneany = 1;
     3031                }
    36703032            }
    36713033        }
     
    36753037  if (doneany)
    36763038    --o;
     3039
     3040  return o;
     3041}
     3042
     3043static char *
     3044func_file (char *o, char **argv, const char *funcname UNUSED)
     3045{
     3046  char *fn = argv[0];
     3047
     3048  if (fn[0] == '>')
     3049    {
     3050      FILE *fp;
     3051      const char *mode = "w";
     3052
     3053      /* We are writing a file.  */
     3054      ++fn;
     3055      if (fn[0] == '>')
     3056        {
     3057          mode = "a";
     3058          ++fn;
     3059        }
     3060      NEXT_TOKEN (fn);
     3061
     3062      if (fn[0] == '\0')
     3063        O (fatal, *expanding_var, _("file: missing filename"));
     3064
     3065      ENULLLOOP (fp, fopen (fn, mode));
     3066      if (fp == NULL)
     3067        OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
     3068
     3069      if (argv[1])
     3070        {
     3071          int l = strlen (argv[1]);
     3072          int nl = l == 0 || argv[1][l-1] != '\n';
     3073
     3074          if (fputs (argv[1], fp) == EOF || (nl && fputc ('\n', fp) == EOF))
     3075            OSS (fatal, reading_file, _("write: %s: %s"), fn, strerror (errno));
     3076        }
     3077      if (fclose (fp))
     3078        OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
     3079    }
     3080  else if (fn[0] == '<')
     3081    {
     3082      char *preo = o;
     3083      FILE *fp;
     3084
     3085      ++fn;
     3086      NEXT_TOKEN (fn);
     3087      if (fn[0] == '\0')
     3088        O (fatal, *expanding_var, _("file: missing filename"));
     3089
     3090      if (argv[1])
     3091        O (fatal, *expanding_var, _("file: too many arguments"));
     3092
     3093      ENULLLOOP (fp, fopen (fn, "r"));
     3094      if (fp == NULL)
     3095        {
     3096          if (errno == ENOENT)
     3097            return o;
     3098          OSS (fatal, reading_file, _("open: %s: %s"), fn, strerror (errno));
     3099        }
     3100
     3101      while (1)
     3102        {
     3103          char buf[1024];
     3104          size_t l = fread (buf, 1, sizeof (buf), fp);
     3105          if (l > 0)
     3106            o = variable_buffer_output (o, buf, l);
     3107
     3108          if (ferror (fp))
     3109            if (errno != EINTR)
     3110              OSS (fatal, reading_file, _("read: %s: %s"), fn, strerror (errno));
     3111          if (feof (fp))
     3112            break;
     3113        }
     3114      if (fclose (fp))
     3115        OSS (fatal, reading_file, _("close: %s: %s"), fn, strerror (errno));
     3116
     3117      /* Remove trailing newline.  */
     3118      if (o > preo && o[-1] == '\n')
     3119        if (--o > preo && o[-1] == '\r')
     3120          --o;
     3121    }
     3122  else
     3123    OS (fatal, *expanding_var, _("file: invalid file operation: %s"), fn);
    36773124
    36783125  return o;
     
    36873134  int doneany = 0;
    36883135  unsigned int len = 0;
    3689   PATH_VAR (in);
    3690   PATH_VAR (out);
    36913136
    36923137  while ((path = find_next_token (&p, &len)) != 0)
     
    36943139      if (len < GET_PATH_MAX)
    36953140        {
     3141          PATH_VAR (in);
     3142          PATH_VAR (out);
     3143
    36963144          strncpy (in, path, len);
    36973145          in[len] = '\0';
     
    37243172     in which case we're exactly like $(abspath ). */
    37253173  if (cwd)
    3726     while (isblank (*cwd))
     3174    while (ISBLANK (*cwd))
    37273175      cwd++;
    37283176  if (!cwd || !*cwd)
     
    38383286    argc++;
    38393287  if (argc > 4)
    3840     fatal (NILF, _("Too many arguments for $(xargs)!\n"));
     3288    O (fatal, NILF, _("Too many arguments for $(xargs)!\n"));
    38413289
    38423290  /* first: the initial / default command.*/
    38433291  initial_cmd = argv[0];
    3844   while (isspace ((unsigned char)*initial_cmd))
     3292  while (ISSPACE (*initial_cmd))
    38453293    initial_cmd++;
    38463294  max_args = initial_cmd_len = strlen (initial_cmd);
     
    38483296  /* second: the command for the subsequent command lines. defaults to the initial cmd. */
    38493297  subsequent_cmd = argc > 2 && argv[1][0] != '\0' ? argv[1] : "";
    3850   while (isspace ((unsigned char)*subsequent_cmd))
     3298  while (ISSPACE (*subsequent_cmd))
    38513299    subsequent_cmd++;
    38523300  if (*subsequent_cmd)
     
    38643312  /* third: the final command. defaults to the subseq cmd. */
    38653313  final_cmd = argc > 3 && argv[2][0] != '\0' ? argv[2] : "";
    3866   while (isspace ((unsigned char)*final_cmd))
     3314  while (ISSPACE (*final_cmd))
    38673315    final_cmd++;
    38683316  if (*final_cmd)
     
    38833331  /* calc the max argument length. */
    38843332  if (XARGS_MAX <= max_args + 2)
    3885     fatal (NILF, _("$(xargs): the commands are longer than the max exec argument length. (%lu <= %lu)\n"),
    3886            (unsigned long)XARGS_MAX, (unsigned long)max_args + 2);
     3333    ONN (fatal, NILF, _("$(xargs): the commands are longer than the max exec argument length. (%lu <= %lu)\n"),
     3334         (unsigned long)XARGS_MAX, (unsigned long)max_args + 2);
    38873335  max_args = XARGS_MAX - max_args - 1;
    38883336
     
    39023350        end = cur + len;
    39033351      if (cur && end == args)
    3904         fatal (NILF, _("$(xargs): command + one single arg is too much. giving up.\n"));
     3352        O (fatal, NILF, _("$(xargs): command + one single arg is too much. giving up.\n"));
    39053353
    39063354      /* emit the command. */
     
    39243372
    39253373      tmp = end;
    3926       while (tmp > args && isspace ((unsigned char)tmp[-1])) /* drop trailing spaces. */
     3374      while (tmp > args && ISSPACE (tmp[-1])) /* drop trailing spaces. */
    39273375        tmp--;
    39283376      o = variable_buffer_output (o, (char *)args, tmp - args);
     
    39333381        break;
    39343382      args = end;
    3935       while (isspace ((unsigned char)*args))
     3383      while (ISSPACE (*args))
    39363384        args++;
    39373385    }
     
    39403388}
    39413389#endif
     3390
     3391
     3392#ifdef CONFIG_WITH_STRING_FUNCTIONS
     3393/*
     3394  $(length string)
     3395
     3396  XXX: This doesn't take multibyte locales into account.
     3397 */
     3398static char *
     3399func_length (char *o, char **argv, const char *funcname UNUSED)
     3400{
     3401  size_t len = strlen (argv[0]);
     3402  return math_int_to_variable_buffer (o, len);
     3403}
     3404
     3405/*
     3406  $(length-var var)
     3407
     3408  XXX: This doesn't take multibyte locales into account.
     3409 */
     3410static char *
     3411func_length_var (char *o, char **argv, const char *funcname UNUSED)
     3412{
     3413  struct variable *var = lookup_variable (argv[0], strlen (argv[0]));
     3414  return math_int_to_variable_buffer (o, var ? var->value_length : 0);
     3415}
     3416
     3417
     3418/* func_insert and func_substr helper. */
     3419static char *
     3420helper_pad (char *o, size_t to_add, const char *pad, size_t pad_len)
     3421{
     3422  while (to_add > 0)
     3423    {
     3424      size_t size = to_add > pad_len ? pad_len : to_add;
     3425      o = variable_buffer_output (o, pad, size);
     3426      to_add -= size;
     3427    }
     3428  return o;
     3429}
     3430
     3431/*
     3432  $(insert in, str[, n[, length[, pad]]])
     3433
     3434  XXX: This doesn't take multibyte locales into account.
     3435 */
     3436static char *
     3437func_insert (char *o, char **argv, const char *funcname UNUSED)
     3438{
     3439  const char *in      = argv[0];
     3440  math_int    in_len  = (math_int)strlen (in);
     3441  const char *str     = argv[1];
     3442  math_int    str_len = (math_int)strlen (str);
     3443  math_int    n       = 0;
     3444  math_int    length  = str_len;
     3445  const char *pad     = "                ";
     3446  size_t      pad_len = 16;
     3447  size_t      i;
     3448
     3449  if (argv[2] != NULL)
     3450    {
     3451      n = math_int_from_string (argv[2]);
     3452      if (n > 0)
     3453        n--;            /* one-origin */
     3454      else if (n == 0)
     3455        n = str_len;    /* append */
     3456      else
     3457        { /* n < 0: from the end */
     3458          n = str_len + n;
     3459          if (n < 0)
     3460            n = 0;
     3461        }
     3462      if (n > 16*1024*1024) /* 16MB */
     3463        OS (fatal, NILF, _("$(insert ): n=%s is out of bounds\n"), argv[2]);
     3464
     3465      if (argv[3] != NULL)
     3466        {
     3467          length = math_int_from_string (argv[3]);
     3468          if (length < 0 || length > 16*1024*1024 /* 16MB */)
     3469              OS (fatal, NILF, _("$(insert ): length=%s is out of bounds\n"), argv[3]);
     3470
     3471          if (argv[4] != NULL)
     3472            {
     3473              const char *tmp = argv[4];
     3474              for (i = 0; tmp[i] == ' '; i++)
     3475                /* nothing */;
     3476              if (tmp[i] != '\0')
     3477                {
     3478                  pad = argv[4];
     3479                  pad_len = strlen (pad);
     3480                }
     3481              /* else: it was all default spaces. */
     3482            }
     3483        }
     3484    }
     3485
     3486  /* the head of the original string */
     3487  if (n > 0)
     3488    {
     3489      if (n <= str_len)
     3490        o = variable_buffer_output (o, str, n);
     3491      else
     3492        {
     3493          o = variable_buffer_output (o, str, str_len);
     3494          o = helper_pad (o, n - str_len, pad, pad_len);
     3495        }
     3496    }
     3497
     3498  /* insert the string */
     3499  if (length <= in_len)
     3500    o = variable_buffer_output (o, in, length);
     3501  else
     3502    {
     3503      o = variable_buffer_output (o, in, in_len);
     3504      o = helper_pad (o, length - in_len, pad, pad_len);
     3505    }
     3506
     3507  /* the tail of the original string */
     3508  if (n < str_len)
     3509    o = variable_buffer_output (o, str + n, str_len - n);
     3510
     3511  return o;
     3512}
     3513
     3514
     3515/*
     3516  $(pos needle, haystack[, start])
     3517  $(lastpos needle, haystack[, start])
     3518
     3519  XXX: This doesn't take multibyte locales into account.
     3520 */
     3521static char *
     3522func_pos (char *o, char **argv, const char *funcname UNUSED)
     3523{
     3524  const char *needle       = *argv[0] ? argv[0] : " ";
     3525  size_t      needle_len   = strlen (needle);
     3526  const char *haystack     = argv[1];
     3527  size_t      haystack_len = strlen (haystack);
     3528  math_int    start        = 0;
     3529  const char *hit;
     3530
     3531  if (argv[2] != NULL)
     3532    {
     3533      start = math_int_from_string (argv[2]);
     3534      if (start > 0)
     3535        start--;            /* one-origin */
     3536      else if (start < 0)
     3537        start = haystack_len + start; /* from the end */
     3538      if (start < 0 || start + needle_len > haystack_len)
     3539        return math_int_to_variable_buffer (o, 0);
     3540    }
     3541  else if (funcname[0] == 'l')
     3542    start = haystack_len - 1;
     3543
     3544  /* do the searching */
     3545  if (funcname[0] != 'l')
     3546    { /* pos */
     3547      if (needle_len == 1)
     3548        hit = strchr (haystack + start, *needle);
     3549      else
     3550        hit = strstr (haystack + start, needle);
     3551    }
     3552  else
     3553    { /* last pos */
     3554      int    ch  = *needle;
     3555      size_t off = start + 1;
     3556
     3557      hit = NULL;
     3558      while (off-- > 0)
     3559        {
     3560          if (   haystack[off] == ch
     3561              && (   needle_len == 1
     3562                  || strncmp (&haystack[off], needle, needle_len) == 0))
     3563            {
     3564              hit = haystack + off;
     3565              break;
     3566            }
     3567        }
     3568    }
     3569
     3570  return math_int_to_variable_buffer (o, hit ? hit - haystack + 1 : 0);
     3571}
     3572
     3573
     3574/*
     3575  $(substr str, start[, length[, pad]])
     3576
     3577  XXX: This doesn't take multibyte locales into account.
     3578 */
     3579static char *
     3580func_substr (char *o, char **argv, const char *funcname UNUSED)
     3581{
     3582  const char *str     = argv[0];
     3583  math_int    str_len = (math_int)strlen (str);
     3584  math_int    start   = math_int_from_string (argv[1]);
     3585  math_int    length  = 0;
     3586  const char *pad     = NULL;
     3587  size_t      pad_len = 0;
     3588
     3589  if (argv[2] != NULL)
     3590    {
     3591      if (argv[3] != NULL)
     3592        {
     3593          pad = argv[3];
     3594          for (pad_len = 0; pad[pad_len] == ' '; pad_len++)
     3595            /* nothing */;
     3596          if (pad[pad_len] != '\0')
     3597              pad_len = strlen (pad);
     3598          else
     3599            {
     3600              pad = "                ";
     3601              pad_len = 16;
     3602            }
     3603        }
     3604      length = math_int_from_string (argv[2]);
     3605      if (pad != NULL && length > 16*1024*1024 /* 16MB */)
     3606        OS (fatal, NILF, _("$(substr ): length=%s is out of bounds\n"), argv[2]);
     3607      if (pad != NULL && length < 0)
     3608        OS (fatal, NILF, _("$(substr ): negative length (%s) and padding doesn't mix.\n"), argv[2]);
     3609      if (length == 0)
     3610        return o;
     3611    }
     3612
     3613  /* Note that negative start is and length are used for referencing from the
     3614     end of the string. */
     3615  if (pad == NULL)
     3616    {
     3617      if (start > 0)
     3618        start--;      /* one-origin */
     3619      else
     3620        {
     3621          start = str_len + start;
     3622          if (start <= 0)
     3623            {
     3624              if (length < 0)
     3625                return o;
     3626              start += length;
     3627              if (start <= 0)
     3628                return o;
     3629              length = start;
     3630              start = 0;
     3631            }
     3632        }
     3633
     3634      if (start >= str_len)
     3635        return o;
     3636      if (length == 0)
     3637        length = str_len - start;
     3638      else if (length < 0)
     3639        {
     3640          if (str_len <= -length)
     3641            return o;
     3642          length += str_len;
     3643          if (length <= start)
     3644            return o;
     3645          length -= start;
     3646        }
     3647      else if (start + length > str_len)
     3648        length = str_len - start;
     3649
     3650      o = variable_buffer_output (o, str + start, length);
     3651    }
     3652  else
     3653    {
     3654      if (start > 0)
     3655        {
     3656          start--;      /* one-origin */
     3657          if (start >= str_len)
     3658            return length ? helper_pad (o, length, pad, pad_len) : o;
     3659          if (length == 0)
     3660            length = str_len - start;
     3661        }
     3662      else
     3663        {
     3664          start = str_len + start;
     3665          if (start <= 0)
     3666            {
     3667              if (start + length <= 0)
     3668                return length ? helper_pad (o, length, pad, pad_len) : o;
     3669              o = helper_pad (o, -start, pad, pad_len);
     3670              return variable_buffer_output (o, str, length + start);
     3671            }
     3672          if (length == 0)
     3673            length = str_len - start;
     3674        }
     3675      if (start + length <= str_len)
     3676        o = variable_buffer_output (o, str + start, length);
     3677      else
     3678        {
     3679          o = variable_buffer_output (o, str + start, str_len - start);
     3680          o = helper_pad (o, start + length - str_len, pad, pad_len);
     3681        }
     3682    }
     3683
     3684  return o;
     3685}
     3686
     3687
     3688/*
     3689  $(translate string, from-set[, to-set[, pad-char]])
     3690
     3691  XXX: This doesn't take multibyte locales into account.
     3692 */
     3693static char *
     3694func_translate (char *o, char **argv, const char *funcname UNUSED)
     3695{
     3696  const unsigned char *str      = (const unsigned char *)argv[0];
     3697  const unsigned char *from_set = (const unsigned char *)argv[1];
     3698  const char          *to_set   = argv[2] != NULL ? argv[2] : "";
     3699  char                 trans_tab[1 << CHAR_BIT];
     3700  int                  i;
     3701  char                 ch;
     3702
     3703  /* init the array. */
     3704  for (i = 0; i < (1 << CHAR_BIT); i++)
     3705    trans_tab[i] = i;
     3706
     3707  while (   (i = *from_set) != '\0'
     3708         && (ch = *to_set) != '\0')
     3709    {
     3710      trans_tab[i] = ch;
     3711      from_set++;
     3712      to_set++;
     3713    }
     3714
     3715  if (i != '\0')
     3716    {
     3717      ch = '\0';                        /* no padding == remove char */
     3718      if (argv[2] != NULL && argv[3] != NULL)
     3719        {
     3720          ch = argv[3][0];
     3721          if (ch && argv[3][1])
     3722            OS (fatal, NILF, _("$(translate ): pad=`%s' expected a single char\n"), argv[3]);
     3723          if (ch == '\0')               /* no char == space */
     3724            ch = ' ';
     3725        }
     3726      while ((i = *from_set++) != '\0')
     3727        trans_tab[i] = ch;
     3728    }
     3729
     3730  /* do the translation */
     3731  while ((i = *str++) != '\0')
     3732    {
     3733      ch = trans_tab[i];
     3734      if (ch)
     3735        o = variable_buffer_output (o, &ch, 1);
     3736    }
     3737
     3738  return o;
     3739}
     3740#endif /* CONFIG_WITH_STRING_FUNCTIONS */
     3741
     3742
     3743#ifdef CONFIG_WITH_LAZY_DEPS_VARS
     3744
     3745/* This is also in file.c (bad).  */
     3746# if VMS
     3747#  define FILE_LIST_SEPARATOR ','
     3748# else
     3749#  define FILE_LIST_SEPARATOR ' '
     3750# endif
     3751
     3752/* Implements $^ and $+.
     3753
     3754   The first comes with FUNCNAME 'deps', the second as 'deps-all'.
     3755
     3756   If no second argument is given, or if it's empty, or if it's zero,
     3757   all dependencies will be returned.  If the second argument is non-zero
     3758   the dependency at that position will be returned.  If the argument is
     3759   negative a fatal error is thrown.  */
     3760static char *
     3761func_deps (char *o, char **argv, const char *funcname)
     3762{
     3763  unsigned int idx = 0;
     3764  struct file *file;
     3765
     3766  /* Handle the argument if present. */
     3767
     3768  if (argv[1])
     3769    {
     3770      char *p = argv[1];
     3771      while (ISSPACE (*p))
     3772        p++;
     3773      if (*p != '\0')
     3774        {
     3775          char *n;
     3776          long l = strtol (p, &n, 0);
     3777          while (ISSPACE (*n))
     3778            n++;
     3779          idx = l;
     3780          if (*n != '\0' || l < 0 || (long)idx != l)
     3781            OSS (fatal, NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
     3782        }
     3783    }
     3784
     3785  /* Find the file and select the list corresponding to FUNCNAME. */
     3786
     3787  file = lookup_file (argv[0]);
     3788  if (file)
     3789    {
     3790      struct dep *deps;
     3791      struct dep *d;
     3792      if (funcname[4] == '\0')
     3793        {
     3794          deps = file->deps_no_dupes;
     3795          if (!deps && file->deps)
     3796            deps = file->deps = create_uniqute_deps_chain (file->deps);
     3797        }
     3798      else
     3799        deps = file->deps;
     3800
     3801      if (   file->double_colon
     3802          && (   file->double_colon != file
     3803              || file->last != file))
     3804          OSS (error, NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
     3805               funcname, file->name);
     3806
     3807      if (idx == 0 /* all */)
     3808        {
     3809          unsigned int total_len = 0;
     3810
     3811          /* calc the result length. */
     3812
     3813          for (d = deps; d; d = d->next)
     3814            if (!d->ignore_mtime)
     3815              {
     3816                const char *c = dep_name (d);
     3817
     3818#ifndef NO_ARCHIVES
     3819                if (ar_name (c))
     3820                  {
     3821                    c = strchr (c, '(') + 1;
     3822                    total_len += strlen (c);
     3823                  }
     3824                else
     3825#elif defined (CONFIG_WITH_STRCACHE2)
     3826                  total_len += strcache2_get_len (&file_strcache, c) + 1;
     3827#else
     3828                  total_len += strlen (c) + 1;
     3829#endif
     3830              }
     3831
     3832          if (total_len)
     3833            {
     3834              /* prepare the variable buffer dude wrt to the output size and
     3835                 pass along the strings.  */
     3836
     3837              o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
     3838
     3839              for (d = deps; d; d = d->next)
     3840                if (!d->ignore_mtime)
     3841                  {
     3842                    unsigned int len;
     3843                    const char *c = dep_name (d);
     3844
     3845#ifndef NO_ARCHIVES
     3846                    if (ar_name (c))
     3847                      {
     3848                        c = strchr (c, '(') + 1;
     3849                        len = strlen (c);
     3850                      }
     3851                    else
     3852#elif defined (CONFIG_WITH_STRCACHE2)
     3853                      len = strcache2_get_len (&file_strcache, c) + 1;
     3854#else
     3855                      len = strlen (c) + 1;
     3856#endif
     3857                    o = variable_buffer_output (o, c, len);
     3858                    o[-1] = FILE_LIST_SEPARATOR;
     3859                  }
     3860
     3861                --o;        /* nuke the last list separator */
     3862                *o = '\0';
     3863            }
     3864        }
     3865      else
     3866        {
     3867          /* Dependency given by index.  */
     3868
     3869          for (d = deps; d; d = d->next)
     3870            if (!d->ignore_mtime)
     3871              {
     3872                if (--idx == 0) /* 1 based indexing */
     3873                  {
     3874                    unsigned int len;
     3875                    const char *c = dep_name (d);
     3876
     3877#ifndef NO_ARCHIVES
     3878                    if (ar_name (c))
     3879                      {
     3880                        c = strchr (c, '(') + 1;
     3881                        len = strlen (c) - 1;
     3882                      }
     3883                    else
     3884#elif defined (CONFIG_WITH_STRCACHE2)
     3885                      len = strcache2_get_len (&file_strcache, c);
     3886#else
     3887                      len = strlen (c);
     3888#endif
     3889                    o = variable_buffer_output (o, c, len);
     3890                    break;
     3891                  }
     3892              }
     3893        }
     3894    }
     3895
     3896  return o;
     3897}
     3898
     3899/* Implements $?.
     3900
     3901   If no second argument is given, or if it's empty, or if it's zero,
     3902   all dependencies will be returned.  If the second argument is non-zero
     3903   the dependency at that position will be returned.  If the argument is
     3904   negative a fatal error is thrown.  */
     3905static char *
     3906func_deps_newer (char *o, char **argv, const char *funcname)
     3907{
     3908  unsigned int idx = 0;
     3909  struct file *file;
     3910
     3911  /* Handle the argument if present. */
     3912
     3913  if (argv[1])
     3914    {
     3915      char *p = argv[1];
     3916      while (ISSPACE (*p))
     3917        p++;
     3918      if (*p != '\0')
     3919        {
     3920          char *n;
     3921          long l = strtol (p, &n, 0);
     3922          while (ISSPACE (*n))
     3923            n++;
     3924          idx = l;
     3925          if (*n != '\0' || l < 0 || (long)idx != l)
     3926            OSS (fatal, NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
     3927        }
     3928    }
     3929
     3930  /* Find the file. */
     3931
     3932  file = lookup_file (argv[0]);
     3933  if (file)
     3934    {
     3935      struct dep *deps = file->deps;
     3936      struct dep *d;
     3937
     3938      if (   file->double_colon
     3939          && (   file->double_colon != file
     3940              || file->last != file))
     3941          OSS (error, NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
     3942               funcname, file->name);
     3943
     3944      if (idx == 0 /* all */)
     3945        {
     3946          unsigned int total_len = 0;
     3947
     3948          /* calc the result length. */
     3949
     3950          for (d = deps; d; d = d->next)
     3951            if (!d->ignore_mtime && d->changed)
     3952              {
     3953                const char *c = dep_name (d);
     3954
     3955#ifndef NO_ARCHIVES
     3956                if (ar_name (c))
     3957                  {
     3958                    c = strchr (c, '(') + 1;
     3959                    total_len += strlen (c);
     3960                  }
     3961                else
     3962#elif defined (CONFIG_WITH_STRCACHE2)
     3963                  total_len += strcache2_get_len (&file_strcache, c) + 1;
     3964#else
     3965                  total_len += strlen (c) + 1;
     3966#endif
     3967              }
     3968
     3969          if (total_len)
     3970            {
     3971              /* prepare the variable buffer dude wrt to the output size and
     3972                 pass along the strings.  */
     3973
     3974              o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
     3975
     3976              for (d = deps; d; d = d->next)
     3977                if (!d->ignore_mtime && d->changed)
     3978                  {
     3979                    unsigned int len;
     3980                    const char *c = dep_name (d);
     3981
     3982#ifndef NO_ARCHIVES
     3983                    if (ar_name (c))
     3984                      {
     3985                        c = strchr (c, '(') + 1;
     3986                        len = strlen (c);
     3987                      }
     3988                    else
     3989#elif defined (CONFIG_WITH_STRCACHE2)
     3990                      len = strcache2_get_len (&file_strcache, c) + 1;
     3991#else
     3992                      len = strlen (c) + 1;
     3993#endif
     3994                    o = variable_buffer_output (o, c, len);
     3995                    o[-1] = FILE_LIST_SEPARATOR;
     3996                  }
     3997
     3998                --o;        /* nuke the last list separator */
     3999                *o = '\0';
     4000            }
     4001        }
     4002      else
     4003        {
     4004          /* Dependency given by index.  */
     4005
     4006          for (d = deps; d; d = d->next)
     4007            if (!d->ignore_mtime && d->changed)
     4008              {
     4009                if (--idx == 0) /* 1 based indexing */
     4010                  {
     4011                    unsigned int len;
     4012                    const char *c = dep_name (d);
     4013
     4014#ifndef NO_ARCHIVES
     4015                    if (ar_name (c))
     4016                      {
     4017                        c = strchr (c, '(') + 1;
     4018                        len = strlen (c) - 1;
     4019                      }
     4020                    else
     4021#elif defined (CONFIG_WITH_STRCACHE2)
     4022                      len = strcache2_get_len (&file_strcache, c);
     4023#else
     4024                      len = strlen (c);
     4025#endif
     4026                    o = variable_buffer_output (o, c, len);
     4027                    break;
     4028                  }
     4029              }
     4030        }
     4031    }
     4032
     4033  return o;
     4034}
     4035
     4036/* Implements $|, the order only dependency list.
     4037
     4038   If no second argument is given, or if it's empty, or if it's zero,
     4039   all dependencies will be returned.  If the second argument is non-zero
     4040   the dependency at that position will be returned.  If the argument is
     4041   negative a fatal error is thrown.  */
     4042static char *
     4043func_deps_order_only (char *o, char **argv, const char *funcname)
     4044{
     4045  unsigned int idx = 0;
     4046  struct file *file;
     4047
     4048  /* Handle the argument if present. */
     4049
     4050  if (argv[1])
     4051    {
     4052      char *p = argv[1];
     4053      while (ISSPACE (*p))
     4054        p++;
     4055      if (*p != '\0')
     4056        {
     4057          char *n;
     4058          long l = strtol (p, &n, 0);
     4059          while (ISSPACE (*n))
     4060            n++;
     4061          idx = l;
     4062          if (*n != '\0' || l < 0 || (long)idx != l)
     4063            OSS (fatal, NILF, _("%s: invalid index value: `%s'\n"), funcname, p);
     4064        }
     4065    }
     4066
     4067  /* Find the file. */
     4068
     4069  file = lookup_file (argv[0]);
     4070  if (file)
     4071    {
     4072      struct dep *deps = file->deps;
     4073      struct dep *d;
     4074
     4075      if (   file->double_colon
     4076          && (   file->double_colon != file
     4077              || file->last != file))
     4078          OSS (error, NILF, _("$(%s ) cannot be used on files with multiple double colon rules like `%s'\n"),
     4079               funcname, file->name);
     4080
     4081      if (idx == 0 /* all */)
     4082        {
     4083          unsigned int total_len = 0;
     4084
     4085          /* calc the result length. */
     4086
     4087          for (d = deps; d; d = d->next)
     4088            if (d->ignore_mtime)
     4089              {
     4090                const char *c = dep_name (d);
     4091
     4092#ifndef NO_ARCHIVES
     4093                if (ar_name (c))
     4094                  {
     4095                    c = strchr (c, '(') + 1;
     4096                    total_len += strlen (c);
     4097                  }
     4098                else
     4099#elif defined (CONFIG_WITH_STRCACHE2)
     4100                  total_len += strcache2_get_len (&file_strcache, c) + 1;
     4101#else
     4102                  total_len += strlen (c) + 1;
     4103#endif
     4104              }
     4105
     4106          if (total_len)
     4107            {
     4108              /* prepare the variable buffer dude wrt to the output size and
     4109                 pass along the strings.  */
     4110
     4111              o = variable_buffer_output (o + total_len, "", 0) - total_len; /* a hack */
     4112
     4113              for (d = deps; d; d = d->next)
     4114                if (d->ignore_mtime)
     4115                  {
     4116                    unsigned int len;
     4117                    const char *c = dep_name (d);
     4118
     4119#ifndef NO_ARCHIVES
     4120                    if (ar_name (c))
     4121                      {
     4122                        c = strchr (c, '(') + 1;
     4123                        len = strlen (c);
     4124                      }
     4125                    else
     4126#elif defined (CONFIG_WITH_STRCACHE2)
     4127                      len = strcache2_get_len (&file_strcache, c) + 1;
     4128#else
     4129                      len = strlen (c) + 1;
     4130#endif
     4131                    o = variable_buffer_output (o, c, len);
     4132                    o[-1] = FILE_LIST_SEPARATOR;
     4133                  }
     4134
     4135                --o;        /* nuke the last list separator */
     4136                *o = '\0';
     4137            }
     4138        }
     4139      else
     4140        {
     4141          /* Dependency given by index.  */
     4142
     4143          for (d = deps; d; d = d->next)
     4144            if (d->ignore_mtime)
     4145              {
     4146                if (--idx == 0) /* 1 based indexing */
     4147                  {
     4148                    unsigned int len;
     4149                    const char *c = dep_name (d);
     4150
     4151#ifndef NO_ARCHIVES
     4152                    if (ar_name (c))
     4153                      {
     4154                        c = strchr (c, '(') + 1;
     4155                        len = strlen (c) - 1;
     4156                      }
     4157                    else
     4158#elif defined (CONFIG_WITH_STRCACHE2)
     4159                      len = strcache2_get_len (&file_strcache, c);
     4160#else
     4161                      len = strlen (c);
     4162#endif
     4163                    o = variable_buffer_output (o, c, len);
     4164                    break;
     4165                  }
     4166              }
     4167        }
     4168    }
     4169
     4170  return o;
     4171}
     4172#endif /* CONFIG_WITH_LAZY_DEPS_VARS */
     4173
     4174
     4175
     4176#ifdef CONFIG_WITH_DEFINED
     4177/* Similar to ifdef. */
     4178static char *
     4179func_defined (char *o, char **argv, const char *funcname UNUSED)
     4180{
     4181  struct variable *v = lookup_variable (argv[0], strlen (argv[0]));
     4182  int result = v != NULL && *v->value != '\0';
     4183  o = variable_buffer_output (o,  result ? "1" : "", result);
     4184  return o;
     4185}
     4186#endif /* CONFIG_WITH_DEFINED*/
    39424187
    39434188#ifdef CONFIG_WITH_TOUPPER_TOLOWER
     
    39744219      {
    39754220        const char ch = *s;
    3976         if (!isblank (ch)
     4221        if (!ISBLANK (ch)
    39774222         && ch != '@'
    39784223#ifdef CONFIG_WITH_COMMANDS_FUNC
     
    40444289              {
    40454290                /* strip */
    4046                 while (s1 < e1 && isblank (*s1))
     4291                while (s1 < e1 && ISBLANK (*s1))
    40474292                  s1++;
    4048                 while (s2 < e2 && isblank (*s2))
     4293                while (s2 < e2 && ISBLANK (*s2))
    40494294                  s2++;
    40504295                if (s1 >= e1 || s2 >= e2)
     
    40734318        if (s1 < e1 || s2 < e2)
    40744319          {
    4075             while (s1 < e1 && (isblank (*s1) || *s1 == '\n'))
     4320            while (s1 < e1 && (ISBLANK (*s1) || *s1 == '\n'))
    40764321              if (*s1++ == '\n')
    40774322                s1 = comp_cmds_strip_leading (s1, e1);
    4078             while (s2 < e2 && (isblank (*s2) || *s2 == '\n'))
     4323            while (s2 < e2 && (ISBLANK (*s2) || *s2 == '\n'))
    40794324              if (*s2++ == '\n')
    40804325                s2 = comp_cmds_strip_leading (s2, e2);
     
    41324377    s1 = var1->value;
    41334378    e1 = s1 + var1->value_length;
    4134     while (isblank ((unsigned char) *s1))
     4379    while (ISBLANK (*s1))
    41354380      s1++;
    4136     while (e1 > s1 && isblank ((unsigned char) e1[-1]))
     4381    while (e1 > s1 && ISBLANK (e1[-1]))
    41374382      e1--;
    41384383
    41394384    s2 = var2->value;
    41404385    e2 = s2 + var2->value_length;
    4141     while (isblank ((unsigned char) *s2))
     4386    while (ISBLANK (*s2))
    41424387      s2++;
    4143     while (e2 > s2 && isblank ((unsigned char) e2[-1]))
     4388    while (e2 > s2 && ISBLANK (e2[-1]))
    41444389      e2--;
    41454390
     
    41544399  s1 = var1->value;
    41554400  e1 = s1 + var1->value_length;
    4156   while (isblank ((unsigned char) *s1))
     4401  while (ISBLANK (*s1))
    41574402    s1++;
    4158   while (e1 > s1 && isblank ((unsigned char) e1[-1]))
     4403  while (e1 > s1 && ISBLANK (e1[-1]))
    41594404    e1--;
    41604405
    41614406  s2 = var2->value;
    41624407  e2 = s2 + var2->value_length;
    4163   while (isblank((unsigned char)*s2))
     4408  while (ISBLANK (*s2))
    41644409    s2++;
    4165   while (e2 > s2 && isblank ((unsigned char) e2[-1]))
     4410  while (e2 > s2 && ISBLANK (e2[-1]))
    41664411    e2--;
    41674412
     
    41944439      s1 = a1 = allocated_variable_expand ((char *)s1 + l);
    41954440      if (!l)
    4196         while (isblank ((unsigned char) *s1))
     4441        while (ISBLANK (*s1))
    41974442          s1++;
    41984443      e1 = strchr (s1, '\0');
    4199       while (e1 > s1 && isblank ((unsigned char) e1[-1]))
     4444      while (e1 > s1 && ISBLANK (e1[-1]))
    42004445        e1--;
    42014446    }
     
    42074452      s2 = a2 = allocated_variable_expand ((char *)s2 + l);
    42084453      if (!l)
    4209         while (isblank ((unsigned char) *s2))
     4454        while (ISBLANK (*s2))
    42104455          s2++;
    42114456      e2 = strchr (s2, '\0');
    4212       while (e2 > s2 && isblank ((unsigned char) e2[-1]))
     4457      while (e2 > s2 && ISBLANK (e2[-1]))
    42134458        e2--;
    42144459    }
     
    42834528  if (!s)
    42844529    return 1;
    4285   while (isspace ((unsigned char)*s))
     4530  while (ISSPACE (*s))
    42864531    s++;
    42874532  return *s == '\0';
     
    43184563      if (!p || *p != '\0')
    43194564        {
    4320           error (NILF, _("$(%s): strptime(%s,%s,) -> %s\n"), funcname,
     4565          OSSSS (error, NILF, _("$(%s): strptime(%s,%s,) -> %s\n"), funcname,
    43214566                 argv[1], input_format, p ? p : "<null>");
    43224567          return variable_buffer_output (o, "", 0);
     
    45604805
    45614806      if (argv[i + 1] == NULL)
    4562         fatal (NILF, _("$(select ): not an even argument count\n"));
    4563 
    4564       while (isspace ((unsigned char)*cond))
     4807        O (fatal, NILF, _("$(select ): not an even argument count\n"));
     4808
     4809      while (ISSPACE (*cond))
    45654810        cond++;
    45664811      if (   (*cond == 'o' && strncmp (cond, "otherwise", 9) == 0)
     
    45684813        {
    45694814          const char *end = cond + (*cond == 'o' ? 9 : 7);
    4570           while (isspace ((unsigned char)*end))
     4815          while (ISSPACE (*end))
    45714816            end++;
    45724817          if (*end == ':')
    45734818            do end++;
    4574             while (isspace ((unsigned char)*end));
     4819            while (ISSPACE (*end));
    45754820          is_otherwise = *end == '\0';
    45764821        }
     
    46484893            {
    46494894              *lastitem = '\0';
    4650               while (lastitem > stack_var->value && isspace (lastitem[-1]))
     4895              while (lastitem > stack_var->value && ISSPACE (lastitem[-1]))
    46514896                *--lastitem = '\0';
    46524897#ifdef CONFIG_WITH_VALUE_LENGTH
     
    47144959
    47154960  /* strip spaces */
    4716   while (isspace (*str))
     4961  while (ISSPACE (*str))
    47174962    str++;
    47184963  if (!*str)
    47194964    {
    4720       error (NILF, _("bad number: empty\n"));
     4965      O (error, NILF, _("bad number: empty\n"));
    47214966      return 0;
    47224967    }
     
    47244969
    47254970  /* check for +/- */
    4726   while (*str == '+' || *str == '-' || isspace (*str))
     4971  while (*str == '+' || *str == '-' || ISSPACE (*str))
    47274972      if (*str++ == '-')
    47284973        negative = !negative;
     
    47524997      ||  !(base == 16 ? isxdigit (*str) : isdigit (*str)) )
    47534998    {
    4754       error (NILF, _("bad number: '%s'\n"), start);
     4999      OS (error, NILF, _("bad number: '%s'\n"), start);
    47555000      return 0;
    47565001    }
    47575002
    47585003  /* convert it! */
    4759   while (*str && !isspace (*str))
     5004  while (*str && !ISSPACE (*str))
    47605005    {
    47615006      int ch = *str++;
     
    47685013      else
    47695014        {
    4770           error (NILF, _("bad number: '%s' (base=%u, pos=%lu)\n"), start, base, (unsigned long)(str - start));
     5015          OSNN (error, NILF, _("bad number: '%s' (base=%u, pos=%lu)\n"), start, base, (unsigned long)(str - start));
    47715016          return 0;
    47725017        }
     
    47765021
    47775022  /* check trailing spaces. */
    4778   while (isspace (*str))
     5023  while (ISSPACE (*str))
    47795024    str++;
    47805025  if (*str)
    47815026    {
    4782       error (NILF, _("bad number: '%s'\n"), start);
     5027      OS (error, NILF, _("bad number: '%s'\n"), start);
    47835028      return 0;
    47845029    }
     
    48435088      if (!divisor)
    48445089        {
    4845           error (NILF, _("divide by zero ('%s')\n"), argv[i]);
     5090          OS (error, NILF, _("divide by zero ('%s')\n"), argv[i]);
    48465091          return math_int_to_variable_buffer (o, 0);
    48475092        }
     
    48645109  if (!divisor)
    48655110    {
    4866       error (NILF, _("divide by zero ('%s')\n"), argv[1]);
     5111      OS (error, NILF, _("divide by zero ('%s')\n"), argv[1]);
    48675112      return math_int_to_variable_buffer (o, 0);
    48685113    }
     
    49975242  else
    49985243    {
    4999       error (NILF, _("$(libpath): unknown variable `%s'"), argv[0]);
     5244      OS (error, NILF, _("$(libpath): unknown variable `%s'"), argv[0]);
    50005245      return variable_buffer_output (o, "", 0);
    50015246    }
     
    50135258      if (rc != NO_ERROR)
    50145259        {
    5015           error (NILF, _("$(libpath): failed to query `%s', rc=%d"), argv[0], rc);
     5260          OSN (error, NILF, _("$(libpath): failed to query `%s', rc=%d"), argv[0], rc);
    50165261          return variable_buffer_output (o, "", 0);
    50175262        }
     
    50285273      if (fVar == 0)
    50295274        {
    5030           error (NILF, _("$(libpath): LIBPATH is read-only"));
     5275          O (error, NILF, _("$(libpath): LIBPATH is read-only"));
    50315276          return variable_buffer_output (o, "", 0);
    50325277        }
     
    50345279      /* strip leading and trailing spaces and check for max length. */
    50355280      val = argv[1];
    5036       while (isspace (*val))
     5281      while (ISSPACE (*val))
    50375282        val++;
    50385283      end = strchr (val, '\0');
    5039       while (end > val && isspace (end[-1]))
     5284      while (end > val && ISSPACE (end[-1]))
    50405285        end--;
    50415286
     
    50435288      if (len >= len_max)
    50445289        {
    5045           error (NILF, _("$(libpath): The new `%s' value is too long (%d bytes, max %d)"),
    5046                  argv[0], len, len_max);
     5290          OSNN (error,  NILF, _("$(libpath): The new `%s' value is too long (%d bytes, max %d)"),
     5291                argv[0], len, len_max);
    50475292          return variable_buffer_output (o, "", 0);
    50485293        }
     
    50545299      if (rc != NO_ERROR)
    50555300        {
    5056           error (NILF, _("$(libpath): failed to set `%s' to `%s', rc=%d"), argv[0], buf, rc);
     5301          OSSN (error, (NILF, _("$(libpath): failed to set `%s' to `%s', rc=%d"), argv[0], buf, rc);
    50575302          return variable_buffer_output (o, "", 0);
    50585303        }
     
    51495394  if (recursive)
    51505395    {
    5151       error (reading_file, _("$(%s ) was invoked recursivly"), funcname);
     5396      OS (error, reading_file, _("$(%s ) was invoked recursivly"), funcname);
    51525397      return variable_buffer_output (o, "recursive", sizeof ("recursive") - 1);
    51535398    }
    51545399  if (*argv[0] == '\0')
    51555400    {
    5156       error (reading_file, _("$(%s ) was invoked with an empty target name"), funcname);
     5401      OS (error, reading_file, _("$(%s ) was invoked with an empty target name"), funcname);
    51575402      return o;
    51585403    }
     
    51965441            continue;
    51975442          p = cmds->command_lines[i];
    5198           while (isblank ((unsigned char)*p))
     5443          while (ISBLANK (*p))
    51995444            p++;
    52005445          if (*p == '\0')
     
    52715516                                 already been written to the output.  */
    52725517                              while (out > ref
    5273                                      && isblank ((unsigned char)out[-1]))
     5518                                     && ISBLANK (out[-1]))
    52745519                                --out;
    52755520
     
    52905535                 dep expansion happens, so it would have to be on a hackish basis. sad... */
    52915536              else if (*ref == '<' || *ref == '*' || *ref == '%' || *ref == '^' || *ref == '+')
    5292                 error (reading_file, _("$(%s ) does not work reliably with $%c in all cases"), funcname, *ref);
     5537                OSN (error, reading_file, _("$(%s ) does not work reliably with $%c in all cases"), funcname, *ref);
    52935538            }
    52945539
     
    53075552          /* Skip it if it has a '%' prefix or is blank. */
    53085553          p = o;
    5309           while (isblank ((unsigned char)*o)
     5554          while (ISBLANK (*o)
    53105555              || *o == '@'
    53115556              || *o == '-'
     
    53705615            symbolic = 1;
    53715616          else
    5372             error (reading_file, _("$(%s ) invalid argument `%s'"),
    5373                    funcname, argv[0]);
     5617            OSS (error, reading_file, _("$(%s ) invalid argument `%s'"),
     5618                 funcname, argv[0]);
    53745619        }
    53755620    }
     
    54245669  /* Figure what kind of input this is. */
    54255670  psz = argv[0];
    5426   while (isblank ((unsigned char)*psz))
     5671  while (ISBLANK (*psz))
    54275672    psz++;
    54285673
     
    54355680          if (*psz < '0' || *psz >= '8')
    54365681            {
    5437               error (reading_file, _("$(%s ) illegal number `%s'"), funcname, argv[0]);
     5682              OSS (error, reading_file, _("$(%s ) illegal number `%s'"), funcname, argv[0]);
    54385683              break;
    54395684            }
     
    54435688
    54445689      if (argv[1] != NULL)
    5445           error (reading_file, _("$(%s ) too many arguments for octal mode"), funcname);
     5690          OS (error, reading_file, _("$(%s ) too many arguments for octal mode"), funcname);
    54465691  }
    54475692  else
     
    54495694      u = umask(0);
    54505695      umask(u);
    5451       error (reading_file, _("$(%s ) symbol mode is not implemented"), funcname);
     5696      OS (error, reading_file, _("$(%s ) symbol mode is not implemented"), funcname);
    54525697  }
    54535698
     
    54655710# ifdef KBUILD_OS_WINDOWS
    54665711  const char *cmd = argv[0];
    5467   while (isblank ((unsigned char)*cmd))
     5712  while (ISBLANK (*cmd))
    54685713    cmd++;
    54695714  if (strcmp (cmd, "invalidate") == 0)
    54705715    {
    54715716      if (argv[1] != NULL)
    5472         error (reading_file, "$(dircache-ctl invalidate) takes no parameters");
     5717        O (error, reading_file, "$(dircache-ctl invalidate) takes no parameters");
    54735718      dir_cache_invalid_all ();
    54745719    }
     
    54765721    {
    54775722      if (argv[1] != NULL)
    5478         error (reading_file, "$(dircache-ctl invalidate-missing) takes no parameters");
     5723        O (error, reading_file, "$(dircache-ctl invalidate-missing) takes no parameters");
    54795724      dir_cache_invalid_missing ();
    54805725    }
     
    54855730        {
    54865731          const char *dir = argv[i];
    5487           while (isblank ((unsigned char)*dir))
     5732          while (ISBLANK (*dir))
    54885733            dir++;
    54895734          if (*dir)
     
    54975742        {
    54985743          const char *dir = argv[i];
    5499           while (isblank ((unsigned char)*dir))
     5744          while (ISBLANK (*dir))
    55005745            dir++;
    55015746          if (*dir)
     
    55045749    }
    55055750  else
    5506     error (reading_file, "Unknown $(dircache-ctl ) command: '%s'", cmd);
     5751    OS (error, reading_file, "Unknown $(dircache-ctl ) command: '%s'", cmd);
    55075752# endif
    55085753  return o;
     
    55265771static char *func_call (char *o, char **argv, const char *funcname);
    55275772
     5773#define FT_ENTRY(_name, _min, _max, _exp, _func) \
     5774  { { (_func) }, STRING_SIZE_TUPLE(_name), (_min), (_max), (_exp), 0 }
    55285775
    55295776static struct function_table_entry function_table_init[] =
    55305777{
    5531  /* Name/size */                    /* MIN MAX EXP? Function */
    5532   { STRING_SIZE_TUPLE("abspath"),       0,  1,  1,  func_abspath},
    5533   { STRING_SIZE_TUPLE("addprefix"),     2,  2,  1,  func_addsuffix_addprefix},
    5534   { STRING_SIZE_TUPLE("addsuffix"),     2,  2,  1,  func_addsuffix_addprefix},
    5535   { STRING_SIZE_TUPLE("basename"),      0,  1,  1,  func_basename_dir},
    5536   { STRING_SIZE_TUPLE("dir"),           0,  1,  1,  func_basename_dir},
    5537   { STRING_SIZE_TUPLE("notdir"),        0,  1,  1,  func_notdir_suffix},
     5778 /*         Name            MIN MAX EXP? Function */
     5779  FT_ENTRY ("abspath",       0,  1,  1,  func_abspath),
     5780  FT_ENTRY ("addprefix",     2,  2,  1,  func_addsuffix_addprefix),
     5781  FT_ENTRY ("addsuffix",     2,  2,  1,  func_addsuffix_addprefix),
     5782  FT_ENTRY ("basename",      0,  1,  1,  func_basename_dir),
     5783  FT_ENTRY ("dir",           0,  1,  1,  func_basename_dir),
     5784  FT_ENTRY ("notdir",        0,  1,  1,  func_notdir_suffix),
    55385785#ifdef CONFIG_WITH_ROOT_FUNC
    5539   { STRING_SIZE_TUPLE("root"),          0,  1,  1,  func_root},
    5540   { STRING_SIZE_TUPLE("notroot"),       0,  1,  1,  func_notroot},
    5541 #endif
    5542   { STRING_SIZE_TUPLE("subst"),         3,  3,  1,  func_subst},
    5543   { STRING_SIZE_TUPLE("suffix"),        0,  1,  1,  func_notdir_suffix},
    5544   { STRING_SIZE_TUPLE("filter"),        2,  2,  1,  func_filter_filterout},
    5545   { STRING_SIZE_TUPLE("filter-out"),    2,  2,  1,  func_filter_filterout},
    5546   { STRING_SIZE_TUPLE("findstring"),    2,  2,  1,  func_findstring},
     5786  FT_ENTRY ("root",          0,  1,  1,  func_root),
     5787  FT_ENTRY ("notroot",       0,  1,  1,  func_notroot),
     5788#endif
     5789  FT_ENTRY ("subst",         3,  3,  1,  func_subst),
     5790  FT_ENTRY ("suffix",        0,  1,  1,  func_notdir_suffix),
     5791  FT_ENTRY ("filter",        2,  2,  1,  func_filter_filterout),
     5792  FT_ENTRY ("filter-out",    2,  2,  1,  func_filter_filterout),
     5793  FT_ENTRY ("findstring",    2,  2,  1,  func_findstring),
    55475794#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
    5548   { STRING_SIZE_TUPLE("firstdefined"),  0,  2,  1,  func_firstdefined},
    5549 #endif
    5550   { STRING_SIZE_TUPLE("firstword"),     0,  1,  1,  func_firstword},
    5551   { STRING_SIZE_TUPLE("flavor"),        0,  1,  1,  func_flavor},
    5552   { STRING_SIZE_TUPLE("join"),          2,  2,  1,  func_join},
     5795  FT_ENTRY ("firstdefined",  0,  2,  1,  func_firstdefined),
     5796#endif
     5797  FT_ENTRY ("firstword",     0,  1,  1,  func_firstword),
     5798  FT_ENTRY ("flavor",        0,  1,  1,  func_flavor),
     5799  FT_ENTRY ("join",          2,  2,  1,  func_join),
    55535800#ifdef CONFIG_WITH_DEFINED_FUNCTIONS
    5554   { STRING_SIZE_TUPLE("lastdefined"),   0,  2,  1,  func_lastdefined},
    5555 #endif
    5556   { STRING_SIZE_TUPLE("lastword"),      0,  1,  1,  func_lastword},
    5557   { STRING_SIZE_TUPLE("patsubst"),      3,  3,  1,  func_patsubst},
    5558   { STRING_SIZE_TUPLE("realpath"),      0,  1,  1,  func_realpath},
     5801  FT_ENTRY ("lastdefined",   0,  2,  1,  func_lastdefined),
     5802#endif
     5803  FT_ENTRY ("lastword",      0,  1,  1,  func_lastword),
     5804  FT_ENTRY ("patsubst",      3,  3,  1,  func_patsubst),
     5805  FT_ENTRY ("realpath",      0,  1,  1,  func_realpath),
    55595806#ifdef CONFIG_WITH_RSORT
    5560   { STRING_SIZE_TUPLE("rsort"),         0,  1,  1,  func_sort},
    5561 #endif
    5562   { STRING_SIZE_TUPLE("shell"),         0,  1,  1,  func_shell},
    5563   { STRING_SIZE_TUPLE("sort"),          0,  1,  1,  func_sort},
    5564   { STRING_SIZE_TUPLE("strip"),         0,  1,  1,  func_strip},
     5807  FT_ENTRY ("rsort",         0,  1,  1,  func_sort),
     5808#endif
     5809  FT_ENTRY ("shell",         0,  1,  1,  func_shell),
     5810  FT_ENTRY ("sort",          0,  1,  1,  func_sort),
     5811  FT_ENTRY ("strip",         0,  1,  1,  func_strip),
    55655812#ifdef CONFIG_WITH_WHERE_FUNCTION
    5566   { STRING_SIZE_TUPLE("where"),         0,  1,  1,  func_where},
    5567 #endif
    5568   { STRING_SIZE_TUPLE("wildcard"),      0,  1,  1,  func_wildcard},
    5569   { STRING_SIZE_TUPLE("word"),          2,  2,  1,  func_word},
    5570   { STRING_SIZE_TUPLE("wordlist"),      3,  3,  1,  func_wordlist},
    5571   { STRING_SIZE_TUPLE("words"),         0,  1,  1,  func_words},
    5572   { STRING_SIZE_TUPLE("origin"),        0,  1,  1,  func_origin},
    5573   { STRING_SIZE_TUPLE("foreach"),       3,  3,  0,  func_foreach},
     5813  FT_ENTRY ("where",         0,  1,  1,  func_where),
     5814#endif
     5815  FT_ENTRY ("wildcard",      0,  1,  1,  func_wildcard),
     5816  FT_ENTRY ("word",          2,  2,  1,  func_word),
     5817  FT_ENTRY ("wordlist",      3,  3,  1,  func_wordlist),
     5818  FT_ENTRY ("words",         0,  1,  1,  func_words),
     5819  FT_ENTRY ("origin",        0,  1,  1,  func_origin),
     5820  FT_ENTRY ("foreach",       3,  3,  0,  func_foreach),
    55745821#ifdef CONFIG_WITH_LOOP_FUNCTIONS
    5575   { STRING_SIZE_TUPLE("for"),           4,  4,  0,  func_for},
    5576   { STRING_SIZE_TUPLE("while"),         2,  2,  0,  func_while},
    5577 #endif
    5578   { STRING_SIZE_TUPLE("call"),          1,  0,  1,  func_call},
    5579   { STRING_SIZE_TUPLE("info"),          0,  1,  1,  func_error},
    5580   { STRING_SIZE_TUPLE("error"),         0,  1,  1,  func_error},
    5581   { STRING_SIZE_TUPLE("warning"),       0,  1,  1,  func_error},
    5582   { STRING_SIZE_TUPLE("if"),            2,  3,  0,  func_if},
    5583   { STRING_SIZE_TUPLE("or"),            1,  0,  0,  func_or},
    5584   { STRING_SIZE_TUPLE("and"),           1,  0,  0,  func_and},
    5585   { STRING_SIZE_TUPLE("value"),         0,  1,  1,  func_value},
    5586   { STRING_SIZE_TUPLE("eval"),          0,  1,  1,  func_eval},
     5822  FT_ENTRY ("for",           4,  4,  0,  func_for),
     5823  FT_ENTRY ("while",         2,  2,  0,  func_while),
     5824#endif
     5825  FT_ENTRY ("call",          1,  0,  1,  func_call),
     5826  FT_ENTRY ("info",          0,  1,  1,  func_error),
     5827  FT_ENTRY ("error",         0,  1,  1,  func_error),
     5828  FT_ENTRY ("warning",       0,  1,  1,  func_error),
     5829  FT_ENTRY ("if",            2,  3,  0,  func_if),
     5830  FT_ENTRY ("or",            1,  0,  0,  func_or),
     5831  FT_ENTRY ("and",           1,  0,  0,  func_and),
     5832  FT_ENTRY ("value",         0,  1,  1,  func_value),
     5833#ifdef EXPERIMENTAL
     5834  FT_ENTRY ("eq",            2,  2,  1,  func_eq),
     5835  FT_ENTRY ("not",           0,  1,  1,  func_not),
     5836#endif
     5837  FT_ENTRY ("eval",          0,  1,  1,  func_eval),
    55875838#ifdef CONFIG_WITH_EVALPLUS
    5588   { STRING_SIZE_TUPLE("evalctx"),       0,  1,  1,  func_evalctx},
    5589   { STRING_SIZE_TUPLE("evalval"),       1,  1,  1,  func_evalval},
    5590   { STRING_SIZE_TUPLE("evalvalctx"),    1,  1,  1,  func_evalval},
    5591   { STRING_SIZE_TUPLE("evalcall"),      1,  0,  1,  func_call},
    5592   { STRING_SIZE_TUPLE("evalcall2"),     1,  0,  1,  func_call},
    5593   { STRING_SIZE_TUPLE("eval-opt-var"),  1,  0,  1,  func_eval_optimize_variable},
    5594 #endif
    5595 #ifdef EXPERIMENTAL
    5596   { STRING_SIZE_TUPLE("eq"),            2,  2,  1,  func_eq},
    5597   { STRING_SIZE_TUPLE("not"),           0,  1,  1,  func_not},
    5598 #endif
     5839  FT_ENTRY ("evalctx",       0,  1,  1,  func_evalctx),
     5840  FT_ENTRY ("evalval",       1,  1,  1,  func_evalval),
     5841  FT_ENTRY ("evalvalctx",    1,  1,  1,  func_evalval),
     5842  FT_ENTRY ("evalcall",      1,  0,  1,  func_call),
     5843  FT_ENTRY ("evalcall2",     1,  0,  1,  func_call),
     5844  FT_ENTRY ("eval-opt-var",  1,  0,  1,  func_eval_optimize_variable),
     5845#endif
     5846  FT_ENTRY ("file",          1,  2,  1,  func_file),
    55995847#ifdef CONFIG_WITH_STRING_FUNCTIONS
    5600   { STRING_SIZE_TUPLE("length"),        1,  1,  1,  func_length},
    5601   { STRING_SIZE_TUPLE("length-var"),    1,  1,  1,  func_length_var},
    5602   { STRING_SIZE_TUPLE("insert"),        2,  5,  1,  func_insert},
    5603   { STRING_SIZE_TUPLE("pos"),           2,  3,  1,  func_pos},
    5604   { STRING_SIZE_TUPLE("lastpos"),       2,  3,  1,  func_pos},
    5605   { STRING_SIZE_TUPLE("substr"),        2,  4,  1,  func_substr},
    5606   { STRING_SIZE_TUPLE("translate"),     2,  4,  1,  func_translate},
     5848  FT_ENTRY ("length",        1,  1,  1,  func_length),
     5849  FT_ENTRY ("length-var",    1,  1,  1,  func_length_var),
     5850  FT_ENTRY ("insert",        2,  5,  1,  func_insert),
     5851  FT_ENTRY ("pos",           2,  3,  1,  func_pos),
     5852  FT_ENTRY ("lastpos",       2,  3,  1,  func_pos),
     5853  FT_ENTRY ("substr",        2,  4,  1,  func_substr),
     5854  FT_ENTRY ("translate",     2,  4,  1,  func_translate),
    56075855#endif
    56085856#ifdef CONFIG_WITH_PRINTF
    5609   { STRING_SIZE_TUPLE("printf"),        1,  0,  1,  kmk_builtin_func_printf},
     5857  FT_ENTRY ("printf",        1,  0,  1,  kmk_builtin_func_printf),
    56105858#endif
    56115859#ifdef CONFIG_WITH_LAZY_DEPS_VARS
    5612   { STRING_SIZE_TUPLE("deps"),          1,  2,  1,  func_deps},
    5613   { STRING_SIZE_TUPLE("deps-all"),      1,  2,  1,  func_deps},
    5614   { STRING_SIZE_TUPLE("deps-newer"),    1,  2,  1,  func_deps_newer},
    5615   { STRING_SIZE_TUPLE("deps-oo"),       1,  2,  1,  func_deps_order_only},
     5860  FT_ENTRY ("deps",          1,  2,  1,  func_deps),
     5861  FT_ENTRY ("deps-all",      1,  2,  1,  func_deps),
     5862  FT_ENTRY ("deps-newer",    1,  2,  1,  func_deps_newer),
     5863  FT_ENTRY ("deps-oo",       1,  2,  1,  func_deps_order_only),
    56165864#endif
    56175865#ifdef CONFIG_WITH_DEFINED
    5618   { STRING_SIZE_TUPLE("defined"),       1,  1,  1,  func_defined},
     5866  FT_ENTRY ("defined",       1,  1,  1,  func_defined),
    56195867#endif
    56205868#ifdef CONFIG_WITH_TOUPPER_TOLOWER
    5621   { STRING_SIZE_TUPLE("toupper"),       0,  1,  1,  func_toupper_tolower},
    5622   { STRING_SIZE_TUPLE("tolower"),       0,  1,  1,  func_toupper_tolower},
     5869  FT_ENTRY ("toupper",       0,  1,  1,  func_toupper_tolower),
     5870  FT_ENTRY ("tolower",       0,  1,  1,  func_toupper_tolower),
    56235871#endif
    56245872#ifdef CONFIG_WITH_ABSPATHEX
    5625   { STRING_SIZE_TUPLE("abspathex"),     0,  2,  1,  func_abspathex},
     5873  FT_ENTRY ("abspathex",     0,  2,  1,  func_abspathex),
    56265874#endif
    56275875#ifdef CONFIG_WITH_XARGS
    5628   { STRING_SIZE_TUPLE("xargs"),         2,  0,  1,  func_xargs},
     5876  FT_ENTRY ("xargs",         2,  0,  1,  func_xargs),
    56295877#endif
    56305878#if defined(CONFIG_WITH_VALUE_LENGTH) && defined(CONFIG_WITH_COMPARE)
    5631   { STRING_SIZE_TUPLE("comp-vars"),     3,  3,  1,  func_comp_vars},
    5632   { STRING_SIZE_TUPLE("comp-cmds"),     3,  3,  1,  func_comp_vars},
    5633   { STRING_SIZE_TUPLE("comp-cmds-ex"),  3,  3,  1,  func_comp_cmds_ex},
     5879  FT_ENTRY ("comp-vars",     3,  3,  1,  func_comp_vars),
     5880  FT_ENTRY ("comp-cmds",     3,  3,  1,  func_comp_vars),
     5881  FT_ENTRY ("comp-cmds-ex",  3,  3,  1,  func_comp_cmds_ex),
    56345882#endif
    56355883#ifdef CONFIG_WITH_DATE
    5636   { STRING_SIZE_TUPLE("date"),          0,  1,  1,  func_date},
    5637   { STRING_SIZE_TUPLE("date-utc"),      0,  3,  1,  func_date},
     5884  FT_ENTRY ("date",          0,  1,  1,  func_date),
     5885  FT_ENTRY ("date-utc",      0,  3,  1,  func_date),
    56385886#endif
    56395887#ifdef CONFIG_WITH_FILE_SIZE
    5640   { STRING_SIZE_TUPLE("file-size"),     1,  1,  1,  func_file_size},
     5888  FT_ENTRY ("file-size",     1,  1,  1,  func_file_size),
    56415889#endif
    56425890#ifdef CONFIG_WITH_WHICH
    5643   { STRING_SIZE_TUPLE("which"),         0,  0,  1,  func_which},
     5891  FT_ENTRY ("which",         0,  0,  1,  func_which),
    56445892#endif
    56455893#ifdef CONFIG_WITH_IF_CONDITIONALS
    5646   { STRING_SIZE_TUPLE("expr"),          1,  1,  0,  func_expr},
    5647   { STRING_SIZE_TUPLE("if-expr"),       2,  3,  0,  func_if_expr},
    5648   { STRING_SIZE_TUPLE("select"),        2,  0,  0,  func_select},
     5894  FT_ENTRY ("expr",          1,  1,  0,  func_expr),
     5895  FT_ENTRY ("if-expr",       2,  3,  0,  func_if_expr),
     5896  FT_ENTRY ("select",        2,  0,  0,  func_select),
    56495897#endif
    56505898#ifdef CONFIG_WITH_SET_CONDITIONALS
    5651   { STRING_SIZE_TUPLE("intersects"),    2,  2,  1,  func_set_intersects},
     5899  FT_ENTRY ("intersects",    2,  2,  1,  func_set_intersects),
    56525900#endif
    56535901#ifdef CONFIG_WITH_STACK
    5654   { STRING_SIZE_TUPLE("stack-push"),    2,  2,  1,  func_stack_push},
    5655   { STRING_SIZE_TUPLE("stack-pop"),     1,  1,  1,  func_stack_pop_top},
    5656   { STRING_SIZE_TUPLE("stack-popv"),    1,  1,  1,  func_stack_pop_top},
    5657   { STRING_SIZE_TUPLE("stack-top"),     1,  1,  1,  func_stack_pop_top},
     5902  FT_ENTRY ("stack-push",    2,  2,  1,  func_stack_push),
     5903  FT_ENTRY ("stack-pop",     1,  1,  1,  func_stack_pop_top),
     5904  FT_ENTRY ("stack-popv",    1,  1,  1,  func_stack_pop_top),
     5905  FT_ENTRY ("stack-top",     1,  1,  1,  func_stack_pop_top),
    56585906#endif
    56595907#ifdef CONFIG_WITH_MATH
    5660   { STRING_SIZE_TUPLE("int-add"),       2,  0,  1,  func_int_add},
    5661   { STRING_SIZE_TUPLE("int-sub"),       2,  0,  1,  func_int_sub},
    5662   { STRING_SIZE_TUPLE("int-mul"),       2,  0,  1,  func_int_mul},
    5663   { STRING_SIZE_TUPLE("int-div"),       2,  0,  1,  func_int_div},
    5664   { STRING_SIZE_TUPLE("int-mod"),       2,  2,  1,  func_int_mod},
    5665   { STRING_SIZE_TUPLE("int-not"),       1,  1,  1,  func_int_not},
    5666   { STRING_SIZE_TUPLE("int-and"),       2,  0,  1,  func_int_and},
    5667   { STRING_SIZE_TUPLE("int-or"),        2,  0,  1,  func_int_or},
    5668   { STRING_SIZE_TUPLE("int-xor"),       2,  0,  1,  func_int_xor},
    5669   { STRING_SIZE_TUPLE("int-eq"),        2,  2,  1,  func_int_cmp},
    5670   { STRING_SIZE_TUPLE("int-ne"),        2,  2,  1,  func_int_cmp},
    5671   { STRING_SIZE_TUPLE("int-gt"),        2,  2,  1,  func_int_cmp},
    5672   { STRING_SIZE_TUPLE("int-ge"),        2,  2,  1,  func_int_cmp},
    5673   { STRING_SIZE_TUPLE("int-lt"),        2,  2,  1,  func_int_cmp},
    5674   { STRING_SIZE_TUPLE("int-le"),        2,  2,  1,  func_int_cmp},
     5908  FT_ENTRY ("int-add",       2,  0,  1,  func_int_add),
     5909  FT_ENTRY ("int-sub",       2,  0,  1,  func_int_sub),
     5910  FT_ENTRY ("int-mul",       2,  0,  1,  func_int_mul),
     5911  FT_ENTRY ("int-div",       2,  0,  1,  func_int_div),
     5912  FT_ENTRY ("int-mod",       2,  2,  1,  func_int_mod),
     5913  FT_ENTRY ("int-not",       1,  1,  1,  func_int_not),
     5914  FT_ENTRY ("int-and",       2,  0,  1,  func_int_and),
     5915  FT_ENTRY ("int-or",        2,  0,  1,  func_int_or),
     5916  FT_ENTRY ("int-xor",       2,  0,  1,  func_int_xor),
     5917  FT_ENTRY ("int-eq",        2,  2,  1,  func_int_cmp),
     5918  FT_ENTRY ("int-ne",        2,  2,  1,  func_int_cmp),
     5919  FT_ENTRY ("int-gt",        2,  2,  1,  func_int_cmp),
     5920  FT_ENTRY ("int-ge",        2,  2,  1,  func_int_cmp),
     5921  FT_ENTRY ("int-lt",        2,  2,  1,  func_int_cmp),
     5922  FT_ENTRY ("int-le",        2,  2,  1,  func_int_cmp),
    56755923#endif
    56765924#ifdef CONFIG_WITH_NANOTS
    5677   { STRING_SIZE_TUPLE("nanots"),        0,  0,  0,  func_nanots},
     5925  FT_ENTRY ("nanots",        0,  0,  0,  func_nanots),
    56785926#endif
    56795927#ifdef CONFIG_WITH_OS2_LIBPATH
    5680   { STRING_SIZE_TUPLE("libpath"),       1,  2,  1,  func_os2_libpath},
     5928  FT_ENTRY ("libpath",       1,  2,  1,  func_os2_libpath),
    56815929#endif
    56825930#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
    5683   { STRING_SIZE_TUPLE("make-stats"),    0,  0,  0,  func_make_stats},
     5931  FT_ENTRY ("make-stats",    0,  0,  0,  func_make_stats),
    56845932#endif
    56855933#ifdef CONFIG_WITH_COMMANDS_FUNC
    5686   { STRING_SIZE_TUPLE("commands"),      1,  1,  1,  func_commands},
    5687   { STRING_SIZE_TUPLE("commands-sc"),   1,  1,  1,  func_commands},
    5688   { STRING_SIZE_TUPLE("commands-usr"),  2,  2,  1,  func_commands},
     5934  FT_ENTRY ("commands",      1,  1,  1,  func_commands),
     5935  FT_ENTRY ("commands-sc",   1,  1,  1,  func_commands),
     5936  FT_ENTRY ("commands-usr",  2,  2,  1,  func_commands),
    56895937#endif
    56905938#ifdef KMK_HELPERS
    5691   { STRING_SIZE_TUPLE("kb-src-tool"),   1,  1,  0,  func_kbuild_source_tool},
    5692   { STRING_SIZE_TUPLE("kb-obj-base"),   1,  1,  0,  func_kbuild_object_base},
    5693   { STRING_SIZE_TUPLE("kb-obj-suff"),   1,  1,  0,  func_kbuild_object_suffix},
    5694   { STRING_SIZE_TUPLE("kb-src-prop"),   3,  4,  0,  func_kbuild_source_prop},
    5695   { STRING_SIZE_TUPLE("kb-src-one"),    0,  1,  0,  func_kbuild_source_one},
    5696   { STRING_SIZE_TUPLE("kb-exp-tmpl"),   6,  6,  1,  func_kbuild_expand_template},
     5939  FT_ENTRY ("kb-src-tool",   1,  1,  0,  func_kbuild_source_tool),
     5940  FT_ENTRY ("kb-obj-base",   1,  1,  0,  func_kbuild_object_base),
     5941  FT_ENTRY ("kb-obj-suff",   1,  1,  0,  func_kbuild_object_suffix),
     5942  FT_ENTRY ("kb-src-prop",   3,  4,  0,  func_kbuild_source_prop),
     5943  FT_ENTRY ("kb-src-one",    0,  1,  0,  func_kbuild_source_one),
     5944  FT_ENTRY ("kb-exp-tmpl",   6,  6,  1,  func_kbuild_expand_template),
    56975945#endif
    56985946#ifdef KMK
    5699   { STRING_SIZE_TUPLE("dircache-ctl"),  1,  0,  1,  func_dircache_ctl},
    5700   { STRING_SIZE_TUPLE("breakpoint"),    0,  0,  0,  func_breakpoint},
    5701   { STRING_SIZE_TUPLE("set-umask"),     1,  3,  1,  func_set_umask},
    5702   { STRING_SIZE_TUPLE("get-umask"),     0,  0,  0,  func_get_umask},
     5947  FT_ENTRY ("dircache-ctl",  1,  0,  1,  func_dircache_ctl),
     5948  FT_ENTRY ("breakpoint",    0,  0,  0,  func_breakpoint),
     5949  FT_ENTRY ("set-umask",     1,  3,  1,  func_set_umask),
     5950  FT_ENTRY ("get-umask",     0,  0,  0,  func_get_umask),
    57035951#endif
    57045952};
     
    57145962                         const struct function_table_entry *entry_p)
    57155963{
     5964  char *p;
     5965
    57165966  if (argc < (int)entry_p->minimum_args)
    5717     fatal (*expanding_var,
    5718            _("insufficient number of arguments (%d) to function `%s'"),
     5967    fatal (*expanding_var, strlen (entry_p->name),
     5968           _("insufficient number of arguments (%d) to function '%s'"),
    57195969           argc, entry_p->name);
    57205970
    5721   /* I suppose technically some function could do something with no
    5722      arguments, but so far none do, so just test it for all functions here
     5971  /* I suppose technically some function could do something with no arguments,
     5972     but so far no internal ones do, so just test it for all functions here
    57235973     rather than in each one.  We can change it later if necessary.  */
    57245974
    5725   if (!argc)
     5975  if (!argc && !entry_p->alloc_fn)
    57265976    return o;
    57275977
    5728   if (!entry_p->func_ptr)
    5729     fatal (*expanding_var,
    5730            _("unimplemented on this platform: function `%s'"), entry_p->name);
    5731 
    5732   return entry_p->func_ptr (o, argv, entry_p->name);
     5978  if (!entry_p->fptr.func_ptr)
     5979    OS (fatal, *expanding_var,
     5980        _("unimplemented on this platform: function '%s'"), entry_p->name);
     5981
     5982  if (!entry_p->alloc_fn)
     5983    return entry_p->fptr.func_ptr (o, argv, entry_p->name);
     5984
     5985  /* This function allocates memory and returns it to us.
     5986     Write it to the variable buffer, then free it.  */
     5987
     5988  p = entry_p->fptr.alloc_func_ptr (entry_p->name, argc, argv);
     5989  if (p)
     5990    {
     5991      o = variable_buffer_output (o, p, strlen (p));
     5992      free (p);
     5993    }
     5994
     5995  return o;
    57335996}
    57345997
     
    57556018     whitespace after the name).  */
    57566019
    5757   beg = next_token (beg + entry_p->len);
     6020  beg += entry_p->len;
     6021  NEXT_TOKEN (beg);
    57586022
    57596023  /* Find the end of the function invocation, counting nested use of
     
    57716035
    57726036  if (count >= 0)
    5773     fatal (*expanding_var,
    5774            _("unterminated call to function `%s': missing `%c'"),
    5775            entry_p->name, closeparen);
     6037    fatal (*expanding_var, strlen (entry_p->name),
     6038           _("unterminated call to function '%s': missing '%c'"),
     6039           entry_p->name, closeparen);
    57766040
    57776041  *stringp = end;
     
    58396103    for (argvp=argv; *argvp != 0; ++argvp)
    58406104      free (*argvp);
    5841   if (abeg)
     6105  else
    58426106    free (abeg);
    58436107
     
    58966160  static int max_args = 0;
    58976161  char *fname;
    5898   char *cp;
    58996162  char *body;
    59006163  int flen;
     
    59076170  unsigned int len;
    59086171#endif
     6172#ifdef CONFIG_WITH_VALUE_LENGTH
     6173  char *fname_end;
     6174#endif
    59096175#if defined (CONFIG_WITH_EVALPLUS) || defined (CONFIG_WITH_VALUE_LENGTH)
    59106176  char num[11];
    59116177#endif
    59126178
    5913   /* There is no way to define a variable with a space in the name, so strip
    5914      leading and trailing whitespace as a favor to the user.  */
    5915   fname = argv[0];
    5916   while (*fname != '\0' && isspace ((unsigned char)*fname))
    5917     ++fname;
    5918 
    5919   cp = fname + strlen (fname) - 1;
    5920   while (cp > fname && isspace ((unsigned char)*cp))
    5921     --cp;
    5922   cp[1] = '\0';
     6179  /* Clean up the name of the variable to be invoked.  */
     6180  fname = next_token (argv[0]);
     6181#ifndef CONFIG_WITH_VALUE_LENGTH
     6182  end_of_token (fname)[0] = '\0';
     6183#else
     6184  fname_end = end_of_token (fname);
     6185  *fname_end = '\0';
     6186#endif
    59236187
    59246188  /* Calling nothing is a no-op */
     6189#ifndef CONFIG_WITH_VALUE_LENGTH
    59256190  if (*fname == '\0')
     6191#else
     6192  if (fname == fname_end)
     6193#endif
    59266194    return o;
    59276195
     
    59316199  entry_p = lookup_function (fname);
    59326200#else
    5933   entry_p = lookup_function (fname, cp - fname + 1);
     6201  entry_p = lookup_function (fname, fname_end - fname);
    59346202#endif
    59356203  if (entry_p)
     
    60256293  else
    60266294    {
    6027       const struct floc *reading_file_saved = reading_file;
     6295      const floc *reading_file_saved = reading_file;
    60286296      char *eos;
    60296297
     
    60496317
    60506318      install_variable_buffer (&buf, &len);
    6051       eval_buffer (o, eos);
     6319      eval_buffer (o, NULL, eos);
    60526320      restore_variable_buffer (buf, len);
    60536321      reading_file = reading_file_saved;
     
    60796347
    60806348void
     6349define_new_function (const floc *flocp, const char *name,
     6350                     unsigned int min, unsigned int max, unsigned int flags,
     6351                     gmk_func_ptr func)
     6352{
     6353  const char *e = name;
     6354  struct function_table_entry *ent;
     6355  size_t len;
     6356
     6357  while (STOP_SET (*e, MAP_USERFUNC))
     6358    e++;
     6359  len = e - name;
     6360
     6361  if (len == 0)
     6362    O (fatal, flocp, _("Empty function name"));
     6363  if (*name == '.' || *e != '\0')
     6364    OS (fatal, flocp, _("Invalid function name: %s"), name);
     6365  if (len > 255)
     6366    OS (fatal, flocp, _("Function name too long: %s"), name);
     6367  if (min > 255)
     6368    ONS (fatal, flocp,
     6369         _("Invalid minimum argument count (%u) for function %s"), min, name);
     6370  if (max > 255 || (max && max < min))
     6371    ONS (fatal, flocp,
     6372         _("Invalid maximum argument count (%u) for function %s"), max, name);
     6373
     6374  ent = xmalloc (sizeof (struct function_table_entry));
     6375  ent->name = name;
     6376  ent->len = len;
     6377  ent->minimum_args = min;
     6378  ent->maximum_args = max;
     6379  ent->expand_args = ANY_SET(flags, GMK_FUNC_NOEXPAND) ? 0 : 1;
     6380  ent->alloc_fn = 1;
     6381  ent->fptr.alloc_func_ptr = func;
     6382
     6383  hash_insert (&function_table, ent);
     6384}
     6385
     6386void
    60816387hash_init_function_table (void)
    60826388{
    60836389  hash_init (&function_table, FUNCTION_TABLE_ENTRIES * 2,
    6084              function_table_entry_hash_1, function_table_entry_hash_2,
    6085              function_table_entry_hash_cmp);
     6390             function_table_entry_hash_1, function_table_entry_hash_2,
     6391             function_table_entry_hash_cmp);
    60866392  hash_load (&function_table, function_table_init,
    6087              FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
     6393             FUNCTION_TABLE_ENTRIES, sizeof (struct function_table_entry));
    60886394#if defined (CONFIG_WITH_OPTIMIZATION_HACKS) || defined (CONFIG_WITH_VALUE_LENGTH)
    60896395  {
  • trunk/src/kmk/getloadavg.c

    r2591 r3140  
    11/* Get the system load averages.
    2 Copyright (C) 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994,
    3 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
    4 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1985-2016 Free Software Foundation, Inc.
    53
    64GNU Make is free software; you can redistribute it and/or modify it under the
     
    8785
    8886/* Exclude all the code except the test program at the end
    89    if the system has its own `getloadavg' function.
    90 
    91    The declaration of `errno' is needed by the test program
     87   if the system has its own 'getloadavg' function.
     88
     89   The declaration of 'errno' is needed by the test program
    9290   as well as the function itself, so it comes first.  */
    9391
     
    748746  /* This call can return -1 for an error, but with good args
    749747     it's not supposed to fail.  The first argument is for no
    750      apparent reason of type `long int *'.  */
     748     apparent reason of type 'long int *'.  */
    751749  dg_sys_info ((long int *) &load_info,
    752750               DG_SYS_INFO_LOAD_INFO_TYPE,
     
    991989
    992990#ifdef TEST
    993 #include "make.h"
     991#include "makeint.h"
    994992
    995993int
  • trunk/src/kmk/getopt.c

    r2591 r3140  
    44before changing it!
    55
    6 Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
    7 1997, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    8 2010 Free Software Foundation, Inc.
     6Copyright (C) 1987-2016 Free Software Foundation, Inc.
    97
    108NOTE: The canonical source of this file is maintained with the GNU C Library.
     
    8482
    8583
    86 /* This version of `getopt' appears to the caller like standard Unix `getopt'
     84/* This version of `getopt' appears to the caller like standard Unix 'getopt'
    8785   but it behaves differently for the user, since it allows the user
    8886   to intersperse the options with the other arguments.
     
    202200# endif
    203201
     202#ifndef KMK
    204203/* Avoid depending on library functions or files
    205204   whose names are inconsistent.  */
    206 
    207205#ifndef getenv
    208206extern char *getenv ();
    209207#endif
     208#endif /* !KMK */
    210209
    211210static char *
     
    662661        {
    663662          if (opterr)
    664             fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
     663            fprintf (stderr, _("%s: option '%s' is ambiguous\n"),
    665664                     argv[0], argv[optind]);
    666665          nextchar += strlen (nextchar);
     
    683682                {
    684683                  if (opterr)
    685                     {
    686                       if (argv[optind - 1][1] == '-')
    687                         /* --option */
    688                         fprintf (stderr,
    689                          _("%s: option `--%s' doesn't allow an argument\n"),
    690                          argv[0], pfound->name);
    691                       else
    692                         /* +option or -option */
    693                         fprintf (stderr,
    694                          _("%s: option `%c%s' doesn't allow an argument\n"),
    695                          argv[0], argv[optind - 1][0], pfound->name);
    696                     }
     684                  { /* bird: disambiguate */
     685                   if (argv[optind - 1][1] == '-')
     686                    /* --option */
     687                    fprintf (stderr,
     688                     _("%s: option '--%s' doesn't allow an argument\n"),
     689                     argv[0], pfound->name);
     690                   else
     691                    /* +option or -option */
     692                    fprintf (stderr,
     693                     _("%s: option '%c%s' doesn't allow an argument\n"),
     694                     argv[0], argv[optind - 1][0], pfound->name);
     695                  }
    697696
    698697                  nextchar += strlen (nextchar);
     
    710709                  if (opterr)
    711710                    fprintf (stderr,
    712                            _("%s: option `%s' requires an argument\n"),
     711                           _("%s: option '%s' requires an argument\n"),
    713712                           argv[0], argv[optind - 1]);
    714713                  nextchar += strlen (nextchar);
     
    739738              if (argv[optind][1] == '-')
    740739                /* --option */
    741                 fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
     740                fprintf (stderr, _("%s: unrecognized option '--%s'\n"),
    742741                         argv[0], nextchar);
    743742              else
    744743                /* +option or -option */
    745                 fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
     744                fprintf (stderr, _("%s: unrecognized option '%c%s'\n"),
    746745                         argv[0], argv[optind][0], nextchar);
    747746            }
     
    849848          {
    850849            if (opterr)
    851               fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
     850              fprintf (stderr, _("%s: option '-W %s' is ambiguous\n"),
    852851                       argv[0], argv[optind]);
    853852            nextchar += strlen (nextchar);
     
    868867                    if (opterr)
    869868                      fprintf (stderr, _("\
    870 %s: option `-W %s' doesn't allow an argument\n"),
     869%s: option '-W %s' doesn't allow an argument\n"),
    871870                               argv[0], pfound->name);
    872871
     
    883882                    if (opterr)
    884883                      fprintf (stderr,
    885                                _("%s: option `%s' requires an argument\n"),
     884                               _("%s: option '%s' requires an argument\n"),
    886885                               argv[0], argv[optind - 1]);
    887886                    nextchar += strlen (nextchar);
     
    10101009
    10111010        case 'c':
    1012           printf ("option c with value `%s'\n", optarg);
     1011          printf ("option c with value '%s'\n", optarg);
    10131012          break;
    10141013
  • trunk/src/kmk/getopt.h

    r2591 r3140  
    11/* Declarations for getopt.
    2 Copyright (C) 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
    3 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free
    4 Software Foundation, Inc.
     2Copyright (C) 1989-2016 Free Software Foundation, Inc.
    53
    64NOTE: The canonical source of this file is maintained with the GNU C Library.
  • trunk/src/kmk/getopt1.c

    r2591 r3140  
    11/* getopt_long and getopt_long_only entry points for GNU getopt.
    2 Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1987-1994, 1996-2016 Free Software Foundation, Inc.
    53
    64NOTE: The canonical source of this file is maintained with the GNU C Library.
     
    152150
    153151        case 'c':
    154           printf ("option c with value `%s'\n", optarg);
     152          printf ("option c with value '%s'\n", optarg);
    155153          break;
    156154
    157155        case 'd':
    158           printf ("option d with value `%s'\n", optarg);
     156          printf ("option d with value '%s'\n", optarg);
    159157          break;
    160158
  • trunk/src/kmk/gettext.h

    r2591 r3140  
    11/* Convenience header for conditional use of GNU <libintl.h>.
    2 Copyright (C) 1995, 1996, 1997, 1998, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1995-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
  • trunk/src/kmk/glob/ChangeLog

    r2591 r3140  
     12013-10-20  Paul Smith  <[email protected]>
     2
     3        * glob.c (glob): Cherry-pick a471e96a5352a5f0bde6d32dd36d33524811a2b1
     4        from git://sourceware.org/git/glibc.git to fix SV 18123,
     5        https://sourceware.org/bugzilla/show_bug.cgi?id=10278
     6
    172008-09-28  Juan Manuel Guerrero  <[email protected]>
    28
  • trunk/src/kmk/glob/glob.c

    r2702 r3140  
    380380    }
    381381
     382  /* POSIX requires all slashes to be matched.  This means that with
     383     a trailing slash we must match only directories.  */
     384  if (pattern[0] && pattern[strlen (pattern) - 1] == '/')
     385    flags |= GLOB_ONLYDIR;
     386
    382387  if (flags & GLOB_BRACE)
    383388    {
  • trunk/src/kmk/glob/glob.h

    r3027 r3140  
    5757/* This is a guess.  */
    5858/*hb
    59  *      Conflicts with DECCs aready defined type __size_t.
     59 *      Conflicts with DECCs already defined type __size_t.
    6060 *      Defining an own type with a name beginning with '__' is no good.
    6161 *      Anyway if DECC is used and __SIZE_T is defined then __size_t is
  • trunk/src/kmk/hash.c

    r2745 r3140  
    1515this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1616
    17 #include "make.h"
     17#include "makeint.h"
    1818#include "hash.h"
    1919#ifdef CONFIG_WITH_STRCACHE2
     
    2121#endif
    2222
    23 
    24 /*#define       CALLOC(t, n) ((t *) calloc (sizeof (t), (n)))*/
    2523#define CALLOC(t, n) ((t *) xcalloc (sizeof (t) * (n)))
    2624#define MALLOC(t, n) ((t *) xmalloc (sizeof (t) * (n)))
     
    3230
    3331/* Implement double hashing with open addressing.  The table size is
    34    always a power of two.  The secondary (`increment') hash function
     32   always a power of two.  The secondary ('increment') hash function
    3533   is forced to return an odd-value, in order to be relatively prime
    3634   to the table size.  This guarantees that the increment can
     
    5452      fprintf (stderr, _("can't allocate %lu bytes for hash table: memory exhausted"),
    5553               ht->ht_size * (unsigned long) sizeof (struct token *));
    56       exit (1);
     54      exit (MAKE_TROUBLE);
    5755    }
    5856
     
    9088#endif /* CONFIG_WITH_STRCACHE2 */
    9189
    92 /* Load an array of items into `ht'.  */
     90/* Load an array of items into 'ht'.  */
    9391
    9492void
     
    119117}
    120118
    121 /* Returns the address of the table slot matching `key'.  If `key' is
     119/* Returns the address of the table slot matching 'key'.  If 'key' is
    122120   not found, return the address of an empty slot suitable for
    123    inserting `key'.  The caller is responsible for incrementing
     121   inserting 'key'.  The caller is responsible for incrementing
    124122   ht_fill on insertion.  */
    125123
  • trunk/src/kmk/hash.h

    r2591 r3140  
    2929# undef __P
    3030# define __P(protos)    ()
    31 /* We can get away without defining `const' here only because in this file
    32    it is used only inside the prototype for `fnmatch', which is elided in
    33    non-ANSI C where `const' is problematical.  */
     31/* We can get away without defining 'const' here only because in this file
     32   it is used only inside the prototype for 'fnmatch', which is elided in
     33   non-ANSI C where 'const' is problematical.  */
    3434#endif /* C++ or ANSI C.  */
    3535
     
    4242{
    4343  void **ht_vec;
     44  hash_func_t ht_hash_1;        /* primary hash function */
     45  hash_func_t ht_hash_2;        /* secondary hash function */
     46  hash_cmp_func_t ht_compare;   /* comparison function */
    4447  unsigned long ht_size;        /* total number of slots (power of 2) */
    4548  unsigned long ht_capacity;    /* usable slots, limited by loading-factor */
     
    4952  unsigned long ht_lookups;     /* # of queries */
    5053  unsigned int ht_rehashes;     /* # of times we've expanded table */
    51   hash_func_t ht_hash_1;        /* primary hash function */
    52   hash_func_t ht_hash_2;        /* secondary hash function */
    53   hash_cmp_func_t ht_compare;   /* comparison function */
    5454#ifdef CONFIG_WITH_STRCACHE2
    5555  struct strcache2 *ht_strcache; /* the string cache pointer. */
  • trunk/src/kmk/implicit.c

    r2591 r3140  
    11/* Implicit rule searching for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018#include "filedef.h"
    2119#include "rule.h"
     
    3937try_implicit_rule (struct file *file, unsigned int depth)
    4038{
    41   DBF (DB_IMPLICIT, _("Looking for an implicit rule for `%s'.\n"));
     39  DBF (DB_IMPLICIT, _("Looking for an implicit rule for '%s'.\n"));
    4240
    4341  /* The order of these searches was previously reversed.  My logic now is
     
    5553    {
    5654      DBF (DB_IMPLICIT,
    57            _("Looking for archive-member implicit rule for `%s'.\n"));
     55           _("Looking for archive-member implicit rule for '%s'.\n"));
    5856      if (pattern_search (file, 1, depth, 0))
    5957        return 1;
     
    7775
    7876  /* Skip any leading whitespace.  */
    79   while (isblank ((unsigned char)*p))
    80     ++p;
     77  NEXT_TOKEN (p);
    8178
    8279  beg = p;
     
    226223
    227224  /* List of dependencies found recursively.  */
    228   struct patdeps *deplist
    229     = xmalloc (max_pattern_deps * sizeof (struct patdeps));
     225  unsigned int max_deps = max_pattern_deps;
     226  struct patdeps *deplist = xmalloc (max_deps * sizeof (struct patdeps));
    230227  struct patdeps *pat = deplist;
    231 
    232   /* All the prerequisites actually found for a rule, after expansion.  */
    233   struct dep *deps;
    234228
    235229  /* Names of possible dependencies are constructed in this buffer.  */
     
    258252
    259253  /* Nonzero if we have matched a pattern-rule target
    260      that is not just `%'.  */
     254     that is not just '%'.  */
    261255  int specific_rule_matched = 0;
    262 
    263   struct dep dep_simple;
    264256
    265257  unsigned int ri;  /* uninit checks OK */
     
    280272         but not counting any slash at the end.  (foo/bar/ counts as
    281273         bar/ in directory foo/, not empty in directory foo/bar/.)  */
     274      lastslash = strrchr (filename, '/');
    282275#ifdef VMS
    283       lastslash = strrchr (filename, ']');
    284       if (lastslash == 0)
     276      if (lastslash == NULL)
     277        lastslash = strrchr (filename, ']');
     278      if (lastslash == NULL)
     279        lastslash = strrchr (filename, '>');
     280      if (lastslash == NULL)
    285281        lastslash = strrchr (filename, ':');
    286 #else
    287       lastslash = strrchr (filename, '/');
     282#endif
    288283#ifdef HAVE_DOS_PATHS
    289284      /* Handle backslashes (possibly mixed with forward slashes)
     
    297292      }
    298293#endif
    299 #endif
    300294      if (lastslash != 0 && lastslash[1] == '\0')
    301295        lastslash = 0;
     
    329323          const char *target = rule->targets[ti];
    330324          const char *suffix = rule->suffixes[ti];
    331           int check_lastslash;
     325          char check_lastslash;
    332326
    333327          /* Rules that can match any filename and are not terminal
     
    353347            {
    354348#ifdef VMS
    355               check_lastslash = (strchr (target, ']') == 0
    356                                  && strchr (target, ':') == 0);
     349              check_lastslash = strpbrk (target, "/]>:") == NULL;
    357350#else
    358351              check_lastslash = strchr (target, '/') == 0;
     352#endif
    359353#ifdef HAVE_DOS_PATHS
    360354              /* Didn't find it yet: check for DOS-type directories.  */
     
    364358                  check_lastslash = !(b || (target[0] && target[1] == ':'));
    365359                }
    366 #endif
    367360#endif
    368361            }
     
    409402             that rule will be in TRYRULES more than once.  */
    410403          tryrules[nrules].rule = rule;
    411           tryrules[nrules].matches = ti;
     404          tryrules[nrules].matches = ti;
    412405          tryrules[nrules].stemlen = stemlen + (check_lastslash ? pathlen : 0);
    413406          tryrules[nrules].order = nrules;
    414           tryrules[nrules].checked_lastslash = check_lastslash;
     407          tryrules[nrules].checked_lastslash = check_lastslash;
    415408          ++nrules;
    416409        }
     
    451444        {
    452445          struct dep *dep;
    453           int check_lastslash;
     446          char check_lastslash;
    454447          unsigned int failed = 0;
    455448          int file_variables_set = 0;
     
    495488            }
    496489
    497           DBS (DB_IMPLICIT, (_("Trying pattern rule with stem `%.*s'.\n"),
     490          if (stemlen > GET_PATH_MAX)
     491            {
     492              DBS (DB_IMPLICIT, (_("Stem too long: '%.*s'.\n"),
     493                                 (int) stemlen, stem));
     494              continue;
     495            }
     496
     497          DBS (DB_IMPLICIT, (_("Trying pattern rule with stem '%.*s'.\n"),
    498498                             (int) stemlen, stem));
    499499
     
    537537              if (! dep->need_2nd_expansion)
    538538                {
    539                   dep_simple = *dep;
    540                   dep_simple.next = 0;
    541539                  p = strchr (nptr, '%');
    542540                  if (p == 0)
    543                     dep_simple.name = nptr;
     541                    strcpy (depname, nptr);
    544542                  else
    545543                    {
     
    555553                      o += stemlen;
    556554                      strcpy (o, p + 1);
    557                       dep_simple.name = strcache_add (depname);
    558                     }
    559                   dl = &dep_simple;
     555                    }
     556
     557                  /* Parse the expanded string.  It might have wildcards.  */
     558                  p = depname;
     559                  dl = PARSE_SIMPLE_SEQ (&p, struct dep);
     560                  for (d = dl; d != NULL; d = d->next)
     561                    {
     562                      ++deps_found;
     563                      d->ignore_mtime = dep->ignore_mtime;
     564                    }
    560565
    561566                  /* We've used up this dep, so next time get a new one.  */
    562567                  nptr = 0;
    563                   ++deps_found;
    564568                }
    565569
     
    577581                  int add_dir = 0;
    578582                  unsigned int len;
     583                  struct dep **dptr;
    579584
    580585                  nptr = get_next_word (nptr, &len);
     
    618623                        add_dir = 1;
    619624                    }
     625
     626                  /* Set up for the next word.  */
     627                  nptr += len;
    620628
    621629                  /* Initialize and set file variables if we haven't already
     
    641649                  /* Perform the 2nd expansion.  */
    642650                  p = variable_expand_for_file (depname, file);
    643 
    644                   /* Parse the expanded string. */
    645                   dl = PARSE_FILE_SEQ (&p, struct dep, order_only ? '\0' : '|',
    646                                        add_dir ? dir : NULL, 0);
    647 
    648                   for (d = dl; d != NULL; d = d->next)
    649                     {
    650                       ++deps_found;
    651                       if (order_only)
    652                         d->ignore_mtime = 1;
    653                     }
    654 
    655                   /* Set up for the next word.  */
    656                   nptr += len;
     651                  dptr = &dl;
     652
     653                  /* Parse the results into a deps list.  */
     654                  do
     655                    {
     656                      /* Parse the expanded string. */
     657                      struct dep *dp = PARSE_FILE_SEQ (&p, struct dep,
     658                                                       order_only ? MAP_NUL : MAP_PIPE,
     659                                                       add_dir ? dir : NULL, PARSEFS_NONE);
     660                      *dptr = dp;
     661
     662                      for (d = dp; d != NULL; d = d->next)
     663                        {
     664                          ++deps_found;
     665                          if (order_only)
     666                            d->ignore_mtime = 1;
     667                          dptr = &d->next;
     668                        }
     669
     670                      /* If we stopped due to an order-only token, note it.  */
     671                      if (*p == '|')
     672                        {
     673                          order_only = 1;
     674                          ++p;
     675                        }
     676                    }
     677                  while (*p != '\0');
    657678                }
    658679
     
    660681                 2nd expansion), reset it and realloc the arrays.  */
    661682
    662               if (deps_found > max_pattern_deps)
     683              if (deps_found > max_deps)
    663684                {
    664685                  unsigned int l = pat - deplist;
     686                  /* This might have changed due to recursion.  */
     687                  max_pattern_deps = MAX(max_pattern_deps, deps_found);
     688                  max_deps = max_pattern_deps;
    665689                  deplist = xrealloc (deplist,
    666                                       deps_found * sizeof (struct patdeps));
     690                                      max_deps * sizeof (struct patdeps));
    667691                  pat = deplist + l;
    668                   max_pattern_deps = deps_found;
    669692                }
    670693
     
    682705                      DBS (DB_IMPLICIT,
    683706                           (is_rule
    684                             ? _("Rejecting impossible rule prerequisite `%s'.\n")
    685                             : _("Rejecting impossible implicit prerequisite `%s'.\n"),
     707                            ? _("Rejecting impossible rule prerequisite '%s'.\n")
     708                            : _("Rejecting impossible implicit prerequisite '%s'.\n"),
    686709                            d->name));
    687710                      tryrules[ri].rule = 0;
     
    696719                  DBS (DB_IMPLICIT,
    697720                       (is_rule
    698                         ? _("Trying rule prerequisite `%s'.\n")
    699                         : _("Trying implicit prerequisite `%s'.\n"), d->name));
     721                        ? _("Trying rule prerequisite '%s'.\n")
     722                        : _("Trying implicit prerequisite '%s'.\n"), d->name));
    700723
    701724                  /* If this prereq is also explicitly mentioned for FILE,
     
    736759                      {
    737760                        DBS (DB_IMPLICIT,
    738                              (_("Found prerequisite `%s' as VPATH `%s'\n"),
     761                             (_("Found prerequisite '%s' as VPATH '%s'\n"),
    739762                              d->name, vname));
    740763                        (pat++)->name = d->name;
     
    750773                    {
    751774                      DBS (DB_IMPLICIT,
    752                            (_("Looking for a rule with intermediate file `%s'.\n"),
     775                           (_("Looking for a rule with intermediate file '%s'.\n"),
    753776                            d->name));
    754777
     
    766789                          int_file->name = d->name;
    767790                          pat->file = int_file;
     791                          int_file = 0;
    768792                          (pat++)->name = d->name;
    769                           int_file = 0;
    770793                          continue;
    771794                        }
     
    788811
    789812              /* Free the ns chain.  */
    790               if (dl != &dep_simple)
    791                 free_dep_chain (dl);
     813              free_dep_chain (dl);
    792814
    793815              if (failed)
     
    799821          file->stem = 0;
    800822
    801           /* This rule is no longer `in use' for recursive searches.  */
     823          /* This rule is no longer 'in use' for recursive searches.  */
    802824          rule->in_use = 0;
    803825
     
    806828            break;
    807829
    808           /* This pattern rule does not apply. If some of its dependencies
    809              succeeded, free the data structure describing them.  */
    810           /* free_idep_chain (deps); */
    811           deps = 0;
     830          /* This pattern rule does not apply.  Keep looking.  */
    812831        }
    813832
     
    855874          /* We don't want to delete an intermediate file that happened
    856875             to be a prerequisite of some (other) target. Mark it as
    857              precious.  */
     876             secondary.  We don't want it to be precious as that disables
     877             DELETE_ON_ERROR etc.  */
    858878          if (f != 0)
    859             f->precious = 1;
     879            f->secondary = 1;
    860880          else
    861881            f = enter_file (imf->name);
     
    901921             the rule that found it was a terminal one, then we want to mark
    902922             the found file so that it will not have implicit rule search done
    903              for it.  If we are not entering a `struct file' for it now, we
    904              indicate this with the `changed' flag.  */
     923             for it.  If we are not entering a 'struct file' for it now, we
     924             indicate this with the 'changed' flag.  */
    905925          if (dep->file == 0)
    906926            dep->changed = 1;
     
    950970
    951971  /* If this rule builds other targets, too, put the others into FILE's
    952      `also_make' member.  */
     972     'also_make' member.  */
    953973
    954974  if (rule->num > 1)
  • trunk/src/kmk/incdep.c

    r3100 r3140  
    3838#endif
    3939
    40 #include "make.h"
     40#include "makeint.h"
    4141
    4242#if !defined(WINDOWS32) && !defined(__OS2__)
     
    4848#include <glob.h>
    4949
     50#include "filedef.h"
    5051#include "dep.h"
    51 #include "filedef.h"
    5252#include "job.h"
    5353#include "commands.h"
     
    108108    int recursive;
    109109    struct variable_set *set;
    110     const struct floc *flocp;               /* NILF */
     110    const floc *flocp;                      /* NILF */
    111111};
    112112
     
    115115    struct incdep_variable_def *next;
    116116    /* the parameters */
    117     const struct floc *flocp;               /* NILF */
     117    const floc *flocp;                      /* NILF */
    118118    struct strcache2_entry *name_entry;     /* dep strcache - WRONG */
    119119    char *value;                            /* xmalloc'ed, free it */
     
    131131    struct strcache2_entry *filename_entry; /* dep strcache; converted to a nameseq record. */
    132132    struct dep *deps;                       /* All the names are dep strcache entries. */
    133     const struct floc *flocp;               /* NILF */
     133    const floc *flocp;                     /* NILF */
    134134};
    135135
     
    238238*   Internal Functions                                                         *
    239239*******************************************************************************/
    240 static void incdep_flush_it (struct floc *);
    241 static void eval_include_dep_file (struct incdep *, struct floc *);
     240static void incdep_flush_it (floc *);
     241static void eval_include_dep_file (struct incdep *, floc *);
    242242static void incdep_commit_recorded_file (const char *filename, struct dep *deps,
    243                                          const struct floc *flocp);
     243                                         const floc *flocp);
    244244
    245245
     
    496496/* Reads a dep file into memory. */
    497497static int
    498 incdep_read_file (struct incdep *cur, struct floc *f)
     498incdep_read_file (struct incdep *cur, floc *f)
    499499{
    500500#ifdef INCDEP_USE_KFSCACHE
     
    513513      incdep_xfree (cur, cur->file_base);
    514514    }
    515   error (f, "%s/%s: error reading file", cur->pFileObj->pParent->Obj.pszName, cur->pFileObj->pszName);
     515  OSS (error, f, "%s/%s: error reading file", cur->pFileObj->pParent->Obj.pszName, cur->pFileObj->pszName);
    516516
    517517#else /* !INCDEP_USE_KFSCACHE */
     
    520520
    521521  errno = 0;
    522 #ifdef O_BINARY
     522# ifdef O_BINARY
    523523  fd = open (cur->name, O_RDONLY | O_BINARY, 0);
    524 #else
     524# else
    525525  fd = open (cur->name, O_RDONLY, 0);
    526 #endif
     526# endif
    527527  if (fd < 0)
    528528    {
     
    531531      if (err == ENOENT || stat (cur->name, &st) != 0)
    532532        return 1;
    533       error (f, "%s: %s", cur->name, strerror (err));
     533      OSS (error, f, "%s: %s", cur->name, strerror (err));
    534534      return -1;
    535535    }
    536 #ifdef KBUILD_OS_WINDOWS /* fewer kernel calls */
     536# ifdef KBUILD_OS_WINDOWS /* fewer kernel calls */
    537537  if (!birdStatOnFdJustSize (fd, &st.st_size))
    538 #else
     538# else
    539539  if (!fstat (fd, &st))
    540 #endif
     540# endif
    541541    {
    542542      cur->file_base = incdep_xmalloc (cur, st.st_size + 1);
     
    673673  if (getenv ("KMK_THREADS_DISABLED"))
    674674    {
    675       message (1, "Threads disabled (environment)");
     675      O (message, 1, "Threads disabled (environment)");
    676676      return 0;
    677677    }
     
    694694   || getenv ("FAKEROOT_DB_SEARCH_PATHS"))
    695695    {
    696       message (1, "Threads disabled (fakeroot)");
     696      O (message, 1, "Threads disabled (fakeroot)");
    697697      return 0;
    698698    }
     
    702702  if (getenv ("LD_PRELOAD"))
    703703    {
    704       message (1, "Threads disabled (LD_PRELOAD)");
     704      O (message, 1, "Threads disabled (LD_PRELOAD)");
    705705      return 0;
    706706    }
     
    723723/* Creates the the worker threads. */
    724724static void
    725 incdep_init (struct floc *f)
     725incdep_init (floc *f)
    726726{
    727727  unsigned i;
     
    754754  rc = pthread_mutex_init (&incdep_mtx, NULL);
    755755  if (rc)
    756     fatal (f, _("pthread_mutex_init failed: err=%d"), rc);
     756    ON (fatal, f, _("pthread_mutex_init failed: err=%d"), rc);
    757757  rc = pthread_cond_init (&incdep_cond_todo, NULL);
    758758  if (rc)
    759     fatal (f, _("pthread_cond_init failed: err=%d"), rc);
     759    ON (fatal, f, _("pthread_cond_init failed: err=%d"), rc);
    760760  rc = pthread_cond_init (&incdep_cond_done, NULL);
    761761  if (rc)
    762     fatal (f, _("pthread_cond_init failed: err=%d"), rc);
     762    ON (fatal, f, _("pthread_cond_init failed: err=%d"), rc);
    763763
    764764#elif defined (WINDOWS32)
     
    766766  incdep_hev_todo = CreateEvent (NULL, TRUE /*bManualReset*/, FALSE /*bInitialState*/, NULL);
    767767  if (!incdep_hev_todo)
    768     fatal (f, _("CreateEvent failed: err=%d"), GetLastError());
     768    ON (fatal, f, _("CreateEvent failed: err=%d"), GetLastError());
    769769  incdep_hev_done = CreateEvent (NULL, TRUE /*bManualReset*/, FALSE /*bInitialState*/, NULL);
    770770  if (!incdep_hev_done)
    771     fatal (f, _("CreateEvent failed: err=%d"), GetLastError());
     771    ON (fatal, f, _("CreateEvent failed: err=%d"), GetLastError());
    772772  incdep_hev_todo_waiters = 0;
    773773  incdep_hev_done_waiters = 0;
     
    777777  rc = DosCreateEventSem (NULL, &incdep_hev_todo, 0, FALSE);
    778778  if (rc)
    779     fatal (f, _("DosCreateEventSem failed: rc=%d"), rc);
     779    ON (fatal, f, _("DosCreateEventSem failed: rc=%d"), rc);
    780780  rc = DosCreateEventSem (NULL, &incdep_hev_done, 0, FALSE);
    781781  if (rc)
    782     fatal (f, _("DosCreateEventSem failed: rc=%d"), rc);
     782    ON (fatal, f, _("DosCreateEventSem failed: rc=%d"), rc);
    783783  incdep_hev_todo_waiters = 0;
    784784  incdep_hev_done_waiters = 0;
     
    827827          rc = pthread_attr_init (&attr);
    828828          if (rc)
    829             fatal (f, _("pthread_attr_init failed: err=%d"), rc);
     829            ON (fatal, f, _("pthread_attr_init failed: err=%d"), rc);
    830830          /*rc = pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE); */
    831831          rc = pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
    832832          if (rc)
    833             fatal (f, _("pthread_attr_setdetachstate failed: err=%d"), rc);
     833            ON (fatal, f, _("pthread_attr_setdetachstate failed: err=%d"), rc);
    834834          rc = pthread_create (&incdep_threads[i], &attr,
    835835                               incdep_worker_pthread, (void *)(size_t)i);
    836836          if (rc)
    837             fatal (f, _("pthread_mutex_init failed: err=%d"), rc);
     837            ON (fatal, f, _("pthread_mutex_init failed: err=%d"), rc);
    838838          pthread_attr_destroy (&attr);
    839839
     
    843843                                    (void *)i, 0, &tid);
    844844          if (hThread == 0 || hThread == ~(uintptr_t)0)
    845             fatal (f, _("_beginthreadex failed: err=%d"), errno);
     845            ON (fatal, f, _("_beginthreadex failed: err=%d"), errno);
    846846          incdep_threads[i] = (HANDLE)hThread;
    847847
     
    849849          tid = _beginthread (incdep_worker_os2, NULL, 128*1024, (void *)i);
    850850          if (tid <= 0)
    851             fatal (f, _("_beginthread failed: err=%d"), errno);
     851            ON (fatal, f, _("_beginthread failed: err=%d"), errno);
    852852          incdep_threads[i] = tid;
    853853#endif
     
    927927  if (cur->err_msg)
    928928#ifdef INCDEP_USE_KFSCACHE
    929     error(NILF, "%s/%s(%d): %s", cur->pFileObj->pParent->Obj.pszName, cur->pFileObj->pszName, cur->err_line_no, cur->err_msg);
     929    OSSNS (error, NILF, "%s/%s(%d): %s", cur->pFileObj->pParent->Obj.pszName, cur->pFileObj->pszName,
     930           cur->err_line_no, cur->err_msg);
    930931#else
    931     error(NILF, "%s(%d): %s", cur->name, cur->err_line_no, cur->err_msg);
     932    OSNS (error,NILF, "%s(%d): %s", cur->name, cur->err_line_no, cur->err_msg);
    932933#endif
    933934
     
    10081009  if (cur->worker_tid == -1)
    10091010#ifdef INCDEP_USE_KFSCACHE
    1010     error (NILF, "%s/%s(%d): %s", cur->pFileObj->pParent->Obj.pszName, cur->pFileObj->pszName, line_no, msg);
     1011    OSSNS (error,NILF, "%s/%s(%d): %s", cur->pFileObj->pParent->Obj.pszName, cur->pFileObj->pszName, line_no, msg);
    10111012#else
    1012     error (NILF, "%s(%d): %s", cur->name, line_no, msg);
     1013    OSNS (error, NILF, "%s(%d): %s", cur->name, line_no, msg);
    10131014#endif
    10141015#ifdef PARSE_IN_WORKER
     
    10791080                               int recursive,
    10801081                               struct variable_set *set,
    1081                                const struct floc *flocp)
     1082                               const floc *flocp)
    10821083{
    10831084  assert (!duplicate_value);
     
    11121113static void
    11131114incdep_record_variable_def (struct incdep *cur,
    1114                             const struct floc *flocp,
     1115                            const floc *flocp,
    11151116                            const char *name,
    11161117                            unsigned int name_length,
     
    11521153static void
    11531154incdep_commit_recorded_file (const char *filename, struct dep *deps,
    1154                              const struct floc *flocp)
     1155                             const floc *flocp)
    11551156{
    11561157  struct file *f;
     
    11741175     )
    11751176    {
    1176       error (flocp, _("reserved filename '%s' used in dependency file, ignored"), filename);
     1177      OS (error, flocp, _("reserved filename '%s' used in dependency file, ignored"), filename);
    11771178      return;
    11781179    }
     
    11821183  if (f->double_colon)
    11831184    {
    1184       error (flocp, _("dependency file '%s' has a double colon entry already, ignoring"), filename);
     1185      OS (error, flocp, _("dependency file '%s' has a double colon entry already, ignoring"), filename);
    11851186      return;
    11861187    }
     
    12081209                    const char *filename,
    12091210                    struct dep *deps,
    1210                     const struct floc *flocp)
     1211                    const floc *flocp)
    12111212{
    12121213  if (cur->worker_tid == -1)
     
    12531254   */
    12541255static void
    1255 eval_include_dep_file (struct incdep *curdep, struct floc *f)
     1256eval_include_dep_file (struct incdep *curdep, floc *f)
    12561257{
    12571258  unsigned line_no = 1;
     
    12681269    {
    12691270      /* skip empty lines */
    1270       while (cur < file_end && isspace ((unsigned char)*cur) && *cur != '\n')
     1271      while (cur < file_end && ISSPACE (*cur) && *cur != '\n')
    12711272        ++cur;
    12721273      if (cur >= file_end)
     
    13121313          /* extract the variable name. */
    13131314          cur += 7;
    1314           while (isblank ((unsigned char)*cur))
     1315          while (ISBLANK (*cur))
    13151316            ++cur;
    13161317          value_start = endp = memchr (cur, '\n', file_end - cur);
    13171318          if (!endp)
    13181319              endp = cur;
    1319           while (endp > cur && isspace ((unsigned char)endp[-1]))
     1320          while (endp > cur && ISSPACE (endp[-1]))
    13201321            --endp;
    13211322          var_len = endp - cur;
     
    13371338                {
    13381339                  endp = cur + 5;
    1339                   while (endp < file_end && isspace ((unsigned char)*endp) && *endp != '\n')
     1340                  while (endp < file_end && ISSPACE (*endp) && *endp != '\n')
    13401341                    endp++;
    13411342                  if (endp >= file_end || *endp == '\n')
     
    14481449              /* extract the variable name. */
    14491450              endp = flavor == f_recursive ? equalp : equalp - 1;
    1450               while (endp > cur && isblank ((unsigned char)endp[-1]))
     1451              while (endp > cur && ISBLANK (endp[-1]))
    14511452                --endp;
    14521453              var_len = endp - cur;
     
    14671468              /* find the start of the value. */
    14681469              cur = equalp + 1;
    1469               while (cur < file_end && isblank ((unsigned char)*cur))
     1470              while (cur < file_end && ISBLANK (*cur))
    14701471                cur++;
    14711472              value_start = cur;
     
    16291630              /* Extract the first filename after trimming and basic checks. */
    16301631              fnend = colonp;
    1631               while ((uintptr_t)fnend > (uintptr_t)cur && isblank ((unsigned char)fnend[-1]))
     1632              while ((uintptr_t)fnend > (uintptr_t)cur && ISBLANK (fnend[-1]))
    16321633                --fnend;
    16331634              if (cur == fnend)
     
    16431644
    16441645              fnnext = cur;
    1645               while (fnnext != fnend && !isblank ((unsigned char)*fnnext))
     1646              while (fnnext != fnend && !ISBLANK (*fnnext))
    16461647                fnnext++;
    16471648              filename = incdep_dep_strcache (curdep, cur, fnnext - cur);
     
    16521653                {
    16531654                  /* skip blanks and count lines. */
    1654                   while (cur < file_end && isspace ((unsigned char)*cur) && *cur != '\n')
     1655                  while (cur < file_end && ISSPACE (*cur) && *cur != '\n')
    16551656                    ++cur;
    16561657                  if (cur >= file_end)
     
    16791680                  /* find the end of the filename */
    16801681                  endp = cur;
    1681                   while (endp < file_end && !isspace ((unsigned char)*endp))
     1682                  while (endp < file_end && !ISSPACE (*endp))
    16821683                    ++endp;
    16831684
     
    17001701                    const char *filename_prev = filename;
    17011702                    const char *fnstart;
    1702                     while (fnnext != fnend && isblank ((unsigned char)*fnnext))
     1703                    while (fnnext != fnend && ISBLANK (*fnnext))
    17031704                      fnnext++;
    17041705                    if (fnnext == fnend)
     
    17061707
    17071708                    fnstart = fnnext;
    1708                     while (fnnext != fnend && !isblank ((unsigned char)*fnnext))
     1709                    while (fnnext != fnend && !ISBLANK (*fnnext))
    17091710                      fnnext++;
    17101711
     
    17241725/* Flushes the incdep todo and done lists. */
    17251726static void
    1726 incdep_flush_it (struct floc *f)
     1727incdep_flush_it (floc *f)
    17271728{
    17281729  incdep_lock ();
     
    17851786   employing threads to try speed up the file reading. */
    17861787void
    1787 eval_include_dep (const char *names, struct floc *f, enum incdep_op op)
     1788eval_include_dep (const char *names, floc *f, enum incdep_op op)
    17881789{
    17891790  struct incdep *head = 0;
  • trunk/src/kmk/job.c

    r3065 r3140  
    11/* Job execution and handling for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018
    2119#include <assert.h>
     
    2624#include "commands.h"
    2725#include "variable.h"
    28 #include "debug.h"
     26#include "os.h"
    2927#ifdef CONFIG_WITH_KMK_BUILTIN
    3028# include "kmkbuiltin.h"
     
    4139#include <windows.h>
    4240
    43 char *default_shell = "sh.exe";
     41const char *default_shell = "sh.exe";
    4442int no_default_sh_exe = 1;
    4543int batch_mode_shell = 1;
     
    4846#elif defined (_AMIGA)
    4947
    50 char default_shell[] = "";
     48const char *default_shell = "";
    5149extern int MyExecute (char **);
    5250int batch_mode_shell = 0;
     
    5856   to search the $PATH for it (since MSDOS doesn't have standard
    5957   directories we could trust).  */
    60 char *default_shell = "command.com";
     58const char *default_shell = "command.com";
    6159int batch_mode_shell = 0;
    6260
    6361#elif defined (__EMX__)
    6462
    65 char *default_shell = "sh.exe"; /* bird changed this from "/bin/sh" as that doesn't make sense on OS/2. */
     63const char *default_shell = "sh.exe"; /* bird changed this from "/bin/sh" as that doesn't make sense on OS/2. */
    6664int batch_mode_shell = 0;
    6765
     
    6967
    7068# include <descrip.h>
    71 char default_shell[] = "";
     69# include <stsdef.h>
     70const char *default_shell = "";
    7271int batch_mode_shell = 0;
    7372
    74 #elif defined (__riscos__)
    75 
    76 char default_shell[] = "";
    77 int batch_mode_shell = 0;
     73#define strsignal vms_strsignal
     74char * vms_strsignal (int status);
     75
     76#ifndef C_FACILITY_NO
     77# define C_FACILITY_NO 0x350000
     78#endif
     79#ifndef VMS_POSIX_EXIT_MASK
     80# define VMS_POSIX_EXIT_MASK (C_FACILITY_NO | 0xA000)
     81#endif
    7882
    7983#else
    8084
    81 char default_shell[] = "/bin/sh";
     85const char *default_shell = "/bin/sh";
    8286int batch_mode_shell = 0;
    8387
     
    116120# include "w32err.h"
    117121# include "pathstuff.h"
     122# define WAIT_NOHANG 1
    118123#endif /* WINDOWS32 */
    119124
     
    127132
    128133#ifdef HAVE_WAITPID
    129 # define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
    130 #else   /* Don't have waitpid.  */
     134# define WAIT_NOHANG(status)    waitpid (-1, (status), WNOHANG)
     135#else   /* Don't have waitpid.  */
    131136# ifdef HAVE_WAIT3
    132137#  ifndef wait3
    133138extern int wait3 ();
    134139#  endif
    135 #  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
     140#  define WAIT_NOHANG(status)   wait3 ((status), WNOHANG, (struct rusage *) 0)
    136141# endif /* Have wait3.  */
    137142#endif /* Have waitpid.  */
     
    141146#endif
    142147
    143 #ifndef HAVE_UNION_WAIT
     148#ifndef HAVE_UNION_WAIT
    144149
    145150# define WAIT_T int
     
    161166# endif
    162167
    163 #else   /* Have `union wait'.  */
     168#else   /* Have 'union wait'.  */
    164169
    165170# define WAIT_T union wait
     
    180185# endif
    181186
    182 #endif  /* Don't have `union wait'.  */
     187#endif  /* Don't have 'union wait'.  */
    183188
    184189#if !defined(HAVE_UNISTD_H) && !defined(WINDOWS32)
     
    212217}
    213218
     219#ifndef HAVE_GETLOADAVG
    214220int getloadavg (double loadavg[], int nelem);
    215 int start_remote_job (char **argv, char **envp, int stdin_fd, int *is_remote,
    216                       int *id_ptr, int *used_stdin);
    217 int start_remote_job_p (int);
    218 int remote_status (int *exit_code_ptr, int *signal_ptr, int *coredump_ptr,
    219                    int block);
    220 
    221 RETSIGTYPE child_handler (int);
     221#endif
     222
    222223static void free_child (struct child *);
    223224static void start_job_command (struct child *child);
     
    238239unsigned int job_slots_used = 0;
    239240
    240 /* Nonzero if the `good' standard input is in use.  */
     241/* Nonzero if the 'good' standard input is in use.  */
    241242
    242243static int good_stdin_used = 0;
     
    257258
    258259unsigned int jobserver_tokens = 0;
     260
    259261
    260262
    261263#ifdef WINDOWS32
    262264/*
    263  * The macro which references this function is defined in make.h.
     265 * The macro which references this function is defined in makeint.h.
    264266 */
    265267int
    266 w32_kill(pid_t pid, int sig)
     268w32_kill (pid_t pid, int sig)
    267269{
    268   return ((process_kill((HANDLE)pid, sig) == TRUE) ? 0 : -1);
     270  return ((process_kill ((HANDLE)pid, sig) == TRUE) ? 0 : -1);
    269271}
    270272
     
    279281  const char *error_string = NULL;
    280282  char temp_path[MAXPATHLEN]; /* need to know its length */
    281   unsigned path_size = GetTempPath(sizeof temp_path, temp_path);
     283  unsigned path_size = GetTempPath (sizeof temp_path, temp_path);
    282284  int path_is_dot = 0;
    283   unsigned uniq = 1;
     285  /* The following variable is static so we won't try to reuse a name
     286     that was generated a little while ago, because that file might
     287     not be on disk yet, since we use FILE_ATTRIBUTE_TEMPORARY below,
     288     which tells the OS it doesn't need to flush the cache to disk.
     289     If the file is not yet on disk, we might think the name is
     290     available, while it really isn't.  This happens in parallel
     291     builds, where Make doesn't wait for one job to finish before it
     292     launches the next one.  */
     293  static unsigned uniq = 0;
     294  static int second_loop = 0;
    284295  const unsigned sizemax = strlen (base) + strlen (ext) + 10;
    285296
     
    290301    }
    291302
     303  ++uniq;
     304  if (uniq >= 0x10000 && !second_loop)
     305    {
     306      /* If we already had 64K batch files in this
     307         process, make a second loop through the numbers,
     308         looking for free slots, i.e. files that were
     309         deleted in the meantime.  */
     310      second_loop = 1;
     311      uniq = 1;
     312    }
    292313  while (path_size > 0 &&
    293314         path_size + sizemax < sizeof temp_path &&
    294          uniq < 0x10000)
     315         !(uniq >= 0x10000 && second_loop))
    295316    {
    296317      unsigned size = sprintf (temp_path + path_size,
     
    309330      if (h == INVALID_HANDLE_VALUE)
    310331        {
    311           const DWORD er = GetLastError();
     332          const DWORD er = GetLastError ();
    312333
    313334          if (er == ERROR_FILE_EXISTS || er == ERROR_ALREADY_EXISTS)
    314             ++uniq;
     335            {
     336              ++uniq;
     337              if (uniq == 0x10000 && !second_loop)
     338                {
     339                  second_loop = 1;
     340                  uniq = 1;
     341                }
     342            }
    315343
    316344          /* the temporary path is not guaranteed to exist */
     
    348376  if (error_string == NULL)
    349377    error_string = _("Cannot create a temporary file\n");
    350   fatal (NILF, error_string);
     378  O (fatal, NILF, error_string);
    351379
    352380  /* not reached */
     
    388416
    389417  i = 0;
    390   while (known_os2shells[i] != NULL) {
    391     if (strcasecmp (name, known_os2shells[i]) == 0)
    392       return 0; /* not a unix shell */
    393     i++;
    394   }
     418  while (known_os2shells[i] != NULL)
     419    {
     420      if (strcasecmp (name, known_os2shells[i]) == 0)
     421        return 0; /* not a unix shell */
     422      i++;
     423    }
    395424
    396425  /* in doubt assume a unix like shell */
     
    403432is_bourne_compatible_shell (const char *path)
    404433{
    405   /* list of known unix (Bourne-like) shells */
    406   const char *unix_shells[] = {
     434  /* List of known POSIX (or POSIX-ish) shells. */
     435  static const char *unix_shells[] = {
    407436    "sh",
    408437    "bash",
     
    414443    NULL
    415444  };
    416   unsigned i, len;
     445  const char **s;
    417446
    418447  /* find the rightmost '/' or '\\' */
     
    427456    name = path;
    428457
    429   if (*name == '/' || *name == '\\') name++;
     458  if (*name == '/' || *name == '\\')
     459    ++name;
    430460
    431461  /* this should be able to deal with extensions on Windows-like systems */
    432   for (i = 0; unix_shells[i] != NULL; i++) {
    433     len = strlen(unix_shells[i]);
     462  for (s = unix_shells; *s != NULL; ++s)
     463    {
    434464#if defined(WINDOWS32) || defined(__MSDOS__)
    435     if ((strncasecmp (name, unix_shells[i], len) == 0) &&
    436       (strlen(name) >= len && (name[len] == '\0' || name[len] == '.')))
     465      unsigned int len = strlen (*s);
     466      if ((strlen (name) >= len && STOP_SET (name[len], MAP_DOT|MAP_NUL))
     467          && strncasecmp (name, *s, len) == 0)
    437468#else
    438     if ((strncmp (name, unix_shells[i], len) == 0) &&
    439       (strlen(name) >= len && name[len] == '\0'))
    440 #endif
    441         return 1; /* a known unix-style shell */
    442   }
     469      if (strcmp (name, *s) == 0)
     470#endif
     471        return 1; /* a known unix-style shell */
     472    }
    443473
    444474  /* if not on the list, assume it's not a Bourne-like shell */
     
    453483
    454484static void
    455 child_error (const char *target_name,
     485child_error (struct child *child,
    456486             int exit_code, int exit_sig, int coredump, int ignored)
    457487{
     488  const char *pre = "*** ";
     489  const char *post = "";
     490  const char *dump = "";
     491  const struct file *f = child->file;
     492  const floc *flocp = &f->cmds->fileinfo;
     493  const char *nm;
     494  size_t l;
     495
    458496  if (ignored && silent_flag)
    459497    return;
    460498
    461 #ifdef VMS
    462   if (!(exit_code & 1))
    463       error (NILF,
    464              (ignored ? _("*** [%s] Error 0x%x (ignored)")
    465               : _("*** [%s] Error 0x%x")),
    466              target_name, exit_code);
    467 #else
     499  if (exit_sig && coredump)
     500    dump = _(" (core dumped)");
     501
     502  if (ignored)
     503    {
     504      pre = "";
     505      post = _(" (ignored)");
     506    }
     507
     508  if (! flocp->filenm)
     509    nm = _("<builtin>");
     510  else
     511    {
     512      char *a = alloca (strlen (flocp->filenm) + 1 + 11 + 1);
     513      sprintf (a, "%s:%lu", flocp->filenm, flocp->lineno + flocp->offset);
     514      nm = a;
     515    }
     516
     517  l = strlen (pre) + strlen (nm) + strlen (f->name) + strlen (post);
     518
     519  OUTPUT_SET (&child->output);
     520
     521  show_goal_error ();
     522
    468523  if (exit_sig == 0)
    469524# if defined(KMK) && defined(KBUILD_OS_WINDOWS)
    470525    {
    471       const char *name = NULL;
     526      const char *exit_name = NULL;
    472527      switch ((unsigned)exit_code)
    473528        {
    474         case 0xc0000005U: name = "STATUS_ACCESS_VIOLATION"; break;
    475         case 0xc000013aU: name = "STATUS_CONTROL_C_EXIT"; break;
    476         case 0xc0000374U: name = "STATUS_HEAP_CORRUPTION"; break;
    477         case 0xc0000409U: name = "STATUS_STACK_BUFFER_OVERRUN"; break;
    478         case 0xc0000417U: name = "STATUS_INVALID_CRUNTIME_PARAMETER"; break;
    479         case 0x80000003U: name = "STATUS_BREAKPOINT"; break;
    480         case 0x40000015U: name = "STATUS_FATAL_APP_EXIT"; break;
    481         case 0x40010004U: name = "DBG_TERMINATE_PROCESS"; break;
    482         case 0x40010005U: name = "DBG_CONTROL_C"; break;
    483         case 0x40010008U: name = "DBG_CONTROL_BREAK"; break;
     529        case 0xc0000005U: exit_name = "STATUS_ACCESS_VIOLATION"; break;
     530        case 0xc000013aU: exit_name = "STATUS_CONTROL_C_EXIT"; break;
     531        case 0xc0000374U: exit_name = "STATUS_HEAP_CORRUPTION"; break;
     532        case 0xc0000409U: exit_name = "STATUS_STACK_BUFFER_OVERRUN"; break;
     533        case 0xc0000417U: exit_name = "STATUS_INVALID_CRUNTIME_PARAMETER"; break;
     534        case 0x80000003U: exit_name = "STATUS_BREAKPOINT"; break;
     535        case 0x40000015U: exit_name = "STATUS_FATAL_APP_EXIT"; break;
     536        case 0x40010004U: exit_name = "DBG_TERMINATE_PROCESS"; break;
     537        case 0x40010005U: exit_name = "DBG_CONTROL_C"; break;
     538        case 0x40010008U: exit_name = "DBG_CONTROL_BREAK"; break;
    484539        }
    485       if (name)
    486         error(NILF, ignored ? _("[%s] Error %d (%s) (ignored)") :
    487                _("*** [%s] Error %d (%s)"),
    488                target_name, exit_code, name);
     540      if (exit_name)
     541        error (NILF, l + strlen (exit_name) + INTSTR_LENGTH,
     542               _("%s[%s: %s] Error %d (%s)%s"),
     543               pre, nm, f->name, exit_code, exit_name, post);
    489544      else
    490         error(NILF, ignored ? _("[%s] Error %d (%#x) (ignored)") :
    491                _("*** [%s] Error %d (%#x)"),
    492                target_name, exit_code, exit_code);
     545        error (NILF, l + INTSTR_LENGTH + INTSTR_LENGTH,
     546               _("%s[%s: %s] Error %d (%#x)%s"),
     547               pre, nm, f->name, exit_code, exit_code, post);
    493548    }
    494549# else
    495     error (NILF, ignored ? _("[%s] Error %d (ignored)") :
    496            _("*** [%s] Error %d"),
    497            target_name, exit_code);
     550    error (NILF, l + INTSTR_LENGTH,
     551           _("%s[%s: %s] Error %d%s"), pre, nm, f->name, exit_code, post);
    498552# endif
    499553  else
    500     error (NILF, "*** [%s] %s%s",
    501            target_name, strsignal (exit_sig),
    502            coredump ? _(" (core dumped)") : "");
    503 #endif /* VMS */
     554    {
     555      const char *s = strsignal (exit_sig);
     556      error (NILF, l + strlen (s) + strlen (dump),
     557             "%s[%s: %s] %s%s%s", pre, nm, f->name, s, dump, post);
     558    }
     559
     560  OUTPUT_UNSET ();
    504561}
    505562
     
    508565/* Handle a dead child.  This handler may or may not ever be installed.
    509566
    510    If we're using the jobserver feature, we need it.  First, installing it
    511    ensures the read will interrupt on SIGCHLD.  Second, we close the dup'd
    512    read FD to ensure we don't enter another blocking read without reaping all
    513    the dead children.  In this case we don't need the dead_children count.
     567   If we're using the jobserver feature without pselect(), we need it.
     568   First, installing it ensures the read will interrupt on SIGCHLD.  Second,
     569   we close the dup'd read FD to ensure we don't enter another blocking read
     570   without reaping all the dead children.  In this case we don't need the
     571   dead_children count.
    514572
    515573   If we don't have either waitpid or wait3, then make is unreliable, but we
     
    523581  ++dead_children;
    524582
    525   if (job_rfd >= 0)
    526     {
    527       close (job_rfd);
    528       job_rfd = -1;
    529     }
     583  jobserver_signal ();
    530584
    531585#if defined __EMX__ && !defined(__INNOTEK_LIBC__) /* bird */
     
    533587  signal (SIGCHLD, SIG_DFL);
    534588#endif
    535 
    536   /* This causes problems if the SIGCHLD interrupts a printf().
    537   DB (DB_JOBS, (_("Got a SIGCHLD; %u unreaped children.\n"), dead_children));
    538   */
    539589}
    540590
    541 extern int shell_function_pid, shell_function_completed;
     591extern pid_t shell_function_pid;
    542592
    543593/* Reap all dead children, storing the returned status and the new command
    544    state (`cs_finished') in the `file' member of the `struct child' for the
     594   state ('cs_finished') in the 'file' member of the 'struct child' for the
    545595   dead child, and removing the child from the chain.  In addition, if BLOCK
    546596   nonzero, we block in this function until we've reaped at least one
     
    553603#ifndef WINDOWS32
    554604  WAIT_T status;
     605#endif
    555606  /* Initially, assume we have some.  */
    556607  int reap_more = 1;
    557 #endif
    558608
    559609#ifdef WAIT_NOHANG
     
    574624         && (block || REAP_MORE))
    575625    {
    576       int remote = 0;
     626      unsigned int remote = 0;
    577627      pid_t pid;
    578628      int exit_code, exit_sig, coredump;
    579       register struct child *lastc, *c;
     629      struct child *lastc, *c;
    580630      int child_failed;
    581631      int any_remote, any_local;
     
    586636
    587637      if (err && block)
    588         {
     638        {
    589639          static int printed = 0;
    590640
    591           /* We might block for a while, so let the user know why.
     641          /* We might block for a while, so let the user know why.
    592642             Only print this message once no matter how many jobs are left.  */
    593           fflush (stdout);
     643          fflush (stdout);
    594644          if (!printed)
    595             error (NILF, _("*** Waiting for unfinished jobs...."));
     645            O (error, NILF, _("*** Waiting for unfinished jobs...."));
    596646          printed = 1;
    597         }
     647        }
    598648
    599649      /* We have one less dead child to reap.  As noted in
    600         child_handler() above, this count is completely unimportant for
    601         all modern, POSIX-y systems that support wait3() or waitpid().
    602         The rest of this comment below applies only to early, broken
    603         pre-POSIX systems.  We keep the count only because... it's there...
    604 
    605         The test and decrement are not atomic; if it is compiled into:
    606                 register = dead_children - 1;
    607                 dead_children = register;
    608         a SIGCHLD could come between the two instructions.
    609         child_handler increments dead_children.
    610         The second instruction here would lose that increment.  But the
    611         only effect of dead_children being wrong is that we might wait
    612         longer than necessary to reap a child, and lose some parallelism;
    613         and we might print the "Waiting for unfinished jobs" message above
    614         when not necessary.  */
     650        child_handler() above, this count is completely unimportant for
     651        all modern, POSIX-y systems that support wait3() or waitpid().
     652        The rest of this comment below applies only to early, broken
     653        pre-POSIX systems.  We keep the count only because... it's there...
     654
     655        The test and decrement are not atomic; if it is compiled into:
     656                register = dead_children - 1;
     657                dead_children = register;
     658        a SIGCHLD could come between the two instructions.
     659        child_handler increments dead_children.
     660        The second instruction here would lose that increment.  But the
     661        only effect of dead_children being wrong is that we might wait
     662        longer than necessary to reap a child, and lose some parallelism;
     663        and we might print the "Waiting for unfinished jobs" message above
     664        when not necessary.  */
    615665
    616666      if (dead_children > 0)
    617         --dead_children;
     667        --dead_children;
    618668
    619669      any_remote = 0;
    620670      any_local = shell_function_pid != 0;
    621671      for (c = children; c != 0; c = c->next)
    622         {
    623           any_remote |= c->remote;
    624           any_local |= ! c->remote;
     672        {
     673          any_remote |= c->remote;
     674          any_local |= ! c->remote;
    625675#ifdef CONFIG_WITH_KMK_BUILTIN
    626676          if (c->has_status)
     
    634684          else
    635685#endif
    636           DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
    637                         (void *)c, c->file->name, pid2str (c->pid),
    638                         c->remote ? _(" (remote)") : ""));
     686            DB (DB_JOBS, (_("Live child %p (%s) PID %s %s\n"),
     687                          (void *)c, c->file->name, pid2str (c->pid),
     688                          c->remote ? _(" (remote)") : ""));
    639689#ifdef VMS
    640           break;
    641 #endif
    642         }
     690          break;
     691#endif
     692        }
    643693
    644694      /* First, check for remote children.  */
    645695      if (any_remote)
    646         pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
     696        pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
    647697      else
    648         pid = 0;
     698        pid = 0;
    649699
    650700      if (pid > 0)
    651         /* We got a remote child.  */
    652         remote = 1;
     701        /* We got a remote child.  */
     702        remote = 1;
    653703      else if (pid < 0)
    654         {
     704        {
    655705          /* A remote status command failed miserably.  Punt.  */
    656         remote_status_lose:
    657           pfatal_with_name ("remote_status");
    658         }
     706        remote_status_lose:
     707          pfatal_with_name ("remote_status");
     708        }
    659709      else
    660         {
    661           /* No remote children.  Check for local children.  */
     710        {
     711          /* No remote children.  Check for local children.  */
    662712#ifdef CONFIG_WITH_KMK_BUILTIN
    663713          if (completed_child)
     
    675725#endif /* CONFIG_WITH_KMK_BUILTIN */
    676726#if !defined(__MSDOS__) && !defined(_AMIGA) && !defined(WINDOWS32)
    677           if (any_local)
    678             {
     727          if (any_local)
     728            {
    679729#ifdef VMS
    680               vmsWaitForChildren (&status);
    681               pid = c->pid;
     730              /* Todo: This needs more untangling multi-process support */
     731              /* Just do single child process support now */
     732              vmsWaitForChildren (&status);
     733              pid = c->pid;
     734
     735              /* VMS failure status can not be fully translated */
     736              status = $VMS_STATUS_SUCCESS (c->cstatus) ? 0 : (1 << 8);
     737
     738              /* A Posix failure can be exactly translated */
     739              if ((c->cstatus & VMS_POSIX_EXIT_MASK) == VMS_POSIX_EXIT_MASK)
     740                status = (c->cstatus >> 3 & 255) << 8;
    682741#else
    683742#ifdef WAIT_NOHANG
    684               if (!block)
    685                 pid = WAIT_NOHANG (&status);
    686               else
    687 #endif
    688                 EINTRLOOP(pid, wait (&status));
     743              if (!block)
     744                pid = WAIT_NOHANG (&status);
     745              else
     746#endif
     747                EINTRLOOP (pid, wait (&status));
    689748#endif /* !VMS */
    690             }
    691           else
    692             pid = 0;
    693 
    694           if (pid < 0)
    695             {
     749            }
     750          else
     751            pid = 0;
     752
     753          if (pid < 0)
     754            {
    696755              /* The wait*() failed miserably.  Punt.  */
    697               pfatal_with_name ("wait");
    698             }
    699           else if (pid > 0)
    700             {
    701               /* We got a child exit; chop the status word up.  */
    702               exit_code = WEXITSTATUS (status);
    703               exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
    704               coredump = WCOREDUMP (status);
     756              pfatal_with_name ("wait");
     757            }
     758          else if (pid > 0)
     759            {
     760              /* We got a child exit; chop the status word up.  */
     761              exit_code = WEXITSTATUS (status);
     762              exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
     763              coredump = WCOREDUMP (status);
    705764
    706765              /* If we have started jobs in this second, remove one.  */
    707766              if (job_counter)
    708767                --job_counter;
    709             }
    710           else
    711             {
    712               /* No local children are dead.  */
     768            }
     769          else
     770            {
     771              /* No local children are dead.  */
    713772              reap_more = 0;
    714773
    715               if (!block || !any_remote)
     774              if (!block || !any_remote)
    716775                break;
    717776
     
    726785              /* We got a remote child.  */
    727786              remote = 1;
    728             }
     787            }
    729788#endif /* !__MSDOS__, !Amiga, !WINDOWS32.  */
    730789
    731790#ifdef __MSDOS__
    732           /* Life is very different on MSDOS.  */
    733           pid = dos_pid - 1;
    734           status = dos_status;
    735           exit_code = WEXITSTATUS (status);
    736           if (exit_code == 0xff)
    737             exit_code = -1;
    738           exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
    739           coredump = 0;
     791          /* Life is very different on MSDOS.  */
     792          pid = dos_pid - 1;
     793          status = dos_status;
     794          exit_code = WEXITSTATUS (status);
     795          if (exit_code == 0xff)
     796            exit_code = -1;
     797          exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
     798          coredump = 0;
    740799#endif /* __MSDOS__ */
    741800#ifdef _AMIGA
    742           /* Same on Amiga */
    743           pid = amiga_pid - 1;
    744           status = amiga_status;
    745           exit_code = amiga_status;
    746           exit_sig = 0;
    747           coredump = 0;
     801          /* Same on Amiga */
     802          pid = amiga_pid - 1;
     803          status = amiga_status;
     804          exit_code = amiga_status;
     805          exit_sig = 0;
     806          coredump = 0;
    748807#endif /* _AMIGA */
    749808#ifdef WINDOWS32
    750809          {
    751810            HANDLE hPID;
    752             int werr;
    753811            HANDLE hcTID, hcPID;
     812            DWORD dwWaitStatus = 0;
    754813            exit_code = 0;
    755814            exit_sig = 0;
     
    768827                    fprintf (stderr,
    769828                             "Determine main thread ID (Error %ld: %s)\n",
    770                              e, map_windows32_error_to_string(e));
     829                             e, map_windows32_error_to_string (e));
    771830                  }
    772831                else
     
    775834
    776835            /* wait for anything to finish */
    777             hPID = process_wait_for_any();
     836            hPID = process_wait_for_any (block, &dwWaitStatus);
    778837            if (hPID)
    779838              {
    780 
    781839                /* was an error found on this process? */
    782                 werr = process_last_err(hPID);
     840                int werr = process_last_err (hPID);
    783841
    784842                /* get exit data */
    785                 exit_code = process_exit_code(hPID);
     843                exit_code = process_exit_code (hPID);
    786844
    787845                if (werr)
    788                   fprintf(stderr, "make (e=%d): %s",
    789                           exit_code, map_windows32_error_to_string(exit_code));
     846                  fprintf (stderr, "make (e=%d): %s", exit_code,
     847                           map_windows32_error_to_string (exit_code));
    790848
    791849                /* signal */
    792                 exit_sig = process_signal(hPID);
     850                exit_sig = process_signal (hPID);
    793851
    794852                /* cleanup process */
    795                 process_cleanup(hPID);
     853                process_cleanup (hPID);
    796854
    797855                coredump = 0;
    798856              }
    799             else if (!process_used_slots())
     857            else if (dwWaitStatus == WAIT_FAILED)
    800858              {
    801                 /* The wait*() failed miserably.  Punt.  */
    802                 errno = ECHILD;
    803                 pfatal_with_name ("wait");
     859                /* The WaitForMultipleObjects() failed miserably.  Punt.  */
     860                pfatal_with_name ("WaitForMultipleObjects");
     861              }
     862            else if (dwWaitStatus == WAIT_TIMEOUT)
     863              {
     864                /* No child processes are finished.  Give up waiting. */
     865                reap_more = 0;
     866                break;
    804867              }
    805868
     
    807870          }
    808871#endif /* WINDOWS32 */
    809         }
    810 
    811       /* Check if this is the child of the `shell' function.  */
     872        }
     873
     874      /* Check if this is the child of the 'shell' function.  */
    812875      if (!remote && pid == shell_function_pid)
    813         {
    814           /* It is.  Leave an indicator for the `shell' function.  */
    815           if (exit_sig == 0 && exit_code == 127)
    816             shell_function_completed = -1;
    817           else
    818             shell_function_completed = 1;
    819           break;
    820         }
    821 
    822       child_failed = exit_sig != 0 || exit_code != 0;
     876        {
     877          shell_completed (exit_code, exit_sig);
     878          break;
     879        }
    823880
    824881      /* Search for a child matching the deceased one.  */
    825882      lastc = 0;
    826883      for (c = children; c != 0; lastc = c, c = c->next)
    827         if (c->remote == remote && c->pid == pid)
    828           break;
     884        if (c->pid == pid && c->remote == remote)
     885          break;
    829886
    830887      if (c == 0)
     
    833890        continue;
    834891
     892      /* Determine the failure status: 0 for success, 1 for updating target in
     893         question mode, 2 for anything else.  */
     894      if (exit_sig == 0 && exit_code == 0)
     895        child_failed = MAKE_SUCCESS;
     896      else if (exit_sig == 0 && exit_code == 1 && question_flag && c->recursive)
     897        child_failed = MAKE_TROUBLE;
     898      else
     899        child_failed = MAKE_FAILURE;
     900
    835901      DB (DB_JOBS, (child_failed
    836902                    ? _("Reaping losing child %p PID %s %s\n")
     
    838904                    (void *)c, pid2str (c->pid), c->remote ? _(" (remote)") : ""));
    839905
    840       if (c->sh_batch_file) {
    841         DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
    842                       c->sh_batch_file));
    843 
    844         /* just try and remove, don't care if this fails */
    845         remove (c->sh_batch_file);
    846 
    847         /* all done with memory */
    848         free (c->sh_batch_file);
    849         c->sh_batch_file = NULL;
    850       }
     906      if (c->sh_batch_file)
     907        {
     908          int rm_status;
     909
     910          DB (DB_JOBS, (_("Cleaning up temp batch file %s\n"),
     911                        c->sh_batch_file));
     912
     913          errno = 0;
     914          rm_status = remove (c->sh_batch_file);
     915          if (rm_status)
     916            DB (DB_JOBS, (_("Cleaning up temp batch file %s failed (%d)\n"),
     917                          c->sh_batch_file, errno));
     918
     919          /* all done with memory */
     920          free (c->sh_batch_file);
     921          c->sh_batch_file = NULL;
     922        }
    851923
    852924      /* If this child had the good stdin, say it is now free.  */
     
    862934          static int delete_on_error = -1;
    863935
    864           if (!dontcare)
     936          if (!dontcare && child_failed == MAKE_FAILURE)
    865937#ifdef KMK
    866938            {
    867               child_error (c->file->name, exit_code, exit_sig, coredump, 0);
     939              child_error (c, exit_code, exit_sig, coredump, 0);
    868940              if (   (  c->file->cmds->lines_flags[c->command_line - 1]
    869941                      & (COMMANDS_SILENT | COMMANDS_RECURSE))
     
    873945# endif
    874946                  || exit_sig != 0)
    875                 message (0, "The failing command:\n%s", c->file->cmds->command_lines[c->command_line - 1]);
     947                OS (message, 0, "The failing command:\n%s", c->file->cmds->command_lines[c->command_line - 1]);
    876948            }
    877949#else  /* !KMK */
    878             child_error (c->file->name, exit_code, exit_sig, coredump, 0);
     950            child_error (c, exit_code, exit_sig, coredump, 0);
    879951#endif /* !KMK */
    880952
    881           c->file->update_status = 2;
     953          c->file->update_status = child_failed == MAKE_FAILURE ? us_failed : us_question;
    882954          if (delete_on_error == -1)
    883955            {
     
    893965            {
    894966              /* The commands failed, but we don't care.  */
    895               child_error (c->file->name,
    896                            exit_code, exit_sig, coredump, 1);
     967              child_error (c, exit_code, exit_sig, coredump, 1);
    897968              child_failed = 0;
    898969            }
     
    907978                     the target was not completely remade.  So we treat
    908979                     this as if a command had failed.  */
    909                   c->file->update_status = 2;
     980                  c->file->update_status = us_failed;
    910981                }
    911982              else
    912983                {
     984#ifndef NO_OUTPUT_SYNC
     985                  /* If we're sync'ing per line, write the previous line's
     986                     output before starting the next one.  */
     987                  if (output_sync == OUTPUT_SYNC_LINE)
     988                    output_dump (&c->output);
     989#endif
    913990                  /* Check again whether to start remotely.
    914991                     Whether or not we want to changes over time.
     
    9281005                }
    9291006
    930               if (c->file->update_status != 0)
     1007              if (c->file->update_status != us_success)
    9311008                /* We failed to start the commands.  */
    9321009                delete_child_targets (c);
     
    9361013               without an unignored error.  Now the target has been
    9371014               successfully updated.  */
    938             c->file->update_status = 0;
     1015            c->file->update_status = us_success;
    9391016        }
    9401017
    941       /* When we get here, all the commands for C->file are finished
    942          (or aborted) and C->file->update_status contains 0 or 2.  But
    943          C->file->command_state is still cs_running if all the commands
     1018      /* When we get here, all the commands for c->file are finished.  */
     1019
     1020#ifndef NO_OUTPUT_SYNC
     1021      /* Synchronize any remaining parallel output.  */
     1022      output_dump (&c->output);
     1023#endif
     1024
     1025      /* At this point c->file->update_status is success or failed.  But
     1026         c->file->command_state is still cs_running if all the commands
    9441027         ran; notice_finish_file looks for cs_running to tell it that
    9451028         it's interesting to check the file's modtime again now.  */
     
    9801063          /* fatal_error_signal will die with the right signal.  */
    9811064          !handling_fatal_signal)
    982         die (2);
     1065        die (child_failed);
    9831066
    9841067      /* Only block for one child.  */
     
    9981081  print_job_time (child);
    9991082#endif
     1083  output_close (&child->output);
     1084
    10001085  if (!jobserver_tokens)
    1001     fatal (NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
    1002            (void *)child, child->file->name);
     1086    ONS (fatal, NILF, "INTERNAL: Freeing child %p (%s) but no tokens left!\n",
     1087         child, child->file->name);
    10031088
    10041089  /* If we're using the jobserver and this child is not the only outstanding
    10051090     job, put a token back into the pipe for it.  */
    10061091
    1007   if (job_fds[1] >= 0 && jobserver_tokens > 1)
    1008     {
    1009       char token = '+';
    1010       int r;
    1011 
    1012       /* Write a job token back to the pipe.  */
    1013 
    1014       EINTRLOOP (r, write (job_fds[1], &token, 1));
    1015       if (r != 1)
    1016         pfatal_with_name (_("write jobserver"));
    1017 
     1092  if (jobserver_enabled () && jobserver_tokens > 1)
     1093    {
     1094      jobserver_release (1);
    10181095      DB (DB_JOBS, (_("Released token for child %p (%s).\n"),
    10191096                    (void *)child, child->file->name));
     
    10291106      register unsigned int i;
    10301107      for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
    1031         free (child->command_lines[i]);
     1108        free (child->command_lines[i]);
    10321109      free (child->command_lines);
    10331110    }
     
    10371114      register char **ep = child->environment;
    10381115      while (*ep != 0)
    1039         free (*ep++);
     1116        free (*ep++);
    10401117      free (child->environment);
    10411118    }
     
    10811158#endif
    10821159
    1083 #ifdef MAKE_JOBSERVER
    1084 RETSIGTYPE
    1085 job_noop (int sig UNUSED)
    1086 {
    1087 }
    1088 /* Set the child handler action flags to FLAGS.  */
    1089 static void
    1090 set_child_handler_action_flags (int set_handler, int set_alarm)
    1091 {
    1092   struct sigaction sa;
    1093   int rval = 0;
    1094 
    1095 #if defined(__EMX__) && !defined(__KLIBC__) /* bird */
    1096   /* The child handler must be turned off here.  */
    1097   signal (SIGCHLD, SIG_DFL);
    1098 #endif
    1099 
    1100   memset (&sa, '\0', sizeof sa);
    1101   sa.sa_handler = child_handler;
    1102   sa.sa_flags = set_handler ? 0 : SA_RESTART;
    1103 #if defined SIGCHLD
    1104   rval = sigaction (SIGCHLD, &sa, NULL);
    1105 #endif
    1106 #if defined SIGCLD && SIGCLD != SIGCHLD
    1107   rval = sigaction (SIGCLD, &sa, NULL);
    1108 #endif
    1109   if (rval != 0)
    1110     fprintf (stderr, "sigaction: %s (%d)\n", strerror (errno), errno);
    1111 #if defined SIGALRM
    1112   if (set_alarm)
    1113     {
    1114       /* If we're about to enter the read(), set an alarm to wake up in a
    1115          second so we can check if the load has dropped and we can start more
    1116          work.  On the way out, turn off the alarm and set SIG_DFL.  */
    1117       alarm (set_handler ? 1 : 0);
    1118       sa.sa_handler = set_handler ? job_noop : SIG_DFL;
    1119       sa.sa_flags = 0;
    1120       sigaction (SIGALRM, &sa, NULL);
    1121     }
    1122 #endif
    1123 }
    1124 #endif
    1125 
    1126 
    11271160/* Start a job to run the commands specified in CHILD.
    11281161   CHILD is updated to reflect the commands and ID of the child process.
    11291162
    11301163   NOTE: On return fatal signals are blocked!  The caller is responsible
    1131    for calling `unblock_sigs', once the new child is safely on the chain so
     1164   for calling 'unblock_sigs', once the new child is safely on the chain so
    11321165   it can be cleaned up in the event of a fatal signal.  */
    11331166
     
    11351168start_job_command (struct child *child)
    11361169{
    1137 #if !defined(_AMIGA) && !defined(WINDOWS32)
    1138   static int bad_stdin = -1;
    1139 #endif
     1170  int flags;
    11401171  char *p;
    1141   /* Must be volatile to silence bogus GCC warning about longjmp/vfork.  */
    1142   /*volatile*/ int flags;
    11431172#ifdef VMS
    11441173  char *argv;
     
    11631192     the flags specified globally for this target.  */
    11641193  flags = (child->file->command_flags
    1165            | child->file->cmds->lines_flags[child->command_line - 1]);
     1194           | child->file->cmds->lines_flags[child->command_line - 1]);
    11661195
    11671196  p = child->command_ptr;
     
    11711200    {
    11721201      if (*p == '@')
    1173         flags |= COMMANDS_SILENT;
     1202        flags |= COMMANDS_SILENT;
    11741203      else if (*p == '+')
    1175         flags |= COMMANDS_RECURSE;
     1204        flags |= COMMANDS_RECURSE;
    11761205      else if (*p == '-')
    1177         child->noerror = 1;
     1206        child->noerror = 1;
    11781207#ifdef CONFIG_WITH_COMMANDS_FUNC
    11791208      else if (*p == '%')
    11801209        flags |= COMMAND_GETTER_SKIP_IT;
    11811210#endif
    1182       else if (!isblank ((unsigned char)*p))
     1211      /* Don't skip newlines.  */
     1212      else if (!ISBLANK (*p))
    11831213#ifndef CONFIG_WITH_KMK_BUILTIN
    11841214        break;
     
    11951225    }
    11961226
     1227  child->recursive = ((flags & COMMANDS_RECURSE) != 0);
     1228
    11971229  /* Update the file's command flags with any new ones we found.  We only
    11981230     keep the COMMANDS_RECURSE setting.  Even this isn't 100% correct; we are
     
    12011233     order to really fix this, we'll have to keep a lines_flags for every
    12021234     actual line, after expansion.  */
    1203   child->file->cmds->lines_flags[child->command_line - 1]
    1204     |= flags & COMMANDS_RECURSE;
     1235  child->file->cmds->lines_flags[child->command_line - 1] |= flags & COMMANDS_RECURSE;
     1236
     1237  /* POSIX requires that a recipe prefix after a backslash-newline should
     1238     be ignored.  Remove it now so the output is correct.  */
     1239  {
     1240    char prefix = child->file->cmds->recipe_prefix;
     1241    char *p1, *p2;
     1242    p1 = p2 = p;
     1243    while (*p1 != '\0')
     1244      {
     1245        *(p2++) = *p1;
     1246        if (p1[0] == '\n' && p1[1] == prefix)
     1247          ++p1;
     1248        ++p1;
     1249      }
     1250    *p2 = *p1;
     1251  }
    12051252
    12061253  /* Figure out an argument list from this command line.  */
    1207 
    12081254  {
    12091255    char *end = 0;
    12101256#ifdef VMS
     1257    /* Skip any leading whitespace */
     1258    while (*p)
     1259      {
     1260        if (!ISSPACE (*p))
     1261          {
     1262            if (*p != '\\')
     1263              break;
     1264            if ((p[1] != '\n') && (p[1] != 'n') && (p[1] != 't'))
     1265              break;
     1266          }
     1267        p++;
     1268      }
     1269
    12111270    argv = p;
     1271    /* Although construct_command_argv contains some code for VMS, it was/is
     1272       not called/used.  Please note, for VMS argv is a string (not an array
     1273       of strings) which contains the complete command line, which for
     1274       multi-line variables still includes the newlines.  So detect newlines
     1275       and set 'end' (which is used for child->command_ptr) instead of
     1276       (re-)writing construct_command_argv */
     1277    if (!one_shell)
     1278      {
     1279        char *s = p;
     1280        int instring = 0;
     1281        while (*s)
     1282          {
     1283            if (*s == '"')
     1284              instring = !instring;
     1285            else if (*s == '\\' && !instring && *(s+1) != 0)
     1286              s++;
     1287            else if (*s == '\n' && !instring)
     1288              {
     1289                end = s;
     1290                break;
     1291              }
     1292            ++s;
     1293          }
     1294      }
    12121295#else
    12131296    argv = construct_command_argv (p, &end, child->file,
    1214                                    child->file->cmds->lines_flags[child->command_line - 1],
    1215                                    &child->sh_batch_file);
     1297                                   child->file->cmds->lines_flags[child->command_line - 1],
     1298                                   &child->sh_batch_file);
    12161299#endif
    12171300    if (end == NULL)
     
    12191302    else
    12201303      {
    1221         *end++ = '\0';
    1222         child->command_ptr = end;
     1304        *end++ = '\0';
     1305        child->command_ptr = end;
    12231306      }
    12241307  }
    12251308
    1226   /* If -q was given, say that updating `failed' if there was any text on the
    1227      command line, or `succeeded' otherwise.  The exit status of 1 tells the
    1228      user that -q is saying `something to do'; the exit status for a random
     1309  /* If -q was given, say that updating 'failed' if there was any text on the
     1310     command line, or 'succeeded' otherwise.  The exit status of 1 tells the
     1311     user that -q is saying 'something to do'; the exit status for a random
    12291312     error is 2.  */
    12301313  if (argv != 0 && question_flag && !(flags & COMMANDS_RECURSE))
     
    12341317      free (argv);
    12351318#endif
    1236       child->file->update_status = 1;
    1237       notice_finished_file (child->file);
    1238       return;
     1319#ifdef VMS
     1320      /* On VMS, argv[0] can be a null string here */
     1321      if (argv[0] != 0)
     1322        {
     1323#endif
     1324          child->file->update_status = us_question;
     1325          notice_finished_file (child->file);
     1326          return;
     1327#ifdef VMS
     1328        }
     1329#endif
    12391330    }
    12401331
     
    12421333    {
    12431334      /* Go on to the next command.  It might be the recursive one.
    1244         We construct ARGV only to find the end of the command line.  */
     1335        We construct ARGV only to find the end of the command line.  */
    12451336#ifndef VMS
    12461337      if (argv)
     
    12611352      /* This line has no commands.  Go to the next.  */
    12621353      if (job_next_command (child))
    1263         start_job_command (child);
     1354        start_job_command (child);
    12641355      else
    1265         {
    1266           /* No more commands.  Make sure we're "running"; we might not be if
     1356        {
     1357          /* No more commands.  Make sure we're "running"; we might not be if
    12671358             (e.g.) all commands were skipped due to -n.  */
    12681359          set_command_state (child->file, cs_running);
    1269           child->file->update_status = 0;
    1270           notice_finished_file (child->file);
    1271         }
     1360          child->file->update_status = us_success;
     1361          notice_finished_file (child->file);
     1362        }
     1363
     1364      OUTPUT_UNSET();
    12721365      return;
    12731366    }
    12741367
    1275   /* Print out the command.  If silent, we call `message' with null so it
    1276      can log the working directory before the command's own error messages
    1277      appear.  */
     1368  /* Are we going to synchronize this command's output?  Do so if either we're
     1369     in SYNC_RECURSE mode or this command is not recursive.  We'll also check
     1370     output_sync separately below in case it changes due to error.  */
     1371  child->output.syncout = output_sync && (output_sync == OUTPUT_SYNC_RECURSE
     1372                                          || !(flags & COMMANDS_RECURSE));
     1373  OUTPUT_SET (&child->output);
     1374
     1375#ifndef NO_OUTPUT_SYNC
     1376  if (! child->output.syncout)
     1377    /* We don't want to sync this command: to avoid misordered
     1378       output ensure any already-synced content is written.  */
     1379    output_dump (&child->output);
     1380#endif
     1381
     1382  /* Print the command if appropriate.  */
    12781383#ifdef CONFIG_PRETTY_COMMAND_PRINTING
    12791384  if (   pretty_command_printing
     
    12831388      unsigned i;
    12841389      for (i = 0; argv[i]; i++)
    1285         message (0, "%s'%s'%s", i ? "\t" : "> ", argv[i], argv[i + 1] ? " \\" : "");
     1390        OSSS ( message, 0, "%s'%s'%s", i ? "\t" : "> ", argv[i], argv[i + 1] ? " \\" : "");
    12861391    }
    12871392  else
    12881393#endif /* CONFIG_PRETTY_COMMAND_PRINTING */
    1289     message (0, (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
    1290              ? "%s" : (char *) 0, p);
     1394  if (just_print_flag || trace_flag
     1395      || (!(flags & COMMANDS_SILENT) && !silent_flag))
     1396    OS (message, 0, "%s", p);
    12911397
    12921398  /* Tell update_goal_chain that a command has been started on behalf of
     
    13081414  if (
    13091415#if defined __MSDOS__ || defined (__EMX__)
    1310       unixy_shell       /* the test is complicated and we already did it */
     1416      unixy_shell       /* the test is complicated and we already did it */
    13111417#else
    1312       (argv[0] && is_bourne_compatible_shell(argv[0]))
     1418      (argv[0] && is_bourne_compatible_shell (argv[0]))
    13131419#endif
    13141420      && (argv[1] && argv[1][0] == '-'
    1315         &&
    1316             ((argv[1][1] == 'c' && argv[1][2] == '\0')
    1317           ||
    1318              (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
     1421        &&
     1422            ((argv[1][1] == 'c' && argv[1][2] == '\0')
     1423          ||
     1424             (argv[1][1] == 'e' && argv[1][2] == 'c' && argv[1][3] == '\0')))
    13191425      && (argv[2] && argv[2][0] == ':' && argv[2][1] == '\0')
    13201426      && argv[3] == NULL)
     
    13951501#endif /* CONFIG_WITH_KMK_BUILTIN */
    13961502
     1503  /* We're sure we're going to invoke a command: set up the output.  */
     1504  output_start ();
     1505
    13971506  /* Flush the output streams so they won't have things written twice.  */
    13981507
     
    14001509  fflush (stderr);
    14011510
    1402 #ifndef VMS
    1403 #if !defined(WINDOWS32) && !defined(_AMIGA) && !defined(__MSDOS__)
    1404 
    1405   /* Set up a bad standard input that reads from a broken pipe.  */
    1406 
    1407   if (bad_stdin == -1)
    1408     {
    1409       /* Make a file descriptor that is the read end of a broken pipe.
    1410          This will be used for some children's standard inputs.  */
    1411       int pd[2];
    1412       if (pipe (pd) == 0)
    1413         {
    1414           /* Close the write side.  */
    1415           (void) close (pd[1]);
    1416           /* Save the read side.  */
    1417           bad_stdin = pd[0];
    1418 
    1419           /* Set the descriptor to close on exec, so it does not litter any
    1420              child's descriptor table.  When it is dup2'd onto descriptor 0,
    1421              that descriptor will not close on exec.  */
    1422           CLOSE_ON_EXEC (bad_stdin);
    1423         }
    1424     }
    1425 
    1426 #endif /* !WINDOWS32 && !_AMIGA && !__MSDOS__ */
    1427 
    1428   /* Decide whether to give this child the `good' standard input
    1429      (one that points to the terminal or whatever), or the `bad' one
     1511  /* Decide whether to give this child the 'good' standard input
     1512     (one that points to the terminal or whatever), or the 'bad' one
    14301513     that points to the read side of a broken pipe.  */
    14311514
     
    14331516  if (child->good_stdin)
    14341517    good_stdin_used = 1;
    1435 
    1436 #endif /* !VMS */
    14371518
    14381519  child->deleted = 0;
     
    14521533      int is_remote, id, used_stdin;
    14531534      if (start_remote_job (argv, child->environment,
    1454                             child->good_stdin ? 0 : bad_stdin,
    1455                             &is_remote, &id, &used_stdin))
     1535                            child->good_stdin ? 0 : get_bad_stdin (),
     1536                            &is_remote, &id, &used_stdin))
    14561537        /* Don't give up; remote execution may fail for various reasons.  If
    14571538           so, simply run the job locally.  */
    1458         goto run_local;
     1539        goto run_local;
    14591540      else
    1460         {
    1461           if (child->good_stdin && !used_stdin)
    1462             {
    1463               child->good_stdin = 0;
    1464               good_stdin_used = 0;
    1465             }
    1466           child->remote = is_remote;
    1467           child->pid = id;
    1468         }
     1541        {
     1542          if (child->good_stdin && !used_stdin)
     1543            {
     1544              child->good_stdin = 0;
     1545              good_stdin_used = 0;
     1546            }
     1547          child->remote = is_remote;
     1548          child->pid = id;
     1549        }
    14691550    }
    14701551  else
     
    14811562
    14821563#ifdef VMS
    1483       if (!child_execute_job (argv, child)) {
    1484         /* Fork failed!  */
    1485         perror_with_name ("vfork", "");
    1486         goto error;
    1487       }
     1564      if (!child_execute_job (child, argv))
     1565        {
     1566          /* Fork failed!  */
     1567          perror_with_name ("fork", "");
     1568          goto error;
     1569        }
    14881570
    14891571#else
     
    14911573      parent_environ = environ;
    14921574
    1493 # ifdef __EMX__
    1494       /* If we aren't running a recursive command and we have a jobserver
    1495          pipe, close it before exec'ing.  */
    1496       if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1497         {
    1498           CLOSE_ON_EXEC (job_fds[0]);
    1499           CLOSE_ON_EXEC (job_fds[1]);
    1500         }
    1501       if (job_rfd >= 0)
    1502         CLOSE_ON_EXEC (job_rfd);
    1503 
    1504       /* Never use fork()/exec() here! Use spawn() instead in exec_command() */
    1505       child->pid = child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
    1506                                       argv, child->environment);
     1575      jobserver_pre_child (flags & COMMANDS_RECURSE);
     1576
     1577      child->pid = child_execute_job (&child->output, child->good_stdin, argv, child->environment);
     1578
     1579      environ = parent_environ; /* Restore value child may have clobbered.  */
     1580      jobserver_post_child (flags & COMMANDS_RECURSE);
     1581
    15071582      if (child->pid < 0)
    1508         {
    1509           /* spawn failed!  */
    1510           unblock_sigs ();
    1511           perror_with_name ("spawn", "");
    1512           goto error;
    1513         }
    1514 
    1515       /* undo CLOSE_ON_EXEC() after the child process has been started */
    1516       if (!(flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1517         {
    1518           fcntl (job_fds[0], F_SETFD, 0);
    1519           fcntl (job_fds[1], F_SETFD, 0);
    1520         }
    1521       if (job_rfd >= 0)
    1522         fcntl (job_rfd, F_SETFD, 0);
    1523 
    1524 #else  /* !__EMX__ */
    1525       volatile_argv  = argv;            /* shut up gcc */
    1526       volatile_flags = flags;           /* ditto */
    1527 
    1528       child->pid = vfork ();
    1529       environ = parent_environ; /* Restore value child may have clobbered.  */
    1530       argv = volatile_argv;             /* shut up gcc */
    1531       if (child->pid == 0)
    1532         {
    1533           /* We are the child side.  */
    1534           unblock_sigs ();
    1535 
    1536           /* If we aren't running a recursive command and we have a jobserver
    1537              pipe, close it before exec'ing.  */
    1538           if (!(volatile_flags & COMMANDS_RECURSE) && job_fds[0] >= 0)
    1539             {
    1540               close (job_fds[0]);
    1541               close (job_fds[1]);
    1542             }
    1543           if (job_rfd >= 0)
    1544             close (job_rfd);
    1545 
    1546 #ifdef SET_STACK_SIZE
    1547           /* Reset limits, if necessary.  */
    1548           if (stack_limit.rlim_cur)
    1549             setrlimit (RLIMIT_STACK, &stack_limit);
    1550 #endif
    1551 
    1552           child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
    1553                              argv, child->environment);
    1554         }
    1555       else if (child->pid < 0)
    1556         {
    1557           /* Fork failed!  */
    1558           unblock_sigs ();
    1559           perror_with_name ("vfork", "");
    1560           goto error;
    1561         }
    1562 # endif  /* !__EMX__ */
     1583        {
     1584          /* Fork failed!  */
     1585          unblock_sigs ();
     1586          perror_with_name ("fork", "");
     1587          goto error;
     1588        }
    15631589#endif /* !VMS */
    15641590    }
    15651591
    1566 #else   /* __MSDOS__ or Amiga or WINDOWS32 */
     1592#else   /* __MSDOS__ or Amiga or WINDOWS32 */
    15671593#ifdef __MSDOS__
    15681594  {
     
    15721598    dos_status = 0;
    15731599
    1574     /* We call `system' to do the job of the SHELL, since stock DOS
    1575        shell is too dumb.  Our `system' knows how to handle long
     1600    /* We call 'system' to do the job of the SHELL, since stock DOS
     1601       shell is too dumb.  Our 'system' knows how to handle long
    15761602       command lines even if pipes/redirection is needed; it will only
    15771603       call COMMAND.COM when its internal commands are used.  */
    15781604    if (execute_by_shell)
    15791605      {
    1580         char *cmdline = argv[0];
    1581         /* We don't have a way to pass environment to `system',
    1582            so we need to save and restore ours, sigh...  */
    1583         char **parent_environ = environ;
    1584 
    1585         environ = child->environment;
    1586 
    1587         /* If we have a *real* shell, tell `system' to call
    1588            it to do everything for us.  */
    1589         if (unixy_shell)
    1590           {
    1591             /* A *real* shell on MSDOS may not support long
    1592                command lines the DJGPP way, so we must use `system'.  */
    1593             cmdline = argv[2];  /* get past "shell -c" */
    1594           }
    1595 
    1596         dos_command_running = 1;
    1597         proc_return = system (cmdline);
    1598         environ = parent_environ;
    1599         execute_by_shell = 0;   /* for the next time */
     1606        char *cmdline = argv[0];
     1607        /* We don't have a way to pass environment to 'system',
     1608           so we need to save and restore ours, sigh...  */
     1609        char **parent_environ = environ;
     1610
     1611        environ = child->environment;
     1612
     1613        /* If we have a *real* shell, tell 'system' to call
     1614           it to do everything for us.  */
     1615        if (unixy_shell)
     1616          {
     1617            /* A *real* shell on MSDOS may not support long
     1618               command lines the DJGPP way, so we must use 'system'.  */
     1619            cmdline = argv[2];  /* get past "shell -c" */
     1620          }
     1621
     1622        dos_command_running = 1;
     1623        proc_return = system (cmdline);
     1624        environ = parent_environ;
     1625        execute_by_shell = 0;   /* for the next time */
    16001626      }
    16011627    else
    16021628      {
    1603         dos_command_running = 1;
    1604         proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
     1629        dos_command_running = 1;
     1630        proc_return = spawnvpe (P_WAIT, argv[0], argv, child->environment);
    16051631      }
    16061632
     
    16311657     DeleteFile (amiga_bname);        /* Ignore errors.  */
    16321658  }
    1633 #endif  /* Amiga */
     1659#endif  /* Amiga */
    16341660#ifdef WINDOWS32
    16351661  {
    16361662      HANDLE hPID;
    16371663      char* arg0;
     1664      int outfd = FD_STDOUT;
     1665      int errfd = FD_STDERR;
    16381666
    16391667      /* make UNC paths safe for CreateProcess -- backslash format */
     
    16451673
    16461674      /* make sure CreateProcess() has Path it needs */
    1647       sync_Path_environment();
    1648 
    1649       hPID = process_easy(argv, child->environment);
     1675      sync_Path_environment ();
     1676
     1677#ifndef NO_OUTPUT_SYNC
     1678      /* Divert child output if output_sync in use.  */
     1679      if (child->output.syncout)
     1680        {
     1681          if (child->output.out >= 0)
     1682            outfd = child->output.out;
     1683          if (child->output.err >= 0)
     1684            errfd = child->output.err;
     1685        }
     1686#else
     1687      outfd = errfd = -1;
     1688#endif
     1689      hPID = process_easy (argv, child->environment, outfd, errfd);
    16501690
    16511691      if (hPID != INVALID_HANDLE_VALUE)
    16521692        child->pid = (pid_t) hPID;
    1653       else {
    1654         int i;
    1655         unblock_sigs();
    1656         fprintf(stderr,
    1657                 _("process_easy() failed to launch process (e=%ld)\n"),
    1658                 process_last_err(hPID));
    1659         for (i = 0; argv[i]; i++)
    1660           fprintf(stderr, "%s ", argv[i]);
    1661         fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
    1662         goto error;
    1663       }
     1693      else
     1694        {
     1695          int i;
     1696          unblock_sigs ();
     1697          fprintf (stderr,
     1698                   _("process_easy() failed to launch process (e=%ld)\n"),
     1699                   process_last_err (hPID));
     1700          for (i = 0; argv[i]; i++)
     1701            fprintf (stderr, "%s ", argv[i]);
     1702          fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
     1703          goto error;
     1704        }
    16641705  }
    16651706#endif /* WINDOWS32 */
    1666 #endif  /* __MSDOS__ or Amiga or WINDOWS32 */
     1707#endif  /* __MSDOS__ or Amiga or WINDOWS32 */
    16671708
    16681709  /* Bump the number of jobs started in this second.  */
     
    16831724#endif
    16841725
     1726  OUTPUT_UNSET();
    16851727  return;
    16861728
    16871729 error:
    1688   child->file->update_status = 2;
     1730  child->file->update_status = us_failed;
    16891731  notice_finished_file (child->file);
    16901732#ifdef KMK /* fix leak */
    16911733  goto cleanup_argv;
    16921734#else
    1693   return;
     1735  OUTPUT_UNSET();
    16941736#endif
    16951737}
     
    16971739/* Try to start a child running.
    16981740   Returns nonzero if the child was started (and maybe finished), or zero if
    1699    the load was too high and the child was put on the `waiting_jobs' chain.  */
     1741   the load was too high and the child was put on the 'waiting_jobs' chain.  */
    17001742
    17011743static int
     
    17331775#endif
    17341776#ifdef WINDOWS32
    1735           || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
    1736 #endif
    1737           ))
     1777          || (process_used_slots () >= MAXIMUM_WAIT_OBJECTS)
     1778#endif
     1779          ))
    17381780    {
    17391781#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
     
    17831825    case cs_not_started:
    17841826      /* All the command lines turned out to be empty.  */
    1785       f->update_status = 0;
     1827      f->update_status = us_success;
    17861828      /* FALLTHROUGH */
    17871829
     
    17991841}
    18001842
    1801 /* Create a `struct child' for FILE and start its commands running.  */
     1843/* Create a 'struct child' for FILE and start its commands running.  */
    18021844
    18031845void
     
    18221864#endif
    18231865
     1866  /* Start the command sequence, record it in a new
     1867     'struct child', and add that to the chain.  */
     1868
     1869  c = xcalloc (sizeof (struct child));
     1870  output_init (&c->output);
     1871
     1872  c->file = file;
     1873  c->sh_batch_file = NULL;
     1874
     1875  /* Cache dontcare flag because file->dontcare can be changed once we
     1876     return. Check dontcare inheritance mechanism for details.  */
     1877  c->dontcare = file->dontcare;
     1878
     1879  /* Start saving output in case the expansion uses $(info ...) etc.  */
     1880  OUTPUT_SET (&c->output);
     1881
    18241882  /* Expand the command lines and store the results in LINES.  */
    18251883  lines = xmalloc (cmds->ncommand_lines * sizeof (char *));
     
    18271885    {
    18281886      /* Collapse backslash-newline combinations that are inside variable
    1829         or function references.  These are left alone by the parser so
    1830         that they will appear in the echoing of commands (where they look
    1831         nice); and collapsed by construct_command_argv when it tokenizes.
    1832         But letting them survive inside function invocations loses because
    1833         we don't want the functions to see them as part of the text.  */
     1887        or function references.  These are left alone by the parser so
     1888        that they will appear in the echoing of commands (where they look
     1889        nice); and collapsed by construct_command_argv when it tokenizes.
     1890        But letting them survive inside function invocations loses because
     1891        we don't want the functions to see them as part of the text.  */
    18341892
    18351893      char *in, *out, *ref;
    18361894
    18371895      /* IN points to where in the line we are scanning.
    1838         OUT points to where in the line we are writing.
    1839         When we collapse a backslash-newline combination,
    1840         IN gets ahead of OUT.  */
     1896        OUT points to where in the line we are writing.
     1897        When we collapse a backslash-newline combination,
     1898        IN gets ahead of OUT.  */
    18411899
    18421900      in = out = cmds->command_lines[i];
    18431901      while ((ref = strchr (in, '$')) != 0)
    1844         {
    1845           ++ref;                /* Move past the $.  */
    1846 
    1847           if (out != in)
    1848             /* Copy the text between the end of the last chunk
    1849                we processed (where IN points) and the new chunk
    1850                we are about to process (where REF points).  */
    1851             memmove (out, in, ref - in);
    1852 
    1853           /* Move both pointers past the boring stuff.  */
    1854           out += ref - in;
    1855           in = ref;
    1856 
    1857           if (*ref == '(' || *ref == '{')
    1858             {
    1859               char openparen = *ref;
    1860               char closeparen = openparen == '(' ? ')' : '}';
    1861               int count;
    1862               char *p;
    1863 
    1864               *out++ = *in++;   /* Copy OPENPAREN.  */
    1865               /* IN now points past the opening paren or brace.
    1866                  Count parens or braces until it is matched.  */
    1867               count = 0;
    1868               while (*in != '\0')
    1869                 {
    1870                   if (*in == closeparen && --count < 0)
    1871                     break;
    1872                   else if (*in == '\\' && in[1] == '\n')
    1873                     {
    1874                       /* We have found a backslash-newline inside a
    1875                          variable or function reference.  Eat it and
    1876                          any following whitespace.  */
    1877 
    1878                       int quoted = 0;
    1879                       for (p = in - 1; p > ref && *p == '\\'; --p)
    1880                         quoted = !quoted;
    1881 
    1882                       if (quoted)
    1883                         /* There were two or more backslashes, so this is
    1884                            not really a continuation line.  We don't collapse
    1885                            the quoting backslashes here as is done in
    1886                            collapse_continuations, because the line will
    1887                            be collapsed again after expansion.  */
    1888                         *out++ = *in++;
    1889                       else
    1890                         {
    1891                           /* Skip the backslash, newline and
    1892                              any following whitespace.  */
    1893                           in = next_token (in + 2);
    1894 
    1895                           /* Discard any preceding whitespace that has
    1896                              already been written to the output.  */
    1897                           while (out > ref
    1898                                  && isblank ((unsigned char)out[-1]))
    1899                             --out;
    1900 
    1901                           /* Replace it all with a single space.  */
    1902                           *out++ = ' ';
    1903                         }
    1904                     }
    1905                   else
    1906                     {
    1907                       if (*in == openparen)
    1908                         ++count;
    1909 
    1910                       *out++ = *in++;
    1911                     }
    1912                 }
    1913             }
    1914         }
     1902        {
     1903          ++ref;                /* Move past the $.  */
     1904
     1905          if (out != in)
     1906            /* Copy the text between the end of the last chunk
     1907               we processed (where IN points) and the new chunk
     1908               we are about to process (where REF points).  */
     1909            memmove (out, in, ref - in);
     1910
     1911          /* Move both pointers past the boring stuff.  */
     1912          out += ref - in;
     1913          in = ref;
     1914
     1915          if (*ref == '(' || *ref == '{')
     1916            {
     1917              char openparen = *ref;
     1918              char closeparen = openparen == '(' ? ')' : '}';
     1919              char *outref;
     1920              int count;
     1921              char *p;
     1922
     1923              *out++ = *in++;   /* Copy OPENPAREN.  */
     1924              outref = out;
     1925              /* IN now points past the opening paren or brace.
     1926                 Count parens or braces until it is matched.  */
     1927              count = 0;
     1928              while (*in != '\0')
     1929                {
     1930                  if (*in == closeparen && --count < 0)
     1931                    break;
     1932                  else if (*in == '\\' && in[1] == '\n')
     1933                    {
     1934                      /* We have found a backslash-newline inside a
     1935                         variable or function reference.  Eat it and
     1936                         any following whitespace.  */
     1937
     1938                      int quoted = 0;
     1939                      for (p = in - 1; p > ref && *p == '\\'; --p)
     1940                        quoted = !quoted;
     1941
     1942                      if (quoted)
     1943                        /* There were two or more backslashes, so this is
     1944                           not really a continuation line.  We don't collapse
     1945                           the quoting backslashes here as is done in
     1946                           collapse_continuations, because the line will
     1947                           be collapsed again after expansion.  */
     1948                        *out++ = *in++;
     1949                      else
     1950                        {
     1951                          /* Skip the backslash, newline, and whitespace.  */
     1952                          in += 2;
     1953                          NEXT_TOKEN (in);
     1954
     1955                          /* Discard any preceding whitespace that has
     1956                             already been written to the output.  */
     1957                          while (out > outref && ISBLANK (out[-1]))
     1958                            --out;
     1959
     1960                          /* Replace it all with a single space.  */
     1961                          *out++ = ' ';
     1962                        }
     1963                    }
     1964                  else
     1965                    {
     1966                      if (*in == openparen)
     1967                        ++count;
     1968
     1969                      *out++ = *in++;
     1970                    }
     1971                }
     1972            }
     1973        }
    19151974
    19161975      /* There are no more references in this line to worry about.
    1917         Copy the remaining uninteresting text to the output.  */
     1976        Copy the remaining uninteresting text to the output.  */
    19181977      if (out != in)
    1919         memmove (out, in, strlen (in) + 1);
     1978        memmove (out, in, strlen (in) + 1);
    19201979
    19211980      /* Finally, expand the line.  */
     1981      cmds->fileinfo.offset = i;
    19221982      lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
    1923                                                      file);
    1924     }
    1925 
    1926   /* Start the command sequence, record it in a new
    1927      `struct child', and add that to the chain.  */
    1928 
    1929   c = xcalloc (sizeof (struct child));
    1930   c->file = file;
     1983                                                     file);
     1984    }
     1985
     1986  cmds->fileinfo.offset = 0;
    19311987  c->command_lines = lines;
    1932   c->sh_batch_file = NULL;
    19331988#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
    19341989  c->start_ts = -1;
    19351990#endif
    1936 
    1937   /* Cache dontcare flag because file->dontcare can be changed once we
    1938      return. Check dontcare inheritance mechanism for details.  */
    1939   c->dontcare = file->dontcare;
    19401991
    19411992  /* Fetch the first command line to be run.  */
     
    19622013     this is where the old parallel job code waits, so...  */
    19632014
    1964   else if (job_fds[0] >= 0)
     2015  else if (jobserver_enabled ())
    19652016    while (1)
    19662017      {
    1967         char token;
    1968         int got_token;
    1969         int saved_errno;
     2018        int got_token;
    19702019
    19712020        DB (DB_JOBS, ("Need a job token; we %shave children\n",
     
    19762025          break;
    19772026
    1978         /* Read a token.  As long as there's no token available we'll block.
    1979            We enable interruptible system calls before the read(2) so that if
    1980            we get a SIGCHLD while we're waiting, we'll return with EINTR and
    1981            we can process the death(s) and return tokens to the free pool.
    1982 
    1983            Once we return from the read, we immediately reinstate restartable
    1984            system calls.  This allows us to not worry about checking for
    1985            EINTR on all the other system calls in the program.
    1986 
    1987            There is one other twist: there is a span between the time
    1988            reap_children() does its last check for dead children and the time
    1989            the read(2) call is entered, below, where if a child dies we won't
    1990            notice.  This is extremely serious as it could cause us to
    1991            deadlock, given the right set of events.
    1992 
    1993            To avoid this, we do the following: before we reap_children(), we
    1994            dup(2) the read FD on the jobserver pipe.  The read(2) call below
    1995            uses that new FD.  In the signal handler, we close that FD.  That
    1996            way, if a child dies during the section mentioned above, the
    1997            read(2) will be invoked with an invalid FD and will return
    1998            immediately with EBADF.  */
    1999 
    2000         /* Make sure we have a dup'd FD.  */
    2001         if (job_rfd < 0)
    2002           {
    2003             DB (DB_JOBS, ("Duplicate the job FD\n"));
    2004             job_rfd = dup (job_fds[0]);
    2005           }
     2027        /* Prepare for jobserver token acquisition.  */
     2028        jobserver_pre_acquire ();
    20062029
    20072030        /* Reap anything that's currently waiting.  */
     
    20092032
    20102033        /* Kick off any jobs we have waiting for an opportunity that
    2011            can run now (ie waiting for load). */
     2034           can run now (i.e., waiting for load). */
    20122035        start_waiting_jobs ();
    20132036
    2014         /* If our "free" slot has become available, use it; we don't need an
    2015            actual token.  */
     2037        /* If our "free" slot is available, use it; we don't need a token.  */
    20162038        if (!jobserver_tokens)
    20172039          break;
     
    20202042           waiting for a token. */
    20212043        if (!children)
    2022           fatal (NILF, "INTERNAL: no children as we go to sleep on read\n");
    2023 
    2024         /* Set interruptible system calls, and read() for a job token.  */
    2025         set_child_handler_action_flags (1, waiting_jobs != NULL);
    2026         got_token = read (job_rfd, &token, 1);
    2027         saved_errno = errno;
    2028         set_child_handler_action_flags (0, waiting_jobs != NULL);
     2044          O (fatal, NILF, "INTERNAL: no children as we go to sleep on read\n");
     2045
     2046        /* Get a token.  */
     2047        got_token = jobserver_acquire (waiting_jobs != NULL);
    20292048
    20302049        /* If we got one, we're done here.  */
    2031         if (got_token == 1)
     2050        if (got_token == 1)
    20322051          {
    20332052            DB (DB_JOBS, (_("Obtained token for child %p (%s).\n"),
     
    20352054            break;
    20362055          }
    2037 
    2038         /* If the error _wasn't_ expected (EINTR or EBADF), punt.  Otherwise,
    2039            go back and reap_children(), and try again.  */
    2040         errno = saved_errno;
    2041         if (errno != EINTR && errno != EBADF)
    2042           pfatal_with_name (_("read jobs pipe"));
    2043         if (errno == EBADF)
    2044           DB (DB_JOBS, ("Read returned EBADF.\n"));
    20452056      }
    20462057#endif
    20472058
    20482059  ++jobserver_tokens;
     2060
     2061  /* Trace the build.
     2062     Use message here so that changes to working directories are logged.  */
     2063  if (trace_flag)
     2064    {
     2065      char *newer = allocated_variable_expand_for_file ("$?", c->file);
     2066      const char *nm;
     2067
     2068      if (! cmds->fileinfo.filenm)
     2069        nm = _("<builtin>");
     2070      else
     2071        {
     2072          char *n = alloca (strlen (cmds->fileinfo.filenm) + 1 + 11 + 1);
     2073          sprintf (n, "%s:%lu", cmds->fileinfo.filenm, cmds->fileinfo.lineno);
     2074          nm = n;
     2075        }
     2076
     2077      if (newer[0] == '\0')
     2078        OSS (message, 0,
     2079             _("%s: target '%s' does not exist"), nm, c->file->name);
     2080      else
     2081        OSSS (message, 0,
     2082              _("%s: update target '%s' due to: %s"), nm, c->file->name, newer);
     2083
     2084      free (newer);
     2085    }
    20492086
    20502087  /* The job is now primed.  Start it running.
    20512088     (This will notice if there is in fact no recipe.)  */
    2052   if (cmds->fileinfo.filenm)
    2053     DB (DB_BASIC, (_("Invoking recipe from %s:%lu to update target `%s'.\n"),
    2054                    cmds->fileinfo.filenm, cmds->fileinfo.lineno,
    2055                    c->file->name));
    2056   else
    2057     DB (DB_BASIC, (_("Invoking builtin recipe to update target `%s'.\n"),
    2058                    c->file->name));
    2059 
    2060 
    20612089  start_waiting_job (c);
    20622090
     
    20642092  if (job_slots == 1 || not_parallel)
    20652093    /* Since there is only one job slot, make things run linearly.
    2066        Wait for the child to die, setting the state to `cs_finished'.  */
     2094       Wait for the child to die, setting the state to 'cs_finished'.  */
    20672095    while (file->command_state == cs_running)
    20682096      reap_children (1, 0);
     
    20882116#endif /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
    20892117
     2118  OUTPUT_UNSET ();
    20902119  return;
    20912120}
     
    21022131      /* There are no more lines in the expansion of this line.  */
    21032132      if (child->command_line == child->file->cmds->ncommand_lines)
    2104         {
    2105           /* There are no more lines to be expanded.  */
    2106           child->command_ptr = 0;
    2107           return 0;
    2108         }
     2133        {
     2134          /* There are no more lines to be expanded.  */
     2135          child->command_ptr = 0;
     2136          child->file->cmds->fileinfo.offset = 0;
     2137          return 0;
     2138        }
    21092139      else
    2110         /* Get the next line to run.  */
    2111         child->command_ptr = child->command_lines[child->command_line++];
    2112     }
     2140        /* Get the next line to run.  */
     2141        child->command_ptr = child->command_lines[child->command_line++];
     2142    }
     2143
     2144  child->file->cmds->fileinfo.offset = child->command_line - 1;
    21132145  return 1;
    21142146}
     
    21812213      /* Complain only once for the same error.  */
    21822214      if (lossage == -1 || errno != lossage)
    2183         {
    2184           if (errno == 0)
    2185             /* An errno value of zero means getloadavg is just unsupported.  */
    2186             error (NILF,
    2187                    _("cannot enforce load limits on this operating system"));
    2188           else
    2189             perror_with_name (_("cannot enforce load limit: "), "getloadavg");
    2190         }
     2215        {
     2216          if (errno == 0)
     2217            /* An errno value of zero means getloadavg is just unsupported.  */
     2218            O (error, NILF,
     2219               _("cannot enforce load limits on this operating system"));
     2220          else
     2221            perror_with_name (_("cannot enforce load limit: "), "getloadavg");
     2222        }
    21912223      lossage = errno;
    21922224      load = 0;
     
    22512283
    22522284      /* Try to start that job.  We break out of the loop as soon
    2253         as start_waiting_job puts one back on the waiting list.  */
     2285        as start_waiting_job puts one back on the waiting list.  */
    22542286    }
    22552287  while (start_waiting_job (job) && waiting_jobs != 0);
     
    22642296# if defined __EMX__
    22652297int
    2266 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
     2298child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
    22672299{
    22682300  int pid;
    2269   /* stdin_fd == 0 means: nothing to do for stdin;
    2270      stdout_fd == 1 means: nothing to do for stdout */
    2271   int save_stdin = (stdin_fd != 0) ? dup (0) : 0;
    2272   int save_stdout = (stdout_fd != 1) ? dup (1): 1;
    2273 
    2274   /* < 0 only if dup() failed */
    2275   if (save_stdin < 0)
    2276     fatal (NILF, _("no more file handles: could not duplicate stdin\n"));
    2277   if (save_stdout < 0)
    2278     fatal (NILF, _("no more file handles: could not duplicate stdout\n"));
    2279 
    2280   /* Close unnecessary file handles for the child.  */
    2281   if (save_stdin != 0)
    2282     CLOSE_ON_EXEC (save_stdin);
    2283   if (save_stdout != 1)
    2284     CLOSE_ON_EXEC (save_stdout);
    2285 
    2286   /* Connect the pipes to the child process.  */
    2287   if (stdin_fd != 0)
    2288     (void) dup2 (stdin_fd, 0);
    2289   if (stdout_fd != 1)
    2290     (void) dup2 (stdout_fd, 1);
    2291 
    2292   /* stdin_fd and stdout_fd must be closed on exit because we are
    2293      still in the parent process */
    2294   if (stdin_fd != 0)
    2295     CLOSE_ON_EXEC (stdin_fd);
    2296   if (stdout_fd != 1)
    2297     CLOSE_ON_EXEC (stdout_fd);
     2301  int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
     2302  int fdout = FD_STDOUT;
     2303  int fderr = FD_STDERR;
     2304  int save_fdin = -1;
     2305  int save_fdout = -1;
     2306  int save_fderr = -1;
     2307
     2308  /* Divert child output if we want to capture output.  */
     2309  if (out && out->syncout)
     2310    {
     2311      if (out->out >= 0)
     2312        fdout = out->out;
     2313      if (out->err >= 0)
     2314        fderr = out->err;
     2315    }
     2316
     2317  /* For each FD which needs to be redirected first make a dup of the standard
     2318     FD to save and mark it close on exec so our child won't see it.  Then
     2319     dup2() the standard FD to the redirect FD, and also mark the redirect FD
     2320     as close on exec. */
     2321  if (fdin != FD_STDIN)
     2322    {
     2323      save_fdin = dup (FD_STDIN);
     2324      if (save_fdin < 0)
     2325        O (fatal, NILF, _("no more file handles: could not duplicate stdin\n"));
     2326      CLOSE_ON_EXEC (save_fdin);
     2327
     2328      dup2 (fdin, FD_STDIN);
     2329      CLOSE_ON_EXEC (fdin);
     2330    }
     2331
     2332  if (fdout != FD_STDOUT)
     2333    {
     2334      save_fdout = dup (FD_STDOUT);
     2335      if (save_fdout < 0)
     2336        O (fatal, NILF,
     2337           _("no more file handles: could not duplicate stdout\n"));
     2338      CLOSE_ON_EXEC (save_fdout);
     2339
     2340      dup2 (fdout, FD_STDOUT);
     2341      CLOSE_ON_EXEC (fdout);
     2342    }
     2343
     2344  if (fderr != FD_STDERR)
     2345    {
     2346      if (fderr != fdout)
     2347        {
     2348          save_fderr = dup (FD_STDERR);
     2349          if (save_fderr < 0)
     2350            O (fatal, NILF,
     2351               _("no more file handles: could not duplicate stderr\n"));
     2352          CLOSE_ON_EXEC (save_fderr);
     2353        }
     2354
     2355      dup2 (fderr, FD_STDERR);
     2356      CLOSE_ON_EXEC (fderr);
     2357    }
    22982358
    22992359  /* Run the command.  */
    23002360  pid = exec_command (argv, envp);
    23012361
    2302   /* Restore stdout/stdin of the parent and close temporary FDs.  */
    2303   if (stdin_fd != 0)
    2304     {
    2305       if (dup2 (save_stdin, 0) != 0)
    2306         fatal (NILF, _("Could not restore stdin\n"));
     2362  /* Restore stdout/stdin/stderr of the parent and close temporary FDs.  */
     2363  if (save_fdin >= 0)
     2364    {
     2365      if (dup2 (save_fdin, FD_STDIN) != FD_STDIN)
     2366        O (fatal, NILF, _("Could not restore stdin\n"));
    23072367      else
    2308         close (save_stdin);
    2309     }
    2310 
    2311   if (stdout_fd != 1)
    2312     {
    2313       if (dup2 (save_stdout, 1) != 1)
    2314         fatal (NILF, _("Could not restore stdout\n"));
     2368        close (save_fdin);
     2369    }
     2370
     2371  if (save_fdout >= 0)
     2372    {
     2373      if (dup2 (save_fdout, FD_STDOUT) != FD_STDOUT)
     2374        O (fatal, NILF, _("Could not restore stdout\n"));
    23152375      else
    2316         close (save_stdout);
     2376        close (save_fdout);
     2377    }
     2378
     2379  if (save_fderr >= 0)
     2380    {
     2381      if (dup2 (save_fderr, FD_STDERR) != FD_STDERR)
     2382        O (fatal, NILF, _("Could not restore stderr\n"));
     2383      else
     2384        close (save_fderr);
    23172385    }
    23182386
     
    23222390#elif !defined (_AMIGA) && !defined (__MSDOS__) && !defined (VMS)
    23232391
    2324 /* UNIX:
    2325    Replace the current process with one executing the command in ARGV.
    2326    STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
    2327    the environment of the new program.  This function does not return.  */
    2328 void
    2329 child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp)
     2392/* POSIX:
     2393   Create a child process executing the command in ARGV.
     2394   ENVP is the environment of the new program.  Returns the PID or -1.  */
     2395int
     2396child_execute_job (struct output *out, int good_stdin, char **argv, char **envp)
    23302397{
    2331   if (stdin_fd != 0)
    2332     (void) dup2 (stdin_fd, 0);
    2333   if (stdout_fd != 1)
    2334     (void) dup2 (stdout_fd, 1);
    2335   if (stdin_fd != 0)
    2336     (void) close (stdin_fd);
    2337   if (stdout_fd != 1)
    2338     (void) close (stdout_fd);
     2398  int r;
     2399  int pid;
     2400  int fdin = good_stdin ? FD_STDIN : get_bad_stdin ();
     2401  int fdout = FD_STDOUT;
     2402  int fderr = FD_STDERR;
     2403
     2404  /* Divert child output if we want to capture it.  */
     2405  if (out && out->syncout)
     2406    {
     2407      if (out->out >= 0)
     2408        fdout = out->out;
     2409      if (out->err >= 0)
     2410        fderr = out->err;
     2411    }
     2412
     2413  pid = vfork();
     2414  if (pid != 0)
     2415    return pid;
     2416
     2417  /* We are the child.  */
     2418  unblock_sigs ();
     2419
     2420#ifdef SET_STACK_SIZE
     2421  /* Reset limits, if necessary.  */
     2422  if (stack_limit.rlim_cur)
     2423    setrlimit (RLIMIT_STACK, &stack_limit);
     2424#endif
     2425
     2426  /* For any redirected FD, dup2() it to the standard FD.
     2427     They are all marked close-on-exec already.  */
     2428  if (fdin != FD_STDIN)
     2429    EINTRLOOP (r, dup2 (fdin, FD_STDIN));
     2430  if (fdout != FD_STDOUT)
     2431    EINTRLOOP (r, dup2 (fdout, FD_STDOUT));
     2432  if (fderr != FD_STDERR)
     2433    EINTRLOOP (r, dup2 (fderr, FD_STDERR));
    23392434
    23402435  /* Run the command.  */
     
    23702465  HANDLE hPID;
    23712466  HANDLE hWaitPID;
    2372   int err = 0;
    23732467  int exit_code = EXIT_FAILURE;
    23742468
    23752469  /* make sure CreateProcess() has Path it needs */
    2376   sync_Path_environment();
     2470  sync_Path_environment ();
    23772471
    23782472  /* launch command */
    2379   hPID = process_easy(argv, envp);
     2473  hPID = process_easy (argv, envp, -1, -1);
    23802474
    23812475  /* make sure launch ok */
     
    23832477    {
    23842478      int i;
    2385       fprintf(stderr,
    2386               _("process_easy() failed to launch process (e=%ld)\n"),
    2387               process_last_err(hPID));
     2479      fprintf (stderr, _("process_easy() failed to launch process (e=%ld)\n"),
     2480               process_last_err (hPID));
    23882481      for (i = 0; argv[i]; i++)
    2389           fprintf(stderr, "%s ", argv[i]);
    2390       fprintf(stderr, _("\nCounted %d args in failed launch\n"), i);
    2391       exit(EXIT_FAILURE);
     2482          fprintf (stderr, "%s ", argv[i]);
     2483      fprintf (stderr, _("\nCounted %d args in failed launch\n"), i);
     2484      exit (EXIT_FAILURE);
    23922485    }
    23932486
    23942487  /* wait and reap last child */
    2395   hWaitPID = process_wait_for_any();
     2488  hWaitPID = process_wait_for_any (1, 0);
    23962489  while (hWaitPID)
    23972490    {
    23982491      /* was an error found on this process? */
    2399       err = process_last_err(hWaitPID);
     2492      int err = process_last_err (hWaitPID);
    24002493
    24012494      /* get exit data */
    2402       exit_code = process_exit_code(hWaitPID);
     2495      exit_code = process_exit_code (hWaitPID);
    24032496
    24042497      if (err)
    2405           fprintf(stderr, "make (e=%d, rc=%d): %s",
    2406                   err, exit_code, map_windows32_error_to_string(err));
     2498          fprintf (stderr, "make (e=%d, rc=%d): %s",
     2499                   err, exit_code, map_windows32_error_to_string (err));
    24072500
    24082501      /* cleanup process */
    2409       process_cleanup(hWaitPID);
     2502      process_cleanup (hWaitPID);
    24102503
    24112504      /* expect to find only last pid, warn about other pids reaped */
     
    24132506          break;
    24142507      else
    2415         {
    2416           char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
    2417 
    2418           fprintf(stderr,
    2419                   _("make reaped child pid %s, still waiting for pid %s\n"),
    2420                   pidstr, pid2str ((pid_t)hPID));
    2421           free (pidstr);
    2422         }
     2508        {
     2509          char *pidstr = xstrdup (pid2str ((pid_t)hWaitPID));
     2510
     2511          fprintf (stderr,
     2512                   _("make reaped child pid %s, still waiting for pid %s\n"),
     2513                   pidstr, pid2str ((pid_t)hPID));
     2514          free (pidstr);
     2515        }
    24232516    }
    24242517
    24252518  /* return child's exit code as our exit code */
    2426   exit(exit_code);
     2519  exit (exit_code);
    24272520
    24282521#else  /* !WINDOWS32 */
     
    24362529
    24372530# ifdef __EMX__
    2438 
    24392531  /* Run the program.  */
    24402532  pid = spawnvpe (P_NOWAIT, argv[0], argv, envp);
    2441 
    24422533  if (pid >= 0)
    24432534    return pid;
     
    24482539
    24492540# else
    2450 
    24512541  /* Run the program.  */
    24522542  environ = envp;
     
    24582548    {
    24592549    case ENOENT:
    2460       error (NILF, _("%s: Command not found"), argv[0]);
     2550      /* We are in the child: don't use the output buffer.
     2551         It's not right to run fprintf() here!  */
     2552      if (makelevel == 0)
     2553        fprintf (stderr, _("%s: %s: Command not found\n"), program, argv[0]);
     2554      else
     2555        fprintf (stderr, _("%s[%u]: %s: Command not found\n"),
     2556                 program, makelevel, argv[0]);
    24612557      break;
    24622558    case ENOEXEC:
    24632559      {
    2464         /* The file is not executable.  Try it as a shell script.  */
    2465         extern char *getenv ();
    2466         char *shell;
    2467         char **new_argv;
    2468         int argc;
     2560        /* The file is not executable.  Try it as a shell script.  */
     2561        const char *shell;
     2562        char **new_argv;
     2563        int argc;
    24692564        int i=1;
    24702565
    24712566# ifdef __EMX__
    24722567        /* Do not use $SHELL from the environment */
    2473         struct variable *p = lookup_variable ("SHELL", 5);
    2474         if (p)
    2475           shell = p->value;
     2568        struct variable *p = lookup_variable ("SHELL", 5);
     2569        if (p)
     2570          shell = p->value;
    24762571        else
    24772572          shell = 0;
    24782573# else
    2479         shell = getenv ("SHELL");
     2574        shell = getenv ("SHELL");
    24802575# endif
    2481         if (shell == 0)
    2482           shell = default_shell;
    2483 
    2484         argc = 1;
    2485         while (argv[argc] != 0)
    2486           ++argc;
     2576        if (shell == 0)
     2577          shell = default_shell;
     2578
     2579        argc = 1;
     2580        while (argv[argc] != 0)
     2581          ++argc;
    24872582
    24882583# ifdef __EMX__
     
    24912586# endif
    24922587
    2493         new_argv = alloca ((1 + argc + 1) * sizeof (char *));
    2494         new_argv[0] = shell;
     2588        new_argv = alloca ((1 + argc + 1) * sizeof (char *));
     2589        new_argv[0] = (char *)shell;
    24952590
    24962591# ifdef __EMX__
     
    25042599
    25052600        new_argv[i] = argv[0];
    2506         while (argc > 0)
    2507           {
    2508             new_argv[i + argc] = argv[argc];
    2509             --argc;
    2510           }
     2601        while (argc > 0)
     2602          {
     2603            new_argv[i + argc] = argv[argc];
     2604            --argc;
     2605          }
    25112606
    25122607# ifdef __EMX__
    2513         pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
    2514         if (pid >= 0)
     2608        pid = spawnvpe (P_NOWAIT, shell, new_argv, envp);
     2609        if (pid >= 0)
    25152610          break;
    25162611# else
    2517         execvp (shell, new_argv);
     2612        execvp (shell, new_argv);
    25182613# endif
    2519         if (errno == ENOENT)
    2520           error (NILF, _("%s: Shell program not found"), shell);
    2521         else
    2522           perror_with_name ("execvp: ", shell);
    2523         break;
     2614        if (errno == ENOENT)
     2615          OS (error, NILF, _("%s: Shell program not found"), shell);
     2616        else
     2617          perror_with_name ("execvp: ", shell);
     2618        break;
    25242619      }
    25252620
     
    25272622    case EINVAL:
    25282623      /* this nasty error was driving me nuts :-( */
    2529       error (NILF, _("spawnvpe: environment space might be exhausted"));
     2624      O (error, NILF, _("spawnvpe: environment space might be exhausted"));
    25302625      /* FALLTHROUGH */
    25312626# endif
     
    25452640}
    25462641#else /* On Amiga */
    2547 void exec_command (char **argv)
     2642void
     2643exec_command (char **argv)
    25482644{
    25492645  MyExecute (argv);
     
    25612657/* Figure out the argument list necessary to run LINE as a command.  Try to
    25622658   avoid using a shell.  This routine handles only ' quoting, and " quoting
    2563    when no backslash, $ or ` characters are seen in the quotes.  Starting
     2659   when no backslash, $ or ' characters are seen in the quotes.  Starting
    25642660   quotes may be escaped with a backslash.  If any of the characters in
    2565    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
     2661   sh_chars is seen, or any of the builtin commands listed in sh_cmds
    25662662   is the first word of a line, the shell is used.
    25672663
     
    25782674
    25792675static char **
    2580 construct_command_argv_internal (char *line, char **restp, char *shell,
    2581                                  char *shellflags, char *ifs, int flags,
    2582                                  char **batch_filename_ptr)
     2676construct_command_argv_internal (char *line, char **restp, const char *shell,
     2677                                 const char *shellflags, const char *ifs,
     2678                                 int flags, char **batch_filename UNUSED)
    25832679{
    25842680#ifdef __MSDOS__
    25852681  /* MSDOS supports both the stock DOS shell and ports of Unixy shells.
    2586      We call `system' for anything that requires ``slow'' processing,
     2682     We call 'system' for anything that requires ''slow'' processing,
    25872683     because DOS shells are too dumb.  When $SHELL points to a real
    2588      (unix-style) shell, `system' just calls it to do everything.  When
    2589      $SHELL points to a DOS shell, `system' does most of the work
     2684     (unix-style) shell, 'system' just calls it to do everything.  When
     2685     $SHELL points to a DOS shell, 'system' does most of the work
    25902686     internally, calling the shell only for its internal commands.
    25912687     However, it looks on the $PATH first, so you can e.g. have an
    2592      external command named `mkdir'.
    2593 
    2594      Since we call `system', certain characters and commands below are
     2688     external command named 'mkdir'.
     2689
     2690     Since we call 'system', certain characters and commands below are
    25952691     actually not specific to COMMAND.COM, but to the DJGPP implementation
    2596      of `system'.  In particular:
     2692     of 'system'.  In particular:
    25972693
    25982694       The shell wildcard characters are in DOS_CHARS because they will
    2599        not be expanded if we call the child via `spawnXX'.
    2600 
    2601        The `;' is in DOS_CHARS, because our `system' knows how to run
     2695       not be expanded if we call the child via 'spawnXX'.
     2696
     2697       The ';' is in DOS_CHARS, because our 'system' knows how to run
    26022698       multiple commands on a single line.
    26032699
     
    26052701       won't have to tell one from another and have one more set of
    26062702       commands and special characters.  */
    2607   static char sh_chars_dos[] = "*?[];|<>%^&()";
    2608   static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
    2609                                  "copy", "ctty", "date", "del", "dir", "echo",
    2610                                  "erase", "exit", "for", "goto", "if", "md",
    2611                                  "mkdir", "path", "pause", "prompt", "rd",
    2612                                  "rmdir", "rem", "ren", "rename", "set",
    2613                                  "shift", "time", "type", "ver", "verify",
    2614                                  "vol", ":", 0 };
    2615 
    2616   static char sh_chars_sh[]  = "#;\"*?[]&|<>(){}$`^";
    2617   static char *sh_cmds_sh[]  = { "cd", "echo", "eval", "exec", "exit", "login",
    2618                                  "logout", "set", "umask", "wait", "while",
    2619                                  "for", "case", "if", ":", ".", "break",
    2620                                  "continue", "export", "read", "readonly",
    2621                                  "shift", "times", "trap", "switch", "unset",
    2622                                  "ulimit", 0 };
    2623 
    2624   char *sh_chars;
    2625   char **sh_cmds;
     2703  static const char *sh_chars_dos = "*?[];|<>%^&()";
     2704  static const char *sh_cmds_dos[] =
     2705    { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
     2706      "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
     2707      "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
     2708      "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
     2709      0 };
     2710
     2711  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
     2712  static const char *sh_cmds_sh[] =
     2713    { "cd", "echo", "eval", "exec", "exit", "login", "logout", "set", "umask",
     2714      "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
     2715      "export", "read", "readonly", "shift", "times", "trap", "switch",
     2716      "unset", "ulimit", 0 };
     2717
     2718  const char *sh_chars;
     2719  const char **sh_cmds;
     2720
    26262721#elif defined (__EMX__)
    2627   static char sh_chars_dos[] = "*?[];|<>%^&()";
    2628   static char *sh_cmds_dos[] = { "break", "call", "cd", "chcp", "chdir", "cls",
    2629                                  "copy", "ctty", "date", "del", "dir", "echo",
    2630                                  "erase", "exit", "for", "goto", "if", "md",
    2631                                  "mkdir", "path", "pause", "prompt", "rd",
    2632                                  "rmdir", "rem", "ren", "rename", "set",
    2633                                  "shift", "time", "type", "ver", "verify",
    2634                                  "vol", ":", 0 };
    2635 
    2636   static char sh_chars_os2[] = "*?[];|<>%^()\"'&";
    2637   static char *sh_cmds_os2[] = { "call", "cd", "chcp", "chdir", "cls", "copy",
    2638                              "date", "del", "detach", "dir", "echo",
    2639                              "endlocal", "erase", "exit", "for", "goto", "if",
    2640                              "keys", "md", "mkdir", "move", "path", "pause",
    2641                              "prompt", "rd", "rem", "ren", "rename", "rmdir",
    2642                              "set", "setlocal", "shift", "start", "time",
    2643                              "type", "ver", "verify", "vol", ":", 0 };
    2644 
    2645   static char sh_chars_sh[]  = "#;\"*?[]&|<>(){}$`^~'";
    2646   static char *sh_cmds_sh[]  = { "echo", "cd", "eval", "exec", "exit", "login",
    2647                                  "logout", "set", "umask", "wait", "while",
    2648                                  "for", "case", "if", ":", ".", "break",
    2649                                  "continue", "export", "read", "readonly",
    2650                                  "shift", "times", "trap", "switch", "unset",
    2651                                  0 };
    2652   char *sh_chars;
    2653   char **sh_cmds;
     2722  static const char *sh_chars_dos = "*?[];|<>%^&()";
     2723  static const char *sh_cmds_dos[] =
     2724    { "break", "call", "cd", "chcp", "chdir", "cls", "copy", "ctty", "date",
     2725      "del", "dir", "echo", "erase", "exit", "for", "goto", "if", "md",
     2726      "mkdir", "path", "pause", "prompt", "rd", "rmdir", "rem", "ren",
     2727      "rename", "set", "shift", "time", "type", "ver", "verify", "vol", ":",
     2728      0 };
     2729
     2730  static const char *sh_chars_os2 = "*?[];|<>%^()\"'&";
     2731  static const char *sh_cmds_os2[] =
     2732    { "call", "cd", "chcp", "chdir", "cls", "copy", "date", "del", "detach",
     2733      "dir", "echo", "endlocal", "erase", "exit", "for", "goto", "if", "keys",
     2734      "md", "mkdir", "move", "path", "pause", "prompt", "rd", "rem", "ren",
     2735      "rename", "rmdir", "set", "setlocal", "shift", "start", "time", "type",
     2736      "ver", "verify", "vol", ":", 0 };
     2737
     2738  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~'";
     2739  static const char *sh_cmds_sh[] =
     2740    { "echo", "cd", "eval", "exec", "exit", "login", "logout", "set", "umask",
     2741      "wait", "while", "for", "case", "if", ":", ".", "break", "continue",
     2742      "export", "read", "readonly", "shift", "times", "trap", "switch",
     2743      "unset", 0 };
     2744
     2745  const char *sh_chars;
     2746  const char **sh_cmds;
    26542747
    26552748#elif defined (_AMIGA)
    2656   static char sh_chars[] = "#;\"|<>()?*$`";
    2657   static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
    2658                              "rename", "set", "setenv", "date", "makedir",
    2659                              "skip", "else", "endif", "path", "prompt",
    2660                              "unset", "unsetenv", "version",
    2661                              0 };
     2749  static const char *sh_chars = "#;\"|<>()?*$`";
     2750  static const char *sh_cmds[] =
     2751    { "cd", "eval", "if", "delete", "echo", "copy", "rename", "set", "setenv",
     2752      "date", "makedir", "skip", "else", "endif", "path", "prompt", "unset",
     2753      "unsetenv", "version", 0 };
     2754
    26622755#elif defined (WINDOWS32)
    2663   static char sh_chars_dos[] = "\"|&<>";
    2664   static char *sh_cmds_dos[] = { "assoc", "break", "call", "cd", "chcp",
    2665                                  "chdir", "cls", "color", "copy", "ctty",
    2666                                  "date", "del", "dir", "echo", "echo.",
    2667                                  "endlocal", "erase", "exit", "for", "ftype",
    2668                                  "goto", "if", "if", "md", "mkdir", "path",
    2669                                  "pause", "prompt", "rd", "rem", "ren",
    2670                                  "rename", "rmdir", "set", "setlocal",
    2671                                  "shift", "time", "title", "type", "ver",
    2672                                  "verify", "vol", ":", 0 };
    2673   static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^";
    2674   static char *sh_cmds_sh[] = { "cd", "eval", "exec", "exit", "login",
    2675                              "logout", "set", "umask", "wait", "while", "for",
    2676                              "case", "if", ":", ".", "break", "continue",
    2677                              "export", "read", "readonly", "shift", "times",
    2678                              "trap", "switch", "test",
     2756  /* We used to have a double quote (") in sh_chars_dos[] below, but
     2757     that caused any command line with quoted file names be run
     2758     through a temporary batch file, which introduces command-line
     2759     limit of 4K charcaters imposed by cmd.exe.  Since CreateProcess
     2760     can handle quoted file names just fine, removing the quote lifts
     2761     the limit from a very frequent use case, because using quoted
     2762     file names is commonplace on MS-Windows.  */
     2763  static const char *sh_chars_dos = "|&<>";
     2764  static const char *sh_cmds_dos[] =
     2765    { "assoc", "break", "call", "cd", "chcp", "chdir", "cls", "color", "copy",
     2766      "ctty", "date", "del", "dir", "echo", "echo.", "endlocal", "erase",
     2767      "exit", "for", "ftype", "goto", "if", "if", "md", "mkdir", "move",
     2768      "path", "pause", "prompt", "rd", "rem", "ren", "rename", "rmdir",
     2769      "set", "setlocal", "shift", "time", "title", "type", "ver", "verify",
     2770      "vol", ":", 0 };
     2771
     2772  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^";
     2773  static const char *sh_cmds_sh[] =
     2774    { "cd", "eval", "exec", "exit", "login", "logout", "set", "umask", "wait",
     2775      "while", "for", "case", "if", ":", ".", "break", "continue", "export",
     2776      "read", "readonly", "shift", "times", "trap", "switch", "test",
    26792777#ifdef BATCH_MODE_ONLY_SHELL
    2680                  "echo",
    2681 #endif
    2682                  0 };
    2683   char*  sh_chars;
    2684   char** sh_cmds;
     2778      "echo",
     2779#endif
     2780      0 };
     2781
     2782  const char *sh_chars;
     2783  const char **sh_cmds;
    26852784#elif defined(__riscos__)
    2686   static char sh_chars[] = "";
    2687   static char *sh_cmds[] = { 0 };
     2785  static const char *sh_chars = "";
     2786  static const char *sh_cmds[] = { 0 };
    26882787#else  /* must be UNIX-ish */
    2689   static char sh_chars_sh[] = "#;\"*?[]&|<>(){}$`^~!";                          /* kmk: +_sh */
    2690   static char *sh_cmds_sh[] = { ".", ":", "break", "case", "cd", "continue",    /* kmk: +_sh */
    2691                              "eval", "exec", "exit", "export", "for", "if",
    2692                              "login", "logout", "read", "readonly", "set",
    2693                              "shift", "switch", "test", "times", "trap",
    2694                              "ulimit", "umask", "unset", "wait", "while", 0 };
    2695 # ifdef HAVE_DOS_PATHS
     2788  static const char *sh_chars_sh = "#;\"*?[]&|<>(){}$`^~!";                     /* kmk: +_sh */
     2789  static const char *sh_cmds_sh[] =                                             /* kmk: +_sh */
     2790  { ".", ":", "break", "case", "cd", "continue", "eval", "exec", "exit",
     2791    "export", "for", "if", "login", "logout", "read", "readonly", "set",
     2792    "shift", "switch", "test", "times", "trap", "ulimit", "umask", "unset",
     2793    "wait", "while", 0 };
     2794
     2795# if 0 /*def HAVE_DOS_PATHS - kmk */
    26962796  /* This is required if the MSYS/Cygwin ports (which do not define
    26972797     WINDOWS32) are compiled with HAVE_DOS_PATHS defined, which uses
    2698      sh_chars_sh[] directly (see below).  */
    2699   static char *sh_chars_sh = sh_chars;
    2700 # endif  /* HAVE_DOS_PATHS */
     2798     sh_chars_sh directly (see below).  The value must be identical
     2799     to that of sh_chars immediately above.  */
     2800  static const char *sh_chars_sh =  "#;\"*?[]&|<>(){}$`^~!";
     2801# endif  /* HAVE_DOS_PATHS */
    27012802  char*  sh_chars = sh_chars_sh;                                                /* kmk: +_sh */
    27022803  char** sh_cmds = sh_cmds_sh;                                                  /* kmk: +_sh */
     
    27052806  static char sh_chars_kash[] = "#;*?[]&|<>(){}$`^~!";                          /* note: no \" - good idea? */
    27062807  static char *sh_cmds_kash[] = {
    2707       ".", ":", "break", "case", "cd", "continue",
    2708       "echo", "eval", "exec", "exit", "export", "for", "if",
    2709       "login", "logout", "read", "readonly", "set",
    2710       "shift", "switch", "test", "times", "trap",
    2711       "umask", "wait", "while", 0
     2808      ".", ":", "break", "case", "cd", "continue", "echo", "eval", "exec", "exit",
     2809      "export", "for", "if", "login", "logout", "read", "readonly", "set",
     2810      "shift", "switch", "test", "times", "trap", "umask", "wait", "while", 0 /* +echo, -ulimit, -unset */
    27122811  };
    27132812  int is_kmk_shell = 0;
     
    27152814  int i;
    27162815  char *p;
    2717   char *ap;
    27182816#ifndef NDEBUG
    27192817  char *end;
    27202818#endif
     2819  char *ap;
     2820  const char *cap;
     2821  const char *cp;
    27212822  int instring, word_has_equals, seen_nonequals, last_argument_was_empty;
    27222823  char **new_argv = 0;
     
    27252826  int slow_flag = 0;
    27262827
    2727   if (!unixy_shell) {
    2728     sh_cmds = sh_cmds_dos;
    2729     sh_chars = sh_chars_dos;
    2730   } else {
    2731     sh_cmds = sh_cmds_sh;
    2732     sh_chars = sh_chars_sh;
    2733   }
     2828  if (!unixy_shell)
     2829    {
     2830      sh_cmds = sh_cmds_dos;
     2831      sh_chars = sh_chars_dos;
     2832    }
     2833  else
     2834    {
     2835      sh_cmds = sh_cmds_sh;
     2836      sh_chars = sh_chars_sh;
     2837    }
    27342838#endif /* WINDOWS32 */
    27352839
     
    27372841    *restp = NULL;
    27382842
    2739   /* Make sure not to bother processing an empty line.  */
    2740   while (isblank ((unsigned char)*line))
     2843  /* Make sure not to bother processing an empty line but stop at newline.  */
     2844  while (ISBLANK (*line))
    27412845    ++line;
    27422846  if (*line == '\0')
    27432847    return 0;
     2848
     2849  if (shellflags == 0)
     2850    shellflags = posix_pedantic ? "-ec" : "-c";
    27442851
    27452852  /* See if it is safe to parse commands internally.  */
     
    27862893    slow_flag = strcmp ((s1 ? s1 : ""), (s2 ? s2 : ""));
    27872894
    2788     if (s1)
    2789       free (s1);
    2790     if (s2)
    2791       free (s2);
     2895    free (s1);
     2896    free (s2);
    27922897  }
    27932898  if (slow_flag)
     
    27992904      extern int _is_unixy_shell (const char *_path);
    28002905
    2801       DB (DB_BASIC, (_("$SHELL changed (was `%s', now `%s')\n"),
     2906      DB (DB_BASIC, (_("$SHELL changed (was '%s', now '%s')\n"),
    28022907                     default_shell, shell));
    28032908      unixy_shell = _is_unixy_shell (shell);
     
    28342939#endif /* not WINDOWS32 */
    28352940
    2836   if (ifs != 0)
    2837     for (ap = ifs; *ap != '\0'; ++ap)
    2838       if (*ap != ' ' && *ap != '\t' && *ap != '\n')
    2839         goto slow;
    2840 
    2841   if (shellflags != 0)
     2941  if (ifs)
     2942    for (cap = ifs; *cap != '\0'; ++cap)
     2943      if (*cap != ' ' && *cap != '\t' && *cap != '\n')
     2944        goto slow;
     2945
     2946  if (shellflags)
    28422947    if (shellflags[0] != '-'
    28432948        || ((shellflags[1] != 'c' || shellflags[2] != '\0')
     
    28642969
    28652970      if (instring)
    2866         {
    2867           /* Inside a string, just copy any char except a closing quote
    2868              or a backslash-newline combination.  */
    2869           if (*p == instring)
    2870             {
    2871               instring = 0;
    2872               if (ap == new_argv[0] || *(ap-1) == '\0')
    2873                 last_argument_was_empty = 1;
    2874             }
    2875           else if (*p == '\\' && p[1] == '\n')
     2971        {
     2972          /* Inside a string, just copy any char except a closing quote
     2973             or a backslash-newline combination.  */
     2974          if (*p == instring)
     2975            {
     2976              instring = 0;
     2977              if (ap == new_argv[0] || *(ap-1) == '\0')
     2978                last_argument_was_empty = 1;
     2979            }
     2980          else if (*p == '\\' && p[1] == '\n')
    28762981            {
    28772982              /* Backslash-newline is handled differently depending on what
    28782983                 kind of string we're in: inside single-quoted strings you
    2879                  keep them; in double-quoted strings they disappear.
    2880                  For DOS/Windows/OS2, if we don't have a POSIX shell,
    2881                  we keep the pre-POSIX behavior of removing the
    2882                  backslash-newline.  */
     2984                 keep them; in double-quoted strings they disappear.  For
     2985                 DOS/Windows/OS2, if we don't have a POSIX shell, we keep the
     2986                 pre-POSIX behavior of removing the backslash-newline.  */
    28832987              if (instring == '"'
    28842988#if defined (__MSDOS__) || defined (__EMX__) || defined (WINDOWS32)
    2885                   || !unixy_shell
    2886 #endif
    2887                   )
     2989                  || !unixy_shell
     2990#endif
     2991                  )
    28882992                ++p;
    28892993              else
     
    28932997                }
    28942998            }
    2895           else if (*p == '\n' && restp != NULL)
    2896             {
    2897               /* End of the command line.  */
    2898               *restp = p;
    2899               goto end_of_line;
    2900             }
    2901           /* Backslash, $, and ` are special inside double quotes.
    2902              If we see any of those, punt.
    2903              But on MSDOS, if we use COMMAND.COM, double and single
    2904              quotes have the same effect.  */
    2905           else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
    2906             goto slow;
    2907           else
    2908             *ap++ = *p;
    2909         }
     2999          else if (*p == '\n' && restp != NULL)
     3000            {
     3001              /* End of the command line.  */
     3002              *restp = p;
     3003              goto end_of_line;
     3004            }
     3005          /* Backslash, $, and ` are special inside double quotes.
     3006             If we see any of those, punt.
     3007             But on MSDOS, if we use COMMAND.COM, double and single
     3008             quotes have the same effect.  */
     3009          else if (instring == '"' && strchr ("\\$`", *p) != 0 && unixy_shell)
     3010            goto slow;
     3011#ifdef WINDOWS32
     3012          /* Quoted wildcard characters must be passed quoted to the
     3013             command, so give up the fast route.  */
     3014          else if (instring == '"' && strchr ("*?", *p) != 0 && !unixy_shell)
     3015            goto slow;
     3016          else if (instring == '"' && strncmp (p, "\\\"", 2) == 0)
     3017            *ap++ = *++p;
     3018#endif
     3019          else
     3020            *ap++ = *p;
     3021        }
    29103022      else if (strchr (sh_chars, *p) != 0)
    29113023#ifdef KMK
     
    29153027          if (   *p == '~'
    29163028              && p > line
    2917               && !isspace (p[-1])
     3029              && !ISSPACE (p[-1])
    29183030              && p[-1] != '='
    29193031              && p[-1] != ':'
     
    29263038        }
    29273039#else  /* !KMK */
    2928         /* Not inside a string, but it's a special char.  */
    2929         goto slow;
     3040        /* Not inside a string, but it's a special char.  */
     3041        goto slow;
    29303042#endif /* !KMK */
    29313043      else if (one_shell && *p == '\n')
    2932         /* In .ONESHELL mode \n is a separator like ; or && */
    2933         goto slow;
     3044        /* In .ONESHELL mode \n is a separator like ; or && */
     3045        goto slow;
    29343046#ifdef  __MSDOS__
    29353047      else if (*p == '.' && p[1] == '.' && p[2] == '.' && p[3] != '.')
    2936         /* `...' is a wildcard in DJGPP.  */
    2937         goto slow;
     3048        /* '...' is a wildcard in DJGPP.  */
     3049        goto slow;
    29383050#endif
    29393051      else
    2940         /* Not a special char.  */
    2941         switch (*p)
    2942           {
    2943           case '=':
    2944             /* Equals is a special character in leading words before the
    2945                first word with no equals sign in it.  This is not the case
    2946                with sh -k, but we never get here when using nonstandard
    2947                shell flags.  */
    2948             if (! seen_nonequals && unixy_shell)
    2949               goto slow;
    2950             word_has_equals = 1;
    2951             *ap++ = '=';
    2952             break;
    2953 
    2954           case '\\':
    2955             /* Backslash-newline has special case handling, ref POSIX.
     3052        /* Not a special char.  */
     3053        switch (*p)
     3054          {
     3055          case '=':
     3056            /* Equals is a special character in leading words before the
     3057               first word with no equals sign in it.  This is not the case
     3058               with sh -k, but we never get here when using nonstandard
     3059               shell flags.  */
     3060            if (! seen_nonequals && unixy_shell)
     3061              goto slow;
     3062            word_has_equals = 1;
     3063            *ap++ = '=';
     3064            break;
     3065
     3066          case '\\':
     3067            /* Backslash-newline has special case handling, ref POSIX.
    29563068               We're in the fastpath, so emulate what the shell would do.  */
    2957             if (p[1] == '\n')
    2958               {
    2959                 /* Throw out the backslash and newline.  */
     3069            if (p[1] == '\n')
     3070              {
     3071                /* Throw out the backslash and newline.  */
    29603072                ++p;
    29613073
    2962                 /* If there's nothing in this argument yet, skip any
    2963                    whitespace before the start of the next word.  */
     3074                /* At the beginning of the argument, skip any whitespace other
     3075                   than newline before the start of the next word.  */
    29643076                if (ap == new_argv[i])
    2965                   p = next_token (p + 1) - 1;
    2966               }
    2967             else if (p[1] != '\0')
     3077                  while (ISBLANK (p[1]))
     3078                    ++p;
     3079              }
     3080#ifdef WINDOWS32
     3081            /* Backslash before whitespace is not special if our shell
     3082               is not Unixy.  */
     3083            else if (ISSPACE (p[1]) && !unixy_shell)
     3084              {
     3085                *ap++ = *p;
     3086                break;
     3087              }
     3088#endif
     3089            else if (p[1] != '\0')
    29683090              {
    29693091#ifdef HAVE_DOS_PATHS
     
    29863108#endif
    29873109                  if (p[1] != '\\' && p[1] != '\''
    2988                       && !isspace ((unsigned char)p[1])
     3110                      && !ISSPACE (p[1])
    29893111# ifdef KMK
    29903112                      && strchr (sh_chars, p[1]) == 0
     
    30003122                *ap++ = *++p;
    30013123              }
    3002             break;
    3003 
    3004           case '\'':
    3005           case '"':
    3006             instring = *p;
    3007             break;
    3008 
    3009           case '\n':
    3010             if (restp != NULL)
    3011               {
    3012                 /* End of the command line.  */
    3013                 *restp = p;
    3014                 goto end_of_line;
    3015               }
    3016             else
    3017               /* Newlines are not special.  */
    3018               *ap++ = '\n';
    3019             break;
    3020 
    3021           case ' ':
    3022           case '\t':
    3023             /* We have the end of an argument.
    3024                Terminate the text of the argument.  */
    3025             *ap++ = '\0';
    3026             new_argv[++i] = ap;
    3027             last_argument_was_empty = 0;
    3028 
    3029             /* Update SEEN_NONEQUALS, which tells us if every word
    3030                heretofore has contained an `='.  */
    3031             seen_nonequals |= ! word_has_equals;
    3032             if (word_has_equals && ! seen_nonequals)
    3033               /* An `=' in a word before the first
    3034                 word without one is magical.  */
    3035               goto slow;
    3036             word_has_equals = 0; /* Prepare for the next word.  */
    3037 
    3038             /* If this argument is the command name,
    3039                see if it is a built-in shell command.
    3040                If so, have the shell handle it.  */
    3041             if (i == 1)
    3042               {
    3043                 register int j;
    3044                 for (j = 0; sh_cmds[j] != 0; ++j)
     3124            break;
     3125
     3126          case '\'':
     3127          case '"':
     3128            instring = *p;
     3129            break;
     3130
     3131          case '\n':
     3132            if (restp != NULL)
     3133              {
     3134                /* End of the command line.  */
     3135                *restp = p;
     3136                goto end_of_line;
     3137              }
     3138            else
     3139              /* Newlines are not special.  */
     3140              *ap++ = '\n';
     3141            break;
     3142
     3143          case ' ':
     3144          case '\t':
     3145            /* We have the end of an argument.
     3146               Terminate the text of the argument.  */
     3147            *ap++ = '\0';
     3148            new_argv[++i] = ap;
     3149            last_argument_was_empty = 0;
     3150
     3151            /* Update SEEN_NONEQUALS, which tells us if every word
     3152               heretofore has contained an '='.  */
     3153            seen_nonequals |= ! word_has_equals;
     3154            if (word_has_equals && ! seen_nonequals)
     3155              /* An '=' in a word before the first
     3156                word without one is magical.  */
     3157              goto slow;
     3158            word_has_equals = 0; /* Prepare for the next word.  */
     3159
     3160            /* If this argument is the command name,
     3161               see if it is a built-in shell command.
     3162               If so, have the shell handle it.  */
     3163            if (i == 1)
     3164              {
     3165                register int j;
     3166                for (j = 0; sh_cmds[j] != 0; ++j)
    30453167                  {
    30463168                    if (streq (sh_cmds[j], new_argv[0]))
    30473169                      goto slow;
    3048 # ifdef __EMX__
     3170#if defined(__EMX__) || defined(WINDOWS32)
    30493171                    /* Non-Unix shells are case insensitive.  */
    30503172                    if (!unixy_shell
    30513173                        && strcasecmp (sh_cmds[j], new_argv[0]) == 0)
    30523174                      goto slow;
    3053 # endif
     3175#endif
    30543176                  }
    3055               }
    3056 
    3057             /* Ignore multiple whitespace chars.  */
    3058             p = next_token (p) - 1;
    3059             break;
    3060 
    3061           default:
    3062             *ap++ = *p;
    3063             break;
    3064           }
     3177              }
     3178
     3179            /* Skip whitespace chars, but not newlines.  */
     3180            while (ISBLANK (p[1]))
     3181              ++p;
     3182            break;
     3183
     3184          default:
     3185            *ap++ = *p;
     3186            break;
     3187          }
    30653188    }
    30663189 end_of_line:
     
    30813204      register int j;
    30823205      for (j = 0; sh_cmds[j] != 0; ++j)
    3083         if (streq (sh_cmds[j], new_argv[0]))
    3084           goto slow;
     3206        if (streq (sh_cmds[j], new_argv[0]))
     3207          goto slow;
    30853208    }
    30863209
     
    31063229
    31073230#ifdef __MSDOS__
    3108   execute_by_shell = 1; /* actually, call `system' if shell isn't unixy */
     3231  execute_by_shell = 1; /* actually, call 'system' if shell isn't unixy */
    31093232#endif
    31103233
     
    31213244    {
    31223245      if (*ptr == '\\' && ptr[1] == '\n')
    3123         ptr += 2;
     3246        ptr += 2;
    31243247      else if (*ptr == '@') /* Kludge: multiline commands */
    31253248      {
    3126         ptr += 2;
    3127         *dptr++ = '\n';
     3249        ptr += 2;
     3250        *dptr++ = '\n';
    31283251      }
    31293252      else
    3130         *dptr++ = *ptr++;
     3253        *dptr++ = *ptr++;
    31313254    }
    31323255    *dptr = 0;
     
    31363259    new_argv[1] = 0;
    31373260  }
    3138 #else   /* Not Amiga  */
     3261#else   /* Not Amiga  */
    31393262#ifdef WINDOWS32
    31403263  /*
     
    31493272
    31503273  /* Make sure not to bother processing an empty line.  */
    3151   while (isspace ((unsigned char)*line))
    3152     ++line;
     3274  NEXT_TOKEN (line);
    31533275  if (*line == '\0')
    31543276    return 0;
     
    31613283       argument list.  */
    31623284
     3285    char *new_line;
    31633286    unsigned int shell_len = strlen (shell);
    31643287    unsigned int line_len = strlen (line);
    3165     unsigned int sflags_len = strlen (shellflags);
    3166 # ifdef WINDOWS32
     3288    unsigned int sflags_len = shellflags ? strlen (shellflags) : 0;
     3289#ifdef WINDOWS32
    31673290    char *command_ptr = NULL; /* used for batch_mode_shell mode */
    3168 # endif
    3169     char *new_line;
     3291#endif
    31703292
    31713293# ifdef __EMX__ /* is this necessary? */
    3172     if (!unixy_shell)
     3294    if (!unixy_shell && shellflags)
    31733295      shellflags[0] = '/'; /* "/c" */
    31743296# endif
    31753297
    31763298    /* In .ONESHELL mode we are allowed to throw the entire current
    3177         recipe string at a single shell and trust that the user
    3178         has configured the shell and shell flags, and formatted
    3179         the string, appropriately. */
     3299        recipe string at a single shell and trust that the user
     3300        has configured the shell and shell flags, and formatted
     3301        the string, appropriately. */
    31803302    if (one_shell)
    31813303      {
    3182         /* If the shell is Bourne compatible, we must remove and ignore
    3183            interior special chars [@+-] because they're meaningless to
    3184            the shell itself. If, however, we're in .ONESHELL mode and
    3185            have changed SHELL to something non-standard, we should
    3186            leave those alone because they could be part of the
    3187            script. In this case we must also leave in place
    3188            any leading [@+-] for the same reason.  */
    3189 
    3190         /* Remove and ignore interior prefix chars [@+-] because they're
    3191              meaningless given a single shell. */
     3304        /* If the shell is Bourne compatible, we must remove and ignore
     3305           interior special chars [@+-] because they're meaningless to
     3306           the shell itself. If, however, we're in .ONESHELL mode and
     3307           have changed SHELL to something non-standard, we should
     3308           leave those alone because they could be part of the
     3309           script. In this case we must also leave in place
     3310           any leading [@+-] for the same reason.  */
     3311
     3312        /* Remove and ignore interior prefix chars [@+-] because they're
     3313             meaningless given a single shell. */
    31923314#if defined __MSDOS__ || defined (__EMX__)
    3193         if (unixy_shell)     /* the test is complicated and we already did it */
     3315        if (unixy_shell)     /* the test is complicated and we already did it */
    31943316#else
    3195         if (is_bourne_compatible_shell(shell))
     3317        if (is_bourne_compatible_shell (shell)
     3318#ifdef WINDOWS32
     3319            /* If we didn't find any sh.exe, don't behave is if we did!  */
     3320            && !no_default_sh_exe
     3321#endif
     3322            )
    31963323#endif
    31973324          {
     
    32053332                int esc = 0;
    32063333
    3207                 /* This is the start of a new recipe line.
    3208                    Skip whitespace and prefix characters.  */
    3209                 while (isblank (*f) || *f == '-' || *f == '@' || *f == '+')
     3334                /* This is the start of a new recipe line.  Skip whitespace
     3335                   and prefix characters but not newlines.  */
     3336                while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
    32103337                  ++f;
    32113338
     
    32293356            *t = '\0';
    32303357          }
    3231 
    3232         new_argv = xmalloc (4 * sizeof (char *));
    3233         new_argv[0] = xstrdup(shell);
    3234         new_argv[1] = xstrdup(shellflags);
    3235         new_argv[2] = line;
    3236         new_argv[3] = NULL;
    3237         return new_argv;
     3358#ifdef WINDOWS32
     3359        else    /* non-Posix shell (cmd.exe etc.) */
     3360          {
     3361            const char *f = line;
     3362            char *t = line;
     3363            char *tstart = t;
     3364            int temp_fd;
     3365            FILE* batch = NULL;
     3366            int id = GetCurrentProcessId ();
     3367            PATH_VAR(fbuf);
     3368
     3369            /* Generate a file name for the temporary batch file.  */
     3370            sprintf (fbuf, "make%d", id);
     3371            *batch_filename = create_batch_file (fbuf, 0, &temp_fd);
     3372            DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
     3373                          *batch_filename));
     3374
     3375            /* Create a FILE object for the batch file, and write to it the
     3376               commands to be executed.  Put the batch file in TEXT mode.  */
     3377            _setmode (temp_fd, _O_TEXT);
     3378            batch = _fdopen (temp_fd, "wt");
     3379            fputs ("@echo off\n", batch);
     3380            DB (DB_JOBS, (_("Batch file contents:\n\t@echo off\n")));
     3381
     3382            /* Copy the recipe, removing and ignoring interior prefix chars
     3383               [@+-]: they're meaningless in .ONESHELL mode.  */
     3384            while (*f != '\0')
     3385              {
     3386                /* This is the start of a new recipe line.  Skip whitespace
     3387                   and prefix characters but not newlines.  */
     3388                while (ISBLANK (*f) || *f == '-' || *f == '@' || *f == '+')
     3389                  ++f;
     3390
     3391                /* Copy until we get to the next logical recipe line.  */
     3392                while (*f != '\0')
     3393                  {
     3394                    /* Remove the escaped newlines in the command, and the
     3395                       blanks that follow them.  Windows shells cannot handle
     3396                       escaped newlines.  */
     3397                    if (*f == '\\' && f[1] == '\n')
     3398                      {
     3399                        f += 2;
     3400                        while (ISBLANK (*f))
     3401                          ++f;
     3402                      }
     3403                    *(t++) = *(f++);
     3404                    /* On an unescaped newline, we're done with this
     3405                       line.  */
     3406                    if (f[-1] == '\n')
     3407                      break;
     3408                  }
     3409                /* Write another line into the batch file.  */
     3410                if (t > tstart)
     3411                  {
     3412                    char c = *t;
     3413                    *t = '\0';
     3414                    fputs (tstart, batch);
     3415                    DB (DB_JOBS, ("\t%s", tstart));
     3416                    tstart = t;
     3417                    *t = c;
     3418                  }
     3419              }
     3420            DB (DB_JOBS, ("\n"));
     3421            fclose (batch);
     3422
     3423            /* Create an argv list for the shell command line that
     3424               will run the batch file.  */
     3425            new_argv = xmalloc (2 * sizeof (char *));
     3426            new_argv[0] = xstrdup (*batch_filename);
     3427            new_argv[1] = NULL;
     3428            return new_argv;
     3429          }
     3430#endif /* WINDOWS32 */
     3431        /* Create an argv list for the shell command line.  */
     3432        {
     3433          int n = 0;
     3434
     3435          new_argv = xmalloc ((4 + sflags_len/2) * sizeof (char *));
     3436          new_argv[n++] = xstrdup (shell);
     3437
     3438          /* Chop up the shellflags (if any) and assign them.  */
     3439          if (! shellflags)
     3440            new_argv[n++] = xstrdup ("");
     3441          else
     3442            {
     3443              const char *s = shellflags;
     3444              char *t;
     3445              unsigned int len;
     3446              while ((t = find_next_token (&s, &len)) != 0)
     3447                new_argv[n++] = xstrndup (t, len);
     3448            }
     3449
     3450          /* Set the command to invoke.  */
     3451          new_argv[n++] = line;
     3452          new_argv[n++] = NULL;
     3453        }
     3454        return new_argv;
    32383455      }
    32393456
    3240     new_line = alloca (shell_len + 1 + sflags_len + 1
    3241                              + (line_len*2) + 1);
     3457    new_line = xmalloc ((shell_len*2) + 1 + sflags_len + 1
     3458                        + (line_len*2) + 1);
    32423459    ap = new_line;
    3243     memcpy (ap, shell, shell_len);
    3244     ap += shell_len;
     3460    /* Copy SHELL, escaping any characters special to the shell.  If
     3461       we don't escape them, construct_command_argv_internal will
     3462       recursively call itself ad nauseam, or until stack overflow,
     3463       whichever happens first.  */
     3464    for (cp = shell; *cp != '\0'; ++cp)
     3465      {
     3466        if (strchr (sh_chars, *cp) != 0)
     3467          *(ap++) = '\\';
     3468        *(ap++) = *cp;
     3469      }
    32453470    *(ap++) = ' ';
    3246     memcpy (ap, shellflags, sflags_len);
     3471    if (shellflags)
     3472      memcpy (ap, shellflags, sflags_len);
    32473473    ap += sflags_len;
    32483474    *(ap++) = ' ';
     
    32523478    for (p = line; *p != '\0'; ++p)
    32533479      {
    3254         if (restp != NULL && *p == '\n')
    3255           {
    3256             *restp = p;
    3257             break;
    3258           }
    3259         else if (*p == '\\' && p[1] == '\n')
    3260           {
    3261             /* POSIX says we keep the backslash-newline.  If we don't have a
     3480        if (restp != NULL && *p == '\n')
     3481          {
     3482            *restp = p;
     3483            break;
     3484          }
     3485        else if (*p == '\\' && p[1] == '\n')
     3486          {
     3487            /* POSIX says we keep the backslash-newline.  If we don't have a
    32623488               POSIX shell on DOS/Windows/OS2, mimic the pre-POSIX behavior
    32633489               and remove the backslash/newline.  */
     
    32673493# define PRESERVE_BSNL  1
    32683494#endif
    3269             if (PRESERVE_BSNL)
    3270               {
    3271                 *(ap++) = '\\';
    3272                 /* Only non-batch execution needs another backslash,
    3273                    because it will be passed through a recursive
    3274                    invocation of this function.  */
    3275                 if (!batch_mode_shell)
    3276                   *(ap++) = '\\';
    3277                 *(ap++) = '\n';
    3278               }
    3279             ++p;
    3280             continue;
    3281           }
     3495            if (PRESERVE_BSNL)
     3496              {
     3497                *(ap++) = '\\';
     3498                /* Only non-batch execution needs another backslash,
     3499                   because it will be passed through a recursive
     3500                   invocation of this function.  */
     3501                if (!batch_mode_shell)
     3502                  *(ap++) = '\\';
     3503                *(ap++) = '\n';
     3504              }
     3505            ++p;
     3506            continue;
     3507          }
    32823508
    32833509        /* DOS shells don't know about backslash-escaping.  */
    3284         if (unixy_shell && !batch_mode_shell &&
     3510        if (unixy_shell && !batch_mode_shell &&
    32853511            (*p == '\\' || *p == '\'' || *p == '"'
    3286              || isspace ((unsigned char)*p)
     3512             || ISSPACE (*p)
    32873513             || strchr (sh_chars, *p) != 0))
    3288           *ap++ = '\\';
     3514          *ap++ = '\\';
    32893515#ifdef __MSDOS__
    32903516        else if (unixy_shell && strneq (p, "...", 3))
    32913517          {
    3292             /* The case of `...' wildcard again.  */
     3518            /* The case of '...' wildcard again.  */
    32933519            strcpy (ap, "\\.\\.\\");
    32943520            ap += 5;
     
    32963522          }
    32973523#endif
    3298         *ap++ = *p;
     3524        *ap++ = *p;
    32993525      }
    33003526    if (ap == new_line + shell_len + sflags_len + 2)
    3301       /* Line was empty.  */
    3302       return 0;
     3527      {
     3528        /* Line was empty.  */
     3529        free (new_line);
     3530        return 0;
     3531      }
    33033532    *ap = '\0';
    33043533
     
    33073536       command line (e.g. Cygnus GNUWIN32 sh.exe on WIN32 systems).  In these
    33083537       cases, run commands via a script file.  */
    3309     if (just_print_flag && !(flags & COMMANDS_RECURSE)) {
    3310       /* Need to allocate new_argv, although it's unused, because
    3311         start_job_command will want to free it and its 0'th element.  */
    3312       new_argv = xmalloc(2 * sizeof (char *));
    3313       new_argv[0] = xstrdup ("");
    3314       new_argv[1] = NULL;
    3315     } else if ((no_default_sh_exe || batch_mode_shell) && batch_filename_ptr) {
    3316       int temp_fd;
    3317       FILE* batch = NULL;
    3318       int id = GetCurrentProcessId();
    3319       PATH_VAR(fbuf);
    3320 
    3321       /* create a file name */
    3322       sprintf(fbuf, "make%d", id);
    3323       *batch_filename_ptr = create_batch_file (fbuf, unixy_shell, &temp_fd);
    3324 
    3325       DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
    3326                     *batch_filename_ptr));
    3327 
    3328       /* Create a FILE object for the batch file, and write to it the
    3329          commands to be executed.  Put the batch file in TEXT mode.  */
    3330       _setmode (temp_fd, _O_TEXT);
    3331       batch = _fdopen (temp_fd, "wt");
    3332       if (!unixy_shell)
    3333         fputs ("@echo off\n", batch);
    3334       fputs (command_ptr, batch);
    3335       fputc ('\n', batch);
    3336       fclose (batch);
    3337       DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
    3338                     !unixy_shell ? "\n\t@echo off" : "", command_ptr));
    3339 
    3340       /* create argv */
    3341       new_argv = xmalloc(3 * sizeof (char *));
    3342       if (unixy_shell) {
    3343         new_argv[0] = xstrdup (shell);
    3344         new_argv[1] = *batch_filename_ptr; /* only argv[0] gets freed later */
    3345       } else {
    3346         new_argv[0] = xstrdup (*batch_filename_ptr);
     3538    if (just_print_flag && !(flags & COMMANDS_RECURSE))
     3539      {
     3540        /* Need to allocate new_argv, although it's unused, because
     3541           start_job_command will want to free it and its 0'th element.  */
     3542        new_argv = xmalloc (2 * sizeof (char *));
     3543        new_argv[0] = xstrdup ("");
    33473544        new_argv[1] = NULL;
    33483545      }
    3349       new_argv[2] = NULL;
    3350     } else
     3546    else if ((no_default_sh_exe || batch_mode_shell) && batch_filename)
     3547      {
     3548        int temp_fd;
     3549        FILE* batch = NULL;
     3550        int id = GetCurrentProcessId ();
     3551        PATH_VAR (fbuf);
     3552
     3553        /* create a file name */
     3554        sprintf (fbuf, "make%d", id);
     3555        *batch_filename = create_batch_file (fbuf, unixy_shell, &temp_fd);
     3556
     3557        DB (DB_JOBS, (_("Creating temporary batch file %s\n"),
     3558                      *batch_filename));
     3559
     3560        /* Create a FILE object for the batch file, and write to it the
     3561           commands to be executed.  Put the batch file in TEXT mode.  */
     3562        _setmode (temp_fd, _O_TEXT);
     3563        batch = _fdopen (temp_fd, "wt");
     3564        if (!unixy_shell)
     3565          fputs ("@echo off\n", batch);
     3566        fputs (command_ptr, batch);
     3567        fputc ('\n', batch);
     3568        fclose (batch);
     3569        DB (DB_JOBS, (_("Batch file contents:%s\n\t%s\n"),
     3570                      !unixy_shell ? "\n\t@echo off" : "", command_ptr));
     3571
     3572        /* create argv */
     3573        new_argv = xmalloc (3 * sizeof (char *));
     3574        if (unixy_shell)
     3575          {
     3576            new_argv[0] = xstrdup (shell);
     3577            new_argv[1] = *batch_filename; /* only argv[0] gets freed later */
     3578          }
     3579        else
     3580          {
     3581            new_argv[0] = xstrdup (*batch_filename);
     3582            new_argv[1] = NULL;
     3583          }
     3584        new_argv[2] = NULL;
     3585      }
     3586    else
    33513587#endif /* WINDOWS32 */
    33523588
    33533589    if (unixy_shell)
    3354       new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0, flags, 0);
     3590      new_argv = construct_command_argv_internal (new_line, 0, 0, 0, 0,
     3591                                                  flags, 0);
    33553592
    33563593#ifdef __EMX__
    33573594    else if (!unixy_shell)
    33583595      {
    3359         /* new_line is local, must not be freed therefore
     3596        /* new_line is local, must not be freed therefore
    33603597           We use line here instead of new_line because we run the shell
    33613598           manually.  */
     
    34373674#else
    34383675    else
    3439       fatal (NILF, _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
     3676      fatal (NILF, CSTRLEN (__FILE__) + INTSTR_LENGTH,
     3677             _("%s (line %d) Bad shell context (!unixy && !batch_mode_shell)\n"),
    34403678            __FILE__, __LINE__);
    34413679#endif
     3680
     3681    free (new_line);
    34423682  }
    3443 #endif  /* ! AMIGA */
     3683#endif  /* ! AMIGA */
    34443684
    34453685  return new_argv;
     
    34493689/* Figure out the argument list necessary to run LINE as a command.  Try to
    34503690   avoid using a shell.  This routine handles only ' quoting, and " quoting
    3451    when no backslash, $ or ` characters are seen in the quotes.  Starting
     3691   when no backslash, $ or ' characters are seen in the quotes.  Starting
    34523692   quotes may be escaped with a backslash.  If any of the characters in
    3453    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
     3693   sh_chars is seen, or any of the builtin commands listed in sh_cmds
    34543694   is the first word of a line, the shell is used.
    34553695
     
    34623702char **
    34633703construct_command_argv (char *line, char **restp, struct file *file,
    3464                         int cmd_flags, char **batch_filename_ptr)
     3704                        int cmd_flags, char **batch_filename)
    34653705{
    34663706  char *shell, *ifs, *shellflags;
     
    34753715  for (;;)
    34763716    {
    3477       while ((*cptr != 0)
    3478              && (isspace ((unsigned char)*cptr)))
    3479         cptr++;
     3717      while ((*cptr != 0) && (ISSPACE (*cptr)))
     3718        cptr++;
    34803719      if (*cptr == 0)
    3481         break;
    3482       while ((*cptr != 0)
    3483              && (!isspace((unsigned char)*cptr)))
    3484         cptr++;
     3720        break;
     3721      while ((*cptr != 0) && (!ISSPACE (*cptr)))
     3722        cptr++;
    34853723      argc++;
    34863724    }
     
    34943732  for (;;)
    34953733    {
    3496       while ((*cptr != 0)
    3497              && (isspace ((unsigned char)*cptr)))
    3498         cptr++;
     3734      while ((*cptr != 0) && (ISSPACE (*cptr)))
     3735        cptr++;
    34993736      if (*cptr == 0)
    3500         break;
     3737        break;
    35013738      DB (DB_JOBS, ("argv[%d] = [%s]\n", argc, cptr));
    35023739      argv[argc++] = cptr;
    3503       while ((*cptr != 0)
    3504              && (!isspace((unsigned char)*cptr)))
    3505         cptr++;
     3740      while ((*cptr != 0) && (!ISSPACE (*cptr)))
     3741        cptr++;
    35063742      if (*cptr != 0)
    3507         *cptr++ = 0;
     3743        *cptr++ = 0;
    35083744    }
    35093745#else
     
    35193755     * is not confused.
    35203756     */
    3521     if (shell) {
    3522       char *p = w32ify (shell, 0);
    3523       strcpy (shell, p);
    3524     }
     3757    if (shell)
     3758      {
     3759        char *p = w32ify (shell, 0);
     3760        strcpy (shell, p);
     3761      }
    35253762#endif
    35263763#ifdef __EMX__
     
    35303767      static int init = 0;
    35313768      if (init == 0)
    3532         {
    3533           unixroot = getenv ("UNIXROOT");
    3534           /* unixroot must be NULL or not empty */
    3535           if (unixroot && unixroot[0] == '\0') unixroot = NULL;
    3536           init = 1;
    3537         }
     3769        {
     3770          unixroot = getenv ("UNIXROOT");
     3771          /* unixroot must be NULL or not empty */
     3772          if (unixroot && unixroot[0] == '\0') unixroot = NULL;
     3773          init = 1;
     3774        }
    35383775
    35393776      /* if we have an unixroot drive and if shell is not default_shell
     
    35433780         "$UNIXROOT/bin/sh" instead.  */
    35443781      if (unixroot && shell && strcmp (shell, last_shell) != 0
    3545           && (shell[0] == '/' || shell[0] == '\\'))
    3546         {
    3547           /* trying a new shell, check whether it exists */
    3548           size_t size = strlen (shell);
    3549           char *buf = xmalloc (size + 7);
    3550           memcpy (buf, shell, size);
    3551           memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
     3782          && (shell[0] == '/' || shell[0] == '\\'))
     3783        {
     3784          /* trying a new shell, check whether it exists */
     3785          size_t size = strlen (shell);
     3786          char *buf = xmalloc (size + 7);
     3787          memcpy (buf, shell, size);
     3788          memcpy (buf + size, ".exe", 5); /* including the trailing '\0' */
    35523789          if (access (shell, F_OK) != 0 && access (buf, F_OK) != 0)
    3553             {
    3554               /* try the same for the unixroot drive */
    3555               memmove (buf + 2, buf, size + 5);
    3556               buf[0] = unixroot[0];
    3557               buf[1] = unixroot[1];
    3558               if (access (buf, F_OK) == 0)
    3559                 /* we have found a shell! */
    3560                 /* free(shell); */
    3561                 shell = buf;
    3562               else
    3563                 free (buf);
    3564             }
    3565           else
     3790            {
     3791              /* try the same for the unixroot drive */
     3792              memmove (buf + 2, buf, size + 5);
     3793              buf[0] = unixroot[0];
     3794              buf[1] = unixroot[1];
     3795              if (access (buf, F_OK) == 0)
     3796                /* we have found a shell! */
     3797                /* free(shell); */
     3798                shell = buf;
     3799              else
     3800                free (buf);
     3801            }
     3802          else
    35663803            free (buf);
    3567         }
     3804        }
    35683805    }
    35693806#endif /* __EMX__ */
     
    35753812  }
    35763813
    3577 #ifdef CONFIG_WITH_KMK_BUILTIN
     3814# ifdef CONFIG_WITH_KMK_BUILTIN
    35783815  /* If it's a kmk_builtin command, make sure we're treated like a
    35793816     unix shell and and don't get batch files. */
    35803817  if (   (  !unixy_shell
    35813818          || batch_mode_shell
    3582 # ifdef WINDOWS32
     3819#  ifdef WINDOWS32
    35833820          || no_default_sh_exe
    3584 # endif
     3821#  endif
    35853822         )
    35863823      && line
    3587       && !strncmp(line, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
     3824      && !strncmp (line, "kmk_builtin_", sizeof("kmk_builtin_") - 1))
    35883825  {
    35893826    int saved_batch_mode_shell = batch_mode_shell;
    35903827    int saved_unixy_shell = unixy_shell;
    3591 # ifdef WINDOWS32
     3828#  ifdef WINDOWS32
    35923829    int saved_no_default_sh_exe = no_default_sh_exe;
    35933830    no_default_sh_exe = 0;
    3594 # endif
     3831#  endif
    35953832    unixy_shell = 1;
    35963833    batch_mode_shell = 0;
    35973834    argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
    3598                                             cmd_flags, batch_filename_ptr);
     3835                                            cmd_flags, batch_filename);
    35993836    batch_mode_shell = saved_batch_mode_shell;
    36003837    unixy_shell = saved_unixy_shell;
    3601 # ifdef WINDOWS32
     3838#  ifdef WINDOWS32
    36023839    no_default_sh_exe = saved_no_default_sh_exe;
    3603 # endif
     3840#  endif
    36043841  }
    36053842  else
    3606 #endif /* CONFIG_WITH_KMK_BUILTIN */
     3843# endif /* CONFIG_WITH_KMK_BUILTIN */
    36073844  argv = construct_command_argv_internal (line, restp, shell, shellflags, ifs,
    3608                                           cmd_flags, batch_filename_ptr);
     3845                                          cmd_flags, batch_filename);
    36093846
    36103847  free (shell);
     
    36233860
    36243861  (void) close (new);
    3625   fd = dup (old);
     3862  EINTRLOOP (fd, dup (old));
    36263863  if (fd != new)
    36273864    {
     
    36503887          if (len > print_time_width)
    36513888            print_time_width = len;
    3652           message (1, _("%*s - %s"), print_time_width, buf, c ->file->name);
     3889          message (1, print_time_width + strlen (c->file->name),
     3890                   _("%*s - %s"), print_time_width, buf, c->file->name);
    36533891        }
    36543892    }
  • trunk/src/kmk/job.h

    r2591 r3140  
    11/* Definitions for managing subprocesses in GNU Make.
    2 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
    3 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
    4 Foundation, Inc.
     2Copyright (C) 1992-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #ifndef SEEN_JOB_H
    20 #define SEEN_JOB_H
     17#include "output.h"
    2118
    2219#ifdef HAVE_FCNTL_H
     
    2825/* How to set close-on-exec for a file descriptor.  */
    2926
    30 #if !defined F_SETFD
    31 # define CLOSE_ON_EXEC(_d)
     27#if !defined(F_SETFD) || !defined(F_GETFD)
     28# ifdef WINDOWS32
     29#  define CLOSE_ON_EXEC(_d)  process_noinherit(_d)
     30# else
     31#  define CLOSE_ON_EXEC(_d)
     32# endif
    3233#else
    3334# ifndef FD_CLOEXEC
     
    3738#endif
    3839
     40#ifdef NO_OUTPUT_SYNC
     41# define RECORD_SYNC_MUTEX(m) \
     42    O (error, NILF,                                                    \
     43       _("-O[TYPE] (--output-sync[=TYPE]) is not configured for this build."));
     44#else
     45# ifdef WINDOWS32
     46/* For emulations in w32/compat/posixfcn.c.  */
     47#  define F_GETFD 1
     48#  define F_SETLKW 2
     49/* Implementation note: None of the values of l_type below can be zero
     50   -- they are compared with a static instance of the struct, so zero
     51   means unknown/invalid, see w32/compat/posixfcn.c. */
     52#  define F_WRLCK 1
     53#  define F_UNLCK 2
     54
     55struct flock
     56  {
     57    short l_type;
     58    short l_whence;
     59    off_t l_start;
     60    off_t l_len;
     61    pid_t l_pid;
     62  };
     63
     64/* This type is actually a HANDLE, but we want to avoid including
     65   windows.h as much as possible.  */
     66typedef intptr_t sync_handle_t;
     67
     68/* Public functions emulated/provided in posixfcn.c.  */
     69int fcntl (intptr_t fd, int cmd, ...);
     70intptr_t create_mutex (void);
     71int same_stream (FILE *f1, FILE *f2);
     72
     73#  define RECORD_SYNC_MUTEX(m) record_sync_mutex(m)
     74void record_sync_mutex (const char *str);
     75void prepare_mutex_handle_string (intptr_t hdl);
     76# else  /* !WINDOWS32 */
     77
     78typedef int sync_handle_t;      /* file descriptor */
     79
     80#  define RECORD_SYNC_MUTEX(m) (void)(m)
     81
     82# endif
     83#endif  /* !NO_OUTPUT_SYNC */
     84
    3985/* Structure describing a running or dead child process.  */
    4086
    4187struct child
    4288  {
    43     struct child *next;         /* Link in the chain.  */
     89    struct child *next;         /* Link in the chain.  */
    4490
    45     struct file *file;          /* File being remade.  */
     91    struct file *file;          /* File being remade.  */
    4692
    47     char **environment;         /* Environment for commands.  */
     93    char **environment;         /* Environment for commands.  */
     94    char *sh_batch_file;        /* Script file for shell commands */
     95    char **command_lines;       /* Array of variable-expanded cmd lines.  */
     96    char *command_ptr;          /* Ptr into command_lines[command_line].  */
    4897
    49     char **command_lines;       /* Array of variable-expanded cmd lines.  */
    50     unsigned int command_line;  /* Index into above.  */
    51     char *command_ptr;          /* Ptr into command_lines[command_line].  */
     98#ifdef VMS
     99    char *comname;              /* Temporary command file name */
     100    int efn;                    /* Completion event flag number */
     101    int cstatus;                /* Completion status */
     102    int vms_launch_status;      /* non-zero if lib$spawn, etc failed */
     103#endif
    52104
    53     pid_t pid;                  /* Child process's ID number.  */
    54 #ifdef VMS
    55     int efn;                    /* Completion event flag number */
    56     int cstatus;                /* Completion status */
    57     char *comname;              /* Temporary command file name */
     105    unsigned int  command_line; /* Index into command_lines.  */
     106    struct output output;       /* Output for this child.  */
     107    pid_t         pid;          /* Child process's ID number.  */
     108    unsigned int  remote:1;     /* Nonzero if executing remotely.  */
     109    unsigned int  noerror:1;    /* Nonzero if commands contained a '-'.  */
     110    unsigned int  good_stdin:1; /* Nonzero if this child has a good stdin.  */
     111    unsigned int  deleted:1;    /* Nonzero if targets have been deleted.  */
     112    unsigned int  recursive:1;  /* Nonzero for recursive command ('+' etc.)  */
     113    unsigned int  dontcare:1;   /* Saved dontcare flag.  */
     114
     115#ifdef CONFIG_WITH_KMK_BUILTIN
     116    unsigned int has_status:1;  /* Nonzero if status is available. */
     117    int status;                 /* Status of the job. */
    58118#endif
    59     char *sh_batch_file;        /* Script file for shell commands */
    60 #ifdef CONFIG_WITH_KMK_BUILTIN
    61     int status;                 /* Status of the job. */
    62     unsigned int has_status:1;  /* Nonzero if status is available. */
    63 #endif
    64     unsigned int remote:1;      /* Nonzero if executing remotely.  */
    65 
    66     unsigned int noerror:1;     /* Nonzero if commands contained a `-'.  */
    67 
    68     unsigned int good_stdin:1;  /* Nonzero if this child has a good stdin.  */
    69     unsigned int deleted:1;     /* Nonzero if targets have been deleted.  */
    70     unsigned int dontcare:1;    /* Saved dontcare flag.  */
    71119#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
    72120    big_int start_ts;           /* nano_timestamp of the first command.  */
     
    76124extern struct child *children;
    77125
     126/* A signal handler for SIGCHLD, if needed.  */
     127RETSIGTYPE child_handler (int sig);
    78128int is_bourne_compatible_shell(const char *path);
    79129void new_job (struct file *file);
     
    83133char **construct_command_argv (char *line, char **restp, struct file *file,
    84134                               int cmd_flags, char** batch_file);
     135
    85136#ifdef VMS
    86 int child_execute_job (char *argv, struct child *child);
    87 #elif defined(__EMX__)
    88 int child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp);
     137int child_execute_job (struct child *child, char *argv);
    89138#else
    90 void child_execute_job (int stdin_fd, int stdout_fd, char **argv, char **envp);
     139# define FD_STDIN       (fileno (stdin))
     140# define FD_STDOUT      (fileno (stdout))
     141# define FD_STDERR      (fileno (stderr))
     142int child_execute_job (struct output *out, int good_stdin, char **argv, char **envp);
    91143#endif
     144
    92145#ifdef _AMIGA
    93 void exec_command (char **argv);
     146void exec_command (char **argv) __attribute__ ((noreturn));
    94147#elif defined(__EMX__)
    95148int exec_command (char **argv, char **envp);
    96149#else
    97 void exec_command (char **argv, char **envp);
     150void exec_command (char **argv, char **envp) __attribute__ ((noreturn));
    98151#endif
    99152
     
    104157void unblock_sigs (void);
    105158#else
    106 #ifdef  HAVE_SIGSETMASK
     159#ifdef  HAVE_SIGSETMASK
    107160extern int fatal_signal_mask;
    108 #define unblock_sigs()  sigsetmask (0)
     161#define unblock_sigs()  sigsetmask (0)
    109162#else
    110 #define unblock_sigs()
     163#define unblock_sigs()
    111164#endif
    112165#endif
    113166
    114167extern unsigned int jobserver_tokens;
    115 
    116 #endif /* SEEN_JOB_H */
  • trunk/src/kmk/kbuild-object.c

    r3065 r3140  
    2929*   Header Files                                                               *
    3030*******************************************************************************/
    31 #include "make.h"
     31#include "makeint.h"
    3232#include "filedef.h"
    3333#include "variable.h"
     
    8181    char                       *pszName;
    8282    /** The file location where this define was declared. */
    83     struct floc                 FileLoc;
     83    floc                        FileLoc;
    8484
    8585    /** Pointer to the next element in the global list. */
     
    153153static struct kbuild_object *
    154154parse_kbuild_object_variable_accessor(const char *pchExpr, size_t cchExpr,
    155                                       enum kBuildSeverity enmSeverity, const struct floc *pFileLoc,
     155                                      enum kBuildSeverity enmSeverity, const floc *pFileLoc,
    156156                                      const char **ppchVarNm, size_t *pcchVarNm, enum kBuildType *penmType);
    157157
     
    176176 * @param   ...                 Arguments for the format string.
    177177 */
    178 static void kbuild_report_problem(enum kBuildSeverity enmSeverity, const struct floc *pFileLoc,
     178static void kbuild_report_problem(enum kBuildSeverity enmSeverity, const floc *pFileLoc,
    179179                                  const char *pszFormat, ...)
    180180{
     
    193193    {
    194194        case kBuildSeverity_Warning:
    195             message(0, "%s", szBuf);
     195            OS(message, 0, "%s", szBuf);
    196196            break;
    197197        case kBuildSeverity_Error:
    198             error(pFileLoc, "%s", szBuf);
     198            OS(error, pFileLoc, "%s", szBuf);
    199199            break;
    200200        default:
    201201        case kBuildSeverity_Fatal:
    202             fatal(pFileLoc, "%s", szBuf);
     202            OS(fatal, pFileLoc, "%s", szBuf);
    203203            break;
    204204    }
     
    340340static const char *
    341341kbuild_replace_special_accessors(const char *pchValue, size_t *pcchValue, int *pfDuplicateValue,
    342                                  const struct floc *pFileLoc)
     342                                 const floc *pFileLoc)
    343343{
    344344    size_t      cchValue    = *pcchValue;
     
    464464        }
    465465        else
    466             error(pFileLoc, _("The '$([%.*s...' accessor can only be used in the context of a kBuild object"),
     466            error(pFileLoc, 20, _("The '$([%.*s...' accessor can only be used in the context of a kBuild object"),
    467467                  MAX(cchLeft, 20), pchLeft);
    468468    }
     
    475475                                     const char *pchValue, size_t cchValue,
    476476                                     int fDuplicateValue, enum variable_origin enmOrigin,
    477                                      int fRecursive, int fNoSpecialAccessors, const struct floc *pFileLoc)
     477                                     int fRecursive, int fNoSpecialAccessors, const floc *pFileLoc)
    478478{
    479479    struct variable *pVar;
     
    504504                                              &global_variable_set, pFileLoc);
    505505        if (!pAlias->alias)
    506             error(pFileLoc, _("Error defining alias '%s'"), pszPrefixed);
     506            OS(error, pFileLoc, _("Error defining alias '%s'"), pszPrefixed);
    507507    }
    508508
     
    515515                              const char *pchValue, size_t cchValue,
    516516                              int fDuplicateValue, enum variable_origin enmOrigin,
    517                               int fRecursive, const struct floc *pFileLoc)
     517                              int fRecursive, const floc *pFileLoc)
    518518{
    519519    return define_kbuild_object_variable_cached(pObj, strcache2_add(&variable_strcache, pchName, cchName),
     
    549549                                               const char *pszValue, size_t cchValue, int fDuplicateValue,
    550550                                               enum variable_origin enmOrigin, int fRecursive,
    551                                                struct floc const *pFileLoc)
     551                                               floc const *pFileLoc)
    552552{
    553553    struct kbuild_object   *pObj;
     
    561561        assert(pObj != NULL);
    562562        if (!is_valid_kbuild_object_variable_name(pchVarNm, cchVarNm))
    563             fatal(pFileLoc, _("Invalid kBuild object variable name: '%.*s' ('%.*s')"),
     563            fatal(pFileLoc, cchVarNm + cchName, _("Invalid kBuild object variable name: '%.*s' ('%.*s')"),
    564564                  (int)cchVarNm, pchVarNm, (int)cchName, pchName);
    565565        return define_kbuild_object_variable_cached(pObj, strcache2_add(&variable_strcache, pchVarNm, cchVarNm),
     
    596596                                         const char *pszValue, size_t cchValue, int fDuplicateValue,
    597597                                         enum variable_origin enmOrigin, int fRecursive,
    598                                          struct floc const *pFileLoc)
     598                                         floc const *pFileLoc)
    599599{
    600600    assert(g_pTopKbEvalData != NULL);
    601601
    602602    if (!is_valid_kbuild_object_variable_name(pchName, cchName))
    603         fatal(pFileLoc, _("Invalid kBuild object variable name: '%.*s'"), (int)cchName, pchName);
     603        fatal(pFileLoc, cchName, _("Invalid kBuild object variable name: '%.*s'"), (int)cchName, pchName);
    604604
    605605    return define_kbuild_object_variable_cached(g_pTopKbEvalData->pObj, strcache2_add(&variable_strcache, pchName, cchName),
     
    631631                                  const char *pchValue, size_t cchValue, int fSimpleValue,
    632632                                  enum variable_origin enmOrigin, int fAppend,
    633                                   const struct floc *pFileLoc)
     633                                  const floc *pFileLoc)
    634634{
    635635    struct kbuild_object   *pObj;
     
    660660     */
    661661    if (!is_valid_kbuild_object_variable_name(pchName, cchName))
    662         fatal(pFileLoc, _("Invalid kBuild object variable name: '%.*s'"), (int)cchName, pchName);
     662        fatal(pFileLoc, cchName, _("Invalid kBuild object variable name: '%.*s'"), (int)cchName, pchName);
    663663
    664664    /*
     
    844844                    &&  (   pCur->pParent == pObj
    845845                         || !strcmp(pCur->pszParent, pObj->pszName)) )
    846                     fatal(&pObj->FileLoc, _("'%s' and '%s' are both trying to be each other children..."),
    847                           pObj->pszName, pCur->pszName);
     846                    OSS(fatal, &pObj->FileLoc, _("'%s' and '%s' are both trying to be each other children..."),
     847                        pObj->pszName, pCur->pszName);
    848848
    849849                pObj->pParent = pCur;
     
    857857        /* Not found. */
    858858        if (!fQuiet)
    859             error(&pObj->FileLoc, _("Could not locate parent '%s' of '%s'"), pObj->pszParent, pObj->pszName);
     859            OSS(error, &pObj->FileLoc, _("Could not locate parent '%s' of '%s'"), pObj->pszParent, pObj->pszName);
    860860    }
    861861    return pObj->pParent;
     
    892892
    893893static int
    894 eval_kbuild_define_xxxx(struct kbuild_eval_data **ppData, const struct floc *pFileLoc,
     894eval_kbuild_define_xxxx(struct kbuild_eval_data **ppData, const floc *pFileLoc,
    895895                        const char *pszLine, const char *pszEos, int fIgnoring, enum kBuildType enmType)
    896896{
     
    933933    pObj->pszName = allocate_expanded_next_token(&pszLine, pszEos, &pObj->cchName, 1 /*strip*/);
    934934    if (!pObj->pszName || !*pObj->pszName)
    935         fatal(pFileLoc, _("The kBuild define requires a name"));
     935        O(fatal, pFileLoc, _("The kBuild define requires a name"));
    936936
    937937    psz = pObj->pszName;
     
    939939        if (!isgraph(ch))
    940940        {
    941             error(pFileLoc, _("The 'kBuild-define-%s' name '%s' contains one or more invalid characters"),
    942                   eval_kbuild_type_to_string(enmType), pObj->pszName);
     941            OSS(error, pFileLoc, _("The 'kBuild-define-%s' name '%s' contains one or more invalid characters"),
     942                eval_kbuild_type_to_string(enmType), pObj->pszName);
    943943            break;
    944944        }
     
    955955        case kBuildType_Unit:        pszPrefix = "UNIT_"; break;
    956956        default:
    957             fatal(pFileLoc, _("enmType=%d"), enmType);
     957            ON(fatal, pFileLoc, _("enmType=%d"), enmType);
    958958            return -1;
    959959    }
     
    974974            /* Inheritance directive. */
    975975            if (pObj->pszParent != NULL)
    976                 fatal(pFileLoc, _("'extending' can only occure once"));
     976                O(fatal, pFileLoc, _("'extending' can only occure once"));
    977977            pObj->pszParent = allocate_expanded_next_token(&pszLine, pszEos, &pObj->cchParent, 1 /*strip*/);
    978978            if (!pObj->pszParent || !*pObj->pszParent)
    979                 fatal(pFileLoc, _("'extending' requires a parent name"));
     979                O(fatal, pFileLoc, _("'extending' requires a parent name"));
    980980        }
    981981        else if (WORD_IS(psz, cch, "using"))
     
    986986            /* Template directive. */
    987987            if (enmType != kBuildType_Target)
    988                 fatal(pFileLoc, _("'using <template>' can only be used with 'kBuild-define-target'"));
     988                O(fatal, pFileLoc, _("'using <template>' can only be used with 'kBuild-define-target'"));
    989989            if (pObj->pszTemplate != NULL)
    990                 fatal(pFileLoc, _("'using' can only occure once"));
     990                O(fatal, pFileLoc, _("'using' can only occure once"));
    991991
    992992            pszTemplate = allocate_expanded_next_token(&pszLine, pszEos, &cchTemplate, 1 /*fStrip*/);
    993993            if (!pszTemplate || !*pszTemplate)
    994                 fatal(pFileLoc, _("'using' requires a template name"));
     994                O(fatal, pFileLoc, _("'using' requires a template name"));
    995995
    996996            define_kbuild_object_variable_cached(pObj, g_pszVarNmTemplate, pszTemplate, cchTemplate,
     
    10001000        }
    10011001        else
    1002             fatal(pFileLoc, _("Don't know what '%.*s' means"), (int)cch, psz);
     1002            fatal(pFileLoc, cch, _("Don't know what '%.*s' means"), (int)cch, psz);
    10031003
    10041004        /* next token */
     
    10271027
    10281028static int
    1029 eval_kbuild_endef_xxxx(struct kbuild_eval_data **ppData, const struct floc *pFileLoc,
     1029eval_kbuild_endef_xxxx(struct kbuild_eval_data **ppData, const floc *pFileLoc,
    10301030                       const char *pszLine, const char *pszEos, int fIgnoring, enum kBuildType enmType)
    10311031{
     
    10441044    if (!pData)
    10451045    {
    1046         error(pFileLoc, _("kBuild-endef-%s is missing kBuild-define-%s"),
    1047               eval_kbuild_type_to_string(enmType), eval_kbuild_type_to_string(enmType));
     1046        OSS(error, pFileLoc, _("kBuild-endef-%s is missing kBuild-define-%s"),
     1047            eval_kbuild_type_to_string(enmType), eval_kbuild_type_to_string(enmType));
    10481048        return 0;
    10491049    }
     
    10541054    pObj = pData->pObj;
    10551055    if (pObj->enmType != enmType)
    1056         error(pFileLoc, _("'kBuild-endef-%s' does not match 'kBuild-define-%s %s'"),
    1057               eval_kbuild_type_to_string(enmType), eval_kbuild_type_to_string(pObj->enmType), pObj->pszName);
     1056        OSSS(error, pFileLoc, _("'kBuild-endef-%s' does not match 'kBuild-define-%s %s'"),
     1057             eval_kbuild_type_to_string(enmType), eval_kbuild_type_to_string(pObj->enmType), pObj->pszName);
    10581058
    10591059    /*
     
    10661066        if (   cchName != pObj->cchName
    10671067            || strcmp(pszName, pObj->pszName))
    1068             error(pFileLoc, _("'kBuild-endef-%s %s' does not match 'kBuild-define-%s %s'"),
     1068            OSSSS(error, pFileLoc, _("'kBuild-endef-%s %s' does not match 'kBuild-define-%s %s'"),
    10691069                  eval_kbuild_type_to_string(enmType), pszName,
    10701070                  eval_kbuild_type_to_string(pObj->enmType), pObj->pszName);
     
    10851085}
    10861086
    1087 int eval_kbuild_read_hook(struct kbuild_eval_data **kdata, const struct floc *flocp,
     1087int eval_kbuild_read_hook(struct kbuild_eval_data **kdata, const floc *flocp,
    10881088                          const char *pchWord, size_t cchWord, const char *line, const char *eos, int ignoring)
    10891089{
     
    11241124     * extensions, at least until legacy assignments/whatever turns up.
    11251125     */
    1126     error(flocp, _("Unknown syntax 'kBuild-%.*s'"), (int)cchWord, pchWord);
     1126    error(flocp, cchWord, _("Unknown syntax 'kBuild-%.*s'"), (int)cchWord, pchWord);
    11271127    return 0;
    11281128}
     
    11891189static struct kbuild_object *
    11901190parse_kbuild_object_variable_accessor(const char *pchExpr, size_t cchExpr,
    1191                                       enum kBuildSeverity enmSeverity, const struct floc *pFileLoc,
     1191                                      enum kBuildSeverity enmSeverity, const floc *pFileLoc,
    11921192                                      const char **ppchVarNm, size_t *pcchVarNm, enum kBuildType *penmType)
    11931193{
     
    13951395        putchar('\n');
    13961396
    1397         print_variable_set(pCur->pVariables->set, "");
     1397        print_variable_set(pCur->pVariables->set, "", 0);
    13981398
    13991399        printf("kBuild-endef-%s  %s\n",
  • trunk/src/kmk/kbuild.c

    r3068 r3140  
    3030*******************************************************************************/
    3131#define NO_MEMCOPY_HACK
    32 #include "make.h"
     32#include "makeint.h"
    3333#include "filedef.h"
    3434#include "variable.h"
     
    116116        g_pszInitialCwd = xstrdup(szTmp);
    117117    else
    118         fatal(NILF, _("getcwd failed"));
     118        O(fatal, NILF, _("getcwd failed"));
    119119
    120120    /*
     
    282282                strcat(strcpy(pszTmp2, get_kbuild_bin_path()), "/../..");
    283283                if (!my_abspath(pszTmp2, szTmpPath))
    284                     fatal(NILF, _("failed to determin KBUILD_PATH"));
     284                    O(fatal, NILF, _("failed to determin KBUILD_PATH"));
    285285#endif
    286286            }
     
    332332
    333333                if (!my_abspath(pszTmp2, szTmpPath))
    334                     fatal(NILF, _("failed to determin KBUILD_BIN_PATH (pszTmp2=%s szTmpPath=%s)"), pszTmp2, szTmpPath);
     334                    OSS(fatal, NILF, _("failed to determin KBUILD_BIN_PATH (pszTmp2=%s szTmpPath=%s)"), pszTmp2, szTmpPath);
    335335#endif /* !KBUILD_PATH */
    336336            }
     
    506506    struct variable *pVar = lookup_variable(pszName, cchName);
    507507    if (!pVar)
    508         fatal(NILF, _("variable `%.*s' isn't defined!"), (int)cchName, pszName);
     508        fatal(NILF, cchName, _("variable `%.*s' isn't defined!"), (int)cchName, pszName);
    509509    if (pVar->recursive)
    510         fatal(NILF, _("variable `%.*s' is defined as `recursive' instead of `simple'!"), (int)cchName, pszName);
     510        fatal(NILF, cchName, _("variable `%.*s' is defined as `recursive' instead of `simple'!"), (int)cchName, pszName);
    511511
    512512    MY_ASSERT_MSG(strlen(pVar->value) == pVar->value_length,
     
    528528    struct variable *pVar = lookup_variable(pszName, strlen(pszName));
    529529    if (!pVar)
    530         fatal(NILF, _("variable `%s' isn't defined!"), pszName);
     530        OS(fatal, NILF, _("variable `%s' isn't defined!"), pszName);
    531531
    532532    MY_ASSERT_MSG(strlen(pVar->value) == pVar->value_length,
     
    980980        psz = pVar->value;
    981981        pszEnd = psz + pVar->value_length;
    982         while (isblank((unsigned char)*psz))
     982        while (ISBLANK(*psz))
    983983            psz++;
    984         while (pszEnd > psz && isblank((unsigned char)pszEnd[-1]))
     984        while (pszEnd > psz && ISBLANK(pszEnd[-1]))
    985985            pszEnd--;
    986986        if (pszEnd > psz)
     
    10351035                                              pszVarName);
    10361036    if (!pVar)
    1037         fatal(NILF, _("no tool for source `%s' in target `%s'!"), pSource->value, pTarget->value);
     1037        OSS(fatal, NILF, _("no tool for source `%s' in target `%s'!"), pSource->value, pTarget->value);
    10381038    return pVar;
    10391039}
     
    10841084                                              pszVarName);
    10851085    if (!pVar)
    1086         fatal(NILF, _("no OBJSUFF attribute or SUFF_OBJ default for source `%s' in target `%s'!"), pSource->value, pTarget->value);
     1086        OSS(fatal, NILF, _("no OBJSUFF attribute or SUFF_OBJ default for source `%s' in target `%s'!"),
     1087            pSource->value, pTarget->value);
    10871088    return pVar;
    10881089}
     
    18411842        iDirection = -1;
    18421843    else
    1843         fatal(NILF, _("incorrect direction argument `%s'!"), argv[2]);
     1844        OS(fatal, NILF, _("incorrect direction argument `%s'!"), argv[2]);
    18441845    if (argv[3])
    18451846    {
    18461847        const char *psz = argv[3];
    1847         while (isspace(*psz))
     1848        while (ISSPACE(*psz))
    18481849            psz++;
    18491850        if (*psz)
     
    19191920        psz--;
    19201921        if (psz <= pszResult)
    1921             fatal(NULL, "whut!?! no path? result=`%s'", pszResult);
     1922            OS(fatal, NULL, "whut!?! no path? result=`%s'", pszResult);
    19221923#ifdef HAVE_DOS_PATHS
    19231924        if (*psz == ':')
     
    20422043                iVer = 0;
    20432044                psz = argv[0];
    2044                 while (isblank((unsigned char)*psz))
     2045                while (ISBLANK(*psz))
    20452046                    psz++;
    20462047                if (*psz)
     
    22642265
    22652266    install_variable_buffer(&pszSavedVarBuf, &cchSavedVarBuf);
    2266     eval_buffer(pszVal, psz);
     2267    eval_buffer(pszVal, NULL, psz);
    22672268    restore_variable_buffer(pszSavedVarBuf, cchSavedVarBuf);
    22682269
     
    25022503     */
    25032504    if (pszVersion[0] != '1' || pszVersion[1])
    2504       fatal(NULL, "%s: Unsupported version `%s'", pszFuncName, pszVersion);
     2505      OSS(fatal, NULL, "%s: Unsupported version `%s'", pszFuncName, pszVersion);
    25052506
    25062507    if (!cchBldTrg)
    2507       fatal(NULL, "%s: missing bldtrg", pszFuncName);
     2508      OS(fatal, NULL, "%s: missing bldtrg", pszFuncName);
    25082509
    25092510    if (!cchBldTrgArch)
    2510       fatal(NULL, "%s: missing bld_trg_arch", pszFuncName);
     2511      OS(fatal, NULL, "%s: missing bld_trg_arch", pszFuncName);
    25112512
    25122513    if (!cchBldTrgCpu)
    2513       fatal(NULL, "%s: missing bld_trg_cpu", pszFuncName);
     2514      OS(fatal, NULL, "%s: missing bld_trg_cpu", pszFuncName);
    25142515
    25152516    if (!cchBldType)
    2516       fatal(NULL, "%s: missing bld_type", pszFuncName);
     2517      OS(fatal, NULL, "%s: missing bld_type", pszFuncName);
    25172518
    25182519    /*
     
    26332634    {
    26342635        if (   pDefTemplate->value_length
    2635             && (   isspace(pDefTemplate->value[0])
    2636                 || isspace(pDefTemplate->value[pDefTemplate->value_length - 1])))
     2636            && (   ISSPACE(pDefTemplate->value[0])
     2637                || ISSPACE(pDefTemplate->value[pDefTemplate->value_length - 1])))
    26372638        {
    26382639            unsigned int off;
    26392640            if (pDefTemplate->rdonly_val)
    2640                 fatal(NULL, "%s: TEMPLATE is read-only", pszFuncName);
     2641                OS(fatal, NULL, "%s: TEMPLATE is read-only", pszFuncName);
    26412642
    26422643            /* head */
    2643             for (off = 0; isspace(pDefTemplate->value[off]); off++)
     2644            for (off = 0; ISSPACE(pDefTemplate->value[off]); off++)
    26442645                /* nothing */;
    26452646            if (off)
     
    26512652            /* tail */
    26522653            off = pDefTemplate->value_length;
    2653             while (off > 0 && isspace(pDefTemplate->value[off - 1]))
     2654            while (off > 0 && ISSPACE(pDefTemplate->value[off - 1]))
    26542655                off--;
    26552656            pDefTemplate->value_length = off;
     
    27062707            pszTmpl = pTmpl->value;
    27072708            cchTmpl = pTmpl->value_length;
    2708             while (isspace(*pszTmpl))
     2709            while (ISSPACE(*pszTmpl))
    27092710                cchTmpl--, pszTmpl++;
    27102711            if (!cchTmpl)
  • trunk/src/kmk/kbuild.h

    r2717 r3140  
    5858                                                                   const char *pszValue, size_t cchValue, int fDuplicateValue,
    5959                                                                   enum variable_origin enmOrigin, int fRecursive,
    60                                                                    struct floc const *pFileLoc);
     60                                                                   floc const *pFileLoc);
    6161struct variable    *define_kbuild_object_variable_in_top_obj(const char *pszName, size_t cchName,
    6262                                                             const char *pszValue, size_t cchValue, int fDuplicateValue,
    6363                                                             enum variable_origin enmOrigin, int fRecursive,
    64                                                              struct floc const *pFileLoc);
     64                                                             floc const *pFileLoc);
    6565struct variable    *kbuild_object_variable_pre_append(const char *pchName, size_t cchName,
    6666                                                      const char *pchValue, size_t cchValue, int fSimpleValue,
    6767                                                      enum variable_origin enmOrigin, int fAppend,
    68                                                       const struct floc *pFileLoc);
    69 int                 eval_kbuild_read_hook(struct kbuild_eval_data **kdata, const struct floc *flocp,
     68                                                      const floc *pFileLoc);
     69int                 eval_kbuild_read_hook(struct kbuild_eval_data **kdata, const floc *flocp,
    7070                                          const char *word, size_t wlen, const char *line, const char *eos, int ignoring);
    7171void                print_kbuild_data_base(void);
  • trunk/src/kmk/kdepdb.c

    r2450 r3140  
    2727*   Header Files                                                               *
    2828*******************************************************************************/
    29 #include "make.h"
     29#include "makeint.h"
    3030#include "../lib/k/kDefs.h"
    3131#include "../lib/k/kTypes.h"
  • trunk/src/kmk/kmk_cc_exec.c

    r2817 r3140  
    2929*   Header Files                                                                                                                 *
    3030*********************************************************************************************************************************/
    31 #include "make.h"
     31#include "makeint.h"
    3232
    3333#include "dep.h"
     
    21142114                        if (   cchName >= MIN_FUNCTION_LENGTH
    21152115                            && cchName <= MAX_FUNCTION_LENGTH
    2116                             && (isblank(ch) || ch == chClose || cchName == cchStr)
     2116                            && (ISBLANK(ch) || ch == chClose || cchName == cchStr)
    21172117                            && (pfnFunction = lookup_function_for_compiler(pchStr, cchName, &cMinArgs, &cMaxArgs,
    21182118                                                                           &fExpandArgs, &pszFunction)) != NULL)
     
    21282128                                /* Skip leading spaces before the first arg. */
    21292129                                cchName++;
    2130                                 while (cchName < cchStr && isblank((unsigned char)pchStr[cchName]))
     2130                                while (cchName < cchStr && ISBLANK(pchStr[cchName]))
    21312131                                    cchName++;
    21322132
  • trunk/src/kmk/kmkbuiltin/append.c

    r3134 r3140  
    2828*******************************************************************************/
    2929#ifndef kmk_builtin_append
    30 # include "make.h"
     30# include "makeint.h"
    3131# include "filedef.h"
    3232# include "variable.h"
  • trunk/src/kmk/kmkbuiltin/expr.c

    r2591 r3140  
    3333static int               is_zero_or_null(struct val *);
    3434static void              nexttoken(int);
    35 static void              error(void);
    3635static struct val       *eval6(void);
    3736static struct val       *eval5(void);
     
    284283__attribute__((noreturn))
    285284#endif
     285#ifdef _MSC_VER
     286__declspec(noreturn)
     287#endif
    286288static void
    287289error(void)
  • trunk/src/kmk/kmkbuiltin/kSubmit.c

    r3051 r3140  
    3030# define _POSIX_C_SOURCE 1 /* 10.4 sdk and unsetenv */
    3131#endif
    32 #include "make.h"
     32#include "makeint.h"
    3333#include "job.h"
    3434#include "variable.h"
  • trunk/src/kmk/kmkbuiltin/mscfakes.c

    r3117 r3140  
    4444#undef utimes
    4545#undef lutimes
    46 
    47 #define timeval windows_timeval
    48 #include <Windows.h>
    49 #undef timeval
    5046
    5147extern ssize_t maybe_con_write(int, void const *, size_t);
     
    662658
    663659
    664 int utimes(const char *pszPath, const struct timeval *paTimes)
     660int utimes(const char *pszPath, const struct msc_timeval *paTimes)
    665661{
    666662    if (paTimes)
     
    677673
    678674
    679 int lutimes(const char *pszPath, const struct timeval *paTimes)
     675int lutimes(const char *pszPath, const struct msc_timeval *paTimes)
    680676{
    681677    if (paTimes)
     
    692688
    693689
    694 int gettimeofday(struct timeval *pNow, void *pvIgnored)
     690int gettimeofday(struct msc_timeval *pNow, void *pvIgnored)
    695691{
    696692    struct __timeb64 Now;
  • trunk/src/kmk/kmkbuiltin/mscfakes.h

    r3092 r3140  
    110110#endif
    111111
    112 struct timeval
     112struct msc_timeval
    113113{
    114114    __time64_t tv_sec;
    115115    long tv_usec;
    116116};
     117#define timeval msc_timeval
    117118
    118119struct iovec
     
    160161#endif
    161162int symlink(const char *pszDst, const char *pszLink);
    162 int utimes(const char *pszPath, const struct timeval *paTimes);
    163 int lutimes(const char *pszPath, const struct timeval *paTimes);
     163int utimes(const char *pszPath, const struct msc_timeval *paTimes);
     164int lutimes(const char *pszPath, const struct msc_timeval *paTimes);
    164165ssize_t writev(int fd, const struct iovec *vector, int count);
    165166
    166 int gettimeofday(struct timeval *pNow, void *pvIgnored);
     167int gettimeofday(struct msc_timeval *pNow, void *pvIgnored);
    167168struct tm *localtime_r(const __time64_t *pNow, struct tm *pResult);
    168169__time64_t timegm(struct tm *pNow);
  • trunk/src/kmk/kmkbuiltin/printf.c

    r2900 r3140  
    4747
    4848#if !defined(kmk_builtin_printf) && !defined(BUILTIN) && !defined(SHELL)
    49 # include "../make.h"
     49# include "../makeint.h"
    5050# include "../filedef.h"
    5151# include "../variable.h"
     
    217217        g_o = NULL;
    218218
    219         (void)funcname;
    220219        if (rc != 0)
    221                 fatal (NILF, _("$(%s): failure rc=%d\n"), funcname, rc);
     220                fatal(NILF, strlen(funcname) + INTSTR_LENGTH, _("$(%s): failure rc=%d\n"), funcname, rc);
    222221        return o;
    223222}
  • trunk/src/kmk/kmkbuiltin/redirect.c

    r3110 r3140  
    3030/*# define _POSIX_C_SOURCE 1  / *  10.4 sdk and unsetenv  * / - breaks O_CLOEXEC on 10.8 */
    3131#endif
    32 #include "make.h"
     32#include "makeint.h"
    3333#include <assert.h>
    3434#include <stdio.h>
  • trunk/src/kmk/kmkbuiltin/touch.c

    r3074 r3140  
    2727*   Header Files                                                               *
    2828*******************************************************************************/
    29 #include "make.h"
     29#include "makeint.h"
    3030#include <assert.h>
    3131#include <stdarg.h>
  • trunk/src/kmk/main.c

    r3123 r3140  
    11/* Argument parsing and main program of GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
     18#include "os.h"
     19#include "filedef.h"
    2020#include "dep.h"
    21 #include "filedef.h"
    2221#include "variable.h"
    2322#include "job.h"
     
    3635#endif
    3736#ifdef WINDOWS32
    38 #include <windows.h>
    39 #include <io.h>
    40 #include "pathstuff.h"
     37# include <windows.h>
     38# include <io.h>
     39# include "pathstuff.h"
     40# include "sub_proc.h"
     41# include "w32err.h"
    4142#endif
    4243#ifdef __EMX__
     
    7576int __stack = 20000; /* Make sure we have 20K of stack space */
    7677#endif
    77 
    78 void init_dir (void);
    79 void remote_setup (void);
    80 void remote_cleanup (void);
    81 RETSIGTYPE fatal_error_signal (int sig);
    82 
    83 void print_variable_data_base (void);
    84 void print_dir_data_base (void);
    85 void print_rule_data_base (void);
    86 void print_vpath_data_base (void);
    87 
    88 void verify_file_data_base (void);
     78#ifdef VMS
     79int vms_use_mcr_command = 0;
     80int vms_always_use_cmd_file = 0;
     81int vms_gnv_shell = 0;
     82int vms_legacy_behavior = 0;
     83int vms_comma_separator = 0;
     84int vms_unix_simulation = 0;
     85int vms_report_unix_paths = 0;
     86
     87/* Evaluates if a VMS environment option is set, only look at first character */
     88static int
     89get_vms_env_flag (const char *name, int default_value)
     90{
     91char * value;
     92char x;
     93
     94  value = getenv (name);
     95  if (value == NULL)
     96    return default_value;
     97
     98  x = toupper (value[0]);
     99  switch (x)
     100    {
     101    case '1':
     102    case 'T':
     103    case 'E':
     104      return 1;
     105      break;
     106    case '0':
     107    case 'F':
     108    case 'D':
     109      return 0;
     110    }
     111}
     112#endif
    89113
    90114#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
     
    101125int chdir ();
    102126#endif
    103 #ifndef STDC_HEADERS
    104 # ifndef sun                    /* Sun has an incorrect decl in a header.  */
     127#ifndef STDC_HEADERS
     128# ifndef sun                    /* Sun has an incorrect decl in a header.  */
    105129void exit (int) __attribute__ ((noreturn));
    106130# endif
     
    111135static void print_data_base (void);
    112136static void print_version (void);
    113 static void decode_switches (int argc, char **argv, int env);
    114 static void decode_env_switches (char *envar, unsigned int len);
    115 static const char *define_makeflags (int all, int makefile);
     137static void decode_switches (int argc, const char **argv, int env);
     138static void decode_env_switches (const char *envar, unsigned int len);
     139static struct variable *define_makeflags (int all, int makefile);
    116140static char *quote_for_env (char *out, const char *in);
    117141static void initialize_global_hash_tables (void);
     
    123147struct command_switch
    124148  {
    125     int c;                      /* The switch character.  */
    126 
    127     enum                        /* Type of the value.  */
     149    int c;                      /* The switch character.  */
     150
     151    enum                        /* Type of the value.  */
    128152      {
    129         flag,                   /* Turn int flag on.  */
    130         flag_off,               /* Turn int flag off.  */
    131         string,                 /* One string per switch.  */
    132         filename,               /* A string containing a file name.  */
    133         positive_int,           /* A positive integer.  */
    134         floating,               /* A floating-point number (double).  */
    135         ignore                  /* Ignored.  */
     153        flag,                   /* Turn int flag on.  */
     154        flag_off,               /* Turn int flag off.  */
     155        string,                 /* One string per invocation.  */
     156        strlist,                /* One string per switch.  */
     157        filename,               /* A string containing a file name.  */
     158        positive_int,           /* A positive integer.  */
     159        floating,               /* A floating-point number (double).  */
     160        ignore                  /* Ignored.  */
    136161      } type;
    137162
    138     void *value_ptr;    /* Pointer to the value-holding variable.  */
    139 
    140     unsigned int env:1;         /* Can come from MAKEFLAGS.  */
    141     unsigned int toenv:1;       /* Should be put in MAKEFLAGS.  */
    142     unsigned int no_makefile:1; /* Don't propagate when remaking makefiles.  */
    143 
    144     const void *noarg_value;    /* Pointer to value used if no arg given.  */
    145     const void *default_value;  /* Pointer to default value.  */
    146 
    147     char *long_name;            /* Long option name.  */
     163    void *value_ptr;    /* Pointer to the value-holding variable.  */
     164
     165    unsigned int env:1;         /* Can come from MAKEFLAGS.  */
     166    unsigned int toenv:1;       /* Should be put in MAKEFLAGS.  */
     167    unsigned int no_makefile:1; /* Don't propagate when remaking makefiles.  */
     168
     169    const void *noarg_value;    /* Pointer to value used if no arg given.  */
     170    const void *default_value;  /* Pointer to default value.  */
     171
     172    const char *long_name;      /* Long option name.  */
    148173  };
    149174
     
    153178
    154179/* The structure used to hold the list of strings given
    155    in command switches of a type that takes string arguments.  */
     180   in command switches of a type that takes strlist arguments.  */
    156181
    157182struct stringlist
    158183  {
    159     const char **list;  /* Nil-terminated list of strings.  */
    160     unsigned int idx;   /* Index into above.  */
    161     unsigned int max;   /* Number of pointers allocated.  */
     184    const char **list;  /* Nil-terminated list of strings.  */
     185    unsigned int idx;   /* Index into above.  */
     186    unsigned int max;   /* Number of pointers allocated.  */
    162187  };
    163188
    164189
    165190/* The recognized command switches.  */
     191
     192/* Nonzero means do extra verification (that may slow things down).  */
     193
     194int verify_flag;
    166195
    167196/* Nonzero means do not print commands to be executed (-s).  */
     
    203232/* Print debugging info (--debug).  */
    204233
    205 static struct stringlist *db_flags;
     234static struct stringlist *db_flags = 0;
    206235static int debug_flag = 0;
    207236
    208237int db_level = 0;
    209238
    210 /* Output level (--verbosity).  */
    211 
    212 static struct stringlist *verbosity_flags;
     239/* Synchronize output (--output-sync).  */
     240
     241char *output_sync_option = 0;
    213242
    214243#ifdef WINDOWS32
     
    275304
    276305
    277 /* Number of job slots (commands that can be run at once).  */
    278 
    279 unsigned int job_slots = 1;
    280 unsigned int default_job_slots = 1;
     306/* Number of job slots for parallelism.  */
     307
     308unsigned int job_slots;
     309
     310#define INVALID_JOB_SLOTS (-1)
    281311static unsigned int master_job_slots = 0;
     312static int arg_job_slots = INVALID_JOB_SLOTS;
     313
     314#ifdef KMK
     315static int default_job_slots = INVALID_JOB_SLOTS;
     316#else
     317static const int default_job_slots = INVALID_JOB_SLOTS;
     318#endif
    282319
    283320/* Value of job_slots that means no limit.  */
    284321
    285 static unsigned int inf_jobs = 0;
    286 
    287 /* File descriptors for the jobs pipe.  */
    288 
    289 static struct stringlist *jobserver_fds = 0;
    290 
    291 int job_fds[2] = { -1, -1 };
    292 int job_rfd = -1;
     322static const int inf_jobs = 0;
     323
     324/* Authorization for the jobserver.  */
     325
     326static char *jobserver_auth = NULL;
     327
     328/* Handle for the mutex used on Windows to synchronize output of our
     329   children under -O.  */
     330
     331char *sync_mutex = NULL;
    293332
    294333/* Maximum load average at which multiple jobs will be run.
     
    429468                              Consider FILE to be very old and don't remake it.\n"),
    430469    N_("\
     470  -O[TYPE], --output-sync[=TYPE]\n\
     471                              Synchronize output of parallel jobs by TYPE.\n"),
     472    N_("\
    431473  -p, --print-data-base       Print make's internal database.\n"),
    432474    N_("\
     
    443485    N_("\
    444486  -t, --touch                 Touch targets instead of remaking them.\n"),
     487    N_("\
     488  --trace                     Print tracing information.\n"),
    445489    N_("\
    446490  -v, --version               Print the version number of make and exit.\n"),
     
    486530  };
    487531
    488 /* The table of command switches.  */
     532/* The table of command switches.
     533   Order matters here: this is the order MAKEFLAGS will be constructed.
     534   So be sure all simple flags (single char, no argument) come first.  */
    489535
    490536static const struct command_switch switches[] =
     
    492538    { 'b', ignore, 0, 0, 0, 0, 0, 0, 0 },
    493539    { 'B', flag, &always_make_set, 1, 1, 0, 0, 0, "always-make" },
    494     { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
    495540    { 'd', flag, &debug_flag, 1, 1, 0, 0, 0, 0 },
    496     { CHAR_MAX+1, string, &db_flags, 1, 1, 0, "basic", 0, "debug" },
    497541#ifdef WINDOWS32
    498542    { 'D', flag, &suspend_flag, 1, 1, 0, 0, 0, "suspend-for-debug" },
    499543#endif
    500544    { 'e', flag, &env_overrides, 1, 1, 0, 0, 0, "environment-overrides", },
    501     { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
    502545    { 'h', flag, &print_usage_flag, 0, 0, 0, 0, 0, "help" },
    503546    { 'i', flag, &ignore_errors_flag, 1, 1, 0, 0, 0, "ignore-errors" },
    504     { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
    505       "include-dir" },
    506     { 'j', positive_int, &job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
    507       "jobs" },
    508     { CHAR_MAX+2, string, &jobserver_fds, 1, 1, 0, 0, 0, "jobserver-fds" },
    509547    { 'k', flag, &keep_going_flag, 1, 1, 0, 0, &default_keep_going_flag,
    510548      "keep-going" },
    511 #ifndef NO_FLOAT
    512     { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
    513       &default_load_average, "load-average" },
    514 #else
    515     { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
    516       &default_load_average, "load-average" },
    517 #endif
    518549    { 'L', flag, &check_symlink_flag, 1, 1, 0, 0, 0, "check-symlink-times" },
    519550    { 'm', ignore, 0, 0, 0, 0, 0, 0, 0 },
    520551    { 'n', flag, &just_print_flag, 1, 1, 1, 0, 0, "just-print" },
    521     { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
    522552    { 'p', flag, &print_data_base_flag, 1, 1, 0, 0, 0, "print-data-base" },
    523553#ifdef CONFIG_PRETTY_COMMAND_PRINTING
     
    554584    { 't', flag, &touch_flag, 1, 1, 1, 0, 0, "touch" },
    555585    { 'v', flag, &print_version_flag, 1, 1, 0, 0, 0, "version" },
    556     { CHAR_MAX+3, string, &verbosity_flags, 1, 1, 0, 0, 0,
    557       "verbosity" },
    558586    { 'w', flag, &print_directory_flag, 1, 1, 0, 0, 0, "print-directory" },
     587
     588    /* These options take arguments.  */
     589    { 'C', filename, &directories, 0, 0, 0, 0, 0, "directory" },
     590    { 'f', filename, &makefiles, 0, 0, 0, 0, 0, "file" },
     591    { 'I', filename, &include_directories, 1, 1, 0, 0, 0,
     592      "include-dir" },
     593    { 'j', positive_int, &arg_job_slots, 1, 1, 0, &inf_jobs, &default_job_slots,
     594      "jobs" },
     595#ifndef NO_FLOAT
     596    { 'l', floating, &max_load_average, 1, 1, 0, &default_load_average,
     597      &default_load_average, "load-average" },
     598#else
     599    { 'l', positive_int, &max_load_average, 1, 1, 0, &default_load_average,
     600      &default_load_average, "load-average" },
     601#endif
     602    { 'o', filename, &old_files, 0, 0, 0, 0, 0, "old-file" },
     603    { 'O', string, &output_sync_option, 1, 1, 0, "target", 0, "output-sync" },
     604    { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
     605
     606    /* These are long-style options.  */
     607    { CHAR_MAX+1, strlist, &db_flags, 1, 1, 0, "basic", 0, "debug" },
     608    { CHAR_MAX+2, string, &jobserver_auth, 1, 1, 0, 0, 0, "jobserver-auth" },
     609    { CHAR_MAX+3, flag, &trace_flag, 1, 1, 0, 0, 0, "trace" },
    559610    { CHAR_MAX+4, flag, &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
    560611      "no-print-directory" },
    561     { 'W', filename, &new_files, 0, 0, 0, 0, 0, "what-if" },
    562612    { CHAR_MAX+5, flag, &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
    563613      "warn-undefined-variables" },
    564     { CHAR_MAX+6, string, &eval_strings, 1, 0, 0, 0, 0, "eval" },
     614    { CHAR_MAX+6, strlist, &eval_strings, 1, 0, 0, 0, 0, "eval" },
     615    { CHAR_MAX+7, string, &sync_mutex, 1, 1, 0, 0, 0, "sync-mutex" },
    565616    { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    566617  };
     
    570621static struct option long_option_aliases[] =
    571622  {
    572     { "quiet",          no_argument,            0, 's' },
    573     { "stop",           no_argument,            0, 'S' },
    574     { "new-file",       required_argument,      0, 'W' },
    575     { "assume-new",     required_argument,      0, 'W' },
    576     { "assume-old",     required_argument,      0, 'o' },
    577     { "max-load",       optional_argument,      0, 'l' },
    578     { "dry-run",        no_argument,            0, 'n' },
    579     { "recon",          no_argument,            0, 'n' },
    580     { "makefile",       required_argument,      0, 'f' },
     623    { "quiet",          no_argument,            0, 's' },
     624    { "stop",           no_argument,            0, 'S' },
     625    { "new-file",       required_argument,      0, 'W' },
     626    { "assume-new",     required_argument,      0, 'W' },
     627    { "assume-old",     required_argument,      0, 'o' },
     628    { "max-load",       optional_argument,      0, 'l' },
     629    { "dry-run",        no_argument,            0, 'n' },
     630    { "recon",          no_argument,            0, 'n' },
     631    { "makefile",       required_argument,      0, 'f' },
    581632  };
    582633
     
    586637static
    587638#endif
    588 struct dep *goals, *lastgoal;
     639struct goaldep *goals, *lastgoal;
    589640
    590641/* List of variables which were defined on the command line
     
    601652/* The name we were invoked with.  */
    602653
     654#ifdef WINDOWS32
     655/* On MS-Windows, we chop off the .exe suffix in 'main', so this
     656   cannot be 'const'.  */
    603657char *program;
     658#else
     659const char *program;
     660#endif
    604661
    605662/* Our current directory before processing any -C options.  */
     
    629686struct file *default_file;
    630687
    631 /* Nonzero if we have seen the magic `.POSIX' target.
     688/* Nonzero if we have seen the magic '.POSIX' target.
    632689   This turns on pedantic compliance with POSIX.2.  */
    633690
     
    638695
    639696int second_expansion;
     697
     698#ifdef CONFIG_WITH_2ND_TARGET_EXPANSION
     699/* Nonzero if we have seen the '.SECONDTARGETEXPANSION' target.
     700   This turns on secondary expansion of targets.  */
     701
     702int second_target_expansion;
     703#endif
    640704
    641705/* Nonzero if we have seen the '.ONESHELL' target.
     
    645709int one_shell;
    646710
    647 #ifdef CONFIG_WITH_2ND_TARGET_EXPANSION
    648 /* Nonzero if we have seen the '.SECONDTARGETEXPANSION' target.
    649    This turns on secondary expansion of targets.  */
    650 
    651 int second_target_expansion;
    652 #endif
     711/* One of OUTPUT_SYNC_* if the "--output-sync" option was given.  This
     712   attempts to synchronize the output of parallel jobs such that the results
     713   of each job stay together.  */
     714
     715int output_sync = OUTPUT_SYNC_NONE;
     716
     717/* Nonzero if the "--trace" option was given.  */
     718
     719int trace_flag = 0;
    653720
    654721#ifndef CONFIG_WITH_EXTENDED_NOTPARALLEL
    655722
    656 /* Nonzero if we have seen the `.NOTPARALLEL' target.
     723/* Nonzero if we have seen the '.NOTPARALLEL' target.
    657724   This turns off parallel builds for this invocation of make.  */
    658725
    659726#else  /* CONFIG_WITH_EXTENDED_NOTPARALLEL */
    660727
    661 /* Negative if we have seen the `.NOTPARALLEL' target with an
     728/* Negative if we have seen the '.NOTPARALLEL' target with an
    662729   empty dependency list.
    663730
    664    Zero if no `.NOTPARALLEL' or no file in the dependency list
     731   Zero if no '.NOTPARALLEL' or no file in the dependency list
    665732   is being executed.
    666733
    667    Positive when a file in the `.NOTPARALLEL' dependency list
     734   Positive when a file in the '.NOTPARALLEL' dependency list
    668735   is in progress, the value is the number of notparallel files
    669736   in progress (running or queued for running).
     
    680747int clock_skew_detected;
    681748
     749/* Map of possible stop characters for searching strings.  */
     750#ifndef UCHAR_MAX
     751# define UCHAR_MAX 255
     752#endif
     753#ifdef _MSC_VER
     754__declspec(align(512)) /* bird: improve cacheline & tlb mojo  */
     755#endif
     756unsigned short stopchar_map[UCHAR_MAX + 1] = {0};
     757
     758/* If output-sync is enabled we'll collect all the output generated due to
     759   options, while reading makefiles, etc.  */
     760
     761struct output make_sync;
     762
     763
    682764
    683765/* Mask of signals that are being caught with fatal_error_signal.  */
    684766
    685 #ifdef  POSIX
     767#ifdef POSIX
    686768sigset_t fatal_signal_set;
    687769#else
    688 # ifdef HAVE_SIGSETMASK
     770# ifdef HAVE_SIGSETMASK
    689771int fatal_signal_mask;
    690772# endif
     
    714796#ifdef CONFIG_WITH_ALLOC_CACHES
    715797struct alloccache dep_cache;
     798struct alloccache goaldep_cache;
     799struct alloccache nameseq_cache;
    716800struct alloccache file_cache;
    717801struct alloccache commands_cache;
    718 struct alloccache nameseq_cache;
    719802struct alloccache variable_cache;
    720803struct alloccache variable_set_cache;
     
    725808{
    726809  alloccache_init (&dep_cache,               sizeof (struct dep),               "dep",               NULL, NULL);
     810  alloccache_init (&goaldep_cache,           sizeof (struct goaldep),           "goaldep",           NULL, NULL);
     811  alloccache_init (&nameseq_cache,           sizeof (struct nameseq),           "nameseq",           NULL, NULL);
    727812  alloccache_init (&file_cache,              sizeof (struct file),              "file",              NULL, NULL);
    728813  alloccache_init (&commands_cache,          sizeof (struct commands),          "commands",          NULL, NULL);
    729   alloccache_init (&nameseq_cache,           sizeof (struct nameseq),           "nameseq",           NULL, NULL);
    730814  alloccache_init (&variable_cache,          sizeof (struct variable),          "variable",          NULL, NULL);
    731815  alloccache_init (&variable_set_cache,      sizeof (struct variable_set),      "variable_set",      NULL, NULL);
     
    744828}
    745829
     830/* This character map locate stop chars when parsing GNU makefiles.
     831   Each element is true if we should stop parsing on that character.  */
     832
     833static void
     834initialize_stopchar_map (void)
     835{
     836  int i;
     837
     838  stopchar_map[(int)'\0'] = MAP_NUL;
     839  stopchar_map[(int)'#'] = MAP_COMMENT;
     840  stopchar_map[(int)';'] = MAP_SEMI;
     841  stopchar_map[(int)'='] = MAP_EQUALS;
     842  stopchar_map[(int)':'] = MAP_COLON;
     843  stopchar_map[(int)'%'] = MAP_PERCENT;
     844  stopchar_map[(int)'|'] = MAP_PIPE;
     845  stopchar_map[(int)'.'] = MAP_DOT | MAP_USERFUNC;
     846  stopchar_map[(int)','] = MAP_COMMA;
     847  stopchar_map[(int)'$'] = MAP_VARIABLE;
     848
     849  stopchar_map[(int)'-'] = MAP_USERFUNC;
     850  stopchar_map[(int)'_'] = MAP_USERFUNC;
     851
     852  stopchar_map[(int)' '] = MAP_BLANK;
     853  stopchar_map[(int)'\t'] = MAP_BLANK;
     854
     855  stopchar_map[(int)'/'] = MAP_DIRSEP;
     856#if defined(VMS)
     857  stopchar_map[(int)':'] |= MAP_DIRSEP;
     858  stopchar_map[(int)']'] |= MAP_DIRSEP;
     859  stopchar_map[(int)'>'] |= MAP_DIRSEP;
     860#elif defined(HAVE_DOS_PATHS)
     861  stopchar_map[(int)'\\'] |= MAP_DIRSEP;
     862#endif
     863
     864  for (i = 1; i <= UCHAR_MAX; ++i)
     865    {
     866      if (isspace (i) && NONE_SET (stopchar_map[i], MAP_BLANK))
     867        /* Don't mark blank characters as newline characters.  */
     868        stopchar_map[i] |= MAP_NEWLINE;
     869      else if (isalnum (i))
     870        stopchar_map[i] |= MAP_USERFUNC;
     871    }
     872}
     873
    746874static const char *
    747 expand_command_line_file (char *name)
     875expand_command_line_file (const char *name)
    748876{
    749877  const char *cp;
     
    751879
    752880  if (name[0] == '\0')
    753     fatal (NILF, _("empty string invalid as file name"));
     881    O (fatal, NILF, _("empty string invalid as file name"));
    754882
    755883  if (name[0] == '~')
    756884    {
    757885      expanded = tilde_expand (name);
    758       if (expanded != 0)
    759         name = expanded;
     886      if (expanded && expanded[0] != '\0')
     887        name = expanded;
    760888    }
    761889
     
    763891     for names read from makefiles.  It is here for names passed
    764892     on the command line.  */
    765   while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
     893  while (name[0] == '.' && name[1] == '/')
    766894    {
    767895      name += 2;
    768       while (*name == '/')
    769         /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
    770         ++name;
    771     }
    772 
    773   if (*name == '\0')
    774     {
    775       /* It was all slashes!  Move back to the dot and truncate
    776          it after the first slash, so it becomes just "./".  */
    777       do
    778         --name;
    779       while (name[0] != '.');
    780       name[2] = '\0';
     896      while (name[0] == '/')
     897        /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
     898        ++name;
     899    }
     900
     901  if (name[0] == '\0')
     902    {
     903      /* Nothing else but one or more "./", maybe plus slashes!  */
     904      name = "./";
    781905    }
    782906
    783907  cp = strcache_add (name);
    784908
    785   if (expanded)
    786     free (expanded);
     909  free (expanded);
    787910
    788911  return cp;
     
    807930    db_level = DB_ALL;
    808931
    809   if (!db_flags)
    810     return;
    811 
    812   for (pp=db_flags->list; *pp; ++pp)
    813     {
    814       const char *p = *pp;
    815 
    816       while (1)
    817         {
    818           switch (tolower (p[0]))
    819             {
    820             case 'a':
    821               db_level |= DB_ALL;
     932  if (db_flags)
     933    for (pp=db_flags->list; *pp; ++pp)
     934      {
     935        const char *p = *pp;
     936
     937        while (1)
     938          {
     939            switch (tolower (p[0]))
     940              {
     941              case 'a':
     942                db_level |= DB_ALL;
     943                break;
     944              case 'b':
     945                db_level |= DB_BASIC;
     946                break;
     947              case 'i':
     948                db_level |= DB_BASIC | DB_IMPLICIT;
     949                break;
     950              case 'j':
     951                db_level |= DB_JOBS;
     952                break;
     953              case 'm':
     954                db_level |= DB_BASIC | DB_MAKEFILES;
     955                break;
     956              case 'n':
     957                db_level = 0;
     958                break;
     959              case 'v':
     960                db_level |= DB_BASIC | DB_VERBOSE;
     961                break;
     962#ifdef DB_KMK
     963              case 'k':
     964                db_level |= DB_KMK;
     965                break;
     966#endif /* DB_KMK */
     967              default:
     968                OS (fatal, NILF,
     969                    _("unknown debug level specification '%s'"), p);
     970              }
     971
     972            while (*(++p) != '\0')
     973              if (*p == ',' || *p == ' ')
     974                {
     975                  ++p;
     976                  break;
     977                }
     978
     979            if (*p == '\0')
    822980              break;
    823             case 'b':
    824               db_level |= DB_BASIC;
    825               break;
    826             case 'i':
    827               db_level |= DB_BASIC | DB_IMPLICIT;
    828               break;
    829             case 'j':
    830               db_level |= DB_JOBS;
    831               break;
    832             case 'm':
    833               db_level |= DB_BASIC | DB_MAKEFILES;
    834               break;
    835             case 'v':
    836               db_level |= DB_BASIC | DB_VERBOSE;
    837               break;
    838 #ifdef DB_KMK
    839             case 'k':
    840               db_level |= DB_KMK;
    841               break;
    842 #endif /* DB_KMK */
    843             default:
    844               fatal (NILF, _("unknown debug level specification `%s'"), p);
    845             }
    846 
    847           while (*(++p) != '\0')
    848             if (*p == ',' || *p == ' ')
    849               break;
    850 
    851           if (*p == '\0')
    852             break;
    853 
    854           ++p;
    855         }
    856     }
     981          }
     982      }
     983
     984  if (db_level)
     985    verify_flag = 1;
     986
     987  if (! db_level)
     988    debug_flag = 0;
     989}
     990
     991static void
     992decode_output_sync_flags (void)
     993{
     994#ifdef NO_OUTPUT_SYNC
     995  output_sync = OUTPUT_SYNC_NONE;
     996#else
     997  if (output_sync_option)
     998    {
     999      if (streq (output_sync_option, "none"))
     1000        output_sync = OUTPUT_SYNC_NONE;
     1001      else if (streq (output_sync_option, "line"))
     1002        output_sync = OUTPUT_SYNC_LINE;
     1003      else if (streq (output_sync_option, "target"))
     1004        output_sync = OUTPUT_SYNC_TARGET;
     1005      else if (streq (output_sync_option, "recurse"))
     1006        output_sync = OUTPUT_SYNC_RECURSE;
     1007      else
     1008        OS (fatal, NILF,
     1009            _("unknown output-sync type '%s'"), output_sync_option);
     1010    }
     1011
     1012  if (sync_mutex)
     1013    RECORD_SYNC_MUTEX (sync_mutex);
     1014#endif
    8571015}
    8581016
     
    8781036      case 4:     dwClass = HIGH_PRIORITY_CLASS;         dwPriority = 0xffffffff; break;
    8791037      case 5:     dwClass = REALTIME_PRIORITY_CLASS;     dwPriority = 0xffffffff; break;
    880       default:    fatal (NILF, _("invalid priority %d\n"), process_priority);
     1038      default:    ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
    8811039    }
    8821040  if (!SetPriorityClass (GetCurrentProcess (), dwClass))
     
    9001058      case 4:     iNewPriority = B_URGENT_DISPLAY_PRIORITY; break;
    9011059      case 5:     iNewPriority = B_REAL_TIME_DISPLAY_PRIORITY; break;
    902       default:    fatal (NILF, _("invalid priority %d\n"), process_priority);
     1060      default:    ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
    9031061    }
    9041062  error = set_thread_priority (find_thread (NULL), iNewPriority);
     
    9171075      case 4:     nice_level = -10; break;
    9181076      case 5:     nice_level = -19; break;
    919       default:    fatal (NILF, _("invalid priority %d\n"), process_priority);
     1077      default:    ON (fatal, NILF, _("invalid priority %d\n"), process_priority);
    9201078    }
    9211079  errno = 0;
     
    9291087
    9301088#ifdef WINDOWS32
    931 # ifndef KMK
     1089
     1090#ifndef NO_OUTPUT_SYNC
     1091
     1092/* This is called from start_job_command when it detects that
     1093   output_sync option is in effect.  The handle to the synchronization
     1094   mutex is passed, as a string, to sub-makes via the --sync-mutex
     1095   command-line argument.  */
     1096void
     1097prepare_mutex_handle_string (sync_handle_t handle)
     1098{
     1099  if (!sync_mutex)
     1100    {
     1101      /* Prepare the mutex handle string for our children.  */
     1102      /* 2 hex digits per byte + 2 characters for "0x" + null.  */
     1103      sync_mutex = xmalloc ((2 * sizeof (sync_handle_t)) + 2 + 1);
     1104      sprintf (sync_mutex, "0x%Ix", handle);
     1105      define_makeflags (1, 0);
     1106    }
     1107}
     1108
     1109#endif  /* NO_OUTPUT_SYNC */
     1110
     1111# ifndef KMK /* I'd rather have WER collect dumps. */
    9321112/*
    9331113 * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
     
    9401120 */
    9411121LONG WINAPI
    942 handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
     1122handle_runtime_exceptions (struct _EXCEPTION_POINTERS *exinfo)
    9431123{
    9441124  PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
    945   LPSTR cmdline = GetCommandLine();
    946   LPSTR prg = strtok(cmdline, " ");
     1125  LPSTR cmdline = GetCommandLine ();
     1126  LPSTR prg = strtok (cmdline, " ");
    9471127  CHAR errmsg[1024];
    9481128#ifdef USE_EVENT_LOG
     
    9531133  if (! ISDB (DB_VERBOSE))
    9541134    {
    955       sprintf(errmsg,
    956               _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
    957               prg, exrec->ExceptionCode, exrec->ExceptionAddress);
    958       fprintf(stderr, errmsg);
    959       exit(255);
    960     }
    961 
    962   sprintf(errmsg,
    963           _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
    964           prg, exrec->ExceptionCode, exrec->ExceptionFlags,
    965           exrec->ExceptionAddress);
     1135      sprintf (errmsg,
     1136               _("%s: Interrupt/Exception caught (code = 0x%lx, addr = 0x%p)\n"),
     1137               prg, exrec->ExceptionCode, exrec->ExceptionAddress);
     1138      fprintf (stderr, errmsg);
     1139      exit (255);
     1140    }
     1141
     1142  sprintf (errmsg,
     1143           _("\nUnhandled exception filter called from program %s\nExceptionCode = %lx\nExceptionFlags = %lx\nExceptionAddress = 0x%p\n"),
     1144           prg, exrec->ExceptionCode, exrec->ExceptionFlags,
     1145           exrec->ExceptionAddress);
    9661146
    9671147  if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
    9681148      && exrec->NumberParameters >= 2)
    969     sprintf(&errmsg[strlen(errmsg)],
    970             (exrec->ExceptionInformation[0]
    971              ? _("Access violation: write operation at address 0x%p\n")
    972              : _("Access violation: read operation at address 0x%p\n")),
    973             (PVOID)exrec->ExceptionInformation[1]);
     1149    sprintf (&errmsg[strlen(errmsg)],
     1150             (exrec->ExceptionInformation[0]
     1151              ? _("Access violation: write operation at address 0x%p\n")
     1152              : _("Access violation: read operation at address 0x%p\n")),
     1153             (PVOID)exrec->ExceptionInformation[1]);
    9741154
    9751155  /* turn this on if we want to put stuff in the event log too */
    9761156#ifdef USE_EVENT_LOG
    977   hEventSource = RegisterEventSource(NULL, "GNU Make");
     1157  hEventSource = RegisterEventSource (NULL, "GNU Make");
    9781158  lpszStrings[0] = errmsg;
    9791159
    9801160  if (hEventSource != NULL)
    9811161    {
    982       ReportEvent(hEventSource,         /* handle of event source */
    983                   EVENTLOG_ERROR_TYPE,  /* event type */
    984                   0,                    /* event category */
    985                   0,                    /* event ID */
    986                   NULL,                 /* current user's SID */
    987                   1,                    /* strings in lpszStrings */
    988                   0,                    /* no bytes of raw data */
    989                   lpszStrings,          /* array of error strings */
    990                   NULL);                /* no raw data */
    991 
    992       (VOID) DeregisterEventSource(hEventSource);
     1162      ReportEvent (hEventSource,         /* handle of event source */
     1163                   EVENTLOG_ERROR_TYPE,  /* event type */
     1164                   0,                    /* event category */
     1165                   0,                    /* event ID */
     1166                   NULL,                 /* current user's SID */
     1167                   1,                    /* strings in lpszStrings */
     1168                   0,                    /* no bytes of raw data */
     1169                   lpszStrings,          /* array of error strings */
     1170                   NULL);                /* no raw data */
     1171
     1172      (VOID) DeregisterEventSource (hEventSource);
    9931173    }
    9941174#endif
    9951175
    9961176  /* Write the error to stderr too */
    997   fprintf(stderr, errmsg);
     1177  fprintf (stderr, errmsg);
    9981178
    9991179#ifdef DEBUG
    10001180  return EXCEPTION_CONTINUE_SEARCH;
    10011181#else
    1002   exit(255);
     1182  exit (255);
    10031183  return (255); /* not reached */
    10041184#endif
     
    10091189 * On WIN32 systems we don't have the luxury of a /bin directory that
    10101190 * is mapped globally to every drive mounted to the system. Since make could
    1011  * be invoked from any drive, and we don't want to propogate /bin/sh
     1191 * be invoked from any drive, and we don't want to propagate /bin/sh
    10121192 * to every single drive. Allow ourselves a chance to search for
    10131193 * a value for default shell here (if the default path does not exist).
     
    10191199  int sh_found = 0;
    10201200  char *atoken = 0;
    1021   char *search_token;
    1022   char *tokend;
     1201  const char *search_token;
     1202  const char *tokend;
    10231203  PATH_VAR(sh_path);
    1024   extern char *default_shell;
     1204  extern const char *default_shell;
    10251205
    10261206  if (!token)
    10271207    search_token = default_shell;
    10281208  else
    1029     atoken = search_token = xstrdup (token);
     1209    search_token = atoken = xstrdup (token);
    10301210
    10311211  /* If the user explicitly requests the DOS cmd shell, obey that request.
     
    10411221           || (tokend - 4 > search_token
    10421222               && (tokend[-5] == '/' || tokend[-5] == '\\')))
    1043           && !strcasecmp (tokend - 4, "cmd.exe"))) {
    1044     batch_mode_shell = 1;
    1045     unixy_shell = 0;
    1046     sprintf (sh_path, "%s", search_token);
    1047     default_shell = xstrdup (w32ify (sh_path, 0));
    1048     DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
    1049                      default_shell));
    1050     sh_found = 1;
    1051   } else if (!no_default_sh_exe &&
    1052              (token == NULL || !strcmp (search_token, default_shell))) {
    1053     /* no new information, path already set or known */
    1054     sh_found = 1;
    1055   } else if (file_exists_p (search_token)) {
    1056     /* search token path was found */
    1057     sprintf (sh_path, "%s", search_token);
    1058     default_shell = xstrdup (w32ify (sh_path, 0));
    1059     DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
    1060                      default_shell));
    1061     sh_found = 1;
    1062   } else {
    1063     char *p;
    1064     struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
    1065 
    1066     /* Search Path for shell */
    1067     if (v && v->value) {
    1068       char *ep;
    1069 
    1070       p  = v->value;
    1071       ep = strchr (p, PATH_SEPARATOR_CHAR);
    1072 
    1073       while (ep && *ep) {
    1074         *ep = '\0';
    1075 
    1076         if (dir_file_exists_p (p, search_token)) {
    1077           sprintf (sh_path, "%s/%s", p, search_token);
    1078           default_shell = xstrdup (w32ify (sh_path, 0));
    1079           sh_found = 1;
    1080           *ep = PATH_SEPARATOR_CHAR;
    1081 
    1082           /* terminate loop */
    1083           p += strlen (p);
    1084         } else {
    1085           *ep = PATH_SEPARATOR_CHAR;
    1086            p = ++ep;
     1223          && !strcasecmp (tokend - 4, "cmd.exe")))
     1224    {
     1225      batch_mode_shell = 1;
     1226      unixy_shell = 0;
     1227      sprintf (sh_path, "%s", search_token);
     1228      default_shell = xstrdup (w32ify (sh_path, 0));
     1229      DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
     1230                       default_shell));
     1231      sh_found = 1;
     1232    }
     1233  else if (!no_default_sh_exe
     1234           && (token == NULL || !strcmp (search_token, default_shell)))
     1235    {
     1236      /* no new information, path already set or known */
     1237      sh_found = 1;
     1238    }
     1239  else if (_access (search_token, 0) == 0)
     1240    {
     1241      /* search token path was found */
     1242      sprintf (sh_path, "%s", search_token);
     1243      default_shell = xstrdup (w32ify (sh_path, 0));
     1244      DB (DB_VERBOSE, (_("find_and_set_shell() setting default_shell = %s\n"),
     1245                       default_shell));
     1246      sh_found = 1;
     1247    }
     1248  else
     1249    {
     1250      char *p;
     1251      struct variable *v = lookup_variable (STRING_SIZE_TUPLE ("PATH"));
     1252
     1253      /* Search Path for shell */
     1254      if (v && v->value)
     1255        {
     1256          char *ep;
     1257
     1258          p  = v->value;
     1259          ep = strchr (p, PATH_SEPARATOR_CHAR);
     1260
     1261          while (ep && *ep)
     1262            {
     1263              *ep = '\0';
     1264
     1265              sprintf (sh_path, "%s/%s", p, search_token);
     1266              if (_access (sh_path, 0) == 0)
     1267                {
     1268                  default_shell = xstrdup (w32ify (sh_path, 0));
     1269                  sh_found = 1;
     1270                  *ep = PATH_SEPARATOR_CHAR;
     1271
     1272                  /* terminate loop */
     1273                  p += strlen (p);
     1274                }
     1275              else
     1276                {
     1277                  *ep = PATH_SEPARATOR_CHAR;
     1278                  p = ++ep;
     1279                }
     1280
     1281              ep = strchr (p, PATH_SEPARATOR_CHAR);
     1282            }
     1283
     1284          /* be sure to check last element of Path */
     1285          if (p && *p)
     1286            {
     1287              sprintf (sh_path, "%s/%s", p, search_token);
     1288              if (_access (sh_path, 0) == 0)
     1289                {
     1290                  default_shell = xstrdup (w32ify (sh_path, 0));
     1291                  sh_found = 1;
     1292                }
     1293            }
     1294
     1295          if (sh_found)
     1296            DB (DB_VERBOSE,
     1297                (_("find_and_set_shell() path search set default_shell = %s\n"),
     1298                 default_shell));
    10871299        }
    1088 
    1089         ep = strchr (p, PATH_SEPARATOR_CHAR);
    1090       }
    1091 
    1092       /* be sure to check last element of Path */
    1093       if (p && *p && dir_file_exists_p (p, search_token)) {
    1094           sprintf (sh_path, "%s/%s", p, search_token);
    1095           default_shell = xstrdup (w32ify (sh_path, 0));
    1096           sh_found = 1;
    1097       }
    1098 
    1099       if (sh_found)
    1100         DB (DB_VERBOSE,
    1101             (_("find_and_set_shell() path search set default_shell = %s\n"),
    1102              default_shell));
    1103     }
    1104   }
    1105 
    1106 #if 0/* def KMK - has been fixed in sub_proc.c */
    1107   /* WORKAROUND:
    1108     With GNU Make 3.81, this kludge was necessary to get double quotes
    1109     working correctly again (worked fine with the 3.81beta1 code).
    1110     beta1 was forcing batch_mode_shell I think, so let's enforce that
    1111     for the kBuild shell. */
    1112   if (sh_found && strstr(default_shell, "kmk_ash")) {
     1300    }
     1301
     1302  /* naive test */
     1303  if (!unixy_shell && sh_found
     1304      && (strstr (default_shell, "sh") || strstr (default_shell, "SH")))
     1305    {
    11131306      unixy_shell = 1;
    1114       batch_mode_shell = 1;
    1115   } else
    1116 #endif
    1117   /* naive test */
    1118   if (!unixy_shell && sh_found &&
    1119       (strstr (default_shell, "sh") || strstr (default_shell, "SH"))) {
    1120     unixy_shell = 1;
    1121     batch_mode_shell = 0;
    1122   }
     1307      batch_mode_shell = 0;
     1308    }
    11231309
    11241310#ifdef BATCH_MODE_ONLY_SHELL
     
    11261312#endif
    11271313
    1128   if (atoken)
    1129     free (atoken);
     1314  free (atoken);
    11301315
    11311316  return (sh_found);
     
    13371522#endif  /* __MSDOS__ */
    13381523
    1339 #ifndef _MSC_VER /* bird */
    1340 char *mktemp (char *template);
    1341 #endif
    1342 int mkstemp (char *template);
    1343 
    1344 FILE *
    1345 open_tmpfile(char **name, const char *template)
     1524static void
     1525reset_jobserver (void)
    13461526{
    1347 #ifdef HAVE_FDOPEN
    1348   int fd;
    1349 #endif
    1350 
    1351 #if defined HAVE_MKSTEMP || defined HAVE_MKTEMP
    1352 # define TEMPLATE_LEN   strlen (template)
    1353 #else
    1354 # define TEMPLATE_LEN   L_tmpnam
    1355 #endif
    1356   *name = xmalloc (TEMPLATE_LEN + 1);
    1357   strcpy (*name, template);
    1358 
    1359 #if defined HAVE_MKSTEMP && defined HAVE_FDOPEN
    1360   /* It's safest to use mkstemp(), if we can.  */
    1361   fd = mkstemp (*name);
    1362   if (fd == -1)
    1363     return 0;
    1364   return fdopen (fd, "w");
    1365 #else
    1366 # ifdef HAVE_MKTEMP
    1367   (void) mktemp (*name);
    1368 # else
    1369   (void) tmpnam (*name);
    1370 # endif
    1371 
    1372 # ifdef HAVE_FDOPEN
    1373   /* Can't use mkstemp(), but guard against a race condition.  */
    1374   fd = open (*name, O_CREAT|O_EXCL|O_WRONLY, 0600);
    1375   if (fd == -1)
    1376     return 0;
    1377   return fdopen (fd, "w");
    1378 # else
    1379   /* Not secure, but what can we do?  */
    1380   return fopen (*name, "w");
    1381 # endif
    1382 #endif
     1527  jobserver_clear ();
     1528  free (jobserver_auth);
     1529  jobserver_auth = NULL;
    13831530}
    1384 
    1385 #ifdef CONFIG_WITH_FAST_IS_SPACE /*bird*/
    1386 char space_map[space_map_size];
    1387 #endif /* CONFIG_WITH_FAST_IS_SPACE */
    1388 
    13891531
    13901532#ifdef _AMIGA
     
    13971539{
    13981540  static char *stdin_nm = 0;
     1541#ifdef CONFIG_WITH_MAKE_STATS
     1542  unsigned long long uStartTick = CURRENT_CLOCK_TICK();
     1543#endif
    13991544  int makefile_status = MAKE_SUCCESS;
    1400   struct dep *read_makefiles;
     1545  struct goaldep *read_files;
    14011546  PATH_VAR (current_directory);
    14021547  unsigned int restarts = 0;
    1403 #ifdef CONFIG_WITH_MAKE_STATS
    1404   unsigned long long uStartTick = CURRENT_CLOCK_TICK();
    1405 #endif
     1548  unsigned int syncing = 0;
     1549  int argv_slots;
    14061550#ifdef WINDOWS32
    1407   char *unix_path = NULL;
    1408   char *windows32_path = NULL;
     1551  const char *unix_path = NULL;
     1552  const char *windows32_path = NULL;
    14091553
    14101554# ifndef ELECTRIC_HEAP /* Drop this because it prevents JIT debugging. */
    14111555#  ifndef KMK /* Don't want none of this crap. */
    1412   SetUnhandledExceptionFilter(handle_runtime_exceptions);
     1556  SetUnhandledExceptionFilter (handle_runtime_exceptions);
    14131557#  endif
    14141558# endif /* !ELECTRIC_HEAP */
     
    14251569  no_default_sh_exe = 1;
    14261570#endif
    1427 #ifdef CONFIG_WITH_FAST_IS_SPACE /* bird */
    1428   memset (space_map, '\0', sizeof(space_map));
    1429   set_space_map_entry (' ');
    1430   set_space_map_entry ('\f');
    1431   set_space_map_entry ('\n');
    1432   set_space_map_entry ('\r');
    1433   set_space_map_entry ('\t');
    1434   set_space_map_entry ('\v');
    1435 #endif /* CONFIG_WITH_FAST_IS_SPACE */
    1436 
    14371571#ifdef CONFIG_WITH_PRINT_TIME_SWITCH
    14381572  make_start_ts = nano_timestamp ();
    14391573#endif
     1574
     1575  output_init (&make_sync);
     1576
     1577  initialize_stopchar_map();
    14401578
    14411579#ifdef SET_STACK_SIZE
     
    14571595#endif
    14581596
    1459 #ifdef HAVE_ATEXIT
    1460   atexit (close_stdout);
    1461 #endif
    1462 
    14631597  /* Needed for OS/2 */
    1464   initialize_main(&argc, &argv);
     1598  initialize_main (&argc, &argv);
    14651599
    14661600#ifdef KMK
     
    14681602#endif
    14691603
    1470   reading_file = 0;
     1604#ifdef MAKE_MAINTAINER_MODE
     1605  /* In maintainer mode we always enable verification.  */
     1606  verify_flag = 1;
     1607#endif
    14711608
    14721609#if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
    1473   /* Request the most powerful version of `system', to
     1610  /* Request the most powerful version of 'system', to
    14741611     make up for the dumb default shell.  */
    14751612  __system_flags = (__system_redirect
    1476                     | __system_use_shell
    1477                     | __system_allow_multiple_cmds
    1478                     | __system_allow_long_cmds
    1479                     | __system_handle_null_commands
    1480                     | __system_emulate_chdir);
     1613                    | __system_use_shell
     1614                    | __system_allow_multiple_cmds
     1615                    | __system_allow_long_cmds
     1616                    | __system_handle_null_commands
     1617                    | __system_emulate_chdir);
    14811618
    14821619#endif
     
    14911628#endif
    14921629
    1493 #ifdef  POSIX
     1630#ifdef  POSIX
    14941631  sigemptyset (&fatal_signal_set);
    1495 #define ADD_SIG(sig)    sigaddset (&fatal_signal_set, sig)
     1632#define ADD_SIG(sig)    sigaddset (&fatal_signal_set, sig)
    14961633#else
    1497 #ifdef  HAVE_SIGSETMASK
     1634#ifdef  HAVE_SIGSETMASK
    14981635  fatal_signal_mask = 0;
    1499 #define ADD_SIG(sig)    fatal_signal_mask |= sigmask (sig)
     1636#define ADD_SIG(sig)    fatal_signal_mask |= sigmask (sig)
    15001637#else
    1501 #define ADD_SIG(sig)    (void)sig      /* Needed to avoid warnings in MSVC.  */
    1502 #endif
    1503 #endif
    1504 
    1505 #define FATAL_SIG(sig)                                                        \
    1506   if (bsd_signal (sig, fatal_error_signal) == SIG_IGN)                        \
    1507     bsd_signal (sig, SIG_IGN);                                                \
    1508   else                                                                        \
     1638#define ADD_SIG(sig)    (void)sig
     1639#endif
     1640#endif
     1641
     1642#define FATAL_SIG(sig)                                                        \
     1643  if (bsd_signal (sig, fatal_error_signal) == SIG_IGN)                        \
     1644    bsd_signal (sig, SIG_IGN);                                                \
     1645  else                                                                        \
    15091646    ADD_SIG (sig);
    15101647
     
    15251662#endif
    15261663
    1527 #ifdef  SIGDANGER
     1664#ifdef  SIGDANGER
    15281665  FATAL_SIG (SIGDANGER);
    15291666#endif
     
    15411678#endif /* CONFIG_NEW_WIN32_CTRL_EVENT */
    15421679
    1543 #undef  FATAL_SIG
     1680#undef  FATAL_SIG
    15441681
    15451682  /* Do not ignore the child-death signal.  This must be done before
     
    15571694#endif
    15581695
    1559   /* Make sure stdout is line-buffered.  */
    1560 
    1561 #ifdef HAVE_SETVBUF
    1562 # ifdef SETVBUF_REVERSED
    1563   setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
    1564 # else  /* setvbuf not reversed.  */
    1565   /* Some buggy systems lose if we pass 0 instead of allocating ourselves.  */
    1566   setvbuf (stdout, 0, _IOLBF, BUFSIZ);
    1567 # endif /* setvbuf reversed.  */
    1568 #elif HAVE_SETLINEBUF
    1569   setlinebuf (stdout);
    1570 #endif  /* setlinebuf missing.  */
     1696  output_init (NULL);
    15711697
    15721698  /* Figure out where this program lives.  */
    15731699
    15741700  if (argv[0] == 0)
    1575     argv[0] = "";
     1701    argv[0] = (char *)"";
    15761702  if (argv[0][0] == '\0')
    15771703#ifdef KMK
     
    15821708  else
    15831709    {
    1584 #ifdef VMS
    1585       program = strrchr (argv[0], ']');
    1586 #else
    15871710      program = strrchr (argv[0], '/');
    1588 #endif
    15891711#if defined(__MSDOS__) || defined(__EMX__)
    15901712      if (program == 0)
    1591         program = strrchr (argv[0], '\\');
     1713        program = strrchr (argv[0], '\\');
    15921714      else
    1593         {
    1594           /* Some weird environments might pass us argv[0] with
    1595              both kinds of slashes; we must find the rightmost.  */
    1596           char *p = strrchr (argv[0], '\\');
    1597           if (p && p > program)
    1598             program = p;
    1599         }
     1715        {
     1716          /* Some weird environments might pass us argv[0] with
     1717             both kinds of slashes; we must find the rightmost.  */
     1718          char *p = strrchr (argv[0], '\\');
     1719          if (p && p > program)
     1720            program = p;
     1721        }
    16001722      if (program == 0 && argv[0][1] == ':')
    1601         program = argv[0] + 1;
     1723        program = argv[0] + 1;
    16021724#endif
    16031725#ifdef WINDOWS32
     
    16051727        {
    16061728          /* Extract program from full path */
    1607           int argv0_len;
    16081729          program = strrchr (argv[0], '\\');
    16091730          if (program)
    16101731            {
    1611               argv0_len = strlen(program);
     1732              int argv0_len = strlen (program);
    16121733              if (argv0_len > 4 && streq (&program[argv0_len - 4], ".exe"))
    16131734                /* Remove .exe extension */
     
    16161737        }
    16171738#endif
     1739#ifdef VMS
     1740      set_program_name (argv[0]);
     1741      program = program_name;
     1742      {
     1743        const char *shell;
     1744        char pwdbuf[256];
     1745        char *pwd;
     1746        shell = getenv ("SHELL");
     1747        if (shell != NULL)
     1748          vms_gnv_shell = 1;
     1749
     1750        /* Need to know if CRTL set to report UNIX paths.  Use getcwd as
     1751           it works on all versions of VMS. */
     1752        pwd = getcwd(pwdbuf, 256);
     1753        if (pwd[0] == '/')
     1754          vms_report_unix_paths = 1;
     1755
     1756        vms_use_mcr_command = get_vms_env_flag ("GNV$MAKE_USE_MCR", 0);
     1757
     1758        vms_always_use_cmd_file = get_vms_env_flag ("GNV$MAKE_USE_CMD_FILE", 0);
     1759
     1760        /* Legacy behavior is on VMS is older behavior that needed to be
     1761           changed to be compatible with standard make behavior.
     1762           For now only completely disable when running under a Bash shell.
     1763           TODO: Update VMS built in recipes and macros to not need this
     1764           behavior, at which time the default may change. */
     1765        vms_legacy_behavior = get_vms_env_flag ("GNV$MAKE_OLD_VMS",
     1766                                                !vms_gnv_shell);
     1767
     1768        /* VMS was changed to use a comma separator in the past, but that is
     1769           incompatible with built in functions that expect space separated
     1770           lists.  Allow this to be selectively turned off. */
     1771        vms_comma_separator = get_vms_env_flag ("GNV$MAKE_COMMA",
     1772                                                vms_legacy_behavior);
     1773
     1774        /* Some Posix shell syntax options are incompatible with VMS syntax.
     1775           VMS requires double quotes for strings and escapes quotes
     1776           differently.  When this option is active, VMS will try
     1777           to simulate Posix shell simulations instead of using
     1778           VMS DCL behavior. */
     1779        vms_unix_simulation = get_vms_env_flag ("GNV$MAKE_SHELL_SIM",
     1780                                                !vms_legacy_behavior);
     1781
     1782      }
     1783      if (need_vms_symbol () && !vms_use_mcr_command)
     1784        create_foreign_command (program_name, argv[0]);
     1785#else
    16181786      if (program == 0)
    1619         program = argv[0];
     1787        program = argv[0];
    16201788      else
    1621         ++program;
     1789        ++program;
     1790#endif
    16221791    }
    16231792
     
    16441813#endif
    16451814    {
    1646 #ifdef  HAVE_GETCWD
     1815#ifdef  HAVE_GETCWD
    16471816      perror_with_name ("getcwd", "");
    16481817#else
    1649       error (NILF, "getwd: %s", current_directory);
     1818      OS (error, NILF, "getwd: %s", current_directory);
    16501819#endif
    16511820      current_directory[0] = '\0';
     
    16541823  else
    16551824    directory_before_chdir = xstrdup (current_directory);
     1825
    16561826#ifdef  __MSDOS__
    16571827  /* Make sure we will return to the initial directory, come what may.  */
     
    16641834  define_variable_cname (".RECIPEPREFIX", "", o_default, 0)->special = 1;
    16651835  define_variable_cname (".SHELLFLAGS", "-c", o_default, 0);
     1836  define_variable_cname (".LOADED", "", o_default, 0);
    16661837
    16671838  /* Set up .FEATURES
    1668      We must do this in multiple calls because define_variable_cname() is
    1669      a macro and some compilers (MSVC) don't like conditionals in macros.  */
     1839     Use a separate variable because define_variable_cname() is a macro and
     1840     some compilers (MSVC) don't like conditionals in macros.  */
    16701841  {
    16711842    const char *features = "target-specific order-only second-expansion"
    1672                            " else-if shortest-stem undefine"
     1843                           " else-if shortest-stem undefine oneshell"
    16731844#ifndef NO_ARCHIVES
    16741845                           " archives"
     
    16771848                           " jobserver"
    16781849#endif
     1850#ifndef NO_OUTPUT_SYNC
     1851                           " output-sync"
     1852#endif
    16791853#ifdef MAKE_SYMLINKS
    16801854                           " check-symlink"
    16811855#endif
     1856#ifdef HAVE_GUILE
     1857                           " guile"
     1858#endif
     1859#ifdef MAKE_LOAD
     1860                           " load"
     1861#endif
    16821862#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    16831863                           " explicit-multitarget"
     
    16931873#ifdef KMK
    16941874  /* Initialize the default number of jobs to the cpu/core/smt count. */
    1695   default_job_slots = job_slots = get_online_cpu_count ();
     1875  default_job_slots = arg_job_slots = job_slots = get_online_cpu_count ();
    16961876#endif /* KMK */
     1877
     1878  /* Configure GNU Guile support */
     1879  guile_gmake_setup (NILF);
    16971880
    16981881  /* Read in variables from the environment.  It is important that this be
     
    17061889    for (i = 0; envp[i] != 0; ++i)
    17071890      {
    1708         int do_not_define = 0;
    1709         char *ep = envp[i];
    1710 
    1711         while (*ep != '\0' && *ep != '=')
     1891        struct variable *v;
     1892        const char *ep = envp[i];
     1893        /* By default, export all variables culled from the environment.  */
     1894        enum variable_export export = v_export;
     1895        unsigned int len;
     1896
     1897        while (! STOP_SET (*ep, MAP_EQUALS))
    17121898          ++ep;
     1899
     1900        /* If there's no equals sign it's a malformed environment.  Ignore.  */
     1901        if (*ep == '\0')
     1902          continue;
     1903
    17131904#ifdef WINDOWS32
    1714         if (!unix_path && strneq(envp[i], "PATH=", 5))
     1905        if (!unix_path && strneq (envp[i], "PATH=", 5))
    17151906          unix_path = ep+1;
    1716         else if (!strnicmp(envp[i], "Path=", 5)) {
    1717           do_not_define = 1; /* it gets defined after loop exits */
    1718           if (!windows32_path)
    1719             windows32_path = ep+1;
    1720         }
    1721 #endif
    1722         /* The result of pointer arithmetic is cast to unsigned int for
    1723            machines where ptrdiff_t is a different size that doesn't widen
    1724            the same.  */
    1725         if (!do_not_define)
     1907        else if (!strnicmp (envp[i], "Path=", 5))
    17261908          {
    1727             struct variable *v;
    1728 
    1729             v = define_variable (envp[i], (unsigned int) (ep - envp[i]),
    1730                                  ep + 1, o_env, 1);
    1731             /* Force exportation of every variable culled from the
    1732                environment.  We used to rely on target_environment's
    1733                v_default code to do this.  But that does not work for the
    1734                case where an environment variable is redefined in a makefile
    1735                with `override'; it should then still be exported, because it
    1736                was originally in the environment.  */
    1737             v->export = v_export;
    1738 
    1739             /* Another wrinkle is that POSIX says the value of SHELL set in
    1740                the makefile won't change the value of SHELL given to
    1741                subprocesses.  */
    1742             if (streq (v->name, "SHELL"))
     1909            if (!windows32_path)
     1910              windows32_path = ep+1;
     1911            /* PATH gets defined after the loop exits.  */
     1912            continue;
     1913          }
     1914#endif
     1915
     1916        /* Length of the variable name, and skip the '='.  */
     1917        len = ep++ - envp[i];
     1918
     1919        /* If this is MAKE_RESTARTS, check to see if the "already printed
     1920           the enter statement" flag is set.  */
     1921        if (len == 13 && strneq (envp[i], "MAKE_RESTARTS", 13))
     1922          {
     1923            if (*ep == '-')
    17431924              {
     1925                OUTPUT_TRACED ();
     1926                ++ep;
     1927              }
     1928            restarts = (unsigned int) atoi (ep);
     1929            export = v_noexport;
     1930          }
     1931
     1932        v = define_variable (envp[i], len, ep, o_env, 1);
     1933
     1934        /* POSIX says the value of SHELL set in the makefile won't change the
     1935           value of SHELL given to subprocesses.  */
     1936        if (streq (v->name, "SHELL"))
     1937          {
    17441938#ifndef __MSDOS__
    1745                 v->export = v_noexport;
     1939            export = v_noexport;
    17461940#endif
    17471941#ifndef CONFIG_WITH_STRCACHE2
    1748                 shell_var.name = "SHELL";
     1942            shell_var.name = xstrdup ("SHELL");
    17491943#else
    1750                 shell_var.name = v->name;
    1751 #endif
    1752                 shell_var.length = 5;
     1944            shell_var.name = v->name;
     1945#endif
     1946            shell_var.length = 5;
    17531947#ifndef CONFIG_WITH_VALUE_LENGTH
    1754                 shell_var.value = xstrdup (ep + 1);
     1948            shell_var.value = xstrdup (ep);
    17551949#else
    1756                 shell_var.value = xstrndup (v->value, v->value_length);
    1757                 shell_var.value_length = v->value_length;
    1758 #endif
    1759               }
    1760 
    1761             /* If MAKE_RESTARTS is set, remember it but don't export it.  */
    1762             if (streq (v->name, "MAKE_RESTARTS"))
    1763               {
    1764                 v->export = v_noexport;
    1765                 restarts = (unsigned int) atoi (ep + 1);
    1766               }
     1950            shell_var.value = xstrndup (v->value, v->value_length);
     1951            shell_var.value_length = v->value_length;
     1952#endif
    17671953          }
     1954
     1955        v->export = export;
    17681956      }
    17691957  }
    17701958#ifdef WINDOWS32
    17711959    /* If we didn't find a correctly spelled PATH we define PATH as
    1772      * either the first mispelled value or an empty string
     1960     * either the first misspelled value or an empty string
    17731961     */
    17741962    if (!unix_path)
     
    17781966#else /* For Amiga, read the ENV: device, ignoring all dirs */
    17791967    {
    1780         BPTR env, file, old;
    1781         char buffer[1024];
    1782         int len;
    1783         __aligned struct FileInfoBlock fib;
    1784 
    1785         env = Lock ("ENV:", ACCESS_READ);
    1786         if (env)
    1787         {
    1788             old = CurrentDir (DupLock(env));
    1789             Examine (env, &fib);
    1790 
    1791             while (ExNext (env, &fib))
    1792             {
    1793                 if (fib.fib_DirEntryType < 0) /* File */
    1794                 {
    1795                     /* Define an empty variable. It will be filled in
    1796                         variable_lookup(). Makes startup quite a bit
    1797                         faster. */
    1798                         define_variable (fib.fib_FileName,
    1799                             strlen (fib.fib_FileName),
    1800                         "", o_env, 1)->export = v_export;
    1801                 }
    1802             }
    1803             UnLock (env);
    1804             UnLock(CurrentDir(old));
    1805         }
     1968        BPTR env, file, old;
     1969        char buffer[1024];
     1970        int len;
     1971        __aligned struct FileInfoBlock fib;
     1972
     1973        env = Lock ("ENV:", ACCESS_READ);
     1974        if (env)
     1975          {
     1976            old = CurrentDir (DupLock (env));
     1977            Examine (env, &fib);
     1978
     1979            while (ExNext (env, &fib))
     1980              {
     1981                if (fib.fib_DirEntryType < 0) /* File */
     1982                  {
     1983                    /* Define an empty variable. It will be filled in
     1984                       variable_lookup(). Makes startup quite a bit faster. */
     1985                    define_variable (fib.fib_FileName,
     1986                                     strlen (fib.fib_FileName),
     1987                                     "", o_env, 1)->export = v_export;
     1988                  }
     1989              }
     1990            UnLock (env);
     1991            UnLock (CurrentDir (old));
     1992          }
    18061993    }
    18071994#endif
    18081995
    18091996  /* Decode the switches.  */
     1997  decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
     1998
     1999  /* Clear GNUMAKEFLAGS to avoid duplication.  */
     2000  define_variable_cname ("GNUMAKEFLAGS", "", o_env, 0);
    18102001
    18112002#ifdef KMK
     
    18132004#else /* !KMK */
    18142005  decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
     2006
    18152007#if 0
    18162008  /* People write things like:
     
    18212013#endif /* !KMK */
    18222014
    1823   decode_switches (argc, argv, 0);
    1824 
    1825 #ifdef WINDOWS32
    1826   if (suspend_flag) {
    1827         fprintf(stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId());
    1828         fprintf(stderr, _("%s is suspending for 30 seconds..."), argv[0]);
    1829         Sleep(30 * 1000);
    1830         fprintf(stderr, _("done sleep(30). Continuing.\n"));
     2015  /* In output sync mode we need to sync any output generated by reading the
     2016     makefiles, such as in $(info ...) or stderr from $(shell ...) etc.  */
     2017
     2018  syncing = make_sync.syncout = (output_sync == OUTPUT_SYNC_LINE
     2019                                 || output_sync == OUTPUT_SYNC_TARGET);
     2020  OUTPUT_SET (&make_sync);
     2021
     2022  /* Remember the job slots set through the environment vs. command line.  */
     2023  {
     2024    int env_slots = arg_job_slots;
     2025    arg_job_slots = INVALID_JOB_SLOTS;
     2026
     2027    decode_switches (argc, (const char **)argv, 0);
     2028    argv_slots = arg_job_slots;
     2029
     2030    if (arg_job_slots == INVALID_JOB_SLOTS)
     2031      arg_job_slots = env_slots;
    18312032  }
    1832 #endif
    1833 
    1834   decode_debug_flags ();
     2033
     2034  /* Set a variable specifying whether stdout/stdin is hooked to a TTY.  */
     2035#ifdef HAVE_ISATTY
     2036  if (isatty (fileno (stdout)))
     2037    if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMOUT")))
     2038      {
     2039        const char *tty = TTYNAME (fileno (stdout));
     2040        define_variable_cname ("MAKE_TERMOUT", tty ? tty : DEFAULT_TTYNAME,
     2041                               o_default, 0)->export = v_export;
     2042      }
     2043  if (isatty (fileno (stderr)))
     2044    if (! lookup_variable (STRING_SIZE_TUPLE ("MAKE_TERMERR")))
     2045      {
     2046        const char *tty = TTYNAME (fileno (stderr));
     2047        define_variable_cname ("MAKE_TERMERR", tty ? tty : DEFAULT_TTYNAME,
     2048                               o_default, 0)->export = v_export;
     2049      }
     2050#endif
     2051
     2052  /* Reset in case the switches changed our minds.  */
     2053  syncing = (output_sync == OUTPUT_SYNC_LINE
     2054             || output_sync == OUTPUT_SYNC_TARGET);
    18352055
    18362056#ifdef KMK
     
    18382058#endif
    18392059
     2060  if (make_sync.syncout && ! syncing)
     2061    output_close (&make_sync);
     2062
     2063  make_sync.syncout = syncing;
     2064  OUTPUT_SET (&make_sync);
     2065
     2066  /* Figure out the level of recursion.  */
     2067  {
     2068    struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
     2069    if (v && v->value[0] != '\0' && v->value[0] != '-')
     2070      makelevel = (unsigned int) atoi (v->value);
     2071    else
     2072      makelevel = 0;
     2073  }
     2074
     2075#ifdef WINDOWS32
     2076  if (suspend_flag)
     2077    {
     2078      fprintf (stderr, "%s (pid = %ld)\n", argv[0], GetCurrentProcessId ());
     2079      fprintf (stderr, _("%s is suspending for 30 seconds..."), argv[0]);
     2080      Sleep (30 * 1000);
     2081      fprintf (stderr, _("done sleep(30). Continuing.\n"));
     2082    }
     2083#endif
     2084
    18402085  /* Set always_make_flag if -B was given and we've not restarted already.  */
    18412086  always_make_flag = always_make_set && (restarts == 0);
    18422087
    1843   /* Print version information.  */
    1844   if (print_version_flag || print_data_base_flag || db_level)
     2088  /* Print version information, and exit.  */
     2089  if (print_version_flag)
    18452090    {
    18462091      print_version ();
    1847 
    1848       /* `make --version' is supposed to just print the version and exit.  */
    1849       if (print_version_flag)
    1850         die (0);
    1851     }
     2092      die (MAKE_SUCCESS);
     2093    }
     2094
     2095  if (ISDB (DB_BASIC))
     2096    print_version ();
    18522097
    18532098#ifndef VMS
     
    18642109   * CreateProcess().
    18652110   */
    1866   if (strpbrk(argv[0], "/:\\") ||
    1867       strstr(argv[0], "..") ||
    1868       strneq(argv[0], "//", 2))
    1869     argv[0] = xstrdup(w32ify(argv[0],1));
     2111  if (strpbrk (argv[0], "/:\\") || strstr (argv[0], "..")
     2112      || strneq (argv[0], "//", 2))
     2113    argv[0] = xstrdup (w32ify (argv[0], 1));
    18702114#else /* WINDOWS32 */
    18712115#if defined (__MSDOS__) || defined (__EMX__)
     
    18762120      argv[0] = xstrdup (argv[0]);
    18772121      for (p = argv[0]; *p; p++)
    1878         if (*p == '\\')
    1879           *p = '/';
     2122        if (*p == '\\')
     2123          *p = '/';
    18802124    }
    18812125  /* If argv[0] is not in absolute form, prepend the current
     
    19042148#endif
    19052149
     2150  /* We may move, but until we do, here we are.  */
     2151  starting_directory = current_directory;
     2152
     2153  /* Set up the job_slots value and the jobserver.  This can't be usefully set
     2154     in the makefile, and we want to verify the authorization is valid before
     2155     make has a chance to start using it for something else.  */
     2156
     2157  if (jobserver_auth)
     2158    {
     2159      if (argv_slots == INVALID_JOB_SLOTS)
     2160        {
     2161          if (jobserver_parse_auth (jobserver_auth))
     2162            {
     2163              /* Success!  Use the jobserver.  */
     2164              job_slots = 0;
     2165              goto job_setup_complete;
     2166            }
     2167
     2168          O (error, NILF, _("warning: jobserver unavailable: using -j1.  Add '+' to parent make rule."));
     2169          arg_job_slots = 1;
     2170        }
     2171
     2172      /* The user provided a -j setting on the command line: use it.  */
     2173      else if (!restarts)
     2174        /* If restarts is >0 we already printed this message.  */
     2175        O (error, NILF,
     2176           _("warning: -jN forced in submake: disabling jobserver mode."));
     2177
     2178      /* We failed to use our parent's jobserver.  */
     2179      reset_jobserver ();
     2180      job_slots = (unsigned int)arg_job_slots;
     2181    }
     2182  else if (arg_job_slots == INVALID_JOB_SLOTS)
     2183#ifdef KMK
     2184    job_slots = default_job_slots; /* The default is set to CPU count early in main. */
     2185#else
     2186    /* The default is one job at a time.  */
     2187    job_slots = 1;
     2188#endif
     2189  else
     2190    /* Use whatever was provided.  */
     2191    job_slots = (unsigned int)arg_job_slots;
     2192
     2193 job_setup_complete:
     2194
    19062195  /* The extra indirection through $(MAKE_COMMAND) is done
    19072196     for hysterical raisins.  */
     2197
     2198#ifdef VMS
     2199  if (vms_use_mcr_command)
     2200    define_variable_cname ("MAKE_COMMAND", vms_command (argv[0]), o_default, 0);
     2201  else
     2202    define_variable_cname ("MAKE_COMMAND", program, o_default, 0);
     2203#else
    19082204  define_variable_cname ("MAKE_COMMAND", argv[0], o_default, 0);
     2205#endif
    19092206  define_variable_cname ("MAKE", "$(MAKE_COMMAND)", o_default, 1);
    19102207#ifdef KMK
     
    19202217
    19212218      /* Figure out how much space will be taken up by the command-line
    1922         variable definitions.  */
     2219        variable definitions.  */
    19232220      for (cv = command_variables; cv != 0; cv = cv->next)
    1924         {
    1925           v = cv->variable;
    1926           len += 2 * strlen (v->name);
    1927           if (! v->recursive)
    1928             ++len;
    1929           ++len;
    1930           len += 2 * strlen (v->value);
    1931           ++len;
    1932         }
     2221        {
     2222          v = cv->variable;
     2223          len += 2 * strlen (v->name);
     2224          if (! v->recursive)
     2225            ++len;
     2226          ++len;
     2227          len += 2 * strlen (v->value);
     2228          ++len;
     2229        }
    19332230
    19342231      /* Now allocate a buffer big enough and fill it.  */
    19352232      p = value = alloca (len);
    19362233      for (cv = command_variables; cv != 0; cv = cv->next)
    1937         {
    1938           v = cv->variable;
    1939           p = quote_for_env (p, v->name);
    1940           if (! v->recursive)
    1941             *p++ = ':';
    1942           *p++ = '=';
    1943           p = quote_for_env (p, v->value);
    1944           *p++ = ' ';
    1945         }
    1946       p[-1] = '\0';             /* Kill the final space and terminate.  */
     2234        {
     2235          v = cv->variable;
     2236          p = quote_for_env (p, v->name);
     2237          if (! v->recursive)
     2238            *p++ = ':';
     2239          *p++ = '=';
     2240          p = quote_for_env (p, v->value);
     2241          *p++ = ' ';
     2242        }
     2243      p[-1] = '\0';             /* Kill the final space and terminate.  */
    19472244
    19482245      /* Define an unchangeable variable with a name that no POSIX.2
    1949         makefile could validly use for its own variable.  */
     2246        makefile could validly use for its own variable.  */
    19502247      define_variable_cname ("-*-command-variables-*-", value, o_automatic, 0);
    19512248
     
    19622259      define_variable_cname ("MAKEOVERRIDES", "${-*-command-variables-*-}",
    19632260                             o_env, 1);
     2261#endif
     2262#ifdef VMS
     2263      vms_export_dcl_symbol ("MAKEOVERRIDES", "${-*-command-variables-*-}");
    19642264#endif
    19652265    }
     
    20322332
    20332333          if (up_levels >= 16)
    2034             fatal (NILF, _("Makefile.kup recursion is too deep."));
     2334            O (fatal, NILF, _("Makefile.kup recursion is too deep."));
    20352335
    20362336          /* attempt to change to the directory. */
     
    20702370#ifdef KMK /* this is really a candidate for all platforms... */
    20712371  {
    2072     extern char *default_shell;
     2372    extern const char *default_shell;
    20732373    const char *bin = get_kbuild_bin_path();
     2374    char *newshell;
    20742375    size_t len = strlen (bin);
    2075     default_shell = xmalloc (len + sizeof("/kmk_ash.exe"));
    2076     memcpy (default_shell, bin, len);
    2077     strcpy (default_shell + len, "/kmk_ash.exe");
     2376    default_shell = newshell = xmalloc (len + sizeof("/kmk_ash.exe"));
     2377    memcpy (newshell, bin, len);
     2378    strcpy (newshell + len, "/kmk_ash.exe");
    20782379    no_default_sh_exe = 0;
    20792380    batch_mode_shell = 1;
     
    20812382  }
    20822383#else /* !KMK */
    2083    no_default_sh_exe = !find_and_set_default_shell(NULL);
     2384   no_default_sh_exe = !find_and_set_default_shell (NULL);
    20842385#endif /* !KMK */
    20852386#endif /* WINDOWS32 */
    2086   /* Figure out the level of recursion.  */
    2087   {
    2088     struct variable *v = lookup_variable (STRING_SIZE_TUPLE (MAKELEVEL_NAME));
    2089     if (v != 0 && v->value[0] != '\0' && v->value[0] != '-')
    2090       makelevel = (unsigned int) atoi (v->value);
    2091     else
    2092       makelevel = 0;
    2093   }
    20942387
    20952388  /* Except under -s, always do -w in sub-makes and under -C.  */
     
    21102403                          ? 0 : include_directories->list);
    21112404
    2112   /* Figure out where we are now, after chdir'ing.  */
    2113   if (directories == 0)
    2114     /* We didn't move, so we're still in the same place.  */
    2115     starting_directory = current_directory;
    2116   else
     2405  /* If we chdir'ed, figure out where we are now.  */
     2406  if (directories)
    21172407    {
    21182408#ifdef WINDOWS32
     
    21212411      if (getcwd (current_directory, GET_PATH_MAX) == 0)
    21222412#endif
    2123         {
    2124 #ifdef  HAVE_GETCWD
    2125           perror_with_name ("getcwd", "");
     2413        {
     2414#ifdef  HAVE_GETCWD
     2415          perror_with_name ("getcwd", "");
    21262416#else
    2127           error (NILF, "getwd: %s", current_directory);
    2128 #endif
    2129           starting_directory = 0;
    2130         }
     2417          OS (error, NILF, "getwd: %s", current_directory);
     2418#endif
     2419          starting_directory = 0;
     2420        }
    21312421      else
    2132         starting_directory = current_directory;
     2422        starting_directory = current_directory;
    21332423    }
    21342424
     
    21412431      unsigned int i;
    21422432      for (i = 0; i < makefiles->idx; ++i)
    2143         if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
    2144           {
    2145             /* This makefile is standard input.  Since we may re-exec
    2146                and thus re-read the makefiles, we read standard input
    2147                into a temporary file and read from that.  */
    2148             FILE *outfile;
    2149             char *template, *tmpdir;
     2433        if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
     2434          {
     2435            /* This makefile is standard input.  Since we may re-exec
     2436               and thus re-read the makefiles, we read standard input
     2437               into a temporary file and read from that.  */
     2438            FILE *outfile;
     2439            char *template;
     2440            const char *tmpdir;
    21502441
    21512442            if (stdin_nm)
    2152               fatal (NILF, _("Makefile from standard input specified twice."));
     2443              O (fatal, NILF,
     2444                 _("Makefile from standard input specified twice."));
    21532445
    21542446#ifdef VMS
    2155 # define DEFAULT_TMPDIR     "sys$scratch:"
     2447# define DEFAULT_TMPDIR     "/sys$scratch/"
    21562448#else
    21572449# ifdef P_tmpdir
     
    21632455#define DEFAULT_TMPFILE     "GmXXXXXX"
    21642456
    2165             if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
     2457            if (((tmpdir = getenv ("TMPDIR")) == NULL || *tmpdir == '\0')
    21662458#if defined (__MSDOS__) || defined (WINDOWS32) || defined (__EMX__)
    21672459                /* These are also used commonly on these platforms.  */
     
    21702462#endif
    21712463               )
    2172               tmpdir = DEFAULT_TMPDIR;
    2173 
    2174             template = alloca (strlen (tmpdir) + sizeof (DEFAULT_TMPFILE) + 1);
    2175             strcpy (template, tmpdir);
     2464              tmpdir = DEFAULT_TMPDIR;
     2465
     2466            template = alloca (strlen (tmpdir) + CSTRLEN (DEFAULT_TMPFILE) + 2);
     2467            strcpy (template, tmpdir);
    21762468
    21772469#ifdef HAVE_DOS_PATHS
    2178             if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
    2179               strcat (template, "/");
     2470            if (strchr ("/\\", template[strlen (template) - 1]) == NULL)
     2471              strcat (template, "/");
    21802472#else
    21812473# ifndef VMS
    2182             if (template[strlen (template) - 1] != '/')
    2183               strcat (template, "/");
     2474            if (template[strlen (template) - 1] != '/')
     2475              strcat (template, "/");
    21842476# endif /* !VMS */
    21852477#endif /* !HAVE_DOS_PATHS */
    21862478
    2187             strcat (template, DEFAULT_TMPFILE);
    2188             outfile = open_tmpfile (&stdin_nm, template);
    2189             if (outfile == 0)
    2190               pfatal_with_name (_("fopen (temporary file)"));
    2191             while (!feof (stdin) && ! ferror (stdin))
    2192               {
    2193                 char buf[2048];
    2194                 unsigned int n = fread (buf, 1, sizeof (buf), stdin);
    2195                 if (n > 0 && fwrite (buf, 1, n, outfile) != n)
    2196                   pfatal_with_name (_("fwrite (temporary file)"));
    2197               }
    2198             fclose (outfile);
    2199 
    2200             /* Replace the name that read_all_makefiles will
    2201                see with the name of the temporary file.  */
     2479            strcat (template, DEFAULT_TMPFILE);
     2480            outfile = output_tmpfile (&stdin_nm, template);
     2481            if (outfile == 0)
     2482              pfatal_with_name (_("fopen (temporary file)"));
     2483            while (!feof (stdin) && ! ferror (stdin))
     2484              {
     2485                char buf[2048];
     2486                unsigned int n = fread (buf, 1, sizeof (buf), stdin);
     2487                if (n > 0 && fwrite (buf, 1, n, outfile) != n)
     2488                  pfatal_with_name (_("fwrite (temporary file)"));
     2489              }
     2490            fclose (outfile);
     2491
     2492            /* Replace the name that read_all_makefiles will
     2493               see with the name of the temporary file.  */
    22022494            makefiles->list[i] = strcache_add (stdin_nm);
    22032495
    2204             /* Make sure the temporary file will not be remade.  */
     2496            /* Make sure the temporary file will not be remade.  */
    22052497            {
    22062498              struct file *f = enter_file (strcache_add (stdin_nm));
    22072499              f->updated = 1;
    2208               f->update_status = 0;
     2500              f->update_status = us_success;
    22092501              f->command_state = cs_finished;
    22102502              /* Can't be intermediate, or it'll be removed too early for
     
    22132505              f->dontcare = 0;
    22142506            }
    2215           }
     2507          }
    22162508    }
    22172509
    22182510#if !defined(__EMX__) || defined(__KLIBC__) /* Don't use a SIGCHLD handler for good old EMX (bird) */
    2219 #if defined(MAKE_JOBSERVER) || !defined(HAVE_WAIT_NOHANG)
     2511#if !defined(HAVE_WAIT_NOHANG) || defined(MAKE_JOBSERVER)
    22202512  /* Set up to handle children dying.  This must be done before
    2221      reading in the makefiles so that `shell' function calls will work.
     2513     reading in the makefiles so that 'shell' function calls will work.
    22222514
    22232515     If we don't have a hanging wait we have to fall back to old, broken
     
    22252517     children.
    22262518
    2227      If we're using the jobs pipe we need a signal handler so that
    2228      SIGCHLD is not ignored; we need it to interrupt the read(2) of the
    2229      jobserver pipe in job.c if we're waiting for a token.
     2519     If we're using the jobs pipe we need a signal handler so that SIGCHLD is
     2520     not ignored; we need it to interrupt the read(2) of the jobserver pipe if
     2521     we're waiting for a token.
    22302522
    22312523     If none of these are true, we don't need a signal handler at all.  */
    22322524  {
    2233     RETSIGTYPE child_handler (int sig);
    22342525# if defined SIGCHLD
    22352526    bsd_signal (SIGCHLD, child_handler);
     
    22392530# endif
    22402531  }
     2532
     2533#ifdef HAVE_PSELECT
     2534  /* If we have pselect() then we need to block SIGCHLD so it's deferred.  */
     2535  {
     2536    sigset_t block;
     2537    sigemptyset (&block);
     2538    sigaddset (&block, SIGCHLD);
     2539    if (sigprocmask (SIG_SETMASK, &block, NULL) < 0)
     2540      pfatal_with_name ("sigprocmask(SIG_SETMASK, SIGCHLD)");
     2541  }
     2542#endif
     2543
    22412544#endif
    22422545#endif
     
    22482551
    22492552  /* Define the initial list of suffixes for old-style rules.  */
    2250 
    22512553  set_default_suffixes ();
    22522554
     
    22562558     makefiles, it results in the built-in pattern rules taking precedence
    22572559     over makefile-specified suffix rules, which is wrong.  */
    2258 
    22592560  install_default_suffix_rules ();
    22602561
    22612562  /* Define some internal and special variables.  */
    2262 
    22632563  define_automatic_variables ();
    22642564
    2265   /* Set up the MAKEFLAGS and MFLAGS variables
    2266      so makefiles can look at them.  */
    2267 
    2268   define_makeflags (0, 0);
     2565  /* Set up the MAKEFLAGS and MFLAGS variables for makefiles to see.
     2566     Initialize it to be exported but allow the makefile to reset it.  */
     2567  define_makeflags (0, 0)->export = v_export;
    22692568
    22702569  /* Define the default variables.  */
     
    22822581      char *p, *value;
    22832582      unsigned int i;
    2284       unsigned int len = sizeof ("--eval=") * eval_strings->idx;
     2583      unsigned int len = (CSTRLEN ("--eval=") + 1) * eval_strings->idx;
    22852584
    22862585      for (i = 0; i < eval_strings->idx; ++i)
     
    22892588          p = xstrdup (eval_strings->list[i]);
    22902589          len += 2 * strlen (p);
    2291           eval_buffer (p);
     2590          eval_buffer (p, NULL);
    22922591#else
    22932592          unsigned int sub_len = strlen(eval_strings->list[i]);
    22942593          p = xstrndup (eval_strings->list[i], sub_len);
    22952594          len += 2 * sub_len;
    2296           eval_buffer (p, p + sub_len);
     2595          eval_buffer (p, NULL, p + sub_len);
    22972596#endif
    22982597          free (p);
     
    23032602        {
    23042603          strcpy (p, "--eval=");
    2305           p += strlen (p);
     2604          p += CSTRLEN ("--eval=");
    23062605          p = quote_for_env (p, eval_strings->list[i]);
    23072606          *(p++) = ' ';
     
    23142613  /* Read all the makefiles.  */
    23152614
    2316   read_makefiles
    2317     = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
     2615  read_files = read_all_makefiles (makefiles == 0 ? 0 : makefiles->list);
    23182616
    23192617#ifdef WINDOWS32
    23202618  /* look one last time after reading all Makefiles */
    23212619  if (no_default_sh_exe)
    2322     no_default_sh_exe = !find_and_set_default_shell(NULL);
     2620    no_default_sh_exe = !find_and_set_default_shell (NULL);
    23232621#endif /* WINDOWS32 */
    23242622
    2325 #if defined (__MSDOS__) || defined (__EMX__)
     2623#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
    23262624  /* We need to know what kind of shell we will be using.  */
    23272625  {
     
    23292627    struct variable *shv = lookup_variable (STRING_SIZE_TUPLE ("SHELL"));
    23302628    extern int unixy_shell;
    2331     extern char *default_shell;
     2629    extern const char *default_shell;
    23322630
    23332631    if (shv && *shv->value)
    23342632      {
    2335         char *shell_path = recursively_expand(shv);
    2336 
    2337         if (shell_path && _is_unixy_shell (shell_path))
    2338           unixy_shell = 1;
    2339         else
    2340           unixy_shell = 0;
    2341         if (shell_path)
    2342           default_shell = shell_path;
     2633        char *shell_path = recursively_expand (shv);
     2634
     2635        if (shell_path && _is_unixy_shell (shell_path))
     2636          unixy_shell = 1;
     2637        else
     2638          unixy_shell = 0;
     2639        if (shell_path)
     2640          default_shell = shell_path;
    23432641      }
    23442642  }
    23452643#endif /* __MSDOS__ || __EMX__ */
    23462644
    2347   /* Decode switches again, in case the variables were set by the makefile.  */
     2645  {
     2646    int old_builtin_rules_flag = no_builtin_rules_flag;
     2647    int old_builtin_variables_flag = no_builtin_variables_flag;
     2648
     2649    /* Decode switches again, for variables set by the makefile.  */
     2650    decode_env_switches (STRING_SIZE_TUPLE ("GNUMAKEFLAGS"));
     2651
     2652    /* Clear GNUMAKEFLAGS to avoid duplication.  */
     2653    define_variable_cname ("GNUMAKEFLAGS", "", o_override, 0);
     2654
    23482655#ifdef KMK
    2349   decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
     2656    decode_env_switches (STRING_SIZE_TUPLE ("KMK_FLAGS"));
    23502657#else /* !KMK */
    2351   decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
     2658    decode_env_switches (STRING_SIZE_TUPLE ("MAKEFLAGS"));
    23522659#if 0
    2353   decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
     2660    decode_env_switches (STRING_SIZE_TUPLE ("MFLAGS"));
    23542661#endif
    23552662#endif /* !KMK */
    23562663
    2357 #if defined (__MSDOS__) || defined (__EMX__)
    2358   if (job_slots != 1
     2664    /* Reset in case the switches changed our mind.  */
     2665    syncing = (output_sync == OUTPUT_SYNC_LINE
     2666               || output_sync == OUTPUT_SYNC_TARGET);
     2667
     2668    if (make_sync.syncout && ! syncing)
     2669      output_close (&make_sync);
     2670
     2671    make_sync.syncout = syncing;
     2672    OUTPUT_SET (&make_sync);
     2673
     2674    /* If we've disabled builtin rules, get rid of them.  */
     2675    if (no_builtin_rules_flag && ! old_builtin_rules_flag)
     2676      {
     2677        if (suffix_file->builtin)
     2678          {
     2679            free_dep_chain (suffix_file->deps);
     2680            suffix_file->deps = 0;
     2681          }
     2682        define_variable_cname ("SUFFIXES", "", o_default, 0);
     2683      }
     2684
     2685    /* If we've disabled builtin variables, get rid of them.  */
     2686    if (no_builtin_variables_flag && ! old_builtin_variables_flag)
     2687      undefine_default_variables ();
     2688  }
     2689
     2690#if defined (__MSDOS__) || defined (__EMX__) || defined (VMS)
     2691  if (arg_job_slots != 1
    23592692# ifdef __EMX__
    23602693      && _osmode != OS2_MODE /* turn off -j if we are in DOS mode */
     
    23622695      )
    23632696    {
    2364       error (NILF,
    2365              _("Parallel jobs (-j) are not supported on this platform."));
    2366       error (NILF, _("Resetting to single job (-j1) mode."));
    2367       job_slots = 1;
    2368     }
    2369 #endif
    2370 
    2371 #ifdef MAKE_JOBSERVER
    2372   /* If the jobserver-fds option is seen, make sure that -j is reasonable.  */
    2373 
    2374   if (jobserver_fds)
    2375     {
    2376       const char *cp;
    2377       unsigned int ui;
    2378 
    2379       for (ui=1; ui < jobserver_fds->idx; ++ui)
    2380         if (!streq (jobserver_fds->list[0], jobserver_fds->list[ui]))
    2381           fatal (NILF, _("internal error: multiple --jobserver-fds options"));
    2382 
    2383       /* Now parse the fds string and make sure it has the proper format.  */
    2384 
    2385       cp = jobserver_fds->list[0];
    2386 
    2387       if (sscanf (cp, "%d,%d", &job_fds[0], &job_fds[1]) != 2)
    2388         fatal (NILF,
    2389                _("internal error: invalid --jobserver-fds string `%s'"), cp);
    2390 
    2391       DB (DB_JOBS,
    2392           (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
    2393 
    2394       /* The combination of a pipe + !job_slots means we're using the
    2395          jobserver.  If !job_slots and we don't have a pipe, we can start
    2396          infinite jobs.  If we see both a pipe and job_slots >0 that means the
    2397          user set -j explicitly.  This is broken; in this case obey the user
    2398          (ignore the jobserver pipe for this make) but print a message.  */
    2399 
    2400       if (job_slots > 0)
    2401         error (NILF,
    2402                _("warning: -jN forced in submake: disabling jobserver mode."));
    2403 
    2404       /* Create a duplicate pipe, that will be closed in the SIGCHLD
    2405          handler.  If this fails with EBADF, the parent has closed the pipe
    2406          on us because it didn't think we were a submake.  If so, print a
    2407          warning then default to -j1.  */
    2408 
    2409       else if ((job_rfd = dup (job_fds[0])) < 0)
     2697      O (error, NILF,
     2698         _("Parallel jobs (-j) are not supported on this platform."));
     2699      O (error, NILF, _("Resetting to single job (-j1) mode."));
     2700      arg_job_slots = job_slots = 1;
     2701    }
     2702#endif
     2703
     2704  /* If we have >1 slot at this point, then we're a top-level make.
     2705     Set up the jobserver.
     2706
     2707     Every make assumes that it always has one job it can run.  For the
     2708     submakes it's the token they were given by their parent.  For the top
     2709     make, we just subtract one from the number the user wants.  */
     2710
     2711  if (job_slots > 1 && jobserver_setup (job_slots - 1))
     2712    {
     2713      /* Fill in the jobserver_auth for our children.  */
     2714      jobserver_auth = jobserver_get_auth ();
     2715
     2716      if (jobserver_auth)
    24102717        {
    2411           if (errno != EBADF)
    2412             pfatal_with_name (_("dup jobserver"));
    2413 
    2414           error (NILF,
    2415                  _("warning: jobserver unavailable: using -j1.  Add `+' to parent make rule."));
    2416           job_slots = 1;
     2718          /* We're using the jobserver so set job_slots to 0.  */
     2719          master_job_slots = job_slots;
     2720          job_slots = 0;
    24172721        }
    2418 
    2419       if (job_slots > 0)
    2420         {
    2421           close (job_fds[0]);
    2422           close (job_fds[1]);
    2423           job_fds[0] = job_fds[1] = -1;
    2424           free (jobserver_fds->list);
    2425           free (jobserver_fds);
    2426           jobserver_fds = 0;
    2427         }
    2428     }
    2429 
    2430   /* If we have >1 slot but no jobserver-fds, then we're a top-level make.
    2431      Set up the pipe and install the fds option for our children.  */
    2432 
    2433   if (job_slots > 1)
    2434     {
    2435       char *cp;
    2436       char c = '+';
    2437 
    2438       if (pipe (job_fds) < 0 || (job_rfd = dup (job_fds[0])) < 0)
    2439         pfatal_with_name (_("creating jobs pipe"));
    2440 
    2441       /* Every make assumes that it always has one job it can run.  For the
    2442          submakes it's the token they were given by their parent.  For the
    2443          top make, we just subtract one from the number the user wants.  We
    2444          want job_slots to be 0 to indicate we're using the jobserver.  */
    2445 
    2446       master_job_slots = job_slots;
    2447 
    2448       while (--job_slots)
    2449         {
    2450           int r;
    2451 
    2452           EINTRLOOP (r, write (job_fds[1], &c, 1));
    2453           if (r != 1)
    2454             pfatal_with_name (_("init jobserver pipe"));
    2455         }
    2456 
    2457       /* Fill in the jobserver_fds struct for our children.  */
    2458 
    2459       cp = xmalloc ((sizeof ("1024")*2)+1);
    2460       sprintf (cp, "%d,%d", job_fds[0], job_fds[1]);
    2461 
    2462       jobserver_fds = (struct stringlist *)
    2463                         xmalloc (sizeof (struct stringlist));
    2464       jobserver_fds->list = xmalloc (sizeof (char *));
    2465       jobserver_fds->list[0] = cp;
    2466       jobserver_fds->idx = 1;
    2467       jobserver_fds->max = 1;
    2468     }
    2469 #endif
     2722    }
     2723
     2724  /* If we're not using parallel jobs, then we don't need output sync.
     2725     This is so people can enable output sync in GNUMAKEFLAGS or similar, but
     2726     not have it take effect unless parallel builds are enabled.  */
     2727  if (syncing && job_slots == 1)
     2728    {
     2729      OUTPUT_UNSET ();
     2730      output_close (&make_sync);
     2731      syncing = 0;
     2732      output_sync = OUTPUT_SYNC_NONE;
     2733    }
    24702734
    24712735#ifndef MAKE_SYMLINKS
    24722736  if (check_symlink_flag)
    24732737    {
    2474       error (NILF, _("Symbolic links not supported: disabling -L."));
     2738      O (error, NILF, _("Symbolic links not supported: disabling -L."));
    24752739      check_symlink_flag = 0;
    24762740    }
     
    24812745  define_makeflags (1, 0);
    24822746
    2483   /* Make each `struct dep' point at the `struct file' for the file
     2747  /* Make each 'struct goaldep' point at the 'struct file' for the file
    24842748     depended on.  Also do magic for special targets.  */
    24852749
     
    25202784          f->last_mtime = f->mtime_before_update = OLD_MTIME;
    25212785          f->updated = 1;
    2522           f->update_status = 0;
     2786          f->update_status = us_success;
    25232787          f->command_state = cs_finished;
    25242788        }
     
    25292793      const char **p;
    25302794      for (p = new_files->list; *p != 0; ++p)
    2531         {
    2532           struct file *f = enter_file (*p);
    2533           f->last_mtime = f->mtime_before_update = NEW_MTIME;
    2534         }
     2795        {
     2796          struct file *f = enter_file (*p);
     2797          f->last_mtime = f->mtime_before_update = NEW_MTIME;
     2798        }
    25352799    }
    25362800
     
    25382802  remote_setup ();
    25392803
    2540   if (read_makefiles != 0)
     2804  /* Dump any output we've collected.  */
     2805
     2806  OUTPUT_UNSET ();
     2807  output_close (&make_sync);
     2808
     2809  if (read_files != 0)
    25412810    {
    25422811      /* Update any makefiles if necessary.  */
     
    25442813      FILE_TIMESTAMP *makefile_mtimes = 0;
    25452814      unsigned int mm_idx = 0;
    2546       char **nargv;
     2815      char **aargv = NULL;
     2816      const char **nargv;
    25472817      int nargc;
    2548       int orig_db_level = db_level;
    2549       int status;
    2550 
    2551       if (! ISDB (DB_MAKEFILES))
    2552         db_level = DB_NONE;
     2818      enum update_status status;
    25532819
    25542820      DB (DB_BASIC, (_("Updating makefiles....\n")));
    25552821
    25562822      /* Remove any makefiles we don't want to try to update.
    2557         Also record the current modtimes so we can compare them later.  */
     2823        Also record the current modtimes so we can compare them later.  */
    25582824      {
    2559         register struct dep *d, *last;
    2560         last = 0;
    2561         d = read_makefiles;
    2562         while (d != 0)
    2563           {
    2564             struct file *f = d->file;
    2565             if (f->double_colon)
    2566               for (f = f->double_colon; f != NULL; f = f->prev)
    2567                 {
    2568                   if (f->deps == 0 && f->cmds != 0)
    2569                     {
    2570                       /* This makefile is a :: target with commands, but
    2571                         no dependencies.  So, it will always be remade.
    2572                         This might well cause an infinite loop, so don't
    2573                         try to remake it.  (This will only happen if
    2574                         your makefiles are written exceptionally
    2575                         stupidly; but if you work for Athena, that's how
    2576                         you write your makefiles.)  */
    2577 
    2578                       DB (DB_VERBOSE,
    2579                           (_("Makefile `%s' might loop; not remaking it.\n"),
     2825        register struct goaldep *d, *last;
     2826        last = 0;
     2827        d = read_files;
     2828        while (d != 0)
     2829          {
     2830            struct file *f = d->file;
     2831            if (f->double_colon)
     2832              for (f = f->double_colon; f != NULL; f = f->prev)
     2833                {
     2834                  if (f->deps == 0 && f->cmds != 0)
     2835                    {
     2836                      /* This makefile is a :: target with commands, but
     2837                        no dependencies.  So, it will always be remade.
     2838                        This might well cause an infinite loop, so don't
     2839                        try to remake it.  (This will only happen if
     2840                        your makefiles are written exceptionally
     2841                        stupidly; but if you work for Athena, that's how
     2842                        you write your makefiles.)  */
     2843
     2844                      DB (DB_VERBOSE,
     2845                          (_("Makefile '%s' might loop; not remaking it.\n"),
    25802846                           f->name));
    25812847
    2582                       if (last == 0)
    2583                         read_makefiles = d->next;
    2584                       else
    2585                         last->next = d->next;
    2586 
    2587                       /* Free the storage.  */
    2588                       free_dep (d);
    2589 
    2590                       d = last == 0 ? read_makefiles : last->next;
    2591 
    2592                       break;
    2593                     }
    2594                 }
    2595             if (f == NULL || !f->double_colon)
    2596               {
     2848                      if (last == 0)
     2849                        read_files = d->next;
     2850                      else
     2851                        last->next = d->next;
     2852
     2853                      /* Free the storage.  */
     2854                      free_goaldep (d);
     2855
     2856                      d = last == 0 ? read_files : last->next;
     2857
     2858                      break;
     2859                    }
     2860                }
     2861
     2862            if (f == NULL || !f->double_colon)
     2863              {
    25972864                makefile_mtimes = xrealloc (makefile_mtimes,
    25982865                                            (mm_idx+1)
    25992866                                            * sizeof (FILE_TIMESTAMP));
    2600                 makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
    2601                 last = d;
    2602                 d = d->next;
    2603               }
    2604           }
     2867                makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
     2868                last = d;
     2869                d = d->next;
     2870              }
     2871          }
    26052872      }
    26062873
    2607       /* Set up `MAKEFLAGS' specially while remaking makefiles.  */
     2874      /* Set up 'MAKEFLAGS' specially while remaking makefiles.  */
    26082875      define_makeflags (1, 1);
    26092876
    2610       rebuilding_makefiles = 1;
    2611       status = update_goal_chain (read_makefiles);
    2612       rebuilding_makefiles = 0;
     2877      {
     2878        int orig_db_level = db_level;
     2879
     2880        if (! ISDB (DB_MAKEFILES))
     2881          db_level = DB_NONE;
     2882
     2883        rebuilding_makefiles = 1;
     2884        status = update_goal_chain (read_files);
     2885        rebuilding_makefiles = 0;
     2886
     2887        db_level = orig_db_level;
     2888      }
    26132889
    26142890      switch (status)
    2615         {
    2616         case 1:
     2891        {
     2892        case us_question:
    26172893          /* The only way this can happen is if the user specified -q and asked
    2618            * for one of the makefiles to be remade as a target on the command
    2619            * line.  Since we're not actually updating anything with -q we can
    2620            * treat this as "did nothing".
    2621            */
    2622 
    2623         case -1:
    2624           /* Did nothing.  */
    2625           break;
    2626 
    2627         case 2:
    2628           /* Failed to update.  Figure out if we care.  */
    2629           {
    2630             /* Nonzero if any makefile was successfully remade.  */
    2631             int any_remade = 0;
    2632             /* Nonzero if any makefile we care about failed
    2633                in updating or could not be found at all.  */
    2634             int any_failed = 0;
    2635             unsigned int i;
    2636             struct dep *d;
    2637 
    2638             for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
     2894             for one of the makefiles to be remade as a target on the command
     2895             line.  Since we're not actually updating anything with -q we can
     2896             treat this as "did nothing".  */
     2897
     2898        case us_none:
     2899          /* Did nothing.  */
     2900          break;
     2901
     2902        case us_failed:
     2903          /* Failed to update.  Figure out if we care.  */
     2904          {
     2905            /* Nonzero if any makefile was successfully remade.  */
     2906            int any_remade = 0;
     2907            /* Nonzero if any makefile we care about failed
     2908               in updating or could not be found at all.  */
     2909            int any_failed = 0;
     2910            unsigned int i;
     2911            struct goaldep *d;
     2912
     2913            for (i = 0, d = read_files; d != 0; ++i, d = d->next)
    26392914              {
    2640                 /* Reset the considered flag; we may need to look at the file
    2641                    again to print an error.  */
    2642                 d->file->considered = 0;
    2643 
    26442915                if (d->file->updated)
    26452916                  {
    26462917                    /* This makefile was updated.  */
    2647                     if (d->file->update_status == 0)
     2918                    if (d->file->update_status == us_success)
    26482919                      {
    26492920                        /* It was successfully updated.  */
     
    26512922                                       != makefile_mtimes[i]);
    26522923                      }
    2653                     else if (! (d->changed & RM_DONTCARE))
     2924                    else if (! (d->flags & RM_DONTCARE))
    26542925                      {
    26552926                        FILE_TIMESTAMP mtime;
    26562927                        /* The update failed and this makefile was not
    26572928                           from the MAKEFILES variable, so we care.  */
    2658                         error (NILF, _("Failed to remake makefile `%s'."),
    2659                                d->file->name);
     2929                        OS (error, NILF, _("Failed to remake makefile '%s'."),
     2930                            d->file->name);
    26602931                        mtime = file_mtime_no_search (d->file);
    26612932                        any_remade |= (mtime != NONEXISTENT_MTIME
     
    26662937                else
    26672938                  /* This makefile was not found at all.  */
    2668                   if (! (d->changed & RM_DONTCARE))
     2939                  if (! (d->flags & RM_DONTCARE))
    26692940                    {
     2941                      const char *dnm = dep_name (d);
     2942                      size_t l = strlen (dnm);
     2943
    26702944                      /* This is a makefile we care about.  See how much.  */
    2671                       if (d->changed & RM_INCLUDED)
    2672                         /* An included makefile.  We don't need
    2673                            to die, but we do want to complain.  */
    2674                         error (NILF,
    2675                                _("Included makefile `%s' was not found."),
    2676                                dep_name (d));
     2945                      if (d->flags & RM_INCLUDED)
     2946                        /* An included makefile.  We don't need to die, but we
     2947                           do want to complain.  */
     2948                        error (NILF, l,
     2949                               _("Included makefile '%s' was not found."), dnm);
    26772950                      else
    26782951                        {
    26792952                          /* A normal makefile.  We must die later.  */
    2680                           error (NILF, _("Makefile `%s' was not found"),
    2681                                  dep_name (d));
     2953                          error (NILF, l,
     2954                                 _("Makefile '%s' was not found"), dnm);
    26822955                          any_failed = 1;
    26832956                        }
     
    26852958              }
    26862959            /* Reset this to empty so we get the right error message below.  */
    2687             read_makefiles = 0;
    2688 
    2689             if (any_remade)
    2690               goto re_exec;
    2691             if (any_failed)
    2692               die (2);
     2960            read_files = 0;
     2961
     2962            if (any_remade)
     2963              goto re_exec;
     2964            if (any_failed)
     2965              die (MAKE_FAILURE);
    26932966            break;
    2694           }
    2695 
    2696         case 0:
    2697         re_exec:
    2698           /* Updated successfully.  Re-exec ourselves.  */
    2699 
    2700           remove_intermediates (0);
    2701 
    2702           if (print_data_base_flag)
    2703             print_data_base ();
    2704 
    2705           log_working_directory (0);
     2967          }
     2968
     2969        case us_success:
     2970        re_exec:
     2971          /* Updated successfully.  Re-exec ourselves.  */
     2972
     2973          remove_intermediates (0);
     2974
     2975          if (print_data_base_flag)
     2976            print_data_base ();
    27062977
    27072978          clean_jobserver (0);
    27082979
    2709           if (makefiles != 0)
    2710             {
    2711               /* These names might have changed.  */
    2712               int i, j = 0;
    2713               for (i = 1; i < argc; ++i)
    2714                 if (strneq (argv[i], "-f", 2)) /* XXX */
    2715                   {
    2716                     if (argv[i][2] == '\0')
     2980          if (makefiles != 0)
     2981            {
     2982              /* These names might have changed.  */
     2983              int i, j = 0;
     2984              for (i = 1; i < argc; ++i)
     2985                if (strneq (argv[i], "-f", 2)) /* XXX */
     2986                  {
     2987                    if (argv[i][2] == '\0')
    27172988                      /* This cast is OK since we never modify argv.  */
    2718                       argv[++i] = (char *) makefiles->list[j];
    2719                     else
    2720                       argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
    2721                     ++j;
    2722                   }
    2723             }
     2989                      argv[++i] = (char *) makefiles->list[j];
     2990                    else
     2991                      argv[i] = xstrdup (concat (2, "-f", makefiles->list[j]));
     2992                    ++j;
     2993                  }
     2994            }
    27242995
    27252996          /* Add -o option for the stdin temporary file, if necessary.  */
     
    27272998          if (stdin_nm)
    27282999            {
    2729               nargv = xmalloc ((nargc + 2) * sizeof (char *));
    2730               memcpy (nargv, argv, argc * sizeof (char *));
    2731               nargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
    2732               nargv[nargc] = 0;
     3000              void *m = xmalloc ((nargc + 2) * sizeof (char *));
     3001              aargv = m;
     3002              memcpy (aargv, argv, argc * sizeof (char *));
     3003              aargv[nargc++] = xstrdup (concat (2, "-o", stdin_nm));
     3004              aargv[nargc] = 0;
     3005              nargv = m;
    27333006            }
    27343007          else
    2735             nargv = argv;
    2736 
    2737           if (directories != 0 && directories->idx > 0)
    2738             {
    2739               int bad = 1;
    2740               if (directory_before_chdir != 0)
    2741                 {
    2742                   if (chdir (directory_before_chdir) < 0)
    2743                       perror_with_name ("chdir", "");
    2744                   else
    2745                     bad = 0;
    2746                 }
    2747               if (bad)
    2748                 fatal (NILF, _("Couldn't change back to original directory."));
    2749             }
     3008            nargv = (const char**)argv;
     3009
     3010          if (directories != 0 && directories->idx > 0)
     3011            {
     3012              int bad = 1;
     3013              if (directory_before_chdir != 0)
     3014                {
     3015                  if (chdir (directory_before_chdir) < 0)
     3016                      perror_with_name ("chdir", "");
     3017                  else
     3018                    bad = 0;
     3019                }
     3020              if (bad)
     3021                O (fatal, NILF,
     3022                   _("Couldn't change back to original directory."));
     3023            }
    27503024
    27513025          ++restarts;
    27523026
    2753           /* Reset makeflags in case they were changed.  */
    2754           {
    2755             const char *pv = define_makeflags (1, 1);
    2756             char *p = alloca (sizeof ("MAKEFLAGS=") + strlen (pv) + 1);
    2757             sprintf (p, "MAKEFLAGS=%s", pv);
    2758             putenv (p);
    2759           }
    2760 
    2761           if (ISDB (DB_BASIC))
    2762             {
    2763               char **p;
    2764               printf (_("Re-executing[%u]:"), restarts);
    2765               for (p = nargv; *p != 0; ++p)
    2766                 printf (" %s", *p);
    2767               putchar ('\n');
    2768             }
     3027          if (ISDB (DB_BASIC))
     3028            {
     3029              const char **p;
     3030              printf (_("Re-executing[%u]:"), restarts);
     3031              for (p = nargv; *p != 0; ++p)
     3032                printf (" %s", *p);
     3033              putchar ('\n');
     3034              fflush (stdout);
     3035            }
    27693036
    27703037#ifndef _AMIGA
     
    27733040            for (p = environ; *p != 0; ++p)
    27743041              {
    2775                 if (strneq (*p, MAKELEVEL_NAME, MAKELEVEL_LENGTH)
    2776                     && (*p)[MAKELEVEL_LENGTH] == '=')
     3042                if (strneq (*p, MAKELEVEL_NAME "=", MAKELEVEL_LENGTH+1))
    27773043                  {
    27783044                    *p = alloca (40);
    27793045                    sprintf (*p, "%s=%u", MAKELEVEL_NAME, makelevel);
     3046#ifdef VMS
     3047                    vms_putenv_symbol (*p);
     3048#endif
    27803049                  }
    2781                 if (strneq (*p, "MAKE_RESTARTS=", 14))
     3050                else if (strneq (*p, "MAKE_RESTARTS=", CSTRLEN ("MAKE_RESTARTS=")))
    27823051                  {
    27833052                    *p = alloca (40);
    2784                     sprintf (*p, "MAKE_RESTARTS=%u", restarts);
     3053                    sprintf (*p, "MAKE_RESTARTS=%s%u",
     3054                             OUTPUT_IS_TRACED () ? "-" : "", restarts);
    27853055                    restarts = 0;
    27863056                  }
     
    27883058          }
    27893059#else /* AMIGA */
    2790           {
    2791             char buffer[256];
     3060          {
     3061            char buffer[256];
    27923062
    27933063            sprintf (buffer, "%u", makelevel);
    27943064            SetVar (MAKELEVEL_NAME, buffer, -1, GVF_GLOBAL_ONLY);
    27953065
    2796             sprintf (buffer, "%u", restarts);
     3066            sprintf (buffer, "%s%u", OUTPUT_IS_TRACED () ? "-" : "", restarts);
    27973067            SetVar ("MAKE_RESTARTS", buffer, -1, GVF_GLOBAL_ONLY);
    27983068            restarts = 0;
    2799           }
     3069          }
    28003070#endif
    28013071
     
    28043074            {
    28053075              char *b = alloca (40);
    2806               sprintf (b, "MAKE_RESTARTS=%u", restarts);
     3076              sprintf (b, "MAKE_RESTARTS=%s%u",
     3077                       OUTPUT_IS_TRACED () ? "-" : "", restarts);
    28073078              putenv (b);
    28083079            }
    28093080
    2810           fflush (stdout);
    2811           fflush (stderr);
    2812 
    2813           /* Close the dup'd jobserver pipe if we opened one.  */
    2814           if (job_rfd >= 0)
    2815             close (job_rfd);
     3081          fflush (stdout);
     3082          fflush (stderr);
    28163083
    28173084#ifdef _AMIGA
    2818           exec_command (nargv);
    2819           exit (0);
     3085          exec_command (nargv);
     3086          exit (0);
    28203087#elif defined (__EMX__)
    2821           {
    2822             /* It is not possible to use execve() here because this
    2823                would cause the parent process to be terminated with
    2824                exit code 0 before the child process has been terminated.
    2825                Therefore it may be the best solution simply to spawn the
    2826                child process including all file handles and to wait for its
    2827                termination. */
    2828             int pid;
    2829             int status;
    2830             pid = child_execute_job (0, 1, nargv, environ);
    2831 
    2832             /* is this loop really necessary? */
    2833             do {
    2834               pid = wait (&status);
    2835             } while (pid <= 0);
    2836             /* use the exit code of the child process */
    2837             exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);
    2838           }
     3088          {
     3089            /* It is not possible to use execve() here because this
     3090               would cause the parent process to be terminated with
     3091               exit code 0 before the child process has been terminated.
     3092               Therefore it may be the best solution simply to spawn the
     3093               child process including all file handles and to wait for its
     3094               termination. */
     3095            int pid;
     3096            int r;
     3097            pid = child_execute_job (NULL, 1, nargv, environ);
     3098
     3099            /* is this loop really necessary? */
     3100            do {
     3101              pid = wait (&r);
     3102            } while (pid <= 0);
     3103            /* use the exit code of the child process */
     3104            exit (WIFEXITED(r) ? WEXITSTATUS(r) : EXIT_FAILURE);
     3105          }
    28393106#else
    2840           exec_command (nargv, environ);
    2841 #endif
    2842           /* NOTREACHED */
    2843 
    2844         default:
    2845 #define BOGUS_UPDATE_STATUS 0
    2846           assert (BOGUS_UPDATE_STATUS);
    2847           break;
    2848         }
    2849 
    2850       db_level = orig_db_level;
    2851 
    2852       /* Free the makefile mtimes (if we allocated any).  */
    2853       if (makefile_mtimes)
    2854         free (makefile_mtimes);
    2855     }
    2856 
    2857   /* Set up `MAKEFLAGS' again for the normal targets.  */
     3107#ifdef SET_STACK_SIZE
     3108          /* Reset limits, if necessary.  */
     3109          if (stack_limit.rlim_cur)
     3110            setrlimit (RLIMIT_STACK, &stack_limit);
     3111#endif
     3112          exec_command ((char **)nargv, environ);
     3113#endif
     3114          free (aargv);
     3115          break;
     3116        }
     3117
     3118      /* Free the makefile mtimes.  */
     3119      free (makefile_mtimes);
     3120    }
     3121
     3122  /* Set up 'MAKEFLAGS' again for the normal targets.  */
    28583123  define_makeflags (1, 0);
    28593124
     
    28663131      const char **p;
    28673132      for (p = new_files->list; *p != 0; ++p)
    2868         {
    2869           struct file *f = enter_file (*p);
    2870           f->last_mtime = f->mtime_before_update = NEW_MTIME;
    2871         }
     3133        {
     3134          struct file *f = enter_file (*p);
     3135          f->last_mtime = f->mtime_before_update = NEW_MTIME;
     3136        }
    28723137    }
    28733138
     
    29013166            {
    29023167              struct nameseq *ns;
    2903               ns = PARSE_FILE_SEQ (&p, struct nameseq, '\0', NULL, 0);
     3168
     3169              ns = PARSE_SIMPLE_SEQ (&p, struct nameseq);
    29043170              if (ns)
    29053171                {
    29063172                  /* .DEFAULT_GOAL should contain one target. */
    29073173                  if (ns->next != 0)
    2908                     fatal (NILF, _(".DEFAULT_GOAL contains more than one target"));
     3174                    O (fatal, NILF,
     3175                       _(".DEFAULT_GOAL contains more than one target"));
    29093176
    29103177#ifndef CONFIG_WITH_VALUE_LENGTH
     
    29213188          if (f)
    29223189            {
    2923               goals = alloc_dep ();
     3190              goals = alloc_goaldep ();
    29243191              goals->file = f;
    29253192            }
     
    29323199  if (!goals)
    29333200    {
    2934       if (read_makefiles == 0)
    2935         fatal (NILF, _("No targets specified and no makefile found"));
    2936 
    2937       fatal (NILF, _("No targets"));
     3201      if (read_files == 0)
     3202        O (fatal, NILF, _("No targets specified and no makefile found"));
     3203
     3204      O (fatal, NILF, _("No targets"));
    29383205    }
    29393206
     
    29433210
    29443211  {
    2945     int status;
    2946 
    29473212    switch (update_goal_chain (goals))
    29483213    {
    2949       case -1:
     3214      case us_none:
    29503215        /* Nothing happened.  */
    2951       case 0:
    2952         /* Updated successfully.  */
    2953         status = makefile_status;
     3216        /* FALLTHROUGH */
     3217      case us_success:
     3218        /* Keep the previous result.  */
    29543219        break;
    2955       case 1:
     3220      case us_question:
    29563221        /* We are under -q and would run some commands.  */
    2957         status = MAKE_TROUBLE;
     3222        makefile_status = MAKE_TROUBLE;
    29583223        break;
    2959       case 2:
    2960         /* Updating failed.  POSIX.2 specifies exit status >1 for this;
    2961            but in VMS, there is only success and failure.  */
    2962         status = MAKE_FAILURE;
     3224      case us_failed:
     3225        /* Updating failed.  POSIX.2 specifies exit status >1 for this; */
     3226        makefile_status = MAKE_FAILURE;
    29633227        break;
    2964       default:
    2965         abort ();
    29663228    }
    29673229
    29683230    /* If we detected some clock skew, generate one last warning */
    29693231    if (clock_skew_detected)
    2970       error (NILF,
    2971              _("warning:  Clock skew detected.  Your build may be incomplete."));
     3232      O (error, NILF,
     3233         _("warning:  Clock skew detected.  Your build may be incomplete."));
    29723234
    29733235    MAKE_STATS_2(if (uStartTick) printf("main ticks elapsed: %ull\n", (unsigned long long)(CURRENT_CLOCK_TICK() - uStartTick)) );
    29743236    /* Exit.  */
    2975     die (status);
     3237    die (makefile_status);
    29763238  }
    29773239
    29783240  /* NOTREACHED */
    2979   return 0;
     3241  exit (MAKE_SUCCESS);
    29803242}
    29813243
     
    29853247static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
    29863248static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
    2987                                   (sizeof (long_option_aliases) /
    2988                                    sizeof (long_option_aliases[0]))];
     3249                                  (sizeof (long_option_aliases) /
     3250                                   sizeof (long_option_aliases[0]))];
    29893251
    29903252/* Fill in the string and vector for getopt.  */
     
    30093271    {
    30103272      long_options[i].name = (switches[i].long_name == 0 ? "" :
    3011                               switches[i].long_name);
     3273                              switches[i].long_name);
    30123274      long_options[i].flag = 0;
    30133275      long_options[i].val = switches[i].c;
    30143276      if (short_option (switches[i].c))
    3015         *p++ = switches[i].c;
     3277        *p++ = switches[i].c;
    30163278      switch (switches[i].type)
    3017         {
    3018         case flag:
    3019         case flag_off:
    3020         case ignore:
    3021           long_options[i].has_arg = no_argument;
    3022           break;
    3023 
    3024         case string:
     3279        {
     3280        case flag:
     3281        case flag_off:
     3282        case ignore:
     3283          long_options[i].has_arg = no_argument;
     3284          break;
     3285
     3286        case string:
     3287        case strlist:
    30253288        case filename:
    3026         case positive_int:
    3027         case floating:
    3028           if (short_option (switches[i].c))
    3029             *p++ = ':';
    3030           if (switches[i].noarg_value != 0)
    3031             {
    3032               if (short_option (switches[i].c))
    3033                 *p++ = ':';
    3034               long_options[i].has_arg = optional_argument;
    3035             }
    3036           else
    3037             long_options[i].has_arg = required_argument;
    3038           break;
    3039         }
     3289        case positive_int:
     3290        case floating:
     3291          if (short_option (switches[i].c))
     3292            *p++ = ':';
     3293          if (switches[i].noarg_value != 0)
     3294            {
     3295              if (short_option (switches[i].c))
     3296                *p++ = ':';
     3297              long_options[i].has_arg = optional_argument;
     3298            }
     3299          else
     3300            long_options[i].has_arg = required_argument;
     3301          break;
     3302        }
    30403303    }
    30413304  *p = '\0';
    30423305  for (c = 0; c < (sizeof (long_option_aliases) /
    3043                    sizeof (long_option_aliases[0]));
     3306                   sizeof (long_option_aliases[0]));
    30443307       ++c)
    30453308    long_options[i++] = long_option_aliases[c];
     
    30473310}
    30483311
     3312
     3313/* Non-option argument.  It might be a variable definition.  */
    30493314static void
    3050 handle_non_switch_argument (char *arg, int env)
     3315handle_non_switch_argument (const char *arg, int env)
    30513316{
    3052   /* Non-option argument.  It might be a variable definition.  */
    30533317  struct variable *v;
     3318
    30543319  if (arg[0] == '-' && arg[1] == '\0')
    3055     /* Ignore plain `-' for compatibility.  */
     3320    /* Ignore plain '-' for compatibility.  */
    30563321    return;
     3322
     3323#ifdef VMS
     3324  {
     3325    /* VMS DCL quoting can result in foo="bar baz" showing up here.
     3326       Need to remove the double quotes from the value. */
     3327    char * eq_ptr;
     3328    char * new_arg;
     3329    eq_ptr = strchr (arg, '=');
     3330    if ((eq_ptr != NULL) && (eq_ptr[1] == '"'))
     3331      {
     3332         int len;
     3333         int seg1;
     3334         int seg2;
     3335         len = strlen(arg);
     3336         new_arg = alloca(len);
     3337         seg1 = eq_ptr - arg + 1;
     3338         strncpy(new_arg, arg, (seg1));
     3339         seg2 = len - seg1 - 1;
     3340         strncpy(&new_arg[seg1], &eq_ptr[2], seg2);
     3341         new_arg[seg1 + seg2] = 0;
     3342         if (new_arg[seg1 + seg2 - 1] == '"')
     3343           new_arg[seg1 + seg2 - 1] = 0;
     3344         arg = new_arg;
     3345      }
     3346  }
     3347#endif
    30573348  v = try_variable_definition (0, arg IF_WITH_VALUE_LENGTH_PARAM(NULL), o_command, 0);
    30583349  if (v != 0)
    30593350    {
    30603351      /* It is indeed a variable definition.  If we don't already have this
    3061         one, record a pointer to the variable for later use in
    3062         define_makeflags.  */
     3352        one, record a pointer to the variable for later use in
     3353        define_makeflags.  */
    30633354      struct command_variable *cv;
    30643355
     
    30673358          break;
    30683359
    3069       if (! cv) {
    3070         cv = xmalloc (sizeof (*cv));
    3071         cv->variable = v;
    3072         cv->next = command_variables;
    3073         command_variables = cv;
    3074       }
     3360      if (! cv)
     3361        {
     3362          cv = xmalloc (sizeof (*cv));
     3363          cv->variable = v;
     3364          cv->next = command_variables;
     3365          command_variables = cv;
     3366        }
    30753367    }
    30763368  else if (! env)
    30773369    {
    30783370      /* Not an option or variable definition; it must be a goal
    3079         target!  Enter it as a file and add it to the dep chain of
    3080         goals.  */
     3371        target!  Enter it as a file and add it to the dep chain of
     3372        goals.  */
    30813373      struct file *f = enter_file (strcache_add (expand_command_line_file (arg)));
    30823374      f->cmd_target = 1;
    30833375
    30843376      if (goals == 0)
    3085         {
    3086           goals = alloc_dep ();
    3087           lastgoal = goals;
    3088         }
     3377        {
     3378          goals = alloc_goaldep ();
     3379          lastgoal = goals;
     3380        }
    30893381      else
    3090         {
    3091           lastgoal->next = alloc_dep ();
    3092           lastgoal = lastgoal->next;
    3093         }
     3382        {
     3383          lastgoal->next = alloc_goaldep ();
     3384          lastgoal = lastgoal->next;
     3385        }
    30943386
    30953387      lastgoal->file = f;
     
    31623454
    31633455static void
    3164 decode_switches (int argc, char **argv, int env)
     3456decode_switches (int argc, const char **argv, int env)
    31653457{
    31663458  int bad = 0;
     
    31823474  while (optind < argc)
    31833475    {
     3476      const char *coptarg;
     3477
    31843478      /* Parse the next argument.  */
    3185       c = getopt_long (argc, argv, options, long_options, (int *) 0);
     3479      c = getopt_long (argc, (char*const*)argv, options, long_options, NULL);
     3480      coptarg = optarg;
    31863481      if (c == EOF)
    3187         /* End of arguments, or "--" marker seen.  */
    3188         break;
     3482        /* End of arguments, or "--" marker seen.  */
     3483        break;
    31893484      else if (c == 1)
    3190         /* An argument not starting with a dash.  */
    3191         handle_non_switch_argument (optarg, env);
     3485        /* An argument not starting with a dash.  */
     3486        handle_non_switch_argument (coptarg, env);
    31923487      else if (c == '?')
    3193         /* Bad option.  We will print a usage message and die later.
    3194            But continue to parse the other options so the user can
    3195            see all he did wrong.  */
    3196         bad = 1;
     3488        /* Bad option.  We will print a usage message and die later.
     3489           But continue to parse the other options so the user can
     3490           see all he did wrong.  */
     3491        bad = 1;
    31973492      else
    3198         for (cs = switches; cs->c != '\0'; ++cs)
    3199           if (cs->c == c)
    3200             {
    3201               /* Whether or not we will actually do anything with
    3202                  this switch.  We test this individually inside the
    3203                  switch below rather than just once outside it, so that
    3204                  options which are to be ignored still consume args.  */
    3205               int doit = !env || cs->env;
    3206 
    3207               switch (cs->type)
    3208                 {
    3209                 default:
    3210                   abort ();
    3211 
    3212                 case ignore:
    3213                   break;
    3214 
    3215                 case flag:
    3216                 case flag_off:
    3217                   if (doit)
    3218                     *(int *) cs->value_ptr = cs->type == flag;
    3219                   break;
    3220 
    3221                 case string:
    3222                 case filename:
    3223                   if (!doit)
    3224                     break;
    3225 
    3226                   if (optarg == 0)
    3227                     optarg = xstrdup (cs->noarg_value);
    3228                   else if (*optarg == '\0')
     3493        for (cs = switches; cs->c != '\0'; ++cs)
     3494          if (cs->c == c)
     3495            {
     3496              /* Whether or not we will actually do anything with
     3497                 this switch.  We test this individually inside the
     3498                 switch below rather than just once outside it, so that
     3499                 options which are to be ignored still consume args.  */
     3500              int doit = !env || cs->env;
     3501
     3502              switch (cs->type)
     3503                {
     3504                default:
     3505                  abort ();
     3506
     3507                case ignore:
     3508                  break;
     3509
     3510                case flag:
     3511                case flag_off:
     3512                  if (doit)
     3513                    *(int *) cs->value_ptr = cs->type == flag;
     3514                  break;
     3515
     3516                case string:
     3517                case strlist:
     3518                case filename:
     3519                  if (!doit)
     3520                    break;
     3521
     3522                  if (! coptarg)
     3523                    coptarg = xstrdup (cs->noarg_value);
     3524                  else if (*coptarg == '\0')
    32293525                    {
    32303526                      char opt[2] = "c";
     
    32363532                        op = cs->long_name;
    32373533
    3238                       error (NILF, _("the `%s%s' option requires a non-empty string argument"),
     3534                      error (NILF, strlen (op),
     3535                             _("the '%s%s' option requires a non-empty string argument"),
    32393536                             short_option (cs->c) ? "-" : "--", op);
    32403537                      bad = 1;
     3538                      break;
    32413539                    }
    32423540
    3243                   sl = *(struct stringlist **) cs->value_ptr;
    3244                   if (sl == 0)
    3245                     {
    3246                       sl = (struct stringlist *)
    3247                         xmalloc (sizeof (struct stringlist));
    3248                       sl->max = 5;
    3249                       sl->idx = 0;
    3250                       sl->list = xmalloc (5 * sizeof (char *));
    3251                       *(struct stringlist **) cs->value_ptr = sl;
    3252                     }
    3253                   else if (sl->idx == sl->max - 1)
    3254                     {
    3255                       sl->max += 5;
     3541                  if (cs->type == string)
     3542                    {
     3543                      char **val = (char **)cs->value_ptr;
     3544                      free (*val);
     3545                      *val = xstrdup (coptarg);
     3546                      break;
     3547                    }
     3548
     3549                  sl = *(struct stringlist **) cs->value_ptr;
     3550                  if (sl == 0)
     3551                    {
     3552                      sl = xmalloc (sizeof (struct stringlist));
     3553                      sl->max = 5;
     3554                      sl->idx = 0;
     3555                      sl->list = xmalloc (5 * sizeof (char *));
     3556                      *(struct stringlist **) cs->value_ptr = sl;
     3557                    }
     3558                  else if (sl->idx == sl->max - 1)
     3559                    {
     3560                      sl->max += 5;
    32563561                      /* MSVC erroneously warns without a cast here.  */
    3257                       sl->list = xrealloc ((void *)sl->list,
     3562                      sl->list = xrealloc ((void *)sl->list,
    32583563                                           sl->max * sizeof (char *));
    3259                     }
     3564                    }
    32603565                  if (cs->type == filename)
    3261                     sl->list[sl->idx++] = expand_command_line_file (optarg);
     3566                    sl->list[sl->idx++] = expand_command_line_file (coptarg);
    32623567                  else
    3263                     sl->list[sl->idx++] = optarg;
    3264                   sl->list[sl->idx] = 0;
    3265                   break;
    3266 
    3267                 case positive_int:
     3568                    sl->list[sl->idx++] = xstrdup (coptarg);
     3569                  sl->list[sl->idx] = 0;
     3570                  break;
     3571
     3572                case positive_int:
    32683573                  /* See if we have an option argument; if we do require that
    32693574                     it's all digits, not something like "10foo".  */
    3270                   if (optarg == 0 && argc > optind)
     3575                  if (coptarg == 0 && argc > optind)
    32713576                    {
    32723577                      const char *cp;
     
    32743579                        ;
    32753580                      if (cp[0] == '\0')
    3276                         optarg = argv[optind++];
     3581                        coptarg = argv[optind++];
    32773582                    }
    32783583
    3279                   if (!doit)
    3280                     break;
    3281 
    3282                   if (optarg != 0)
    3283                     {
    3284                       int i = atoi (optarg);
     3584                  if (!doit)
     3585                    break;
     3586
     3587                  if (coptarg)
     3588                    {
     3589                      int i = atoi (coptarg);
    32853590                      const char *cp;
    32863591
    32873592                      /* Yes, I realize we're repeating this in some cases.  */
    3288                       for (cp = optarg; ISDIGIT (cp[0]); ++cp)
     3593                      for (cp = coptarg; ISDIGIT (cp[0]); ++cp)
    32893594                        ;
    32903595
    3291                       if (i < 1 || cp[0] != '\0')
    3292                         {
    3293                           error (NILF, _("the `-%c' option requires a positive integral argument"),
     3596                      if (i < 1 || cp[0] != '\0')
     3597                        {
     3598                          error (NILF, 0,
     3599                                 _("the '-%c' option requires a positive integer argument"),
    32943600                                 cs->c);
    3295                           bad = 1;
    3296                         }
    3297                       else
    3298                         *(unsigned int *) cs->value_ptr = i;
    3299                     }
    3300                   else
    3301                     *(unsigned int *) cs->value_ptr
    3302                       = *(unsigned int *) cs->noarg_value;
    3303                   break;
     3601                          bad = 1;
     3602                        }
     3603                      else
     3604                        *(unsigned int *) cs->value_ptr = i;
     3605                    }
     3606                  else
     3607                    *(unsigned int *) cs->value_ptr
     3608                      = *(unsigned int *) cs->noarg_value;
     3609                  break;
    33043610
    33053611#ifndef NO_FLOAT
    3306                 case floating:
    3307                   if (optarg == 0 && optind < argc
    3308                       && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
    3309                     optarg = argv[optind++];
    3310 
    3311                   if (doit)
    3312                     *(double *) cs->value_ptr
    3313                       = (optarg != 0 ? atof (optarg)
    3314                         : *(double *) cs->noarg_value);
    3315 
    3316                   break;
    3317 #endif
    3318                 }
    3319 
    3320               /* We've found the switch.  Stop looking.  */
    3321               break;
    3322             }
     3612                case floating:
     3613                  if (coptarg == 0 && optind < argc
     3614                      && (ISDIGIT (argv[optind][0]) || argv[optind][0] == '.'))
     3615                    coptarg = argv[optind++];
     3616
     3617                  if (doit)
     3618                    *(double *) cs->value_ptr
     3619                      = (coptarg != 0 ? atof (coptarg)
     3620                        : *(double *) cs->noarg_value);
     3621
     3622                  break;
     3623#endif
     3624                }
     3625
     3626              /* We've found the switch.  Stop looking.  */
     3627              break;
     3628            }
    33233629    }
    33243630
     
    33303636    handle_non_switch_argument (argv[optind++], env);
    33313637
    3332 
    33333638  if (!env && (bad || print_usage_flag))
    33343639    {
    33353640      print_usage (bad);
    3336       die (bad ? 2 : 0);
    3337     }
     3641      die (bad ? MAKE_FAILURE : MAKE_SUCCESS);
     3642    }
     3643
     3644  /* If there are any options that need to be decoded do it now.  */
     3645  decode_debug_flags ();
     3646  decode_output_sync_flags ();
    33383647}
    33393648
     
    33443653
    33453654static void
    3346 decode_env_switches (char *envar, unsigned int len)
     3655decode_env_switches (const char *envar, unsigned int len)
    33473656{
    33483657  char *varref = alloca (2 + len + 2);
    3349   char *value, *p;
     3658  char *value, *p, *buf;
    33503659  int argc;
    3351   char **argv;
     3660  const char **argv;
    33523661
    33533662  /* Get the variable's value.  */
     
    33603669
    33613670  /* Skip whitespace, and check for an empty value.  */
    3362   value = next_token (value);
     3671  NEXT_TOKEN (value);
    33633672  len = strlen (value);
    33643673  if (len == 0)
     
    33673676  /* Allocate a vector that is definitely big enough.  */
    33683677  argv = alloca ((1 + len + 1) * sizeof (char *));
    3369 
    3370   /* Allocate a buffer to copy the value into while we split it into words
    3371      and unquote it.  We must use permanent storage for this because
    3372      decode_switches may store pointers into the passed argument words.  */
    3373   p = xmalloc (2 * len);
    33743678
    33753679  /* getopt will look at the arguments starting at ARGV[1].
     
    33773681  argv[0] = 0;
    33783682  argc = 1;
     3683
     3684  /* We need a buffer to copy the value into while we split it into words
     3685     and unquote it.  Set up in case we need to prepend a dash later.  */
     3686  buf = alloca (1 + len + 1);
     3687  buf[0] = '-';
     3688  p = buf+1;
    33793689  argv[argc] = p;
    33803690  while (*value != '\0')
    33813691    {
    33823692      if (*value == '\\' && value[1] != '\0')
    3383         ++value;                /* Skip the backslash.  */
    3384       else if (isblank ((unsigned char)*value))
    3385         {
    3386           /* End of the word.  */
    3387           *p++ = '\0';
    3388           argv[++argc] = p;
    3389           do
    3390             ++value;
    3391           while (isblank ((unsigned char)*value));
    3392           continue;
    3393         }
     3693        ++value;                /* Skip the backslash.  */
     3694      else if (ISBLANK (*value))
     3695        {
     3696          /* End of the word.  */
     3697          *p++ = '\0';
     3698          argv[++argc] = p;
     3699          do
     3700            ++value;
     3701          while (ISBLANK (*value));
     3702          continue;
     3703        }
    33943704      *p++ = *value++;
    33953705    }
    33963706  *p = '\0';
    33973707  argv[++argc] = 0;
     3708  assert (p < buf + len + 2);
    33983709
    33993710  if (argv[1][0] != '-' && strchr (argv[1], '=') == 0)
    34003711    /* The first word doesn't start with a dash and isn't a variable
    3401        definition.  Add a dash and pass it along to decode_switches.  We
    3402        need permanent storage for this in case decode_switches saves
    3403        pointers into the value.  */
    3404     argv[1] = xstrdup (concat (2, "-", argv[1]));
     3712       definition, so add a dash.  */
     3713    argv[1] = buf;
    34053714
    34063715  /* Parse those words.  */
     
    34213730    {
    34223731      if (*in == '$')
    3423         *out++ = '$';
    3424       else if (isblank ((unsigned char)*in) || *in == '\\')
     3732        *out++ = '$';
     3733      else if (ISBLANK (*in) || *in == '\\')
    34253734        *out++ = '\\';
    34263735      *out++ = *in++;
     
    34323741/* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
    34333742   command switches.  Include options with args if ALL is nonzero.
    3434    Don't include options with the `no_makefile' flag set if MAKEFILE.  */
    3435 
    3436 static const char *
     3743   Don't include options with the 'no_makefile' flag set if MAKEFILE.  */
     3744
     3745static struct variable *
    34373746define_makeflags (int all, int makefile)
    34383747{
     
    34463755  const struct command_switch *cs;
    34473756  char *flagstring;
    3448   register char *p;
    3449   unsigned int words;
    3450   struct variable *v;
    3451 
    3452   /* We will construct a linked list of `struct flag's describing
     3757  char *p;
     3758
     3759  /* We will construct a linked list of 'struct flag's describing
    34533760     all the flags which need to go in MAKEFLAGS.  Then, once we
    34543761     know how many there are and their lengths, we can put them all
     
    34623769    };
    34633770  struct flag *flags = 0;
     3771  struct flag *last = 0;
    34643772  unsigned int flagslen = 0;
    3465 #define ADD_FLAG(ARG, LEN) \
    3466   do {                                                                        \
    3467     struct flag *new = alloca (sizeof (struct flag));                         \
    3468     new->cs = cs;                                                             \
    3469     new->arg = (ARG);                                                         \
    3470     new->next = flags;                                                        \
    3471     flags = new;                                                              \
    3472     if (new->arg == 0)                                                        \
    3473       ++flagslen;               /* Just a single flag letter.  */             \
    3474     else                                                                      \
    3475       /* " -x foo", plus space to expand "foo".  */                           \
    3476       flagslen += 1 + 1 + 1 + 1 + (3 * (LEN));                                \
    3477     if (!short_option (cs->c))                                                \
     3773#define ADD_FLAG(ARG, LEN) \
     3774  do {                                                                        \
     3775    struct flag *new = alloca (sizeof (struct flag));                         \
     3776    new->cs = cs;                                                             \
     3777    new->arg = (ARG);                                                         \
     3778    new->next = 0;                                                            \
     3779    if (! flags)                                                              \
     3780      flags = new;                                                            \
     3781    else                                                                      \
     3782      last->next = new;                                                       \
     3783    last = new;                                                               \
     3784    if (new->arg == 0)                                                        \
     3785      /* Just a single flag letter: " -x"  */                                 \
     3786      flagslen += 3;                                                          \
     3787    else                                                                      \
     3788      /* " -xfoo", plus space to escape "foo".  */                            \
     3789      flagslen += 1 + 1 + 1 + (3 * (LEN));                                    \
     3790    if (!short_option (cs->c))                                                \
    34783791      /* This switch has no single-letter version, so we use the long.  */    \
    3479       flagslen += 2 + strlen (cs->long_name);                                 \
     3792      flagslen += 2 + strlen (cs->long_name);                                 \
    34803793  } while (0)
    34813794
     
    34833796    if (cs->toenv && (!makefile || !cs->no_makefile))
    34843797      switch (cs->type)
    3485         {
    3486         case ignore:
    3487           break;
    3488 
    3489         case flag:
    3490         case flag_off:
    3491           if (!*(int *) cs->value_ptr == (cs->type == flag_off)
    3492               && (cs->default_value == 0
    3493                   || *(int *) cs->value_ptr != *(int *) cs->default_value))
    3494             ADD_FLAG (0, 0);
    3495           break;
    3496 
    3497         case positive_int:
    3498           if (all)
    3499             {
    3500               if ((cs->default_value != 0
    3501                    && (*(unsigned int *) cs->value_ptr
    3502                        == *(unsigned int *) cs->default_value)))
    3503                 break;
    3504               else if (cs->noarg_value != 0
    3505                        && (*(unsigned int *) cs->value_ptr ==
    3506                            *(unsigned int *) cs->noarg_value))
    3507                 ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
    3508 #if !defined(KMK) || !defined(WINDOWS32) /* jobserver stuff doesn't work on windows???. */
    3509               else if (cs->c == 'j')
    3510                 /* Special case for `-j'.  */
    3511                 ADD_FLAG ("1", 1);
    3512 #endif
    3513               else
    3514                 {
    3515                   char *buf = alloca (30);
    3516                   sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
    3517                   ADD_FLAG (buf, strlen (buf));
    3518                 }
    3519             }
    3520           break;
     3798        {
     3799        case ignore:
     3800          break;
     3801
     3802        case flag:
     3803        case flag_off:
     3804          if ((!*(int *) cs->value_ptr) == (cs->type == flag_off)
     3805              && (cs->default_value == 0
     3806                  || *(int *) cs->value_ptr != *(int *) cs->default_value))
     3807            ADD_FLAG (0, 0);
     3808          break;
     3809
     3810        case positive_int:
     3811          if (all)
     3812            {
     3813              if ((cs->default_value != 0
     3814                   && (*(unsigned int *) cs->value_ptr
     3815                       == *(unsigned int *) cs->default_value)))
     3816                break;
     3817              else if (cs->noarg_value != 0
     3818                       && (*(unsigned int *) cs->value_ptr ==
     3819                           *(unsigned int *) cs->noarg_value))
     3820                ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
     3821              else
     3822                {
     3823                  char *buf = alloca (30);
     3824                  sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
     3825                  ADD_FLAG (buf, strlen (buf));
     3826                }
     3827            }
     3828          break;
    35213829
    35223830#ifndef NO_FLOAT
    3523         case floating:
    3524           if (all)
    3525             {
    3526               if (cs->default_value != 0
    3527                   && (*(double *) cs->value_ptr
    3528                       == *(double *) cs->default_value))
    3529                 break;
    3530               else if (cs->noarg_value != 0
    3531                        && (*(double *) cs->value_ptr
    3532                            == *(double *) cs->noarg_value))
    3533                 ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
    3534               else
    3535                 {
    3536                   char *buf = alloca (100);
    3537                   sprintf (buf, "%g", *(double *) cs->value_ptr);
    3538                   ADD_FLAG (buf, strlen (buf));
    3539                 }
    3540             }
    3541           break;
    3542 #endif
    3543 
    3544         case filename:
    3545         case string:
    3546           if (all)
    3547             {
    3548               struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
    3549               if (sl != 0)
    3550                 {
    3551                   /* Add the elements in reverse order, because all the flags
    3552                      get reversed below; and the order matters for some
    3553                      switches (like -I).  */
    3554                   unsigned int i = sl->idx;
    3555                   while (i-- > 0)
    3556                     ADD_FLAG (sl->list[i], strlen (sl->list[i]));
    3557                 }
    3558             }
    3559           break;
    3560 
    3561         default:
    3562           abort ();
    3563         }
    3564 
    3565   /* Four more for the possible " -- ".  */
    3566   flagslen += 4 + sizeof (posixref) + sizeof (evalref);
    3567 
    3568 #undef  ADD_FLAG
     3831        case floating:
     3832          if (all)
     3833            {
     3834              if (cs->default_value != 0
     3835                  && (*(double *) cs->value_ptr
     3836                      == *(double *) cs->default_value))
     3837                break;
     3838              else if (cs->noarg_value != 0
     3839                       && (*(double *) cs->value_ptr
     3840                           == *(double *) cs->noarg_value))
     3841                ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
     3842              else
     3843                {
     3844                  char *buf = alloca (100);
     3845                  sprintf (buf, "%g", *(double *) cs->value_ptr);
     3846                  ADD_FLAG (buf, strlen (buf));
     3847                }
     3848            }
     3849          break;
     3850#endif
     3851
     3852        case string:
     3853          if (all)
     3854            {
     3855              p = *((char **)cs->value_ptr);
     3856              if (p)
     3857                ADD_FLAG (p, strlen (p));
     3858            }
     3859          break;
     3860
     3861        case filename:
     3862        case strlist:
     3863          if (all)
     3864            {
     3865              struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
     3866              if (sl != 0)
     3867                {
     3868                  unsigned int i;
     3869                  for (i = 0; i < sl->idx; ++i)
     3870                    ADD_FLAG (sl->list[i], strlen (sl->list[i]));
     3871                }
     3872            }
     3873          break;
     3874
     3875        default:
     3876          abort ();
     3877        }
     3878
     3879#undef  ADD_FLAG
     3880
     3881  /* Four more for the possible " -- ", plus variable references.  */
     3882  flagslen += 4 + CSTRLEN (posixref) + 1 + CSTRLEN (evalref) + 1;
    35693883
    35703884  /* Construct the value in FLAGSTRING.
     
    35733887  memset (flagstring, '\0', 1 + flagslen + 1);
    35743888  p = flagstring;
    3575   words = 1;
     3889
     3890  /* Start with a dash, for MFLAGS.  */
    35763891  *p++ = '-';
    3577   while (flags != 0)
    3578     {
     3892
     3893  /* Add simple options as a group.  */
     3894  while (flags != 0 && !flags->arg && short_option (flags->cs->c))
     3895    {
     3896      *p++ = flags->cs->c;
     3897      flags = flags->next;
     3898    }
     3899
     3900  /* Now add more complex flags: ones with options and/or long names.  */
     3901  while (flags)
     3902    {
     3903      *p++ = ' ';
     3904      *p++ = '-';
     3905
    35793906      /* Add the flag letter or name to the string.  */
    35803907      if (short_option (flags->cs->c))
    3581         *p++ = flags->cs->c;
     3908        *p++ = flags->cs->c;
    35823909      else
    3583         {
    3584           if (*p != '-')
    3585             {
    3586               *p++ = ' ';
    3587               *p++ = '-';
    3588             }
    3589           *p++ = '-';
    3590           strcpy (p, flags->cs->long_name);
    3591           p += strlen (p);
    3592         }
    3593       if (flags->arg != 0)
    3594         {
    3595           /* A flag that takes an optional argument which in this case is
    3596              omitted is specified by ARG being "".  We must distinguish
    3597              because a following flag appended without an intervening " -"
    3598              is considered the arg for the first.  */
    3599           if (flags->arg[0] != '\0')
    3600             {
    3601               /* Add its argument too.  */
    3602               *p++ = !short_option (flags->cs->c) ? '=' : ' ';
    3603               p = quote_for_env (p, flags->arg);
    3604             }
    3605           ++words;
    3606           /* Write a following space and dash, for the next flag.  */
    3607           *p++ = ' ';
    3608           *p++ = '-';
    3609         }
    3610       else if (!short_option (flags->cs->c))
    3611         {
    3612           ++words;
    3613           /* Long options must each go in their own word,
    3614              so we write the following space and dash.  */
    3615           *p++ = ' ';
    3616           *p++ = '-';
    3617         }
     3910        {
     3911          /* Long options require a double-dash.  */
     3912          *p++ = '-';
     3913          strcpy (p, flags->cs->long_name);
     3914          p += strlen (p);
     3915        }
     3916      /* An omitted optional argument has an ARG of "".  */
     3917      if (flags->arg && flags->arg[0] != '\0')
     3918        {
     3919          if (!short_option (flags->cs->c))
     3920            /* Long options require '='.  */
     3921            *p++ = '=';
     3922          p = quote_for_env (p, flags->arg);
     3923        }
    36183924      flags = flags->next;
    36193925    }
    36203926
    3621   /* Define MFLAGS before appending variable definitions.  */
    3622 
     3927  /* If no flags at all, get rid of the initial dash.  */
    36233928  if (p == &flagstring[1])
    3624     /* No flags.  */
    3625     flagstring[0] = '\0';
    3626   else if (p[-1] == '-')
    3627     {
    3628       /* Kill the final space and dash.  */
    3629       p -= 2;
    3630       *p = '\0';
    3631     }
    3632   else
    3633     /* Terminate the string.  */
    3634     *p = '\0';
     3929    {
     3930      flagstring[0] = '\0';
     3931      p = flagstring;
     3932    }
    36353933
    36363934#ifdef KMK
    3637   /* Since MFLAGS is not parsed for flags, there is no reason to
     3935  /* Define MFLAGS before appending variable definitions.  Omit an initial
     3936     empty dash.  Since MFLAGS is not parsed for flags, there is no reason to
    36383937     override any makefile redefinition.  */
    3639   define_variable_cname ("MFLAGS", flagstring, o_env, 1);
     3938  define_variable_cname ("MFLAGS",
     3939                         flagstring + (flagstring[0] == '-' && flagstring[1] == ' ' ? 2 : 0),
     3940                         o_env, 1);
    36403941#endif /* !KMK */
    36413942
     
    36443945  if (eval_strings)
    36453946    {
    3646       if (p == &flagstring[1])
    3647         /* No flags written, so elide the leading dash already written.  */
    3648         p = flagstring;
    3649       else
    3650         *p++ = ' ';
    3651       memcpy (p, evalref, sizeof (evalref) - 1);
    3652       p += sizeof (evalref) - 1;
    3653     }
    3654 
    3655   if (all && command_variables != 0)
    3656     {
    3657       /* Now write a reference to $(MAKEOVERRIDES), which contains all the
    3658          command-line variable definitions.  */
    3659 
    3660       if (p == &flagstring[1])
    3661         /* No flags written, so elide the leading dash already written.  */
    3662         p = flagstring;
    3663       else
    3664         {
    3665           /* Separate the variables from the switches with a "--" arg.  */
    3666           if (p[-1] != '-')
    3667             {
    3668               /* We did not already write a trailing " -".  */
    3669               *p++ = ' ';
    3670               *p++ = '-';
    3671             }
    3672           /* There is a trailing " -"; fill it out to " -- ".  */
    3673           *p++ = '-';
    3674           *p++ = ' ';
    3675         }
     3947      *p++ = ' ';
     3948      memcpy (p, evalref, CSTRLEN (evalref));
     3949      p += CSTRLEN (evalref);
     3950    }
     3951
     3952  if (all && command_variables)
     3953    {
     3954      /* Write a reference to $(MAKEOVERRIDES), which contains all the
     3955         command-line variable definitions.  Separate the variables from the
     3956         switches with a "--" arg.  */
     3957
     3958      strcpy (p, " -- ");
     3959      p += 4;
    36763960
    36773961      /* Copy in the string.  */
    36783962      if (posix_pedantic)
    3679         {
    3680           memcpy (p, posixref, sizeof (posixref) - 1);
    3681           p += sizeof (posixref) - 1;
    3682         }
     3963        {
     3964          memcpy (p, posixref, CSTRLEN (posixref));
     3965          p += CSTRLEN (posixref);
     3966        }
    36833967      else
    3684         {
    3685           memcpy (p, ref, sizeof (ref) - 1);
    3686           p += sizeof (ref) - 1;
    3687         }
    3688     }
    3689   else if (p == &flagstring[1])
    3690     {
    3691       words = 0;
    3692       --p;
    3693     }
    3694   else if (p[-1] == '-')
    3695     /* Kill the final space and dash.  */
    3696     p -= 2;
    3697   /* Terminate the string.  */
    3698   *p = '\0';
    3699 
    3700   /* If there are switches, omit the leading dash unless it is a single long
    3701      option with two leading dashes.  */
    3702   if (flagstring[0] == '-' && flagstring[1] != '-')
     3968        {
     3969          memcpy (p, ref, CSTRLEN (ref));
     3970          p += CSTRLEN (ref);
     3971        }
     3972    }
     3973
     3974  /* If there is a leading dash, omit it.  */
     3975  if (flagstring[0] == '-')
    37033976    ++flagstring;
    3704 
    3705 #ifdef KMK
    3706   v = define_variable_cname ("KMK_FLAGS", flagstring,
    3707                              /* This used to use o_env, but that lost when a
    3708                                 makefile defined MAKEFLAGS.  Makefiles set
    3709                                 MAKEFLAGS to add switches, but we still want
    3710                                 to redefine its value with the full set of
    3711                                 switches.  Of course, an override or command
    3712                                 definition will still take precedence.  */
    3713                              o_file, 1);
    3714 #else
    3715   v = define_variable_cname ("MAKEFLAGS", flagstring,
    3716                              /* This used to use o_env, but that lost when a
    3717                                 makefile defined MAKEFLAGS.  Makefiles set
    3718                                 MAKEFLAGS to add switches, but we still want
    3719                                 to redefine its value with the full set of
    3720                                 switches.  Of course, an override or command
    3721                                 definition will still take precedence.  */
    3722                              o_file, 1);
    3723 #endif
    3724 
    3725   if (! all)
    3726     /* The first time we are called, set MAKEFLAGS to always be exported.
    3727        We should not do this again on the second call, because that is
    3728        after reading makefiles which might have done `unexport MAKEFLAGS'. */
    3729     v->export = v_export;
    37303977
    37313978#ifdef KMK
     
    37544001#endif
    37554002
    3756   return v->value;
     4003  /* This used to use o_env, but that lost when a makefile defined MAKEFLAGS.
     4004     Makefiles set MAKEFLAGS to add switches, but we still want to redefine
     4005     its value with the full set of switches.  Then we used o_file, but that
     4006     lost when users added -e, causing a previous MAKEFLAGS env. var. to take
     4007     precedence over the new one.  Of course, an override or command
     4008     definition will still take precedence.  */
     4009#ifdef KMK
     4010  return define_variable_cname ("KMK_FLAGS", flagstring,
     4011                                env_overrides ? o_env_override : o_file, 1);
     4012#else
     4013  return define_variable_cname ("MAKEFLAGS", flagstring,
     4014                                env_overrides ? o_env_override : o_file, 1);
     4015#endif
    37574016}
    37584017
     
    37654024  static int printed_version = 0;
    37664025
    3767   char *precede = print_data_base_flag ? "# " : "";
     4026  const char *precede = print_data_base_flag ? "# " : "";
    37684027
    37694028  if (printed_version)
     
    37924051     (C) to the copyright symbol, but this string is going to change every
    37934052     year, and none of the rest of it should be translated (including the
    3794      word "Copyright", so it hardly seems worth it.  */
    3795 
    3796   printf ("%sCopyright (C) 2010  Free Software Foundation, Inc.\n", precede);
     4053     word "Copyright"), so it hardly seems worth it.  */
     4054
     4055  printf ("%sCopyright (C) 1988-2016 Free Software Foundation, Inc.\n",
     4056          precede);
    37974057
    37984058  printf (_("%sLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\
     
    38404100
    38414101  /* Flush stdout so the user doesn't have to wait to see the
    3842      version information while things are thought about.  */
     4102     version information while make thinks about things.  */
    38434103  fflush (stdout);
    38444104}
     
    38474107
    38484108static void
    3849 print_data_base ()
     4109print_data_base (void)
    38504110{
    3851   time_t when;
    3852 
    3853   when = time ((time_t *) 0);
     4111  time_t when = time ((time_t *) 0);
     4112
     4113  print_version ();
     4114
    38544115  printf (_("\n# Make data base, printed on %s"), ctime (&when));
    38554116
     
    39204181clean_jobserver (int status)
    39214182{
    3922   char token = '+';
    3923 
    39244183  /* Sanity: have we written all our jobserver tokens back?  If our
    39254184     exit status is 2 that means some kind of syntax error; we might not
     
    39274186     after any other error code, that's bad.  */
    39284187
    3929   if (job_fds[0] != -1 && jobserver_tokens)
     4188  if (jobserver_enabled() && jobserver_tokens)
    39304189    {
    39314190      if (status != 2)
    3932         error (NILF,
    3933                "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
    3934                jobserver_tokens);
     4191        ON (error, NILF,
     4192            "INTERNAL: Exiting with %u jobserver tokens (should be 0)!",
     4193            jobserver_tokens);
    39354194      else
    3936         while (jobserver_tokens--)
    3937           {
    3938             int r;
    3939 
    3940             EINTRLOOP (r, write (job_fds[1], &token, 1));
    3941             if (r != 1)
    3942               perror_with_name ("write", "");
    3943           }
     4195        /* Don't write back the "free" token */
     4196        while (--jobserver_tokens)
     4197          jobserver_release (0);
    39444198    }
    39454199
     
    39504204    {
    39514205      /* We didn't write one for ourself, so start at 1.  */
    3952       unsigned int tcnt = 1;
    3953 
    3954       /* Close the write side, so the read() won't hang.  */
    3955       close (job_fds[1]);
    3956 
    3957       while (read (job_fds[0], &token, 1) == 1)
    3958         ++tcnt;
    3959 
    3960       if (tcnt != master_job_slots)
    3961         error (NILF,
    3962                "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
    3963                tcnt, master_job_slots);
    3964 
    3965       close (job_fds[0]);
    3966 
    3967       /* Clean out jobserver_fds so we don't pass this information to any
    3968          sub-makes.  Also reset job_slots since it will be put on the command
    3969          line, not in MAKEFLAGS.  */
    3970       job_slots = default_job_slots;
    3971       if (jobserver_fds)
    3972         {
    3973           /* MSVC erroneously warns without a cast here.  */
    3974           free ((void *)jobserver_fds->list);
    3975           free (jobserver_fds);
    3976           jobserver_fds = 0;
    3977         }
     4206      unsigned int tokens = 1 + jobserver_acquire_all ();
     4207
     4208      if (tokens != master_job_slots)
     4209        ONN (error, NILF,
     4210             "INTERNAL: Exiting with %u jobserver tokens available; should be %u!",
     4211             tokens, master_job_slots);
     4212
     4213      reset_jobserver ();
    39784214    }
    39794215}
     
    39974233
    39984234      if (print_version_flag)
    3999         print_version ();
     4235        print_version ();
    40004236
    40014237#ifdef KMK
     
    40114247      err = (status != 0);
    40124248      while (job_slots_used > 0)
    4013         reap_children (1, err);
     4249        reap_children (1, err);
    40144250
    40154251      /* Let the remote job module clean up its state.  */
     
    40204256
    40214257      if (print_data_base_flag)
    4022         print_data_base ();
     4258        print_data_base ();
    40234259
    40244260#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
     
    40264262        print_stats ();
    40274263#endif
     4264      if (verify_flag)
     4265        verify_file_data_base ();
    40284266
    40294267#ifdef NDEBUG /* bird: Don't waste time on debug sanity checks.  */
     
    40344272      clean_jobserver (status);
    40354273
     4274      if (output_context)
     4275        {
     4276          /* die() might be called in a recipe output context due to an
     4277             $(error ...) function.  */
     4278          output_close (output_context);
     4279
     4280          if (output_context != &make_sync)
     4281            output_close (&make_sync);
     4282
     4283          OUTPUT_UNSET ();
     4284        }
     4285
     4286      output_close (NULL);
     4287
    40364288      /* Try to move back to the original directory.  This is essential on
    4037         MS-DOS (where there is really only one process), and on Unix it
    4038         puts core files in the original directory instead of the -C
    4039         directory.  Must wait until after remove_intermediates(), or unlinks
     4289        MS-DOS (where there is really only one process), and on Unix it
     4290        puts core files in the original directory instead of the -C
     4291        directory.  Must wait until after remove_intermediates(), or unlinks
    40404292         of relative pathnames fail.  */
    40414293      if (directory_before_chdir != 0)
    40424294        {
    40434295          /* If it fails we don't care: shut up GCC.  */
    4044           int _x;
     4296          int _x UNUSED;
    40454297          _x = chdir (directory_before_chdir);
    40464298        }
     
    40544306              char buf[64];
    40554307              format_elapsed_nano (buf, sizeof (buf), elapsed);
    4056               message (1, _("%*s"), print_time_width, buf);
     4308              message (1, strlen (buf), _("%*s"), print_time_width, buf);
    40574309            }
    40584310        }
    40594311#endif
    4060 
    4061       log_working_directory (0);
    40624312    }
    40634313
     
    40664316     failure again before exiting. */
    40674317  if (need_2nd_error != 0)
    4068     error (NILF, _("*** Exiting with status %d"), status);
     4318    ON (error, NILF, _("*** Exiting with status %d"), status);
    40694319#endif
    40704320
    40714321  exit (status);
    40724322}
    4073 
    4074 
    4075 /* Write a message indicating that we've just entered or
    4076    left (according to ENTERING) the current directory.  */
    4077 
    4078 void
    4079 log_working_directory (int entering)
    4080 {
    4081   static int entered = 0;
    4082 
    4083   /* Print nothing without the flag.  Don't print the entering message
    4084      again if we already have.  Don't print the leaving message if we
    4085      haven't printed the entering message.  */
    4086   if (! print_directory_flag || entering == entered)
    4087     return;
    4088 
    4089   entered = entering;
    4090 
    4091   if (print_data_base_flag)
    4092     fputs ("# ", stdout);
    4093 
    4094   /* Use entire sentences to give the translators a fighting chance.  */
    4095 
    4096   if (makelevel == 0)
    4097     if (starting_directory == 0)
    4098       if (entering)
    4099         printf (_("%s: Entering an unknown directory\n"), program);
    4100       else
    4101         printf (_("%s: Leaving an unknown directory\n"), program);
    4102     else
    4103       if (entering)
    4104         printf (_("%s: Entering directory `%s'\n"),
    4105                 program, starting_directory);
    4106       else
    4107         printf (_("%s: Leaving directory `%s'\n"),
    4108                 program, starting_directory);
    4109   else
    4110     if (starting_directory == 0)
    4111       if (entering)
    4112         printf (_("%s[%u]: Entering an unknown directory\n"),
    4113                 program, makelevel);
    4114       else
    4115         printf (_("%s[%u]: Leaving an unknown directory\n"),
    4116                 program, makelevel);
    4117     else
    4118       if (entering)
    4119         printf (_("%s[%u]: Entering directory `%s'\n"),
    4120                 program, makelevel, starting_directory);
    4121       else
    4122         printf (_("%s[%u]: Leaving directory `%s'\n"),
    4123                 program, makelevel, starting_directory);
    4124 
    4125   /* Flush stdout to be sure this comes before any stderr output.  */
    4126   fflush (stdout);
    4127 }
  • trunk/src/kmk/maintMakefile

    r2591 r3140  
    11# Maintainer-only makefile segment.  This contains things that are relevant
    2 # only if you have the full copy of the GNU make sources from the CVS
     2# only if you have the full copy of the GNU make sources from the Git
    33# tree, not a dist copy.
     4
     5BUGLIST := [email protected]
     6
     7# These are related to my personal setup.
     8GPG_FINGERPRINT := 6338B6D4
     9
     10# SRCROOTDIR is just a handy location to keep source files in
     11SRCROOTDIR ?= $(HOME)/src
     12
     13# Where the gnulib project has been locally cloned
     14GNULIBDIR ?= $(SRCROOTDIR)/gnulib
     15
     16# Where to put the CVS checkout of the GNU web repository
     17GNUWEBDIR ?= $(SRCROOTDIR)/gnu-www
     18
     19# Where to put the CVS checkout of the GNU make web repository
     20MAKEWEBDIR ?= $(SRCROOTDIR)/make/make-web
    421
    522# We like mondo-warnings!
    623ifeq ($(KBUILD_TARGET),openbsd) # bird
    7 AM_CFLAGS += -Wall -Wshadow -Wpointer-arith -Wbad-function-cast
     24AM_CFLAGS += -Wall -Wwrite-strings -Wshadow -Wpointer-arith -Wbad-function-cast
    825else
    9 AM_CFLAGS += -Wall -Wextra -Wdeclaration-after-statement -Wshadow -Wpointer-arith -Wbad-function-cast
     26AM_CFLAGS += -Wall -Wwrite-strings -Wextra -Wdeclaration-after-statement -Wshadow -Wpointer-arith -Wbad-function-cast
    1027endif
     28
     29MAKE_MAINTAINER_MODE := -DMAKE_MAINTAINER_MODE
     30AM_CPPFLAGS += $(MAKE_MAINTAINER_MODE)
    1131
    1232# I want this one but I have to wait for the const cleanup!
     
    2343# These are built as a side-effect of the dist rule
    2444#all-am: $(TEMPLATES) $(MTEMPLATES) build.sh.in
     45
     46# Create preprocessor output files--GCC specific!
     47%.i : %.c
     48        $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) -E -dD -o $@ $<
    2549
    2650# General rule for turning a .template into a regular file.
     
    85109         done) > $@
    86110
    87 # Get rid of everything "else".
    88 #
    89 maintFILES = configure aclocal.m4 config.h.in Makefile.in stamp-h.in
    90 
    91 CVS-CLEAN-FILES +=      $(maintFILES) $(TEMPLATES) $(MTEMPLATES) NMakefile \
    92                         build.sh.in .deps .dep_segment ABOUT-NLS \
    93                         ansi2knr.*
    94 
    95 # This rule tries to clean the tree right down to how it looks when you do a
    96 # virgin CVS checkout.
    97 
    98 # This target is potentially dangerous since it removes _ANY FILE_ that
    99 # is not in CVS.  Including files you might mean to add to CVS but
    100 # haven't yet...  I only use this in subdirectories where it's unlikely
    101 # we have any new files.  Still... be careful!!
    102 
    103 cvsclean = $(PERL) -e '$$k{CVS} = 1; open(E,"< CVS/Entries") || die "CVS/Entries: $$!\n"; while (defined ($$_ = <E>)) { m%^/([^/]*)% or next; $$k{$$1} = 1; } close(E) || die "CVS/Entries: $$!\n"; opendir(D, ".") || die ".: $$!\n"; while (defined ($$_ = readdir(D))) { -f $$_ && ! exists $$k{$$_} && unlink($$_); } closedir(D) || die ".: $$!\n";'
    104 
    105 .PHONY: cvs-clean
    106 cvs-clean: maintainer-clean
    107         -rm -rf *~ $(CVS-CLEAN-FILES)
    108         -cd config && $(cvsclean)
    109         -cd po     && $(cvsclean)
    110         -cd doc    && $(cvsclean)
    111         -cd glob   && $(cvsclean)
    112 
    113 
    114 # ----------------------------------------------------------------------
    115 #
    116 # The sections below were stolen from the Makefile.maint used by fileutils,
    117 # sh-utils, textutils, CPPI, Bison, and Autoconf.
     111# Cleaning
     112
     113GIT :=  git
     114
     115# git-clean:      Clean all "ignored" files.  Leave untracked files.
     116# git-very-clean: Clean all files that aren't stored in source control.
     117
     118.PHONY: git-clean git-very-clean
     119git-clean:
     120        -$(GIT) clean -fdX
     121git-very-clean: git-clean
     122        -$(GIT) clean -fd
     123
     124
     125
     126## ---------------------- ##
     127## Generating ChangeLog.  ##
     128## ---------------------- ##
     129
     130gl2cl-date := 2013-10-10
     131gl2cl := $(GNULIBDIR)/build-aux/gitlog-to-changelog
     132
     133# Rebuild the changelog whenever a new commit is added
     134ChangeLog: .check-git-HEAD
     135        if test -f '$(gl2cl)'; then \
     136            '$(gl2cl)' --since='$(gl2cl-date)' > '$@'; \
     137        else \
     138            echo "WARNING: $(gl2cl) is not available.  No $@ generated."; \
     139        fi
     140
     141.PHONY: .check-git-HEAD
     142.check-git-HEAD:
     143        sha="`git rev-parse HEAD`"; \
     144        [ -f '$@' ] && [ "`cat '$@' 2>/dev/null`" = "$$sha" ] \
     145            || echo "$$sha" > '$@'
    118146
    119147
     
    121149## Updating files.  ##
    122150## ---------------- ##
    123 
    124 WGET = wget --passive-ftp -nv
     151RSYNC = rsync -Lrtvz
     152WGET = wget --passive-ftp -np -nv
    125153ftp-gnu = ftp://ftp.gnu.org/gnu
    126154
     
    128156                    echo $(target) is unchanged; rm -f $(target).t; \
    129157                  else \
    130                     mv $(target).t $(target); \
     158                    mv -f $(target).t $(target); \
    131159                  fi
    132160
     
    140168#   ftp://tiger.informatik.hu-berlin.de/pub/po/maint/
    141169
     170po_wget_flags = --recursive --level=1 --no-directories --no-check-certificate
    142171po_repo = http://translationproject.org/latest/$(PACKAGE)
     172po_sync = translationproject.org::tp/latest/$(PACKAGE)/
     173
    143174.PHONY: do-po-update po-update
    144175do-po-update:
     
    146177          && rm -rf "$$tmppo" \
    147178          && mkdir "$$tmppo" \
    148           && (cd "$$tmppo" \
    149                 && $(WGET) -r -l1 -nd --no-parent -A '*.po' $(po_repo)) \
    150           && cp "$$tmppo"/*.po $(top_srcdir)/po && rm -rf "$$tmppo"
     179          && $(RSYNC) $(po_sync) "$$tmppo" \
     180          && cp "$$tmppo"/*.po $(top_srcdir)/po \
     181          && rm -rf "$$tmppo"
    151182        cd po && $(MAKE) update-po
    152183        $(MAKE) po-check
     
    197228
    198229
     230# ---------------------------------- #
     231# Alternative configuration checks.  #
     232# ---------------------------------- #
     233
     234.PHONY: check-alt-config
     235check-alt-config: \
     236        checkcfg.--disable-job-server \
     237        checkcfg.--disable-load \
     238        checkcfg.--without-guile \
     239        checkcfg.CPPFLAGS^-DNO_OUTPUT_SYNC \
     240        checkcfg.CPPFLAGS^-DNO_ARCHIVES
     241
     242# Trick GNU make so it doesn't run the submake as a recursive make.
     243NR_MAKE = $(MAKE)
     244
     245# Check builds both with build.sh and with make
     246checkcfg.%: distdir
     247        @echo "Building $@ (output in checkcfg.$*.log)"
     248        @exec >'checkcfg.$*.log' 2>&1; \
     249           rm -rf $(distdir)/_build \
     250        && mkdir $(distdir)/_build \
     251        && cd $(distdir)/_build \
     252        && echo "Testing configure with $(subst ^,=,$*)" \
     253        && ../configure --srcdir=.. $(subst ^,=,$*) \
     254                $(AM_DISTCHECK_CONFIGURE_FLAGS) $(DISTCHECK_CONFIGURE_FLAGS) \
     255                CFLAGS='$(AM_CFLAGS)' \
     256        && ./build.sh \
     257        && ./make $(AM_MAKEFLAGS) check \
     258        && rm -f *.o make \
     259        && $(NR_MAKE) $(AM_MAKEFLAGS) \
     260        && ./make $(AM_MAKEFLAGS) check
     261
     262
    199263## --------------- ##
    200264## Sanity checks.  ##
    201265## --------------- ##
    202266
    203 # Checks that don't require cvs.  Run `changelog-check' last as
     267# Before we build a distribution be sure we run our local checks
     268#distdir: local-check
     269
     270.PHONY: local-check po-check changelog-check
     271
     272# Checks that don't require Git.  Run 'changelog-check' last as
    204273# previous test may reveal problems requiring new ChangeLog entries.
    205274local-check: po-check changelog-check
     
    216285
    217286# Verify that all source files using _() are listed in po/POTFILES.in.
    218 # Ignore make.h; it defines _().
     287# Ignore makeint.h; it defines _().
    219288po-check:
    220289        if test -f po/POTFILES.in; then \
    221290          grep '^[^#]' po/POTFILES.in | sort > $@-1; \
    222           $(PERL) -wn -e 'if (/\b_\(/) { $$ARGV eq "make.h" || print "$$ARGV\n" and close ARGV }' *.c *.h | sort > $@-2; \
     291          $(PERL) -wn -e 'if (/\b_\(/) { $$ARGV eq "./makeint.h" || print "$$ARGV\n" and close ARGV }' `find . -name '*.[ch]'` | sed 's,^\./,,' | sort > $@-2; \
    223292          diff -u $@-1 $@-2 || exit 1; \
    224293          rm -f $@-1 $@-2; \
    225294        fi
    226295
     296
     297## --------------- ##
     298## Generate docs.  ##
     299## --------------- ##
     300
     301.PHONY: update-makeweb gendocs
     302
     303CVS = cvs
     304
     305makeweb-repo = $(USER)@cvs.sv.gnu.org:/web/make
     306gnuweb-repo = :pserver:[email protected]:/web/www
     307gnuweb-dir = www/server/standards
     308
     309# Get the GNU make web page boilerplate etc.
     310update-makeweb:
     311        [ -d '$(MAKEWEBDIR)' ] || mkdir -p '$(MAKEWEBDIR)'
     312        [ -d '$(MAKEWEBDIR)'/CVS ] \
     313            && { cd '$(MAKEWEBDIR)' && $(CVS) update; } \
     314            || { mkdir -p '$(dir $(MAKEWEBDIR))' && cd '$(dir $(MAKEWEBDIR))' \
     315                 && $(CVS) -d $(makeweb-repo) co -d '$(notdir $(MAKEWEBDIR))' make; }
     316
     317# Get the GNU web page boilerplate etc.
     318update-gnuweb:
     319        [ -d '$(GNUWEBDIR)' ] || mkdir -p '$(GNUWEBDIR)'
     320        [ -d '$(GNUWEBDIR)/$(gnuweb-dir)'/CVS ] \
     321            && { cd '$(GNUWEBDIR)/$(gnuweb-dir)' && $(CVS) update; } \
     322            || { cd '$(GNUWEBDIR)' && $(CVS) -d $(gnuweb-repo) co '$(gnuweb-dir)'; }
     323
     324gendocs: update-gnuweb update-makeweb
     325        cp $(GNULIBDIR)/doc/gendocs_template doc
     326        cd doc \
     327          && rm -rf doc/manual \
     328          && $(GNULIBDIR)/build-aux/gendocs.sh --email '$(BUGLIST)' \
     329                make 'GNU Make Manual'
     330        find '$(MAKEWEBDIR)'/manual \( -name CVS -prune \) -o \( -name '[!.]*' -type f -exec rm -f '{}' \; \)
     331        cp -r doc/manual '$(MAKEWEBDIR)'
     332        @echo 'Status of $(MAKEWEBDIR) repo:' && cd '$(MAKEWEBDIR)' \
     333            && cvs -q -n update | grep -v '^M ' \
     334            && echo '- cvs add <new files>' \
     335            && echo '- cvs remove <deleted files>' \
     336            && echo '- cvs commit' \
     337            && echo '- cvs tag make-$(subst .,-,$(VERSION))'
     338
     339## ------------------------- ##
     340## Make release targets.     ##
     341## ------------------------- ##
     342
     343.PHONY: tag-release
     344tag-release:
     345        case '$(VERSION)' in \
     346            (*.*.9*) message=" candidate" ;; \
     347            (*)      message= ;; \
     348        esac; \
     349        $(GIT) tag -m "GNU Make release$$message $(VERSION)" -u '$(GPG_FINGERPRINT)' '$(VERSION)'
     350
    227351## ------------------------- ##
    228352## GNU FTP upload artifacts. ##
     
    234358
    235359GPG = gpg
    236 GPGFLAGS = -u 6338B6D4
     360GPGFLAGS = -u $(GPG_FINGERPRINT)
    237361
    238362DIST_ARCHIVES_SIG = $(addsuffix .sig,$(DIST_ARCHIVES))
     
    271395
    272396
    273 # Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    274 # 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     397# Rebuild Makefile.in if this file is modifed.
     398Makefile.in: maintMakefile
     399
     400# Copyright (C) 1997-2016 Free Software Foundation, Inc.
    275401# This file is part of GNU Make.
    276402#
  • trunk/src/kmk/make.1

    r2591 r3140  
    1 .TH MAKE 1 "22 August 1989" "GNU" "LOCAL USER COMMANDS"
     1.TH MAKE 1 "28 February 2016" "GNU" "User Commands"
    22.SH NAME
    33make \- GNU make utility to maintain groups of programs
    44.SH SYNOPSIS
    5 .B "make "
    6 [
    7 .B \-f
    8 .I makefile
    9 ] [ options ] ... [ targets ] ...
    10 .SH WARNING
    11 This man page is an extract of the documentation of GNU
    12 .IR make .
    13 It is updated only occasionally, because the GNU project does not use nroff.
    14 For complete, current documentation, refer to the Info file
    15 .B make.info
    16 which is made from the Texinfo source file
    17 .BR make.texi .
     5.B make
     6[\fIOPTION\fR]... [\fITARGET\fR]...
    187.SH DESCRIPTION
    198.LP
    20 The purpose of the
     9The
    2110.I make
    22 utility is to determine automatically which
    23 pieces of a large program need to be recompiled, and issue the commands to
    24 recompile them.
    25 The manual describes the GNU implementation of
    26 .IR make ,
    27 which was written by Richard Stallman and Roland McGrath, and is
    28 currently maintained by Paul Smith.
    29 Our examples show C programs, since they are most common, but you can use
    30 .I make
    31 with any programming language whose compiler can be run with a
    32 shell command.
     11utility will determine automatically which pieces of a large program need to
     12be recompiled, and issue the commands to recompile them.  The manual describes
     13the GNU implementation of
     14.BR make ,
     15which was written by Richard Stallman and Roland McGrath, and is currently
     16maintained by Paul Smith.  Our examples show C programs, since they are very
     17common, but you can use
     18.B make
     19with any programming language whose compiler can be run with a shell command.
    3320In fact,
    34 .I make
    35 is not limited to programs.
    36 You can use it to describe any task where some files must be
    37 updated automatically from others whenever the others change.
     21.B make
     22is not limited to programs.  You can use it to describe any task where some
     23files must be updated automatically from others whenever the others change.
    3824.LP
    3925To prepare to use
    40 .IR make ,
     26.BR make ,
    4127you must write a file called the
    4228.I makefile
    43 that describes the relationships among files in your program, and the
    44 states the commands for updating each file.
    45 In a program, typically the executable file is updated from object
    46 files, which are in turn made by compiling source files.
     29that describes the relationships among files in your program, and the states
     30the commands for updating each file.  In a program, typically the executable
     31file is updated from object files, which are in turn made by compiling source
     32files.
    4733.LP
    4834Once a suitable makefile exists, each time you change some source files,
     
    5541suffices to perform all necessary recompilations.
    5642The
    57 .I make
    58 program uses the makefile data base and the last-modification times
    59 of the files to decide which of the files need to be updated.
    60 For each of those files, it issues the commands recorded in the data base.
    61 .LP
    62 .I make
     43.B make
     44program uses the makefile description and the last-modification times of the
     45files to decide which of the files need to be updated.  For each of those
     46files, it issues the commands recorded in the makefile.
     47.LP
     48.B make
    6349executes commands in the
    6450.I makefile
    65 to update
    66 one or more target
     51to update one or more target
    6752.IR names ,
    6853where
     
    7257.B \-f
    7358option is present,
    74 .I make
     59.B make
    7560will look for the makefiles
    7661.IR GNUmakefile ,
     
    9176The first name checked,
    9277.IR GNUmakefile ,
    93 is not recommended for most makefiles.
    94 You should use this name if you have a makefile that is specific to GNU
    95 .IR make ,
     78is not recommended for most makefiles.  You should use this name if you have a
     79makefile that is specific to GNU
     80.BR make ,
    9681and will not be understood by other versions of
    97 .IR make .
     82.BR make .
    9883If
    9984.I makefile
    100 is `\-', the standard input is read.
    101 .LP
    102 .I make
     85is '\-', the standard input is read.
     86.LP
     87.B make
    10388updates a target if it depends on prerequisite files
    10489that have been modified since the target was last modified,
     
    10792.sp 1
    10893.TP 0.5i
    109 .BR \-b , " \-m"
     94\fB\-b\fR, \fB\-m\fR
    11095These options are ignored for compatibility with other versions of
    111 .IR make .
    112 .TP 0.5i
    113 .BR \-B , " \-\-always\-make"
     96.BR make .
     97.TP 0.5i
     98\fB\-B\fR, \fB\-\-always\-make\fR
    11499Unconditionally make all targets.
    115100.TP 0.5i
     
    127112.BR "\-C " /etc.
    128113This is typically used with recursive invocations of
    129 .IR make .
     114.BR make .
    130115.TP 0.5i
    131116.B \-d
     
    135120which files actually need to be remade, which implicit rules are
    136121considered and which are applied---everything interesting about how
    137 .I make
     122.B make
    138123decides what to do.
    139124.TP 0.5i
     
    159144for details on invocation of commands, and
    160145.I m
    161 for debugging while remaking makefiles.
    162 .TP 0.5i
    163 .BR \-e , " \-\-environment\-overrides"
     146for debugging while remaking makefiles.  Use
     147.I n
     148to disable all previous debugging flags.
     149.TP 0.5i
     150\fB\-e\fR, \fB\-\-environment\-overrides\fR
    164151Give variables taken from the environment precedence
    165152over variables from makefiles.
     
    170157as a makefile.
    171158.TP 0.5i
    172 .BR \-i , " \-\-ignore\-errors"
     159\fB\-i\fR, \fB\-\-ignore\-errors\fR
    173160Ignore all errors in commands executed to remake files.
    174161.TP 0.5i
     
    182169searched in the order specified.
    183170Unlike the arguments to other flags of
    184 .IR make ,
     171.BR make ,
    185172directories given with
    186173.B \-I
     
    188175.BI \-I dir
    189176is allowed, as well as
    190 .BI "\-I " dir.
     177.B \-I
     178.IR dir .
    191179This syntax is allowed for compatibility with the C
    192180preprocessor's
     
    204192.B \-j
    205193option is given without an argument,
    206 .IR make
     194.BR make
    207195will not limit the number of jobs that can run simultaneously.
    208196.TP 0.5i
    209 .BR \-k , " \-\-keep\-going"
     197\fB\-k\fR, \fB\-\-keep\-going\fR
    210198Continue as much as possible after an error.
    211199While the target that failed, and those that depend on it, cannot
     
    220208With no argument, removes a previous load limit.
    221209.TP 0.5i
    222 .BR \-L , " \-\-check\-symlink\-times"
     210\fB\-L\fR, \fB\-\-check\-symlink\-times\fR
    223211Use the latest mtime between symlinks and target.
    224212.TP 0.5i
    225 .BR \-n , " \-\-just\-print" , " \-\-dry\-run" , " \-\-recon"
     213\fB\-n\fR, \fB\-\-just\-print\fR, \fB\-\-dry\-run\fR, \fB\-\-recon\fR
    226214Print the commands that would be executed, but do not execute them (except in
    227215certain circumstances).
     
    235223Essentially the file is treated as very old and its rules are ignored.
    236224.TP 0.5i
    237 .BR \-p , " \-\-print\-data\-base"
     225\fB\-O\fR[\fItype\fR], \fB\-\-output\-sync\fR[=\fItype\fR]
     226When running multiple jobs in parallel with \fB-j\fR, ensure the output of
     227each job is collected together rather than interspersed with output from
     228other jobs.  If
     229.I type
     230is not specified or is
     231.B target
     232the output from the entire recipe for each target is grouped together.  If
     233.I type
     234is
     235.B line
     236the output from each command line within a recipe is grouped together.
     237If
     238.I type
     239is
     240.B recurse
     241output from an entire recursive make is grouped together.  If
     242.I type
     243is
     244.B none
     245output synchronization is disabled.
     246.TP 0.5i
     247\fB\-p\fR, \fB\-\-print\-data\-base\fR
    238248Print the data base (rules and variable values) that results from
    239249reading the makefiles; then execute as usual or as otherwise
     
    243253switch (see below).
    244254To print the data base without trying to remake any files, use
    245 .B make
    246 .B \-p
    247 .BI \-f /dev/null.
    248 .TP 0.5i
    249 .BR \-q , " \-\-question"
     255.IR "make \-p \-f/dev/null" .
     256.TP 0.5i
     257\fB\-q\fR, \fB\-\-question\fR
    250258``Question mode''.
    251259Do not run any commands, or print anything; just return an exit status
     
    253261otherwise.
    254262.TP 0.5i
    255 .BR \-r , " \-\-no\-builtin\-rules"
     263\fB\-r\fR, \fB\-\-no\-builtin\-rules\fR
    256264Eliminate use of the built\-in implicit rules.
    257265Also clear out the default list of suffixes for suffix rules.
    258266.TP 0.5i
    259 .BR \-R , " \-\-no\-builtin\-variables"
     267\fB\-R\fR, \fB\-\-no\-builtin\-variables\fR
    260268Don't define any built\-in variables.
    261269.TP 0.5i
    262 .BR \-s , " \-\-silent" , " \-\-quiet"
     270\fB\-s\fR, \fB\-\-silent\fR, \fB\-\-quiet\fR
    263271Silent operation; do not print the commands as they are executed.
    264272.TP 0.5i
    265 .BR \-S , " \-\-no\-keep\-going" , " \-\-stop"
     273\fB\-S\fR, \fB\-\-no\-keep\-going\fR, \fB\-\-stop\fR
    266274Cancel the effect of the
    267275.B \-k
    268276option.
    269277This is never necessary except in a recursive
    270 .I make
     278.B make
    271279where
    272280.B \-k
    273281might be inherited from the top-level
    274 .I make
     282.B make
    275283via MAKEFLAGS or if you set
    276284.B \-k
    277285in MAKEFLAGS in your environment.
    278286.TP 0.5i
    279 .BR \-t , " \-\-touch"
     287\fB\-t\fR, \fB\-\-touch\fR
    280288Touch files (mark them up to date without really changing them)
    281289instead of running their commands.
    282290This is used to pretend that the commands were done, in order to fool
    283291future invocations of
    284 .IR make .
    285 .TP 0.5i
    286 .BR \-v , " \-\-version"
     292.BR make .
     293.TP 0.5i
     294.B \-\-trace
     295Information about the disposition of each target is printed (why the target is
     296being rebuilt and what commands are run to rebuild it).
     297.TP 0.5i
     298\fB\-v\fR, \fB\-\-version\fR
    287299Print the version of the
    288 .I make
     300.B make
    289301program plus a copyright, a list of authors and a notice that there
    290302is no warranty.
    291303.TP 0.5i
    292 .BR \-w , " \-\-print\-directory"
     304\fB\-w\fR, \fB\-\-print\-directory\fR
    293305Print a message containing the working directory
    294306before and after other processing.
    295307This may be useful for tracking down errors from complicated nests of
    296308recursive
    297 .I make
     309.B make
    298310commands.
    299311.TP 0.5i
     
    315327.I touch
    316328command on the given file before running
    317 .IR make ,
     329.BR make ,
    318330except that the modification time is changed only in the imagination of
    319 .IR make .
     331.BR make .
    320332.TP 0.5i
    321333.B \-\-warn\-undefined\-variables
     
    323335.SH "EXIT STATUS"
    324336GNU
    325 .I make
     337.B make
    326338exits with a status of zero if all makefiles were successfully parsed
    327339and no targets that were built failed.  A status of one will be returned
     
    329341.B \-q
    330342flag was used and
    331 .I make
     343.B make
    332344determines that a target needs to be rebuilt.  A status of two will be
    333345returned if any errors were encountered.
    334346.SH "SEE ALSO"
    335 .I "The GNU Make Manual"
     347The full documentation for
     348.B make
     349is maintained as a Texinfo manual.  If the
     350.B info
     351and
     352.B make
     353programs are properly installed at your site, the command
     354.IP
     355.B info make
     356.PP
     357should give you access to the complete manual.
    336358.SH BUGS
    337 See the chapter `Problems and Bugs' in
     359See the chapter ``Problems and Bugs'' in
    338360.IR "The GNU Make Manual" .
    339361.SH AUTHOR
    340362This manual page contributed by Dennis Morse of Stanford University.
    341 It has been reworked by Roland McGrath.  Further updates contributed by
    342 Mike Frysinger.
     363Further updates contributed by Mike Frysinger.  It has been reworked by Roland
     364McGrath.  Maintained by Paul Smith.
    343365.SH "COPYRIGHT"
    344 Copyright (C) 1992, 1993, 1996, 1999, 2007 Free Software Foundation, Inc.
    345 This file is part of GNU
    346 .IR make .
     366Copyright \(co 1992-1993, 1996-2016 Free Software Foundation, Inc.
     367This file is part of
     368.IR "GNU make" .
    347369.LP
    348370GNU Make is free software; you can redistribute it and/or modify it under the
  • trunk/src/kmk/make.lnk

    r503 r3140  
    1 FROM LIB:cres.o "commands.o"+"job.o"+"dir.o"+"file.o"+"misc.o"+"main.o"+"read.o"+"remake.o"+"rule.o"+"implicit.o"+"default.o"+"variable.o"+"expand.o"+"function.o"+"vpath.o"+"version.o"+"ar.o"+"arscan.o"+"signame.o"+"remote-stub.o"+"getopt.o"+"getopt1.o"+"alloca.o"+"amiga.o"+"hash.o"+"strcache.o"
     1FROM LIB:cres.o "commands.o"+"job.o"+"dir.o"+"file.o"+"misc.o"+"main.o"+"read.o"+"remake.o"+"rule.o"+"implicit.o"+"default.o"+"variable.o"+"expand.o"+"function.o"+"vpath.o"+"version.o"+"ar.o"+"arscan.o"+"signame.o"+"remote-stub.o"+"getopt.o"+"getopt1.o"+"alloca.o"+"amiga.o"+"hash.o"+"strcache.o"+"output.o"
    22TO "make.new"
    33LIB glob/glob.lib LIB:sc.lib LIB:amiga.lib
  • trunk/src/kmk/make_msvc_net2003.vcproj

    r503 r3140  
    155155                                RelativePath=".\getopt1.c">
    156156                        </File>
     157
     158                        <File
     159                                RelativePath=".\guile.c">
     160                        </File>
     161
    157162                        <File
    158163                                RelativePath=".\hash.c">
     
    166171                        <File
    167172                                RelativePath=".\job.c">
     173                        </File>
     174                        <File
     175                                RelativePath=".\load.c">
     176                        </File>
     177                        <File
     178                                RelativePath=".\output.c">
    168179                        </File>
    169180                        <File
     
    202213                                <File
    203214                                        RelativePath=".\w32\compat\dirent.c">
     215                                </File>
     216                                <File
     217                                        RelativePath=".\w32\compat\posixfcn.c">
    204218                                </File>
    205219                                <File
     
    222236                                </File>
    223237                                <File
     238                                        RelativePath=".\w32\w32os.c">
     239                                </File>
     240                                <File
    224241                                        RelativePath=".\w32\subproc\sub_proc.c">
    225242                                </File>
     
    265282                        </File>
    266283                        <File
     284                                RelativePath=".\gmk-default.h">
     285                        </File>
     286                        <File
    267287                                RelativePath=".\hash.h">
    268288                        </File>
     
    271291                        </File>
    272292                        <File
    273                                 RelativePath=".\make.h">
     293                                RelativePath=".\output.h">
     294                        </File>
     295                        <File
     296                                RelativePath=".\makeint.h">
    274297                        </File>
    275298                        <File
  • trunk/src/kmk/makefile.com

    r2591 r3140  
    22$! Makefile.com - builds GNU Make for VMS
    33$!
    4 $! P1 is non-empty if you want to link with the VAXCRTL library instead
    5 $!    of the shareable executable
     4$! P1 = LIST will provide compiler listings.
    65$! P2 = DEBUG will build an image with debug information
    76$! P3 = WALL will enable all warning messages (some are suppressed since
     
    5150$ endif
    5251$!
     52$!
     53$ if (p1 .eqs. "LIST")
     54$ then
     55$   ccopt = ccopt + "/list/show=(expan,inclu)"
     56$ endif
     57$!
    5358$! Should we build a debug image
    5459$!
     
    6873$ endif
    6974$ filelist = "alloca ar arscan commands default dir expand file function " + -
    70              "hash implicit job main misc read remake remote-stub rule " + -
    71              "signame variable version vmsfunctions vmsify vpath " + -
    72              "[.glob]glob [.glob]fnmatch getopt1 getopt strcache"
     75             "guile hash implicit job load main misc read remake " + -
     76             "remote-stub rule output signame variable version " + -
     77             "vmsfunctions vmsify vpath vms_progname vms_exit " + -
     78             "vms_export_symbol [.glob]glob [.glob]fnmatch getopt1 " + -
     79             "getopt strcache"
     80$!
    7381$ copy config.h-vms config.h
    7482$ n=0
     
    7886$ if cfile .eqs. " " then goto linkit
    7987$ write sys$output "Compiling ''cfile'..."
    80 $ call compileit 'cfile' 'p1'
     88$ call compileit 'cfile'
    8189$ n = n + 1
    8290$ goto loop
    8391$ linkit:
    8492$ close optf
    85 $ if p1 .nes. "" then goto link_using_library
    8693$ link/exe=make make.opt/opt'lopt
    8794$ goto cleanup
    88 $
    89 $ link_using_library:
    90 $ link/exe=make make.opt/opt,sys$library:vaxcrtl/lib'lopt
    9195$
    9296$ cleanup:
     
    129133$ compileit : subroutine
    130134$ ploc = f$locate("]",p1)
    131 $ filnam = p1
    132 $ if ploc .lt. f$length(p1) then filnam=f$extract(ploc+1,100,p1)
    133 $ write optf "''filnam'"
    134 $ cc'ccopt'/include=([],[.glob]) -
    135   /define=("allocated_variable_expand_for_file=alloc_var_expand_for_file","unlink=remove","HAVE_CONFIG_H","VMS") -
     135$! filnam = p1
     136$ if ploc .lt. f$length(p1)
     137$ then
     138$   objdir = f$extract(0, ploc+1, p1)
     139$   write optf p1
     140$ else
     141$   objdir := []
     142$   write optf objdir+p1
     143$ endif
     144$ cc'ccopt'/nested=none/include=([],[.glob])/obj='objdir' -
     145  /define=("allocated_variable_expand_for_file=alloc_var_expand_for_file",-
     146  "unlink=remove","HAVE_CONFIG_H","VMS") -
    136147  'p1'
    137148$ exit
     
    139150$!
    140151$!-----------------------------------------------------------------------------
    141 $!Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    142 $!2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     152$!Copyright (C) 1996-2016 Free Software Foundation, Inc.
    143153$!This file is part of GNU Make.
    144154$!
  • trunk/src/kmk/makefile.vms

    r2591 r3140  
    11# -*-Makefile-*- to build GNU make on VMS
    22#
    3 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    4 # 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     3# Copyright (C) 1996-2016 Free Software Foundation, Inc.
    54# This file is part of GNU Make.
    65#
     
    2221# Modified for version 3.78.1 by [email protected].
    2322# Modified for version 3.80 by [email protected]
    24 # Modified for version 3.81 by Hartmut Becker
     23# Modified for versions 3.81, 3.99.90 by Hartmut Becker
    2524
    2625CC = cc
     
    3433
    3534ifeq ($(CC),cc)
    36 CFLAGS = $(defines) /include=([],[.glob])/prefix=(all,except=(glob,globfree))/standard=relaxed/warn=(disable=questcompare)
     35cinclude = /nested=none/include=([],[.glob])
     36cprefix = /prefix=(all,except=(glob,globfree))
     37cwarn = /standard=relaxed/warn=(disable=questcompare)
     38CFLAGS = $(defines) $(cinclude)$(cprefix)$(cwarn)
    3739else
    38 CFLAGS = $(defines) /include=([],[.glob])
     40CFLAGS = $(defines) $(cinclude)
    3941endif
    4042#LDFLAGS = /deb
     
    8385glob = ,[.glob]glob.obj,[.glob]fnmatch.obj
    8486getopt = ,getopt.obj,getopt1.obj
    85 # Directory to install `make' in.
     87# Directory to install 'make' in.
    8688bindir = []
    8789# Directory to install the man page in.
     
    9092manext = 1
    9193
    92 objs = commands.obj,job.obj,dir.obj,file.obj,misc.obj,hash.obj,\
    93        main.obj,read.obj,remake.obj,rule.obj,implicit.obj,\
     94guile = ,guile.obj
     95
     96objs = commands.obj,job.obj,output.obj,dir.obj,file.obj,misc.obj,hash.obj,\
     97       load.obj,main.obj,read.obj,remake.obj,rule.obj,implicit.obj,\
    9498       default.obj,variable.obj,expand.obj,function.obj,strcache.obj,\
    95        vpath.obj,version.obj$(ARCHIVES)$(ALLOCA)$(extras)$(getopt)$(glob)
    96 srcs = commands.c job.c dir.c file.c misc.c  hash.c \
    97         main.c read.c remake.c rule.c implicit.c \
     99       vpath.obj,version.obj,vms_progname.obj,vms_exit.obj,\
     100       vms_export_symbol.obj$(guile)$(ARCHIVES)$(extras)$(getopt)$(glob)
     101
     102srcs = commands.c job.c output.c dir.c file.c misc.c guile.c hash.c \
     103        load.c main.c read.c remake.c rule.c implicit.c \
    98104        default.c variable.c expand.c function.c strcache.c \
    99         vpath.c version.c vmsfunctions.c vmsify.c $(ARCHIVES_SRC) $(ALLOCASRC) \
    100         commands.h dep.h filedef.h job.h make.h rule.h variable.h
     105        vpath.c version.c vmsfunctions.c vmsify.c vms_progname.c vms_exit.c \
     106        vms_export_symbol.c $(ARCHIVES_SRC) $(ALLOCASRC) \
     107        commands.h dep.h filedef.h job.h output.h makeint.h rule.h variable.h
    101108
    102109
     
    112119.PHONY: clean realclean
    113120clean:
    114         $$ purge [...]
     121        -purge [...]
    115122        -$(RM) make.exe;,*.obj;
    116123        -$(RM) [.glob]*.obj;
    117124
    118 # Automatically generated dependencies.
    119 commands.obj: commands.c make.h dep.h commands.h filedef.h variable.h job.h
    120 job.obj: job.c vmsjobs.c make.h commands.h job.h filedef.h variable.h
    121 dir.obj: dir.c make.h
    122 file.obj: file.c make.h commands.h dep.h filedef.h variable.h
    123 misc.obj: misc.c make.h dep.h
    124 hash.obj: hash.c make.h hash.h
    125 strcache.obj: strcache.c make.h hash.h
    126 main.obj: main.c make.h commands.h dep.h filedef.h variable.h job.h
    127 read.obj: read.c make.h commands.h dep.h filedef.h variable.h
    128 remake.obj: remake.c make.h commands.h job.h dep.h filedef.h
    129 rule.obj: rule.c make.h commands.h dep.h filedef.h variable.h rule.h
    130 implicit.obj: implicit.c make.h rule.h dep.h filedef.h
    131 default.obj: default.c make.h rule.h dep.h filedef.h commands.h variable.h
    132 variable.obj: variable.c make.h commands.h variable.h dep.h filedef.h
    133 expand.obj: expand.c make.h commands.h filedef.h variable.h
    134 function.obj: function.c make.h variable.h dep.h commands.h job.h
    135 vpath.obj: vpath.c make.h filedef.h variable.h
     125ar.obj: ar.c makeint.h config.h gnumake.h gettext.h filedef.h hash.h dep.h \
     126     [.glob]fnmatch.h
     127arscan.obj: arscan.c makeint.h config.h gnumake.h gettext.h
     128commands.obj: commands.c makeint.h config.h gnumake.h gettext.h filedef.h \
     129     hash.h dep.h variable.h job.h output.h commands.h
     130default.obj: default.c makeint.h config.h gnumake.h gettext.h filedef.h \
     131     hash.h variable.h rule.h dep.h job.h output.h commands.h
     132dir.obj: dir.c makeint.h config.h gnumake.h gettext.h hash.h filedef.h \
     133     dep.h [.glob]glob.h
     134expand.obj: expand.c makeint.h config.h gnumake.h gettext.h filedef.h \
     135     hash.h job.h output.h commands.h variable.h rule.h
     136file.obj: file.c makeint.h config.h gnumake.h gettext.h filedef.h hash.h \
     137     dep.h job.h output.h commands.h variable.h debug.h
     138[.glob]fnmatch.obj: [.glob]fnmatch.c config.h [.glob]fnmatch.h
     139function.obj: function.c makeint.h config.h gnumake.h gettext.h filedef.h \
     140     hash.h variable.h dep.h job.h output.h commands.h debug.h
     141getopt.obj: getopt.c config.h gettext.h getopt.h
     142getopt1.obj: getopt1.c config.h getopt.h
     143[.glob]glob.obj: [.glob]glob.c config.h [.glob]fnmatch.h [.glob]glob.h
     144guile.obj: guile.c makeint.h config.h gnumake.h gettext.h
     145hash.obj: hash.c makeint.h config.h gnumake.h gettext.h hash.h
     146implicit.obj: implicit.c makeint.h config.h gnumake.h gettext.h filedef.h \
     147     hash.h rule.h dep.h debug.h variable.h job.h output.h commands.h
     148job.obj: job.c makeint.h config.h gnumake.h gettext.h job.h output.h debug.h \
     149     filedef.h hash.h commands.h variable.h debug.h vmsjobs.c
     150load.obj: load.c makeint.h config.h gnumake.h gettext.h
     151main.obj: main.c makeint.h config.h gnumake.h gettext.h filedef.h hash.h \
     152     dep.h variable.h job.h output.h commands.h rule.h debug.h getopt.h
     153misc.obj: misc.c makeint.h config.h gnumake.h gettext.h filedef.h hash.h \
     154     dep.h debug.h
     155output.obj: output.c makeint.h config.h gnumake.h gettext.h job.h output.h
     156read.obj: read.c makeint.h config.h gnumake.h gettext.h [.glob]glob.h \
     157     filedef.h hash.h dep.h job.h output.h commands.h variable.h rule.h \
     158     debug.h
     159remake.obj: remake.c makeint.h config.h gnumake.h gettext.h filedef.h \
     160     hash.h job.h output.h commands.h dep.h variable.h debug.h
     161remote-stub.obj: remote-stub.c makeint.h config.h gnumake.h gettext.h \
     162     filedef.h hash.h job.h output.h commands.h
     163rule.obj: rule.c makeint.h config.h gnumake.h gettext.h filedef.h hash.h \
     164     dep.h job.h output.h commands.h variable.h rule.h
     165signame.obj: signame.c makeint.h config.h gnumake.h gettext.h
     166strcache.obj: strcache.c makeint.h config.h gnumake.h gettext.h hash.h
     167variable.obj: variable.c makeint.h config.h gnumake.h gettext.h filedef.h \
     168     hash.h dep.h job.h output.h commands.h variable.h rule.h
    136169version.obj: version.c config.h
    137 arscan.obj: arscan.c
    138 ar.obj: ar.c make.h filedef.h
    139 signame.obj: signame.c
    140 remote-stub.obj: remote-stub.c
    141 [.glob]glob.obj: [.glob]glob.c
    142 [.glob]fnmatch.obj: [.glob]fnmatch.c
    143 getopt.obj: getopt.c
    144 getopt1.obj: getopt1.c
    145 vmsfunctions.obj: vmsfunctions.c make.h vmsdir.h
    146 vmsify.obj: vmsify.c make.h
     170vmsfunctions.obj: vmsfunctions.c makeint.h config.h gnumake.h gettext.h \
     171     debug.h job.h output.h vmsdir.h
     172vmsify.obj: vmsify.c
     173vpath.obj: vpath.c makeint.h config.h gnumake.h gettext.h filedef.h hash.h \
     174     variable.h
     175vms_progname.obj: vms_progname.c
     176vms_exit.obj: vms_exit.c
     177vms_export_symbol.obj: vms_export_symbol.c
    147178
    148179config.h: config.h-vms
  • trunk/src/kmk/makeint.h

    r3139 r3140  
    11/* Miscellaneous global declarations and portability cruft for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1917/* We use <config.h> instead of "config.h" so that a compilation
    2018   using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
    21    (which it would do because make.h was found in $srcdir).  */
     19   (which it would do because makeint.h was found in $srcdir).  */
    2220#include <config.h>
    2321#undef  HAVE_CONFIG_H
    2422#define HAVE_CONFIG_H 1
     23
     24#include <k/kDefs.h> /* bird */
    2525
    2626/* Specify we want GNU source code.  This must be defined before any
     
    4444#endif
    4545
     46/* Disable assert() unless we're a maintainer.
     47   Some asserts are compute-intensive.  */
     48#ifndef MAKE_MAINTAINER_MODE
     49# define NDEBUG 1
     50#endif
     51
     52/* Include the externally-visible content.
     53   Be sure to use the local one, and not one installed on the system.
     54   Define GMK_BUILDING_MAKE for proper selection of dllexport/dllimport
     55   declarations for MS-Windows.  */
     56#ifdef WINDOWS32
     57# define GMK_BUILDING_MAKE
     58#endif
     59#include "gnumake.h"
    4660
    4761#ifdef  CRAY
     
    6175#include <stdio.h>
    6276#include <ctype.h>
     77
    6378#ifdef HAVE_SYS_TIMEB_H
    64 /* SCO 3.2 "devsys 4.2" has a prototype for `ftime' in <time.h> that bombs
    65    unless <sys/timeb.h> has been included first.  Does every system have a
    66    <sys/timeb.h>?  If any does not, configure should check for it.  */
     79/* SCO 3.2 "devsys 4.2" has a prototype for 'ftime' in <time.h> that bombs
     80   unless <sys/timeb.h> has been included first.  */
    6781# include <sys/timeb.h>
    6882#endif
    69 
    7083#if TIME_WITH_SYS_TIME
    7184# include <sys/time.h>
     
    8598#endif
    8699
    87 #ifndef isblank
    88 # define isblank(c)     ((c) == ' ' || (c) == '\t')
     100#ifdef __VMS
     101/* In strict ANSI mode, VMS compilers should not be defining the
     102   VMS macro.  Define it here instead of a bulk edit for the correct code.
     103 */
     104# ifndef VMS
     105#  define VMS
     106# endif
    89107#endif
    90108
     
    92110# include <unistd.h>
    93111/* Ultrix's unistd.h always defines _POSIX_VERSION, but you only get
    94    POSIX.1 behavior with `cc -YPOSIX', which predefines POSIX itself!  */
     112   POSIX.1 behavior with 'cc -YPOSIX', which predefines POSIX itself!  */
    95113# if defined (_POSIX_VERSION) && !defined (ultrix) && !defined (VMS)
    96114#  define POSIX 1
     
    117135#ifndef HAVE_SA_RESTART
    118136# define SA_RESTART 0
     137#endif
     138
     139#ifdef HAVE_VFORK_H
     140# include <vfork.h>
    119141#endif
    120142
     
    187209
    188210#ifdef KMK
    189 # include <ctype.h>
    190 # if 1 /* See if this speeds things up (Windows is doing this anyway, so,
     211/** @todo measure performance diff here!   */
     212# if 0 /* See if this speeds things up (Windows is doing this anyway, so,
    191213          we might as well try be consistent in speed + features).  */
    192 #  if 1
    193 #   define MY_IS_BLANK(ch)          ((ch) == ' ' || (ch) == '\t')
    194 #   define MY_IS_BLANK_OR_EOS(ch)   ((ch) == ' ' || (ch) == '\t' || (ch) == '\0')
    195 #  else
    196 #   define MY_IS_BLANK(ch)          (((ch) == ' ') | ((ch) == '\t'))
    197 #   define MY_IS_BLANK_OR_EOS(ch)   (((ch) == ' ') | ((ch) == '\t') | ((ch) == '\0'))
    198 #  endif
    199 #  undef isblank
    200 #  define isblank(ch)               MY_IS_BLANK(ch)
    201 # else
    202 #  define MY_IS_BLANK(ch)           isblank ((unsigned char)(ch))
    203 #  define MY_IS_BLANK_OR_EOS(ch)    (isblank ((unsigned char)(ch)) || (ch) == '\0')
     214#  define MY_IS_BLANK(ch)           ((ch) == ' ' || (ch) == '\t')
     215#  define MY_IS_BLANK_OR_EOS(ch)    ((ch) == ' ' || (ch) == '\t' || (ch) == '\0')
     216# else
     217#  define MY_IS_BLANK(ch)           ISBLANK ((ch))
     218#  define MY_IS_BLANK_OR_EOS(ch)    (ISBLANK ((ch)) || (ch) == '\0')
    204219# endif
    205220#endif
     
    277292#endif
    278293
    279 /* Nonzero if the integer type T is signed.  */
    280 #define INTEGER_TYPE_SIGNED(t) ((t) -1 < 0)
     294#ifndef USHRT_MAX
     295# define USHRT_MAX 65535
     296#endif
     297
     298/* Nonzero if the integer type T is signed.
     299   Use <= to avoid GCC warnings about always-false expressions.  */
     300#define INTEGER_TYPE_SIGNED(t) ((t) -1 <= 0)
    281301
    282302/* The minimum and maximum values for the integer type T.
     
    307327
    308328#ifdef VMS
     329# include <fcntl.h>
    309330# include <types.h>
    310331# include <unixlib.h>
     
    313334/* Needed to use alloca on VMS.  */
    314335# include <builtins.h>
     336
     337extern int vms_use_mcr_command;
     338extern int vms_always_use_cmd_file;
     339extern int vms_gnv_shell;
     340extern int vms_comma_separator;
     341extern int vms_legacy_behavior;
     342extern int vms_unix_simulation;
    315343#endif
    316344
     
    320348#  define __attribute__(x)
    321349# endif
    322 /* The __-protected variants of `format' and `printf' attributes
     350/* The __-protected variants of 'format' and 'printf' attributes
    323351   are accepted by gcc versions 2.6.4 (effectively 2.7) and later.  */
    324352# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
     
    378406# include <inttypes.h>
    379407#endif
     408#if HAVE_STDINT_H
     409# include <stdint.h>
     410#endif
    380411#define FILE_TIMESTAMP uintmax_t
    381412
     
    391422   POSIX 1003.2-1992 section 2.5.2.1 page 50 lines 1556-1558 says that
    392423   only '0' through '9' are digits.  Prefer ISDIGIT to isdigit() unless
    393    it's important to use the locale's definition of `digit' even when the
     424   it's important to use the locale's definition of 'digit' even when the
    394425   host does not conform to POSIX.  */
    395426#define ISDIGIT(c) ((unsigned) (c) - '0' <= 9)
     
    414445#define strneq(a, b, l) (strncmp ((a), (b), (l)) == 0)
    415446
    416 #if (defined(__GNUC__) || defined(ENUM_BITFIELDS)) && !defined(NO_ENUM_BITFIELDS)
     447#if (defined(__GNUC__) || defined(ENUM_BITFIELDS)) && !defined(NO_ENUM_BITFIELDS) /* bird: NO_ENUM_BITFIELDS */
    417448# define ENUM_BITFIELD(bits)    :bits
    418449#else
     
    433464#define N_(msgid)           gettext_noop (msgid)
    434465#define S_(msg1,msg2,num)   ngettext (msg1,msg2,num)
    435 
    436 /* Handle other OSs.  */
    437 #ifndef PATH_SEPARATOR_CHAR
    438 # if defined(HAVE_DOS_PATHS)
    439 #  define PATH_SEPARATOR_CHAR ';'
    440 # elif defined(VMS)
    441 #  define PATH_SEPARATOR_CHAR ','
    442 # else
    443 #  define PATH_SEPARATOR_CHAR ':'
    444 # endif
    445 #endif
    446466
    447467/* This is needed for getcwd() and chdir(), on some W32 systems.  */
     
    455475# define pipe(_p)        _pipe((_p), 512, O_BINARY)
    456476# define kill(_pid,_sig) w32_kill((_pid),(_sig))
     477/* MSVC and Watcom C don't have ftruncate.  */
     478# if defined(_MSC_VER) || defined(__WATCOMC__)
     479#  define ftruncate(_fd,_len) _chsize(_fd,_len)
     480# endif
     481/* MinGW64 doesn't have _S_ISDIR.  */
     482# ifndef _S_ISDIR
     483#  define _S_ISDIR(m)  S_ISDIR(m)
     484# endif
    457485
    458486void sync_Path_environment (void);
    459487int w32_kill (pid_t pid, int sig);
    460 char *end_of_token_w32 (const char *s, char stopchar);
    461488int find_and_set_default_shell (const char *token);
    462489
     
    466493/* is default_shell unixy? */
    467494extern int unixy_shell;
     495
     496/* We don't have a preferred fixed value for LOCALEDIR.  */
     497# ifndef LOCALEDIR
     498#  define LOCALEDIR NULL
     499# endif
     500
     501/* Include only the minimal stuff from windows.h.   */
     502# define WIN32_LEAN_AND_MEAN
    468503#endif  /* WINDOWS32 */
     504
     505#define ANY_SET(_v,_m)  (((_v)&(_m)) != 0)
     506#define NONE_SET(_v,_m) (! ANY_SET ((_v),(_m)))
     507
     508#define MAP_NUL         0x0001
     509#define MAP_BLANK       0x0002
     510#define MAP_NEWLINE     0x0004
     511#define MAP_COMMENT     0x0008
     512#define MAP_SEMI        0x0010
     513#define MAP_EQUALS      0x0020
     514#define MAP_COLON       0x0040
     515#define MAP_PERCENT     0x0080
     516#define MAP_PIPE        0x0100
     517#define MAP_DOT         0x0200
     518#define MAP_COMMA       0x0400
     519
     520/* These are the valid characters for a user-defined function.  */
     521#define MAP_USERFUNC    0x2000
     522/* This means not only a '$', but skip the variable reference.  */
     523#define MAP_VARIABLE    0x4000
     524/* The set of characters which are directory separators is OS-specific.  */
     525#define MAP_DIRSEP      0x8000
     526
     527#ifdef VMS
     528# define MAP_VMSCOMMA   MAP_COMMA
     529#else
     530# define MAP_VMSCOMMA   0x0000
     531#endif
     532
     533#define MAP_SPACE       (MAP_BLANK|MAP_NEWLINE)
     534
     535/* Handle other OSs.
     536   To overcome an issue parsing paths in a DOS/Windows environment when
     537   built in a unix based environment, override the PATH_SEPARATOR_CHAR
     538   definition unless being built for Cygwin. */
     539#if defined(HAVE_DOS_PATHS) && !defined(__CYGWIN__)
     540# undef PATH_SEPARATOR_CHAR
     541# define PATH_SEPARATOR_CHAR ';'
     542# define MAP_PATHSEP    MAP_SEMI
     543#elif !defined(PATH_SEPARATOR_CHAR)
     544# if defined (VMS)
     545#  define PATH_SEPARATOR_CHAR (vms_comma_separator ? ',' : ':')
     546#  define MAP_PATHSEP    (vms_comma_separator ? MAP_COMMA : MAP_SEMI)
     547# else
     548#  define PATH_SEPARATOR_CHAR ':'
     549#  define MAP_PATHSEP    MAP_COLON
     550# endif
     551#elif PATH_SEPARATOR_CHAR == ':'
     552# define MAP_PATHSEP     MAP_COLON
     553#elif PATH_SEPARATOR_CHAR == ';'
     554# define MAP_PATHSEP     MAP_SEMI
     555#elif PATH_SEPARATOR_CHAR == ','
     556# define MAP_PATHSEP     MAP_COMMA
     557#else
     558# error "Unknown PATH_SEPARATOR_CHAR"
     559#endif
     560
     561#define STOP_SET(_v,_m) ANY_SET(stopchar_map[(unsigned char)(_v)],(_m))
     562
     563#define ISBLANK(c)      STOP_SET((c),MAP_BLANK)
     564#define ISSPACE(c)      STOP_SET((c),MAP_SPACE)
     565#define NEXT_TOKEN(s)   while (ISSPACE (*(s))) ++(s)
     566#define END_OF_TOKEN(s) while (! STOP_SET (*(s), MAP_SPACE|MAP_NUL)) ++(s)
    469567
    470568#if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT)
     
    473571#ifdef SET_STACK_SIZE
    474572# include <sys/resource.h>
    475 struct rlimit stack_limit;
    476 #endif
    477 
    478 struct floc
     573extern struct rlimit stack_limit;
     574#endif
     575
     576#include "glob.h" /* bird double quotes */
     577
     578#define NILF ((floc *)0)
     579
     580#define CSTRLEN(_s)           (sizeof (_s)-1)
     581#define STRING_SIZE_TUPLE(_s) (_s), CSTRLEN(_s) /* The number of bytes needed to represent the largest integer as a string.  */
     582#define INTSTR_LENGTH         CSTRLEN ("18446744073709551616")
     583
     584#define DEFAULT_TTYNAME "true"
     585#ifdef HAVE_TTYNAME
     586#  define TTYNAME(_f) ttyname (_f)
     587#else
     588#  define TTYNAME(_f) DEFAULT_TTYNAME
     589#endif
     590
     591
     592
     593
     594/* Specify the location of elements read from makefiles.  */
     595typedef struct
    479596  {
    480597    const char *filenm;
    481598    unsigned long lineno;
    482   };
    483 #define NILF ((struct floc *)0)
    484 
    485 #define STRING_SIZE_TUPLE(_s) (_s), (sizeof (_s)-1)
    486 
    487 #if defined (CONFIG_WITH_MATH) \
     599    unsigned long offset;
     600  } floc;
     601
     602#if defined (CONFIG_WITH_MATH) /* bird start */ \
    488603 || defined (CONFIG_WITH_NANOTS) \
    489604 || defined (CONFIG_WITH_FILE_SIZE) \
    490  || defined (CONFIG_WITH_PRINT_TIME_SWITCH) /* bird */
     605 || defined (CONFIG_WITH_PRINT_TIME_SWITCH)
    491606# ifdef _MSC_VER
    492607typedef __int64 big_int;
     
    501616#  define BIG_UINT_C(c)     UINT64_C(c)
    502617# endif
    503 #endif
    504 
    505 
    506 
    507 /* We have to have stdarg.h or varargs.h AND v*printf or doprnt to use
    508    variadic versions of these functions.  */
    509 
    510 #if HAVE_STDARG_H || HAVE_VARARGS_H
    511 # if HAVE_VPRINTF || HAVE_DOPRNT
    512 #  define USE_VARIADIC 1
    513 # endif
    514 #endif
    515 
    516 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
     618#endif /* bird end */
     619
    517620const char *concat (unsigned int, ...);
    518 void message (int prefix, const char *fmt, ...)
    519               __attribute__ ((__format__ (__printf__, 2, 3)));
    520 void error (const struct floc *flocp, const char *fmt, ...)
    521             __attribute__ ((__format__ (__printf__, 2, 3)));
    522 void fatal (const struct floc *flocp, const char *fmt, ...)
    523                    __attribute__ ((noreturn, __format__ (__printf__, 2, 3)));
    524 #else
    525 const char *concat ();
    526 void message ();
    527 void error ();
    528 void fatal ();
    529 #endif
     621void message (int prefix, size_t length, const char *fmt, ...)
     622              __attribute__ ((__format__ (__printf__, 3, 4)));
     623void error (const floc *flocp, size_t length, const char *fmt, ...)
     624            __attribute__ ((__format__ (__printf__, 3, 4)));
     625void fatal (const floc *flocp, size_t length, const char *fmt, ...)
     626            __attribute__ ((noreturn, __format__ (__printf__, 3, 4)));
     627
     628#define O(_t,_a,_f)           _t((_a), 0, (_f))
     629#define OS(_t,_a,_f,_s)       _t((_a), strlen (_s), (_f), (_s))
     630#define OSS(_t,_a,_f,_s1,_s2) _t((_a), strlen (_s1) + strlen (_s2), \
     631                                 (_f), (_s1), (_s2))
     632#define OSSS(_t,_a,_f,_s1,_s2,_s3) _t((_a), strlen (_s1) + strlen (_s2) + strlen (_s3), \
     633                                      (_f), (_s1), (_s2), (_s3))
     634#define ON(_t,_a,_f,_n)       _t((_a), INTSTR_LENGTH, (_f), (_n))
     635#define ONN(_t,_a,_f,_n1,_n2) _t((_a), INTSTR_LENGTH*2, (_f), (_n1), (_n2))
     636
     637#define OSN(_t,_a,_f,_s,_n)   _t((_a), strlen (_s) + INTSTR_LENGTH, \
     638                                 (_f), (_s), (_n))
     639#define ONS(_t,_a,_f,_n,_s)   _t((_a), INTSTR_LENGTH + strlen (_s), \
     640                                 (_f), (_n), (_s))
     641
     642/* bird: more wrappers */
     643#define OSNN(_t,_a,_f,_s,_n1,_n2)   _t((_a), strlen (_s) + INTSTR_LENGTH + INTSTR_LENGTH, \
     644                                       (_f), (_s), (_n1), (_n2))                    /* bird */
     645#define OSNS(_t,_a,_f,_s1,_n,_s2)   _t((_a), strlen (_s1) + strlen (_s2) + INTSTR_LENGTH, \
     646                                      (_f), (_s1), (_n), (_s2))                     /* bird */
     647#define OSSSS(_t,_a,_f,_s1,_s2,_s3,_s4) _t((_a), strlen (_s1) + strlen (_s2) + strlen (_s3) + strlen (_s4), \
     648                                           (_f), (_s1), (_s2), (_s3), (_s4))        /* bird */
     649#define OSSNS(_t,_a,_f,_s1,_s2,_n,_s3) _t((_a), strlen (_s1) + strlen (_s2) + strlen (_s3) + INTSTR_LENGTH, \
     650                                          (_f), (_s1), (_s2), (_n), (_s3))          /* bird */
     651
     652#define OUT_OF_MEM() O (fatal, NILF, _("virtual memory exhausted"))
    530653
    531654void die (int) __attribute__ ((noreturn));
    532 void log_working_directory (int);
    533655void pfatal_with_name (const char *) __attribute__ ((noreturn));
    534656void perror_with_name (const char *, const char *);
     657#define xstrlen(_s) ((_s)==NULL ? 0 : strlen (_s))
    535658void *xmalloc (unsigned int);
    536659void *xcalloc (unsigned int);
     
    561684char *find_percent (char *);
    562685const char *find_percent_cached (const char **);
    563 FILE *open_tmpfile (char **, const char *);
    564686
    565687#ifndef NO_ARCHIVES
     
    570692
    571693typedef long int (*ar_member_func_t) (int desc, const char *mem, int truncated,
    572                                       long int hdrpos, long int datapos,
    573                                       long int size, long int date, int uid,
    574                                       int gid, int mode, const void *arg);
     694                                      long int hdrpos, long int datapos,
     695                                      long int size, long int date, int uid,
     696                                      int gid, unsigned int mode,
     697                                      const void *arg);
    575698
    576699long int ar_scan (const char *archive, ar_member_func_t function, const void *arg);
     
    586709void file_impossible (const char *);
    587710const char *dir_name (const char *);
     711void print_dir_data_base (void);
     712void dir_setup_glob (glob_t *);
    588713void hash_init_directories (void);
    589714
    590715void define_default_variables (void);
     716void undefine_default_variables (void);
    591717void set_default_suffixes (void);
    592718void install_default_suffix_rules (void);
     
    605731void child_access (void);
    606732
    607 void close_stdout (void);
    608 
    609733char *strip_whitespace (const char **begpp, const char **endpp);
    610734
    611 #ifdef CONFIG_WITH_ALLOC_CACHES
     735void show_goal_error (void);
     736
     737
     738#ifdef CONFIG_WITH_ALLOC_CACHES /* bird start */
    612739/* alloccache (misc.c) */
    613740
     
    675802/* the alloc caches */
    676803extern struct alloccache dep_cache;
     804extern struct alloccache goaldep_cache;
     805extern struct alloccache nameseq_cache;
    677806extern struct alloccache file_cache;
    678807extern struct alloccache commands_cache;
    679 extern struct alloccache nameseq_cache;
    680808extern struct alloccache variable_cache;
    681809extern struct alloccache variable_set_cache;
    682810extern struct alloccache variable_set_list_cache;
    683811
    684 #endif /* CONFIG_WITH_ALLOC_CACHES */
     812#endif /* CONFIG_WITH_ALLOC_CACHES - bird end*/
    685813
    686814
     
    688816void strcache_init (void);
    689817void strcache_print_stats (const char *prefix);
    690 #ifndef CONFIG_WITH_STRCACHE2
     818#ifndef CONFIG_WITH_STRCACHE2 /* bird */
    691819int strcache_iscached (const char *str);
    692820const char *strcache_add (const char *str);
    693 const char *strcache_add_len (const char *str, int len);
    694 int strcache_setbufsize (int size);
     821const char *strcache_add_len (const char *str, unsigned int len);
    695822#else  /* CONFIG_WITH_STRCACHE2 */
    696823
     
    706833#endif /* CONFIG_WITH_STRCACHE2 */
    707834
    708 #ifdef  HAVE_VFORK_H
    709 # include <vfork.h>
    710 #endif
     835/* Guile support  */
     836int guile_gmake_setup (const floc *flocp);
     837
     838/* Loadable object support.  Sets to the strcached name of the loaded file.  */
     839typedef int (*load_func_t)(const floc *flocp);
     840int load_file (const floc *flocp, const char **filename, int noerror);
     841void unload_file (const char *name);
    711842
    712843/* We omit these declarations on non-POSIX systems which define _POSIX_VERSION,
     
    720851# endif
    721852
     853# ifdef  HAVE_GETCWD
     854#  if !defined(VMS) && !defined(__DECC) && !defined(_MSC_VER) /* bird: MSC */
     855char *getcwd ();
     856#  endif
     857# else
     858char *getwd ();
     859#  define getcwd(buf, len)       getwd (buf)
     860# endif
     861
    722862#endif  /* Not GNU C library or POSIX.  */
    723 
    724 #ifdef  HAVE_GETCWD
    725 # if !defined(VMS) && !defined(__DECC) && !defined(_MSC_VER) /* bird: MSC */
    726 char *getcwd ();
    727 # endif
    728 #else
    729 char *getwd ();
    730 # define getcwd(buf, len)       getwd (buf)
    731 #endif
    732863
    733864#if !HAVE_STRCASECMP
     
    753884#endif
    754885
    755 extern const struct floc *reading_file;
    756 extern const struct floc **expanding_var;
     886#define OUTPUT_SYNC_NONE    0
     887#define OUTPUT_SYNC_LINE    1
     888#define OUTPUT_SYNC_TARGET  2
     889#define OUTPUT_SYNC_RECURSE 3
    757890
    758891#if !defined(_MSC_VER) /* bird */
     892/* Non-GNU systems may not declare this in unistd.h.  */
    759893extern char **environ;
    760894#endif
     895
     896extern const floc *reading_file;
     897extern const floc **expanding_var;
     898
     899extern unsigned short stopchar_map[];
    761900
    762901extern int just_print_flag, silent_flag, ignore_errors_flag, keep_going_flag;
     
    764903extern int env_overrides, no_builtin_rules_flag, no_builtin_variables_flag;
    765904extern int print_version_flag, print_directory_flag, check_symlink_flag;
    766 extern int warn_undefined_variables_flag, posix_pedantic, not_parallel;
    767 extern int second_expansion, clock_skew_detected, rebuilding_makefiles;
    768 extern int one_shell;
    769 
    770 #ifdef CONFIG_WITH_2ND_TARGET_EXPANSION
     905extern int warn_undefined_variables_flag, trace_flag, posix_pedantic;
     906extern int not_parallel, second_expansion, clock_skew_detected;
     907extern int rebuilding_makefiles, one_shell, output_sync, verify_flag;
     908
     909#ifdef CONFIG_WITH_2ND_TARGET_EXPANSION /* bird start */
    771910extern int second_target_expansion;
    772911#endif
     
    779918#if defined (CONFIG_WITH_MAKE_STATS) || defined (CONFIG_WITH_MINIMAL_STATS)
    780919extern int make_expensive_statistics;
    781 #endif
    782 
     920#endif                                  /* bird end */
     921
     922extern const char *default_shell;
    783923
    784924/* can we run commands via 'sh -c xxx' or must we use batch files? */
     
    791931
    792932extern unsigned int job_slots;
    793 extern int job_fds[2];
    794 extern int job_rfd;
    795933#ifndef NO_FLOAT
    796934extern double max_load_average;
     
    799937#endif
    800938
     939#ifdef WINDOWS32
    801940extern char *program;
     941#else
     942extern const char *program;
     943#endif
     944
     945#ifdef VMS
     946const char *vms_command (const char *argv0);
     947const char *vms_progname (const char *argv0);
     948
     949void vms_exit (int);
     950# define _exit(foo) vms_exit(foo)
     951# define exit(foo) vms_exit(foo)
     952
     953extern char *program_name;
     954
     955void
     956set_program_name (const char *arv0);
     957
     958int
     959need_vms_symbol (void);
     960
     961int
     962create_foreign_command (const char *command, const char *image);
     963
     964int
     965vms_export_dcl_symbol (const char *name, const char *value);
     966
     967int
     968vms_putenv_symbol (const char *string);
     969
     970void
     971vms_restore_symbol (const char *string);
     972
     973#endif
     974
     975void remote_setup (void);
     976void remote_cleanup (void);
     977int start_remote_job_p (int);
     978int start_remote_job (char **, char **, int, int *, int *, int *);
     979int remote_status (int *, int *, int *, int);
     980void block_remote_children (void);
     981void unblock_remote_children (void);
     982int remote_kill (int id, int sig);
     983void print_variable_data_base (void);
     984void print_vpath_data_base (void);
     985
    802986extern char *starting_directory;
    803987extern unsigned int makelevel;
     
    8161000#endif
    8171001
    818 #ifdef VMS
    819 #  define MAKE_SUCCESS 1
    820 #  define MAKE_TROUBLE 2
    821 #  define MAKE_FAILURE 3
    822 #else
    823 #  define MAKE_SUCCESS 0
    824 #  define MAKE_TROUBLE 1
    825 #  define MAKE_FAILURE 2
    826 #endif
     1002
     1003#define MAKE_SUCCESS 0
     1004#define MAKE_TROUBLE 1
     1005#define MAKE_FAILURE 2
    8271006
    8281007/* Set up heap debugging library dmalloc.  */
     
    9731152
    9741153#ifdef CONFIG_WITH_IF_CONDITIONALS
    975 extern int expr_eval_if_conditionals(const char *line, const struct floc *flocp);
     1154extern int expr_eval_if_conditionals(const char *line, const floc *flocp);
    9761155extern char *expr_eval_to_string(char *o, const char *expr);
    9771156#endif
  • trunk/src/kmk/misc.c

    r3068 r3140  
    11/* Miscellaneous generic support functions for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
     18#include "filedef.h"
    2019#include "dep.h"
    2120#include "debug.h"
     21
     22/* GNU make no longer supports pre-ANSI89 environments.  */
     23
     24#include <stdarg.h>
     25
     26#ifdef HAVE_FCNTL_H
     27# include <fcntl.h>
     28#else
     29# include <sys/file.h>
     30#endif
     31
    2232#if defined (CONFIG_WITH_VALUE_LENGTH) || defined (CONFIG_WITH_ALLOC_CACHES)
    2333# include <assert.h>
     
    3141# endif
    3242#endif
    33 
    3443#if defined (CONFIG_WITH_NANOTS) || defined (CONFIG_WITH_PRINT_TIME_SWITCH)
    3544# ifdef WINDOWS32
     
    4857#endif
    4958
    50 /* Variadic functions.  We go through contortions to allow proper function
    51    prototypes for both ANSI and pre-ANSI C compilers, and also for those
    52    which support stdarg.h vs. varargs.h, and finally those which have
    53    vfprintf(), etc. and those who have _doprnt... or nothing.
    54 
    55    This fancy stuff all came from GNU fileutils, except for the VA_PRINTF and
    56    VA_END macros used here since we have multiple print functions.  */
    57 
    58 #if USE_VARIADIC
    59 # if HAVE_STDARG_H
    60 #  include <stdarg.h>
    61 #  define VA_START(args, lastarg) va_start(args, lastarg)
    62 # else
    63 #  include <varargs.h>
    64 #  define VA_START(args, lastarg) va_start(args)
    65 # endif
    66 # if HAVE_VPRINTF
    67 #  define VA_PRINTF(fp, lastarg, args) vfprintf((fp), (lastarg), (args))
    68 # else
    69 #  define VA_PRINTF(fp, lastarg, args) _doprnt((lastarg), (args), (fp))
    70 # endif
    71 # define VA_END(args) va_end(args)
    72 #else
    73 /* We can't use any variadic interface! */
    74 # define va_alist a1, a2, a3, a4, a5, a6, a7, a8
    75 # define va_dcl char *a1, *a2, *a3, *a4, *a5, *a6, *a7, *a8;
    76 # define VA_START(args, lastarg)
    77 # define VA_PRINTF(fp, lastarg, args) fprintf((fp), (lastarg), va_alist)
    78 # define VA_END(args)
    79 #endif
    80 
    8159
    8260/* Compare strings *S1 and *S2.
     
    10886#endif
    10987{
    110   register char *in, *out, *p;
    111   register int backslash;
    112   register unsigned int bs_write;
     88  char *in, *out, *p;
    11389
    11490#ifndef CONFIG_WITH_VALUE_LENGTH
     
    143119    {
    144120      /* BS_WRITE gets the number of quoted backslashes at
    145         the end just before IN, and BACKSLASH gets nonzero
    146         if the next character is quoted.  */
    147       backslash = 0;
    148       bs_write = 0;
     121        the end just before IN, and BACKSLASH gets nonzero
     122        if the next character is quoted.  */
     123      unsigned int backslash = 0;
     124      unsigned int bs_write = 0;
    149125      for (p = in - 1; p >= line && *p == '\\'; --p)
    150         {
    151           if (backslash)
    152             ++bs_write;
    153           backslash = !backslash;
    154 
    155           /* It should be impossible to go back this far without exiting,
    156              but if we do, we can't get the right answer.  */
    157           if (in == out - 1)
    158             abort ();
    159         }
     126        {
     127          if (backslash)
     128            ++bs_write;
     129          backslash = !backslash;
     130
     131          /* It should be impossible to go back this far without exiting,
     132             but if we do, we can't get the right answer.  */
     133          if (in == out - 1)
     134            abort ();
     135        }
    160136
    161137      /* Output the appropriate number of backslashes.  */
    162138      while (bs_write-- > 0)
    163         *out++ = '\\';
     139        *out++ = '\\';
    164140
    165141      /* Skip the newline.  */
    166142      ++in;
    167143
    168       /* If the newline is escaped, discard following whitespace leaving just
    169          one space.  POSIX requires that each backslash/newline/following
    170          whitespace sequence be reduced to a single space.  */
    171144      if (backslash)
    172         {
    173           in = next_token (in);
    174           /* Removing this loop will fix Savannah bug #16670: do we want to? */
    175           while (out > line && isblank ((unsigned char)out[-1]))
    176             --out;
    177           *out++ = ' ';
    178         }
     145        {
     146          /* Backslash/newline handling:
     147             In traditional GNU make all trailing whitespace, consecutive
     148             backslash/newlines, and any leading non-newline whitespace on the
     149             next line is reduced to a single space.
     150             In POSIX, each backslash/newline and is replaced by a space.  */
     151          while (ISBLANK (*in))
     152            ++in;
     153          if (! posix_pedantic)
     154            while (out > line && ISBLANK (out[-1]))
     155              --out;
     156          *out++ = ' ';
     157        }
    179158      else
    180         /* If the newline isn't quoted, put it in the output.  */
    181         *out++ = '\n';
     159        /* If the newline isn't quoted, put it in the output.  */
     160        *out++ = '\n';
    182161
    183162      /* Now copy the following line to the output.
    184         Stop when we find backslashes followed by a newline.  */
     163        Stop when we find backslashes followed by a newline.  */
    185164      while (*in != '\0')
    186         if (*in == '\\')
    187           {
    188             p = in + 1;
    189             while (*p == '\\')
    190               ++p;
    191             if (*p == '\n')
    192               {
    193                 in = p;
    194                 break;
    195               }
    196             while (in < p)
    197               *out++ = *in++;
    198           }
    199         else
    200           *out++ = *in++;
     165        if (*in == '\\')
     166          {
     167            p = in + 1;
     168            while (*p == '\\')
     169              ++p;
     170            if (*p == '\n')
     171              {
     172                in = p;
     173                break;
     174              }
     175            while (in < p)
     176              *out++ = *in++;
     177          }
     178        else
     179          *out++ = *in++;
    201180    }
    202181
     
    224203
    225204const char *
    226 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
    227205concat (unsigned int num, ...)
    228 #else
    229 concat (num, va_alist)
    230      unsigned int num;
    231      va_dcl
    232 #endif
    233206{
    234207  static unsigned int rlen = 0;
    235208  static char *result = NULL;
    236   unsigned int ri = 0; /* bird: must be unsigned */
    237 
    238 #if USE_VARIADIC
     209  unsigned int ri = 0;
    239210  va_list args;
    240 #endif
    241 
    242   VA_START (args, num);
     211
     212  va_start (args, num);
    243213
    244214  while (num-- > 0)
    245215    {
    246216      const char *s = va_arg (args, const char *);
    247       unsigned int l = s ? strlen (s) : 0;
     217      unsigned int l = xstrlen (s);
    248218
    249219      if (l == 0)
     
    260230    }
    261231
    262   VA_END (args);
     232  va_end (args);
    263233
    264234  /* Get some more memory if we don't have enough space for the
     
    276246
    277247
    278 /* Print a message on stdout.  */
    279 
    280 void
    281 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
    282 message (int prefix, const char *fmt, ...)
    283 #else
    284 message (prefix, fmt, va_alist)
    285      int prefix;
    286      const char *fmt;
    287      va_dcl
    288 #endif
    289 {
    290 #if USE_VARIADIC
    291   va_list args;
    292 #endif
    293 
    294   log_working_directory (1);
    295 
    296   if (fmt != 0)
    297     {
    298 #ifdef KBUILD_OS_WINDOWS
    299       char szMsg[16384];
    300       int cchMsg = 0;
    301       int cchUser;
    302       if (prefix)
    303         {
    304           if (makelevel == 0)
    305             cchMsg = snprintf (szMsg, sizeof(szMsg), "%s: ", program);
    306           else
    307             cchMsg = snprintf (szMsg, sizeof(szMsg), "%s[%u]: ", program, makelevel);
    308         }
    309       VA_START (args, fmt);
    310       cchMsg += cchUser = vsnprintf (&szMsg[cchMsg], sizeof(szMsg) - cchMsg, fmt, args);
    311       VA_END (args);
    312       if (   cchMsg < sizeof(szMsg)
    313           && cchUser >= 0)
    314         {
    315           extern size_t maybe_con_fwrite(void const *, size_t, size_t, FILE *);
    316           szMsg[cchMsg++] = '\n';
    317           maybe_con_fwrite(szMsg, cchMsg, 1, stdout);
    318         }
    319       else
    320         {
    321 #endif
    322       if (prefix)
    323         {
    324           if (makelevel == 0)
    325             printf ("%s: ", program);
    326           else
    327             printf ("%s[%u]: ", program, makelevel);
    328         }
    329       VA_START (args, fmt);
    330       VA_PRINTF (stdout, fmt, args);
    331       VA_END (args);
    332       putchar ('\n');
    333 #ifdef KBUILD_OS_WINDOWS
    334         }
    335 #endif
    336     }
    337 
    338   fflush (stdout);
    339 }
    340 
    341 /* Print an error message.  */
    342 
    343 void
    344 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
    345 error (const struct floc *flocp, const char *fmt, ...)
    346 #else
    347 error (flocp, fmt, va_alist)
    348      const struct floc *flocp;
    349      const char *fmt;
    350      va_dcl
    351 #endif
    352 {
    353 #if USE_VARIADIC
    354   va_list args;
    355 #endif
    356 #ifdef KMK
    357   char szMsg[16384];
    358   int cchMsg = 0;
    359   int cchUser;
    360 #endif
    361 
    362   log_working_directory (1);
    363 
    364 #ifdef KMK /* Try avoid getting the error split by child output.  */
    365   if (flocp && flocp->filenm)
    366     cchMsg = snprintf (szMsg, sizeof(szMsg), "%s:%lu: ", flocp->filenm, flocp->lineno);
    367   else if (makelevel == 0)
    368     cchMsg = snprintf (szMsg, sizeof(szMsg), "%s: ", program);
    369   else
    370     cchMsg = snprintf (szMsg, sizeof(szMsg), "%s[%u]: ", program, makelevel);
    371 
    372   VA_START (args, fmt);
    373   cchMsg += cchUser = vsnprintf (&szMsg[cchMsg], sizeof(szMsg) - cchMsg, fmt, args);
    374   VA_END (args);
    375   if (   cchMsg < (int)sizeof(szMsg)
    376       && cchUser >= 0)
    377     {
    378       extern size_t maybe_con_fwrite(void const *, size_t, size_t, FILE *);
    379       szMsg[cchMsg++] = '\n';
    380       maybe_con_fwrite(szMsg, cchMsg, 1, stderr);
    381     }
    382   else
    383     {
    384 #endif /* KMK */
    385 
    386   if (flocp && flocp->filenm)
    387     fprintf (stderr, "%s:%lu: ", flocp->filenm, flocp->lineno);
    388   else if (makelevel == 0)
    389     fprintf (stderr, "%s: ", program);
    390   else
    391     fprintf (stderr, "%s[%u]: ", program, makelevel);
    392 
    393   VA_START(args, fmt);
    394   VA_PRINTF (stderr, fmt, args);
    395   VA_END (args);
    396 
    397   putc ('\n', stderr);
    398 #ifdef KMK
    399     }
    400 #endif
    401   fflush (stderr);
    402 }
    403 
    404 /* Print an error message and exit.  */
    405 
    406 void
    407 #if HAVE_ANSI_COMPILER && USE_VARIADIC && HAVE_STDARG_H
    408 fatal (const struct floc *flocp, const char *fmt, ...)
    409 #else
    410 fatal (flocp, fmt, va_alist)
    411      const struct floc *flocp;
    412      const char *fmt;
    413      va_dcl
    414 #endif
    415 {
    416 #if USE_VARIADIC
    417   va_list args;
    418 #endif
    419 #ifdef KMK
    420   char szMsg[16384];
    421   int cchMsg = 0;
    422   int cchUser;
    423   const char *pszStop = _(".  Stop.\n");
    424   int         cchStop = (int)strlen(pszStop);
    425 #endif
    426 
    427   log_working_directory (1);
    428 
    429 #ifdef KMK /* Try avoid getting the error split by child output.  */
    430   if (flocp && flocp->filenm)
    431     cchMsg = snprintf (szMsg, sizeof(szMsg), "%s:%lu: *** ", flocp->filenm, flocp->lineno);
    432   else if (makelevel == 0)
    433     cchMsg = snprintf (szMsg, sizeof(szMsg), "%s: *** ", program);
    434   else
    435     cchMsg = snprintf (szMsg, sizeof(szMsg), "%s[%u]: *** ", program, makelevel);
    436 
    437   VA_START (args, fmt);
    438   cchMsg += cchUser = vsnprintf (&szMsg[cchMsg], sizeof(szMsg) - cchMsg, fmt, args);
    439   VA_END (args);
    440   if (   cchMsg + cchStop <= (int)sizeof(szMsg)
    441       && cchUser >= 0)
    442     {
    443       extern size_t maybe_con_fwrite(void const *, size_t, size_t, FILE *);
    444       memcpy(&szMsg[cchMsg], pszStop, cchStop);
    445       cchMsg += cchStop;
    446       maybe_con_fwrite(szMsg, cchMsg, 1, stderr);
    447     }
    448   else
    449     {
    450 #endif /* KMK */
    451   if (flocp && flocp->filenm)
    452     fprintf (stderr, "%s:%lu: *** ", flocp->filenm, flocp->lineno);
    453   else if (makelevel == 0)
    454     fprintf (stderr, "%s: *** ", program);
    455   else
    456     fprintf (stderr, "%s[%u]: *** ", program, makelevel);
    457 
    458   VA_START(args, fmt);
    459   VA_PRINTF (stderr, fmt, args);
    460   VA_END (args);
    461 
    462   fputs (_(".  Stop.\n"), stderr);
    463 #ifdef KMK
    464     }
    465 #endif
    466 
    467   die (2);
    468 }
    469248
    470249#ifndef HAVE_STRERROR
    471 
    472 #undef  strerror
    473 
     250#undef  strerror
    474251char *
    475252strerror (int errnum)
     
    488265}
    489266#endif
    490 
    491 /* Print an error message from errno.  */
    492 
    493 void
    494 perror_with_name (const char *str, const char *name)
    495 {
    496   error (NILF, _("%s%s: %s"), str, name, strerror (errno));
    497 }
    498 
    499 /* Print an error message from errno and exit.  */
    500 
    501 void
    502 pfatal_with_name (const char *name)
    503 {
    504   fatal (NILF, _("%s: %s"), name, strerror (errno));
    505 
    506   /* NOTREACHED */
    507 }
    508267
    509268
     
    524283  void *result = malloc (size ? size : 1);
    525284  if (result == 0)
    526     fatal (NILF, _("virtual memory exhausted"));
     285    OUT_OF_MEM();
    527286
    528287#ifdef CONFIG_WITH_MAKE_STATS
     
    543302  void *result = calloc (size ? size : 1, 1);
    544303  if (result == 0)
    545     fatal (NILF, _("virtual memory exhausted"));
     304    OUT_OF_MEM();
    546305
    547306#ifdef CONFIG_WITH_MAKE_STATS
     
    574333  result = ptr ? realloc (ptr, size) : malloc (size);
    575334  if (result == 0)
    576     fatal (NILF, _("virtual memory exhausted"));
     335    OUT_OF_MEM();
    577336
    578337#ifdef CONFIG_WITH_MAKE_STATS
     
    598357
    599358  if (result == 0)
    600     fatal (NILF, _("virtual memory exhausted"));
     359    OUT_OF_MEM();
    601360
    602361#ifdef CONFIG_WITH_MAKE_STATS
     
    624383  result = strndup (str, length);
    625384  if (result == 0)
    626     fatal (NILF, _("virtual memory exhausted"));
     385    OUT_OF_MEM();
    627386#else
    628387  result = xmalloc (length + 1);
     
    663422end_of_token (const char *s)
    664423{
    665 #ifdef KMK
     424#if 0 /* @todo def KMK */
    666425    for (;;)
    667426      {
     
    685444
    686445#else
    687   while (*s != '\0' && !isblank ((unsigned char)*s))
    688     ++s;
     446  END_OF_TOKEN (s);
    689447  return (char *)s;
    690448#endif
    691449}
    692 
    693 #ifdef WINDOWS32
    694 /*
    695  * Same as end_of_token, but take into account a stop character
    696  */
    697 char *
    698 end_of_token_w32 (const char *s, char stopchar)
    699 {
    700   const char *p = s;
    701   int backslash = 0;
    702 
    703   while (*p != '\0' && *p != stopchar
    704          && (backslash || !isblank ((unsigned char)*p)))
    705     {
    706       if (*p++ == '\\')
    707         {
    708           backslash = !backslash;
    709           while (*p == '\\')
    710             {
    711               backslash = !backslash;
    712               ++p;
    713             }
    714         }
    715       else
    716         backslash = 0;
    717     }
    718 
    719   return (char *)p;
    720 }
    721 #endif
    722450
    723451/* Return the address of the first nonwhitespace or null in the string S.  */
     
    726454next_token (const char *s)
    727455{
    728 #ifdef KMK
     456#if 0 /* @todo def KMK */
    729457  for (;;)
    730458    {
     
    748476
    749477#else  /* !KMK */
    750   while (isblank ((unsigned char)*s))
    751     ++s;
     478  NEXT_TOKEN (s);
    752479  return (char *)s;
    753480#endif /* !KMK */
     
    932659
    933660
    934 /* Copy a chain of `struct dep'.  For 2nd expansion deps, dup the name.  */
     661/* Copy a chain of 'struct dep'.  For 2nd expansion deps, dup the name.  */
    935662
    936663struct dep *
     
    955682      c->next = 0;
    956683      if (firstnew == 0)
    957         firstnew = lastnew = c;
     684        firstnew = lastnew = c;
    958685      else
    959         lastnew = lastnew->next = c;
     686        lastnew = lastnew->next = c;
    960687
    961688      d = d->next;
     
    963690
    964691  return firstnew;
    965 }
    966 
    967 /* Free a chain of 'struct dep'.  */
    968 
    969 void
    970 free_dep_chain (struct dep *d)
    971 {
    972   while (d != 0)
    973     {
    974       struct dep *df = d;
    975       d = d->next;
    976       free_dep (df);
    977     }
    978692}
    979693
     
    989703      ns = ns->next;
    990704#ifndef CONFIG_WITH_ALLOC_CACHES
    991       free (t);
     705      free_ns (t);
    992706#else
    993707      alloccache_free (&nameseq_cache, t);
     
    997711
    998712
     713#ifdef CONFIG_WITH_ALLOC_CACHES
     714
     715void
     716free_dep_chain (struct dep *d)
     717{
     718  while (d != 0)
     719    {
     720      struct dep *tofree = d;
     721      d = d->next;
     722      alloccache_free (&dep_cache, tofree);
     723    }
     724}
     725
     726void
     727free_goal_chain (struct goaldep *g)
     728{
     729  while (g != 0)
     730    {
     731      struct goaldep *tofree = g;
     732      g = g->next;
     733      alloccache_free (&dep_cache, tofree);
     734    }
     735}
     736
     737#endif /* CONFIG_WITH_ALLOC_CACHES */
     738
     739
    999740
    1000741#if !HAVE_STRCASECMP && !HAVE_STRICMP && !HAVE_STRCMPI
    1001 
    1002742/* If we don't have strcasecmp() (from POSIX), or anything that can substitute
    1003743   for it, define our own version.  */
     
    1025765
    1026766#if !HAVE_STRNCASECMP && !HAVE_STRNICMP && !HAVE_STRNCMPI
    1027 
    1028767/* If we don't have strncasecmp() (from POSIX), or anything that can
    1029768   substitute for it, define our own version.  */
     
    1053792
    1054793
    1055 #ifdef  GETLOADAVG_PRIVILEGED
     794#ifdef  GETLOADAVG_PRIVILEGED
    1056795
    1057796#ifdef POSIX
     
    1066805#undef HAVE_SETREGID
    1067806
    1068 #else   /* Not POSIX.  */
     807#else   /* Not POSIX.  */
    1069808
    1070809/* Some POSIX.1 systems have the seteuid and setegid functions.  In a
     
    1076815#undef HAVE_SETEGID
    1077816
    1078 #endif  /* POSIX.  */
    1079 
    1080 #ifndef HAVE_UNISTD_H
     817#endif  /* POSIX.  */
     818
     819#ifndef HAVE_UNISTD_H
    1081820extern int getuid (), getgid (), geteuid (), getegid ();
    1082821extern int setuid (), setgid ();
     
    1084823extern int seteuid ();
    1085824#else
    1086 #ifdef  HAVE_SETREUID
     825#ifdef  HAVE_SETREUID
    1087826extern int setreuid ();
    1088 #endif  /* Have setreuid.  */
    1089 #endif  /* Have seteuid.  */
     827#endif  /* Have setreuid.  */
     828#endif  /* Have seteuid.  */
    1090829#ifdef HAVE_SETEGID
    1091830extern int setegid ();
    1092831#else
    1093 #ifdef  HAVE_SETREGID
     832#ifdef  HAVE_SETREGID
    1094833extern int setregid ();
    1095 #endif  /* Have setregid.  */
    1096 #endif  /* Have setegid.  */
    1097 #endif  /* No <unistd.h>.  */
     834#endif  /* Have setregid.  */
     835#endif  /* Have setegid.  */
     836#endif  /* No <unistd.h>.  */
    1098837
    1099838/* Keep track of the user and group IDs for user- and make- access.  */
    1100839static int user_uid = -1, user_gid = -1, make_uid = -1, make_gid = -1;
    1101 #define access_inited   (user_uid != -1)
     840#define access_inited   (user_uid != -1)
    1102841static enum { make, user } current_access;
    1103842
     
    1116855
    1117856  fprintf (stderr, _("%s: user %lu (real %lu), group %lu (real %lu)\n"),
    1118            flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
     857           flavor, (unsigned long) geteuid (), (unsigned long) getuid (),
    1119858           (unsigned long) getegid (), (unsigned long) getgid ());
    1120859  fflush (stderr);
     
    1142881}
    1143882
    1144 #endif  /* GETLOADAVG_PRIVILEGED */
     883#endif  /* GETLOADAVG_PRIVILEGED */
    1145884
    1146885/* Give the process appropriate permissions for access to
     
    1149888user_access (void)
    1150889{
    1151 #ifdef  GETLOADAVG_PRIVILEGED
     890#ifdef  GETLOADAVG_PRIVILEGED
    1152891
    1153892  if (!access_inited)
     
    1162901     which are the IDs of the process that exec'd make.  */
    1163902
    1164 #ifdef  HAVE_SETEUID
     903#ifdef  HAVE_SETEUID
    1165904
    1166905  /* Modern systems have the seteuid/setegid calls which set only the
     
    1170909    pfatal_with_name ("user_access: seteuid");
    1171910
    1172 #else   /* Not HAVE_SETEUID.  */
    1173 
    1174 #ifndef HAVE_SETREUID
     911#else   /* Not HAVE_SETEUID.  */
     912
     913#ifndef HAVE_SETREUID
    1175914
    1176915  /* System V has only the setuid/setgid calls to set user/group IDs.
     
    1185924    pfatal_with_name ("user_access: setuid");
    1186925
    1187 #else   /* HAVE_SETREUID.  */
     926#else   /* HAVE_SETREUID.  */
    1188927
    1189928  /* In 4BSD, the setreuid/setregid calls set both the real and effective IDs.
     
    1197936    pfatal_with_name ("user_access: setreuid");
    1198937
    1199 #endif  /* Not HAVE_SETREUID.  */
    1200 #endif  /* HAVE_SETEUID.  */
    1201 
    1202 #ifdef  HAVE_SETEGID
     938#endif  /* Not HAVE_SETREUID.  */
     939#endif  /* HAVE_SETEUID.  */
     940
     941#ifdef  HAVE_SETEGID
    1203942  if (setegid (user_gid) < 0)
    1204943    pfatal_with_name ("user_access: setegid");
    1205944#else
    1206 #ifndef HAVE_SETREGID
     945#ifndef HAVE_SETREGID
    1207946  if (setgid (user_gid) < 0)
    1208947    pfatal_with_name ("user_access: setgid");
     
    1217956  log_access (_("User access"));
    1218957
    1219 #endif  /* GETLOADAVG_PRIVILEGED */
     958#endif  /* GETLOADAVG_PRIVILEGED */
    1220959}
    1221960
     
    1225964make_access (void)
    1226965{
    1227 #ifdef  GETLOADAVG_PRIVILEGED
     966#ifdef  GETLOADAVG_PRIVILEGED
    1228967
    1229968  if (!access_inited)
     
    1235974  /* See comments in user_access, above.  */
    1236975
    1237 #ifdef  HAVE_SETEUID
     976#ifdef  HAVE_SETEUID
    1238977  if (seteuid (make_uid) < 0)
    1239978    pfatal_with_name ("make_access: seteuid");
    1240979#else
    1241 #ifndef HAVE_SETREUID
     980#ifndef HAVE_SETREUID
    1242981  if (setuid (make_uid) < 0)
    1243982    pfatal_with_name ("make_access: setuid");
     
    1248987#endif
    1249988
    1250 #ifdef  HAVE_SETEGID
     989#ifdef  HAVE_SETEGID
    1251990  if (setegid (make_gid) < 0)
    1252991    pfatal_with_name ("make_access: setegid");
    1253992#else
    1254 #ifndef HAVE_SETREGID
     993#ifndef HAVE_SETREGID
    1255994  if (setgid (make_gid) < 0)
    1256995    pfatal_with_name ("make_access: setgid");
     
    12651004  log_access (_("Make access"));
    12661005
    1267 #endif  /* GETLOADAVG_PRIVILEGED */
     1006#endif  /* GETLOADAVG_PRIVILEGED */
    12681007}
    12691008
     
    12731012child_access (void)
    12741013{
    1275 #ifdef  GETLOADAVG_PRIVILEGED
     1014#ifdef  GETLOADAVG_PRIVILEGED
    12761015
    12771016  if (!access_inited)
     
    12811020     They cannot be changed back to make's.  */
    12821021
    1283 #ifndef HAVE_SETREUID
     1022#ifndef HAVE_SETREUID
    12841023  if (setuid (user_uid) < 0)
    12851024    pfatal_with_name ("child_access: setuid");
     
    12891028#endif
    12901029
    1291 #ifndef HAVE_SETREGID
     1030#ifndef HAVE_SETREGID
    12921031  if (setgid (user_gid) < 0)
    12931032    pfatal_with_name ("child_access: setgid");
     
    12991038  log_access (_("Child access"));
    13001039
    1301 #endif  /* GETLOADAVG_PRIVILEGED */
    1302 }
    1303 
     1040#endif  /* GETLOADAVG_PRIVILEGED */
     1041}
    13041042
    13051043#ifdef NEED_GET_PATH_MAX
     
    13131051      long int x = pathconf ("/", _PC_PATH_MAX);
    13141052      if (x > 0)
    1315         value = x;
     1053        value = x;
    13161054      else
    1317         return MAXPATHLEN;
     1055        return MAXPATHLEN;
    13181056    }
    13191057
     
    13211059}
    13221060#endif
    1323 
    1324 
    1325 
    1326 /* This code is stolen from gnulib.
    1327    If/when we abandon the requirement to work with K&R compilers, we can
    1328    remove this (and perhaps other parts of GNU make!) and migrate to using
    1329    gnulib directly.
    1330 
    1331    This is called only through atexit(), which means die() has already been
    1332    invoked.  So, call exit() here directly.  Apparently that works...?
    1333 */
    1334 
    1335 /* Close standard output, exiting with status 'exit_failure' on failure.
    1336    If a program writes *anything* to stdout, that program should close
    1337    stdout and make sure that it succeeds before exiting.  Otherwise,
    1338    suppose that you go to the extreme of checking the return status
    1339    of every function that does an explicit write to stdout.  The last
    1340    printf can succeed in writing to the internal stream buffer, and yet
    1341    the fclose(stdout) could still fail (due e.g., to a disk full error)
    1342    when it tries to write out that buffered data.  Thus, you would be
    1343    left with an incomplete output file and the offending program would
    1344    exit successfully.  Even calling fflush is not always sufficient,
    1345    since some file systems (NFS and CODA) buffer written/flushed data
    1346    until an actual close call.
    1347 
    1348    Besides, it's wasteful to check the return value from every call
    1349    that writes to stdout -- just let the internal stream state record
    1350    the failure.  That's what the ferror test is checking below.
    1351 
    1352    It's important to detect such failures and exit nonzero because many
    1353    tools (most notably `make' and other build-management systems) depend
    1354    on being able to detect failure in other tools via their exit status.  */
    1355 
    1356 void
    1357 close_stdout (void)
    1358 {
    1359   int prev_fail = ferror (stdout);
    1360   int fclose_fail = fclose (stdout);
    1361 
    1362   if (prev_fail || fclose_fail)
    1363     {
    1364       if (fclose_fail)
    1365         error (NILF, _("write error: %s"), strerror (errno));
    1366       else
    1367         error (NILF, _("write error"));
    1368       exit (EXIT_FAILURE);
    1369     }
    1370 }
    13711061
    13721062#ifdef CONFIG_WITH_PRINT_STATS_SWITCH
     
    15051195  else
    15061196    {
    1507       error (NILF, _("gettimeofday failed"));
     1197      O (error, NILF, _("gettimeofday failed"));
    15081198      ts = -1;
    15091199    }
     
    15551245    }
    15561246  if (sz >= size)
    1557     fatal (NILF, _("format_elapsed_nano buffer overflow: %u written, %lu buffer"),
    1558            sz, (unsigned long)size);
     1247    ONN (fatal, NILF, _("format_elapsed_nano buffer overflow: %u written, %lu buffer"),
     1248         sz, (unsigned long)size);
    15591249  return sz;
    15601250}
    15611251#endif /* CONFIG_WITH_PRINT_TIME_SWITCH */
     1252
  • trunk/src/kmk/output.c

    r3139 r3140  
    6060    {
    6161      FILE *f = is_err ? stderr : stdout;
     62#ifdef KBUILD_OS_WINDOWS
     63      /** @todo check if fputs is also subject to char-by-char stupidity */
     64      extern size_t maybe_con_fwrite(void const *, size_t, size_t, FILE *);
     65      maybe_con_fwrite(msg, strlen(msg), 1, f);
     66#else
    6267      fputs (msg, f);
     68#endif
    6369      fflush (f);
    6470    }
  • trunk/src/kmk/po/LINGUAS

    r2591 r3140  
    1 # Set of available languages: 24 languages
     1# Set of available languages: 25 languages
    22
    3 be da de es fi fr ga gl he hr id it ja ko lt nl pl pt_BR ru sv tr uk vi zh_CN
     3be cs da de es fi fr ga gl he hr id it ja ko lt nl pl pt_BR ru sv tr uk vi zh_CN
    44
    55# Can't seem to get en@quot and en@boldquot to build properly?
  • trunk/src/kmk/po/Makevars

    r2591 r3140  
    11# This is a -*-Makefile-*-
    2 # Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free
    3 # Software Foundation, Inc.
     2# Copyright (C) 2002-2016 Free Software Foundation, Inc.
    43# This file is part of GNU Make.
    54#
  • trunk/src/kmk/po/POTFILES.in

    r2591 r3140  
    11# List of source files containing translatable strings.
    2 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    3 # 2010 Free Software Foundation, Inc.
     2# Copyright (C) 2000-2016 Free Software Foundation, Inc.
    43# This file is part of GNU Make.
    54#
     
    2524function.c
    2625getopt.c
     26guile.c
    2727hash.c
    2828implicit.c
    2929job.c
     30job.h
    3031kbuild.c
     32load.c
    3133main.c
    3234misc.c
     35output.c
     36posixos.c
    3337read.c
    3438remake.c
     
    4246vmsjobs.c
    4347vpath.c
     48w32/w32os.c
  • trunk/src/kmk/prepare_w32.bat

    r1993 r3140  
    11@echo off
    2 @echo Windows32 CVS build preparation of config.h.W32 and NMakefile.
     2@echo Windows32 SCM build preparation of config.h.W32 and NMakefile.
    33if not exist config.h.W32 copy config.h.W32.template config.h.W32
    44if not exist config.h copy config.h.W32 config.h
  • trunk/src/kmk/read.c

    r2857 r3140  
    11/* Reading and parsing of makefiles for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018
    2119#include <assert.h>
    2220
    23 #include <glob.h>
    24 
     21#include "filedef.h"
    2522#include "dep.h"
    26 #include "filedef.h"
    2723#include "job.h"
    2824#include "commands.h"
     
    3531#endif
    3632
    37 #ifndef WINDOWS32
     33#ifdef WINDOWS32
     34#include <windows.h>
     35#include "sub_proc.h"
     36#else  /* !WINDOWS32 */
    3837#ifndef _AMIGA
    3938#ifndef VMS
     
    5958    unsigned int size;  /* Malloc'd size of buffer. */
    6059    FILE *fp;           /* File, or NULL if this is an internal buffer.  */
    61     struct floc floc;   /* Info on the file in fp (if any).  */
     60    floc floc;          /* Info on the file in fp (if any).  */
    6261  };
    6362
     
    8281
    8382
    84 /* A `struct conditionals' contains the information describing
     83/* A 'struct conditionals' contains the information describing
    8584   all the active conditionals in a makefile.
    8685
    87    The global variable `conditionals' contains the conditionals
     86   The global variable 'conditionals' contains the conditionals
    8887   information for the current makefile.  It is initialized from
    89    the static structure `toplevel_conditionals' and is later changed
     88   the static structure 'toplevel_conditionals' and is later changed
    9089   to new structures for included makefiles.  */
    9190
    9291struct conditionals
    9392  {
    94     unsigned int if_cmds;       /* Depth of conditional nesting.  */
    95     unsigned int allocated;     /* Elts allocated in following arrays.  */
    96     char *ignoring;             /* Are we ignoring or interpreting?
     93    unsigned int if_cmds;       /* Depth of conditional nesting.  */
     94    unsigned int allocated;     /* Elts allocated in following arrays.  */
     95    char *ignoring;             /* Are we ignoring or interpreting?
    9796                                   0=interpreting, 1=not yet interpreted,
    9897                                   2=already interpreted */
    99     char *seen_else;            /* Have we already seen an `else'?  */
     98    char *seen_else;            /* Have we already seen an 'else'?  */
    10099#ifdef KMK
    101100    char ignoring_first[8];
     
    154153   makefile currently being read in.  */
    155154
    156 const struct floc *reading_file = 0;
    157 
    158 /* The chain of makefiles read by read_makefile.  */
    159 
    160 static struct dep *read_makefiles = 0;
    161 
    162 static int eval_makefile (const char *filename, int flags);
     155const floc *reading_file = 0;
     156
     157/* The chain of files read by read_all_makefiles.  */
     158
     159static struct goaldep *read_files = 0;
     160
     161static struct goaldep *eval_makefile (const char *filename, int flags);
    163162static void eval (struct ebuffer *buffer, int flags);
    164163
     
    169168                                   enum variable_origin origin, struct ebuffer *ebuf);
    170169#ifndef CONFIG_WITH_VALUE_LENGTH
    171 static int conditional_line (char *line, int len, const struct floc *flocp);
    172 #else
    173 static int conditional_line (char *line, char *eol, int len, const struct floc *flocp);
     170static int conditional_line (char *line, int len, const floc *flocp);
     171#else
     172static int conditional_line (char *line, char *eol, int len, const floc *flocp);
    174173#endif
    175174static void record_files (struct nameseq *filenames, const char *pattern,
     
    177176                          unsigned int cmds_started, char *commands,
    178177                          unsigned int commands_idx, int two_colon,
    179                           const struct floc *flocp);
     178                          char prefix, const floc *flocp);
    180179static void record_target_var (struct nameseq *filenames, char *defn,
    181180                               enum variable_origin origin,
    182181                               struct vmodifiers *vmod,
    183                                const struct floc *flocp);
     182                               const floc *flocp);
    184183static enum make_word_type get_next_mword (char *buffer, char *delim,
    185184                                           char **startp, unsigned int *length);
    186185#ifndef CONFIG_WITH_VALUE_LENGTH
    187186static void remove_comments (char *line);
    188 static char *find_char_unquote (char *string, int stop1, int stop2,
    189                                 int blank, int ignorevars);
    190 #else  /* CONFIG_WITH_VALUE_LENGTH */
    191 __inline static char *remove_comments (char *line, char *eol);
    192 __inline static char *find_char_unquote_0 (char *string, int stop1, char **eosp);
    193 static char * find_char_unquote_2 (char *string, int stop1, int stop2,
    194                                    int blank, int ignorevars,
    195                                    unsigned int string_len);
    196 MY_INLINE char *
    197 find_char_unquote (char *string, int stop1, int stop2, int blank, int ignorevars)
    198 {
    199     if (!stop2 && !blank && !ignorevars)
    200       {
    201         char *p = strchr (string, stop1);
    202         if (!p)
    203           return NULL;
    204         if (p <= string || p[-1] != '\\')
    205           return p;
    206         /* fall back on find_char_unquote_2 */
    207       }
    208     return find_char_unquote_2 (string, stop1, stop2, blank, ignorevars, 0);
    209 }
     187static char *find_char_unquote (char *string, int map);
     188#else /* CONFIG_WITH_VALUE_LENGTH */
     189static char *remove_comments (char *line, char *eos);
     190static char *find_char_unquote (char *string, int map, unsigned int string_len);
     191K_INLINE char *find_char_unquote_0 (char *string, int stop1, int map, char **eosp);
    210192#endif /* CONFIG_WITH_VALUE_LENGTH */
     193static char *unescape_char (char *string, int c);
    211194
    212195
     
    214197   P must point to the word to be tested, and WLEN must be the length.
    215198*/
    216 #define word1eq(s)      (wlen == sizeof(s)-1 && strneq (s, p, sizeof(s)-1))
    217 
    218 
    219 
    220 /* Read in all the makefiles and return the chain of their names.  */
    221 
    222 struct dep *
     199#define word1eq(s)      (wlen == CSTRLEN (s) && strneq (s, p, CSTRLEN (s)))
     200
     201
     202
     203/* Read in all the makefiles and return a chain of targets to rebuild.  */
     204
     205struct goaldep *
    223206read_all_makefiles (const char **makefiles)
    224207{
     
    261244    while ((name = find_next_token ((const char **)&p, &length)) != 0)
    262245      {
    263         if (*p != '\0')
    264           *p++ = '\0';
    265         eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
     246        if (*p != '\0')
     247          *p++ = '\0';
     248        eval_makefile (name, RM_NO_DEFAULT_GOAL|RM_INCLUDED|RM_DONTCARE);
    266249      }
    267250
     
    274257    while (*makefiles != 0)
    275258      {
    276         struct dep *tail = read_makefiles;
    277         register struct dep *d;
    278 
    279         if (! eval_makefile (*makefiles, 0))
    280           perror_with_name ("", *makefiles);
    281 
    282         /* Find the right element of read_makefiles.  */
    283         d = read_makefiles;
    284         while (d->next != tail)
    285           d = d->next;
    286 
    287         /* Use the storage read_makefile allocates.  */
    288         *makefiles = dep_name (d);
    289         ++num_makefiles;
    290         ++makefiles;
     259        struct goaldep *d = eval_makefile (*makefiles, 0);
     260
     261        if (errno)
     262          perror_with_name ("", *makefiles);
     263
     264        /* Reuse the storage allocated for the read_file.  */
     265        *makefiles = dep_name (d);
     266        ++num_makefiles;
     267        ++makefiles;
    291268      }
    292269
     
    295272  if (num_makefiles == 0)
    296273    {
    297       static char *default_makefiles[] =
     274      static const char *default_makefiles[] =
    298275#ifdef VMS
    299         /* all lower case since readdir() (the vms version) 'lowercasifies' */
     276        /* all lower case since readdir() (the vms version) 'lowercasifies' */
     277        /* TODO: Above is not always true, this needs more work */
    300278# ifdef KMK
    301         { "makefile.kmk", "makefile.vms", "gnumakefile.", "makefile.", 0 };
     279        { "makefile.kmk", "makefile.vms", "gnumakefile.", "makefile.", 0 };
    302280# else
    303         { "makefile.vms", "gnumakefile.", "makefile.", 0 };
     281        { "makefile.vms", "gnumakefile", "makefile", 0 };
    304282# endif
    305283#else
    306284#ifdef _AMIGA
    307         /* what's the deal here? no dots? */
    308285# ifdef KMK
    309         { "Makefile.kmk", "makefile.kmk", "GNUmakefile", "Makefile", "SMakefile", 0 };
     286        { "Makefile.kmk", "makefile.kmk", "GNUmakefile", "Makefile", "SMakefile", 0 };
    310287# else
    311         { "GNUmakefile", "Makefile", "SMakefile", 0 };
     288        { "GNUmakefile", "Makefile", "SMakefile", 0 };
    312289# endif
    313290#else /* !Amiga && !VMS */
     291#ifdef WINDOWS32
    314292# ifdef KMK
    315         { "Makefile.kmk", "makefile.kmk", "GNUmakefile", "makefile", "Makefile", 0 };
     293        { "Makefile.kmk", "makefile.kmk", "GNUmakefile", "makefile", "Makefile", "makefile.mak", 0 };
    316294# else
    317         { "GNUmakefile", "makefile", "Makefile", 0 };
     295        { "GNUmakefile", "makefile", "Makefile", "makefile.mak", 0 };
     296# endif       
     297#else /* !Amiga && !VMS && !WINDOWS32 */
     298# ifdef KMK
     299        { "Makefile.kmk", "makefile.kmk", "GNUmakefile", "makefile", "Makefile", 0 };
     300# else
     301        { "GNUmakefile", "makefile", "Makefile", 0 };
    318302# endif
     303#endif /* !Amiga && !VMS && !WINDOWS32 */
    319304#endif /* AMIGA */
    320305#endif /* VMS */
    321       register char **p = default_makefiles;
     306      const char **p = default_makefiles;
    322307      while (*p != 0 && !file_exists_p (*p))
    323         ++p;
     308        ++p;
    324309
    325310      if (*p != 0)
    326         {
    327           if (! eval_makefile (*p, 0))
    328             perror_with_name ("", *p);
    329         }
     311        {
     312          eval_makefile (*p, 0);
     313          if (errno)
     314            perror_with_name ("", *p);
     315        }
    330316      else
    331         {
    332           /* No default makefile was found.  Add the default makefiles to the
    333              `read_makefiles' chain so they will be updated if possible.  */
    334           struct dep *tail = read_makefiles;
    335           /* Add them to the tail, after any MAKEFILES variable makefiles.  */
    336           while (tail != 0 && tail->next != 0)
    337             tail = tail->next;
    338           for (p = default_makefiles; *p != 0; ++p)
    339             {
    340               struct dep *d = alloc_dep ();
    341               d->file = enter_file (strcache_add (*p));
    342               d->dontcare = 1;
    343               /* Tell update_goal_chain to bail out as soon as this file is
    344                  made, and main not to die if we can't make this file.  */
    345               d->changed = RM_DONTCARE;
    346               if (tail == 0)
    347                 read_makefiles = d;
    348               else
    349                 tail->next = d;
    350               tail = d;
    351             }
    352           if (tail != 0)
    353             tail->next = 0;
    354         }
     317        {
     318          /* No default makefile was found.  Add the default makefiles to the
     319             'read_files' chain so they will be updated if possible.  */
     320          struct goaldep *tail = read_files;
     321          /* Add them to the tail, after any MAKEFILES variable makefiles.  */
     322          while (tail != 0 && tail->next != 0)
     323            tail = tail->next;
     324          for (p = default_makefiles; *p != 0; ++p)
     325            {
     326              struct goaldep *d = alloc_goaldep ();
     327              d->file = enter_file (strcache_add (*p));
     328              /* Tell update_goal_chain to bail out as soon as this file is
     329                 made, and main not to die if we can't make this file.  */
     330              d->flags = RM_DONTCARE;
     331              if (tail == 0)
     332                read_files = d;
     333              else
     334                tail->next = d;
     335              tail = d;
     336            }
     337          if (tail != 0)
     338            tail->next = 0;
     339        }
    355340    }
    356341
    357   return read_makefiles;
     342  return read_files;
    358343}
    359344
     
    386371  /* Free any space allocated by conditional_line.  */
    387372#ifdef KMK
    388   if (conditionals->allocated > sizeof (conditionals->ignoring_first))
    389 #endif
    390     {
    391       if (conditionals->ignoring)
    392         free (conditionals->ignoring);
    393       if (conditionals->seen_else)
    394         free (conditionals->seen_else);
    395     }
     373 if (conditionals->allocated > sizeof (conditionals->ignoring_first))
     374 {
     375#endif
     376  free (conditionals->ignoring);
     377  free (conditionals->seen_else);
     378#ifdef KMK
     379 }
     380#endif
    396381
    397382  /* Restore state.  */
     
    400385
    401386
    402 static int
     387static struct goaldep *
    403388eval_makefile (const char *filename, int flags)
    404389{
    405   struct dep *deps;
     390  struct goaldep *deps;
    406391  struct ebuffer ebuf;
    407   const struct floc *curfile;
     392  const floc *curfile;
    408393  char *expanded = 0;
    409394  int makefile_errno;
    410395
    411   filename = strcache_add (filename);
    412   ebuf.floc.filenm = filename;
     396  ebuf.floc.filenm = filename; /* Use the original file name.  */
    413397  ebuf.floc.lineno = 1;
     398  ebuf.floc.offset = 0;
    414399
    415400  if (ISDB (DB_VERBOSE))
    416401    {
    417       printf (_("Reading makefile `%s'"), filename);
     402      printf (_("Reading makefile '%s'"), filename);
    418403      if (flags & RM_NO_DEFAULT_GOAL)
    419         printf (_(" (no default goal)"));
     404        printf (_(" (no default goal)"));
    420405      if (flags & RM_INCLUDED)
    421         printf (_(" (search path)"));
     406        printf (_(" (search path)"));
    422407      if (flags & RM_DONTCARE)
    423         printf (_(" (don't care)"));
     408        printf (_(" (don't care)"));
    424409      if (flags & RM_NO_TILDE)
    425         printf (_(" (no ~ expansion)"));
     410        printf (_(" (no ~ expansion)"));
    426411      puts ("...");
    427412    }
     
    429414  /* First, get a stream to read.  */
    430415
    431   /* Expand ~ in FILENAME unless it came from `include',
     416  /* Expand ~ in FILENAME unless it came from 'include',
    432417     in which case it was already done.  */
    433418  if (!(flags & RM_NO_TILDE) && filename[0] == '~')
     
    435420      expanded = tilde_expand (filename);
    436421      if (expanded != 0)
    437         filename = expanded;
     422        filename = expanded;
    438423    }
    439424
    440   ebuf.fp = fopen (filename, "r");
     425  ENULLLOOP (ebuf.fp, fopen (filename, "r"));
     426
    441427  /* Save the error code so we print the right message later.  */
    442428  makefile_errno = errno;
    443429
     430  /* Check for unrecoverable errors: out of mem or FILE slots.  */
     431  switch (makefile_errno)
     432    {
     433#ifdef EMFILE
     434    case EMFILE:
     435#endif
     436#ifdef ENFILE
     437    case ENFILE:
     438#endif
     439    case ENOMEM:
     440      {
     441        const char *err = strerror (makefile_errno);
     442        OS (fatal, reading_file, "%s", err);
     443      }
     444    }
     445
    444446  /* If the makefile wasn't found and it's either a makefile from
    445      the `MAKEFILES' variable or an included makefile,
     447     the 'MAKEFILES' variable or an included makefile,
    446448     search the included makefile search path for this makefile.  */
    447449  if (ebuf.fp == 0 && (flags & RM_INCLUDED) && *filename != '/')
     
    449451      unsigned int i;
    450452      for (i = 0; include_directories[i] != 0; ++i)
    451         {
    452           const char *included = concat (3, include_directories[i],
     453        {
     454          const char *included = concat (3, include_directories[i],
    453455                                         "/", filename);
    454           ebuf.fp = fopen (included, "r");
    455           if (ebuf.fp)
    456             {
    457               filename = strcache_add (included);
    458               break;
    459             }
    460         }
     456          ebuf.fp = fopen (included, "r");
     457          if (ebuf.fp)
     458            {
     459              filename = included;
     460              break;
     461            }
     462        }
    461463    }
    462464
     465  /* Now we have the final name for this makefile. Enter it into
     466     the cache.  */
     467  filename = strcache_add (filename);
     468
    463469  /* Add FILENAME to the chain of read makefiles.  */
    464   deps = alloc_dep ();
    465   deps->next = read_makefiles;
    466   read_makefiles = deps;
     470  deps = alloc_goaldep ();
     471  deps->next = read_files;
     472  read_files = deps;
    467473#ifndef CONFIG_WITH_STRCACHE2
    468474  deps->file = lookup_file (filename);
     
    473479    deps->file = enter_file (filename);
    474480  filename = deps->file->name;
    475   deps->changed = flags;
    476   if (flags & RM_DONTCARE)
    477     deps->dontcare = 1;
    478 
    479   if (expanded)
    480     free (expanded);
     481  deps->flags = flags;
     482
     483  free (expanded);
    481484
    482485  /* If the makefile can't be found at all, give up entirely.  */
     
    485488    {
    486489      /* If we did some searching, errno has the error from the last
    487          attempt, rather from FILENAME itself.  Restore it in case the
    488         caller wants to use it in a message.  */
     490         attempt, rather from FILENAME itself.  Store it in case the
     491        caller wants to use it in a message.  */
    489492      errno = makefile_errno;
    490       return 0;
     493      return deps;
    491494    }
    492495
     
    576579  alloca (0);
    577580
    578   return 1;
     581  errno = 0;
     582  return deps;
    579583}
    580584
    581585void
    582 #ifndef CONFIG_WITH_VALUE_LENGTH
    583 eval_buffer (char *buffer)
    584 #else
    585 eval_buffer (char *buffer, char *eos)
    586 #endif
     586eval_buffer (char *buffer, const floc *flocp IF_WITH_VALUE_LENGTH_PARAM(char *eos))
    587587{
    588588  struct ebuffer ebuf;
    589589  struct conditionals *saved;
    590590  struct conditionals new;
    591   const struct floc *curfile;
     591  const floc *curfile;
    592592
    593593  /* Evaluate the buffer */
     
    603603  ebuf.fp = NULL;
    604604
    605   if (reading_file)
     605  if (flocp)
     606    ebuf.floc = *flocp;
     607  else if (reading_file)
    606608    ebuf.floc = *reading_file;
    607609  else
    608     ebuf.floc.filenm = NULL;
     610    {
     611      ebuf.floc.filenm = NULL;
     612      ebuf.floc.lineno = 1;
     613      ebuf.floc.offset = 0;
     614    }
    609615
    610616  curfile = reading_file;
     
    641647
    642648  /* Find the start of the next token.  If there isn't one we're done.  */
    643   line = next_token (line);
     649  NEXT_TOKEN (line);
    644650  if (*line == '\0')
    645651    return (char *)line;
     
    650656      int wlen;
    651657      const char *p2;
    652       enum variable_flavor flavor;
    653 
    654       p2 = parse_variable_definition (p, &flavor);
     658      struct variable v;
     659
     660      p2 = parse_variable_definition (p, &v);
    655661
    656662      /* If this is a variable assignment, we're done.  */
     
    713719  unsigned int cmds_started, tgts_started;
    714720  int ignoring = 0, in_ignored_define = 0;
    715   int no_targets = 0;           /* Set when reading a rule without targets.  */
     721  int no_targets = 0;           /* Set when reading a rule without targets.  */
    716722  struct nameseq *filenames = 0;
    717723  char *depstr = 0;
    718724  long nlines = 0;
    719725  int two_colon = 0;
     726  char prefix = cmd_prefix;
    720727  const char *pattern = 0;
    721728  const char *pattern_percent;
    722   struct floc *fstart;
    723   struct floc fi;
     729  floc *fstart;
     730  floc fi;
    724731#ifdef CONFIG_WITH_VALUE_LENGTH
    725732  unsigned int tmp_len;
     
    730737#endif
    731738
    732 #define record_waiting_files()                                                \
    733   do                                                                          \
    734     {                                                                         \
    735       if (filenames != 0)                                                     \
     739#define record_waiting_files()                                                \
     740  do                                                                          \
     741    {                                                                         \
     742      if (filenames != 0)                                                     \
    736743        {                                                                     \
    737           fi.lineno = tgts_started;                                           \
    738           record_files (filenames, pattern, pattern_percent, depstr,          \
     744          fi.lineno = tgts_started;                                           \
     745          fi.offset = 0;                                                      \
     746          record_files (filenames, pattern, pattern_percent, depstr,          \
    739747                        cmds_started, commands, commands_idx, two_colon,      \
    740                         &fi);                                                 \
    741           filenames = 0;                                                      \
     748                        prefix, &fi);                                         \
     749          filenames = 0;                                                      \
    742750        }                                                                     \
    743       commands_idx = 0;                                                       \
     751      commands_idx = 0;                                                       \
    744752      no_targets = 0;                                                         \
    745753      pattern = 0;                                                            \
     
    758766
    759767     When you see a "continue" in the loop below, that means we are moving on
    760      to the next line _without_ ending any rule that we happen to be working
    761      with at the moment.  If you see a "goto rule_complete", then the
    762      statement we just parsed also finishes the previous rule.  */
     768     to the next line.  If you see record_waiting_files(), then the statement
     769     we are parsing also finishes the previous rule.  */
    763770
    764771  commands = xmalloc (200);
     
    785792        break;
    786793
     794      line = ebuf->buffer;
     795
     796      /* If this is the first line, check for a UTF-8 BOM and skip it.  */
     797      if (ebuf->floc.lineno == 1 && line[0] == (char)0xEF
     798          && line[1] == (char)0xBB && line[2] == (char)0xBF)
     799        {
     800          line += 3;
     801          if (ISDB(DB_BASIC))
     802            {
     803              if (ebuf->floc.filenm)
     804                printf (_("Skipping UTF-8 BOM in makefile '%s'\n"),
     805                        ebuf->floc.filenm);
     806              else
     807                printf (_("Skipping UTF-8 BOM in makefile buffer\n"));
     808            }
     809        }
     810
    787811      /* If this line is empty, skip it.  */
    788       line = ebuf->buffer;
    789812      if (line[0] == '\0')
    790813        continue;
     
    798821
    799822      /* Check for a shell command line first.
    800          If it is not one, we can stop treating tab specially.  */
     823         If it is not one, we can stop treating cmd_prefix specially.  */
    801824      if (line[0] == cmd_prefix)
    802         {
    803           if (no_targets)
    804             /* Ignore the commands in a rule with no targets.  */
    805             continue;
    806 
    807           /* If there is no preceding rule line, don't treat this line
    808              as a command, even though it begins with a recipe prefix.
    809              SunOS 4 make appears to behave this way.  */
    810 
    811           if (filenames != 0)
    812             {
    813               if (ignoring)
    814                 /* Yep, this is a shell command, and we don't care.  */
    815                 continue;
    816 
    817               /* Append this command line to the line being accumulated.
    818                  Strip command prefix chars that appear after newlines.  */
    819               if (commands_idx == 0)
    820                 cmds_started = ebuf->floc.lineno;
    821 
    822               if (linelen + commands_idx > commands_len)
    823                 {
    824                   commands_len = (linelen + commands_idx) * 2;
    825                   commands = xrealloc (commands, commands_len);
    826                 }
    827               p = &commands[commands_idx];
    828               p2 = line + 1;
    829               while (--linelen)
     825        {
     826          if (no_targets)
     827            /* Ignore the commands in a rule with no targets.  */
     828            continue;
     829
     830          /* If there is no preceding rule line, don't treat this line
     831             as a command, even though it begins with a recipe prefix.
     832             SunOS 4 make appears to behave this way.  */
     833
     834          if (filenames != 0)
     835            {
     836              if (ignoring)
     837                /* Yep, this is a shell command, and we don't care.  */
     838                continue;
     839
     840              if (commands_idx == 0)
     841                cmds_started = ebuf->floc.lineno;
     842
     843              /* Append this command line to the line being accumulated.
     844                 Skip the initial command prefix character.  */
     845              if (linelen + commands_idx > commands_len)
    830846                {
    831                   ++commands_idx;
    832                   *(p++) = *p2;
    833                   if (p2[0] == '\n' && p2[1] == cmd_prefix)
    834                     {
    835                       ++p2;
    836                       --linelen;
    837                     }
    838                   ++p2;
     847                  commands_len = (linelen + commands_idx) * 2;
     848                  commands = xrealloc (commands, commands_len);
    839849                }
    840               *p = '\n';
    841               ++commands_idx;
    842 
    843               continue;
    844             }
    845         }
     850              memcpy (&commands[commands_idx], line + 1, linelen - 1);
     851              commands_idx += linelen - 1;
     852              commands[commands_idx++] = '\n';
     853              continue;
     854            }
     855        }
    846856
    847857      /* This line is not a shell command line.  Don't worry about whitespace.
     
    850860
    851861      if (collapsed_length < linelen+1)
    852         {
    853           collapsed_length = linelen+1;
    854           if (collapsed)
    855             free (collapsed);
     862        {
     863          collapsed_length = linelen+1;
     864          free (collapsed);
    856865          /* Don't need xrealloc: we don't need to preserve the content.  */
    857           collapsed = xmalloc (collapsed_length);
    858         }
     866          collapsed = xmalloc (collapsed_length);
     867        }
    859868#ifndef CONFIG_WITH_VALUE_LENGTH
    860869      strcpy (collapsed, line);
     
    873882      /* Get rid if starting space (including formfeed, vtab, etc.)  */
    874883      p = collapsed;
    875       while (isspace ((unsigned char)*p))
    876         ++p;
     884      NEXT_TOKEN (p);
    877885
    878886      /* See if this is a variable assignment.  We need to do this early, to
    879887         allow variables with names like 'ifdef', 'export', 'private', etc.  */
    880       p = parse_var_assignment(p, &vmod);
     888      p = parse_var_assignment (p, &vmod);
    881889      if (vmod.assign_v)
    882890        {
     
    885893
    886894          /* If we're ignoring then we're done now.  */
    887           if (ignoring)
     895          if (ignoring)
    888896            {
    889897              if (vmod.define_v)
     
    892900            }
    893901
     902          /* Variable assignment ends the previous rule.  */
     903          record_waiting_files ();
     904
    894905          if (vmod.undefine_v)
    895906          {
    896907            do_undefine (p, origin, ebuf);
    897 
    898             /* This line has been dealt with.  */
    899             goto rule_complete;
     908            continue;
    900909          }
    901910          else if (vmod.define_v)
     
    912921
    913922          /* This line has been dealt with.  */
    914           goto rule_complete;
     923          continue;
    915924        }
    916925
    917926      /* If this line is completely empty, ignore it.  */
    918927      if (*p == '\0')
    919         continue;
     928        continue;
    920929
    921930      p2 = end_of_token (p);
    922931      wlen = p2 - p;
    923       p2 = next_token (p2);
     932      NEXT_TOKEN (p2);
    924933
    925934      /* If we're in an ignored define, skip this line (but maybe get out).  */
    926935      if (in_ignored_define)
    927         {
     936        {
    928937          /* See if this is an endef line (plus optional comment).  */
    929           if (word1eq ("endef") && (*p2 == '\0' || *p2 == '#'))
     938          if (word1eq ("endef") && STOP_SET (*p2, MAP_COMMENT|MAP_NUL))
    930939            in_ignored_define = 0;
    931940
    932           continue;
    933         }
     941          continue;
     942        }
    934943
    935944      /* Check for conditional state changes.  */
     
    943952          {
    944953            if (i == -1)
    945               fatal (fstart, _("invalid syntax in conditional"));
     954              O (fatal, fstart, _("invalid syntax in conditional"));
    946955
    947956            ignoring = i;
     
    952961      /* Nothing to see here... move along.  */
    953962      if (ignoring)
    954         continue;
     963        continue;
    955964
    956965#ifdef CONFIG_WITH_LOCAL_VARIABLES
     
    958967        {
    959968          if (*p2 == '\0')
    960             error (fstart, _("empty `local' directive"));
     969            O (error, fstart, _("empty `local' directive"));
    961970
    962971          if (strneq (p2, "define", 6)
    963               && (isblank ((unsigned char)p2[6]) || p2[6] == '\0'))
     972              && (ISBLANK (p2[6]) || p2[6] == '\0'))
    964973            {
    965974              if (ignoring)
     
    969978                  p2 = next_token (p2 + 6);
    970979                  if (*p2 == '\0')
    971                     fatal (fstart, _("empty variable name"));
     980                    O (fatal, fstart, _("empty variable name"));
    972981
    973982                  /* Let the variable name be the whole rest of the line,
     
    976985                     reference that might contain blanks.  */
    977986                  p = strchr (p2, '\0');
    978                   while (isblank ((unsigned char)p[-1]))
     987                  while (ISBLANK (p[-1]))
    979988                    --p;
    980989                  do_define (p2 IF_WITH_VALUE_LENGTH_PARAM(p), o_local, ebuf);
     
    983992          else if (!ignoring
    984993                   && !try_variable_definition (fstart, p2 IF_WITH_VALUE_LENGTH_PARAM(eol), o_local, 0))
    985             error (fstart, _("invalid `local' directive"));
     994            O (error, fstart, _("invalid `local' directive"));
    986995
    987996          continue;
     
    9981007            {
    9991008              if (krc != 0)
    1000                 error (fstart, _("krc=%d"), krc);
     1009                ON (error, fstart, _("krc=%d"), krc);
    10011010              continue;
    10021011            }
     
    10071016         as well as "unexport".  */
    10081017      if (word1eq ("export") || word1eq ("unexport"))
    1009         {
     1018        {
    10101019          int exporting = *p == 'u' ? 0 : 1;
    10111020
     1021          /* Export/unexport ends the previous rule.  */
     1022          record_waiting_files ();
     1023
    10121024          /* (un)export by itself causes everything to be (un)exported. */
    1013           if (*p2 == '\0')
     1025          if (*p2 == '\0')
    10141026            export_all_variables = exporting;
    10151027          else
     
    10331045                  struct variable *v = lookup_variable (p, l);
    10341046                  if (v == 0)
    1035                     v = define_variable_loc (p, l, "", o_file, 0, fstart);
     1047                    v = define_variable_global (p, l, "", o_file, 0, fstart);
    10361048                  v->export = exporting ? v_export : v_noexport;
    10371049                }
     
    10431055#endif
    10441056            }
    1045           goto rule_complete;
    1046         }
     1057          continue;
     1058        }
    10471059
    10481060      /* Handle the special syntax for vpath.  */
    10491061      if (word1eq ("vpath"))
    1050         {
     1062        {
    10511063          const char *cp;
    1052           char *vpat;
    1053           unsigned int l;
    1054           cp = variable_expand (p2);
    1055           p = find_next_token (&cp, &l);
    1056           if (p != 0)
    1057             {
    1058               vpat = xstrndup (p, l);
    1059               p = find_next_token (&cp, &l);
    1060               /* No searchpath means remove all previous
    1061                  selective VPATH's with the same pattern.  */
    1062             }
    1063           else
    1064             /* No pattern means remove all previous selective VPATH's.  */
    1065             vpat = 0;
    1066           construct_vpath_list (vpat, p);
    1067           if (vpat != 0)
    1068             free (vpat);
    1069 
    1070           goto rule_complete;
    1071         }
     1064          char *vpat;
     1065          unsigned int l;
     1066
     1067          /* vpath ends the previous rule.  */
     1068          record_waiting_files ();
     1069
     1070          cp = variable_expand (p2);
     1071          p = find_next_token (&cp, &l);
     1072          if (p != 0)
     1073            {
     1074              vpat = xstrndup (p, l);
     1075              p = find_next_token (&cp, &l);
     1076              /* No searchpath means remove all previous
     1077                 selective VPATH's with the same pattern.  */
     1078            }
     1079          else
     1080            /* No pattern means remove all previous selective VPATH's.  */
     1081            vpat = 0;
     1082          construct_vpath_list (vpat, p);
     1083          free (vpat);
     1084
     1085          continue;
     1086        }
    10721087
    10731088#ifdef CONFIG_WITH_INCLUDEDEP
     
    10921107              free_me = name = allocated_variable_expand_3 (name, eol - name, &name_len, &buf_len);
    10931108              eol = name + name_len;
    1094               while (isspace ((unsigned char)*name))
     1109              while (ISSPACE (*name))
    10951110                ++name;
    10961111            }
    10971112
    1098           while (eol > name && isspace ((unsigned char)eol[-1]))
     1113          while (eol > name && ISSPACE (eol[-1]))
    10991114            --eol;
    11001115
     
    11041119          if (free_me)
    11051120            recycle_variable_buffer (free_me, buf_len);
    1106           goto rule_complete;
     1121          continue;
    11071122        }
    11081123#endif /* CONFIG_WITH_INCLUDEDEP */
     
    11101125      /* Handle include and variants.  */
    11111126      if (word1eq ("include") || word1eq ("-include") || word1eq ("sinclude"))
    1112         {
    1113           /* We have found an `include' line specifying a nested
    1114              makefile to be read at this point.  */
    1115           struct conditionals *save;
     1127        {
     1128          /* We have found an 'include' line specifying a nested
     1129             makefile to be read at this point.  */
     1130          struct conditionals *save;
    11161131          struct conditionals new_conditionals;
    1117           struct nameseq *files;
    1118           /* "-include" (vs "include") says no error if the file does not
    1119              exist.  "sinclude" is an alias for this from SGI.  */
    1120           int noerror = (p[0] != 'i');
     1132          struct nameseq *files;
     1133          /* "-include" (vs "include") says no error if the file does not
     1134             exist.  "sinclude" is an alias for this from SGI.  */
     1135          int noerror = (p[0] != 'i');
     1136#ifdef CONFIG_WITH_VALUE_LENGTH
     1137          unsigned int buf_len;
     1138#endif
     1139
     1140          /* Include ends the previous rule.  */
     1141          record_waiting_files ();
    11211142
    11221143#ifndef CONFIG_WITH_VALUE_LENGTH
    1123           p = allocated_variable_expand (p2);
    1124 #else
    1125           unsigned int buf_len;
     1144          p = allocated_variable_expand (p2);
     1145#else
    11261146          p = allocated_variable_expand_3 (p2, eol - p2, NULL, &buf_len);
    11271147#endif
    11281148
     1149
    11291150          /* If no filenames, it's a no-op.  */
    1130           if (*p == '\0')
     1151          if (*p == '\0')
    11311152            {
    11321153#ifndef CONFIG_WITH_VALUE_LENGTH
     
    11381159            }
    11391160
    1140           /* Parse the list of file names.  Don't expand archive references!  */
    1141           p2 = p;
    1142           files = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL,
     1161          /* Parse the list of file names.  Don't expand archive references!  */
     1162          p2 = p;
     1163          files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
    11431164                                  PARSEFS_NOAR);
    11441165#ifndef CONFIG_WITH_VALUE_LENGTH
    1145           free (p);
     1166          free (p);
    11461167#else
    11471168          recycle_variable_buffer (p, buf_len);
    11481169#endif
    11491170
    1150           /* Save the state of conditionals and start
    1151              the included makefile with a clean slate.  */
    1152           save = install_conditionals (&new_conditionals);
    1153 
    1154           /* Record the rules that are waiting so they will determine
    1155              the default goal before those in the included makefile.  */
    1156           record_waiting_files ();
    1157 
    1158           /* Read each included makefile.  */
    1159           while (files != 0)
    1160             {
    1161               struct nameseq *next = files->next;
    1162               const char *name = files->name;
     1171          /* Save the state of conditionals and start
     1172             the included makefile with a clean slate.  */
     1173          save = install_conditionals (&new_conditionals);
     1174
     1175          /* Record the rules that are waiting so they will determine
     1176             the default goal before those in the included makefile.  */
     1177          record_waiting_files ();
     1178
     1179          /* Read each included makefile.  */
     1180          while (files != 0)
     1181            {
     1182              struct nameseq *next = files->next;
     1183              int flags = (RM_INCLUDED | RM_NO_TILDE
     1184                           | (noerror ? RM_DONTCARE : 0)
     1185                           | (set_default ? 0 : RM_NO_DEFAULT_GOAL));
     1186
     1187              struct goaldep *d = eval_makefile (files->name, flags);
     1188
     1189              if (errno)
     1190                {
     1191                  d->error = (unsigned short)errno;
     1192                  d->floc = *fstart;
     1193                }
     1194
     1195              free_ns (files);
     1196              files = next;
     1197            }
     1198
     1199          /* Restore conditional state.  */
     1200          restore_conditionals (save);
     1201
     1202          continue;
     1203        }
     1204
     1205      /* Handle the load operations.  */
     1206      if (word1eq ("load") || word1eq ("-load"))
     1207        {
     1208          /* A 'load' line specifies a dynamic object to load.  */
     1209          struct nameseq *files;
     1210          int noerror = (p[0] == '-');
     1211
     1212          /* Load ends the previous rule.  */
     1213          record_waiting_files ();
     1214
     1215          p = allocated_variable_expand (p2);
     1216
     1217          /* If no filenames, it's a no-op.  */
     1218          if (*p == '\0')
     1219            {
     1220              free (p);
     1221              continue;
     1222            }
     1223
     1224          /* Parse the list of file names.
     1225             Don't expand archive references or strip "./"  */
     1226          p2 = p;
     1227          files = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_NUL, NULL,
     1228                                  PARSEFS_NOAR);
     1229          free (p);
     1230
     1231          /* Load each file.  */
     1232          while (files != 0)
     1233            {
     1234              struct nameseq *next = files->next;
     1235              const char *name = files->name;
     1236              struct goaldep *deps;
    11631237              int r;
    11641238
    1165               free_ns (files);
    1166               files = next;
    1167 
    1168               r = eval_makefile (name,
    1169                                  (RM_INCLUDED | RM_NO_TILDE
    1170                                   | (noerror ? RM_DONTCARE : 0)
    1171                                   | (set_default ? 0 : RM_NO_DEFAULT_GOAL)));
    1172               if (!r && !noerror)
    1173                 error (fstart, "%s: %s", name, strerror (errno));
    1174             }
    1175 
    1176           /* Restore conditional state.  */
    1177           restore_conditionals (save);
    1178 
    1179           goto rule_complete;
    1180         }
     1239              /* Load the file.  0 means failure.  */
     1240              r = load_file (&ebuf->floc, &name, noerror);
     1241              if (! r && ! noerror)
     1242                OS (fatal, &ebuf->floc, _("%s: failed to load"), name);
     1243
     1244              free_ns (files);
     1245              files = next;
     1246
     1247              /* Return of -1 means a special load: don't rebuild it.  */
     1248              if (r == -1)
     1249                continue;
     1250
     1251              /* It succeeded, so add it to the list "to be rebuilt".  */
     1252              deps = alloc_goaldep ();
     1253              deps->next = read_files;
     1254              read_files = deps;
     1255              deps->file = lookup_file (name);
     1256              if (deps->file == 0)
     1257                deps->file = enter_file (name);
     1258              deps->file->loaded = 1;
     1259            }
     1260
     1261          continue;
     1262        }
    11811263
    11821264      /* This line starts with a tab but was not caught above because there
     
    11841266         variable definition.  But now we know it is definitely lossage.  */
    11851267      if (line[0] == cmd_prefix)
    1186         fatal(fstart, _("recipe commences before first target"));
     1268        O (fatal, fstart, _("recipe commences before first target"));
    11871269
    11881270      /* This line describes some target files.  This is complicated by
    11891271         the existence of target-specific variables, because we can't
    11901272         expand the entire line until we know if we have one or not.  So
    1191          we expand the line word by word until we find the first `:',
     1273         we expand the line word by word until we find the first ':',
    11921274         then check to see if it's a target-specific variable.
    11931275
    1194          In this algorithm, `lb_next' will point to the beginning of the
    1195          unexpanded parts of the input buffer, while `p2' points to the
     1276         In this algorithm, 'lb_next' will point to the beginning of the
     1277         unexpanded parts of the input buffer, while 'p2' points to the
    11961278         parts of the expanded buffer we haven't searched yet. */
    11971279
     
    12101292        /* Search the line for an unquoted ; that is not after an
    12111293           unquoted #.  */
    1212 #ifndef CONFIG_WITH_VALUE_LENGTH
    1213         cmdleft = find_char_unquote (line, ';', '#', 0, 1);
    1214 #else
    1215         cmdleft = find_char_unquote_2 (line, ';', '#', 0, 1, ebuf->eol - line);
    1216 #endif
     1294        cmdleft = find_char_unquote (line, MAP_SEMI|MAP_COMMENT|MAP_VARIABLE IF_WITH_VALUE_LENGTH_PARAM(ebuf->eol - line));
    12171295        if (cmdleft != 0 && *cmdleft == '#')
    12181296          {
     
    12361314           beginning, expanding as we go, and looking for "interesting"
    12371315           chars.  The first word is always expandable.  */
    1238         wtype = get_next_mword(line, NULL, &lb_next, &wlen);
     1316        wtype = get_next_mword (line, NULL, &lb_next, &wlen);
    12391317        switch (wtype)
    12401318          {
    12411319          case w_eol:
    12421320            if (cmdleft != 0)
    1243               fatal(fstart, _("missing rule before recipe"));
     1321              O (fatal, fstart, _("missing rule before recipe"));
    12441322            /* This line contained something but turned out to be nothing
    12451323               but whitespace (a comment?).  */
     
    12571335          }
    12581336
    1259 
    12601337#ifndef CONFIG_WITH_VALUE_LENGTH
    1261         p2 = variable_expand_string(NULL, lb_next, wlen);
     1338        p2 = variable_expand_string (NULL, lb_next, wlen);
    12621339#else
    12631340        p2 = variable_expand_string_2 (NULL, lb_next, wlen, &eol);
     
    12721349                /* Look for a semicolon in the expanded line.  */
    12731350#ifndef CONFIG_WITH_VALUE_LENGTH
    1274                 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
    1275 #else
    1276                 cmdleft = find_char_unquote_0 (p2, ';', &eol);
     1351                cmdleft = find_char_unquote (p2, MAP_SEMI);
     1352#else
     1353                cmdleft = find_char_unquote_0 (p2, ';', MAP_SEMI, &eol);
    12771354#endif
    12781355
     
    12821359                    unsigned long cmd_off = cmdleft - variable_buffer;
    12831360#ifndef CONFIG_WITH_VALUE_LENGTH
    1284                     char *pend = p2 + strlen(p2);
     1361                    char *pend = p2 + strlen (p2);
    12851362#endif
    12861363
     
    12931370                       and into a command script.  However, the old parser
    12941371                       expanded the whole line, so we continue that for
    1295                        backwards-compatiblity.  Also, it wouldn't be
     1372                       backwards-compatibility.  Also, it wouldn't be
    12961373                       entirely consistent, since we do an unconditional
    12971374                       expand below once we know we don't have a
    12981375                       target-specific variable. */
    12991376#ifndef CONFIG_WITH_VALUE_LENGTH
    1300                     (void)variable_expand_string(pend, lb_next, (long)-1);
    1301                     lb_next += strlen(lb_next);
     1377                    (void)variable_expand_string (pend, lb_next, (long)-1);
     1378                    lb_next += strlen (lb_next);
    13021379#else
    13031380                    tmp_len = strlen (lb_next);
     
    13111388
    13121389#ifndef CONFIG_WITH_VALUE_LENGTH
    1313             colonp = find_char_unquote(p2, ':', 0, 0, 0);
    1314 #else
    1315             colonp = find_char_unquote_0 (p2, ':', &eol);
     1390            colonp = find_char_unquote (p2, MAP_COLON);
     1391#else
     1392            colonp = find_char_unquote_0 (p2, ':', MAP_COLON, &eol);
    13161393#endif
    13171394#ifdef HAVE_DOS_PATHS
     
    13241401                   (colonp == p2 + 1 || strchr (" \t(", colonp[-2]) != 0))
    13251402# ifndef CONFIG_WITH_VALUE_LENGTH
    1326               colonp = find_char_unquote(colonp + 1, ':', 0, 0, 0);
     1403              colonp = find_char_unquote (colonp + 1, MAP_COLON);
    13271404# else
    1328               colonp = find_char_unquote_0 (colonp + 1, ':', &eol);
     1405              colonp = find_char_unquote_0 (colonp + 1, ':', MAP_COLON, &eol);
    13291406# endif
    13301407#endif
     
    13321409              break;
    13331410
    1334             wtype = get_next_mword(lb_next, NULL, &lb_next, &wlen);
     1411            wtype = get_next_mword (lb_next, NULL, &lb_next, &wlen);
    13351412            if (wtype == w_eol)
    13361413              break;
    13371414
    13381415#ifndef CONFIG_WITH_VALUE_LENGTH
    1339             p2 += strlen(p2);
     1416            p2 += strlen (p2);
    13401417            *(p2++) = ' ';
    1341             p2 = variable_expand_string(p2, lb_next, wlen);
     1418            p2 = variable_expand_string (p2, lb_next, wlen);
    13421419#else
    13431420            *(eol++) = ' ';
     
    13561433        if (wtype == w_eol)
    13571434          {
    1358             if (*p2 != '\0')
    1359               /* There's no need to be ivory-tower about this: check for
    1360                  one of the most common bugs found in makefiles...  */
    1361               fatal (fstart, _("missing separator%s"),
    1362                      (cmd_prefix == '\t' && !strneq(line, "        ", 8))
    1363                      ? "" : _(" (did you mean TAB instead of 8 spaces?)"));
    1364             continue;
     1435            if (*p2 == '\0')
     1436              continue;
     1437
     1438            /* There's no need to be ivory-tower about this: check for
     1439               one of the most common bugs found in makefiles...  */
     1440            if (cmd_prefix == '\t' && strneq (line, "        ", 8))
     1441              O (fatal, fstart, _("missing separator (did you mean TAB instead of 8 spaces?)"));
     1442            else
     1443              O (fatal, fstart, _("missing separator"));
    13651444          }
    13661445
    13671446        /* Make the colon the end-of-string so we know where to stop
    1368            looking for targets.  */
     1447           looking for targets.  Start there again once we're done.  */
    13691448        *colonp = '\0';
    1370         filenames = PARSE_FILE_SEQ (&p2, struct nameseq, '\0', NULL, 0);
    1371         *p2 = ':';
     1449        filenames = PARSE_SIMPLE_SEQ (&p2, struct nameseq);
     1450        *colonp = ':';
     1451        p2 = colonp;
    13721452
    13731453        if (!filenames)
     
    14061486            if (semip)
    14071487              {
    1408                 unsigned int l = p - variable_buffer;
     1488                unsigned int l = p2 - variable_buffer;
    14091489                *(--semip) = ';';
    14101490#ifndef CONFIG_WITH_VALUE_LENGTH
     
    14151495                variable_buffer_output (p2 + strlen (p2),
    14161496                                        semip, strlen (semip)+1);
    1417                 p = variable_buffer + l;
     1497                p2 = variable_buffer + l;
    14181498              }
    14191499            record_target_var (filenames, p2,
     
    14261506        /* This is a normal target, _not_ a target-specific variable.
    14271507           Unquote any = in the dependency list.  */
    1428         find_char_unquote (lb_next, '=', 0, 0, 0);
     1508#ifndef CONFIG_WITH_VALUE_LENGTH
     1509        find_char_unquote (lb_next, MAP_EQUALS);
     1510#else
     1511        {
     1512          char *tmp_eos = strchr(lb_next, '\0'); /** @todo see if we can optimize this away... */
     1513          find_char_unquote_0 (lb_next, '=', MAP_EQUALS, &tmp_eos);
     1514        }
     1515#endif
     1516
     1517        /* Remember the command prefix for this target.  */
     1518        prefix = cmd_prefix;
    14291519
    14301520        /* We have some targets, so don't ignore the following commands.  */
     
    14471537              {
    14481538#ifndef CONFIG_WITH_VALUE_LENGTH
    1449                 cmdleft = find_char_unquote (p2, ';', 0, 0, 0);
    1450 #else
    1451                 cmdleft = find_char_unquote_0 (p2, ';', &eos);
     1539                cmdleft = find_char_unquote (p2, MAP_SEMI);
     1540#else
     1541                cmdleft = find_char_unquote_0 (p2, ';', MAP_SEMI, &eos);
    14521542#endif
    14531543                if (cmdleft != 0)
     
    14561546          }
    14571547
    1458         /* Is this a static pattern rule: `target: %targ: %dep; ...'?  */
     1548        /* Is this a static pattern rule: 'target: %targ: %dep; ...'?  */
    14591549        p = strchr (p2, ':');
    14601550        while (p != 0 && p[-1] == '\\')
     
    14821572           OR a space around the :.
    14831573        */
    1484         if (p && !(isspace ((unsigned char)p[1]) || !p[1]
    1485                    || isspace ((unsigned char)p[-1])))
     1574        if (p && !(ISSPACE (p[1]) || !p[1] || ISSPACE (p[-1])))
    14861575          p = 0;
    14871576#endif
     
    15041593          {
    15051594            struct nameseq *target;
    1506             target = PARSE_FILE_SEQ (&p2, struct nameseq, ':', NULL,
     1595            target = PARSE_FILE_SEQ (&p2, struct nameseq, MAP_COLON, NULL,
    15071596                                     PARSEFS_NOGLOB);
    15081597            ++p2;
    15091598            if (target == 0)
    1510               fatal (fstart, _("missing target pattern"));
     1599              O (fatal, fstart, _("missing target pattern"));
    15111600            else if (target->next != 0)
    1512               fatal (fstart, _("multiple target patterns (target `%s')"), target->name); /* bird */
     1601              OS (fatal, fstart, _("multiple target patterns (target '%s')"), target->name); /* bird added target */
    15131602            pattern_percent = find_percent_cached (&target->name);
    15141603            pattern = target->name;
    15151604            if (pattern_percent == 0)
    1516               fatal (fstart, _("target pattern contains no `%%' (target `%s')"), target->name); /* bird */
     1605              OS (fatal, fstart, _("target pattern contains no '%%' (target '%s')"), target->name); /* bird added target */
    15171606            free_ns (target);
    15181607          }
     
    15671656        if (set_default && default_goal_var->value[0] == '\0')
    15681657          {
    1569             const char *name;
    15701658            struct dep *d;
    15711659            struct nameseq *t = filenames;
     
    15741662              {
    15751663                int reject = 0;
    1576                 name = t->name;
     1664                const char *name = t->name;
    15771665
    15781666                /* We have nothing to do if this is an implicit rule. */
     
    15801668                  break;
    15811669
    1582                 /* See if this target's name does not start with a `.',
     1670                /* See if this target's name does not start with a '.',
    15831671                   unless it contains a slash.  */
    15841672                if (*name == '.' && strchr (name, '/') == 0
     
    16331721
    16341722      /* We get here except in the case that we just read a rule line.
    1635          Record now the last rule we read, so following spurious
    1636          commands are properly diagnosed.  */
    1637  rule_complete:
     1723         Record now the last rule we read, so following spurious
     1724         commands are properly diagnosed.  */
    16381725      record_waiting_files ();
    16391726    }
    16401727
    1641 #undef  word1eq
     1728#undef word1eq
    16421729
    16431730  if (conditionals->if_cmds)
    1644     fatal (fstart, _("missing `endif'"));
     1731    O (fatal, fstart, _("missing 'endif'"));
    16451732#ifdef KMK
    16461733
    16471734  if (kdata != NULL)
    1648     fatal (fstart, _("missing `kBuild-endef-*'"));
     1735    O (fatal, fstart, _("missing `kBuild-endef-*'"));
    16491736#endif
    16501737
     
    16521739  record_waiting_files ();
    16531740
    1654   if (collapsed)
    1655     free (collapsed);
     1741  free (collapsed);
    16561742  free (commands);
    16571743}
     
    16651751static void
    16661752remove_comments (char *line)
     1753#else
     1754static char *
     1755remove_comments (char *line, char *eos)
     1756#endif
    16671757{
    16681758  char *comment;
    16691759
    1670   comment = find_char_unquote (line, '#', 0, 0, 0);
     1760#ifndef CONFIG_WITH_VALUE_LENGTH
     1761  comment = find_char_unquote (line, MAP_COMMENT);
    16711762
    16721763  if (comment != 0)
    16731764    /* Cut off the line at the #.  */
    16741765    *comment = '\0';
     1766#else
     1767  comment = find_char_unquote_0 (line, '#', MAP_COMMENT, &eos);
     1768  if (comment)
     1769    {
     1770      /* Cut off the line at the #.  */
     1771      *comment = '\0';
     1772      return comment;
     1773    }
     1774  return eos;
     1775#endif
    16751776}
    1676 #else  /* CONFIG_WITH_VALUE_LENGTH */
    1677 __inline static char *
    1678 remove_comments (char *line, char *eol)
    1679 {
    1680   unsigned int string_len = eol - line;
    1681   register int ch;
    1682   char *p;
    1683 
    1684   /* Hope for simple (no comments). */
    1685   p = memchr (line, '#', string_len);
    1686   if (!p)
    1687     return eol;
    1688 
    1689   /* Found potential comment, enter the slow route. */
    1690   for (;;)
    1691     {
    1692       if (p > line && p[-1] == '\\')
    1693         {
    1694           /* Search for more backslashes.  */
    1695           int i = -2;
    1696           while (&p[i] >= line && p[i] == '\\')
    1697             --i;
    1698           ++i;
    1699 
    1700           /* The number of backslashes is now -I.
    1701              Copy P over itself to swallow half of them.  */
    1702           memmove (&p[i], &p[i/2], (string_len - (p - line)) - (i/2) + 1);
    1703           p += i/2;
    1704           if (i % 2 == 0)
    1705             {
    1706               /* All the backslashes quoted each other; the STOPCHAR was
    1707                  unquoted.  */
    1708               *p = '\0';
    1709               return p;
    1710             }
    1711 
    1712           /* The '#' was quoted by a backslash.  Look for another.  */
    1713         }
    1714       else
    1715         {
    1716           /* No backslash in sight.  */
    1717           *p = '\0';
    1718           return p;
    1719         }
    1720 
    1721       /* lazy, string_len isn't correct so do it the slow way. */
    1722       while ((ch = *p) != '#')
    1723         {
    1724           if (ch == '\0')
    1725             return p;
    1726           ++p;
    1727         }
    1728     }
    1729   /* won't ever get here. */
    1730 }
    1731 #endif /* CONFIG_WITH_VALUE_LENGTH */
    1732 
    1733 /* Execute a `undefine' directive.
     1777
     1778/* Execute a 'undefine' directive.
    17341779   The undefine line has already been read, and NAME is the name of
    17351780   the variable to be undefined. */
     
    17441789  name = next_token (var);
    17451790  if (*name == '\0')
    1746     fatal (&ebuf->floc, _("empty variable name"));
     1791    O (fatal, &ebuf->floc, _("empty variable name"));
    17471792  p = name + strlen (name) - 1;
    1748   while (p > name && isblank ((unsigned char)*p))
     1793  while (p > name && ISBLANK (*p))
    17491794    --p;
    17501795  p[1] = '\0';
     
    17541799}
    17551800
    1756 /* Execute a `define' directive.
     1801/* Execute a 'define' directive.
    17571802   The first line has already been read, and NAME is the name of
    17581803   the variable to be defined.  The following lines remain to be read.  */
     
    17631808{
    17641809  struct variable *v;
    1765   enum variable_flavor flavor;
    1766   struct floc defstart;
     1810  struct variable var;
     1811  floc defstart;
    17671812  int nlevels = 1;
    17681813  unsigned int length = 100;
    17691814  char *definition = xmalloc (length);
    17701815  unsigned int idx = 0;
    1771   char *p, *var;
     1816  char *p, *n;
    17721817
    17731818  defstart = ebuf->floc;
    17741819
    1775   p = parse_variable_definition (name, &flavor);
     1820  p = parse_variable_definition (name, &var);
    17761821  if (p == NULL)
    17771822    /* No assignment token, so assume recursive.  */
    1778     flavor = f_recursive;
     1823    var.flavor = f_recursive;
    17791824  else
    17801825    {
    1781       if (*(next_token (p)) != '\0')
    1782         error (&defstart, _("extraneous text after `define' directive"));
     1826      if (var.value[0] != '\0')
     1827        O (error, &defstart, _("extraneous text after 'define' directive"));
    17831828
    17841829      /* Chop the string before the assignment token to get the name.  */
    1785       p[flavor == f_recursive ? -1 : -2] = '\0';
     1830#ifndef CONFIG_WITH_STRCACHE2
     1831      var.name[var.length] = '\0';
     1832#else
     1833      assert (!strcache2_is_cached (&variable_strcache, var.name));
     1834      ((char *)var.name)[var.length] = '\0';
     1835#endif
    17861836    }
    17871837
    17881838  /* Expand the variable name and find the beginning (NAME) and end.  */
    1789   var = allocated_variable_expand (name);
    1790   name = next_token (var);
    1791   if (*name == '\0')
    1792     fatal (&defstart, _("empty variable name"));
     1839  n = allocated_variable_expand (name);
     1840  name = next_token (n);
     1841  if (name[0] == '\0')
     1842    O (fatal, &defstart, _("empty variable name"));
    17931843  p = name + strlen (name) - 1;
    1794   while (p > name && isblank ((unsigned char)*p))
     1844  while (p > name && ISBLANK (*p))
    17951845    --p;
    17961846  p[1] = '\0';
     
    18051855      /* If there is nothing left to be eval'd, there's no 'endef'!!  */
    18061856      if (nlines < 0)
    1807         fatal (&defstart, _("missing `endef', unterminated `define'"));
     1857        O (fatal, &defstart, _("missing 'endef', unterminated 'define'"));
    18081858
    18091859      ebuf->floc.lineno += nlines;
     
    18291879
    18301880          /* If this is another 'define', increment the level count.  */
    1831           if ((len == 6 || (len > 6 && isblank ((unsigned char)p[6])))
     1881          if ((len == 6 || (len > 6 && ISBLANK (p[6])))
    18321882              && strneq (p, "define", 6))
    18331883            ++nlevels;
     
    18351885          /* If this is an 'endef', decrement the count.  If it's now 0,
    18361886             we've found the last one.  */
    1837           else if ((len == 5 || (len > 5 && isblank ((unsigned char)p[5])))
     1887          else if ((len == 5 || (len > 5 && ISBLANK (p[5])))
    18381888                   && strneq (p, "endef", 5))
    18391889            {
     
    18451895#endif
    18461896              if (*(next_token (p)) != '\0')
    1847                 error (&ebuf->floc,
    1848                        _("extraneous text after `endef' directive"));
     1897                O (error, &ebuf->floc,
     1898                   _("extraneous text after 'endef' directive"));
    18491899
    18501900              if (--nlevels == 0)
     
    18791929
    18801930#ifndef CONFIG_WITH_VALUE_LENGTH
    1881   v = do_variable_definition (&defstart, name, definition, origin, flavor, 0);
     1931  v = do_variable_definition (&defstart, name,
     1932                              definition, origin, var.flavor, 0);
    18821933#else
    18831934  v = do_variable_definition_2 (&defstart, name, definition,
    1884                                 idx ? idx - 1 : idx,  flavor == f_simple,
    1885                                 0 /* free_value */, origin, flavor,
     1935                                idx ? idx - 1 : idx,  var.flavor == f_simple,
     1936                                0 /* free_value */, origin, var.flavor,
    18861937                                0 /*target_var*/);
    18871938#endif
    18881939  free (definition);
    1889   free (var);
     1940  free (n);
    18901941  return (v);
    18911942}
     
    19051956
    19061957static int
    1907 #ifndef CONFIG_WITH_VALUE_LENGTH
    1908 conditional_line (char *line, int len, const struct floc *flocp)
    1909 #else
    1910 conditional_line (char *line, char *eol, int len, const struct floc *flocp)
    1911 #endif
     1958conditional_line (char *line IF_WITH_VALUE_LENGTH_PARAM(char *eol), int len, const floc *flocp)
    19121959{
    1913   char *cmdname;
     1960  const char *cmdname;
    19141961  enum { c_ifdef, c_ifndef, c_ifeq, c_ifneq,
    19151962#ifdef CONFIG_WITH_SET_CONDITIONALS
     
    19281975
    19291976  /* Compare a word, both length and contents. */
    1930 #define word1eq(s)      (len == sizeof(s)-1 && strneq (s, line, sizeof(s)-1))
    1931 #define chkword(s, t)   if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
     1977#define word1eq(s)      (len == CSTRLEN (s) && strneq (s, line, CSTRLEN (s)))
     1978#define chkword(s, t)   if (word1eq (s)) { cmdtype = (t); cmdname = (s); }
    19321979
    19331980  /* Make sure this line is a conditional.  */
     
    19491996
    19501997  /* Found one: skip past it and any whitespace after it.  */
    1951   line = next_token (line + len);
    1952 
    1953 #define EXTRANEOUS() error (flocp, _("Extraneous text after `%s' directive"), cmdname)
     1998  line += len;
     1999  NEXT_TOKEN (line);
     2000
     2001#define EXTRATEXT() OS (error, flocp, _("extraneous text after '%s' directive"), cmdname)
     2002#define EXTRACMD()  OS (fatal, flocp, _("extraneous '%s'"), cmdname)
    19542003
    19552004  /* An 'endif' cannot contain extra text, and reduces the if-depth by 1  */
     
    19572006    {
    19582007      if (*line != '\0')
    1959         EXTRANEOUS ();
     2008        EXTRATEXT ();
    19602009
    19612010      if (!conditionals->if_cmds)
    1962         fatal (flocp, _("extraneous `%s'"), cmdname);
     2011        EXTRACMD ();
    19632012
    19642013      --conditionals->if_cmds;
     
    19742023
    19752024      if (!conditionals->if_cmds)
    1976         fatal (flocp, _("extraneous `%s'"), cmdname);
     2025        EXTRACMD ();
    19772026
    19782027      o = conditionals->if_cmds - 1;
    19792028
    19802029      if (conditionals->seen_else[o])
    1981         fatal (flocp, _("only one `else' per conditional"));
     2030        O (fatal, flocp, _("only one 'else' per conditional"));
    19822031
    19832032      /* Change the state of ignorance.  */
     
    20052054
    20062055      /* Find the length of the next word.  */
    2007       for (p = line+1; *p != '\0' && !isspace ((unsigned char)*p); ++p)
     2056      for (p = line+1; ! STOP_SET (*p, MAP_SPACE|MAP_NUL); ++p)
    20082057        ;
    20092058      len = p - line;
    20102059
    20112060      /* If it's 'else' or 'endif' or an illegal conditional, fail.  */
    2012       if (word1eq("else") || word1eq("endif")
    2013 #ifndef CONFIG_WITH_VALUE_LENGTH
    2014           || conditional_line (line, len, flocp) < 0)
    2015 #else
    2016           || conditional_line (line, eol, len, flocp) < 0)
    2017 #endif
    2018         EXTRANEOUS ();
     2061      if (word1eq ("else") || word1eq ("endif")
     2062          || conditional_line (line IF_WITH_VALUE_LENGTH_PARAM(eol), len, flocp) < 0)
     2063        EXTRATEXT ();
    20192064      else
    20202065        {
     
    20682113    }
    20692114
    2070   /* Record that we have seen an `if...' but no `else' so far.  */
     2115  /* Record that we have seen an 'if...' but no 'else' so far.  */
    20712116  conditionals->seen_else[o] = 0;
    20722117
     
    20752120    if (conditionals->ignoring[i])
    20762121      {
    2077         /* We are already ignoring, so just push a level to match the next
    2078            "else" or "endif", and keep ignoring.  We don't want to expand
    2079            variables in the condition.  */
    2080         conditionals->ignoring[o] = 1;
    2081         return 1;
     2122        /* We are already ignoring, so just push a level to match the next
     2123           "else" or "endif", and keep ignoring.  We don't want to expand
     2124           variables in the condition.  */
     2125        conditionals->ignoring[o] = 1;
     2126        return 1;
    20822127      }
    20832128
     
    20992144      p = end_of_token (var);
    21002145      i = p - var;
    2101       p = next_token (p);
     2146      NEXT_TOKEN (p);
    21022147      if (*p != '\0')
    2103         return -1;
     2148        return -1;
    21042149
    21052150      var[i] = '\0';
     
    21372182
    21382183      if (termin != ',' && termin != '"' && termin != '\'')
    2139         return -1;
     2184        return -1;
    21402185
    21412186      s1 = ++line;
    21422187      /* Find the end of the first string.  */
    21432188      if (termin == ',')
    2144         {
    2145           int count = 0;
    2146           for (; *line != '\0'; ++line)
    2147             if (*line == '(')
    2148               ++count;
    2149             else if (*line == ')')
    2150               --count;
    2151             else if (*line == ',' && count <= 0)
    2152               break;
    2153         }
     2189        {
     2190          int count = 0;
     2191          for (; *line != '\0'; ++line)
     2192            if (*line == '(')
     2193              ++count;
     2194            else if (*line == ')')
     2195              --count;
     2196            else if (*line == ',' && count <= 0)
     2197              break;
     2198        }
    21542199      else
    2155         while (*line != '\0' && *line != termin)
    2156           ++line;
     2200        while (*line != '\0' && *line != termin)
     2201          ++line;
    21572202
    21582203      if (*line == '\0')
    2159         return -1;
     2204        return -1;
    21602205
    21612206      if (termin == ',')
    2162         {
    2163           /* Strip blanks after the first string.  */
    2164           char *p = line++;
    2165           while (isblank ((unsigned char)p[-1]))
    2166             --p;
    2167           *p = '\0';
     2207        {
     2208          /* Strip blanks after the first string.  */
     2209          char *p = line++;
     2210          while (ISBLANK (p[-1]))
     2211            --p;
     2212          *p = '\0';
    21682213#ifdef CONFIG_WITH_VALUE_LENGTH
    21692214          l = p - s1;
    21702215#endif
    2171         }
     2216        }
    21722217      else
    21732218        {
     
    21752220          l = line - s1;
    21762221#endif
    2177           *line++ = '\0';
     2222          *line++ = '\0';
    21782223        }
    21792224
     
    21812226      s2 = variable_expand (s1);
    21822227      /* We must allocate a new copy of the expanded string because
    2183         variable_expand re-uses the same buffer.  */
     2228        variable_expand re-uses the same buffer.  */
    21842229      l = strlen (s2);
    21852230      s1 = alloca (l + 1);
     
    21902235
    21912236      if (termin != ',')
    2192         /* Find the start of the second string.  */
    2193         line = next_token (line);
     2237        /* Find the start of the second string.  */
     2238        NEXT_TOKEN (line);
    21942239
    21952240      termin = termin == ',' ? ')' : *line;
    21962241      if (termin != ')' && termin != '"' && termin != '\'')
    2197         return -1;
     2242        return -1;
    21982243
    21992244      /* Find the end of the second string.  */
    22002245      if (termin == ')')
    2201         {
    2202           int count = 0;
    2203           s2 = next_token (line);
    2204           for (line = s2; *line != '\0'; ++line)
    2205             {
    2206               if (*line == '(')
    2207                 ++count;
    2208               else if (*line == ')')
    2209                 {
    2210                   if (count <= 0)
    2211                     break;
    2212                   else
    2213                     --count;
    2214                 }
    2215             }
    2216         }
     2246        {
     2247          int count = 0;
     2248          s2 = next_token (line);
     2249          for (line = s2; *line != '\0'; ++line)
     2250            {
     2251              if (*line == '(')
     2252                ++count;
     2253              else if (*line == ')')
     2254                {
     2255                  if (count <= 0)
     2256                    break;
     2257                  else
     2258                    --count;
     2259                }
     2260            }
     2261        }
    22172262      else
    2218         {
    2219           ++line;
    2220           s2 = line;
    2221           while (*line != '\0' && *line != termin)
    2222             ++line;
    2223         }
     2263        {
     2264          ++line;
     2265          s2 = line;
     2266          while (*line != '\0' && *line != termin)
     2267            ++line;
     2268        }
    22242269
    22252270      if (*line == '\0')
    2226         return -1;
    2227 
    2228       *line = '\0';
     2271        return -1;
     2272
    22292273#ifdef CONFIG_WITH_VALUE_LENGTH
    22302274      l = line - s2;
    22312275#endif
    2232       line = next_token (++line);
     2276      *(line++) = '\0';
     2277      NEXT_TOKEN (line);
    22332278      if (*line != '\0')
    2234         EXTRANEOUS ();
     2279        EXTRATEXT ();
    22352280
    22362281#ifndef CONFIG_WITH_VALUE_LENGTH
     
    22912336record_target_var (struct nameseq *filenames, char *defn,
    22922337                   enum variable_origin origin, struct vmodifiers *vmod,
    2293                    const struct floc *flocp)
     2338                   const floc *flocp)
    22942339{
    22952340  struct nameseq *nextf;
     
    23052350      struct variable *v;
    23062351      const char *name = filenames->name;
    2307       const char *fname;
    23082352      const char *percent;
    23092353      struct pattern_var *p;
     2354#ifdef CONFIG_WITH_VALUE_LENGTH
     2355      const char *fname;
     2356#endif
    23102357
    23112358      nextf = filenames->next;
     
    23392386          v->value_alloc_len = v->value_length + 1;
    23402387#endif
    2341 
    2342           fname = p->target;
    23432388        }
    23442389      else
     
    23652410
    23662411          initialize_file_variables (f, 1);
    2367           fname = f->name;
    23682412
    23692413          current_variable_set_list = f->variables;
    23702414          v = try_variable_definition (flocp, defn IF_WITH_VALUE_LENGTH_PARAM(NULL), origin, 1);
    23712415          if (!v)
    2372             fatal (flocp, _("Malformed target-specific variable definition"));
     2416            O (fatal, flocp, _("Malformed target-specific variable definition"));
    23732417          current_variable_set_list = global;
    23742418        }
     
    23852429          struct variable *gv;
    23862430#ifndef CONFIG_WITH_STRCACHE2
    2387           int len = strlen(v->name);
     2431          int len = strlen (v->name);
    23882432#else
    23892433          int len = !percent
     
    23932437
    23942438          gv = lookup_variable (v->name, len);
    2395           if (gv && (gv->origin == o_env_override || gv->origin == o_command))
     2439          if (gv && v != gv
     2440              && (gv->origin == o_env_override || gv->origin == o_command))
    23962441            {
    23972442#ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
    23982443              assert (!v->rdonly_val); /* paranoia */
    23992444#endif
    2400               if (v->value != 0)
    2401                 free (v->value);
     2445              free (v->value);
    24022446#ifndef CONFIG_WITH_VALUE_LENGTH
    24032447              v->value = xstrdup (gv->value);
     
    24202464   by COMMANDS and COMMANDS_IDX, coming from FILENAME:COMMANDS_STARTED.
    24212465   TWO_COLON is nonzero if a double colon was used.
    2422    If not nil, PATTERN is the `%' pattern to make this
     2466   If not nil, PATTERN is the '%' pattern to make this
    24232467   a static pattern rule, and PATTERN_PERCENT is a pointer
    2424    to the `%' within it.
     2468   to the '%' within it.
    24252469
    24262470   The links of FILENAMES are freed, and so are any names in it
     
    24322476              unsigned int cmds_started, char *commands,
    24332477              unsigned int commands_idx, int two_colon,
    2434               const struct floc *flocp)
     2478              char prefix, const floc *flocp)
    24352479{
    24362480#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
     
    24492493     See Savannah bug # 12124.  */
    24502494  if (snapped_deps)
    2451     fatal (flocp, _("prerequisites cannot be defined in recipes"));
     2495    O (fatal, flocp, _("prerequisites cannot be defined in recipes"));
    24522496
    24532497  /* Determine if this is a pattern rule or not.  */
     
    24652509      cmds->fileinfo.filenm = flocp->filenm;
    24662510      cmds->fileinfo.lineno = cmds_started;
     2511      cmds->fileinfo.offset = 0;
    24672512      cmds->commands = xstrndup (commands, commands_idx);
    24682513      cmds->command_lines = 0;
     2514      cmds->recipe_prefix = prefix;
    24692515#ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
    24702516      cmds->refs = 0;
     
    24782524  if (depstr == 0)
    24792525    deps = 0;
    2480   else if (second_expansion && strchr (depstr, '$'))
    2481     {
    2482       deps = alloc_dep ();
    2483       deps->name = depstr;
    2484       deps->need_2nd_expansion = 1;
    2485       deps->staticpattern = pattern != 0;
    2486     }
    24872526  else
    24882527    {
    2489       deps = split_prereqs (depstr);
    2490       free (depstr);
    2491 
    2492       /* We'll enter static pattern prereqs later when we have the stem.  We
    2493          don't want to enter pattern rules at all so that we don't think that
    2494          they ought to exist (make manual "Implicit Rule Search Algorithm",
    2495          item 5c).  */
    2496       if (! pattern && ! implicit_percent)
    2497         deps = enter_prereqs (deps, NULL);
     2528      depstr = unescape_char (depstr, ':');
     2529      if (second_expansion && strchr (depstr, '$'))
     2530        {
     2531          deps = alloc_dep ();
     2532          deps->name = depstr;
     2533          deps->need_2nd_expansion = 1;
     2534          deps->staticpattern = pattern != 0;
     2535        }
     2536      else
     2537        {
     2538          deps = split_prereqs (depstr);
     2539          free (depstr);
     2540
     2541          /* We'll enter static pattern prereqs later when we have the stem.
     2542             We don't want to enter pattern rules at all so that we don't
     2543             think that they ought to exist (make manual "Implicit Rule Search
     2544             Algorithm", item 5c).  */
     2545          if (! pattern && ! implicit_percent)
     2546            deps = enter_prereqs (deps, NULL);
     2547        }
    24982548    }
    24992549
     
    25092559
    25102560      if (pattern != 0)
    2511         fatal (flocp, _("mixed implicit and static pattern rules"));
     2561        O (fatal, flocp, _("mixed implicit and static pattern rules"));
    25122562
    25132563      /* Count the targets to create an array of target names.
     
    25322582
    25332583          if (implicit_percent == 0)
    2534             fatal (flocp, _("mixed implicit and normal rules"));
    2535 
    2536           targets[c] = name;
    2537           target_pats[c] = implicit_percent;
     2584            O (fatal, flocp, _("mixed implicit and normal rules"));
     2585
     2586          targets[c] = name;
     2587          target_pats[c] = implicit_percent;
    25382588          ++c;
    25392589
     
    25652615          posix_pedantic = 1;
    25662616          define_variable_cname (".SHELLFLAGS", "-ec", o_default, 0);
     2617          /* These default values are based on IEEE Std 1003.1-2008.  */
     2618          define_variable_cname ("ARFLAGS", "-rv", o_default, 0);
     2619          define_variable_cname ("CC", "c99", o_default, 0);
     2620          define_variable_cname ("CFLAGS", "-O", o_default, 0);
     2621          define_variable_cname ("FC", "fort77", o_default, 0);
     2622          define_variable_cname ("FFLAGS", "-O 1", o_default, 0);
     2623          define_variable_cname ("SCCSGETFLAGS", "-s", o_default, 0);
    25672624        }
    25682625      else if (streq (name, ".SECONDEXPANSION"))
     
    25722629        second_target_expansion = 1;
    25732630#endif
    2574 #if !defined(WINDOWS32) && !defined (__MSDOS__) && !defined (__EMX__)
     2631#if !defined (__MSDOS__) && !defined (__EMX__)
    25752632      else if (streq (name, ".ONESHELL"))
    25762633        one_shell = 1;
     
    26212678
    26222679      /* If this is a static pattern rule:
    2623          `targets: target%pattern: prereq%pattern; recipe',
     2680         'targets: target%pattern: prereq%pattern; recipe',
    26242681         make sure the pattern matches this target name.  */
    26252682      if (pattern && !pattern_matches (pattern, pattern_percent, name))
    2626         error (flocp, _("target `%s' doesn't match the target pattern"), name);
     2683        OS (error, flocp,
     2684            _("target '%s' doesn't match the target pattern"), name);
    26272685      else if (deps)
    26282686        /* If there are multiple targets, copy the chain DEPS for all but the
     
    26332691      /* Find or create an entry in the file database for this target.  */
    26342692      if (!two_colon)
    2635         {
    2636           /* Single-colon.  Combine this rule with the file's existing record,
    2637              if any.  */
     2693        {
     2694          /* Single-colon.  Combine this rule with the file's existing record,
     2695             if any.  */
    26382696#ifndef KMK
    2639           f = enter_file (strcache_add (name));
     2697          f = enter_file (strcache_add (name));
    26402698#else  /* KMK - the name is already in the cache, don't waste time.  */
    26412699          f = enter_file (name);
    26422700#endif
    2643           if (f->double_colon)
    2644             fatal (flocp,
    2645                    _("target file `%s' has both : and :: entries"), f->name);
    2646 
    2647           /* If CMDS == F->CMDS, this target was listed in this rule
    2648              more than once.  Just give a warning since this is harmless.  */
    2649           if (cmds != 0 && cmds == f->cmds)
    2650             error (flocp,
    2651                    _("target `%s' given more than once in the same rule."),
    2652                    f->name);
    2653 
    2654           /* Check for two single-colon entries both with commands.
    2655              Check is_target so that we don't lose on files such as .c.o
    2656              whose commands were preinitialized.  */
    2657           else if (cmds != 0 && f->cmds != 0 && f->is_target)
    2658             {
    2659               error (&cmds->fileinfo,
    2660                      _("warning: overriding recipe for target `%s'"),
     2701          if (f->double_colon)
     2702            OS (fatal, flocp,
     2703                _("target file '%s' has both : and :: entries"), f->name);
     2704
     2705          /* If CMDS == F->CMDS, this target was listed in this rule
     2706             more than once.  Just give a warning since this is harmless.  */
     2707          if (cmds != 0 && cmds == f->cmds)
     2708            OS (error, flocp,
     2709                _("target '%s' given more than once in the same rule"),
     2710                f->name);
     2711
     2712          /* Check for two single-colon entries both with commands.
     2713             Check is_target so that we don't lose on files such as .c.o
     2714             whose commands were preinitialized.  */
     2715          else if (cmds != 0 && f->cmds != 0 && f->is_target)
     2716            {
     2717              size_t l = strlen (f->name);
     2718              error (&cmds->fileinfo, l,
     2719                     _("warning: overriding recipe for target '%s'"),
    26612720                     f->name);
    2662               error (&f->cmds->fileinfo,
    2663                      _("warning: ignoring old recipe for target `%s'"),
     2721              error (&f->cmds->fileinfo, l,
     2722                     _("warning: ignoring old recipe for target '%s'"),
    26642723                     f->name);
    2665             }
    2666 
    2667           /* Defining .DEFAULT with no deps or cmds clears it.  */
    2668           if (f == default_file && this == 0 && cmds == 0)
    2669             f->cmds = 0;
    2670           if (cmds != 0)
    2671             f->cmds = cmds;
     2724            }
     2725
     2726          /* Defining .DEFAULT with no deps or cmds clears it.  */
     2727          if (f == default_file && this == 0 && cmds == 0)
     2728            f->cmds = 0;
     2729          if (cmds != 0)
     2730            f->cmds = cmds;
    26722731
    26732732#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
     
    26842743
    26852744              if (f == suffix_file)
    2686                 error (flocp,
    2687                        _(".SUFFIXES encountered in an explicit multi target rule"));
     2745                O (error, flocp,
     2746                   _(".SUFFIXES encountered in an explicit multi target rule"));
    26882747            }
    26892748          prev_file = f;
    26902749#endif
    26912750
    2692           /* Defining .SUFFIXES with no dependencies clears out the list of
    2693              suffixes.  */
    2694           if (f == suffix_file && this == 0)
    2695             {
     2751          /* Defining .SUFFIXES with no dependencies clears out the list of
     2752             suffixes.  */
     2753          if (f == suffix_file && this == 0)
     2754            {
    26962755              free_dep_chain (f->deps);
    2697               f->deps = 0;
    2698             }
    2699         }
     2756              f->deps = 0;
     2757            }
     2758        }
    27002759      else
    2701         {
    2702           /* Double-colon.  Make a new record even if there already is one.  */
     2760        {
     2761          /* Double-colon.  Make a new record even if there already is one.  */
    27032762#ifndef CONFIG_WITH_STRCACHE2
    27042763          f = lookup_file (name);
     
    27072766#endif /* CONFIG_WITH_STRCACHE2 */
    27082767
    2709           /* Check for both : and :: rules.  Check is_target so we don't lose
    2710              on default suffix rules or makefiles.  */
    2711           if (f != 0 && f->is_target && !f->double_colon)
    2712             fatal (flocp,
    2713                    _("target file `%s' has both : and :: entries"), f->name);
     2768          /* Check for both : and :: rules.  Check is_target so we don't lose
     2769             on default suffix rules or makefiles.  */
     2770          if (f != 0 && f->is_target && !f->double_colon)
     2771            OS (fatal, flocp,
     2772                _("target file '%s' has both : and :: entries"), f->name);
    27142773
    27152774#ifndef KMK
    2716           f = enter_file (strcache_add (name));
     2775          f = enter_file (strcache_add (name));
    27172776#else  /* KMK - the name is already in the cache, don't waste time.  */
    2718           f = enter_file (name);
    2719 #endif
    2720           /* If there was an existing entry and it was a double-colon entry,
    2721              enter_file will have returned a new one, making it the prev
    2722              pointer of the old one, and setting its double_colon pointer to
    2723              the first one.  */
    2724           if (f->double_colon == 0)
    2725             /* This is the first entry for this name, so we must set its
    2726                double_colon pointer to itself.  */
    2727             f->double_colon = f;
    2728 
    2729           f->cmds = cmds;
    2730         }
     2777          f = enter_file (name);
     2778#endif
     2779          /* If there was an existing entry and it was a double-colon entry,
     2780             enter_file will have returned a new one, making it the prev
     2781             pointer of the old one, and setting its double_colon pointer to
     2782             the first one.  */
     2783          if (f->double_colon == 0)
     2784            /* This is the first entry for this name, so we must set its
     2785               double_colon pointer to itself.  */
     2786            f->double_colon = f;
     2787
     2788          f->cmds = cmds;
     2789        }
    27312790
    27322791      f->is_target = 1;
    27332792
    27342793      /* If this is a static pattern rule, set the stem to the part of its
    2735          name that matched the `%' in the pattern, so you can use $* in the
     2794         name that matched the '%' in the pattern, so you can use $* in the
    27362795         commands.  If we didn't do it before, enter the prereqs now.  */
    27372796      if (pattern)
     
    27962855      name = filenames->name;
    27972856      if (find_percent_cached (&name))
    2798         fatal (flocp, _("mixed implicit and normal rules"));
     2857        O (error, flocp,
     2858           _("*** mixed implicit and normal rules: deprecated syntax"));
    27992859    }
    28002860}
     
    28102870   STOPCHAR _cannot_ be '$' if IGNOREVARS is true.  */
    28112871
    2812 #ifndef CONFIG_WITH_VALUE_LENGTH
    28132872static char *
    2814 find_char_unquote (char *string, int stop1, int stop2, int blank,
    2815                    int ignorevars)
    2816 #else
    2817 static char *
    2818 find_char_unquote_2 (char *string, int stop1, int stop2, int blank,
    2819                      int ignorevars, unsigned int string_len)
    2820 #endif
     2873find_char_unquote (char *string, int map IF_WITH_VALUE_LENGTH_PARAM(unsigned int string_len))
    28212874{
    28222875#ifndef CONFIG_WITH_VALUE_LENGTH
     
    28242877#endif
    28252878  char *p = string;
    2826   register int ch; /* bird: 'optimiziations' */
    28272879#ifdef CONFIG_WITH_VALUE_LENGTH
    28282880  assert (string_len == 0 || string_len == strlen (string));
    28292881#endif
    28302882
    2831   if (ignorevars)
    2832     ignorevars = '$';
     2883  /* Always stop on NUL.  */
     2884  map |= MAP_NUL;
    28332885
    28342886  while (1)
    28352887    {
    2836       if (stop2 && blank)
    2837         while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1 && ch != stop2
    2838                && ! isblank ((unsigned char) ch))
    2839           ++p;
    2840       else if (stop2)
    2841         while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1 && ch != stop2)
    2842           ++p;
    2843       else if (blank)
    2844         while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1
    2845                && ! isblank ((unsigned char) ch))
    2846           ++p;
    2847       else
    2848         while ((ch = *p) != '\0' && ch != ignorevars && ch != stop1)
    2849           ++p;
    2850 
    2851       if (ch == '\0')
    2852         break;
     2888      while (! STOP_SET (*p, map))
     2889        ++p;
     2890
     2891      if (*p == '\0')
     2892        break;
    28532893
    28542894      /* If we stopped due to a variable reference, skip over its contents.  */
    2855       if (ch == ignorevars)
     2895      if (STOP_SET (*p, MAP_VARIABLE))
    28562896        {
    28572897          char openparen = p[1];
     2898
     2899          /* Check if '$' is the last character in the string.  */
     2900          if (openparen == '\0')
     2901            break;
    28582902
    28592903          p += 2;
     
    28642908              unsigned int pcount = 1;
    28652909              char closeparen = (openparen == '(' ? ')' : '}');
     2910              char ch; /* bird */
    28662911
    28672912              while ((ch = *p))
     
    28842929
    28852930      if (p > string && p[-1] == '\\')
    2886         {
    2887           /* Search for more backslashes.  */
    2888           int i = -2;
    2889           while (&p[i] >= string && p[i] == '\\')
    2890             --i;
    2891           ++i;
    2892           /* Only compute the length if really needed.  */
    2893           if (string_len == 0)
    2894             string_len = strlen (string);
    2895           /* The number of backslashes is now -I.
    2896              Copy P over itself to swallow half of them.  */
    2897           memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
    2898           p += i/2;
    2899           if (i % 2 == 0)
    2900             /* All the backslashes quoted each other; the STOPCHAR was
    2901                unquoted.  */
    2902             return p;
    2903 
    2904           /* The STOPCHAR was quoted by a backslash.  Look for another.  */
    2905         }
     2931        {
     2932          /* Search for more backslashes.  */
     2933          int i = -2;
     2934          while (&p[i] >= string && p[i] == '\\')
     2935            --i;
     2936          ++i;
     2937          /* Only compute the length if really needed.  */
     2938          if (string_len == 0)
     2939            string_len = strlen (string);
     2940          /* The number of backslashes is now -I.
     2941             Copy P over itself to swallow half of them.  */
     2942          memmove (&p[i], &p[i/2], (string_len - (p - string)) - (i/2) + 1);
     2943          p += i/2;
     2944          if (i % 2 == 0)
     2945            /* All the backslashes quoted each other; the STOPCHAR was
     2946               unquoted.  */
     2947            return p;
     2948
     2949          /* The STOPCHAR was quoted by a backslash.  Look for another.  */
     2950        }
    29062951      else
    2907         /* No backslash in sight.  */
    2908         return p;
     2952        /* No backslash in sight.  */
     2953        return p;
    29092954    }
    29102955
     
    29142959
    29152960#ifdef CONFIG_WITH_VALUE_LENGTH
    2916 /* Special case version of find_char_unquote that only takes stop1.
    2917    This is so common that it makes a lot of sense to specialize this.
    2918    */
    2919 __inline static char *
    2920 find_char_unquote_0 (char *string, int stop1, char **eosp)
     2961/* Special case version of find_char_unquote that only takes stop character.
     2962   This is so common that it makes a lot of sense to specialize this. */
     2963
     2964K_INLINE char *
     2965find_char_unquote_0 (char *string, int stop1, int map, char **eosp)
    29212966{
    29222967  unsigned int string_len = *eosp - string;
    2923   char *p = (char *)memchr (string, stop1, string_len);
     2968  char *p;
     2969
    29242970  assert (strlen (string) == string_len);
     2971  assert (!(map & MAP_VARIABLE) && map != 0);
     2972  assert ((stopchar_map[(unsigned char)stop1] & map) == map);
     2973
     2974  p = (char *)memchr (string, stop1, string_len);
    29252975  if (!p)
    29262976    return NULL;
    2927   if (p <= string || p[-1] != '\\')
     2977  if (p <= string || p[-1] != '\\') 
    29282978    return p;
    29292979
    2930   p = find_char_unquote_2 (string, stop1, 0, 0, 0, string_len);
     2980  p = find_char_unquote (string, map, string_len);
    29312981  *eosp = memchr (string, '\0', string_len);
    29322982  return p;
     
    29342984#endif
    29352985
     2986/* Unescape a character in a string.  The string is compressed onto itself.  */
     2987
     2988static char *
     2989unescape_char (char *string, int c)
     2990{
     2991  char *p = string;
     2992  char *s = string;
     2993
     2994  while (*s != '\0')
     2995    {
     2996      if (*s == '\\')
     2997        {
     2998          char *e = s;
     2999          int l;
     3000
     3001          /* We found a backslash.  See if it's escaping our character.  */
     3002          while (*e == '\\')
     3003            ++e;
     3004          l = e - s;
     3005
     3006          if (*e != c || l%2 == 0)
     3007            {
     3008              /* It's not; just take it all without unescaping.  */
     3009              memmove (p, s, l);
     3010              p += l;
     3011
     3012              // If we hit the end of the string, we're done
     3013              if (*e == '\0')
     3014                break;
     3015            }
     3016          else if (l > 1)
     3017            {
     3018              /* It is, and there's >1 backslash.  Take half of them.  */
     3019              l /= 2;
     3020              memmove (p, s, l);
     3021              p += l;
     3022            }
     3023
     3024          s = e;
     3025        }
     3026
     3027      *(p++) = *(s++);
     3028    }
     3029
     3030  *p = '\0';
     3031  return string;
     3032}
     3033
    29363034/* Search PATTERN for an unquoted % and handle quoting.  */
    29373035
     
    29393037find_percent (char *pattern)
    29403038{
    2941   return find_char_unquote (pattern, '%', 0, 0, 0);
     3039#ifndef CONFIG_WITH_VALUE_LENGTH
     3040  return find_char_unquote (pattern, MAP_PERCENT);
     3041#else
     3042  char *eos = strchr(pattern, '\0');
     3043  return find_char_unquote_0 (pattern, '%', MAP_PERCENT, &eos);
     3044#endif
    29423045}
    29433046
     
    29623065  while (1)
    29633066    {
    2964       while (*p != '\0' && *p != '%')
     3067      while (! STOP_SET (*p, MAP_PERCENT|MAP_NUL))
    29653068        ++p;
    29663069
     
    30323135 */
    30333136
    3034 static unsigned long
     3137static long
    30353138readstring (struct ebuffer *ebuf)
    30363139{
     
    31253228      len = strlen (p);
    31263229      if (len == 0)
    3127         {
    3128           /* This only happens when the first thing on the line is a '\0'.
    3129              It is a pretty hopeless case, but (wonder of wonders) Athena
    3130              lossage strikes again!  (xmkmf puts NULs in its makefiles.)
    3131              There is nothing really to be done; we synthesize a newline so
    3132              the following line doesn't appear to be part of this line.  */
    3133           error (&ebuf->floc,
    3134                  _("warning: NUL character seen; rest of line ignored"));
    3135           p[0] = '\n';
    3136           len = 1;
    3137         }
     3230        {
     3231          /* This only happens when the first thing on the line is a '\0'.
     3232             It is a pretty hopeless case, but (wonder of wonders) Athena
     3233             lossage strikes again!  (xmkmf puts NULs in its makefiles.)
     3234             There is nothing really to be done; we synthesize a newline so
     3235             the following line doesn't appear to be part of this line.  */
     3236          O (error, &ebuf->floc,
     3237             _("warning: NUL character seen; rest of line ignored"));
     3238          p[0] = '\n';
     3239          len = 1;
     3240        }
    31383241
    31393242      /* Jump past the text we just read.  */
     
    31543257        {
    31553258          --p;
    3156           p[-1] = '\n';
     3259          memmove (p-1, p, strlen (p) + 1);
    31573260        }
    31583261#endif
     
    31603263      backslash = 0;
    31613264      for (p2 = p - 2; p2 >= start; --p2)
    3162         {
    3163           if (*p2 != '\\')
    3164             break;
     3265        {
     3266          if (*p2 != '\\')
     3267            break;
    31653268          backslash = !backslash;
    3166         }
     3269        }
    31673270
    31683271      if (!backslash)
    3169         {
    3170           p[-1] = '\0';
     3272        {
     3273          p[-1] = '\0';
    31713274#ifdef CONFIG_WITH_VALUE_LENGTH
    31723275          ebuf->eol = p - 1;
    31733276#endif
    3174           break;
    3175         }
     3277          break;
     3278        }
    31763279
    31773280      /* It was a backslash/newline combo.  If we have more space, read
     
    32253328     w_dcolon       A double-colon
    32263329     w_semicolon    A semicolon
    3227      w_varassign    A variable assignment operator (=, :=, +=, >=, or ?=)
     3330     w_varassign    A variable assignment operator (=, :=, ::=, +=, >=, ?=, or !=)
    32283331
    32293332   Note that this function is only used when reading certain parts of the
     
    32393342
    32403343  /* Skip any leading whitespace.  */
    3241   while (isblank ((unsigned char)*p))
     3344  while (ISBLANK (*p))
    32423345    ++p;
    32433346
     
    32643367        case ':':
    32653368          ++p;
    3266           wtype = w_dcolon;
     3369          if (p[1] != '=')
     3370            wtype = w_dcolon;
     3371          else
     3372            {
     3373              wtype = w_varassign;
     3374              ++p;
     3375            }
    32673376          break;
    32683377
     
    32763385    case '+':
    32773386    case '?':
     3387    case '!':
    32783388#ifdef CONFIG_WITH_PREPEND_ASSIGNMENT
    32793389    case '>':
     
    32983408  /* This is some non-operator word.  A word consists of the longest
    32993409     string of characters that doesn't contain whitespace, one of [:=#],
    3300      or [?+]=, or one of the chars in the DELIM string.  */
     3410     or [?+!]=, or one of the chars in the DELIM string.  */
    33013411
    33023412  /* We start out assuming a static word; if we see a variable we'll
     
    33203430        case ':':
    33213431#ifdef HAVE_DOS_PATHS
    3322           /* A word CAN include a colon in its drive spec.  The drive
    3323              spec is allowed either at the beginning of a word, or as part
    3324              of the archive member name, like in "libfoo.a(d:/foo/bar.o)".  */
    3325           if (!(p - beg >= 2
    3326                 && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
    3327                 && (p - beg == 2 || p[-3] == '(')))
    3328 #endif
    3329           goto done_word;
     3432          /* A word CAN include a colon in its drive spec.  The drive
     3433             spec is allowed either at the beginning of a word, or as part
     3434             of the archive member name, like in "libfoo.a(d:/foo/bar.o)".  */
     3435          if (!(p - beg >= 2
     3436                && (*p == '/' || *p == '\\') && isalpha ((unsigned char)p[-2])
     3437                && (p - beg == 2 || p[-3] == '(')))
     3438#endif
     3439          goto done_word;
    33303440
    33313441        case '$':
     
    33333443          if (c == '$')
    33343444            break;
     3445          if (c == '\0')
     3446            goto done_word;
    33353447
    33363448          /* This is a variable reference, so note that it's expandable.
     
    34053517construct_include_path (const char **arg_dirs)
    34063518{
    3407 #ifdef VAXC             /* just don't ask ... */
     3519#ifdef VAXC             /* just don't ask ... */
    34083520  stat_t stbuf;
    34093521#else
     
    34403552    while (*arg_dirs != 0)
    34413553      {
    3442         const char *dir = *(arg_dirs++);
     3554        const char *dir = *(arg_dirs++);
    34433555        char *expanded = 0;
    34443556        int e;
    34453557
    3446         if (dir[0] == '~')
    3447           {
    3448             expanded = tilde_expand (dir);
    3449             if (expanded != 0)
    3450               dir = expanded;
    3451           }
     3558        if (dir[0] == '~')
     3559          {
     3560            expanded = tilde_expand (dir);
     3561            if (expanded != 0)
     3562              dir = expanded;
     3563          }
    34523564
    34533565        EINTRLOOP (e, stat (dir, &stbuf));
    3454         if (e == 0 && S_ISDIR (stbuf.st_mode))
     3566        if (e == 0 && S_ISDIR (stbuf.st_mode))
    34553567          {
    34563568            unsigned int len = strlen (dir);
     
    34633575          }
    34643576
    3465         if (expanded)
    3466           free (expanded);
     3577        free (expanded);
    34673578      }
    34683579
     
    34783589      {
    34793590        unsigned int len = strlen (djdir->value) + 8;
    3480         char *defdir = alloca (len + 1);
    3481 
    3482         strcat (strcpy (defdir, djdir->value), "/include");
    3483         dirs[idx++] = strcache_add (defdir);
     3591        char *defdir = alloca (len + 1);
     3592
     3593        strcat (strcpy (defdir, djdir->value), "/include");
     3594        dirs[idx++] = strcache_add (defdir);
    34843595
    34853596        if (len > max_incl_len)
     
    35363647  if (name[1] == '/' || name[1] == '\0')
    35373648    {
    3538       extern char *getenv ();
    35393649      char *home_dir;
    35403650      int is_variable;
    35413651
    35423652      {
    3543         /* Turn off --warn-undefined-variables while we expand HOME.  */
    3544         int save = warn_undefined_variables_flag;
    3545         warn_undefined_variables_flag = 0;
     3653        /* Turn off --warn-undefined-variables while we expand HOME.  */
     3654        int save = warn_undefined_variables_flag;
     3655        warn_undefined_variables_flag = 0;
    35463656
    35473657#ifndef CONFIG_WITH_VALUE_LENGTH
    3548         home_dir = allocated_variable_expand ("$(HOME)");
    3549 #else
    3550         home_dir = allocated_variable_expand_2 (STRING_SIZE_TUPLE("$(HOME)"), NULL);
    3551 #endif
    3552 
    3553         warn_undefined_variables_flag = save;
     3658        home_dir = allocated_variable_expand ("$(HOME)");
     3659#else
     3660        home_dir = allocated_variable_expand_2 (STRING_SIZE_TUPLE("$(HOME)"), NULL);
     3661#endif
     3662
     3663        warn_undefined_variables_flag = save;
    35543664      }
    35553665
    35563666      is_variable = home_dir[0] != '\0';
    35573667      if (!is_variable)
    3558         {
    3559           free (home_dir);
    3560           home_dir = getenv ("HOME");
    3561         }
     3668        {
     3669          free (home_dir);
     3670          home_dir = getenv ("HOME");
     3671        }
    35623672# if !defined(_AMIGA) && !defined(WINDOWS32)
    35633673      if (home_dir == 0 || home_dir[0] == '\0')
    3564         {
    3565           extern char *getlogin ();
    3566           char *logname = getlogin ();
    3567           home_dir = 0;
    3568           if (logname != 0)
    3569             {
    3570               struct passwd *p = getpwnam (logname);
    3571               if (p != 0)
    3572                 home_dir = p->pw_dir;
    3573             }
    3574         }
     3674        {
     3675          char *logname = getlogin ();
     3676          home_dir = 0;
     3677          if (logname != 0)
     3678            {
     3679              struct passwd *p = getpwnam (logname);
     3680              if (p != 0)
     3681                home_dir = p->pw_dir;
     3682            }
     3683        }
    35753684# endif /* !AMIGA && !WINDOWS32 */
    35763685      if (home_dir != 0)
    3577         {
    3578           char *new = xstrdup (concat (2, home_dir, name + 1));
    3579           if (is_variable)
    3580             free (home_dir);
    3581           return new;
    3582         }
     3686        {
     3687          char *new = xstrdup (concat (2, home_dir, name + 1));
     3688          if (is_variable)
     3689            free (home_dir);
     3690          return new;
     3691        }
    35833692    }
    35843693# if !defined(_AMIGA) && !defined(WINDOWS32)
     
    35883697      char *userend = strchr (name + 1, '/');
    35893698      if (userend != 0)
    3590         *userend = '\0';
     3699        *userend = '\0';
    35913700      pwent = getpwnam (name + 1);
    35923701      if (pwent != 0)
    3593         {
    3594           if (userend == 0)
    3595             return xstrdup (pwent->pw_dir);
    3596           else
    3597             return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
    3598         }
     3702        {
     3703          if (userend == 0)
     3704            return xstrdup (pwent->pw_dir);
     3705          else
     3706            return xstrdup (concat (3, pwent->pw_dir, "/", userend + 1));
     3707        }
    35993708      else if (userend != 0)
    3600         *userend = '/';
     3709        *userend = '/';
    36013710    }
    36023711# endif /* !AMIGA && !WINDOWS32 */
     
    36303739
    36313740void *
    3632 parse_file_seq (char **stringp, unsigned int size, int stopchar,
     3741parse_file_seq (char **stringp, unsigned int size, int stopmap,
    36333742                const char *prefix, int flags
    36343743                IF_WITH_ALLOC_CACHES_PARAM(struct alloccache *alloc_cache) )
    36353744{
    3636   extern void dir_setup_glob (glob_t *glob);
    3637 
    36383745  /* tmp points to tmpbuf after the prefix, if any.
    36393746     tp is the end of the buffer. */
    36403747  static char *tmpbuf = NULL;
    3641   static int tmpbuf_len = 0;
    3642 
    3643   int cachep = (! (flags & PARSEFS_NOCACHE));
     3748
     3749  int cachep = NONE_SET (flags, PARSEFS_NOCACHE);
    36443750
    36453751  struct nameseq *new = 0;
     
    36653771  char *tp;
    36663772
    3667 #ifdef VMS
    3668 # define VMS_COMMA ','
    3669 #else
    3670 # define VMS_COMMA 0
    3671 #endif
     3773  /* Always stop on NUL.  */
     3774  stopmap |= MAP_NUL;
    36723775
    36733776  if (size < sizeof (struct nameseq))
    36743777    size = sizeof (struct nameseq);
    36753778
    3676   if (! (flags & PARSEFS_NOGLOB))
     3779  if (NONE_SET (flags, PARSEFS_NOGLOB))
    36773780    dir_setup_glob (&gl);
    36783781
    36793782  /* Get enough temporary space to construct the largest possible target.  */
    36803783  {
     3784    static int tmpbuf_len = 0;
    36813785    int l = strlen (*stringp) + 1;
    36823786    if (l > tmpbuf_len)
     
    36953799      const char **nlist = 0;
    36963800      char *tildep = 0;
     3801      int globme = 1;
    36973802#ifndef NO_ARCHIVES
    36983803      char *arname = 0;
     
    37043809
    37053810      /* Skip whitespace; at the end of the string or STOPCHAR we're done.  */
    3706       p = next_token (p);
    3707       if (*p == '\0' || *p == stopchar)
    3708         break;
     3811      NEXT_TOKEN (p);
     3812      if (STOP_SET (*p, stopmap))
     3813        break;
    37093814
    37103815      /* There are names left, so find the end of the next name.
    37113816         Throughout this iteration S points to the start.  */
    37123817      s = p;
    3713       p = find_char_unquote (p, stopchar, VMS_COMMA, 1, 0);
     3818      p = find_char_unquote (p, stopmap|MAP_VMSCOMMA|MAP_BLANK IF_WITH_VALUE_LENGTH_PARAM(0));
    37143819#ifdef VMS
    3715         /* convert comma separated list to space separated */
     3820        /* convert comma separated list to space separated */
    37163821      if (p && *p == ',')
    3717         *p =' ';
     3822        *p =' ';
    37183823#endif
    37193824#ifdef _AMIGA
    3720       if (stopchar == ':' && p && *p == ':'
    3721           && !(isspace ((unsigned char)p[1]) || !p[1]
    3722                || isspace ((unsigned char)p[-1])))
    3723         p = find_char_unquote (p+1, stopchar, VMS_COMMA, 1, 0);
     3825      if (p && STOP_SET (*p, stopmap & MAP_COLON)
     3826          && !(ISSPACE (p[1]) || !p[1] || ISSPACE (p[-1])))
     3827        p = find_char_unquote (p+1, stopmap|MAP_VMSCOMMA|MAP_BLANK);
    37243828#endif
    37253829#ifdef HAVE_DOS_PATHS
     
    37283832       Note that tokens separated by spaces should be treated as separate
    37293833       tokens since make doesn't allow path names with spaces */
    3730     if (stopchar == ':')
    3731       while (p != 0 && !isspace ((unsigned char)*p) &&
     3834    if (stopmap | MAP_COLON)
     3835      while (p != 0 && !ISSPACE (*p) &&
    37323836             (p[1] == '\\' || p[1] == '/') && isalpha ((unsigned char)p[-1]))
    3733         p = find_char_unquote (p + 1, stopchar, VMS_COMMA, 1, 0);
     3837        p = find_char_unquote (p + 1, stopmap|MAP_VMSCOMMA|MAP_BLANK IF_WITH_VALUE_LENGTH_PARAM(0));
    37343838#endif
    37353839      if (p == 0)
    3736         p = s + strlen (s);
     3840        p = s + strlen (s);
    37373841
    37383842      /* Strip leading "this directory" references.  */
    3739       if (! (flags & PARSEFS_NOSTRIP))
     3843      if (NONE_SET (flags, PARSEFS_NOSTRIP))
    37403844#ifdef VMS
    3741         /* Skip leading `[]'s.  */
    3742         while (p - s > 2 && s[0] == '[' && s[1] == ']')
    3743 #else
    3744         /* Skip leading `./'s.  */
    3745         while (p - s > 2 && s[0] == '.' && s[1] == '/')
    3746 #endif
    3747           {
     3845        /* Skip leading '[]'s. should only be one set or bug somwhere else */
     3846        if (p - s > 2 && s[0] == '[' && s[1] == ']')
     3847            s += 2;
     3848        /* Skip leading '<>'s. should only be one set or bug somwhere else */
     3849        if (p - s > 2 && s[0] == '<' && s[1] == '>')
     3850            s += 2;
     3851#endif
     3852        /* Skip leading './'s.  */
     3853        while (p - s > 2 && s[0] == '.' && s[1] == '/')
     3854          {
    37483855            /* Skip "./" and all following slashes.  */
    3749             s += 2;
    3750             while (*s == '/')
    3751               ++s;
    3752           }
     3856            s += 2;
     3857            while (*s == '/')
     3858              ++s;
     3859          }
    37533860
    37543861      /* Extract the filename just found, and skip it.
     
    37573864      if (s == p)
    37583865        {
    3759         /* The name was stripped to empty ("./"). */
    3760 #if defined(VMS)
    3761           continue;
    3762 #elif defined(_AMIGA)
     3866        /* The name was stripped to empty ("./"). */
     3867#if defined(_AMIGA)
    37633868          /* PDS-- This cannot be right!! */
    37643869          tp[0] = '\0';
     
    37723877        }
    37733878      else
    3774         {
     3879        {
    37753880#ifdef VMS
    37763881/* VMS filenames can have a ':' in them but they have to be '\'ed but we need
     
    37783883 * xstrdup called because S may be read-only string constant.
    37793884 */
    3780           char *n = tp;
    3781           while (s < p)
    3782             {
    3783               if (s[0] == '\\' && s[1] == ':')
     3885          char *n = tp;
     3886          while (s < p)
     3887            {
     3888              if (s[0] == '\\' && s[1] == ':')
    37843889                ++s;
    3785               *(n++) = *(s++);
    3786             }
     3890              *(n++) = *(s++);
     3891            }
    37873892          n[0] = '\0';
    37883893          nlen = strlen (tp);
     
    38033908
    38043909         TP == TMP means we're not already in an archive group.  Ignore
    3805          something starting with `(', as that cannot actually be an
     3910         something starting with '(', as that cannot actually be an
    38063911         archive-member reference (and treating it as such results in an empty
    38073912         file name, which causes much lossage).  Also if it ends in ")" then
     
    38113916         character, so ensure there's some word ending like that before
    38123917         considering this an archive group.  */
    3813       if (! (flags & PARSEFS_NOAR)
     3918      if (NONE_SET (flags, PARSEFS_NOAR)
    38143919          && tp == tmpbuf && tp[0] != '(' && tp[nlen-1] != ')')
    38153920        {
     
    38193924              /* This looks like the first element in an open archive group.
    38203925                 A valid group MUST have ')' as the last character.  */
    3821               const char *e = p + nlen;
     3926              const char *e = p;
    38223927              do
    38233928                {
    3824                   e = next_token (e);
     3929                  const char *o = e;
     3930                  NEXT_TOKEN (e);
    38253931                  /* Find the end of this word.  We don't want to unquote and
    38263932                     we don't care about quoting since we're looking for the
    38273933                     last char in the word. */
    3828                   while (*e != '\0' && *e != stopchar && *e != VMS_COMMA
    3829                          && ! isblank ((unsigned char) *e))
     3934                  while (! STOP_SET (*e, stopmap|MAP_BLANK|MAP_VMSCOMMA))
    38303935                    ++e;
     3936                  /* If we didn't move, we're done now.  */
     3937                  if (e == o)
     3938                    break;
    38313939                  if (e[-1] == ')')
    38323940                    {
     
    38373945                      tp = n + 1;
    38383946
    3839                       /* If we have just "lib(", part of something like
    3840                          "lib( a b)", go to the next item.  */
    3841                       if (! nlen)
    3842                         continue;
    3843 
    38443947                      /* We can stop looking now.  */
    38453948                      break;
     
    38473950                }
    38483951              while (*e != '\0');
     3952
     3953              /* If we have just "lib(", part of something like "lib( a b)",
     3954                 go to the next item.  */
     3955              if (! nlen)
     3956                continue;
    38493957            }
    38503958        }
     
    38733981      /* If we're not globbing we're done: add it to the end of the chain.
    38743982         Go to the next item in the string.  */
    3875       if (flags & PARSEFS_NOGLOB)
    3876         {
    3877           NEWELT (concat (2, prefix, tp));
     3983      if (ANY_SET (flags, PARSEFS_NOGLOB))
     3984        {
     3985          NEWELT (concat (2, prefix, tmpbuf));
    38783986          continue;
    38793987        }
     
    38823990         TP is a string in tmpbuf.  NLEN is no longer used.
    38833991         We may need to do more work: after this NAME will be set.  */
    3884       name = tp;
     3992      name = tmpbuf;
    38853993
    38863994      /* Expand tilde if applicable.  */
    3887       if (tp[0] == '~')
    3888         {
    3889           tildep = tilde_expand (tp);
    3890           if (tildep != 0)
     3995      if (tmpbuf[0] == '~')
     3996        {
     3997          tildep = tilde_expand (tmpbuf);
     3998          if (tildep != 0)
    38913999            name = tildep;
    3892         }
     4000        }
    38934001
    38944002#ifndef NO_ARCHIVES
     
    38964004         file name, and save the member name in MEMNAME.  We will glob on the
    38974005         archive name and then reattach MEMNAME later.  */
    3898       if (! (flags & PARSEFS_NOAR) && ar_name (name))
    3899         {
    3900           ar_parse_name (name, &arname, &memname);
    3901           name = arname;
    3902         }
     4006      if (NONE_SET (flags, PARSEFS_NOAR) && ar_name (name))
     4007        {
     4008          ar_parse_name (name, &arname, &memname);
     4009          name = arname;
     4010        }
    39034011#endif /* !NO_ARCHIVES */
    39044012
    3905       switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
    3906         {
    3907         case GLOB_NOSPACE:
    3908           fatal (NILF, _("virtual memory exhausted"));
    3909 
    3910         case 0:
    3911           /* Success.  */
    3912           i = gl.gl_pathc;
    3913           nlist = (const char **)gl.gl_pathv;
    3914           break;
    3915 
    3916         case GLOB_NOMATCH:
    3917           /* If we want only existing items, skip this one.  */
    3918           if (flags & PARSEFS_EXISTS)
    3919             {
    3920               i = 0;
    3921               break;
    3922             }
    3923           /* FALLTHROUGH */
    3924 
    3925         default:
    3926           /* By default keep this name.  */
     4013      /* glob() is expensive: don't call it unless we need to.  */
     4014      if (NONE_SET (flags, PARSEFS_EXISTS) && strpbrk (name, "?*[") == NULL)
     4015        {
     4016          globme = 0;
    39274017          i = 1;
    39284018          nlist = &name;
    3929           break;
    3930         }
     4019        }
     4020      else
     4021        switch (glob (name, GLOB_NOSORT|GLOB_ALTDIRFUNC, NULL, &gl))
     4022          {
     4023          case GLOB_NOSPACE:
     4024            OUT_OF_MEM();
     4025
     4026          case 0:
     4027            /* Success.  */
     4028            i = gl.gl_pathc;
     4029            nlist = (const char **)gl.gl_pathv;
     4030            break;
     4031
     4032          case GLOB_NOMATCH:
     4033            /* If we want only existing items, skip this one.  */
     4034            if (ANY_SET (flags, PARSEFS_EXISTS))
     4035              {
     4036                i = 0;
     4037                break;
     4038              }
     4039            /* FALLTHROUGH */
     4040
     4041          default:
     4042            /* By default keep this name.  */
     4043            i = 1;
     4044            nlist = &name;
     4045            break;
     4046          }
    39314047
    39324048      /* For each matched element, add it to the list.  */
     
    39434059              {
    39444060                /* We got a chain of items.  Attach them.  */
    3945                 (*newp)->next = found;
     4061                if (*newp)
     4062                  (*newp)->next = found;
     4063                else
     4064                  *newp = found;
    39464065
    39474066                /* Find and set the new end.  Massage names if necessary.  */
     
    39654084          NEWELT (concat (2, prefix, nlist[i]));
    39664085
     4086      if (globme)
    39674087        globfree (&gl);
    39684088
    39694089#ifndef NO_ARCHIVES
    3970       if (arname)
    3971         free (arname);
    3972 #endif
    3973 
    3974       if (tildep)
    3975         free (tildep);
     4090      free (arname);
     4091#endif
     4092
     4093      free (tildep);
    39764094    }
    39774095
  • trunk/src/kmk/remake.c

    r2857 r3140  
    11/* Basic dependency engine for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018#include "filedef.h"
    2119#include "job.h"
     
    4038#endif
    4139
    42 extern int try_implicit_rule (struct file *file, unsigned int depth);
    43 
    4440
    4541/* The test for circular dependencies is based on the 'updating' bit in
    46    `struct file'.  However, double colon targets have seperate `struct
     42   'struct file'.  However, double colon targets have separate 'struct
    4743   file's; make sure we always use the base of the double colon chain. */
    4844
     
    5854unsigned int commands_started = 0;
    5955
    60 /* Current value for pruning the scan of the goal chain (toggle 0/1).  */
    61 static unsigned int considered;
    62 
    63 static int update_file (struct file *file, unsigned int depth);
    64 static int update_file_1 (struct file *file, unsigned int depth);
    65 static int check_dep (struct file *file, unsigned int depth,
    66                       FILE_TIMESTAMP this_mtime, int *must_make_ptr);
    67 #ifdef CONFIG_WITH_DOT_MUST_MAKE
    68 static int call_must_make_target_var (struct file *file, unsigned int depth);
    69 #endif
    70 #ifdef CONFIG_WITH_DOT_IS_CHANGED
    71 static int call_is_changed_target_var (struct file *file);
    72 #endif
    73 static int touch_file (struct file *file);
     56/* Set to the goal dependency.  Mostly needed for remaking makefiles.  */
     57static struct goaldep *goal_list;
     58static struct dep *goal_dep;
     59
     60/* Current value for pruning the scan of the goal chain.
     61   All files start with considered == 0.  */
     62static unsigned int considered = 0;
     63
     64static enum update_status update_file (struct file *file, unsigned int depth);
     65static enum update_status update_file_1 (struct file *file, unsigned int depth);
     66static enum update_status check_dep (struct file *file, unsigned int depth,
     67                                     FILE_TIMESTAMP this_mtime, int *must_make);
     68static enum update_status touch_file (struct file *file);
    7469static void remake_file (struct file *file);
    7570static FILE_TIMESTAMP name_mtime (const char *name);
    7671static const char *library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr);
    7772
    78 
    79 
    80 /* Remake all the goals in the `struct dep' chain GOALS.  Return -1 if nothing
     73#ifdef CONFIG_WITH_DOT_MUST_MAKE
     74static int call_must_make_target_var (struct file *file, unsigned int depth);
     75#endif
     76#ifdef CONFIG_WITH_DOT_IS_CHANGED
     77static int call_is_changed_target_var (struct file *file);
     78#endif
     79
     80
     81
     82/* Remake all the goals in the 'struct dep' chain GOALS.  Return -1 if nothing
    8183   was done, 0 if all goals were updated successfully, or 1 if a goal failed.
    8284
     
    8486   and -n should be disabled for them unless they were also command-line
    8587   targets, and we should only make one goal at a time and return as soon as
    86    one goal whose `changed' member is nonzero is successfully made.  */
    87 
    88 int
    89 update_goal_chain (struct dep *goals)
     88   one goal whose 'changed' member is nonzero is successfully made.  */
     89
     90enum update_status
     91update_goal_chain (struct goaldep *goaldeps)
    9092{
    9193  int t = touch_flag, q = question_flag, n = just_print_flag;
    92   int status = -1;
    93 
    94 #define MTIME(file) (rebuilding_makefiles ? file_mtime_no_search (file) \
    95                      : file_mtime (file))
     94  enum update_status status = us_none;
    9695
    9796  /* Duplicate the chain so we can remove things from it.  */
    9897
    99   goals = copy_dep_chain (goals);
    100 
    101   {
    102     /* Clear the `changed' flag of each goal in the chain.
    103        We will use the flag below to notice when any commands
    104        have actually been run for a target.  When no commands
    105        have been run, we give an "up to date" diagnostic.  */
    106 
    107     struct dep *g;
    108     for (g = goals; g != 0; g = g->next)
    109       g->changed = 0;
    110   }
    111 
    112   /* All files start with the considered bit 0, so the global value is 1.  */
    113   considered = 1;
     98  struct dep *goals = copy_dep_chain ((struct dep *)goaldeps);
     99
     100  goal_list = rebuilding_makefiles ? goaldeps : NULL;
     101
     102#define MTIME(file) (rebuilding_makefiles ? file_mtime_no_search (file) \
     103                     : file_mtime (file))
     104
     105  /* Start a fresh batch of consideration.  */
     106  ++considered;
    114107
    115108  /* Update all the goals until they are all finished.  */
     
    130123      g = goals;
    131124      while (g != 0)
    132         {
    133           /* Iterate over all double-colon entries for this file.  */
    134           struct file *file;
    135           int stop = 0, any_not_updated = 0;
    136 
    137           for (file = g->file->double_colon ? g->file->double_colon : g->file;
    138                file != NULL;
    139                file = file->prev)
    140             {
    141               unsigned int ocommands_started;
    142               int x;
    143 
    144               file->dontcare = g->dontcare;
    145 
    146               check_renamed (file);
    147               if (rebuilding_makefiles)
    148                 {
    149                   if (file->cmd_target)
    150                     {
    151                       touch_flag = t;
    152                       question_flag = q;
    153                       just_print_flag = n;
    154                     }
    155                   else
    156                     touch_flag = question_flag = just_print_flag = 0;
    157                 }
    158 
    159               /* Save the old value of `commands_started' so we can compare
    160                  later.  It will be incremented when any commands are
    161                  actually run.  */
    162               ocommands_started = commands_started;
    163 
    164               x = update_file (file, rebuilding_makefiles ? 1 : 0);
    165               check_renamed (file);
    166 
    167               /* Set the goal's `changed' flag if any commands were started
    168                  by calling update_file above.  We check this flag below to
    169                  decide when to give an "up to date" diagnostic.  */
     125        {
     126          /* Iterate over all double-colon entries for this file.  */
     127          struct file *file;
     128          int stop = 0, any_not_updated = 0;
     129
     130          goal_dep = g;
     131
     132          for (file = g->file->double_colon ? g->file->double_colon : g->file;
     133               file != NULL;
     134               file = file->prev)
     135            {
     136              unsigned int ocommands_started;
     137              enum update_status fail;
     138
     139              file->dontcare = ANY_SET (g->flags, RM_DONTCARE);
     140
     141              check_renamed (file);
     142              if (rebuilding_makefiles)
     143                {
     144                  if (file->cmd_target)
     145                    {
     146                      touch_flag = t;
     147                      question_flag = q;
     148                      just_print_flag = n;
     149                    }
     150                  else
     151                    touch_flag = question_flag = just_print_flag = 0;
     152                }
     153
     154              /* Save the old value of 'commands_started' so we can compare
     155                 later.  It will be incremented when any commands are
     156                 actually run.  */
     157              ocommands_started = commands_started;
     158
     159              fail = update_file (file, rebuilding_makefiles ? 1 : 0);
     160              check_renamed (file);
     161
     162              /* Set the goal's 'changed' flag if any commands were started
     163                 by calling update_file above.  We check this flag below to
     164                 decide when to give an "up to date" diagnostic.  */
    170165              if (commands_started > ocommands_started)
    171166                g->changed = 1;
    172167
    173               /* If we updated a file and STATUS was not already 1, set it to
    174                  1 if updating failed, or to 0 if updating succeeded.  Leave
    175                  STATUS as it is if no updating was done.  */
    176 
    177               stop = 0;
    178               if ((x != 0 || file->updated) && status < 1)
     168              stop = 0;
     169              if ((fail || file->updated) && status < us_question)
    179170                {
    180                   if (file->update_status != 0)
     171                  /* We updated this goal.  Update STATUS and decide whether
     172                     to stop.  */
     173                  if (file->update_status)
    181174                    {
    182175                      /* Updating failed, or -q triggered.  The STATUS value
     
    205198                          if (!rebuilding_makefiles
    206199                              || (!just_print_flag && !question_flag))
    207                             status = 0;
     200                            status = us_success;
    208201                          if (rebuilding_makefiles && file->dontcare)
    209202                            /* This is a default makefile; stop remaking.  */
     
    213206                }
    214207
    215               /* Keep track if any double-colon entry is not finished.
     208              /* Keep track if any double-colon entry is not finished.
    216209                 When they are all finished, the goal is finished.  */
    217               any_not_updated |= !file->updated;
     210              any_not_updated |= !file->updated;
    218211
    219212              file->dontcare = 0;
    220213
    221               if (stop)
    222                 break;
    223             }
    224 
    225           /* Reset FILE since it is null at the end of the loop.  */
    226           file = g->file;
    227 
    228           if (stop || !any_not_updated)
    229             {
    230               /* If we have found nothing whatever to do for the goal,
    231                 print a message saying nothing needs doing.  */
    232 
    233               if (!rebuilding_makefiles
    234                   /* If the update_status is zero, we updated successfully
    235                      or not at all.  G->changed will have been set above if
    236                      any commands were actually started for this goal.  */
    237                   && file->update_status == 0 && !g->changed
    238                   /* Never give a message under -s or -q.  */
    239                   && !silent_flag && !question_flag)
    240                 message (1, ((file->phony || file->cmds == 0)
    241                              ? _("Nothing to be done for `%s'.")
    242                              : _("`%s' is up to date.")),
    243                         file->name);
    244 
    245               /* This goal is finished.  Remove it from the chain.  */
    246               if (lastgoal == 0)
    247                 goals = g->next;
    248               else
    249                 lastgoal->next = g->next;
    250 
    251               /* Free the storage.  */
     214              if (stop)
     215                break;
     216            }
     217
     218          /* Reset FILE since it is null at the end of the loop.  */
     219          file = g->file;
     220
     221          if (stop || !any_not_updated)
     222            {
     223              /* If we have found nothing whatever to do for the goal,
     224                print a message saying nothing needs doing.  */
     225
     226              if (!rebuilding_makefiles
     227                  /* If the update_status is success, we updated successfully
     228                     or not at all.  G->changed will have been set above if
     229                     any commands were actually started for this goal.  */
     230                  && file->update_status == us_success && !g->changed
     231                  /* Never give a message under -s or -q.  */
     232                  && !silent_flag && !question_flag)
     233                OS (message, 1, ((file->phony || file->cmds == 0)
     234                                 ? _("Nothing to be done for '%s'.")
     235                                 : _("'%s' is up to date.")),
     236                    file->name);
     237
     238              /* This goal is finished.  Remove it from the chain.  */
     239              if (lastgoal == 0)
     240                goals = g->next;
     241              else
     242                lastgoal->next = g->next;
     243
     244              /* Free the storage.  */
    252245#ifndef CONFIG_WITH_ALLOC_CACHES
    253               free (g);
     246              free (g);
    254247#else
    255248              free_dep (g);
    256249#endif
    257250
    258               g = lastgoal == 0 ? goals : lastgoal->next;
    259 
    260               if (stop)
    261                 break;
    262             }
    263           else
    264             {
    265               lastgoal = g;
    266               g = g->next;
    267             }
    268         }
    269 
    270       /* If we reached the end of the dependency graph toggle the considered
    271          flag for the next pass.  */
     251              g = lastgoal == 0 ? goals : lastgoal->next;
     252
     253              if (stop)
     254                break;
     255            }
     256          else
     257            {
     258              lastgoal = g;
     259              g = g->next;
     260            }
     261        }
     262
     263      /* If we reached the end of the dependency graph update CONSIDERED
     264         for the next pass.  */
    272265      if (g == 0)
    273         considered = !considered;
     266        ++considered;
    274267    }
    275268
     
    285278
    286279
     280/* If we're rebuilding an included makefile that failed, and we care
     281   about errors, show an error message the first time.  */
     282
     283void
     284show_goal_error (void)
     285{
     286  struct goaldep *goal;
     287
     288  if ((goal_dep->flags & (RM_INCLUDED|RM_DONTCARE)) != RM_INCLUDED)
     289    return;
     290
     291  for (goal = goal_list; goal; goal = goal->next)
     292    if (goal_dep->file == goal->file)
     293      {
     294        if (goal->error)
     295          {
     296            OSS (error, &goal->floc, "%s: %s",
     297                 goal->file->name, strerror ((int)goal->error));
     298            goal->error = 0;
     299          }
     300        return;
     301      }
     302}
     303
     304
    287305/* If FILE is not up to date, execute the commands for it.
    288    Return 0 if successful, 1 if unsuccessful;
    289    but with some flag settings, just call `exit' if unsuccessful.
     306   Return 0 if successful, non-0 if unsuccessful;
     307   but with some flag settings, just call 'exit' if unsuccessful.
    290308
    291309   DEPTH is the depth in recursions of this function.
     
    297315   each is considered in turn.  */
    298316
    299 static int
     317static enum update_status
    300318update_file (struct file *file, unsigned int depth)
    301319{
    302   register int status = 0;
    303   register struct file *f;
     320  enum update_status status = us_success;
     321  struct file *f;
    304322
    305323  f = file->double_colon ? file->double_colon : file;
     
    312330    {
    313331      /* Check for the case where a target has been tried and failed but
    314          the diagnostics hasn't been issued. If we need the diagnostics
     332         the diagnostics haven't been issued. If we need the diagnostics
    315333         then we will have to continue. */
    316       if (!(f->updated && f->update_status > 0 && !f->dontcare && f->no_diag))
    317         {
    318           DBF (DB_VERBOSE, _("Pruning file `%s'.\n"));
    319           return f->command_state == cs_finished ? f->update_status : 0;
     334      if (!(f->updated && f->update_status > us_none
     335            && !f->dontcare && f->no_diag))
     336        {
     337          DBF (DB_VERBOSE, _("Pruning file '%s'.\n"));
     338          return f->command_state == cs_finished ? f->update_status : us_success;
    320339        }
    321340    }
     
    325344  for (; f != 0; f = f->prev)
    326345    {
     346      enum update_status new;
     347
    327348      f->considered = considered;
    328349
    329       status |= update_file_1 (f, depth);
     350      new = update_file_1 (f, depth);
    330351      check_renamed (f);
    331352
     
    334355
    335356      /* If we got an error, don't bother with double_colon etc.  */
    336       if (status != 0 && !keep_going_flag)
    337         return status;
     357      if (new && !keep_going_flag)
     358        return new;
    338359
    339360      if (f->command_state == cs_running
    340361          || f->command_state == cs_deps_running)
    341         {
    342           /* Don't run the other :: rules for this
    343              file until this rule is finished.  */
    344           status = 0;
    345           break;
    346         }
     362        /* Don't run other :: rules for this target until
     363           this rule is finished.  */
     364        return us_success;
     365
     366      if (new > status)
     367        status = new;
    347368    }
    348369
     
    357378
    358379        for (d = f->deps; d != 0; d = d->next)
    359           status |= update_file (d->file, depth + 1);
     380          {
     381            enum update_status new = update_file (d->file, depth + 1);
     382            if (new > status)
     383              status = new;
     384          }
    360385      }
    361386
     
    369394complain (struct file *file)
    370395{
    371   const char *msg_noparent
    372     = _("%sNo rule to make target `%s'%s");
    373   const char *msg_parent
    374     = _("%sNo rule to make target `%s', needed by `%s'%s");
    375 
    376396  /* If this file has no_diag set then it means we tried to update it
    377397     before in the dontcare mode and failed. The target that actually
     
    384404  for (d = file->deps; d != 0; d = d->next)
    385405    {
    386       if (d->file->updated && d->file->update_status > 0 && file->no_diag)
     406      if (d->file->updated && d->file->update_status > us_none && file->no_diag)
    387407        {
    388408          complain (d->file);
     
    393413  if (d == 0)
    394414    {
     415      show_goal_error ();
     416
    395417      /* Didn't find any dependencies to complain about. */
    396418
     
    435457#endif /* KMK */
    436458
    437       if (!keep_going_flag)
    438         {
    439           if (file->parent == 0)
    440             fatal (NILF, msg_noparent, "", file->name, "");
    441 
    442           fatal (NILF, msg_parent, "", file->name, file->parent->name, "");
    443         }
    444 
    445       if (file->parent == 0)
    446         error (NILF, msg_noparent, "*** ", file->name, ".");
     459      if (file->parent)
     460        {
     461          size_t l = strlen (file->name) + strlen (file->parent->name) + 4;
     462          const char *m = _("%sNo rule to make target '%s', needed by '%s'%s");
     463
     464          if (!keep_going_flag)
     465            fatal (NILF, l, m, "", file->name, file->parent->name, "");
     466
     467          error (NILF, l, m, "*** ", file->name, file->parent->name, ".");
     468        }
    447469      else
    448         error (NILF, msg_parent, "*** ", file->name, file->parent->name, ".");
     470        {
     471          size_t l = strlen (file->name) + 4;
     472          const char *m = _("%sNo rule to make target '%s'%s");
     473
     474          if (!keep_going_flag)
     475            fatal (NILF, l, m, "", file->name, "");
     476
     477          error (NILF, l, m, "*** ", file->name, ".");
     478        }
    449479
    450480      file->no_diag = 0;
     
    452482}
    453483
    454 /* Consider a single `struct file' and update it as appropriate.  */
    455 
    456 static int
     484/* Consider a single 'struct file' and update it as appropriate.
     485   Return 0 on success, or non-0 on failure.  */
     486
     487static enum update_status
    457488update_file_1 (struct file *file, unsigned int depth)
    458489{
     490  enum update_status dep_status = us_success;
    459491  FILE_TIMESTAMP this_mtime;
    460492  int noexist, must_make, deps_changed;
    461   int dep_status = 0;
    462493  struct file *ofile;
    463494  struct dep *d, *ad;
     
    482513    {
    483514      if (file->multi_head == file)
    484         DBS (DB_VERBOSE, (_("Considering target file `%s'  (multi head).\n"), file->name));
     515        DBS (DB_VERBOSE, (_("Considering target file '%s'  (multi head).\n"), file->name));
    485516      else
    486517        {
    487518          org_file = file = file->multi_head;
    488           DBS (DB_VERBOSE, (_("Considering target file `%s' -> multi head `%s'.\n"),
     519          DBS (DB_VERBOSE, (_("Considering target file '%s' -> multi head '%s'.\n"),
    489520                              req_file->name, file->name));
    490521          assert (file->multi_head == file);
     
    493524  else
    494525#endif /* CONFIG_WITH_EXPLICIT_MULTITARGET */
    495     DBF (DB_VERBOSE, _("Considering target file `%s'.\n"));
     526    DBF (DB_VERBOSE, _("Considering target file '%s'.\n"));
    496527
    497528  if (file->updated)
    498529    {
    499       if (file->update_status > 0)
    500         {
    501           DBF (DB_VERBOSE,
    502                _("Recently tried and failed to update file `%s'.\n"));
     530      if (file->update_status > us_none)
     531        {
     532          DBF (DB_VERBOSE,
     533               _("Recently tried and failed to update file '%s'.\n"));
    503534
    504535          /* If the file we tried to make is marked no_diag then no message
     
    509540              complain (file);
    510541
    511           return file->update_status;
    512         }
    513 
    514       DBF (DB_VERBOSE, _("File `%s' was considered already.\n"));
     542          return file->update_status;
     543        }
     544
     545      DBF (DB_VERBOSE, _("File '%s' was considered already.\n"));
    515546      return 0;
    516547    }
     
    522553      break;
    523554    case cs_running:
    524       DBF (DB_VERBOSE, _("Still updating file `%s'.\n"));
     555      DBF (DB_VERBOSE, _("Still updating file '%s'.\n"));
    525556      return 0;
    526557    case cs_finished:
    527       DBF (DB_VERBOSE, _("Finished updating file `%s'.\n"));
     558      DBF (DB_VERBOSE, _("Finished updating file '%s'.\n"));
    528559      return file->update_status;
    529560    default:
     
    582613  noexist = this_mtime == NONEXISTENT_MTIME;
    583614  if (noexist)
    584     DBS (DB_BASIC, (_("File `%s' does not exist.\n"), f3->name));
     615    DBS (DB_BASIC, (_("File '%s' does not exist.\n"), f3->name));
    585616#else /* !CONFIG_WITH_EXPLICIT_MULTITARGET */
    586617  this_mtime = file_mtime (file);
     
    588619  noexist = this_mtime == NONEXISTENT_MTIME;
    589620  if (noexist)
    590     DBF (DB_BASIC, _("File `%s' does not exist.\n"));
     621    DBF (DB_BASIC, _("File '%s' does not exist.\n"));
    591622#endif /* !CONFIG_WITH_EXPLICIT_MULTITARGET */
    592623  else if (ORDINARY_MTIME_MIN <= this_mtime && this_mtime <= ORDINARY_MTIME_MAX
    593            && file->low_resolution_time)
     624           && file->low_resolution_time)
    594625    {
    595626      /* Avoid spurious rebuilds due to low resolution time stamps.  */
    596627      int ns = FILE_TIMESTAMP_NS (this_mtime);
    597628      if (ns != 0)
    598         error (NILF, _("*** Warning: .LOW_RESOLUTION_TIME file `%s' has a high resolution time stamp"),
    599                file->name);
     629        OS (error, NILF,
     630            _("*** Warning: .LOW_RESOLUTION_TIME file '%s' has a high resolution time stamp"),
     631            file->name);
    600632      this_mtime += FILE_TIMESTAMPS_PER_S - 1 - ns;
    601633    }
     
    609641    {
    610642      if (try_implicit_rule (file, depth))
    611         DBF (DB_IMPLICIT, _("Found an implicit rule for `%s'.\n"));
     643        DBF (DB_IMPLICIT, _("Found an implicit rule for '%s'.\n"));
    612644      else
    613         DBF (DB_IMPLICIT, _("No implicit rule found for `%s'.\n"));
     645        DBF (DB_IMPLICIT, _("No implicit rule found for '%s'.\n"));
    614646      file->tried_implicit = 1;
    615647    }
     
    617649      && default_file != 0 && default_file->cmds != 0)
    618650    {
    619       DBF (DB_IMPLICIT, _("Using default recipe for `%s'.\n"));
     651      DBF (DB_IMPLICIT, _("Using default recipe for '%s'.\n"));
    620652      file->cmds = default_file->cmds;
    621653    }
     
    648680      while (d)
    649681        {
     682          enum update_status new;
    650683          FILE_TIMESTAMP mtime;
    651684          int maybe_make;
     
    669702#endif
    670703
    671               error (NILF, _("Circular %s <- %s dependency dropped."),
    672                      file->name, d->file->name);
     704              OSS (error, NILF, _("Circular %s <- %s dependency dropped."),
     705                   file->name, d->file->name);
    673706              /* We cannot free D here because our the caller will still have
    674707                 a reference to it when we were called recursively via
     
    692725            }
    693726
    694           dep_status |= check_dep (d->file, depth, this_mtime, &maybe_make);
     727          new = check_dep (d->file, depth, this_mtime, &maybe_make);
     728          if (new > dep_status)
     729            dep_status = new;
    695730
    696731          /* Restore original dontcare flag. */
     
    716751          }
    717752
    718           if (dep_status != 0 && !keep_going_flag)
     753          if (dep_status && !keep_going_flag)
    719754            break;
    720755
    721756          if (!running)
    722             /* The prereq is considered changed if the timestamp has changed while
    723                it was built, OR it doesn't exist.  */
     757            /* The prereq is considered changed if the timestamp has changed
     758               while it was built, OR it doesn't exist.  */
    724759            d->changed = ((file_mtime (d->file) != mtime)
    725760                          || (mtime == NONEXISTENT_MTIME));
     
    757792    {
    758793#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    759       for (file = f2 = org_file; f2; file = f2 = f2->multi_next)
    760 #endif
    761         for (d = file->deps; d != 0; d = d->next)
    762           if (d->file->intermediate)
     794     for (file = f2 = org_file; f2; file = f2 = f2->multi_next)
     795#endif
     796      for (d = file->deps; d != 0; d = d->next)
     797        if (d->file->intermediate)
     798          {
     799            enum update_status new;
     800            int dontcare = 0;
     801
     802            FILE_TIMESTAMP mtime = file_mtime (d->file);
     803            check_renamed (d->file);
     804            d->file->parent = file;
     805
     806            /* Inherit dontcare flag from our parent. */
     807            if (rebuilding_makefiles)
     808              {
     809                dontcare = d->file->dontcare;
     810                d->file->dontcare = file->dontcare;
     811              }
     812
     813            /* We may have already considered this file, when we didn't know
     814               we'd need to update it.  Force update_file() to consider it and
     815               not prune it.  */
     816            d->file->considered = 0;
     817
     818            new = update_file (d->file, depth);
     819            if (new > dep_status)
     820              dep_status = new;
     821
     822            /* Restore original dontcare flag. */
     823            if (rebuilding_makefiles)
     824              d->file->dontcare = dontcare;
     825
     826            check_renamed (d->file);
     827
    763828            {
    764               int dontcare = 0;
    765 
    766               FILE_TIMESTAMP mtime = file_mtime (d->file);
    767               check_renamed (d->file);
    768               d->file->parent = file;
    769 
    770               /* Inherit dontcare flag from our parent. */
    771               if (rebuilding_makefiles)
     829              register struct file *f = d->file;
     830              if (f->double_colon)
     831                f = f->double_colon;
     832              do
    772833                {
    773                   dontcare = d->file->dontcare;
    774                   d->file->dontcare = file->dontcare;
     834                  running |= (f->command_state == cs_running
     835                              || f->command_state == cs_deps_running);
     836                  f = f->prev;
    775837                }
    776 
    777 
    778               dep_status |= update_file (d->file, depth);
    779 
    780               /* Restore original dontcare flag. */
    781               if (rebuilding_makefiles)
    782                 d->file->dontcare = dontcare;
    783 
    784               check_renamed (d->file);
    785 
    786               {
    787                 register struct file *f = d->file;
    788                 if (f->double_colon)
    789                 f = f->double_colon;
    790                 do
    791                 {
    792                   running |= (f->command_state == cs_running
    793                               || f->command_state == cs_deps_running);
    794                   f = f->prev;
    795                 }
    796                 while (f != 0);
    797               }
    798 
    799               if (dep_status != 0 && !keep_going_flag)
    800                 break;
    801 
    802               if (!running)
    803                 d->changed = ((file->phony && file->cmds != 0)
    804                             || file_mtime (d->file) != mtime);
     838              while (f != 0);
    805839            }
     840
     841            if (dep_status && !keep_going_flag)
     842              break;
     843
     844            if (!running)
     845              d->changed = ((file->phony && file->cmds != 0)
     846                            || file_mtime (d->file) != mtime);
     847          }
    806848#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    807849      file = org_file;
     
    812854  finish_updating (ofile);
    813855
    814   DBF (DB_VERBOSE, _("Finished prerequisites of target file `%s'.\n"));
     856  DBF (DB_VERBOSE, _("Finished prerequisites of target file '%s'.\n"));
    815857
    816858  if (running)
     
    818860      set_command_state (file, cs_deps_running);
    819861      --depth;
    820       DBF (DB_VERBOSE, _("The prerequisites of `%s' are being made.\n"));
     862      DBF (DB_VERBOSE, _("The prerequisites of '%s' are being made.\n"));
    821863      return 0;
    822864    }
     
    824866  /* If any dependency failed, give up now.  */
    825867
    826   if (dep_status != 0)
    827     {
    828       file->update_status = dep_status;
     868  if (dep_status)
     869    {
     870      /* I'm not sure if we can't just assign dep_status...  */
     871      file->update_status = dep_status == us_none ? us_failed : dep_status;
    829872      notice_finished_file (file);
    830873
    831874      --depth;
    832875
    833       DBF (DB_VERBOSE, _("Giving up on target file `%s'.\n"));
     876      DBF (DB_VERBOSE, _("Giving up on target file '%s'.\n"));
    834877
    835878      if (depth == 0 && keep_going_flag
    836           && !just_print_flag && !question_flag)
    837         error (NILF,
    838                _("Target `%s' not remade because of errors."), file->name);
     879          && !just_print_flag && !question_flag)
     880        OS (error, NILF,
     881            _("Target '%s' not remade because of errors."), file->name);
    839882
    840883      return dep_status;
     
    857900  deps_changed = 0;
    858901#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    859   for (file = f2 = org_file; f2; file = f2 = f2->multi_next)
    860 #endif
    861     for (d = file->deps; d != 0; d = d->next)
    862       {
    863         FILE_TIMESTAMP d_mtime = file_mtime (d->file);
     902 for (file = f2 = org_file; f2; file = f2 = f2->multi_next)
     903#endif
     904  for (d = file->deps; d != 0; d = d->next)
     905    {
     906      FILE_TIMESTAMP d_mtime = file_mtime (d->file);
    864907#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    865908        if (d->file == file && file->multi_maybe)
    866909          continue;
    867910#endif
    868         check_renamed (d->file);
    869 
    870         if (! d->ignore_mtime)
    871           {
     911      check_renamed (d->file);
     912
     913      if (! d->ignore_mtime)
     914        {
    872915#if 1
    873             /* %%% In version 4, remove this code completely to
    874              implement not remaking deps if their deps are newer
    875              than their parents.  */
    876             if (d_mtime == NONEXISTENT_MTIME && !d->file->intermediate)
    877               /* We must remake if this dep does not
    878                  exist and is not intermediate.  */
    879               must_make = 1;
    880 #endif
    881 
    882             /* Set DEPS_CHANGED if this dep actually changed.  */
    883             deps_changed |= d->changed;
    884           }
    885 
    886         /* Set D->changed if either this dep actually changed,
    887            or its dependent, FILE, is older or does not exist.  */
    888         d->changed |= noexist || d_mtime > this_mtime;
    889 
    890         if (!noexist && ISDB (DB_BASIC|DB_VERBOSE))
    891           {
    892             const char *fmt = 0;
    893 
    894             if (d->ignore_mtime)
    895               {
    896                 if (ISDB (DB_VERBOSE))
    897                   fmt = _("Prerequisite `%s' is order-only for target `%s'.\n");
    898               }
    899             else if (d_mtime == NONEXISTENT_MTIME)
    900               {
    901                 if (ISDB (DB_BASIC))
    902                   fmt = _("Prerequisite `%s' of target `%s' does not exist.\n");
    903               }
    904             else if (d->changed)
    905               {
    906                 if (ISDB (DB_BASIC))
    907                   fmt = _("Prerequisite `%s' is newer than target `%s'.\n");
    908               }
    909             else if (ISDB (DB_VERBOSE))
    910               fmt = _("Prerequisite `%s' is older than target `%s'.\n");
    911 
    912             if (fmt)
    913               {
    914                 print_spaces (depth);
    915                 printf (fmt, dep_name (d), file->name);
    916                 fflush (stdout);
    917               }
    918           }
    919       }
     916          /* %%% In version 4, remove this code completely to
     917           implement not remaking deps if their deps are newer
     918           than their parents.  */
     919          if (d_mtime == NONEXISTENT_MTIME && !d->file->intermediate)
     920            /* We must remake if this dep does not
     921               exist and is not intermediate.  */
     922            must_make = 1;
     923#endif
     924
     925          /* Set DEPS_CHANGED if this dep actually changed.  */
     926          deps_changed |= d->changed;
     927        }
     928
     929      /* Set D->changed if either this dep actually changed,
     930         or its dependent, FILE, is older or does not exist.  */
     931      d->changed |= noexist || d_mtime > this_mtime;
     932
     933      if (!noexist && ISDB (DB_BASIC|DB_VERBOSE))
     934        {
     935          const char *fmt = 0;
     936
     937          if (d->ignore_mtime)
     938            {
     939              if (ISDB (DB_VERBOSE))
     940                fmt = _("Prerequisite '%s' is order-only for target '%s'.\n");
     941            }
     942          else if (d_mtime == NONEXISTENT_MTIME)
     943            {
     944              if (ISDB (DB_BASIC))
     945                fmt = _("Prerequisite '%s' of target '%s' does not exist.\n");
     946            }
     947          else if (d->changed)
     948            {
     949              if (ISDB (DB_BASIC))
     950                fmt = _("Prerequisite '%s' is newer than target '%s'.\n");
     951            }
     952          else if (ISDB (DB_VERBOSE))
     953            fmt = _("Prerequisite '%s' is older than target '%s'.\n");
     954
     955          if (fmt)
     956            {
     957              print_spaces (depth);
     958              printf (fmt, dep_name (d), file->name);
     959              fflush (stdout);
     960            }
     961        }
     962    }
    920963#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    921964  file = org_file;
     
    929972      must_make = 1;
    930973      DBF (DB_BASIC,
    931            _("Target `%s' is double-colon and has no prerequisites.\n"));
     974           _("Target '%s' is double-colon and has no prerequisites.\n"));
    932975    }
    933976  else if (!noexist && file->is_target && !deps_changed && file->cmds == 0
     
    936979      must_make = 0;
    937980      DBF (DB_VERBOSE,
    938            _("No recipe for `%s' and no prerequisites actually changed.\n"));
     981           _("No recipe for '%s' and no prerequisites actually changed.\n"));
    939982    }
    940983  else if (!must_make && file->cmds != 0 && always_make_flag)
    941984    {
    942985      must_make = 1;
    943       DBF (DB_VERBOSE, _("Making `%s' due to always-make flag.\n"));
     986      DBF (DB_VERBOSE, _("Making '%s' due to always-make flag.\n"));
    944987    }
    945988
     
    949992        {
    950993          print_spaces (depth);
    951           printf (_("No need to remake target `%s'"), file->name);
     994          printf (_("No need to remake target '%s'"), file->name);
    952995          if (!streq (file->name, file->hname))
    953               printf (_("; using VPATH name `%s'"), file->hname);
     996              printf (_("; using VPATH name '%s'"), file->hname);
    954997          puts (".");
    955998          fflush (stdout);
     
    9711014    }
    9721015
    973   DBF (DB_BASIC, _("Must remake target `%s'.\n"));
     1016  DBF (DB_BASIC, _("Must remake target '%s'.\n"));
    9741017
    9751018  /* It needs to be remade.  If it's VPATH and not reset via GPATH, toss the
    9761019     VPATH.  */
    977   if (!streq(file->name, file->hname))
    978     {
    979       DB (DB_BASIC, (_("  Ignoring VPATH name `%s'.\n"), file->hname));
     1020  if (!streq (file->name, file->hname))
     1021    {
     1022      DB (DB_BASIC, (_("  Ignoring VPATH name '%s'.\n"), file->hname));
    9801023      file->ignore_vpath = 1;
    9811024    }
     
    9861029  if (file->command_state != cs_finished)
    9871030    {
    988       DBF (DB_VERBOSE, _("Recipe of `%s' is being run.\n"));
     1031      DBF (DB_VERBOSE, _("Recipe of '%s' is being run.\n"));
    9891032      return 0;
    9901033    }
     
    9921035  switch (file->update_status)
    9931036    {
    994     case 2:
    995       DBF (DB_BASIC, _("Failed to remake target file `%s'.\n"));
     1037    case us_failed:
     1038      DBF (DB_BASIC, _("Failed to remake target file '%s'.\n"));
    9961039      break;
    997     case 0:
    998       DBF (DB_BASIC, _("Successfully remade target file `%s'.\n"));
     1040    case us_success:
     1041      DBF (DB_BASIC, _("Successfully remade target file '%s'.\n"));
    9991042      break;
    1000     case 1:
    1001       DBF (DB_BASIC, _("Target file `%s' needs remade under -q.\n"));
     1043    case us_question:
     1044      DBF (DB_BASIC, _("Target file '%s' needs to be remade under -q.\n"));
    10021045      break;
    1003     default:
    1004       assert (file->update_status >= 0 && file->update_status <= 2);
     1046    case us_none:
    10051047      break;
    10061048    }
     
    10091051  return file->update_status;
    10101052}
     1053
     1054
    10111055#ifdef CONFIG_WITH_DOT_MUST_MAKE
    1012 
    1013 
    10141056/* Consider the .MUST_MAKE target variable if present.
    10151057
     
    10481090
    10491091          ch = *str;
    1050           while (isspace (ch))
     1092          while (ISSPACE (ch))
    10511093            ch = *++str;
    10521094
     
    10661108}
    10671109#endif /* CONFIG_WITH_DOT_MUST_MAKE */
     1110
     1111
    10681112#ifdef CONFIG_WITH_DOT_IS_CHANGED
    1069 
    1070 
    10711113/* Consider the .IS_CHANGED target variable if present.
    10721114
     
    11041146          do
    11051147            ch = *str++;
    1106           while (isspace (ch));
     1148          while (ISSPACE (ch));
    11071149
    11081150          return (ch != '\0');
     
    11141156
    11151157
    1116 /* Set FILE's `updated' flag and re-check its mtime and the mtime's of all
    1117    files listed in its `also_make' member.  Under -t, this function also
     1158/* Set FILE's 'updated' flag and re-check its mtime and the mtime's of all
     1159   files listed in its 'also_make' member.  Under -t, this function also
    11181160   touches FILE.
    11191161
    1120    On return, FILE->update_status will no longer be -1 if it was.  */
     1162   On return, FILE->update_status will no longer be us_none if it was.  */
    11211163
    11221164void
     
    11611203  if (touch_flag
    11621204      /* The update status will be:
    1163                 -1      if this target was not remade;
    1164                 0       if 0 or more commands (+ or ${MAKE}) were run and won;
    1165                 1       if some commands were run and lost.
    1166         We touch the target if it has commands which either were not run
    1167         or won when they ran (i.e. status is 0).  */
    1168       && file->update_status == 0)
     1205           us_success   if 0 or more commands (+ or ${MAKE}) were run and won;
     1206           us_none      if this target was not remade;
     1207           >us_none     if some commands were run and lost.
     1208        We touch the target if it has commands which either were not run
     1209        or won when they ran (i.e. status is 0).  */
     1210      && file->update_status == us_success)
    11691211    {
    11701212      if (file->cmds != 0 && file->cmds->any_recurse)
    1171         {
    1172           /* If all the command lines were recursive,
    1173              we don't want to do the touching.  */
    1174           unsigned int i;
    1175           for (i = 0; i < file->cmds->ncommand_lines; ++i)
    1176             if (!(file->cmds->lines_flags[i] & COMMANDS_RECURSE))
    1177               goto have_nonrecursing;
    1178         }
     1213        {
     1214          /* If all the command lines were recursive,
     1215             we don't want to do the touching.  */
     1216          unsigned int i;
     1217          for (i = 0; i < file->cmds->ncommand_lines; ++i)
     1218            if (!(file->cmds->lines_flags[i] & COMMANDS_RECURSE))
     1219              goto have_nonrecursing;
     1220        }
    11791221      else
    1180         {
    1181         have_nonrecursing:
    1182           if (file->phony)
     1222        {
     1223        have_nonrecursing:
     1224          if (file->phony)
    11831225#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    11841226            {
    1185               file->update_status = 0;
     1227              file->update_status = us_success;
    11861228              if (file->multi_head)
    11871229                for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
    1188                   f2->update_status = 0;
     1230                  f2->update_status = us_success;
    11891231            }
    11901232#else
    1191             file->update_status = 0;
     1233            file->update_status = us_success;
    11921234#endif
    11931235          /* According to POSIX, -t doesn't affect targets with no cmds.  */
    1194           else if (file->cmds != 0)
     1236          else if (file->cmds != 0)
    11951237            {
    11961238              /* Should set file's modification date and do nothing else.  */
     
    12051247
    12061248              /* Pretend we ran a real touch command, to suppress the
    1207                  "`foo' is up to date" message.  */
     1249                 "'foo' is up to date" message.  */
    12081250              commands_started++;
    12091251
     
    12141256              touched = 1;
    12151257            }
    1216         }
     1258        }
    12171259    }
    12181260
     
    12441286
    12451287      else if (file->is_target && file->cmds == 0)
    1246         i = 1;
     1288        i = 1;
    12471289
    12481290      file->last_mtime = i == 0 ? UNKNOWN_MTIME : NEW_MTIME;
     
    12821324    }
    12831325
    1284   if (ran && file->update_status != -1)
     1326  if (ran && file->update_status != us_none)
    12851327#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    1286     {
    1287 #endif
    1288       /* We actually tried to update FILE, which has
    1289          updated its also_make's as well (if it worked).
    1290          If it didn't work, it wouldn't work again for them.
    1291          So mark them as updated with the same status.  */
    1292       for (d = file->also_make; d != 0; d = d->next)
    1293         {
    1294           d->file->command_state = cs_finished;
    1295           d->file->updated = 1;
    1296           d->file->update_status = file->update_status;
    1297 
    1298           if (ran && !d->file->phony)
    1299             /* Fetch the new modification time.
    1300                We do this instead of just invalidating the cached time
    1301                so that a vpath_search can happen.  Otherwise, it would
    1302                never be done because the target is already updated.  */
    1303             f_mtime (d->file, 0);
    1304         }
     1328   {
     1329#endif
     1330    /* We actually tried to update FILE, which has
     1331       updated its also_make's as well (if it worked).
     1332       If it didn't work, it wouldn't work again for them.
     1333       So mark them as updated with the same status.  */
     1334    for (d = file->also_make; d != 0; d = d->next)
     1335      {
     1336        d->file->command_state = cs_finished;
     1337        d->file->updated = 1;
     1338        d->file->update_status = file->update_status;
     1339
     1340        if (ran && !d->file->phony)
     1341          /* Fetch the new modification time.
     1342             We do this instead of just invalidating the cached time
     1343             so that a vpath_search can happen.  Otherwise, it would
     1344             never be done because the target is already updated.  */
     1345          f_mtime (d->file, 0);
     1346      }
    13051347#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    1306       /* Same as above but for explicit multi target rules. */
    1307       if (file->multi_head)
    1308         for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
    1309           {
    1310             f2->update_status = file->update_status;
    1311             if (!f2->phony)
    1312               f_mtime (f2, 0);
    1313           }
    1314     }
    1315 #endif
    1316   else if (file->update_status == -1)
     1348    /* Same as above but for explicit multi target rules. */
     1349    if (file->multi_head)
     1350      for (f2 = file->multi_next; f2 != 0; f2 = f2->multi_next)
     1351        {
     1352          f2->update_status = file->update_status;
     1353          if (!f2->phony)
     1354            f_mtime (f2, 0);
     1355        }
     1356   }
     1357#endif
     1358  else if (file->update_status == us_none)
    13171359#ifdef CONFIG_WITH_EXPLICIT_MULTITARGET
    13181360    {
     
    13271369    /* Nothing was done for FILE, but it needed nothing done.
    13281370       So mark it now as "succeeded".  */
    1329     file->update_status = 0;
     1371    file->update_status = us_success;
    13301372#endif
    13311373
     
    13451387   failed.  */
    13461388
    1347 static int
     1389static enum update_status
    13481390check_dep (struct file *file, unsigned int depth,
    13491391           FILE_TIMESTAMP this_mtime, int *must_make_ptr)
     
    13511393  struct file *ofile;
    13521394  struct dep *d;
    1353   int dep_status = 0;
     1395  enum update_status dep_status = us_success;
    13541396
    13551397  ++depth;
     
    13701412      check_renamed (file);
    13711413      if (mtime == NONEXISTENT_MTIME || mtime > this_mtime)
    1372         *must_make_ptr = 1;
     1414        *must_make_ptr = 1;
    13731415#ifdef CONFIG_WITH_DOT_IS_CHANGED
    13741416      else if (   *must_make_ptr == 0
     
    13831425
    13841426      if (!file->phony && file->cmds == 0 && !file->tried_implicit)
    1385         {
    1386           if (try_implicit_rule (file, depth))
    1387             DBF (DB_IMPLICIT, _("Found an implicit rule for `%s'.\n"));
    1388           else
    1389             DBF (DB_IMPLICIT, _("No implicit rule found for `%s'.\n"));
    1390           file->tried_implicit = 1;
    1391         }
     1427        {
     1428          if (try_implicit_rule (file, depth))
     1429            DBF (DB_IMPLICIT, _("Found an implicit rule for '%s'.\n"));
     1430          else
     1431            DBF (DB_IMPLICIT, _("No implicit rule found for '%s'.\n"));
     1432          file->tried_implicit = 1;
     1433        }
    13921434      if (file->cmds == 0 && !file->is_target
    1393           && default_file != 0 && default_file->cmds != 0)
    1394         {
    1395           DBF (DB_IMPLICIT, _("Using default commands for `%s'.\n"));
    1396           file->cmds = default_file->cmds;
    1397         }
     1435          && default_file != 0 && default_file->cmds != 0)
     1436        {
     1437          DBF (DB_IMPLICIT, _("Using default commands for '%s'.\n"));
     1438          file->cmds = default_file->cmds;
     1439        }
    13981440
    13991441      check_renamed (file);
     
    14031445        /* If the intermediate file actually exists and is newer, then we
    14041446           should remake from it.  */
    1405         *must_make_ptr = 1;
     1447        *must_make_ptr = 1;
    14061448      else
    1407         {
     1449        {
    14081450          /* Otherwise, update all non-intermediate files we depend on, if
    14091451             necessary, and see whether any of them is more recent than the
    14101452             file on whose behalf we are checking.  */
    1411           struct dep *ld;
     1453          struct dep *ld;
    14121454          int deps_running = 0;
    14131455
     
    14161458             prerequisite and so wasn't rebuilt then, but should be now.  */
    14171459          if (file->command_state != cs_running)
    1418             set_command_state (file, cs_not_started);
    1419 
    1420           ld = 0;
    1421           d = file->deps;
    1422           while (d != 0)
    1423             {
     1460            {
     1461              /* If the target was waiting for a dependency it has to be
     1462                 reconsidered, as that dependency might have finished.  */
     1463              if (file->command_state == cs_deps_running)
     1464                file->considered = 0;
     1465
     1466              set_command_state (file, cs_not_started);
     1467            }
     1468
     1469          ld = 0;
     1470          d = file->deps;
     1471          while (d != 0)
     1472            {
     1473              enum update_status new;
    14241474              int maybe_make;
    14251475
    1426               if (is_updating (d->file))
    1427                 {
    1428                   error (NILF, _("Circular %s <- %s dependency dropped."),
    1429                         file->name, d->file->name);
    1430                   if (ld == 0)
    1431                     {
    1432                       file->deps = d->next;
     1476              if (is_updating (d->file))
     1477                {
     1478                  OSS (error, NILF, _("Circular %s <- %s dependency dropped."),
     1479                      file->name, d->file->name);
     1480                  if (ld == 0)
     1481                    {
     1482                      file->deps = d->next;
    14331483                      free_dep (d);
    1434                       d = file->deps;
    1435                     }
    1436                   else
    1437                     {
    1438                       ld->next = d->next;
     1484                      d = file->deps;
     1485                    }
     1486                  else
     1487                    {
     1488                      ld->next = d->next;
    14391489                      free_dep (d);
    1440                       d = ld->next;
    1441                     }
    1442                   continue;
    1443                 }
    1444 
    1445               d->file->parent = file;
     1490                      d = ld->next;
     1491                    }
     1492                  continue;
     1493                }
     1494
     1495              d->file->parent = file;
    14461496              maybe_make = *must_make_ptr;
    1447               dep_status |= check_dep (d->file, depth, this_mtime,
    1448                                        &maybe_make);
     1497              new = check_dep (d->file, depth, this_mtime, &maybe_make);
     1498              if (new > dep_status)
     1499                dep_status = new;
     1500
    14491501              if (! d->ignore_mtime)
    14501502                *must_make_ptr = maybe_make;
    1451               check_renamed (d->file);
    1452               if (dep_status != 0 && !keep_going_flag)
    1453                 break;
    1454 
    1455               if (d->file->command_state == cs_running
    1456                   || d->file->command_state == cs_deps_running)
    1457                 deps_running = 1;
    1458 
    1459               ld = d;
    1460               d = d->next;
    1461             }
     1503              check_renamed (d->file);
     1504              if (dep_status && !keep_going_flag)
     1505                break;
     1506
     1507              if (d->file->command_state == cs_running
     1508                  || d->file->command_state == cs_deps_running)
     1509                deps_running = 1;
     1510
     1511              ld = d;
     1512              d = d->next;
     1513            }
    14621514
    14631515          if (deps_running)
     
    14661518               commands are finished.  */
    14671519            set_command_state (file, cs_deps_running);
    1468         }
     1520        }
    14691521    }
    14701522
     
    14761528
    14771529
    1478 /* Touch FILE.  Return zero if successful, one if not.  */
    1479 
    1480 #define TOUCH_ERROR(call) return (perror_with_name (call, file->name), 1)
    1481 
    1482 static int
     1530/* Touch FILE.  Return us_success if successful, us_failed if not.  */
     1531
     1532#define TOUCH_ERROR(call) do{ perror_with_name ((call), file->name);    \
     1533                              return us_failed; }while(0)
     1534
     1535static enum update_status
    14831536touch_file (struct file *file)
    14841537{
    14851538  if (!silent_flag)
    1486     message (0, "touch %s", file->name);
    1487 
    1488 #ifndef NO_ARCHIVES
     1539    OS (message, 0, "touch %s", file->name);
     1540
     1541  /* Print-only (-n) takes precedence over touch (-t).  */
     1542  if (just_print_flag)
     1543    return us_success;
     1544
     1545#ifndef NO_ARCHIVES
    14891546  if (ar_name (file->name))
    1490     return ar_touch (file->name);
     1547    return ar_touch (file->name) ? us_failed : us_success;
    14911548  else
    14921549#endif
    14931550    {
    1494       int fd = open (file->name, O_RDWR | O_CREAT, 0666);
    1495 
     1551      int fd;
     1552
     1553      EINTRLOOP (fd, open (file->name, O_RDWR | O_CREAT, 0666));
    14961554      if (fd < 0)
    1497         TOUCH_ERROR ("touch: open: ");
     1555        TOUCH_ERROR ("touch: open: ");
    14981556      else
    1499         {
    1500           struct stat statbuf;
    1501           char buf = 'x';
     1557        {
     1558          struct stat statbuf;
     1559          char buf = 'x';
    15021560          int e;
    15031561
    15041562          EINTRLOOP (e, fstat (fd, &statbuf));
    1505           if (e < 0)
    1506             TOUCH_ERROR ("touch: fstat: ");
    1507           /* Rewrite character 0 same as it already is.  */
    1508           if (read (fd, &buf, 1) < 0)
    1509             TOUCH_ERROR ("touch: read: ");
    1510           if (lseek (fd, 0L, 0) < 0L)
    1511             TOUCH_ERROR ("touch: lseek: ");
    1512           if (write (fd, &buf, 1) < 0)
    1513             TOUCH_ERROR ("touch: write: ");
    1514           /* If file length was 0, we just
    1515              changed it, so change it back.  */
    1516           if (statbuf.st_size == 0)
    1517             {
    1518               (void) close (fd);
    1519               fd = open (file->name, O_RDWR | O_TRUNC, 0666);
    1520               if (fd < 0)
    1521                 TOUCH_ERROR ("touch: open: ");
    1522             }
    1523           (void) close (fd);
    1524         }
    1525     }
    1526 
    1527   return 0;
     1563          if (e < 0)
     1564            TOUCH_ERROR ("touch: fstat: ");
     1565          /* Rewrite character 0 same as it already is.  */
     1566          EINTRLOOP (e, read (fd, &buf, 1));
     1567          if (e < 0)
     1568            TOUCH_ERROR ("touch: read: ");
     1569          {
     1570            off_t o;
     1571            EINTRLOOP (o, lseek (fd, 0L, 0));
     1572            if (o < 0L)
     1573              TOUCH_ERROR ("touch: lseek: ");
     1574          }
     1575          EINTRLOOP (e, write (fd, &buf, 1));
     1576          if (e < 0)
     1577            TOUCH_ERROR ("touch: write: ");
     1578
     1579          /* If file length was 0, we just changed it, so change it back.  */
     1580          if (statbuf.st_size == 0)
     1581            {
     1582              (void) close (fd);
     1583              EINTRLOOP (fd, open (file->name, O_RDWR | O_TRUNC, 0666));
     1584              if (fd < 0)
     1585                TOUCH_ERROR ("touch: open: ");
     1586            }
     1587          (void) close (fd);
     1588        }
     1589    }
     1590
     1591  return us_success;
    15281592}
    15291593
     
    15431607    {
    15441608      if (file->phony)
    1545         /* Phony target.  Pretend it succeeded.  */
    1546         file->update_status = 0;
     1609        /* Phony target.  Pretend it succeeded.  */
     1610        file->update_status = us_success;
    15471611      else if (file->is_target)
    1548         /* This is a nonexistent target file we cannot make.
    1549            Pretend it was successfully remade.  */
    1550         file->update_status = 0;
     1612        /* This is a nonexistent target file we cannot make.
     1613           Pretend it was successfully remade.  */
     1614        file->update_status = us_success;
    15511615      else
    15521616        {
     
    15541618          if (!rebuilding_makefiles || !file->dontcare)
    15551619            complain (file);
    1556           file->update_status = 2;
     1620          file->update_status = us_failed;
    15571621        }
    15581622    }
     
    15631627      /* The normal case: start some commands.  */
    15641628      if (!touch_flag || file->cmds->any_recurse)
    1565         {
    1566           execute_file_commands (file);
    1567           return;
    1568         }
     1629        {
     1630          execute_file_commands (file);
     1631          return;
     1632        }
    15691633
    15701634      /* This tells notice_finished_file it is ok to touch the file.  */
    1571       file->update_status = 0;
     1635      file->update_status = us_success;
    15721636    }
    15731637
     
    15771641
    15781642
    1579 /* Return the mtime of a file, given a `struct file'.
     1643/* Return the mtime of a file, given a 'struct file'.
    15801644   Caches the time in the struct file to avoid excess stat calls.
    15811645
     
    15891653{
    15901654  FILE_TIMESTAMP mtime;
     1655  int propagate_timestamp;
    15911656
    15921657  /* File's mtime is not known; must get it from the system.  */
    15931658
    1594 #ifndef NO_ARCHIVES
     1659#ifndef NO_ARCHIVES
    15951660  if (ar_name (file->name))
    15961661    {
     
    16051670
    16061671      /* Find the modification time of the archive itself.
    1607         Also allow for its name to be changed via VPATH search.  */
     1672        Also allow for its name to be changed via VPATH search.  */
    16081673      arfile = lookup_file (arname);
    16091674      if (arfile == 0)
     
    16121677      check_renamed (arfile);
    16131678      if (search && strcmp (arfile->hname, arname))
    1614         {
    1615           /* The archive's name has changed.
    1616              Change the archive-member reference accordingly.  */
     1679        {
     1680          /* The archive's name has changed.
     1681             Change the archive-member reference accordingly.  */
    16171682
    16181683          char *name;
    1619           unsigned int arlen, memlen;
    1620 
    1621           arlen = strlen (arfile->hname);
    1622           memlen = strlen (memname);
    1623 
    1624           name = xmalloc (arlen + 1 + memlen + 2);
    1625           memcpy (name, arfile->hname, arlen);
    1626           name[arlen] = '(';
    1627           memcpy (name + arlen + 1, memname, memlen);
    1628           name[arlen + 1 + memlen] = ')';
    1629           name[arlen + 1 + memlen + 1] = '\0';
     1684          unsigned int arlen, memlen;
     1685
     1686          arlen = strlen (arfile->hname);
     1687          memlen = strlen (memname);
     1688
     1689          name = alloca (arlen + 1 + memlen + 2);
     1690          memcpy (name, arfile->hname, arlen);
     1691          name[arlen] = '(';
     1692          memcpy (name + arlen + 1, memname, memlen);
     1693          name[arlen + 1 + memlen] = ')';
     1694          name[arlen + 1 + memlen + 1] = '\0';
    16301695
    16311696          /* If the archive was found with GPATH, make the change permanent;
    16321697             otherwise defer it until later.  */
    16331698          if (arfile->name == arfile->hname)
    1634             rename_file (file, name);
     1699            rename_file (file, strcache_add (name));
    16351700          else
    1636             rehash_file (file, name);
     1701            rehash_file (file, strcache_add (name));
    16371702          check_renamed (file);
    1638         }
     1703        }
    16391704
    16401705      free (arname);
     
    16431708
    16441709      if (mtime == NONEXISTENT_MTIME)
    1645         /* The archive doesn't exist, so its members don't exist either.  */
    1646         return NONEXISTENT_MTIME;
     1710        /* The archive doesn't exist, so its members don't exist either.  */
     1711        return NONEXISTENT_MTIME;
    16471712
    16481713      member_date = ar_member_date (file->hname);
     
    16571722
    16581723      if (mtime == NONEXISTENT_MTIME && search && !file->ignore_vpath)
    1659         {
    1660           /* If name_mtime failed, search VPATH.  */
    1661           const char *name = vpath_search (file->name, &mtime, NULL, NULL);
    1662           if (name
    1663               /* Last resort, is it a library (-lxxx)?  */
    1664               || (file->name[0] == '-' && file->name[1] == 'l'
    1665                   && (name = library_search (file->name, &mtime)) != 0))
    1666             {
    1667               if (mtime != UNKNOWN_MTIME)
    1668                 /* vpath_search and library_search store UNKNOWN_MTIME
    1669                    if they didn't need to do a stat call for their work.  */
    1670                 file->last_mtime = mtime;
     1724        {
     1725          /* If name_mtime failed, search VPATH.  */
     1726          const char *name = vpath_search (file->name, &mtime, NULL, NULL);
     1727          if (name
     1728              /* Last resort, is it a library (-lxxx)?  */
     1729              || (file->name[0] == '-' && file->name[1] == 'l'
     1730                  && (name = library_search (file->name, &mtime)) != 0))
     1731            {
     1732              int name_len;
     1733
     1734              if (mtime != UNKNOWN_MTIME)
     1735                /* vpath_search and library_search store UNKNOWN_MTIME
     1736                   if they didn't need to do a stat call for their work.  */
     1737                file->last_mtime = mtime;
    16711738
    16721739              /* If we found it in VPATH, see if it's in GPATH too; if so,
    16731740                 change the name right now; if not, defer until after the
    16741741                 dependencies are updated. */
    1675               if (gpath_search (name, strlen(name) - strlen(file->name) - 1))
     1742#ifndef VMS
     1743              name_len = strlen (name) - strlen (file->name) - 1;
     1744#else
     1745              name_len = strlen (name) - strlen (file->name);
     1746              if (name[name_len - 1] == '/')
     1747                  name_len--;
     1748#endif
     1749              if (gpath_search (name, name_len))
    16761750                {
    16771751                  rename_file (file, name);
     
    16801754                }
    16811755
    1682               rehash_file (file, name);
    1683               check_renamed (file);
     1756              rehash_file (file, name);
     1757              check_renamed (file);
    16841758              /* If the result of a vpath search is -o or -W, preserve it.
    16851759                 Otherwise, find the mtime of the resulting file.  */
    16861760              if (mtime != OLD_MTIME && mtime != NEW_MTIME)
    16871761                mtime = name_mtime (name);
    1688             }
    1689         }
     1762            }
     1763        }
    16901764    }
    16911765
     
    17331807            {
    17341808#ifdef NO_FLOAT
    1735               error (NILF, _("Warning: File `%s' has modification time in the future"),
    1736                      file->name);
     1809              OS (error, NILF,
     1810                  _("Warning: File '%s' has modification time in the future"),
     1811                  file->name);
    17371812#else
    17381813              double from_now =
     
    17461821              else
    17471822                sprintf (from_now_string, "%.2g", from_now);
    1748               error (NILF, _("Warning: File `%s' has modification time %s s in the future"),
    1749                      file->name, from_now_string);
     1823              OSS (error, NILF,
     1824                   _("Warning: File '%s' has modification time %s s in the future"),
     1825                   file->name, from_now_string);
    17501826#endif
    17511827              clock_skew_detected = 1;
     
    17541830    }
    17551831
    1756   /* Store the mtime into all the entries for this file.  */
     1832  /* Store the mtime into all the entries for this file for which it is safe
     1833     to do so: avoid propagating timestamps to double-colon rules that haven't
     1834     been examined so they're run or not based on the pre-update timestamp.  */
    17571835  if (file->double_colon)
    17581836    file = file->double_colon;
    17591837
     1838  propagate_timestamp = file->updated;
    17601839  do
    17611840    {
    17621841      /* If this file is not implicit but it is intermediate then it was
    1763         made so by the .INTERMEDIATE target.  If this file has never
    1764         been built by us but was found now, it existed before make
    1765         started.  So, turn off the intermediate bit so make doesn't
    1766         delete it, since it didn't create it.  */
     1842        made so by the .INTERMEDIATE target.  If this file has never
     1843        been built by us but was found now, it existed before make
     1844        started.  So, turn off the intermediate bit so make doesn't
     1845        delete it, since it didn't create it.  */
    17671846      if (mtime != NONEXISTENT_MTIME && file->command_state == cs_not_started
    1768           && file->command_state == cs_not_started
    1769           && !file->tried_implicit && file->intermediate)
    1770         file->intermediate = 0;
    1771 
    1772       file->last_mtime = mtime;
     1847          && !file->tried_implicit && file->intermediate)
     1848        file->intermediate = 0;
     1849
     1850      if (file->updated == propagate_timestamp)
     1851        file->last_mtime = mtime;
    17731852      file = file->prev;
    17741853    }
     
    18901969library_search (const char *lib, FILE_TIMESTAMP *mtime_ptr)
    18911970{
    1892   static char *dirs[] =
     1971  static const char *dirs[] =
    18931972    {
    18941973#ifdef KMK
     
    19071986#endif
    19081987# ifdef LIBDIR      /* bird */
    1909       LIBDIR,                   /* Defined by configuration.  */
     1988      LIBDIR,                   /* Defined by configuration.  */
    19101989# else              /* bird */
    19111990      ".",          /* bird */
     
    19262005
    19272006  /* Information about the earliest (in the vpath sequence) match.  */
    1928   unsigned int best_vpath = 0, best_path = 0; /* bird: gcc maybe used uninitialized (both) */
    1929   unsigned int std_dirs = 0;
    1930 
    1931   char **dp;
     2007  unsigned int best_vpath = 0, best_path = 0;
     2008
     2009  const char **dp;
    19322010
    19332011  libpatterns = xstrdup (variable_expand ("$(.LIBPATTERNS)"));
     
    19462024      static unsigned int buflen = 0;
    19472025      static int libdir_maxlen = -1;
     2026      static unsigned int std_dirs = 0;
    19482027      char *libbuf = variable_expand ("");
    19492028      const size_t libbuf_offset = libbuf - variable_buffer; /* bird */
     
    19512030      /* Expand the pattern using LIB as a replacement.  */
    19522031      {
    1953         char c = p[len];
    1954         char *p3, *p4;
    1955 
    1956         p[len] = '\0';
    1957         p3 = find_percent (p);
    1958         if (!p3)
    1959           {
    1960             /* Give a warning if there is no pattern.  */
    1961             error (NILF, _(".LIBPATTERNS element `%s' is not a pattern"), p);
     2032        char c = p[len];
     2033        char *p3, *p4;
     2034
     2035        p[len] = '\0';
     2036        p3 = find_percent (p);
     2037        if (!p3)
     2038          {
     2039            /* Give a warning if there is no pattern.  */
     2040            OS (error, NILF,
     2041                _(".LIBPATTERNS element '%s' is not a pattern"), p);
    19622042            p[len] = c;
    1963             continue;
    1964           }
    1965         p4 = variable_buffer_output (libbuf, p, p3-p);
    1966         p4 = variable_buffer_output (p4, lib, liblen);
    1967         p4 = variable_buffer_output (p4, p3+1, len - (p3-p));
    1968         p[len] = c;
    1969         libbuf = variable_buffer + libbuf_offset; /* bird - variable_buffer may have been reallocated. */
     2043            continue;
     2044          }
     2045        p4 = variable_buffer_output (libbuf, p, p3-p);
     2046        p4 = variable_buffer_output (p4, lib, liblen);
     2047        p4 = variable_buffer_output (p4, p3+1, len - (p3-p));
     2048        p[len] = c;
     2049        libbuf = variable_buffer + libbuf_offset; /* bird - variable_buffer may have been reallocated. UPSTREAM */
    19702050      }
    19712051
    1972       /* Look first for `libNAME.a' in the current directory.  */
     2052      /* Look first for 'libNAME.a' in the current directory.  */
    19732053      mtime = name_mtime (libbuf);
    19742054      if (mtime != NONEXISTENT_MTIME)
    1975         {
    1976           if (mtime_ptr != 0)
    1977             *mtime_ptr = mtime;
    1978           file = strcache_add (libbuf);
     2055        {
     2056          if (mtime_ptr != 0)
     2057            *mtime_ptr = mtime;
     2058          file = strcache_add (libbuf);
    19792059          /* This by definition will have the best index, so stop now.  */
    19802060          break;
    1981         }
     2061        }
    19822062
    19832063      /* Now try VPATH search on that.  */
     
    20162096            }
    20172097          buflen = strlen (libbuf);
    2018           buf = xmalloc(libdir_maxlen + buflen + 2);
     2098          buf = xmalloc (libdir_maxlen + buflen + 2);
    20192099        }
    20202100      else if (buflen < strlen (libbuf))
     
    20302110
    20312111        for (dp = dirs; *dp != 0; ++dp)
    2032           {
     2112          {
    20332113            sprintf (buf, "%s/%s", *dp, libbuf);
    20342114            mtime = name_mtime (buf);
    20352115            if (mtime != NONEXISTENT_MTIME)
    2036               {
     2116              {
    20372117                if (file == 0 || vpath_index < best_vpath)
    20382118                  {
  • trunk/src/kmk/remote-cstms.c

    r2591 r3140  
    44   the Make maintainers.
    55
    6 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    7 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    8 2010 Free Software Foundation, Inc.
     6Copyright (C) 1988-2016 Free Software Foundation, Inc.
    97This file is part of GNU Make.
    108
     
    2119this program.  If not, see <http://www.gnu.org/licenses/>.  */
    2220
    23 #include "make.h"
    24 #include "job.h"
     21#include "makeint.h"
    2522#include "filedef.h"
    2623#include "commands.h"
     
    3532char *remote_description = "Customs";
    3633
    37 /* File name of the Customs `export' client command.
     34/* File name of the Customs 'export' client command.
    3835   A full path name can be used to avoid some path-searching overhead.  */
    39 #define EXPORT_COMMAND  "/usr/local/bin/export"
     36#define EXPORT_COMMAND  "/usr/local/bin/export"
    4037
    4138/* ExportPermit gotten by start_remote_job_p, and used by start_remote_job.  */
     
    8077
    8178      /* For secure Customs, make is installed setuid root and
    82         Customs requires a privileged source port be used.  */
     79        Customs requires a privileged source port be used.  */
    8380      make_access ();
    8481
    8582      if (ISDB (DB_JOBS))
    86         Rpc_Debug(1);
     83        Rpc_Debug (1);
    8784
    8885      /* Ping the daemon once to see if it is there.  */
     
    9390
    9491      if (starting_directory == 0)
    95         /* main couldn't figure it out.  */
    96         inited = -1;
     92        /* main couldn't figure it out.  */
     93        inited = -1;
    9794      else
    98         {
    99           /* Normalize the current directory path name to something
    100              that should work on all machines exported to.  */
    101 
    102           normalized_cwd = xmalloc (GET_PATH_MAX);
    103           strcpy (normalized_cwd, starting_directory);
    104           if (Customs_NormPath (normalized_cwd, GET_PATH_MAX) < 0)
    105             /* Path normalization failure means using Customs
    106                won't work, but it's not really an error.  */
    107             inited = -1;
    108         }
     95        {
     96          /* Normalize the current directory path name to something
     97             that should work on all machines exported to.  */
     98
     99          normalized_cwd = xmalloc (GET_PATH_MAX);
     100          strcpy (normalized_cwd, starting_directory);
     101          if (Customs_NormPath (normalized_cwd, GET_PATH_MAX) < 0)
     102            /* Path normalization failure means using Customs
     103               won't work, but it's not really an error.  */
     104            inited = -1;
     105        }
    109106    }
    110107
     
    114111  njobs = job_slots_used;
    115112  if (!first_p)
    116     njobs -= 1;         /* correction for being called from reap_children() */
     113    njobs -= 1;         /* correction for being called from reap_children() */
    117114
    118115  /* the first job should run locally, or, if the -l flag is given, we use
     
    157154  if (retsock < 0)
    158155    {
    159       error (NILF, "exporting: Couldn't create return socket.");
     156      O (error, NILF, "exporting: Couldn't create return socket.");
    160157      return 1;
    161158    }
     
    176173  /* Create a WayBill to give to the server.  */
    177174  len = Customs_MakeWayBill (&permit, normalized_cwd, argv[0], argv,
    178                              envp, retport, waybill);
    179 
    180   /* Modify the waybill as if the remote child had done `child_access ()'.  */
     175                             envp, retport, waybill);
     176
     177  /* Modify the waybill as if the remote child had done 'child_access ()'.  */
    181178  {
    182179    WayBill *wb = (WayBill *) waybill;
     
    192189  sin.sin_addr = permit.addr;
    193190  status = Rpc_Call (sock, &sin, (Rpc_Proc) CUSTOMS_IMPORT,
    194                      len, (Rpc_Opaque) waybill,
    195                      sizeof(msg), (Rpc_Opaque) msg,
    196                      1, &timeout);
    197 
    198   host = gethostbyaddr((char *)&permit.addr, sizeof(permit.addr), AF_INET);
    199 
    200   if (status != RPC_SUCCESS)
    201     {
    202       (void) close (retsock);
    203       (void) close (sock);
    204       error (NILF, "exporting to %s: %s",
    205              host ? host->h_name : inet_ntoa (permit.addr),
    206              Rpc_ErrorMessage (status));
    207       return 1;
    208     }
    209   else if (msg[0] != 'O' || msg[1] != 'k' || msg[2] != '\0')
    210     {
    211       (void) close (retsock);
    212       (void) close (sock);
    213       error (NILF, "exporting to %s: %s",
    214              host ? host->h_name : inet_ntoa (permit.addr),
    215              msg);
    216       return 1;
    217     }
    218   else
    219     {
    220       error (NILF, "*** exported to %s (id %u)",
    221               host ? host->h_name : inet_ntoa (permit.addr),
    222               permit.id);
    223     }
    224 
    225   fflush (stdout);
    226   fflush (stderr);
     191                     len, (Rpc_Opaque) waybill,
     192                     sizeof (msg), (Rpc_Opaque) msg,
     193                     1, &timeout);
     194
     195  host = gethostbyaddr ((char *)&permit.addr, sizeof(permit.addr), AF_INET);
     196
     197  {
     198    const char *hnm = host ? host->h_name : inet_ntoa (permit.addr);
     199    size_t hlen = strlen (hnm);
     200
     201    if (status != RPC_SUCCESS)
     202      {
     203        const char *err = Rpc_ErrorMessage (status);
     204        (void) close (retsock);
     205        (void) close (sock);
     206        error (NILF, hlen + strlen (err),
     207               "exporting to %s: %s", hnm, err);
     208        return 1;
     209      }
     210    else if (msg[0] != 'O' || msg[1] != 'k' || msg[2] != '\0')
     211      {
     212        (void) close (retsock);
     213        (void) close (sock);
     214        error (NILF, hlen + strlen (msg), "exporting to %s: %s", hnm, msg);
     215        return 1;
     216      }
     217    else
     218      {
     219        error (NILF, hlen + INTSTR_LENGTH,
     220               "*** exported to %s (id %u)", hnm, permit.id);
     221      }
     222
     223    fflush (stdout);
     224    fflush (stderr);
     225  }
    227226
    228227  pid = vfork ();
     
    230229    {
    231230      /* The fork failed!  */
    232       perror_with_name ("vfork", "");
     231      perror_with_name ("fork", "");
    233232      return 1;
    234233    }
    235234  else if (pid == 0)
    236235    {
    237       /* Child side.  Run `export' to handle the connection.  */
     236      /* Child side.  Run 'export' to handle the connection.  */
    238237      static char sock_buf[20], retsock_buf[20], id_buf[20];
    239238      static char *new_argv[6] =
    240         { EXPORT_COMMAND, "-id", sock_buf, retsock_buf, id_buf, 0 };
     239        { EXPORT_COMMAND, "-id", sock_buf, retsock_buf, id_buf, 0 };
    241240
    242241      /* Set up the arguments.  */
     
    247246      /* Get the right stdin.  */
    248247      if (stdin_fd != 0)
    249         (void) dup2 (stdin_fd, 0);
     248        (void) dup2 (stdin_fd, 0);
    250249
    251250      /* Unblock signals in the child.  */
     
    256255    }
    257256
    258   /* Parent side.  Return the `export' process's ID.  */
     257  /* Parent side.  Return the 'export' process's ID.  */
    259258  (void) close (retsock);
    260259  (void) close (sock);
  • trunk/src/kmk/remote-stub.c

    r2591 r3140  
    11/* Template for the remote job exportation interface to GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018#include "filedef.h"
    2119#include "job.h"
  • trunk/src/kmk/rule.c

    r2591 r3140  
    11/* Pattern and suffix rule internals for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018
    2119#include <assert.h>
    2220
     21#include "filedef.h"
    2322#include "dep.h"
    24 #include "filedef.h"
    2523#include "job.h"
    2624#include "commands.h"
     
    7573  char *name;
    7674  int namelen;
    77   struct rule *rule, *lastrule;
     75  struct rule *rule;
    7876
    7977  num_pattern_rules = max_pattern_targets = max_pattern_deps = 0;
     
    8381  namelen = 0;
    8482  rule = pattern_rules;
    85   lastrule = 0;
    8683  while (rule != 0)
    8784    {
     
    9390
    9491      if (rule->num > max_pattern_targets)
    95         max_pattern_targets = rule->num;
     92        max_pattern_targets = rule->num;
    9693
    9794      for (dep = rule->deps; dep != 0; dep = dep->next)
    98         {
     95        {
    9996          const char *dname = dep_name (dep);
    10097          unsigned int len = strlen (dname);
     
    112109          ndeps++;
    113110
    114           if (len > max_pattern_dep_length)
    115             max_pattern_dep_length = len;
    116 
    117           if (p != 0 && p2 > p)
    118             {
    119               /* There is a slash before the % in the dep name.
    120                 Extract the directory name.  */
    121               if (p == dname)
    122                 ++p;
    123               if (p - dname > namelen)
    124                 {
    125                   namelen = p - dname;
    126                   name = xrealloc (name, namelen + 1);
    127                 }
    128               memcpy (name, dname, p - dname);
    129               name[p - dname] = '\0';
    130 
    131               /* In the deps of an implicit rule the `changed' flag
    132                 actually indicates that the dependency is in a
    133                 nonexistent subdirectory.  */
    134 
    135               dep->changed = !dir_file_exists_p (name, "");
    136             }
    137           else
    138             /* This dependency does not reside in a subdirectory.  */
    139             dep->changed = 0;
    140         }
     111          if (len > max_pattern_dep_length)
     112            max_pattern_dep_length = len;
     113
     114          if (p != 0 && p2 > p)
     115            {
     116              /* There is a slash before the % in the dep name.
     117                Extract the directory name.  */
     118              if (p == dname)
     119                ++p;
     120              if (p - dname > namelen)
     121                {
     122                  namelen = p - dname;
     123                  name = xrealloc (name, namelen + 1);
     124                }
     125              memcpy (name, dname, p - dname);
     126              name[p - dname] = '\0';
     127
     128              /* In the deps of an implicit rule the 'changed' flag
     129                actually indicates that the dependency is in a
     130                nonexistent subdirectory.  */
     131
     132              dep->changed = !dir_file_exists_p (name, "");
     133            }
     134          else
     135            /* This dependency does not reside in a subdirectory.  */
     136            dep->changed = 0;
     137        }
    141138
    142139      if (ndeps > max_pattern_deps)
    143         max_pattern_deps = ndeps;
    144 
    145       lastrule = rule;
     140        max_pattern_deps = ndeps;
     141
    146142      rule = next;
    147143    }
    148144
    149   if (name != 0)
    150     free (name);
     145  free (name);
    151146}
    152147
     
    155150   TARGET is the target suffix; SOURCE is the source suffix.
    156151   CMDS are the commands.
    157    If TARGET is nil, it means the target pattern should be `(%.o)'.
     152   If TARGET is nil, it means the target pattern should be '(%.o)'.
    158153   If SOURCE is nil, it means there should be no deps.  */
    159154
     
    170165  if (target == 0)
    171166    {
    172       /* Special case: TARGET being nil means we are defining a `.X.a' suffix
    173          rule; the target pattern is always `(%.o)'.  */
     167      /* Special case: TARGET being nil means we are defining a '.X.a' suffix
     168         rule; the target pattern is always '(%.o)'.  */
    174169#ifdef VMS
    175170      *names = strcache_add_len ("(%.obj)", 7);
     
    225220      unsigned int l = strlen (dep_name (d));
    226221      if (l > maxsuffix)
    227         maxsuffix = l;
     222        maxsuffix = l;
    228223    }
    229224
     
    236231
    237232      /* Make a rule that is just the suffix, with no deps or commands.
    238         This rule exists solely to disqualify match-anything rules.  */
     233        This rule exists solely to disqualify match-anything rules.  */
    239234      convert_suffix_rule (dep_name (d), 0, 0);
    240235
    241236      if (d->file->cmds != 0)
    242         /* Record a pattern for this suffix's null-suffix rule.  */
    243         convert_suffix_rule ("", dep_name (d), d->file->cmds);
     237        /* Record a pattern for this suffix's null-suffix rule.  */
     238        convert_suffix_rule ("", dep_name (d), d->file->cmds);
    244239
    245240      /* Add every other suffix to this one and see if it exists as a
     
    249244
    250245      for (d2 = suffix_file->deps; d2 != 0; d2 = d2->next)
    251         {
     246        {
    252247          struct file *f;
    253248          unsigned int s2len;
    254249
    255           s2len = strlen (dep_name (d2));
     250          s2len = strlen (dep_name (d2));
    256251
    257252          /* Can't build something from itself.  */
    258           if (slen == s2len && streq (dep_name (d), dep_name (d2)))
    259             continue;
    260 
    261           memcpy (rulename + slen, dep_name (d2), s2len + 1);
    262           f = lookup_file (rulename);
    263           if (f == 0 || f->cmds == 0)
    264             continue;
    265 
    266           if (s2len == 2 && rulename[slen] == '.' && rulename[slen + 1] == 'a')
    267             /* A suffix rule `.X.a:' generates the pattern rule `(%.o): %.X'.
    268                It also generates a normal `%.a: %.X' rule below.  */
    269             convert_suffix_rule (NULL, /* Indicates `(%.o)'.  */
    270                                 dep_name (d),
    271                                 f->cmds);
    272 
    273           /* The suffix rule `.X.Y:' is converted
    274              to the pattern rule `%.Y: %.X'.  */
    275           convert_suffix_rule (dep_name (d2), dep_name (d), f->cmds);
    276         }
     253          if (slen == s2len && streq (dep_name (d), dep_name (d2)))
     254            continue;
     255
     256          memcpy (rulename + slen, dep_name (d2), s2len + 1);
     257          f = lookup_file (rulename);
     258          if (f == 0 || f->cmds == 0)
     259            continue;
     260
     261          if (s2len == 2 && rulename[slen] == '.' && rulename[slen + 1] == 'a')
     262            /* A suffix rule '.X.a:' generates the pattern rule '(%.o): %.X'.
     263               It also generates a normal '%.a: %.X' rule below.  */
     264            convert_suffix_rule (NULL, /* Indicates '(%.o)'.  */
     265                                dep_name (d),
     266                                f->cmds);
     267
     268          /* The suffix rule '.X.Y:' is converted
     269             to the pattern rule '%.Y: %.X'.  */
     270          convert_suffix_rule (dep_name (d2), dep_name (d), f->cmds);
     271        }
    277272    }
    278273}
     
    302297    for (i = 0; i < rule->num; ++i)
    303298      {
    304         for (j = 0; j < r->num; ++j)
    305           if (!streq (rule->targets[i], r->targets[j]))
    306             break;
     299        for (j = 0; j < r->num; ++j)
     300          if (!streq (rule->targets[i], r->targets[j]))
     301            break;
    307302        /* If all the targets matched...  */
    308         if (j == r->num)
    309           {
    310             struct dep *d, *d2;
    311             for (d = rule->deps, d2 = r->deps;
    312                 d != 0 && d2 != 0; d = d->next, d2 = d2->next)
    313               if (!streq (dep_name (d), dep_name (d2)))
    314                 break;
    315             if (d == 0 && d2 == 0)
    316               {
    317                 /* All the dependencies matched.  */
    318                 if (override)
    319                   {
    320                     /* Remove the old rule.  */
    321                     freerule (r, lastrule);
    322                     /* Install the new one.  */
    323                     if (pattern_rules == 0)
    324                       pattern_rules = rule;
    325                     else
    326                       last_pattern_rule->next = rule;
    327                     last_pattern_rule = rule;
    328 
    329                     /* We got one.  Stop looking.  */
    330                     goto matched;
    331                   }
    332                 else
    333                   {
    334                     /* The old rule stays intact.  Destroy the new one.  */
    335                     freerule (rule, (struct rule *) 0);
    336                     return 0;
    337                   }
    338               }
    339           }
     303        if (j == r->num)
     304          {
     305            struct dep *d, *d2;
     306            for (d = rule->deps, d2 = r->deps;
     307                d != 0 && d2 != 0; d = d->next, d2 = d2->next)
     308              if (!streq (dep_name (d), dep_name (d2)))
     309                break;
     310            if (d == 0 && d2 == 0)
     311              {
     312                /* All the dependencies matched.  */
     313                if (override)
     314                  {
     315                    /* Remove the old rule.  */
     316                    freerule (r, lastrule);
     317                    /* Install the new one.  */
     318                    if (pattern_rules == 0)
     319                      pattern_rules = rule;
     320                    else
     321                      last_pattern_rule->next = rule;
     322                    last_pattern_rule = rule;
     323
     324                    /* We got one.  Stop looking.  */
     325                    goto matched;
     326                  }
     327                else
     328                  {
     329                    /* The old rule stays intact.  Destroy the new one.  */
     330                    freerule (rule, (struct rule *) 0);
     331                    return 0;
     332                  }
     333              }
     334          }
    340335      }
    341336
     
    346341      /* There was no rule to replace.  */
    347342      if (pattern_rules == 0)
    348         pattern_rules = rule;
     343        pattern_rules = rule;
    349344      else
    350         last_pattern_rule->next = rule;
     345        last_pattern_rule->next = rule;
    351346      last_pattern_rule = rule;
    352347    }
     
    359354   in the structure P points to.  These strings come from one of
    360355   the arrays of default implicit pattern rules.
    361    TERMINAL specifies what the `terminal' field of the rule should be.  */
     356   TERMINAL specifies what the 'terminal' field of the rule should be.  */
    362357
    363358void
     
    365360{
    366361  struct rule *r;
    367   char *ptr;
     362  const char *ptr;
    368363
    369364  r = xmalloc (sizeof (struct rule));
     
    381376
    382377  ptr = p->dep;
    383   r->deps = PARSE_FILE_SEQ (&ptr, struct dep, '\0', NULL, 0);
     378  r->deps = PARSE_SIMPLE_SEQ ((char **)&ptr, struct dep);
    384379
    385380  if (new_pattern_rule (r, 0))
     
    393388      r->cmds->fileinfo.filenm = 0;
    394389      r->cmds->fileinfo.lineno = 0;
     390      r->cmds->fileinfo.offset = 0;
    395391      /* These will all be string literals, but we malloc space for them
    396         anyway because somebody might want to free them later.  */
     392        anyway because somebody might want to free them later.  */
    397393      r->cmds->commands = xstrdup (p->commands);
    398394      r->cmds->command_lines = 0;
     395      r->cmds->recipe_prefix = RECIPEPREFIX_DEFAULT;
     396
    399397#ifdef CONFIG_WITH_MEMORY_OPTIMIZATIONS
    400398      r->cmds->refs = 1000;
     
    423421     are ways that they could be in more than one place:
    424422       * If the commands came from a suffix rule, they could also be in
    425        the `struct file's for other suffix rules or plain targets given
     423       the 'struct file's for other suffix rules or plain targets given
    426424       on the same makefile line.
    427425       * If two suffixes that together make a two-suffix rule were each
    428426       given twice in the .SUFFIXES list, and in the proper order, two
    429427       identical pattern rules would be created and the second one would
    430        be discarded here, but both would contain the same `struct commands'
    431        pointer from the `struct file' for the suffix rule.  */
     428       be discarded here, but both would contain the same 'struct commands'
     429       pointer from the 'struct file' for the suffix rule.  */
    432430
    433431  free (rule);
     
    488486/* Print the data base of rules.  */
    489487
    490 static void                     /* Useful to call from gdb.  */
     488static void                     /* Useful to call from gdb.  */
    491489print_rule (struct rule *r)
    492490{
     
    524522
    525523      if (r->terminal)
    526         ++terminal;
     524        ++terminal;
    527525    }
    528526
     
    532530    {
    533531      printf (_("\n# %u implicit rules, %u"), rules, terminal);
    534 #ifndef NO_FLOAT
     532#ifndef NO_FLOAT
    535533      printf (" (%.1f%%)", (double) terminal / (double) rules * 100.0);
    536534#else
    537535      {
    538         int f = (terminal * 1000 + 5) / rules;
    539         printf (" (%d.%d%%)", f/10, f%10);
     536        int f = (terminal * 1000 + 5) / rules;
     537        printf (" (%d.%d%%)", f/10, f%10);
    540538      }
    541539#endif
     
    548546         makefiles and thus count_implicit_rule_limits wasn't called yet.  */
    549547      if (num_pattern_rules != 0)
    550         fatal (NILF, _("BUG: num_pattern_rules is wrong!  %u != %u"),
    551                num_pattern_rules, rules);
    552     }
    553 }
     548        ONN (fatal, NILF, _("BUG: num_pattern_rules is wrong!  %u != %u"),
     549             num_pattern_rules, rules);
     550    }
     551}
  • trunk/src/kmk/rule.h

    r2591 r3140  
    11/* Definitions for using pattern rules in GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    2321  {
    2422    struct rule *next;
    25     const char **targets;       /* Targets of the rule.  */
    26     unsigned int *lens;         /* Lengths of each target.  */
    27     const char **suffixes;      /* Suffixes (after `%') of each target.  */
    28     struct dep *deps;           /* Dependencies of the rule.  */
    29     struct commands *cmds;      /* Commands to execute.  */
     23    const char **targets;       /* Targets of the rule.  */
     24    unsigned int *lens;         /* Lengths of each target.  */
     25    const char **suffixes;      /* Suffixes (after '%') of each target.  */
     26    struct dep *deps;           /* Dependencies of the rule.  */
     27    struct commands *cmds;      /* Commands to execute.  */
    3028    unsigned short num;         /* Number of targets.  */
    31     char terminal;              /* If terminal (double-colon).  */
    32     char in_use;                /* If in use by a parent pattern_search.  */
     29    char terminal;              /* If terminal (double-colon).  */
     30    char in_use;                /* If in use by a parent pattern_search.  */
    3331  };
    3432
     
    3634struct pspec
    3735  {
    38     char *target, *dep, *commands;
     36    const char *target, *dep, *commands;
    3937  };
    4038
     
    5856                          unsigned int num, int terminal, struct dep *deps,
    5957                          struct commands *commands, int override);
     58void print_rule_data_base (void);
  • trunk/src/kmk/signame.c

    r2591 r3140  
    11/* Convert between signal names and numbers.
    2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
    3 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
    4 Foundation, Inc.
     2Copyright (C) 1990-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018
    2119/* If the system provides strsignal, we don't need it. */
     
    3028
    3129/* Some systems do not define NSIG in <signal.h>.  */
    32 #ifndef NSIG
    33 #ifdef  _NSIG
    34 #define NSIG    _NSIG
     30#ifndef NSIG
     31#ifdef  _NSIG
     32#define NSIG    _NSIG
    3533#else
    36 #define NSIG    32
     34#define NSIG    32
    3735#endif
    3836#endif
     
    195193#endif
    196194#if defined (SIGIO)
    197   /* "I/O pending" has also been suggested.  A disadvantage is
    198      that signal only happens when the process has
    199      asked for it, not everytime I/O is pending.  Another disadvantage
    200      is the confusion from giving it a different name than under Unix.  */
     195  /* "I/O pending" has also been suggested.  A disadvantage is that signal
     196     only happens when the process has asked for it, not every time I/O is
     197     pending.  Another disadvantage is the confusion from giving it a
     198     different name than under Unix.  */
    201199  init_sig (SIGIO, "IO", _("I/O possible"));
    202200#endif
     
    247245#endif
    248246
    249   if (sig > 0 || sig < NSIG)
     247  if (sig > 0 && sig < NSIG)
    250248    return (char *) sys_siglist[sig];
    251249
  • trunk/src/kmk/strcache.c

    r3090 r3140  
    11/* Constant string caching for GNU Make.
    2 Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 2006-2016 Free Software Foundation, Inc.
    33This file is part of GNU Make.
    44
     
    1515this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1616
    17 #include "make.h"
     17#include "makeint.h"
    1818#ifndef CONFIG_WITH_STRCACHE2
    1919
     20#include <stddef.h>
    2021#include <assert.h>
    2122
    2223#include "hash.h"
    23 
    24 /* The size (in bytes) of each cache buffer.
    25    Try to pick something that will map well into the heap.  */
    26 #define CACHE_BUFFER_SIZE   (8192 - 16)
    27 
    2824
    2925/* A string cached here will never be freed, so we don't need to worry about
     
    3127   hash so it can be looked up again. */
    3228
     29typedef unsigned short int sc_buflen_t;
     30
    3331struct strcache {
    34   struct strcache *next;    /* The next block of strings.  */
    35   char *end;                /* Pointer to the beginning of the free space.  */
    36   int count;                /* # of strings in this buffer (for stats).  */
    37   int bytesfree;            /* The amount of the buffer that is free.  */
     32  struct strcache *next;    /* The next block of strings.  Must be first!  */
     33  sc_buflen_t end;          /* Offset to the beginning of free space.  */
     34  sc_buflen_t bytesfree;    /* Free space left in this buffer.  */
     35  sc_buflen_t count;        /* # of strings in this buffer (for stats).  */
    3836  char buffer[1];           /* The buffer comes after this.  */
    3937};
    4038
    41 static int bufsize = CACHE_BUFFER_SIZE;
     39/* The size (in bytes) of each cache buffer.
     40   Try to pick something that will map well into the heap.
     41   This must be able to be represented by a short int (<=65535).  */
     42#define CACHE_BUFFER_BASE       (8192)
     43#define CACHE_BUFFER_ALLOC(_s)  ((_s) - (2 * sizeof (size_t)))
     44#define CACHE_BUFFER_OFFSET     (offsetof (struct strcache, buffer))
     45#define CACHE_BUFFER_SIZE(_s)   (CACHE_BUFFER_ALLOC(_s) - CACHE_BUFFER_OFFSET)
     46#define BUFSIZE                 CACHE_BUFFER_SIZE (CACHE_BUFFER_BASE)
     47
    4248static struct strcache *strcache = NULL;
     49static struct strcache *fullcache = NULL;
     50
     51static unsigned long total_buffers = 0;
     52static unsigned long total_strings = 0;
     53static unsigned long total_size = 0;
    4354
    4455/* Add a new buffer to the cache.  Add it at the front to reduce search time.
     
    4859 */
    4960static struct strcache *
    50 new_cache()
    51 {
    52   struct strcache *new;
    53   new = xmalloc (sizeof (*new) + bufsize);
    54   new->end = new->buffer;
     61new_cache (struct strcache **head, sc_buflen_t buflen)
     62{
     63  struct strcache *new = xmalloc (buflen + CACHE_BUFFER_OFFSET);
     64  new->end = 0;
    5565  new->count = 0;
    56   new->bytesfree = bufsize;
    57 
    58   new->next = strcache;
    59   strcache = new;
    60 
     66  new->bytesfree = buflen;
     67
     68  new->next = *head;
     69  *head = new;
     70
     71  ++total_buffers;
    6172  return new;
    6273}
    6374
    6475static const char *
    65 add_string(const char *str, int len)
    66 {
    67   struct strcache *best = NULL;
     76copy_string (struct strcache *sp, const char *str, unsigned int len)
     77{
     78  /* Add the string to this cache.  */
     79  char *res = &sp->buffer[sp->end];
     80
     81  memmove (res, str, len);
     82  res[len++] = '\0';
     83  sp->end += len;
     84  sp->bytesfree -= len;
     85  ++sp->count;
     86
     87  return res;
     88}
     89
     90static const char *
     91add_string (const char *str, unsigned int len)
     92{
     93  const char *res;
    6894  struct strcache *sp;
    69   const char *res;
     95  struct strcache **spp = &strcache;
     96  /* We need space for the nul char.  */
     97  unsigned int sz = len + 1;
     98
     99  ++total_strings;
     100  total_size += sz;
    70101
    71102  /* If the string we want is too large to fit into a single buffer, then
    72      we're screwed; nothing will ever fit!  Change the maximum size of the
    73      cache to be big enough.  */
    74   if (len > bufsize)
    75     bufsize = len * 2;
    76 
    77   /* First, find a cache with enough free space.  We always look through all
    78      the blocks and choose the one with the best fit (the one that leaves the
    79      least amount of space free).  */
    80   for (sp = strcache; sp != NULL; sp = sp->next)
    81     if (sp->bytesfree > len && (!best || best->bytesfree > sp->bytesfree))
    82       best = sp;
    83 
    84   /* If nothing is big enough, make a new cache.  */
    85   if (!best)
    86     best = new_cache();
    87 
    88   assert (best->bytesfree > len);
    89 
    90   /* Add the string to the best cache.  */
    91   res = best->end;
    92   memcpy (best->end, str, len);
    93   best->end += len;
    94   *(best->end++) = '\0';
    95   best->bytesfree -= len + 1;
    96   ++best->count;
     103     no existing cache is large enough.  Add it directly to the fullcache.  */
     104  if (sz > BUFSIZE)
     105    {
     106      sp = new_cache (&fullcache, sz);
     107      return copy_string (sp, str, len);
     108    }
     109
     110  /* Find the first cache with enough free space.  */
     111  for (; *spp != NULL; spp = &(*spp)->next)
     112    if ((*spp)->bytesfree > sz)
     113      break;
     114  sp = *spp;
     115
     116  /* If nothing is big enough, make a new cache at the front.  */
     117  if (sp == NULL)
     118    {
     119      sp = new_cache (&strcache, BUFSIZE);
     120      spp = &strcache;
     121    }
     122
     123  /* Add the string to this cache.  */
     124  res = copy_string (sp, str, len);
     125
     126  /* If the amount free in this cache is less than the average string size,
     127     consider it full and move it to the full list.  */
     128  if (total_strings > 20 && sp->bytesfree < (total_size / total_strings) + 1)
     129    {
     130      *spp = sp->next;
     131      sp->next = fullcache;
     132      fullcache = sp;
     133    }
    97134
    98135  return res;
    99136}
    100137
     138/* For strings too large for the strcache, we just save them in a list.  */
     139struct hugestring {
     140  struct hugestring *next;  /* The next string.  */
     141  char buffer[1];           /* The string.  */
     142};
     143
     144static struct hugestring *hugestrings = NULL;
     145
     146static const char *
     147add_hugestring (const char *str, unsigned int len)
     148{
     149  struct hugestring *new = xmalloc (sizeof (struct hugestring) + len);
     150  memcpy (new->buffer, str, len);
     151  new->buffer[len] = '\0';
     152
     153  new->next = hugestrings;
     154  hugestrings = new;
     155
     156  return new->buffer;
     157}
    101158
    102159/* Hash table of strings in the cache.  */
     
    124181
    125182static const char *
    126 add_hash (const char *str, int len)
    127 {
     183add_hash (const char *str, unsigned int len)
     184{
     185  char *const *slot;
     186  const char *key;
     187
     188  /* If it's too large for the string cache, just copy it.
     189     We don't bother trying to match these.  */
     190  if (len > USHRT_MAX - 1)
     191    return add_hugestring (str, len);
     192
    128193  /* Look up the string in the hash.  If it's there, return it.  */
    129   char *const *slot = (char *const *) hash_find_slot (&strings, str);
    130   const char *key = *slot;
    131 
    132   /* Count the total number of adds we performed.  */
     194  slot = (char *const *) hash_find_slot (&strings, str);
     195  key = *slot;
     196
     197  /* Count the total number of add operations we performed.  */
    133198  ++total_adds;
    134199
     
    149214
    150215  for (sp = strcache; sp != 0; sp = sp->next)
    151     if (str >= sp->buffer && str < sp->end)
     216    if (str >= sp->buffer && str < sp->buffer + sp->end)
    152217      return 1;
     218  for (sp = fullcache; sp != 0; sp = sp->next)
     219    if (str >= sp->buffer && str < sp->buffer + sp->end)
     220      return 1;
     221
     222  {
     223    struct hugestring *hp;
     224    for (hp = hugestrings; hp != 0; hp = hp->next)
     225      if (str == hp->buffer)
     226        return 1;
     227  }
    153228
    154229  return 0;
     
    165240
    166241const char *
    167 strcache_add_len (const char *str, int len)
     242strcache_add_len (const char *str, unsigned int len)
    168243{
    169244  /* If we're not given a nul-terminated string we have to create one, because
     
    180255}
    181256
    182 int
    183 strcache_setbufsize(int size)
    184 {
    185   if (size > bufsize)
    186     bufsize = size;
    187   return bufsize;
    188 }
    189 
    190257void
    191258strcache_init (void)
     
    200267strcache_print_stats (const char *prefix)
    201268{
    202   int numbuffs = 0, numstrs = 0;
    203   int totsize = 0, avgsize, maxsize = 0, minsize = bufsize;
    204   int totfree = 0, avgfree, maxfree = 0, minfree = bufsize;
    205   int lastused = 0, lastfree = 0;
    206 
    207   if (strcache)
    208     {
    209       const struct strcache *sp;
    210 
    211       /* Count the first buffer separately since it's not full.  */
    212       lastused = strcache->end - strcache->buffer;
    213       lastfree = strcache->bytesfree;
    214 
    215       for (sp = strcache->next; sp != NULL; sp = sp->next)
    216         {
    217           int bf = sp->bytesfree;
    218           int sz = sp->end - sp->buffer;
    219 
    220           ++numbuffs;
    221           numstrs += sp->count;
    222 
    223           totsize += sz;
    224           maxsize = (sz > maxsize ? sz : maxsize);
    225           minsize = (sz < minsize ? sz : minsize);
    226 
    227           totfree += bf;
    228           maxfree = (bf > maxfree ? bf : maxfree);
    229           minfree = (bf < minfree ? bf : minfree);
    230         }
    231     }
    232 
    233   avgsize = numbuffs ? (int)(totsize / numbuffs) : 0;
    234   avgfree = numbuffs ? (int)(totfree / numbuffs) : 0;
    235 
    236   printf (_("\n%s # of strings in strcache: %d / lookups = %lu / hits = %lu\n"),
    237           prefix, numstrs, total_adds, (total_adds - numstrs));
    238   printf (_("%s # of strcache buffers: %d (* %d B/buffer = %d B)\n"),
    239           prefix, (numbuffs + 1), bufsize, ((numbuffs + 1) * bufsize));
    240   printf (_("%s strcache used: total = %d (%d) / max = %d / min = %d / avg = %d\n"),
    241           prefix, totsize, lastused, maxsize, minsize, avgsize);
    242   printf (_("%s strcache free: total = %d (%d) / max = %d / min = %d / avg = %d\n"),
    243           prefix, totfree, lastfree, maxfree, minfree, avgfree);
    244 
    245   fputs (_("\n# strcache hash-table stats:\n# "), stdout);
     269  const struct strcache *sp;
     270  unsigned long numbuffs = 0, fullbuffs = 0;
     271  unsigned long totfree = 0, maxfree = 0, minfree = BUFSIZE;
     272
     273  if (! strcache)
     274    {
     275      printf (_("\n%s No strcache buffers\n"), prefix);
     276      return;
     277    }
     278
     279  /* Count the first buffer separately since it's not full.  */
     280  for (sp = strcache->next; sp != NULL; sp = sp->next)
     281    {
     282      sc_buflen_t bf = sp->bytesfree;
     283
     284      totfree += bf;
     285      maxfree = (bf > maxfree ? bf : maxfree);
     286      minfree = (bf < minfree ? bf : minfree);
     287
     288      ++numbuffs;
     289    }
     290  for (sp = fullcache; sp != NULL; sp = sp->next)
     291    {
     292      sc_buflen_t bf = sp->bytesfree;
     293
     294      totfree += bf;
     295      maxfree = (bf > maxfree ? bf : maxfree);
     296      minfree = (bf < minfree ? bf : minfree);
     297
     298      ++numbuffs;
     299      ++fullbuffs;
     300    }
     301
     302  /* Make sure we didn't lose any buffers.  */
     303  assert (total_buffers == numbuffs + 1);
     304
     305  printf (_("\n%s strcache buffers: %lu (%lu) / strings = %lu / storage = %lu B / avg = %lu B\n"),
     306          prefix, numbuffs + 1, fullbuffs, total_strings, total_size,
     307          (total_size / total_strings));
     308
     309  printf (_("%s current buf: size = %hu B / used = %hu B / count = %hu / avg = %hu B\n"),
     310          prefix, (sc_buflen_t)BUFSIZE, strcache->end, strcache->count,
     311          (strcache->end / strcache->count));
     312
     313  if (numbuffs)
     314    {
     315      /* Show information about non-current buffers.  */
     316      unsigned long sz = total_size - strcache->end;
     317      unsigned long cnt = total_strings - strcache->count;
     318      sc_buflen_t avgfree = totfree / numbuffs;
     319
     320      printf (_("%s other used: total = %lu B / count = %lu / avg = %lu B\n"),
     321              prefix, sz, cnt, sz / cnt);
     322
     323      printf (_("%s other free: total = %lu B / max = %lu B / min = %lu B / avg = %hu B\n"),
     324              prefix, totfree, maxfree, minfree, avgfree);
     325    }
     326
     327  printf (_("\n%s strcache performance: lookups = %lu / hit rate = %lu%%\n"),
     328          prefix, total_adds, (long unsigned)(100.0 * (total_adds - total_strings) / total_adds));
     329  fputs (_("# hash-table stats:\n# "), stdout);
    246330  hash_print_stats (&strings, stdout);
    247331}
  • trunk/src/kmk/strcache2.c

    r3091 r3140  
    2727*   Header Files                                                               *
    2828*******************************************************************************/
    29 #include "make.h"
     29#include "makeint.h"
    3030#include "strcache2.h"
    3131
  • trunk/src/kmk/subproc.bat

    r2591 r3140  
    11@echo off
    2 rem Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
    3 rem 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2rem Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43rem This file is part of GNU Make.
    54rem
     
    2221if x%2 == x set MAKE=nmake
    2322%MAKE% /f %MAKEFILE%
     23if ERRORLEVEL 1 exit /B
    2424cd ..\..
  • trunk/src/kmk/tests/NEWS

    r2591 r3140  
    7373    Also, some tests and stuff still haven't made it in because I
    7474    haven't had time to write the test scripts for them.  But they,
    75     too, will get in eventually.  Contributions of scripts (ie, tests
     75    too, will get in eventually.  Contributions of scripts (i.e., tests
    7676    that I can just drop in) are particularly welcome and will be
    7777    incorporated immediately.
     
    164164
    165165-------------------------------------------------------------------------------
    166 Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
    167 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
     166Copyright (C) 1992-2016 Free Software Foundation, Inc.
    168167This file is part of GNU Make.
    169168
  • trunk/src/kmk/tests/README

    r2591 r3140  
    88
    99 -----------------------------------------------------------------------------
    10  Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
    11  2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
     10 Copyright (C) 1992-2016 Free Software Foundation, Inc.
    1211 This file is part of GNU Make.
    1312
     
    4039
    4140By default, the test engine picks up the first executable called "make"
    42 that it finds in your path.  You may use the -make_path option (ie,
     41that it finds in your path.  You may use the -make_path option (i.e.,
    4342"perl run_make_tests -make_path /usr/local/src/make-3.78/make") if
    4443you want to run a particular copy.  This now works correctly with
     
    6059make to be setgid sys or kmem for this; if you don't want to install
    6160make just to test it, make it setgid to kmem or whatever group /dev/kmem
    62 is (ie, "chgrp kmem make;chmod g+s make" as root).  In any case, the
     61is (i.e., "chgrp kmem make;chmod g+s make" as root).  In any case, the
    6362options/dash-l test should no longer *fail* because make can't read
    6463/dev/kmem.
  • trunk/src/kmk/tests/mkshadow

    r2591 r3140  
    44# Typically you'd put the shadow in /tmp or another local disk
    55#
    6 # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
    7 # 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
    8 # Foundation, Inc.
     6# Copyright (C) 1992-2016 Free Software Foundation, Inc.
    97# This file is part of GNU Make.
    108#
     
    2927
    3028if [ ! -d "$dest" ]; then
    31   echo "Destination directory \`$dest' must exist!"
     29  echo "Destination directory '$dest' must exist!"
    3230  exit 1
    3331fi
     
    5654rm -rf work
    5755
    58 echo "Shadow test suite created in \`$dest/$name'."
     56echo "Shadow test suite created in '$dest/$name'."
    5957exit 0
  • trunk/src/kmk/tests/run_make_tests.pl

    r2591 r3140  
    1212#                        (and others)
    1313
    14 # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
    15 # 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
    16 # Foundation, Inc.
     14# Copyright (C) 1992-2016 Free Software Foundation, Inc.
    1715# This file is part of GNU Make.
    1816#
     
    3028# this program.  If not, see <http://www.gnu.org/licenses/>.
    3129
     30%FEATURES = ();
    3231
    3332$valgrind = 0;              # invoke make with valgrind
    3433$valgrind_args = '';
    35 $memcheck_args = '--num-callers=15 --tool=memcheck --leak-check=full';
     34$memcheck_args = '--num-callers=15 --tool=memcheck --leak-check=full --suppressions=guile.supp';
    3635$massif_args = '--num-callers=15 --tool=massif --alloc-fn=xmalloc --alloc-fn=xcalloc --alloc-fn=xrealloc --alloc-fn=xstrdup --alloc-fn=xstrndup';
    3736$pure_log = undef;
    3837
     38# The location of the GNU make source directory
     39$srcdir = '';
     40
    3941$command_string = '';
    4042
    4143$all_tests = 0;
    4244
     45# rmdir broken in some Perls on VMS.
     46if ($^O eq 'VMS')
     47{
     48  require VMS::Filespec;
     49  VMS::Filespec->import();
     50
     51  sub vms_rmdir {
     52    my $vms_file = vmspath($_[0]);
     53    $vms_file = fileify($vms_file);
     54    my $ret = unlink(vmsify($vms_file));
     55    return $ret
     56  };
     57
     58  *CORE::GLOBAL::rmdir = \&vms_rmdir;
     59}
     60
    4361require "test_driver.pl";
     62require "config-flags.pm";
    4463
    4564# Some target systems might not have the POSIX module...
     
    6180   }
    6281
     82   if ($option =~ /^-srcdir$/i) {
     83       $srcdir = shift @argv;
     84       if (! -f "$srcdir/gnumake.h") {
     85           print "$option $srcdir: Not a valid GNU make source directory.\n";
     86           exit 0;
     87       }
     88       return 1;
     89   }
     90
    6391   if ($option =~ /^-all([-_]?tests)?$/i) {
    6492       $all_tests = 1;
     
    99127$old_makefile = undef;
    100128
     129sub subst_make_string
     130{
     131    local $_ = shift;
     132    $makefile and s/#MAKEFILE#/$makefile/g;
     133    s/#MAKEPATH#/$mkpath/g;
     134    s/#MAKE#/$make_name/g;
     135    s/#PERL#/$perl_name/g;
     136    s/#PWD#/$pwd/g;
     137    return $_;
     138}
     139
    101140sub run_make_test
    102141{
    103142  local ($makestring, $options, $answer, $err_code, $timeout) = @_;
     143  my @call = caller;
    104144
    105145  # If the user specified a makefile string, create a new makefile to contain
     
    116156    }
    117157
    118     # Make sure it ends in a newline.
     158    # Make sure it ends in a newline and substitute any special tokens.
    119159    $makestring && $makestring !~ /\n$/s and $makestring .= "\n";
    120 
    121     # Replace @MAKEFILE@ with the makefile name and @MAKE@ with the path to
    122     # make
    123     $makestring =~ s/#MAKEFILE#/$makefile/g;
    124     $makestring =~ s/#MAKEPATH#/$mkpath/g;
    125     $makestring =~ s/#MAKE#/$make_name/g;
    126     $makestring =~ s/#PERL#/$perl_name/g;
    127     $makestring =~ s/#PWD#/$pwd/g;
     160    $makestring = subst_make_string($makestring);
    128161
    129162    # Populate the makefile!
     
    134167
    135168  # Do the same processing on $answer as we did on $makestring.
    136 
    137   $answer && $answer !~ /\n$/s and $answer .= "\n";
    138   $answer =~ s/#MAKEFILE#/$makefile/g;
    139   $answer =~ s/#MAKEPATH#/$mkpath/g;
    140   $answer =~ s/#MAKE#/$make_name/g;
    141   $answer =~ s/#PERL#/$perl_name/g;
    142   $answer =~ s/#PWD#/$pwd/g;
     169  if (defined $answer) {
     170      $answer && $answer !~ /\n$/s and $answer .= "\n";
     171      $answer = subst_make_string($answer);
     172  }
    143173
    144174  run_make_with_options($makefile, $options, &get_logfile(0),
    145                         $err_code, $timeout);
     175                        $err_code, $timeout, @call);
    146176  &compare_output($answer, &get_logfile(1));
    147177
     
    152182# The old-fashioned way...
    153183sub run_make_with_options {
    154   local ($filename,$options,$logname,$expected_code,$timeout) = @_;
     184  my ($filename,$options,$logname,$expected_code,$timeout,@call) = @_;
     185  @call = caller unless @call;
    155186  local($code);
    156187  local($command) = $make_path;
     
    166197
    167198  if ($options) {
     199    if ($^O eq 'VMS') {
     200      # Try to make sure arguments are properly quoted.
     201      # This does not handle all cases.
     202
     203      # VMS uses double quotes instead of single quotes.
     204      $options =~ s/\'/\"/g;
     205
     206      # If the leading quote is inside non-whitespace, then the
     207      # quote must be doubled, because it will be enclosed in another
     208      # set of quotes.
     209      $options =~ s/(\S)(\".*\")/$1\"$2\"/g;
     210
     211      # Options must be quoted to preserve case if not already quoted.
     212      $options =~ s/(\S+)/\"$1\"/g;
     213
     214      # Special fixup for embedded quotes.
     215      $options =~ s/(\"\".+)\"(\s+)\"(.+\"\")/$1$2$3/g;
     216
     217      $options =~ s/(\A)(?:\"\")(.+)(?:\"\")/$1\"$2\"/g;
     218
     219      # Special fixup for misc/general4 test.
     220      $options =~ s/""\@echo" "cc""/\@echo cc"/;
     221      $options =~ s/"\@echo link"""/\@echo link"/;
     222
     223      # Remove shell escapes expected to be removed by bash
     224      if ($options !~ /path=pre/) {
     225        $options =~ s/\\//g;
     226      }
     227
     228      # special fixup for options/eval
     229      $options =~ s/"--eval=\$\(info" "eval/"--eval=\$\(info eval/;
     230
     231      print ("Options fixup = -$options-\n") if $debug;
     232    }
    168233    $command .= " $options";
    169234  }
    170235
    171   $command_string = "$command\n";
     236  $command_string = "";
     237  if (@call) {
     238      $command_string = "#$call[1]:$call[2]\n";
     239  }
     240  $command_string .= "$command\n";
    172241
    173242  if ($valgrind) {
     
    184253
    185254      $code = &run_command_with_output($logname,$command);
    186 
    187255      $test_timeout = $old_timeout;
    188256  }
     
    229297{
    230298   &print_standard_usage ("run_make_tests",
    231                           "[-make_path make_pathname] [-memcheck] [-massif]",);
     299                          "[-make MAKE_PATHNAME] [-srcdir SRCDIR] [-memcheck] [-massif]",);
    232300}
    233301
     
    235303{
    236304   &print_standard_help (
    237         "-make_path",
     305        "-make",
    238306        "\tYou may specify the pathname of the copy of make to run.",
     307        "-srcdir",
     308        "\tSpecify the make source directory.",
    239309        "-valgrind",
    240310        "-memcheck",
     
    296366     $port_type = 'OS/2';
    297367   }
     368
     369   # VMS has a GNV Unix mode or a DCL mode.
     370   # The SHELL environment variable should not be defined in VMS-DCL mode.
     371   elsif ($osname eq 'VMS' && !defined $ENV{"SHELL"}) {
     372     $port_type = 'VMS-DCL';
     373   }
    298374   # Everything else, right now, is UNIX.  Note that we should integrate
    299375   # the VOS support into this as well and get rid of $vos; we'll do
     
    314390   # Find the full pathname of Make.  For DOS systems this is more
    315391   # complicated, so we ask make itself.
    316    my $mk = `sh -c 'echo "all:;\@echo \\\$(MAKE)" | $make_path -f-'`;
    317    chop $mk;
    318    $mk or die "FATAL ERROR: Cannot determine the value of \$(MAKE):\n
     392   if ($osname eq 'VMS') {
     393     $port_type = 'VMS-DCL' unless defined $ENV{"SHELL"};
     394     # On VMS pre-setup make to be found with simply 'make'.
     395     $make_path = 'make';
     396   } else {
     397     my $mk = `sh -c 'echo "all:;\@echo \\\$(MAKE)" | $make_path -f-'`;
     398     chop $mk;
     399     $mk or die "FATAL ERROR: Cannot determine the value of \$(MAKE):\n
    319400'echo \"all:;\@echo \\\$(MAKE)\" | $make_path -f-' failed!\n";
    320    $make_path = $mk;
    321    print "Make\t= `$make_path'\n" if $debug;
    322 
    323    $string = `$make_path -v -f /dev/null 2> /dev/null`;
     401     $make_path = $mk;
     402   }
     403   print "Make\t= '$make_path'\n" if $debug;
     404
     405   my $redir2 = '2> /dev/null';
     406   $redir2 = '' if os_name eq 'VMS';
     407   $string = `$make_path -v -f /dev/null $redir2`;
    324408
    325409   $string =~ /^(GNU Make [^,\n]*)/;
    326410   $testee_version = "$1\n";
    327411
    328    $string = `sh -c "$make_path -f /dev/null 2>&1"`;
     412   my $redir = '2>&1';
     413   $redir = '' if os_name eq 'VMS';
     414   $string = `sh -c "$make_path -f /dev/null $redir"`;
    329415   if ($string =~ /(.*): \*\*\* No targets\.  Stop\./) {
    330416     $make_name = $1;
    331417   }
    332418   else {
    333      if ($make_path =~ /$pathsep([^\n$pathsep]*)$/) {
    334        $make_name = $1;
    335      }
    336      else {
    337        $make_name = $make_path;
    338      }
     419     $make_path =~ /^(?:.*$pathsep)?(.+)$/;
     420     $make_name = $1;
    339421   }
    340422
     
    350432   {
    351433      $mkpath = $make_path;
     434   }
     435
     436   # If srcdir wasn't provided on the command line, see if the
     437   # location of the make program gives us a clue.  Don't fail if not;
     438   # we'll assume it's been installed into /usr/include or wherever.
     439   if (! $srcdir) {
     440       $make_path =~ /^(.*$pathsep)?/;
     441       my $d = $1 || '../';
     442       -f "${d}gnumake.h" and $srcdir = $d;
     443   }
     444
     445   # Not with the make program, so see if we can get it out of the makefile
     446   if (! $srcdir && open(MF, "< ../Makefile")) {
     447       local $/ = undef;
     448       $_ = <MF>;
     449       close(MF);
     450       /^abs_srcdir\s*=\s*(.*?)\s*$/m;
     451       -f "$1/gnumake.h" and $srcdir = $1;
    352452   }
    353453
     
    361461   }
    362462
    363    $string = `sh -c "$make_path -j 2 -f /dev/null 2>&1"`;
     463   $string = `sh -c "$make_path -j 2 -f /dev/null $redir"`;
    364464   if ($string =~ /not supported/) {
    365465     $parallel_jobs = 0;
     
    369469   }
    370470
     471   %FEATURES = map { $_ => 1 } split /\s+/, `sh -c "echo '\\\$(info \\\$(.FEATURES))' | $make_path -f- 2>/dev/null"`;
     472
    371473   # Set up for valgrind, if requested.
     474
     475   $make_command = $make_path;
    372476
    373477   if ($valgrind) {
  • trunk/src/kmk/tests/scripts/features/conditionals

    r969 r3140  
    142142              'success');
    143143
     144# SV 47960 : ensure variable assignments in non-taken legs don't cause problems
     145run_make_test('
     146ifneq ($(FOO),yes)
     147target:
     148else
     149BAR = bar
     150target:
     151endif
     152        @echo one
     153',
     154              '', "one\n");
     155
    144156
    145157# This tells the test driver that the perl test script executed properly.
    1461581;
     159
     160### Local Variables:
     161### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     162### End:
  • trunk/src/kmk/tests/scripts/features/default_names

    r1937 r3140  
    1111close(MAKEFILE);
    1212
    13 # DOS/WIN32 platforms preserve case, but Makefile is the same file as makefile.
    14 # Just test what we can here (avoid Makefile versus makefile test).
    15 # bird: made this generic, darwin is also defaulting to case insensitive fs.
     13# Create another makefile called "makefile"
     14open(MAKEFILE,"> makefile");
     15print MAKEFILE "SECOND: ; \@echo It chose makefile\n";
     16close(MAKEFILE);
    1617
    17 if ($port_type eq 'UNIX' && !$case_insensitive_fs) {
    18   # Create another makefile called "makefile"
    19   open(MAKEFILE,"> makefile");
    20   print MAKEFILE "SECOND: ; \@echo It chose makefile\n";
    21   close(MAKEFILE);
     18# DOS/WIN32/MacOSX platforms are case-insensitive / case-preserving, so
     19# Makefile is the same file as makefile.  Just test what we can here.
     20
     21my $case_sensitive = 0;
     22if (! -f 'Makefile') {
     23    # Create another makefile called "Makefile"
     24    $case_sensitive = 1;
     25    open(MAKEFILE,"> Makefile");
     26    print MAKEFILE "THIRD: ; \@echo It chose Makefile\n";
     27    close(MAKEFILE);
    2228}
    2329
    24 # Create another makefile called "Makefile"
    25 open(MAKEFILE,"> Makefile");
    26 print MAKEFILE "THIRD: ; \@echo It chose Makefile\n";
    27 close(MAKEFILE);
     30run_make_with_options("","",&get_logfile);
     31compare_output("It chose GNUmakefile\n",&get_logfile(1));
     32unlink($makefile);
    2833
     34run_make_with_options("","",&get_logfile);
     35compare_output("It chose makefile\n",&get_logfile(1));
     36unlink("makefile");
    2937
    30 &run_make_with_options("","",&get_logfile);
    31 &compare_output("It chose GNUmakefile\n",&get_logfile(1));
    32 unlink $makefile;
    33 
    34 if ($port_type eq 'UNIX' && !$case_insensitive_fs) {
    35   &run_make_with_options("","",&get_logfile);
    36   &compare_output("It chose makefile\n",&get_logfile(1));
    37   unlink "makefile";
     38if ($case_sensitive) {
     39    run_make_with_options("","",&get_logfile);
     40    compare_output("It chose Makefile\n",&get_logfile(1));
     41    unlink("Makefile");
    3842}
    3943
    40 &run_make_with_options("","",&get_logfile);
    41 &compare_output("It chose Makefile\n",&get_logfile(1));
    42 unlink "Makefile";
     441;
  • trunk/src/kmk/tests/scripts/features/double_colon

    r969 r3140  
    152152unlink('result','one','two');
    153153
     154# TEST 10: SV 33399 : check for proper backslash handling
     155
     156run_make_test('
     157a\ xb :: ; @echo one
     158a\ xb :: ; @echo two
     159',
     160              '', "one\ntwo\n");
     161
     162# Test 11: SV 44742 : All double-colon rules should be run in parallel build.
     163
     164run_make_test('result :: 01
     165        @echo update
     166        @touch $@
     167result :: 02
     168        @echo update
     169        @touch $@
     170result :: 03
     171        @echo update
     172        @touch $@
     173result :: 04
     174        @echo update
     175        @touch $@
     176result :: 05
     177        @echo update
     178        @touch $@
     17901 02 03 04 05:
     180        @touch 01 02 03 04 05
     181',
     182              '-j10 result', "update\nupdate\nupdate\nupdate\nupdate\n");
     183
     184unlink('result', '01', '02', '03', '04', '05');
     185
     186# Test 12: SV 44742 : Double-colon rules with parallelism
     187
     188run_make_test('
     189root: all
     190        echo root
     191all::
     192        echo all_one
     193all:: 3
     194        echo all_two
     195%:
     196        sleep $*
     197',
     198              '-rs -j2 1 2 root', "all_one\nall_two\nroot\n");
     199
     200# SV 47995 : Parallel double-colon rules with FORCE
     201
     202run_make_test('
     203all:: ; @echo one
     204
     205all:: joe ; @echo four
     206
     207joe: FORCE ; touch joe-is-forced
     208
     209FORCE:
     210',
     211              '-j5', "one\ntouch joe-is-forced\nfour\n");
     212
     213unlink('joe-is-forced');
     214
    154215# This tells the test driver that the perl test script executed properly.
    1552161;
     217
     218### Local Variables:
     219### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     220### End:
  • trunk/src/kmk/tests/scripts/features/errors

    r969 r3140  
    3131              ."\t-$rm_command cleanit\n"
    3232              ."\t$rm_command foo\n"
    33               ."clean2: \n"
     33              ."clean2: \n"
    3434              ."\t$rm_command cleanit\n"
    3535              ."\t$rm_command foo\n";
     
    4343unlink("cleanit");
    4444$cleanit_error = `sh -c "$rm_command cleanit 2>&1"`;
     45chomp $cleanit_error;
    4546$delete_error_code = $? >> 8;
    4647
     
    4849# -------
    4950
    50 $answer = "$rm_command cleanit\n"
    51          . $cleanit_error
    52          ."$make_name: [clean] Error $delete_error_code (ignored)\n"
    53          ."$rm_command foo\n";
     51$answer = "$rm_command cleanit
     52$cleanit_error
     53$make_name: [$makefile:2: clean] Error $delete_error_code (ignored)
     54$rm_command foo\n";
    5455
    5556&run_make_with_options($makefile,"",&get_logfile);
     
    7576# -------
    7677
    77 $answer = "$rm_command cleanit\n"
    78          . $cleanit_error
    79          ."$make_name: [clean2] Error $delete_error_code (ignored)\n"
    80          ."$rm_command foo\n";
     78$answer = "$rm_command cleanit
     79$cleanit_error
     80$make_name: [$makefile:5: clean2] Error $delete_error_code (ignored)
     81$rm_command foo\n";
    8182
    8283&run_make_with_options($makefile,"clean2 -i",&get_logfile);
     
    9091}
    9192
     93# Test that error line offset works
     94
     95run_make_test(q!
     96all:
     97        @echo hi
     98        @echo there
     99        @exit 1
     100!,
     101              '', "hi\nthere\n#MAKE#: *** [#MAKEFILE#:5: all] Error 1", 512);
     102
    921031;
     104
     105### Local Variables:
     106### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     107### End:
  • trunk/src/kmk/tests/scripts/features/escape

    r1938 r3140  
    33
    44$details = "\
    5 Make sure that escaping of `:' works in target names.
     5Make sure that escaping of ':' works in target names.
    66Make sure escaping of whitespace works in target names.
    7 Make sure that escaping of '#' works.";
    8 
    9 
    10 close(MAKEFILE);
     7Make sure that escaping of '#' works.
     8Make sure that backslash before non-special characters are kept.";
    119
    1210
     
    2725run_make_test(undef,
    2826              'path=pre:',
    29               "#MAKEFILE#:2: *** target pattern contains no `%' (target `foo').  Stop.",
     27              "#MAKEFILE#:2: *** target pattern contains no '%' (target 'foo').  Stop.",
    3028              512);
    3129
     
    4038run_make_test(undef,
    4139              "'path=pre\\\\:'",
    42               "#MAKEFILE#:2: *** target pattern contains no `%' (target `foo').  Stop.",
     40              "#MAKEFILE#:2: *** target pattern contains no '%'  (target 'foo').  Stop.",
    4341              512);
    4442
     
    5553              'foo#bar.ext = (foo#bar.ext)');
    5654
     55# Test escaped colons in prerequisites
     56# Quoting of backslashes in q!! is kind of messy.
     57# Solaris sh does not properly handle backslashes even in '' so just
     58# check the output make prints, not what the shell interprets.
     59run_make_test(q!
     60foo: foo\\:bar foo\\\\\\:bar foo\\\\\\\\\\:bar
     61foo foo\\:bar foo\\\\\\:bar foo\\\\\\\\\\:bar: ; : '$@'
     62!,
     63              '', ": 'foo:bar'\n: 'foo\\:bar'\n: 'foo\\\\:bar'\n: 'foo'\n");
     64
     65# Test backslash before non-special chars: should be kept as-is
     66
     67run_make_test(q!
     68all: ..\foo
     69.DEFAULT: ; : '$@'
     70!,
     71              '', ": '..\\foo'\n");
     72
    5773# This tells the test driver that the perl test script executed properly.
    58741;
  • trunk/src/kmk/tests/scripts/features/include

    r2591 r3140  
    11#                                     -*-mode: perl; rm-trailing-spaces: nil-*-
    22
    3 $description = "Test various forms of the GNU make `include' command.";
     3$description = "Test various forms of the GNU make 'include' command.";
    44
    55$details = "\
     
    6161',
    6262   '',
    63    "#MAKE#: *** No rule to make target `foo.mk', needed by `error'.  Stop.\n",
     63   "#MAKE#: *** No rule to make target 'foo.mk', needed by 'error'.  Stop.\n",
    6464   512
    6565  );
     
    129129',
    130130'',
    131 "#MAKE#: *** No rule to make target `baz', needed by `bar'.  Stop.\n",
     131"#MAKE#: *** No rule to make target 'baz', needed by 'bar'.  Stop.\n",
    132132512);
    133133
     
    145145',
    146146'',
    147 "#MAKE#: *** No rule to make target `end', needed by `baz'.  Stop.\n",
     147"#MAKE#: *** No rule to make target 'end', needed by 'baz'.  Stop.\n",
    148148512);
    149149
     
    163163'',
    164164"#MAKEFILE#:2: bar: No such file or directory
    165 #MAKE#: *** No rule to make target `end', needed by `baz'.  Stop.\n",
     165#MAKE#: *** No rule to make target 'end', needed by 'baz'.  Stop.\n",
    166166512);
     167
     168# Test include of make-able file doesn't show an error (Savannah #102)
     169run_make_test(q!
     170.PHONY: default
     171default:; @echo DONE
     172
     173inc1:; echo > $@
     174include inc1
     175include inc2
     176inc2:; echo > $@
     177!,
     178              '', "echo > inc2\necho > inc1\nDONE\n");
     179
     180rmfiles('inc1', 'inc2');
     181
     182# Test include of non-make-able file does show an error (Savannah #102)
     183run_make_test(q!
     184.PHONY: default
     185default:; @echo DONE
     186
     187inc1:; echo > $@
     188include inc1
     189include inc2
     190!,
     191              '', "#MAKEFILE#:7: inc2: No such file or directory\n#MAKE#: *** No rule to make target 'inc2'.  Stop.\n", 512);
     192
     193rmfiles('inc1');
     194
     195# Include same file multiple times
     196
     197run_make_test(q!
     198default:; @echo DEFAULT
     199include inc1
     200inc1:; echo > $@
     201include inc1
     202!,
     203              '', "echo > inc1\nDEFAULT\n");
     204
     205rmfiles('inc1');
     206
     207# Included file has a prerequisite that fails to build
     208
     209run_make_test(q!
     210default:; @echo DEFAULT
     211include inc1
     212inc1: foo; echo > $@
     213foo:; exit 1
     214!,
     215              '', "exit 1\n#MAKEFILE#:3: inc1: No such file or directory\n#MAKE#: *** [#MAKEFILE#:5: foo] Error 1\n", 512);
     216
     217rmfiles('inc1');
     218
     219# Included file has a prerequisite we don't know how to build
     220
     221run_make_test(q!
     222default:; @echo DEFAULT
     223include inc1
     224inc1: foo; echo > $@
     225!,
     226              '', "#MAKEFILE#:3: inc1: No such file or directory\n#MAKE#: *** No rule to make target 'foo', needed by 'inc1'.  Stop.\n", 512);
     227
     228rmfiles('inc1');
     229
     230# include a directory
    167231
    168232if ($all_tests) {
     
    173237foo: ; @echo foo = bar > $@
    174238!,
    175                   '', "#MAKE#: `foo' is up to date.\n");
     239                  '', "#MAKE#: 'foo' is up to date.\n");
    176240    rmfiles('foo');
    177241}
  • trunk/src/kmk/tests/scripts/features/mult_rules

    r969 r3140  
    4848
    4949# Create the answer to what should be produced by this Makefile
    50 $answer = "$make_name: *** No rule to make target `extra.h', needed by `foo.o'.  Stop.\n";
     50$answer = "$make_name: *** No rule to make target 'extra.h', needed by 'foo.o'.  Stop.\n";
    5151
    5252&compare_output($answer,&get_logfile(1));
  • trunk/src/kmk/tests/scripts/features/parallelism

    r2591 r3140  
    42422.inc: ; \@$sleep_command 1; echo THREE.inc; echo '2: ; \@$sleep_command 1; echo THREE' > \$\@",
    4343              "-j4",
    44               "ONE.inc\nTHREE.inc\nTWO.inc\nONE\nTHREE\nTWO\nsuccess\n");
     44              "ONE.inc\nTHREE.inc\nTWO.inc\nONE\nTHREE\nTWO\nsuccess\n", 0, 7);
    4545
    4646rmfiles(qw(1.inc 2.inc));
     
    61612.inc: ; \@$sleep_command 1; echo THREE.inc; echo '2: ; \@$sleep_command 1; echo THREE' > \$\@",
    6262              "-j4",
    63               "ONE.inc\nTHREE.inc\nTWO.inc\nONE\nTHREE\nTWO\nsuccess\n");
     63              "ONE.inc\nTHREE.inc\nTWO.inc\nONE\nTHREE\nTWO\nsuccess\n", 0, 7);
    6464
    6565rmfiles(qw(1.inc 2.inc));
     
    9292
    9393fail.1 fail.2 fail.3:
    94         \@sleep \$(patsubst fail.%,%,\$\@)
     94        \@$sleep_command \$(patsubst fail.%,%,\$\@)
    9595        \@echo Fail
    9696        \@exit 1
    9797
    9898ok:
    99         \@sleep 4
     99        \@$sleep_command 4
    100100        \@echo Ok done",
    101               '-rR -j5', (!$is_kmk) ? 'Fail
    102 #MAKE#: *** [fail.1] Error 1
     101              '-rR -j5', (!$is_kmk) ? "Fail
     102#MAKE#: *** [#MAKEFILE#:8: fail.1] Error 1
    103103#MAKE#: *** Waiting for unfinished jobs....
    104104Fail
    105 #MAKE#: *** [fail.2] Error 1
    106 Fail
    107 #MAKE#: *** [fail.3] Error 1
    108 Ok done' : 'Fail
     105#MAKE#: *** [#MAKEFILE#:8: fail.2] Error 1
     106Fail
     107#MAKE#: *** [#MAKEFILE#:8: fail.3] Error 1
     108Ok done" : 'Fail
    109109#MAKE#: *** [fail.1] Error 1
    110110The failing command:
     
    155155rmfiles('target');
    156156
    157 # TEST #10: Don't put --jobserver-fds into a re-exec'd MAKEFLAGS.
    158 # We can't test this directly because there's no way a makefile can
    159 # show the value of MAKEFLAGS we were re-exec'd with.  We can intuit it
    160 # by looking for "disabling jobserver mode" warnings; we should only
    161 # get one from the original invocation and none from the re-exec.
    162 # See Savannah bug #18124
     157# TEST #11: Make sure -jN from MAKEFLAGS is processed even when we re-exec
     158# See Savannah bug #33873
     159
     160$extraENV{MAKEFLAGS} = '-j4';
    163161
    164162run_make_test(q!
     163things = thing1 thing2
     164all: $(things)
     165thing1:; @sleep 1; echo '$@ start'; sleep 2; echo '$@ end'
     166thing2:; @echo '$@ start'; sleep 2; echo '$@ end'
    165167-include inc.mk
    166 recur:
    167 #       @echo 'MAKEFLAGS = $(MAKEFLAGS)'
    168         @rm -f inc.mk
    169         @$(MAKE) -j2 -f #MAKEFILE# all
    170 all:
    171 #       @echo 'MAKEFLAGS = $(MAKEFLAGS)'
    172         @echo $@
    173 inc.mk:
    174 #       @echo 'MAKEFLAGS = $(MAKEFLAGS)'
    175         @echo 'FOO = bar' > $@
     168inc.mk: ; @touch $@
    176169!,
    177               '--no-print-directory -j2', "#MAKE#[1]: warning: -jN forced in submake: disabling jobserver mode.\nall\n");
    178 
     170              '', "thing2 start\nthing1 start\nthing2 end\nthing1 end\n");
     171
     172delete $extraENV{MAKEFLAGS};
    179173rmfiles('inc.mk');
    180174
    181 if ($all_tests) {
    182     # Implicit files aren't properly recreated during parallel builds
    183     # Savannah bug #26864
    184 
    185     # The first run works fine
    186     run_make_test(q!
    187 %.bar: %.x foo.y ; cat $^ > $@
    188 %.x: ; touch $@
    189 foo.y: foo.y.in ; cp $< $@
    190 foo.y.in: ; touch $@
     175# Ensure intermediate/secondary files are not pruned incorrectly.
     176# See Savannah bug #30653
     177
     178utouch(-15, 'file2');
     179utouch(-10, 'file4');
     180utouch(-5,  'file1');
     181
     182run_make_test(q!
     183.INTERMEDIATE: file3
     184file4: file3 ; @mv -f $< $@
     185file3: file2 ; touch $@
     186file2: file1 ; @touch $@
    191187!,
    192                   '-j2 main.bar',
    193                   "touch foo.y.in
    194 touch main.x
    195 cp foo.y.in foo.y
    196 cat main.x foo.y > main.bar
    197 rm main.x");
    198 
    199     # Now we touch the .in file and make sure it still works
    200     touch('foo.y.in');
    201 
    202     run_make_test(undef, '-j2 main.bar', "cp foo.y.in foo.y
    203 touch main.x
    204 cat main.x foo.y > main.bar
    205 rm main.x");
    206 
    207     # Clean up
    208     rmfiles(qw(foo.y foo.y.in main.bar));
    209 }
    210 
    211 if ($all_tests) {
    212     # Jobserver FD handling is messed up in some way.
    213     # Savannah bug #28189
    214     # It doesn't look like that bug anymore but this is the code it runs
    215 
    216     run_make_test(q!
    217 ifdef EXTRA
    218 vpath %.dst /
    219 xxx.dst: ; true
    220 yyy.dst: ; true
    221 endif
    222 
    223 M := $(MAKE)
    224 xx: ; $M --no-print-directory -j2 -f $(MAKEFILE_LIST) xxx.dst yyy.dst EXTRA=1
    225 !,
    226                   '-j2',
    227                   '#MAKE#[1]: warning: -jN forced in submake: disabling jobserver mode.
    228 true
    229 true
    230 ');
    231 }
     188              '--no-print-directory -j2', "touch file3");
     189
     190rmfiles('file1', 'file2', 'file3', 'file4');
    232191
    233192# Make sure that all jobserver FDs are closed if we need to re-exec the
     
    267226
    2682271;
     228
     229### Local Variables:
     230### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     231### End:
  • trunk/src/kmk/tests/scripts/features/patspecific_vars

    r2591 r3140  
    8282b%: pattern := good $$t
    8383
    84 global := orginal $$t
     84global := original $$t
    8585
    8686
     
    104104endif
    105105
    106 %z: ; @echo \'pattrn: $a;\'
     106%z: ; @echo \'pattern: $a;\'
    107107
    108108
     
    110110',
    111111'-j1',
    112 'normal: global: orginal $t pattern:  inherit: ;
    113 pattrn: global: orginal $t pattern:  inherit: ;');
     112'normal: global: original $t pattern:  inherit: ;
     113pattern: global: original $t pattern:  inherit: ;');
    114114
    115115
     
    119119'-j1 rec=1',
    120120'normal: global: new $t pattern: good $t inherit: good $t;
    121 pattrn: global: new $t pattern: good $t inherit: good $t;');
     121pattern: global: new $t pattern: good $t inherit: good $t;');
    122122
    123123# TEST #8: override in pattern-specific variables
  • trunk/src/kmk/tests/scripts/features/patternrules

    r2591 r3140  
    112112"dir=$dir",
    113113(!$is_kmk) ?
    114 "#MAKE#: *** [$dir/foo.bar] Error 1" :
     114"#MAKE#: *** [#MAKEFILE#:6: $dir/foo.bar] Error 1":
    115115"#MAKE#: *** [$dir/foo.bar] Error 1" . '
    116116The failing command:
     
    208208!,
    209209              'foo.tex',
    210               "#MAKE#: *** No rule to make target `foo.tex'.  Stop.", 512);
     210              "#MAKE#: *** No rule to make target 'foo.tex'.  Stop.", 512);
    211211
    212212unlink(@f);
     
    227227# This tells the test driver that the perl test script executed properly.
    2282281;
     229
     230### Local Variables:
     231### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     232### End:
  • trunk/src/kmk/tests/scripts/features/recursion

    r2591 r3140  
    1919              ('CFLAGS=-O -w' . ($parallel_jobs ? ' -j 2' : '')),
    2020              ($vos
    21                ? "#MAKE#: Entering directory `#PWD#'
     21               ? "#MAKE#: Entering directory '#PWD#'
    2222make 'CFLAGS=-O' -f #MAKEFILE# foo
    2323make CFLAGS=-O
     
    2727MAKELEVEL = 0
    2828THE END
    29 #MAKE#: Leaving directory `#PWD#'"
    30                : "#MAKE#: Entering directory `#PWD#'
     29#MAKE#: Leaving directory '#PWD#'"
     30               : "#MAKE#: Entering directory '#PWD#'
    3131#MAKEPATH# -f #MAKEFILE# foo
    32 #MAKE#[1]: Entering directory `#PWD#'
     32#MAKE#[1]: Entering directory '#PWD#'
    3333#MAKEPATH#
    3434MAKELEVEL = 1
    3535#MAKEPATH# -f #MAKEFILE# last
    36 #MAKE#[2]: Entering directory `#PWD#'
     36#MAKE#[2]: Entering directory '#PWD#'
    3737#MAKEPATH#
    3838MAKELEVEL = 2
    3939THE END
    40 #MAKE#[2]: Leaving directory `#PWD#'
    41 #MAKE#[1]: Leaving directory `#PWD#'
    42 #MAKE#: Leaving directory `#PWD#'"));
     40#MAKE#[2]: Leaving directory '#PWD#'
     41#MAKE#[1]: Leaving directory '#PWD#'
     42#MAKE#: Leaving directory '#PWD#'"));
    4343
    4444
  • trunk/src/kmk/tests/scripts/features/reinvoke

    r969 r3140  
    5858# including: this and the previous one test different parts of the code.
    5959
    60 run_make_test(undef, "F=b", "[ -f b ] || echo >> b\nhello\n")
     60run_make_test(undef, 'F=b', "[ -f b ] || echo >> b\nhello\n")
    6161
    6262&rmfiles('a','b','c');
    6363
     64# Ensure command line variables are preserved properly across re-exec
     65# Tests for Savannah bug #30723
     66
     67run_make_test('
     68ifdef RECURSE
     69-include foo30723
     70endif
     71recurse: ; @$(MAKE) -f $(MAKEFILE_LIST) RECURSE=1 test
     72test: ; @echo F.O=$(F.O)
     73foo30723: ; @touch $@
     74',
     75              '--no-print-directory F.O=bar', "F.O=bar\n");
     76
     77unlink('foo30723');
     78
    6479# This tells the test driver that the perl test script executed properly.
    65801;
  • trunk/src/kmk/tests/scripts/features/se_explicit

    r2591 r3140  
    88# bird: Modified this test to use ${PRE} instead of $(PRE) as it failes
    99#       when make is built with NO_ARCHIVES defined.
     10
     11# If we don't support archives then the prerequisite is different
     12my $prereq = exists $FEATURES{'archives'} ? '$' : '$(PRE)';
    1013
    1114run_make_test(q!
     
    2124!,
    2225              '',
    23               "\${PRE}\nbar\$biz\nfoo\$bar : bar\$baz bar\$biz");
     26              "$prereq\nbar\$biz\nfoo\$bar : bar\$baz bar\$biz");
    2427
    2528run_make_test(undef, 'SE=1', "three\nfour\nbariz\nfoo\$bar : baraz bariz");
     
    118121all : $$(eval $$(info test))
    119122!,
    120             '', "test\n#MAKE#: Nothing to be done for `all'.\n");
     123            '', "test\n#MAKE#: Nothing to be done for 'all'.\n");
    121124
    122125# TEST #5: (NEGATIVE) catch eval in a prereq list trying to create new
     
    155158
    156159
    157 # This tells the test driver that the perl test script executed properly.
     160# Allow patsubst shorthand in second expansion context.
     161# Requires the colon to be quoted.  Savannah bug #16545
     162run_make_test(q!
     163.PHONY: foo.bar
     164.SECONDEXPANSION:
     165foo: $$(@\\:%=%.bar); @echo '$^'
     166!,
     167              '', "foo.bar\n");
     168
    1581691;
  • trunk/src/kmk/tests/scripts/features/se_implicit

    r2591 r3140  
    223223              '', "\n");
    224224
     225# Test #10: Test second expansion with second expansion prerequisites
     226# Ensures pattern_search() recurses with SE prereqs.
     227touch('a');
     228run_make_test(q!
     229.SECONDEXPANSION:
     230sim_base_rgg := just_a_name
     231sim_base_src := a
     232sim_base_f := a a a
     233sim_%.f: $${sim_$$*_f}
     234        echo $@
     235sim_%.src: $${sim_$$*_src}
     236        echo $@
     237sim_%: \
     238        $$(if $$(sim_$$*_src),sim_%.src) \
     239        $$(if $$(sim_$$*_f),sim_%.f) \
     240        $$(if $$(sim_$$*_rgg),$$(sim_$$*_rgg).s)
     241        echo $@
     242!,
     243              '-s sim_base', "#MAKE#: *** No rule to make target 'sim_base'.  Stop.", 512);
     244
     245unlink('a');
     246
     247# Ensure that order-only tokens embedded in second expansions are parsed
     248run_make_test(q!
     249.SECONDEXPANSION:
     250PREREQS=p1|p2
     251P2=p2
     252all : foo bar
     253f%o: $$(PREREQS) ; @echo '$@' from '$^' and '$|'
     254b%r: p1|$$(P2)   ; @echo '$@' from '$^' and '$|'
     255p% : ; : $@
     256!,
     257              "", ": p1\n: p2\nfoo from p1 and p2\nbar from p1 and p2\n");
     258
    225259# This tells the test driver that the perl test script executed properly.
    2262601;
  • trunk/src/kmk/tests/scripts/features/targetvars

    r2591 r3140  
    238238run_make_test(undef, 'FOO=C', "C f1\n");
    239239
     240# TEST #19: Conditional variables with command-line settings
     241
     242run_make_test('
     243a: FOO ?= f1
     244a: ; @echo "$(FOO)"
     245',
     246              '', "f1\n");
     247
     248run_make_test(undef, 'FOO=C', "C\n");
     249
    240250# TEST #20: Check for continuation after semicolons
    241251
    242252run_make_test(q!
    243 a: A = 'hello; \
     253a: A = 'hello;\
    244254world'
    245255a: ; @echo $(A)
  • trunk/src/kmk/tests/scripts/features/varnesting

    r969 r3140  
    1 $description = "The following test creates a makefile to ...";
     1#                                                                    -*-perl-*-
     2$description = "Test recursive variables";
    23
    34$details = "";
    45
    5 open(MAKEFILE,"> $makefile");
     6run_make_test('
     7x = variable1
     8variable2 := Hello
     9y = $(subst 1,2,$(x))
     10z = y
     11a := $($($(z)))
     12all:
     13        @echo $(a)
     14',
     15              '', "Hello\n");
    616
    7 # The Contents of the MAKEFILE ...
     17# This tests resetting the value of a variable while expanding it.
     18# You may only see problems with this if you're using valgrind or
     19# some other memory checker that poisons freed memory.
     20# See Savannah patch #7534
    821
    9 print MAKEFILE "x = variable1\n"
    10               ."variable2 := Hello\n"
    11               ."y = \$(subst 1,2,\$(x))\n"
    12               ."z = y\n"
    13               ."a := \$(\$(\$(z)))\n"
    14               ."all: \n"
    15               ."\t\@echo \$(a)\n";
    16 
    17 # END of Contents of MAKEFILE
    18 
    19 close(MAKEFILE);
    20 
    21 &run_make_with_options($makefile,"",&get_logfile);
    22 
    23 # Create the answer to what should be produced by this Makefile
    24 $answer = "Hello\n";
    25 
    26 &compare_output($answer,&get_logfile(1));
     22run_make_test('
     23VARIABLE = $(eval VARIABLE := echo hi)$(VARIABLE)
     24wololo:
     25        @$(VARIABLE)
     26',
     27              '', "hi\n");
    2728
    28291;
  • trunk/src/kmk/tests/scripts/features/vpath

    r2591 r3140  
    7676vpath-d/fail.te:
    7777!,
    78               '', "#MAKE#: Nothing to be done for `default'.\n");
     78              '', "#MAKE#: Nothing to be done for 'default'.\n");
    7979
    8080rmdir('vpath-d');
  • trunk/src/kmk/tests/scripts/features/vpath3

    r2591 r3140  
    1 #                                                                     -*-perl-*-
     1#                                                                    -*-perl-*-
    22
    33$description = "Test the interaction of the -lfoo feature and vpath";
    44$details = "";
    55
    6 open(MAKEFILE,"> $makefile");
     6my @dirs_to_make = qw(a1 b1 a2 b2 b3);
     7for my $d (@dirs_to_make) {
     8    mkdir($d, 0777);
     9}
    710
    8 # The Contents of the MAKEFILE ...
    9 
    10 print MAKEFILE "vpath %.a a1\n";
    11 print MAKEFILE "vpath %.so b1\n";
    12 print MAKEFILE "vpath % a2 b2\n";
    13 print MAKEFILE "vpath % b3\n";
    14 print MAKEFILE "all: -l1 -l2 -l3; \@echo \$^\n";
    15 
    16 # END of Contents of MAKEFILE
    17 
    18 close(MAKEFILE);
    19 
    20 mkdir("a1", 0777);
    21 mkdir("b1", 0777);
    22 mkdir("a2", 0777);
    23 mkdir("b2", 0777);
    24 mkdir("b3", 0777);
    25 
    26 @files_to_touch = ("a1${pathsep}lib1.a",
    27                    "b1${pathsep}lib1.so",
    28                    "a2${pathsep}lib2.a",
    29                    "b2${pathsep}lib2.so",
    30                    "lib3.a",
    31                    "b3${pathsep}lib3.so");
    32 
     11my @files_to_touch = ("a1${pathsep}lib1.a",
     12                      "a1${pathsep}libc.a",
     13                      "b1${pathsep}lib1.so",
     14                      "a2${pathsep}lib2.a",
     15                      "b2${pathsep}lib2.so",
     16                      "lib3.a",
     17                      "b3${pathsep}lib3.so");
    3318&touch(@files_to_touch);
    3419
    35 &run_make_with_options($makefile,"",&get_logfile);
     20my $answer = "a1${pathsep}lib1.a a1${pathsep}libc.a " .
     21             "a2${pathsep}lib2.a lib3.a\n";
     22if ($port_type eq 'VMS-DCL') {
     23    $answer =~ s/ /,/g;
     24}
    3625
    37 # Create the answer to what should be produced by this Makefile
    38 $answer = "a1${pathsep}lib1.a a2${pathsep}lib2.a lib3.a\n";
     26run_make_test('
     27vpath %.h b3
     28vpath %.a a1
     29vpath %.so b1
     30vpath % a2 b2
     31vpath % b3
     32all: -l1 -lc -l2 -l3; @echo $^
     33',
     34              '', $answer);
    3935
    40 if (&compare_output($answer,&get_logfile(1)))
    41 {
    42   unlink @files_to_touch;
    43   rmdir("a1");
    44   rmdir("b1");
    45   rmdir("a2");
    46   rmdir("b2");
    47   rmdir("b3");
     36unlink(@files_to_touch);
     37for my $d (@dirs_to_make) {
     38    rmdir($d);
    4839}
    4940
  • trunk/src/kmk/tests/scripts/features/vpathgpath

    r969 r3140  
    5858push(@touchedfiles, "bar.c");
    5959
    60 $answer = "$make_name: Nothing to be done for `general'.\n";
     60$answer = "$make_name: Nothing to be done for 'general'.\n";
    6161
    6262&compare_output($answer,&get_logfile(1));
  • trunk/src/kmk/tests/scripts/features/vpathplus

    r969 r3140  
    8787$answer = "not creating notarget.c from notarget.d
    8888cat notarget.c > notarget.b 2>/dev/null || exit 1
    89 $make_name: *** [notarget.b] Error 1
     89$make_name: *** [$makefile:16: notarget.b] Error 1
    9090";
    9191
     
    127127
    1281281;
     129
     130### Local Variables:
     131### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     132### End:
  • trunk/src/kmk/tests/scripts/functions/call

    r969 r3140  
    55results.\n";
    66
    7 open(MAKEFILE, "> $makefile");
    8 
    9 # The Contents of the MAKEFILE ...
    10 
    11 print MAKEFILE <<'EOMAKE';
     7run_make_test(q!
    128# Simple, just reverse two things
    139#
    1410reverse = $2 $1
    1511
    16 # A complex `map' function, using recursive `call'.
     12# A complex 'map' function, using recursive 'call'.
    1713#
    1814map = $(foreach a,$2,$(call $1,$a))
     
    3935DEP_baz = quux blarp
    4036rest = $(wordlist 2,$(words ${1}),${1})
    41 tclose = $(if $1,$(firstword $1) \
     37tclose = $(if $1,$(firstword $1)\
    4238                $(call tclose,$(sort ${DEP_$(firstword $1)} $(call rest,$1))))
    4339
     
    4945        echo '$(call my-if,a,b,c)'; \
    5046        echo '$(call two,bar,baz)'; \
    51         echo '$(call tclose,foo)'
     47        echo '$(call tclose,foo)';
     48!,
     49              "", "foo bar\ndefault file file\nb d f\n\n\nb\nbar foo baz\nfoo bar baz blarp quux \n");
    5250
    53 
    54 
    55 EOMAKE
    56 
    57 # These won't work until/unless PR/1527 is resolved.
    58 #        echo '$(call my-foreach,a,x y z,$(a)$(a))'; \
    59 #        echo '$(call my-if,,$(warning don't print this),ok)'
     51# These won't work because call expands all its arguments first, before
     52# passing them on, then marks them as resolved/simple, so they're not
     53# expanded again by the function.
    6054#
    61 # $answer = "xx yy zz\nok\n";
    62 
    63 # END of Contents of MAKEFILE
    64 
    65 close(MAKEFILE);
    66 
    67 &run_make_with_options($makefile, "", &get_logfile);
    68 $answer = "foo bar\ndefault file file\nb d f\n\n\nb\nbar foo baz\nfoo bar baz blarp quux \n";
    69 &compare_output($answer, &get_logfile(1));
    70 
     55#        echo '$(call my-foreach,a,x y z,$$(a)$$(a))'; \
     56#        echo '$(call my-if,,$$(info don't print this),$$(info do print this))'
     57#
     58# $answer = "xx yy zz\ndo print this\n";
    7159
    7260# TEST eclipsing of arguments when invoking sub-calls
    7361
    74 $makefile2 = &get_tmpfile;
    75 
    76 open(MAKEFILE,"> $makefile2");
    77 
    78 print MAKEFILE <<'EOF';
    79 
     62run_make_test(q!
    8063all = $1 $2 $3 $4 $5 $6 $7 $8 $9
    8164
     
    8972        @echo $(call level2,1,2,3,4,5,6,7,8)
    9073        @echo $(call level3,1,2,3,4,5,6,7,8)
    91 EOF
     74!,
     75              "", "1 2 3 4 5 6 7 8 9\n1 2 3 4 5\n1 2 3\n1 2 3\n");
    9276
    93 close(MAKEFILE);
     77# Ensure that variables are defined in global scope even in a $(call ...)
    9478
    95 &run_make_with_options($makefile2, "", &get_logfile);
    96 $answer = "1 2 3 4 5 6 7 8 9\n1 2 3 4 5\n1 2 3\n1 2 3\n";
    97 &compare_output($answer,&get_logfile(1));
     79delete $ENV{X123};
     80
     81run_make_test('
     82tst = $(eval export X123)
     83$(call tst)
     84all: ; @echo "$${X123-not set}"
     85',
     86              '', "\n");
    9887
    99881;
     89
     90### Local Variables:
     91### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     92### End:
  • trunk/src/kmk/tests/scripts/functions/error

    r969 r3140  
    5555
    5656&run_make_with_options($makefile, "ERROR4=definitely", &get_logfile, 512);
    57 $answer = "Some stuff\n$makefile:16: *** error is definitely.  Stop.\n";
     57$answer = "Some stuff\n$makefile:17: *** error is definitely.  Stop.\n";
    5858&compare_output($answer,&get_logfile(1));
    5959
     
    67671;
    6868
    69 
    70 
    71 
    72 
    73 
     69### Local Variables:
     70### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     71### End:
  • trunk/src/kmk/tests/scripts/functions/filter-out

    r969 r3140  
    11#                                                                    -*-perl-*-
    22
    3 $description = "Test the filter-out function.";
     3$description = "Test the filter and filter-out functions.";
    44
    55$details = "The makefile created in this test has two variables.  The
     
    1212functions is the same single .elc name.\n";
    1313
    14 open(MAKEFILE,"> $makefile");
     14# Basic test -- filter
     15run_make_test(q!
     16files1 := $(filter %.o, foo.elc bar.o lose.o)
     17files2 := $(filter %.o foo.i, foo.i bar.i lose.i foo.elc bar.o lose.o)
     18all: ; @echo '$(files1) $(files2)'
     19!,
     20              '', "bar.o lose.o foo.i bar.o lose.o\n");
    1521
    16 print MAKEFILE <<'EOF';
     22# Basic test -- filter-out
     23run_make_test(q!
    1724files1 := $(filter-out %.o, foo.elc bar.o lose.o)
    1825files2 := $(filter-out foo.i bar.i lose.i %.o, foo.i bar.i lose.i foo.elc bar.o lose.o)
    19 all: ; @echo $(files1) $(files2)
    20 EOF
     26all: ; @echo '$(files1) $(files2)'
     27!,
     28              '', "foo.elc foo.elc\n");
    2129
    22 close(MAKEFILE);
     30# Escaped patterns
     31run_make_test(q!all:;@echo '$(filter foo\%bar,foo%bar fooXbar)'!,
     32              '', "foo%bar\n");
    2333
    24 &run_make_with_options($makefile, "", &get_logfile, 0);
    25 $answer = "foo.elc foo.elc\n";
    26 &compare_output($answer,&get_logfile(1));
     34run_make_test(q!all:;@echo '$(filter foo\%\%\\\\\%\%bar,foo%%\\%%bar fooX\\Ybar)'!,
     35              '', "foo%%\\%%bar\n");
     36
     37run_make_test(q!
     38X = $(filter foo\\\\\%bar,foo\%bar foo\Xbar)
     39all:;@echo '$(X)'!,
     40              '', "foo\\%bar\n");
    2741
    28421;
  • trunk/src/kmk/tests/scripts/functions/foreach

    r2175 r3140  
    11#                                                                    -*-perl-*-
    2 # $Id: foreach,v 1.5 2006/03/10 02:20:46 psmith Exp $
     2# $Id$
    33
    44$description = "Test the foreach function.";
     
    5656              'FOREACH');
    5757
     58# Allow variable names with trailing space
     59run_make_test(q!
     60$(foreach \
     61  a \
     62, b c d \
     63, $(info $a))
     64all:;@:
     65!,
     66              "", "b\nc\nd\n");
    5867
    59 # TEST 2: Check some error conditions.
     68# Allow empty variable names.  We still expand the body.
     69
     70run_make_test('
     71x = $(foreach ,1 2 3,a)
     72y := $x
     73
     74all: ; @echo $y',
     75              '', "a a a\n");
     76
     77# Check some error conditions.
    6078
    6179run_make_test('
     
    6583all: ; @echo $y',
    6684              '',
    67               "#MAKEFILE#:2: *** insufficient number of arguments (1) to function `foreach'.  Stop.",
     85              "#MAKEFILE#:2: *** insufficient number of arguments (1) to function 'foreach'.  Stop.",
    6886              512);
    6987
    7088run_make_test('
    71 x = $(foreach )
     89x = $(foreach x,y)
    7290y := $x
    7391
    7492all: ; @echo $y',
    7593              '',
    76               "#MAKEFILE#:2: *** insufficient number of arguments (1) to function `foreach'.  Stop.",
     94              "#MAKEFILE#:2: *** insufficient number of arguments (2) to function 'foreach'.  Stop.",
    7795              512);
    7896
  • trunk/src/kmk/tests/scripts/functions/shell

    r2591 r3140  
    55$details = '';
    66
     7# Test standard shell
     8run_make_test('.PHONY: all
     9OUT := $(shell echo hi)
     10all: ; @echo $(OUT)
     11              ','','hi');
    712
    813# Test shells inside rules.
    914run_make_test('.PHONY: all
    1015all: ; @echo $(shell echo hi)
    11 ','','hi');
     16              ','','hi');
     17
     18# Verify .SHELLSTATUS
     19run_make_test('.PHONY: all
     20PRE := $(.SHELLSTATUS)
     21$(shell exit 0)
     22OK := $(.SHELLSTATUS)
     23$(shell exit 1)
     24BAD := $(.SHELLSTATUS)
     25all: ; @echo PRE=$(PRE) OK=$(OK) BAD=$(BAD)
     26              ','','PRE= OK=0 BAD=1');
    1227
    1328
     
    2843.PHONY: all
    2944all: ; @echo $$HI
    30 ','','hi');
     45    ','','hi');
     46
     47# Test shell errors in recipes including offset
     48run_make_test('
     49all:
     50        @echo hi
     51        $(shell ./basdfdfsed there)
     52        @echo there
     53',
     54              '', "#MAKE#: ./basdfdfsed: Command not found\nhi\nthere\n");
    3155
    32561;
     57
     58### Local Variables:
     59### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     60### End:
  • trunk/src/kmk/tests/scripts/functions/sort

    r969 r3140  
    1 $description = "The following test creates a makefile to verify\n"
    2               ."the ability of make to sort lists of object. Sort\n"
    3               ."will also remove any duplicate entries. This will also\n"
    4               ."be tested.";
     1#                                                                    -*-perl-*-
    52
    6 $details = "The make file is built with a list of object in a random order\n"
    7           ."and includes some duplicates. Make should sort all of the elements\n"
    8           ."remove all duplicates\n";
     3$description = "The following test creates a makefile to verify
     4the ability of make to sort lists of object. Sort
     5will also remove any duplicate entries. This will also
     6be tested.";
    97
    10 open(MAKEFILE,"> $makefile");
     8$details = "The make file is built with a list of object in a random order
     9and includes some duplicates. Make should sort all of the elements
     10remove all duplicates\n";
    1111
    12 # The Contents of the MAKEFILE ...
    13 
    14 print MAKEFILE "foo := moon_light days \n"
    15               ."foo1:= jazz\n"
    16               ."bar := captured \n"
    17               ."bar2 = boy end, has rise A midnight \n"
    18               ."bar3:= \$(foo)\n"
    19               ."s1  := _by\n"
    20               ."s2  := _and_a\n"
    21               ."t1  := \$(addsuffix \$(s1), \$(bar) )\n"
    22               ."t2  := \$(addsuffix \$(s2), \$(foo1) )\n"
    23               ."t3  := \$(t2) \$(t2) \$(t2) \$(t2) \$(t2) \$(t2) \$(t2) \$(t2) \$(t2) \$(t2) \n"
    24               ."t4  := \$(t3) \$(t3) \$(t3) \$(t3) \$(t3) \$(t3) \$(t3) \$(t3) \$(t3) \$(t3) \n"
    25               ."t5  := \$(t4) \$(t4) \$(t4) \$(t4) \$(t4) \$(t4) \$(t4) \$(t4) \$(t4) \$(t4) \n"
    26               ."t6  := \$(t5) \$(t5) \$(t5) \$(t5) \$(t5) \$(t5) \$(t5) \$(t5) \$(t5) \$(t5) \n"
    27               ."t7  := \$(t6) \$(t6) \$(t6) \n"
    28               ."p1  := \$(addprefix \$(foo1), \$(s2) )\n"
    29               ."blank:= \n"
    30               ."all:\n"
    31               ."\t\@echo \$(sort \$(bar2) \$(foo)  \$(addsuffix \$(s1), \$(bar) ) \$(t2) \$(bar2) \$(bar3))\n"
    32               ."\t\@echo \$(sort \$(blank) \$(foo) \$(bar2) \$(t1) \$(p1) )\n"
    33               ."\t\@echo \$(sort \$(foo) \$(bar2) \$(t1) \$(t4) \$(t5) \$(t7) \$(t6) )\n";
     12run_make_test('
     13foo := moon_light days
     14foo1:= jazz
     15bar := captured
     16bar2 = boy end, has rise A midnight
     17bar3:= $(foo)
     18s1  := _by
     19s2  := _and_a
     20t1  := $(addsuffix $(s1), $(bar) )
     21t2  := $(addsuffix $(s2), $(foo1) )
     22t3  := $(t2) $(t2) $(t2) $(t2) $(t2) $(t2) $(t2) $(t2) $(t2) $(t2)
     23t4  := $(t3) $(t3) $(t3) $(t3) $(t3) $(t3) $(t3) $(t3) $(t3) $(t3)
     24t5  := $(t4) $(t4) $(t4) $(t4) $(t4) $(t4) $(t4) $(t4) $(t4) $(t4)
     25t6  := $(t5) $(t5) $(t5) $(t5) $(t5) $(t5) $(t5) $(t5) $(t5) $(t5)
     26t7  := $(t6) $(t6) $(t6)
     27p1  := $(addprefix $(foo1), $(s2) )
     28blank:=
     29all:
     30        @echo $(sort $(bar2) $(foo)  $(addsuffix $(s1), $(bar) ) $(t2) $(bar2) $(bar3))
     31        @echo $(sort $(blank) $(foo) $(bar2) $(t1) $(p1) )
     32        @echo $(sort $(foo) $(bar2) $(t1) $(t4) $(t5) $(t7) $(t6) )
     33',
     34              '', 'A boy captured_by days end, has jazz_and_a midnight moon_light rise
     35A boy captured_by days end, has jazz_and_a midnight moon_light rise
     36A boy captured_by days end, has jazz_and_a midnight moon_light rise
     37');
    3438
    3539
    36 # END of Contents of MAKEFILE
     40# Test with non-space/tab whitespace.  Note that you can't see the
     41# original bug except using valgrind.
    3742
    38 close(MAKEFILE);
    39 
    40 &run_make_with_options($makefile,"",&get_logfile);
    41 
    42 # Create the answer to what should be produced by this Makefile
    43 $answer = "A boy captured_by days end, has jazz_and_a midnight moon_light rise\n"
    44          ."A boy captured_by days end, has jazz_and_a midnight moon_light rise\n"
    45          ."A boy captured_by days end, has jazz_and_a midnight moon_light rise\n";
    46 
    47 &compare_output($answer,&get_logfile(1));
     43run_make_test("FOO = a b\tc\rd\fe \f \f \f \f \ff
     44all: ; \@echo \$(words \$(sort \$(FOO)))\n",
     45              '', "6\n");
    4846
    49471;
    5048
    51 
    52 
    53 
    54 
    55 
     49### Local Variables:
     50### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     51### End:
  • trunk/src/kmk/tests/scripts/functions/warning

    r969 r3140  
    5353
    5454&run_make_with_options($makefile, "WARNING4=definitely", &get_logfile, 0);
    55 $answer = "Some stuff\n$makefile:14: warning is definitely\nhi\nthere\n";
     55$answer = "Some stuff\n$makefile:15: warning is definitely\nhi\nthere\n";
    5656&compare_output($answer,&get_logfile(1));
     57
     58# Test linenumber offset
     59
     60run_make_test(q!
     61all: one two
     62        $(warning in $@ line 3)
     63        @true
     64        $(warning in $@ line 5)
     65
     66one two:
     67        $(warning in $@ line 8)
     68        @true
     69        $(warning in $@ line 10)
     70!,
     71              '', "#MAKEFILE#:8: in one line 8
     72#MAKEFILE#:10: in one line 10
     73#MAKEFILE#:8: in two line 8
     74#MAKEFILE#:10: in two line 10
     75#MAKEFILE#:3: in all line 3
     76#MAKEFILE#:5: in all line 5\n");
    5777
    5878# This tells the test driver that the perl test script executed properly.
    59791;
    6080
    61 
    62 
    63 
    64 
    65 
     81### Local Variables:
     82### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     83### End:
  • trunk/src/kmk/tests/scripts/functions/wildcard

    r2591 r3140  
    8989              '', "\n");
    9090
     91# TEST #5: wildcard used to verify file existence
     92
     93touch('xxx.yyy');
     94
     95run_make_test(q!exists: ; @echo file=$(wildcard xxx.yyy)!,
     96              '', "file=xxx.yyy\n");
     97
     98unlink('xxx.yyy');
     99
     100run_make_test(q!exists: ; @echo file=$(wildcard xxx.yyy)!,
     101              '', "file=\n");
     102
    911031;
  • trunk/src/kmk/tests/scripts/functions/word

    r969 r3140  
    5757wordlist-e3: ; @echo $(wordlist 1, 12a ,$(FOO))',
    5858              'word-e1',
    59               "#MAKEFILE#:3: *** non-numeric first argument to `word' function: ''.  Stop.",
     59              "#MAKEFILE#:3: *** non-numeric first argument to 'word' function: ''.  Stop.",
    6060              512);
    6161
    6262run_make_test(undef,
    6363              'word-e2',
    64               "#MAKEFILE#:4: *** non-numeric first argument to `word' function: 'abc '.  Stop.",
     64              "#MAKEFILE#:4: *** non-numeric first argument to 'word' function: 'abc '.  Stop.",
    6565              512);
    6666
    6767run_make_test(undef,
    6868              'word-e3',
    69               "#MAKEFILE#:5: *** non-numeric first argument to `word' function: '1a'.  Stop.",
     69              "#MAKEFILE#:5: *** non-numeric first argument to 'word' function: '1a'.  Stop.",
    7070              512);
    7171
    7272run_make_test(undef,
    7373              'wordlist-e1',
    74               "#MAKEFILE#:7: *** non-numeric first argument to `wordlist' function: ''.  Stop.",
     74              "#MAKEFILE#:7: *** non-numeric first argument to 'wordlist' function: ''.  Stop.",
    7575              512);
    7676
    7777run_make_test(undef,
    7878              'wordlist-e2',
    79               "#MAKEFILE#:8: *** non-numeric first argument to `wordlist' function: 'abc '.  Stop.",
     79              "#MAKEFILE#:8: *** non-numeric first argument to 'wordlist' function: 'abc '.  Stop.",
    8080              512);
    8181
    8282run_make_test(undef,
    8383              'wordlist-e3',
    84               "#MAKEFILE#:9: *** non-numeric second argument to `wordlist' function: ' 12a '.  Stop.",
     84              "#MAKEFILE#:9: *** non-numeric second argument to 'wordlist' function: ' 12a '.  Stop.",
    8585              512);
    8686
     
    9595wordlist-e: ; @echo $(WL)',
    9696              'word-e x=',
    97               "#MAKEFILE#:3: *** non-numeric first argument to `word' function: ''.  Stop.",
     97              "#MAKEFILE#:3: *** non-numeric first argument to 'word' function: ''.  Stop.",
    9898              512);
    9999
    100100run_make_test(undef,
    101101              'word-e x=abc',
    102               "#MAKEFILE#:3: *** non-numeric first argument to `word' function: 'abc'.  Stop.",
     102              "#MAKEFILE#:3: *** non-numeric first argument to 'word' function: 'abc'.  Stop.",
    103103              512);
    104104
    105105run_make_test(undef,
    106106              'word-e x=0',
    107               "#MAKEFILE#:3: *** first argument to `word' function must be greater than 0.  Stop.",
     107              "#MAKEFILE#:3: *** first argument to 'word' function must be greater than 0.  Stop.",
    108108              512);
    109109
    110110run_make_test(undef,
    111111              'wordlist-e s= e=',
    112               "#MAKEFILE#:4: *** non-numeric first argument to `wordlist' function: ''.  Stop.",
     112              "#MAKEFILE#:4: *** non-numeric first argument to 'wordlist' function: ''.  Stop.",
    113113              512);
    114114
    115115run_make_test(undef,
    116116              'wordlist-e s=abc e=',
    117               "#MAKEFILE#:4: *** non-numeric first argument to `wordlist' function: 'abc'.  Stop.",
     117              "#MAKEFILE#:4: *** non-numeric first argument to 'wordlist' function: 'abc'.  Stop.",
    118118              512);
    119119
    120120run_make_test(undef,
    121121              'wordlist-e s=4 e=12a',
    122               "#MAKEFILE#:4: *** non-numeric second argument to `wordlist' function: '12a'.  Stop.",
     122              "#MAKEFILE#:4: *** non-numeric second argument to 'wordlist' function: '12a'.  Stop.",
    123123              512);
    124124
    125125run_make_test(undef,
    126126              'wordlist-e s=0 e=12',
    127               "#MAKEFILE#:4: *** invalid first argument to `wordlist' function: `0'.  Stop.",
     127              "#MAKEFILE#:4: *** invalid first argument to 'wordlist' function: '0'.  Stop.",
    128128              512);
    129129
  • trunk/src/kmk/tests/scripts/misc/general3

    r969 r3140  
    2727
    2828\$(STR) \$(TAB)",
    29               '', "#MAKE#: Nothing to be done for `all'.");
     29              '', "#MAKE#: Nothing to be done for 'all'.");
    3030
    3131# TEST 2
     
    311311foo     bar');
    312312
     313run_make_test('x:;@-exit 1', '', "#MAKE#: [#MAKEFILE#:1: x] Error 1 (ignored)\n");
     314
    3133151;
  • trunk/src/kmk/tests/scripts/options/dash-B

    r2591 r3140  
    2323              '', 'cp bar.x foo');
    2424
    25 run_make_test(undef, '', "#MAKE#: Nothing to be done for `all'.");
     25run_make_test(undef, '', "#MAKE#: Nothing to be done for 'all'.");
    2626run_make_test(undef, '-B', 'cp bar.x foo');
    2727
     
    2929
    3030utouch(1000, 'foo');
    31 run_make_test(undef, '', "#MAKE#: Nothing to be done for `all'.");
     31run_make_test(undef, '', "#MAKE#: Nothing to be done for 'all'.");
    3232run_make_test(undef, '-B', 'cp bar.x foo');
    3333
     
    4646',
    4747              '-B', 'MAKE_RESTARTS=
    48 #MAKEFILE#:4: foo.x: No such file or directory
    4948MAKE_RESTARTS=1');
    5049
     
    6463',
    6564              '-B', 'MAKE_RESTARTS=
    66 #MAKEFILE#:4: foo.x: No such file or directory
    6765MAKE_RESTARTS=1
    6866blah.x
     
    8482
    85831;
     84
     85### Local Variables:
     86### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     87### End:
  • trunk/src/kmk/tests/scripts/options/dash-C

    r969 r3140  
    3535
    3636# Create the answer to what should be produced by this Makefile
    37 $answer = "$make_name: Entering directory `$wpath'\n"
     37$answer = "$make_name: Entering directory '$wpath'\n"
    3838        . "$delete_command EXAMPLE\n"
    39         . "$make_name: Leaving directory `$wpath'\n";
     39        . "$make_name: Leaving directory '$wpath'\n";
    4040
    4141&compare_output($answer,&get_logfile(1));
     
    6363
    6464# Create the answer to what should be produced by this Makefile
    65 $answer = "$make_name: Entering directory `$wpath'\n"
     65$answer = "$make_name: Entering directory '$wpath'\n"
    6666        . "$delete_command EXAMPLEslash\n"
    67         . "$make_name: Leaving directory `$wpath'\n";
     67        . "$make_name: Leaving directory '$wpath'\n";
    6868
    6969&compare_output($answer,&get_logfile(1));
  • trunk/src/kmk/tests/scripts/options/dash-I

    r969 r3140  
    5252
    5353$answer = "$mkpath ANOTHER -f $makefile
    54 ${make_name}[1]: Entering directory `$pwd'
     54${make_name}[1]: Entering directory '$pwd'
    5555This is another included makefile
    56 ${make_name}[1]: Leaving directory `$pwd'\n";
     56${make_name}[1]: Leaving directory '$pwd'\n";
    5757
    5858&run_make_with_options($makefile,"-I $workdir recurse",&get_logfile);
  • trunk/src/kmk/tests/scripts/options/dash-W

    r969 r3140  
    1313# Run it again: nothing should happen
    1414
    15 run_make_test(undef, '', "#MAKE#: `a.x' is up to date.");
     15run_make_test(undef, '', "#MAKE#: 'a.x' is up to date.");
    1616
    1717# Now run it with -W b.x: should rebuild a.x
     
    2222
    2323utouch(1000, 'a.x');
    24 run_make_test(undef, '', "#MAKE#: `a.x' is up to date.");
     24run_make_test(undef, '', "#MAKE#: 'a.x' is up to date.");
    2525run_make_test(undef, '-W b.x', 'echo >> a.x');
    2626
     
    4343baz.x: bar.x ; @echo "touch $@"
    4444',
    45               '', '#MAKEFILE#:3: foo.x: No such file or directory
    46 echo >> bar.x
     45              '', 'echo >> bar.x
    4746touch foo.x
    4847restarts=1
     
    8786
    88871;
     88
     89### Local Variables:
     90### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     91### End:
  • trunk/src/kmk/tests/scripts/options/dash-k

    r1964 r3140  
    4343               "$workdir${pathsep}commands.c","$workdir${pathsep}display.c",
    4444               "$workdir${pathsep}buffer.h",
    45                "$workdir${pathsep}command.c");
     45               "$workdir${pathsep}command.c");
    4646
    4747&touch(@files_to_touch);
     
    5858# Create the answer to what should be produced by this Makefile
    5959$answer = "cc -c main.c
    60 $make_name: *** No rule to make target `kbd.c', needed by `kbd.o'.
     60$make_name: *** No rule to make target 'kbd.c', needed by 'kbd.o'.
    6161cc -c commands.c
    6262cc -c display.c
    63 $make_name: Target `edit' not remade because of errors.\n";
     63$make_name: Target 'edit' not remade because of errors.\n";
    6464
    6565# COMPARE RESULTS
     
    9393
    9494$answer = "exit 1
    95 $make_name: *** [foo.o] Error 1
    96 $make_name: Target `all' not remade because of errors.\n";
     95$make_name: *** [$makefile2:9: foo.o] Error 1
     96$make_name: Target 'all' not remade because of errors.\n";
    9797
    9898&compare_output($answer, &get_logfile(1));
     
    107107              '-k',
    108108              "#MAKEFILE#:2: ifile: No such file or directory
    109 #MAKE#: *** No rule to make target `no-such-file', needed by `ifile'.
    110 #MAKE#: Failed to remake makefile `ifile'.
     109#MAKE#: *** No rule to make target 'no-such-file', needed by 'ifile'.
     110#MAKE#: Failed to remake makefile 'ifile'.
    111111hi\n",
    112112              512);
  • trunk/src/kmk/tests/scripts/options/dash-n

    r969 r3140  
    44$details = "Try various uses of -n and ensure they all give the correct results.\n";
    55
    6 open(MAKEFILE, "> $makefile");
     6touch('orig');
    77
    8 # The Contents of the MAKEFILE ...
    9 
    10 print MAKEFILE <<'EOMAKE';
    11 
     8run_make_test(q!
    129final: intermediate ; echo >> $@
    1310intermediate: orig ; echo >> $@
    14 
    15 EOMAKE
    16 
    17 close(MAKEFILE);
    18 
    19 &touch('orig');
    20 
    21 # TEST 0
    22 
    23 &run_make_with_options($makefile, "", &get_logfile);
    24 $answer = "echo >> intermediate\necho >> final\n";
    25 &compare_output($answer, &get_logfile(1));
     11!,
     12              '', "echo >> intermediate\necho >> final\n");
    2613
    2714# TEST 1
    2815
    29 &run_make_with_options($makefile, "-Worig -n", &get_logfile);
    30 $answer = "echo >> intermediate\necho >> final\n";
    31 &compare_output($answer, &get_logfile(1));
     16run_make_test(undef, '-Worig -n', "echo >> intermediate\necho >> final\n");
    3217
    33 unlink('orig', 'intermediate', 'final');
     18rmfiles(qw(orig intermediate final));
    3419
    3520# We consider the actual updated timestamp of targets with all
    36 # recursive commands, even with -n.
     21# recursive commands, even with -n.  Switching this to the new model
     22# is non-trivial because we use a trick below to change the log content
     23# before we compare it ...
    3724
    3825$makefile2 = &get_tmpfile;
     
    5744
    5845&run_make_with_options($makefile2, "", &get_logfile);
    59 $answer = "$make_name: `a' is up to date.\n";
     46$answer = "$make_name: 'a' is up to date.\n";
    6047&compare_output($answer, &get_logfile(1));
    6148
     
    6350
    6451&run_make_with_options($makefile2, "-n", &get_logfile);
    65 $answer = "$make_name: `a' is up to date.\n";
     52$answer = "$make_name: 'a' is up to date.\n";
    6653&compare_output($answer, &get_logfile(1));
    6754
    68 unlink('a', 'b', 'c');
     55# TEST 4
     56
     57unlink(qw(a b));
     58
     59&run_make_with_options($makefile2, "-t -n", &get_logfile);
     60
     61open(DASH_N_LOG, ">>" . &get_logfile(1));
     62print DASH_N_LOG "a exists but should not!\n" if -e 'a';
     63print DASH_N_LOG "b exists but should not!\n" if -e 'b';
     64close(DASH_N_LOG);
     65
     66&compare_output("touch b\ntouch a\n", &get_logfile(1));
     67
     68# CLEANUP
     69
     70unlink(qw(a b c));
     71
     72# Ensure -n continues to be included with recursive/re-execed make
     73# See Savannah bug #38051
     74
     75$topmake = &get_tmpfile;
     76$submake = &get_tmpfile;
     77
     78open(MAKEFILE, "> $topmake");
     79print MAKEFILE <<"EOF";
     80foo: ; \@\$(MAKE) -f "$submake" bar
     81EOF
     82close(MAKEFILE);
     83
     84
     85# The bar target should print what would happen, but not actually run
     86open(MAKEFILE, "> $submake");
     87print MAKEFILE <<'EOF';
     88inc: ; touch $@
     89-include inc
     90bar: ; @echo $(strip $(MAKEFLAGS))
     91EOF
     92close(MAKEFILE);
     93
     94&run_make_with_options($topmake, '-n --no-print-directory', &get_logfile);
     95$answer = "$make_command -f \"$submake\" bar\ntouch inc\necho n --no-print-directory\n";
     96&compare_output($answer, &get_logfile(1));
     97
     98unlink('inc');
    6999
    701001;
  • trunk/src/kmk/tests/scripts/options/dash-q

    r969 r3140  
    66# TEST 0
    77
    8 run_make_test('
     8run_make_test(qq!
    99one:
    1010two: ;
    1111three: ; :
    12 four: ; $(.XY)
    13 five: ; \
    14  $(.XY)
    15 six: ; \
    16  $(.XY)
    17         $(.XY)
    18 seven: ; \
    19  $(.XY)
    20         : foo
    21         $(.XY)
    22 ',
     12four: ; \$(.XY)
     13five: ; \\
     14 \$(.XY)
     15six: ; \\
     16 \$(.XY)
     17\t\$(.XY)
     18seven: ; \\
     19 \$(.XY)
     20\t: foo
     21\t\$(.XY)
     22!,
    2323              '-q one', '');
    2424
     
    5555              '-q', '', 256);
    5656
     57# TEST 7 : Savannah bug # 42249
     58# Make sure we exit with 1 even for prerequisite updates
     59run_make_test('
     60build-stamp: ; echo $@
     61build-arch: build-stamp
     62build-x: build-arch
     63build-y: build-x
     64',
     65              '-q build-y', '', 256);
     66
     67# TEST 8
     68# Make sure we exit with 2 on error even with -q
     69run_make_test('
     70build-stamp: ; echo $@
     71build-arch: build-stamp-2
     72build-x: build-arch
     73build-y: build-x
     74',
     75              '-q build-y', "#MAKE#: *** No rule to make target 'build-stamp-2', needed by 'build-arch'.  Stop.\n", 512);
     76
     77# TEST 9 : Savannah bug # 47151
     78# Make sure we exit with 1 when invoking a recursive make
     79run_make_test('
     80foo: bar ; echo foo
     81bar: ; @$(MAKE) -f #MAKEFILE# baz
     82baz: ; echo baz
     83',
     84              '-q foo', '', 256);
     85
    57861;
  • trunk/src/kmk/tests/scripts/options/eval

    r2591 r3140  
    1717              "eval\neval\nall\nrecurse");
    1818
     19# Make sure that --eval is handled correctly during restarting
     20run_make_test(q!
     21all: ; @echo $@
     22-include gen.mk
     23gen.mk: ; @echo > $@
     24!,
     25              '--eval=\$\(info\ eval\)', "eval\neval\nall");
     26
     27unlink('gen.mk');
     28
    19291;
  • trunk/src/kmk/tests/scripts/options/symlinks

    r2591 r3140  
    2727  # With -L, it should update targ
    2828  run_make_test('targ: sym ; @echo make $@ from $<', '',
    29                 "#MAKE#: `targ' is up to date.");
     29                "#MAKE#: 'targ' is up to date.");
    3030  run_make_test(undef, '-L', "make targ from sym");
    3131
     
    3737  # Now update targ; in all cases targ should be up to date.
    3838  &touch('targ');
    39   run_make_test(undef, '', "#MAKE#: `targ' is up to date.");
    40   run_make_test(undef, '-L', "#MAKE#: `targ' is up to date.");
     39  run_make_test(undef, '', "#MAKE#: 'targ' is up to date.");
     40  run_make_test(undef, '-L', "#MAKE#: 'targ' is up to date.");
    4141
    4242  # Add in a new link between sym and dep.  Be sure it's newer than targ.
     
    4747  # Without -L, nothing should happen
    4848  # With -L, it should update targ
    49   run_make_test(undef, '', "#MAKE#: `targ' is up to date.");
     49  run_make_test(undef, '', "#MAKE#: 'targ' is up to date.");
    5050  run_make_test(undef, '-L', "make targ from sym");
    5151
     
    5757  symlink("../$dirname/dep", 'sym');
    5858  run_make_test('targ: sym ; @echo make $@ from $<', '',
    59                 "#MAKE#: *** No rule to make target `sym', needed by `targ'.  Stop.", 512);
     59                "#MAKE#: *** No rule to make target 'sym', needed by 'targ'.  Stop.", 512);
    6060
    6161  run_make_test('targ: sym ; @echo make $@ from $<', '-L',
  • trunk/src/kmk/tests/scripts/options/warn-undefined-variables

    r969 r3140  
    1919# With --warn-undefined-variables, it should warn me
    2020run_make_test(undef, '--warn-undefined-variables',
    21               "#MAKEFILE#:7: warning: undefined variable `UNDEFINED'
    22 #MAKEFILE#:9: warning: undefined variable `UNDEFINED'
     21              "#MAKEFILE#:7: warning: undefined variable 'UNDEFINED'
     22#MAKEFILE#:9: warning: undefined variable 'UNDEFINED'
    2323ref");
    2424
  • trunk/src/kmk/tests/scripts/targets/DEFAULT

    r969 r3140  
    3636
    3737# Create the answer to what should be produced by this Makefile
    38 $answer = "${make_name}[1]: Entering directory `$pwd'\n"
     38$answer = "${make_name}[1]: Entering directory '$pwd'\n"
    3939        . "Executing rule BAR\n"
    40         . "${make_name}[1]: Leaving directory `$pwd'\n";
     40        . "${make_name}[1]: Leaving directory '$pwd'\n";
    4141
    4242# COMPARE RESULTS
  • trunk/src/kmk/tests/scripts/targets/INTERMEDIATE

    r1994 r3140  
    4343
    4444&run_make_with_options($makefile,'foo.d',&get_logfile);
    45 $answer = "$make_name: `foo.d' is up to date.\n";
     45$answer = "$make_name: 'foo.d' is up to date.\n";
    4646&compare_output($answer, &get_logfile(1));
    4747
     
    6666
    6767&run_make_with_options($makefile,'foo.c',&get_logfile);
    68 $answer = "$make_name: `foo.c' is up to date.\n";
     68$answer = "$make_name: 'foo.c' is up to date.\n";
    6969&compare_output($answer, &get_logfile(1));
    7070
  • trunk/src/kmk/tests/scripts/targets/ONESHELL

    r2591 r3140  
    55$details = "";
    66
     7# Some shells (*shakes fist at Solaris*) cannot handle multiple flags in
     8# separate arguments.
     9my $t = `/bin/sh -e -c true 2>/dev/null`;
     10my $multi_ok = $? == 0;
    711
    812# Simple
     
    1721[ 0"$a" -eq "$$" ] || echo fail
    1822');
     23
     24# Simple but use multi-word SHELLFLAGS
     25
     26if ($multi_ok) {
     27    run_make_test(q!
     28.ONESHELL:
     29.SHELLFLAGS = -e -c
     30all:
     31        a=$$$$
     32        [ 0"$$a" -eq "$$$$" ] || echo fail
     33!,
     34              '', 'a=$$
     35[ 0"$a" -eq "$$" ] || echo fail
     36');
     37}
    1938
    2039# Again, but this time with inner prefix chars
  • trunk/src/kmk/tests/scripts/targets/POSIX

    r2591 r3140  
    11#                                                                    -*-perl-*-
    22
    3 $description = "Test the behaviour of the .PHONY target.";
     3$description = "Test the behaviour of the .POSIX target.";
    44
    55$details = "";
     
    1818all: ; \@$script
    1919!,
    20               '', "#MAKE#: *** [all] Error $err\n", 512);
     20              '', "#MAKE#: *** [#MAKEFILE#:3: all] Error $err\n", 512);
    2121
    2222# User settings must override .POSIX
     
    3030              '', $out);
    3131
     32# Test the default value of various POSIX-specific variables
     33my %POSIX = (AR => 'ar', ARFLAGS => '-rv',
     34             YACC => 'yacc', YFLAGS => '',
     35             LEX => 'lex', LFLAGS => '',
     36             LDFLAGS => '',
     37             CC => 'c99', CFLAGS => '-O',
     38             FC => 'fort77', FFLAGS => '-O 1',
     39             GET => 'get', GFLAGS => '',
     40             SCCSFLAGS => '', SCCSGETFLAGS => '-s');
     41my $make = join('', map { "\t\@echo '$_=\$($_)'\n" } sort keys %POSIX);
     42my $r = join('', map { "$_=$POSIX{$_}\n"} sort keys %POSIX);
     43run_make_test(qq!
     44.POSIX:
     45all:
     46$make
     47!,
     48              '', $r);
     49
     50# Make sure that local settings take precedence
     51%extraENV = map { $_ => "xx-$_" } keys %POSIX;
     52$r = join('', map { "$_=xx-$_\n"} sort keys %POSIX);
     53run_make_test(undef, '', $r);
     54
    3255# This tells the test driver that the perl test script executed properly.
    33561;
  • trunk/src/kmk/tests/scripts/targets/SECONDARY

    r1994 r3140  
    4545
    4646&run_make_with_options($makefile,'foo.d',&get_logfile);
    47 $answer = "$make_name: `foo.d' is up to date.\n";
     47$answer = "$make_name: 'foo.d' is up to date.\n";
    4848&compare_output($answer, &get_logfile(1));
    4949
     
    6868
    6969&run_make_with_options($makefile,'foo.c',&get_logfile);
    70 $answer = "$make_name: `foo.c' is up to date.\n";
     70$answer = "$make_name: 'foo.c' is up to date.\n";
    7171&compare_output($answer, &get_logfile(1));
    7272
     
    104104
    105105&run_make_with_options($makefile2, '', &get_logfile);
    106 $answer = "$make_name: `final' is up to date.\n";
     106$answer = "$make_name: 'final' is up to date.\n";
    107107&compare_output($answer, &get_logfile(1));
    108108
     
    130130%.c : %.b ; cp $< $@
    131131%.b : %.a ; cp $< $@
    132 all : 1.c 2.c', '-rR -j',
     132all : 1.c 2.c
     1332.a: 1.c', '-rR -j',
    133134'cp 1.a 1.b
     135cp 1.b 1.c
    134136cp 2.a 2.b
    135 cp 1.b 1.c
    136137cp 2.b 2.c
    137138rm 1.b 2.b');
  • trunk/src/kmk/tests/scripts/variables/DEFAULT_GOAL

    r2591 r3140  
    4343',
    4444'',
    45 '#MAKE#: *** No rule to make target `foo\'.  Stop.',
     45"#MAKE#: *** No rule to make target 'foo'.  Stop.",
    4646512);
    4747
  • trunk/src/kmk/tests/scripts/variables/LIBPATTERNS

    r2591 r3140  
    2121all: -lfoo ; @echo "build $@ from $<"
    2222',
    23               '', "#MAKE#: .LIBPATTERNS element `mtest_foo.a' is not a pattern
     23              '', "#MAKE#: .LIBPATTERNS element 'mtest_foo.a' is not a pattern
    2424build all from mtest_foo.a\n");
    2525
  • trunk/src/kmk/tests/scripts/variables/MAKE

    r2591 r3140  
    1717              '',
    1818              "#MAKEPATH#\n#MAKEPATH# -f #MAKEFILE# foo\n"
    19               . "#MAKE#[1]: Entering directory `#PWD#'\n"
    20               . "#MAKEPATH#\n#MAKE#[1]: Leaving directory `#PWD#'\n");
     19              . "#MAKE#[1]: Entering directory '#PWD#'\n"
     20              . "#MAKEPATH#\n#MAKE#[1]: Leaving directory '#PWD#'\n");
    2121
    2222rmfiles("foo");
  • trunk/src/kmk/tests/scripts/variables/MAKEFLAGS

    r2591 r3140  
    1 #                                                                    -*-perl-*-
     1#                                                                    -*-perl-*-
    22
    33$description = "Test proper behavior of MAKEFLAGS";
     
    99all: ; @echo $(MAKEFLAGS)
    1010!,
    11               '-e -r -R', 'Rre');
     11              '-e -r -R', 'erR');
    1212
    1313# Long arguments mean everything is prefixed with "-"
     
    1515all: ; @echo $(MAKEFLAGS)
    1616!,
    17               '--no-print-directory -e -r -R', '--no-print-directory -Rre');
     17              '--no-print-directory -e -r -R --trace', "#MAKEFILE#:2: target 'all' does not exist
     18echo erR --trace --no-print-directory
     19erR --trace --no-print-directory");
    1820
    1921
    20 if ($all_tests) {
    21     # Recursive invocations of make should accumulate MAKEFLAGS values.
    22     # Savannah bug #2216
    23     run_make_test(q!
     22# Recursive invocations of make should accumulate MAKEFLAGS values.
     23# Savannah bug #2216
     24run_make_test(q!
    2425MSG = Fails
    2526all:
     
    2728        @MSG=Works $(MAKE) -e -f #MAKEFILE# jump
    2829jump:
    29         @echo '$@: MAKEFLAGS=$(MAKEFLAGS)'
     30        @echo '$@ $(MSG): MAKEFLAGS=$(MAKEFLAGS)'
    3031        @$(MAKE) -f #MAKEFILE# print
    3132print:
    32         @echo '$@: MAKEFLAGS=$(MAKEFLAGS)'
    33         @echo $(MSG)
     33        @echo '$@ $(MSG): MAKEFLAGS=$(MAKEFLAGS)'
    3434.PHONY: all jump print
    3535!,
    3636                  '--no-print-directory',
    3737                  'all: MAKEFLAGS= --no-print-directory
    38 jump: MAKEFLAGS= --no-print-directory -e
    39 print: MAKEFLAGS= --no-print-directory -e
    40 Works');
    41 }
     38jump Works: MAKEFLAGS=e --no-print-directory
     39print Works: MAKEFLAGS=e --no-print-directory');
    4240
    43411;
     42
     43### Local Variables:
     44### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     45### End:
  • trunk/src/kmk/tests/scripts/variables/MAKE_RESTARTS

    r969 r3140  
    1212',
    1313              '', 'MAKE_RESTARTS=
    14 #MAKEFILE#:4: foo.x: No such file or directory
    1514MAKE_RESTARTS=1');
    1615
     
    2726',
    2827              '', 'MAKE_RESTARTS=
    29 #MAKEFILE#:4: foo.x: No such file or directory
    3028MAKE_RESTARTS=1
    31 foo.x:1: bar.x: No such file or directory
    3229MAKE_RESTARTS=2');
    3330
     
    4845',
    4946              '', "MAKE_RESTARTS=
    50 #MAKEFILE#:8: foo.x: No such file or directory
    5147MAKE_RESTARTS=1
    52 foo.x:1: bar.x: No such file or directory
    5348MAKE_RESTARTS=2
    5449recurse MAKE_RESTARTS=
     50#MAKE#[1]: Entering directory '#PWD#'
    5551MAKE_RESTARTS=
    56 #MAKE#[1]: Entering directory `#PWD#'
    5752all MAKE_RESTARTS=
    58 #MAKE#[1]: Leaving directory `#PWD#'");
     53#MAKE#[1]: Leaving directory '#PWD#'");
    5954
    6055rmfiles('foo.x', 'bar.x');
    6156
    62571;
     58
     59### Local Variables:
     60### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     61### End:
  • trunk/src/kmk/tests/scripts/variables/SHELL

    r2591 r3140  
    7272              '', $out);
    7373
     74# Do it again but add spaces to SHELLFLAGS
     75
     76# Some shells (*shakes fist at Solaris*) cannot handle multiple flags in
     77# separate arguments.
     78my $t = `/bin/sh -e -c true 2>/dev/null`;
     79my $multi_ok = $? == 0;
     80
     81if ($multi_ok) {
     82    $flags = '-x -c';
     83    run_make_test(qq!
     84.SHELLFLAGS = $flags
     85all: ; \@$script
     86!,
     87              '', $out);
     88}
     89
    7490# We can't just use "false" because on different systems it provides a
    7591# different exit code--once again Solaris: false exits with 255 not 1
     
    8399all: ; \@$script
    84100!,
    85               '', "$out#MAKE#: *** [all] Error $err\n", 512);
     101              '', "$out#MAKE#: *** [#MAKEFILE#:3: all] Error $err\n", 512);
    86102
    871031;
  • trunk/src/kmk/tests/scripts/variables/define

    r2591 r3140  
    3131endef
    3232
     33define posix ::=
     34@echo $(FOO)
     35endef
     36
    3337append = @echo a
    3438
     
    5054all: ; $(multi)
    5155        $(simple)
     56        $(posix)
    5257        $(append)
    5358        $(cond)
    5459',
    55               '', "echo hi\nhi\nthere\nfoo\na\nb\nfirst\n");
     60              '', "echo hi\nhi\nthere\nfoo\nfoo\na\nb\nfirst\n");
     61
     62# TEST 1a: Various new-style define/endef, with no spaces
     63
     64run_make_test('
     65FOO = foo
     66
     67define multi=
     68echo hi
     69@echo $(FOO)
     70endef # this is the end
     71
     72define simple:=
     73@echo $(FOO)
     74endef
     75
     76define posix::=
     77@echo $(FOO)
     78endef
     79
     80append = @echo a
     81
     82define append+=
     83
     84@echo b
     85endef
     86
     87define cond?= # this is a conditional
     88@echo first
     89endef
     90
     91define cond?=
     92@echo second
     93endef
     94
     95FOO = there
     96
     97all: ; $(multi)
     98        $(simple)
     99        $(posix)
     100        $(append)
     101        $(cond)
     102',
     103              '', "echo hi\nhi\nthere\nfoo\nfoo\na\nb\nfirst\n");
    56104
    57105# TEST 2: define in true section of conditional (containing conditional)
     
    113161all: ; @echo ok
    114162',
    115               '', "#MAKEFILE#:3: extraneous text after `define' directive\nok\n");
     163              '', "#MAKEFILE#:3: extraneous text after 'define' directive\nok\n");
    116164
    117165# TEST 7: NEGATIVE: extra text after endef
     
    124172all: ; @echo ok
    125173',
    126               '', "#MAKEFILE#:5: extraneous text after `endef' directive\nok\n");
     174              '', "#MAKEFILE#:5: extraneous text after 'endef' directive\nok\n");
    127175
    128176# TEST 8: NEGATIVE: missing endef
     
    135183endef$(NAME)
    136184',
    137               '', "#MAKEFILE#:4: *** missing `endef', unterminated `define'.  Stop.\n", 512);
     185              '', "#MAKEFILE#:4: *** missing 'endef', unterminated 'define'.  Stop.\n", 512);
    138186
    139187# -------------------------
  • trunk/src/kmk/tests/scripts/variables/flavors

    r2591 r3140  
    7474              '', "Hello\n");
    7575
     76# TEST 6: Simple using POSIX syntax
     77run_make_test('
     78bar = Goodbye
     79foo ::= $(bar)
     80bar = ${ugh}
     81ugh = Hello
     82all: ; @echo $(foo)
     83',
     84              '', "Goodbye\n");
     85
     86# TEST 7: POSIX syntax no spaces
     87run_make_test('
     88bar = Goodbye
     89foo::=$(bar)
     90bar = ${ugh}
     91ugh = Hello
     92all: ; @echo $(foo)
     93',
     94              '', "Goodbye\n");
     95
    76961;
  • trunk/src/kmk/tests/scripts/variables/private

    r2591 r3140  
    7676               '', "b=a\na=a\n");
    7777
     78# 9: make sure private suppresses inheritance
     79run_make_test(q!
     80DEFS = FOO
     81all: bar1
     82bar1: private DEFS += 1
     83bar3: private DEFS += 3
     84bar1: bar2
     85bar2: bar3
     86bar1 bar2 bar3: ; @echo '$@: $(DEFS)'
     87!,
     88              '', "bar3: FOO 3\nbar2: FOO\nbar1: FOO 1\n");
     89
     90# 10: Test append with pattern-specific variables and private
     91
     92run_make_test(q!
     93IA = global
     94PA = global
     95PS = global
     96S = global
     97PS = global
     98SV = global
     99b%: IA += b%
     100b%: private PA += b%
     101b%: private PS = b%
     102bar: all
     103bar: IA += bar
     104bar: private PA += bar
     105bar: private PS = bar
     106a%: IA += a%
     107a%: private PA += a%
     108a%: private PS = a%
     109all: IA += all
     110all: private PA += all
     111all: private PS = all
     112
     113bar all: ; @echo '$@: IA=$(IA)'; echo '$@: PA=$(PA)'; echo '$@: PS=$(PS)'
     114!,
     115              '', "all: IA=global b% bar a% all
     116all: PA=global a% all
     117all: PS=all
     118bar: IA=global b% bar
     119bar: PA=global b% bar
     120bar: PS=bar\n");
     121
    781221;
  • trunk/src/kmk/tests/scripts/variables/special

    r2000 r3140  
    1515BAR := bar
    1616
    17 all:
    18         @echo X1 = $(X1)
    19         @echo X2 = $(X2)
    20         @echo LAST = $(sort $(filter FOO BAR,$(.VARIABLES)))
     17all: ; @echo X1 = $(X1); echo X2 = $(X2); echo LAST = $(sort $(filter FOO BAR,$(.VARIABLES)))
    2118',
    2219               '', "X1 =\nX2 = FOO\nLAST = BAR FOO\n");
    2320
     21# SV 45728: Test that undefining a variable is reflected properly
    2422
     23&run_make_test('
     24FOO := foo
     25BAR := bar
     26$(info one: $(sort $(filter FOO BAR BAZ,$(.VARIABLES))))
     27undefine BAR
     28BAZ := baz
     29$(info two: $(sort $(filter FOO BAR BAZ,$(.VARIABLES))))
     30all:;@:
     31',
     32               '', "one: BAR FOO\ntwo: BAZ FOO\n");
    2533
    2634# $makefile2 = &get_tmpfile;
     
    3240
    3341# all: foo
    34 #       @echo X1 = $(X1)
    35 #       @echo X2 = $(X2)
    36 #       @echo LAST = $(sort $(.TARGETS))
     42#       @echo X1 = $(X1)
     43#       @echo X2 = $(X2)
     44#       @echo LAST = $(sort $(.TARGETS))
    3745
    3846# X2 := $(sort $(.TARGETS))
     
    5563&run_make_test('
    5664define foo
    57 : foo-one \
     65: foo-one\
    5866foo-two
    5967: foo-three
     
    116124: foo-four');
    117125
     126# Test that the "did you mean TAB" message is printed properly
     127
     128run_make_test(q!
     129$x.
     130!,
     131              '', '#MAKEFILE#:2: *** missing separator.  Stop.', 512);
     132
     133run_make_test(q!
     134foo:
     135        bar
     136!,
     137              '', '#MAKEFILE#:3: *** missing separator (did you mean TAB instead of 8 spaces?).  Stop.', 512);
     138
     139run_make_test(q!
     140.RECIPEPREFIX = :
     141foo:
     142        bar
     143!,
     144              '', '#MAKEFILE#:4: *** missing separator.  Stop.', 512);
     145
    1181461;
     147
     148### Local Variables:
     149### eval: (setq whitespace-action (delq 'auto-cleanup whitespace-action))
     150### End:
  • trunk/src/kmk/tests/test_driver.pl

    r2591 r3140  
    66# Modified 92-02-11 through 92-02-22 by Chris Arthur to further generalize.
    77#
    8 # Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
    9 # 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
    10 # Foundation, Inc.
     8# Copyright (C) 1991-2016 Free Software Foundation, Inc.
    119# This file is part of GNU Make.
    1210#
     
    3129# variables and then calls &toplevel, which does all the real work.
    3230
    33 # $Id: test_driver.pl,v 1.30 2010/07/28 05:39:50 psmith Exp $
     31# $Id$
    3432
    3533
     
    5149$test_passed = 1;
    5250
    53 
    5451# Timeout in seconds.  If the test takes longer than this we'll fail it.
    5552$test_timeout = 5;
     53$test_timeout = 10 if $^O eq 'VMS';
    5654
    5755# Path to Perl
     
    6563%extraENV = ();
    6664
     65sub vms_get_process_logicals {
     66  # Sorry for the long note here, but to keep this test running on
     67  # VMS, it is needed to be understood.
     68  #
     69  # Perl on VMS by default maps the %ENV array to the system wide logical
     70  # name table.
     71  #
     72  # This is a very large dynamically changing table.
     73  # On Linux, this would be the equivalent of a table that contained
     74  # every mount point, temporary pipe, and symbolic link on every
     75  # file system.  You normally do not have permission to clear or replace it,
     76  # and if you did, the results would be catastrophic.
     77  #
     78  # On VMS, added/changed %ENV items show up in the process logical
     79  # name table.  So to track changes, a copy of it needs to be captured.
     80
     81  my $raw_output = `show log/process/access_mode=supervisor`;
     82  my @raw_output_lines = split('\n',$raw_output);
     83  my %log_hash;
     84  foreach my $line (@raw_output_lines) {
     85    if ($line =~ /^\s+"([A-Za-z\$_]+)"\s+=\s+"(.+)"$/) {
     86      $log_hash{$1} = $2;
     87    }
     88  }
     89  return \%log_hash
     90}
     91
    6792# %origENV is the caller's original environment
    68 %origENV = %ENV;
     93if ($^O ne 'VMS') {
     94  %origENV = %ENV;
     95} else {
     96  my $proc_env = vms_get_process_logicals;
     97  %origENV = %{$proc_env};
     98}
    6999
    70100sub resetENV
     
    73103  # through Perl 5.004.  It was fixed in Perl 5.004_01, but we don't
    74104  # want to require that here, so just delete each one individually.
    75   foreach $v (keys %ENV) {
    76     delete $ENV{$v};
    77   }
    78 
    79   %ENV = %makeENV;
     105
     106  if ($^O ne 'VMS') {
     107    foreach $v (keys %ENV) {
     108      delete $ENV{$v};
     109    }
     110
     111    %ENV = %makeENV;
     112  } else {
     113    my $proc_env = vms_get_process_logicals();
     114    my %delta = %{$proc_env};
     115    foreach my $v (keys %delta) {
     116      if (exists $origENV{$v}) {
     117        if ($origENV{$v} ne $delta{$v}) {
     118          $ENV{$v} = $origENV{$v};
     119        }
     120      } else {
     121        delete $ENV{$v};
     122      }
     123    }
     124  }
     125
    80126  foreach $v (keys %extraENV) {
    81127    $ENV{$v} = $extraENV{$v};
     
    90136  foreach (# UNIX-specific things
    91137           'TZ', 'TMPDIR', 'HOME', 'USER', 'LOGNAME', 'PATH',
     138           'LD_LIBRARY_PATH',
    92139           # Purify things
    93140           'PURIFYOPTIONS',
     
    107154  # Replace the environment with the new one
    108155  #
    109   %origENV = %ENV;
     156  %origENV = %ENV unless $^O eq 'VMS';
    110157
    111158  resetENV();
     
    135182  &parse_command_line (@ARGV);
    136183
    137   print "OS name = `$osname'\n" if $debug;
     184  print "OS name = '$osname'\n" if $debug;
    138185
    139186  $workpath = "$cwdslash$workdir";
     
    143190
    144191  &print_banner;
     192
     193  if ($osname eq 'VMS' && $cwdslash eq "")
     194  {
     195    # Porting this script to VMS revealed a small bug in opendir() not
     196    # handling search lists correctly when the directory only exists in
     197    # one of the logical_devices.  Need to find the first directory in
     198    # the search list, as that is where things will be written to.
     199    my @dirs = split("/", $pwd);
     200
     201    my $logical_device = $ENV{$dirs[1]};
     202    if ($logical_device =~ /([A-Za-z0-9_]+):(:?.+:)+/)
     203    {
     204        # A search list was found.  Grab the first logical device
     205        # and use it instead of the search list.
     206        $dirs[1]=$1;
     207        my $lcl_pwd = join('/', @dirs);
     208        $workpath = $lcl_pwd . '/' . $workdir
     209    }
     210  }
    145211
    146212  if (-d $workpath)
     
    170236        push (@rmdirs, $dir);
    171237        -d "$workpath/$dir"
    172            || mkdir ("$workpath/$dir", 0777)
     238           || mkdir ("$workpath/$dir", 0777)
    173239           || &error ("Couldn't mkdir $workpath/$dir: $!\n");
    174240      }
     
    179245    print "Finding tests...\n";
    180246    opendir (SCRIPTDIR, $scriptpath)
    181         || &error ("Couldn't opendir $scriptpath: $!\n");
     247        || &error ("Couldn't opendir $scriptpath: $!\n");
    182248    @dirs = grep (!/^(\..*|CVS|RCS)$/, readdir (SCRIPTDIR) );
    183249    closedir (SCRIPTDIR);
     
    186252      next if ($dir =~ /^(\..*|CVS|RCS)$/ || ! -d "$scriptpath/$dir");
    187253      push (@rmdirs, $dir);
     254      # VMS can have overlayed file systems, so directories may repeat.
     255      next if -d "$workpath/$dir";
    188256      mkdir ("$workpath/$dir", 0777)
    189            || &error ("Couldn't mkdir $workpath/$dir: $!\n");
     257          || &error ("Couldn't mkdir $workpath/$dir: $!\n");
    190258      opendir (SCRIPTDIR, "$scriptpath/$dir")
    191           || &error ("Couldn't opendir $scriptpath/$dir: $!\n");
     259          || &error ("Couldn't opendir $scriptpath/$dir: $!\n");
    192260      @files = grep (!/^(\..*|CVS|RCS|.*~)$/, readdir (SCRIPTDIR) );
    193261      closedir (SCRIPTDIR);
     
    195263      {
    196264        -d $test and next;
    197         push (@TESTS, "$dir/$test");
     265        push (@TESTS, "$dir/$test");
    198266      }
    199267    }
     
    207275  print "\n";
    208276
    209   &run_each_test;
     277  run_all_tests();
    210278
    211279  foreach $dir (@rmdirs)
     
    225293    print " in $categories_failed Categor";
    226294    print ($categories_failed == 1 ? "y" : "ies");
    227     print " Failed (See .$diffext files in $workdir dir for details) :-(\n\n";
     295    print " Failed (See .$diffext* files in $workdir dir for details) :-(\n\n";
    228296    return 0;
    229297  }
     
    244312  $osname = defined($^O) ? $^O : '';
    245313
     314  if ($osname eq 'VMS')
     315  {
     316    $vos = 0;
     317    $pathsep = "/";
     318    return;
     319  }
     320
    246321  # Find a path to Perl
    247322
     
    280355    if ($osname =~ /not found/i)
    281356    {
    282         $osname = "(something posixy with no uname)";
     357        $osname = "(something posixy with no uname)";
    283358    }
    284359    elsif ($@ ne "" || $?)
     
    287362        if ($@ ne "" || $?)
    288363        {
    289             $osname = "(something posixy)";
    290         }
     364            $osname = "(something posixy)";
     365        }
    291366    }
    292367    $vos = 0;
     
    441516}
    442517
    443 sub run_each_test
    444 {
    445   $categories_run = 0;
    446 
    447   foreach $testname (sort @TESTS)
    448   {
    449     ++$categories_run;
    450     $suite_passed = 1;       # reset by test on failure
    451     $num_of_logfiles = 0;
    452     $num_of_tmpfiles = 0;
    453     $description = "";
    454     $details = "";
    455     $old_makefile = undef;
    456     $testname =~ s/^$scriptpath$pathsep//;
    457     $perl_testname = "$scriptpath$pathsep$testname";
    458     $testname =~ s/(\.pl|\.perl)$//;
    459     $testpath = "$workpath$pathsep$testname";
    460     # Leave enough space in the extensions to append a number, even
    461     # though it needs to fit into 8+3 limits.
    462     if ($short_filenames) {
    463       $logext = 'l';
    464       $diffext = 'd';
    465       $baseext = 'b';
    466       $runext = 'r';
    467       $extext = '';
    468     } else {
    469       $logext = 'log';
    470       $diffext = 'diff';
    471       $baseext = 'base';
    472       $runext = 'run';
    473       $extext = '.';
    474     }
    475     $log_filename = "$testpath.$logext";
    476     $diff_filename = "$testpath.$diffext";
    477     $base_filename = "$testpath.$baseext";
    478     $run_filename = "$testpath.$runext";
    479     $tmp_filename = "$testpath.$tmpfilesuffix";
    480 
    481     &setup_for_test;          # suite-defined
    482 
    483     $output = "........................................................ ";
    484 
    485     substr($output,0,length($testname)) = "$testname ";
    486 
    487     print $output;
    488 
    489     # Run the actual test!
    490     $tests_run = 0;
    491     $tests_passed = 0;
    492 
    493     $code = do $perl_testname;
    494 
    495     $total_tests_run += $tests_run;
    496     $total_tests_passed += $tests_passed;
    497 
    498     # How did it go?
    499     if (!defined($code))
    500     {
    501       $suite_passed = 0;
    502       if (length ($@)) {
    503         warn "\n*** Test died ($testname): $@\n";
    504       } else {
    505         warn "\n*** Couldn't run $perl_testname\n";
    506       }
    507     }
    508     elsif ($code == -1) {
    509       $suite_passed = 0;
    510     }
    511     elsif ($code != 1 && $code != -1) {
    512       $suite_passed = 0;
    513       warn "\n*** Test returned $code\n";
    514     }
    515 
    516     if ($suite_passed) {
    517       ++$categories_passed;
    518       $status = "ok     ($tests_passed passed)";
    519       for ($i = $num_of_tmpfiles; $i; $i--)
    520       {
    521         &rmfiles ($tmp_filename . &num_suffix ($i) );
    522       }
    523 
    524       for ($i = $num_of_logfiles ? $num_of_logfiles : 1; $i; $i--)
    525       {
    526         &rmfiles ($log_filename . &num_suffix ($i) );
    527         &rmfiles ($base_filename . &num_suffix ($i) );
    528       }
    529     }
    530     elsif (!defined $code || $code > 0) {
    531       $status = "FAILED ($tests_passed/$tests_run passed)";
    532     }
    533     elsif ($code < 0) {
    534       $status = "N/A";
    535       --$categories_run;
    536     }
    537 
    538     # If the verbose option has been specified, then a short description
    539     # of each test is printed before displaying the results of each test
    540     # describing WHAT is being tested.
    541 
    542     if ($verbose)
    543     {
    544       if ($detail)
    545       {
    546         print "\nWHAT IS BEING TESTED\n";
    547         print "--------------------";
    548       }
    549       print "\n\n$description\n\n";
    550     }
    551 
    552     # If the detail option has been specified, then the details of HOW
    553     # the test is testing what it says it is testing in the verbose output
    554     # will be displayed here before the results of the test are displayed.
    555 
    556     if ($detail)
    557     {
    558       print "\nHOW IT IS TESTED\n";
    559       print "----------------";
    560       print "\n\n$details\n\n";
    561     }
    562 
    563     print "$status\n";
    564   }
     518sub run_all_tests
     519{
     520    $categories_run = 0;
     521
     522    $lasttest = '';
     523    foreach $testname (sort @TESTS) {
     524        # Skip duplicates on VMS caused by logical name search lists.
     525        next if $testname eq $lasttest;
     526        $lasttest = $testname;
     527        $suite_passed = 1;       # reset by test on failure
     528        $num_of_logfiles = 0;
     529        $num_of_tmpfiles = 0;
     530        $description = "";
     531        $details = "";
     532        $old_makefile = undef;
     533        $testname =~ s/^$scriptpath$pathsep//;
     534        $perl_testname = "$scriptpath$pathsep$testname";
     535        $testname =~ s/(\.pl|\.perl)$//;
     536        $testpath = "$workpath$pathsep$testname";
     537        # Leave enough space in the extensions to append a number, even
     538        # though it needs to fit into 8+3 limits.
     539        if ($short_filenames) {
     540            $logext = 'l';
     541            $diffext = 'd';
     542            $baseext = 'b';
     543            $runext = 'r';
     544            $extext = '';
     545        } else {
     546            $logext = 'log';
     547            $diffext = 'diff';
     548            $baseext = 'base';
     549            $runext = 'run';
     550            $extext = '.';
     551        }
     552        $extext = '_' if $^O eq 'VMS';
     553        $log_filename = "$testpath.$logext";
     554        $diff_filename = "$testpath.$diffext";
     555        $base_filename = "$testpath.$baseext";
     556        $run_filename = "$testpath.$runext";
     557        $tmp_filename = "$testpath.$tmpfilesuffix";
     558
     559        setup_for_test();
     560
     561        $output = "........................................................ ";
     562
     563        substr($output,0,length($testname)) = "$testname ";
     564
     565        print $output;
     566
     567        $tests_run = 0;
     568        $tests_passed = 0;
     569
     570        # Run the test!
     571        $code = do $perl_testname;
     572
     573        ++$categories_run;
     574        $total_tests_run += $tests_run;
     575        $total_tests_passed += $tests_passed;
     576
     577        # How did it go?
     578        if (!defined($code)) {
     579            # Failed to parse or called die
     580            if (length ($@)) {
     581                warn "\n*** Test died ($testname): $@\n";
     582            } else {
     583                warn "\n*** Couldn't parse $perl_testname\n";
     584            }
     585            $status = "FAILED ($tests_passed/$tests_run passed)";
     586        }
     587
     588        elsif ($code == -1) {
     589            # Skipped... not supported
     590            $status = "N/A";
     591            --$categories_run;
     592        }
     593
     594        elsif ($code != 1) {
     595            # Bad result... this shouldn't really happen.  Usually means that
     596            # the suite forgot to end with "1;".
     597            warn "\n*** Test returned $code\n";
     598            $status = "FAILED ($tests_passed/$tests_run passed)";
     599        }
     600
     601        elsif ($tests_run == 0) {
     602            # Nothing was done!!
     603            $status = "FAILED (no tests found!)";
     604        }
     605
     606        elsif ($tests_run > $tests_passed) {
     607            # Lose!
     608            $status = "FAILED ($tests_passed/$tests_run passed)";
     609        }
     610
     611        else {
     612            # Win!
     613            ++$categories_passed;
     614            $status = "ok     ($tests_passed passed)";
     615
     616            # Clean up
     617            for ($i = $num_of_tmpfiles; $i; $i--) {
     618                rmfiles($tmp_filename . num_suffix($i));
     619            }
     620            for ($i = $num_of_logfiles ? $num_of_logfiles : 1; $i; $i--) {
     621                rmfiles($log_filename . num_suffix($i));
     622                rmfiles($base_filename . num_suffix($i));
     623            }
     624        }
     625
     626        # If the verbose option has been specified, then a short description
     627        # of each test is printed before displaying the results of each test
     628        # describing WHAT is being tested.
     629
     630        if ($verbose) {
     631            if ($detail) {
     632                print "\nWHAT IS BEING TESTED\n";
     633                print "--------------------";
     634            }
     635            print "\n\n$description\n\n";
     636        }
     637
     638        # If the detail option has been specified, then the details of HOW
     639        # the test is testing what it says it is testing in the verbose output
     640        # will be displayed here before the results of the test are displayed.
     641
     642        if ($detail) {
     643            print "\nHOW IT IS TESTED\n";
     644            print "----------------";
     645            print "\n\n$details\n\n";
     646        }
     647
     648        print "$status\n";
     649    }
    565650}
    566651
     
    679764  local($slurp, $answer_matched) = ('', 0);
    680765
    681   print "Comparing Output ........ " if $debug;
    682 
    683   $slurp = &read_file_into_string ($logfile);
    684 
    685   # For make, get rid of any time skew error before comparing--too bad this
    686   # has to go into the "generic" driver code :-/
    687   $slurp =~ s/^.*modification time .*in the future.*\n//gm;
    688   $slurp =~ s/^.*Clock skew detected.*\n//gm;
    689 
    690766  ++$tests_run;
    691767
    692   if ($slurp eq $answer) {
    693     $answer_matched = 1;
     768  if (! defined $answer) {
     769      print "Ignoring output ........ " if $debug;
     770      $answer_matched = 1;
    694771  } else {
    695     # See if it is a slash or CRLF problem
    696     local ($answer_mod, $slurp_mod) = ($answer, $slurp);
    697 
    698     $answer_mod =~ tr,\\,/,;
    699     $answer_mod =~ s,\r\n,\n,gs;
    700 
    701     $slurp_mod =~ tr,\\,/,;
    702     $slurp_mod =~ s,\r\n,\n,gs;
    703 
    704     $answer_matched = ($slurp_mod eq $answer_mod);
    705 
    706     # If it still doesn't match, see if the answer might be a regex.
    707     if (!$answer_matched && $answer =~ m,^/(.+)/$,) {
    708       $answer_matched = ($slurp =~ /$1/);
    709       if (!$answer_matched && $answer_mod =~ m,^/(.+)/$,) {
    710           $answer_matched = ($slurp_mod =~ /$1/);
     772      print "Comparing Output ........ " if $debug;
     773
     774      $slurp = &read_file_into_string ($logfile);
     775
     776      # For make, get rid of any time skew error before comparing--too bad this
     777      # has to go into the "generic" driver code :-/
     778      $slurp =~ s/^.*modification time .*in the future.*\n//gm;
     779      $slurp =~ s/^.*Clock skew detected.*\n//gm;
     780
     781      if ($slurp eq $answer) {
     782          $answer_matched = 1;
     783      } else {
     784          # See if it is a slash or CRLF problem
     785          local ($answer_mod, $slurp_mod) = ($answer, $slurp);
     786
     787          $answer_mod =~ tr,\\,/,;
     788          $answer_mod =~ s,\r\n,\n,gs;
     789
     790          $slurp_mod =~ tr,\\,/,;
     791          $slurp_mod =~ s,\r\n,\n,gs;
     792
     793          $answer_matched = ($slurp_mod eq $answer_mod);
     794          if ($^O eq 'VMS') {
     795
     796            # VMS has extra blank lines in output sometimes.
     797            # Ticket #41760
     798            if (!$answer_matched) {
     799              $slurp_mod =~ s/\n\n+/\n/gm;
     800              $slurp_mod =~ s/\A\n+//g;
     801              $answer_matched = ($slurp_mod eq $answer_mod);
     802            }
     803
     804            # VMS adding a "Waiting for unfinished jobs..."
     805            # Remove it for now to see what else is going on.
     806            if (!$answer_matched) {
     807              $slurp_mod =~ s/^.+\*\*\* Waiting for unfinished jobs.+$//m;
     808              $slurp_mod =~ s/\n\n/\n/gm;
     809              $slurp_mod =~ s/^\n+//gm;
     810              $answer_matched = ($slurp_mod eq $answer_mod);
     811            }
     812
     813            # VMS wants target device to exist or generates an error,
     814            # Some test tagets look like VMS devices and trip this.
     815            if (!$answer_matched) {
     816              $slurp_mod =~ s/^.+\: no such device or address.*$//gim;
     817              $slurp_mod =~ s/\n\n/\n/gm;
     818              $slurp_mod =~ s/^\n+//gm;
     819              $answer_matched = ($slurp_mod eq $answer_mod);
     820            }
     821
     822            # VMS error message has a different case
     823            if (!$answer_matched) {
     824              $slurp_mod =~ s/no such file /No such file /gm;
     825              $answer_matched = ($slurp_mod eq $answer_mod);
     826            }
     827
     828            # VMS is putting comas instead of spaces in output
     829            if (!$answer_matched) {
     830              $slurp_mod =~ s/,/ /gm;
     831              $answer_matched = ($slurp_mod eq $answer_mod);
     832            }
     833
     834            # VMS Is sometimes adding extra leading spaces to output?
     835            if (!$answer_matched) {
     836               my $slurp_mod = $slurp_mod;
     837               $slurp_mod =~ s/^ +//gm;
     838               $answer_matched = ($slurp_mod eq $answer_mod);
     839            }
     840
     841            # VMS port not handling POSIX encoded child status
     842            # Translate error case it for now.
     843            if (!$answer_matched) {
     844              $slurp_mod =~ s/0x1035a00a/1/gim;
     845              $answer_matched = 1 if $slurp_mod =~ /\Q$answer_mod\E/i;
     846
     847            }
     848            if (!$answer_matched) {
     849              $slurp_mod =~ s/0x1035a012/2/gim;
     850              $answer_matched = ($slurp_mod eq $answer_mod);
     851            }
     852
     853            # Tests are using a UNIX null command, temp hack
     854            # until this can be handled by the VMS port.
     855            # ticket # 41761
     856            if (!$answer_matched) {
     857              $slurp_mod =~ s/^.+DCL-W-NOCOMD.*$//gim;
     858              $slurp_mod =~ s/\n\n+/\n/gm;
     859              $slurp_mod =~ s/^\n+//gm;
     860              $answer_matched = ($slurp_mod eq $answer_mod);
     861            }
     862            # Tests are using exit 0;
     863            # this generates a warning that should stop the make, but does not
     864            if (!$answer_matched) {
     865              $slurp_mod =~ s/^.+NONAME-W-NOMSG.*$//gim;
     866              $slurp_mod =~ s/\n\n+/\n/gm;
     867              $slurp_mod =~ s/^\n+//gm;
     868              $answer_matched = ($slurp_mod eq $answer_mod);
     869            }
     870
     871            # VMS is sometimes adding single quotes to output?
     872            if (!$answer_matched) {
     873              my $noq_slurp_mod = $slurp_mod;
     874              $noq_slurp_mod =~ s/\'//gm;
     875              $answer_matched = ($noq_slurp_mod eq $answer_mod);
     876
     877              # And missing an extra space in output
     878              if (!$answer_matched) {
     879                $noq_answer_mod = $answer_mod;
     880                $noq_answer_mod =~ s/\h\h+/ /gm;
     881                $answer_matched = ($noq_slurp_mod eq $noq_answer_mod);
     882              }
     883
     884              # VMS adding ; to end of some lines.
     885              if (!$answer_matched) {
     886                $noq_slurp_mod =~ s/;\n/\n/gm;
     887                $answer_matched = ($noq_slurp_mod eq $noq_answer_mod);
     888              }
     889
     890              # VMS adding trailing space to end of some quoted lines.
     891              if (!$answer_matched) {
     892                $noq_slurp_mod =~ s/\h+\n/\n/gm;
     893                $answer_matched = ($noq_slurp_mod eq $noq_answer_mod);
     894              }
     895
     896              # And VMS missing leading blank line
     897              if (!$answer_matched) {
     898                $noq_answer_mod =~ s/\A\n//g;
     899                $answer_matched = ($noq_slurp_mod eq $noq_answer_mod);
     900              }
     901
     902              # Unix double quotes showing up as single quotes on VMS.
     903              if (!$answer_matched) {
     904                $noq_answer_mod =~ s/\"//g;
     905                $answer_matched = ($noq_slurp_mod eq $noq_answer_mod);
     906              }
     907            }
     908          }
     909
     910          # If it still doesn't match, see if the answer might be a regex.
     911          if (!$answer_matched && $answer =~ m,^/(.+)/$,) {
     912              $answer_matched = ($slurp =~ /$1/);
     913              if (!$answer_matched && $answer_mod =~ m,^/(.+)/$,) {
     914                  $answer_matched = ($slurp_mod =~ /$1/);
     915              }
     916          }
    711917      }
    712     }
    713918  }
    714919
     
    732937    local($command) = "diff -c " . &get_basefile . " " . $logfile;
    733938    &run_command_with_output(&get_difffile,$command);
    734   } else {
    735       &rmfiles ();
    736   }
    737 
    738   $suite_passed = 0;
     939  }
     940
    739941  return 0;
    740942}
     
    756958}
    757959
     960my @OUTSTACK = ();
     961my @ERRSTACK = ();
     962
    758963sub attach_default_output
    759964{
     
    768973  }
    769974
    770   open ("SAVEDOS" . $default_output_stack_level . "out", ">&STDOUT")
    771         || &error ("ado: $! duping STDOUT\n", 1);
    772   open ("SAVEDOS" . $default_output_stack_level . "err", ">&STDERR")
    773         || &error ("ado: $! duping STDERR\n", 1);
    774 
    775   open (STDOUT, "> " . $filename)
    776         || &error ("ado: $filename: $!\n", 1);
    777   open (STDERR, ">&STDOUT")
    778         || &error ("ado: $filename: $!\n", 1);
    779 
    780   $default_output_stack_level++;
     975  my $dup = undef;
     976  open($dup, '>&', STDOUT) or error("ado: $! duping STDOUT\n", 1);
     977  push @OUTSTACK, $dup;
     978
     979  $dup = undef;
     980  open($dup, '>&', STDERR) or error("ado: $! duping STDERR\n", 1);
     981  push @ERRSTACK, $dup;
     982
     983  open(STDOUT, '>', $filename) or error("ado: $filename: $!\n", 1);
     984  open(STDERR, ">&STDOUT") or error("ado: $filename: $!\n", 1);
    781985}
    782986
     
    795999  }
    7961000
    797   if (--$default_output_stack_level < 0)
    798   {
    799     &error ("default output stack has flown under!\n", 1);
    800   }
    801 
    802   close (STDOUT);
    803   close (STDERR);
    804 
    805   open (STDOUT, ">&SAVEDOS" . $default_output_stack_level . "out")
    806         || &error ("ddo: $! duping STDOUT\n", 1);
    807   open (STDERR, ">&SAVEDOS" . $default_output_stack_level . "err")
    808         || &error ("ddo: $! duping STDERR\n", 1);
    809 
    810   close ("SAVEDOS" . $default_output_stack_level . "out")
    811         || &error ("ddo: $! closing SCSDOSout\n", 1);
    812   close ("SAVEDOS" . $default_output_stack_level . "err")
    813          || &error ("ddo: $! closing SAVEDOSerr\n", 1);
     1001  @OUTSTACK or error("default output stack has flown under!\n", 1);
     1002
     1003  close(STDOUT);
     1004  close(STDERR) unless $^O eq 'VMS';
     1005
     1006
     1007  open (STDOUT, '>&', pop @OUTSTACK) or error("ddo: $! duping STDOUT\n", 1);
     1008  open (STDERR, '>&', pop @ERRSTACK) or error("ddo: $! duping STDERR\n", 1);
    8141009}
    8151010
     
    8251020
    8261021  eval {
    827       local $SIG{ALRM} = sub { die "timeout\n"; };
    828       alarm $test_timeout;
    829       $code = system(@_);
     1022      if ($^O eq 'VMS') {
     1023          local $SIG{ALRM} = sub {
     1024              my $e = $ERRSTACK[0];
     1025              print $e "\nTest timed out after $test_timeout seconds\n";
     1026              die "timeout\n"; };
     1027#          alarm $test_timeout;
     1028          system(@_);
     1029          my $severity = ${^CHILD_ERROR_NATIVE} & 7;
     1030          $code = 0;
     1031          if (($severity & 1) == 0) {
     1032              $code = 512;
     1033          }
     1034
     1035          # Get the vms status.
     1036          my $vms_code = ${^CHILD_ERROR_NATIVE};
     1037
     1038          # Remove the print status bit
     1039          $vms_code &= ~0x10000000;
     1040
     1041          # Posix code translation.
     1042          if (($vms_code & 0xFFFFF000) == 0x35a000) {
     1043              $code = (($vms_code & 0xFFF) >> 3) * 256;
     1044          }
     1045      } else {
     1046          my $pid = fork();
     1047          if (! $pid) {
     1048              exec(@_) or die "Cannot execute $_[0]\n";
     1049          }
     1050          local $SIG{ALRM} = sub { my $e = $ERRSTACK[0]; print $e "\nTest timed out after $test_timeout seconds\n"; die "timeout\n"; };
     1051          alarm $test_timeout;
     1052          waitpid($pid, 0) > 0 or die "No such pid: $pid\n";
     1053          $code = $?;
     1054      }
    8301055      alarm 0;
    8311056  };
    8321057  if ($@) {
    8331058      # The eval failed.  If it wasn't SIGALRM then die.
    834       $@ eq "timeout\n" or die;
     1059      $@ eq "timeout\n" or die "Command failed: $@";
    8351060
    8361061      # Timed out.  Resend the alarm to our process group to kill the children.
     
    8511076  my $code = _run_command(@_);
    8521077  print "run_command returned $code.\n" if $debug;
    853 
     1078  print "vms status = ${^CHILD_ERROR_NATIVE}\n" if $debug and $^O eq 'VMS';
    8541079  return $code;
    8551080}
     
    8661091  print "\nrun_command_with_output($filename,$runname): @_\n" if $debug;
    8671092  &attach_default_output ($filename);
    868   my $code = _run_command(@_);
     1093  my $code = eval { _run_command(@_) };
     1094  my $err = $@;
    8691095  &detach_default_output;
     1096
     1097  $err and die $err;
     1098
    8701099  print "run_command_with_output returned $code.\n" if $debug;
    871 
     1100  print "vms status = ${^CHILD_ERROR_NATIVE}\n" if $debug and $^O eq 'VMS';
    8721101  return $code;
    8731102}
     
    9291158    else
    9301159    {
    931       unlink $object || return 0;
     1160      if ($^O ne 'VMS')
     1161      {
     1162        unlink $object || return 0;
     1163      }
     1164      else
     1165      {
     1166        # VMS can have multiple versions of a file.
     1167        1 while unlink $object;
     1168      }
    9321169    }
    9331170  }
     
    9671204  foreach $file (@_) {
    9681205    (open(T, ">> $file") && print(T "\n") && close(T))
    969         || &error("Couldn't touch $file: $!\n", 1);
     1206        || &error("Couldn't touch $file: $!\n", 1);
    9701207  }
    9711208}
  • trunk/src/kmk/variable.c

    r3090 r3140  
    11/* Internals of variables for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018
    2119#include <assert.h>
    2220
     21#include "filedef.h"
    2322#include "dep.h"
    24 #include "filedef.h"
    2523#include "job.h"
    2624#include "commands.h"
     
    6563#endif
    6664
     65/* Incremented every time we add or remove a global variable.  */
     66static unsigned long variable_changenum;
    6767
    6868/* Chain of all pattern-specific variables.  */
     
    135135{
    136136  struct pattern_var *p;
    137   unsigned int targlen = strlen(target);
     137  unsigned int targlen = strlen (target);
    138138
    139139  for (p = start ? start->next : pattern_vars; p != 0; p = p->next)
     
    203203#endif /* !CONFIG_WITH_STRCACHE2 */
    204204
    205 #ifndef VARIABLE_BUCKETS
     205#ifndef VARIABLE_BUCKETS
    206206# ifdef KMK /* Move to Makefile.kmk? (insanely high, but wtf, it gets the collitions down) */
    207 #  define VARIABLE_BUCKETS              65535
     207#  define VARIABLE_BUCKETS              65535
    208208# else  /*!KMK*/
    209 #define VARIABLE_BUCKETS                523
     209#define VARIABLE_BUCKETS                523
    210210# endif /*!KMK*/
    211211#endif
    212 #ifndef PERFILE_VARIABLE_BUCKETS
     212#ifndef PERFILE_VARIABLE_BUCKETS
    213213# ifdef KMK /* Move to Makefile.kmk? */
    214 #  define PERFILE_VARIABLE_BUCKETS      127
     214#  define PERFILE_VARIABLE_BUCKETS      127
    215215# else
    216 #define PERFILE_VARIABLE_BUCKETS        23
     216#define PERFILE_VARIABLE_BUCKETS        23
    217217# endif
    218218#endif
    219 #ifndef SMALL_SCOPE_VARIABLE_BUCKETS
     219#ifndef SMALL_SCOPE_VARIABLE_BUCKETS
    220220# ifdef KMK /* Move to Makefile.kmk? */
    221221#  define SMALL_SCOPE_VARIABLE_BUCKETS  63
    222222# else
    223 #define SMALL_SCOPE_VARIABLE_BUCKETS    13
     223#define SMALL_SCOPE_VARIABLE_BUCKETS    13
    224224# endif
    225225#endif
     
    247247#ifndef CONFIG_WITH_STRCACHE2
    248248  hash_init (&global_variable_set.table, VARIABLE_BUCKETS,
    249              variable_hash_1, variable_hash_2, variable_hash_cmp);
     249             variable_hash_1, variable_hash_2, variable_hash_cmp);
    250250#else  /* CONFIG_WITH_STRCACHE2 */
    251251  strcache2_init (&variable_strcache, "variable", 262144, 0, 0, 0);
     
    268268                        int duplicate_value, enum variable_origin origin,
    269269                        int recursive, struct variable_set *set,
    270                         const struct floc *flocp)
     270                        const floc *flocp)
    271271#else
    272272struct variable *
     
    274274                        const char *value, enum variable_origin origin,
    275275                        int recursive, struct variable_set *set,
    276                         const struct floc *flocp)
     276                        const floc *flocp)
    277277#endif
    278278{
     
    316316  var_key.length = length;
    317317  var_slot = (struct variable **) hash_find_slot (&set->table, &var_key);
     318  v = *var_slot;
     319
     320#ifdef VMS
     321  /* VMS does not populate envp[] with DCL symbols and logical names which
     322     historically are mapped to environent variables.
     323     If the variable is not yet defined, then we need to check if getenv()
     324     can find it.  Do not do this for origin == o_env to avoid infinte
     325     recursion */
     326  if (HASH_VACANT (v) && (origin != o_env))
     327    {
     328      struct variable * vms_variable;
     329      char * vname = alloca (length + 1);
     330      char * vvalue;
     331
     332      strncpy (vname, name, length);
     333      vvalue = getenv(vname);
     334
     335      /* Values starting with '$' are probably foreign commands.
     336         We want to treat them as Shell aliases and not look them up here */
     337      if ((vvalue != NULL) && (vvalue[0] != '$'))
     338        {
     339          vms_variable =  lookup_variable(name, length);
     340          /* Refresh the slot */
     341          var_slot = (struct variable **) hash_find_slot (&set->table,
     342                                                          &var_key);
     343          v = *var_slot;
     344        }
     345    }
     346#endif
    318347
    319348  /* if (env_overrides && origin == o_env)
    320349    origin = o_env_override; - bird moved this up */
    321350
    322   v = *var_slot;
    323351#else  /* CONFIG_WITH_STRCACHE2 */
    324352  name = strcache2_add (&variable_strcache, name, length);
     
    343371#endif
    344372      if (env_overrides && v->origin == o_env)
    345         /* V came from in the environment.  Since it was defined
    346            before the switches were parsed, it wasn't affected by -e.  */
    347         v->origin = o_env_override;
     373        /* V came from in the environment.  Since it was defined
     374           before the switches were parsed, it wasn't affected by -e.  */
     375        v->origin = o_env_override;
    348376
    349377      /* A variable of this name is already defined.
    350         If the old definition is from a stronger source
    351         than this one, don't redefine it.  */
     378        If the old definition is from a stronger source
     379        than this one, don't redefine it.  */
    352380      if ((int) origin >= (int) v->origin)
    353         {
     381        {
    354382#ifdef CONFIG_WITH_VALUE_LENGTH
    355383          if (value_len == ~0U)
     
    390418          v->value_length = value_len;
    391419#else  /* !CONFIG_WITH_VALUE_LENGTH */
    392           if (v->value != 0)
    393             free (v->value);
    394           v->value = xstrdup (value);
     420          free (v->value);
     421          v->value = xstrdup (value);
    395422#endif /* !CONFIG_WITH_VALUE_LENGTH */
    396423          if (flocp != 0)
     
    398425          else
    399426            v->fileinfo.filenm = 0;
    400           v->origin = origin;
    401           v->recursive = recursive;
    402          VARIABLE_CHANGED (v);
    403         }
     427          v->origin = origin;
     428          v->recursive = recursive;
     429          VARIABLE_CHANGED (v);
     430        }
    404431      return v;
    405432    }
     
    419446  v->length = length;
    420447  hash_insert_at (&set->table, v, var_slot);
     448  if (set == &global_variable_set)
     449    ++variable_changenum;
     450
    421451#ifdef CONFIG_WITH_VALUE_LENGTH
    422452  if (value_len == ~0U)
     
    507537
    508538static void
    509 free_variable_name_and_value (const void *item);
     539free_variable_name_and_value (const void *item)
     540{
     541  struct variable *v = (struct variable *) item;
     542#ifndef CONFIG_WITH_STRCACHE2
     543  free (v->name);
     544#endif
     545#ifdef CONFIG_WITH_COMPILER
     546  if (v->evalprog || v->expandprog)
     547    kmk_cc_variable_deleted (v);
     548#endif
     549#ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
     550  if (!v->rdonly_val)
     551#endif
     552    free (v->value);
     553}
     554
     555void
     556free_variable_set (struct variable_set_list *list)
     557{
     558  hash_map (&list->set->table, free_variable_name_and_value);
     559#ifndef CONFIG_WITH_ALLOC_CACHES
     560  hash_free (&list->set->table, 1);
     561  free (list->set);
     562  free (list);
     563#else
     564  hash_free_cached (&list->set->table, 1, &variable_cache);
     565  alloccache_free (&variable_set_cache, list->set);
     566  alloccache_free (&variable_set_list_cache, list);
     567#endif
     568}
    510569
    511570void
     
    547606        {
    548607           if (v->aliased)
    549              error (NULL, _("Cannot undefine the aliased variable '%s'"), v->name);
     608             OS (error, NULL, _("Cannot undefine the aliased variable '%s'"), v->name);
    550609           else
    551              error (NULL, _("Cannot undefine the variable alias '%s'"), v->name);
     610             OS (error, NULL, _("Cannot undefine the variable alias '%s'"), v->name);
    552611          return;
    553612        }
     
    555614
    556615      if (env_overrides && v->origin == o_env)
    557         /* V came from in the environment.  Since it was defined
    558            before the switches were parsed, it wasn't affected by -e.  */
    559         v->origin = o_env_override;
    560 
    561       /* If the definition is from a stronger source than this one, don't
    562          undefine it.  */
     616        /* V came from in the environment.  Since it was defined
     617           before the switches were parsed, it wasn't affected by -e.  */
     618        v->origin = o_env_override;
     619
     620      /* Undefine only if this undefinition is from an equal or stronger
     621         source than the variable definition.  */
    563622      if ((int) origin >= (int) v->origin)
    564         {
     623        {
    565624          hash_delete_at (&set->table, var_slot);
    566625#ifdef CONFIG_WITH_STRCACHE2
     
    569628#endif
    570629          free_variable_name_and_value (v);
    571         }
     630          free (v);
     631          if (set == &global_variable_set)
     632            ++variable_changenum;
     633        }
    572634    }
    573635}
     
    580642define_variable_alias_in_set (const char *name, unsigned int length,
    581643                              struct variable *target, enum variable_origin origin,
    582                               struct variable_set *set, const struct floc *flocp)
     644                              struct variable_set *set, const floc *flocp)
    583645{
    584646  struct variable     *v;
     
    707769lookup_special_var (struct variable *var)
    708770{
    709   static unsigned long last_var_count = 0;
     771  static unsigned long last_changenum = 0;
    710772
    711773
     
    735797  */
    736798
    737   if (streq (var->name, ".VARIABLES")
    738       && global_variable_set.table.ht_fill != last_var_count)
     799  if (variable_changenum != last_changenum && streq (var->name, ".VARIABLES"))
    739800    {
    740801#ifndef CONFIG_WITH_VALUE_LENGTH
     
    783844      VARIABLE_CHANGED (var);
    784845
    785       /* Remember how many variables are in our current count.  Since we never
    786          remove variables from the list, this is a reliable way to know whether
    787          the list is up to date or needs to be recomputed.  */
    788 
    789       last_var_count = global_variable_set.table.ht_fill;
     846      /* Remember the current variable change number.  */
     847      last_changenum = variable_changenum;
    790848    }
    791849
     
    920978/* Lookup a variable whose name is a string starting at NAME
    921979   and with LENGTH chars.  NAME need not be null-terminated.
    922    Returns address of the `struct variable' containing all info
     980   Returns address of the 'struct variable' containing all info
    923981   on the variable, or nil if no such variable is defined.  */
    924982
     
    9801038# endif
    9811039          MAKE_STATS_2 (v->references++);
    982            return v->special ? lookup_special_var (v) : v;
     1040          return v->special ? lookup_special_var (v) : v;
    9831041        }
    9841042
     
    9961054#endif /* KMK - need for speed */
    9971055#ifdef VMS
    998   /* since we don't read envp[] on startup, try to get the
    999      variable via getenv() here. */
     1056  /* VMS does not populate envp[] with DCL symbols and logical names which
     1057     historically are mapped to enviroment varables and returned by getenv() */
    10001058  {
    10011059    char *vname = alloca (length + 1);
     
    11271185/* Lookup a variable whose name is a string starting at NAME
    11281186   and with LENGTH chars in set SET.  NAME need not be null-terminated.
    1129    Returns address of the `struct variable' containing all info
     1187   Returns address of the 'struct variable' containing all info
    11301188   on the variable, or nil if no such variable is defined.  */
    11311189
     
    12041262#ifndef CONFIG_WITH_ALLOC_CACHES
    12051263      l = (struct variable_set_list *)
    1206         xmalloc (sizeof (struct variable_set_list));
     1264        xmalloc (sizeof (struct variable_set_list));
    12071265      l->set = xmalloc (sizeof (struct variable_set));
    12081266#else  /* CONFIG_WITH_ALLOC_CACHES */
     
    13311389#ifndef CONFIG_WITH_STRCACHE2
    13321390  hash_init (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
    1333              variable_hash_1, variable_hash_2, variable_hash_cmp);
     1391             variable_hash_1, variable_hash_2, variable_hash_cmp);
    13341392#else  /* CONFIG_WITH_STRCACHE2 */
    13351393  hash_init_strcached (&set->table, SMALL_SCOPE_VARIABLE_BUCKETS,
     
    13511409}
    13521410
    1353 static void
    1354 free_variable_name_and_value (const void *item)
    1355 {
    1356   struct variable *v = (struct variable *) item;
    1357 #ifndef CONFIG_WITH_STRCACHE2
    1358   free (v->name);
    1359 #endif
    1360 #ifdef CONFIG_WITH_COMPILER
    1361   if (v->evalprog || v->expandprog)
    1362     kmk_cc_variable_deleted (v);
    1363 #endif
    1364 #ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
    1365   if (!v->rdonly_val)
    1366 #endif
    1367     free (v->value);
    1368 }
    1369 
    1370 void
    1371 free_variable_set (struct variable_set_list *list)
    1372 {
    1373   hash_map (&list->set->table, free_variable_name_and_value);
    1374 #ifndef CONFIG_WITH_ALLOC_CACHES
    1375   hash_free (&list->set->table, 1);
    1376   free (list->set);
    1377   free (list);
    1378 #else
    1379   hash_free_cached (&list->set->table, 1, &variable_cache);
    1380   alloccache_free (&variable_set_cache, list->set);
    1381   alloccache_free (&variable_set_list_cache, list);
    1382 #endif
    1383 }
    1384 
    13851411/* Create a new variable set and push it on the current setlist.
    13861412   If we're pushing a global scope (that is, the current scope is the global
     
    13921418push_new_variable_scope (void)
    13931419{
    1394   current_variable_set_list = create_new_variable_set();
     1420  current_variable_set_list = create_new_variable_set ();
    13951421  if (current_variable_set_list->next == &global_setlist)
    13961422    {
     
    14151441
    14161442  /* Can't call this if there's no scope to pop!  */
    1417   assert(current_variable_set_list->next != NULL);
     1443  assert (current_variable_set_list->next != NULL);
    14181444
    14191445  if (current_variable_set_list != &global_setlist)
     
    14601486  struct variable **from_var_end = from_var_slot + from_set->table.ht_size;
    14611487
     1488  int inc = to_set == &global_variable_set ? 1 : 0;
     1489
    14621490  for ( ; from_var_slot < from_var_end; from_var_slot++)
    14631491    if (! HASH_VACANT (*from_var_slot))
    14641492      {
    1465         struct variable *from_var = *from_var_slot;
    1466         struct variable **to_var_slot
     1493        struct variable *from_var = *from_var_slot;
     1494        struct variable **to_var_slot
    14671495#ifndef CONFIG_WITH_STRCACHE2
    1468           = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
     1496          = (struct variable **) hash_find_slot (&to_set->table, *from_var_slot);
    14691497#else  /* CONFIG_WITH_STRCACHE2 */
    14701498          = (struct variable **) hash_find_slot_strcached (&to_set->table,
    14711499                                                           *from_var_slot);
    14721500#endif /* CONFIG_WITH_STRCACHE2 */
    1473         if (HASH_VACANT (*to_var_slot))
    1474           hash_insert_at (&to_set->table, from_var, to_var_slot);
    1475         else
    1476           {
    1477             /* GKM FIXME: delete in from_set->table */
     1501        if (HASH_VACANT (*to_var_slot))
     1502          {
     1503            hash_insert_at (&to_set->table, from_var, to_var_slot);
     1504            variable_changenum += inc;
     1505          }
     1506        else
     1507          {
     1508            /* GKM FIXME: delete in from_set->table */
    14781509#ifdef KMK
    14791510            if (from_var->aliased)
    1480               fatal(NULL, ("Attempting to delete aliased variable '%s'"), from_var->name);
     1511              OS (fatal, NULL, ("Attempting to delete aliased variable '%s'"), from_var->name);
    14811512            if (from_var->alias)
    1482               fatal(NULL, ("Attempting to delete variable aliased '%s'"), from_var->name);
     1513              OS (fatal, NULL, ("Attempting to delete variable aliased '%s'"), from_var->name);
    14831514#endif
    14841515#ifdef CONFIG_WITH_COMPILER
     
    14901521#endif
    14911522              free (from_var->value);
    1492             free (from_var);
    1493           }
     1523            free (from_var);
     1524          }
    14941525      }
    14951526}
     
    15251556    {
    15261557      if (last0 == 0)
    1527         *setlist0 = setlist1;
     1558        *setlist0 = setlist1;
    15281559      else
    1529         last0->next = setlist1;
     1560        last0->next = setlist1;
    15301561    }
    15311562}
     
    15631594define_automatic_variables (void)
    15641595{
    1565 #if defined(WINDOWS32) || defined(__EMX__)
    1566   extern char* default_shell;
    1567 #else
    1568   extern char default_shell[];
    1569 #endif
    1570   register struct variable *v;
     1596  struct variable *v;
    15711597#ifndef KMK
    15721598  char buf[200];
     
    15881614
    15891615  sprintf (buf, "%s%s%s",
    1590            version_string,
    1591            (remote_description == 0 || remote_description[0] == '\0')
    1592            ? "" : "-",
    1593            (remote_description == 0 || remote_description[0] == '\0')
    1594            ? "" : remote_description);
     1616           version_string,
     1617           (remote_description == 0 || remote_description[0] == '\0')
     1618           ? "" : "-",
     1619           (remote_description == 0 || remote_description[0] == '\0')
     1620           ? "" : remote_description);
    15951621#ifndef KMK
    15961622  define_variable_cname ("MAKE_VERSION", buf, o_default, 0);
     1623  define_variable_cname ("MAKE_HOST", make_host, o_default, 0);
    15971624#else /* KMK */
    15981625
     
    16191646  val = envvar1 ? envvar1->value : envvar2 ? envvar2->value : KBUILD_HOST;
    16201647  if (envvar1 && envvar2 && strcmp (envvar1->value, envvar2->value))
    1621     error (NULL, _("KBUILD_HOST and BUILD_PLATFORM differs, using KBUILD_HOST=%s."), val);
     1648    OS (error, NULL, _("KBUILD_HOST and BUILD_PLATFORM differs, using KBUILD_HOST=%s."), val);
    16221649  if (!envvar1)
    16231650    define_variable_cname ("KBUILD_HOST", val, o_default, 0);
     
    16291656  val = envvar1 ? envvar1->value : envvar2 ? envvar2->value : KBUILD_HOST_ARCH;
    16301657  if (envvar1 && envvar2 && strcmp (envvar1->value, envvar2->value))
    1631     error (NULL, _("KBUILD_HOST_ARCH and BUILD_PLATFORM_ARCH differs, using KBUILD_HOST_ARCH=%s."), val);
     1658    OS (error, NULL, _("KBUILD_HOST_ARCH and BUILD_PLATFORM_ARCH differs, using KBUILD_HOST_ARCH=%s."), val);
    16321659  if (!envvar1)
    16331660    define_variable_cname ("KBUILD_HOST_ARCH", val, o_default, 0);
     
    16391666  val = envvar1 ? envvar1->value : envvar2 ? envvar2->value : KBUILD_HOST_CPU;
    16401667  if (envvar1 && envvar2 && strcmp (envvar1->value, envvar2->value))
    1641     error (NULL, _("KBUILD_HOST_CPU and BUILD_PLATFORM_CPU differs, using KBUILD_HOST_CPU=%s."), val);
     1668    OS (error, NULL, _("KBUILD_HOST_CPU and BUILD_PLATFORM_CPU differs, using KBUILD_HOST_CPU=%s."), val);
    16421669  if (!envvar1)
    16431670    define_variable_cname ("KBUILD_HOST_CPU", val, o_default, 0);
     
    18611888    if (mshp)
    18621889      (void) define_variable (shell_str, shlen,
    1863                               mshp->value, o_env_override, 0);
     1890                              mshp->value, o_env_override, 0);
    18641891    else if (comp)
    18651892      {
    1866         /* $(COMSPEC) shouldn't override $(SHELL).  */
    1867         struct variable *shp = lookup_variable (shell_str, shlen);
    1868 
    1869         if (!shp)
    1870           (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
     1893        /* $(COMSPEC) shouldn't override $(SHELL).  */
     1894        struct variable *shp = lookup_variable (shell_str, shlen);
     1895
     1896        if (!shp)
     1897          (void) define_variable (shell_str, shlen, comp->value, o_env, 0);
    18711898      }
    18721899  }
     
    18861913    if (!replace || !*replace->value)
    18871914      if (shell && *shell->value && (shell->origin == o_env
    1888           || shell->origin == o_env_override))
    1889         {
    1890           /* overwrite whatever we got from the environment */
    1891           free(shell->value);
    1892           shell->value = xstrdup (default_shell);
    1893           shell->origin = o_default;
    1894         }
     1915          || shell->origin == o_env_override))
     1916        {
     1917          /* overwrite whatever we got from the environment */
     1918          free (shell->value);
     1919          shell->value = xstrdup (default_shell);
     1920          shell->origin = o_default;
     1921        }
    18951922
    18961923    /* Some people do not like cmd to be used as the default
     
    19121939      /* overwrite $SHELL */
    19131940      (void) define_variable (shell_str, shlen, replace->value,
    1914                               replace->origin, 0);
     1941                              replace->origin, 0);
    19151942    else
    19161943      /* provide a definition if there is none */
    19171944      (void) define_variable (shell_str, shlen, default_shell,
    1918                               o_default, 0);
     1945                              o_default, 0);
    19191946  }
    19201947
     
    19581985     the automatic variables they are variations of.  */
    19591986
    1960 #ifdef VMS
    1961   define_variable_cname ("@D", "$(dir $@)", o_automatic, 1);
    1962   define_variable_cname ("%D", "$(dir $%)", o_automatic, 1);
    1963   define_variable_cname ("*D", "$(dir $*)", o_automatic, 1);
    1964   define_variable_cname ("<D", "$(dir $<)", o_automatic, 1);
    1965   define_variable_cname ("?D", "$(dir $?)", o_automatic, 1);
    1966   define_variable_cname ("^D", "$(dir $^)", o_automatic, 1);
    1967   define_variable_cname ("+D", "$(dir $+)", o_automatic, 1);
    1968 #else
     1987#if defined(__MSDOS__) || defined(WINDOWS32)
     1988  /* For consistency, remove the trailing backslash as well as slash.  */
     1989  define_variable_cname ("@D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $@)))",
     1990                         o_automatic, 1);
     1991  define_variable_cname ("%D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $%)))",
     1992                         o_automatic, 1);
     1993  define_variable_cname ("*D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $*)))",
     1994                         o_automatic, 1);
     1995  define_variable_cname ("<D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $<)))",
     1996                         o_automatic, 1);
     1997  define_variable_cname ("?D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $?)))",
     1998                         o_automatic, 1);
     1999  define_variable_cname ("^D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $^)))",
     2000                         o_automatic, 1);
     2001  define_variable_cname ("+D", "$(patsubst %/,%,$(patsubst %\\,%,$(dir $+)))",
     2002                         o_automatic, 1);
     2003#else  /* not __MSDOS__, not WINDOWS32 */
    19692004  define_variable_cname ("@D", "$(patsubst %/,%,$(dir $@))", o_automatic, 1);
    19702005  define_variable_cname ("%D", "$(patsubst %/,%,$(dir $%))", o_automatic, 1);
     
    20732108
    20742109/* Create a new environment for FILE's commands.
    2075    If FILE is nil, this is for the `shell' function.
     2110   If FILE is nil, this is for the 'shell' function.
    20762111   The child's MAKELEVEL variable is incremented.  */
    20772112
     
    21032138#ifndef CONFIG_WITH_STRCACHE2
    21042139  hash_init (&table, ENVIRONMENT_VARIABLE_BUCKETS,
    2105              variable_hash_1, variable_hash_2, variable_hash_cmp);
     2140             variable_hash_1, variable_hash_2, variable_hash_cmp);
    21062141#else  /* CONFIG_WITH_STRCACHE2 */
    21072142  hash_init_strcached (&table, ENVIRONMENT_VARIABLE_BUCKETS,
     
    21242159      v_end = v_slot + set->table.ht_size;
    21252160      for ( ; v_slot < v_end; v_slot++)
    2126         if (! HASH_VACANT (*v_slot))
    2127           {
    2128             struct variable **new_slot;
    2129             struct variable *v = *v_slot;
    2130 
    2131             /* If this is a per-target variable and it hasn't been touched
    2132                already then look up the global version and take its export
    2133                value.  */
    2134             if (v->per_target && v->export == v_default)
    2135               {
    2136                 struct variable *gv;
     2161        if (! HASH_VACANT (*v_slot))
     2162          {
     2163            struct variable **new_slot;
     2164            struct variable *v = *v_slot;
     2165
     2166            /* If this is a per-target variable and it hasn't been touched
     2167               already then look up the global version and take its export
     2168               value.  */
     2169            if (v->per_target && v->export == v_default)
     2170              {
     2171                struct variable *gv;
    21372172
    21382173#ifndef CONFIG_WITH_VALUE_LENGTH
    2139                 gv = lookup_variable_in_set (v->name, strlen(v->name),
     2174                gv = lookup_variable_in_set (v->name, strlen (v->name),
    21402175                                             &global_variable_set);
    21412176#else
    21422177                assert ((int)strlen(v->name) == v->length);
    21432178                gv = lookup_variable_in_set (v->name, v->length,
    2144                                                      &global_variable_set);
    2145 #endif
    2146                 if (gv)
    2147                   v->export = gv->export;
    2148               }
    2149 
    2150             switch (v->export)
    2151               {
    2152               case v_default:
    2153                 if (v->origin == o_default || v->origin == o_automatic)
    2154                   /* Only export default variables by explicit request.  */
    2155                   continue;
     2179                                             &global_variable_set);
     2180#endif
     2181                if (gv)
     2182                  v->export = gv->export;
     2183              }
     2184
     2185            switch (v->export)
     2186              {
     2187              case v_default:
     2188                if (v->origin == o_default || v->origin == o_automatic)
     2189                  /* Only export default variables by explicit request.  */
     2190                  continue;
    21562191
    21572192                /* The variable doesn't have a name that can be exported.  */
     
    21592194                  continue;
    21602195
    2161                 if (! export_all_variables
    2162                     && v->origin != o_command
    2163                     && v->origin != o_env && v->origin != o_env_override)
    2164                   continue;
    2165                 break;
    2166 
    2167               case v_export:
    2168                 break;
    2169 
    2170               case v_noexport:
    2171                 {
    2172                   /* If this is the SHELL variable and it's not exported,
    2173                      then add the value from our original environment, if
    2174                      the original environment defined a value for SHELL.  */
    2175                   extern struct variable shell_var;
    2176                   if (streq (v->name, "SHELL") && shell_var.value)
    2177                     {
    2178                       v = &shell_var;
    2179                       break;
    2180                     }
    2181                   continue;
    2182                 }
    2183 
    2184               case v_ifset:
    2185                 if (v->origin == o_default)
    2186                   continue;
    2187                 break;
    2188               }
     2196                if (! export_all_variables
     2197                    && v->origin != o_command
     2198                    && v->origin != o_env && v->origin != o_env_override)
     2199                  continue;
     2200                break;
     2201
     2202              case v_export:
     2203                break;
     2204
     2205              case v_noexport:
     2206                {
     2207                  /* If this is the SHELL variable and it's not exported,
     2208                     then add the value from our original environment, if
     2209                     the original environment defined a value for SHELL.  */
     2210                  if (streq (v->name, "SHELL") && shell_var.value)
     2211                    {
     2212                      v = &shell_var;
     2213                      break;
     2214                    }
     2215                  continue;
     2216                }
     2217
     2218              case v_ifset:
     2219                if (v->origin == o_default)
     2220                  continue;
     2221                break;
     2222              }
    21892223
    21902224#ifndef CONFIG_WITH_STRCACHE2
    2191             new_slot = (struct variable **) hash_find_slot (&table, v);
     2225            new_slot = (struct variable **) hash_find_slot (&table, v);
    21922226#else  /* CONFIG_WITH_STRCACHE2 */
    21932227            assert (strcache2_is_cached (&variable_strcache, v->name));
    21942228            new_slot = (struct variable **) hash_find_slot_strcached (&table, v);
    21952229#endif /* CONFIG_WITH_STRCACHE2 */
    2196             if (HASH_VACANT (*new_slot))
    2197               hash_insert_at (&table, v, new_slot);
    2198           }
     2230            if (HASH_VACANT (*new_slot))
     2231              hash_insert_at (&table, v, new_slot);
     2232          }
    21992233    }
    22002234
     
    22162250
    22172251#ifndef CONFIG_WITH_STRCACHE2
    2218   makelevel_key.name = MAKELEVEL_NAME;
     2252  makelevel_key.name = (char *)MAKELEVEL_NAME;
    22192253  makelevel_key.length = MAKELEVEL_LENGTH;
    22202254  hash_delete (&table, &makelevel_key);
     
    22392273    if (! HASH_VACANT (*v_slot))
    22402274      {
    2241         struct variable *v = *v_slot;
    2242 
    2243         /* If V is recursively expanded and didn't come from the environment,
    2244            expand its value.  If it came from the environment, it should
    2245            go back into the environment unchanged.  */
    2246         if (v->recursive
    2247             && v->origin != o_env && v->origin != o_env_override)
    2248           {
     2275        struct variable *v = *v_slot;
     2276
     2277        /* If V is recursively expanded and didn't come from the environment,
     2278           expand its value.  If it came from the environment, it should
     2279           go back into the environment unchanged.  */
     2280        if (v->recursive
     2281            && v->origin != o_env && v->origin != o_env_override)
     2282          {
    22492283#ifndef CONFIG_WITH_VALUE_LENGTH
    2250             char *value = recursively_expand_for_file (v, file);
     2284            char *value = recursively_expand_for_file (v, file);
    22512285#else
    22522286            char *value = recursively_expand_for_file (v, file, NULL);
    22532287#endif
    22542288#ifdef WINDOWS32
    2255             if (strcmp(v->name, "Path") == 0 ||
    2256                 strcmp(v->name, "PATH") == 0)
    2257               convert_Path_to_windows32(value, ';');
    2258 #endif
    2259             *result++ = xstrdup (concat (3, v->name, "=", value));
    2260             free (value);
    2261           }
    2262         else
    2263           {
     2289            if (strcmp (v->name, "Path") == 0 ||
     2290                strcmp (v->name, "PATH") == 0)
     2291              convert_Path_to_windows32 (value, ';');
     2292#endif
     2293            *result++ = xstrdup (concat (3, v->name, "=", value));
     2294            free (value);
     2295          }
     2296        else
     2297          {
    22642298#ifdef WINDOWS32
    2265             if (strcmp(v->name, "Path") == 0 ||
    2266                 strcmp(v->name, "PATH") == 0)
    2267               convert_Path_to_windows32(v->value, ';');
    2268 #endif
    2269             *result++ = xstrdup (concat (3, v->name, "=", v->value));
    2270           }
     2299            if (strcmp (v->name, "Path") == 0 ||
     2300                strcmp (v->name, "PATH") == 0)
     2301              convert_Path_to_windows32 (v->value, ';');
     2302#endif
     2303            *result++ = xstrdup (concat (3, v->name, "=", v->value));
     2304          }
    22712305      }
    22722306
     
    23542388
    23552389struct variable *
    2356 do_variable_definition_append (const struct floc *flocp, struct variable *v,
     2390do_variable_definition_append (const floc *flocp, struct variable *v,
    23572391                               const char *value, unsigned int value_len,
    23582392                               int simple_value, enum variable_origin origin,
     
    24112445
    24122446
     2447/* Given a string, shell-execute it and return a malloc'ed string of the
     2448 * result. This removes only ONE newline (if any) at the end, for maximum
     2449 * compatibility with the *BSD makes.  If it fails, returns NULL. */
     2450
     2451static char *
     2452shell_result (const char *p)
     2453{
     2454  char *buf;
     2455  unsigned int len;
     2456  char *args[2];
     2457  char *result;
     2458
     2459  install_variable_buffer (&buf, &len);
     2460
     2461  args[0] = (char *) p;
     2462  args[1] = NULL;
     2463  variable_buffer_output (func_shell_base (variable_buffer, args, 0), "\0", 1);
     2464  result = strdup (variable_buffer);
     2465
     2466  restore_variable_buffer (buf, len);
     2467  return result;
     2468}
     2469
     2470
    24132471/* Given a variable, a value, and a flavor, define the variable.
    24142472   See the try_variable_definition() function for details on the parameters. */
     
    24162474struct variable *
    24172475#ifndef CONFIG_WITH_VALUE_LENGTH
    2418 do_variable_definition (const struct floc *flocp, const char *varname,
     2476do_variable_definition (const floc *flocp, const char *varname,
    24192477                        const char *value, enum variable_origin origin,
    24202478                        enum variable_flavor flavor, int target_var)
    24212479#else  /* CONFIG_WITH_VALUE_LENGTH */
    2422 do_variable_definition_2 (const struct floc *flocp,
     2480do_variable_definition_2 (const floc *flocp,
    24232481                          const char *varname, const char *value,
    24242482                          unsigned int value_len, int simple_value,
     
    24542512      /* A simple variable definition "var := value".  Expand the value.
    24552513         We have to allocate memory since otherwise it'll clobber the
    2456         variable buffer, and we may still need that if we're looking at a
     2514        variable buffer, and we may still need that if we're looking at a
    24572515         target-specific variable.  */
    24582516#ifndef CONFIG_WITH_VALUE_LENGTH
     
    24762534#endif /* CONFIG_WITH_VALUE_LENGTH */
    24772535      break;
     2536    case f_shell:
     2537      {
     2538        /* A shell definition "var != value".  Expand value, pass it to
     2539           the shell, and store the result in recursively-expanded var. */
     2540        char *q = allocated_variable_expand (value);
     2541        p = alloc_value = shell_result (q);
     2542        free (q);
     2543        flavor = f_recursive;
     2544        break;
     2545      }
    24782546    case f_conditional:
    24792547      /* A conditional variable definition "var ?= value".
     
    24962564    case f_recursive:
    24972565      /* A recursive variable definition "var = value".
    2498         The value is used verbatim.  */
     2566        The value is used verbatim.  */
    24992567      p = value;
    25002568      break;
     
    26052673              }
    26062674
    2607             if (tp)
    2608               free (tp);
     2675            free (tp);
    26092676#endif /* !CONFIG_WITH_VALUE_LENGTH */
    26102677          }
     
    26152682  /* Many Unix Makefiles include a line saying "SHELL=/bin/sh", but
    26162683     non-Unix systems don't conform to this default configuration (in
    2617      fact, most of them don't even have `/bin').  On the other hand,
     2684     fact, most of them don't even have '/bin').  On the other hand,
    26182685     $SHELL in the environment, if set, points to the real pathname of
    26192686     the shell.
     
    26342701      /* See if we can find "/bin/sh.exe", "/bin/sh.com", etc.  */
    26352702      if (__dosexec_find_on_path (p, NULL, shellpath))
    2636         {
    2637           char *tp;
    2638 
    2639           for (tp = shellpath; *tp; tp++)
     2703        {
     2704          char *tp;
     2705
     2706          for (tp = shellpath; *tp; tp++)
    26402707            if (*tp == '\\')
    26412708              *tp = '/';
    26422709
    2643           v = define_variable_loc (varname, varname_len,
     2710          v = define_variable_loc (varname, varname_len,
    26442711                                   shellpath, origin, flavor == f_recursive,
    26452712                                   flocp);
    2646         }
     2713        }
    26472714      else
    2648         {
    2649           const char *shellbase, *bslash;
    2650           struct variable *pathv = lookup_variable ("PATH", 4);
    2651           char *path_string;
    2652           char *fake_env[2];
    2653           size_t pathlen = 0;
    2654 
    2655           shellbase = strrchr (p, '/');
    2656           bslash = strrchr (p, '\\');
    2657           if (!shellbase || bslash > shellbase)
    2658             shellbase = bslash;
    2659           if (!shellbase && p[1] == ':')
    2660             shellbase = p + 1;
    2661           if (shellbase)
    2662             shellbase++;
    2663           else
    2664             shellbase = p;
    2665 
    2666           /* Search for the basename of the shell (with standard
    2667              executable extensions) along the $PATH.  */
    2668           if (pathv)
    2669             pathlen = strlen (pathv->value);
    2670           path_string = xmalloc (5 + pathlen + 2 + 1);
    2671           /* On MSDOS, current directory is considered as part of $PATH.  */
    2672           sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
    2673           fake_env[0] = path_string;
    2674           fake_env[1] = 0;
    2675           if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
    2676             {
    2677               char *tp;
    2678 
    2679               for (tp = shellpath; *tp; tp++)
     2715        {
     2716          const char *shellbase, *bslash;
     2717          struct variable *pathv = lookup_variable ("PATH", 4);
     2718          char *path_string;
     2719          char *fake_env[2];
     2720          size_t pathlen = 0;
     2721
     2722          shellbase = strrchr (p, '/');
     2723          bslash = strrchr (p, '\\');
     2724          if (!shellbase || bslash > shellbase)
     2725            shellbase = bslash;
     2726          if (!shellbase && p[1] == ':')
     2727            shellbase = p + 1;
     2728          if (shellbase)
     2729            shellbase++;
     2730          else
     2731            shellbase = p;
     2732
     2733          /* Search for the basename of the shell (with standard
     2734             executable extensions) along the $PATH.  */
     2735          if (pathv)
     2736            pathlen = strlen (pathv->value);
     2737          path_string = xmalloc (5 + pathlen + 2 + 1);
     2738          /* On MSDOS, current directory is considered as part of $PATH.  */
     2739          sprintf (path_string, "PATH=.;%s", pathv ? pathv->value : "");
     2740          fake_env[0] = path_string;
     2741          fake_env[1] = 0;
     2742          if (__dosexec_find_on_path (shellbase, fake_env, shellpath))
     2743            {
     2744              char *tp;
     2745
     2746              for (tp = shellpath; *tp; tp++)
    26802747                if (*tp == '\\')
    26812748                  *tp = '/';
    26822749
    2683               v = define_variable_loc (varname, varname_len,
     2750              v = define_variable_loc (varname, varname_len,
    26842751                                       shellpath, origin,
    26852752                                       flavor == f_recursive, flocp);
    26862753            }
    2687           else
    2688             v = lookup_variable (varname, varname_len);
    2689 
    2690           free (path_string);
    2691         }
     2754          else
     2755            v = lookup_variable (varname, varname_len);
     2756
     2757          free (path_string);
     2758        }
    26922759    }
    26932760  else
     
    26982765      && streq (varname, "SHELL"))
    26992766    {
    2700       extern char *default_shell;
     2767      extern const char *default_shell;
    27012768
    27022769      /* Call shell locator function. If it returns TRUE, then
    2703         set no_default_sh_exe to indicate sh was found and
     2770        set no_default_sh_exe to indicate sh was found and
    27042771         set new value for SHELL variable.  */
    27052772
     
    27392806            v = lookup_variable (varname, varname_len);
    27402807
    2741           if (tp)
    2742             free (tp);
     2808          free (tp);
    27432809        }
    27442810    }
     
    27682834
    27692835#ifndef CONFIG_WITH_VALUE_LENGTH
    2770   if (alloc_value)
    2771     free (alloc_value);
     2836  free (alloc_value);
    27722837#else
    27732838  if (free_value)
     
    27812846/* Parse P (a null-terminated string) as a variable definition.
    27822847
    2783    If it is not a variable definition, return NULL.
     2848   If it is not a variable definition, return NULL and the contents of *VAR
     2849   are undefined, except NAME is set to the first non-space character or NIL.
    27842850
    27852851   If it is a variable definition, return a pointer to the char after the
    2786    assignment token and set *FLAVOR to the type of variable assignment.  */
     2852   assignment token and set the following fields (only) of *VAR:
     2853    name   : name of the variable (ALWAYS SET) (NOT NUL-TERMINATED!)
     2854    length : length of the variable name
     2855    value  : value of the variable (nul-terminated)
     2856    flavor : flavor of the variable
     2857   Other values in *VAR are unchanged.
     2858  */
    27872859
    27882860char *
    2789 parse_variable_definition (const char *p, enum variable_flavor *flavor)
     2861parse_variable_definition (const char *p, struct variable *var)
    27902862{
    27912863  int wspace = 0;
    2792 
    2793   p = next_token (p);
     2864  const char *e = NULL;
     2865
     2866/** @todo merge 4.2.1: parse_variable_definition does more now */
     2867  NEXT_TOKEN (p);
     2868  var->name = (char *)p;
     2869  var->length = 0;
    27942870
    27952871  while (1)
     
    27982874
    27992875      /* If we find a comment or EOS, it's not a variable definition.  */
    2800       if (c == '\0' || c == '#')
    2801         return NULL;
     2876      if (STOP_SET (c, MAP_COMMENT|MAP_NUL))
     2877        return NULL;
    28022878
    28032879      if (c == '$')
    2804         {
    2805           /* This begins a variable expansion reference.  Make sure we don't
    2806              treat chars inside the reference as assignment tokens.  */
    2807           char closeparen;
    2808           int count;
    2809           c = *p++;
    2810           if (c == '(')
    2811             closeparen = ')';
    2812           else if (c == '{')
    2813             closeparen = '}';
    2814           else
     2880        {
     2881          /* This begins a variable expansion reference.  Make sure we don't
     2882             treat chars inside the reference as assignment tokens.  */
     2883          char closeparen;
     2884          unsigned int count;
     2885
     2886          c = *p++;
     2887          if (c == '(')
     2888            closeparen = ')';
     2889          else if (c == '{')
     2890            closeparen = '}';
     2891          else if (c == '\0')
     2892            return NULL;
     2893          else
    28152894            /* '$$' or '$X'.  Either way, nothing special to do here.  */
    2816             continue;
    2817 
    2818           /* P now points past the opening paren or brace.
    2819              Count parens or braces until it is matched.  */
    2820           count = 0;
    2821           for (; *p != '\0'; ++p)
    2822             {
    2823               if (*p == c)
    2824                 ++count;
    2825               else if (*p == closeparen && --count < 0)
    2826                 {
    2827                   ++p;
    2828                   break;
    2829                 }
    2830             }
     2895            continue;
     2896
     2897          /* P now points past the opening paren or brace.
     2898             Count parens or braces until it is matched.  */
     2899          for (count = 1; *p != '\0'; ++p)
     2900            {
     2901              if (*p == closeparen && --count == 0)
     2902                {
     2903                  ++p;
     2904                  break;
     2905                }
     2906              if (*p == c)
     2907                ++count;
     2908            }
    28312909          continue;
    2832         }
     2910        }
    28332911
    28342912      /* If we find whitespace skip it, and remember we found it.  */
    2835       if (isblank ((unsigned char)c))
     2913      if (ISBLANK (c))
    28362914        {
    28372915          wspace = 1;
    2838           p = next_token (p);
     2916          e = p - 1;
     2917          NEXT_TOKEN (p);
    28392918          c = *p;
    28402919          if (c == '\0')
     
    28452924
    28462925      if (c == '=')
    2847         {
    2848           *flavor = f_recursive;
    2849           return (char *)p;
    2850         }
    2851 
    2852       /* Match assignment variants (:=, +=, ?=)  */
     2926        {
     2927          var->flavor = f_recursive;
     2928          if (! e)
     2929            e = p - 1;
     2930          break;
     2931        }
     2932
     2933      /* Match assignment variants (:=, +=, ?=, !=)  */
    28532934      if (*p == '=')
    28542935        {
     
    28562937            {
    28572938              case ':':
    2858                 *flavor = f_simple;
     2939                var->flavor = f_simple;
    28592940                break;
    28602941              case '+':
    2861                 *flavor = f_append;
     2942                var->flavor = f_append;
    28622943                break;
    28632944#ifdef CONFIG_WITH_PREPEND_ASSIGNMENT
    28642945              case '<':
    2865                *flavor = f_prepend;
     2946                var->flavor = f_prepend;
    28662947                break;
    28672948#endif
    28682949              case '?':
    2869                 *flavor = f_conditional;
     2950                var->flavor = f_conditional;
     2951                break;
     2952              case '!':
     2953                var->flavor = f_shell;
    28702954                break;
    28712955              default:
     
    28772961                continue;
    28782962            }
    2879           return (char *)++p;
     2963          if (! e)
     2964            e = p - 1;
     2965          ++p;
     2966          break;
    28802967        }
    2881       else if (c == ':')
    2882         /* A colon other than := is a rule line, not a variable defn.  */
    2883         return NULL;
     2968
     2969      /* Check for POSIX ::= syntax  */
     2970      if (c == ':')
     2971        {
     2972          /* A colon other than :=/::= is not a variable defn.  */
     2973          if (*p != ':' || p[1] != '=')
     2974            return NULL;
     2975
     2976          /* POSIX allows ::= to be the same as GNU make's := */
     2977          var->flavor = f_simple;
     2978          if (! e)
     2979            e = p - 1;
     2980          p += 2;
     2981          break;
     2982        }
    28842983
    28852984      /* If we skipped whitespace, non-assignments means no var.  */
     
    28882987    }
    28892988
     2989  var->length = e - var->name;
     2990  var->value = next_token (p);
     2991#ifdef CONFIG_WITH_VALUE_LENGTH
     2992  var->value_alloc_len = ~(unsigned int)0;
     2993  var->value_length =  -1;
     2994# ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
     2995  var->rdonly_val = 0;
     2996# endif
     2997#endif
    28902998  return (char *)p;
    28912999}
     
    28943002/* Try to interpret LINE (a null-terminated string) as a variable definition.
    28953003
    2896    If LINE was recognized as a variable definition, a pointer to its `struct
     3004   If LINE was recognized as a variable definition, a pointer to its 'struct
    28973005   variable' is returned.  If LINE is not a variable definition, NULL is
    28983006   returned.  */
    28993007
    29003008struct variable *
    2901 assign_variable_definition (struct variable *v, char *line IF_WITH_VALUE_LENGTH_PARAM(char *eos))
    2902 {
    2903   char *beg;
    2904   char *end;
    2905   enum variable_flavor flavor;
     3009assign_variable_definition (struct variable *v, const char *line IF_WITH_VALUE_LENGTH_PARAM(char *eos))
     3010{
    29063011#ifndef CONFIG_WITH_VALUE_LENGTH
    29073012  char *name;
    29083013#endif
    29093014
    2910   beg = next_token (line);
    2911   line = parse_variable_definition (beg, &flavor);
    2912   if (!line)
     3015  if (!parse_variable_definition (line, v))
    29133016    return NULL;
    29143017
    2915   end = line - (flavor == f_recursive ? 1 : 2);
    2916   while (end > beg && isblank ((unsigned char)end[-1]))
    2917     --end;
    2918   line = next_token (line);
    2919   v->value = line;
    2920   v->flavor = flavor;
    29213018#ifdef CONFIG_WITH_VALUE_LENGTH
    2922   v->value_alloc_len = ~(unsigned int)0;
    2923   v->value_length = eos != NULL ? eos - line : -1;
    2924   assert (eos == NULL || strchr (line, '\0') == eos);
    2925 # ifdef CONFIG_WITH_RDONLY_VARIABLE_VALUE
    2926   v->rdonly_val = 0;
    2927 # endif
     3019  if (eos)
     3020    {
     3021      v->value_length = eos - v->value;
     3022      assert (strchr (v->value, '\0') == eos);
     3023    }
    29283024#endif
    29293025
    29303026  /* Expand the name, so "$(foo)bar = baz" works.  */
    29313027#ifndef CONFIG_WITH_VALUE_LENGTH
    2932   name = alloca (end - beg + 1);
    2933   memcpy (name, beg, end - beg);
    2934   name[end - beg] = '\0';
     3028  name = alloca (v->length + 1);
     3029  memcpy (name, v->name, v->length);
     3030  name[v->length] = '\0';
    29353031  v->name = allocated_variable_expand (name);
    29363032#else  /* CONFIG_WITH_VALUE_LENGTH */
    2937   v->name = allocated_variable_expand_2 (beg, end - beg, NULL);
     3033  v->name = allocated_variable_expand_2 (v->name, v->length, NULL);
    29383034#endif /* CONFIG_WITH_VALUE_LENGTH */
    29393035
    29403036  if (v->name[0] == '\0')
    2941     fatal (&v->fileinfo, _("empty variable name"));
     3037    O (fatal, &v->fileinfo, _("empty variable name"));
    29423038
    29433039  return v;
     
    29543050   See the comments for assign_variable_definition().
    29553051
    2956    If LINE was recognized as a variable definition, a pointer to its `struct
     3052   If LINE was recognized as a variable definition, a pointer to its 'struct
    29573053   variable' is returned.  If LINE is not a variable definition, NULL is
    29583054   returned.  */
    29593055
    29603056struct variable *
    2961 try_variable_definition (const struct floc *flocp, char *line
     3057try_variable_definition (const floc *flocp, const char *line
    29623058                         IF_WITH_VALUE_LENGTH_PARAM(char *eos),
    29633059                         enum variable_origin origin, int target_var)
     
    30253121  switch (v->origin)
    30263122    {
     3123    case o_automatic:
     3124      origin = _("automatic");
     3125      break;
    30273126    case o_default:
    30283127      origin = _("default");
     
    30413140      break;
    30423141    case o_override:
    3043       origin = _("`override' directive");
    3044       break;
    3045     case o_automatic:
    3046       origin = _("automatic");
     3142      origin = _("'override' directive");
    30473143      break;
    30483144#ifdef CONFIG_WITH_LOCAL_VARIABLES
     
    30613157#ifndef KMK
    30623158  if (v->fileinfo.filenm)
    3063     printf (_(" (from `%s', line %lu)"),
    3064             v->fileinfo.filenm, v->fileinfo.lineno);
     3159    printf (_(" (from '%s', line %lu)"),
     3160            v->fileinfo.filenm, v->fileinfo.lineno + v->fileinfo.offset);
    30653161#else  /* KMK */
    30663162  if (alias->fileinfo.filenm)
     
    31393235  fputs (prefix, stdout);
    31403236
    3141   /* Is this a `define'?  */
     3237  /* Is this a 'define'?  */
    31423238  if (v->recursive && strchr (v->value, '\n') != 0)
    31433239#ifndef KMK /** @todo language feature for aliases */
     
    31593255      p = next_token (v->value);
    31603256      if (p != v->value && *p == '\0')
    3161         /* All whitespace.  */
    3162         printf ("$(subst ,,%s)", v->value);
     3257        /* All whitespace.  */
     3258        printf ("$(subst ,,%s)", v->value);
    31633259      else if (v->recursive)
    3164         fputs (v->value, stdout);
     3260        fputs (v->value, stdout);
    31653261      else
    3166         /* Double up dollar signs.  */
    3167         for (p = v->value; *p != '\0'; ++p)
    3168           {
    3169             if (*p == '$')
    3170               putchar ('$');
    3171             putchar (*p);
    3172           }
     3262        /* Double up dollar signs.  */
     3263        for (p = v->value; *p != '\0'; ++p)
     3264          {
     3265            if (*p == '$')
     3266              putchar ('$');
     3267            putchar (*p);
     3268          }
    31733269      putchar ('\n');
    31743270    }
     3271}
     3272
     3273
     3274static void
     3275print_auto_variable (const void *item, void *arg)
     3276{
     3277  const struct variable *v = item;
     3278
     3279  if (v->origin == o_automatic)
     3280    print_variable (item, arg);
     3281}
     3282
     3283
     3284static void
     3285print_noauto_variable (const void *item, void *arg)
     3286{
     3287  const struct variable *v = item;
     3288
     3289  if (v->origin != o_automatic)
     3290    print_variable (item, arg);
    31753291}
    31763292
     
    31793295   the actual variable definitions (everything else is comments).  */
    31803296
     3297#ifndef KMK
     3298static
     3299#endif
    31813300void
    3182 print_variable_set (struct variable_set *set, char *prefix)
     3301print_variable_set (struct variable_set *set, const char *prefix, int pauto)
    31833302{
    31843303#if defined (CONFIG_WITH_COMPILER) || defined (CONFIG_WITH_MAKE_STATS)
     
    31963315#endif
    31973316
    3198   hash_map_arg (&set->table, print_variable, prefix);
     3317  hash_map_arg (&set->table, (pauto ? print_auto_variable : print_variable),
     3318                (void *)prefix);
    31993319
    32003320  if (set->table.ht_fill)
     
    32663386  puts (_("\n# Variables\n"));
    32673387
    3268   print_variable_set (&global_variable_set, "");
     3388  print_variable_set (&global_variable_set, "", 0);
    32693389
    32703390  puts (_("\n# Pattern-specific Variable Values"));
     
    32723392  {
    32733393    struct pattern_var *p;
    3274     int rules = 0;
     3394    unsigned int rules = 0;
    32753395
    32763396    for (p = pattern_vars; p != 0; p = p->next)
     
    32783398        ++rules;
    32793399        printf ("\n%s :\n", p->target);
    3280         print_variable (&p->variable, "# ");
     3400        print_variable (&p->variable, (void *)"# ");
    32813401      }
    32823402
     
    33083428{
    33093429  if (file->variables != 0)
    3310     print_variable_set (file->variables->set, "# ");
     3430    print_variable_set (file->variables->set, "# ", 1);
     3431}
     3432
     3433void
     3434print_target_variables (const struct file *file)
     3435{
     3436  if (file->variables != 0)
     3437    {
     3438      int l = strlen (file->name);
     3439      char *t = alloca (l + 3);
     3440
     3441      strcpy (t, file->name);
     3442      t[l] = ':';
     3443      t[l+1] = ' ';
     3444      t[l+2] = '\0';
     3445
     3446      hash_map_arg (&file->variables->set->table, print_noauto_variable, t);
     3447    }
    33113448}
    33123449
     
    33213458    return;
    33223459
    3323   /*
    3324    * If done this before, don't leak memory unnecessarily.
    3325    * Free the previous entry before allocating new one.
    3326    */
    3327   if (environ_path)
    3328     free (environ_path);
    3329 
    3330   /*
    3331    * Create something WINDOWS32 world can grok
    3332    */
     3460  /* If done this before, free the previous entry before allocating new one.  */
     3461  free (environ_path);
     3462
     3463  /* Create something WINDOWS32 world can grok.  */
    33333464  convert_Path_to_windows32 (path, ';');
    33343465  environ_path = xstrdup (concat (3, "PATH", "=", path));
  • trunk/src/kmk/variable.h

    r3068 r3140  
    11/* Definitions for using variables in GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software
    4 Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    2624enum variable_origin
    2725  {
    28     o_default,          /* Variable from the default set.  */
    29     o_env,              /* Variable from environment.  */
    30     o_file,             /* Variable given in a makefile.  */
    31     o_env_override,     /* Variable from environment, if -e.  */
    32     o_command,          /* Variable given by user.  */
    33     o_override,         /* Variable from an `override' directive.  */
     26    o_default,          /* Variable from the default set.  */
     27    o_env,              /* Variable from environment.  */
     28    o_file,             /* Variable given in a makefile.  */
     29    o_env_override,     /* Variable from environment, if -e.  */
     30    o_command,          /* Variable given by user.  */
     31    o_override,         /* Variable from an 'override' directive.  */
    3432#ifdef CONFIG_WITH_LOCAL_VARIABLES
    3533    o_local,            /* Variable from an 'local' directive.  */
    3634#endif
    37     o_automatic,        /* Automatic variable -- cannot be set.  */
    38     o_invalid           /* Core dump time.  */
     35    o_automatic,        /* Automatic variable -- cannot be set.  */
     36    o_invalid           /* Core dump time.  */
    3937  };
    4038
     
    4240  {
    4341    f_bogus,            /* Bogus (error) */
    44     f_simple,           /* Simple definition (:=) */
     42    f_simple,           /* Simple definition (:= or ::=) */
    4543    f_recursive,        /* Recursive definition (=) */
    4644    f_append,           /* Appending definition (+=) */
     
    4846    f_prepend,          /* Prepending definition (>=) */
    4947#endif
    50     f_conditional       /* Conditional definition (?=) */
     48    f_conditional,      /* Conditional definition (?=) */
     49    f_shell             /* Shell assignment (!=) */
    5150  };
    5251
    5352/* Structure that represents one variable definition.
    5453   Each bucket of the hash table is a chain of these,
    55    chained through `next'.  */
     54   chained through 'next'.  */
    5655
    5756#define EXP_COUNT_BITS  15      /* This gets all the bitfields into 32 bits */
    5857#define EXP_COUNT_MAX   ((1<<EXP_COUNT_BITS)-1)
    5958#ifdef CONFIG_WITH_VALUE_LENGTH
    60 #define VAR_ALIGN_VALUE_ALLOC(len)  ( ((len) + (unsigned int)15) & ~(unsigned int)15 )
     59# define VAR_ALIGN_VALUE_ALLOC(len)  ( ((len) + (unsigned int)15) & ~(unsigned int)15 )
    6160#endif
    6261
     
    6463  {
    6564#ifndef CONFIG_WITH_STRCACHE2
    66     char *name;                 /* Variable name.  */
     65    char *name;                 /* Variable name.  */
    6766#else
    6867    const char *name;           /* Variable name (in varaible_strcache).  */
    6968#endif
    70     int length;                 /* strlen (name) */
     69    char *value;                /* Variable value.  */
     70    floc fileinfo;              /* Where the variable was defined.  */
     71    int length;                 /* strlen (name) */
    7172#ifdef CONFIG_WITH_VALUE_LENGTH
    7273    unsigned int value_length;  /* The length of the value.  */
     
    7475    /* FIXME: make lengths unsigned! */
    7576#endif
    76     char *value;                /* Variable value.  */
    77     struct floc fileinfo;       /* Where the variable was defined.  */
    78     unsigned int recursive:1;   /* Gets recursively re-evaluated.  */
    79     unsigned int append:1;      /* Nonzero if an appending target-specific
     77    unsigned int recursive:1;   /* Gets recursively re-evaluated.  */
     78    unsigned int append:1;      /* Nonzero if an appending target-specific
    8079                                   variable.  */
    8180    unsigned int conditional:1; /* Nonzero if set with a ?=. */
    82     unsigned int per_target:1;  /* Nonzero if a target-specific variable.  */
     81    unsigned int per_target:1;  /* Nonzero if a target-specific variable.  */
    8382    unsigned int special:1;     /* Nonzero if this is a special variable. */
    8483    unsigned int exportable:1;  /* Nonzero if the variable _could_ be
    8584                                   exported.  */
    86     unsigned int expanding:1;   /* Nonzero if currently being expanded.  */
     85    unsigned int expanding:1;   /* Nonzero if currently being expanded.  */
    8786    unsigned int private_var:1; /* Nonzero avoids inheritance of this
    8887                                   target-specific variable.  */
     
    9897#endif
    9998    enum variable_flavor
    100       flavor ENUM_BITFIELD (3); /* Variable flavor.  */
     99      flavor ENUM_BITFIELD (3); /* Variable flavor.  */
    101100    enum variable_origin
    102101#ifdef CONFIG_WITH_LOCAL_VARIABLES
    103102      origin ENUM_BITFIELD (4); /* Variable origin.  */
    104103#else
    105       origin ENUM_BITFIELD (3); /* Variable origin.  */
     104      origin ENUM_BITFIELD (3); /* Variable origin.  */
    106105#endif
    107106    enum variable_export
    108107      {
    109         v_export,               /* Export this variable.  */
    110         v_noexport,             /* Don't export this variable.  */
    111         v_ifset,                /* Export it if it has a non-default value.  */
    112         v_default               /* Decide in target_environment.  */
     108        v_export,               /* Export this variable.  */
     109        v_noexport,             /* Don't export this variable.  */
     110        v_ifset,                /* Export it if it has a non-default value.  */
     111        v_default               /* Decide in target_environment.  */
    113112      } export ENUM_BITFIELD (2);
    114113#ifdef CONFIG_WITH_COMPILER
     
    159158struct variable_set
    160159  {
    161     struct hash_table table;    /* Hash table of variables.  */
     160    struct hash_table table;    /* Hash table of variables.  */
    162161  };
    163162
     
    166165struct variable_set_list
    167166  {
    168     struct variable_set_list *next;     /* Link in the chain.  */
    169     struct variable_set *set;           /* Variable set.  */
     167    struct variable_set_list *next;     /* Link in the chain.  */
     168    struct variable_set *set;           /* Variable set.  */
    170169    int next_is_parent;                 /* True if next is a parent target.  */
    171170  };
     
    185184extern struct variable_set_list *current_variable_set_list;
    186185extern struct variable *default_goal_var;
     186extern struct variable shell_var;
    187187
    188188#ifdef KMK
     
    198198variable_buffer_output (char *ptr, const char *string, unsigned int length);
    199199#else /* KMK */
     200# include <k/kDefs.h>
    200201/* Subroutine of variable_expand and friends:
    201202   The text to add is LENGTH chars starting at STRING to the variable_buffer.
     
    205206   the following call.  */
    206207
    207 __inline static char *
    208 variable_buffer_output (char *ptr, const char *string, unsigned int length)
     208K_INLINE char *variable_buffer_output (char *ptr, const char *string, unsigned int length)
    209209{
    210210  register unsigned int newlen = length + (ptr - variable_buffer);
     
    239239  return ptr + length;
    240240}
    241 
    242241#endif /* KMK */
     242
    243243char *variable_expand (const char *line);
    244244char *variable_expand_for_file (const char *line, struct file *file);
     
    249249char *allocated_variable_expand_for_file (const char *line, struct file *file);
    250250#ifndef CONFIG_WITH_VALUE_LENGTH
    251 #define allocated_variable_expand(line) \
     251#define allocated_variable_expand(line) \
    252252  allocated_variable_expand_for_file (line, (struct file *) 0)
    253253#else  /* CONFIG_WITH_VALUE_LENGTH */
     
    264264variable_expand_string (char *line, const char *string, long length);
    265265#else  /* CONFIG_WITH_VALUE_LENGTH */
     266# include <k/kDefs.h>
    266267char *
    267268variable_expand_string_2 (char *line, const char *string, long length, char **eol);
    268 __inline static char *
    269 variable_expand_string (char *line, const char *string, long length)
     269K_INLINE char *variable_expand_string (char *line, const char *string, long length)
    270270{
    271271    char *ignored;
     
    274274#endif /* CONFIG_WITH_VALUE_LENGTH */
    275275void install_variable_buffer (char **bufp, unsigned int *lenp);
    276 char *install_variable_buffer_with_hint (char **bufp, unsigned int *lenp, unsigned int size_hint);
    277276void restore_variable_buffer (char *buf, unsigned int len);
    278 char *ensure_variable_buffer_space(char *ptr, unsigned int size);
     277char *install_variable_buffer_with_hint (char **bufp, unsigned int *lenp, unsigned int size_hint); /* bird */
     278char *ensure_variable_buffer_space (char *ptr, unsigned int size); /* bird */
    279279#ifdef CONFIG_WITH_VALUE_LENGTH
    280280void append_expanded_string_to_variable (struct variable *v, const char *value,
     
    302302                           const char *replace_percent);
    303303char *patsubst_expand (char *o, const char *text, char *pattern, char *replace);
    304 #ifdef CONFIG_WITH_COMMANDS_FUNC
     304char *func_shell_base (char *o, char **argv, int trim_newlines);
     305void shell_completed (int exit_code, int exit_sig);
     306
     307#ifdef CONFIG_WITH_COMMANDS_FUNC /* for append.c */
    305308char *func_commands (char *o, char **argv, const char *funcname);
    306309#endif
     310
    307311#if defined (CONFIG_WITH_VALUE_LENGTH)
    308312/* Avoid calling handle_function for every variable, do the
     
    311315# define MAX_FUNCTION_LENGTH    12
    312316# define MIN_FUNCTION_LENGTH    2
    313 MY_INLINE const char *
    314 may_be_function_name (const char *name, const char *eos)
     317K_INLINE const char *may_be_function_name (const char *name, const char *eos)
    315318{
    316319  unsigned char ch;
     
    325328    return 0;
    326329  if (MY_PREDICT_TRUE(!func_char_map[ch = name[2]]))
    327     return isspace (ch) ? name + 2 : 0;
     330    return ISSPACE (ch) ? name + 2 : 0;
    328331
    329332  name += 3;
     
    343346      name++;
    344347    }
    345   if (ch == '\0' || isblank (ch))
     348  if (ch == '\0' || ISBLANK (ch))
    346349    return name;
    347350  return 0;
     
    356359char *recursively_expand_for_file (struct variable *v, struct file *file,
    357360                                   unsigned int *value_lenp);
    358 #define recursively_expand(v)   recursively_expand_for_file (v, NULL, NULL)
    359 #endif
     361# define recursively_expand(v)  recursively_expand_for_file (v, NULL, NULL)
     362#endif /* CONFIG_WITH_VALUE_LENGTH */
    360363#ifdef CONFIG_WITH_COMPILER
    361364char *reference_recursive_variable (char *o, struct variable *v);
     
    370373void initialize_file_variables (struct file *file, int reading);
    371374void print_file_variables (const struct file *file);
    372 void print_variable_set (struct variable_set *set, char *prefix);
     375void print_target_variables (const struct file *file);
    373376void merge_variable_set_lists (struct variable_set_list **to_list,
    374377                               struct variable_set_list *from_list);
     378#ifdef KMK
     379void print_variable_set (struct variable_set *set, const char *prefix, int pauto);
     380#endif
     381
    375382#ifndef CONFIG_WITH_VALUE_LENGTH
    376 struct variable *do_variable_definition (const struct floc *flocp,
     383struct variable *do_variable_definition (const floc *flocp,
    377384                                         const char *name, const char *value,
    378385                                         enum variable_origin origin,
     
    383390    do_variable_definition_2 ((flocp), (varname), (value), ~0U, 0, NULL, \
    384391                              (origin), (flavor), (target_var))
    385 struct variable *do_variable_definition_2 (const struct floc *flocp,
     392struct variable *do_variable_definition_2 (const floc *flocp,
    386393                                           const char *varname,
    387394                                           const char *value,
     
    393400#endif /* CONFIG_WITH_VALUE_LENGTH */
    394401char *parse_variable_definition (const char *line,
    395                                           enum variable_flavor *flavor);
    396 struct variable *assign_variable_definition (struct variable *v, char *line IF_WITH_VALUE_LENGTH_PARAM(char *eos));
    397 struct variable *try_variable_definition (const struct floc *flocp, char *line
     402                                 struct variable *v);
     403struct variable *assign_variable_definition (struct variable *v, const char *line IF_WITH_VALUE_LENGTH_PARAM(char *eos));
     404struct variable *try_variable_definition (const floc *flocp, const char *line
    398405                                          IF_WITH_VALUE_LENGTH_PARAM(char *eos),
    399406                                          enum variable_origin origin,
     
    401408void init_hash_global_variable_set (void);
    402409void hash_init_function_table (void);
     410void define_new_function(const floc *flocp, const char *name,
     411                         unsigned int min, unsigned int max, unsigned int flags,
     412                         gmk_func_ptr func);
    403413struct variable *lookup_variable (const char *name, unsigned int length);
    404414struct variable *lookup_variable_in_set (const char *name, unsigned int length,
     
    411421void append_string_to_variable (struct variable *v, const char *value,
    412422                                unsigned int value_len, int append);
    413 struct variable * do_variable_definition_append (const struct floc *flocp, struct variable *v,
     423struct variable * do_variable_definition_append (const floc *flocp, struct variable *v,
    414424                                                 const char *value, unsigned int value_len,
    415425                                                 int simple_value, enum variable_origin origin,
     
    423433                                         int recursive,
    424434                                         struct variable_set *set,
    425                                          const struct floc *flocp);
     435                                         const floc *flocp);
    426436
    427437/* Define a variable in the current variable set.  */
     
    467477                                         int recursive,
    468478                                         struct variable_set *set,
    469                                          const struct floc *flocp);
     479                                         const floc *flocp);
    470480
    471481/* Define a variable in the current variable set.  */
     
    500510
    501511void undefine_variable_in_set (const char *name, unsigned int length,
    502                                          enum variable_origin origin,
    503                                          struct variable_set *set);
     512                               enum variable_origin origin,
     513                               struct variable_set *set);
    504514
    505515/* Remove variable from the current variable set. */
     
    512522define_variable_alias_in_set (const char *name, unsigned int length,
    513523                              struct variable *target, enum variable_origin origin,
    514                               struct variable_set *set, const struct floc *flocp);
     524                              struct variable_set *set, const floc *flocp);
    515525#endif
    516526
     
    518528
    519529#define warn_undefined(n,l) do{\
    520                               if (warn_undefined_variables_flag) \
    521                                 error (reading_file, \
    522                                        _("warning: undefined variable `%.*s'"), \
    523                                 (int)(l), (n)); \
     530                              if (warn_undefined_variables_flag)        \
     531                                error (reading_file, (l),               \
     532                                       _("warning: undefined variable '%.*s'"), \
     533                                       (int)(l), (n));                  \
    524534                              }while(0)
    525535
     
    539549#define MAKELEVEL_NAME "MAKELEVEL"
    540550#endif
    541 #define MAKELEVEL_LENGTH (sizeof (MAKELEVEL_NAME) - 1)
    542 
     551#define MAKELEVEL_LENGTH (CSTRLEN (MAKELEVEL_NAME))
  • trunk/src/kmk/version.c

    r2591 r3140  
    11/* Record version and build host architecture for GNU make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1917/* We use <config.h> instead of "config.h" so that a compilation
    2018   using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
    21    (which it would do because make.h was found in $srcdir).  */
     19   (which it would do because makeint.h was found in $srcdir).  */
    2220#include <config.h>
    2321
     
    2624#endif
    2725
    28 char *version_string = VERSION;
    29 char *make_host = MAKE_HOST;
     26const char *version_string = VERSION;
     27const char *make_host = MAKE_HOST;
    3028
    3129
  • trunk/src/kmk/vmsdir.h

    r2591 r3140  
    11/* dirent.h for vms
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    3 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    4645    + 3) & ~3)
    4746
    48 #define d_ino   d_fileno                /* compatability */
     47#define d_ino   d_fileno                /* compatibility */
    4948
    5049
  • trunk/src/kmk/vmsfunctions.c

    r2591 r3140  
    11/* VMS functions
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    3 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    1615this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1716
    18 #include "make.h"
     17#include "makeint.h"
    1918#include "debug.h"
    2019#include "job.h"
    2120
     21#include <ctype.h>
     22#include <string.h>
     23
    2224#ifdef __DECC
    2325#include <starlet.h>
    2426#endif
    25 #include <descrip.h>
     27
    2628#include <rms.h>
    27 #include <iodef.h>
    28 #include <atrdef.h>
    29 #include <fibdef.h>
    3029#include "vmsdir.h"
    3130
     
    120119      struct NAM *dnam = (struct NAM *)(dfab->fab$l_nam);
    121120      if (dnam != NULL)
    122         free (dnam->nam$l_esa);
     121        free (dnam->nam$l_esa);
    123122      free (dnam);
    124123      free (dir);
     
    129128#endif /* compiled for OpenVMS prior to V7.x */
    130129
    131 char *
    132 getwd (char *cwd)
    133 {
    134   static char buf[512];
    135 
    136   if (cwd)
    137     return (getcwd (cwd, 512));
    138   else
    139     return (getcwd (buf, 512));
    140 }
    141 
    142 #if 0
    143 /*
    144  * Is this used? I don't see any reference, so I suggest to remove it.
    145  */
    146 int
    147 vms_stat (char *name, struct stat *buf)
     130/* Argv0 will be a full vms file specification, like
     131   node$dka100:[utils.gnumake]make.exe;47
     132   prefix it with "mcr " to make it a vms command, executable for DCL. */
     133const char *
     134vms_command(const char* argv0)
     135{
     136  size_t l = strlen(argv0) + 1;
     137  char* s = xmalloc(l + 4);
     138  memcpy(s, "mcr ", 4);
     139  memcpy(s+4, argv0, l);
     140  return s;
     141}
     142
     143/* Argv0 aka argv[0] will be a full vms file specification, like
     144   node$dka100:[utils.gnumake]make.exe;47, set up by the CRTL.
     145   The vms progname should be ^^^^, the file name without
     146   file type .exe and ;version.
     147   Use sys$parse to get the name part of the file specification. That is
     148   in the above example, pick up "make" and return a copy of that string.
     149   If something goes wrong in sys$parse (unlikely, this is a VMS/CRTL supplied
     150   file specification) or if there is an empty name part (not easy to produce,
     151   but it is possible) just return "make".
     152   Somes notes ...
     153   NAM[L]$M_SYNCHK requests a syntax check, only.
     154   NAM is for ODS2 names (shorter parts, output usually converted to UPPERCASE).
     155   NAML is for ODS2/ODS5 names (longer parts, output unchanged).
     156   NAM$M_NO_SHORT_UPCASE may not be available for older versions of VMS.
     157   NAML is not available on older versions of VMS (NAML$C_BID not defined).
     158   argv[0] on older versions of VMS (no extended parse style and no
     159   CRTL feature DECC$ARGV_PARSE_STYLE) is always in lowercase. */
     160const char *
     161vms_progname(const char* argv0)
    148162{
    149163  int status;
    150   int i;
    151 
    152   static struct FAB Fab;
    153   static struct NAM Nam;
    154   static struct fibdef Fib;     /* short fib */
    155   static struct dsc$descriptor FibDesc =
    156   { sizeof (Fib), DSC$K_DTYPE_Z, DSC$K_CLASS_S, (char *) &Fib };
    157   static struct dsc$descriptor_s DevDesc =
    158   { 0, DSC$K_DTYPE_T, DSC$K_CLASS_S, &Nam.nam$t_dvi[1] };
    159   static char EName[NAM$C_MAXRSS];
    160   static char RName[NAM$C_MAXRSS];
    161   static struct dsc$descriptor_s FileName =
    162   { 0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0 };
    163   static struct dsc$descriptor_s string =
    164   { 0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0 };
    165   static unsigned long Rdate[2];
    166   static unsigned long Cdate[2];
    167   static struct atrdef Atr[] =
    168   {
    169 #if defined(VAX)
    170     /* Revision date */
    171     { sizeof (Rdate), ATR$C_REVDATE, (unsigned int) &Rdate[0] },
    172     /* Creation date */
    173     { sizeof (Cdate), ATR$C_CREDATE, (unsigned int) &Cdate[0] },
     164  static struct FAB fab;
     165  char *progname;
     166  const char *fallback = "make";
     167
     168#ifdef NAML$C_BID
     169  static char esa[NAML$C_MAXRSS];
     170  static struct NAML naml;
    174171#else
    175     /* Revision date */
    176     { sizeof (Rdate), ATR$C_REVDATE, &Rdate[0] },
    177     /* Creation date */
    178     { sizeof (Cdate), ATR$C_CREDATE, &Cdate[0]},
    179 #endif
    180     { 0, 0, 0 }
    181   };
    182   static short int DevChan;
    183   static short int iosb[4];
    184 
    185   name = vmsify (name, 0);
    186 
    187   /* initialize RMS structures, we need a NAM to retrieve the FID */
    188   Fab = cc$rms_fab;
    189   Fab.fab$l_fna = name;         /* name of file */
    190   Fab.fab$b_fns = strlen (name);
    191   Fab.fab$l_nam = &Nam;         /* FAB has an associated NAM */
    192 
    193   Nam = cc$rms_nam;
    194   Nam.nam$l_esa = EName;        /* expanded filename */
    195   Nam.nam$b_ess = sizeof (EName);
    196   Nam.nam$l_rsa = RName;        /* resultant filename */
    197   Nam.nam$b_rss = sizeof (RName);
    198 
    199   /* do $PARSE and $SEARCH here */
    200   status = sys$parse (&Fab);
     172  static char esa[NAM$C_MAXRSS];
     173  static struct NAM nam;
     174#endif
     175
     176  fab = cc$rms_fab;
     177  fab.fab$l_fna = (char*)argv0;
     178  fab.fab$b_fns = strlen(argv0);
     179
     180#ifdef NAML$C_BID
     181  fab.fab$l_naml = &naml;
     182  naml = cc$rms_naml;
     183  naml.naml$l_long_expand = esa;
     184  naml.naml$l_long_expand_alloc = NAML$C_MAXRSS;
     185  naml.naml$b_nop = NAML$M_SYNCHK;
     186  naml.naml$l_input_flags = NAML$M_NO_SHORT_OUTPUT;
     187#else
     188  fab.fab$l_nam = &nam;
     189  nam = cc$rms_nam;
     190  nam.nam$l_esa = esa;
     191  nam.nam$b_ess = NAM$C_MAXRSS;
     192# ifdef NAM$M_NO_SHORT_UPCASE
     193  nam.nam$b_nop = NAM$M_SYNCHK | NAM$M_NO_SHORT_UPCASE;
     194# else
     195  nam.nam$b_nop = NAM$M_SYNCHK;
     196# endif
     197#endif
     198
     199  status = sys$parse(&fab);
    201200  if (!(status & 1))
    202     return -1;
    203 
    204   DevDesc.dsc$w_length = Nam.nam$t_dvi[0];
    205   status = sys$assign (&DevDesc, &DevChan, 0, 0);
    206   if (!(status & 1))
    207     return -1;
    208 
    209   FileName.dsc$a_pointer = Nam.nam$l_name;
    210   FileName.dsc$w_length = Nam.nam$b_name + Nam.nam$b_type + Nam.nam$b_ver;
    211 
    212   /* Initialize the FIB */
    213   for (i = 0; i < 3; i++)
    214     {
    215 #ifndef __VAXC
    216       Fib.fib$w_fid[i] = Nam.nam$w_fid[i];
    217       Fib.fib$w_did[i] = Nam.nam$w_did[i];
     201    return fallback;
     202
     203#ifdef NAML$C_BID
     204  if (naml.naml$l_long_name_size == 0)
     205    return fallback;
     206  progname = xmalloc(naml.naml$l_long_name_size + 1);
     207  memcpy(progname, naml.naml$l_long_name, naml.naml$l_long_name_size);
     208  progname[naml.naml$l_long_name_size] = '\0';
    218209#else
    219       Fib.fib$r_fid_overlay.fib$w_fid[i] = Nam.nam$w_fid[i];
    220       Fib.fib$r_did_overlay.fib$w_did[i] = Nam.nam$w_did[i];
    221 #endif
    222     }
    223 
    224   status = sys$qiow (0, DevChan, IO$_ACCESS, &iosb, 0, 0,
    225                      &FibDesc, &FileName, 0, 0, &Atr, 0);
    226   sys$dassgn (DevChan);
    227   if (!(status & 1))
    228     return -1;
    229   status = iosb[0];
    230   if (!(status & 1))
    231     return -1;
    232 
    233   status = stat (name, buf);
    234   if (status)
    235     return -1;
    236 
    237   buf->st_mtime = ((Rdate[0] >> 24) & 0xff) + ((Rdate[1] << 8) & 0xffffff00);
    238   buf->st_ctime = ((Cdate[0] >> 24) & 0xff) + ((Cdate[1] << 8) & 0xffffff00);
    239 
    240   return 0;
    241 }
    242 #endif
    243 
    244 char *
    245 cvt_time (unsigned long tval)
    246 {
    247   static long int date[2];
    248   static char str[27];
    249   static struct dsc$descriptor date_str =
    250   { 26, DSC$K_DTYPE_T, DSC$K_CLASS_S, str };
    251 
    252   date[0] = (tval & 0xff) << 24;
    253   date[1] = ((tval >> 8) & 0xffffff);
    254 
    255   if ((date[0] == 0) && (date[1] == 0))
    256     return ("never");
    257 
    258   sys$asctim (0, &date_str, date, 0);
    259   str[26] = '\0';
    260 
    261   return (str);
    262 }
     210  if (nam.nam$b_name == 0)
     211    return fallback;
     212  progname = xmalloc(nam.nam$b_name + 1);
     213# ifdef NAM$M_NO_SHORT_UPCASE
     214  memcpy(progname, nam.nam$l_name, nam.nam$b_name);
     215# else
     216    {
     217      int i;
     218      for (i = 0; i < nam.nam$b_name; i++)
     219        progname[i] = tolower(nam.nam$l_name[i]);
     220    }
     221# endif
     222  progname[nam.nam$b_name] = '\0';
     223#endif
     224
     225  return progname;
     226}
  • trunk/src/kmk/vmsify.c

    r2591 r3140  
    11/* vmsify.c -- Module for vms <-> unix file name conversion
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    3 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    2322#include <string.h>
    2423#include <ctype.h>
     24
     25#include "makeint.h"
    2526
    2627#if VMS
     
    139140  reslt[resltlen] = '\0';
    140141
    141   s = malloc (resltlen+1);
    142   if (s == 0)
    143     return "";
     142  s = xmalloc (resltlen+1);
    144143  strcpy (s, reslt);
    145144  return s;
     
    223222   max 5 version
    224223*/
    225 #define MAXPATHLEN 512
     224/* todo: VMSMAXPATHLEN is defined for ODS2 names: it needs to be adjusted. */
     225#define VMSMAXPATHLEN 512
    226226
    227227  enum namestate nstate;
    228   static char vmsname[MAXPATHLEN+1];
     228  static char vmsname[VMSMAXPATHLEN+1];
    229229  const char *fptr;
    230230  const char *t;
     
    404404            if (*fptr == 0)             /* just // */
    405405              {
    406                 char cwdbuf[MAXPATHLEN+1];
    407 
    408                 s1 = getcwd(cwdbuf, MAXPATHLEN);
     406                char cwdbuf[VMSMAXPATHLEN+1];
     407
     408                s1 = getcwd(cwdbuf, VMSMAXPATHLEN);
    409409                if (s1 == 0)
    410410                  {
     
    798798            {                                   /* got '..' or '../' */
    799799              char *vp;
    800               char cwdbuf[MAXPATHLEN+1];
    801 
    802               vp = getcwd(cwdbuf, MAXPATHLEN);
     800              char cwdbuf[VMSMAXPATHLEN+1];
     801
     802              vp = getcwd(cwdbuf, VMSMAXPATHLEN);
    803803              if (vp == 0)
    804804                {
     
    858858            {
    859859              char *vp;
    860               char cwdbuf[MAXPATHLEN+1];
    861 
    862               vp = getcwd(cwdbuf, MAXPATHLEN);
     860              char cwdbuf[VMSMAXPATHLEN+1];
     861
     862              vp = getcwd(cwdbuf, VMSMAXPATHLEN);
    863863              if (vp == 0)
    864864                {
  • trunk/src/kmk/vmsjobs.c

    r2591 r3140  
    22   This file must be #included in job.c, as it accesses static functions.
    33
    4 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    5 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     4Copyright (C) 1996-2016 Free Software Foundation, Inc.
    65This file is part of GNU Make.
    76
     
    2221#include <clidef.h>
    2322
     23/* TODO - VMS specific header file conditionally included in makeint.h */
     24
     25#include <stsdef.h>
     26#include <ssdef.h>
     27void
     28decc$exit (int status);
     29
     30/* Lowest legal non-success VMS exit code is 8 */
     31/* GNU make only defines codes 0, 1, 2 */
     32/* So assume any exit code > 8 is a VMS exit code */
     33
     34#ifndef MAX_EXPECTED_EXIT_CODE
     35# define MAX_EXPECTED_EXIT_CODE 7
     36#endif
     37
     38
     39#if __CRTL_VER >= 70302000 && !defined(__VAX)
     40# define MAX_DCL_LINE_LENGTH 4095
     41# define MAX_DCL_CMD_LINE_LENGTH 8192
     42#else
     43# define MAX_DCL_LINE_LENGTH 255
     44# define MAX_DCL_CMD_LINE_LENGTH 1024
     45#endif
     46#define MAX_DCL_TOKEN_LENGTH 255
     47#define MAX_DCL_TOKENS 127
     48
     49enum auto_pipe { nopipe, add_pipe, dcl_pipe };
     50
    2451char *vmsify (char *name, int type);
    2552
    2653static int vms_jobsefnmask = 0;
     54
     55/* returns whether path is assumed to be a unix like shell. */
     56int
     57_is_unixy_shell (const char *path)
     58{
     59  return vms_gnv_shell;
     60}
     61
     62#define VMS_GETMSG_MAX 256
     63static char vms_strsignal_text[VMS_GETMSG_MAX + 2];
     64
     65char *
     66vms_strsignal (int status)
     67{
     68  if (status <= MAX_EXPECTED_EXIT_CODE)
     69    sprintf (vms_strsignal_text, "lib$spawn returned %x", status);
     70  else
     71    {
     72      int vms_status;
     73      unsigned short * msg_len;
     74      unsigned char out[4];
     75      vms_status = SYS$GETMSG (status, &msg_len,
     76                               vms_strsignal_text, 7, *out);
     77    }
     78
     79  return vms_strsignal_text;
     80}
     81
    2782
    2883/* Wait for nchildren children to terminate */
    2984static void
    30 vmsWaitForChildren(int *status)
     85vmsWaitForChildren (int *status)
    3186{
    3287  while (1)
    3388    {
    3489      if (!vms_jobsefnmask)
    35         {
    36           *status = 0;
    37           return;
    38         }
     90        {
     91          *status = 0;
     92          return;
     93        }
    3994
    4095      *status = sys$wflor (32, vms_jobsefnmask);
    4196    }
    4297  return;
    43 }
    44 
    45 /* Set up IO redirection.  */
    46 
    47 char *
    48 vms_redirect (struct dsc$descriptor_s *desc, char *fname, char *ibuf)
    49 {
    50   char *fptr;
    51 
    52   ibuf++;
    53   while (isspace ((unsigned char)*ibuf))
    54     ibuf++;
    55   fptr = ibuf;
    56   while (*ibuf && !isspace ((unsigned char)*ibuf))
    57     ibuf++;
    58   *ibuf = 0;
    59   if (strcmp (fptr, "/dev/null") != 0)
    60     {
    61       strcpy (fname, vmsify (fptr, 0));
    62       if (strchr (fname, '.') == 0)
    63         strcat (fname, ".");
    64     }
    65   desc->dsc$w_length = strlen(fname);
    66   desc->dsc$a_pointer = fname;
    67   desc->dsc$b_dtype = DSC$K_DTYPE_T;
    68   desc->dsc$b_class = DSC$K_CLASS_S;
    69 
    70   if (*fname == 0)
    71     printf (_("Warning: Empty redirection\n"));
    72   return ibuf;
    73 }
    74 
    75 
    76 /* found apostrophe at (p-1)
    77    inc p until after closing apostrophe.
    78  */
    79 
    80 char *
    81 vms_handle_apos (char *p)
    82 {
    83   int alast;
    84 
    85 #define SEPCHARS ",/()= "
    86 
    87   alast = 0;
    88 
    89   while (*p != 0)
    90     {
    91       if (*p == '"')
    92         {
    93           if (alast)
    94             {
    95               alast = 0;
    96               p++;
    97             }
    98           else
    99             {
    100               p++;
    101               if (strchr (SEPCHARS, *p))
    102                 break;
    103               alast = 1;
    104             }
    105         }
    106       else
    107         p++;
    108     }
    109 
    110   return p;
    11198}
    11299
     
    117104   inner mode level AST.
    118105*/
    119 int
    120 vmsHandleChildTerm(struct child *child)
     106static int
     107vmsHandleChildTerm (struct child *child)
    121108{
    122     int status;
    123     register struct child *lastc, *c;
    124     int child_failed;
    125 
     109  int exit_code;
     110  register struct child *lastc, *c;
     111  int child_failed;
     112
     113  /* The child efn is 0 when a built-in or null command is executed
     114     successfully with out actually creating a child.
     115  */
     116  if (child->efn > 0)
     117  {
    126118    vms_jobsefnmask &= ~(1 << (child->efn - 32));
    127119
    128     lib$free_ef(&child->efn);
    129     if (child->comname)
    130       {
    131         if (!ISDB (DB_JOBS)&&!ctrlYPressed)
    132           unlink (child->comname);
    133         free (child->comname);
    134       }
    135 
    136     (void) sigblock (fatal_signal_mask);
    137 
    138     child_failed = !(child->cstatus & 1 || ((child->cstatus & 7) == 0));
    139 
    140     /* Search for a child matching the deceased one.  */
    141     lastc = 0;
    142 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
    143     for (c = children; c != 0 && c != child; lastc = c, c = c->next)
    144       ;
     120    lib$free_ef (&child->efn);
     121  }
     122  if (child->comname)
     123    {
     124      if (!ISDB (DB_JOBS) && !ctrlYPressed)
     125        unlink (child->comname);
     126      free (child->comname);
     127    }
     128
     129  (void) sigblock (fatal_signal_mask);
     130
     131  /* First check to see if this is a POSIX exit status and handle */
     132  if ((child->cstatus & VMS_POSIX_EXIT_MASK) == VMS_POSIX_EXIT_MASK)
     133    {
     134      exit_code = (child->cstatus >> 3) & 255;
     135      if (exit_code != MAKE_SUCCESS)
     136        child_failed = 1;
     137    }
     138  else
     139    {
     140      child_failed = !$VMS_STATUS_SUCCESS (child->cstatus);
     141      if (child_failed)
     142        exit_code = child->cstatus;
     143    }
     144
     145  /* Search for a child matching the deceased one.  */
     146  lastc = 0;
     147#if defined(RECURSIVEJOBS)
     148  /* I've had problems with recursive stuff and process handling */
     149  for (c = children; c != 0 && c != child; lastc = c, c = c->next)
     150    ;
    145151#else
    146     c = child;
     152  c = child;
    147153#endif
    148154
    149     if (child_failed && !c->noerror && !ignore_errors_flag)
    150       {
    151         /* The commands failed.  Write an error message,
    152            delete non-precious targets, and abort.  */
    153         child_error (c->file->name, c->cstatus, 0, 0, 0);
    154         c->file->update_status = 1;
    155         delete_child_targets (c);
    156       }
    157     else
    158       {
    159         if (child_failed)
    160           {
    161             /* The commands failed, but we don't care.  */
    162             child_error (c->file->name, c->cstatus, 0, 0, 1);
    163             child_failed = 0;
    164           }
    165 
    166 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
    167         /* If there are more commands to run, try to start them.  */
    168         start_job (c);
    169 
    170         switch (c->file->command_state)
    171           {
    172           case cs_running:
    173             /* Successfully started.  */
    174             break;
    175 
    176           case cs_finished:
    177             if (c->file->update_status != 0) {
    178                 /* We failed to start the commands.  */
    179                 delete_child_targets (c);
    180             }
    181             break;
    182 
    183           default:
    184             error (NILF, _("internal error: `%s' command_state"),
    185                    c->file->name);
    186             abort ();
    187             break;
    188           }
    189 #endif /* RECURSIVEJOBS */
    190       }
    191 
    192     /* Set the state flag to say the commands have finished.  */
    193     c->file->command_state = cs_finished;
    194     notice_finished_file (c->file);
    195 
    196 #if defined(RECURSIVEJOBS) /* I've had problems with recursive stuff and process handling */
    197     /* Remove the child from the chain and free it.  */
    198     if (lastc == 0)
    199       children = c->next;
    200     else
    201       lastc->next = c->next;
    202     free_child (c);
    203 #endif /* RECURSIVEJOBS */
    204 
    205     /* There is now another slot open.  */
    206     if (job_slots_used > 0)
    207       --job_slots_used;
    208 
    209     /* If the job failed, and the -k flag was not given, die.  */
    210     if (child_failed && !keep_going_flag)
    211       die (EXIT_FAILURE);
    212 
    213     (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
    214 
    215     return 1;
     155  if ($VMS_STATUS_SUCCESS (child->vms_launch_status))
     156    {
     157      /* Convert VMS success status to 0 for UNIX code to be happy */
     158      child->vms_launch_status = 0;
     159    }
     160
     161  /* Set the state flag to say the commands have finished.  */
     162  c->file->command_state = cs_finished;
     163  notice_finished_file (c->file);
     164
     165  (void) sigsetmask (sigblock (0) & ~(fatal_signal_mask));
     166
     167  return 1;
    216168}
    217169
    218170/* VMS:
    219171   Spawn a process executing the command in ARGV and return its pid. */
    220 
    221 #define MAXCMDLEN 200
    222172
    223173/* local helpers to make ctrl+c and ctrl+y working, see below */
     
    234184reEnableAst(void)
    235185{
    236         lib$enable_ctrl (&oldCtrlMask,0);
     186  lib$enable_ctrl (&oldCtrlMask,0);
    237187}
    238188
     
    240190astYHandler (void)
    241191{
    242         struct child *c;
    243         for (c = children; c != 0; c = c->next)
    244                 sys$delprc (&c->pid, 0, 0);
    245         ctrlYPressed= 1;
    246         kill (getpid(),SIGQUIT);
    247         return SS$_NORMAL;
     192  struct child *c;
     193  for (c = children; c != 0; c = c->next)
     194    sys$delprc (&c->pid, 0, 0);
     195  ctrlYPressed= 1;
     196  kill (getpid(),SIGQUIT);
     197  return SS$_NORMAL;
    248198}
    249199
     
    251201tryToSetupYAst(void)
    252202{
    253         $DESCRIPTOR(inputDsc,"SYS$COMMAND");
    254         int     status;
    255         struct {
    256                 short int       status, count;
    257                 int     dvi;
    258         } iosb;
    259         unsigned short int loc_chan;
    260 
    261         setupYAstTried++;
    262 
    263         if (chan)
    264           loc_chan= chan;
    265         else {
    266                 status= sys$assign(&inputDsc,&loc_chan,0,0);
    267                 if (!(status&SS$_NORMAL)) {
    268                         lib$signal(status);
    269                         return;
    270                 }
    271         }
    272         status= sys$qiow (0, loc_chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
    273                           astYHandler,0,0,0,0,0);
    274         if (status==SS$_NORMAL)
    275                 status= iosb.status;
    276         if (status!=SS$_NORMAL) {
    277                 if (!chan)
    278                         sys$dassgn(loc_chan);
    279                 if (status!=SS$_ILLIOFUNC && status!=SS$_NOPRIV)
    280                         lib$signal(status);
    281                 return;
    282         }
    283 
    284         /* called from AST handler ? */
    285         if (setupYAstTried>1)
    286                 return;
    287         if (atexit(reEnableAst))
    288                 fprintf (stderr,
    289                          _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
    290         status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
    291         if (!(status&SS$_NORMAL)) {
    292                 lib$signal(status);
    293                 return;
    294         }
    295         if (!chan)
    296                 chan = loc_chan;
     203  $DESCRIPTOR(inputDsc,"SYS$COMMAND");
     204  int     status;
     205  struct {
     206    short int       status, count;
     207    int     dvi;
     208  } iosb;
     209  unsigned short int loc_chan;
     210
     211  setupYAstTried++;
     212
     213  if (chan)
     214    loc_chan= chan;
     215  else
     216    {
     217      status= sys$assign(&inputDsc,&loc_chan,0,0);
     218      if (!(status&SS$_NORMAL))
     219        {
     220          lib$signal(status);
     221          return;
     222        }
     223    }
     224  status= sys$qiow (0, loc_chan, IO$_SETMODE|IO$M_CTRLYAST,&iosb,0,0,
     225                    astYHandler,0,0,0,0,0);
     226  if (status==SS$_NORMAL)
     227    status= iosb.status;
     228  if (status!=SS$_NORMAL)
     229    {
     230      if (!chan)
     231        sys$dassgn(loc_chan);
     232      if (status!=SS$_ILLIOFUNC && status!=SS$_NOPRIV)
     233        lib$signal(status);
     234      return;
     235    }
     236
     237  /* called from AST handler ? */
     238  if (setupYAstTried>1)
     239    return;
     240  if (atexit(reEnableAst))
     241    fprintf (stderr,
     242             _("-warning, you may have to re-enable CTRL-Y handling from DCL.\n"));
     243  status= lib$disable_ctrl (&ctrlMask, &oldCtrlMask);
     244  if (!(status&SS$_NORMAL))
     245    {
     246      lib$signal(status);
     247      return;
     248    }
     249  if (!chan)
     250    chan = loc_chan;
    297251}
    298252
     253/* Check if a token is too long */
     254#define INC_TOKEN_LEN_OR_RETURN(x) {token->length++; \
     255  if (token->length >= MAX_DCL_TOKEN_LENGTH) \
     256    { token->cmd_errno = ERANGE; return x; }}
     257
     258#define INC_TOKEN_LEN_OR_BREAK {token->length++; \
     259  if (token->length >= MAX_DCL_TOKEN_LENGTH) \
     260    { token->cmd_errno = ERANGE; break; }}
     261
     262#define ADD_TOKEN_LEN_OR_RETURN(add_len, x) {token->length += add_len; \
     263  if (token->length >= MAX_DCL_TOKEN_LENGTH) \
     264    { token->cmd_errno = ERANGE; return x; }}
     265
     266/* Check if we are out of space for more tokens */
     267#define V_NEXT_TOKEN { if (cmd_tkn_index < MAX_DCL_TOKENS) \
     268  cmd_tokens[++cmd_tkn_index] = NULL; \
     269  else { token.cmd_errno = E2BIG; break; } \
     270  token.length = 0;}
     271
     272
     273#define UPDATE_TOKEN {cmd_tokens[cmd_tkn_index] = strdup(token.text); \
     274  V_NEXT_TOKEN;}
     275
     276#define EOS_ERROR(x) { if (*x == 0) { token->cmd_errno = ERANGE; break; }}
     277
     278struct token_info
     279  {
     280    char *text;       /* Parsed text */
     281    int length;       /* Length of parsed text */
     282    char *src;        /* Pointer to source text */
     283    int cmd_errno;    /* Error status of parse */
     284    int use_cmd_file; /* Force use of a command file */
     285  };
     286
     287
     288/* Extract a Posix single quoted string from input line */
     289static char *
     290posix_parse_sq (struct token_info *token)
     291{
     292  /* A Posix quoted string with no expansion unless in a string
     293     Unix simulation means no lexical functions present.
     294  */
     295  char * q;
     296  char * p;
     297  q = token->text;
     298  p = token->src;
     299
     300  *q++ = '"';
     301  p++;
     302  INC_TOKEN_LEN_OR_RETURN (p);
     303
     304  while (*p != '\'' && (token->length < MAX_DCL_TOKEN_LENGTH))
     305    {
     306      EOS_ERROR (p);
     307      if (*p == '"')
     308        {
     309          /* Embedded double quotes need to be doubled */
     310          *q++ = '"';
     311          INC_TOKEN_LEN_OR_BREAK;
     312          *q = '"';
     313        }
     314      else
     315        *q = *p;
     316
     317      q++;
     318      p++;
     319      INC_TOKEN_LEN_OR_BREAK;
     320    }
     321  *q++ = '"';
     322  p++;
     323  INC_TOKEN_LEN_OR_RETURN (p);
     324  *q = 0;
     325  return p;
     326}
     327
     328/* Extract a Posix double quoted string from input line */
     329static char *
     330posix_parse_dq (struct token_info *token)
     331{
     332  /* Unix mode:  Any imbedded \" becomes doubled.
     333                 \t is tab, \\, \$ leading character stripped.
     334                 $ character replaced with \' unless escaped.
     335  */
     336  char * q;
     337  char * p;
     338  q = token->text;
     339  p = token->src;
     340  *q++ = *p++;
     341  INC_TOKEN_LEN_OR_RETURN (p);
     342  while (*p != 0)
     343    {
     344      if (*p == '\\')
     345        {
     346          switch(p[1])
     347            {
     348            case 't':     /* Convert tabs */
     349              *q = '\t';
     350              p++;
     351              break;
     352            case '\\':     /* Just remove leading backslash */
     353            case '$':
     354              p++;
     355              *q = *p;
     356              break;
     357            case '"':
     358              p++;
     359              *q = *p;
     360              *q++ = '"';
     361              INC_TOKEN_LEN_OR_BREAK;
     362            default:      /* Pass through unchanged */
     363              *q++ = *p++;
     364              INC_TOKEN_LEN_OR_BREAK;
     365            }
     366          INC_TOKEN_LEN_OR_BREAK;
     367        }
     368      else if (*p == '$' && isalpha (p[1]))
     369        {
     370          /* A symbol we should be able to substitute */
     371          *q++ = '\'';
     372          INC_TOKEN_LEN_OR_BREAK;
     373          *q = '\'';
     374          INC_TOKEN_LEN_OR_BREAK;
     375          token->use_cmd_file = 1;
     376        }
     377      else
     378        {
     379          *q = *p;
     380          INC_TOKEN_LEN_OR_BREAK;
     381          if (*p == '"')
     382            {
     383              p++;
     384              q++;
     385              break;
     386            }
     387        }
     388      p++;
     389      q++;
     390    }
     391  *q = 0;
     392  return p;
     393}
     394
     395/* Extract a VMS quoted string or substitution string from input line */
     396static char *
     397vms_parse_quotes (struct token_info *token)
     398{
     399  /* VMS mode, the \' means that a symbol substitution is starting
     400     so while you might think you can just copy until the next
     401     \'.  Unfortunately the substitution can be a lexical function
     402     which can contain embedded strings and lexical functions.
     403     Messy, so both types need to be handled together.
     404  */
     405  char * q;
     406  char * p;
     407  q = token->text;
     408  p = token->src;
     409  int parse_level[MAX_DCL_TOKENS + 1];
     410  int nest = 0;
     411
     412  parse_level[0] = *p;
     413  if (parse_level[0] == '\'')
     414    token->use_cmd_file = 1;
     415
     416  *q++ = *p++;
     417  INC_TOKEN_LEN_OR_RETURN (p);
     418
     419
     420  /* Copy everything until after the next single quote at nest == 0 */
     421  while (token->length < MAX_DCL_TOKEN_LENGTH)
     422    {
     423      EOS_ERROR (p);
     424      *q = *p;
     425      INC_TOKEN_LEN_OR_BREAK;
     426      if ((*p == parse_level[nest]) && (p[1] != '"'))
     427        {
     428          if (nest == 0)
     429            {
     430              *q++ = *p++;
     431              break;
     432            }
     433          nest--;
     434        }
     435      else
     436        {
     437          switch(*p)
     438            {
     439            case '\\':
     440              /* Handle continuation on to next line */
     441              if (p[1] != '\n')
     442                break;
     443              p++;
     444              p++;
     445              *q = *p;
     446              break;
     447            case '(':
     448              /* Parenthesis only in single quote level */
     449              if (parse_level[nest] == '\'')
     450                {
     451                  nest++;
     452                  parse_level[nest] == ')';
     453                }
     454              break;
     455            case '"':
     456              /* Double quotes only in parenthesis */
     457              if (parse_level[nest] == ')')
     458                {
     459                  nest++;
     460                  parse_level[nest] == '"';
     461                }
     462              break;
     463            case '\'':
     464              /* Symbol substitution ony in double quotes */
     465              if ((p[1] == '\'') && (parse_level[nest] == '"'))
     466                {
     467                  nest++;
     468                  parse_level[nest] == '\'';
     469                  *p++ = *q++;
     470                  token->use_cmd_file = 1;
     471                  INC_TOKEN_LEN_OR_BREAK;
     472                  break;
     473                }
     474              *q = *p;
     475            }
     476        }
     477      p++;
     478      q++;
     479      /* Pass through doubled double quotes */
     480      if ((*p == '"') && (p[1] == '"') && (parse_level[nest] == '"'))
     481      {
     482        *p++ = *q++;
     483        INC_TOKEN_LEN_OR_BREAK;
     484        *p++ = *q++;
     485        INC_TOKEN_LEN_OR_BREAK;
     486      }
     487    }
     488  *q = 0;
     489  return p;
     490}
     491
     492/* Extract a $ string from the input line */
     493static char *
     494posix_parse_dollar (struct token_info *token)
     495{
     496  /* $foo becomes 'foo' */
     497  char * q;
     498  char * p;
     499  q = token->text;
     500  p = token->src;
     501  token->use_cmd_file = 1;
     502
     503  p++;
     504  *q++ = '\'';
     505  INC_TOKEN_LEN_OR_RETURN (p);
     506
     507  while ((isalnum (*p)) || (*p == '_'))
     508    {
     509      *q++ = *p++;
     510      INC_TOKEN_LEN_OR_BREAK;
     511    }
     512  *q++ = '\'';
     513  while (1)
     514    {
     515      INC_TOKEN_LEN_OR_BREAK;
     516      break;
     517    }
     518  *q = 0;
     519  return p;
     520}
     521
     522const char *vms_filechars = "0123456789abcdefghijklmnopqrstuvwxyz" \
     523   "ABCDEFGHIJKLMNOPQRSTUVWXYZ[]<>:/_-.$";
     524
     525/* Simple text copy */
     526static char *
     527parse_text (struct token_info *token, int assignment_hack)
     528{
     529  char * q;
     530  char * p;
     531  int str_len;
     532  q = token->text;
     533  p = token->src;
     534
     535  /* If assignment hack, then this text needs to be double quoted. */
     536  if (vms_unix_simulation && (assignment_hack == 2))
     537    {
     538      *q++ = '"';
     539      INC_TOKEN_LEN_OR_RETURN (p);
     540    }
     541
     542  *q++ = *p++;
     543  INC_TOKEN_LEN_OR_RETURN (p);
     544
     545  while (*p != 0)
     546    {
     547      str_len = strspn (p, vms_filechars);
     548      if (str_len == 0)
     549        {
     550          /* Pass through backslash escapes in Unix simulation
     551             probably will not work anyway.
     552             All any character after a ^ otherwise to support EFS.
     553          */
     554          if (vms_unix_simulation && (p[0] == '\\') && (p[1] != 0))
     555            str_len = 2;
     556          else if ((p[0] == '^') && (p[1] != 0))
     557            str_len = 2;
     558          else if (!vms_unix_simulation && (p[0] == ';'))
     559            str_len = 1;
     560
     561          if (str_len == 0)
     562            {
     563              /* If assignment hack, then this needs to be double quoted. */
     564              if (vms_unix_simulation && (assignment_hack == 2))
     565              {
     566                *q++ = '"';
     567                INC_TOKEN_LEN_OR_RETURN (p);
     568              }
     569              *q = 0;
     570              return p;
     571            }
     572        }
     573      if (str_len > 0)
     574        {
     575          ADD_TOKEN_LEN_OR_RETURN (str_len, p);
     576          strncpy (q, p, str_len);
     577          p += str_len;
     578          q += str_len;
     579          *q = 0;
     580        }
     581    }
     582  /* If assignment hack, then this text needs to be double quoted. */
     583  if (vms_unix_simulation && (assignment_hack == 2))
     584    {
     585      *q++ = '"';
     586      INC_TOKEN_LEN_OR_RETURN (p);
     587    }
     588  return p;
     589}
     590
     591/* single character copy */
     592static char *
     593parse_char (struct token_info *token, int count)
     594{
     595  char * q;
     596  char * p;
     597  q = token->text;
     598  p = token->src;
     599
     600  while (count > 0)
     601    {
     602      *q++ = *p++;
     603      INC_TOKEN_LEN_OR_RETURN (p);
     604      count--;
     605    }
     606  *q = 0;
     607  return p;
     608}
     609
     610/* Build a command string from the collected tokens
     611   and process built-ins now
     612*/
     613static struct dsc$descriptor_s *
     614build_vms_cmd (char **cmd_tokens,
     615               enum auto_pipe use_pipe_cmd,
     616               int append_token)
     617{
     618  struct dsc$descriptor_s *cmd_dsc;
     619  int cmd_tkn_index;
     620  char * cmd;
     621  int cmd_len;
     622  int semicolon_seen;
     623
     624  cmd_tkn_index = 0;
     625  cmd_dsc = xmalloc (sizeof (struct dsc$descriptor_s));
     626
     627  /* Empty command? */
     628  if (cmd_tokens[0] == NULL)
     629    {
     630      cmd_dsc->dsc$a_pointer = NULL;
     631      cmd_dsc->dsc$w_length = 0;
     632      return cmd_dsc;
     633    }
     634
     635  /* Max DCL command + 1 extra token and trailing space */
     636  cmd = xmalloc (MAX_DCL_CMD_LINE_LENGTH + 256);
     637
     638  cmd[0] = '$';
     639  cmd[1] = 0;
     640  cmd_len = 1;
     641
     642  /* Handle real or auto-pipe */
     643  if (use_pipe_cmd == add_pipe)
     644    {
     645      /* We need to auto convert to a pipe command */
     646      strcat (cmd, "pipe ");
     647      cmd_len += 5;
     648    }
     649
     650  semicolon_seen = 0;
     651  while (cmd_tokens[cmd_tkn_index] != NULL)
     652    {
     653
     654      /* Check for buffer overflow */
     655      if (cmd_len > MAX_DCL_CMD_LINE_LENGTH)
     656        {
     657          errno = E2BIG;
     658          break;
     659        }
     660
     661      /* Eliminate double ';' */
     662      if (semicolon_seen && (cmd_tokens[cmd_tkn_index][0] == ';'))
     663        {
     664          semicolon_seen = 0;
     665          free (cmd_tokens[cmd_tkn_index++]);
     666          if (cmd_tokens[cmd_tkn_index] == NULL)
     667            break;
     668        }
     669
     670      /* Special handling for CD built-in */
     671      if (strncmp (cmd_tokens[cmd_tkn_index], "builtin_cd", 11) == 0)
     672        {
     673          int result;
     674          semicolon_seen = 0;
     675          free (cmd_tokens[cmd_tkn_index]);
     676          cmd_tkn_index++;
     677          if (cmd_tokens[cmd_tkn_index] == NULL)
     678            break;
     679          DB(DB_JOBS, (_("BUILTIN CD %s\n"), cmd_tokens[cmd_tkn_index]));
     680
     681          /* TODO: chdir fails with some valid syntaxes */
     682          result = chdir (cmd_tokens[cmd_tkn_index]);
     683          if (result != 0)
     684            {
     685              /* TODO: Handle failure better */
     686              free (cmd);
     687              while (cmd_tokens[cmd_tkn_index] == NULL)
     688                free (cmd_tokens[cmd_tkn_index++]);
     689              cmd_dsc->dsc$w_length = -1;
     690              cmd_dsc->dsc$a_pointer = NULL;
     691              return cmd_dsc;
     692            }
     693        }
     694      else if (strncmp (cmd_tokens[cmd_tkn_index], "exit", 5) == 0)
     695        {
     696          /* Copy the exit command */
     697          semicolon_seen = 0;
     698          strcpy (&cmd[cmd_len], cmd_tokens[cmd_tkn_index]);
     699          cmd_len += strlen (cmd_tokens[cmd_tkn_index]);
     700          free (cmd_tokens[cmd_tkn_index++]);
     701          if (cmd_len > MAX_DCL_CMD_LINE_LENGTH)
     702            {
     703              errno = E2BIG;
     704              break;
     705            }
     706
     707          /* Optional whitespace */
     708          if (isspace (cmd_tokens[cmd_tkn_index][0]))
     709            {
     710              strcpy (&cmd[cmd_len], cmd_tokens[cmd_tkn_index]);
     711              cmd_len += strlen (cmd_tokens[cmd_tkn_index]);
     712              free (cmd_tokens[cmd_tkn_index++]);
     713              if (cmd_len > MAX_DCL_CMD_LINE_LENGTH)
     714              {
     715                errno = E2BIG;
     716                break;
     717              }
     718            }
     719
     720          /* There should be a status, but it is optional */
     721          if (cmd_tokens[cmd_tkn_index][0] == ';')
     722            continue;
     723
     724          /* If Unix simulation, add '((' */
     725          if (vms_unix_simulation)
     726            {
     727              strcpy (&cmd[cmd_len], "((");
     728              cmd_len += 2;
     729              if (cmd_len > MAX_DCL_CMD_LINE_LENGTH)
     730                {
     731                  errno = E2BIG;
     732                  break;
     733                }
     734            }
     735
     736          /* Add the parameter */
     737          strcpy (&cmd[cmd_len], cmd_tokens[cmd_tkn_index]);
     738          cmd_len += strlen (cmd_tokens[cmd_tkn_index]);
     739          free (cmd_tokens[cmd_tkn_index++]);
     740          if (cmd_len > MAX_DCL_CMD_LINE_LENGTH)
     741            {
     742              errno = E2BIG;
     743              break;
     744            }
     745
     746          /* Add " * 8) .and. %x7f8) .or. %x1035a002" */
     747          if (vms_unix_simulation)
     748            {
     749              const char *end_str = " * 8) .and. %x7f8) .or. %x1035a002";
     750              strcpy (&cmd[cmd_len], end_str);
     751              cmd_len += strlen (end_str);
     752              if (cmd_len > MAX_DCL_CMD_LINE_LENGTH)
     753                {
     754                  errno = E2BIG;
     755                  break;
     756                }
     757            }
     758          continue;
     759        }
     760
     761      /* auto pipe needs spaces before semicolon */
     762      if (use_pipe_cmd == add_pipe)
     763        if (cmd_tokens[cmd_tkn_index][0] == ';')
     764          {
     765            cmd[cmd_len++] = ' ';
     766            semicolon_seen = 1;
     767            if (cmd_len > MAX_DCL_CMD_LINE_LENGTH)
     768              {
     769                errno = E2BIG;
     770                break;
     771              }
     772          }
     773        else
     774          {
     775            char ch;
     776            ch = cmd_tokens[cmd_tkn_index][0];
     777            if (!(ch == ' ' || ch == '\t'))
     778              semicolon_seen = 0;
     779          }
     780
     781      strcpy (&cmd[cmd_len], cmd_tokens[cmd_tkn_index]);
     782      cmd_len += strlen (cmd_tokens[cmd_tkn_index]);
     783
     784      free (cmd_tokens[cmd_tkn_index++]);
     785
     786      /* Skip the append tokens if they exist */
     787      if (cmd_tkn_index == append_token)
     788        {
     789          free (cmd_tokens[cmd_tkn_index++]);
     790          if (isspace (cmd_tokens[cmd_tkn_index][0]))
     791            free (cmd_tokens[cmd_tkn_index++]);
     792          free (cmd_tokens[cmd_tkn_index++]);
     793        }
     794    }
     795
     796  cmd[cmd_len] = 0;
     797  cmd_dsc->dsc$w_length = cmd_len;
     798  cmd_dsc->dsc$a_pointer = cmd;
     799  cmd_dsc->dsc$b_dtype = DSC$K_DTYPE_T;
     800  cmd_dsc->dsc$b_class = DSC$K_CLASS_S;
     801
     802  return cmd_dsc;
     803}
     804
    299805int
    300 child_execute_job (char *argv, struct child *child)
     806child_execute_job (struct child *child, char *argv)
    301807{
    302808  int i;
    303   static struct dsc$descriptor_s cmddsc;
     809
     810  static struct dsc$descriptor_s *cmd_dsc;
    304811  static struct dsc$descriptor_s pnamedsc;
    305   static struct dsc$descriptor_s ifiledsc;
    306   static struct dsc$descriptor_s ofiledsc;
    307   static struct dsc$descriptor_s efiledsc;
    308   int have_redirection = 0;
    309   int have_append = 0;
    310   int have_newline = 0;
    311 
    312812  int spflags = CLI$M_NOWAIT;
    313813  int status;
    314   char *cmd = alloca (strlen (argv) + 512), *p, *q;
    315   char ifile[256], ofile[256], efile[256];
    316814  int comnamelen;
    317815  char procname[100];
    318   int in_string;
     816
     817  char *p;
     818  char *cmd_tokens[(MAX_DCL_TOKENS * 2) + 1]; /* whitespace does not count */
     819  char token_str[MAX_DCL_TOKEN_LENGTH + 1];
     820  struct token_info token;
     821  int cmd_tkn_index;
     822  int paren_level = 0;
     823  enum auto_pipe use_pipe_cmd = nopipe;
     824  int append_token = -1;
     825  char *append_file = NULL;
     826  int unix_echo_cmd = 0;  /* Special handle Unix echo command */
     827  int assignment_hack = 0; /* Handle x=y command as piped command */
    319828
    320829  /* Parse IO redirection.  */
    321830
    322   ifile[0] = 0;
    323   ofile[0] = 0;
    324   efile[0] = 0;
    325831  child->comname = NULL;
    326832
     
    331837
    332838  if (*argv == 0)
    333     return 0;
     839    {
     840      /* Only a built-in or a null command - Still need to run term AST */
     841      child->cstatus = VMS_POSIX_EXIT_MASK;
     842      child->vms_launch_status = SS$_NORMAL;
     843      /* TODO what is this "magic number" */
     844      child->pid = 270163; /* Special built-in */
     845      child->efn = 0;
     846      vmsHandleChildTerm (child);
     847      return 1;
     848    }
    334849
    335850  sprintf (procname, "GMAKE_%05x", getpid () & 0xfffff);
    336   pnamedsc.dsc$w_length = strlen(procname);
     851  pnamedsc.dsc$w_length = strlen (procname);
    337852  pnamedsc.dsc$a_pointer = procname;
    338853  pnamedsc.dsc$b_dtype = DSC$K_DTYPE_T;
    339854  pnamedsc.dsc$b_class = DSC$K_CLASS_S;
    340855
    341   in_string = 0;
    342   /* Handle comments and redirection. */
    343   for (p = argv, q = cmd; *p; p++, q++)
    344     {
    345       if (*p == '"')
    346         in_string = !in_string;
    347       if (in_string)
    348         {
    349           *q = *p;
    350           continue;
    351         }
     856  /* Old */
     857  /* Handle comments and redirection.
     858     For ONESHELL, the redirection must be on the first line. Any other
     859     redirection token is handled by DCL, that is, the pipe command with
     860     redirection can be used, but it should not be used on the first line
     861     for ONESHELL. */
     862
     863  /* VMS parser notes:
     864     1. A token is any of DCL verbs, qualifiers, parameters, or punctuation.
     865     2. Only MAX_DCL_TOKENS per line in both one line or command file mode.
     866     3. Each token limited to MAC_DCL_TOKEN_LENGTH
     867     4. If the line to DCL is greater than MAX_DCL_LINE_LENGTH then a
     868        command file must be used.
     869     5. Currently a command file must be used symbol substitution is to
     870        be performed.
     871     6. Currently limiting command files to 2 * MAX_DCL_TOKENS.
     872
     873     Build both a command file token list and command line token list
     874     until it is determined that the command line limits are exceeded.
     875  */
     876
     877  cmd_tkn_index = 0;
     878  cmd_tokens[cmd_tkn_index] = NULL;
     879  p = argv;
     880
     881  token.text = token_str;
     882  token.length = 0;
     883  token.cmd_errno = 0;
     884  token.use_cmd_file = 0;
     885
     886  while (*p != 0)
     887    {
     888      /* We can not build this command so give up */
     889      if (token.cmd_errno != 0)
     890        break;
     891
     892      token.src = p;
     893
    352894      switch (*p)
    353         {
    354           case '#':
    355             *p-- = 0;
    356             *q-- = 0;
    357             break;
    358           case '\\':
    359             p++;
    360             if (*p == '\n')
    361               p++;
    362             if (isspace ((unsigned char)*p))
    363               {
    364                 do { p++; } while (isspace ((unsigned char)*p));
    365                 p--;
    366               }
    367             *q = *p;
    368             break;
    369           case '<':
    370             p = vms_redirect (&ifiledsc, ifile, p);
    371             *q = ' ';
    372             have_redirection = 1;
    373             break;
    374           case '>':
    375             have_redirection = 1;
    376             if (*(p-1) == '2')
    377               {
    378                 q--;
    379                 if (strncmp (p, ">&1", 3) == 0)
    380                   {
    381                     p += 3;
    382                     strcpy (efile, "sys$output");
    383                     efiledsc.dsc$w_length = strlen(efile);
    384                     efiledsc.dsc$a_pointer = efile;
    385                     efiledsc.dsc$b_dtype = DSC$K_DTYPE_T;
    386                     efiledsc.dsc$b_class = DSC$K_CLASS_S;
    387                   }
    388                 else
    389                   {
    390                     p = vms_redirect (&efiledsc, efile, p);
    391                   }
    392               }
    393             else
    394               {
    395                 if (*(p+1) == '>')
    396                   {
    397                     have_append = 1;
    398                     p += 1;
    399                   }
    400                 p = vms_redirect (&ofiledsc, ofile, p);
    401               }
    402             *q = ' ';
    403             break;
    404           case '\n':
    405             have_newline = 1;
    406           default:
    407             *q = *p;
    408             break;
    409         }
    410     }
    411   *q = *p;
    412   while (isspace ((unsigned char)*--q))
    413     *q = '\0';
    414 
    415   if (strncmp (cmd, "builtin_", 8) == 0)
    416     {
    417       child->pid = 270163;
     895        {
     896        case '\'':
     897          if (vms_unix_simulation || unix_echo_cmd)
     898            {
     899              p = posix_parse_sq (&token);
     900              UPDATE_TOKEN;
     901              break;
     902            }
     903
     904          /* VMS mode, the \' means that a symbol substitution is starting
     905             so while you might think you can just copy until the next
     906             \'.  Unfortunately the substitution can be a lexical function
     907             which can contain embedded strings and lexical functions.
     908             Messy.
     909          */
     910          p = vms_parse_quotes (&token);
     911          UPDATE_TOKEN;
     912          break;
     913        case '"':
     914          if (vms_unix_simulation)
     915            {
     916              p = posix_parse_dq (&token);
     917              UPDATE_TOKEN;
     918              break;
     919            }
     920
     921          /* VMS quoted string, can contain lexical functions with
     922             quoted strings and nested lexical functions.
     923          */
     924          p = vms_parse_quotes (&token);
     925          UPDATE_TOKEN;
     926          break;
     927
     928        case '$':
     929          if (vms_unix_simulation)
     930            {
     931              p = posix_parse_dollar (&token);
     932              UPDATE_TOKEN;
     933              break;
     934            }
     935
     936          /* Otherwise nothing special */
     937          p = parse_text (&token, 0);
     938          UPDATE_TOKEN;
     939          break;
     940        case '\\':
     941          if (p[1] == '\n')
     942            {
     943              /* Line continuation, remove it */
     944              p += 2;
     945              break;
     946            }
     947
     948          /* Ordinary character otherwise */
     949          if (assignment_hack != 0)
     950            assignment_hack++;
     951          if (assignment_hack > 2)
     952            {
     953              assignment_hack = 0;          /* Reset */
     954              if (use_pipe_cmd == nopipe)   /* force pipe use */
     955                use_pipe_cmd = add_pipe;
     956              token_str[0] = ';';              /* add ; token */
     957              token_str[1] = 0;
     958              UPDATE_TOKEN;
     959            }
     960          p = parse_text (&token, assignment_hack);
     961          UPDATE_TOKEN;
     962          break;
     963        case '!':
     964        case '#':
     965          /* Unix '#' is VMS '!' which comments out the rest of the line.
     966             Historically the rest of the line has been skipped.
     967             Not quite the right thing to do, as the f$verify lexical
     968             function works in comments.  But this helps keep the line
     969             lengths short.
     970          */
     971          unix_echo_cmd = 0;
     972          while (*p != '\n' && *p != 0)
     973            p++;
     974          break;
     975        case '(':
     976          /* Subshell, equation, or lexical function argument start */
     977          p = parse_char (&token, 1);
     978          UPDATE_TOKEN;
     979          paren_level++;
     980          break;
     981        case ')':
     982          /* Close out a paren level */
     983          p = parse_char (&token, 1);
     984          UPDATE_TOKEN;
     985          paren_level--;
     986          /* TODO: Should we diagnose if paren_level goes negative? */
     987          break;
     988        case '&':
     989          if (isalpha (p[1]) && !vms_unix_simulation)
     990            {
     991              /* VMS symbol substitution */
     992              p = parse_text (&token, 0);
     993              token.use_cmd_file = 1;
     994              UPDATE_TOKEN;
     995              break;
     996            }
     997          if (use_pipe_cmd == nopipe)
     998            use_pipe_cmd = add_pipe;
     999          if (p[1] != '&')
     1000            p = parse_char (&token, 1);
     1001          else
     1002            p = parse_char (&token, 2);
     1003          UPDATE_TOKEN;
     1004          break;
     1005        case '|':
     1006          if (use_pipe_cmd == nopipe)
     1007            use_pipe_cmd = add_pipe;
     1008          if (p[1] != '|')
     1009            p = parse_char (&token, 1);
     1010          else
     1011            p = parse_char (&token, 2);
     1012          UPDATE_TOKEN;
     1013          break;
     1014        case ';':
     1015          /* Separator - convert to a pipe command. */
     1016          unix_echo_cmd = 0;
     1017        case '<':
     1018          if (use_pipe_cmd == nopipe)
     1019            use_pipe_cmd = add_pipe;
     1020          p = parse_char (&token, 1);
     1021          UPDATE_TOKEN;
     1022          break;
     1023        case '>':
     1024          if (use_pipe_cmd == nopipe)
     1025            use_pipe_cmd = add_pipe;
     1026          if (p[1] == '>')
     1027            {
     1028              /* Parsing would have been simple until support for the >>
     1029                 append redirect was added.
     1030                 Implementation needs:
     1031                 * if not exist output file create empty
     1032                 * open/append gnv$make_temp??? output_file
     1033                 * define/user sys$output gnv$make_temp???
     1034                 ** And all this done before the command previously tokenized.
     1035                 * command previously tokenized
     1036                 * close gnv$make_temp???
     1037              */
     1038              p = parse_char (&token, 2);
     1039              append_token = cmd_tkn_index;
     1040              token.use_cmd_file = 1;
     1041            }
     1042          else
     1043            p = parse_char (&token, 1);
     1044          UPDATE_TOKEN;
     1045          break;
     1046        case '/':
     1047          /* Unix path or VMS option start, read until non-path symbol */
     1048          if (assignment_hack != 0)
     1049            assignment_hack++;
     1050          if (assignment_hack > 2)
     1051            {
     1052              assignment_hack = 0;          /* Reset */
     1053              if (use_pipe_cmd == nopipe)   /* force pipe use */
     1054                use_pipe_cmd = add_pipe;
     1055              token_str[0] = ';';              /* add ; token */
     1056              token_str[1] = 0;
     1057              UPDATE_TOKEN;
     1058            }
     1059          p = parse_text (&token, assignment_hack);
     1060          UPDATE_TOKEN;
     1061          break;
     1062        case ':':
     1063          if ((p[1] == 0) || isspace (p[1]))
     1064            {
     1065              /* Unix Null command - treat as comment until next command */
     1066              unix_echo_cmd = 0;
     1067              p++;
     1068              while (*p != 0)
     1069                {
     1070                  if (*p == ';')
     1071                    {
     1072                      /* Remove Null command from pipeline */
     1073                      p++;
     1074                      break;
     1075                    }
     1076                  p++;
     1077                }
     1078              break;
     1079            }
     1080
     1081          /* String assignment */
     1082          /* := :== or : */
     1083          if (p[1] != '=')
     1084            p = parse_char (&token, 1);
     1085          else if (p[2] != '=')
     1086            p = parse_char (&token, 2);
     1087          else
     1088            p = parse_char (&token, 3);
     1089          UPDATE_TOKEN;
     1090          break;
     1091        case '=':
     1092          /* = or == */
     1093          /* If this is not an echo statement, this could be a shell
     1094             assignment.  VMS requires the target to be quoted if it
     1095             is not a macro substitution */
     1096          if (!unix_echo_cmd && vms_unix_simulation && (assignment_hack == 0))
     1097            assignment_hack = 1;
     1098          if (p[1] != '=')
     1099            p = parse_char (&token, 1);
     1100          else
     1101            p = parse_char (&token, 2);
     1102          UPDATE_TOKEN;
     1103          break;
     1104        case '+':
     1105        case '-':
     1106        case '*':
     1107          p = parse_char (&token, 1);
     1108          UPDATE_TOKEN;
     1109          break;
     1110        case '.':
     1111          /* .xxx. operation, VMS does not require the trailing . */
     1112          p = parse_text (&token, 0);
     1113          UPDATE_TOKEN;
     1114          break;
     1115        default:
     1116          /* Skip repetitive whitespace */
     1117          if (isspace (*p))
     1118            {
     1119              p = parse_char (&token, 1);
     1120
     1121              /* Force to a space or a tab */
     1122              if ((token_str[0] != ' ') ||
     1123                  (token_str[0] != '\t'))
     1124                token_str[0] = ' ';
     1125              UPDATE_TOKEN;
     1126
     1127              while (isspace (*p))
     1128                p++;
     1129              if (assignment_hack != 0)
     1130                assignment_hack++;
     1131              break;
     1132            }
     1133
     1134          if (assignment_hack != 0)
     1135            assignment_hack++;
     1136          if (assignment_hack > 2)
     1137            {
     1138              assignment_hack = 0;          /* Reset */
     1139              if (use_pipe_cmd == nopipe)   /* force pipe use */
     1140                use_pipe_cmd = add_pipe;
     1141              token_str[0] = ';';              /* add ; token */
     1142              token_str[1] = 0;
     1143              UPDATE_TOKEN;
     1144            }
     1145          p = parse_text (&token, assignment_hack);
     1146          if (strncasecmp (token.text, "echo", 4) == 0)
     1147            unix_echo_cmd = 1;
     1148          else if (strncasecmp (token.text, "pipe", 4) == 0)
     1149            use_pipe_cmd = dcl_pipe;
     1150          UPDATE_TOKEN;
     1151          break;
     1152        }
     1153    }
     1154
     1155  /* End up here with a list of tokens to build a command line.
     1156     Deal with errors detected during parsing.
     1157   */
     1158  if (token.cmd_errno != 0)
     1159    {
     1160      while (cmd_tokens[cmd_tkn_index] == NULL)
     1161        free (cmd_tokens[cmd_tkn_index++]);
     1162      child->cstatus = VMS_POSIX_EXIT_MASK | (MAKE_TROUBLE << 3);
     1163      child->vms_launch_status = SS$_ABORT;
     1164      /* TODO what is this "magic number" */
     1165      child->pid = 270163; /* Special built-in */
    4181166      child->efn = 0;
    419       child->cstatus = 1;
    420 
    421       DB (DB_JOBS, (_("BUILTIN [%s][%s]\n"), cmd, cmd+8));
    422 
    423       p = cmd + 8;
    424 
    425       if ((*(p) == 'c')
    426           && (*(p+1) == 'd')
    427           && ((*(p+2) == ' ') || (*(p+2) == '\t')))
    428         {
    429           p += 3;
    430           while ((*p == ' ') || (*p == '\t'))
    431             p++;
    432           DB (DB_JOBS, (_("BUILTIN CD %s\n"), p));
    433           if (chdir (p))
    434             return 0;
    435           else
    436             return 1;
    437         }
    438       else if ((*(p) == 'r')
    439           && (*(p+1) == 'm')
    440           && ((*(p+2) == ' ') || (*(p+2) == '\t')))
    441         {
    442           int in_arg;
    443 
    444           /* rm  */
    445           p += 3;
    446           while ((*p == ' ') || (*p == '\t'))
    447             p++;
    448           in_arg = 1;
    449 
    450           DB (DB_JOBS, (_("BUILTIN RM %s\n"), p));
    451           while (*p)
    452             {
    453               switch (*p)
    454                 {
    455                   case ' ':
    456                   case '\t':
    457                     if (in_arg)
    458                       {
    459                         *p++ = ';';
    460                         in_arg = 0;
    461                       }
    462                     break;
    463                   default:
    464                     break;
    465                 }
    466               p++;
    467             }
    468         }
     1167      errno = token.cmd_errno;
     1168      return 0;
     1169    }
     1170
     1171  /* Save any redirection to append file */
     1172  if (append_token != -1)
     1173    {
     1174      int file_token;
     1175      char * lastdot;
     1176      char * lastdir;
     1177      char * raw_append_file;
     1178      file_token = append_token;
     1179      file_token++;
     1180      if (isspace (cmd_tokens[file_token][0]))
     1181        file_token++;
     1182      raw_append_file = vmsify (cmd_tokens[file_token], 0);
     1183      /* VMS DCL needs a trailing dot if null file extension */
     1184      lastdot = strrchr(raw_append_file, '.');
     1185      lastdir = strrchr(raw_append_file, ']');
     1186      if (lastdir == NULL)
     1187        lastdir = strrchr(raw_append_file, '>');
     1188      if (lastdir == NULL)
     1189        lastdir = strrchr(raw_append_file, ':');
     1190      if ((lastdot == NULL) || (lastdot > lastdir))
     1191        {
     1192          append_file = xmalloc (strlen (raw_append_file) + 1);
     1193          strcpy (append_file, raw_append_file);
     1194          strcat (append_file, ".");
     1195        }
    4691196      else
    470         {
    471           printf(_("Unknown builtin command '%s'\n"), cmd);
    472           fflush(stdout);
    473           return 0;
    474         }
    475     }
    476 
    477   /* Create a *.com file if either the command is too long for
    478      lib$spawn, or the command contains a newline, or if redirection
    479      is desired. Forcing commands with newlines into DCLs allows to
    480      store search lists on user mode logicals.  */
    481 
    482   if (strlen (cmd) > MAXCMDLEN
    483       || (have_redirection != 0)
    484       || (have_newline != 0))
     1197        append_file = strdup(raw_append_file);
     1198    }
     1199
     1200  cmd_dsc = build_vms_cmd (cmd_tokens, use_pipe_cmd, append_token);
     1201  if (cmd_dsc->dsc$a_pointer == NULL)
     1202    {
     1203      if (cmd_dsc->dsc$w_length < 0)
     1204        {
     1205          free (cmd_dsc);
     1206          child->cstatus = VMS_POSIX_EXIT_MASK | (MAKE_TROUBLE << 3);
     1207          child->vms_launch_status = SS$_ABORT;
     1208          /* TODO what is this "magic number" */
     1209          child->pid = 270163; /* Special built-in */
     1210          child->efn = 0;
     1211          return 0;
     1212        }
     1213
     1214      /* Only a built-in or a null command - Still need to run term AST */
     1215      free (cmd_dsc);
     1216      child->cstatus = VMS_POSIX_EXIT_MASK;
     1217      child->vms_launch_status = SS$_NORMAL;
     1218      /* TODO what is this "magic number" */
     1219      child->pid = 270163; /* Special built-in */
     1220      child->efn = 0;
     1221      vmsHandleChildTerm (child);
     1222      return 1;
     1223    }
     1224
     1225  if (cmd_dsc->dsc$w_length > MAX_DCL_LINE_LENGTH)
     1226    token.use_cmd_file = 1;
     1227
     1228  DB(DB_JOBS, (_("DCL: %s\n"), cmd_dsc->dsc$a_pointer));
     1229
     1230  /* Enforce the creation of a command file if "vms_always_use_cmd_file" is
     1231     non-zero.
     1232     Further, this way DCL reads the input stream and therefore does
     1233     'forced' symbol substitution, which it doesn't do for one-liners when
     1234     they are 'lib$spawn'ed.
     1235
     1236     Otherwise the behavior is:
     1237
     1238     Create a *.com file if either the command is too long for
     1239     lib$spawn, or if a redirect appending to a file is desired, or
     1240     symbol substitition.
     1241  */
     1242
     1243  if (vms_always_use_cmd_file || token.use_cmd_file)
    4851244    {
    4861245      FILE *outfile;
    487       char c;
    488       char *sep;
    489       int alevel = 0;   /* apostrophe level */
    490 
    491       if (strlen (cmd) == 0)
    492         {
    493           printf (_("Error, empty command\n"));
    494           fflush (stdout);
    495           return 0;
    496         }
    497 
    498       outfile = open_tmpfile (&child->comname, "sys$scratch:CMDXXXXXX.COM");
     1246      int cmd_len;
     1247
     1248      outfile = output_tmpfile (&child->comname,
     1249                                "sys$scratch:gnv$make_cmdXXXXXX.com");
     1250      /*                                          012345678901234567890 */
    4991251      if (outfile == 0)
    500         pfatal_with_name (_("fopen (temporary file)"));
     1252        pfatal_with_name (_("fopen (temporary file)"));
    5011253      comnamelen = strlen (child->comname);
    5021254
    503       if (ifile[0])
    504         {
    505           fprintf (outfile, "$ assign/user %s sys$input\n", ifile);
    506           DB (DB_JOBS, (_("Redirected input from %s\n"), ifile));
    507           ifiledsc.dsc$w_length = 0;
    508         }
    509 
    510       if (efile[0])
    511         {
    512           fprintf (outfile, "$ define sys$error %s\n", efile);
    513           DB (DB_JOBS, (_("Redirected error to %s\n"), efile));
    514           efiledsc.dsc$w_length = 0;
    515         }
    516 
    517       if (ofile[0])
    518         {
    519           if (have_append)
    520             {
    521               fprintf (outfile, "$ set noon\n");
    522               fprintf (outfile, "$ define sys$output %.*s\n", comnamelen-3, child->comname);
    523               DB (DB_JOBS, (_("Append output to %s\n"), ofile));
    524               ofiledsc.dsc$w_length = 0;
    525             }
    526           else
    527             {
    528               fprintf (outfile, "$ define sys$output %s\n", ofile);
    529               DB (DB_JOBS, (_("Redirected output to %s\n"), ofile));
    530               ofiledsc.dsc$w_length = 0;
    531             }
    532         }
    533 
    534       p = sep = q = cmd;
    535       for (c = '\n'; c; c = *q++)
    536         {
    537           switch (c)
    538             {
    539             case '\n':
    540               /* At a newline, skip any whitespace around a leading $
    541                  from the command and issue exactly one $ into the DCL. */
    542               while (isspace ((unsigned char)*p))
    543                 p++;
    544               if (*p == '$')
    545                 p++;
    546               while (isspace ((unsigned char)*p))
    547                 p++;
    548               fwrite (p, 1, q - p, outfile);
    549               fputc ('$', outfile);
    550               fputc (' ', outfile);
    551               /* Reset variables. */
    552               p = sep = q;
    553               break;
    554 
    555               /* Nice places for line breaks are after strings, after
    556                  comma or space and before slash. */
    557             case '"':
    558               q = vms_handle_apos (q);
    559               sep = q;
    560               break;
    561             case ',':
    562             case ' ':
    563               sep = q;
    564               break;
    565             case '/':
    566             case '\0':
    567               sep = q - 1;
    568               break;
    569             default:
    570               break;
    571             }
    572           if (sep - p > 78)
    573             {
    574               /* Enough stuff for a line. */
    575               fwrite (p, 1, sep - p, outfile);
    576               p = sep;
    577               if (*sep)
    578                 {
    579                   /* The command continues.  */
    580                   fputc ('-', outfile);
    581                 }
    582               fputc ('\n', outfile);
    583             }
    584         }
    585 
    586       if (*p)
    587         {
    588           fwrite (p, 1, --q - p, outfile);
    589       fputc ('\n', outfile);
    590         }
    591 
    592       if (have_append)
    593         {
    594           fprintf (outfile, "$ deassign sys$output ! 'f$verify(0)\n");
    595           fprintf (outfile, "$ append:=append\n");
    596           fprintf (outfile, "$ delete:=delete\n");
    597           fprintf (outfile, "$ append/new %.*s %s\n", comnamelen-3, child->comname, ofile);
    598           fprintf (outfile, "$ delete %.*s;*\n", comnamelen-3, child->comname);
    599           DB (DB_JOBS, (_("Append %.*s and cleanup\n"), comnamelen-3, child->comname));
    600         }
     1255      /* The whole DCL "script" is executed as one action, and it behaves as
     1256         any DCL "script", that is errors stop it but warnings do not. Usually
     1257         the command on the last line, defines the exit code.  However, with
     1258         redirections there is a prolog and possibly an epilog to implement
     1259         the redirection.  Both are part of the script which is actually
     1260         executed. So if the redirection encounters an error in the prolog,
     1261         the user actions will not run; if in the epilog, the user actions
     1262         ran, but output is not captured. In both error cases, the error of
     1263         redirection is passed back and not the exit code of the actions. The
     1264         user should be able to enable DCL "script" verification with "set
     1265         verify". However, the prolog and epilog commands are not shown. Also,
     1266         if output redirection is used, the verification output is redirected
     1267         into that file as well. */
     1268      fprintf (outfile, "$ gnv$$make_verify = \"''f$verify(0)'\"\n");
     1269      fprintf (outfile, "$ gnv$$make_pid = f$getjpi(\"\",\"pid\")\n");
     1270      fprintf (outfile, "$ on error then $ goto gnv$$make_error\n");
     1271
     1272      /* Handle append redirection */
     1273      if (append_file != NULL)
     1274        {
     1275          /* If file does not exist, create it */
     1276          fprintf (outfile,
     1277                   "$ gnv$$make_al = \"gnv$$make_append''gnv$$make_pid'\"\n");
     1278          fprintf (outfile,
     1279                   "$ if f$search(\"%s\") .eqs. \"\" then create %s\n",
     1280                   append_file, append_file);
     1281
     1282          fprintf (outfile,
     1283                   "$ open/append 'gnv$$make_al' %s\n", append_file);
     1284
     1285          /* define sys$output to that file */
     1286          fprintf (outfile,
     1287                   "$ define/user sys$output 'gnv$$make_al'\n");
     1288          DB (DB_JOBS, (_("Append output to %s\n"), append_file));
     1289          free(append_file);
     1290        }
     1291
     1292      fprintf (outfile, "$ gnv$$make_verify = f$verify(gnv$$make_verify)\n");
     1293
     1294      /* TODO:
     1295         Only for ONESHELL there will be several commands separated by
     1296         '\n'. But there can always be multiple continuation lines.
     1297      */
     1298
     1299      fprintf (outfile, "%s\n", cmd_dsc->dsc$a_pointer);
     1300      fprintf (outfile, "$ gnv$$make_status_2 = $status\n");
     1301      fprintf (outfile, "$ goto gnv$$make_exit\n");
     1302
     1303      /* Exit and clean up */
     1304      fprintf (outfile, "$ gnv$$make_error: ! 'f$verify(0)\n");
     1305      fprintf (outfile, "$ gnv$$make_status_2 = $status\n");
     1306
     1307      if (append_token != -1)
     1308        {
     1309          fprintf (outfile, "$ deassign sys$output\n");
     1310          fprintf (outfile, "$ close 'gnv$$make_al'\n");
     1311
     1312          DB (DB_JOBS,
     1313              (_("Append %.*s and cleanup\n"), comnamelen-3, child->comname));
     1314        }
     1315      fprintf (outfile, "$ gnv$$make_exit: ! 'f$verify(0)\n");
     1316      fprintf (outfile,
     1317             "$ exit 'gnv$$make_status_2' + (0*f$verify(gnv$$make_verify))\n");
    6011318
    6021319      fclose (outfile);
    6031320
    604       sprintf (cmd, "$ @%s", child->comname);
    605 
    606       DB (DB_JOBS, (_("Executing %s instead\n"), cmd));
    607     }
    608 
    609   cmddsc.dsc$w_length = strlen(cmd);
    610   cmddsc.dsc$a_pointer = cmd;
    611   cmddsc.dsc$b_dtype = DSC$K_DTYPE_T;
    612   cmddsc.dsc$b_class = DSC$K_CLASS_S;
     1321      free (cmd_dsc->dsc$a_pointer);
     1322      cmd_dsc->dsc$a_pointer = xmalloc (256 + 4);
     1323      sprintf (cmd_dsc->dsc$a_pointer, "$ @%s", child->comname);
     1324      cmd_dsc->dsc$w_length = strlen (cmd_dsc->dsc$a_pointer);
     1325
     1326      DB (DB_JOBS, (_("Executing %s instead\n"), child->comname));
     1327    }
    6131328
    6141329  child->efn = 0;
    6151330  while (child->efn < 32 || child->efn > 63)
    6161331    {
    617       status = lib$get_ef ((unsigned long *)&child->efn);
    618       if (!(status & 1))
     1332      status = LIB$GET_EF ((unsigned long *)&child->efn);
     1333      if (!$VMS_STATUS_SUCCESS (status))
    6191334        {
    6201335          if (child->comname)
     
    6281343    }
    6291344
    630   sys$clref (child->efn);
     1345  SYS$CLREF (child->efn);
    6311346
    6321347  vms_jobsefnmask |= (1 << (child->efn - 32));
    6331348
    634 /*
    635              LIB$SPAWN  [command-string]
    636                         [,input-file]
    637                         [,output-file]
    638                         [,flags]
    639                         [,process-name]
    640                         [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
    641                         [,AST-address] [,varying-AST-argument]
    642                         [,prompt-string] [,cli] [,table]
    643 */
     1349  /* Export the child environment into DCL symbols */
     1350  if (child->environment != 0)
     1351    {
     1352      char **ep = child->environment;
     1353      while (*ep != 0)
     1354        {
     1355          vms_putenv_symbol (*ep);
     1356          *ep++;
     1357        }
     1358    }
     1359
     1360  /*
     1361    LIB$SPAWN  [command-string]
     1362    [,input-file]
     1363    [,output-file]
     1364    [,flags]
     1365    [,process-name]
     1366    [,process-id] [,completion-status-address] [,byte-integer-event-flag-num]
     1367    [,AST-address] [,varying-AST-argument]
     1368    [,prompt-string] [,cli] [,table]
     1369  */
    6441370
    6451371#ifndef DONTWAITFORCHILD
    646 /*
    647  *      Code to make ctrl+c and ctrl+y working.
    648  *      The problem starts with the synchronous case where after lib$spawn is
    649  *      called any input will go to the child. But with input re-directed,
    650  *      both control characters won't make it to any of the programs, neither
    651  *      the spawning nor to the spawned one. Hence the caller needs to spawn
    652  *      with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
    653  *      has to follow to simulate the wanted synchronous behaviour.
    654  *      The next problem is ctrl+y which isn't caught by the crtl and
    655  *      therefore isn't converted to SIGQUIT (for a signal handler which is
    656  *      already established). The only way to catch ctrl+y, is an AST
    657  *      assigned to the input channel. But ctrl+y handling of DCL needs to be
    658  *      disabled, otherwise it will handle it. Not to mention the previous
    659  *      ctrl+y handling of DCL needs to be re-established before make exits.
    660  *      One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
    661  *      make it to the signal handler after the child "normally" terminates.
    662  *      This isn't enough. It seems reasonable for simple command lines like
    663  *      a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
    664  *      spawning make. Therefore we need to abort the process in the AST.
    665  *
    666  *      Prior to the spawn it is checked if an AST is already set up for
    667  *      ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
    668  *      this will work except if make is run in a batch environment, but there
    669  *      nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
    670  *      is disabled and an exit handler is established to re-enable it.
    671  *      If the user interrupts with ctrl+y, the assigned AST will fire, force
    672  *      an abort to the subprocess and signal SIGQUIT, which will be caught by
    673  *      the already established handler and will bring us back to common code.
    674  *      After the spawn (now /nowait) a sys$waitfr simulates the /wait and
    675  *      enables the ctrl+y be delivered to this code. And the ctrl+c too,
    676  *      which the crtl converts to SIGINT and which is caught by the common
    677  *      signal handler. Because signals were blocked before entering this code
    678  *      sys$waitfr will always complete and the SIGQUIT will be processed after
    679  *      it (after termination of the current block, somewhere in common code).
    680  *      And SIGINT too will be delayed. That is ctrl+c can only abort when the
    681  *      current command completes. Anyway it's better than nothing :-)
    682  */
     1372  /*
     1373   * Code to make ctrl+c and ctrl+y working.
     1374   * The problem starts with the synchronous case where after lib$spawn is
     1375   * called any input will go to the child. But with input re-directed,
     1376   * both control characters won't make it to any of the programs, neither
     1377   * the spawning nor to the spawned one. Hence the caller needs to spawn
     1378   * with CLI$M_NOWAIT to NOT give up the input focus. A sys$waitfr
     1379   * has to follow to simulate the wanted synchronous behaviour.
     1380   * The next problem is ctrl+y which isn't caught by the crtl and
     1381   * therefore isn't converted to SIGQUIT (for a signal handler which is
     1382   * already established). The only way to catch ctrl+y, is an AST
     1383   * assigned to the input channel. But ctrl+y handling of DCL needs to be
     1384   * disabled, otherwise it will handle it. Not to mention the previous
     1385   * ctrl+y handling of DCL needs to be re-established before make exits.
     1386   * One more: At the time of LIB$SPAWN signals are blocked. SIGQUIT will
     1387   * make it to the signal handler after the child "normally" terminates.
     1388   * This isn't enough. It seems reasonable for simple command lines like
     1389   * a 'cc foobar.c' spawned in a subprocess but it is unacceptable for
     1390   * spawning make. Therefore we need to abort the process in the AST.
     1391   *
     1392   * Prior to the spawn it is checked if an AST is already set up for
     1393   * ctrl+y, if not one is set up for a channel to SYS$COMMAND. In general
     1394   * this will work except if make is run in a batch environment, but there
     1395   * nobody can press ctrl+y. During the setup the DCL handling of ctrl+y
     1396   * is disabled and an exit handler is established to re-enable it.
     1397   * If the user interrupts with ctrl+y, the assigned AST will fire, force
     1398   * an abort to the subprocess and signal SIGQUIT, which will be caught by
     1399   * the already established handler and will bring us back to common code.
     1400   * After the spawn (now /nowait) a sys$waitfr simulates the /wait and
     1401   * enables the ctrl+y be delivered to this code. And the ctrl+c too,
     1402   * which the crtl converts to SIGINT and which is caught by the common
     1403   * signal handler. Because signals were blocked before entering this code
     1404   * sys$waitfr will always complete and the SIGQUIT will be processed after
     1405   * it (after termination of the current block, somewhere in common code).
     1406   * And SIGINT too will be delayed. That is ctrl+c can only abort when the
     1407   * current command completes. Anyway it's better than nothing :-)
     1408   */
    6831409
    6841410  if (!setupYAstTried)
    6851411    tryToSetupYAst();
    686   status = lib$spawn (&cmddsc,                                  /* cmd-string  */
    687                       (ifiledsc.dsc$w_length == 0)?0:&ifiledsc, /* input-file  */
    688                       (ofiledsc.dsc$w_length == 0)?0:&ofiledsc, /* output-file */
    689                       &spflags,                                 /* flags  */
    690                       &pnamedsc,                                /* proc name  */
    691                       &child->pid, &child->cstatus, &child->efn,
    692                       0, 0,
    693                       0, 0, 0);
    694   if (status & 1)
    695     {
    696       status= sys$waitfr (child->efn);
    697       vmsHandleChildTerm(child);
     1412  child->vms_launch_status = lib$spawn (cmd_dsc,               /* cmd-string */
     1413                     NULL, /* input-file */
     1414                     NULL, /* output-file */
     1415                     &spflags,                                 /* flags */
     1416                     &pnamedsc,                                /* proc name */
     1417                     &child->pid, &child->cstatus, &child->efn,
     1418                     0, 0,
     1419                     0, 0, 0);
     1420
     1421  status = child->vms_launch_status;
     1422  if ($VMS_STATUS_SUCCESS (status))
     1423    {
     1424      status = sys$waitfr (child->efn);
     1425      vmsHandleChildTerm (child);
    6981426    }
    6991427#else
    700   status = lib$spawn (&cmddsc,
    701                       (ifiledsc.dsc$w_length == 0)?0:&ifiledsc,
    702                       (ofiledsc.dsc$w_length == 0)?0:&ofiledsc,
    703                       &spflags,
    704                       &pnamedsc,
    705                       &child->pid, &child->cstatus, &child->efn,
    706                       vmsHandleChildTerm, child,
    707                       0, 0, 0);
     1428  child->vms_launch_status = lib$spawn (cmd_dsc,
     1429                      NULL,
     1430                      NULL,
     1431                      &spflags,
     1432                      &pnamedsc,
     1433                      &child->pid, &child->cstatus, &child->efn,
     1434                      vmsHandleChildTerm, child,
     1435                      0, 0, 0);
     1436   status = child->vms_launch_status;
    7081437#endif
    7091438
    710   if (!(status & 1))
    711     {
    712       printf (_("Error spawning, %d\n") ,status);
    713       fflush (stdout);
     1439  /* Free the pointer if not a command file */
     1440  if (!vms_always_use_cmd_file && !token.use_cmd_file)
     1441    free (cmd_dsc->dsc$a_pointer);
     1442  free (cmd_dsc);
     1443
     1444  if (!$VMS_STATUS_SUCCESS (status))
     1445    {
    7141446      switch (status)
    7151447        {
    716         case 0x1c:
     1448        case SS$_EXQUOTA:
    7171449          errno = EPROCLIM;
    7181450          break;
     
    7221454    }
    7231455
     1456  /* Restore the VMS symbols that were changed */
     1457  if (child->environment != 0)
     1458    {
     1459      char **ep = child->environment;
     1460      while (*ep != 0)
     1461        {
     1462          vms_restore_symbol (*ep);
     1463          *ep++;
     1464        }
     1465    }
     1466
    7241467  return (status & 1);
    7251468}
  • trunk/src/kmk/vpath.c

    r2592 r3140  
    11/* Implementation of pattern-matching file search paths for GNU Make.
    2 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
    3 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
    4 2010 Free Software Foundation, Inc.
     2Copyright (C) 1988-2016 Free Software Foundation, Inc.
    53This file is part of GNU Make.
    64
     
    1715this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1816
    19 #include "make.h"
     17#include "makeint.h"
    2018#include "filedef.h"
    2119#include "variable.h"
     
    2927struct vpath
    3028  {
    31     struct vpath *next; /* Pointer to next struct in the linked list.  */
     29    struct vpath *next; /* Pointer to next struct in the linked list.  */
    3230    const char *pattern;/* The pattern to match.  */
    33     const char *percent;/* Pointer into `pattern' where the `%' is.  */
     31    const char *percent;/* Pointer into 'pattern' where the '%' is.  */
    3432    unsigned int patlen;/* Length of the pattern.  */
    3533    const char **searchpath; /* Null-terminated list of directories.  */
     
    5654
    5755void
    58 build_vpath_lists ()
     56build_vpath_lists (void)
    5957{
    6058  register struct vpath *new = 0;
     
    9896      char gp[] = "%";
    9997
    100       /* Empty `vpaths' so the new one will have no next, and `vpaths'
    101         will still be nil if P contains no existing directories.  */
     98      /* Empty 'vpaths' so the new one will have no next, and 'vpaths'
     99        will still be nil if P contains no existing directories.  */
    102100      vpaths = 0;
    103101
     
    106104
    107105      /* Store the created path as the general path,
    108         and restore the old list of vpaths.  */
     106        and restore the old list of vpaths.  */
    109107      general_vpath = vpaths;
    110108      vpaths = save_vpaths;
     
    135133      char gp[] = "%";
    136134
    137       /* Empty `vpaths' so the new one will have no next, and `vpaths'
    138         will still be nil if P contains no existing directories.  */
     135      /* Empty 'vpaths' so the new one will have no next, and 'vpaths'
     136        will still be nil if P contains no existing directories.  */
    139137      vpaths = 0;
    140138
     
    143141
    144142      /* Store the created path as the GPATH,
    145         and restore the old list of vpaths.  */
     143        and restore the old list of vpaths.  */
    146144      gpaths = vpaths;
    147145      vpaths = save_vpaths;
     
    161159   pattern.  If PATTERN is nil, remove all VPATH listings.  Existing
    162160   and readable directories that are not "." given in the DIRPATH
    163    separated by the path element separator (defined in make.h) are
     161   separated by the path element separator (defined in makeint.h) are
    164162   loaded into the directory hash table if they are not there already
    165163   and put in the VPATH searchpath for the given pattern with trailing
     
    190188      path = vpaths;
    191189      while (path != 0)
    192         {
    193           struct vpath *next = path->next;
    194 
    195           if (pattern == 0
    196               || (((percent == 0 && path->percent == 0)
    197                    || (percent - pattern == path->percent - path->pattern))
    198                   && streq (pattern, path->pattern)))
    199             {
    200               /* Remove it from the linked list.  */
    201               if (lastpath == 0)
    202                 vpaths = path->next;
    203               else
    204                 lastpath->next = next;
    205 
    206               /* Free its unused storage.  */
     190        {
     191          struct vpath *next = path->next;
     192
     193          if (pattern == 0
     194              || (((percent == 0 && path->percent == 0)
     195                   || (percent - pattern == path->percent - path->pattern))
     196                  && streq (pattern, path->pattern)))
     197            {
     198              /* Remove it from the linked list.  */
     199              if (lastpath == 0)
     200                vpaths = path->next;
     201              else
     202                lastpath->next = next;
     203
     204              /* Free its unused storage.  */
    207205              /* MSVC erroneously warns without a cast here.  */
    208               free ((void *)path->searchpath);
    209               free (path);
    210             }
    211           else
    212             lastpath = path;
    213 
    214           path = next;
    215         }
     206              free ((void *)path->searchpath);
     207              free (path);
     208            }
     209          else
     210            lastpath = path;
     211
     212          path = next;
     213        }
    216214
    217215      return;
     
    219217
    220218#ifdef WINDOWS32
    221     convert_vpath_to_windows32(dirpath, ';');
     219    convert_vpath_to_windows32 (dirpath, ';');
    222220#endif
    223221
    224222  /* Skip over any initial separators and blanks.  */
    225   while (*dirpath == PATH_SEPARATOR_CHAR || isblank ((unsigned char)*dirpath))
     223  while (STOP_SET (*dirpath, MAP_BLANK|MAP_PATHSEP))
    226224    ++dirpath;
    227225
     
    233231  p = dirpath;
    234232  while (*p != '\0')
    235     if (*p++ == PATH_SEPARATOR_CHAR || isblank ((unsigned char)*p))
     233    if (STOP_SET (*p++, MAP_BLANK|MAP_PATHSEP))
    236234      ++maxelem;
    237235
     
    250248      while (*p != '\0'
    251249#if defined(HAVE_DOS_PATHS) && (PATH_SEPARATOR_CHAR == ':')
    252              /* Platforms whose PATH_SEPARATOR_CHAR is ':' and which
    253                 also define HAVE_DOS_PATHS would like us to recognize
    254                 colons after the drive letter in the likes of
    255                 "D:/foo/bar:C:/xyzzy".  */
    256              && (*p != PATH_SEPARATOR_CHAR
    257                 || (p == v + 1 && (p[1] == '/' || p[1] == '\\')))
     250             /* Platforms whose PATH_SEPARATOR_CHAR is ':' and which
     251                also define HAVE_DOS_PATHS would like us to recognize
     252                colons after the drive letter in the likes of
     253                "D:/foo/bar:C:/xyzzy".  */
     254             && (*p != PATH_SEPARATOR_CHAR
     255                || (p == v + 1 && (p[1] == '/' || p[1] == '\\')))
    258256#else
    259              && *p != PATH_SEPARATOR_CHAR
    260 #endif
    261              && !isblank ((unsigned char)*p))
    262         ++p;
     257             && *p != PATH_SEPARATOR_CHAR
     258#endif
     259             && !ISBLANK (*p))
     260        ++p;
    263261
    264262      len = p - v;
    265263      /* Make sure there's no trailing slash,
    266         but still allow "/" as a directory.  */
     264        but still allow "/" as a directory.  */
    267265#if defined(__MSDOS__) || defined(__EMX__) || defined(HAVE_DOS_PATHS)
    268266      /* We need also to leave alone a trailing slash in "d:/".  */
     
    270268#endif
    271269      if (len > 1 && p[-1] == '/')
    272         --len;
     270        --len;
    273271
    274272      /* Put the directory on the vpath list.  */
    275273      if (len > 1 || *v != '.')
    276         {
     274        {
    277275          vpath[elem++] = dir_name (strcache_add_len (v, len));
    278276          if (len > maxvpath)
    279277            maxvpath = len;
    280         }
     278        }
    281279
    282280      /* Skip over separators and blanks between entries.  */
    283       while (*p == PATH_SEPARATOR_CHAR || isblank ((unsigned char)*p))
    284         ++p;
     281      while (STOP_SET (*p, MAP_BLANK|MAP_PATHSEP))
     282        ++p;
    285283    }
    286284
     
    289287      struct vpath *path;
    290288      /* ELEM is now incremented one element past the last
    291         entry, to where the nil-pointer terminator goes.
    292         Usually this is maxelem - 1.  If not, shrink down.  */
     289        entry, to where the nil-pointer terminator goes.
     290        Usually this is maxelem - 1.  If not, shrink down.  */
    293291      if (elem < (maxelem - 1))
    294         vpath = (const char **)xrealloc (vpath, (elem+1) * sizeof (const char *));
     292        vpath = xrealloc ((void *)vpath, (elem+1) * sizeof (const char *)); /* bird: Weird cast for msc. */
    295293
    296294      /* Put the nil-pointer terminator on the end of the VPATH list.  */
     
    322320gpath_search (const char *file, unsigned int len)
    323321{
    324   const char **gp;
    325 
    326322  if (gpaths && (len <= gpaths->maxlen))
    327     for (gp = gpaths->searchpath; *gp != NULL; ++gp)
    328       if (strneq (*gp, file, len) && (*gp)[len] == '\0')
    329         return 1;
     323    {
     324      const char **gp;
     325      for (gp = gpaths->searchpath; *gp != NULL; ++gp)
     326        if (strneq (*gp, file, len) && (*gp)[len] == '\0')
     327          return 1;
     328    }
    330329
    331330  return 0;
     
    351350  unsigned int maxvpath = path->maxlen;
    352351  unsigned int i;
    353   unsigned int flen, vlen, name_dplen;
     352  unsigned int flen, name_dplen;
    354353  int exists = 0;
    355354
     
    372371  /* We need the rightmost slash or backslash.  */
    373372  {
    374     const char *bslash = strrchr(file, '\\');
     373    const char *bslash = strrchr (file, '\\');
    375374    if (!n || bslash > n)
    376375      n = bslash;
     
    391390    {
    392391      int exists_in_cache = 0;
    393       char *p;
    394 
    395       p = name;
     392      char *p = name;
     393      unsigned int vlen = strlen (vpath[i]);
    396394
    397395      /* Put the next VPATH entry into NAME at P and increment P past it.  */
    398       vlen = strlen (vpath[i]);
    399396      memcpy (p, vpath[i], vlen);
    400397      p += vlen;
     
    402399      /* Add the directory prefix already in *FILE.  */
    403400      if (name_dplen > 0)
    404         {
     401        {
    405402#ifndef VMS
    406           *p++ = '/';
    407 #endif
    408           memcpy (p, file, name_dplen);
    409           p += name_dplen;
    410         }
     403          *p++ = '/';
     404#else
     405          /* VMS: if this is not in VMS format, treat as Unix format */
     406          if ((*p != ':') && (*p != ']') && (*p != '>'))
     407            *p++ = '/';
     408#endif
     409          memcpy (p, file, name_dplen);
     410          p += name_dplen;
     411        }
    411412
    412413#ifdef HAVE_DOS_PATHS
    413414      /* Cause the next if to treat backslash and slash alike.  */
    414415      if (p != name && p[-1] == '\\' )
    415         p[-1] = '/';
     416        p[-1] = '/';
    416417#endif
    417418      /* Now add the name-within-directory at the end of NAME.  */
    418419#ifndef VMS
    419420      if (p != name && p[-1] != '/')
    420         {
    421           *p = '/';
    422           memcpy (p + 1, filename, flen + 1);
    423         }
     421        {
     422          *p = '/';
     423          memcpy (p + 1, filename, flen + 1);
     424        }
    424425      else
    425 #endif
    426         memcpy (p, filename, flen + 1);
     426#else
     427      /* VMS use a slash if no directory terminator present */
     428      if (p != name && p[-1] != '/' && p[-1] != ':' &&
     429          p[-1] != '>' && p[-1] != ']')
     430        {
     431          *p = '/';
     432          memcpy (p + 1, filename, flen + 1);
     433        }
     434      else
     435#endif
     436        memcpy (p, filename, flen + 1);
    427437
    428438      /* Check if the file is mentioned in a makefile.  If *FILE is not
    429         a target, that is enough for us to decide this file exists.
    430         If *FILE is a target, then the file must be mentioned in the
    431         makefile also as a target to be chosen.
    432 
    433         The restriction that *FILE must not be a target for a
    434         makefile-mentioned file to be chosen was added by an
    435         inadequately commented change in July 1990; I am not sure off
    436         hand what problem it fixes.
    437 
    438         In December 1993 I loosened this restriction to allow a file
    439         to be chosen if it is mentioned as a target in a makefile.  This
    440         seem logical.
     439        a target, that is enough for us to decide this file exists.
     440        If *FILE is a target, then the file must be mentioned in the
     441        makefile also as a target to be chosen.
     442
     443        The restriction that *FILE must not be a target for a
     444        makefile-mentioned file to be chosen was added by an
     445        inadequately commented change in July 1990; I am not sure off
     446        hand what problem it fixes.
     447
     448        In December 1993 I loosened this restriction to allow a file
     449        to be chosen if it is mentioned as a target in a makefile.  This
     450        seem logical.
    441451
    442452         Special handling for -W / -o: make sure we preserve the special
     
    448458      */
    449459      {
    450         struct file *f = lookup_file (name);
    451         if (f != 0)
     460        struct file *f = lookup_file (name);
     461        if (f != 0)
    452462          {
    453463            exists = not_target || f->is_target;
     
    462472
    463473      if (!exists)
    464         {
    465           /* That file wasn't mentioned in the makefile.
    466              See if it actually exists.  */
     474        {
     475          /* That file wasn't mentioned in the makefile.
     476             See if it actually exists.  */
    467477
    468478#ifdef VMS
    469           exists_in_cache = exists = dir_file_exists_p (vpath[i], filename);
     479          /* For VMS syntax just use the original vpath */
     480          if (*p != '/')
     481            exists_in_cache = exists = dir_file_exists_p (vpath[i], filename);
     482          else
     483#endif
     484            {
     485              /* Clobber a null into the name at the last slash.
     486                 Now NAME is the name of the directory to look in.  */
     487              *p = '\0';
     488              /* We know the directory is in the hash table now because either
     489                 construct_vpath_list or the code just above put it there.
     490                 Does the file we seek exist in it?  */
     491              exists_in_cache = exists = dir_file_exists_p (name, filename);
     492            }
     493        }
     494
     495      if (exists)
     496        {
     497          /* The file is in the directory cache.
     498             Now check that it actually exists in the filesystem.
     499             The cache may be out of date.  When vpath thinks a file
     500             exists, but stat fails for it, confusion results in the
     501             higher levels.  */
     502
     503          struct stat st;
     504
     505#ifndef VMS
     506          /* Put the slash back in NAME.  */
     507          *p = '/';
    470508#else
    471           /* Clobber a null into the name at the last slash.
    472              Now NAME is the name of the directory to look in.  */
    473           *p = '\0';
    474 
    475           /* We know the directory is in the hash table now because either
    476              construct_vpath_list or the code just above put it there.
    477              Does the file we seek exist in it?  */
    478           exists_in_cache = exists = dir_file_exists_p (name, filename);
    479 #endif
    480         }
    481 
    482       if (exists)
    483         {
    484           /* The file is in the directory cache.
    485              Now check that it actually exists in the filesystem.
    486              The cache may be out of date.  When vpath thinks a file
    487              exists, but stat fails for it, confusion results in the
    488              higher levels.  */
    489 
    490           struct stat st;
    491 
    492 #ifndef VMS
    493           /* Put the slash back in NAME.  */
    494           *p = '/';
    495 #endif
    496 
    497           if (exists_in_cache)  /* Makefile-mentioned file need not exist.  */
    498             {
     509          /* If the slash was removed, put it back */
     510          if (*p == 0)
     511            *p = '/';
     512#endif
     513
     514          if (exists_in_cache)  /* Makefile-mentioned file need not exist.  */
     515            {
    499516              int e;
    500517
     
    526543
    527544          return strcache_add_len (name, (p + 1 - name) + flen);
    528         }
     545        }
    529546    }
    530547
     
    611628
    612629      for (i = 0; v->searchpath[i] != 0; ++i)
    613         printf ("%s%c", v->searchpath[i],
    614                 v->searchpath[i + 1] == 0 ? '\n' : PATH_SEPARATOR_CHAR);
     630        printf ("%s%c", v->searchpath[i],
     631                v->searchpath[i + 1] == 0 ? '\n' : PATH_SEPARATOR_CHAR);
    615632    }
    616633
    617634  if (vpaths == 0)
    618     puts (_("# No `vpath' search paths."));
     635    puts (_("# No 'vpath' search paths."));
    619636  else
    620     printf (_("\n# %u `vpath' search paths.\n"), nvpaths);
     637    printf (_("\n# %u 'vpath' search paths.\n"), nvpaths);
    621638
    622639  if (general_vpath == 0)
    623     puts (_("\n# No general (`VPATH' variable) search path."));
     640    puts (_("\n# No general ('VPATH' variable) search path."));
    624641  else
    625642    {
     
    627644      unsigned int i;
    628645
    629       fputs (_("\n# General (`VPATH' variable) search path:\n# "), stdout);
     646      fputs (_("\n# General ('VPATH' variable) search path:\n# "), stdout);
    630647
    631648      for (i = 0; path[i] != 0; ++i)
    632         printf ("%s%c", path[i],
    633                 path[i + 1] == 0 ? '\n' : PATH_SEPARATOR_CHAR);
     649        printf ("%s%c", path[i],
     650                path[i + 1] == 0 ? '\n' : PATH_SEPARATOR_CHAR);
    634651    }
    635652}
  • trunk/src/kmk/w32/Makefile.am

    r2591 r3140  
    11# Makefile.am to create libw32.a for mingw32 host.
    2 # Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    3 # 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2# Copyright (C) 1997-2016 Free Software Foundation, Inc.
    43# This file is part of GNU Make.
    54#
     
    1716# this program.  If not, see <http://www.gnu.org/licenses/>.
    1817
     18AUTOMAKE_OPTIONS = subdir-objects
     19
    1920noinst_LIBRARIES = libw32.a
    2021
    2122libw32_a_SOURCES =  subproc/misc.c subproc/sub_proc.c subproc/w32err.c \
    22                     pathstuff.c
     23                    compat/posixfcn.c pathstuff.c w32os.c
    2324
    24 libw32_a_CPPFLAGS = -I$(srcdir)/include -I$(srcdir)/subproc -I$(top_srcdir)
     25libw32_a_CPPFLAGS = -I$(srcdir)/include -I$(srcdir)/subproc -I$(top_srcdir) \
     26                    -I$(top_srcdir)/glob
  • trunk/src/kmk/w32/compat/dirent.c

    r2591 r3140  
    11/* Directory entry code for Window platforms.
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    3231opendir(const char* pDirName)
    3332{
    34         struct stat sb;
    35         DIR*    pDir;
    36         char*   pEndDirName;
    37         int     nBufferLen;
    38 
    39         /* sanity checks */
    40         if (!pDirName) {
    41                 errno = EINVAL;
    42                 return NULL;
    43         }
    44         if (stat(pDirName, &sb) != 0) {
    45                 errno = ENOENT;
    46                 return NULL;
    47         }
    48         if ((sb.st_mode & S_IFMT) != S_IFDIR) {
    49                 errno = ENOTDIR;
    50                 return NULL;
    51         }
    52 
    53         /* allocate a DIR structure to return */
    54         pDir = (DIR *) malloc(sizeof (DIR));
    55 
    56         if (!pDir)
    57                 return NULL;
    58 
    59         /* input directory name length */
    60         nBufferLen = strlen(pDirName);
    61 
    62         /* copy input directory name to DIR buffer */
    63         strcpy(pDir->dir_pDirectoryName, pDirName);
    64 
    65         /* point to end of the copied directory name */
    66         pEndDirName = &pDir->dir_pDirectoryName[nBufferLen - 1];
    67 
    68         /* if directory name did not end in '/' or '\', add '/' */
    69         if ((*pEndDirName != '/') && (*pEndDirName != '\\')) {
    70                 pEndDirName++;
    71                 *pEndDirName = '/';
    72         }
    73 
    74         /* now append the wildcard character to the buffer */
    75         pEndDirName++;
    76         *pEndDirName = '*';
    77         pEndDirName++;
    78         *pEndDirName = '\0';
    79 
    80         /* other values defaulted */
    81         pDir->dir_nNumFiles = 0;
    82         pDir->dir_hDirHandle = INVALID_HANDLE_VALUE;
    83         pDir->dir_ulCookie = __DIRENT_COOKIE;
     33        struct stat sb;
     34        DIR*    pDir;
     35        char*   pEndDirName;
     36        int     nBufferLen;
     37
     38        /* sanity checks */
     39        if (!pDirName) {
     40                errno = EINVAL;
     41                return NULL;
     42        }
     43        if (stat(pDirName, &sb) != 0) {
     44                errno = ENOENT;
     45                return NULL;
     46        }
     47        if ((sb.st_mode & S_IFMT) != S_IFDIR) {
     48                errno = ENOTDIR;
     49                return NULL;
     50        }
     51
     52        /* allocate a DIR structure to return */
     53        pDir = (DIR *) malloc(sizeof (DIR));
     54
     55        if (!pDir)
     56                return NULL;
     57
     58        /* input directory name length */
     59        nBufferLen = strlen(pDirName);
     60
     61        /* copy input directory name to DIR buffer */
     62        strcpy(pDir->dir_pDirectoryName, pDirName);
     63
     64        /* point to end of the copied directory name */
     65        pEndDirName = &pDir->dir_pDirectoryName[nBufferLen - 1];
     66
     67        /* if directory name did not end in '/' or '\', add '/' */
     68        if ((*pEndDirName != '/') && (*pEndDirName != '\\')) {
     69                pEndDirName++;
     70                *pEndDirName = '/';
     71        }
     72
     73        /* now append the wildcard character to the buffer */
     74        pEndDirName++;
     75        *pEndDirName = '*';
     76        pEndDirName++;
     77        *pEndDirName = '\0';
     78
     79        /* other values defaulted */
     80        pDir->dir_nNumFiles = 0;
     81        pDir->dir_hDirHandle = INVALID_HANDLE_VALUE;
     82        pDir->dir_ulCookie = __DIRENT_COOKIE;
    8483
    8584#ifdef KMK_PRF
    86         fprintf(stderr, "opendir(%s) -> %p\n", pDirName, pDir);
     85        fprintf(stderr, "opendir(%s) -> %p\n", pDirName, pDir);
    8786#endif
    88         return pDir;
     87        return pDir;
    8988}
    9089
     
    9291closedir(DIR *pDir)
    9392{
    94         /* got a valid pointer? */
    95         if (!pDir) {
    96                 errno = EINVAL;
    97                 return;
    98         }
    99 
    100         /* sanity check that this is a DIR pointer */
    101         if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
    102                 errno = EINVAL;
    103                 return;
    104         }
    105 
    106         /* close the WINDOWS32 directory handle */
    107         if (pDir->dir_hDirHandle != INVALID_HANDLE_VALUE)
    108                 FindClose(pDir->dir_hDirHandle);
    109 
    110         free(pDir);
    111 
    112         return;
     93        /* got a valid pointer? */
     94        if (!pDir) {
     95                errno = EINVAL;
     96                return;
     97        }
     98
     99        /* sanity check that this is a DIR pointer */
     100        if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
     101                errno = EINVAL;
     102                return;
     103        }
     104
     105        /* close the WINDOWS32 directory handle */
     106        if (pDir->dir_hDirHandle != INVALID_HANDLE_VALUE)
     107                FindClose(pDir->dir_hDirHandle);
     108
     109        free(pDir);
     110
     111        return;
    113112}
    114113
     
    116115readdir(DIR* pDir)
    117116{
    118         WIN32_FIND_DATA wfdFindData;
    119 
    120         if (!pDir) {
    121                 errno = EINVAL;
    122                 return NULL;
    123         }
    124 
    125         /* sanity check that this is a DIR pointer */
    126         if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
    127                 errno = EINVAL;
    128                 return NULL;
    129         }
    130 
    131         if (pDir->dir_nNumFiles == 0) {
    132                 pDir->dir_hDirHandle = FindFirstFile(pDir->dir_pDirectoryName, &wfdFindData);
    133                 if (pDir->dir_hDirHandle == INVALID_HANDLE_VALUE)
    134                         return NULL;
    135         } else if (!FindNextFile(pDir->dir_hDirHandle, &wfdFindData))
    136                         return NULL;
    137 
    138         /* bump count for next call to readdir() or telldir() */
    139         pDir->dir_nNumFiles++;
    140 
    141         /* fill in struct dirent values */
    142         pDir->dir_sdReturn.d_ino = (ino_t)-1;
    143         strcpy(pDir->dir_sdReturn.d_name, wfdFindData.cFileName);
    144 
    145         return &pDir->dir_sdReturn;
     117        WIN32_FIND_DATA wfdFindData;
     118
     119        if (!pDir) {
     120                errno = EINVAL;
     121                return NULL;
     122        }
     123
     124        /* sanity check that this is a DIR pointer */
     125        if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
     126                errno = EINVAL;
     127                return NULL;
     128        }
     129
     130        if (pDir->dir_nNumFiles == 0) {
     131                pDir->dir_hDirHandle = FindFirstFile(pDir->dir_pDirectoryName, &wfdFindData);
     132                if (pDir->dir_hDirHandle == INVALID_HANDLE_VALUE)
     133                        return NULL;
     134        } else if (!FindNextFile(pDir->dir_hDirHandle, &wfdFindData))
     135                        return NULL;
     136
     137        /* bump count for next call to readdir() or telldir() */
     138        pDir->dir_nNumFiles++;
     139
     140        /* fill in struct dirent values */
     141        pDir->dir_sdReturn.d_ino = (ino_t)-1;
     142        strcpy(pDir->dir_sdReturn.d_name, wfdFindData.cFileName);
     143
     144        return &pDir->dir_sdReturn;
    146145}
    147146
     
    149148rewinddir(DIR* pDir)
    150149{
    151         if (!pDir) {
    152                 errno = EINVAL;
    153                 return;
    154         }
    155 
    156         /* sanity check that this is a DIR pointer */
    157         if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
    158                 errno = EINVAL;
    159                 return;
    160         }
    161 
    162         /* close the WINDOWS32 directory handle */
    163         if (pDir->dir_hDirHandle != INVALID_HANDLE_VALUE)
    164                 if (!FindClose(pDir->dir_hDirHandle))
    165                         errno = EBADF;
    166 
    167         /* reset members which control readdir() */
    168         pDir->dir_hDirHandle = INVALID_HANDLE_VALUE;
    169         pDir->dir_nNumFiles = 0;
    170 
    171         return;
     150        if (!pDir) {
     151                errno = EINVAL;
     152                return;
     153        }
     154
     155        /* sanity check that this is a DIR pointer */
     156        if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
     157                errno = EINVAL;
     158                return;
     159        }
     160
     161        /* close the WINDOWS32 directory handle */
     162        if (pDir->dir_hDirHandle != INVALID_HANDLE_VALUE)
     163                if (!FindClose(pDir->dir_hDirHandle))
     164                        errno = EBADF;
     165
     166        /* reset members which control readdir() */
     167        pDir->dir_hDirHandle = INVALID_HANDLE_VALUE;
     168        pDir->dir_nNumFiles = 0;
     169
     170        return;
    172171}
    173172
     
    175174telldir(DIR* pDir)
    176175{
    177         if (!pDir) {
    178                 errno = EINVAL;
    179                 return -1;
    180         }
    181 
    182         /* sanity check that this is a DIR pointer */
    183         if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
    184                 errno = EINVAL;
    185                 return -1;
    186         }
    187 
    188         /* return number of times readdir() called */
    189         return pDir->dir_nNumFiles;
     176        if (!pDir) {
     177                errno = EINVAL;
     178                return -1;
     179        }
     180
     181        /* sanity check that this is a DIR pointer */
     182        if (pDir->dir_ulCookie != __DIRENT_COOKIE) {
     183                errno = EINVAL;
     184                return -1;
     185        }
     186
     187        /* return number of times readdir() called */
     188        return pDir->dir_nNumFiles;
    190189}
    191190
     
    193192seekdir(DIR* pDir, long nPosition)
    194193{
    195         if (!pDir)
    196                 return;
    197 
    198         /* sanity check that this is a DIR pointer */
    199         if (pDir->dir_ulCookie != __DIRENT_COOKIE)
    200                 return;
    201 
    202         /* go back to beginning of directory */
    203         rewinddir(pDir);
    204 
    205         /* loop until we have found position we care about */
    206         for (--nPosition; nPosition && readdir(pDir); nPosition--);
    207 
    208         /* flag invalid nPosition value */
    209         if (nPosition)
    210                 errno = EINVAL;
    211 
    212         return;
    213 }
     194        if (!pDir)
     195                return;
     196
     197        /* sanity check that this is a DIR pointer */
     198        if (pDir->dir_ulCookie != __DIRENT_COOKIE)
     199                return;
     200
     201        /* go back to beginning of directory */
     202        rewinddir(pDir);
     203
     204        /* loop until we have found position we care about */
     205        for (--nPosition; nPosition && readdir(pDir); nPosition--);
     206
     207        /* flag invalid nPosition value */
     208        if (nPosition)
     209                errno = EINVAL;
     210
     211        return;
     212}
  • trunk/src/kmk/w32/imagecache.c

    r2640 r3140  
    2929*   Header Files                                                               *
    3030*******************************************************************************/
    31 #include "make.h"
     31#include "makeint.h"
    3232
    3333#include <Windows.h>
  • trunk/src/kmk/w32/include/dirent.h

    r2702 r3140  
    11/* Windows version of dirent.h
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    3 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    4443struct dirent
    4544{
    46   ino_t d_ino;                  /* unused - no equivalent on WINDOWS32 */
     45  ino_t d_ino;                  /* unused - no equivalent on WINDOWS32 */
    4746  char d_name[NAME_MAX+1];
    4847};
    4948
    5049typedef struct dir_struct {
    51         ULONG   dir_ulCookie;
    52         HANDLE  dir_hDirHandle;
    53         DWORD   dir_nNumFiles;
    54         char    dir_pDirectoryName[NAME_MAX+1];
    55         struct dirent dir_sdReturn;
     50        ULONG   dir_ulCookie;
     51        HANDLE  dir_hDirHandle;
     52        DWORD   dir_nNumFiles;
     53        char    dir_pDirectoryName[NAME_MAX+1];
     54        struct dirent dir_sdReturn;
    5655} DIR;
    5756
  • trunk/src/kmk/w32/include/pathstuff.h

    r2591 r3140  
    11/* Definitions for Windows path manipulation.
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    3 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
  • trunk/src/kmk/w32/include/sub_proc.h

    r2912 r3140  
    11/* Definitions for Windows process invocation.
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    2221 * Component Name:
    2322 *
    24  * $Date: 2010/07/13 01:20:43 $
     23 * $Date$
    2524 *
    26  * $Source: /sources/make/make/w32/include/sub_proc.h,v $
     25 * $Source$
    2726 *
    28  * $Id: sub_proc.h,v 1.12 2010/07/13 01:20:43 psmith Exp $
     27 * $Id$
    2928 */
    3029
     
    3433EXTERN_DECL(HANDLE process_init, (VOID_DECL));
    3534EXTERN_DECL(HANDLE process_init_fd, (HANDLE stdinh, HANDLE stdouth,
    36         HANDLE stderrh));
     35                                     HANDLE stderrh));
    3736EXTERN_DECL(long process_begin, (HANDLE proc, char **argv, char **envp,
    38         char *exec_path, char *as_user));
     37                                 char *exec_path, char *as_user));
    3938EXTERN_DECL(long process_pipe_io, (HANDLE proc, char *stdin_data,
    40         int stdin_data_len));
     39                                   int stdin_data_len));
    4140#ifndef KMK /* unused */
    4241EXTERN_DECL(long process_file_io, (HANDLE proc));
    4342#endif
    4443EXTERN_DECL(void process_cleanup, (HANDLE proc));
    45 EXTERN_DECL(HANDLE process_wait_for_any, (VOID_DECL));
     44EXTERN_DECL(HANDLE process_wait_for_any, (int block, DWORD* pdwWaitStatus));
    4645EXTERN_DECL(void process_register, (HANDLE proc));
    47 EXTERN_DECL(HANDLE process_easy, (char** argv, char** env));
     46EXTERN_DECL(HANDLE process_easy, (char** argv, char** env,
     47                                  int outfd, int errfd));
    4848EXTERN_DECL(BOOL process_kill, (HANDLE proc, int signal));
    4949EXTERN_DECL(int process_used_slots, (VOID_DECL));
     50EXTERN_DECL(DWORD process_set_handles, (HANDLE *handles));
     51
    5052#ifdef KMK
    5153EXTERN_DECL(int process_kmk_register_submit, (HANDLE hEvent, intptr_t clue, pid_t *pPid));
     
    6365EXTERN_DECL(int process_errcnt, (HANDLE proc));
    6466EXTERN_DECL(void process_pipes, (HANDLE proc, int pipes[3]));
     67EXTERN_DECL(void process_noinherit, (int fildes));
    6568
    6669#endif
  • trunk/src/kmk/w32/include/w32err.h

    r2591 r3140  
    11/* Definitions for Windows error handling.
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    2322#endif
    2423
    25 EXTERN_DECL(char * map_windows32_error_to_string, (DWORD error));
     24EXTERN_DECL(const char * map_windows32_error_to_string, (DWORD error));
    2625
    2726#endif /* !_W32ERR_H */
  • trunk/src/kmk/w32/pathstuff.c

    r3060 r3140  
    11/* Path conversion for Windows pathnames.
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
    3 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    1615this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1716
    18 #include "make.h"
     17#include "makeint.h"
    1918#include <string.h>
    2019#include <stdlib.h>
     
    3231    char *etok;            /* token separator for old Path */
    3332
    34         /*
    35         * Convert all spaces to delimiters. Note that pathnames which
    36         * contain blanks get trounced here. Use 8.3 format as a workaround.
    37         */
    38         for (etok = Path; etok && *etok; etok++)
    39                 if (isblank ((unsigned char) *etok))
    40                         *etok = to_delim;
    41 
    42         return (convert_Path_to_windows32(Path, to_delim));
     33        /*
     34        * Convert all spaces to delimiters. Note that pathnames which
     35        * contain blanks get trounced here. Use 8.3 format as a workaround.
     36        */
     37        for (etok = Path; etok && *etok; etok++)
     38                if (ISBLANK ((unsigned char) *etok))
     39                        *etok = to_delim;
     40
     41        return (convert_Path_to_windows32(Path, to_delim));
    4342}
    4443
     
    8483                *etok = to_delim;
    8584                p = ++etok;
    86             } else
     85            } else
    8786                p += strlen(p);
    8887        } else {
     
    128127getcwd_fs(char* buf, int len)
    129128{
    130         char *p = getcwd(buf, len);
    131 
    132         if (p) {
    133                 char *q = w32ify(buf, 0);
    134 #if 1  /* bird */
     129        char *p = getcwd(buf, len);
     130
     131        if (p) {
     132                char *q = w32ify(buf, 0);
     133#if 1  /* bird - UPSTREAM? */
    135134                buf[0] = '\0';
    136135                strncat(buf, q, len);
    137136#else  /* !bird */
    138                 strncpy(buf, q, len);
    139 #endif /* !bird */
    140         }
    141 
    142         return p;
     137                strncpy(buf, q, len);
     138#endif
     139        }
     140
     141        return p;
    143142}
    144143
  • trunk/src/kmk/w32/subproc/NMakefile

    r2591 r3140  
    1 # NOTE: If you have no `make' program at all to process this makefile, run
    2 # `build.bat' instead.
     1# NOTE: If you have no 'make' program at all to process this makefile, run
     2# 'build.bat' instead.
    33#
    4 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    5 # 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     4# Copyright (C) 1996-2016 Free Software Foundation, Inc.
    65# This file is part of GNU Make.
    76#
  • trunk/src/kmk/w32/subproc/misc.c

    r2591 r3140  
    11/* Process handling for Windows
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    2625/*
    2726 * Description:  Convert a NULL string terminated UNIX environment block to
    28  *              an environment block suitable for a windows32 system call
     27 *              an environment block suitable for a windows32 system call
    2928 *
    3029 * Returns:  TRUE= success, FALSE=fail
    3130 *
    3231 * Notes/Dependencies:  the environment block is sorted in case-insensitive
    33  *      order, is double-null terminated, and is a char *, not a char **
     32 *      order, is double-null terminated, and is a char *, not a char **
    3433 */
    3534int _cdecl compare(const void *a1, const void *a2)
    3635{
    37         return _stricoll(*((char**)a1),*((char**)a2));
     36        return _stricoll(*((char**)a1),*((char**)a2));
    3837}
    3938bool_t
    40 arr2envblk(char **arr, char **envblk_out)
     39arr2envblk(char **arr, char **envblk_out, int *envsize_needed)
    4140{
    42         char **tmp;
    43         int size_needed;
    44         int arrcnt;
    45         char *ptr;
     41        char **tmp;
     42        int size_needed;
     43        int arrcnt;
     44        char *ptr;
    4645
    47         arrcnt = 0;
    48         while (arr[arrcnt]) {
    49                 arrcnt++;
    50         }
     46        arrcnt = 0;
     47        while (arr[arrcnt]) {
     48                arrcnt++;
     49        }
    5150
    52         tmp = (char**) calloc(arrcnt + 1, sizeof(char *));
    53         if (!tmp) {
    54                 return FALSE;
    55         }
     51        tmp = (char**) calloc(arrcnt + 1, sizeof(char *));
     52        if (!tmp) {
     53                return FALSE;
     54        }
    5655
    57         arrcnt = 0;
    58         size_needed = 0;
    59         while (arr[arrcnt]) {
    60                 tmp[arrcnt] = arr[arrcnt];
    61                 size_needed += strlen(arr[arrcnt]) + 1;
    62                 arrcnt++;
    63         }
    64         size_needed++;
     56        arrcnt = 0;
     57        size_needed = *envsize_needed = 0;
     58        while (arr[arrcnt]) {
     59                tmp[arrcnt] = arr[arrcnt];
     60                size_needed += strlen(arr[arrcnt]) + 1;
     61                arrcnt++;
     62        }
     63        size_needed++;
     64        *envsize_needed = size_needed;
    6565
    66         qsort((void *) tmp, (size_t) arrcnt, sizeof (char*), compare);
     66        qsort((void *) tmp, (size_t) arrcnt, sizeof (char*), compare);
    6767
    68         ptr = *envblk_out = calloc(size_needed, 1);
    69         if (!ptr) {
    70                 free(tmp);
    71                 return FALSE;
    72         }
     68        ptr = *envblk_out = calloc(size_needed, 1);
     69        if (!ptr) {
     70                free(tmp);
     71                return FALSE;
     72        }
    7373
    74         arrcnt = 0;
    75         while (tmp[arrcnt]) {
    76                 strcpy(ptr, tmp[arrcnt]);
    77                 ptr += strlen(tmp[arrcnt]) + 1;
    78                 arrcnt++;
    79         }
     74        arrcnt = 0;
     75        while (tmp[arrcnt]) {
     76                strcpy(ptr, tmp[arrcnt]);
     77                ptr += strlen(tmp[arrcnt]) + 1;
     78                arrcnt++;
     79        }
    8080
    81         free(tmp);
    82         return TRUE;
     81        free(tmp);
     82        return TRUE;
    8383}
  • trunk/src/kmk/w32/subproc/proc.h

    r2591 r3140  
    11/* Definitions for Windows
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    2120typedef int bool_t;
    2221
    23 #define E_SCALL         101
    24 #define E_IO            102
    25 #define E_NO_MEM        103
    26 #define E_FORK          104
     22#define E_SCALL         101
     23#define E_IO            102
     24#define E_NO_MEM        103
     25#define E_FORK          104
    2726
    28 extern bool_t arr2envblk(char **arr, char **envblk_out);
     27extern bool_t arr2envblk(char **arr, char **envblk_out, int *envsize_needed);
    2928
    3029#endif
  • trunk/src/kmk/w32/subproc/sub_proc.c

    r3051 r3140  
    11/* Process handling for Windows.
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    1918#include <stdlib.h>
    2019#include <stdio.h>
     20#include <io.h>         /* for _get_osfhandle */
    2121#ifdef _MSC_VER
    2222# include <stddef.h>    /* for intptr_t */
     
    2424# include <stdint.h>
    2525#endif
     26#include <string.h>
    2627#include <process.h>  /* for msvc _beginthreadex, _endthreadex */
    2728#include <signal.h>
    2829#include <windows.h>
    29 #ifdef KMK
    30 # include <assert.h>
    31 # include "make.h"
    32 # include "kmkbuiltin.h"
    33 #endif
    34 
    35 
     30
     31#include "makeint.h"
     32#include "filedef.h"
     33#include "variable.h"
    3634#include "sub_proc.h"
    3735#include "proc.h"
     
    3937#include "debug.h"
    4038
     39#ifdef KMK
     40# include <assert.h>
     41# include "kmkbuiltin.h"
     42extern void kmk_cache_exec_image(const char *); /* imagecache.c */
     43#endif
     44
    4145static char *make_command_line(char *shell_name, char *exec_path, char **argv);
    42 #ifndef KMK
    43 extern char *xmalloc (unsigned int);
    44 #else
    45 extern void kmk_cache_exec_image(const char *); /* imagecache.c */
    46 #endif
    4746
    4847typedef struct sub_process_t {
    4948#ifdef KMK
    50         enum { kRegular = 0, kSubmit, kSubProcFreed } enmType;
    51         intptr_t clue;
    52 #endif
    53         intptr_t sv_stdin[2];
    54         intptr_t sv_stdout[2];
    55         intptr_t sv_stderr[2];
    56         int using_pipes;
    57         char *inp;
    58         DWORD incnt;
    59         char * volatile outp;
    60         volatile DWORD outcnt;
    61         char * volatile errp;
    62         volatile DWORD errcnt;
    63         pid_t pid;
    64         int exit_code;
    65         int signal;
    66         long last_err;
    67         long lerrno;
     49        enum { kRegular = 0, kSubmit, kSubProcFreed } enmType;
     50        intptr_t clue;
     51#endif
     52        intptr_t sv_stdin[2];
     53        intptr_t sv_stdout[2];
     54        intptr_t sv_stderr[2];
     55        int using_pipes;
     56        char *inp;
     57        DWORD incnt;
     58        char * volatile outp;
     59        volatile DWORD outcnt;
     60        char * volatile errp;
     61        volatile DWORD errcnt;
     62        pid_t pid;
     63        int exit_code;
     64        int signal;
     65        long last_err;
     66        long lerrno;
    6867} sub_process;
    6968
     
    7473static int proc_index = 0;
    7574static int fake_exits_pending = 0;
     75
     76
     77/*
     78 * Fill a HANDLE list with handles to wait for.
     79 */
     80DWORD
     81process_set_handles(HANDLE *handles)
     82{
     83    DWORD count = 0;
     84    int i;
     85
     86    /* Build array of handles to wait for */
     87    for (i = 0; i < proc_index; i++) {
     88        /* Don't wait on child processes that have already finished */
     89        if (fake_exits_pending && proc_array[i]->exit_code)
     90            continue;
     91
     92        handles[count++] = (HANDLE) proc_array[i]->pid;
     93    }
     94
     95    return count;
     96}
    7697
    7798#ifndef KMK /* Inefficient! */
     
    83104process_adjust_wait_state(sub_process* pproc)
    84105{
    85         int i;
    86 
    87         if (!proc_index)
    88                 return;
    89 
    90         for (i = 0; i < proc_index; i++)
    91                 if (proc_array[i]->pid == pproc->pid)
    92                         break;
    93 
    94         if (i < proc_index) {
    95                 proc_index--;
    96                 if (i != proc_index)
    97                         memmove(&proc_array[i], &proc_array[i+1],
    98                                 (proc_index-i) * sizeof(sub_process*));
    99                 proc_array[proc_index] = NULL;
    100         }
    101 }
     106        int i;
     107
     108        if (!proc_index)
     109                return;
     110
     111        for (i = 0; i < proc_index; i++)
     112                if (proc_array[i]->pid == pproc->pid)
     113                        break;
     114
     115        if (i < proc_index) {
     116                proc_index--;
     117                if (i != proc_index)
     118                        memmove(&proc_array[i], &proc_array[i+1],
     119                                (proc_index-i) * sizeof(sub_process*));
     120                proc_array[proc_index] = NULL;
     121        }
     122}
     123
    102124#endif /* !KMK */
    103125
     
    106128 */
    107129static sub_process *
    108 process_wait_for_any_private(void)
    109 {
    110         HANDLE handles[MAXIMUM_WAIT_OBJECTS];
    111         DWORD retval, which;
    112         int i;
    113 
    114         if (!proc_index)
    115                 return NULL;
    116 
    117         /* build array of handles to wait for */
    118         for (i = 0; i < proc_index; i++) {
    119                 handles[i] = (HANDLE) proc_array[i]->pid;
    120 
    121                 if (fake_exits_pending && proc_array[i]->exit_code)
    122                         break;
    123         }
    124 
    125         /* wait for someone to exit */
    126         if (!fake_exits_pending) {
     130process_wait_for_any_private(int block, DWORD* pdwWaitStatus)
     131{
     132        HANDLE handles[MAXIMUM_WAIT_OBJECTS];
     133        DWORD retval, which;
     134        int i;
     135
     136        if (!proc_index)
     137                return NULL;
     138
     139        /* build array of handles to wait for */
     140        for (i = 0; i < proc_index; i++) {
     141                handles[i] = (HANDLE) proc_array[i]->pid;
     142
     143                if (fake_exits_pending && proc_array[i]->exit_code)
     144                        break;
     145        }
     146
     147        /* wait for someone to exit */
     148        if (!fake_exits_pending) {
    127149#ifdef KMK
    128150l_wait_again:
    129151#endif
    130                 retval = WaitForMultipleObjects(proc_index, handles, FALSE, INFINITE);
    131                 which = retval - WAIT_OBJECT_0;
    132         } else {
    133                 fake_exits_pending--;
    134                 retval = !WAIT_FAILED;
    135                 which = i;
    136         }
    137 
    138         /* return pointer to process */
    139         if (retval != WAIT_FAILED) {
    140                 sub_process* pproc = proc_array[which];
    141 #ifdef KMK
    142                 if (pproc->enmType == kSubmit) {
    143                     /* Try get the result from kSubmit.c.  This may not succeed if the whole
    144                        result hasn't arrived yet, in which we just restart the wait. */
    145                     if (kSubmitSubProcGetResult(pproc->clue, &pproc->exit_code, &pproc->signal) != 0) {
    146                         goto l_wait_again;
    147                     }
    148                 }
     152                retval = WaitForMultipleObjects(proc_index, handles, FALSE, (block ? INFINITE : 0));
     153                which = retval - WAIT_OBJECT_0;
     154        } else {
     155                fake_exits_pending--;
     156                retval = !WAIT_FAILED;
     157                which = i;
     158        }
     159
     160        /* If the pointer is not NULL, set the wait status result variable. */
     161        if (pdwWaitStatus)
     162            *pdwWaitStatus = retval;
     163
     164        /* return pointer to process */
     165        if ((retval == WAIT_TIMEOUT) || (retval == WAIT_FAILED)) {
     166                return NULL;
     167        }
     168        else {
     169                sub_process* pproc = proc_array[which];
     170#ifdef KMK
     171                if (pproc->enmType == kSubmit) {
     172                        /* Try get the result from kSubmit.c.  This may not succeed if the whole
     173                           result hasn't arrived yet, in which we just restart the wait. */
     174                        if (kSubmitSubProcGetResult(pproc->clue, &pproc->exit_code, &pproc->signal) != 0) {
     175                                goto l_wait_again;
     176                        }
     177                }
    149178#endif
    150179#ifndef KMK /* Inefficient! */
    151                 process_adjust_wait_state(pproc);
     180                process_adjust_wait_state(pproc);
    152181#else
    153                 proc_index--;
    154                 if ((int)which < proc_index)
    155                         proc_array[which] = proc_array[proc_index];
    156                 proc_array[proc_index] = NULL;
    157 #endif
    158                 return pproc;
    159         } else
    160                 return NULL;
     182                proc_index--;
     183                if ((int)which < proc_index)
     184                        proc_array[which] = proc_array[proc_index];
     185                proc_array[proc_index] = NULL;
     186#endif
     187                return pproc;
     188        }
    161189}
    162190
     
    167195 process_kill(HANDLE proc, int signal)
    168196{
    169         sub_process* pproc = (sub_process*) proc;
    170         pproc->signal = signal;
    171 #ifdef KMK
    172         if (pproc->enmType == kRegular) {
    173 #endif
    174         return (TerminateProcess((HANDLE) pproc->pid, signal));
    175 #ifdef KMK
    176         } else if (pproc->enmType == kSubmit) {
    177                 return kSubmitSubProcKill(pproc->clue, signal) == 0;
    178         }
    179         assert(0);
    180         return FALSE;
     197        sub_process* pproc = (sub_process*) proc;
     198#ifdef KMK
     199    if (pproc->enmType == kRegular) {
     200#endif
     201        pproc->signal = signal;
     202        return (TerminateProcess((HANDLE) pproc->pid, signal));
     203#ifdef KMK
     204    } else if (pproc->enmType == kSubmit)
     205        return kSubmitSubProcKill(pproc->clue, signal) == 0;
     206    assert(0);
     207    return FALSE;
    181208#endif
    182209}
     
    192219{
    193220#ifdef KMK
    194         assert(((sub_process *)proc)->enmType == kRegular);
    195 #endif
    196         if (proc_index < MAXIMUM_WAIT_OBJECTS)
    197                 proc_array[proc_index++] = (sub_process *) proc;
     221        assert(((sub_process *)proc)->enmType == kRegular);
     222#endif
     223        if (proc_index < MAXIMUM_WAIT_OBJECTS)
     224                proc_array[proc_index++] = (sub_process *) proc;
    198225}
    199226
     
    255282process_used_slots(void)
    256283{
    257         return proc_index;
     284        return proc_index;
    258285}
    259286
     
    263290 * you must do 1 of things:
    264291 *
    265  *      x = process_easy(...);
     292 *      x = process_easy(...);
    266293 *
    267294 * or
    268295 *
    269  *      x = process_init_fd();
    270  *      process_register(x);
     296 *      x = process_init_fd();
     297 *      process_register(x);
    271298 *
    272299 * or
    273300 *
    274  *      x = process_init();
    275  *      process_register(x);
     301 *      x = process_init();
     302 *      process_register(x);
    276303 *
    277304 * You must NOT then call process_pipe_io() because this function is
     
    281308
    282309HANDLE
    283 process_wait_for_any(void)
    284 {
    285         sub_process* pproc = process_wait_for_any_private();
    286 
    287         if (!pproc)
    288                 return NULL;
    289         else {
    290                 /*
    291                 * Ouch! can't tell caller if this fails directly. Caller
    292                 * will have to use process_last_err()
    293                 */
    294 #ifdef KMK
    295                 /* Invalidate negative directory cache entries now that a
    296                    job has completed and possibly created new files that
    297                    was missing earlier. */
    298                 dir_cache_invalid_after_job ();
    299 
    300                 if (pproc->enmType == kRegular) {
    301                     (void)process_file_io_private(pproc, FALSE);
    302                 }
     310process_wait_for_any(int block, DWORD* pdwWaitStatus)
     311{
     312        sub_process* pproc = process_wait_for_any_private(block, pdwWaitStatus);
     313
     314        if (!pproc)
     315                return NULL;
     316        else {
     317                /*
     318                * Ouch! can't tell caller if this fails directly. Caller
     319                * will have to use process_last_err()
     320                */
     321#ifdef KMK
     322                /* Invalidate negative directory cache entries now that a
     323                   job has completed and possibly created new files that
     324                   was missing earlier. */
     325                dir_cache_invalid_after_job ();
     326
     327                if (pproc->enmType == kRegular) {
     328                        (void)process_file_io_private(pproc, FALSE);
     329                }
    303330#else
    304                 (void) process_file_io(pproc);
    305 #endif
    306                 return ((HANDLE) pproc);
    307         }
     331                (void) process_file_io(pproc);
     332#endif
     333                return ((HANDLE) pproc);
     334        }
    308335}
    309336
     
    319346{
    320347        if (proc == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE;
    321         return (((sub_process *)proc)->last_err);
     348        return (((sub_process *)proc)->last_err);
    322349}
    323350
     
    326353{
    327354        if (proc == INVALID_HANDLE_VALUE) return EXIT_FAILURE;
    328         return (((sub_process *)proc)->exit_code);
     355        return (((sub_process *)proc)->exit_code);
     356}
     357
     358void
     359process_noinherit(int fd)
     360{
     361  HANDLE fh = (HANDLE)_get_osfhandle(fd);
     362
     363  if (fh && fh != INVALID_HANDLE_VALUE)
     364        SetHandleInformation(fh, HANDLE_FLAG_INHERIT, 0);
    329365}
    330366
     
    339375process_outbuf(HANDLE proc)
    340376{
    341         return (((sub_process *)proc)->outp);
     377        return (((sub_process *)proc)->outp);
    342378}
    343379
     
    345381process_errbuf(HANDLE proc)
    346382{
    347         return (((sub_process *)proc)->errp);
     383        return (((sub_process *)proc)->errp);
    348384}
    349385
     
    351387process_outcnt(HANDLE proc)
    352388{
    353         return (((sub_process *)proc)->outcnt);
     389        return (((sub_process *)proc)->outcnt);
    354390}
    355391
     
    357393process_errcnt(HANDLE proc)
    358394{
    359         return (((sub_process *)proc)->errcnt);
     395        return (((sub_process *)proc)->errcnt);
    360396}
    361397
     
    363399process_pipes(HANDLE proc, int pipes[3])
    364400{
    365         pipes[0] = ((sub_process *)proc)->sv_stdin[0];
    366         pipes[1] = ((sub_process *)proc)->sv_stdout[0];
    367         pipes[2] = ((sub_process *)proc)->sv_stderr[0];
    368         return;
     401        pipes[0] = ((sub_process *)proc)->sv_stdin[0];
     402        pipes[1] = ((sub_process *)proc)->sv_stdout[0];
     403        pipes[2] = ((sub_process *)proc)->sv_stderr[0];
     404        return;
    369405}
    370406*/
    371407
    372         HANDLE
     408        HANDLE
    373409process_init()
    374410{
    375         sub_process *pproc;
    376         /*
    377         * open file descriptors for attaching stdin/stdout/sterr
    378         */
    379         HANDLE stdin_pipes[2];
    380         HANDLE stdout_pipes[2];
    381         HANDLE stderr_pipes[2];
    382         SECURITY_ATTRIBUTES inherit;
    383         BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
    384 
    385         pproc = malloc(sizeof(*pproc));
    386         memset(pproc, 0, sizeof(*pproc));
    387 
    388         /* We can't use NULL for lpSecurityDescriptor because that
    389            uses the default security descriptor of the calling process.
    390            Instead we use a security descriptor with no DACL.  This
    391            allows nonrestricted access to the associated objects. */
    392 
    393         if (!InitializeSecurityDescriptor((PSECURITY_DESCRIPTOR)(&sd),
    394                                           SECURITY_DESCRIPTOR_REVISION)) {
    395                 pproc->last_err = GetLastError();
    396                 pproc->lerrno = E_SCALL;
    397                 return((HANDLE)pproc);
    398         }
    399 
    400         inherit.nLength = sizeof(inherit);
    401         inherit.lpSecurityDescriptor = (PSECURITY_DESCRIPTOR)(&sd);
    402         inherit.bInheritHandle = TRUE;
    403 
    404         // By convention, parent gets pipe[0], and child gets pipe[1]
    405         // This means the READ side of stdin pipe goes into pipe[1]
    406         // and the WRITE side of the stdout and stderr pipes go into pipe[1]
    407         if (CreatePipe( &stdin_pipes[1], &stdin_pipes[0], &inherit, 0) == FALSE ||
    408         CreatePipe( &stdout_pipes[0], &stdout_pipes[1], &inherit, 0) == FALSE ||
    409         CreatePipe( &stderr_pipes[0], &stderr_pipes[1], &inherit, 0) == FALSE) {
    410 
    411                 pproc->last_err = GetLastError();
    412                 pproc->lerrno = E_SCALL;
    413                 return((HANDLE)pproc);
    414         }
    415 
    416         //
    417         // Mark the parent sides of the pipes as non-inheritable
    418         //
    419         if (SetHandleInformation(stdin_pipes[0],
    420                                 HANDLE_FLAG_INHERIT, 0) == FALSE ||
    421                 SetHandleInformation(stdout_pipes[0],
    422                                 HANDLE_FLAG_INHERIT, 0) == FALSE ||
    423                 SetHandleInformation(stderr_pipes[0],
    424                                 HANDLE_FLAG_INHERIT, 0) == FALSE) {
    425 
    426                 pproc->last_err = GetLastError();
    427                 pproc->lerrno = E_SCALL;
    428                 return((HANDLE)pproc);
    429         }
    430         pproc->sv_stdin[0]  = (intptr_t) stdin_pipes[0];
    431         pproc->sv_stdin[1]  = (intptr_t) stdin_pipes[1];
    432         pproc->sv_stdout[0] = (intptr_t) stdout_pipes[0];
    433         pproc->sv_stdout[1] = (intptr_t) stdout_pipes[1];
    434         pproc->sv_stderr[0] = (intptr_t) stderr_pipes[0];
    435         pproc->sv_stderr[1] = (intptr_t) stderr_pipes[1];
    436 
    437         pproc->using_pipes = 1;
    438 
    439         pproc->lerrno = 0;
    440 
    441         return((HANDLE)pproc);
    442 }
    443 
    444 
    445         HANDLE
     411        sub_process *pproc;
     412        /*
     413        * open file descriptors for attaching stdin/stdout/sterr
     414        */
     415        HANDLE stdin_pipes[2];
     416        HANDLE stdout_pipes[2];
     417        HANDLE stderr_pipes[2];
     418        SECURITY_ATTRIBUTES inherit;
     419        BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
     420
     421        pproc = malloc(sizeof(*pproc));
     422        memset(pproc, 0, sizeof(*pproc));
     423
     424        /* We can't use NULL for lpSecurityDescriptor because that
     425           uses the default security descriptor of the calling process.
     426           Instead we use a security descriptor with no DACL.  This
     427           allows nonrestricted access to the associated objects. */
     428
     429        if (!InitializeSecurityDescriptor((PSECURITY_DESCRIPTOR)(&sd),
     430                                          SECURITY_DESCRIPTOR_REVISION)) {
     431                pproc->last_err = GetLastError();
     432                pproc->lerrno = E_SCALL;
     433                return((HANDLE)pproc);
     434        }
     435
     436        inherit.nLength = sizeof(inherit);
     437        inherit.lpSecurityDescriptor = (PSECURITY_DESCRIPTOR)(&sd);
     438        inherit.bInheritHandle = TRUE;
     439
     440        // By convention, parent gets pipe[0], and child gets pipe[1]
     441        // This means the READ side of stdin pipe goes into pipe[1]
     442        // and the WRITE side of the stdout and stderr pipes go into pipe[1]
     443        if (CreatePipe( &stdin_pipes[1], &stdin_pipes[0], &inherit, 0) == FALSE ||
     444        CreatePipe( &stdout_pipes[0], &stdout_pipes[1], &inherit, 0) == FALSE ||
     445        CreatePipe( &stderr_pipes[0], &stderr_pipes[1], &inherit, 0) == FALSE) {
     446
     447                pproc->last_err = GetLastError();
     448                pproc->lerrno = E_SCALL;
     449                return((HANDLE)pproc);
     450        }
     451
     452        //
     453        // Mark the parent sides of the pipes as non-inheritable
     454        //
     455        if (SetHandleInformation(stdin_pipes[0],
     456                                HANDLE_FLAG_INHERIT, 0) == FALSE ||
     457                SetHandleInformation(stdout_pipes[0],
     458                                HANDLE_FLAG_INHERIT, 0) == FALSE ||
     459                SetHandleInformation(stderr_pipes[0],
     460                                HANDLE_FLAG_INHERIT, 0) == FALSE) {
     461
     462                pproc->last_err = GetLastError();
     463                pproc->lerrno = E_SCALL;
     464                return((HANDLE)pproc);
     465        }
     466        pproc->sv_stdin[0]  = (intptr_t) stdin_pipes[0];
     467        pproc->sv_stdin[1]  = (intptr_t) stdin_pipes[1];
     468        pproc->sv_stdout[0] = (intptr_t) stdout_pipes[0];
     469        pproc->sv_stdout[1] = (intptr_t) stdout_pipes[1];
     470        pproc->sv_stderr[0] = (intptr_t) stderr_pipes[0];
     471        pproc->sv_stderr[1] = (intptr_t) stderr_pipes[1];
     472
     473        pproc->using_pipes = 1;
     474
     475        pproc->lerrno = 0;
     476
     477        return((HANDLE)pproc);
     478}
     479
     480
     481        HANDLE
    446482process_init_fd(HANDLE stdinh, HANDLE stdouth, HANDLE stderrh)
    447483{
    448         sub_process *pproc;
    449 
    450         pproc = malloc(sizeof(*pproc));
    451         memset(pproc, 0, sizeof(*pproc));
    452 
    453         /*
    454          * Just pass the provided file handles to the 'child side' of the
    455          * pipe, bypassing pipes altogether.
    456          */
    457         pproc->sv_stdin[1]  = (intptr_t) stdinh;
    458         pproc->sv_stdout[1] = (intptr_t) stdouth;
    459         pproc->sv_stderr[1] = (intptr_t) stderrh;
    460 
    461         pproc->last_err = pproc->lerrno = 0;
    462 
    463         return((HANDLE)pproc);
     484        sub_process *pproc;
     485
     486        pproc = malloc(sizeof(*pproc));
     487        if (pproc) {
     488                memset(pproc, 0, sizeof(*pproc));
     489
     490                /*
     491                 * Just pass the provided file handles to the 'child
     492                 * side' of the pipe, bypassing pipes altogether.
     493                 */
     494                pproc->sv_stdin[1]  = (intptr_t) stdinh;
     495                pproc->sv_stdout[1] = (intptr_t) stdouth;
     496                pproc->sv_stderr[1] = (intptr_t) stderrh;
     497
     498                pproc->last_err = pproc->lerrno = 0;
     499        }
     500
     501        return((HANDLE)pproc);
    464502}
    465503
     
    467505static HANDLE
    468506find_file(const char *exec_path, const char *path_var,
    469           char *full_fname, DWORD full_len)
    470 {
    471         HANDLE exec_handle;
    472         char *fname;
    473         char *ext;
    474         DWORD req_len;
    475         int i;
    476         static const char *extensions[] =
    477           /* Should .com come before no-extension case?  */
    478           { ".exe", ".cmd", ".bat", "", ".com", NULL };
    479 
    480         fname = xmalloc(strlen(exec_path) + 5);
    481         strcpy(fname, exec_path);
    482         ext = fname + strlen(fname);
    483 
    484         for (i = 0; extensions[i]; i++) {
    485                 strcpy(ext, extensions[i]);
    486                 if (((req_len = SearchPath (path_var, fname, NULL, full_len,
    487                                             full_fname, NULL)) > 0
    488                      /* For compatibility with previous code, which
    489                         used OpenFile, and with Windows operation in
    490                         general, also look in various default
    491                         locations, such as Windows directory and
    492                         Windows System directory.  Warning: this also
    493                         searches PATH in the Make's environment, which
    494                         might not be what the Makefile wants, but it
    495                         seems to be OK as a fallback, after the
    496                         previous SearchPath failed to find on child's
    497                         PATH.  */
    498                      || (req_len = SearchPath (NULL, fname, NULL, full_len,
    499                                                full_fname, NULL)) > 0)
    500                     && req_len <= full_len
    501                     && (exec_handle =
    502                                 CreateFile(full_fname,
    503                                            GENERIC_READ,
    504                                            FILE_SHARE_READ | FILE_SHARE_WRITE,
    505                                            NULL,
    506                                            OPEN_EXISTING,
    507                                            FILE_ATTRIBUTE_NORMAL,
    508                                            NULL)) != INVALID_HANDLE_VALUE) {
    509                         free(fname);
    510                         return(exec_handle);
    511                 }
    512         }
    513 
    514         free(fname);
    515         return INVALID_HANDLE_VALUE;
     507          char *full_fname, DWORD full_len)
     508{
     509        HANDLE exec_handle;
     510        char *fname;
     511        char *ext;
     512        DWORD req_len;
     513        int i;
     514        static const char *extensions[] =
     515          /* Should .com come before no-extension case?  */
     516          { ".exe", ".cmd", ".bat", "", ".com", NULL };
     517
     518        fname = xmalloc(strlen(exec_path) + 5);
     519        strcpy(fname, exec_path);
     520        ext = fname + strlen(fname);
     521
     522        for (i = 0; extensions[i]; i++) {
     523                strcpy(ext, extensions[i]);
     524                if (((req_len = SearchPath (path_var, fname, NULL, full_len,
     525                                            full_fname, NULL)) > 0
     526                     /* For compatibility with previous code, which
     527                        used OpenFile, and with Windows operation in
     528                        general, also look in various default
     529                        locations, such as Windows directory and
     530                        Windows System directory.  Warning: this also
     531                        searches PATH in the Make's environment, which
     532                        might not be what the Makefile wants, but it
     533                        seems to be OK as a fallback, after the
     534                        previous SearchPath failed to find on child's
     535                        PATH.  */
     536                     || (req_len = SearchPath (NULL, fname, NULL, full_len,
     537                                               full_fname, NULL)) > 0)
     538                    && req_len <= full_len
     539                    && (exec_handle =
     540                                CreateFile(full_fname,
     541                                           GENERIC_READ,
     542                                           FILE_SHARE_READ | FILE_SHARE_WRITE,
     543                                           NULL,
     544                                           OPEN_EXISTING,
     545                                           FILE_ATTRIBUTE_NORMAL,
     546                                           NULL)) != INVALID_HANDLE_VALUE) {
     547                        free(fname);
     548                        return(exec_handle);
     549                }
     550        }
     551
     552        free(fname);
     553        return INVALID_HANDLE_VALUE;
     554}
     555
     556/*
     557 * Return non-zero of FNAME specifies a batch file and its name
     558 * includes embedded whitespace.
     559 */
     560
     561static int
     562batch_file_with_spaces(const char *fname)
     563{
     564        size_t fnlen = strlen(fname);
     565
     566        return (fnlen > 4
     567                && (_strnicmp(fname + fnlen - 4, ".bat", 4) == 0
     568                    || _strnicmp(fname + fnlen - 4, ".cmd", 4) == 0)
     569                /* The set of characters in the 2nd arg to strpbrk
     570                   should be the same one used by make_command_line
     571                   below to decide whether an argv[] element needs
     572                   quoting.  */
     573                && strpbrk(fname, " \t") != NULL);
    516574}
    517575
     
    526584long
    527585process_begin(
    528         HANDLE proc,
    529         char **argv,
    530         char **envp,
    531         char *exec_path,
    532         char *as_user)
    533 {
    534         sub_process *pproc = (sub_process *)proc;
    535         char *shell_name = 0;
    536         int file_not_found=0;
    537         HANDLE exec_handle;
    538         char exec_fname[MAX_PATH];
    539         const char *path_var = NULL;
    540         char **ep;
    541         char buf[256];
    542         DWORD bytes_returned;
    543         DWORD flags;
    544         char *command_line;
    545         STARTUPINFO startInfo;
    546         PROCESS_INFORMATION procInfo;
    547         char *envblk=NULL;
     586        HANDLE proc,
     587        char **argv,
     588        char **envp,
     589        char *exec_path,
     590        char *as_user)
     591{
     592        sub_process *pproc = (sub_process *)proc;
     593        char *shell_name = 0;
     594        int file_not_found=0;
     595        HANDLE exec_handle;
     596        char exec_fname[MAX_PATH];
     597        const char *path_var = NULL;
     598        char **ep;
     599        char buf[MAX_PATH];
     600        DWORD bytes_returned;
     601        DWORD flags;
     602        char *command_line;
     603        STARTUPINFO startInfo;
     604        PROCESS_INFORMATION procInfo;
     605        char *envblk=NULL;
     606        int envsize_needed = 0;
     607        int pass_null_exec_path = 0;
    548608#ifdef KMK
    549609        size_t exec_path_len;
     
    552612        assert (pproc->enmType == kRegular);
    553613#endif
    554 
    555614
    556615        /*
     
    574633        else {
    575634#endif /* KMK */
    576                 /* Use the Makefile's value of PATH to look for the program to
    577                    execute, because it could be different from Make's PATH
    578                    (e.g., if the target sets its own value.  */
    579                 if (envp)
    580                         for (ep = envp; *ep; ep++) {
    581                                 if (strncmp (*ep, "PATH=", 5) == 0
    582                                     || strncmp (*ep, "Path=", 5) == 0) {
    583                                         path_var = *ep + 5;
    584                                         break;
    585                                 }
    586                         }
    587                 exec_handle = find_file(exec_path, path_var,
    588                                         exec_fname, sizeof(exec_fname));
    589 #ifdef KMK
    590         }
    591 #endif
    592 
    593         /*
    594          * If we couldn't open the file, just assume that Windows will be
    595          * somehow able to find and execute it.
    596          */
    597         if (exec_handle == INVALID_HANDLE_VALUE) {
    598                 file_not_found++;
    599         }
    600         else {
    601                 /* Attempt to read the first line of the file */
    602                 if (ReadFile( exec_handle,
    603                                 buf, sizeof(buf) - 1, /* leave room for trailing NULL */
    604                                 &bytes_returned, 0) == FALSE || bytes_returned < 2) {
    605 
    606                         pproc->last_err = GetLastError();
    607                         pproc->lerrno = E_IO;
    608                         CloseHandle(exec_handle);
    609                         return(-1);
    610                 }
    611                 if (buf[0] == '#' && buf[1] == '!') {
    612                         /*
    613                          *  This is a shell script...  Change the command line from
    614                          *      exec_path args to shell_name exec_path args
    615                          */
    616                         char *p;
    617 
    618                         /*  Make sure buf is NULL terminated */
    619                         buf[bytes_returned] = 0;
    620                         /*
    621                          * Depending on the file system type, etc. the first line
    622                          * of the shell script may end with newline or newline-carriage-return
    623                          * Whatever it ends with, cut it off.
    624                          */
    625                         p= strchr(buf, '\n');
    626                         if (p)
    627                                 *p = 0;
    628                         p = strchr(buf, '\r');
    629                         if (p)
    630                                 *p = 0;
    631 
    632                         /*
    633                          *  Find base name of shell
    634                          */
    635                         shell_name = strrchr( buf, '/');
    636                         if (shell_name) {
    637                                 shell_name++;
    638                         } else {
    639                                 shell_name = &buf[2];/* skipping "#!" */
    640                         }
    641 
    642                 }
    643                 CloseHandle(exec_handle);
    644         }
    645 
    646         flags = 0;
    647 
    648         if (file_not_found)
    649                 command_line = make_command_line( shell_name, exec_path, argv);
    650         else
    651                 command_line = make_command_line( shell_name, exec_fname, argv);
    652 
    653         if ( command_line == NULL ) {
    654                 pproc->last_err = 0;
    655                 pproc->lerrno = E_NO_MEM;
    656                 return(-1);
    657         }
    658 
    659         if (envp) {
    660                 if (arr2envblk(envp, &envblk) ==FALSE) {
    661                         pproc->last_err = 0;
    662                         pproc->lerrno = E_NO_MEM;
    663                         free( command_line );
    664                         return(-1);
    665                 }
    666         }
    667 
    668         if ((shell_name) || (file_not_found)) {
    669                 exec_path = 0;  /* Search for the program in %Path% */
    670         } else {
    671                 exec_path = exec_fname;
    672         }
    673 
    674         /*
    675          *  Set up inherited stdin, stdout, stderr for child
    676          */
    677         GetStartupInfo(&startInfo);
     635
     636        /* Use the Makefile's value of PATH to look for the program to
     637           execute, because it could be different from Make's PATH
     638           (e.g., if the target sets its own value.  */
     639        if (envp)
     640                for (ep = envp; *ep; ep++) {
     641                        if (strncmp (*ep, "PATH=", 5) == 0
     642                            || strncmp (*ep, "Path=", 5) == 0) {
     643                                path_var = *ep + 5;
     644                                break;
     645                        }
     646                }
     647        exec_handle = find_file(exec_path, path_var,
     648                                exec_fname, sizeof(exec_fname));
     649#ifdef KMK
     650        }
     651#endif
     652
     653        /*
     654         * If we couldn't open the file, just assume that Windows will be
     655         * somehow able to find and execute it.  If the first character
     656         * of the command is '/', assume they set SHELL to a Unixy shell
     657         * that have some magic mounts known only to it, and run the whole
     658         * command via $SHELL -c "COMMAND" instead.
     659         */
     660        if (exec_handle == INVALID_HANDLE_VALUE) {
     661                if (exec_path[0] == '/') {
     662                        char *new_argv0;
     663                        char **argvi = argv;
     664                        int arglen = 0;
     665
     666                        strcpy(buf, variable_expand ("$(SHELL)"));
     667                        shell_name = &buf[0];
     668                        strcpy(exec_fname, "-c");
     669                        /* Construct a single command string in argv[0].  */
     670                        while (*argvi) {
     671                                arglen += strlen(*argvi) + 1;
     672                                argvi++;
     673                        }
     674                        new_argv0 = xmalloc(arglen + 1);
     675                        new_argv0[0] = '\0';
     676                        for (argvi = argv; *argvi; argvi++) {
     677                                strcat(new_argv0, *argvi);
     678                                strcat(new_argv0, " ");
     679                        }
     680                        /* Remove the extra blank at the end.  */
     681                        new_argv0[arglen-1] = '\0';
     682                        free(argv[0]);
     683                        argv[0] = new_argv0;
     684                        argv[1] = NULL;
     685                }
     686                else
     687                        file_not_found++;
     688        }
     689        else {
     690                /* Attempt to read the first line of the file */
     691                if (ReadFile( exec_handle,
     692                                buf, sizeof(buf) - 1, /* leave room for trailing NULL */
     693                                &bytes_returned, 0) == FALSE || bytes_returned < 2) {
     694
     695                        pproc->last_err = GetLastError();
     696                        pproc->lerrno = E_IO;
     697                        CloseHandle(exec_handle);
     698                        return(-1);
     699                }
     700                if (buf[0] == '#' && buf[1] == '!') {
     701                        /*
     702                         *  This is a shell script...  Change the command line from
     703                         *      exec_path args to shell_name exec_path args
     704                         */
     705                        char *p;
     706
     707                        /*  Make sure buf is NULL terminated */
     708                        buf[bytes_returned] = 0;
     709                        /*
     710                         * Depending on the file system type, etc. the first line
     711                         * of the shell script may end with newline or newline-carriage-return
     712                         * Whatever it ends with, cut it off.
     713                         */
     714                        p= strchr(buf, '\n');
     715                        if (p)
     716                                *p = 0;
     717                        p = strchr(buf, '\r');
     718                        if (p)
     719                                *p = 0;
     720
     721                        /*
     722                         *  Find base name of shell
     723                         */
     724                        shell_name = strrchr( buf, '/');
     725                        if (shell_name) {
     726                                shell_name++;
     727                        } else {
     728                                shell_name = &buf[2];/* skipping "#!" */
     729                        }
     730
     731                }
     732                CloseHandle(exec_handle);
     733        }
     734
     735        flags = 0;
     736
     737        if (file_not_found)
     738                command_line = make_command_line( shell_name, exec_path, argv);
     739        else {
     740                /* If exec_fname includes whitespace, CreateProcess
     741                   behaves erratically and unreliably, and often fails
     742                   if argv[0] also includes whitespace (and thus will
     743                   be quoted by make_command_line below).  So in that
     744                   case, we don't pass exec_fname as the 1st arg to
     745                   CreateProcess, but instead replace argv[0] with
     746                   exec_fname (to keep its leading directories and
     747                   extension as found by find_file), and pass NULL to
     748                   CreateProcess as its 1st arg.  This works around
     749                   the bugs in CreateProcess, which are probably
     750                   caused by its passing the command to cmd.exe with
     751                   some incorrect quoting.  */
     752                if (!shell_name
     753                    && batch_file_with_spaces(exec_fname)
     754                    && _stricmp(exec_path, argv[0]) == 0) {
     755                        char *new_argv, *p;
     756                        char **argvi;
     757                        int arglen, i;
     758                        pass_null_exec_path = 1;
     759                        /* Rewrite argv[] replacing argv[0] with exec_fname.  */
     760                        for (argvi = argv + 1, arglen = strlen(exec_fname) + 1;
     761                             *argvi;
     762                             argvi++) {
     763                                arglen += strlen(*argvi) + 1;
     764                        }
     765                        new_argv = xmalloc(arglen);
     766                        p = strcpy(new_argv, exec_fname) + strlen(exec_fname) + 1;
     767                        for (argvi = argv + 1, i = 1; *argvi; argvi++, i++) {
     768                                strcpy(p, *argvi);
     769                                argv[i] = p;
     770                                p += strlen(*argvi) + 1;
     771                        }
     772                        argv[i] = NULL;
     773                        free (argv[0]);
     774                        argv[0] = new_argv;
     775                }
     776                command_line = make_command_line( shell_name, exec_fname, argv);
     777        }
     778
     779        if ( command_line == NULL ) {
     780                pproc->last_err = 0;
     781                pproc->lerrno = E_NO_MEM;
     782                return(-1);
     783        }
     784
     785        if (envp) {
     786                if (arr2envblk(envp, &envblk, &envsize_needed) == FALSE) {
     787                        pproc->lerrno = E_NO_MEM;
     788                        free( command_line );
     789                        if ((pproc->last_err == ERROR_INVALID_PARAMETER
     790                             || pproc->last_err == ERROR_MORE_DATA)
     791                            && envsize_needed > 32*1024) {
     792                                fprintf (stderr, "CreateProcess failed, probably because environment is too large (%d bytes).\n",
     793                                         envsize_needed);
     794                        }
     795                        pproc->last_err = 0;
     796                        return(-1);
     797                }
     798        }
     799
     800        if (shell_name || file_not_found || pass_null_exec_path) {
     801                exec_path = 0;  /* Search for the program in %Path% */
     802        } else {
     803                exec_path = exec_fname;
     804        }
     805
     806        /*
     807         *  Set up inherited stdin, stdout, stderr for child
     808         */
     809        memset(&startInfo, '\0', sizeof(startInfo));
     810        GetStartupInfo(&startInfo);
    678811#ifndef KMK
    679         startInfo.dwFlags = STARTF_USESTDHANDLES;
    680 #endif
    681         startInfo.lpReserved = 0;
    682         startInfo.cbReserved2 = 0;
    683         startInfo.lpReserved2 = 0;
    684         startInfo.lpTitle = shell_name ? shell_name : exec_path;
     812        startInfo.dwFlags = STARTF_USESTDHANDLES;
     813#endif
     814        startInfo.lpReserved = 0;
     815        startInfo.cbReserved2 = 0;
     816        startInfo.lpReserved2 = 0;
    685817#ifndef KMK
    686         startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
    687         startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
    688         startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];
     818        startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
     819        startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
     820        startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];
    689821#else
    690         if (    pproc->sv_stdin[1]
    691                 ||  pproc->sv_stdout[1]
    692                 ||  pproc->sv_stderr[1]) {
    693                 startInfo.dwFlags = STARTF_USESTDHANDLES;
    694                 startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
    695                 startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
    696                 startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];
    697         } else {
    698                 startInfo.dwFlags = 0;
    699                 startInfo.hStdInput = 0;
    700                 startInfo.hStdOutput = 0;
    701                 startInfo.hStdError = 0;
    702         }
    703 #endif
    704 
    705         if (as_user) {
    706                 if (envblk) free(envblk);
    707                 return -1;
    708         } else {
    709                 DB (DB_JOBS, ("CreateProcess(%s,%s,...)\n",
    710                         exec_path ? exec_path : "NULL",
    711                         command_line ? command_line : "NULL"));
     822        if (   ((HANDLE)pproc->sv_stdin[1]  != INVALID_HANDLE_VALUE && pproc->sv_stdin[1])
     823            || ((HANDLE)pproc->sv_stdout[1] != INVALID_HANDLE_VALUE && pproc->sv_stdout[1])
     824            || ((HANDLE)pproc->sv_stderr[1] != INVALID_HANDLE_VALUE && pproc->sv_stderr[1]) ) {
     825                startInfo.dwFlags = STARTF_USESTDHANDLES;
     826                startInfo.hStdInput = (HANDLE)pproc->sv_stdin[1];
     827                startInfo.hStdOutput = (HANDLE)pproc->sv_stdout[1];
     828                startInfo.hStdError = (HANDLE)pproc->sv_stderr[1];
     829        } else {
     830                startInfo.dwFlags = 0;
     831                startInfo.hStdInput = 0;
     832                startInfo.hStdOutput = 0;
     833                startInfo.hStdError = 0;
     834        }
     835#endif
     836
     837        if (as_user) {
     838                free(envblk);
     839                return -1;
     840        } else {
     841                DB (DB_JOBS, ("CreateProcess(%s,%s,...)\n",
     842                        exec_path ? exec_path : "NULL",
     843                        command_line ? command_line : "NULL"));
    712844#ifdef KMK
    713845                if (exec_fname[0])
     
    726858                }
    727859#endif
    728                 if (CreateProcess(
    729                         exec_path,
    730                         command_line,
    731                         NULL,
    732                         0, /* default security attributes for thread */
    733                         TRUE, /* inherit handles (e.g. helper pipes, oserv socket) */
    734                         flags,
    735                         envblk,
    736                         0, /* default starting directory */
    737                         &startInfo,
    738                         &procInfo) == FALSE) {
    739 
    740                         pproc->last_err = GetLastError();
    741                         pproc->lerrno = E_FORK;
    742 #ifdef KMK
    743                         if (pproc->last_err == ERROR_FILE_NOT_FOUND)
    744                                 pproc->exit_code = 127; /* see execve failure in job.c. */
    745 #endif
    746                         fprintf(stderr, "process_begin: CreateProcess(%s, %s, ...) failed.\n",
     860                if (CreateProcess(
     861                        exec_path,
     862                        command_line,
     863                        NULL,
     864                        0, /* default security attributes for thread */
     865                        TRUE, /* inherit handles (e.g. helper pipes, oserv socket) */
     866                        flags,
     867                        envblk,
     868                        0, /* default starting directory */
     869                        &startInfo,
     870                        &procInfo) == FALSE) {
     871
     872                        pproc->last_err = GetLastError();
     873                        pproc->lerrno = E_FORK;
     874                        fprintf(stderr, "process_begin: CreateProcess(%s, %s, ...) failed.\n",
    747875                                exec_path ? exec_path : "NULL", command_line);
    748                         if (envblk) free(envblk);
    749                         free( command_line );
    750                         return(-1);
    751                 }
    752 #ifdef KMK
    753                 switch (process_priority) {
    754                 case 1: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_IDLE); break;
    755                 case 2: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_BELOW_NORMAL); break;
    756                 case 3: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_NORMAL); break;
    757                 case 4: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_HIGHEST); break;
    758                 case 5: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_TIME_CRITICAL); break;
    759                 }
    760                 ResumeThread(procInfo.hThread);
    761 #endif
    762         }
    763 
    764         pproc->pid = (pid_t)procInfo.hProcess;
    765         /* Close the thread handle -- we'll just watch the process */
    766         CloseHandle(procInfo.hThread);
    767 
    768         /* Close the halves of the pipes we don't need */
    769 #ifndef KMK
    770         CloseHandle((HANDLE)pproc->sv_stdin[1]);
    771         CloseHandle((HANDLE)pproc->sv_stdout[1]);
    772         CloseHandle((HANDLE)pproc->sv_stderr[1]);
    773         pproc->sv_stdin[1] = 0;
    774         pproc->sv_stdout[1] = 0;
    775         pproc->sv_stderr[1] = 0;
    776 #else
    777         if ((HANDLE)pproc->sv_stdin[1]) {
    778                 CloseHandle((HANDLE)pproc->sv_stdin[1]);
    779                 pproc->sv_stdin[1] = 0;
    780         }
    781         if ((HANDLE)pproc->sv_stdout[1]) {
    782                 CloseHandle((HANDLE)pproc->sv_stdout[1]);
    783                 pproc->sv_stdout[1] = 0;
    784         }
    785         if ((HANDLE)pproc->sv_stderr[1]) {
    786                 CloseHandle((HANDLE)pproc->sv_stderr[1]);
    787                 pproc->sv_stderr[1] = 0;
    788         }
    789 #endif
    790 
    791         free( command_line );
    792         if (envblk) free(envblk);
    793         pproc->lerrno=0;
    794         return 0;
    795 }
    796 
    797 
    798 
     876                        free(envblk);
     877                        free( command_line );
     878                        return(-1);
     879                }
     880#ifdef KMK
     881                switch (process_priority) {
     882                case 1: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_IDLE); break;
     883                case 2: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_BELOW_NORMAL); break;
     884                case 3: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_NORMAL); break;
     885                case 4: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_HIGHEST); break;
     886                case 5: SetThreadPriority(procInfo.hThread, THREAD_PRIORITY_TIME_CRITICAL); break;
     887                }
     888                ResumeThread(procInfo.hThread);
     889#endif
     890        }
     891
     892        pproc->pid = (pid_t)procInfo.hProcess;
     893        /* Close the thread handle -- we'll just watch the process */
     894        CloseHandle(procInfo.hThread);
     895
     896        /* Close the halves of the pipes we don't need */
     897        if ((HANDLE)pproc->sv_stdin[1] != INVALID_HANDLE_VALUE && pproc->sv_stdin[1])
     898          CloseHandle((HANDLE)pproc->sv_stdin[1]);
     899        if ((HANDLE)pproc->sv_stdout[1] != INVALID_HANDLE_VALUE && pproc->sv_stdout[1])
     900          CloseHandle((HANDLE)pproc->sv_stdout[1]);
     901        if ((HANDLE)pproc->sv_stderr[1] != INVALID_HANDLE_VALUE && pproc->sv_stderr[1])
     902          CloseHandle((HANDLE)pproc->sv_stderr[1]);
     903        pproc->sv_stdin[1] = 0;
     904        pproc->sv_stdout[1] = 0;
     905        pproc->sv_stderr[1] = 0;
     906
     907        free( command_line );
     908        free(envblk);
     909        pproc->lerrno=0;
     910        return 0;
     911}
     912
     913
     914
     915#if 0   /* unused */
    799916static DWORD
    800917proc_stdin_thread(sub_process *pproc)
    801918{
    802         DWORD in_done;
    803         for (;;) {
    804                 if (WriteFile( (HANDLE) pproc->sv_stdin[0], pproc->inp, pproc->incnt,
    805                                         &in_done, NULL) == FALSE)
    806                         _endthreadex(0);
    807                 // This if should never be true for anonymous pipes, but gives
    808                 // us a chance to change I/O mechanisms later
    809                 if (in_done < pproc->incnt) {
    810                         pproc->incnt -= in_done;
    811                         pproc->inp += in_done;
    812                 } else {
    813                         _endthreadex(0);
    814                 }
    815         }
    816         return 0; // for compiler warnings only.. not reached
     919        DWORD in_done;
     920        for (;;) {
     921                if (WriteFile( (HANDLE) pproc->sv_stdin[0], pproc->inp, pproc->incnt,
     922                                        &in_done, NULL) == FALSE)
     923                        _endthreadex(0);
     924                // This if should never be true for anonymous pipes, but gives
     925                // us a chance to change I/O mechanisms later
     926                if (in_done < pproc->incnt) {
     927                        pproc->incnt -= in_done;
     928                        pproc->inp += in_done;
     929                } else {
     930                        _endthreadex(0);
     931                }
     932        }
     933        return 0; // for compiler warnings only.. not reached
    817934}
    818935
     
    820937proc_stdout_thread(sub_process *pproc)
    821938{
    822         DWORD bufsize = 1024;
    823         char c;
    824         DWORD nread;
    825         pproc->outp = malloc(bufsize);
    826         if (pproc->outp == NULL)
    827                 _endthreadex(0);
    828         pproc->outcnt = 0;
    829 
    830         for (;;) {
    831                 if (ReadFile( (HANDLE)pproc->sv_stdout[0], &c, 1, &nread, NULL)
    832                                         == FALSE) {
    833 /*                      map_windows32_error_to_string(GetLastError());*/
    834                         _endthreadex(0);
    835                 }
    836                 if (nread == 0)
    837                         _endthreadex(0);
    838                 if (pproc->outcnt + nread > bufsize) {
    839                         bufsize += nread + 512;
    840                         pproc->outp = realloc(pproc->outp, bufsize);
    841                         if (pproc->outp == NULL) {
    842                                 pproc->outcnt = 0;
    843                                 _endthreadex(0);
    844                         }
    845                 }
    846                 pproc->outp[pproc->outcnt++] = c;
    847         }
    848         return 0;
     939        DWORD bufsize = 1024;
     940        char c;
     941        DWORD nread;
     942        pproc->outp = malloc(bufsize);
     943        if (pproc->outp == NULL)
     944                _endthreadex(0);
     945        pproc->outcnt = 0;
     946
     947        for (;;) {
     948                if (ReadFile( (HANDLE)pproc->sv_stdout[0], &c, 1, &nread, NULL)
     949                                        == FALSE) {
     950/*                      map_windows32_error_to_string(GetLastError());*/
     951                        _endthreadex(0);
     952                }
     953                if (nread == 0)
     954                        _endthreadex(0);
     955                if (pproc->outcnt + nread > bufsize) {
     956                        bufsize += nread + 512;
     957                        pproc->outp = realloc(pproc->outp, bufsize);
     958                        if (pproc->outp == NULL) {
     959                                pproc->outcnt = 0;
     960                                _endthreadex(0);
     961                        }
     962                }
     963                pproc->outp[pproc->outcnt++] = c;
     964        }
     965        return 0;
    849966}
    850967
     
    852969proc_stderr_thread(sub_process *pproc)
    853970{
    854         DWORD bufsize = 1024;
    855         char c;
    856         DWORD nread;
    857         pproc->errp = malloc(bufsize);
    858         if (pproc->errp == NULL)
    859                 _endthreadex(0);
    860         pproc->errcnt = 0;
    861 
    862         for (;;) {
    863                 if (ReadFile( (HANDLE)pproc->sv_stderr[0], &c, 1, &nread, NULL) == FALSE) {
    864                         map_windows32_error_to_string(GetLastError());
    865                         _endthreadex(0);
    866                 }
    867                 if (nread == 0)
    868                         _endthreadex(0);
    869                 if (pproc->errcnt + nread > bufsize) {
    870                         bufsize += nread + 512;
    871                         pproc->errp = realloc(pproc->errp, bufsize);
    872                         if (pproc->errp == NULL) {
    873                                 pproc->errcnt = 0;
    874                                 _endthreadex(0);
    875                         }
    876                 }
    877                 pproc->errp[pproc->errcnt++] = c;
    878         }
    879         return 0;
     971        DWORD bufsize = 1024;
     972        char c;
     973        DWORD nread;
     974        pproc->errp = malloc(bufsize);
     975        if (pproc->errp == NULL)
     976                _endthreadex(0);
     977        pproc->errcnt = 0;
     978
     979        for (;;) {
     980                if (ReadFile( (HANDLE)pproc->sv_stderr[0], &c, 1, &nread, NULL) == FALSE) {
     981                        map_windows32_error_to_string(GetLastError());
     982                        _endthreadex(0);
     983                }
     984                if (nread == 0)
     985                        _endthreadex(0);
     986                if (pproc->errcnt + nread > bufsize) {
     987                        bufsize += nread + 512;
     988                        pproc->errp = realloc(pproc->errp, bufsize);
     989                        if (pproc->errp == NULL) {
     990                                pproc->errcnt = 0;
     991                                _endthreadex(0);
     992                        }
     993                }
     994                pproc->errp[pproc->errcnt++] = c;
     995        }
     996        return 0;
    880997}
    881998
     
    8901007 * Notes/Dependencies:
    8911008 */
    892         long
     1009        long
    8931010process_pipe_io(
    894         HANDLE proc,
    895         char *stdin_data,
    896         int stdin_data_len)
    897 {
    898         sub_process *pproc = (sub_process *)proc;
    899         bool_t stdin_eof = FALSE, stdout_eof = FALSE, stderr_eof = FALSE;
    900         HANDLE childhand = (HANDLE) pproc->pid;
    901         HANDLE tStdin = NULL, tStdout = NULL, tStderr = NULL;
    902         unsigned int dwStdin, dwStdout, dwStderr;
    903         HANDLE wait_list[4];
    904         DWORD wait_count;
    905         DWORD wait_return;
    906         HANDLE ready_hand;
    907         bool_t child_dead = FALSE;
    908         BOOL GetExitCodeResult;
     1011        HANDLE proc,
     1012        char *stdin_data,
     1013        int stdin_data_len)
     1014{
     1015        sub_process *pproc = (sub_process *)proc;
     1016        bool_t stdin_eof = FALSE, stdout_eof = FALSE, stderr_eof = FALSE;
     1017        HANDLE childhand = (HANDLE) pproc->pid;
     1018        HANDLE tStdin = NULL, tStdout = NULL, tStderr = NULL;
     1019        unsigned int dwStdin, dwStdout, dwStderr;
     1020        HANDLE wait_list[4];
     1021        DWORD wait_count;
     1022        DWORD wait_return;
     1023        HANDLE ready_hand;
     1024        bool_t child_dead = FALSE;
     1025        BOOL GetExitCodeResult;
    9091026#ifdef KMK
    9101027        assert (pproc->enmType == kRegular);
    9111028#endif
    9121029
    913         /*
    914         *  Create stdin thread, if needed
    915         */
    916         pproc->inp = stdin_data;
    917         pproc->incnt = stdin_data_len;
    918         if (!pproc->inp) {
    919                 stdin_eof = TRUE;
    920                 CloseHandle((HANDLE)pproc->sv_stdin[0]);
    921                 pproc->sv_stdin[0] = 0;
    922         } else {
    923                 tStdin = (HANDLE) _beginthreadex( 0, 1024,
    924                         (unsigned (__stdcall *) (void *))proc_stdin_thread,
    925                                                   pproc, 0, &dwStdin);
    926                 if (tStdin == 0) {
    927                         pproc->last_err = GetLastError();
    928                         pproc->lerrno = E_SCALL;
    929                         goto done;
    930                 }
    931         }
    932 
    933         /*
    934         *   Assume child will produce stdout and stderr
    935         */
    936         tStdout = (HANDLE) _beginthreadex( 0, 1024,
    937                 (unsigned (__stdcall *) (void *))proc_stdout_thread, pproc, 0,
    938                 &dwStdout);
    939         tStderr = (HANDLE) _beginthreadex( 0, 1024,
    940                 (unsigned (__stdcall *) (void *))proc_stderr_thread, pproc, 0,
    941                 &dwStderr);
    942 
    943         if (tStdout == 0 || tStderr == 0) {
    944 
    945                 pproc->last_err = GetLastError();
    946                 pproc->lerrno = E_SCALL;
    947                 goto done;
    948         }
    949 
    950 
    951         /*
    952         *  Wait for all I/O to finish and for the child process to exit
    953         */
    954 
    955         while (!stdin_eof || !stdout_eof || !stderr_eof || !child_dead) {
    956                 wait_count = 0;
    957                 if (!stdin_eof) {
    958                         wait_list[wait_count++] = tStdin;
    959                 }
    960                 if (!stdout_eof) {
    961                         wait_list[wait_count++] = tStdout;
    962                 }
    963                 if (!stderr_eof) {
    964                         wait_list[wait_count++] = tStderr;
    965                 }
    966                 if (!child_dead) {
    967                         wait_list[wait_count++] = childhand;
    968                 }
    969 
    970                 wait_return = WaitForMultipleObjects(wait_count, wait_list,
    971                         FALSE, /* don't wait for all: one ready will do */
    972                         child_dead? 1000 :INFINITE); /* after the child dies, subthreads have
    973                                 one second to collect all remaining output */
     1030        /*
     1031        *  Create stdin thread, if needed
     1032        */
     1033        pproc->inp = stdin_data;
     1034        pproc->incnt = stdin_data_len;
     1035        if (!pproc->inp) {
     1036                stdin_eof = TRUE;
     1037                CloseHandle((HANDLE)pproc->sv_stdin[0]);
     1038                pproc->sv_stdin[0] = 0;
     1039        } else {
     1040                tStdin = (HANDLE) _beginthreadex( 0, 1024,
     1041                        (unsigned (__stdcall *) (void *))proc_stdin_thread,
     1042                                                  pproc, 0, &dwStdin);
     1043                if (tStdin == 0) {
     1044                        pproc->last_err = GetLastError();
     1045                        pproc->lerrno = E_SCALL;
     1046                        goto done;
     1047                }
     1048        }
     1049
     1050        /*
     1051        *   Assume child will produce stdout and stderr
     1052        */
     1053        tStdout = (HANDLE) _beginthreadex( 0, 1024,
     1054                (unsigned (__stdcall *) (void *))proc_stdout_thread, pproc, 0,
     1055                &dwStdout);
     1056        tStderr = (HANDLE) _beginthreadex( 0, 1024,
     1057                (unsigned (__stdcall *) (void *))proc_stderr_thread, pproc, 0,
     1058                &dwStderr);
     1059
     1060        if (tStdout == 0 || tStderr == 0) {
     1061
     1062                pproc->last_err = GetLastError();
     1063                pproc->lerrno = E_SCALL;
     1064                goto done;
     1065        }
     1066
     1067
     1068        /*
     1069        *  Wait for all I/O to finish and for the child process to exit
     1070        */
     1071
     1072        while (!stdin_eof || !stdout_eof || !stderr_eof || !child_dead) {
     1073                wait_count = 0;
     1074                if (!stdin_eof) {
     1075                        wait_list[wait_count++] = tStdin;
     1076                }
     1077                if (!stdout_eof) {
     1078                        wait_list[wait_count++] = tStdout;
     1079                }
     1080                if (!stderr_eof) {
     1081                        wait_list[wait_count++] = tStderr;
     1082                }
     1083                if (!child_dead) {
     1084                        wait_list[wait_count++] = childhand;
     1085                }
     1086
     1087                wait_return = WaitForMultipleObjects(wait_count, wait_list,
     1088                        FALSE, /* don't wait for all: one ready will do */
     1089                        child_dead? 1000 :INFINITE); /* after the child dies, subthreads have
     1090                                one second to collect all remaining output */
    9741091
    9751092                if (wait_return == WAIT_FAILED) {
    976 /*                      map_windows32_error_to_string(GetLastError());*/
    977                         pproc->last_err = GetLastError();
    978                         pproc->lerrno = E_SCALL;
    979                         goto done;
    980                 }
    981 
    982                 ready_hand = wait_list[wait_return - WAIT_OBJECT_0];
    983 
    984                 if (ready_hand == tStdin) {
    985                         CloseHandle((HANDLE)pproc->sv_stdin[0]);
    986                         pproc->sv_stdin[0] = 0;
    987                         CloseHandle(tStdin);
    988                         tStdin = 0;
    989                         stdin_eof = TRUE;
    990 
    991                 } else if (ready_hand == tStdout) {
    992 
    993                         CloseHandle((HANDLE)pproc->sv_stdout[0]);
    994                         pproc->sv_stdout[0] = 0;
    995                         CloseHandle(tStdout);
    996                         tStdout = 0;
    997                         stdout_eof = TRUE;
    998 
    999                 } else if (ready_hand == tStderr) {
    1000 
    1001                         CloseHandle((HANDLE)pproc->sv_stderr[0]);
    1002                         pproc->sv_stderr[0] = 0;
    1003                         CloseHandle(tStderr);
    1004                         tStderr = 0;
    1005                         stderr_eof = TRUE;
    1006 
    1007                 } else if (ready_hand == childhand) {
    1008 
    1009                         DWORD ierr;
    1010                         GetExitCodeResult = GetExitCodeProcess(childhand, &ierr);
    1011                         if (ierr == CONTROL_C_EXIT) {
    1012                                 pproc->signal = SIGINT;
    1013                         } else {
    1014                                 pproc->exit_code = ierr;
    1015                         }
    1016                         if (GetExitCodeResult == FALSE) {
    1017                                 pproc->last_err = GetLastError();
    1018                                 pproc->lerrno = E_SCALL;
    1019                                 goto done;
    1020                         }
    1021                         child_dead = TRUE;
    1022 
    1023                 } else {
    1024 
    1025                         /* ?? Got back a handle we didn't query ?? */
    1026                         pproc->last_err = 0;
    1027                         pproc->lerrno = E_FAIL;
    1028                         goto done;
    1029                 }
    1030         }
     1093/*                      map_windows32_error_to_string(GetLastError());*/
     1094                        pproc->last_err = GetLastError();
     1095                        pproc->lerrno = E_SCALL;
     1096                        goto done;
     1097                }
     1098
     1099                ready_hand = wait_list[wait_return - WAIT_OBJECT_0];
     1100
     1101                if (ready_hand == tStdin) {
     1102                        CloseHandle((HANDLE)pproc->sv_stdin[0]);
     1103                        pproc->sv_stdin[0] = 0;
     1104                        CloseHandle(tStdin);
     1105                        tStdin = 0;
     1106                        stdin_eof = TRUE;
     1107
     1108                } else if (ready_hand == tStdout) {
     1109
     1110                        CloseHandle((HANDLE)pproc->sv_stdout[0]);
     1111                        pproc->sv_stdout[0] = 0;
     1112                        CloseHandle(tStdout);
     1113                        tStdout = 0;
     1114                        stdout_eof = TRUE;
     1115
     1116                } else if (ready_hand == tStderr) {
     1117
     1118                        CloseHandle((HANDLE)pproc->sv_stderr[0]);
     1119                        pproc->sv_stderr[0] = 0;
     1120                        CloseHandle(tStderr);
     1121                        tStderr = 0;
     1122                        stderr_eof = TRUE;
     1123
     1124                } else if (ready_hand == childhand) {
     1125
     1126                        DWORD ierr;
     1127                        GetExitCodeResult = GetExitCodeProcess(childhand, &ierr);
     1128                        if (ierr == CONTROL_C_EXIT) {
     1129                                pproc->signal = SIGINT;
     1130                        } else {
     1131                                pproc->exit_code = ierr;
     1132                        }
     1133                        if (GetExitCodeResult == FALSE) {
     1134                                pproc->last_err = GetLastError();
     1135                                pproc->lerrno = E_SCALL;
     1136                                goto done;
     1137                        }
     1138                        child_dead = TRUE;
     1139
     1140                } else {
     1141
     1142                        /* ?? Got back a handle we didn't query ?? */
     1143                        pproc->last_err = 0;
     1144                        pproc->lerrno = E_FAIL;
     1145                        goto done;
     1146                }
     1147        }
    10311148
    10321149 done:
    1033         if (tStdin != 0)
    1034                 CloseHandle(tStdin);
    1035         if (tStdout != 0)
    1036                 CloseHandle(tStdout);
    1037         if (tStderr != 0)
    1038                 CloseHandle(tStderr);
    1039 
    1040         if (pproc->lerrno)
    1041                 return(-1);
    1042         else
    1043                 return(0);
    1044 
    1045 }
     1150        if (tStdin != 0)
     1151                CloseHandle(tStdin);
     1152        if (tStdout != 0)
     1153                CloseHandle(tStdout);
     1154        if (tStderr != 0)
     1155                CloseHandle(tStderr);
     1156
     1157        if (pproc->lerrno)
     1158                return(-1);
     1159        else
     1160                return(0);
     1161
     1162}
     1163#endif  /* unused */
    10461164
    10471165#ifndef KMK /* unused */
     
    10551173 * Notes/Dependencies:
    10561174 */
    1057         long
     1175        long
    10581176process_file_io(
    1059         HANDLE proc)
    1060 {
    1061         sub_process *pproc;
    1062         if (proc == NULL)
    1063                 pproc = process_wait_for_any_private();
    1064         else
    1065                 pproc = (sub_process *)proc;
    1066 
    1067         /* some sort of internal error */
    1068         if (!pproc)
    1069                 return -1;
     1177        HANDLE proc)
     1178{
     1179        sub_process *pproc;
     1180
     1181        if (proc == NULL)
     1182                pproc = process_wait_for_any_private(1, 0);
     1183        else
     1184                pproc = (sub_process *)proc;
     1185
     1186        /* some sort of internal error */
     1187        if (!pproc)
     1188                return -1;
    10701189
    10711190        return process_file_io_private(proc, TRUE);
     
    10841203        DWORD ierr;
    10851204
    1086         childhand = (HANDLE) pproc->pid;
    1087 
    1088         /*
    1089         * This function is poorly named, and could also be used just to wait
    1090         * for child death if you're doing your own pipe I/O.  If that is
    1091         * the case, close the pipe handles here.
    1092         */
    1093         if (pproc->sv_stdin[0]) {
    1094                 CloseHandle((HANDLE)pproc->sv_stdin[0]);
    1095                 pproc->sv_stdin[0] = 0;
    1096         }
    1097         if (pproc->sv_stdout[0]) {
    1098                 CloseHandle((HANDLE)pproc->sv_stdout[0]);
    1099                 pproc->sv_stdout[0] = 0;
    1100         }
    1101         if (pproc->sv_stderr[0]) {
    1102                 CloseHandle((HANDLE)pproc->sv_stderr[0]);
    1103                 pproc->sv_stderr[0] = 0;
    1104         }
     1205        childhand = (HANDLE) pproc->pid;
     1206
     1207        /*
     1208        * This function is poorly named, and could also be used just to wait
     1209        * for child death if you're doing your own pipe I/O.  If that is
     1210        * the case, close the pipe handles here.
     1211        */
     1212        if (pproc->sv_stdin[0]) {
     1213                CloseHandle((HANDLE)pproc->sv_stdin[0]);
     1214                pproc->sv_stdin[0] = 0;
     1215        }
     1216        if (pproc->sv_stdout[0]) {
     1217                CloseHandle((HANDLE)pproc->sv_stdout[0]);
     1218                pproc->sv_stdout[0] = 0;
     1219        }
     1220        if (pproc->sv_stderr[0]) {
     1221                CloseHandle((HANDLE)pproc->sv_stderr[0]);
     1222                pproc->sv_stderr[0] = 0;
     1223        }
    11051224
    11061225#ifdef KMK
     
    11101229#endif
    11111230
    1112         /*
    1113          *  Wait for the child process to exit it we didn't do that already.
    1114          */
    1115         if (fNeedToWait) {
    1116                 wait_return = WaitForSingleObject(childhand, INFINITE);
    1117                 if (wait_return != WAIT_OBJECT_0) {
    1118 /*                      map_windows32_error_to_string(GetLastError());*/
    1119                         pproc->last_err = GetLastError();
    1120                         pproc->lerrno = E_SCALL;
    1121                         goto done2;
    1122                 }
    1123         }
    1124 
    1125         GetExitCodeResult = GetExitCodeProcess(childhand, &ierr);
    1126         if (ierr == CONTROL_C_EXIT) {
    1127                 pproc->signal = SIGINT;
    1128         } else {
    1129                 pproc->exit_code = ierr;
    1130         }
    1131         if (GetExitCodeResult == FALSE) {
    1132                 pproc->last_err = GetLastError();
    1133                 pproc->lerrno = E_SCALL;
    1134         }
     1231        /*
     1232         *  Wait for the child process to exit
     1233         */
     1234
     1235    if (fNeedToWait) { /* bird */
     1236        wait_return = WaitForSingleObject(childhand, INFINITE);
     1237
     1238        if (wait_return != WAIT_OBJECT_0) {
     1239/*              map_windows32_error_to_string(GetLastError());*/
     1240                pproc->last_err = GetLastError();
     1241                pproc->lerrno = E_SCALL;
     1242                goto done2;
     1243        }
     1244    } /* bird */
     1245
     1246        GetExitCodeResult = GetExitCodeProcess(childhand, &ierr);
     1247        if (ierr == CONTROL_C_EXIT) {
     1248                pproc->signal = SIGINT;
     1249        } else {
     1250                pproc->exit_code = ierr;
     1251        }
     1252        if (GetExitCodeResult == FALSE) {
     1253                pproc->last_err = GetLastError();
     1254                pproc->lerrno = E_SCALL;
     1255        }
    11351256
    11361257done2:
    1137         if (pproc->lerrno)
    1138                 return(-1);
    1139         else
    1140                 return(0);
     1258        if (pproc->lerrno)
     1259                return(-1);
     1260        else
     1261                return(0);
    11411262
    11421263}
     
    11441265/*
    11451266 * Description:  Clean up any leftover handles, etc.  It is up to the
    1146  * caller to manage and free the input, ouput, and stderr buffers.
     1267 * caller to manage and free the input, output, and stderr buffers.
    11471268 */
    1148         void
     1269        void
    11491270process_cleanup(
    1150         HANDLE proc)
    1151 {
    1152         sub_process *pproc = (sub_process *)proc;
    1153         int i;
    1154 
    1155 #ifdef KMK
    1156         if (pproc->enmType == kRegular) {
    1157 #endif
    1158 
    1159         if (pproc->using_pipes) {
    1160                 for (i= 0; i <= 1; i++) {
    1161                         if ((HANDLE)pproc->sv_stdin[i])
    1162                                 CloseHandle((HANDLE)pproc->sv_stdin[i]);
    1163                         if ((HANDLE)pproc->sv_stdout[i])
    1164                                 CloseHandle((HANDLE)pproc->sv_stdout[i]);
    1165                         if ((HANDLE)pproc->sv_stderr[i])
    1166                                 CloseHandle((HANDLE)pproc->sv_stderr[i]);
    1167                 }
    1168         }
    1169         if ((HANDLE)pproc->pid)
    1170                 CloseHandle((HANDLE)pproc->pid);
    1171 #ifdef KMK
    1172         } else if (pproc->enmType == kSubmit) {
    1173             kSubmitSubProcCleanup(pproc->clue);
    1174         } else {
    1175             assert(0);
    1176             return;
    1177         }
    1178         pproc->enmType = kSubProcFreed;
    1179 #endif
    1180 
    1181         free(pproc);
     1271        HANDLE proc)
     1272{
     1273        sub_process *pproc = (sub_process *)proc;
     1274        int i;
     1275
     1276#ifdef KMK
     1277    if (pproc->enmType == kRegular) {
     1278#endif
     1279        if (pproc->using_pipes) {
     1280                for (i= 0; i <= 1; i++) {
     1281                        if ((HANDLE)pproc->sv_stdin[i]
     1282                            && (HANDLE)pproc->sv_stdin[i] != INVALID_HANDLE_VALUE)
     1283                                CloseHandle((HANDLE)pproc->sv_stdin[i]);
     1284                        if ((HANDLE)pproc->sv_stdout[i]
     1285                            && (HANDLE)pproc->sv_stdout[i] != INVALID_HANDLE_VALUE)
     1286                                CloseHandle((HANDLE)pproc->sv_stdout[i]);
     1287                        if ((HANDLE)pproc->sv_stderr[i]
     1288                            && (HANDLE)pproc->sv_stderr[i] != INVALID_HANDLE_VALUE)
     1289                                CloseHandle((HANDLE)pproc->sv_stderr[i]);
     1290                }
     1291        }
     1292        if ((HANDLE)pproc->pid)
     1293                CloseHandle((HANDLE)pproc->pid);
     1294#ifdef KMK
     1295    } else if (pproc->enmType == kSubmit) {
     1296        kSubmitSubProcCleanup(pproc->clue);
     1297    } else {
     1298       assert(0);
     1299       return;
     1300    }
     1301        pproc->enmType = kSubProcFreed;
     1302#endif
     1303
     1304        free(pproc);
    11821305}
    11831306
     
    11851308/*
    11861309 * Description:
    1187  *      Create a command line buffer to pass to CreateProcess
     1310 *      Create a command line buffer to pass to CreateProcess
    11881311 *
    11891312 * Returns:  the buffer or NULL for failure
    1190  *      Shell case:  sh_name a:/full/path/to/script argv[1] argv[2] ...
     1313 *      Shell case:  sh_name a:/full/path/to/script argv[1] argv[2] ...
    11911314 *  Otherwise:   argv[0] argv[1] argv[2] ...
    11921315 *
     
    11991322make_command_line( char *shell_name, char *full_exec_path, char **argv)
    12001323{
    1201         int             argc = 0;
    1202         char**          argvi;
    1203         int*            enclose_in_quotes = NULL;
    1204         int*            enclose_in_quotes_i;
    1205         unsigned int    bytes_required = 0;
    1206         char*           command_line;
    1207         char*           command_line_i;
    1208         int  cygwin_mode = 0; /* HAVE_CYGWIN_SHELL */
    1209         int have_sh = 0; /* HAVE_CYGWIN_SHELL */
    1210 #undef HAVE_CYGWIN_SHELL
     1324        int             argc = 0;
     1325        char**          argvi;
     1326        int*            enclose_in_quotes = NULL;
     1327        int*            enclose_in_quotes_i;
     1328        unsigned int    bytes_required = 0;
     1329        char*           command_line;
     1330        char*           command_line_i;
     1331        int  cygwin_mode = 0; /* HAVE_CYGWIN_SHELL */
     1332        int have_sh = 0; /* HAVE_CYGWIN_SHELL */
     1333#undef HAVE_CYGWIN_SHELL /* bird: paranoia */
    12111334#ifdef HAVE_CYGWIN_SHELL
    1212         have_sh = (shell_name != NULL || strstr(full_exec_path, "sh.exe"));
    1213         cygwin_mode = 1;
    1214 #endif
    1215 
    1216         if (shell_name && full_exec_path) {
    1217                 bytes_required
    1218                   = strlen(shell_name) + 1 + strlen(full_exec_path);
    1219                 /*
    1220                  * Skip argv[0] if any, when shell_name is given.
    1221                  */
    1222                 if (*argv) argv++;
    1223                 /*
    1224                  * Add one for the intervening space.
    1225                  */
    1226                 if (*argv) bytes_required++;
    1227         }
    1228 
    1229         argvi = argv;
    1230         while (*(argvi++)) argc++;
    1231 
    1232         if (argc) {
    1233                 enclose_in_quotes = (int*) calloc(1, argc * sizeof(int));
    1234 
    1235                 if (!enclose_in_quotes) {
    1236                         return NULL;
    1237                 }
    1238         }
    1239 
    1240         /* We have to make one pass through each argv[i] to see if we need
    1241          * to enclose it in ", so we might as well figure out how much
    1242          * memory we'll need on the same pass.
    1243          */
    1244 
    1245         argvi = argv;
    1246         enclose_in_quotes_i = enclose_in_quotes;
    1247         while(*argvi) {
    1248                 char* p = *argvi;
    1249                 unsigned int backslash_count = 0;
    1250 
    1251                 /*
    1252                  * We have to enclose empty arguments in ".
    1253                  */
    1254                 if (!(*p)) *enclose_in_quotes_i = 1;
    1255 
    1256                 while(*p) {
    1257                         switch (*p) {
    1258                         case '\"':
    1259                                 /*
    1260                                  * We have to insert a backslash for each "
    1261                                  * and each \ that precedes the ".
    1262                                  */
    1263                                 bytes_required += (backslash_count + 1);
    1264                                 backslash_count = 0;
    1265                                 break;
     1335        have_sh = (shell_name != NULL || strstr(full_exec_path, "sh.exe"));
     1336        cygwin_mode = 1;
     1337#endif
     1338
     1339        if (shell_name && full_exec_path) {
     1340                bytes_required
     1341                  = strlen(shell_name) + 1 + strlen(full_exec_path);
     1342                /*
     1343                 * Skip argv[0] if any, when shell_name is given.
     1344                 * The special case of "-c" in full_exec_path means
     1345                 * argv[0] is not the shell name, but the command string
     1346                 * to pass to the shell.
     1347                 */
     1348                if (*argv && strcmp(full_exec_path, "-c")) argv++;
     1349                /*
     1350                 * Add one for the intervening space.
     1351                 */
     1352                if (*argv) bytes_required++;
     1353        }
     1354
     1355        argvi = argv;
     1356        while (*(argvi++)) argc++;
     1357
     1358        if (argc) {
     1359                enclose_in_quotes = (int*) calloc(1, argc * sizeof(int));
     1360
     1361                if (!enclose_in_quotes) {
     1362                        return NULL;
     1363                }
     1364        }
     1365
     1366        /* We have to make one pass through each argv[i] to see if we need
     1367         * to enclose it in ", so we might as well figure out how much
     1368         * memory we'll need on the same pass.
     1369         */
     1370
     1371        argvi = argv;
     1372        enclose_in_quotes_i = enclose_in_quotes;
     1373        while(*argvi) {
     1374                char* p = *argvi;
     1375                unsigned int backslash_count = 0;
     1376
     1377                /*
     1378                 * We have to enclose empty arguments in ".
     1379                 */
     1380                if (!(*p)) *enclose_in_quotes_i = 1;
     1381
     1382                while(*p) {
     1383                        switch (*p) {
     1384                        case '\"':
     1385                                /*
     1386                                 * We have to insert a backslash for each "
     1387                                 * and each \ that precedes the ".
     1388                                 */
     1389                                bytes_required += (backslash_count + 1);
     1390                                backslash_count = 0;
     1391                                break;
    12661392
    12671393#if !defined(HAVE_MKS_SHELL) && !defined(HAVE_CYGWIN_SHELL)
    1268                         case '\\':
    1269                                 backslash_count++;
    1270                                 break;
    1271 #endif
    1272         /*
    1273         * At one time we set *enclose_in_quotes_i for '*' or '?' to suppress
    1274         * wildcard expansion in programs linked with MSVC's SETARGV.OBJ so
    1275         * that argv in always equals argv out. This was removed.  Say you have
    1276         * such a program named glob.exe.  You enter
    1277         * glob '*'
    1278         * at the sh command prompt.  Obviously the intent is to make glob do the
    1279         * wildcarding instead of sh.  If we set *enclose_in_quotes_i for '*' or '?',
    1280         * then the command line that glob would see would be
    1281         * glob "*"
    1282         * and the _setargv in SETARGV.OBJ would _not_ expand the *.
    1283         */
    1284                         case ' ':
    1285                         case '\t':
    1286                                 *enclose_in_quotes_i = 1;
    1287                                 /* fall through */
    1288 
    1289                         default:
    1290                                 backslash_count = 0;
    1291                                 break;
    1292                         }
    1293 
    1294                         /*
    1295                         * Add one for each character in argv[i].
    1296                         */
    1297                         bytes_required++;
    1298 
    1299                         p++;
    1300                 }
    1301 
    1302                 if (*enclose_in_quotes_i) {
    1303                         /*
    1304                         * Add one for each enclosing ",
    1305                         * and one for each \ that precedes the
    1306                         * closing ".
    1307                         */
    1308                         bytes_required += (backslash_count + 2);
    1309                 }
    1310 
    1311                 /*
    1312                 * Add one for the intervening space.
    1313                 */
    1314                 if (*(++argvi)) bytes_required++;
    1315                 enclose_in_quotes_i++;
    1316         }
    1317 
    1318         /*
    1319         * Add one for the terminating NULL.
    1320         */
    1321         bytes_required++;
     1394                        case '\\':
     1395                                backslash_count++;
     1396                                break;
     1397#endif
     1398        /*
     1399        * At one time we set *enclose_in_quotes_i for '*' or '?' to suppress
     1400        * wildcard expansion in programs linked with MSVC's SETARGV.OBJ so
     1401        * that argv in always equals argv out. This was removed.  Say you have
     1402        * such a program named glob.exe.  You enter
     1403        * glob '*'
     1404        * at the sh command prompt.  Obviously the intent is to make glob do the
     1405        * wildcarding instead of sh.  If we set *enclose_in_quotes_i for '*' or '?',
     1406        * then the command line that glob would see would be
     1407        * glob "*"
     1408        * and the _setargv in SETARGV.OBJ would _not_ expand the *.
     1409        */
     1410                        case ' ':
     1411                        case '\t':
     1412                                *enclose_in_quotes_i = 1;
     1413                                /* fall through */
     1414
     1415                        default:
     1416                                backslash_count = 0;
     1417                                break;
     1418                        }
     1419
     1420                        /*
     1421                        * Add one for each character in argv[i].
     1422                        */
     1423                        bytes_required++;
     1424
     1425                        p++;
     1426                }
     1427
     1428                if (*enclose_in_quotes_i) {
     1429                        /*
     1430                        * Add one for each enclosing ",
     1431                        * and one for each \ that precedes the
     1432                        * closing ".
     1433                        */
     1434                        bytes_required += (backslash_count + 2);
     1435                }
     1436
     1437                /*
     1438                * Add one for the intervening space.
     1439                */
     1440                if (*(++argvi)) bytes_required++;
     1441                enclose_in_quotes_i++;
     1442        }
     1443
     1444        /*
     1445        * Add one for the terminating NULL.
     1446        */
     1447        bytes_required++;
    13221448#ifdef KMK /* for the space before the final " in case we need it. */
    13231449        bytes_required++;
    13241450#endif
    13251451
    1326         command_line = (char*) malloc(bytes_required);
    1327 
    1328         if (!command_line) {
    1329                 if (enclose_in_quotes) free(enclose_in_quotes);
    1330                 return NULL;
    1331         }
    1332 
    1333         command_line_i = command_line;
    1334 
    1335         if (shell_name && full_exec_path) {
    1336                 while(*shell_name) {
    1337                         *(command_line_i++) = *(shell_name++);
    1338                 }
    1339 
    1340                 *(command_line_i++) = ' ';
    1341 
    1342                 while(*full_exec_path) {
    1343                         *(command_line_i++) = *(full_exec_path++);
    1344                 }
    1345 
    1346                 if (*argv) {
    1347                         *(command_line_i++) = ' ';
    1348                 }
    1349         }
    1350 
    1351         argvi = argv;
    1352         enclose_in_quotes_i = enclose_in_quotes;
    1353 
    1354         while(*argvi) {
    1355                 char* p = *argvi;
    1356                 unsigned int backslash_count = 0;
    1357 
    1358                 if (*enclose_in_quotes_i) {
    1359                         *(command_line_i++) = '\"';
    1360                 }
    1361 
    1362                 while(*p) {
    1363                         if (*p == '\"') {
    1364                                 if (cygwin_mode && have_sh) { /* HAVE_CYGWIN_SHELL */
    1365                                         /* instead of a \", cygwin likes "" */
    1366                                         *(command_line_i++) = '\"';
    1367                                 } else {
    1368 
    1369                                         /*
    1370                                         * We have to insert a backslash for the "
    1371                                         * and each \ that precedes the ".
    1372                                         */
    1373                                         backslash_count++;
    1374 
    1375                                         while(backslash_count) {
    1376                                                 *(command_line_i++) = '\\';
    1377                                                 backslash_count--;
    1378                                         };
    1379                                 }
     1452        command_line = (char*) malloc(bytes_required);
     1453
     1454        if (!command_line) {
     1455                free(enclose_in_quotes);
     1456                return NULL;
     1457        }
     1458
     1459        command_line_i = command_line;
     1460
     1461        if (shell_name && full_exec_path) {
     1462                while(*shell_name) {
     1463                        *(command_line_i++) = *(shell_name++);
     1464                }
     1465
     1466                *(command_line_i++) = ' ';
     1467
     1468                while(*full_exec_path) {
     1469                        *(command_line_i++) = *(full_exec_path++);
     1470                }
     1471
     1472                if (*argv) {
     1473                        *(command_line_i++) = ' ';
     1474                }
     1475        }
     1476
     1477        argvi = argv;
     1478        enclose_in_quotes_i = enclose_in_quotes;
     1479
     1480        while(*argvi) {
     1481                char* p = *argvi;
     1482                unsigned int backslash_count = 0;
     1483
     1484                if (*enclose_in_quotes_i) {
     1485                        *(command_line_i++) = '\"';
     1486                }
     1487
     1488                while(*p) {
     1489                        if (*p == '\"') {
     1490                                if (cygwin_mode && have_sh) { /* HAVE_CYGWIN_SHELL */
     1491                                        /* instead of a \", cygwin likes "" */
     1492                                        *(command_line_i++) = '\"';
     1493                                } else {
     1494
     1495                                /*
     1496                                * We have to insert a backslash for the "
     1497                                * and each \ that precedes the ".
     1498                                */
     1499                                backslash_count++;
     1500
     1501                                while(backslash_count) {
     1502                                        *(command_line_i++) = '\\';
     1503                                        backslash_count--;
     1504                                };
     1505                                }
    13801506#if !defined(HAVE_MKS_SHELL) && !defined(HAVE_CYGWIN_SHELL)
    1381                         } else if (*p == '\\') {
    1382                                 backslash_count++;
    1383                         } else {
    1384                                 backslash_count = 0;
    1385 #endif
    1386                         }
    1387 
    1388                         /*
    1389                         * Copy the character.
    1390                         */
    1391                         *(command_line_i++) = *(p++);
    1392                 }
    1393 
    1394                 if (*enclose_in_quotes_i) {
     1507                        } else if (*p == '\\') {
     1508                                backslash_count++;
     1509                        } else {
     1510                                backslash_count = 0;
     1511#endif
     1512                        }
     1513
     1514                        /*
     1515                        * Copy the character.
     1516                        */
     1517                        *(command_line_i++) = *(p++);
     1518                }
     1519
     1520                if (*enclose_in_quotes_i) {
    13951521#if !defined(HAVE_MKS_SHELL) && !defined(HAVE_CYGWIN_SHELL)
    1396                         /*
    1397                         * Add one \ for each \ that precedes the
    1398                         * closing ".
    1399                         */
    1400                         while(backslash_count--) {
    1401                                 *(command_line_i++) = '\\';
    1402                         };
     1522                        /*
     1523                        * Add one \ for each \ that precedes the
     1524                        * closing ".
     1525                        */
     1526                        while(backslash_count--) {
     1527                                *(command_line_i++) = '\\';
     1528                        };
    14031529#endif
    14041530#ifdef KMK
     
    14131539                        }
    14141540#endif
    1415                         *(command_line_i++) = '\"';
    1416                 }
    1417 
    1418                 /*
    1419                  * Append an intervening space.
    1420                  */
    1421                 if (*(++argvi)) {
    1422                         *(command_line_i++) = ' ';
    1423                 }
    1424 
    1425                 enclose_in_quotes_i++;
    1426         }
    1427 
    1428         /*
    1429          * Append the terminating NULL.
    1430          */
    1431         *command_line_i = '\0';
    1432 
    1433         if (enclose_in_quotes) free(enclose_in_quotes);
    1434         return command_line;
     1541
     1542                        *(command_line_i++) = '\"';
     1543                }
     1544
     1545                /*
     1546                 * Append an intervening space.
     1547                 */
     1548                if (*(++argvi)) {
     1549                        *(command_line_i++) = ' ';
     1550                }
     1551
     1552                enclose_in_quotes_i++;
     1553        }
     1554
     1555        /*
     1556         * Append the terminating NULL.
     1557         */
     1558        *command_line_i = '\0';
     1559
     1560        free(enclose_in_quotes);
     1561        return command_line;
    14351562}
    14361563
     
    14391566 *              using the default stdin, stdout, and stderr handles.
    14401567 *              Also, register process so that process_wait_for_any_private()
    1441  *              can be used via process_file_io(NULL) or
    1442  *              process_wait_for_any().
     1568 *              can be used via process_file_io(NULL) or
     1569 *              process_wait_for_any().
    14431570 *
    14441571 * Returns:
     
    14481575HANDLE
    14491576process_easy(
    1450         char **argv,
    1451         char **envp)
    1452 {
    1453 #ifndef KMK
    1454   HANDLE hIn;
    1455   HANDLE hOut;
    1456   HANDLE hErr;
    1457 #endif
    1458   HANDLE hProcess;
     1577        char **argv,
     1578        char **envp,
     1579        int outfd,
     1580        int errfd)
     1581{
     1582  HANDLE hIn = INVALID_HANDLE_VALUE;
     1583  HANDLE hOut = INVALID_HANDLE_VALUE;
     1584  HANDLE hErr = INVALID_HANDLE_VALUE;
     1585  HANDLE hProcess, tmpIn, tmpOut, tmpErr;
     1586  DWORD e;
    14591587
    14601588  if (proc_index >= MAXIMUM_WAIT_OBJECTS) {
    1461         DB (DB_JOBS, ("process_easy: All process slots used up\n"));
    1462         return INVALID_HANDLE_VALUE;
     1589        DB (DB_JOBS, ("process_easy: All process slots used up\n"));
     1590        return INVALID_HANDLE_VALUE;
    14631591  }
    1464 #ifndef KMK
     1592#ifdef KMK /* We can effort here by lettering CreateProcess/kernel do the standard handle duplication. */
     1593 if (outfd != -1 || errfd != -1) {
     1594#endif
     1595  /* Standard handles returned by GetStdHandle can be NULL or
     1596     INVALID_HANDLE_VALUE if the parent process closed them.  If that
     1597     happens, we open the null device and pass its handle to
     1598     CreateProcess as the corresponding handle to inherit.  */
     1599  tmpIn = GetStdHandle(STD_INPUT_HANDLE);
    14651600  if (DuplicateHandle(GetCurrentProcess(),
    1466                       GetStdHandle(STD_INPUT_HANDLE),
     1601                      tmpIn,
    14671602                      GetCurrentProcess(),
    14681603                      &hIn,
     
    14701605                      TRUE,
    14711606                      DUPLICATE_SAME_ACCESS) == FALSE) {
    1472     fprintf(stderr,
    1473             "process_easy: DuplicateHandle(In) failed (e=%ld)\n",
    1474             GetLastError());
    1475     return INVALID_HANDLE_VALUE;
     1607    if ((e = GetLastError()) == ERROR_INVALID_HANDLE) {
     1608      tmpIn = CreateFile("NUL", GENERIC_READ,
     1609                         FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
     1610                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     1611      if (tmpIn != INVALID_HANDLE_VALUE
     1612          && DuplicateHandle(GetCurrentProcess(),
     1613                             tmpIn,
     1614                             GetCurrentProcess(),
     1615                             &hIn,
     1616                             0,
     1617                             TRUE,
     1618                             DUPLICATE_SAME_ACCESS) == FALSE)
     1619        CloseHandle(tmpIn);
     1620    }
     1621    if (hIn == INVALID_HANDLE_VALUE) {
     1622      fprintf(stderr, "process_easy: DuplicateHandle(In) failed (e=%ld)\n", e);
     1623      return INVALID_HANDLE_VALUE;
     1624    }
    14761625  }
     1626  if (outfd >= 0)
     1627    tmpOut = (HANDLE)_get_osfhandle (outfd);
     1628  else
     1629    tmpOut = GetStdHandle (STD_OUTPUT_HANDLE);
    14771630  if (DuplicateHandle(GetCurrentProcess(),
    1478                       GetStdHandle(STD_OUTPUT_HANDLE),
     1631                      tmpOut,
    14791632                      GetCurrentProcess(),
    14801633                      &hOut,
     
    14821635                      TRUE,
    14831636                      DUPLICATE_SAME_ACCESS) == FALSE) {
    1484     fprintf(stderr,
    1485            "process_easy: DuplicateHandle(Out) failed (e=%ld)\n",
    1486            GetLastError());
    1487     return INVALID_HANDLE_VALUE;
     1637    if ((e = GetLastError()) == ERROR_INVALID_HANDLE) {
     1638      tmpOut = CreateFile("NUL", GENERIC_WRITE,
     1639                          FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
     1640                          OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     1641      if (tmpOut != INVALID_HANDLE_VALUE
     1642          && DuplicateHandle(GetCurrentProcess(),
     1643                             tmpOut,
     1644                             GetCurrentProcess(),
     1645                             &hOut,
     1646                             0,
     1647                             TRUE,
     1648                             DUPLICATE_SAME_ACCESS) == FALSE)
     1649        CloseHandle(tmpOut);
     1650    }
     1651    if (hOut == INVALID_HANDLE_VALUE) {
     1652      fprintf(stderr, "process_easy: DuplicateHandle(Out) failed (e=%ld)\n", e);
     1653      return INVALID_HANDLE_VALUE;
     1654    }
    14881655  }
     1656  if (errfd >= 0)
     1657    tmpErr = (HANDLE)_get_osfhandle (errfd);
     1658  else
     1659    tmpErr = GetStdHandle(STD_ERROR_HANDLE);
    14891660  if (DuplicateHandle(GetCurrentProcess(),
    1490                       GetStdHandle(STD_ERROR_HANDLE),
     1661                      tmpErr,
    14911662                      GetCurrentProcess(),
    14921663                      &hErr,
     
    14941665                      TRUE,
    14951666                      DUPLICATE_SAME_ACCESS) == FALSE) {
    1496     fprintf(stderr,
    1497             "process_easy: DuplicateHandle(Err) failed (e=%ld)\n",
    1498             GetLastError());
    1499     return INVALID_HANDLE_VALUE;
     1667    if ((e = GetLastError()) == ERROR_INVALID_HANDLE) {
     1668      tmpErr = CreateFile("NUL", GENERIC_WRITE,
     1669                          FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
     1670                          OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     1671      if (tmpErr != INVALID_HANDLE_VALUE
     1672          && DuplicateHandle(GetCurrentProcess(),
     1673                             tmpErr,
     1674                             GetCurrentProcess(),
     1675                             &hErr,
     1676                             0,
     1677                             TRUE,
     1678                             DUPLICATE_SAME_ACCESS) == FALSE)
     1679        CloseHandle(tmpErr);
     1680    }
     1681    if (hErr == INVALID_HANDLE_VALUE) {
     1682      fprintf(stderr, "process_easy: DuplicateHandle(Err) failed (e=%ld)\n", e);
     1683      return INVALID_HANDLE_VALUE;
     1684    }
    15001685  }
     1686#ifdef KMK /* saving effort */
     1687 }
     1688#endif
    15011689
    15021690  hProcess = process_init_fd(hIn, hOut, hErr);
    1503 #else
    1504   hProcess = process_init_fd(0, 0, 0);
    1505 #endif /* !KMK */
    15061691
    15071692  if (process_begin(hProcess, argv, envp, argv[0], NULL)) {
     
    15151700      ((sub_process*) hProcess)->exit_code = process_last_err(hProcess);
    15161701
    1517 #ifndef KMK
    15181702    /* close up unused handles */
    1519     CloseHandle(hIn);
    1520     CloseHandle(hOut);
    1521     CloseHandle(hErr);
    1522 #endif
     1703    if (hIn != INVALID_HANDLE_VALUE)
     1704      CloseHandle(hIn);
     1705    if (hOut != INVALID_HANDLE_VALUE)
     1706      CloseHandle(hOut);
     1707    if (hErr != INVALID_HANDLE_VALUE)
     1708      CloseHandle(hErr);
    15231709  }
    15241710
  • trunk/src/kmk/w32/subproc/w32err.c

    r2591 r3140  
    11/* Error handling for Windows
    2 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
    3 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
     2Copyright (C) 1996-2016 Free Software Foundation, Inc.
    43This file is part of GNU Make.
    54
     
    1615this program.  If not, see <http://www.gnu.org/licenses/>.  */
    1716
     17#include <stdlib.h>
    1818#include <windows.h>
     19#include "makeint.h"
    1920#include "w32err.h"
    2021
     
    2728 *      comp.os.ms-windows.programmer.win32
    2829 */
    29 char *
     30const char *
    3031map_windows32_error_to_string (DWORD ercode) {
    31 /* __declspec (thread) necessary if you will use multiple threads on MSVC */
    32 #ifdef _MSC_VER
    33 __declspec (thread) static char szMessageBuffer[128];
    34 #else
    35 static char szMessageBuffer[128];
    36 #endif
    37         /* Fill message buffer with a default message in
    38          * case FormatMessage fails
    39          */
     32/*
     33 * We used to have an MSVC-specific '__declspec (thread)' qualifier
     34 * here, with the following comment:
     35 *
     36 * __declspec (thread) necessary if you will use multiple threads on MSVC
     37 *
     38 * However, Make was never multithreaded on Windows (except when
     39 * Ctrl-C is hit, in which case the main thread is stopped
     40 * immediately, so it doesn't matter in this context).  The functions
     41 * on sub_proc.c that started and stopped additional threads were
     42 * never used, and are now #ifdef'ed away.  Until we need more than
     43 * one thread, we have no problems with the following buffer being
     44 * static.  (If and when we do need it to be in thread-local storage,
     45 * the corresponding GCC qualifier is '__thread'.)
     46 */
     47    static char szMessageBuffer[128];
     48        /* Fill message buffer with a default message in
     49         * case FormatMessage fails
     50         */
    4051    wsprintf (szMessageBuffer, "Error %ld\n", ercode);
    4152
    42         /*
    43          *  Special code for winsock error handling.
    44          */
    45         if (ercode > WSABASEERR) {
    46                 HMODULE hModule = GetModuleHandle("wsock32");
    47                 if (hModule != NULL) {
    48                         FormatMessage(FORMAT_MESSAGE_FROM_HMODULE,
    49                                 hModule,
    50                                 ercode,
    51                                 LANG_NEUTRAL,
    52                                 szMessageBuffer,
    53                                 sizeof(szMessageBuffer),
    54                                 NULL);
    55                         FreeLibrary(hModule);
    56                 }
    57         } else {
    58                 /*
    59                  *  Default system message handling
    60                  */
    61         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
    62                   NULL,
    63                   ercode,
    64                   LANG_NEUTRAL,
    65                   szMessageBuffer,
    66                   sizeof(szMessageBuffer),
    67                   NULL);
    68         }
     53        /*
     54         *  Special code for winsock error handling.
     55         */
     56        if (ercode > WSABASEERR) {
     57#if 0
     58                HMODULE hModule = GetModuleHandle("wsock32");
     59                if (hModule != NULL) {
     60                        FormatMessage(FORMAT_MESSAGE_FROM_HMODULE,
     61                                hModule,
     62                                ercode,
     63                                LANG_NEUTRAL,
     64                                szMessageBuffer,
     65                                sizeof(szMessageBuffer),
     66                                NULL);
     67                        FreeLibrary(hModule);
     68                }
     69#else
     70                O (fatal, NILF, szMessageBuffer);
     71#endif
     72        } else {
     73                /*
     74                 *  Default system message handling
     75                 */
     76                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
     77                        NULL,
     78                        ercode,
     79                        LANG_NEUTRAL,
     80                        szMessageBuffer,
     81                        sizeof(szMessageBuffer),
     82                        NULL);
     83        }
    6984    return szMessageBuffer;
    7085}
  • trunk/src/kmk/w32/w32os.c

    r3139 r3140  
    169169jobserver_acquire (int timeout)
    170170{
    171     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
     171    HANDLE handles[MAXIMUM_WAIT_OBJECTS + 1]; /* bird: + 1 to prevent trashing the stack. */
    172172    DWORD dwHandleCount;
    173173    DWORD dwEvent;
  • trunk/src/lib/kDep.c

    r3114 r3140  
    3434*******************************************************************************/
    3535#ifdef KMK /* For when it gets compiled and linked into kmk. */
    36 # include "make.h"
     36# include "makeint.h"
    3737#endif
    3838#include <stdio.h>
Note: See TracChangeset for help on using the changeset viewer.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette