aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimon J. Gerraty <sjg@FreeBSD.org>2021-01-14 01:24:34 +0000
committerSimon J. Gerraty <sjg@FreeBSD.org>2021-01-14 01:24:34 +0000
commit8e11a9b4250be3c3379c45fa820bff78d99d5946 (patch)
treeea4954dbe7647b6211a20458b2a881e3d943639f
parent1b65f0bd2bda7121a90f8cb4c1cacaa20f1b681d (diff)
downloadsrc-8e11a9b4250be3c3379c45fa820bff78d99d5946.tar.gz
src-8e11a9b4250be3c3379c45fa820bff78d99d5946.zip
Import bmake-20210110vendor/NetBSD/bmake/20210110
Quite a lot of churn on style, but lots of good work refactoring complicated functions and lots more unit-tests. Thanks mostly to rillig at NetBSD Some interesting entries from ChangeLog o .MAKE.{UID,GID} represent uid and gid running make. o allow env var MAKE_OBJDIR_CHECK_WRITABLE=no to skip writable checks in InitObjdir. Explicit .OBJDIR target always allows read-only directory. o add more unit tests for META MODE Change-Id: I4d3bcf08b4c864d98b343f602efe5a75dbfa7a94
-rw-r--r--ChangeLog241
-rw-r--r--FILES64
-rw-r--r--LICENSE4
-rw-r--r--PSD.doc/tutorial.ms10
-rw-r--r--VERSION2
-rw-r--r--arch.c1323
-rw-r--r--bmake.118
-rw-r--r--bmake.cat1248
-rw-r--r--buf.c139
-rw-r--r--buf.h28
-rw-r--r--compat.c932
-rw-r--r--cond.c1611
-rw-r--r--dir.c2047
-rw-r--r--dir.h36
-rwxr-xr-xenum.c11
-rwxr-xr-xenum.h69
-rw-r--r--filemon/filemon.h6
-rw-r--r--filemon/filemon_dev.c6
-rw-r--r--filemon/filemon_ktrace.c79
-rw-r--r--for.c633
-rw-r--r--hash.c41
-rw-r--r--hash.h72
-rwxr-xr-ximport.sh87
-rw-r--r--job.c3876
-rw-r--r--job.h84
-rw-r--r--lst.c304
-rw-r--r--lst.h88
-rw-r--r--main.c364
-rw-r--r--make-conf.h20
-rw-r--r--make.118
-rw-r--r--make.c1825
-rw-r--r--make.h812
-rw-r--r--make_malloc.c7
-rw-r--r--make_malloc.h12
-rw-r--r--meta.c359
-rw-r--r--meta.h4
-rw-r--r--metachar.h4
-rw-r--r--mk/ChangeLog39
-rw-r--r--mk/dirdeps-options.mk5
-rw-r--r--mk/dirdeps-targets.mk7
-rw-r--r--mk/dirdeps.mk25
-rw-r--r--mk/init.mk17
-rwxr-xr-x[-rw-r--r--]mk/install-mk4
-rw-r--r--mk/meta.subdir.mk4
-rw-r--r--[-rwxr-xr-x]mk/mkopt.sh0
-rw-r--r--mk/own.mk6
-rw-r--r--mk/sys.mk6
-rw-r--r--nonints.h278
-rw-r--r--[-rwxr-xr-x]os.sh0
-rw-r--r--parse.c4058
-rw-r--r--pathnames.h15
-rw-r--r--str.c15
-rw-r--r--suff.c2897
-rw-r--r--targ.c568
-rw-r--r--trace.c16
-rw-r--r--trace.h6
-rw-r--r--unit-tests/Makefile159
-rw-r--r--unit-tests/cmd-errors-jobs.exp9
-rw-r--r--unit-tests/cmd-errors-jobs.mk32
-rw-r--r--unit-tests/cmd-errors.mk4
-rw-r--r--unit-tests/cmdline.mk2
-rw-r--r--unit-tests/compat-error.exp15
-rw-r--r--unit-tests/compat-error.mk37
-rw-r--r--unit-tests/cond-eof.exp9
-rw-r--r--unit-tests/cond-eof.mk20
-rw-r--r--unit-tests/cond-func-empty.mk27
-rw-r--r--unit-tests/cond-func-exists.mk11
-rw-r--r--unit-tests/cond-func-make-main.exp3
-rw-r--r--unit-tests/cond-func-make-main.mk62
-rw-r--r--unit-tests/cond-short.exp12
-rw-r--r--unit-tests/cond-short.mk64
-rw-r--r--unit-tests/cond-token-string.exp2
-rw-r--r--unit-tests/dep-percent.exp5
-rw-r--r--unit-tests/depsrc-meta.exp4
-rw-r--r--unit-tests/depsrc-meta.mk27
-rw-r--r--unit-tests/depsrc-optional.exp18
-rw-r--r--unit-tests/depsrc.exp3
-rw-r--r--unit-tests/depsrc.mk17
-rw-r--r--unit-tests/deptgt-begin-fail-indirect.exp6
-rw-r--r--unit-tests/deptgt-begin-fail-indirect.mk16
-rw-r--r--unit-tests/deptgt-begin-fail.exp6
-rw-r--r--unit-tests/deptgt-begin-fail.mk10
-rw-r--r--unit-tests/deptgt-end-fail-all.exp7
-rw-r--r--unit-tests/deptgt-end-fail-all.mk19
-rw-r--r--unit-tests/deptgt-end-fail-indirect.exp7
-rw-r--r--unit-tests/deptgt-end-fail-indirect.mk16
-rw-r--r--unit-tests/deptgt-end-fail.exp163
-rw-r--r--unit-tests/deptgt-end-fail.mk69
-rw-r--r--unit-tests/deptgt-suffixes.exp26
-rw-r--r--unit-tests/deptgt-suffixes.mk23
-rw-r--r--unit-tests/deptgt.exp1
-rw-r--r--unit-tests/deptgt.mk10
-rw-r--r--unit-tests/directive-elif.exp32
-rw-r--r--unit-tests/directive-elif.mk126
-rw-r--r--unit-tests/directive-else.exp16
-rw-r--r--unit-tests/directive-else.mk15
-rw-r--r--unit-tests/directive-endfor.exp4
-rw-r--r--unit-tests/directive-endfor.mk9
-rw-r--r--unit-tests/directive-endif.exp9
-rw-r--r--unit-tests/directive-endif.mk28
-rw-r--r--unit-tests/directive-error.mk6
-rw-r--r--unit-tests/directive-export-env.mk4
-rw-r--r--unit-tests/directive-export-impl.exp56
-rw-r--r--unit-tests/directive-export-impl.mk62
-rw-r--r--unit-tests/directive-export-literal.mk4
-rw-r--r--unit-tests/directive-export.exp5
-rw-r--r--unit-tests/directive-export.mk16
-rw-r--r--unit-tests/directive-for-errors.exp22
-rw-r--r--unit-tests/directive-for-errors.mk75
-rw-r--r--unit-tests/directive-for-escape.exp74
-rw-r--r--unit-tests/directive-for-escape.mk96
-rw-r--r--unit-tests/directive-for-lines.exp10
-rw-r--r--unit-tests/directive-for-lines.mk32
-rw-r--r--unit-tests/directive-for-null.exp10
-rw-r--r--unit-tests/directive-for-null.mk19
-rwxr-xr-xunit-tests/directive-for.exp7
-rwxr-xr-xunit-tests/directive-for.mk9
-rw-r--r--unit-tests/directive-if.exp6
-rw-r--r--unit-tests/directive-if.mk14
-rwxr-xr-xunit-tests/directive-include.mk5
-rw-r--r--unit-tests/directive-info.exp23
-rw-r--r--unit-tests/directive-info.mk18
-rw-r--r--unit-tests/directive-misspellings.exp45
-rw-r--r--unit-tests/directive-misspellings.mk79
-rw-r--r--unit-tests/directive-undef.exp3
-rw-r--r--unit-tests/directive-undef.mk85
-rw-r--r--unit-tests/directive-unexport-env.exp19
-rw-r--r--unit-tests/directive-unexport-env.mk19
-rw-r--r--unit-tests/directive-unexport.exp13
-rw-r--r--unit-tests/directive-unexport.mk12
-rw-r--r--unit-tests/directive-warning.exp16
-rw-r--r--unit-tests/directive-warning.mk10
-rw-r--r--unit-tests/jobs-error-indirect.exp8
-rw-r--r--unit-tests/jobs-error-indirect.mk21
-rw-r--r--unit-tests/jobs-error-nested-make.exp11
-rw-r--r--unit-tests/jobs-error-nested-make.mk20
-rw-r--r--unit-tests/jobs-error-nested.exp15
-rw-r--r--unit-tests/jobs-error-nested.mk20
-rwxr-xr-xunit-tests/make-exported.mk2
-rw-r--r--unit-tests/meta-cmd-cmp.exp37
-rw-r--r--unit-tests/meta-cmd-cmp.mk52
-rw-r--r--unit-tests/modmisc.exp1
-rw-r--r--unit-tests/modmisc.mk29
-rw-r--r--unit-tests/opt-chdir.exp4
-rw-r--r--unit-tests/opt-debug-errors.exp5
-rw-r--r--unit-tests/opt-debug-graph1.exp36
-rw-r--r--unit-tests/opt-debug-jobs.exp4
-rw-r--r--unit-tests/opt-debug-lint.exp3
-rw-r--r--unit-tests/opt-debug-lint.mk15
-rw-r--r--unit-tests/opt-file.exp13
-rw-r--r--unit-tests/opt-file.mk101
-rw-r--r--unit-tests/opt-jobs-no-action.exp61
-rw-r--r--unit-tests/opt-jobs-no-action.mk102
-rw-r--r--unit-tests/opt-keep-going-multiple.exp9
-rw-r--r--unit-tests/opt-keep-going-multiple.mk21
-rw-r--r--unit-tests/opt-keep-going.exp5
-rw-r--r--unit-tests/opt-keep-going.mk6
-rw-r--r--unit-tests/opt-no-action-runflags.exp34
-rw-r--r--unit-tests/opt-no-action-runflags.mk32
-rw-r--r--unit-tests/opt.exp4
-rw-r--r--unit-tests/posix.exp5
-rw-r--r--unit-tests/qequals.exp2
-rw-r--r--unit-tests/qequals.mk8
-rwxr-xr-xunit-tests/sh-dots.exp12
-rw-r--r--unit-tests/sh-errctl.exp27
-rw-r--r--unit-tests/sh-errctl.mk26
-rw-r--r--unit-tests/sh-flags.exp4325
-rw-r--r--unit-tests/sh-flags.mk138
-rw-r--r--unit-tests/sh-jobs.exp7
-rw-r--r--unit-tests/sh-jobs.mk34
-rw-r--r--unit-tests/sh-meta-chars.mk17
-rw-r--r--unit-tests/shell-csh.mk6
-rw-r--r--unit-tests/suff-add-later.exp8
-rw-r--r--unit-tests/suff-clear-regular.exp5
-rw-r--r--unit-tests/suff-clear-regular.mk3
-rw-r--r--unit-tests/suff-clear-single.exp5
-rw-r--r--unit-tests/suff-incomplete.exp42
-rw-r--r--unit-tests/suff-incomplete.mk31
-rw-r--r--unit-tests/suff-lookup.exp21
-rw-r--r--unit-tests/suff-main-several.exp141
-rw-r--r--unit-tests/suff-main-several.mk42
-rw-r--r--unit-tests/suff-phony.exp13
-rw-r--r--unit-tests/suff-phony.mk21
-rw-r--r--unit-tests/suff-rebuild.exp76
-rw-r--r--unit-tests/suff-rebuild.mk23
-rw-r--r--unit-tests/suff-self.exp5
-rw-r--r--unit-tests/suff-transform-debug.exp62
-rw-r--r--unit-tests/suff-transform-debug.mk12
-rw-r--r--unit-tests/suff-transform-endless.exp44
-rw-r--r--unit-tests/suff-transform-endless.mk9
-rw-r--r--unit-tests/suff-transform-expand.exp5
-rw-r--r--unit-tests/suff-transform-select.exp45
-rw-r--r--unit-tests/suff-transform-select.mk7
-rw-r--r--unit-tests/use-inference.exp5
-rw-r--r--unit-tests/use-inference.mk6
-rw-r--r--unit-tests/var-op-default.mk72
-rw-r--r--unit-tests/var-op-expand.exp9
-rw-r--r--unit-tests/var-op-expand.mk191
-rw-r--r--unit-tests/vardebug.exp2
-rw-r--r--unit-tests/varmisc.mk14
-rw-r--r--unit-tests/varmod-defined.exp18
-rw-r--r--unit-tests/varmod-edge.exp41
-rw-r--r--unit-tests/varmod-extension.exp1
-rw-r--r--unit-tests/varmod-extension.mk4
-rw-r--r--unit-tests/varmod-gmtime.exp40
-rw-r--r--unit-tests/varmod-gmtime.mk197
-rw-r--r--unit-tests/varmod-head.exp1
-rw-r--r--unit-tests/varmod-head.mk4
-rw-r--r--unit-tests/varmod-ifelse.exp4
-rw-r--r--unit-tests/varmod-ifelse.mk20
-rw-r--r--unit-tests/varmod-indirect.exp59
-rw-r--r--unit-tests/varmod-indirect.mk157
-rw-r--r--unit-tests/varmod-localtime.exp40
-rw-r--r--unit-tests/varmod-localtime.mk196
-rw-r--r--unit-tests/varmod-range.exp9
-rw-r--r--unit-tests/varmod-root.exp1
-rw-r--r--unit-tests/varmod-root.mk4
-rw-r--r--unit-tests/varmod-subst-regex.exp2
-rw-r--r--unit-tests/varmod-subst-regex.mk7
-rw-r--r--unit-tests/varmod-sysv.exp4
-rw-r--r--unit-tests/varmod-sysv.mk16
-rw-r--r--unit-tests/varmod-tail.exp1
-rw-r--r--unit-tests/varmod-tail.mk4
-rw-r--r--unit-tests/varmod-to-many-words.mk16
-rw-r--r--unit-tests/varmod-to-one-word.mk16
-rw-r--r--unit-tests/varmod-to-separator.exp2
-rw-r--r--unit-tests/varmod.exp2
-rw-r--r--unit-tests/varmod.mk4
-rw-r--r--unit-tests/varname-dot-makeflags.exp3
-rw-r--r--unit-tests/varname-dot-makeflags.mk15
-rwxr-xr-xunit-tests/varname-dot-shell.exp2
-rw-r--r--unit-tests/varname-make_print_var_on_error-jobs.exp5
-rw-r--r--unit-tests/varname-make_print_var_on_error-jobs.mk15
-rw-r--r--unit-tests/varname-make_print_var_on_error.exp3
-rw-r--r--unit-tests/varname-make_print_var_on_error.mk15
-rw-r--r--unit-tests/varname-makeflags.mk24
-rw-r--r--unit-tests/varparse-dynamic.mk12
-rw-r--r--unit-tests/varparse-errors.exp6
-rw-r--r--unit-tests/varparse-errors.mk18
-rw-r--r--util.c91
-rw-r--r--var.c6010
241 files changed, 24256 insertions, 14514 deletions
diff --git a/ChangeLog b/ChangeLog
index ac723511d75a..5cf7f1f45384 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,8 +1,247 @@
+2021-01-10 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20210110
+ Merge with NetBSD make, pick up
+ o fix lint warnings
+ o consistently use boolean expressions in conditions
+
+2021-01-08 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20210108
+ Merge with NetBSD make, pick up
+ o job.c: back to polling token pipe if we want a token
+ o main.c: always print 'stopped in' on first call
+ The execption is if we bail because of an abort token
+ in which case just exit 6.
+
+2021-01-01 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20210101
+ Merge with NetBSD make, pick up
+ o Happy New Year!
+ o rename CmdOpts.lint to strict
+ o exit 2 on technical errors
+ o replace pointers in controlling conditions with booleans
+ o replace global preserveUndefined with VARE_KEEP_UNDEF
+ o compat.c: re-export variables from the actual make process
+ if using vfork this is the effect anyway
+ o cond.c: clean up VarParseResult constants
+ o for.c: fix undefined behavior in SubstVarLong
+ make control flow in SubstVarLong of .for loops more obvious
+ clean up SubstVarShort in .for loops
+ extract ForSubstBody from ForReadMore
+ clean up ForReadMore
+ simplify termination condition for .for loop
+ add error handling for .for loop items
+ job.c: re-export variables from the actual make process
+ parse.c: remove mmap for loading files, only allow files < 1 GiB
+ fix edge case in := with undefined in variable name
+ skip variable expansion in ParseDependencyTargetWord
+ var.c: split ExportVar into separate functions
+ clean up code in extracted ExportVar functions
+ remove dead code from ApplyModifiersIndirect
+ split Var_Subst into easily understandable functions
+ clean up VarParseResult constants
+
+2020-12-25 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * main.c: use .MAKE.DEPENDFILE as set by makefiles
+
+2020-12-22 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20201222
+ Merge with NetBSD make, pick up
+ o make DEBUG macro return boolean
+ o parse.c: fix assertion failure for files without trailing newline
+ o var.c: allow .undef to undefine multiple variables at once
+ remove excess newline from parse errors
+
+2020-12-21 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20201221
+ Merge with NetBSD make, pick up
+ o some unit-test updates
+
+2020-12-20 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20201220
+ Merge with NetBSD make, pick up
+ o more unit tests
+ o return FStr from Var_Parse and Var_Value
+ o spell nonexistent consistently
+ o add str_basename to reduce duplicate code
+ o compat.c: fix .ERROR_TARGET in compat -k mode
+ extract InitSignals from Compat_Run
+ extract UseShell from Compat_RunCommand
+ o cond.c: error out if an '.endif' or '.else' contain extraneous text
+ o for.c: rename ForIterate to ForReadMore
+ o hash.c: clean up hash function for HashTable
+ o lst.c: rename Vector.priv_cap to cap
+ o main.c: remove constant parameter from MakeMode
+ o make.c: use symbolic time for 0 in Make_Recheck
+ extract MakeChildren from MakeStartJobs
+ o parse.c: clean up memory handling in VarAssign_EvalShell, Parse_DoVar
+ fix error message for .info/.warning/.error without argument
+ extract Var_Undef from ParseDirective
+ extract ParseSkippedBranches, ParseForLoop from ParseReadLine
+ rename mode constants for ParseGetLine to be more expressive
+ reduce debugging details in Parse_SetInput
+ fix line numbers in .for loops
+ split ParseGetLine into separate functions
+ fix garbled output for failed shell command
+ var.c: remove redundant assignment in ApplyModifier_SysV
+ error out on unknown variable modifiers at parse time
+ remove wrong error message for indirect modifier in lint mode
+ extract ApplySingleModifier from ApplyModifiers
+ use FStr for memory management in Var_SetWithFlags
+ extract SetVar from Var_SetWithFlags
+ use FStr in VarNew
+ extract string functions from ApplyModifier_To
+ error out if .undef has not exactly 1 argument
+ extract Var_DeleteVar from Var_Delete
+ extract Var_Undef from ParseDirective
+ clean up memory management for expanding variable expressions
+
+2020-12-12 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * avoid %zu
+
+ * lst.c: avoid anonymous union
+
+ * VERSION (_MAKE_VERSION): 20201212
+ Merge with NetBSD make, pick up
+ o more unit tests
+ o inline Targ_Ignore and Targ_Silent
+ o split JobFlags into separate fields
+ o remove const from function parameters (left overs from refactoring)
+ o eliminate boolean argument of Var_Export
+ o make API of Buf_Init simpler
+ o rename ParseRunOptions to ParseCommandFlags
+ o replace *line with line[0]
+ o compat.c: fix wrong exit status for multiple failed main targets
+ refactor Compat_Run to show the error condition more clearly
+ don't make .END if the main targets already failed (-k mode)
+ fix exit status in -k mode if a dependency fails
+ o for.c: clean up Buf_AddEscaped in .for loops
+ o job.c: extract ShellWriter_ErrOn from JobPrintCommand
+ make Job_Touch simpler
+ refactor JobFinish
+ rename Shell.exitFlag to errFlag
+ move Job.xtraced to ShellWriter
+ make printing of shell commands independent from the job
+ rename shell flags in struct Shell
+ extract JobOpenTmpFile from JobStart
+ rename RunFlags to CommandFlags
+ split various Job.* into separate fields
+ rename commandShell to shell
+ extract InitShellNameAndPath from Shell_Init
+ replace signal handling macros with local functions
+ replace macro MESSAGE with local function
+ parse.c: error out on null bytes in makefiles
+ error out on misspelled directives
+ rename IFile.nextbuf to readMore
+ fix undefined behavior in ParseEOF
+ str.c: remove redundant call to strlen in Str_Words
+ var.c: error out on misspelled .unexport-env
+ error out on misspelled .export directives
+ extract ExportVars from Var_Export
+ extract ExportVarsExpand from Var_Export
+ eliminate boolean argument of Var_Export
+ fix undefined behavior when exporting ${:U }
+ rename Var_ExportVars to Var_ReexportVars
+ rename Var_Export1 to ExportVar
+
+2020-12-06 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20201206
+ Merge with NetBSD make, pick up
+ o more unit tests
+ o inline macros for debug logging
+ o use consistent variable names for list nodes
+ o define constants for enum zero-values
+ o dir.c: use fixed format for debug output of the directory cache
+ remove Dir_InitDir
+ o lst.c: inline Lst_Enqueue, Vector_Done
+ o meta.c: remove unused parameter from meta_needed
+ o parse.c: rename parse functions
+ o suff.c: extract ExpandChildrenRegular from ExpandChildren
+ o targ.c: don't concatenate identifiers in Targ_PrintType
+ o var.c: remove comment decoration
+ extract UnexportVars from Var_UnExport
+ extract GetVarnamesToUnexport from Var_UnExport
+ extract UnexportEnv from Var_UnExport
+ extract UnexportVar from Var_UnExport
+ move CleanEnv to UnexportVars
+ replace pointer comparisons with enum
+ add FStr to var.c to make memory handling simpler
+ use FStr in Var_UnExport
+ move type definitions in var.c to the top
+ extract FreeEnvVar from Var_Parse
+ extract ShuffleStrings from ApplyModifier_Order
+
+2020-11-30 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20201130
+ Merge with NetBSD make, pick up
+ o add unit tests for META MODE
+ o reduce memory allocation for dirSearchPath, GNode.parents,
+ GNode.children, OpenDirs
+ o reduce pointer indirection for GNode.cohorts and
+ GNode.implicitParents
+ o remove pointer indirection from GNode.commands
+ o inline Lst_ForEachUntil in meta mode
+ o dir.c: fix memory leak for lstat cache in -DCLEANUP mode
+ clean up memory management for CachedDirs
+ fix the reference count of dotLast going negative
+ add debug logging for OpenDirs_Done
+ extract CacheNewDir from Dir_AddDir
+ add debug logging for reference counting of CachedDir
+ rename some Dir functions to SearchPath
+ o job.c: rename some global variables
+ o main.c: reduce memory allocation in ReadBuiltinRules
+ reduce memory allocation in CmdOpts.create, CmdOpts.variables,
+ CmdOpts.makefiles
+ Add .MAKE.UID and .MAKE.GID
+ o make.c: reduce memory allocation for/in toBeMade,
+ Make_ProcessWait, Make_ExpandUse
+ o meta.c: reduce memory allocation in meta_oodate
+ o parse.c: reduce memory allocations for parsing dependencies and
+ targets
+ o suff.c: reduce memory allocation in suffix handling
+
+2020-11-24 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20201124
+ Merge with NetBSD make, pick up
+ o .MAKE.{UID,GID} represent uid and gid running make.
+ o fix error handling for .BEGIN and .END dependency in -k mode
+ o fix missing "Stop." after failed .END node in -k mode
+ o use properly typed comparisons in boolean contexts
+ o replace a few HashTable_CreateEntry with HashTable_Set
+ o add HashSet type
+ o compat.c: split Compat_Make into smaller functions
+ extract DebugFailedTarget from Compat_RunCommand
+ o dir.c: refactor Dir_UpdateMTime
+ migrate CachedDir.files from HashTable to HashSet
+ o make.c: add high-level API for GNode.made
+
+2020-11-22 Simon J Gerraty <sjg@beast.crufty.net>
+
+ * VERSION (_MAKE_VERSION): 20201122
+ Merge with NetBSD make, pick up
+ o rename GNode.context to vars
+ o suff.c: cleanup and refactor
+ rename some functions and vars to better reflect usage
+ add high-level API for CandidateSearcher
+ o targ.c: add more debug logging for suffix handling
+ o more unit tests
+ o add debug logging for setting and resetting the main target
+
2020-11-17 Simon J Gerraty <sjg@beast.crufty.net>
* VERSION (_MAKE_VERSION): 20201117
Merge with NetBSD make, pick up
- o fix some unit-tests when dash is .SHELL
+ o fix some unit-tests when .SHELL is dash
o rename Targ_NewGN to GNode_New
o make some GNode functions const
o main.c: call Targ_Init before Var_Init
diff --git a/FILES b/FILES
index dedc29767658..8e2513e1c183 100644
--- a/FILES
+++ b/FILES
@@ -75,6 +75,8 @@ unit-tests/archive-suffix.exp
unit-tests/archive-suffix.mk
unit-tests/archive.exp
unit-tests/archive.mk
+unit-tests/cmd-errors-jobs.exp
+unit-tests/cmd-errors-jobs.mk
unit-tests/cmd-errors-lint.exp
unit-tests/cmd-errors-lint.mk
unit-tests/cmd-errors.exp
@@ -87,6 +89,8 @@ unit-tests/cmdline.exp
unit-tests/cmdline.mk
unit-tests/comment.exp
unit-tests/comment.mk
+unit-tests/compat-error.exp
+unit-tests/compat-error.mk
unit-tests/cond-cmp-numeric-eq.exp
unit-tests/cond-cmp-numeric-eq.mk
unit-tests/cond-cmp-numeric-ge.exp
@@ -105,6 +109,8 @@ unit-tests/cond-cmp-string.exp
unit-tests/cond-cmp-string.mk
unit-tests/cond-cmp-unary.exp
unit-tests/cond-cmp-unary.mk
+unit-tests/cond-eof.exp
+unit-tests/cond-eof.mk
unit-tests/cond-func-commands.exp
unit-tests/cond-func-commands.mk
unit-tests/cond-func-defined.exp
@@ -113,6 +119,8 @@ unit-tests/cond-func-empty.exp
unit-tests/cond-func-empty.mk
unit-tests/cond-func-exists.exp
unit-tests/cond-func-exists.mk
+unit-tests/cond-func-make-main.exp
+unit-tests/cond-func-make-main.mk
unit-tests/cond-func-make.exp
unit-tests/cond-func-make.mk
unit-tests/cond-func-target.exp
@@ -213,12 +221,22 @@ unit-tests/depsrc-wait.exp
unit-tests/depsrc-wait.mk
unit-tests/depsrc.exp
unit-tests/depsrc.mk
+unit-tests/deptgt-begin-fail-indirect.exp
+unit-tests/deptgt-begin-fail-indirect.mk
+unit-tests/deptgt-begin-fail.exp
+unit-tests/deptgt-begin-fail.mk
unit-tests/deptgt-begin.exp
unit-tests/deptgt-begin.mk
unit-tests/deptgt-default.exp
unit-tests/deptgt-default.mk
unit-tests/deptgt-delete_on_error.exp
unit-tests/deptgt-delete_on_error.mk
+unit-tests/deptgt-end-fail-all.exp
+unit-tests/deptgt-end-fail-all.mk
+unit-tests/deptgt-end-fail-indirect.exp
+unit-tests/deptgt-end-fail-indirect.mk
+unit-tests/deptgt-end-fail.exp
+unit-tests/deptgt-end-fail.mk
unit-tests/deptgt-end-jobs.exp
unit-tests/deptgt-end-jobs.mk
unit-tests/deptgt-end.exp
@@ -279,6 +297,8 @@ unit-tests/directive-elifnmake.exp
unit-tests/directive-elifnmake.mk
unit-tests/directive-else.exp
unit-tests/directive-else.mk
+unit-tests/directive-endfor.exp
+unit-tests/directive-endfor.mk
unit-tests/directive-endif.exp
unit-tests/directive-endif.mk
unit-tests/directive-error.exp
@@ -287,12 +307,22 @@ unit-tests/directive-export-env.exp
unit-tests/directive-export-env.mk
unit-tests/directive-export-gmake.exp
unit-tests/directive-export-gmake.mk
+unit-tests/directive-export-impl.exp
+unit-tests/directive-export-impl.mk
unit-tests/directive-export-literal.exp
unit-tests/directive-export-literal.mk
unit-tests/directive-export.exp
unit-tests/directive-export.mk
+unit-tests/directive-for-errors.exp
+unit-tests/directive-for-errors.mk
+unit-tests/directive-for-escape.exp
+unit-tests/directive-for-escape.mk
unit-tests/directive-for-generating-endif.exp
unit-tests/directive-for-generating-endif.mk
+unit-tests/directive-for-lines.exp
+unit-tests/directive-for-lines.mk
+unit-tests/directive-for-null.exp
+unit-tests/directive-for-null.mk
unit-tests/directive-for.exp
unit-tests/directive-for.mk
unit-tests/directive-hyphen-include.exp
@@ -315,6 +345,8 @@ unit-tests/directive-include.exp
unit-tests/directive-include.mk
unit-tests/directive-info.exp
unit-tests/directive-info.mk
+unit-tests/directive-misspellings.exp
+unit-tests/directive-misspellings.mk
unit-tests/directive-sinclude.exp
unit-tests/directive-sinclude.mk
unit-tests/directive-undef.exp
@@ -365,10 +397,18 @@ unit-tests/job-flags.exp
unit-tests/job-flags.mk
unit-tests/job-output-long-lines.exp
unit-tests/job-output-long-lines.mk
+unit-tests/jobs-error-indirect.exp
+unit-tests/jobs-error-indirect.mk
+unit-tests/jobs-error-nested-make.exp
+unit-tests/jobs-error-nested-make.mk
+unit-tests/jobs-error-nested.exp
+unit-tests/jobs-error-nested.mk
unit-tests/lint.exp
unit-tests/lint.mk
unit-tests/make-exported.exp
unit-tests/make-exported.mk
+unit-tests/meta-cmd-cmp.exp
+unit-tests/meta-cmd-cmp.mk
unit-tests/moderrs.exp
unit-tests/moderrs.mk
unit-tests/modmatch.exp
@@ -447,14 +487,20 @@ unit-tests/opt-include-dir.exp
unit-tests/opt-include-dir.mk
unit-tests/opt-jobs-internal.exp
unit-tests/opt-jobs-internal.mk
+unit-tests/opt-jobs-no-action.exp
+unit-tests/opt-jobs-no-action.mk
unit-tests/opt-jobs.exp
unit-tests/opt-jobs.mk
+unit-tests/opt-keep-going-multiple.exp
+unit-tests/opt-keep-going-multiple.mk
unit-tests/opt-keep-going.exp
unit-tests/opt-keep-going.mk
unit-tests/opt-m-include-dir.exp
unit-tests/opt-m-include-dir.mk
unit-tests/opt-no-action-at-all.exp
unit-tests/opt-no-action-at-all.mk
+unit-tests/opt-no-action-runflags.exp
+unit-tests/opt-no-action-runflags.mk
unit-tests/opt-no-action.exp
unit-tests/opt-no-action.mk
unit-tests/opt-query.exp
@@ -491,12 +537,14 @@ unit-tests/posix.exp
unit-tests/posix.mk
unit-tests/posix1.exp
unit-tests/posix1.mk
-unit-tests/qequals.exp
-unit-tests/qequals.mk
unit-tests/recursive.exp
unit-tests/recursive.mk
unit-tests/sh-dots.exp
unit-tests/sh-dots.mk
+unit-tests/sh-errctl.exp
+unit-tests/sh-errctl.mk
+unit-tests/sh-flags.exp
+unit-tests/sh-flags.mk
unit-tests/sh-jobs-error.exp
unit-tests/sh-jobs-error.mk
unit-tests/sh-jobs.exp
@@ -529,14 +577,22 @@ unit-tests/suff-clear-regular.exp
unit-tests/suff-clear-regular.mk
unit-tests/suff-clear-single.exp
unit-tests/suff-clear-single.mk
+unit-tests/suff-incomplete.exp
+unit-tests/suff-incomplete.mk
unit-tests/suff-lookup.exp
unit-tests/suff-lookup.mk
+unit-tests/suff-main-several.exp
+unit-tests/suff-main-several.mk
unit-tests/suff-main.exp
unit-tests/suff-main.mk
+unit-tests/suff-phony.exp
+unit-tests/suff-phony.mk
unit-tests/suff-rebuild.exp
unit-tests/suff-rebuild.mk
unit-tests/suff-self.exp
unit-tests/suff-self.mk
+unit-tests/suff-transform-debug.exp
+unit-tests/suff-transform-debug.mk
unit-tests/suff-transform-endless.exp
unit-tests/suff-transform-endless.mk
unit-tests/suff-transform-expand.exp
@@ -607,6 +663,8 @@ unit-tests/varmod-head.exp
unit-tests/varmod-head.mk
unit-tests/varmod-ifelse.exp
unit-tests/varmod-ifelse.mk
+unit-tests/varmod-indirect.exp
+unit-tests/varmod-indirect.mk
unit-tests/varmod-l-name-to-value.exp
unit-tests/varmod-l-name-to-value.mk
unit-tests/varmod-localtime.exp
@@ -721,6 +779,8 @@ unit-tests/varname-dot-make-ppid.exp
unit-tests/varname-dot-make-ppid.mk
unit-tests/varname-dot-make-save_dollars.exp
unit-tests/varname-dot-make-save_dollars.mk
+unit-tests/varname-dot-makeflags.exp
+unit-tests/varname-dot-makeflags.mk
unit-tests/varname-dot-makeoverrides.exp
unit-tests/varname-dot-makeoverrides.mk
unit-tests/varname-dot-newline.exp
diff --git a/LICENSE b/LICENSE
index 283dd20cccd0..0d460e91d230 100644
--- a/LICENSE
+++ b/LICENSE
@@ -2,11 +2,11 @@ The individual files in this distribution are copyright their
original contributors or assignees.
Including:
- Copyright (c) 1993-2020, Simon J Gerraty
+ Copyright (c) 1993-2021, Simon J Gerraty
Copyright (c) 2020, Roland Illig <rillig@NetBSD.org>
Copyright (c) 2009-2016, Juniper Networks, Inc.
Copyright (c) 2009, John Birrell.
- Copyright (c) 1997-2020 The NetBSD Foundation, Inc.
+ Copyright (c) 1997-2021 The NetBSD Foundation, Inc.
Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
Copyright (c) 1989 by Berkeley Softworks
Copyright (c) 1988, 1989, 1990, 1992, 1993
diff --git a/PSD.doc/tutorial.ms b/PSD.doc/tutorial.ms
index 814a09a62146..da17f950f2b5 100644
--- a/PSD.doc/tutorial.ms
+++ b/PSD.doc/tutorial.ms
@@ -1,4 +1,4 @@
-.\" $NetBSD: tutorial.ms,v 1.13 2017/03/01 13:05:11 kre Exp $
+.\" $NetBSD: tutorial.ms,v 1.14 2020/12/18 15:47:34 rillig Exp $
.\" Copyright (c) 1988, 1989, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
@@ -1918,15 +1918,15 @@ Suff_FindDeps (jive.c)
applying .l -> .c to "jive.l"
Suff_FindDeps (jive.l)
Examining jive.l...modified 17:16:01 Oct 4, 1987...up-to-date
-Examining jive.c...non-existent...out-of-date
+Examining jive.c...nonexistent...out-of-date
--- jive.c ---
lex jive.l
\&.\|.\|. meaningless lex output deleted .\|.\|.
mv lex.yy.c jive.c
-Examining jive.o...non-existent...out-of-date
+Examining jive.o...nonexistent...out-of-date
--- jive.o ---
cc -c jive.c
-Examining jive.out...non-existent...out-of-date
+Examining jive.out...nonexistent...out-of-date
--- jive.out ---
cc -o jive.out jive.o
.DE
@@ -2871,7 +2871,7 @@ current directory. While people have suggested that PMake should read
the directories each time, my experience suggests that the caching seldom
causes problems. In addition, not caching the directories slows things
down enormously because of PMake's attempts to apply transformation
-rules through non-existent files \*- the number of extra file-system
+rules through nonexistent files \*- the number of extra file-system
searches is truly staggering, especially if many files without
suffixes are used and the null suffix isn't changed from
.CW .out .
diff --git a/VERSION b/VERSION
index 6dfd755ffdc8..70e0f68a60b0 100644
--- a/VERSION
+++ b/VERSION
@@ -1,2 +1,2 @@
# keep this compatible with sh and make
-_MAKE_VERSION=20201117
+_MAKE_VERSION=20210110
diff --git a/arch.c b/arch.c
index 81552dee2bb9..037f6bc548cf 100644
--- a/arch.c
+++ b/arch.c
@@ -1,4 +1,4 @@
-/* $NetBSD: arch.c,v 1.177 2020/11/14 21:29:44 rillig Exp $ */
+/* $NetBSD: arch.c,v 1.193 2021/01/09 16:06:09 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990, 1993
@@ -68,7 +68,8 @@
* SUCH DAMAGE.
*/
-/* Manipulate libraries, archives and their members.
+/*
+ * Manipulate libraries, archives and their members.
*
* The first time an archive is referenced, all of its members' headers are
* read and cached and the archive closed again. All cached archives are kept
@@ -146,19 +147,19 @@ struct ar_hdr {
#include "dir.h"
/* "@(#)arch.c 8.2 (Berkeley) 1/2/94" */
-MAKE_RCSID("$NetBSD: arch.c,v 1.177 2020/11/14 21:29:44 rillig Exp $");
+MAKE_RCSID("$NetBSD: arch.c,v 1.193 2021/01/09 16:06:09 rillig Exp $");
typedef struct List ArchList;
typedef struct ListNode ArchListNode;
-static ArchList *archives; /* The archives we've already examined */
+static ArchList archives; /* The archives we've already examined */
typedef struct Arch {
- char *name; /* Name of archive */
- HashTable members; /* All the members of the archive described
+ char *name; /* Name of archive */
+ HashTable members; /* All the members of the archive described
* by <name, struct ar_hdr *> key/value pairs */
- char *fnametab; /* Extended name table strings */
- size_t fnamesize; /* Size of the string table */
+ char *fnametab; /* Extended name table strings */
+ size_t fnamesize; /* Size of the string table */
} Arch;
static FILE *ArchFindMember(const char *, const char *,
@@ -200,240 +201,244 @@ static int ArchSVR4Entry(Arch *, char *, size_t, FILE *);
static void
ArchFree(void *ap)
{
- Arch *a = ap;
- HashIter hi;
-
- /* Free memory from hash entries */
- HashIter_Init(&hi, &a->members);
- while (HashIter_Next(&hi) != NULL)
- free(hi.entry->value);
-
- free(a->name);
- free(a->fnametab);
- HashTable_Done(&a->members);
- free(a);
+ Arch *a = ap;
+ HashIter hi;
+
+ /* Free memory from hash entries */
+ HashIter_Init(&hi, &a->members);
+ while (HashIter_Next(&hi) != NULL)
+ free(hi.entry->value);
+
+ free(a->name);
+ free(a->fnametab);
+ HashTable_Done(&a->members);
+ free(a);
}
#endif
/*
* Parse an archive specification such as "archive.a(member1 member2.${EXT})",
- * adding nodes for the expanded members to nodeLst. Nodes are created as
+ * adding nodes for the expanded members to gns. Nodes are created as
* necessary.
*
* Input:
* pp The start of the specification.
- * nodeLst The list on which to place the nodes.
+ * gns The list on which to place the nodes.
* ctxt The context in which to expand variables.
*
* Output:
* return TRUE if it was a valid specification.
* *pp Points to the first non-space after the archive spec.
- * *nodeLst Nodes for the members have been added.
*/
Boolean
-Arch_ParseArchive(char **pp, GNodeList *nodeLst, GNode *ctxt)
+Arch_ParseArchive(char **pp, GNodeList *gns, GNode *ctxt)
{
- char *cp; /* Pointer into line */
- GNode *gn; /* New node */
- char *libName; /* Library-part of specification */
- char *libName_freeIt = NULL;
- char *memName; /* Member-part of specification */
- char saveChar; /* Ending delimiter of member-name */
- Boolean expandLibName; /* Whether the parsed libName contains
+ char *cp; /* Pointer into line */
+ GNode *gn; /* New node */
+ MFStr libName; /* Library-part of specification */
+ char *memName; /* Member-part of specification */
+ char saveChar; /* Ending delimiter of member-name */
+ Boolean expandLibName; /* Whether the parsed libName contains
* variable expressions that need to be
* expanded */
- libName = *pp;
- expandLibName = FALSE;
-
- for (cp = libName; *cp != '(' && *cp != '\0';) {
- if (*cp == '$') {
- /*
- * Variable spec, so call the Var module to parse the puppy
- * so we can safely advance beyond it...
- */
- const char *nested_p = cp;
- void *result_freeIt;
- const char *result;
- Boolean isError;
-
- /* XXX: is expanded twice: once here and once below */
- (void)Var_Parse(&nested_p, ctxt, VARE_WANTRES | VARE_UNDEFERR,
- &result, &result_freeIt);
- /* TODO: handle errors */
- isError = result == var_Error;
- free(result_freeIt);
- if (isError)
- return FALSE;
-
- expandLibName = TRUE;
- cp += nested_p - cp;
- } else
- cp++;
- }
-
- *cp++ = '\0';
- if (expandLibName) {
- (void)Var_Subst(libName, ctxt, VARE_WANTRES | VARE_UNDEFERR, &libName);
- /* TODO: handle errors */
- libName_freeIt = libName;
- }
-
-
- for (;;) {
- /*
- * First skip to the start of the member's name, mark that
- * place and skip to the end of it (either white-space or
- * a close paren).
- */
- Boolean doSubst = FALSE; /* TRUE if need to substitute in memName */
-
- pp_skip_whitespace(&cp);
-
- memName = cp;
- while (*cp != '\0' && *cp != ')' && !ch_isspace(*cp)) {
- if (*cp == '$') {
- /*
- * Variable spec, so call the Var module to parse the puppy
- * so we can safely advance beyond it...
- */
- void *freeIt;
- const char *result;
- Boolean isError;
- const char *nested_p = cp;
-
- (void)Var_Parse(&nested_p, ctxt, VARE_WANTRES | VARE_UNDEFERR,
- &result, &freeIt);
- /* TODO: handle errors */
- isError = result == var_Error;
- free(freeIt);
-
- if (isError)
- return FALSE;
-
- doSubst = TRUE;
- cp += nested_p - cp;
- } else {
- cp++;
- }
- }
-
- /*
- * If the specification ends without a closing parenthesis,
- * chances are there's something wrong (like a missing backslash),
- * so it's better to return failure than allow such things to happen
- */
- if (*cp == '\0') {
- Parse_Error(PARSE_FATAL, "No closing parenthesis in archive specification");
- return FALSE;
+ libName = MFStr_InitRefer(*pp);
+ expandLibName = FALSE;
+
+ for (cp = libName.str; *cp != '(' && *cp != '\0';) {
+ if (*cp == '$') {
+ /* Expand nested variable expressions. */
+ /* XXX: This code can probably be shortened. */
+ const char *nested_p = cp;
+ FStr result;
+ Boolean isError;
+
+ /* XXX: is expanded twice: once here and once below */
+ (void)Var_Parse(&nested_p, ctxt,
+ VARE_WANTRES | VARE_UNDEFERR, &result);
+ /* TODO: handle errors */
+ isError = result.str == var_Error;
+ FStr_Done(&result);
+ if (isError)
+ return FALSE;
+
+ expandLibName = TRUE;
+ cp += nested_p - cp;
+ } else
+ cp++;
}
- /*
- * If we didn't move anywhere, we must be done
- */
- if (cp == memName) {
- break;
+ *cp++ = '\0';
+ if (expandLibName) {
+ char *expanded;
+ (void)Var_Subst(libName.str, ctxt,
+ VARE_WANTRES | VARE_UNDEFERR, &expanded);
+ /* TODO: handle errors */
+ libName = MFStr_InitOwn(expanded);
}
- saveChar = *cp;
- *cp = '\0';
- /*
- * XXX: This should be taken care of intelligently by
- * SuffExpandChildren, both for the archive and the member portions.
- */
- /*
- * If member contains variables, try and substitute for them.
- * This will slow down archive specs with dynamic sources, of course,
- * since we'll be (non-)substituting them three times, but them's
- * the breaks -- we need to do this since SuffExpandChildren calls
- * us, otherwise we could assume the thing would be taken care of
- * later.
- */
- if (doSubst) {
- char *buf;
- char *sacrifice;
- char *oldMemName = memName;
-
- (void)Var_Subst(memName, ctxt, VARE_WANTRES | VARE_UNDEFERR,
- &memName);
- /* TODO: handle errors */
-
- /*
- * Now form an archive spec and recurse to deal with nested
- * variables and multi-word variable values.... The results
- * are just placed at the end of the nodeLst we're returning.
- */
- buf = sacrifice = str_concat4(libName, "(", memName, ")");
-
- if (strchr(memName, '$') != NULL &&
- strcmp(memName, oldMemName) == 0) {
+ for (;;) {
/*
- * Must contain dynamic sources, so we can't deal with it now.
- * Just create an ARCHV node for the thing and let
- * SuffExpandChildren handle it...
+ * First skip to the start of the member's name, mark that
+ * place and skip to the end of it (either white-space or
+ * a close paren).
*/
- gn = Targ_GetNode(buf);
- gn->type |= OP_ARCHV;
- Lst_Append(nodeLst, gn);
-
- } else if (!Arch_ParseArchive(&sacrifice, nodeLst, ctxt)) {
- /* Error in nested call. */
- free(buf);
- return FALSE;
- }
- free(buf);
+ Boolean doSubst = FALSE;
+
+ pp_skip_whitespace(&cp);
+
+ memName = cp;
+ while (*cp != '\0' && *cp != ')' && !ch_isspace(*cp)) {
+ if (*cp == '$') {
+ /* Expand nested variable expressions. */
+ /* XXX: This code can probably be shortened. */
+ FStr result;
+ Boolean isError;
+ const char *nested_p = cp;
+
+ (void)Var_Parse(&nested_p, ctxt,
+ VARE_WANTRES | VARE_UNDEFERR,
+ &result);
+ /* TODO: handle errors */
+ isError = result.str == var_Error;
+ FStr_Done(&result);
+
+ if (isError)
+ return FALSE;
+
+ doSubst = TRUE;
+ cp += nested_p - cp;
+ } else {
+ cp++;
+ }
+ }
- } else if (Dir_HasWildcards(memName)) {
- StringList *members = Lst_New();
- Dir_Expand(memName, dirSearchPath, members);
+ /*
+ * If the specification ends without a closing parenthesis,
+ * chances are there's something wrong (like a missing
+ * backslash), so it's better to return failure than allow
+ * such things to happen
+ */
+ if (*cp == '\0') {
+ Parse_Error(PARSE_FATAL,
+ "No closing parenthesis "
+ "in archive specification");
+ return FALSE;
+ }
- while (!Lst_IsEmpty(members)) {
- char *member = Lst_Dequeue(members);
- char *fullname = str_concat4(libName, "(", member, ")");
- free(member);
+ /*
+ * If we didn't move anywhere, we must be done
+ */
+ if (cp == memName)
+ break;
- gn = Targ_GetNode(fullname);
- free(fullname);
+ saveChar = *cp;
+ *cp = '\0';
- gn->type |= OP_ARCHV;
- Lst_Append(nodeLst, gn);
- }
- Lst_Free(members);
+ /*
+ * XXX: This should be taken care of intelligently by
+ * SuffExpandChildren, both for the archive and the member
+ * portions.
+ */
+ /*
+ * If member contains variables, try and substitute for them.
+ * This will slow down archive specs with dynamic sources, of
+ * course, since we'll be (non-)substituting them three
+ * times, but them's the breaks -- we need to do this since
+ * SuffExpandChildren calls us, otherwise we could assume the
+ * thing would be taken care of later.
+ */
+ if (doSubst) {
+ char *fullName;
+ char *p;
+ char *unexpandedMemName = memName;
+
+ (void)Var_Subst(memName, ctxt,
+ VARE_WANTRES | VARE_UNDEFERR,
+ &memName);
+ /* TODO: handle errors */
+
+ /*
+ * Now form an archive spec and recurse to deal with
+ * nested variables and multi-word variable values.
+ */
+ fullName = str_concat4(libName.str, "(", memName, ")");
+ p = fullName;
+
+ if (strchr(memName, '$') != NULL &&
+ strcmp(memName, unexpandedMemName) == 0) {
+ /*
+ * Must contain dynamic sources, so we can't
+ * deal with it now. Just create an ARCHV node
+ * for the thing and let SuffExpandChildren
+ * handle it.
+ */
+ gn = Targ_GetNode(fullName);
+ gn->type |= OP_ARCHV;
+ Lst_Append(gns, gn);
+
+ } else if (!Arch_ParseArchive(&p, gns, ctxt)) {
+ /* Error in nested call. */
+ free(fullName);
+ /* XXX: does unexpandedMemName leak? */
+ return FALSE;
+ }
+ free(fullName);
+ /* XXX: does unexpandedMemName leak? */
+
+ } else if (Dir_HasWildcards(memName)) {
+ StringList members = LST_INIT;
+ Dir_Expand(memName, &dirSearchPath, &members);
+
+ while (!Lst_IsEmpty(&members)) {
+ char *member = Lst_Dequeue(&members);
+ char *fullname = str_concat4(libName.str, "(",
+ member, ")");
+ free(member);
+
+ gn = Targ_GetNode(fullname);
+ free(fullname);
+
+ gn->type |= OP_ARCHV;
+ Lst_Append(gns, gn);
+ }
+ Lst_Done(&members);
+
+ } else {
+ char *fullname = str_concat4(libName.str, "(", memName,
+ ")");
+ gn = Targ_GetNode(fullname);
+ free(fullname);
+
+ /*
+ * We've found the node, but have to make sure the
+ * rest of the world knows it's an archive member,
+ * without having to constantly check for parentheses,
+ * so we type the thing with the OP_ARCHV bit before
+ * we place it on the end of the provided list.
+ */
+ gn->type |= OP_ARCHV;
+ Lst_Append(gns, gn);
+ }
+ if (doSubst)
+ free(memName);
- } else {
- char *fullname = str_concat4(libName, "(", memName, ")");
- gn = Targ_GetNode(fullname);
- free(fullname);
-
- /*
- * We've found the node, but have to make sure the rest of the
- * world knows it's an archive member, without having to
- * constantly check for parentheses, so we type the thing with
- * the OP_ARCHV bit before we place it on the end of the
- * provided list.
- */
- gn->type |= OP_ARCHV;
- Lst_Append(nodeLst, gn);
+ *cp = saveChar;
}
- if (doSubst) {
- free(memName);
- }
-
- *cp = saveChar;
- }
- free(libName_freeIt);
+ MFStr_Done(&libName);
- cp++; /* skip the ')' */
- /* We promised that pp would be set up at the next non-space. */
- pp_skip_whitespace(&cp);
- *pp = cp;
- return TRUE;
+ cp++; /* skip the ')' */
+ /* We promised that pp would be set up at the next non-space. */
+ pp_skip_whitespace(&cp);
+ *pp = cp;
+ return TRUE;
}
-/* Locate a member of an archive, given the path of the archive and the path
+/*
+ * Locate a member of an archive, given the path of the archive and the path
* of the desired member.
*
* Input:
@@ -449,264 +454,261 @@ Arch_ParseArchive(char **pp, GNodeList *nodeLst, GNode *ctxt)
static struct ar_hdr *
ArchStatMember(const char *archive, const char *member, Boolean addToCache)
{
-#define AR_MAX_NAME_LEN (sizeof arh.AR_NAME - 1)
- FILE *arch; /* Stream to archive */
- size_t size; /* Size of archive member */
- char magic[SARMAG];
- ArchListNode *ln;
- Arch *ar; /* Archive descriptor */
- struct ar_hdr arh; /* archive-member header for reading archive */
- char memName[MAXPATHLEN + 1];
- /* Current member name while hashing. */
-
- /*
- * Because of space constraints and similar things, files are archived
- * using their basename, not the entire path.
- */
- const char *lastSlash = strrchr(member, '/');
- if (lastSlash != NULL)
- member = lastSlash + 1;
-
- for (ln = archives->first; ln != NULL; ln = ln->next) {
- const Arch *a = ln->datum;
- if (strcmp(a->name, archive) == 0)
- break;
- }
-
- if (ln != NULL) {
- struct ar_hdr *hdr;
-
- ar = ln->datum;
- hdr = HashTable_FindValue(&ar->members, member);
- if (hdr != NULL)
- return hdr;
-
- {
- /* Try truncated name */
- char copy[AR_MAX_NAME_LEN + 1];
- size_t len = strlen(member);
-
- if (len > AR_MAX_NAME_LEN) {
- len = AR_MAX_NAME_LEN;
- snprintf(copy, sizeof copy, "%s", member);
- hdr = HashTable_FindValue(&ar->members, copy);
- }
- return hdr;
- }
- }
+#define AR_MAX_NAME_LEN (sizeof arh.ar_name - 1)
+ FILE *arch;
+ size_t size; /* Size of archive member */
+ char magic[SARMAG];
+ ArchListNode *ln;
+ Arch *ar; /* Archive descriptor */
+ struct ar_hdr arh; /* archive-member header for reading archive */
+ char memName[MAXPATHLEN + 1];
+ /* Current member name while hashing. */
- if (!addToCache) {
/*
- * Caller doesn't want the thing cached, just use ArchFindMember
- * to read the header for the member out and close down the stream
- * again. Since the archive is not to be cached, we assume there's
- * no need to allocate extra room for the header we're returning,
- * so just declare it static.
+ * Because of space constraints and similar things, files are archived
+ * using their basename, not the entire path.
*/
- static struct ar_hdr sarh;
+ member = str_basename(member);
- arch = ArchFindMember(archive, member, &sarh, "r");
- if (arch == NULL)
- return NULL;
+ for (ln = archives.first; ln != NULL; ln = ln->next) {
+ const Arch *a = ln->datum;
+ if (strcmp(a->name, archive) == 0)
+ break;
+ }
- fclose(arch);
- return &sarh;
- }
-
- /*
- * We don't have this archive on the list yet, so we want to find out
- * everything that's in it and cache it so we can get at it quickly.
- */
- arch = fopen(archive, "r");
- if (arch == NULL)
- return NULL;
+ if (ln != NULL) {
+ struct ar_hdr *hdr;
- /*
- * We use the ARMAG string to make sure this is an archive we
- * can handle...
- */
- if (fread(magic, SARMAG, 1, arch) != 1 ||
- strncmp(magic, ARMAG, SARMAG) != 0) {
- (void)fclose(arch);
- return NULL;
- }
+ ar = ln->datum;
+ hdr = HashTable_FindValue(&ar->members, member);
+ if (hdr != NULL)
+ return hdr;
- ar = bmake_malloc(sizeof *ar);
- ar->name = bmake_strdup(archive);
- ar->fnametab = NULL;
- ar->fnamesize = 0;
- HashTable_Init(&ar->members);
- memName[AR_MAX_NAME_LEN] = '\0';
+ {
+ /* Try truncated name */
+ char copy[AR_MAX_NAME_LEN + 1];
+ size_t len = strlen(member);
- while (fread(&arh, sizeof arh, 1, arch) == 1) {
- char *nameend;
+ if (len > AR_MAX_NAME_LEN) {
+ snprintf(copy, sizeof copy, "%s", member);
+ hdr = HashTable_FindValue(&ar->members, copy);
+ }
+ return hdr;
+ }
+ }
+
+ if (!addToCache) {
+ /*
+ * Caller doesn't want the thing cached, just use
+ * ArchFindMember to read the header for the member out and
+ * close down the stream again. Since the archive is not to be
+ * cached, we assume there's no need to allocate extra room
+ * for the header we're returning, so just declare it static.
+ */
+ static struct ar_hdr sarh;
- /* If the header is bogus, there's no way we can recover. */
- if (strncmp(arh.AR_FMAG, ARFMAG, sizeof arh.AR_FMAG) != 0)
- goto badarch;
+ arch = ArchFindMember(archive, member, &sarh, "r");
+ if (arch == NULL)
+ return NULL;
+
+ fclose(arch);
+ return &sarh;
+ }
/*
- * We need to advance the stream's pointer to the start of the
- * next header. Files are padded with newlines to an even-byte
- * boundary, so we need to extract the size of the file from the
- * 'size' field of the header and round it up during the seek.
+ * We don't have this archive on the list yet, so we want to find out
+ * everything that's in it and cache it so we can get at it quickly.
*/
- arh.AR_SIZE[sizeof arh.AR_SIZE - 1] = '\0';
- size = (size_t)strtol(arh.AR_SIZE, NULL, 10);
-
- memcpy(memName, arh.AR_NAME, sizeof arh.AR_NAME);
- nameend = memName + AR_MAX_NAME_LEN;
- while (nameend > memName && *nameend == ' ')
- nameend--;
- nameend[1] = '\0';
+ arch = fopen(archive, "r");
+ if (arch == NULL)
+ return NULL;
-#ifdef SVR4ARCHIVES
/*
- * svr4 names are slash terminated. Also svr4 extended AR format.
+ * We use the ARMAG string to make sure this is an archive we
+ * can handle...
*/
- if (memName[0] == '/') {
- /*
- * svr4 magic mode; handle it
- */
- switch (ArchSVR4Entry(ar, memName, size, arch)) {
- case -1: /* Invalid data */
- goto badarch;
- case 0: /* List of files entry */
- continue;
- default: /* Got the entry */
- break;
- }
- } else {
- if (nameend[0] == '/')
- nameend[0] = '\0';
+ if (fread(magic, SARMAG, 1, arch) != 1 ||
+ strncmp(magic, ARMAG, SARMAG) != 0) {
+ (void)fclose(arch);
+ return NULL;
}
+
+ ar = bmake_malloc(sizeof *ar);
+ ar->name = bmake_strdup(archive);
+ ar->fnametab = NULL;
+ ar->fnamesize = 0;
+ HashTable_Init(&ar->members);
+ memName[AR_MAX_NAME_LEN] = '\0';
+
+ while (fread(&arh, sizeof arh, 1, arch) == 1) {
+ char *nameend;
+
+ /* If the header is bogus, there's no way we can recover. */
+ if (strncmp(arh.AR_FMAG, ARFMAG, sizeof arh.AR_FMAG) != 0)
+ goto badarch;
+
+ /*
+ * We need to advance the stream's pointer to the start of the
+ * next header. Files are padded with newlines to an even-byte
+ * boundary, so we need to extract the size of the file from
+ * the 'size' field of the header and round it up during the
+ * seek.
+ */
+ arh.AR_SIZE[sizeof arh.AR_SIZE - 1] = '\0';
+ size = (size_t)strtol(arh.AR_SIZE, NULL, 10);
+
+ memcpy(memName, arh.AR_NAME, sizeof arh.AR_NAME);
+ nameend = memName + AR_MAX_NAME_LEN;
+ while (nameend > memName && *nameend == ' ')
+ nameend--;
+ nameend[1] = '\0';
+
+#ifdef SVR4ARCHIVES
+ /*
+ * svr4 names are slash-terminated.
+ * Also svr4 extended the AR format.
+ */
+ if (memName[0] == '/') {
+ /* svr4 magic mode; handle it */
+ switch (ArchSVR4Entry(ar, memName, size, arch)) {
+ case -1: /* Invalid data */
+ goto badarch;
+ case 0: /* List of files entry */
+ continue;
+ default: /* Got the entry */
+ break;
+ }
+ } else {
+ if (nameend[0] == '/')
+ nameend[0] = '\0';
+ }
#endif
#ifdef AR_EFMT1
- /*
- * BSD 4.4 extended AR format: #1/<namelen>, with name as the
- * first <namelen> bytes of the file
- */
- if (strncmp(memName, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
- ch_isdigit(memName[sizeof AR_EFMT1 - 1])) {
-
- int elen = atoi(memName + sizeof AR_EFMT1 - 1);
-
- if ((unsigned int)elen > MAXPATHLEN)
- goto badarch;
- if (fread(memName, (size_t)elen, 1, arch) != 1)
- goto badarch;
- memName[elen] = '\0';
- if (fseek(arch, -elen, SEEK_CUR) != 0)
- goto badarch;
- if (DEBUG(ARCH) || DEBUG(MAKE))
- debug_printf("ArchStatMember: Extended format entry for %s\n",
- memName);
- }
+ /*
+ * BSD 4.4 extended AR format: #1/<namelen>, with name as the
+ * first <namelen> bytes of the file
+ */
+ if (strncmp(memName, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
+ ch_isdigit(memName[sizeof AR_EFMT1 - 1])) {
+
+ int elen = atoi(memName + sizeof AR_EFMT1 - 1);
+
+ if ((unsigned int)elen > MAXPATHLEN)
+ goto badarch;
+ if (fread(memName, (size_t)elen, 1, arch) != 1)
+ goto badarch;
+ memName[elen] = '\0';
+ if (fseek(arch, -elen, SEEK_CUR) != 0)
+ goto badarch;
+ if (DEBUG(ARCH) || DEBUG(MAKE))
+ debug_printf(
+ "ArchStatMember: "
+ "Extended format entry for %s\n",
+ memName);
+ }
#endif
- {
- struct ar_hdr *cached_hdr = bmake_malloc(sizeof *cached_hdr);
- memcpy(cached_hdr, &arh, sizeof arh);
- HashTable_Set(&ar->members, memName, cached_hdr);
- }
+ {
+ struct ar_hdr *cached_hdr = bmake_malloc(
+ sizeof *cached_hdr);
+ memcpy(cached_hdr, &arh, sizeof arh);
+ HashTable_Set(&ar->members, memName, cached_hdr);
+ }
- if (fseek(arch, ((long)size + 1) & ~1, SEEK_CUR) != 0)
- goto badarch;
- }
+ if (fseek(arch, ((long)size + 1) & ~1, SEEK_CUR) != 0)
+ goto badarch;
+ }
- fclose(arch);
+ fclose(arch);
- Lst_Append(archives, ar);
+ Lst_Append(&archives, ar);
- /*
- * Now that the archive has been read and cached, we can look into
- * the addToCache table to find the desired member's header.
- */
- return HashTable_FindValue(&ar->members, member);
+ /*
+ * Now that the archive has been read and cached, we can look into
+ * the addToCache table to find the desired member's header.
+ */
+ return HashTable_FindValue(&ar->members, member);
badarch:
- fclose(arch);
- HashTable_Done(&ar->members);
- free(ar->fnametab);
- free(ar);
- return NULL;
+ fclose(arch);
+ HashTable_Done(&ar->members);
+ free(ar->fnametab);
+ free(ar);
+ return NULL;
}
#ifdef SVR4ARCHIVES
-/*-
- *-----------------------------------------------------------------------
- * ArchSVR4Entry --
- * Parse an SVR4 style entry that begins with a slash.
- * If it is "//", then load the table of filenames
- * If it is "/<offset>", then try to substitute the long file name
- * from offset of a table previously read.
- * If a table is read, the file pointer is moved to the next archive
- * member.
+/*
+ * Parse an SVR4 style entry that begins with a slash.
+ * If it is "//", then load the table of filenames.
+ * If it is "/<offset>", then try to substitute the long file name
+ * from offset of a table previously read.
+ * If a table is read, the file pointer is moved to the next archive member.
*
* Results:
* -1: Bad data in archive
* 0: A table was loaded from the file
* 1: Name was successfully substituted from table
* 2: Name was not successfully substituted from table
- *-----------------------------------------------------------------------
*/
static int
ArchSVR4Entry(Arch *ar, char *inout_name, size_t size, FILE *arch)
{
#define ARLONGNAMES1 "//"
#define ARLONGNAMES2 "/ARFILENAMES"
- size_t entry;
- char *ptr, *eptr;
+ size_t entry;
+ char *ptr, *eptr;
- if (strncmp(inout_name, ARLONGNAMES1, sizeof ARLONGNAMES1 - 1) == 0 ||
- strncmp(inout_name, ARLONGNAMES2, sizeof ARLONGNAMES2 - 1) == 0) {
+ if (strncmp(inout_name, ARLONGNAMES1, sizeof ARLONGNAMES1 - 1) == 0 ||
+ strncmp(inout_name, ARLONGNAMES2, sizeof ARLONGNAMES2 - 1) == 0) {
- if (ar->fnametab != NULL) {
- DEBUG0(ARCH, "Attempted to redefine an SVR4 name table\n");
- return -1;
+ if (ar->fnametab != NULL) {
+ DEBUG0(ARCH,
+ "Attempted to redefine an SVR4 name table\n");
+ return -1;
+ }
+
+ /*
+ * This is a table of archive names, so we build one for
+ * ourselves
+ */
+ ar->fnametab = bmake_malloc(size);
+ ar->fnamesize = size;
+
+ if (fread(ar->fnametab, size, 1, arch) != 1) {
+ DEBUG0(ARCH, "Reading an SVR4 name table failed\n");
+ return -1;
+ }
+ eptr = ar->fnametab + size;
+ for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)
+ if (*ptr == '/') {
+ entry++;
+ *ptr = '\0';
+ }
+ DEBUG1(ARCH, "Found svr4 archive name table with %lu entries\n",
+ (unsigned long)entry);
+ return 0;
}
- /*
- * This is a table of archive names, so we build one for
- * ourselves
- */
- ar->fnametab = bmake_malloc(size);
- ar->fnamesize = size;
+ if (inout_name[1] == ' ' || inout_name[1] == '\0')
+ return 2;
- if (fread(ar->fnametab, size, 1, arch) != 1) {
- DEBUG0(ARCH, "Reading an SVR4 name table failed\n");
- return -1;
+ entry = (size_t)strtol(&inout_name[1], &eptr, 0);
+ if ((*eptr != ' ' && *eptr != '\0') || eptr == &inout_name[1]) {
+ DEBUG1(ARCH, "Could not parse SVR4 name %s\n", inout_name);
+ return 2;
+ }
+ if (entry >= ar->fnamesize) {
+ DEBUG2(ARCH, "SVR4 entry offset %s is greater than %lu\n",
+ inout_name, (unsigned long)ar->fnamesize);
+ return 2;
}
- eptr = ar->fnametab + size;
- for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)
- if (*ptr == '/') {
- entry++;
- *ptr = '\0';
- }
- DEBUG1(ARCH, "Found svr4 archive name table with %lu entries\n",
- (unsigned long)entry);
- return 0;
- }
-
- if (inout_name[1] == ' ' || inout_name[1] == '\0')
- return 2;
-
- entry = (size_t)strtol(&inout_name[1], &eptr, 0);
- if ((*eptr != ' ' && *eptr != '\0') || eptr == &inout_name[1]) {
- DEBUG1(ARCH, "Could not parse SVR4 name %s\n", inout_name);
- return 2;
- }
- if (entry >= ar->fnamesize) {
- DEBUG2(ARCH, "SVR4 entry offset %s is greater than %lu\n",
- inout_name, (unsigned long)ar->fnamesize);
- return 2;
- }
-
- DEBUG2(ARCH, "Replaced %s with %s\n", inout_name, &ar->fnametab[entry]);
-
- snprintf(inout_name, MAXPATHLEN + 1, "%s", &ar->fnametab[entry]);
- return 1;
+
+ DEBUG2(ARCH, "Replaced %s with %s\n", inout_name, &ar->fnametab[entry]);
+
+ snprintf(inout_name, MAXPATHLEN + 1, "%s", &ar->fnametab[entry]);
+ return 1;
}
#endif
@@ -715,29 +717,30 @@ static Boolean
ArchiveMember_HasName(const struct ar_hdr *hdr,
const char *name, size_t namelen)
{
- const size_t ar_name_len = sizeof hdr->AR_NAME;
- const char *ar_name = hdr->AR_NAME;
+ const size_t ar_name_len = sizeof hdr->AR_NAME;
+ const char *ar_name = hdr->AR_NAME;
- if (strncmp(ar_name, name, namelen) != 0)
- return FALSE;
+ if (strncmp(ar_name, name, namelen) != 0)
+ return FALSE;
- if (namelen >= ar_name_len)
- return namelen == ar_name_len;
+ if (namelen >= ar_name_len)
+ return namelen == ar_name_len;
- /* hdr->AR_NAME is space-padded to the right. */
- if (ar_name[namelen] == ' ')
- return TRUE;
+ /* hdr->AR_NAME is space-padded to the right. */
+ if (ar_name[namelen] == ' ')
+ return TRUE;
- /* In archives created by GNU binutils 2.27, the member names end with
- * a slash. */
- if (ar_name[namelen] == '/' &&
- (namelen == ar_name_len || ar_name[namelen + 1] == ' '))
- return TRUE;
+ /* In archives created by GNU binutils 2.27, the member names end with
+ * a slash. */
+ if (ar_name[namelen] == '/' &&
+ (namelen == ar_name_len || ar_name[namelen + 1] == ' '))
+ return TRUE;
- return FALSE;
+ return FALSE;
}
-/* Locate a member of an archive, given the path of the archive and the path
+/*
+ * Locate a member of an archive, given the path of the archive and the path
* of the desired member.
*
* Input:
@@ -759,130 +762,130 @@ static FILE *
ArchFindMember(const char *archive, const char *member, struct ar_hdr *out_arh,
const char *mode)
{
- FILE *arch; /* Stream to archive */
- int size; /* Size of archive member */
- char magic[SARMAG];
- size_t len, tlen;
- const char *lastSlash;
-
- arch = fopen(archive, mode);
- if (arch == NULL)
- return NULL;
+ FILE *arch; /* Stream to archive */
+ int size; /* Size of archive member */
+ char magic[SARMAG];
+ size_t len;
- /*
- * We use the ARMAG string to make sure this is an archive we
- * can handle...
- */
- if (fread(magic, SARMAG, 1, arch) != 1 ||
- strncmp(magic, ARMAG, SARMAG) != 0) {
- fclose(arch);
- return NULL;
- }
-
- /*
- * Because of space constraints and similar things, files are archived
- * using their basename, not the entire path.
- */
- lastSlash = strrchr(member, '/');
- if (lastSlash != NULL)
- member = lastSlash + 1;
-
- len = tlen = strlen(member);
- if (len > sizeof out_arh->AR_NAME) {
- tlen = sizeof out_arh->AR_NAME;
- }
-
- while (fread(out_arh, sizeof *out_arh, 1, arch) == 1) {
-
- if (strncmp(out_arh->AR_FMAG, ARFMAG, sizeof out_arh->AR_FMAG) != 0) {
- /*
- * The header is bogus, so the archive is bad
- * and there's no way we can recover...
- */
- fclose(arch);
- return NULL;
- }
+ arch = fopen(archive, mode);
+ if (arch == NULL)
+ return NULL;
- DEBUG5(ARCH, "Reading archive %s member %.*s mtime %.*s\n",
- archive,
- (int)sizeof out_arh->AR_NAME, out_arh->AR_NAME,
- (int)sizeof out_arh->ar_date, out_arh->ar_date);
-
- if (ArchiveMember_HasName(out_arh, member, len)) {
- /*
- * To make life easier for callers that want to update the
- * archive, we reposition the file at the start
- * of the header we just read before we return the stream.
- * In a more general situation, it might be better to leave
- * the file at the actual member, rather than its header, but
- * not here.
- */
- if (fseek(arch, -(long)sizeof *out_arh, SEEK_CUR) != 0) {
+ /*
+ * We use the ARMAG string to make sure this is an archive we
+ * can handle...
+ */
+ if (fread(magic, SARMAG, 1, arch) != 1 ||
+ strncmp(magic, ARMAG, SARMAG) != 0) {
fclose(arch);
return NULL;
- }
- return arch;
}
-#ifdef AR_EFMT1
/*
- * BSD 4.4 extended AR format: #1/<namelen>, with name as the
- * first <namelen> bytes of the file
+ * Because of space constraints and similar things, files are archived
+ * using their basename, not the entire path.
*/
- if (strncmp(out_arh->AR_NAME, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&
- ch_isdigit(out_arh->AR_NAME[sizeof AR_EFMT1 - 1]))
- {
- int elen = atoi(&out_arh->AR_NAME[sizeof AR_EFMT1 - 1]);
- char ename[MAXPATHLEN + 1];
+ member = str_basename(member);
- if ((unsigned int)elen > MAXPATHLEN) {
- fclose(arch);
- return NULL;
- }
- if (fread(ename, (size_t)elen, 1, arch) != 1) {
- fclose(arch);
- return NULL;
- }
- ename[elen] = '\0';
- if (DEBUG(ARCH) || DEBUG(MAKE))
- debug_printf("ArchFindMember: Extended format entry for %s\n",
- ename);
- if (strncmp(ename, member, len) == 0) {
- /* Found as extended name */
- if (fseek(arch, -(long)sizeof(struct ar_hdr) - elen,
- SEEK_CUR) != 0) {
- fclose(arch);
- return NULL;
+ len = strlen(member);
+
+ while (fread(out_arh, sizeof *out_arh, 1, arch) == 1) {
+
+ if (strncmp(out_arh->AR_FMAG, ARFMAG,
+ sizeof out_arh->AR_FMAG) != 0) {
+ /*
+ * The header is bogus, so the archive is bad
+ * and there's no way we can recover...
+ */
+ fclose(arch);
+ return NULL;
+ }
+
+ DEBUG5(ARCH, "Reading archive %s member %.*s mtime %.*s\n",
+ archive,
+ (int)sizeof out_arh->AR_NAME, out_arh->AR_NAME,
+ (int)sizeof out_arh->ar_date, out_arh->ar_date);
+
+ if (ArchiveMember_HasName(out_arh, member, len)) {
+ /*
+ * To make life easier for callers that want to update
+ * the archive, we reposition the file at the start of
+ * the header we just read before we return the
+ * stream. In a more general situation, it might be
+ * better to leave the file at the actual member,
+ * rather than its header, but not here.
+ */
+ if (fseek(arch, -(long)sizeof *out_arh, SEEK_CUR) !=
+ 0) {
+ fclose(arch);
+ return NULL;
+ }
+ return arch;
+ }
+
+#ifdef AR_EFMT1
+ /*
+ * BSD 4.4 extended AR format: #1/<namelen>, with name as the
+ * first <namelen> bytes of the file
+ */
+ if (strncmp(out_arh->AR_NAME, AR_EFMT1, sizeof AR_EFMT1 - 1) ==
+ 0 &&
+ (ch_isdigit(out_arh->AR_NAME[sizeof AR_EFMT1 - 1]))) {
+ int elen = atoi(&out_arh->AR_NAME[sizeof AR_EFMT1 - 1]);
+ char ename[MAXPATHLEN + 1];
+
+ if ((unsigned int)elen > MAXPATHLEN) {
+ fclose(arch);
+ return NULL;
+ }
+ if (fread(ename, (size_t)elen, 1, arch) != 1) {
+ fclose(arch);
+ return NULL;
+ }
+ ename[elen] = '\0';
+ if (DEBUG(ARCH) || DEBUG(MAKE))
+ debug_printf(
+ "ArchFindMember: "
+ "Extended format entry for %s\n",
+ ename);
+ if (strncmp(ename, member, len) == 0) {
+ /* Found as extended name */
+ if (fseek(arch,
+ -(long)sizeof(struct ar_hdr) - elen,
+ SEEK_CUR) != 0) {
+ fclose(arch);
+ return NULL;
+ }
+ return arch;
+ }
+ if (fseek(arch, -elen, SEEK_CUR) != 0) {
+ fclose(arch);
+ return NULL;
+ }
}
- return arch;
- }
- if (fseek(arch, -elen, SEEK_CUR) != 0) {
- fclose(arch);
- return NULL;
- }
- }
#endif
- /*
- * This isn't the member we're after, so we need to advance the
- * stream's pointer to the start of the next header. Files are
- * padded with newlines to an even-byte boundary, so we need to
- * extract the size of the file from the 'size' field of the
- * header and round it up during the seek.
- */
- out_arh->AR_SIZE[sizeof out_arh->AR_SIZE - 1] = '\0';
- size = (int)strtol(out_arh->AR_SIZE, NULL, 10);
- if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0) {
- fclose(arch);
- return NULL;
+ /*
+ * This isn't the member we're after, so we need to advance the
+ * stream's pointer to the start of the next header. Files are
+ * padded with newlines to an even-byte boundary, so we need to
+ * extract the size of the file from the 'size' field of the
+ * header and round it up during the seek.
+ */
+ out_arh->AR_SIZE[sizeof out_arh->AR_SIZE - 1] = '\0';
+ size = (int)strtol(out_arh->AR_SIZE, NULL, 10);
+ if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0) {
+ fclose(arch);
+ return NULL;
+ }
}
- }
- fclose(arch);
- return NULL;
+ fclose(arch);
+ return NULL;
}
-/* Touch a member of an archive, on disk.
+/*
+ * Touch a member of an archive, on disk.
* The GNode's modification time is left as-is.
*
* The st_mtime of the entire archive is also changed.
@@ -897,97 +900,107 @@ ArchFindMember(const char *archive, const char *member, struct ar_hdr *out_arh,
void
Arch_Touch(GNode *gn)
{
- FILE *f;
- struct ar_hdr arh;
+ FILE *f;
+ struct ar_hdr arh;
- f = ArchFindMember(GNode_VarArchive(gn), GNode_VarMember(gn), &arh, "r+");
- if (f == NULL)
- return;
+ f = ArchFindMember(GNode_VarArchive(gn), GNode_VarMember(gn), &arh,
+ "r+");
+ if (f == NULL)
+ return;
- snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
- (void)fwrite(&arh, sizeof arh, 1, f);
- fclose(f); /* TODO: handle errors */
+ snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
+ (void)fwrite(&arh, sizeof arh, 1, f);
+ fclose(f); /* TODO: handle errors */
}
-/* Given a node which represents a library, touch the thing, making sure that
+/*
+ * Given a node which represents a library, touch the thing, making sure that
* the table of contents is also touched.
*
* Both the modification time of the library and of the RANLIBMAG member are
- * set to 'now'. */
+ * set to 'now'.
+ */
+/*ARGSUSED*/
void
Arch_TouchLib(GNode *gn MAKE_ATTR_UNUSED)
{
#ifdef RANLIBMAG
- FILE *f;
- struct ar_hdr arh; /* Header describing table of contents */
- struct utimbuf times;
+ FILE *f;
+ struct ar_hdr arh; /* Header describing table of contents */
+ struct utimbuf times;
- f = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");
- if (f == NULL)
- return;
+ f = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");
+ if (f == NULL)
+ return;
- snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
- (void)fwrite(&arh, sizeof arh, 1, f);
- fclose(f); /* TODO: handle errors */
+ snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);
+ (void)fwrite(&arh, sizeof arh, 1, f);
+ fclose(f); /* TODO: handle errors */
- times.actime = times.modtime = now;
- utime(gn->path, &times); /* TODO: handle errors */
+ times.actime = times.modtime = now;
+ utime(gn->path, &times); /* TODO: handle errors */
#endif
}
-/* Update the mtime of the GNode with the mtime from the archive member on
- * disk (or in the cache). */
+/*
+ * Update the mtime of the GNode with the mtime from the archive member on
+ * disk (or in the cache).
+ */
void
Arch_UpdateMTime(GNode *gn)
{
- struct ar_hdr *arh;
+ struct ar_hdr *arh;
- arh = ArchStatMember(GNode_VarArchive(gn), GNode_VarMember(gn), TRUE);
- if (arh != NULL)
- gn->mtime = (time_t)strtol(arh->ar_date, NULL, 10);
- else
- gn->mtime = 0;
+ arh = ArchStatMember(GNode_VarArchive(gn), GNode_VarMember(gn), TRUE);
+ if (arh != NULL)
+ gn->mtime = (time_t)strtol(arh->ar_date, NULL, 10);
+ else
+ gn->mtime = 0;
}
-/* Given a non-existent archive member's node, update gn->mtime from its
- * archived form, if it exists. */
+/*
+ * Given a nonexistent archive member's node, update gn->mtime from its
+ * archived form, if it exists.
+ */
void
Arch_UpdateMemberMTime(GNode *gn)
{
- GNodeListNode *ln;
-
- for (ln = gn->parents->first; ln != NULL; ln = ln->next) {
- GNode *pgn = ln->datum;
-
- if (pgn->type & OP_ARCHV) {
- /*
- * If the parent is an archive specification and is being made
- * and its member's name matches the name of the node we were
- * given, record the modification time of the parent in the
- * child. We keep searching its parents in case some other
- * parent requires this child to exist...
- */
- const char *nameStart = strchr(pgn->name, '(') + 1;
- const char *nameEnd = strchr(nameStart, ')');
- size_t nameLen = (size_t)(nameEnd - nameStart);
-
- if ((pgn->flags & REMAKE) &&
- strncmp(nameStart, gn->name, nameLen) == 0) {
- Arch_UpdateMTime(pgn);
- gn->mtime = pgn->mtime;
- }
- } else if (pgn->flags & REMAKE) {
- /*
- * Something which isn't a library depends on the existence of
- * this target, so it needs to exist.
- */
- gn->mtime = 0;
- break;
+ GNodeListNode *ln;
+
+ for (ln = gn->parents.first; ln != NULL; ln = ln->next) {
+ GNode *pgn = ln->datum;
+
+ if (pgn->type & OP_ARCHV) {
+ /*
+ * If the parent is an archive specification and is
+ * being made and its member's name matches the name
+ * of the node we were given, record the modification
+ * time of the parent in the child. We keep searching
+ * its parents in case some other parent requires this
+ * child to exist.
+ */
+ const char *nameStart = strchr(pgn->name, '(') + 1;
+ const char *nameEnd = strchr(nameStart, ')');
+ size_t nameLen = (size_t)(nameEnd - nameStart);
+
+ if ((pgn->flags & REMAKE) &&
+ strncmp(nameStart, gn->name, nameLen) == 0) {
+ Arch_UpdateMTime(pgn);
+ gn->mtime = pgn->mtime;
+ }
+ } else if (pgn->flags & REMAKE) {
+ /*
+ * Something which isn't a library depends on the
+ * existence of this target, so it needs to exist.
+ */
+ gn->mtime = 0;
+ break;
+ }
}
- }
}
-/* Search for a library along the given search path.
+/*
+ * Search for a library along the given search path.
*
* The node's 'path' field is set to the found path (including the
* actual file name, not -l...). If the system can handle the -L
@@ -1004,18 +1017,19 @@ Arch_UpdateMemberMTime(GNode *gn)
void
Arch_FindLib(GNode *gn, SearchPath *path)
{
- char *libName = str_concat3("lib", gn->name + 2, ".a");
- gn->path = Dir_FindFile(libName, path);
- free(libName);
+ char *libName = str_concat3("lib", gn->name + 2, ".a");
+ gn->path = Dir_FindFile(libName, path);
+ free(libName);
#ifdef LIBRARIES
- Var_Set(TARGET, gn->name, gn);
+ Var_Set(TARGET, gn->name, gn);
#else
- Var_Set(TARGET, gn->path == NULL ? gn->name : gn->path, gn);
+ Var_Set(TARGET, gn->path == NULL ? gn->name : gn->path, gn);
#endif
}
-/* Decide if a node with the OP_LIB attribute is out-of-date. Called from
+/*
+ * Decide if a node with the OP_LIB attribute is out-of-date. Called from
* GNode_IsOODate to make its life easier.
* The library is cached if it hasn't been already.
*
@@ -1047,50 +1061,53 @@ Arch_FindLib(GNode *gn, SearchPath *path)
Boolean
Arch_LibOODate(GNode *gn)
{
- Boolean oodate;
-
- if (gn->type & OP_PHONY) {
- oodate = TRUE;
- } else if (!GNode_IsTarget(gn) && Lst_IsEmpty(gn->children)) {
- oodate = FALSE;
- } else if ((!Lst_IsEmpty(gn->children) && gn->youngestChild == NULL) ||
- (gn->mtime > now) ||
- (gn->youngestChild != NULL &&
- gn->mtime < gn->youngestChild->mtime)) {
- oodate = TRUE;
- } else {
-#ifdef RANLIBMAG
- struct ar_hdr *arh; /* Header for __.SYMDEF */
- int modTimeTOC; /* The table-of-contents's mod time */
-
- arh = ArchStatMember(gn->path, RANLIBMAG, FALSE);
-
- if (arh != NULL) {
- modTimeTOC = (int)strtol(arh->ar_date, NULL, 10);
-
- if (DEBUG(ARCH) || DEBUG(MAKE))
- debug_printf("%s modified %s...",
- RANLIBMAG, Targ_FmtTime(modTimeTOC));
- oodate = gn->youngestChild == NULL ||
- gn->youngestChild->mtime > modTimeTOC;
+ Boolean oodate;
+
+ if (gn->type & OP_PHONY) {
+ oodate = TRUE;
+ } else if (!GNode_IsTarget(gn) && Lst_IsEmpty(&gn->children)) {
+ oodate = FALSE;
+ } else if ((!Lst_IsEmpty(&gn->children) && gn->youngestChild == NULL) ||
+ (gn->mtime > now) ||
+ (gn->youngestChild != NULL &&
+ gn->mtime < gn->youngestChild->mtime)) {
+ oodate = TRUE;
} else {
- /* A library without a table of contents is out-of-date. */
- if (DEBUG(ARCH) || DEBUG(MAKE))
- debug_printf("no toc...");
- oodate = TRUE;
- }
+#ifdef RANLIBMAG
+ struct ar_hdr *arh; /* Header for __.SYMDEF */
+ int modTimeTOC; /* The table-of-contents' mod time */
+
+ arh = ArchStatMember(gn->path, RANLIBMAG, FALSE);
+
+ if (arh != NULL) {
+ modTimeTOC = (int)strtol(arh->ar_date, NULL, 10);
+
+ if (DEBUG(ARCH) || DEBUG(MAKE))
+ debug_printf("%s modified %s...",
+ RANLIBMAG,
+ Targ_FmtTime(modTimeTOC));
+ oodate = gn->youngestChild == NULL ||
+ gn->youngestChild->mtime > modTimeTOC;
+ } else {
+ /*
+ * A library without a table of contents is out-of-date.
+ */
+ if (DEBUG(ARCH) || DEBUG(MAKE))
+ debug_printf("no toc...");
+ oodate = TRUE;
+ }
#else
- oodate = FALSE;
+ oodate = FALSE;
#endif
- }
- return oodate;
+ }
+ return oodate;
}
/* Initialize the archives module. */
void
Arch_Init(void)
{
- archives = Lst_New();
+ Lst_Init(&archives);
}
/* Clean up the archives module. */
@@ -1098,26 +1115,26 @@ void
Arch_End(void)
{
#ifdef CLEANUP
- Lst_Destroy(archives, ArchFree);
+ Lst_DoneCall(&archives, ArchFree);
#endif
}
Boolean
Arch_IsLib(GNode *gn)
{
- static const char armag[] = "!<arch>\n";
- char buf[sizeof armag - 1];
- int fd;
+ static const char armag[] = "!<arch>\n";
+ char buf[sizeof armag - 1];
+ int fd;
- if ((fd = open(gn->path, O_RDONLY)) == -1)
- return FALSE;
+ if ((fd = open(gn->path, O_RDONLY)) == -1)
+ return FALSE;
- if (read(fd, buf, sizeof buf) != sizeof buf) {
- (void)close(fd);
- return FALSE;
- }
+ if (read(fd, buf, sizeof buf) != sizeof buf) {
+ (void)close(fd);
+ return FALSE;
+ }
- (void)close(fd);
+ (void)close(fd);
- return memcmp(buf, armag, sizeof buf) == 0;
+ return memcmp(buf, armag, sizeof buf) == 0;
}
diff --git a/bmake.1 b/bmake.1
index cbd1ae9f8677..f35c14cc1eee 100644
--- a/bmake.1
+++ b/bmake.1
@@ -1,4 +1,4 @@
-.\" $NetBSD: make.1,v 1.292 2020/11/14 22:19:13 rillig Exp $
+.\" $NetBSD: make.1,v 1.295 2020/12/23 13:49:12 rillig Exp $
.\"
.\" Copyright (c) 1990, 1993
.\" The Regents of the University of California. All rights reserved.
@@ -29,7 +29,7 @@
.\"
.\" from: @(#)make.1 8.4 (Berkeley) 3/19/94
.\"
-.Dd November 14, 2020
+.Dd December 22, 2020
.Dt BMAKE 1
.Os
.Sh NAME
@@ -1019,6 +1019,12 @@ If set to false,
becomes
.Ql $
per normal evaluation rules.
+.It Va .MAKE.UID
+The user-id running
+.Nm .
+.It Va .MAKE.GID
+The group-id running
+.Nm .
.It Va MAKE_PRINT_VAR_ON_ERROR
When
.Nm
@@ -1097,7 +1103,7 @@ to that directory before executing any targets.
.Pp
Except in the case of an explicit
.Ql Ic .OBJDIR
-target,
+target,
.Nm
will check that the specified directory is writable and ignore it if not.
This check can be skipped by setting the environment variable
@@ -1743,9 +1749,9 @@ The same as
except that variables in the value are not expanded.
.It Ic .info Ar message
The message is printed along with the name of the makefile and line number.
-.It Ic .undef Ar variable
-Un-define the specified global variable.
-Only global variables may be un-defined.
+.It Ic .undef Ar variable ...
+Un-define the specified global variables.
+Only global variables can be un-defined.
.It Ic .unexport Ar variable ...
The opposite of
.Ql .export .
diff --git a/bmake.cat1 b/bmake.cat1
index 46e07ba9cc4f..9ed1dcdd9018 100644
--- a/bmake.cat1
+++ b/bmake.cat1
@@ -45,10 +45,10 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
`-' they are added to the MAKEFLAGS environment variable and will
be processed by any child make processes. By default, debugging
information is printed to standard error, but this can be changed
- using the F debugging flag. The debugging output is always
- unbuffered; in addition, if debugging is enabled but debugging
- output is not directed to standard output, then the standard out-
- put is line buffered. Flags is one or more of the following:
+ using the F debugging flag. The debugging output is always un-
+ buffered; in addition, if debugging is enabled but debugging out-
+ put is not directed to standard output, then the standard output
+ is line buffered. Flags is one or more of the following:
A Print all possible debugging information; equivalent to
specifying all of the debugging flags.
@@ -178,8 +178,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
can be used multiple times to form a search path. This path will
override the default system include path: /usr/share/mk. Fur-
thermore the system include path will be appended to the search
- path used for "file"-style include statements (see the -I
- option).
+ path used for "file"-style include statements (see the -I op-
+ tion).
If a file or directory name in the -m argument (or the
MAKESYSPATH environment variable) starts with the string ".../"
@@ -232,9 +232,9 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.MAKE.EXPAND_VARIABLES is set to true and the -dV option has not
been used to override it. Note that loop-local and target-local
variables, as well as values taken temporarily by global vari-
- ables during makefile processing, are not accessible via this
- option. The -dv debug mode can be used to see these at the cost
- of generating substantial extraneous output.
+ ables during makefile processing, are not accessible via this op-
+ tion. The -dv debug mode can be used to see these at the cost of
+ generating substantial extraneous output.
-v variable
Like -V but the variable is always expanded to its complete
@@ -247,8 +247,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
-X Don't export variables passed on the command line to the environ-
ment individually. Variables passed on the command line are
- still exported via the MAKEFLAGS environment variable. This
- option may be useful on systems which have a small limit on the
+ still exported via the MAKEFLAGS environment variable. This op-
+ tion may be useful on systems which have a small limit on the
size of command arguments.
variable=value
@@ -268,9 +268,9 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
FILE DEPENDENCY SPECIFICATIONS
Dependency lines consist of one or more targets, an operator, and zero or
- more sources. This creates a relationship where the targets ``depend''
- on the sources and are customarily created from them. A target is con-
- sidered out-of-date if it does not exist, or if its modification time is
+ more sources. This creates a relationship where the targets "depend" on
+ the sources and are customarily created from them. A target is consid-
+ ered out-of-date if it does not exist, or if its modification time is
less than that of any of its sources. An out-of-date target will be re-
created, but not until all sources have been examined and themselves re-
created as needed. Three operators may be used:
@@ -285,20 +285,20 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
out of date.
:: Any dependency line may have attached shell commands, but each one
- is handled independently: its sources are considered and the
- attached shell commands are run if the target is out of date with
- respect to (only) those sources. Thus, different groups of the
- attached shell commands may be run depending on the circumstances.
+ is handled independently: its sources are considered and the at-
+ tached shell commands are run if the target is out of date with re-
+ spect to (only) those sources. Thus, different groups of the at-
+ tached shell commands may be run depending on the circumstances.
Furthermore, unlike :, for dependency lines with no sources, the
attached shell commands are always run. Also unlike :, the target
will not be removed if bmake is interrupted.
- All dependency lines mentioning a particular target must use the same
- operator.
+ All dependency lines mentioning a particular target must use the same op-
+ erator.
Targets and sources may contain the shell wildcard values `?', `*', `[]',
and `{}'. The values `?', `*', and `[]' may only be used as part of the
- final component of the target or source, and must be used to describe
- existing files. The value `{}' need not necessarily be used to describe
+ final component of the target or source, and must be used to describe ex-
+ isting files. The value `{}' need not necessarily be used to describe
existing files. Expansion is in directory order, not alphabetically as
done in the shell.
@@ -306,8 +306,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
Each target may have associated with it one or more lines of shell com-
mands, normally used to create the target. Each of the lines in this
script must be preceded by a tab. (For historical reasons, spaces are
- not accepted.) While targets can appear in many dependency lines if
- desired, by default only one of these rules may be followed by a creation
+ not accepted.) While targets can appear in many dependency lines if de-
+ sired, by default only one of these rules may be followed by a creation
script. If the `::' operator is used, however, all rules may include
scripts and the scripts are executed in the order found.
@@ -333,10 +333,10 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
failed.
Makefiles should be written so that the mode of bmake operation does not
- change their behavior. For example, any command which needs to use
- ``cd'' or ``chdir'' without potentially changing the directory for subse-
- quent commands should be put in parentheses so it executes in a subshell.
- To force the use of one shell, escape the line breaks so as to make the
+ change their behavior. For example, any command which needs to use "cd"
+ or "chdir" without potentially changing the directory for subsequent com-
+ mands should be put in parentheses so it executes in a subshell. To
+ force the use of one shell, escape the line breaks so as to make the
whole script one command. For example:
avoid-chdir-side-effects:
@@ -373,13 +373,13 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
not expanded. This can cause problems when variable modifiers
are used.
- != Expand the value and pass it to the shell for execution and
- assign the result to the variable. Any newlines in the result
- are replaced with spaces.
+ != Expand the value and pass it to the shell for execution and as-
+ sign the result to the variable. Any newlines in the result are
+ replaced with spaces.
- Any white-space before the assigned value is removed; if the value is
- being appended, a single space is inserted between the previous contents
- of the variable and the appended value.
+ Any white-space before the assigned value is removed; if the value is be-
+ ing appended, a single space is inserted between the previous contents of
+ the variable and the appended value.
Variables are expanded by surrounding the variable name with either curly
braces (`{}') or parentheses (`()') and preceding it with a dollar sign
@@ -403,7 +403,7 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
2. Variables in shell commands are expanded when the shell command is
executed.
- 3. ``.for'' loop index variables are expanded on each loop iteration.
+ 3. ".for" loop index variables are expanded on each loop iteration.
Note that other variables are not expanded inside loops so the fol-
lowing example code:
@@ -423,9 +423,9 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
1 2 3
3 3 3
- Because while ${a} contains ``1 2 3'' after the loop is executed,
- ${b} contains ``${j} ${j} ${j}'' which expands to ``3 3 3'' since
- after the loop completes ${j} contains ``3''.
+ Because while ${a} contains "1 2 3" after the loop is executed, ${b}
+ contains "${j} ${j} ${j}" which expands to "3 3 3" since after the
+ loop completes ${j} contains "3".
Variable classes
The four different classes of variables (in order of increasing prece-
@@ -454,8 +454,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.IMPSRC In suffix-transformation rules, the name/path of the
source from which the target is to be transformed (the
- ``implied'' source); also known as `<'. It is not
- defined in explicit rules.
+ "implied" source); also known as `<'. It is not defined
+ in explicit rules.
.MEMBER The name of the archive member; also known as `%'.
@@ -546,10 +546,10 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.MAKE.LEVEL The recursion depth of bmake. The initial instance of
bmake will be 0, and an incremented value is put into the
- environment to be seen by the next generation. This
- allows tests like: .if ${.MAKE.LEVEL} == 0 to protect
- things which should only be evaluated in the initial
- instance of bmake.
+ environment to be seen by the next generation. This al-
+ lows tests like: .if ${.MAKE.LEVEL} == 0 to protect
+ things which should only be evaluated in the initial in-
+ stance of bmake.
.MAKE.MAKEFILE_PREFERENCE
The ordered list of makefile names (default `makefile',
@@ -647,9 +647,9 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
Building ${.TARGET:H:tA}/${.TARGET:T}
.MAKEOVERRIDES This variable is used to record the names of variables
- assigned to on the command line, so that they may be
- exported as part of `MAKEFLAGS'. This behavior can be
- disabled by assigning an empty value to `.MAKEOVERRIDES'
+ assigned to on the command line, so that they may be ex-
+ ported as part of `MAKEFLAGS'. This behavior can be dis-
+ abled by assigning an empty value to `.MAKEOVERRIDES'
within a makefile. Extra variables can be exported from
a makefile by appending their names to `.MAKEOVERRIDES'.
`MAKEFLAGS' is re-exported whenever `.MAKEOVERRIDES' is
@@ -668,8 +668,12 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
value should be a boolean that controls whether `$$' are
preserved when doing `:=' assignments. The default is
false, for backwards compatibility. Set to true for com-
- patability with other makes. If set to false, `$$'
- becomes `$' per normal evaluation rules.
+ patability with other makes. If set to false, `$$' be-
+ comes `$' per normal evaluation rules.
+
+ .MAKE.UID The user-id running bmake.
+
+ .MAKE.GID The group-id running bmake.
MAKE_PRINT_VAR_ON_ERROR
When bmake stops due to an error, it sets `.ERROR_TARGET'
@@ -733,8 +737,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.PARSEFILE The basename of the current `Makefile' being parsed.
This variable and `.PARSEDIR' are both set only while the
`Makefiles' are being parsed. If you want to retain
- their current values, assign them to a variable using
- assignment with expansion: (`:=').
+ their current values, assign them to a variable using as-
+ signment with expansion: (`:=').
.PATH A variable that represents the list of directories that
bmake will search for files. The search list should be
@@ -756,14 +760,14 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.TARGETS The list of targets explicitly specified on the command
line, if any.
- VPATH Colon-separated (``:'') lists of directories that bmake
+ VPATH Colon-separated (":") lists of directories that bmake
will search for files. The variable is supported for
compatibility with old make programs only, use `.PATH'
instead.
Variable modifiers
Variable expansion may be modified to select or modify each word of the
- variable (where a ``word'' is white-space delimited sequence of charac-
+ variable (where a "word" is white-space delimited sequence of charac-
ters). The general format of a variable expansion is as follows:
${variable[:modifier[:...]]}
@@ -831,8 +835,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
passed safely to the shell.
:q Quotes every shell meta-character in the variable, and also doubles
- `$' characters so that it can be passed safely through recursive
- invocations of bmake. This is equivalent to: `:S/\$/&&/g:Q'.
+ `$' characters so that it can be passed safely through recursive in-
+ vocations of bmake. This is equivalent to: `:S/\$/&&/g:Q'.
:R Replaces each word in the variable with everything but its suffix.
@@ -872,11 +876,11 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
:S/old_string/new_string/[1gW]
Modifies the first occurrence of old_string in each word of the
- variable's value, replacing it with new_string. If a `g' is
- appended to the last delimiter of the pattern, all occurrences in
- each word are replaced. If a `1' is appended to the last delimiter
- of the pattern, only the first occurrence is affected. If a `W' is
- appended to the last delimiter of the pattern, then the value is
+ variable's value, replacing it with new_string. If a `g' is ap-
+ pended to the last delimiter of the pattern, all occurrences in each
+ word are replaced. If a `1' is appended to the last delimiter of
+ the pattern, only the first occurrence is affected. If a `W' is ap-
+ pended to the last delimiter of the pattern, then the value is
treated as a single word (possibly containing embedded white space).
If old_string begins with a caret (`^'), old_string is anchored at
the beginning of each word. If old_string ends with a dollar sign
@@ -927,8 +931,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
This is the AT&T System V UNIX style variable substitution. It must
be the last modifier specified. If old_string or new_string do not
contain the pattern matching character % then it is assumed that
- they are anchored at the end of each word, so only suffixes or
- entire words may be replaced. Otherwise % is the substring of
+ they are anchored at the end of each word, so only suffixes or en-
+ tire words may be replaced. Otherwise % is the substring of
old_string to be replaced in new_string. If only old_string con-
tains the pattern matching character %, and old_string matches, then
the result is the new_string. If only the new_string contains the
@@ -971,8 +975,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
:Unewval
If the variable is undefined, newval is the value. If the variable
is defined, the existing value is returned. This is another ODE
- make feature. It is handy for setting per-target CFLAGS for
- instance:
+ make feature. It is handy for setting per-target CFLAGS for in-
+ stance:
${_${.TARGET:T}_CFLAGS:U${DEF_CFLAGS}}
If a value is only required if the variable is undefined, use:
${VAR:D:Unewval}
@@ -1027,8 +1031,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
gers (where index 1 represents the first word), and backwards using
negative integers (where index -1 represents the last word).
- The range is subjected to variable expansion, and the expanded
- result is then interpreted as follows:
+ The range is subjected to variable expansion, and the expanded re-
+ sult is then interpreted as follows:
index Selects a single word from the value.
@@ -1037,8 +1041,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
`:[2..-1]' selects all words from the second word to the last
word. If start is greater than end, then the words are out-
put in reverse order. For example, `:[-1..1]' selects all
- the words from last to first. If the list is already
- ordered, then this effectively reverses the list, but it is
+ the words from last to first. If the list is already or-
+ dered, then this effectively reverses the list, but it is
more efficient to use `:Or' instead of `:O:[-1..1]'.
* Causes subsequent modifiers to treat the value as a single
@@ -1059,18 +1063,18 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
are identified by a line beginning with a single dot (`.') character.
Files are included with either .include <file> or .include "file". Vari-
ables between the angle brackets or double quotes are expanded to form
- the file name. If angle brackets are used, the included makefile is
- expected to be in the system makefile directory. If double quotes are
+ the file name. If angle brackets are used, the included makefile is ex-
+ pected to be in the system makefile directory. If double quotes are
used, the including makefile's directory and any directories specified
using the -I option are searched before the system makefile directory.
For compatibility with other versions of bmake `include file ...' is also
accepted.
- If the include statement is written as .-include or as .sinclude then
- errors locating and/or opening include files are ignored.
+ If the include statement is written as .-include or as .sinclude then er-
+ rors locating and/or opening include files are ignored.
- If the include statement is written as .dinclude not only are errors
- locating and/or opening include files ignored, but stale dependencies
+ If the include statement is written as .dinclude not only are errors lo-
+ cating and/or opening include files ignored, but stale dependencies
within the included file will be ignored just like .MAKE.DEPENDFILE.
Conditional expressions are also preceded by a single dot as the first
@@ -1087,8 +1091,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
flag, so should be used with caution. For compatibility with
other bmake programs `export variable=value' is also accepted.
- Appending a variable name to .MAKE.EXPORTED is equivalent to
- exporting a variable.
+ Appending a variable name to .MAKE.EXPORTED is equivalent to ex-
+ porting a variable.
.export-env variable ...
The same as `.export', except that the variable is not appended
@@ -1103,9 +1107,9 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
The message is printed along with the name of the makefile and
line number.
- .undef variable
- Un-define the specified global variable. Only global variables
- may be un-defined.
+ .undef variable ...
+ Un-define the specified global variables. Only global variables
+ can be un-defined.
.unexport variable ...
The opposite of `.export'. The specified global variable will be
@@ -1172,7 +1176,7 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
|| Logical OR.
- && Logical AND; of higher precedence than ``||''.
+ && Logical AND; of higher precedence than "||".
As in C, bmake will only evaluate a conditional as far as is necessary to
determine its value. Parentheses may be used to change the order of
@@ -1185,9 +1189,9 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
the variable has been defined.
make Takes a target name as an argument and evaluates to true if the
- target was specified as part of bmake's command line or was
- declared the default target (either implicitly or explicitly,
- see .MAIN) before the line containing the conditional.
+ target was specified as part of bmake's command line or was de-
+ clared the default target (either implicitly or explicitly, see
+ .MAIN) before the line containing the conditional.
empty Takes a variable, with possible modifiers, and evaluates to true
if the expansion of the variable would result in an empty
@@ -1204,10 +1208,10 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
Takes a target name as an argument and evaluates to true if the
target has been defined and has commands associated with it.
- Expression may also be an arithmetic or string comparison. Variable
- expansion is performed on both sides of the comparison, after which the
- numerical values are compared. A value is interpreted as hexadecimal if
- it is preceded by 0x, otherwise it is decimal; octal numbers are not sup-
+ Expression may also be an arithmetic or string comparison. Variable ex-
+ pansion is performed on both sides of the comparison, after which the nu-
+ merical values are compared. A value is interpreted as hexadecimal if it
+ is preceded by 0x, otherwise it is decimal; octal numbers are not sup-
ported. The standard C relational operators are all supported. If after
variable expansion, either the left or right hand side of a `==' or `!='
operator is not a numerical value, then string comparison is performed
@@ -1215,12 +1219,12 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
is assumed that the expanded variable is being compared against 0, or an
empty string in the case of a string comparison.
- When bmake is evaluating one of these conditional expressions, and it
- encounters a (white-space separated) word it doesn't recognize, either
- the ``make'' or ``defined'' expression is applied to it, depending on the
- form of the conditional. If the form is `.ifdef', `.ifndef', or `.if'
- the ``defined'' expression is applied. Similarly, if the form is
- `.ifmake' or `.ifnmake', the ``make'' expression is applied.
+ When bmake is evaluating one of these conditional expressions, and it en-
+ counters a (white-space separated) word it doesn't recognize, either the
+ "make" or "defined" expression is applied to it, depending on the form of
+ the conditional. If the form is `.ifdef', `.ifndef', or `.if' the
+ "defined" expression is applied. Similarly, if the form is `.ifmake' or
+ `.ifnmake', the "make" expression is applied.
If the conditional evaluates to true the parsing of the makefile contin-
ues as before. If it evaluates to false, the following lines are
@@ -1272,8 +1276,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
always changes. If the number of commands change, though, the
target will still be out of date. The same effect applies to
any command line that uses the variable .OODATE, which can be
- used for that purpose even when not otherwise needed or
- desired:
+ used for that purpose even when not otherwise needed or de-
+ sired:
skip-compare-for-some:
@@ -1303,8 +1307,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.PRECIOUS
When bmake is interrupted, it normally removes any partially
- made targets. This source prevents the target from being
- removed.
+ made targets. This source prevents the target from being re-
+ moved.
.RECURSIVE
Synonym for .MAKE.
@@ -1324,10 +1328,10 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.WAIT If .WAIT appears in a dependency line, the sources that precede
it are made before the sources that succeed it in the line.
- Since the dependents of files are not made until the file
- itself could be made, this also stops the dependents being
- built unless they are needed for another branch of the depen-
- dency tree. So given:
+ Since the dependents of files are not made until the file it-
+ self could be made, this also stops the dependents being built
+ unless they are needed for another branch of the dependency
+ tree. So given:
x: a .WAIT b
echo x
@@ -1361,14 +1365,14 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
make to delete targets whose commands fail. (By default, only
targets whose commands are interrupted during execution are
deleted. This is the historical behavior.) This setting can be
- used to help prevent half-finished or malformed targets from
- being left around and corrupting future rebuilds.
+ used to help prevent half-finished or malformed targets from be-
+ ing left around and corrupting future rebuilds.
- .END Any command lines attached to this target are executed after
- everything else is done.
+ .END Any command lines attached to this target are executed after ev-
+ erything else is done.
- .ERROR Any command lines attached to this target are executed when
- another target fails. The .ERROR_TARGET variable is set to the
+ .ERROR Any command lines attached to this target are executed when an-
+ other target fails. The .ERROR_TARGET variable is set to the
target that failed. See also MAKE_PRINT_VAR_ON_ERROR.
.IGNORE Mark each of the sources with the .IGNORE attribute. If no
@@ -1425,8 +1429,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
.PRECIOUS
Apply the .PRECIOUS attribute to any specified sources. If no
- sources are specified, the .PRECIOUS attribute is applied to
- every target in the file.
+ sources are specified, the .PRECIOUS attribute is applied to ev-
+ ery target in the file.
.SHELL Sets the shell that bmake will use to execute commands. The
sources are a set of field=value pairs.
@@ -1469,8 +1473,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
sources are specified, the .SILENT attribute is applied to every
command in the file.
- .STALE This target gets run when a dependency file contains stale
- entries, having .ALLSRC set to the name of that dependency file.
+ .STALE This target gets run when a dependency file contains stale en-
+ tries, having .ALLSRC set to the name of that dependency file.
.SUFFIXES
Each source specifies a suffix to bmake. If no sources are
@@ -1509,8 +1513,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
The way that .for loop variables are substituted changed after NetBSD 5.0
so that they still appear to be variable expansions. In particular this
- stops them being treated as syntax, and removes some obscure problems
- using them in .if statements.
+ stops them being treated as syntax, and removes some obscure problems us-
+ ing them in .if statements.
The way that parallel makes are scheduled changed in NetBSD 4.0 so that
.ORDER and .WAIT apply recursively to the dependent nodes. The algo-
@@ -1518,8 +1522,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
Other make dialects
Other make dialects (GNU make, SVR4 make, POSIX make, etc.) do not sup-
- port most of the features of bmake as described in this manual. Most
- notably:
+ port most of the features of bmake as described in this manual. Most no-
+ tably:
+o The .WAIT and .ORDER declarations and most functionality per-
taining to parallelization. (GNU make supports parallelization
@@ -1544,8 +1548,8 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
Some features are somewhat more portable, such as assignment with +=, ?=,
and !=. The .PATH functionality is based on an older feature VPATH found
- in GNU make and many versions of SVR4 make; however, historically its
- behavior is too ill-defined (and too buggy) to rely upon.
+ in GNU make and many versions of SVR4 make; however, historically its be-
+ havior is too ill-defined (and too buggy) to rely upon.
The $@ and $< variables are more or less universally portable, as is the
$(MAKE) variable. Basic use of suffix rules (for files only in the cur-
@@ -1562,11 +1566,11 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
A make command appeared in Version 7 AT&T UNIX. This make implementation
is based on Adam De Boor's pmake program which was written for Sprite at
Berkeley. It was designed to be a parallel distributed make running jobs
- on different machines using a daemon called ``customs''.
+ on different machines using a daemon called "customs".
- Historically the target/dependency ``FRC'' has been used to FoRCe
- rebuilding (since the target/dependency does not exist... unless someone
- creates an ``FRC'' file).
+ Historically the target/dependency "FRC" has been used to FoRCe rebuild-
+ ing (since the target/dependency does not exist... unless someone creates
+ an "FRC" file).
BUGS
The make syntax is difficult to parse without actually acting on the
@@ -1577,4 +1581,4 @@ BMAKE(1) FreeBSD General Commands Manual BMAKE(1)
There is no way of escaping a space character in a filename.
-FreeBSD 11.3 November 14, 2020 FreeBSD 11.3
+FreeBSD 13.0 December 22, 2020 FreeBSD 13.0
diff --git a/buf.c b/buf.c
index 6cbf31a2bd60..b6a2e9192b60 100644
--- a/buf.c
+++ b/buf.c
@@ -1,4 +1,4 @@
-/* $NetBSD: buf.c,v 1.44 2020/11/07 14:11:58 rillig Exp $ */
+/* $NetBSD: buf.c,v 1.47 2020/12/30 10:03:16 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -69,146 +69,153 @@
* SUCH DAMAGE.
*/
-/* Automatically-expanding null-terminated buffers. */
+/* Automatically-expanding null-terminated character buffers. */
#include <limits.h>
#include "make.h"
/* "@(#)buf.c 8.1 (Berkeley) 6/6/93" */
-MAKE_RCSID("$NetBSD: buf.c,v 1.44 2020/11/07 14:11:58 rillig Exp $");
+MAKE_RCSID("$NetBSD: buf.c,v 1.47 2020/12/30 10:03:16 rillig Exp $");
-/* Make space in the buffer for adding a single byte. */
+/* Make space in the buffer for adding at least 16 more bytes. */
void
-Buf_Expand_1(Buffer *buf)
+Buf_Expand(Buffer *buf)
{
- buf->cap += buf->cap > 16 ? buf->cap : 16;
- buf->data = bmake_realloc(buf->data, buf->cap);
+ buf->cap += buf->cap > 16 ? buf->cap : 16;
+ buf->data = bmake_realloc(buf->data, buf->cap);
}
/* Add the bytes to the buffer. */
void
Buf_AddBytes(Buffer *buf, const char *bytes, size_t bytes_len)
{
- size_t old_len = buf->len;
- char *end;
-
- if (__predict_false(old_len + bytes_len >= buf->cap)) {
- buf->cap += buf->cap > bytes_len + 16 ? buf->cap : bytes_len + 16;
- buf->data = bmake_realloc(buf->data, buf->cap);
- }
-
- end = buf->data + old_len;
- buf->len = old_len + bytes_len;
- memcpy(end, bytes, bytes_len);
- end[bytes_len] = '\0';
+ size_t old_len = buf->len;
+ char *end;
+
+ if (__predict_false(old_len + bytes_len >= buf->cap)) {
+ size_t minIncr = bytes_len + 16;
+ buf->cap += buf->cap > minIncr ? buf->cap : minIncr;
+ buf->data = bmake_realloc(buf->data, buf->cap);
+ }
+
+ end = buf->data + old_len;
+ buf->len = old_len + bytes_len;
+ memcpy(end, bytes, bytes_len);
+ end[bytes_len] = '\0';
}
/* Add the bytes between start and end to the buffer. */
void
Buf_AddBytesBetween(Buffer *buf, const char *start, const char *end)
{
- Buf_AddBytes(buf, start, (size_t)(end - start));
+ Buf_AddBytes(buf, start, (size_t)(end - start));
}
/* Add the string to the buffer. */
void
Buf_AddStr(Buffer *buf, const char *str)
{
- Buf_AddBytes(buf, str, strlen(str));
+ Buf_AddBytes(buf, str, strlen(str));
}
/* Add the number to the buffer. */
void
Buf_AddInt(Buffer *buf, int n)
{
- enum {
- bits = sizeof(int) * CHAR_BIT,
- max_octal_digits = (bits + 2) / 3,
- max_decimal_digits = /* at most */ max_octal_digits,
- max_sign_chars = 1,
- str_size = max_sign_chars + max_decimal_digits + 1
- };
- char str[str_size];
-
- size_t len = (size_t)snprintf(str, sizeof str, "%d", n);
- Buf_AddBytes(buf, str, len);
+ enum {
+ bits = sizeof(int) * CHAR_BIT,
+ max_octal_digits = (bits + 2) / 3,
+ max_decimal_digits = /* at most */ max_octal_digits,
+ max_sign_chars = 1,
+ str_size = max_sign_chars + max_decimal_digits + 1
+ };
+ char str[str_size];
+
+ size_t len = (size_t)snprintf(str, sizeof str, "%d", n);
+ Buf_AddBytes(buf, str, len);
}
-/* Get the data (usually a string) from the buffer.
+/*
+ * Get the data (usually a string) from the buffer.
* The returned data is valid until the next modifying operation
* on the buffer.
*
- * Returns the data and optionally the length of the data. */
+ * Returns the data and optionally the length of the data.
+ */
char *
Buf_GetAll(Buffer *buf, size_t *out_len)
{
- if (out_len != NULL)
- *out_len = buf->len;
- return buf->data;
+ if (out_len != NULL)
+ *out_len = buf->len;
+ return buf->data;
}
/* Mark the buffer as empty, so it can be filled with data again. */
void
Buf_Empty(Buffer *buf)
{
- buf->len = 0;
- buf->data[0] = '\0';
+ buf->len = 0;
+ buf->data[0] = '\0';
}
/* Initialize a buffer. */
void
Buf_InitSize(Buffer *buf, size_t cap)
{
- buf->cap = cap;
- buf->len = 0;
- buf->data = bmake_malloc(cap);
- buf->data[0] = '\0';
+ buf->cap = cap;
+ buf->len = 0;
+ buf->data = bmake_malloc(cap);
+ buf->data[0] = '\0';
}
void
Buf_Init(Buffer *buf)
{
- Buf_InitSize(buf, 256);
+ Buf_InitSize(buf, 256);
}
-/* Reset the buffer.
+/*
+ * Reset the buffer.
* If freeData is TRUE, the data from the buffer is freed as well.
- * Otherwise it is kept and returned. */
+ * Otherwise it is kept and returned.
+ */
char *
Buf_Destroy(Buffer *buf, Boolean freeData)
{
- char *data = buf->data;
- if (freeData) {
- free(data);
- data = NULL;
- }
+ char *data = buf->data;
+ if (freeData) {
+ free(data);
+ data = NULL;
+ }
- buf->cap = 0;
- buf->len = 0;
- buf->data = NULL;
+ buf->cap = 0;
+ buf->len = 0;
+ buf->data = NULL;
- return data;
+ return data;
}
#ifndef BUF_COMPACT_LIMIT
-# define BUF_COMPACT_LIMIT 128 /* worthwhile saving */
+# define BUF_COMPACT_LIMIT 128 /* worthwhile saving */
#endif
-/* Reset the buffer and return its data.
+/*
+ * Reset the buffer and return its data.
*
* If the buffer size is much greater than its content,
- * a new buffer will be allocated and the old one freed. */
+ * a new buffer will be allocated and the old one freed.
+ */
char *
Buf_DestroyCompact(Buffer *buf)
{
#if BUF_COMPACT_LIMIT > 0
- if (buf->cap - buf->len >= BUF_COMPACT_LIMIT) {
- /* We trust realloc to be smart */
- char *data = bmake_realloc(buf->data, buf->len + 1);
- data[buf->len] = '\0'; /* XXX: unnecessary */
- Buf_Destroy(buf, FALSE);
- return data;
- }
+ if (buf->cap - buf->len >= BUF_COMPACT_LIMIT) {
+ /* We trust realloc to be smart */
+ char *data = bmake_realloc(buf->data, buf->len + 1);
+ data[buf->len] = '\0'; /* XXX: unnecessary */
+ Buf_Destroy(buf, FALSE);
+ return data;
+ }
#endif
- return Buf_Destroy(buf, FALSE);
+ return Buf_Destroy(buf, FALSE);
}
diff --git a/buf.h b/buf.h
index 6ab3d3288a43..942b115c76e6 100644
--- a/buf.h
+++ b/buf.h
@@ -1,4 +1,4 @@
-/* $NetBSD: buf.h,v 1.36 2020/11/10 00:32:12 rillig Exp $ */
+/* $NetBSD: buf.h,v 1.38 2020/12/28 15:42:53 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -81,9 +81,9 @@
/* An automatically growing null-terminated buffer of characters. */
typedef struct Buffer {
- size_t cap; /* Allocated size of the buffer, including the null */
- size_t len; /* Number of bytes in buffer, excluding the null */
- char *data; /* The buffer itself (always null-terminated) */
+ size_t cap; /* Allocated size of the buffer, including the null */
+ size_t len; /* Number of bytes in buffer, excluding the null */
+ char *data; /* The buffer itself (always null-terminated) */
} Buffer;
/* If we aren't on NetBSD, __predict_false() might not be defined. */
@@ -91,31 +91,31 @@ typedef struct Buffer {
#define __predict_false(x) (x)
#endif
-void Buf_Expand_1(Buffer *);
+void Buf_Expand(Buffer *);
/* Buf_AddByte adds a single byte to a buffer. */
MAKE_INLINE void
Buf_AddByte(Buffer *buf, char byte)
{
- size_t old_len = buf->len++;
- char *end;
- if (__predict_false(old_len + 1 >= buf->cap))
- Buf_Expand_1(buf);
- end = buf->data + old_len;
- end[0] = byte;
- end[1] = '\0';
+ size_t old_len = buf->len++;
+ char *end;
+ if (__predict_false(old_len + 1 >= buf->cap))
+ Buf_Expand(buf);
+ end = buf->data + old_len;
+ end[0] = byte;
+ end[1] = '\0';
}
MAKE_INLINE size_t
Buf_Len(const Buffer *buf)
{
- return buf->len;
+ return buf->len;
}
MAKE_INLINE Boolean
Buf_EndsWith(const Buffer *buf, char ch)
{
- return buf->len > 0 && buf->data[buf->len - 1] == ch;
+ return buf->len > 0 && buf->data[buf->len - 1] == ch;
}
void Buf_AddBytes(Buffer *, const char *, size_t);
diff --git a/compat.c b/compat.c
index 2307e9f2d935..6c7238318959 100644
--- a/compat.c
+++ b/compat.c
@@ -1,4 +1,4 @@
-/* $NetBSD: compat.c,v 1.183 2020/11/15 22:31:03 rillig Exp $ */
+/* $NetBSD: compat.c,v 1.219 2021/01/10 21:20:46 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -99,7 +99,7 @@
#include "pathnames.h"
/* "@(#)compat.c 8.2 (Berkeley) 3/19/94" */
-MAKE_RCSID("$NetBSD: compat.c,v 1.183 2020/11/15 22:31:03 rillig Exp $");
+MAKE_RCSID("$NetBSD: compat.c,v 1.219 2021/01/10 21:20:46 rillig Exp $");
static GNode *curTarg = NULL;
static pid_t compatChild;
@@ -112,16 +112,17 @@ static int compatSigno;
static void
CompatDeleteTarget(GNode *gn)
{
- if (gn != NULL && !Targ_Precious(gn)) {
- const char *file = GNode_VarTarget(gn);
+ if (gn != NULL && !Targ_Precious(gn)) {
+ const char *file = GNode_VarTarget(gn);
- if (!opts.noExecute && eunlink(file) != -1) {
- Error("*** %s removed", file);
+ if (!opts.noExecute && eunlink(file) != -1) {
+ Error("*** %s removed", file);
+ }
}
- }
}
-/* Interrupt the creation of the current target and remove it if it ain't
+/*
+ * Interrupt the creation of the current target and remove it if it ain't
* precious. Then exit.
*
* If .INTERRUPT exists, its commands are run first WITH INTERRUPTS IGNORED.
@@ -132,348 +133,362 @@ CompatDeleteTarget(GNode *gn)
static void
CompatInterrupt(int signo)
{
- CompatDeleteTarget(curTarg);
+ CompatDeleteTarget(curTarg);
+
+ if (curTarg != NULL && !Targ_Precious(curTarg)) {
+ /*
+ * Run .INTERRUPT only if hit with interrupt signal
+ */
+ if (signo == SIGINT) {
+ GNode *gn = Targ_FindNode(".INTERRUPT");
+ if (gn != NULL) {
+ Compat_Make(gn, gn);
+ }
+ }
+ }
+
+ if (signo == SIGQUIT)
+ _exit(signo);
- if (curTarg != NULL && !Targ_Precious(curTarg)) {
/*
- * Run .INTERRUPT only if hit with interrupt signal
+ * If there is a child running, pass the signal on.
+ * We will exist after it has exited.
*/
- if (signo == SIGINT) {
- GNode *gn = Targ_FindNode(".INTERRUPT");
- if (gn != NULL) {
- Compat_Make(gn, gn);
- }
- }
- }
-
- if (signo == SIGQUIT)
- _exit(signo);
-
- /*
- * If there is a child running, pass the signal on.
- * We will exist after it has exited.
- */
- compatSigno = signo;
- if (compatChild > 0) {
- KILLPG(compatChild, signo);
- } else {
- bmake_signal(signo, SIG_DFL);
- kill(myPid, signo);
- }
+ compatSigno = signo;
+ if (compatChild > 0) {
+ KILLPG(compatChild, signo);
+ } else {
+ bmake_signal(signo, SIG_DFL);
+ kill(myPid, signo);
+ }
+}
+
+static void
+DebugFailedTarget(const char *cmd, GNode *gn)
+{
+ const char *p = cmd;
+ debug_printf("\n*** Failed target: %s\n*** Failed command: ",
+ gn->name);
+
+ /* Replace runs of whitespace with a single space, to reduce
+ * the amount of whitespace for multi-line command lines. */
+ while (*p != '\0') {
+ if (ch_isspace(*p)) {
+ debug_printf(" ");
+ cpp_skip_whitespace(&p);
+ } else {
+ debug_printf("%c", *p);
+ p++;
+ }
+ }
+ debug_printf("\n");
}
-/* Execute the next command for a target. If the command returns an error,
+static Boolean
+UseShell(const char *cmd MAKE_ATTR_UNUSED)
+{
+#if !defined(MAKE_NATIVE)
+ /*
+ * In a non-native build, the host environment might be weird enough
+ * that it's necessary to go through a shell to get the correct
+ * behaviour. Or perhaps the shell has been replaced with something
+ * that does extra logging, and that should not be bypassed.
+ */
+ return TRUE;
+#else
+ /*
+ * Search for meta characters in the command. If there are no meta
+ * characters, there's no need to execute a shell to execute the
+ * command.
+ *
+ * Additionally variable assignments and empty commands
+ * go to the shell. Therefore treat '=' and ':' like shell
+ * meta characters as documented in make(1).
+ */
+
+ return needshell(cmd);
+#endif
+}
+
+/*
+ * Execute the next command for a target. If the command returns an error,
* the node's made field is set to ERROR and creation stops.
*
* Input:
* cmdp Command to execute
- * gnp Node from which the command came
+ * gn Node from which the command came
+ * ln List node that contains the command
*
* Results:
* 0 if the command succeeded, 1 if an error occurred.
*/
int
-Compat_RunCommand(const char *cmdp, GNode *gn)
+Compat_RunCommand(const char *cmdp, GNode *gn, StringListNode *ln)
{
- char *cmdStart; /* Start of expanded command */
- char *bp;
- Boolean silent; /* Don't print command */
- Boolean doIt; /* Execute even if -n */
- volatile Boolean errCheck; /* Check errors */
- WAIT_T reason; /* Reason for child's death */
- int status; /* Description of child's death */
- pid_t cpid; /* Child actually found */
- pid_t retstat; /* Result of wait */
- StringListNode *cmdNode; /* Node where current command is located */
- const char **volatile av; /* Argument vector for thing to exec */
- char **volatile mav; /* Copy of the argument vector for freeing */
- Boolean useShell; /* TRUE if command should be executed
+ char *cmdStart; /* Start of expanded command */
+ char *bp;
+ Boolean silent; /* Don't print command */
+ Boolean doIt; /* Execute even if -n */
+ volatile Boolean errCheck; /* Check errors */
+ WAIT_T reason; /* Reason for child's death */
+ WAIT_T status; /* Description of child's death */
+ pid_t cpid; /* Child actually found */
+ pid_t retstat; /* Result of wait */
+ const char **volatile av; /* Argument vector for thing to exec */
+ char **volatile mav; /* Copy of the argument vector for freeing */
+ Boolean useShell; /* TRUE if command should be executed
* using a shell */
- const char *volatile cmd = cmdp;
-
- silent = (gn->type & OP_SILENT) != 0;
- errCheck = !(gn->type & OP_IGNORE);
- doIt = FALSE;
-
- /* Luckily the commands don't end up in a string pool, otherwise
- * this comparison could match too early, in a dependency using "..."
- * for delayed commands, run in parallel mode, using the same shell
- * command line more than once; see JobPrintCommand.
- * TODO: write a unit-test to protect against this potential bug. */
- cmdNode = Lst_FindDatum(gn->commands, cmd);
- (void)Var_Subst(cmd, gn, VARE_WANTRES, &cmdStart);
- /* TODO: handle errors */
-
- if (cmdStart[0] == '\0') {
- free(cmdStart);
- return 0;
- }
- cmd = cmdStart;
- LstNode_Set(cmdNode, cmdStart);
-
- if (gn->type & OP_SAVE_CMDS) {
- GNode *endNode = Targ_GetEndNode();
- if (gn != endNode) {
- Lst_Append(endNode->commands, cmdStart);
- return 0;
- }
- }
- if (strcmp(cmdStart, "...") == 0) {
- gn->type |= OP_SAVE_CMDS;
- return 0;
- }
-
- for (;;) {
- if (*cmd == '@')
- silent = !DEBUG(LOUD);
- else if (*cmd == '-')
- errCheck = FALSE;
- else if (*cmd == '+') {
- doIt = TRUE;
- if (!shellName) /* we came here from jobs */
- Shell_Init();
- } else
- break;
- cmd++;
- }
+ const char *volatile cmd = cmdp;
- while (ch_isspace(*cmd))
- cmd++;
+ silent = (gn->type & OP_SILENT) != 0;
+ errCheck = !(gn->type & OP_IGNORE);
+ doIt = FALSE;
- /*
- * If we did not end up with a command, just skip it.
- */
- if (cmd[0] == '\0')
- return 0;
+ (void)Var_Subst(cmd, gn, VARE_WANTRES, &cmdStart);
+ /* TODO: handle errors */
-#if !defined(MAKE_NATIVE)
- /*
- * In a non-native build, the host environment might be weird enough
- * that it's necessary to go through a shell to get the correct
- * behaviour. Or perhaps the shell has been replaced with something
- * that does extra logging, and that should not be bypassed.
- */
- useShell = TRUE;
-#else
- /*
- * Search for meta characters in the command. If there are no meta
- * characters, there's no need to execute a shell to execute the
- * command.
- *
- * Additionally variable assignments and empty commands
- * go to the shell. Therefore treat '=' and ':' like shell
- * meta characters as documented in make(1).
- */
-
- useShell = needshell(cmd);
-#endif
+ if (cmdStart[0] == '\0') {
+ free(cmdStart);
+ return 0;
+ }
+ cmd = cmdStart;
+ LstNode_Set(ln, cmdStart);
+
+ if (gn->type & OP_SAVE_CMDS) {
+ GNode *endNode = Targ_GetEndNode();
+ if (gn != endNode) {
+ /*
+ * Append the expanded command, to prevent the
+ * local variables from being interpreted in the
+ * context of the .END node.
+ *
+ * A probably unintended side effect of this is that
+ * the expanded command will be expanded again in the
+ * .END node. Therefore, a literal '$' in these
+ * commands must be written as '$$$$' instead of the
+ * usual '$$'.
+ */
+ Lst_Append(&endNode->commands, cmdStart);
+ return 0;
+ }
+ }
+ if (strcmp(cmdStart, "...") == 0) {
+ gn->type |= OP_SAVE_CMDS;
+ return 0;
+ }
+
+ for (;;) {
+ if (*cmd == '@')
+ silent = !DEBUG(LOUD);
+ else if (*cmd == '-')
+ errCheck = FALSE;
+ else if (*cmd == '+') {
+ doIt = TRUE;
+ if (shellName == NULL) /* we came here from jobs */
+ Shell_Init();
+ } else
+ break;
+ cmd++;
+ }
+
+ while (ch_isspace(*cmd))
+ cmd++;
- /*
- * Print the command before echoing if we're not supposed to be quiet for
- * this one. We also print the command if -n given.
- */
- if (!silent || !GNode_ShouldExecute(gn)) {
- printf("%s\n", cmd);
- fflush(stdout);
- }
-
- /*
- * If we're not supposed to execute any commands, this is as far as
- * we go...
- */
- if (!doIt && !GNode_ShouldExecute(gn))
- return 0;
-
- DEBUG1(JOB, "Execute: '%s'\n", cmd);
-
- if (useShell) {
/*
- * We need to pass the command off to the shell, typically
- * because the command contains a "meta" character.
+ * If we did not end up with a command, just skip it.
*/
- static const char *shargv[5];
-
- /* The following work for any of the builtin shell specs. */
- int shargc = 0;
- shargv[shargc++] = shellPath;
- if (errCheck && shellErrFlag)
- shargv[shargc++] = shellErrFlag;
- shargv[shargc++] = DEBUG(SHELL) ? "-xc" : "-c";
- shargv[shargc++] = cmd;
- shargv[shargc] = NULL;
- av = shargv;
- bp = NULL;
- mav = NULL;
- } else {
+ if (cmd[0] == '\0')
+ return 0;
+
+ useShell = UseShell(cmd);
/*
- * No meta-characters, so no need to exec a shell. Break the command
- * into words to form an argument vector we can execute.
+ * Print the command before echoing if we're not supposed to be quiet
+ * for this one. We also print the command if -n given.
*/
- Words words = Str_Words(cmd, FALSE);
- mav = words.words;
- bp = words.freeIt;
- av = (void *)mav;
- }
+ if (!silent || !GNode_ShouldExecute(gn)) {
+ printf("%s\n", cmd);
+ fflush(stdout);
+ }
-#ifdef USE_META
- if (useMeta) {
- meta_compat_start();
- }
-#endif
+ /*
+ * If we're not supposed to execute any commands, this is as far as
+ * we go...
+ */
+ if (!doIt && !GNode_ShouldExecute(gn))
+ return 0;
+
+ DEBUG1(JOB, "Execute: '%s'\n", cmd);
+
+ if (useShell) {
+ /*
+ * We need to pass the command off to the shell, typically
+ * because the command contains a "meta" character.
+ */
+ static const char *shargv[5];
+
+ /* The following work for any of the builtin shell specs. */
+ int shargc = 0;
+ shargv[shargc++] = shellPath;
+ if (errCheck && shellErrFlag != NULL)
+ shargv[shargc++] = shellErrFlag;
+ shargv[shargc++] = DEBUG(SHELL) ? "-xc" : "-c";
+ shargv[shargc++] = cmd;
+ shargv[shargc] = NULL;
+ av = shargv;
+ bp = NULL;
+ mav = NULL;
+ } else {
+ /*
+ * No meta-characters, so no need to exec a shell. Break the
+ * command into words to form an argument vector we can
+ * execute.
+ */
+ Words words = Str_Words(cmd, FALSE);
+ mav = words.words;
+ bp = words.freeIt;
+ av = (void *)mav;
+ }
- /*
- * Fork and execute the single command. If the fork fails, we abort.
- */
- compatChild = cpid = vFork();
- if (cpid < 0) {
- Fatal("Could not fork");
- }
- if (cpid == 0) {
- Var_ExportVars();
#ifdef USE_META
if (useMeta) {
- meta_compat_child();
+ meta_compat_start();
}
#endif
- (void)execvp(av[0], (char *const *)UNCONST(av));
- execDie("exec", av[0]);
- }
- free(mav);
- free(bp);
+ Var_ReexportVars();
- /* XXX: Memory management looks suspicious here. */
- /* XXX: Setting a list item to NULL is unexpected. */
- LstNode_SetNull(cmdNode);
+ /*
+ * Fork and execute the single command. If the fork fails, we abort.
+ */
+ compatChild = cpid = vFork();
+ if (cpid < 0) {
+ Fatal("Could not fork");
+ }
+ if (cpid == 0) {
+#ifdef USE_META
+ if (useMeta) {
+ meta_compat_child();
+ }
+#endif
+ (void)execvp(av[0], (char *const *)UNCONST(av));
+ execDie("exec", av[0]);
+ }
+
+ free(mav);
+ free(bp);
+
+ /* XXX: Memory management looks suspicious here. */
+ /* XXX: Setting a list item to NULL is unexpected. */
+ LstNode_SetNull(ln);
#ifdef USE_META
- if (useMeta) {
- meta_compat_parent(cpid);
- }
+ if (useMeta) {
+ meta_compat_parent(cpid);
+ }
#endif
- /*
- * The child is off and running. Now all we can do is wait...
- */
- while ((retstat = wait(&reason)) != cpid) {
- if (retstat > 0)
- JobReapChild(retstat, reason, FALSE); /* not ours? */
- if (retstat == -1 && errno != EINTR) {
- break;
+ /*
+ * The child is off and running. Now all we can do is wait...
+ */
+ while ((retstat = wait(&reason)) != cpid) {
+ if (retstat > 0)
+ JobReapChild(retstat, reason, FALSE); /* not ours? */
+ if (retstat == -1 && errno != EINTR) {
+ break;
+ }
}
- }
- if (retstat < 0)
- Fatal("error in wait: %d: %s", retstat, strerror(errno));
+ if (retstat < 0)
+ Fatal("error in wait: %d: %s", retstat, strerror(errno));
- if (WIFSTOPPED(reason)) {
- status = WSTOPSIG(reason); /* stopped */
- } else if (WIFEXITED(reason)) {
- status = WEXITSTATUS(reason); /* exited */
+ if (WIFSTOPPED(reason)) {
+ status = WSTOPSIG(reason); /* stopped */
+ } else if (WIFEXITED(reason)) {
+ status = WEXITSTATUS(reason); /* exited */
#if defined(USE_META) && defined(USE_FILEMON_ONCE)
- if (useMeta) {
- meta_cmd_finish(NULL);
- }
+ if (useMeta) {
+ meta_cmd_finish(NULL);
+ }
#endif
- if (status != 0) {
- if (DEBUG(ERROR)) {
- const char *p = cmd;
- debug_printf("\n*** Failed target: %s\n*** Failed command: ",
- gn->name);
-
- /* Replace runs of whitespace with a single space, to reduce
- * the amount of whitespace for multi-line command lines. */
- while (*p != '\0') {
- if (ch_isspace(*p)) {
- debug_printf(" ");
- cpp_skip_whitespace(&p);
- } else {
- debug_printf("%c", *p);
- p++;
- }
+ if (status != 0) {
+ if (DEBUG(ERROR))
+ DebugFailedTarget(cmd, gn);
+ printf("*** Error code %d", status);
}
- debug_printf("\n");
- }
- printf("*** Error code %d", status);
+ } else {
+ status = WTERMSIG(reason); /* signaled */
+ printf("*** Signal %d", status);
}
- } else {
- status = WTERMSIG(reason); /* signaled */
- printf("*** Signal %d", status);
- }
- if (!WIFEXITED(reason) || status != 0) {
- if (errCheck) {
+ if (!WIFEXITED(reason) || status != 0) {
+ if (errCheck) {
#ifdef USE_META
- if (useMeta) {
- meta_job_error(NULL, gn, 0, status);
- }
+ if (useMeta) {
+ meta_job_error(NULL, gn, FALSE, status);
+ }
#endif
- gn->made = ERROR;
- if (opts.keepgoing) {
- /* Abort the current target, but let others continue. */
- printf(" (continuing)\n");
- } else {
- printf("\n");
- }
- if (deleteOnError)
- CompatDeleteTarget(gn);
- } else {
- /*
- * Continue executing commands for this target.
- * If we return 0, this will happen...
- */
- printf(" (ignored)\n");
- status = 0;
- }
- }
-
- free(cmdStart);
- compatChild = 0;
- if (compatSigno) {
- bmake_signal(compatSigno, SIG_DFL);
- kill(myPid, compatSigno);
- }
-
- return status;
+ gn->made = ERROR;
+ if (opts.keepgoing) {
+ /*
+ * Abort the current target,
+ * but let others continue.
+ */
+ printf(" (continuing)\n");
+ } else {
+ printf("\n");
+ }
+ if (deleteOnError)
+ CompatDeleteTarget(gn);
+ } else {
+ /*
+ * Continue executing commands for this target.
+ * If we return 0, this will happen...
+ */
+ printf(" (ignored)\n");
+ status = 0;
+ }
+ }
+
+ free(cmdStart);
+ compatChild = 0;
+ if (compatSigno != 0) {
+ bmake_signal(compatSigno, SIG_DFL);
+ kill(myPid, compatSigno);
+ }
+
+ return status;
}
static void
RunCommands(GNode *gn)
{
- StringListNode *ln;
- for (ln = gn->commands->first; ln != NULL; ln = ln->next) {
- const char *cmd = ln->datum;
- if (Compat_RunCommand(cmd, gn) != 0)
- break;
- }
+ StringListNode *ln;
+
+ for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
+ const char *cmd = ln->datum;
+ if (Compat_RunCommand(cmd, gn, ln) != 0)
+ break;
+ }
}
static void
MakeNodes(GNodeList *gnodes, GNode *pgn)
{
- GNodeListNode *ln;
- for (ln = gnodes->first; ln != NULL; ln = ln->next) {
- GNode *cohort = ln->datum;
- Compat_Make(cohort, pgn);
- }
+ GNodeListNode *ln;
+
+ for (ln = gnodes->first; ln != NULL; ln = ln->next) {
+ GNode *cohort = ln->datum;
+ Compat_Make(cohort, pgn);
+ }
}
-/* Make a target.
- *
- * If an error is detected and not being ignored, the process exits.
- *
- * Input:
- * gn The node to make
- * pgn Parent to abort if necessary
- */
-void
-Compat_Make(GNode *gn, GNode *pgn)
+static Boolean
+MakeUnmade(GNode *gn, GNode *pgn)
{
- if (shellName == NULL) /* we came here from jobs */
- Shell_Init();
- if (gn->made == UNMADE && (gn == pgn || !(pgn->type & OP_MADE))) {
+ assert(gn->made == UNMADE);
+
/*
* First mark ourselves to be made, then apply whatever transformations
* the suffix module thinks are necessary. Once that's done, we can
@@ -484,17 +499,20 @@ Compat_Make(GNode *gn, GNode *pgn)
*/
gn->flags |= REMAKE;
gn->made = BEINGMADE;
+
if (!(gn->type & OP_MADE))
- Suff_FindDeps(gn);
- MakeNodes(gn->children, gn);
+ Suff_FindDeps(gn);
+
+ MakeNodes(&gn->children, gn);
+
if (!(gn->flags & REMAKE)) {
- gn->made = ABORTED;
- pgn->flags &= ~(unsigned)REMAKE;
- goto cohorts;
+ gn->made = ABORTED;
+ pgn->flags &= ~(unsigned)REMAKE;
+ return FALSE;
}
- if (Lst_FindDatum(gn->implicitParents, pgn) != NULL)
- Var_Set(IMPSRC, GNode_VarTarget(gn), pgn);
+ if (Lst_FindDatum(&gn->implicitParents, pgn) != NULL)
+ Var_Set(IMPSRC, GNode_VarTarget(gn), pgn);
/*
* All the children were made ok. Now youngestChild->mtime contains the
@@ -504,115 +522,185 @@ Compat_Make(GNode *gn, GNode *pgn)
*/
DEBUG1(MAKE, "Examining %s...", gn->name);
if (!GNode_IsOODate(gn)) {
- gn->made = UPTODATE;
- DEBUG0(MAKE, "up-to-date.\n");
- goto cohorts;
- } else
- DEBUG0(MAKE, "out-of-date.\n");
+ gn->made = UPTODATE;
+ DEBUG0(MAKE, "up-to-date.\n");
+ return FALSE;
+ }
/*
* If the user is just seeing if something is out-of-date, exit now
* to tell him/her "yes".
*/
+ DEBUG0(MAKE, "out-of-date.\n");
if (opts.queryFlag)
- exit(1);
+ exit(1);
/*
- * We need to be re-made. We also have to make sure we've got a $?
- * variable. To be nice, we also define the $> variable using
- * Make_DoAllVar().
+ * We need to be re-made.
+ * Ensure that $? (.OODATE) and $> (.ALLSRC) are both set.
*/
Make_DoAllVar(gn);
/*
* Alter our type to tell if errors should be ignored or things
- * should not be printed so CompatRunCommand knows what to do.
+ * should not be printed so Compat_RunCommand knows what to do.
*/
- if (Targ_Ignore(gn))
- gn->type |= OP_IGNORE;
- if (Targ_Silent(gn))
- gn->type |= OP_SILENT;
+ if (opts.ignoreErrors)
+ gn->type |= OP_IGNORE;
+ if (opts.beSilent)
+ gn->type |= OP_SILENT;
if (Job_CheckCommands(gn, Fatal)) {
- /*
- * Our commands are ok, but we still have to worry about the -t
- * flag...
- */
- if (!opts.touchFlag || (gn->type & OP_MAKE)) {
- curTarg = gn;
+ /*
+ * Our commands are ok, but we still have to worry about
+ * the -t flag.
+ */
+ if (!opts.touchFlag || (gn->type & OP_MAKE)) {
+ curTarg = gn;
#ifdef USE_META
- if (useMeta && GNode_ShouldExecute(gn)) {
- meta_job_start(NULL, gn);
- }
+ if (useMeta && GNode_ShouldExecute(gn)) {
+ meta_job_start(NULL, gn);
+ }
#endif
- RunCommands(gn);
- curTarg = NULL;
- } else {
- Job_Touch(gn, (gn->type & OP_SILENT) != 0);
- }
+ RunCommands(gn);
+ curTarg = NULL;
+ } else {
+ Job_Touch(gn, (gn->type & OP_SILENT) != 0);
+ }
} else {
- gn->made = ERROR;
+ gn->made = ERROR;
}
#ifdef USE_META
if (useMeta && GNode_ShouldExecute(gn)) {
- if (meta_job_finish(NULL) != 0)
- gn->made = ERROR;
+ if (meta_job_finish(NULL) != 0)
+ gn->made = ERROR;
}
#endif
if (gn->made != ERROR) {
- /*
- * If the node was made successfully, mark it so, update
- * its modification time and timestamp all its parents.
- * This is to keep its state from affecting that of its parent.
- */
- gn->made = MADE;
- if (Make_Recheck(gn) == 0)
- pgn->flags |= FORCE;
- if (!(gn->type & OP_EXEC)) {
- pgn->flags |= CHILDMADE;
- GNode_UpdateYoungestChild(pgn, gn);
- }
+ /*
+ * If the node was made successfully, mark it so, update
+ * its modification time and timestamp all its parents.
+ * This is to keep its state from affecting that of its parent.
+ */
+ gn->made = MADE;
+ if (Make_Recheck(gn) == 0)
+ pgn->flags |= FORCE;
+ if (!(gn->type & OP_EXEC)) {
+ pgn->flags |= CHILDMADE;
+ GNode_UpdateYoungestChild(pgn, gn);
+ }
} else if (opts.keepgoing) {
- pgn->flags &= ~(unsigned)REMAKE;
+ pgn->flags &= ~(unsigned)REMAKE;
} else {
- PrintOnError(gn, "\nStop.");
- exit(1);
- }
- } else if (gn->made == ERROR) {
- /* Already had an error when making this. Tell the parent to abort. */
- pgn->flags &= ~(unsigned)REMAKE;
- } else {
- if (Lst_FindDatum(gn->implicitParents, pgn) != NULL) {
- const char *target = GNode_VarTarget(gn);
- Var_Set(IMPSRC, target != NULL ? target : "", pgn);
- }
- switch(gn->made) {
- case BEINGMADE:
+ PrintOnError(gn, "\nStop.");
+ exit(1);
+ }
+ return TRUE;
+}
+
+static void
+MakeOther(GNode *gn, GNode *pgn)
+{
+
+ if (Lst_FindDatum(&gn->implicitParents, pgn) != NULL) {
+ const char *target = GNode_VarTarget(gn);
+ Var_Set(IMPSRC, target != NULL ? target : "", pgn);
+ }
+
+ switch (gn->made) {
+ case BEINGMADE:
Error("Graph cycles through %s", gn->name);
gn->made = ERROR;
pgn->flags &= ~(unsigned)REMAKE;
break;
- case MADE:
+ case MADE:
if (!(gn->type & OP_EXEC)) {
- pgn->flags |= CHILDMADE;
- GNode_UpdateYoungestChild(pgn, gn);
+ pgn->flags |= CHILDMADE;
+ GNode_UpdateYoungestChild(pgn, gn);
}
break;
- case UPTODATE:
+ case UPTODATE:
if (!(gn->type & OP_EXEC))
- GNode_UpdateYoungestChild(pgn, gn);
+ GNode_UpdateYoungestChild(pgn, gn);
break;
- default:
+ default:
break;
}
- }
+}
+
+/*
+ * Make a target.
+ *
+ * If an error is detected and not being ignored, the process exits.
+ *
+ * Input:
+ * gn The node to make
+ * pgn Parent to abort if necessary
+ *
+ * Output:
+ * gn->made
+ * UPTODATE gn was already up-to-date.
+ * MADE gn was recreated successfully.
+ * ERROR An error occurred while gn was being created,
+ * either due to missing commands or in -k mode.
+ * ABORTED gn was not remade because one of its
+ * dependencies could not be made due to errors.
+ */
+void
+Compat_Make(GNode *gn, GNode *pgn)
+{
+ if (shellName == NULL) /* we came here from jobs */
+ Shell_Init();
+
+ if (gn->made == UNMADE && (gn == pgn || !(pgn->type & OP_MADE))) {
+ if (!MakeUnmade(gn, pgn))
+ goto cohorts;
+
+ /* XXX: Replace with GNode_IsError(gn) */
+ } else if (gn->made == ERROR) {
+ /*
+ * Already had an error when making this.
+ * Tell the parent to abort.
+ */
+ pgn->flags &= ~(unsigned)REMAKE;
+ } else {
+ MakeOther(gn, pgn);
+ }
cohorts:
- MakeNodes(gn->cohorts, pgn);
+ MakeNodes(&gn->cohorts, pgn);
+}
+
+static void
+MakeBeginNode(void)
+{
+ GNode *gn = Targ_FindNode(".BEGIN");
+ if (gn == NULL)
+ return;
+
+ Compat_Make(gn, gn);
+ if (GNode_IsError(gn)) {
+ PrintOnError(gn, "\nStop.");
+ exit(1);
+ }
+}
+
+static void
+InitSignals(void)
+{
+ if (bmake_signal(SIGINT, SIG_IGN) != SIG_IGN)
+ bmake_signal(SIGINT, CompatInterrupt);
+ if (bmake_signal(SIGTERM, SIG_IGN) != SIG_IGN)
+ bmake_signal(SIGTERM, CompatInterrupt);
+ if (bmake_signal(SIGHUP, SIG_IGN) != SIG_IGN)
+ bmake_signal(SIGHUP, CompatInterrupt);
+ if (bmake_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
+ bmake_signal(SIGQUIT, CompatInterrupt);
}
-/* Initialize this module and start making.
+/*
+ * Initialize this module and start making.
*
* Input:
* targs The target nodes to re-create
@@ -620,79 +708,51 @@ cohorts:
void
Compat_Run(GNodeList *targs)
{
- GNode *gn = NULL; /* Current root target */
- int errors; /* Number of targets not remade due to errors */
-
- if (!shellName)
- Shell_Init();
-
- if (bmake_signal(SIGINT, SIG_IGN) != SIG_IGN)
- bmake_signal(SIGINT, CompatInterrupt);
- if (bmake_signal(SIGTERM, SIG_IGN) != SIG_IGN)
- bmake_signal(SIGTERM, CompatInterrupt);
- if (bmake_signal(SIGHUP, SIG_IGN) != SIG_IGN)
- bmake_signal(SIGHUP, CompatInterrupt);
- if (bmake_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
- bmake_signal(SIGQUIT, CompatInterrupt);
-
- /* Create the .END node now, to keep the (debug) output of the
- * counter.mk test the same as before 2020-09-23. This implementation
- * detail probably doesn't matter though. */
- (void)Targ_GetEndNode();
- /*
- * If the user has defined a .BEGIN target, execute the commands attached
- * to it.
- */
- if (!opts.queryFlag) {
- gn = Targ_FindNode(".BEGIN");
- if (gn != NULL) {
- Compat_Make(gn, gn);
- if (gn->made == ERROR) {
- PrintOnError(gn, "\nStop.");
- exit(1);
- }
- }
- }
-
- /*
- * Expand .USE nodes right now, because they can modify the structure
- * of the tree.
- */
- Make_ExpandUse(targs);
-
- /*
- * For each entry in the list of targets to create, call Compat_Make on
- * it to create the thing. Compat_Make will leave the 'made' field of gn
- * in one of several states:
- * UPTODATE gn was already up-to-date
- * MADE gn was recreated successfully
- * ERROR An error occurred while gn was being created
- * ABORTED gn was not remade because one of its inferiors
- * could not be made due to errors.
- */
- errors = 0;
- while (!Lst_IsEmpty(targs)) {
- gn = Lst_Dequeue(targs);
- Compat_Make(gn, gn);
+ GNode *errorNode = NULL;
+
+ if (shellName == NULL)
+ Shell_Init();
- if (gn->made == UPTODATE) {
- printf("`%s' is up to date.\n", gn->name);
- } else if (gn->made == ABORTED) {
- printf("`%s' not remade because of errors.\n", gn->name);
- errors++;
- }
- }
-
- /*
- * If the user has defined a .END target, run its commands.
- */
- if (errors == 0) {
- GNode *endNode = Targ_GetEndNode();
- Compat_Make(endNode, endNode);
- /* XXX: Did you mean endNode->made instead of gn->made? */
- if (gn->made == ERROR) {
- PrintOnError(gn, "\nStop.");
- exit(1);
- }
- }
+ InitSignals();
+
+ /* Create the .END node now, to keep the (debug) output of the
+ * counter.mk test the same as before 2020-09-23. This implementation
+ * detail probably doesn't matter though. */
+ (void)Targ_GetEndNode();
+
+ if (!opts.queryFlag)
+ MakeBeginNode();
+
+ /*
+ * Expand .USE nodes right now, because they can modify the structure
+ * of the tree.
+ */
+ Make_ExpandUse(targs);
+
+ while (!Lst_IsEmpty(targs)) {
+ GNode *gn = Lst_Dequeue(targs);
+ Compat_Make(gn, gn);
+
+ if (gn->made == UPTODATE) {
+ printf("`%s' is up to date.\n", gn->name);
+ } else if (gn->made == ABORTED) {
+ printf("`%s' not remade because of errors.\n",
+ gn->name);
+ }
+ if (GNode_IsError(gn) && errorNode == NULL)
+ errorNode = gn;
+ }
+
+ /* If the user has defined a .END target, run its commands. */
+ if (errorNode == NULL) {
+ GNode *endNode = Targ_GetEndNode();
+ Compat_Make(endNode, endNode);
+ if (GNode_IsError(endNode))
+ errorNode = endNode;
+ }
+
+ if (errorNode != NULL) {
+ PrintOnError(errorNode, "\nStop.");
+ exit(1);
+ }
}
diff --git a/cond.c b/cond.c
index a1b0d75dcb09..1a8aba637fe9 100644
--- a/cond.c
+++ b/cond.c
@@ -1,4 +1,4 @@
-/* $NetBSD: cond.c,v 1.214 2020/11/13 09:01:59 rillig Exp $ */
+/* $NetBSD: cond.c,v 1.235 2021/01/10 21:20:46 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -69,7 +69,8 @@
* SUCH DAMAGE.
*/
-/* Handling of conditionals in a makefile.
+/*
+ * Handling of conditionals in a makefile.
*
* Interface:
* Cond_EvalLine Evaluate the conditional directive, such as
@@ -94,7 +95,7 @@
#include "dir.h"
/* "@(#)cond.c 8.2 (Berkeley) 1/2/94" */
-MAKE_RCSID("$NetBSD: cond.c,v 1.214 2020/11/13 09:01:59 rillig Exp $");
+MAKE_RCSID("$NetBSD: cond.c,v 1.235 2021/01/10 21:20:46 rillig Exp $");
/*
* The parsing of conditional expressions is based on this grammar:
@@ -135,20 +136,22 @@ MAKE_RCSID("$NetBSD: cond.c,v 1.214 2020/11/13 09:01:59 rillig Exp $");
* CondParser_Term) return either TOK_FALSE, TOK_TRUE, or TOK_ERROR on error.
*/
typedef enum Token {
- TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
- TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
+ TOK_FALSE = 0, TOK_TRUE = 1, TOK_AND, TOK_OR, TOK_NOT,
+ TOK_LPAREN, TOK_RPAREN, TOK_EOF, TOK_NONE, TOK_ERROR
} Token;
typedef struct CondParser {
- const struct If *if_info; /* Info for current statement */
- const char *p; /* The remaining condition to parse */
- Token curr; /* Single push-back token used in parsing */
-
- /* Whether an error message has already been printed for this condition.
- * The first available error message is usually the most specific one,
- * therefore it makes sense to suppress the standard "Malformed
- * conditional" message. */
- Boolean printedError;
+ const struct If *if_info; /* Info for current statement */
+ const char *p; /* The remaining condition to parse */
+ Token curr; /* Single push-back token used in parsing */
+
+ /*
+ * Whether an error message has already been printed for this
+ * condition. The first available error message is usually the most
+ * specific one, therefore it makes sense to suppress the standard
+ * "Malformed conditional" message.
+ */
+ Boolean printedError;
} CondParser;
static Token CondParser_Expr(CondParser *par, Boolean);
@@ -168,35 +171,36 @@ static unsigned int cond_min_depth = 0; /* depth at makefile open */
*/
static Boolean lhsStrict;
-static int
+static Boolean
is_token(const char *str, const char *tok, size_t len)
{
- return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
+ return strncmp(str, tok, len) == 0 && !ch_isalpha(str[len]);
}
static Token
ToToken(Boolean cond)
{
- return cond ? TOK_TRUE : TOK_FALSE;
+ return cond ? TOK_TRUE : TOK_FALSE;
}
/* Push back the most recent token read. We only need one level of this. */
static void
CondParser_PushBack(CondParser *par, Token t)
{
- assert(par->curr == TOK_NONE);
- assert(t != TOK_NONE);
+ assert(par->curr == TOK_NONE);
+ assert(t != TOK_NONE);
- par->curr = t;
+ par->curr = t;
}
static void
CondParser_SkipWhitespace(CondParser *par)
{
- cpp_skip_whitespace(&par->p);
+ cpp_skip_whitespace(&par->p);
}
-/* Parse the argument of a built-in function.
+/*
+ * Parse the argument of a built-in function.
*
* Arguments:
* *pp initially points at the '(',
@@ -207,128 +211,139 @@ CondParser_SkipWhitespace(CondParser *par)
* func says whether the argument belongs to an actual function, or
* whether the parsed argument is passed to the default function.
*
- * Return the length of the argument, or 0 on error. */
+ * Return the length of the argument, or 0 on error.
+ */
static size_t
ParseFuncArg(const char **pp, Boolean doEval, const char *func,
- char **out_arg) {
- const char *p = *pp;
- Buffer argBuf;
- int paren_depth;
- size_t argLen;
-
- if (func != NULL)
- p++; /* Skip opening '(' - verified by caller */
-
- if (*p == '\0') {
- *out_arg = NULL; /* Missing closing parenthesis: */
- return 0; /* .if defined( */
- }
-
- cpp_skip_hspace(&p);
-
- Buf_InitSize(&argBuf, 16);
-
- paren_depth = 0;
- for (;;) {
- char ch = *p;
- if (ch == '\0' || ch == ' ' || ch == '\t')
- break;
- if ((ch == '&' || ch == '|') && paren_depth == 0)
- break;
- if (*p == '$') {
- /*
- * Parse the variable spec and install it as part of the argument
- * if it's valid. We tell Var_Parse to complain on an undefined
- * variable, so we don't need to do it. Nor do we return an error,
- * though perhaps we should...
- */
- void *nestedVal_freeIt;
- VarEvalFlags eflags = doEval ? VARE_WANTRES | VARE_UNDEFERR
- : VARE_NONE;
- const char *nestedVal;
- (void)Var_Parse(&p, VAR_CMDLINE, eflags, &nestedVal,
- &nestedVal_freeIt);
- /* TODO: handle errors */
- Buf_AddStr(&argBuf, nestedVal);
- free(nestedVal_freeIt);
- continue;
+ char **out_arg)
+{
+ const char *p = *pp;
+ Buffer argBuf;
+ int paren_depth;
+ size_t argLen;
+
+ if (func != NULL)
+ p++; /* Skip opening '(' - verified by caller */
+
+ if (*p == '\0') {
+ *out_arg = NULL; /* Missing closing parenthesis: */
+ return 0; /* .if defined( */
}
- if (ch == '(')
- paren_depth++;
- else if (ch == ')' && --paren_depth < 0)
- break;
- Buf_AddByte(&argBuf, *p);
- p++;
- }
-
- *out_arg = Buf_GetAll(&argBuf, &argLen);
- Buf_Destroy(&argBuf, FALSE);
-
- cpp_skip_hspace(&p);
-
- if (func != NULL && *p++ != ')') {
- Parse_Error(PARSE_WARNING, "Missing closing parenthesis for %s()",
- func);
- /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
- return 0;
- }
-
- *pp = p;
- return argLen;
+
+ cpp_skip_hspace(&p);
+
+ Buf_InitSize(&argBuf, 16);
+
+ paren_depth = 0;
+ for (;;) {
+ char ch = *p;
+ if (ch == '\0' || ch == ' ' || ch == '\t')
+ break;
+ if ((ch == '&' || ch == '|') && paren_depth == 0)
+ break;
+ if (*p == '$') {
+ /*
+ * Parse the variable expression and install it as
+ * part of the argument if it's valid. We tell
+ * Var_Parse to complain on an undefined variable,
+ * (XXX: but Var_Parse ignores that request)
+ * so we don't need to do it. Nor do we return an
+ * error, though perhaps we should.
+ */
+ VarEvalFlags eflags = doEval
+ ? VARE_WANTRES | VARE_UNDEFERR
+ : VARE_NONE;
+ FStr nestedVal;
+ (void)Var_Parse(&p, VAR_CMDLINE, eflags, &nestedVal);
+ /* TODO: handle errors */
+ Buf_AddStr(&argBuf, nestedVal.str);
+ FStr_Done(&nestedVal);
+ continue;
+ }
+ if (ch == '(')
+ paren_depth++;
+ else if (ch == ')' && --paren_depth < 0)
+ break;
+ Buf_AddByte(&argBuf, *p);
+ p++;
+ }
+
+ *out_arg = Buf_GetAll(&argBuf, &argLen);
+ Buf_Destroy(&argBuf, FALSE);
+
+ cpp_skip_hspace(&p);
+
+ if (func != NULL && *p++ != ')') {
+ Parse_Error(PARSE_WARNING,
+ "Missing closing parenthesis for %s()",
+ func);
+ /* The PARSE_FATAL follows in CondEvalExpression. */
+ return 0;
+ }
+
+ *pp = p;
+ return argLen;
}
/* Test whether the given variable is defined. */
+/*ARGSUSED*/
static Boolean
FuncDefined(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
{
- void *freeIt;
- Boolean result = Var_Value(arg, VAR_CMDLINE, &freeIt) != NULL;
- bmake_free(freeIt);
- return result;
+ FStr value = Var_Value(arg, VAR_CMDLINE);
+ Boolean result = value.str != NULL;
+ FStr_Done(&value);
+ return result;
}
/* See if the given target is being made. */
+/*ARGSUSED*/
static Boolean
FuncMake(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
{
- StringListNode *ln;
+ StringListNode *ln;
- for (ln = opts.create->first; ln != NULL; ln = ln->next)
- if (Str_Match(ln->datum, arg))
- return TRUE;
- return FALSE;
+ for (ln = opts.create.first; ln != NULL; ln = ln->next)
+ if (Str_Match(ln->datum, arg))
+ return TRUE;
+ return FALSE;
}
/* See if the given file exists. */
+/*ARGSUSED*/
static Boolean
FuncExists(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
{
- Boolean result;
- char *path;
-
- path = Dir_FindFile(arg, dirSearchPath);
- DEBUG2(COND, "exists(%s) result is \"%s\"\n",
- arg, path != NULL ? path : "");
- result = path != NULL;
- free(path);
- return result;
+ Boolean result;
+ char *path;
+
+ path = Dir_FindFile(arg, &dirSearchPath);
+ DEBUG2(COND, "exists(%s) result is \"%s\"\n",
+ arg, path != NULL ? path : "");
+ result = path != NULL;
+ free(path);
+ return result;
}
/* See if the given node exists and is an actual target. */
+/*ARGSUSED*/
static Boolean
FuncTarget(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
{
- GNode *gn = Targ_FindNode(arg);
- return gn != NULL && GNode_IsTarget(gn);
+ GNode *gn = Targ_FindNode(arg);
+ return gn != NULL && GNode_IsTarget(gn);
}
-/* See if the given node exists and is an actual target with commands
- * associated with it. */
+/*
+ * See if the given node exists and is an actual target with commands
+ * associated with it.
+ */
+/*ARGSUSED*/
static Boolean
FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
{
- GNode *gn = Targ_FindNode(arg);
- return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(gn->commands);
+ GNode *gn = Targ_FindNode(arg);
+ return gn != NULL && GNode_IsTarget(gn) && !Lst_IsEmpty(&gn->commands);
}
/*
@@ -343,36 +358,36 @@ FuncCommands(size_t argLen MAKE_ATTR_UNUSED, const char *arg)
static Boolean
TryParseNumber(const char *str, double *out_value)
{
- char *end;
- unsigned long ul_val;
- double dbl_val;
-
- errno = 0;
- if (str[0] == '\0') { /* XXX: why is an empty string a number? */
- *out_value = 0.0;
- return TRUE;
- }
+ char *end;
+ unsigned long ul_val;
+ double dbl_val;
+
+ errno = 0;
+ if (str[0] == '\0') { /* XXX: why is an empty string a number? */
+ *out_value = 0.0;
+ return TRUE;
+ }
- ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
- if (*end == '\0' && errno != ERANGE) {
- *out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
- return TRUE;
- }
+ ul_val = strtoul(str, &end, str[1] == 'x' ? 16 : 10);
+ if (*end == '\0' && errno != ERANGE) {
+ *out_value = str[0] == '-' ? -(double)-ul_val : (double)ul_val;
+ return TRUE;
+ }
- if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
- return FALSE; /* skip the expensive strtod call */
- dbl_val = strtod(str, &end);
- if (*end != '\0')
- return FALSE;
+ if (*end != '\0' && *end != '.' && *end != 'e' && *end != 'E')
+ return FALSE; /* skip the expensive strtod call */
+ dbl_val = strtod(str, &end);
+ if (*end != '\0')
+ return FALSE;
- *out_value = dbl_val;
- return TRUE;
+ *out_value = dbl_val;
+ return TRUE;
}
static Boolean
is_separator(char ch)
{
- return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
+ return ch == '\0' || ch_isspace(ch) || strchr("!=><)", ch) != NULL;
}
/*-
@@ -385,124 +400,126 @@ is_separator(char ch)
* Sets out_freeIt.
*/
/* coverity:[+alloc : arg-*4] */
-static const char *
+static void
CondParser_String(CondParser *par, Boolean doEval, Boolean strictLHS,
- Boolean *out_quoted, void **out_freeIt)
+ FStr *out_str, Boolean *out_quoted)
{
- Buffer buf;
- const char *str;
- Boolean atStart;
- const char *nested_p;
- Boolean quoted;
- const char *start;
- VarEvalFlags eflags;
- VarParseResult parseResult;
-
- Buf_Init(&buf);
- str = NULL;
- *out_freeIt = NULL;
- *out_quoted = quoted = par->p[0] == '"';
- start = par->p;
- if (quoted)
- par->p++;
- while (par->p[0] != '\0' && str == NULL) {
- switch (par->p[0]) {
- case '\\':
- par->p++;
- if (par->p[0] != '\0') {
- Buf_AddByte(&buf, par->p[0]);
+ Buffer buf;
+ FStr str;
+ Boolean atStart;
+ const char *nested_p;
+ Boolean quoted;
+ const char *start;
+ VarEvalFlags eflags;
+ VarParseResult parseResult;
+
+ Buf_Init(&buf);
+ str = FStr_InitRefer(NULL);
+ *out_quoted = quoted = par->p[0] == '"';
+ start = par->p;
+ if (quoted)
par->p++;
- }
- continue;
- case '"':
- if (quoted) {
- par->p++; /* skip the closing quote */
- goto got_str;
- }
- Buf_AddByte(&buf, par->p[0]); /* likely? */
- par->p++;
- continue;
- case ')': /* see is_separator */
- case '!':
- case '=':
- case '>':
- case '<':
- case ' ':
- case '\t':
- if (!quoted)
- goto got_str;
- Buf_AddByte(&buf, par->p[0]);
- par->p++;
- continue;
- case '$':
- /* if we are in quotes, an undefined variable is ok */
- eflags = doEval && !quoted ? VARE_WANTRES | VARE_UNDEFERR :
- doEval ? VARE_WANTRES :
- VARE_NONE;
-
- nested_p = par->p;
- atStart = nested_p == start;
- parseResult = Var_Parse(&nested_p, VAR_CMDLINE, eflags, &str,
- out_freeIt);
- /* TODO: handle errors */
- if (str == var_Error) {
- if (parseResult & VPR_ANY_MSG)
- par->printedError = TRUE;
- if (*out_freeIt != NULL) {
- /* XXX: Can there be any situation in which a returned
- * var_Error requires freeIt? */
- free(*out_freeIt);
- *out_freeIt = NULL;
+
+ while (par->p[0] != '\0' && str.str == NULL) {
+ switch (par->p[0]) {
+ case '\\':
+ par->p++;
+ if (par->p[0] != '\0') {
+ Buf_AddByte(&buf, par->p[0]);
+ par->p++;
+ }
+ continue;
+ case '"':
+ if (quoted) {
+ par->p++; /* skip the closing quote */
+ goto got_str;
+ }
+ Buf_AddByte(&buf, par->p[0]); /* likely? */
+ par->p++;
+ continue;
+ case ')': /* see is_separator */
+ case '!':
+ case '=':
+ case '>':
+ case '<':
+ case ' ':
+ case '\t':
+ if (!quoted)
+ goto got_str;
+ Buf_AddByte(&buf, par->p[0]);
+ par->p++;
+ continue;
+ case '$':
+ /* if we are in quotes, an undefined variable is ok */
+ eflags =
+ doEval && !quoted ? VARE_WANTRES | VARE_UNDEFERR :
+ doEval ? VARE_WANTRES :
+ VARE_NONE;
+
+ nested_p = par->p;
+ atStart = nested_p == start;
+ parseResult = Var_Parse(&nested_p, VAR_CMDLINE, eflags,
+ &str);
+ /* TODO: handle errors */
+ if (str.str == var_Error) {
+ if (parseResult == VPR_ERR)
+ par->printedError = TRUE;
+ /*
+ * XXX: Can there be any situation in which
+ * a returned var_Error requires freeIt?
+ */
+ FStr_Done(&str);
+ /*
+ * Even if !doEval, we still report syntax
+ * errors, which is what getting var_Error
+ * back with !doEval means.
+ */
+ str = FStr_InitRefer(NULL);
+ goto cleanup;
+ }
+ par->p = nested_p;
+
+ /*
+ * If the '$' started the string literal (which means
+ * no quotes), and the variable expression is followed
+ * by a space, looks like a comparison operator or is
+ * the end of the expression, we are done.
+ */
+ if (atStart && is_separator(par->p[0]))
+ goto cleanup;
+
+ Buf_AddStr(&buf, str.str);
+ FStr_Done(&str);
+ str = FStr_InitRefer(NULL); /* not finished yet */
+ continue;
+ default:
+ if (strictLHS && !quoted && *start != '$' &&
+ !ch_isdigit(*start)) {
+ /*
+ * The left-hand side must be quoted,
+ * a variable reference or a number.
+ */
+ str = FStr_InitRefer(NULL);
+ goto cleanup;
+ }
+ Buf_AddByte(&buf, par->p[0]);
+ par->p++;
+ continue;
}
- /*
- * Even if !doEval, we still report syntax errors, which
- * is what getting var_Error back with !doEval means.
- */
- str = NULL;
- goto cleanup;
- }
- par->p = nested_p;
-
- /*
- * If the '$' started the string literal (which means no quotes),
- * and the variable expression is followed by a space, looks like
- * a comparison operator or is the end of the expression, we are
- * done.
- */
- if (atStart && is_separator(par->p[0]))
- goto cleanup;
-
- Buf_AddStr(&buf, str);
- if (*out_freeIt) {
- free(*out_freeIt);
- *out_freeIt = NULL;
- }
- str = NULL; /* not finished yet */
- continue;
- default:
- if (strictLHS && !quoted && *start != '$' && !ch_isdigit(*start)) {
- /* lhs must be quoted, a variable reference or number */
- str = NULL;
- goto cleanup;
- }
- Buf_AddByte(&buf, par->p[0]);
- par->p++;
- continue;
}
- }
got_str:
- *out_freeIt = Buf_GetAll(&buf, NULL);
- str = *out_freeIt;
+ str = FStr_InitOwn(Buf_GetAll(&buf, NULL));
cleanup:
- Buf_Destroy(&buf, FALSE);
- return str;
+ Buf_Destroy(&buf, FALSE);
+ *out_str = str;
}
struct If {
- const char *form; /* Form of if */
- size_t formlen; /* Length of form */
- Boolean doNot; /* TRUE if default function should be negated */
- Boolean (*defProc)(size_t, const char *); /* Default function to apply */
+ const char *form; /* Form of if */
+ size_t formlen; /* Length of form */
+ Boolean doNot; /* TRUE if default function should be negated */
+ /* The default function to apply on unquoted bare words. */
+ Boolean (*defProc)(size_t, const char *);
};
/* The different forms of .if directives. */
@@ -514,82 +531,87 @@ static const struct If ifs[] = {
{ "", 0, FALSE, FuncDefined },
{ NULL, 0, FALSE, NULL }
};
-enum { PLAIN_IF_INDEX = 4 };
+enum {
+ PLAIN_IF_INDEX = 4
+};
static Boolean
If_Eval(const struct If *if_info, const char *arg, size_t arglen)
{
- Boolean res = if_info->defProc(arglen, arg);
- return if_info->doNot ? !res : res;
+ Boolean res = if_info->defProc(arglen, arg);
+ return if_info->doNot ? !res : res;
}
-/* Evaluate a "comparison without operator", such as in ".if ${VAR}" or
- * ".if 0". */
+/*
+ * Evaluate a "comparison without operator", such as in ".if ${VAR}" or
+ * ".if 0".
+ */
static Boolean
EvalNotEmpty(CondParser *par, const char *value, Boolean quoted)
{
- double num;
+ double num;
- /* For .ifxxx "...", check for non-empty string. */
- if (quoted)
- return value[0] != '\0';
+ /* For .ifxxx "...", check for non-empty string. */
+ if (quoted)
+ return value[0] != '\0';
- /* For .ifxxx <number>, compare against zero */
- if (TryParseNumber(value, &num))
- return num != 0.0;
+ /* For .ifxxx <number>, compare against zero */
+ if (TryParseNumber(value, &num))
+ return num != 0.0;
- /* For .if ${...}, check for non-empty string. This is different from
- * the evaluation function from that .if variant, which would test
- * whether a variable of the given name were defined. */
- /* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
- if (par->if_info->form[0] == '\0')
- return value[0] != '\0';
+ /* For .if ${...}, check for non-empty string. This is different from
+ * the evaluation function from that .if variant, which would test
+ * whether a variable of the given name were defined. */
+ /* XXX: Whitespace should count as empty, just as in ParseEmptyArg. */
+ if (par->if_info->form[0] == '\0')
+ return value[0] != '\0';
- /* For the other variants of .ifxxx ${...}, use its default function. */
- return If_Eval(par->if_info, value, strlen(value));
+ /* For the other variants of .ifxxx ${...}, use its default function. */
+ return If_Eval(par->if_info, value, strlen(value));
}
/* Evaluate a numerical comparison, such as in ".if ${VAR} >= 9". */
static Token
EvalCompareNum(double lhs, const char *op, double rhs)
{
- DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
-
- switch (op[0]) {
- case '!':
- if (op[1] != '=') {
- Parse_Error(PARSE_WARNING, "Unknown operator");
- /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
- return TOK_ERROR;
- }
- return ToToken(lhs != rhs);
- case '=':
- if (op[1] != '=') {
- Parse_Error(PARSE_WARNING, "Unknown operator");
- /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
- return TOK_ERROR;
+ DEBUG3(COND, "lhs = %f, rhs = %f, op = %.2s\n", lhs, rhs, op);
+
+ switch (op[0]) {
+ case '!':
+ if (op[1] != '=') {
+ Parse_Error(PARSE_WARNING, "Unknown operator");
+ /* The PARSE_FATAL follows in CondEvalExpression. */
+ return TOK_ERROR;
+ }
+ return ToToken(lhs != rhs);
+ case '=':
+ if (op[1] != '=') {
+ Parse_Error(PARSE_WARNING, "Unknown operator");
+ /* The PARSE_FATAL follows in CondEvalExpression. */
+ return TOK_ERROR;
+ }
+ return ToToken(lhs == rhs);
+ case '<':
+ return ToToken(op[1] == '=' ? lhs <= rhs : lhs < rhs);
+ case '>':
+ return ToToken(op[1] == '=' ? lhs >= rhs : lhs > rhs);
}
- return ToToken(lhs == rhs);
- case '<':
- return ToToken(op[1] == '=' ? lhs <= rhs : lhs < rhs);
- case '>':
- return ToToken(op[1] == '=' ? lhs >= rhs : lhs > rhs);
- }
- return TOK_ERROR;
+ return TOK_ERROR;
}
static Token
EvalCompareStr(const char *lhs, const char *op, const char *rhs)
{
- if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
- Parse_Error(PARSE_WARNING,
- "String comparison operator must be either == or !=");
- /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
- return TOK_ERROR;
- }
+ if (!((op[0] == '!' || op[0] == '=') && op[1] == '=')) {
+ Parse_Error(PARSE_WARNING,
+ "String comparison operator "
+ "must be either == or !=");
+ /* The PARSE_FATAL follows in CondEvalExpression. */
+ return TOK_ERROR;
+ }
- DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", lhs, rhs, op);
- return ToToken((*op == '=') == (strcmp(lhs, rhs) == 0));
+ DEBUG3(COND, "lhs = \"%s\", rhs = \"%s\", op = %.2s\n", lhs, rhs, op);
+ return ToToken((*op == '=') == (strcmp(lhs, rhs) == 0));
}
/* Evaluate a comparison, such as "${VAR} == 12345". */
@@ -597,16 +619,17 @@ static Token
EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
const char *rhs, Boolean rhsQuoted)
{
- double left, right;
+ double left, right;
- if (!rhsQuoted && !lhsQuoted)
- if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
- return EvalCompareNum(left, op, right);
+ if (!rhsQuoted && !lhsQuoted)
+ if (TryParseNumber(lhs, &left) && TryParseNumber(rhs, &right))
+ return EvalCompareNum(left, op, right);
- return EvalCompareStr(lhs, op, rhs);
+ return EvalCompareStr(lhs, op, rhs);
}
-/* Parse a comparison condition such as:
+/*
+ * Parse a comparison condition such as:
*
* 0
* ${VAR:Mpattern}
@@ -616,266 +639,277 @@ EvalCompare(const char *lhs, Boolean lhsQuoted, const char *op,
static Token
CondParser_Comparison(CondParser *par, Boolean doEval)
{
- Token t = TOK_ERROR;
- const char *lhs, *op, *rhs;
- void *lhs_freeIt, *rhs_freeIt;
- Boolean lhsQuoted, rhsQuoted;
-
- /*
- * Parse the variable spec and skip over it, saving its
- * value in lhs.
- */
- lhs = CondParser_String(par, doEval, lhsStrict, &lhsQuoted, &lhs_freeIt);
- if (lhs == NULL)
- goto done_lhs;
-
- CondParser_SkipWhitespace(par);
-
- op = par->p;
- switch (par->p[0]) {
- case '!':
- case '=':
- case '<':
- case '>':
- if (par->p[1] == '=')
- par->p += 2;
- else
- par->p++;
- break;
- default:
- /* Unknown operator, compare against an empty string or 0. */
- t = ToToken(doEval && EvalNotEmpty(par, lhs, lhsQuoted));
- goto done_lhs;
- }
-
- CondParser_SkipWhitespace(par);
-
- if (par->p[0] == '\0') {
- Parse_Error(PARSE_WARNING, "Missing right-hand-side of operator");
- /* The PARSE_FATAL is done as a follow-up by CondEvalExpression. */
- goto done_lhs;
- }
-
- rhs = CondParser_String(par, doEval, FALSE, &rhsQuoted, &rhs_freeIt);
- if (rhs == NULL)
- goto done_rhs;
-
- if (!doEval) {
- t = TOK_FALSE;
- goto done_rhs;
- }
-
- t = EvalCompare(lhs, lhsQuoted, op, rhs, rhsQuoted);
+ Token t = TOK_ERROR;
+ FStr lhs, rhs;
+ const char *op;
+ Boolean lhsQuoted, rhsQuoted;
+
+ /*
+ * Parse the variable spec and skip over it, saving its
+ * value in lhs.
+ */
+ CondParser_String(par, doEval, lhsStrict, &lhs, &lhsQuoted);
+ if (lhs.str == NULL)
+ goto done_lhs;
+
+ CondParser_SkipWhitespace(par);
+
+ op = par->p;
+ switch (par->p[0]) {
+ case '!':
+ case '=':
+ case '<':
+ case '>':
+ if (par->p[1] == '=')
+ par->p += 2;
+ else
+ par->p++;
+ break;
+ default:
+ /* Unknown operator, compare against an empty string or 0. */
+ t = ToToken(doEval && EvalNotEmpty(par, lhs.str, lhsQuoted));
+ goto done_lhs;
+ }
+
+ CondParser_SkipWhitespace(par);
+
+ if (par->p[0] == '\0') {
+ Parse_Error(PARSE_WARNING,
+ "Missing right-hand-side of operator");
+ /* The PARSE_FATAL follows in CondEvalExpression. */
+ goto done_lhs;
+ }
+
+ CondParser_String(par, doEval, FALSE, &rhs, &rhsQuoted);
+ if (rhs.str == NULL)
+ goto done_rhs;
+
+ if (!doEval) {
+ t = TOK_FALSE;
+ goto done_rhs;
+ }
+
+ t = EvalCompare(lhs.str, lhsQuoted, op, rhs.str, rhsQuoted);
done_rhs:
- free(rhs_freeIt);
+ FStr_Done(&rhs);
done_lhs:
- free(lhs_freeIt);
- return t;
+ FStr_Done(&lhs);
+ return t;
}
-/* The argument to empty() is a variable name, optionally followed by
- * variable modifiers. */
+/*
+ * The argument to empty() is a variable name, optionally followed by
+ * variable modifiers.
+ */
+/*ARGSUSED*/
static size_t
ParseEmptyArg(const char **pp, Boolean doEval,
const char *func MAKE_ATTR_UNUSED, char **out_arg)
{
- void *val_freeIt;
- const char *val;
- size_t magic_res;
-
- /* We do all the work here and return the result as the length */
- *out_arg = NULL;
-
- (*pp)--; /* Make (*pp)[1] point to the '('. */
- (void)Var_Parse(pp, VAR_CMDLINE, doEval ? VARE_WANTRES : VARE_NONE,
- &val, &val_freeIt);
- /* TODO: handle errors */
- /* If successful, *pp points beyond the closing ')' now. */
-
- if (val == var_Error) {
- free(val_freeIt);
- return (size_t)-1;
- }
-
- /* A variable is empty when it just contains spaces... 4/15/92, christos */
- cpp_skip_whitespace(&val);
-
- /*
- * For consistency with the other functions we can't generate the
- * true/false here.
- */
- magic_res = *val != '\0' ? 2 : 1;
- free(val_freeIt);
- return magic_res;
+ FStr val;
+ size_t magic_res;
+
+ /* We do all the work here and return the result as the length */
+ *out_arg = NULL;
+
+ (*pp)--; /* Make (*pp)[1] point to the '('. */
+ (void)Var_Parse(pp, VAR_CMDLINE, doEval ? VARE_WANTRES : VARE_NONE,
+ &val);
+ /* TODO: handle errors */
+ /* If successful, *pp points beyond the closing ')' now. */
+
+ if (val.str == var_Error) {
+ FStr_Done(&val);
+ return (size_t)-1;
+ }
+
+ /*
+ * A variable is empty when it just contains spaces...
+ * 4/15/92, christos
+ */
+ cpp_skip_whitespace(&val.str);
+
+ /*
+ * For consistency with the other functions we can't generate the
+ * true/false here.
+ */
+ magic_res = val.str[0] != '\0' ? 2 : 1;
+ FStr_Done(&val);
+ return magic_res;
}
+/*ARGSUSED*/
static Boolean
FuncEmpty(size_t arglen, const char *arg MAKE_ATTR_UNUSED)
{
- /* Magic values ahead, see ParseEmptyArg. */
- return arglen == 1;
+ /* Magic values ahead, see ParseEmptyArg. */
+ return arglen == 1;
}
static Boolean
CondParser_Func(CondParser *par, Boolean doEval, Token *out_token)
{
- static const struct fn_def {
- const char *fn_name;
- size_t fn_name_len;
- size_t (*fn_parse)(const char **, Boolean, const char *, char **);
- Boolean (*fn_eval)(size_t, const char *);
- } fns[] = {
- { "defined", 7, ParseFuncArg, FuncDefined },
- { "make", 4, ParseFuncArg, FuncMake },
- { "exists", 6, ParseFuncArg, FuncExists },
- { "empty", 5, ParseEmptyArg, FuncEmpty },
- { "target", 6, ParseFuncArg, FuncTarget },
- { "commands", 8, ParseFuncArg, FuncCommands }
- };
- const struct fn_def *fn;
- char *arg = NULL;
- size_t arglen;
- const char *cp = par->p;
- const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
-
- for (fn = fns; fn != fns_end; fn++) {
- if (!is_token(cp, fn->fn_name, fn->fn_name_len))
- continue;
-
- cp += fn->fn_name_len;
- cpp_skip_whitespace(&cp);
- if (*cp != '(')
- break;
-
- arglen = fn->fn_parse(&cp, doEval, fn->fn_name, &arg);
- if (arglen == 0 || arglen == (size_t)-1) {
- par->p = cp;
- *out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
- return TRUE;
- }
+ static const struct fn_def {
+ const char *fn_name;
+ size_t fn_name_len;
+ size_t (*fn_parse)(const char **, Boolean, const char *,
+ char **);
+ Boolean (*fn_eval)(size_t, const char *);
+ } fns[] = {
+ { "defined", 7, ParseFuncArg, FuncDefined },
+ { "make", 4, ParseFuncArg, FuncMake },
+ { "exists", 6, ParseFuncArg, FuncExists },
+ { "empty", 5, ParseEmptyArg, FuncEmpty },
+ { "target", 6, ParseFuncArg, FuncTarget },
+ { "commands", 8, ParseFuncArg, FuncCommands }
+ };
+ const struct fn_def *fn;
+ char *arg = NULL;
+ size_t arglen;
+ const char *cp = par->p;
+ const struct fn_def *fns_end = fns + sizeof fns / sizeof fns[0];
+
+ for (fn = fns; fn != fns_end; fn++) {
+ if (!is_token(cp, fn->fn_name, fn->fn_name_len))
+ continue;
+
+ cp += fn->fn_name_len;
+ cpp_skip_whitespace(&cp);
+ if (*cp != '(')
+ break;
+
+ arglen = fn->fn_parse(&cp, doEval, fn->fn_name, &arg);
+ if (arglen == 0 || arglen == (size_t)-1) {
+ par->p = cp;
+ *out_token = arglen == 0 ? TOK_FALSE : TOK_ERROR;
+ return TRUE;
+ }
- /* Evaluate the argument using the required function. */
- *out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
- free(arg);
- par->p = cp;
- return TRUE;
- }
+ /* Evaluate the argument using the required function. */
+ *out_token = ToToken(!doEval || fn->fn_eval(arglen, arg));
+ free(arg);
+ par->p = cp;
+ return TRUE;
+ }
- return FALSE;
+ return FALSE;
}
-/* Parse a function call, a number, a variable expression or a string
- * literal. */
+/*
+ * Parse a function call, a number, a variable expression or a string
+ * literal.
+ */
static Token
CondParser_LeafToken(CondParser *par, Boolean doEval)
{
- Token t;
- char *arg = NULL;
- size_t arglen;
- const char *cp = par->p;
- const char *cp1;
+ Token t;
+ char *arg = NULL;
+ size_t arglen;
+ const char *cp;
+ const char *cp1;
- if (CondParser_Func(par, doEval, &t))
- return t;
+ if (CondParser_Func(par, doEval, &t))
+ return t;
- /* Push anything numeric through the compare expression */
- cp = par->p;
- if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
- return CondParser_Comparison(par, doEval);
-
- /*
- * Most likely we have a naked token to apply the default function to.
- * However ".if a == b" gets here when the "a" is unquoted and doesn't
- * start with a '$'. This surprises people.
- * If what follows the function argument is a '=' or '!' then the syntax
- * would be invalid if we did "defined(a)" - so instead treat as an
- * expression.
- */
- arglen = ParseFuncArg(&cp, doEval, NULL, &arg);
- cp1 = cp;
- cpp_skip_whitespace(&cp1);
- if (*cp1 == '=' || *cp1 == '!')
- return CondParser_Comparison(par, doEval);
- par->p = cp;
-
- /*
- * Evaluate the argument using the default function.
- * This path always treats .if as .ifdef. To get here, the character
- * after .if must have been taken literally, so the argument cannot
- * be empty - even if it contained a variable expansion.
- */
- t = ToToken(!doEval || If_Eval(par->if_info, arg, arglen));
- free(arg);
- return t;
+ /* Push anything numeric through the compare expression */
+ cp = par->p;
+ if (ch_isdigit(cp[0]) || cp[0] == '-' || cp[0] == '+')
+ return CondParser_Comparison(par, doEval);
+
+ /*
+ * Most likely we have a naked token to apply the default function to.
+ * However ".if a == b" gets here when the "a" is unquoted and doesn't
+ * start with a '$'. This surprises people.
+ * If what follows the function argument is a '=' or '!' then the
+ * syntax would be invalid if we did "defined(a)" - so instead treat
+ * as an expression.
+ */
+ arglen = ParseFuncArg(&cp, doEval, NULL, &arg);
+ cp1 = cp;
+ cpp_skip_whitespace(&cp1);
+ if (*cp1 == '=' || *cp1 == '!')
+ return CondParser_Comparison(par, doEval);
+ par->p = cp;
+
+ /*
+ * Evaluate the argument using the default function.
+ * This path always treats .if as .ifdef. To get here, the character
+ * after .if must have been taken literally, so the argument cannot
+ * be empty - even if it contained a variable expansion.
+ */
+ t = ToToken(!doEval || If_Eval(par->if_info, arg, arglen));
+ free(arg);
+ return t;
}
/* Return the next token or comparison result from the parser. */
static Token
CondParser_Token(CondParser *par, Boolean doEval)
{
- Token t;
+ Token t;
- t = par->curr;
- if (t != TOK_NONE) {
- par->curr = TOK_NONE;
- return t;
- }
+ t = par->curr;
+ if (t != TOK_NONE) {
+ par->curr = TOK_NONE;
+ return t;
+ }
- cpp_skip_hspace(&par->p);
+ cpp_skip_hspace(&par->p);
- switch (par->p[0]) {
+ switch (par->p[0]) {
- case '(':
- par->p++;
- return TOK_LPAREN;
+ case '(':
+ par->p++;
+ return TOK_LPAREN;
- case ')':
- par->p++;
- return TOK_RPAREN;
+ case ')':
+ par->p++;
+ return TOK_RPAREN;
- case '|':
- par->p++;
- if (par->p[0] == '|')
- par->p++;
- else if (opts.lint) {
- Parse_Error(PARSE_FATAL, "Unknown operator '|'");
- par->printedError = TRUE;
- return TOK_ERROR;
- }
- return TOK_OR;
-
- case '&':
- par->p++;
- if (par->p[0] == '&')
- par->p++;
- else if (opts.lint) {
- Parse_Error(PARSE_FATAL, "Unknown operator '&'");
- par->printedError = TRUE;
- return TOK_ERROR;
- }
- return TOK_AND;
+ case '|':
+ par->p++;
+ if (par->p[0] == '|')
+ par->p++;
+ else if (opts.strict) {
+ Parse_Error(PARSE_FATAL, "Unknown operator '|'");
+ par->printedError = TRUE;
+ return TOK_ERROR;
+ }
+ return TOK_OR;
- case '!':
- par->p++;
- return TOK_NOT;
+ case '&':
+ par->p++;
+ if (par->p[0] == '&')
+ par->p++;
+ else if (opts.strict) {
+ Parse_Error(PARSE_FATAL, "Unknown operator '&'");
+ par->printedError = TRUE;
+ return TOK_ERROR;
+ }
+ return TOK_AND;
- case '#': /* XXX: see unit-tests/cond-token-plain.mk */
- case '\n': /* XXX: why should this end the condition? */
- /* Probably obsolete now, from 1993-03-21. */
- case '\0':
- return TOK_EOF;
+ case '!':
+ par->p++;
+ return TOK_NOT;
- case '"':
- case '$':
- return CondParser_Comparison(par, doEval);
+ case '#': /* XXX: see unit-tests/cond-token-plain.mk */
+ case '\n': /* XXX: why should this end the condition? */
+ /* Probably obsolete now, from 1993-03-21. */
+ case '\0':
+ return TOK_EOF;
- default:
- return CondParser_LeafToken(par, doEval);
- }
+ case '"':
+ case '$':
+ return CondParser_Comparison(par, doEval);
+
+ default:
+ return CondParser_LeafToken(par, doEval);
+ }
}
-/* Parse a single term in the expression. This consists of a terminal symbol
+/*
+ * Parse a single term in the expression. This consists of a terminal symbol
* or TOK_NOT and a term (not including the binary operators):
*
* T -> defined(variable) | make(target) | exists(file) | symbol
@@ -887,38 +921,39 @@ CondParser_Token(CondParser *par, Boolean doEval)
static Token
CondParser_Term(CondParser *par, Boolean doEval)
{
- Token t;
+ Token t;
- t = CondParser_Token(par, doEval);
+ t = CondParser_Token(par, doEval);
- if (t == TOK_EOF) {
- /*
- * If we reached the end of the expression, the expression
- * is malformed...
- */
- t = TOK_ERROR;
- } else if (t == TOK_LPAREN) {
- /*
- * T -> ( E )
- */
- t = CondParser_Expr(par, doEval);
- if (t != TOK_ERROR) {
- if (CondParser_Token(par, doEval) != TOK_RPAREN) {
+ if (t == TOK_EOF) {
+ /*
+ * If we reached the end of the expression, the expression
+ * is malformed...
+ */
t = TOK_ERROR;
- }
- }
- } else if (t == TOK_NOT) {
- t = CondParser_Term(par, doEval);
- if (t == TOK_TRUE) {
- t = TOK_FALSE;
- } else if (t == TOK_FALSE) {
- t = TOK_TRUE;
+ } else if (t == TOK_LPAREN) {
+ /*
+ * T -> ( E )
+ */
+ t = CondParser_Expr(par, doEval);
+ if (t != TOK_ERROR) {
+ if (CondParser_Token(par, doEval) != TOK_RPAREN) {
+ t = TOK_ERROR;
+ }
+ }
+ } else if (t == TOK_NOT) {
+ t = CondParser_Term(par, doEval);
+ if (t == TOK_TRUE) {
+ t = TOK_FALSE;
+ } else if (t == TOK_FALSE) {
+ t = TOK_TRUE;
+ }
}
- }
- return t;
+ return t;
}
-/* Parse a conjunctive factor (nice name, wot?)
+/*
+ * Parse a conjunctive factor (nice name, wot?)
*
* F -> T && F | T
*
@@ -928,37 +963,38 @@ CondParser_Term(CondParser *par, Boolean doEval)
static Token
CondParser_Factor(CondParser *par, Boolean doEval)
{
- Token l, o;
-
- l = CondParser_Term(par, doEval);
- if (l != TOK_ERROR) {
- o = CondParser_Token(par, doEval);
-
- if (o == TOK_AND) {
- /*
- * F -> T && F
- *
- * If T is TOK_FALSE, the whole thing will be TOK_FALSE, but we
- * have to parse the r.h.s. anyway (to throw it away).
- * If T is TOK_TRUE, the result is the r.h.s., be it a TOK_ERROR
- * or not.
- */
- if (l == TOK_TRUE) {
- l = CondParser_Factor(par, doEval);
- } else {
- (void)CondParser_Factor(par, FALSE);
- }
- } else {
- /*
- * F -> T
- */
- CondParser_PushBack(par, o);
+ Token l, o;
+
+ l = CondParser_Term(par, doEval);
+ if (l != TOK_ERROR) {
+ o = CondParser_Token(par, doEval);
+
+ if (o == TOK_AND) {
+ /*
+ * F -> T && F
+ *
+ * If T is TOK_FALSE, the whole thing will be
+ * TOK_FALSE, but we have to parse the r.h.s. anyway
+ * (to throw it away). If T is TOK_TRUE, the result
+ * is the r.h.s., be it a TOK_ERROR or not.
+ */
+ if (l == TOK_TRUE) {
+ l = CondParser_Factor(par, doEval);
+ } else {
+ (void)CondParser_Factor(par, FALSE);
+ }
+ } else {
+ /*
+ * F -> T
+ */
+ CondParser_PushBack(par, o);
+ }
}
- }
- return l;
+ return l;
}
-/* Main expression production.
+/*
+ * Main expression production.
*
* E -> F || E | F
*
@@ -968,55 +1004,58 @@ CondParser_Factor(CondParser *par, Boolean doEval)
static Token
CondParser_Expr(CondParser *par, Boolean doEval)
{
- Token l, o;
-
- l = CondParser_Factor(par, doEval);
- if (l != TOK_ERROR) {
- o = CondParser_Token(par, doEval);
-
- if (o == TOK_OR) {
- /*
- * E -> F || E
- *
- * A similar thing occurs for ||, except that here we make sure
- * the l.h.s. is TOK_FALSE before we bother to evaluate the r.h.s.
- * Once again, if l is TOK_FALSE, the result is the r.h.s. and once
- * again if l is TOK_TRUE, we parse the r.h.s. to throw it away.
- */
- if (l == TOK_FALSE) {
- l = CondParser_Expr(par, doEval);
- } else {
- (void)CondParser_Expr(par, FALSE);
- }
- } else {
- /*
- * E -> F
- */
- CondParser_PushBack(par, o);
+ Token l, o;
+
+ l = CondParser_Factor(par, doEval);
+ if (l != TOK_ERROR) {
+ o = CondParser_Token(par, doEval);
+
+ if (o == TOK_OR) {
+ /*
+ * E -> F || E
+ *
+ * A similar thing occurs for ||, except that here
+ * we make sure the l.h.s. is TOK_FALSE before we
+ * bother to evaluate the r.h.s. Once again, if l
+ * is TOK_FALSE, the result is the r.h.s. and once
+ * again if l is TOK_TRUE, we parse the r.h.s. to
+ * throw it away.
+ */
+ if (l == TOK_FALSE) {
+ l = CondParser_Expr(par, doEval);
+ } else {
+ (void)CondParser_Expr(par, FALSE);
+ }
+ } else {
+ /*
+ * E -> F
+ */
+ CondParser_PushBack(par, o);
+ }
}
- }
- return l;
+ return l;
}
static CondEvalResult
CondParser_Eval(CondParser *par, Boolean *value)
{
- Token res;
+ Token res;
- DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
+ DEBUG1(COND, "CondParser_Eval: %s\n", par->p);
- res = CondParser_Expr(par, TRUE);
- if (res != TOK_FALSE && res != TOK_TRUE)
- return COND_INVALID;
+ res = CondParser_Expr(par, TRUE);
+ if (res != TOK_FALSE && res != TOK_TRUE)
+ return COND_INVALID;
- if (CondParser_Token(par, TRUE /* XXX: Why TRUE? */) != TOK_EOF)
- return COND_INVALID;
+ if (CondParser_Token(par, FALSE) != TOK_EOF)
+ return COND_INVALID;
- *value = res == TOK_TRUE;
- return COND_PARSE;
+ *value = res == TOK_TRUE;
+ return COND_PARSE;
}
-/* Evaluate the condition, including any side effects from the variable
+/*
+ * Evaluate the condition, including any side effects from the variable
* expressions in the condition. The condition consists of &&, ||, !,
* function(arg), comparisons and parenthetical groupings thereof.
*
@@ -1028,37 +1067,47 @@ CondParser_Eval(CondParser *par, Boolean *value)
*/
static CondEvalResult
CondEvalExpression(const struct If *info, const char *cond, Boolean *value,
- Boolean eprint, Boolean strictLHS)
+ Boolean eprint, Boolean strictLHS)
{
- CondParser par;
- CondEvalResult rval;
+ CondParser par;
+ CondEvalResult rval;
- lhsStrict = strictLHS;
+ lhsStrict = strictLHS;
- cpp_skip_hspace(&cond);
+ cpp_skip_hspace(&cond);
- par.if_info = info != NULL ? info : ifs + PLAIN_IF_INDEX;
- par.p = cond;
- par.curr = TOK_NONE;
- par.printedError = FALSE;
+ par.if_info = info != NULL ? info : ifs + PLAIN_IF_INDEX;
+ par.p = cond;
+ par.curr = TOK_NONE;
+ par.printedError = FALSE;
- rval = CondParser_Eval(&par, value);
+ rval = CondParser_Eval(&par, value);
- if (rval == COND_INVALID && eprint && !par.printedError)
- Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
+ if (rval == COND_INVALID && eprint && !par.printedError)
+ Parse_Error(PARSE_FATAL, "Malformed conditional (%s)", cond);
- return rval;
+ return rval;
}
-/* Evaluate a condition in a :? modifier, such as
- * ${"${VAR}" == value:?yes:no}. */
+/*
+ * Evaluate a condition in a :? modifier, such as
+ * ${"${VAR}" == value:?yes:no}.
+ */
CondEvalResult
Cond_EvalCondition(const char *cond, Boolean *out_value)
{
return CondEvalExpression(NULL, cond, out_value, FALSE, FALSE);
}
-/* Evaluate the conditional directive in the line, which is one of:
+static Boolean
+IsEndif(const char *p)
+{
+ return p[0] == 'e' && p[1] == 'n' && p[2] == 'd' &&
+ p[3] == 'i' && p[4] == 'f' && !ch_isalpha(p[5]);
+}
+
+/*
+ * Evaluate the conditional directive in the line, which is one of:
*
* .if <cond>
* .ifmake <cond>
@@ -1088,194 +1137,212 @@ Cond_EvalCondition(const char *cond, Boolean *out_value)
* or because the condition could not be evaluated
*/
CondEvalResult
-Cond_EvalLine(const char *const line)
+Cond_EvalLine(const char *line)
{
- typedef enum IfState {
+ typedef enum IfState {
- /* None of the previous <cond> evaluated to TRUE. */
- IFS_INITIAL = 0,
+ /* None of the previous <cond> evaluated to TRUE. */
+ IFS_INITIAL = 0,
- /* The previous <cond> evaluated to TRUE.
- * The lines following this condition are interpreted. */
- IFS_ACTIVE = 1 << 0,
+ /* The previous <cond> evaluated to TRUE.
+ * The lines following this condition are interpreted. */
+ IFS_ACTIVE = 1 << 0,
- /* The previous directive was an '.else'. */
- IFS_SEEN_ELSE = 1 << 1,
+ /* The previous directive was an '.else'. */
+ IFS_SEEN_ELSE = 1 << 1,
- /* One of the previous <cond> evaluated to TRUE. */
- IFS_WAS_ACTIVE = 1 << 2
+ /* One of the previous <cond> evaluated to TRUE. */
+ IFS_WAS_ACTIVE = 1 << 2
- } IfState;
+ } IfState;
- static enum IfState *cond_states = NULL;
- static unsigned int cond_states_cap = 128;
+ static enum IfState *cond_states = NULL;
+ static unsigned int cond_states_cap = 128;
- const struct If *ifp;
- Boolean isElif;
- Boolean value;
- IfState state;
- const char *p = line;
+ const struct If *ifp;
+ Boolean isElif;
+ Boolean value;
+ IfState state;
+ const char *p = line;
- if (cond_states == NULL) {
- cond_states = bmake_malloc(cond_states_cap * sizeof *cond_states);
- cond_states[0] = IFS_ACTIVE;
- }
+ if (cond_states == NULL) {
+ cond_states = bmake_malloc(
+ cond_states_cap * sizeof *cond_states);
+ cond_states[0] = IFS_ACTIVE;
+ }
- p++; /* skip the leading '.' */
- cpp_skip_hspace(&p);
+ p++; /* skip the leading '.' */
+ cpp_skip_hspace(&p);
- /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
- if (p[0] == 'e') {
- if (p[1] != 'l') {
- if (!is_token(p + 1, "ndif", 4)) {
- /* Unknown directive. It might still be a transformation
- * rule like '.elisp.scm', therefore no error message here. */
- return COND_INVALID;
- }
+ if (IsEndif(p)) { /* It is an '.endif'. */
+ if (p[5] != '\0') {
+ Parse_Error(PARSE_FATAL,
+ "The .endif directive does not take arguments.");
+ }
- /* It is an '.endif'. */
- /* TODO: check for extraneous <cond> */
+ if (cond_depth == cond_min_depth) {
+ Parse_Error(PARSE_FATAL, "if-less endif");
+ return COND_PARSE;
+ }
- if (cond_depth == cond_min_depth) {
- Parse_Error(PARSE_FATAL, "if-less endif");
- return COND_PARSE;
- }
+ /* Return state for previous conditional */
+ cond_depth--;
+ return cond_states[cond_depth] & IFS_ACTIVE
+ ? COND_PARSE : COND_SKIP;
+ }
- /* Return state for previous conditional */
- cond_depth--;
- return cond_states[cond_depth] & IFS_ACTIVE
- ? COND_PARSE : COND_SKIP;
+ /* Parse the name of the directive, such as 'if', 'elif', 'endif'. */
+ if (p[0] == 'e') {
+ if (p[1] != 'l') {
+ /*
+ * Unknown directive. It might still be a
+ * transformation rule like '.elisp.scm',
+ * therefore no error message here.
+ */
+ return COND_INVALID;
+ }
+
+ /* Quite likely this is 'else' or 'elif' */
+ p += 2;
+ if (is_token(p, "se", 2)) { /* It is an 'else'. */
+
+ if (p[2] != '\0')
+ Parse_Error(PARSE_FATAL,
+ "The .else directive "
+ "does not take arguments.");
+
+ if (cond_depth == cond_min_depth) {
+ Parse_Error(PARSE_FATAL, "if-less else");
+ return COND_PARSE;
+ }
+
+ state = cond_states[cond_depth];
+ if (state == IFS_INITIAL) {
+ state = IFS_ACTIVE | IFS_SEEN_ELSE;
+ } else {
+ if (state & IFS_SEEN_ELSE)
+ Parse_Error(PARSE_WARNING,
+ "extra else");
+ state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
+ }
+ cond_states[cond_depth] = state;
+
+ return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
+ }
+ /* Assume for now it is an elif */
+ isElif = TRUE;
+ } else
+ isElif = FALSE;
+
+ if (p[0] != 'i' || p[1] != 'f') {
+ /*
+ * Unknown directive. It might still be a transformation rule
+ * like '.elisp.scm', therefore no error message here.
+ */
+ return COND_INVALID; /* Not an ifxxx or elifxxx line */
}
- /* Quite likely this is 'else' or 'elif' */
+ /*
+ * Figure out what sort of conditional it is -- what its default
+ * function is, etc. -- by looking in the table of valid "ifs"
+ */
p += 2;
- if (is_token(p, "se", 2)) { /* It is an 'else'. */
-
- if (opts.lint && p[2] != '\0')
- Parse_Error(PARSE_FATAL,
- "The .else directive does not take arguments.");
-
- if (cond_depth == cond_min_depth) {
- Parse_Error(PARSE_FATAL, "if-less else");
- return COND_PARSE;
- }
-
- state = cond_states[cond_depth];
- if (state == IFS_INITIAL) {
- state = IFS_ACTIVE | IFS_SEEN_ELSE;
- } else {
- if (state & IFS_SEEN_ELSE)
- Parse_Error(PARSE_WARNING, "extra else");
- state = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
- }
- cond_states[cond_depth] = state;
-
- return state & IFS_ACTIVE ? COND_PARSE : COND_SKIP;
- }
- /* Assume for now it is an elif */
- isElif = TRUE;
- } else
- isElif = FALSE;
-
- if (p[0] != 'i' || p[1] != 'f') {
- /* Unknown directive. It might still be a transformation rule like
- * '.elisp.scm', therefore no error message here. */
- return COND_INVALID; /* Not an ifxxx or elifxxx line */
- }
-
- /*
- * Figure out what sort of conditional it is -- what its default
- * function is, etc. -- by looking in the table of valid "ifs"
- */
- p += 2;
- for (ifp = ifs;; ifp++) {
- if (ifp->form == NULL) {
- /* TODO: Add error message about unknown directive,
- * since there is no other known directive that starts with 'el'
- * or 'if'.
- * Example: .elifx 123 */
- return COND_INVALID;
- }
- if (is_token(p, ifp->form, ifp->formlen)) {
- p += ifp->formlen;
- break;
+ for (ifp = ifs;; ifp++) {
+ if (ifp->form == NULL) {
+ /*
+ * TODO: Add error message about unknown directive,
+ * since there is no other known directive that starts
+ * with 'el' or 'if'.
+ *
+ * Example: .elifx 123
+ */
+ return COND_INVALID;
+ }
+ if (is_token(p, ifp->form, ifp->formlen)) {
+ p += ifp->formlen;
+ break;
+ }
}
- }
- /* Now we know what sort of 'if' it is... */
+ /* Now we know what sort of 'if' it is... */
- if (isElif) {
- if (cond_depth == cond_min_depth) {
- Parse_Error(PARSE_FATAL, "if-less elif");
- return COND_PARSE;
- }
- state = cond_states[cond_depth];
- if (state & IFS_SEEN_ELSE) {
- Parse_Error(PARSE_WARNING, "extra elif");
- cond_states[cond_depth] = IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
- return COND_SKIP;
- }
- if (state != IFS_INITIAL) {
- cond_states[cond_depth] = IFS_WAS_ACTIVE;
- return COND_SKIP;
+ if (isElif) {
+ if (cond_depth == cond_min_depth) {
+ Parse_Error(PARSE_FATAL, "if-less elif");
+ return COND_PARSE;
+ }
+ state = cond_states[cond_depth];
+ if (state & IFS_SEEN_ELSE) {
+ Parse_Error(PARSE_WARNING, "extra elif");
+ cond_states[cond_depth] =
+ IFS_WAS_ACTIVE | IFS_SEEN_ELSE;
+ return COND_SKIP;
+ }
+ if (state != IFS_INITIAL) {
+ cond_states[cond_depth] = IFS_WAS_ACTIVE;
+ return COND_SKIP;
+ }
+ } else {
+ /* Normal .if */
+ if (cond_depth + 1 >= cond_states_cap) {
+ /*
+ * This is rare, but not impossible.
+ * In meta mode, dirdeps.mk (only runs at level 0)
+ * can need more than the default.
+ */
+ cond_states_cap += 32;
+ cond_states = bmake_realloc(cond_states,
+ cond_states_cap *
+ sizeof *cond_states);
+ }
+ state = cond_states[cond_depth];
+ cond_depth++;
+ if (!(state & IFS_ACTIVE)) {
+ /*
+ * If we aren't parsing the data,
+ * treat as always false.
+ */
+ cond_states[cond_depth] = IFS_WAS_ACTIVE;
+ return COND_SKIP;
+ }
}
- } else {
- /* Normal .if */
- if (cond_depth + 1 >= cond_states_cap) {
- /*
- * This is rare, but not impossible.
- * In meta mode, dirdeps.mk (only runs at level 0)
- * can need more than the default.
- */
- cond_states_cap += 32;
- cond_states = bmake_realloc(cond_states,
- cond_states_cap * sizeof *cond_states);
+
+ /* And evaluate the conditional expression */
+ if (CondEvalExpression(ifp, p, &value, TRUE, TRUE) == COND_INVALID) {
+ /* Syntax error in conditional, error message already output. */
+ /* Skip everything to matching .endif */
+ /* XXX: An extra '.else' is not detected in this case. */
+ cond_states[cond_depth] = IFS_WAS_ACTIVE;
+ return COND_SKIP;
}
- state = cond_states[cond_depth];
- cond_depth++;
- if (!(state & IFS_ACTIVE)) {
- /* If we aren't parsing the data, treat as always false */
- cond_states[cond_depth] = IFS_WAS_ACTIVE;
- return COND_SKIP;
+
+ if (!value) {
+ cond_states[cond_depth] = IFS_INITIAL;
+ return COND_SKIP;
}
- }
-
- /* And evaluate the conditional expression */
- if (CondEvalExpression(ifp, p, &value, TRUE, TRUE) == COND_INVALID) {
- /* Syntax error in conditional, error message already output. */
- /* Skip everything to matching .endif */
- /* XXX: An extra '.else' is not detected in this case. */
- cond_states[cond_depth] = IFS_WAS_ACTIVE;
- return COND_SKIP;
- }
-
- if (!value) {
- cond_states[cond_depth] = IFS_INITIAL;
- return COND_SKIP;
- }
- cond_states[cond_depth] = IFS_ACTIVE;
- return COND_PARSE;
+ cond_states[cond_depth] = IFS_ACTIVE;
+ return COND_PARSE;
}
void
Cond_restore_depth(unsigned int saved_depth)
{
- unsigned int open_conds = cond_depth - cond_min_depth;
+ unsigned int open_conds = cond_depth - cond_min_depth;
- if (open_conds != 0 || saved_depth > cond_depth) {
- Parse_Error(PARSE_FATAL, "%u open conditional%s", open_conds,
- open_conds == 1 ? "" : "s");
- cond_depth = cond_min_depth;
- }
+ if (open_conds != 0 || saved_depth > cond_depth) {
+ Parse_Error(PARSE_FATAL, "%u open conditional%s",
+ open_conds, open_conds == 1 ? "" : "s");
+ cond_depth = cond_min_depth;
+ }
- cond_min_depth = saved_depth;
+ cond_min_depth = saved_depth;
}
unsigned int
Cond_save_depth(void)
{
- unsigned int depth = cond_min_depth;
+ unsigned int depth = cond_min_depth;
- cond_min_depth = cond_depth;
- return depth;
+ cond_min_depth = cond_depth;
+ return depth;
}
diff --git a/dir.c b/dir.c
index 359e61adb669..230b66b3baf3 100644
--- a/dir.c
+++ b/dir.c
@@ -1,4 +1,4 @@
-/* $NetBSD: dir.c,v 1.210 2020/11/14 21:29:44 rillig Exp $ */
+/* $NetBSD: dir.c,v 1.255 2021/01/10 21:20:46 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -69,7 +69,8 @@
* SUCH DAMAGE.
*/
-/* Directory searching using wildcards and/or normal names.
+/*
+ * Directory searching using wildcards and/or normal names.
* Used both for source wildcarding in the makefile and for finding
* implicit sources.
*
@@ -106,7 +107,8 @@
*
* Dir_AddDir Add a directory to a search path.
*
- * Dir_MakeFlags Given a search path and a command flag, create
+ * SearchPath_ToFlags
+ * Given a search path and a command flag, create
* a string with each of the directories in the path
* preceded by the command flag and all of them
* separated by a space.
@@ -116,7 +118,8 @@
* as the element is no longer referenced by any other
* search path.
*
- * Dir_ClearPath Resets a search path to the empty list.
+ * SearchPath_Clear
+ * Resets a search path to the empty list.
*
* For debugging:
* Dir_PrintDirectories
@@ -134,13 +137,10 @@
#include "job.h"
/* "@(#)dir.c 8.2 (Berkeley) 1/2/94" */
-MAKE_RCSID("$NetBSD: dir.c,v 1.210 2020/11/14 21:29:44 rillig Exp $");
-
-#define DIR_DEBUG0(text) DEBUG0(DIR, text)
-#define DIR_DEBUG1(fmt, arg1) DEBUG1(DIR, fmt, arg1)
-#define DIR_DEBUG2(fmt, arg1, arg2) DEBUG2(DIR, fmt, arg1, arg2)
+MAKE_RCSID("$NetBSD: dir.c,v 1.255 2021/01/10 21:20:46 rillig Exp $");
-/* A search path is a list of CachedDir structures. A CachedDir has in it the
+/*
+ * A search path is a list of CachedDir structures. A CachedDir has in it the
* name of the directory and the names of all the files in the directory.
* This is used to cut down on the number of system calls necessary to find
* implicit dependents and their like. Since these searches are made before
@@ -207,179 +207,277 @@ MAKE_RCSID("$NetBSD: dir.c,v 1.210 2020/11/14 21:29:44 rillig Exp $");
* the mtime in a cache for when Dir_UpdateMTime was actually called.
*/
+
+/* A cache for the filenames in a directory. */
+struct CachedDir {
+ /*
+ * Name of directory, either absolute or relative to the current
+ * directory. The name is not normalized in any way, that is, "."
+ * and "./." are different.
+ *
+ * Not sure what happens when .CURDIR is assigned a new value; see
+ * Parse_DoVar.
+ */
+ char *name;
+
+ /*
+ * The number of SearchPaths that refer to this directory.
+ * Plus the number of global variables that refer to this directory.
+ * References from openDirs do not count though.
+ */
+ int refCount;
+
+ /* The number of times a file in this directory has been found. */
+ int hits;
+
+ /* The names of the directory entries. */
+ HashSet files;
+};
+
typedef List CachedDirList;
typedef ListNode CachedDirListNode;
typedef ListNode SearchPathNode;
-SearchPath *dirSearchPath; /* main search path */
-
/* A list of cached directories, with fast lookup by directory name. */
typedef struct OpenDirs {
- CachedDirList *list;
- HashTable /* of CachedDirListNode */ table;
+ CachedDirList list;
+ HashTable /* of CachedDirListNode */ table;
} OpenDirs;
+typedef enum CachedStatsFlags {
+ CST_NONE = 0,
+ CST_LSTAT = 1 << 0, /* call lstat(2) instead of stat(2) */
+ CST_UPDATE = 1 << 1 /* ignore existing cached entry */
+} CachedStatsFlags;
+
+
+SearchPath dirSearchPath = LST_INIT; /* main search path */
+
+static OpenDirs openDirs; /* all cached directories */
+
+/*
+ * Variables for gathering statistics on the efficiency of the caching
+ * mechanism.
+ */
+static int hits; /* Found in directory cache */
+static int misses; /* Sad, but not evil misses */
+static int nearmisses; /* Found under search path */
+static int bigmisses; /* Sought by itself */
+
+/* The cached contents of ".", the relative current directory. */
+static CachedDir *dot = NULL;
+/* The cached contents of the absolute current directory. */
+static CachedDir *cur = NULL;
+/* A fake path entry indicating we need to look for '.' last. */
+static CachedDir *dotLast = NULL;
+
+/*
+ * Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
+ * the system to find the file, we might as well have its mtime on record.
+ *
+ * XXX: If this is done way early, there's a chance other rules will have
+ * already updated the file, in which case we'll update it again. Generally,
+ * there won't be two rules to update a single file, so this should be ok,
+ * but...
+ */
+static HashTable mtimes;
+
+static HashTable lmtimes; /* same as mtimes but for lstat */
+
+
+static void OpenDirs_Remove(OpenDirs *, const char *);
+
+
+static CachedDir *
+CachedDir_New(const char *name)
+{
+ CachedDir *dir = bmake_malloc(sizeof *dir);
+
+ dir->name = bmake_strdup(name);
+ dir->refCount = 0;
+ dir->hits = 0;
+ HashSet_Init(&dir->files);
+
+#ifdef DEBUG_REFCNT
+ DEBUG2(DIR, "CachedDir %p new for \"%s\"\n", dir, dir->name);
+#endif
+
+ return dir;
+}
+
+static CachedDir *
+CachedDir_Ref(CachedDir *dir)
+{
+ dir->refCount++;
+
+#ifdef DEBUG_REFCNT
+ DEBUG3(DIR, "CachedDir %p ++ %d for \"%s\"\n",
+ dir, dir->refCount, dir->name);
+#endif
+
+ return dir;
+}
+
+static void
+CachedDir_Unref(CachedDir *dir)
+{
+ dir->refCount--;
+
+#ifdef DEBUG_REFCNT
+ DEBUG3(DIR, "CachedDir %p -- %d for \"%s\"\n",
+ dir, dir->refCount, dir->name);
+#endif
+
+ if (dir->refCount > 0)
+ return;
+
+#ifdef DEBUG_REFCNT
+ DEBUG2(DIR, "CachedDir %p free for \"%s\"\n", dir, dir->name);
+#endif
+
+ OpenDirs_Remove(&openDirs, dir->name);
+
+ free(dir->name);
+ HashSet_Done(&dir->files);
+ free(dir);
+}
+
+/* Update the value of the CachedDir variable, updating the reference counts. */
+static void
+CachedDir_Assign(CachedDir **var, CachedDir *dir)
+{
+ CachedDir *prev;
+
+ prev = *var;
+ *var = dir;
+ if (dir != NULL)
+ CachedDir_Ref(dir);
+ if (prev != NULL)
+ CachedDir_Unref(prev);
+}
+
static void
OpenDirs_Init(OpenDirs *odirs)
{
- odirs->list = Lst_New();
- HashTable_Init(&odirs->table);
+ Lst_Init(&odirs->list);
+ HashTable_Init(&odirs->table);
}
#ifdef CLEANUP
static void
OpenDirs_Done(OpenDirs *odirs)
{
- CachedDirListNode *ln = odirs->list->first;
- while (ln != NULL) {
- CachedDirListNode *next = ln->next;
- CachedDir *dir = ln->datum;
- Dir_Destroy(dir); /* removes the dir from odirs->list */
- ln = next;
- }
- Lst_Free(odirs->list);
- HashTable_Done(&odirs->table);
+ CachedDirListNode *ln = odirs->list.first;
+ DEBUG1(DIR, "OpenDirs_Done: %u entries to remove\n",
+ odirs->table.numEntries);
+ while (ln != NULL) {
+ CachedDirListNode *next = ln->next;
+ CachedDir *dir = ln->datum;
+ DEBUG2(DIR, "OpenDirs_Done: refCount %d for \"%s\"\n",
+ dir->refCount, dir->name);
+ CachedDir_Unref(dir); /* removes the dir from odirs->list */
+ ln = next;
+ }
+ Lst_Done(&odirs->list);
+ HashTable_Done(&odirs->table);
}
#endif
static CachedDir *
OpenDirs_Find(OpenDirs *odirs, const char *name)
{
- CachedDirListNode *ln = HashTable_FindValue(&odirs->table, name);
- return ln != NULL ? ln->datum : NULL;
+ CachedDirListNode *ln = HashTable_FindValue(&odirs->table, name);
+ return ln != NULL ? ln->datum : NULL;
}
static void
OpenDirs_Add(OpenDirs *odirs, CachedDir *cdir)
{
- if (HashTable_FindEntry(&odirs->table, cdir->name) != NULL)
- return;
- Lst_Append(odirs->list, cdir);
- HashTable_Set(&odirs->table, cdir->name, odirs->list->last);
+ if (HashTable_FindEntry(&odirs->table, cdir->name) != NULL)
+ return;
+ Lst_Append(&odirs->list, cdir);
+ HashTable_Set(&odirs->table, cdir->name, odirs->list.last);
}
static void
OpenDirs_Remove(OpenDirs *odirs, const char *name)
{
- HashEntry *he = HashTable_FindEntry(&odirs->table, name);
- CachedDirListNode *ln;
- if (he == NULL)
- return;
- ln = HashEntry_Get(he);
- HashTable_DeleteEntry(&odirs->table, he);
- Lst_Remove(odirs->list, ln);
+ HashEntry *he = HashTable_FindEntry(&odirs->table, name);
+ CachedDirListNode *ln;
+ if (he == NULL)
+ return;
+ ln = HashEntry_Get(he);
+ HashTable_DeleteEntry(&odirs->table, he);
+ Lst_Remove(&odirs->list, ln);
}
-static OpenDirs openDirs; /* all cached directories */
-
/*
- * Variables for gathering statistics on the efficiency of the caching
- * mechanism.
+ * Returns 0 and the result of stat(2) or lstat(2) in *out_cst,
+ * or -1 on error.
*/
-static int hits; /* Found in directory cache */
-static int misses; /* Sad, but not evil misses */
-static int nearmisses; /* Found under search path */
-static int bigmisses; /* Sought by itself */
-
-static CachedDir *dot; /* contents of current directory */
-static CachedDir *cur; /* contents of current directory, if not dot */
-static CachedDir *dotLast; /* a fake path entry indicating we need to
- * look for . last */
-
-/* Results of doing a last-resort stat in Dir_FindFile -- if we have to go to
- * the system to find the file, we might as well have its mtime on record.
- *
- * XXX: If this is done way early, there's a chance other rules will have
- * already updated the file, in which case we'll update it again. Generally,
- * there won't be two rules to update a single file, so this should be ok,
- * but... */
-static HashTable mtimes;
-
-static HashTable lmtimes; /* same as mtimes but for lstat */
-
-typedef enum CachedStatsFlags {
- CST_NONE = 0,
- CST_LSTAT = 1 << 0, /* call lstat(2) instead of stat(2) */
- CST_UPDATE = 1 << 1 /* ignore existing cached entry */
-} CachedStatsFlags;
-
-/* Returns 0 and the result of stat(2) or lstat(2) in *out_cst,
- * or -1 on error. */
static int
cached_stats(const char *pathname, struct cached_stat *out_cst,
CachedStatsFlags flags)
{
- HashTable *tbl = flags & CST_LSTAT ? &lmtimes : &mtimes;
- struct stat sys_st;
- struct cached_stat *cst;
- int rc;
-
- if (pathname == NULL || pathname[0] == '\0')
- return -1; /* This can happen in meta mode. */
-
- cst = HashTable_FindValue(tbl, pathname);
- if (cst != NULL && !(flags & CST_UPDATE)) {
- *out_cst = *cst;
- DIR_DEBUG2("Using cached time %s for %s\n",
- Targ_FmtTime(cst->cst_mtime), pathname);
- return 0;
- }
+ HashTable *tbl = flags & CST_LSTAT ? &lmtimes : &mtimes;
+ struct stat sys_st;
+ struct cached_stat *cst;
+ int rc;
+
+ if (pathname == NULL || pathname[0] == '\0')
+ return -1; /* This can happen in meta mode. */
+
+ cst = HashTable_FindValue(tbl, pathname);
+ if (cst != NULL && !(flags & CST_UPDATE)) {
+ *out_cst = *cst;
+ DEBUG2(DIR, "Using cached time %s for %s\n",
+ Targ_FmtTime(cst->cst_mtime), pathname);
+ return 0;
+ }
- rc = (flags & CST_LSTAT ? lstat : stat)(pathname, &sys_st);
- if (rc == -1)
- return -1; /* don't cache negative lookups */
+ rc = (flags & CST_LSTAT ? lstat : stat)(pathname, &sys_st);
+ if (rc == -1)
+ return -1; /* don't cache negative lookups */
- if (sys_st.st_mtime == 0)
- sys_st.st_mtime = 1; /* avoid confusion with missing file */
+ if (sys_st.st_mtime == 0)
+ sys_st.st_mtime = 1; /* avoid confusion with missing file */
- if (cst == NULL) {
- cst = bmake_malloc(sizeof *cst);
- HashTable_Set(tbl, pathname, cst);
- }
+ if (cst == NULL) {
+ cst = bmake_malloc(sizeof *cst);
+ HashTable_Set(tbl, pathname, cst);
+ }
- cst->cst_mtime = sys_st.st_mtime;
- cst->cst_mode = sys_st.st_mode;
+ cst->cst_mtime = sys_st.st_mtime;
+ cst->cst_mode = sys_st.st_mode;
- *out_cst = *cst;
- DIR_DEBUG2(" Caching %s for %s\n",
- Targ_FmtTime(sys_st.st_mtime), pathname);
+ *out_cst = *cst;
+ DEBUG2(DIR, " Caching %s for %s\n",
+ Targ_FmtTime(sys_st.st_mtime), pathname);
- return 0;
+ return 0;
}
int
cached_stat(const char *pathname, struct cached_stat *cst)
{
- return cached_stats(pathname, cst, CST_NONE);
+ return cached_stats(pathname, cst, CST_NONE);
}
int
cached_lstat(const char *pathname, struct cached_stat *cst)
{
- return cached_stats(pathname, cst, CST_LSTAT);
+ return cached_stats(pathname, cst, CST_LSTAT);
}
/* Initialize the directories module. */
void
Dir_Init(void)
{
- dirSearchPath = Lst_New();
- OpenDirs_Init(&openDirs);
- HashTable_Init(&mtimes);
- HashTable_Init(&lmtimes);
-}
-
-void
-Dir_InitDir(const char *cdname)
-{
- Dir_InitCur(cdname);
-
- dotLast = bmake_malloc(sizeof *dotLast);
- dotLast->refCount = 1;
- dotLast->hits = 0;
- dotLast->name = bmake_strdup(".DOTLAST");
- HashTable_Init(&dotLast->files);
+ OpenDirs_Init(&openDirs);
+ HashTable_Init(&mtimes);
+ HashTable_Init(&lmtimes);
+ CachedDir_Assign(&dotLast, CachedDir_New(".DOTLAST"));
}
/*
@@ -388,58 +486,40 @@ Dir_InitDir(const char *cdname)
void
Dir_InitCur(const char *cdname)
{
- CachedDir *dir;
-
- if (cdname == NULL)
- return;
-
- /*
- * Our build directory is not the same as our source directory.
- * Keep this one around too.
- */
- dir = Dir_AddDir(NULL, cdname);
- if (dir == NULL)
- return;
-
- /* XXX: Reference counting is wrong here.
- * If this function is called repeatedly with the same directory name,
- * its reference count increases each time even though the number of
- * actual references stays the same. */
-
- dir->refCount++;
- if (cur != NULL && cur != dir) {
+ CachedDir *dir;
+
+ if (cdname == NULL)
+ return;
+
/*
- * We've been here before, clean up.
+ * Our build directory is not the same as our source directory.
+ * Keep this one around too.
*/
- cur->refCount--;
- Dir_Destroy(cur);
- }
- cur = dir;
+ dir = Dir_AddDir(NULL, cdname);
+ if (dir == NULL)
+ return;
+
+ CachedDir_Assign(&cur, dir);
}
-/* (Re)initialize "dot" (current/object directory) path hash.
- * Some directories may be opened. */
+/*
+ * (Re)initialize "dot" (current/object directory) path hash.
+ * Some directories may be cached.
+ */
void
Dir_InitDot(void)
{
- if (dot != NULL) {
- /* Remove old entry from openDirs, but do not destroy. */
- OpenDirs_Remove(&openDirs, dot->name);
- }
-
- dot = Dir_AddDir(NULL, ".");
-
- if (dot == NULL) {
- Error("Cannot open `.' (%s)", strerror(errno));
- exit(1);
- }
-
- /*
- * We always need to have dot around, so we increment its reference count
- * to make sure it's not destroyed.
- */
- dot->refCount++;
- Dir_SetPATH(); /* initialize */
+ CachedDir *dir;
+
+ dir = Dir_AddDir(NULL, ".");
+ if (dir == NULL) {
+ Error("Cannot open `.' (%s)", strerror(errno));
+ exit(2); /* Not 1 so -q can distinguish error */
+ }
+
+ CachedDir_Assign(&dot, dir);
+
+ Dir_SetPATH(); /* initialize */
}
/* Clean up the directories module. */
@@ -447,18 +527,13 @@ void
Dir_End(void)
{
#ifdef CLEANUP
- if (cur) {
- cur->refCount--;
- Dir_Destroy(cur);
- }
- dot->refCount--;
- dotLast->refCount--;
- Dir_Destroy(dotLast);
- Dir_Destroy(dot);
- Dir_ClearPath(dirSearchPath);
- Lst_Free(dirSearchPath);
- OpenDirs_Done(&openDirs);
- HashTable_Done(&mtimes);
+ CachedDir_Assign(&cur, NULL);
+ CachedDir_Assign(&dot, NULL);
+ CachedDir_Assign(&dotLast, NULL);
+ SearchPath_Clear(&dirSearchPath);
+ OpenDirs_Done(&openDirs);
+ HashTable_Done(&mtimes);
+ HashTable_Done(&lmtimes);
#endif
}
@@ -470,44 +545,45 @@ Dir_End(void)
void
Dir_SetPATH(void)
{
- CachedDirListNode *ln;
- Boolean hasLastDot = FALSE; /* true if we should search dot last */
+ CachedDirListNode *ln;
+ Boolean seenDotLast = FALSE; /* true if we should search '.' last */
+
+ Var_Delete(".PATH", VAR_GLOBAL);
+
+ if ((ln = dirSearchPath.first) != NULL) {
+ CachedDir *dir = ln->datum;
+ if (dir == dotLast) {
+ seenDotLast = TRUE;
+ Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
+ }
+ }
+
+ if (!seenDotLast) {
+ if (dot != NULL)
+ Var_Append(".PATH", dot->name, VAR_GLOBAL);
+ if (cur != NULL)
+ Var_Append(".PATH", cur->name, VAR_GLOBAL);
+ }
- Var_Delete(".PATH", VAR_GLOBAL);
+ for (ln = dirSearchPath.first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ if (dir == dotLast)
+ continue;
+ if (dir == dot && seenDotLast)
+ continue;
+ Var_Append(".PATH", dir->name, VAR_GLOBAL);
+ }
- if ((ln = dirSearchPath->first) != NULL) {
- CachedDir *dir = ln->datum;
- if (dir == dotLast) {
- hasLastDot = TRUE;
- Var_Append(".PATH", dotLast->name, VAR_GLOBAL);
+ if (seenDotLast) {
+ if (dot != NULL)
+ Var_Append(".PATH", dot->name, VAR_GLOBAL);
+ if (cur != NULL)
+ Var_Append(".PATH", cur->name, VAR_GLOBAL);
}
- }
-
- if (!hasLastDot) {
- if (dot)
- Var_Append(".PATH", dot->name, VAR_GLOBAL);
- if (cur)
- Var_Append(".PATH", cur->name, VAR_GLOBAL);
- }
-
- for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- if (dir == dotLast)
- continue;
- if (dir == dot && hasLastDot)
- continue;
- Var_Append(".PATH", dir->name, VAR_GLOBAL);
- }
-
- if (hasLastDot) {
- if (dot)
- Var_Append(".PATH", dot->name, VAR_GLOBAL);
- if (cur)
- Var_Append(".PATH", cur->name, VAR_GLOBAL);
- }
}
-/* See if the given name has any wildcard characters in it and all braces and
+/*
+ * See if the given name has any wildcard characters in it and all braces and
* brackets are properly balanced.
*
* XXX: This code is not 100% correct ([^]] fails etc.). I really don't think
@@ -519,38 +595,39 @@ Dir_SetPATH(void)
Boolean
Dir_HasWildcards(const char *name)
{
- const char *p;
- Boolean wild = FALSE;
- int braces = 0, brackets = 0;
-
- for (p = name; *p != '\0'; p++) {
- switch (*p) {
- case '{':
- braces++;
- wild = TRUE;
- break;
- case '}':
- braces--;
- break;
- case '[':
- brackets++;
- wild = TRUE;
- break;
- case ']':
- brackets--;
- break;
- case '?':
- case '*':
- wild = TRUE;
- break;
- default:
- break;
+ const char *p;
+ Boolean wild = FALSE;
+ int braces = 0, brackets = 0;
+
+ for (p = name; *p != '\0'; p++) {
+ switch (*p) {
+ case '{':
+ braces++;
+ wild = TRUE;
+ break;
+ case '}':
+ braces--;
+ break;
+ case '[':
+ brackets++;
+ wild = TRUE;
+ break;
+ case ']':
+ brackets--;
+ break;
+ case '?':
+ case '*':
+ wild = TRUE;
+ break;
+ default:
+ break;
+ }
}
- }
- return wild && brackets == 0 && braces == 0;
+ return wild && brackets == 0 && braces == 0;
}
-/* See if any files match the pattern and add their names to the 'expansions'
+/*
+ * See if any files match the pattern and add their names to the 'expansions'
* list if they do.
*
* This is incomplete -- wildcards are only expanded in the final path
@@ -566,105 +643,114 @@ Dir_HasWildcards(const char *name)
static void
DirMatchFiles(const char *pattern, CachedDir *dir, StringList *expansions)
{
- const char *dirName = dir->name;
- Boolean isDot = dirName[0] == '.' && dirName[1] == '\0';
- HashIter hi;
-
- /* XXX: Iterating over all hash entries is inefficient. If the pattern
- * is a plain string without any wildcards, a direct lookup is faster. */
-
- HashIter_Init(&hi, &dir->files);
- while (HashIter_Next(&hi) != NULL) {
- const char *base = hi.entry->key;
-
- if (!Str_Match(base, pattern))
- continue;
+ const char *dirName = dir->name;
+ Boolean isDot = dirName[0] == '.' && dirName[1] == '\0';
+ HashIter hi;
/*
- * Follow the UNIX convention that dot files are only found if the
- * pattern begins with a dot. The pattern '.*' does not match '.' or
- * '..' since these are not included in the directory cache.
- *
- * This means that the pattern '[a-z.]*' does not find '.file', which
- * is consistent with bash, NetBSD sh and csh.
+ * XXX: Iterating over all hash entries is inefficient. If the
+ * pattern is a plain string without any wildcards, a direct lookup
+ * is faster.
*/
- if (base[0] == '.' && pattern[0] != '.')
- continue;
- {
- char *fullName = isDot
- ? bmake_strdup(base)
- : str_concat3(dirName, "/", base);
- Lst_Append(expansions, fullName);
+ HashIter_InitSet(&hi, &dir->files);
+ while (HashIter_Next(&hi) != NULL) {
+ const char *base = hi.entry->key;
+
+ if (!Str_Match(base, pattern))
+ continue;
+
+ /*
+ * Follow the UNIX convention that dot files are only found
+ * if the pattern begins with a dot. The pattern '.*' does
+ * not match '.' or '..' since these are not included in the
+ * directory cache.
+ *
+ * This means that the pattern '[a-z.]*' does not find
+ * '.file', which is consistent with bash, NetBSD sh and csh.
+ */
+ if (base[0] == '.' && pattern[0] != '.')
+ continue;
+
+ {
+ char *fullName = isDot
+ ? bmake_strdup(base)
+ : str_concat3(dirName, "/", base);
+ Lst_Append(expansions, fullName);
+ }
}
- }
}
-/* Find the next closing brace in the string, taking nested braces into
- * account. */
+/*
+ * Find the next closing brace in the string, taking nested braces into
+ * account.
+ */
static const char *
closing_brace(const char *p)
{
- int nest = 0;
- while (*p != '\0') {
- if (*p == '}' && nest == 0)
- break;
- if (*p == '{')
- nest++;
- if (*p == '}')
- nest--;
- p++;
- }
- return p;
+ int nest = 0;
+ while (*p != '\0') {
+ if (*p == '}' && nest == 0)
+ break;
+ if (*p == '{')
+ nest++;
+ if (*p == '}')
+ nest--;
+ p++;
+ }
+ return p;
}
-/* Find the next closing brace or comma in the string, taking nested braces
- * into account. */
+/*
+ * Find the next closing brace or comma in the string, taking nested braces
+ * into account.
+ */
static const char *
separator_comma(const char *p)
{
- int nest = 0;
- while (*p != '\0') {
- if ((*p == '}' || *p == ',') && nest == 0)
- break;
- if (*p == '{')
- nest++;
- if (*p == '}')
- nest--;
- p++;
- }
- return p;
+ int nest = 0;
+ while (*p != '\0') {
+ if ((*p == '}' || *p == ',') && nest == 0)
+ break;
+ if (*p == '{')
+ nest++;
+ if (*p == '}')
+ nest--;
+ p++;
+ }
+ return p;
}
static Boolean
contains_wildcard(const char *p)
{
- for (; *p != '\0'; p++) {
- switch (*p) {
- case '*':
- case '?':
- case '{':
- case '[':
- return TRUE;
+ for (; *p != '\0'; p++) {
+ switch (*p) {
+ case '*':
+ case '?':
+ case '{':
+ case '[':
+ return TRUE;
+ }
}
- }
- return FALSE;
+ return FALSE;
}
static char *
concat3(const char *a, size_t a_len, const char *b, size_t b_len,
const char *c, size_t c_len)
{
- size_t s_len = a_len + b_len + c_len;
- char *s = bmake_malloc(s_len + 1);
- memcpy(s, a, a_len);
- memcpy(s + a_len, b, b_len);
- memcpy(s + a_len + b_len, c, c_len);
- s[s_len] = '\0';
- return s;
+ size_t s_len = a_len + b_len + c_len;
+ char *s = bmake_malloc(s_len + 1);
+ memcpy(s, a, a_len);
+ memcpy(s + a_len, b, b_len);
+ memcpy(s + a_len + b_len, c, c_len);
+ s[s_len] = '\0';
+ return s;
}
-/* Expand curly braces like the C shell. Brace expansion by itself is purely
+/*
+ * Expand curly braces like the C shell. Brace expansion by itself is purely
* textual, the expansions are not looked up in the file system. But if an
* expanded word contains wildcard characters, it is expanded further,
* matching only the actually existing files.
@@ -683,42 +769,43 @@ static void
DirExpandCurly(const char *word, const char *brace, SearchPath *path,
StringList *expansions)
{
- const char *prefix, *middle, *piece, *middle_end, *suffix;
- size_t prefix_len, suffix_len;
-
- /* Split the word into prefix '{' middle '}' suffix. */
-
- middle = brace + 1;
- middle_end = closing_brace(middle);
- if (*middle_end == '\0') {
- Error("Unterminated {} clause \"%s\"", middle);
- return;
- }
-
- prefix = word;
- prefix_len = (size_t)(brace - prefix);
- suffix = middle_end + 1;
- suffix_len = strlen(suffix);
-
- /* Split the middle into pieces, separated by commas. */
-
- piece = middle;
- while (piece < middle_end + 1) {
- const char *piece_end = separator_comma(piece);
- size_t piece_len = (size_t)(piece_end - piece);
-
- char *file = concat3(prefix, prefix_len, piece, piece_len,
- suffix, suffix_len);
-
- if (contains_wildcard(file)) {
- Dir_Expand(file, path, expansions);
- free(file);
- } else {
- Lst_Append(expansions, file);
+ const char *prefix, *middle, *piece, *middle_end, *suffix;
+ size_t prefix_len, suffix_len;
+
+ /* Split the word into prefix '{' middle '}' suffix. */
+
+ middle = brace + 1;
+ middle_end = closing_brace(middle);
+ if (*middle_end == '\0') {
+ Error("Unterminated {} clause \"%s\"", middle);
+ return;
}
- piece = piece_end + 1; /* skip over the comma or closing brace */
- }
+ prefix = word;
+ prefix_len = (size_t)(brace - prefix);
+ suffix = middle_end + 1;
+ suffix_len = strlen(suffix);
+
+ /* Split the middle into pieces, separated by commas. */
+
+ piece = middle;
+ while (piece < middle_end + 1) {
+ const char *piece_end = separator_comma(piece);
+ size_t piece_len = (size_t)(piece_end - piece);
+
+ char *file = concat3(prefix, prefix_len, piece, piece_len,
+ suffix, suffix_len);
+
+ if (contains_wildcard(file)) {
+ Dir_Expand(file, path, expansions);
+ free(file);
+ } else {
+ Lst_Append(expansions, file);
+ }
+
+ /* skip over the comma or closing brace */
+ piece = piece_end + 1;
+ }
}
@@ -726,27 +813,28 @@ DirExpandCurly(const char *word, const char *brace, SearchPath *path,
static void
DirExpandPath(const char *word, SearchPath *path, StringList *expansions)
{
- SearchPathNode *ln;
- for (ln = path->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- DirMatchFiles(word, dir, expansions);
- }
+ SearchPathNode *ln;
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ DirMatchFiles(word, dir, expansions);
+ }
}
static void
PrintExpansions(StringList *expansions)
{
- const char *sep = "";
- StringListNode *ln;
- for (ln = expansions->first; ln != NULL; ln = ln->next) {
- const char *word = ln->datum;
- debug_printf("%s%s", sep, word);
- sep = " ";
- }
- debug_printf("\n");
+ const char *sep = "";
+ StringListNode *ln;
+ for (ln = expansions->first; ln != NULL; ln = ln->next) {
+ const char *word = ln->datum;
+ debug_printf("%s%s", sep, word);
+ sep = " ";
+ }
+ debug_printf("\n");
}
-/* Expand the given word into a list of words by globbing it, looking in the
+/*
+ * Expand the given word into a list of words by globbing it, looking in the
* directories on the given search path.
*
* Input:
@@ -757,185 +845,214 @@ PrintExpansions(StringList *expansions)
void
Dir_Expand(const char *word, SearchPath *path, StringList *expansions)
{
- const char *cp;
+ const char *cp;
+
+ assert(path != NULL);
+ assert(expansions != NULL);
- assert(path != NULL);
- assert(expansions != NULL);
+ DEBUG1(DIR, "Expanding \"%s\"... ", word);
+
+ cp = strchr(word, '{');
+ if (cp != NULL) {
+ DirExpandCurly(word, cp, path, expansions);
+ goto done;
+ }
- DIR_DEBUG1("Expanding \"%s\"... ", word);
+ /* At this point, the word does not contain '{'. */
- cp = strchr(word, '{');
- if (cp) {
- DirExpandCurly(word, cp, path, expansions);
- } else {
cp = strchr(word, '/');
- if (cp) {
- /*
- * The thing has a directory component -- find the first wildcard
- * in the string.
- */
- for (cp = word; *cp; cp++) {
- if (*cp == '?' || *cp == '[' || *cp == '*') {
- break;
- }
- }
+ if (cp == NULL) {
+ /* The word has no directory component. */
+ /* First the files in dot. */
+ DirMatchFiles(word, dot, expansions);
- if (*cp != '\0') {
+ /* Then the files in every other directory on the path. */
+ DirExpandPath(word, path, expansions);
+ goto done;
+ }
+
+ /* At this point, the word has a directory component. */
+
+ /* Find the first wildcard in the word. */
+ for (cp = word; *cp != '\0'; cp++)
+ if (*cp == '?' || *cp == '[' || *cp == '*')
+ break;
+
+ if (*cp == '\0') {
/*
- * Back up to the start of the component
+ * No directory component and no wildcard at all -- this
+ * should never happen as in such a simple case there is no
+ * need to expand anything.
*/
- while (cp > word && *cp != '/') {
- cp--;
- }
- if (cp != word) {
- char *prefix = bmake_strsedup(word, cp + 1);
- /*
- * If the glob isn't in the first component, try and find
- * all the components up to the one with a wildcard.
- */
- char *dirpath = Dir_FindFile(prefix, path);
- free(prefix);
- /*
- * dirpath is null if can't find the leading component
- * XXX: Dir_FindFile won't find internal components.
- * i.e. if the path contains ../Etc/Object and we're
- * looking for Etc, it won't be found. Ah well.
- * Probably not important.
- */
- if (dirpath != NULL) {
- char *dp = &dirpath[strlen(dirpath) - 1];
- if (*dp == '/')
- *dp = '\0';
- path = Lst_New();
- (void)Dir_AddDir(path, dirpath);
- DirExpandPath(cp + 1, path, expansions);
- Lst_Free(path);
- }
- } else {
- /*
- * Start the search from the local directory
- */
- DirExpandPath(word, path, expansions);
- }
- } else {
+ DirExpandPath(word, path, expansions);
+ goto done;
+ }
+
+ /* Back up to the start of the component containing the wildcard. */
+ /* XXX: This handles '///' and '/' differently. */
+ while (cp > word && *cp != '/')
+ cp--;
+
+ if (cp == word) {
+ /* The first component contains the wildcard. */
+ /* Start the search from the local directory */
+ DirExpandPath(word, path, expansions);
+ goto done;
+ }
+
+ {
+ char *prefix = bmake_strsedup(word, cp + 1);
/*
- * Return the file -- this should never happen.
+ * The wildcard isn't in the first component.
+ * Find all the components up to the one with the wildcard.
*/
- DirExpandPath(word, path, expansions);
- }
- } else {
- /*
- * First the files in dot
- */
- DirMatchFiles(word, dot, expansions);
-
- /*
- * Then the files in every other directory on the path.
- */
- DirExpandPath(word, path, expansions);
+ /*
+ * XXX: Check the "the directory is added to the path" part.
+ * It is probably surprising that the directory before a
+ * wildcard gets added to the path.
+ */
+ /*
+ * XXX: Only the first match of the prefix in the path is
+ * taken, any others are ignored. The expectation may be
+ * that the pattern is expanded in the whole path.
+ */
+ char *dirpath = Dir_FindFile(prefix, path);
+ free(prefix);
+
+ /*
+ * dirpath is null if can't find the leading component
+ * XXX: Dir_FindFile won't find internal components.
+ * i.e. if the path contains ../Etc/Object and we're
+ * looking for Etc, it won't be found. Ah well.
+ * Probably not important.
+ * XXX: Check whether the above comment is still true.
+ */
+ if (dirpath != NULL) {
+ SearchPath *partPath;
+
+ char *end = &dirpath[strlen(dirpath) - 1];
+ /* XXX: What about multiple trailing slashes? */
+ if (*end == '/')
+ *end = '\0';
+
+ partPath = SearchPath_New();
+ (void)Dir_AddDir(partPath, dirpath);
+ DirExpandPath(cp + 1, partPath, expansions);
+ SearchPath_Free(partPath);
+ }
}
- }
- if (DEBUG(DIR))
- PrintExpansions(expansions);
+
+done:
+ if (DEBUG(DIR))
+ PrintExpansions(expansions);
}
-/* Find if the file with the given name exists in the given path.
- * Return the freshly allocated path to the file, or NULL. */
+/*
+ * Find if the file with the given name exists in the given path.
+ * Return the freshly allocated path to the file, or NULL.
+ */
static char *
DirLookup(CachedDir *dir, const char *base)
{
- char *file; /* the current filename to check */
+ char *file; /* the current filename to check */
- DIR_DEBUG1(" %s ...\n", dir->name);
+ DEBUG1(DIR, " %s ...\n", dir->name);
- if (HashTable_FindEntry(&dir->files, base) == NULL)
- return NULL;
+ if (!HashSet_Contains(&dir->files, base))
+ return NULL;
- file = str_concat3(dir->name, "/", base);
- DIR_DEBUG1(" returning %s\n", file);
- dir->hits++;
- hits++;
- return file;
+ file = str_concat3(dir->name, "/", base);
+ DEBUG1(DIR, " returning %s\n", file);
+ dir->hits++;
+ hits++;
+ return file;
}
-/* Find if the file with the given name exists in the given directory.
- * Return the freshly allocated path to the file, or NULL. */
+/*
+ * Find if the file with the given name exists in the given directory.
+ * Return the freshly allocated path to the file, or NULL.
+ */
static char *
DirLookupSubdir(CachedDir *dir, const char *name)
{
- struct cached_stat cst;
- char *file = dir == dot ? bmake_strdup(name)
- : str_concat3(dir->name, "/", name);
+ struct cached_stat cst;
+ char *file = dir == dot ? bmake_strdup(name)
+ : str_concat3(dir->name, "/", name);
- DIR_DEBUG1("checking %s ...\n", file);
+ DEBUG1(DIR, "checking %s ...\n", file);
- if (cached_stat(file, &cst) == 0) {
- nearmisses++;
- return file;
- }
- free(file);
- return NULL;
+ if (cached_stat(file, &cst) == 0) {
+ nearmisses++;
+ return file;
+ }
+ free(file);
+ return NULL;
}
-/* Find if the file with the given name exists in the given path.
+/*
+ * Find if the file with the given name exists in the given path.
* Return the freshly allocated path to the file, the empty string, or NULL.
* Returning the empty string means that the search should be terminated.
*/
static char *
DirLookupAbs(CachedDir *dir, const char *name, const char *cp)
{
- const char *dnp; /* pointer into dir->name */
- const char *np; /* pointer into name */
-
- DIR_DEBUG1(" %s ...\n", dir->name);
-
- /*
- * If the file has a leading path component and that component
- * exactly matches the entire name of the current search
- * directory, we can attempt another cache lookup. And if we don't
- * have a hit, we can safely assume the file does not exist at all.
- */
- for (dnp = dir->name, np = name; *dnp != '\0' && *dnp == *np; dnp++, np++)
- continue;
- if (*dnp != '\0' || np != cp - 1)
- return NULL;
+ const char *dnp; /* pointer into dir->name */
+ const char *np; /* pointer into name */
+
+ DEBUG1(DIR, " %s ...\n", dir->name);
- if (HashTable_FindEntry(&dir->files, cp) == NULL) {
- DIR_DEBUG0(" must be here but isn't -- returning\n");
- return bmake_strdup(""); /* to terminate the search */
- }
+ /*
+ * If the file has a leading path component and that component
+ * exactly matches the entire name of the current search
+ * directory, we can attempt another cache lookup. And if we don't
+ * have a hit, we can safely assume the file does not exist at all.
+ */
+ for (dnp = dir->name, np = name;
+ *dnp != '\0' && *dnp == *np; dnp++, np++)
+ continue;
+ if (*dnp != '\0' || np != cp - 1)
+ return NULL;
+
+ if (!HashSet_Contains(&dir->files, cp)) {
+ DEBUG0(DIR, " must be here but isn't -- returning\n");
+ return bmake_strdup(""); /* to terminate the search */
+ }
- dir->hits++;
- hits++;
- DIR_DEBUG1(" returning %s\n", name);
- return bmake_strdup(name);
+ dir->hits++;
+ hits++;
+ DEBUG1(DIR, " returning %s\n", name);
+ return bmake_strdup(name);
}
-/* Find the file given on "." or curdir.
- * Return the freshly allocated path to the file, or NULL. */
+/*
+ * Find the file given on "." or curdir.
+ * Return the freshly allocated path to the file, or NULL.
+ */
static char *
DirFindDot(const char *name, const char *base)
{
- if (HashTable_FindEntry(&dot->files, base) != NULL) {
- DIR_DEBUG0(" in '.'\n");
- hits++;
- dot->hits++;
- return bmake_strdup(name);
- }
+ if (HashSet_Contains(&dot->files, base)) {
+ DEBUG0(DIR, " in '.'\n");
+ hits++;
+ dot->hits++;
+ return bmake_strdup(name);
+ }
- if (cur != NULL && HashTable_FindEntry(&cur->files, base) != NULL) {
- DIR_DEBUG1(" in ${.CURDIR} = %s\n", cur->name);
- hits++;
- cur->hits++;
- return str_concat3(cur->name, "/", base);
- }
+ if (cur != NULL && HashSet_Contains(&cur->files, base)) {
+ DEBUG1(DIR, " in ${.CURDIR} = %s\n", cur->name);
+ hits++;
+ cur->hits++;
+ return str_concat3(cur->name, "/", base);
+ }
- return NULL;
+ return NULL;
}
-/* Find the file with the given name along the given search path.
+/*
+ * Find the file with the given name along the given search path.
*
* If the file is found in a directory that is not on the path
* already (either 'name' is absolute or it is a relative path
@@ -954,250 +1071,244 @@ DirFindDot(const char *name, const char *base)
char *
Dir_FindFile(const char *name, SearchPath *path)
{
- SearchPathNode *ln;
- char *file; /* the current filename to check */
- const char *base; /* Terminal name of file */
- Boolean hasLastDot = FALSE; /* true if we should search dot last */
- Boolean hasSlash; /* true if 'name' contains a / */
- struct cached_stat cst; /* Buffer for stat, if necessary */
- const char *trailing_dot = ".";
-
- /*
- * Find the final component of the name and note whether it has a
- * slash in it (the name, I mean)
- */
- base = strrchr(name, '/');
- if (base) {
- hasSlash = TRUE;
- base++;
- } else {
- hasSlash = FALSE;
- base = name;
- }
-
- DIR_DEBUG1("Searching for %s ...", name);
-
- if (path == NULL) {
- DIR_DEBUG0("couldn't open path, file not found\n");
- misses++;
- return NULL;
- }
+ char *file; /* the current filename to check */
+ Boolean seenDotLast = FALSE; /* true if we should search dot last */
+ struct cached_stat cst; /* Buffer for stat, if necessary */
+ const char *trailing_dot = ".";
+ const char *base = str_basename(name);
+
+ DEBUG1(DIR, "Searching for %s ...", name);
- if ((ln = path->first) != NULL) {
- CachedDir *dir = ln->datum;
- if (dir == dotLast) {
- hasLastDot = TRUE;
- DIR_DEBUG0("[dot last]...");
+ if (path == NULL) {
+ DEBUG0(DIR, "couldn't open path, file not found\n");
+ misses++;
+ return NULL;
+ }
+
+ if (path->first != NULL) {
+ CachedDir *dir = path->first->datum;
+ if (dir == dotLast) {
+ seenDotLast = TRUE;
+ DEBUG0(DIR, "[dot last]...");
+ }
}
- }
- DIR_DEBUG0("\n");
-
- /*
- * If there's no leading directory components or if the leading
- * directory component is exactly `./', consult the cached contents
- * of each of the directories on the search path.
- */
- if (!hasSlash || (base - name == 2 && *name == '.')) {
+ DEBUG0(DIR, "\n");
+
/*
- * We look through all the directories on the path seeking one which
- * contains the final component of the given name. If such a beast
- * is found, we concatenate the directory name and the final
- * component and return the resulting string. If we don't find any
- * such thing, we go on to phase two...
- *
- * No matter what, we always look for the file in the current
- * directory before anywhere else (unless we found the magic
- * DOTLAST path, in which case we search it last) and we *do not*
- * add the ./ to it if it exists.
- * This is so there are no conflicts between what the user
- * specifies (fish.c) and what pmake finds (./fish.c).
+ * If there's no leading directory components or if the leading
+ * directory component is exactly `./', consult the cached contents
+ * of each of the directories on the search path.
*/
- if (!hasLastDot && (file = DirFindDot(name, base)) != NULL)
- return file;
+ if (base == name || (base - name == 2 && *name == '.')) {
+ SearchPathNode *ln;
- for (; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- if (dir == dotLast)
- continue;
- if ((file = DirLookup(dir, base)) != NULL)
- return file;
+ /*
+ * We look through all the directories on the path seeking one
+ * which contains the final component of the given name. If
+ * such a beast is found, we concatenate the directory name
+ * and the final component and return the resulting string.
+ * If we don't find any such thing, we go on to phase two.
+ *
+ * No matter what, we always look for the file in the current
+ * directory before anywhere else (unless we found the magic
+ * DOTLAST path, in which case we search it last) and we *do
+ * not* add the ./ to it if it exists.
+ * This is so there are no conflicts between what the user
+ * specifies (fish.c) and what pmake finds (./fish.c).
+ */
+ if (!seenDotLast && (file = DirFindDot(name, base)) != NULL)
+ return file;
+
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ if (dir == dotLast)
+ continue;
+ if ((file = DirLookup(dir, base)) != NULL)
+ return file;
+ }
+
+ if (seenDotLast && (file = DirFindDot(name, base)) != NULL)
+ return file;
}
- if (hasLastDot && (file = DirFindDot(name, base)) != NULL)
- return file;
- }
-
- /*
- * We didn't find the file on any directory in the search path.
- * If the name doesn't contain a slash, that means it doesn't exist.
- * If it *does* contain a slash, however, there is still hope: it
- * could be in a subdirectory of one of the members of the search
- * path. (eg. /usr/include and sys/types.h. The above search would
- * fail to turn up types.h in /usr/include, but it *is* in
- * /usr/include/sys/types.h).
- * [ This no longer applies: If we find such a beast, we assume there
- * will be more (what else can we assume?) and add all but the last
- * component of the resulting name onto the search path (at the
- * end).]
- * This phase is only performed if the file is *not* absolute.
- */
- if (!hasSlash) {
- DIR_DEBUG0(" failed.\n");
- misses++;
- return NULL;
- }
+ /*
+ * We didn't find the file on any directory in the search path.
+ * If the name doesn't contain a slash, that means it doesn't exist.
+ * If it *does* contain a slash, however, there is still hope: it
+ * could be in a subdirectory of one of the members of the search
+ * path. (eg. /usr/include and sys/types.h. The above search would
+ * fail to turn up types.h in /usr/include, but it *is* in
+ * /usr/include/sys/types.h).
+ * [ This no longer applies: If we find such a beast, we assume there
+ * will be more (what else can we assume?) and add all but the last
+ * component of the resulting name onto the search path (at the
+ * end).]
+ * This phase is only performed if the file is *not* absolute.
+ */
+ if (base == name) {
+ DEBUG0(DIR, " failed.\n");
+ misses++;
+ return NULL;
+ }
- if (*base == '\0') {
- /* we were given a trailing "/" */
- base = trailing_dot;
- }
+ if (*base == '\0') {
+ /* we were given a trailing "/" */
+ base = trailing_dot;
+ }
- if (name[0] != '/') {
- Boolean checkedDot = FALSE;
+ if (name[0] != '/') {
+ SearchPathNode *ln;
+ Boolean checkedDot = FALSE;
+
+ DEBUG0(DIR, " Trying subdirectories...\n");
+
+ if (!seenDotLast) {
+ if (dot != NULL) {
+ checkedDot = TRUE;
+ if ((file = DirLookupSubdir(dot, name)) != NULL)
+ return file;
+ }
+ if (cur != NULL &&
+ (file = DirLookupSubdir(cur, name)) != NULL)
+ return file;
+ }
- DIR_DEBUG0(" Trying subdirectories...\n");
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ if (dir == dotLast)
+ continue;
+ if (dir == dot) {
+ if (checkedDot)
+ continue;
+ checkedDot = TRUE;
+ }
+ if ((file = DirLookupSubdir(dir, name)) != NULL)
+ return file;
+ }
- if (!hasLastDot) {
- if (dot) {
- checkedDot = TRUE;
- if ((file = DirLookupSubdir(dot, name)) != NULL)
- return file;
- }
- if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
- return file;
- }
+ if (seenDotLast) {
+ if (dot != NULL && !checkedDot) {
+ checkedDot = TRUE;
+ if ((file = DirLookupSubdir(dot, name)) != NULL)
+ return file;
+ }
+ if (cur != NULL &&
+ (file = DirLookupSubdir(cur, name)) != NULL)
+ return file;
+ }
- for (ln = path->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- if (dir == dotLast)
- continue;
- if (dir == dot) {
- if (checkedDot)
- continue;
- checkedDot = TRUE;
- }
- if ((file = DirLookupSubdir(dir, name)) != NULL)
- return file;
- }
+ if (checkedDot) {
+ /*
+ * Already checked by the given name, since . was in
+ * the path, so no point in proceeding.
+ */
+ DEBUG0(DIR, " Checked . already, returning NULL\n");
+ return NULL;
+ }
- if (hasLastDot) {
- if (dot && !checkedDot) {
- checkedDot = TRUE;
- if ((file = DirLookupSubdir(dot, name)) != NULL)
- return file;
- }
- if (cur && (file = DirLookupSubdir(cur, name)) != NULL)
- return file;
- }
+ } else { /* name[0] == '/' */
+ SearchPathNode *ln;
- if (checkedDot) {
- /*
- * Already checked by the given name, since . was in the path,
- * so no point in proceeding...
- */
- DIR_DEBUG0(" Checked . already, returning NULL\n");
- return NULL;
- }
+ /*
+ * For absolute names, compare directory path prefix against
+ * the the directory path of each member on the search path
+ * for an exact match. If we have an exact match on any member
+ * of the search path, use the cached contents of that member
+ * to lookup the final file component. If that lookup fails we
+ * can safely assume that the file does not exist at all.
+ * This is signified by DirLookupAbs() returning an empty
+ * string.
+ */
+ DEBUG0(DIR, " Trying exact path matches...\n");
+
+ if (!seenDotLast && cur != NULL &&
+ ((file = DirLookupAbs(cur, name, base)) != NULL)) {
+ if (file[0] == '\0') {
+ free(file);
+ return NULL;
+ }
+ return file;
+ }
- } else { /* name[0] == '/' */
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ if (dir == dotLast)
+ continue;
+ if ((file = DirLookupAbs(dir, name, base)) != NULL) {
+ if (file[0] == '\0') {
+ free(file);
+ return NULL;
+ }
+ return file;
+ }
+ }
+
+ if (seenDotLast && cur != NULL &&
+ ((file = DirLookupAbs(cur, name, base)) != NULL)) {
+ if (file[0] == '\0') {
+ free(file);
+ return NULL;
+ }
+ return file;
+ }
+ }
/*
- * For absolute names, compare directory path prefix against the
- * the directory path of each member on the search path for an exact
- * match. If we have an exact match on any member of the search path,
- * use the cached contents of that member to lookup the final file
- * component. If that lookup fails we can safely assume that the
- * file does not exist at all. This is signified by DirLookupAbs()
- * returning an empty string.
+ * Didn't find it that way, either. Sigh. Phase 3. Add its directory
+ * onto the search path in any case, just in case, then look for the
+ * thing in the hash table. If we find it, grand. We return a new
+ * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
+ * Note that if the directory holding the file doesn't exist, this
+ * will do an extra search of the final directory on the path. Unless
+ * something weird happens, this search won't succeed and life will
+ * be groovy.
+ *
+ * Sigh. We cannot add the directory onto the search path because
+ * of this amusing case:
+ * $(INSTALLDIR)/$(FILE): $(FILE)
+ *
+ * $(FILE) exists in $(INSTALLDIR) but not in the current one.
+ * When searching for $(FILE), we will find it in $(INSTALLDIR)
+ * b/c we added it here. This is not good...
*/
- DIR_DEBUG0(" Trying exact path matches...\n");
-
- if (!hasLastDot && cur &&
- ((file = DirLookupAbs(cur, name, base)) != NULL)) {
- if (file[0] == '\0') {
- free(file);
- return NULL;
- }
- return file;
- }
+#if 0
+ {
+ CachedDir *dir;
+ char *prefix;
- for (ln = path->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- if (dir == dotLast)
- continue;
- if ((file = DirLookupAbs(dir, name, base)) != NULL) {
- if (file[0] == '\0') {
- free(file);
- return NULL;
+ if (base == trailing_dot) {
+ base = strrchr(name, '/');
+ base++;
}
- return file;
- }
- }
+ prefix = bmake_strsedup(name, base - 1);
+ (void)Dir_AddDir(path, prefix);
+ free(prefix);
+
+ bigmisses++;
+ if (path->last == NULL)
+ return NULL;
- if (hasLastDot && cur &&
- ((file = DirLookupAbs(cur, name, base)) != NULL)) {
- if (file[0] == '\0') {
- free(file);
+ dir = path->last->datum;
+ if (HashSet_Contains(&dir->files, base))
+ return bmake_strdup(name);
return NULL;
- }
- return file;
}
- }
-
- /*
- * Didn't find it that way, either. Sigh. Phase 3. Add its directory
- * onto the search path in any case, just in case, then look for the
- * thing in the hash table. If we find it, grand. We return a new
- * copy of the name. Otherwise we sadly return a NULL pointer. Sigh.
- * Note that if the directory holding the file doesn't exist, this will
- * do an extra search of the final directory on the path. Unless something
- * weird happens, this search won't succeed and life will be groovy.
- *
- * Sigh. We cannot add the directory onto the search path because
- * of this amusing case:
- * $(INSTALLDIR)/$(FILE): $(FILE)
- *
- * $(FILE) exists in $(INSTALLDIR) but not in the current one.
- * When searching for $(FILE), we will find it in $(INSTALLDIR)
- * b/c we added it here. This is not good...
- */
-#if 0
- if (base == trailing_dot) {
- base = strrchr(name, '/');
- base++;
- }
- base[-1] = '\0';
- (void)Dir_AddDir(path, name);
- base[-1] = '/';
-
- bigmisses++;
- ln = Lst_Last(path);
- if (ln == NULL) {
- return NULL;
- } else {
- dir = LstNode_Datum(ln);
- }
-
- if (Hash_FindEntry(&dir->files, base) != NULL) {
- return bmake_strdup(name);
- } else {
- return NULL;
- }
#else
- DIR_DEBUG1(" Looking for \"%s\" ...\n", name);
+ DEBUG1(DIR, " Looking for \"%s\" ...\n", name);
- bigmisses++;
- if (cached_stat(name, &cst) == 0) {
- return bmake_strdup(name);
- }
+ bigmisses++;
+ if (cached_stat(name, &cst) == 0) {
+ return bmake_strdup(name);
+ }
- DIR_DEBUG0(" failed. Returning NULL\n");
- return NULL;
+ DEBUG0(DIR, " failed. Returning NULL\n");
+ return NULL;
#endif
}
-/* Search for a path starting at a given directory and then working our way
+/*
+ * Search for a path starting at a given directory and then working our way
* up towards the root.
*
* Input:
@@ -1210,346 +1321,376 @@ Dir_FindFile(const char *name, SearchPath *path)
char *
Dir_FindHereOrAbove(const char *here, const char *search_path)
{
- struct cached_stat cst;
- char *dirbase, *dirbase_end;
- char *try, *try_end;
-
- /* copy out our starting point */
- dirbase = bmake_strdup(here);
- dirbase_end = dirbase + strlen(dirbase);
-
- /* loop until we determine a result */
- for (;;) {
-
- /* try and stat(2) it ... */
- try = str_concat3(dirbase, "/", search_path);
- if (cached_stat(try, &cst) != -1) {
- /*
- * success! if we found a file, chop off
- * the filename so we return a directory.
- */
- if ((cst.cst_mode & S_IFMT) != S_IFDIR) {
- try_end = try + strlen(try);
- while (try_end > try && *try_end != '/')
- try_end--;
- if (try_end > try)
- *try_end = '\0'; /* chop! */
- }
-
- free(dirbase);
- return try;
+ struct cached_stat cst;
+ char *dirbase, *dirbase_end;
+ char *try, *try_end;
+
+ /* copy out our starting point */
+ dirbase = bmake_strdup(here);
+ dirbase_end = dirbase + strlen(dirbase);
+
+ /* loop until we determine a result */
+ for (;;) {
+
+ /* try and stat(2) it ... */
+ try = str_concat3(dirbase, "/", search_path);
+ if (cached_stat(try, &cst) != -1) {
+ /*
+ * success! if we found a file, chop off
+ * the filename so we return a directory.
+ */
+ if ((cst.cst_mode & S_IFMT) != S_IFDIR) {
+ try_end = try + strlen(try);
+ while (try_end > try && *try_end != '/')
+ try_end--;
+ if (try_end > try)
+ *try_end = '\0'; /* chop! */
+ }
+
+ free(dirbase);
+ return try;
+ }
+ free(try);
+
+ /*
+ * nope, we didn't find it. if we used up dirbase we've
+ * reached the root and failed.
+ */
+ if (dirbase_end == dirbase)
+ break; /* failed! */
+
+ /*
+ * truncate dirbase from the end to move up a dir
+ */
+ while (dirbase_end > dirbase && *dirbase_end != '/')
+ dirbase_end--;
+ *dirbase_end = '\0'; /* chop! */
}
- free(try);
+
+ free(dirbase);
+ return NULL;
+}
+
+/*
+ * This is an implied source, and it may have moved,
+ * see if we can find it via the current .PATH
+ */
+static char *
+ResolveMovedDepends(GNode *gn)
+{
+ char *fullName;
+
+ const char *base = str_basename(gn->name);
+ if (base == gn->name)
+ return NULL;
+
+ fullName = Dir_FindFile(base, Suff_FindPath(gn));
+ if (fullName == NULL)
+ return NULL;
/*
- * nope, we didn't find it. if we used up dirbase we've
- * reached the root and failed.
+ * Put the found file in gn->path so that we give that to the compiler.
*/
- if (dirbase_end == dirbase)
- break; /* failed! */
-
/*
- * truncate dirbase from the end to move up a dir
+ * XXX: Better just reset gn->path to NULL; updating it is already done
+ * by Dir_UpdateMTime.
*/
- while (dirbase_end > dirbase && *dirbase_end != '/')
- dirbase_end--;
- *dirbase_end = '\0'; /* chop! */
- }
+ gn->path = bmake_strdup(fullName);
+ if (!Job_RunTarget(".STALE", gn->fname))
+ fprintf(stdout, /* XXX: Why stdout? */
+ "%s: %s, %d: ignoring stale %s for %s, found %s\n",
+ progname, gn->fname, gn->lineno,
+ makeDependfile, gn->name, fullName);
+
+ return fullName;
+}
+
+static char *
+ResolveFullName(GNode *gn)
+{
+ char *fullName;
+
+ fullName = gn->path;
+ if (fullName == NULL && !(gn->type & OP_NOPATH)) {
+
+ fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
+
+ if (fullName == NULL && gn->flags & FROM_DEPEND &&
+ !Lst_IsEmpty(&gn->implicitParents))
+ fullName = ResolveMovedDepends(gn);
+
+ DEBUG2(DIR, "Found '%s' as '%s'\n",
+ gn->name, fullName != NULL ? fullName : "(not found)");
+ }
+
+ if (fullName == NULL)
+ fullName = bmake_strdup(gn->name);
+
+ /* XXX: Is every piece of memory freed as it should? */
- free(dirbase);
- return NULL;
+ return fullName;
}
-/* Search gn along dirSearchPath and store its modification time in gn->mtime.
+/*
+ * Search gn along dirSearchPath and store its modification time in gn->mtime.
* If no file is found, store 0 instead.
*
- * The found file is stored in gn->path, unless the node already had a path. */
+ * The found file is stored in gn->path, unless the node already had a path.
+ */
void
Dir_UpdateMTime(GNode *gn, Boolean recheck)
{
- char *fullName;
- struct cached_stat cst;
-
- if (gn->type & OP_ARCHV) {
- Arch_UpdateMTime(gn);
- return;
- }
-
- if (gn->type & OP_PHONY) {
- gn->mtime = 0;
- return;
- }
-
- if (gn->path == NULL) {
- if (gn->type & OP_NOPATH)
- fullName = NULL;
- else {
- fullName = Dir_FindFile(gn->name, Suff_FindPath(gn));
- if (fullName == NULL && gn->flags & FROM_DEPEND &&
- !Lst_IsEmpty(gn->implicitParents)) {
- char *cp;
-
- cp = strrchr(gn->name, '/');
- if (cp) {
- /*
- * This is an implied source, and it may have moved,
- * see if we can find it via the current .PATH
- */
- cp++;
-
- fullName = Dir_FindFile(cp, Suff_FindPath(gn));
- if (fullName) {
- /*
- * Put the found file in gn->path
- * so that we give that to the compiler.
- */
- gn->path = bmake_strdup(fullName);
- if (!Job_RunTarget(".STALE", gn->fname))
- fprintf(stdout,
- "%s: %s, %d: ignoring stale %s for %s, "
- "found %s\n", progname, gn->fname,
- gn->lineno,
- makeDependfile, gn->name, fullName);
- }
+ char *fullName;
+ struct cached_stat cst;
+
+ if (gn->type & OP_ARCHV) {
+ Arch_UpdateMTime(gn);
+ return;
+ }
+
+ if (gn->type & OP_PHONY) {
+ gn->mtime = 0;
+ return;
+ }
+
+ fullName = ResolveFullName(gn);
+
+ if (cached_stats(fullName, &cst, recheck ? CST_UPDATE : CST_NONE) < 0) {
+ if (gn->type & OP_MEMBER) {
+ if (fullName != gn->path)
+ free(fullName);
+ Arch_UpdateMemberMTime(gn);
+ return;
}
- }
- DIR_DEBUG2("Found '%s' as '%s'\n",
- gn->name, fullName ? fullName : "(not found)");
+
+ cst.cst_mtime = 0;
}
- } else {
- fullName = gn->path;
- }
- if (fullName == NULL)
- fullName = bmake_strdup(gn->name);
+ if (fullName != NULL && gn->path == NULL)
+ gn->path = fullName;
+ /* XXX: else free(fullName)? */
+
+ gn->mtime = cst.cst_mtime;
+}
+
+/*
+ * Read the directory and add it to the cache in openDirs.
+ * If a path is given, add the directory to that path as well.
+ */
+static CachedDir *
+CacheNewDir(const char *name, SearchPath *path)
+{
+ CachedDir *dir = NULL;
+ DIR *d;
+ struct dirent *dp;
- if (cached_stats(fullName, &cst, recheck ? CST_UPDATE : CST_NONE) < 0) {
- if (gn->type & OP_MEMBER) {
- if (fullName != gn->path)
- free(fullName);
- Arch_UpdateMemberMTime(gn);
- return;
+ if ((d = opendir(name)) == NULL) {
+ DEBUG1(DIR, "Caching %s ... not found\n", name);
+ return dir;
}
- cst.cst_mtime = 0;
- }
+ DEBUG1(DIR, "Caching %s ...\n", name);
- if (fullName != NULL && gn->path == NULL)
- gn->path = fullName;
+ dir = CachedDir_New(name);
+
+ while ((dp = readdir(d)) != NULL) {
+
+#if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
+ /*
+ * The sun directory library doesn't check for a 0 inode
+ * (0-inode slots just take up space), so we have to do
+ * it ourselves.
+ */
+ if (dp->d_fileno == 0)
+ continue;
+#endif /* sun && d_ino */
+
+ (void)HashSet_Add(&dir->files, dp->d_name);
+ }
+ (void)closedir(d);
+
+ OpenDirs_Add(&openDirs, dir);
+ if (path != NULL)
+ Lst_Append(path, CachedDir_Ref(dir));
- gn->mtime = cst.cst_mtime;
+ DEBUG1(DIR, "Caching %s done\n", name);
+ return dir;
}
-/* Read the list of filenames in the directory and store the result
- * in openDirectories.
+/*
+ * Read the list of filenames in the directory and store the result
+ * in openDirs.
*
* If a path is given, append the directory to that path.
*
* Input:
* path The path to which the directory should be
- * added, or NULL to only add the directory to
- * openDirectories
+ * added, or NULL to only add the directory to openDirs
* name The name of the directory to add.
* The name is not normalized in any way.
+ * Output:
+ * result If no path is given and the directory exists, the
+ * returned CachedDir has a reference count of 0. It
+ * must either be assigned to a variable using
+ * CachedDir_Assign or be appended to a SearchPath using
+ * Lst_Append and CachedDir_Ref.
*/
CachedDir *
Dir_AddDir(SearchPath *path, const char *name)
{
- CachedDir *dir = NULL; /* the added directory */
- DIR *d;
- struct dirent *dp;
- if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
- SearchPathNode *ln;
+ if (path != NULL && strcmp(name, ".DOTLAST") == 0) {
+ SearchPathNode *ln;
- /* XXX: Linear search gets slow with thousands of entries. */
- for (ln = path->first; ln != NULL; ln = ln->next) {
- CachedDir *pathDir = ln->datum;
- if (strcmp(pathDir->name, name) == 0)
- return pathDir;
- }
-
- dotLast->refCount++;
- Lst_Prepend(path, dotLast);
- }
+ /* XXX: Linear search gets slow with thousands of entries. */
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ CachedDir *pathDir = ln->datum;
+ if (strcmp(pathDir->name, name) == 0)
+ return pathDir;
+ }
- if (path != NULL)
- dir = OpenDirs_Find(&openDirs, name);
- if (dir != NULL) {
- if (Lst_FindDatum(path, dir) == NULL) {
- dir->refCount++;
- Lst_Append(path, dir);
+ Lst_Prepend(path, CachedDir_Ref(dotLast));
}
- return dir;
- }
-
- DIR_DEBUG1("Caching %s ...", name);
-
- if ((d = opendir(name)) != NULL) {
- dir = bmake_malloc(sizeof *dir);
- dir->name = bmake_strdup(name);
- dir->hits = 0;
- dir->refCount = 1;
- HashTable_Init(&dir->files);
- while ((dp = readdir(d)) != NULL) {
-#if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */
- /*
- * The sun directory library doesn't check for a 0 inode
- * (0-inode slots just take up space), so we have to do
- * it ourselves.
- */
- if (dp->d_fileno == 0) {
- continue;
- }
-#endif /* sun && d_ino */
- (void)HashTable_CreateEntry(&dir->files, dp->d_name, NULL);
+ if (path != NULL) {
+ /* XXX: Why is OpenDirs only checked if path != NULL? */
+ CachedDir *dir = OpenDirs_Find(&openDirs, name);
+ if (dir != NULL) {
+ if (Lst_FindDatum(path, dir) == NULL)
+ Lst_Append(path, CachedDir_Ref(dir));
+ return dir;
+ }
}
- (void)closedir(d);
- OpenDirs_Add(&openDirs, dir);
- if (path != NULL)
- Lst_Append(path, dir);
- }
- DIR_DEBUG0("done\n");
- return dir;
+
+ return CacheNewDir(name, path);
}
-/* Return a copy of dirSearchPath, incrementing the reference counts for
- * the contained directories. */
+/*
+ * Return a copy of dirSearchPath, incrementing the reference counts for
+ * the contained directories.
+ */
SearchPath *
Dir_CopyDirSearchPath(void)
{
- SearchPath *path = Lst_New();
- SearchPathNode *ln;
- for (ln = dirSearchPath->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- dir->refCount++;
- Lst_Append(path, dir);
- }
- return path;
+ SearchPath *path = SearchPath_New();
+ SearchPathNode *ln;
+ for (ln = dirSearchPath.first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ Lst_Append(path, CachedDir_Ref(dir));
+ }
+ return path;
}
-/*-
- *-----------------------------------------------------------------------
- * Dir_MakeFlags --
- * Make a string by taking all the directories in the given search
- * path and preceding them by the given flag. Used by the suffix
- * module to create variables for compilers based on suffix search
- * paths.
+/*
+ * Make a string by taking all the directories in the given search path and
+ * preceding them by the given flag. Used by the suffix module to create
+ * variables for compilers based on suffix search paths.
*
* Input:
* flag flag which should precede each directory
* path list of directories
*
* Results:
- * The string mentioned above. Note that there is no space between
- * the given flag and each directory. The empty string is returned if
- * Things don't go well.
- *
- * Side Effects:
- * None
- *-----------------------------------------------------------------------
+ * The string mentioned above. Note that there is no space between the
+ * given flag and each directory. The empty string is returned if things
+ * don't go well.
*/
char *
-Dir_MakeFlags(const char *flag, SearchPath *path)
+SearchPath_ToFlags(const char *flag, SearchPath *path)
{
- Buffer buf;
- SearchPathNode *ln;
+ Buffer buf;
+ SearchPathNode *ln;
- Buf_Init(&buf);
+ Buf_Init(&buf);
- if (path != NULL) {
- for (ln = path->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- Buf_AddStr(&buf, " ");
- Buf_AddStr(&buf, flag);
- Buf_AddStr(&buf, dir->name);
+ if (path != NULL) {
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ Buf_AddStr(&buf, " ");
+ Buf_AddStr(&buf, flag);
+ Buf_AddStr(&buf, dir->name);
+ }
}
- }
- return Buf_Destroy(&buf, FALSE);
+ return Buf_Destroy(&buf, FALSE);
}
-/* Nuke a directory descriptor, if possible. Callback procedure for the
- * suffixes module when destroying a search path.
- *
- * Input:
- * dirp The directory descriptor to nuke
- */
+/* Free the search path and all directories mentioned in it. */
void
-Dir_Destroy(void *dirp)
+SearchPath_Free(SearchPath *path)
{
- CachedDir *dir = dirp;
- dir->refCount--;
-
- if (dir->refCount == 0) {
- OpenDirs_Remove(&openDirs, dir->name);
+ SearchPathNode *ln;
- HashTable_Done(&dir->files);
- free(dir->name);
- free(dir);
- }
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ CachedDir_Unref(dir);
+ }
+ Lst_Free(path);
}
-/* Clear out all elements from the given search path.
- * The path is set to the empty list but is not destroyed. */
+/*
+ * Clear out all elements from the given search path.
+ * The path is set to the empty list but is not destroyed.
+ */
void
-Dir_ClearPath(SearchPath *path)
+SearchPath_Clear(SearchPath *path)
{
- while (!Lst_IsEmpty(path)) {
- CachedDir *dir = Lst_Dequeue(path);
- Dir_Destroy(dir);
- }
+ while (!Lst_IsEmpty(path)) {
+ CachedDir *dir = Lst_Dequeue(path);
+ CachedDir_Unref(dir);
+ }
}
-/* Concatenate two paths, adding the second to the end of the first,
- * skipping duplicates. */
+/*
+ * Concatenate two paths, adding the second to the end of the first,
+ * skipping duplicates.
+ */
void
-Dir_Concat(SearchPath *dst, SearchPath *src)
+SearchPath_AddAll(SearchPath *dst, SearchPath *src)
{
- SearchPathNode *ln;
+ SearchPathNode *ln;
- for (ln = src->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- if (Lst_FindDatum(dst, dir) == NULL) {
- dir->refCount++;
- Lst_Append(dst, dir);
+ for (ln = src->first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ if (Lst_FindDatum(dst, dir) == NULL)
+ Lst_Append(dst, CachedDir_Ref(dir));
}
- }
}
static int
percentage(int num, int den)
{
- return den != 0 ? num * 100 / den : 0;
+ return den != 0 ? num * 100 / den : 0;
}
/********** DEBUG INFO **********/
void
Dir_PrintDirectories(void)
{
- CachedDirListNode *ln;
-
- debug_printf("#*** Directory Cache:\n");
- debug_printf("# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
- hits, misses, nearmisses, bigmisses,
- percentage(hits, hits + bigmisses + nearmisses));
- debug_printf("# %-20s referenced\thits\n", "directory");
-
- for (ln = openDirs.list->first; ln != NULL; ln = ln->next) {
- CachedDir *dir = ln->datum;
- debug_printf("# %-20s %10d\t%4d\n", dir->name, dir->refCount,
- dir->hits);
- }
+ CachedDirListNode *ln;
+
+ debug_printf("#*** Directory Cache:\n");
+ debug_printf(
+ "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n",
+ hits, misses, nearmisses, bigmisses,
+ percentage(hits, hits + bigmisses + nearmisses));
+ debug_printf("# refs hits directory\n");
+
+ for (ln = openDirs.list.first; ln != NULL; ln = ln->next) {
+ CachedDir *dir = ln->datum;
+ debug_printf("# %4d %4d %s\n",
+ dir->refCount, dir->hits, dir->name);
+ }
}
void
-Dir_PrintPath(SearchPath *path)
+SearchPath_Print(SearchPath *path)
{
- SearchPathNode *node;
- for (node = path->first; node != NULL; node = node->next) {
- const CachedDir *dir = node->datum;
- debug_printf("%s ", dir->name);
- }
+ SearchPathNode *ln;
+
+ for (ln = path->first; ln != NULL; ln = ln->next) {
+ const CachedDir *dir = ln->datum;
+ debug_printf("%s ", dir->name);
+ }
}
diff --git a/dir.h b/dir.h
index d0badcd1dec7..9d9002b166be 100644
--- a/dir.h
+++ b/dir.h
@@ -1,4 +1,4 @@
-/* $NetBSD: dir.h,v 1.34 2020/11/14 19:24:24 rillig Exp $ */
+/* $NetBSD: dir.h,v 1.40 2020/12/01 19:28:32 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -72,27 +72,12 @@
* from: @(#)dir.h 8.1 (Berkeley) 6/6/93
*/
-#ifndef MAKE_DIR_H
-#define MAKE_DIR_H
+#ifndef MAKE_DIR_H
+#define MAKE_DIR_H
-/* A cache for the filenames in a directory. */
-typedef struct CachedDir {
- char *name; /* Name of directory, either absolute or
- * relative to the current directory.
- * The name is not normalized in any way,
- * that is, "." and "./." are different.
- *
- * Not sure what happens when .CURDIR is
- * assigned a new value; see Parse_DoVar. */
- int refCount; /* Number of SearchPaths with this directory */
- int hits; /* The number of times a file in this
- * directory has been found */
- HashTable files; /* Hash set of files in directory;
- * all values are NULL. */
-} CachedDir;
+typedef struct CachedDir CachedDir;
void Dir_Init(void);
-void Dir_InitDir(const char *);
void Dir_InitCur(const char *);
void Dir_InitDot(void);
void Dir_End(void);
@@ -103,18 +88,17 @@ char *Dir_FindFile(const char *, SearchPath *);
char *Dir_FindHereOrAbove(const char *, const char *);
void Dir_UpdateMTime(GNode *, Boolean);
CachedDir *Dir_AddDir(SearchPath *, const char *);
-char *Dir_MakeFlags(const char *, SearchPath *);
-void Dir_ClearPath(SearchPath *);
-void Dir_Concat(SearchPath *, SearchPath *);
+char *SearchPath_ToFlags(const char *, SearchPath *);
+void SearchPath_Clear(SearchPath *);
+void SearchPath_AddAll(SearchPath *, SearchPath *);
void Dir_PrintDirectories(void);
-void Dir_PrintPath(SearchPath *);
-void Dir_Destroy(void *);
+void SearchPath_Print(SearchPath *);
SearchPath *Dir_CopyDirSearchPath(void);
/* Stripped-down variant of struct stat. */
struct cached_stat {
- time_t cst_mtime;
- mode_t cst_mode;
+ time_t cst_mtime;
+ mode_t cst_mode;
};
int cached_lstat(const char *, struct cached_stat *);
diff --git a/enum.c b/enum.c
index cce986905411..f08b4edd978d 100755
--- a/enum.c
+++ b/enum.c
@@ -1,4 +1,4 @@
-/* $NetBSD: enum.c,v 1.12 2020/10/05 19:27:47 rillig Exp $ */
+/* $NetBSD: enum.c,v 1.14 2021/01/09 16:06:09 rillig Exp $ */
/*
Copyright (c) 2020 Roland Illig <rillig@NetBSD.org>
@@ -29,13 +29,15 @@
#include "make.h"
-MAKE_RCSID("$NetBSD: enum.c,v 1.12 2020/10/05 19:27:47 rillig Exp $");
+MAKE_RCSID("$NetBSD: enum.c,v 1.14 2021/01/09 16:06:09 rillig Exp $");
-/* Convert a bitset into a string representation, showing the names of the
+/*
+ * Convert a bitset into a string representation, showing the names of the
* individual bits.
*
* Optionally, shortcuts for groups of bits can be added. To have an effect,
- * they need to be listed before their individual bits. */
+ * they need to be listed before their individual bits.
+ */
const char *
Enum_FlagsToString(char *buf, size_t buf_size,
int value, const EnumToStringSpec *spec)
@@ -86,4 +88,5 @@ Enum_ValueToString(int value, const EnumToStringSpec *spec)
return spec->es_name;
}
abort(/* unknown enum value */);
+ /*NOTREACHED*/
}
diff --git a/enum.h b/enum.h
index ba7c7a826e97..6707214e8b0d 100755
--- a/enum.h
+++ b/enum.h
@@ -1,4 +1,4 @@
-/* $NetBSD: enum.h,v 1.12 2020/09/25 15:54:50 rillig Exp $ */
+/* $NetBSD: enum.h,v 1.14 2020/12/30 10:03:16 rillig Exp $ */
/*
Copyright (c) 2020 Roland Illig <rillig@NetBSD.org>
@@ -45,8 +45,10 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
/* For Enum_FlagsToString, the separator between flags. */
#define ENUM__SEP "|"
-/* Generate the string that joins all possible flags, to see how large the
- * buffer must be. */
+/*
+ * Generate the string that joins all possible flags, to see how large the
+ * buffer must be.
+ */
#define ENUM__JOIN_STR_1(v1) \
#v1
#define ENUM__JOIN_STR_2(v1, v2) \
@@ -107,8 +109,10 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
static const EnumToStringSpec typnam ## _ ## ToStringSpecs[] = specs; \
enum { typnam ## _ ## ToStringSize = sizeof joined }
-/* Declare the necessary data structures for calling Enum_FlagsToString
- * for an enum with 2 flags. */
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 2 flags.
+ */
#define ENUM_FLAGS_RTTI_2(typnam, v1, v2) \
ENUM__FLAGS_RTTI(typnam, \
ENUM__SPECS_2( \
@@ -118,8 +122,10 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
ENUM__JOIN_STR_1(v1), \
ENUM__JOIN_STR_1(v2)))
-/* Declare the necessary data structures for calling Enum_FlagsToString
- * for an enum with 3 flags. */
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 3 flags.
+ */
#define ENUM_FLAGS_RTTI_3(typnam, v1, v2, v3) \
ENUM__FLAGS_RTTI(typnam, \
ENUM__SPECS_2( \
@@ -129,8 +135,23 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
ENUM__JOIN_STR_2(v1, v2), \
ENUM__JOIN_STR_1(v3)))
-/* Declare the necessary data structures for calling Enum_FlagsToString
- * for an enum with 6 flags. */
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 4 flags.
+ */
+#define ENUM_FLAGS_RTTI_4(typnam, v1, v2, v3, v4) \
+ ENUM__FLAGS_RTTI(typnam, \
+ ENUM__SPECS_2( \
+ ENUM__SPEC_2(v1, v2), \
+ ENUM__SPEC_2(v3, v4)), \
+ ENUM__JOIN_2( \
+ ENUM__JOIN_STR_2(v1, v2), \
+ ENUM__JOIN_STR_2(v3, v4)))
+
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 6 flags.
+ */
#define ENUM_FLAGS_RTTI_6(typnam, v1, v2, v3, v4, v5, v6) \
ENUM__FLAGS_RTTI(typnam, \
ENUM__SPECS_2( \
@@ -140,8 +161,10 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
ENUM__JOIN_STR_4(v1, v2, v3, v4), \
ENUM__JOIN_STR_2(v5, v6)))
-/* Declare the necessary data structures for calling Enum_FlagsToString
- * for an enum with 8 flags. */
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 8 flags.
+ */
#define ENUM_FLAGS_RTTI_8(typnam, v1, v2, v3, v4, v5, v6, v7, v8) \
ENUM__FLAGS_RTTI(typnam, \
ENUM__SPECS_2( \
@@ -151,16 +174,20 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
ENUM__JOIN_STR_4(v1, v2, v3, v4), \
ENUM__JOIN_STR_4(v5, v6, v7, v8)))
-/* Declare the necessary data structures for calling Enum_ValueToString
- * for an enum with 8 constants. */
+/*
+ * Declare the necessary data structures for calling Enum_ValueToString
+ * for an enum with 8 constants.
+ */
#define ENUM_VALUE_RTTI_8(typnam, v1, v2, v3, v4, v5, v6, v7, v8) \
ENUM__VALUE_RTTI(typnam, \
ENUM__SPECS_2( \
ENUM__SPEC_4(v1, v2, v3, v4), \
ENUM__SPEC_4(v5, v6, v7, v8)))
-/* Declare the necessary data structures for calling Enum_FlagsToString
- * for an enum with 10 flags. */
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 10 flags.
+ */
#define ENUM_FLAGS_RTTI_10(typnam, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) \
ENUM__FLAGS_RTTI(typnam, \
ENUM__SPECS_2( \
@@ -170,8 +197,10 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
ENUM__JOIN_STR_8(v1, v2, v3, v4, v5, v6, v7, v8), \
ENUM__JOIN_STR_2(v9, v10)))
-/* Declare the necessary data structures for calling Enum_FlagsToString
- * for an enum with 31 flags. */
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 31 flags.
+ */
#define ENUM_FLAGS_RTTI_31(typnam, \
v01, v02, v03, v04, v05, v06, v07, v08, \
v09, v10, v11, v12, v13, v14, v15, v16, \
@@ -193,8 +222,10 @@ const char *Enum_ValueToString(int, const EnumToStringSpec *);
ENUM__JOIN_STR_2(v29, v30), \
ENUM__JOIN_STR_1(v31)))
-/* Declare the necessary data structures for calling Enum_FlagsToString
- * for an enum with 32 flags. */
+/*
+ * Declare the necessary data structures for calling Enum_FlagsToString
+ * for an enum with 32 flags.
+ */
#define ENUM_FLAGS_RTTI_32(typnam, \
v01, v02, v03, v04, v05, v06, v07, v08, \
v09, v10, v11, v12, v13, v14, v15, v16, \
diff --git a/filemon/filemon.h b/filemon/filemon.h
index fcf37a3ab54b..4bd11bbde608 100644
--- a/filemon/filemon.h
+++ b/filemon/filemon.h
@@ -1,4 +1,4 @@
-/* $NetBSD: filemon.h,v 1.3 2020/10/18 11:49:47 rillig Exp $ */
+/* $NetBSD: filemon.h,v 1.4 2020/11/29 09:27:40 rillig Exp $ */
/*-
* Copyright (c) 2019 The NetBSD Foundation, Inc.
@@ -30,7 +30,7 @@
*/
#ifndef MAKE_FILEMON_H
-#define MAKE_FILEMON_H
+#define MAKE_FILEMON_H
#include <sys/types.h>
@@ -50,4 +50,4 @@ int filemon_setpid_child(const struct filemon *, pid_t);
int filemon_readfd(const struct filemon *);
int filemon_process(struct filemon *);
-#endif /* MAKE_FILEMON_H */
+#endif /* MAKE_FILEMON_H */
diff --git a/filemon/filemon_dev.c b/filemon/filemon_dev.c
index afedb3c57e58..e4c583417b51 100644
--- a/filemon/filemon_dev.c
+++ b/filemon/filemon_dev.c
@@ -1,4 +1,4 @@
-/* $NetBSD: filemon_dev.c,v 1.4 2020/11/05 17:27:16 rillig Exp $ */
+/* $NetBSD: filemon_dev.c,v 1.6 2020/11/29 09:27:40 rillig Exp $ */
/*-
* Copyright (c) 2020 The NetBSD Foundation, Inc.
@@ -43,7 +43,7 @@
#endif
#ifndef _PATH_FILEMON
-#define _PATH_FILEMON "/dev/filemon"
+#define _PATH_FILEMON "/dev/filemon"
#endif
struct filemon {
@@ -127,7 +127,7 @@ filemon_close(struct filemon *F)
free(F);
/* Set errno and return -1 if anything went wrong. */
- if (error) {
+ if (error != 0) {
errno = error;
return -1;
}
diff --git a/filemon/filemon_ktrace.c b/filemon/filemon_ktrace.c
index 857e72e78028..699d66bad9f3 100644
--- a/filemon/filemon_ktrace.c
+++ b/filemon/filemon_ktrace.c
@@ -1,4 +1,4 @@
-/* $NetBSD: filemon_ktrace.c,v 1.4 2020/11/05 17:27:16 rillig Exp $ */
+/* $NetBSD: filemon_ktrace.c,v 1.12 2021/01/10 23:59:53 rillig Exp $ */
/*-
* Copyright (c) 2019 The NetBSD Foundation, Inc.
@@ -29,7 +29,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#define _KERNTYPES /* register_t */
+#define _KERNTYPES /* register_t */
#include "filemon.h"
@@ -90,9 +90,9 @@ static filemon_syscall_t *const filemon_syscalls[] = {
};
struct filemon {
- int ktrfd; /* kernel writes ktrace events here */
- FILE *in; /* we read ktrace events from here */
- FILE *out; /* we write filemon events to here */
+ int ktrfd; /* kernel writes ktrace events here */
+ FILE *in; /* we read ktrace events from here */
+ FILE *out; /* we write filemon events to here */
rb_tree_t active;
pid_t child;
@@ -130,6 +130,7 @@ struct filemon_state {
char *path[/*npath*/];
};
+/*ARGSUSED*/
static int
compare_filemon_states(void *cookie, const void *na, const void *nb)
{
@@ -147,6 +148,7 @@ compare_filemon_states(void *cookie, const void *na, const void *nb)
return 0;
}
+/*ARGSUSED*/
static int
compare_filemon_key(void *cookie, const void *n, const void *k)
{
@@ -225,7 +227,6 @@ filemon_open(void)
/* Success! */
return F;
-fail2: __unused
(void)fclose(F->in);
fail1: (void)close(ktrpipe[0]);
(void)close(ktrpipe[1]);
@@ -262,7 +263,7 @@ filemon_closefd(struct filemon *F)
F->out = NULL;
/* Set errno and return -1 if anything went wrong. */
- if (error) {
+ if (error != 0) {
errno = error;
return -1;
}
@@ -373,7 +374,7 @@ filemon_close(struct filemon *F)
free(F);
/* Set errno and return -1 if anything went wrong. */
- if (error) {
+ if (error != 0) {
errno = error;
return -1;
}
@@ -518,12 +519,12 @@ top: /* If the child has exited, nothing to do. */
return 0;
/* If we're waiting for input, read some. */
- if (F->resid) {
+ if (F->resid > 0) {
nread = fread(F->p, 1, F->resid, F->in);
if (nread == 0) {
- if (feof(F->in))
+ if (feof(F->in) != 0)
return 0;
- assert(ferror(F->in));
+ assert(ferror(F->in) != 0);
/*
* If interrupted or would block, there may be
* more events. Otherwise fail.
@@ -538,7 +539,7 @@ top: /* If the child has exited, nothing to do. */
assert(nread <= F->resid);
F->p += nread;
F->resid -= nread;
- if (F->resid) /* may be more events */
+ if (F->resid > 0) /* may be more events */
return 1;
}
@@ -582,7 +583,7 @@ top: /* If the child has exited, nothing to do. */
}
static struct filemon_state *
-syscall_enter(struct filemon *F,
+syscall_enter(
const struct filemon_key *key, const struct ktr_syscall *call,
unsigned npath,
void (*show)(struct filemon *, const struct filemon_state *,
@@ -618,7 +619,7 @@ show_paths(struct filemon *F, const struct filemon_state *S,
* Ignore it if it failed or yielded EJUSTRETURN (-2), or if
* we're not producing output.
*/
- if (ret->ktr_error && ret->ktr_error != -2)
+ if (ret->ktr_error != 0 && ret->ktr_error != -2)
return;
if (F->out == NULL)
return;
@@ -644,7 +645,7 @@ show_retval(struct filemon *F, const struct filemon_state *S,
* Ignore it if it failed or yielded EJUSTRETURN (-2), or if
* we're not producing output.
*/
- if (ret->ktr_error && ret->ktr_error != -2)
+ if (ret->ktr_error != 0 && ret->ktr_error != -2)
return;
if (F->out == NULL)
return;
@@ -664,7 +665,7 @@ static void
show_execve(struct filemon *F, const struct filemon_state *S,
const struct ktr_sysret *ret)
{
- return show_paths(F, S, ret, "E");
+ show_paths(F, S, ret, "E");
}
static void
@@ -752,18 +753,20 @@ show_rename(struct filemon *F, const struct filemon_state *S,
show_paths(F, S, ret, "M");
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_chdir(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
{
- return syscall_enter(F, key, call, 1, &show_chdir);
+ return syscall_enter(key, call, 1, &show_chdir);
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_execve(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
{
- return syscall_enter(F, key, call, 1, &show_execve);
+ return syscall_enter(key, call, 1, &show_execve);
}
static struct filemon_state *
@@ -773,7 +776,7 @@ filemon_sys_exit(struct filemon *F, const struct filemon_key *key,
const register_t *args = (const void *)&call[1];
int status = (int)args[0];
- if (F->out) {
+ if (F->out != NULL) {
fprintf(F->out, "X %jd %d\n", (intmax_t)key->pid, status);
if (key->pid == F->child) {
fprintf(F->out, "# Bye bye\n");
@@ -783,20 +786,23 @@ filemon_sys_exit(struct filemon *F, const struct filemon_key *key,
return NULL;
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_fork(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
{
- return syscall_enter(F, key, call, 0, &show_fork);
+ return syscall_enter(key, call, 0, &show_fork);
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_link(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
{
- return syscall_enter(F, key, call, 2, &show_link);
+ return syscall_enter(key, call, 2, &show_link);
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_open(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
@@ -809,15 +815,16 @@ filemon_sys_open(struct filemon *F, const struct filemon_key *key,
flags = (int)args[1];
if ((flags & O_RDWR) == O_RDWR)
- return syscall_enter(F, key, call, 1, &show_open_readwrite);
+ return syscall_enter(key, call, 1, &show_open_readwrite);
else if ((flags & O_WRONLY) == O_WRONLY)
- return syscall_enter(F, key, call, 1, &show_open_write);
+ return syscall_enter(key, call, 1, &show_open_write);
else if ((flags & O_RDONLY) == O_RDONLY)
- return syscall_enter(F, key, call, 1, &show_open_read);
+ return syscall_enter(key, call, 1, &show_open_read);
else
return NULL; /* XXX Do we care if no read or write? */
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_openat(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
@@ -832,47 +839,47 @@ filemon_sys_openat(struct filemon *F, const struct filemon_key *key,
if (fd == AT_CWD) {
if ((flags & O_RDWR) == O_RDWR)
- return syscall_enter(F, key, call, 1,
+ return syscall_enter(key, call, 1,
&show_open_readwrite);
else if ((flags & O_WRONLY) == O_WRONLY)
- return syscall_enter(F, key, call, 1,
- &show_open_write);
+ return syscall_enter(key, call, 1, &show_open_write);
else if ((flags & O_RDONLY) == O_RDONLY)
- return syscall_enter(F, key, call, 1, &show_open_read);
+ return syscall_enter(key, call, 1, &show_open_read);
else
return NULL;
} else {
if ((flags & O_RDWR) == O_RDWR)
- return syscall_enter(F, key, call, 1,
+ return syscall_enter(key, call, 1,
&show_openat_readwrite);
else if ((flags & O_WRONLY) == O_WRONLY)
- return syscall_enter(F, key, call, 1,
- &show_openat_write);
+ return syscall_enter(key, call, 1, &show_openat_write);
else if ((flags & O_RDONLY) == O_RDONLY)
- return syscall_enter(F, key, call, 1,
- &show_openat_read);
+ return syscall_enter(key, call, 1, &show_openat_read);
else
return NULL;
}
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_symlink(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
{
- return syscall_enter(F, key, call, 2, &show_symlink);
+ return syscall_enter(key, call, 2, &show_symlink);
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_unlink(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
{
- return syscall_enter(F, key, call, 1, &show_unlink);
+ return syscall_enter(key, call, 1, &show_unlink);
}
+/*ARGSUSED*/
static struct filemon_state *
filemon_sys_rename(struct filemon *F, const struct filemon_key *key,
const struct ktr_syscall *call)
{
- return syscall_enter(F, key, call, 2, &show_rename);
+ return syscall_enter(key, call, 2, &show_rename);
}
diff --git a/for.c b/for.c
index 8730ab5c157d..af55179dee8d 100644
--- a/for.c
+++ b/for.c
@@ -1,4 +1,4 @@
-/* $NetBSD: for.c,v 1.115 2020/11/07 21:04:43 rillig Exp $ */
+/* $NetBSD: for.c,v 1.134 2021/01/10 21:20:46 rillig Exp $ */
/*
* Copyright (c) 1992, The Regents of the University of California.
@@ -32,24 +32,22 @@
/*-
* Handling of .for/.endfor loops in a makefile.
*
- * For loops are of the form:
+ * For loops have the form:
*
- * .for <varname...> in <value...>
- * ...
- * .endfor
- *
- * When a .for line is parsed, all following lines are accumulated into a
- * buffer, up to but excluding the corresponding .endfor line. To find the
- * corresponding .endfor, the number of nested .for and .endfor directives
- * are counted.
+ * .for <varname...> in <value...>
+ * # the body
+ * .endfor
*
- * During parsing, any nested .for loops are just passed through; they get
- * handled recursively in For_Eval when the enclosing .for loop is evaluated
- * in For_Run.
+ * When a .for line is parsed, the following lines are copied to the body of
+ * the .for loop, until the corresponding .endfor line is reached. In this
+ * phase, the body is not yet evaluated. This also applies to any nested
+ * .for loops.
*
- * When the .for loop has been parsed completely, the variable expressions
- * for the iteration variables are replaced with expressions of the form
- * ${:Uvalue}, and then this modified body is "included" as a special file.
+ * After reaching the .endfor, the values from the .for line are grouped
+ * according to the number of variables. For each such group, the unexpanded
+ * body is scanned for variable expressions, and those that match the variable
+ * names are replaced with expressions of the form ${:U...} or $(:U...).
+ * After that, the body is treated like a file from an .include directive.
*
* Interface:
* For_Eval Evaluate the loop in the passed line.
@@ -60,29 +58,29 @@
#include "make.h"
/* "@(#)for.c 8.1 (Berkeley) 6/6/93" */
-MAKE_RCSID("$NetBSD: for.c,v 1.115 2020/11/07 21:04:43 rillig Exp $");
+MAKE_RCSID("$NetBSD: for.c,v 1.134 2021/01/10 21:20:46 rillig Exp $");
static int forLevel = 0; /* Nesting level */
/* One of the variables to the left of the "in" in a .for loop. */
typedef struct ForVar {
- char *name;
- size_t len;
+ char *name;
+ size_t nameLen;
} ForVar;
/*
* State of a for loop.
*/
typedef struct For {
- Buffer body; /* Unexpanded body of the loop */
- Vector /* of ForVar */ vars; /* Iteration variables */
- Words items; /* Substitution items */
- Buffer curBody; /* Expanded body of the current iteration */
- /* Is any of the names 1 character long? If so, when the variable values
- * are substituted, the parser must handle $V expressions as well, not
- * only ${V} and $(V). */
- Boolean short_var;
- unsigned int sub_next; /* Where to continue iterating */
+ Buffer body; /* Unexpanded body of the loop */
+ Vector /* of ForVar */ vars; /* Iteration variables */
+ Words items; /* Substitution items */
+ Buffer curBody; /* Expanded body of the current iteration */
+ /* Is any of the names 1 character long? If so, when the variable values
+ * are substituted, the parser must handle $V expressions as well, not
+ * only ${V} and $(V). */
+ Boolean short_var;
+ unsigned int sub_next; /* Where to continue iterating */
} For;
static For *accumFor; /* Loop being accumulated */
@@ -90,42 +88,43 @@ static For *accumFor; /* Loop being accumulated */
static void
ForAddVar(For *f, const char *name, size_t len)
{
- ForVar *var = Vector_Push(&f->vars);
- var->name = bmake_strldup(name, len);
- var->len = len;
+ ForVar *var = Vector_Push(&f->vars);
+ var->name = bmake_strldup(name, len);
+ var->nameLen = len;
}
static void
For_Free(For *f)
{
- Buf_Destroy(&f->body, TRUE);
+ Buf_Destroy(&f->body, TRUE);
- while (f->vars.len > 0) {
- ForVar *var = Vector_Pop(&f->vars);
- free(var->name);
- }
- Vector_Done(&f->vars);
+ while (f->vars.len > 0) {
+ ForVar *var = Vector_Pop(&f->vars);
+ free(var->name);
+ }
+ Vector_Done(&f->vars);
- Words_Free(f->items);
- Buf_Destroy(&f->curBody, TRUE);
+ Words_Free(f->items);
+ Buf_Destroy(&f->curBody, TRUE);
- free(f);
+ free(f);
}
static Boolean
IsFor(const char *p)
{
- return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
+ return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
}
static Boolean
IsEndfor(const char *p)
{
- return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
- (p[6] == '\0' || ch_isspace(p[6]));
+ return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
+ (p[6] == '\0' || ch_isspace(p[6]));
}
-/* Evaluate the for loop in the passed line. The line looks like this:
+/*
+ * Evaluate the for loop in the passed line. The line looks like this:
* .for <varname...> in <value...>
*
* Input:
@@ -139,98 +138,108 @@ IsEndfor(const char *p)
int
For_Eval(const char *line)
{
- For *f;
- const char *p;
+ For *f;
+ const char *p;
- p = line + 1; /* skip the '.' */
- cpp_skip_whitespace(&p);
+ p = line + 1; /* skip the '.' */
+ cpp_skip_whitespace(&p);
- if (!IsFor(p)) {
- if (IsEndfor(p)) {
- Parse_Error(PARSE_FATAL, "for-less endfor");
- return -1;
+ if (!IsFor(p)) {
+ if (IsEndfor(p)) {
+ Parse_Error(PARSE_FATAL, "for-less endfor");
+ return -1;
+ }
+ return 0;
+ }
+ p += 3;
+
+ /*
+ * we found a for loop, and now we are going to parse it.
+ */
+
+ f = bmake_malloc(sizeof *f);
+ Buf_Init(&f->body);
+ Vector_Init(&f->vars, sizeof(ForVar));
+ f->items.words = NULL;
+ f->items.freeIt = NULL;
+ Buf_Init(&f->curBody);
+ f->short_var = FALSE;
+ f->sub_next = 0;
+
+ /* Grab the variables. Terminate on "in". */
+ for (;;) {
+ size_t len;
+
+ cpp_skip_whitespace(&p);
+ if (*p == '\0') {
+ Parse_Error(PARSE_FATAL, "missing `in' in for");
+ For_Free(f);
+ return -1;
+ }
+
+ /*
+ * XXX: This allows arbitrary variable names;
+ * see directive-for.mk.
+ */
+ for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
+ continue;
+
+ if (len == 2 && p[0] == 'i' && p[1] == 'n') {
+ p += 2;
+ break;
+ }
+ if (len == 1)
+ f->short_var = TRUE;
+
+ ForAddVar(f, p, len);
+ p += len;
}
- return 0;
- }
- p += 3;
-
- /*
- * we found a for loop, and now we are going to parse it.
- */
-
- f = bmake_malloc(sizeof *f);
- Buf_Init(&f->body);
- Vector_Init(&f->vars, sizeof(ForVar));
- f->items.words = NULL;
- f->items.freeIt = NULL;
- Buf_Init(&f->curBody);
- f->short_var = FALSE;
- f->sub_next = 0;
-
- /* Grab the variables. Terminate on "in". */
- for (;;) {
- size_t len;
- cpp_skip_whitespace(&p);
- if (*p == '\0') {
- Parse_Error(PARSE_FATAL, "missing `in' in for");
- For_Free(f);
- return -1;
+ if (f->vars.len == 0) {
+ Parse_Error(PARSE_FATAL, "no iteration variables in for");
+ For_Free(f);
+ return -1;
}
- /* XXX: This allows arbitrary variable names; see directive-for.mk. */
- for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
- continue;
+ cpp_skip_whitespace(&p);
+
+ {
+ char *items;
+ if (Var_Subst(p, VAR_GLOBAL, VARE_WANTRES, &items) != VPR_OK) {
+ Parse_Error(PARSE_FATAL, "Error in .for loop items");
+ f->items.len = 0;
+ goto done;
+ }
+
+ f->items = Str_Words(items, FALSE);
+ free(items);
- if (len == 2 && p[0] == 'i' && p[1] == 'n') {
- p += 2;
- break;
+ if (f->items.len == 1 && f->items.words[0][0] == '\0')
+ f->items.len = 0; /* .for var in ${:U} */
}
- if (len == 1)
- f->short_var = TRUE;
-
- ForAddVar(f, p, len);
- p += len;
- }
-
- if (f->vars.len == 0) {
- Parse_Error(PARSE_FATAL, "no iteration variables in for");
- For_Free(f);
- return -1;
- }
-
- cpp_skip_whitespace(&p);
-
- {
- char *items;
- (void)Var_Subst(p, VAR_GLOBAL, VARE_WANTRES, &items);
- /* TODO: handle errors */
- f->items = Str_Words(items, FALSE);
- free(items);
-
- if (f->items.len == 1 && f->items.words[0][0] == '\0')
- f->items.len = 0; /* .for var in ${:U} */
- }
-
- {
- size_t nitems, nvars;
-
- if ((nitems = f->items.len) > 0 && nitems % (nvars = f->vars.len)) {
- Parse_Error(PARSE_FATAL,
- "Wrong number of words (%zu) in .for substitution list"
- " with %zu variables", nitems, nvars);
- /*
- * Return 'success' so that the body of the .for loop is
- * accumulated.
- * Remove all items so that the loop doesn't iterate.
- */
- f->items.len = 0;
+
+ {
+ size_t nitems, nvars;
+
+ if ((nitems = f->items.len) > 0 &&
+ nitems % (nvars = f->vars.len) != 0) {
+ Parse_Error(PARSE_FATAL,
+ "Wrong number of words (%u) in .for "
+ "substitution list with %u variables",
+ (unsigned)nitems, (unsigned)nvars);
+ /*
+ * Return 'success' so that the body of the .for loop
+ * is accumulated.
+ * Remove all items so that the loop doesn't iterate.
+ */
+ f->items.len = 0;
+ }
}
- }
- accumFor = f;
- forLevel = 1;
- return 1;
+done:
+ accumFor = f;
+ forLevel = 1;
+ return 1;
}
/*
@@ -240,240 +249,256 @@ For_Eval(const char *line)
Boolean
For_Accum(const char *line)
{
- const char *ptr = line;
-
- if (*ptr == '.') {
- ptr++;
- cpp_skip_whitespace(&ptr);
-
- if (IsEndfor(ptr)) {
- DEBUG1(FOR, "For: end for %d\n", forLevel);
- if (--forLevel <= 0)
- return FALSE;
- } else if (IsFor(ptr)) {
- forLevel++;
- DEBUG1(FOR, "For: new loop %d\n", forLevel);
+ const char *ptr = line;
+
+ if (*ptr == '.') {
+ ptr++;
+ cpp_skip_whitespace(&ptr);
+
+ if (IsEndfor(ptr)) {
+ DEBUG1(FOR, "For: end for %d\n", forLevel);
+ if (--forLevel <= 0)
+ return FALSE;
+ } else if (IsFor(ptr)) {
+ forLevel++;
+ DEBUG1(FOR, "For: new loop %d\n", forLevel);
+ }
}
- }
- Buf_AddStr(&accumFor->body, line);
- Buf_AddByte(&accumFor->body, '\n');
- return TRUE;
+ Buf_AddStr(&accumFor->body, line);
+ Buf_AddByte(&accumFor->body, '\n');
+ return TRUE;
}
static size_t
for_var_len(const char *var)
{
- char ch, var_start, var_end;
- int depth;
- size_t len;
-
- var_start = *var;
- if (var_start == '\0')
- /* just escape the $ */
- return 0;
-
- if (var_start == '(')
- var_end = ')';
- else if (var_start == '{')
- var_end = '}';
- else
- /* Single char variable */
- return 1;
+ char ch, var_start, var_end;
+ int depth;
+ size_t len;
- depth = 1;
- for (len = 1; (ch = var[len++]) != '\0';) {
- if (ch == var_start)
- depth++;
- else if (ch == var_end && --depth == 0)
- return len;
- }
+ var_start = *var;
+ if (var_start == '\0')
+ /* just escape the $ */
+ return 0;
+
+ if (var_start == '(')
+ var_end = ')';
+ else if (var_start == '{')
+ var_end = '}';
+ else
+ return 1; /* Single char variable */
+
+ depth = 1;
+ for (len = 1; (ch = var[len++]) != '\0';) {
+ if (ch == var_start)
+ depth++;
+ else if (ch == var_end && --depth == 0)
+ return len;
+ }
- /* Variable end not found, escape the $ */
- return 0;
+ /* Variable end not found, escape the $ */
+ return 0;
}
-/* The .for loop substitutes the items as ${:U<value>...}, which means
- * that characters that break this syntax must be backslash-escaped. */
+/*
+ * The .for loop substitutes the items as ${:U<value>...}, which means
+ * that characters that break this syntax must be backslash-escaped.
+ */
static Boolean
NeedsEscapes(const char *word, char endc)
{
- const char *p;
+ const char *p;
- for (p = word; *p != '\0'; p++) {
- if (*p == ':' || *p == '$' || *p == '\\' || *p == endc)
- return TRUE;
- }
- return FALSE;
+ for (p = word; *p != '\0'; p++) {
+ if (*p == ':' || *p == '$' || *p == '\\' || *p == endc)
+ return TRUE;
+ }
+ return FALSE;
}
-/* While expanding the body of a .for loop, write the item in the ${:U...}
+/*
+ * While expanding the body of a .for loop, write the item in the ${:U...}
* expression, escaping characters as needed.
*
- * The result is later unescaped by ApplyModifier_Defined. */
+ * The result is later unescaped by ApplyModifier_Defined.
+ */
static void
-Buf_AddEscaped(Buffer *cmds, const char *item, char ech)
+Buf_AddEscaped(Buffer *cmds, const char *item, char endc)
{
- char ch;
+ char ch;
- if (!NeedsEscapes(item, ech)) {
- Buf_AddStr(cmds, item);
- return;
- }
-
- /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
- * :U processing, see ApplyModifier_Defined. */
- while ((ch = *item++) != '\0') {
- if (ch == '$') {
- size_t len = for_var_len(item);
- if (len != 0) {
- Buf_AddBytes(cmds, item - 1, len + 1);
- item += len;
- continue;
- }
- Buf_AddByte(cmds, '\\');
- } else if (ch == ':' || ch == '\\' || ch == ech)
- Buf_AddByte(cmds, '\\');
- Buf_AddByte(cmds, ch);
- }
+ if (!NeedsEscapes(item, endc)) {
+ Buf_AddStr(cmds, item);
+ return;
+ }
+
+ /* Escape ':', '$', '\\' and 'endc' - these will be removed later by
+ * :U processing, see ApplyModifier_Defined. */
+ while ((ch = *item++) != '\0') {
+ if (ch == '$') {
+ size_t len = for_var_len(item);
+ if (len != 0) {
+ Buf_AddBytes(cmds, item - 1, len + 1);
+ item += len;
+ continue;
+ }
+ Buf_AddByte(cmds, '\\');
+ } else if (ch == ':' || ch == '\\' || ch == endc)
+ Buf_AddByte(cmds, '\\');
+ Buf_AddByte(cmds, ch);
+ }
}
-/* While expanding the body of a .for loop, replace expressions like
- * ${i}, ${i:...}, $(i) or $(i:...) with their ${:U...} expansion. */
+/*
+ * While expanding the body of a .for loop, replace the variable name of an
+ * expression like ${i} or ${i:...} or $(i) or $(i:...) with ":Uvalue".
+ */
static void
-SubstVarLong(For *f, const char **pp, const char **inout_mark, char ech)
+SubstVarLong(For *f, const char **pp, const char *bodyEnd, char endc,
+ const char **inout_mark)
{
- size_t i;
- const char *p = *pp;
-
- for (i = 0; i < f->vars.len; i++) {
- ForVar *forVar = Vector_Get(&f->vars, i);
- char *var = forVar->name;
- size_t vlen = forVar->len;
-
- /* XXX: undefined behavior for p if vlen is longer than p? */
- if (memcmp(p, var, vlen) != 0)
- continue;
- /* XXX: why test for backslash here? */
- if (p[vlen] != ':' && p[vlen] != ech && p[vlen] != '\\')
- continue;
-
- /* Found a variable match. Replace with :U<value> */
- Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
- Buf_AddStr(&f->curBody, ":U");
- Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], ech);
-
- p += vlen;
- *inout_mark = p;
- break;
- }
-
- *pp = p;
+ size_t i;
+ const char *p = *pp;
+
+ for (i = 0; i < f->vars.len; i++) {
+ ForVar *forVar = Vector_Get(&f->vars, i);
+ char *varname = forVar->name;
+ size_t varnameLen = forVar->nameLen;
+
+ if (varnameLen >= (size_t)(bodyEnd - p))
+ continue;
+ if (memcmp(p, varname, varnameLen) != 0)
+ continue;
+ /* XXX: why test for backslash here? */
+ if (p[varnameLen] != ':' && p[varnameLen] != endc &&
+ p[varnameLen] != '\\')
+ continue;
+
+ /*
+ * Found a variable match. Skip over the variable name and
+ * instead add ':U<value>' to the current body.
+ */
+ Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
+ Buf_AddStr(&f->curBody, ":U");
+ Buf_AddEscaped(&f->curBody,
+ f->items.words[f->sub_next + i], endc);
+
+ p += varnameLen;
+ *inout_mark = p;
+ *pp = p;
+ return;
+ }
}
-/* While expanding the body of a .for loop, replace single-character
- * variable expressions like $i with their ${:U...} expansion. */
+/*
+ * While expanding the body of a .for loop, replace single-character
+ * variable expressions like $i with their ${:U...} expansion.
+ */
static void
-SubstVarShort(For *f, char const ch, const char **pp, const char **inout_mark)
+SubstVarShort(For *f, const char *p, const char **inout_mark)
{
- const char *p = *pp;
- size_t i;
-
- /* Probably a single character name, ignore $$ and stupid ones. */
- if (!f->short_var || strchr("}):$", ch) != NULL) {
- p++;
- *pp = p;
+ const char ch = *p;
+ ForVar *vars;
+ size_t i;
+
+ /* Skip $$ and stupid ones. */
+ if (!f->short_var || strchr("}):$", ch) != NULL)
+ return;
+
+ vars = Vector_Get(&f->vars, 0);
+ for (i = 0; i < f->vars.len; i++) {
+ const char *varname = vars[i].name;
+ if (varname[0] == ch && varname[1] == '\0')
+ goto found;
+ }
return;
- }
-
- for (i = 0; i < f->vars.len; i++) {
- ForVar *var = Vector_Get(&f->vars, i);
- const char *varname = var->name;
- if (varname[0] != ch || varname[1] != '\0')
- continue;
- /* Found a variable match. Replace with ${:U<value>} */
- Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
+found:
+ /* Replace $<ch> with ${:U<value>} */
+ Buf_AddBytesBetween(&f->curBody, *inout_mark, p), *inout_mark = p + 1;
Buf_AddStr(&f->curBody, "{:U");
Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], '}');
Buf_AddByte(&f->curBody, '}');
-
- *inout_mark = ++p;
- break;
- }
-
- *pp = p;
}
/*
- * Scan the for loop body and replace references to the loop variables
- * with variable references that expand to the required text.
+ * Compute the body for the current iteration by copying the unexpanded body,
+ * replacing the expressions for the iteration variables on the way.
*
- * Using variable expansions ensures that the .for loop can't generate
+ * Using variable expressions ensures that the .for loop can't generate
* syntax, and that the later parsing will still see a variable.
- * We assume that the null variable will never be defined.
+ * This code assumes that the variable with the empty name will never be
+ * defined, see unit-tests/varname-empty.mk for more details.
*
* The detection of substitutions of the loop control variable is naive.
* Many of the modifiers use \ to escape $ (not $) so it is possible
* to contrive a makefile where an unwanted substitution happens.
*/
-static char *
-ForIterate(void *v_arg, size_t *out_len)
+static void
+ForSubstBody(For *f)
{
- For *f = v_arg;
- const char *p;
- const char *mark; /* where the last replacement left off */
- const char *body_end;
- char *cmds_str;
-
- if (f->sub_next + f->vars.len > f->items.len) {
- /* No more iterations */
- For_Free(f);
- return NULL;
- }
-
- Buf_Empty(&f->curBody);
-
- mark = Buf_GetAll(&f->body, NULL);
- body_end = mark + Buf_Len(&f->body);
- for (p = mark; (p = strchr(p, '$')) != NULL;) {
- char ch, ech;
- ch = *++p;
- if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
- p++;
- /* Check variable name against the .for loop variables */
- SubstVarLong(f, &p, &mark, ech);
- continue;
+ const char *p, *bodyEnd;
+ const char *mark; /* where the last replacement left off */
+
+ Buf_Empty(&f->curBody);
+
+ mark = f->body.data;
+ bodyEnd = f->body.data + f->body.len;
+ for (p = mark; (p = strchr(p, '$')) != NULL;) {
+ if (p[1] == '{' || p[1] == '(') {
+ p += 2;
+ SubstVarLong(f, &p, bodyEnd, p[-1] == '{' ? '}' : ')',
+ &mark);
+ } else if (p[1] != '\0') {
+ SubstVarShort(f, p + 1, &mark);
+ p += 2;
+ } else
+ break;
}
- if (ch == '\0')
- break;
- SubstVarShort(f, ch, &p, &mark);
- }
- Buf_AddBytesBetween(&f->curBody, mark, body_end);
+ Buf_AddBytesBetween(&f->curBody, mark, bodyEnd);
+}
- *out_len = Buf_Len(&f->curBody);
- cmds_str = Buf_GetAll(&f->curBody, NULL);
- DEBUG1(FOR, "For: loop body:\n%s", cmds_str);
+/*
+ * Compute the body for the current iteration by copying the unexpanded body,
+ * replacing the expressions for the iteration variables on the way.
+ */
+static char *
+ForReadMore(void *v_arg, size_t *out_len)
+{
+ For *f = v_arg;
+
+ if (f->sub_next == f->items.len) {
+ /* No more iterations */
+ For_Free(f);
+ return NULL;
+ }
- f->sub_next += f->vars.len;
+ ForSubstBody(f);
+ DEBUG1(FOR, "For: loop body:\n%s", f->curBody.data);
+ f->sub_next += (unsigned int)f->vars.len;
- return cmds_str;
+ *out_len = f->curBody.len;
+ return f->curBody.data;
}
-/* Run the for loop, imitating the actions of an include file. */
+/* Run the .for loop, imitating the actions of an include file. */
void
For_Run(int lineno)
{
- For *f = accumFor;
- accumFor = NULL;
-
- if (f->items.len == 0) {
- /* Nothing to expand - possibly due to an earlier syntax error. */
- For_Free(f);
- return;
- }
+ For *f = accumFor;
+ accumFor = NULL;
+
+ if (f->items.len == 0) {
+ /*
+ * Nothing to expand - possibly due to an earlier syntax
+ * error.
+ */
+ For_Free(f);
+ return;
+ }
- Parse_SetInput(NULL, lineno, -1, ForIterate, f);
+ Parse_SetInput(NULL, lineno, -1, ForReadMore, f);
}
diff --git a/hash.c b/hash.c
index a1e3ad3b45b4..82735f59c6fd 100644
--- a/hash.c
+++ b/hash.c
@@ -1,4 +1,4 @@
-/* $NetBSD: hash.c,v 1.57 2020/11/14 21:29:44 rillig Exp $ */
+/* $NetBSD: hash.c,v 1.60 2020/12/30 10:03:16 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -74,7 +74,7 @@
#include "make.h"
/* "@(#)hash.c 8.1 (Berkeley) 6/6/93" */
-MAKE_RCSID("$NetBSD: hash.c,v 1.57 2020/11/14 21:29:44 rillig Exp $");
+MAKE_RCSID("$NetBSD: hash.c,v 1.60 2020/12/30 10:03:16 rillig Exp $");
/*
* The ratio of # entries to # buckets at which we rebuild the table to
@@ -86,10 +86,13 @@ MAKE_RCSID("$NetBSD: hash.c,v 1.57 2020/11/14 21:29:44 rillig Exp $");
static unsigned int
hash(const char *key, size_t *out_keylen)
{
- unsigned int h = 0;
- const char *p = key;
- while (*p != '\0')
- h = (h << 5) - h + (unsigned char)*p++;
+ unsigned int h;
+ const char *p;
+
+ h = 0;
+ for (p = key; *p != '\0'; p++)
+ h = 31 * h + (unsigned char)*p;
+
if (out_keylen != NULL)
*out_keylen = (size_t)(p - key);
return h;
@@ -98,7 +101,7 @@ hash(const char *key, size_t *out_keylen)
unsigned int
Hash_Hash(const char *key)
{
- return hash(key, NULL);
+ return hash(key, NULL);
}
static HashEntry *
@@ -177,8 +180,10 @@ HashTable_FindValue(HashTable *t, const char *key)
return he != NULL ? he->value : NULL;
}
-/* Find the value corresponding to the key and the precomputed hash,
- * or return NULL. */
+/*
+ * Find the value corresponding to the key and the precomputed hash,
+ * or return NULL.
+ */
void *
HashTable_FindValueHash(HashTable *t, const char *key, unsigned int h)
{
@@ -186,8 +191,10 @@ HashTable_FindValueHash(HashTable *t, const char *key, unsigned int h)
return he != NULL ? he->value : NULL;
}
-/* Make the hash table larger. Any bucket numbers from the old table become
- * invalid; the hash codes stay valid though. */
+/*
+ * Make the hash table larger. Any bucket numbers from the old table become
+ * invalid; the hash codes stay valid though.
+ */
static void
HashTable_Enlarge(HashTable *t)
{
@@ -221,8 +228,10 @@ HashTable_Enlarge(HashTable *t)
t->maxchain = 0;
}
-/* Find or create an entry corresponding to the key.
- * Return in out_isNew whether a new entry has been created. */
+/*
+ * Find or create an entry corresponding to the key.
+ * Return in out_isNew whether a new entry has been created.
+ */
HashEntry *
HashTable_CreateEntry(HashTable *t, const char *key, Boolean *out_isNew)
{
@@ -288,8 +297,10 @@ HashIter_Init(HashIter *hi, HashTable *t)
hi->entry = NULL;
}
-/* Return the next entry in the hash table, or NULL if the end of the table
- * is reached. */
+/*
+ * Return the next entry in the hash table, or NULL if the end of the table
+ * is reached.
+ */
HashEntry *
HashIter_Next(HashIter *hi)
{
diff --git a/hash.h b/hash.h
index 30a8485bbd2e..b101137aa0ce 100644
--- a/hash.h
+++ b/hash.h
@@ -1,4 +1,4 @@
-/* $NetBSD: hash.h,v 1.33 2020/11/14 21:29:44 rillig Exp $ */
+/* $NetBSD: hash.h,v 1.38 2020/12/15 01:23:55 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -74,45 +74,50 @@
/* Hash tables with strings as keys and arbitrary pointers as values. */
-#ifndef MAKE_HASH_H
-#define MAKE_HASH_H
+#ifndef MAKE_HASH_H
+#define MAKE_HASH_H
/* A single key-value entry in the hash table. */
typedef struct HashEntry {
- struct HashEntry *next; /* Used to link together all the entries
+ struct HashEntry *next; /* Used to link together all the entries
* associated with the same bucket. */
- void *value;
- unsigned int key_hash; /* hash value of the key */
- char key[1]; /* key string, variable length */
+ void *value;
+ unsigned int key_hash; /* hash value of the key */
+ char key[1]; /* key string, variable length */
} HashEntry;
/* The hash table containing the entries. */
typedef struct HashTable {
- HashEntry **buckets; /* Pointers to HashEntry, one
+ HashEntry **buckets; /* Pointers to HashEntry, one
* for each bucket in the table. */
- unsigned int bucketsSize;
- unsigned int numEntries; /* Number of entries in the table. */
- unsigned int bucketsMask; /* Used to select the bucket for a hash. */
- unsigned int maxchain; /* max length of chain detected */
+ unsigned int bucketsSize;
+ unsigned int numEntries; /* Number of entries in the table. */
+ unsigned int bucketsMask; /* Used to select the bucket for a hash. */
+ unsigned int maxchain; /* max length of chain detected */
} HashTable;
/* State of an iteration over all entries in a table. */
typedef struct HashIter {
- HashTable *table; /* Table being searched. */
- unsigned int nextBucket; /* Next bucket to check (after current). */
- HashEntry *entry; /* Next entry to check in current bucket. */
+ HashTable *table; /* Table being searched. */
+ unsigned int nextBucket; /* Next bucket to check (after current). */
+ HashEntry *entry; /* Next entry to check in current bucket. */
} HashIter;
+/* A set of strings. */
+typedef struct HashSet {
+ HashTable tbl;
+} HashSet;
+
MAKE_INLINE void *
HashEntry_Get(HashEntry *h)
{
- return h->value;
+ return h->value;
}
MAKE_INLINE void
HashEntry_Set(HashEntry *h, void *datum)
{
- h->value = datum;
+ h->value = datum;
}
void HashTable_Init(HashTable *);
@@ -129,4 +134,37 @@ void HashTable_DebugStats(HashTable *, const char *);
void HashIter_Init(HashIter *, HashTable *);
HashEntry *HashIter_Next(HashIter *);
+MAKE_INLINE void
+HashSet_Init(HashSet *set)
+{
+ HashTable_Init(&set->tbl);
+}
+
+MAKE_INLINE void
+HashSet_Done(HashSet *set)
+{
+ HashTable_Done(&set->tbl);
+}
+
+MAKE_INLINE Boolean
+HashSet_Add(HashSet *set, const char *key)
+{
+ Boolean isNew;
+
+ (void)HashTable_CreateEntry(&set->tbl, key, &isNew);
+ return isNew;
+}
+
+MAKE_INLINE Boolean
+HashSet_Contains(HashSet *set, const char *key)
+{
+ return HashTable_FindEntry(&set->tbl, key) != NULL;
+}
+
+MAKE_INLINE void
+HashIter_InitSet(HashIter *hi, HashSet *set)
+{
+ HashIter_Init(hi, &set->tbl);
+}
+
#endif /* MAKE_HASH_H */
diff --git a/import.sh b/import.sh
new file mode 100755
index 000000000000..d4554a078951
--- /dev/null
+++ b/import.sh
@@ -0,0 +1,87 @@
+#!/bin/sh
+
+# Import bmake
+
+ECHO=
+GIT=${GIT:-git}
+
+# For consistency...
+Error() {
+ echo ERROR: ${1+"$@"} >&2
+ exit 1
+}
+
+Cd() {
+ [ $# -eq 1 ] || Error "Cd() takes a single parameter."
+ cd $1 || Error "cannot \"cd $1\" from $PWD"
+}
+
+# Call this function and then follow it by any specific import script additions
+option_parsing() {
+ local _shift=$#
+ # Parse command line options
+ while :
+ do
+ case "$1" in
+ *=*) eval "$1"; shift;;
+ --) shift; break;;
+ -a) TARBALL=$2; shift 2;;
+ -n) ECHO=echo; shift;;
+ -P) PR=$2; shift 2;;
+ -r) REVIEWER=$2; shift 2;;
+ -u) url=$2; shift 2;;
+ -h) echo "Usage:";
+ echo " "$0 '[-ahnPr] [TARBALL=] [PR=] [REVIEWER=]'
+ echo " "$0 '-a <filename> # (a)rchive'
+ echo " "$0 '-h # print usage'
+ echo " "$0 '-n # do not import, check only.'
+ echo " "$0 '-P <PR Number> # Use PR'
+ echo " "$0 '-r <reviewer(s) list> # (r)eviewed by'
+ echo " "$0 'PR=<PR Number>'
+ echo " "$0 'REVIEWER=<reviewer(s) list>'
+ exit 1;;
+ *) break;;
+ esac
+ done
+ return $(($_shift - $#))
+}
+
+###
+
+option_parsing "$@"
+shift $?
+
+TF=/tmp/.$USER.$$
+Cd `dirname $0`
+test -s ${TARBALL:-/dev/null} || Error need TARBALL
+here=`pwd`
+# thing should match what the TARBALL contains
+thing=`basename $here`
+
+case "$thing" in
+bmake) (cd .. && tar zxf $TARBALL);;
+*) Error "we should be in bmake";;
+esac
+
+VERSION=`grep '^_MAKE_VERSION' VERSION | sed 's,.*=[[:space:]]*,,'`
+
+rm -f *~
+mkdir -p ../tmp
+
+if [ -z "$ECHO" ]; then
+ # new files are handled automatically
+ # but we need to rm if needed
+ $GIT diff FILES | sed -n '/^-[^-]/s,^-,,p' > $TF.rm
+ test -s $TF.rm && xargs rm -f < $TF.rm
+ $GIT add -A
+ $GIT diff --staged | tee ../tmp/bmake-import.diff
+ echo "$GIT tag -a vendor/NetBSD/bmake/$VERSION" > ../tmp/bmake-post.sh
+ echo "After you commit, run $here/../tmp/bmake-post.sh"
+else
+ # FILES is kept sorted so we can determine what was added and deleted
+ $GIT diff FILES | sed -n '/^+[^+]/s,^+,,p' > $TF.add
+ $GIT diff FILES | sed -n '/^-[^-]/s,^-,,p' > $TF.rm
+ test -s $TF.rm && { echo Removing:; cat $TF.rm; }
+ test -s $TF.add && { echo Adding:; cat $TF.add; }
+ $GIT diff
+fi
diff --git a/job.c b/job.c
index ff0f1bcb8f4c..2a43a64e9749 100644
--- a/job.c
+++ b/job.c
@@ -1,4 +1,4 @@
-/* $NetBSD: job.c,v 1.326 2020/11/16 18:28:27 rillig Exp $ */
+/* $NetBSD: job.c,v 1.397 2021/01/10 23:59:53 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -156,9 +156,10 @@
#include "trace.h"
/* "@(#)job.c 8.2 (Berkeley) 3/19/94" */
-MAKE_RCSID("$NetBSD: job.c,v 1.326 2020/11/16 18:28:27 rillig Exp $");
+MAKE_RCSID("$NetBSD: job.c,v 1.397 2021/01/10 23:59:53 rillig Exp $");
-/* A shell defines how the commands are run. All commands for a target are
+/*
+ * A shell defines how the commands are run. All commands for a target are
* written into a single file, which is then given to the shell to execute
* the commands from it. The commands are written to the file using a few
* templates for echo control and error control.
@@ -174,12 +175,12 @@ MAKE_RCSID("$NetBSD: job.c,v 1.326 2020/11/16 18:28:27 rillig Exp $");
* it is filtered out using noPrint and noPrintLen.
*
* The error checking for individual commands is controlled using hasErrCtl,
- * errOnOrEcho, errOffOrExecIgnore and errExit.
+ * errOn, errOff and runChkTmpl.
*
- * If a shell doesn't have error control, errOnOrEcho becomes a printf template
- * for echoing the command, should echoing be on; errOffOrExecIgnore becomes
+ * If a shell doesn't have error control, echoTmpl becomes a printf template
+ * for echoing the command, should echoing be on; runIgnTmpl becomes
* another printf template for executing the command while ignoring the return
- * status. Finally errExit is a printf template for running the command and
+ * status. Finally runChkTmpl is a printf template for running the command and
* causing the shell to exit on error. If any of these strings are empty when
* hasErrCtl is FALSE, the command will be executed anyway as is, and if it
* causes an error, so be it. Any templates set up to echo the command will
@@ -193,64 +194,91 @@ MAKE_RCSID("$NetBSD: job.c,v 1.326 2020/11/16 18:28:27 rillig Exp $");
*/
typedef struct Shell {
- /* The name of the shell. For Bourne and C shells, this is used only to
- * find the shell description when used as the single source of a .SHELL
- * target. For user-defined shells, this is the full path of the shell. */
- const char *name;
+ /*
+ * The name of the shell. For Bourne and C shells, this is used only
+ * to find the shell description when used as the single source of a
+ * .SHELL target. For user-defined shells, this is the full path of
+ * the shell.
+ */
+ const char *name;
- Boolean hasEchoCtl; /* True if both echoOff and echoOn defined */
- const char *echoOff; /* command to turn off echo */
- const char *echoOn; /* command to turn it back on again */
- const char *noPrint; /* text to skip when printing output from
+ Boolean hasEchoCtl; /* whether both echoOff and echoOn are there */
+ const char *echoOff; /* command to turn echoing off */
+ const char *echoOn; /* command to turn echoing back on */
+ const char *noPrint; /* text to skip when printing output from the
* shell. This is usually the same as echoOff */
- size_t noPrintLen; /* length of noPrint command */
+ size_t noPrintLen; /* length of noPrint command */
+
+ Boolean hasErrCtl; /* whether error checking can be controlled
+ * for individual commands */
+ const char *errOn; /* command to turn on error checking */
+ const char *errOff; /* command to turn off error checking */
+
+ const char *echoTmpl; /* template to echo a command */
+ const char *runIgnTmpl; /* template to run a command
+ * without error checking */
+ const char *runChkTmpl; /* template to run a command
+ * with error checking */
+
+ /* string literal that results in a newline character when it appears
+ * outside of any 'quote' or "quote" characters */
+ const char *newline;
+ char commentChar; /* character used by shell for comment lines */
+
+ const char *echoFlag; /* shell flag to echo commands */
+ const char *errFlag; /* shell flag to exit on error */
+} Shell;
- Boolean hasErrCtl; /* set if can control error checking for
- * individual commands */
- /* XXX: split into errOn and echoCmd */
- const char *errOnOrEcho; /* template to turn on error checking */
- /* XXX: split into errOff and execIgnore */
- const char *errOffOrExecIgnore; /* template to turn off error checking */
- const char *errExit; /* template to use for testing exit code */
+typedef struct CommandFlags {
+ /* Whether to echo the command before running it. */
+ Boolean echo;
- /* string literal that results in a newline character when it appears
- * outside of any 'quote' or "quote" characters */
- const char *newline;
- char commentChar; /* character used by shell for comment lines */
+ /* Run the command even in -n or -N mode. */
+ Boolean always;
- /*
- * command-line flags
- */
- const char *echo; /* echo commands */
- const char *exit; /* exit on error */
-} Shell;
+ /*
+ * true if we turned error checking off before printing the command
+ * and need to turn it back on
+ */
+ Boolean ignerr;
+} CommandFlags;
+
+/*
+ * Write shell commands to a file.
+ *
+ * TODO: keep track of whether commands are echoed.
+ * TODO: keep track of whether error checking is active.
+ */
+typedef struct ShellWriter {
+ FILE *f;
+
+ /* we've sent 'set -x' */
+ Boolean xtraced;
+
+} ShellWriter;
/*
* error handling variables
*/
-static int errors = 0; /* number of errors reported */
+static int job_errors = 0; /* number of errors reported */
typedef enum AbortReason { /* why is the make aborting? */
- ABORT_NONE,
- ABORT_ERROR, /* Because of an error */
- ABORT_INTERRUPT, /* Because it was interrupted */
- ABORT_WAIT /* Waiting for jobs to finish */
+ ABORT_NONE,
+ ABORT_ERROR, /* Because of an error */
+ ABORT_INTERRUPT, /* Because it was interrupted */
+ ABORT_WAIT /* Waiting for jobs to finish */
} AbortReason;
static AbortReason aborting = ABORT_NONE;
-#define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
+#define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
/*
* this tracks the number of tokens currently "out" to build jobs.
*/
int jobTokensRunning = 0;
-/* The number of commands actually printed to the shell commands file for
- * the current job. Should this number be 0, no shell will be executed. */
-static int numCommands;
-
typedef enum JobStartResult {
- JOB_RUNNING, /* Job is running */
- JOB_ERROR, /* Error in starting the job */
- JOB_FINISHED /* The job is already finished */
+ JOB_RUNNING, /* Job is running */
+ JOB_ERROR, /* Error in starting the job */
+ JOB_FINISHED /* The job is already finished */
} JobStartResult;
/*
@@ -283,7 +311,7 @@ typedef enum JobStartResult {
#define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
#endif /* !DEFSHELL_INDEX */
-static Shell shells[] = {
+static Shell shells[] = {
#ifdef DEFSHELL_CUSTOM
/*
* An sh-compatible shell with a non-standard name.
@@ -292,93 +320,103 @@ static Shell shells[] = {
* non-portable features that might not be supplied by all
* sh-compatible shells.
*/
-{
- DEFSHELL_CUSTOM, /* .name */
- FALSE, /* .hasEchoCtl */
- "", /* .echoOff */
- "", /* .echoOn */
- "", /* .noPrint */
- 0, /* .noPrintLen */
- FALSE, /* .hasErrCtl */
- "echo \"%s\"\n", /* .errOnOrEcho */
- "%s\n", /* .errOffOrExecIgnore */
- "{ %s \n} || exit $?\n", /* .errExit */
- "'\n'", /* .newline */
- '#', /* .commentChar */
- "", /* .echo */
- "", /* .exit */
-},
+ {
+ DEFSHELL_CUSTOM, /* .name */
+ FALSE, /* .hasEchoCtl */
+ "", /* .echoOff */
+ "", /* .echoOn */
+ "", /* .noPrint */
+ 0, /* .noPrintLen */
+ FALSE, /* .hasErrCtl */
+ "", /* .errOn */
+ "", /* .errOff */
+ "echo \"%s\"\n", /* .echoTmpl */
+ "%s\n", /* .runIgnTmpl */
+ "{ %s \n} || exit $?\n", /* .runChkTmpl */
+ "'\n'", /* .newline */
+ '#', /* .commentChar */
+ "", /* .echoFlag */
+ "", /* .errFlag */
+ },
#endif /* DEFSHELL_CUSTOM */
/*
* SH description. Echo control is also possible and, under
* sun UNIX anyway, one can even control error checking.
*/
-{
- "sh", /* .name */
- FALSE, /* .hasEchoCtl */
- "", /* .echoOff */
- "", /* .echoOn */
- "", /* .noPrint */
- 0, /* .noPrintLen */
- FALSE, /* .hasErrCtl */
- "echo \"%s\"\n", /* .errOnOrEcho */
- "%s\n", /* .errOffOrExecIgnore */
- "{ %s \n} || exit $?\n", /* .errExit */
- "'\n'", /* .newline */
- '#', /* .commentChar*/
+ {
+ "sh", /* .name */
+ FALSE, /* .hasEchoCtl */
+ "", /* .echoOff */
+ "", /* .echoOn */
+ "", /* .noPrint */
+ 0, /* .noPrintLen */
+ FALSE, /* .hasErrCtl */
+ "", /* .errOn */
+ "", /* .errOff */
+ "echo \"%s\"\n", /* .echoTmpl */
+ "%s\n", /* .runIgnTmpl */
+ "{ %s \n} || exit $?\n", /* .runChkTmpl */
+ "'\n'", /* .newline */
+ '#', /* .commentChar*/
#if defined(MAKE_NATIVE) && defined(__NetBSD__)
- "q", /* .echo */
+ /* XXX: -q is not really echoFlag, it's more like noEchoInSysFlag. */
+ "q", /* .echoFlag */
#else
- "", /* .echo */
+ "", /* .echoFlag */
#endif
- "", /* .exit */
-},
+ "", /* .errFlag */
+ },
/*
* KSH description.
*/
-{
- "ksh", /* .name */
- TRUE, /* .hasEchoCtl */
- "set +v", /* .echoOff */
- "set -v", /* .echoOn */
- "set +v", /* .noPrint */
- 6, /* .noPrintLen */
- FALSE, /* .hasErrCtl */
- "echo \"%s\"\n", /* .errOnOrEcho */
- "%s\n", /* .errOffOrExecIgnore */
- "{ %s \n} || exit $?\n", /* .errExit */
- "'\n'", /* .newline */
- '#', /* .commentChar */
- "v", /* .echo */
- "", /* .exit */
-},
+ {
+ "ksh", /* .name */
+ TRUE, /* .hasEchoCtl */
+ "set +v", /* .echoOff */
+ "set -v", /* .echoOn */
+ "set +v", /* .noPrint */
+ 6, /* .noPrintLen */
+ FALSE, /* .hasErrCtl */
+ "", /* .errOn */
+ "", /* .errOff */
+ "echo \"%s\"\n", /* .echoTmpl */
+ "%s\n", /* .runIgnTmpl */
+ "{ %s \n} || exit $?\n", /* .runChkTmpl */
+ "'\n'", /* .newline */
+ '#', /* .commentChar */
+ "v", /* .echoFlag */
+ "", /* .errFlag */
+ },
/*
* CSH description. The csh can do echo control by playing
* with the setting of the 'echo' shell variable. Sadly,
* however, it is unable to do error control nicely.
*/
-{
- "csh", /* .name */
- TRUE, /* .hasEchoCtl */
- "unset verbose", /* .echoOff */
- "set verbose", /* .echoOn */
- "unset verbose", /* .noPrint */
- 13, /* .noPrintLen */
- FALSE, /* .hasErrCtl */
- "echo \"%s\"\n", /* .errOnOrEcho */
- /* XXX: Mismatch between errOn and execIgnore */
- "csh -c \"%s || exit 0\"\n", /* .errOffOrExecIgnore */
- "", /* .errExit */
- "'\\\n'", /* .newline */
- '#', /* .commentChar */
- "v", /* .echo */
- "e", /* .exit */
-}
+ {
+ "csh", /* .name */
+ TRUE, /* .hasEchoCtl */
+ "unset verbose", /* .echoOff */
+ "set verbose", /* .echoOn */
+ "unset verbose", /* .noPrint */
+ 13, /* .noPrintLen */
+ FALSE, /* .hasErrCtl */
+ "", /* .errOn */
+ "", /* .errOff */
+ "echo \"%s\"\n", /* .echoTmpl */
+ "csh -c \"%s || exit 0\"\n", /* .runIgnTmpl */
+ "", /* .runChkTmpl */
+ "'\\\n'", /* .newline */
+ '#', /* .commentChar */
+ "v", /* .echoFlag */
+ "e", /* .errFlag */
+ }
};
-/* This is the shell to which we pass all commands in the Makefile.
- * It is set by the Job_ParseShell function. */
-static Shell *commandShell = &shells[DEFSHELL_INDEX];
+/*
+ * This is the shell to which we pass all commands in the Makefile.
+ * It is set by the Job_ParseShell function.
+ */
+static Shell *shell = &shells[DEFSHELL_INDEX];
const char *shellPath = NULL; /* full pathname of executable image */
const char *shellName = NULL; /* last component of shellPath */
char *shellErrFlag = NULL;
@@ -389,62 +427,82 @@ static Job *job_table; /* The structures that describe them */
static Job *job_table_end; /* job_table + maxJobs */
static unsigned int wantToken; /* we want a token */
static Boolean lurking_children = FALSE;
-static Boolean make_suspended = FALSE; /* Whether we've seen a SIGTSTP (etc) */
+static Boolean make_suspended = FALSE; /* Whether we've seen a SIGTSTP (etc) */
/*
* Set of descriptors of pipes connected to
* the output channels of children
*/
static struct pollfd *fds = NULL;
-static Job **jobfds = NULL;
-static nfds_t nfds = 0;
+static Job **allJobs = NULL;
+static nfds_t nJobs = 0;
static void watchfd(Job *);
static void clearfd(Job *);
-static int readyfd(Job *);
+static Boolean readyfd(Job *);
-static GNode *lastNode; /* The node for which output was most recently
- * produced. */
-static char *targPrefix = NULL; /* What we print at the start of TARG_FMT */
+static char *targPrefix = NULL; /* To identify a job change in the output. */
static Job tokenWaitJob; /* token wait pseudo-job */
static Job childExitJob; /* child exit pseudo-job */
-#define CHILD_EXIT "."
-#define DO_JOB_RESUME "R"
+#define CHILD_EXIT "."
+#define DO_JOB_RESUME "R"
-enum { npseudojobs = 2 }; /* number of pseudo-jobs */
-
-#define TARG_FMT "%s %s ---\n" /* Default format */
-#define MESSAGE(fp, gn) \
- if (opts.maxJobs != 1 && targPrefix && *targPrefix) \
- (void)fprintf(fp, TARG_FMT, targPrefix, gn->name)
+enum {
+ npseudojobs = 2 /* number of pseudo-jobs */
+};
static sigset_t caught_signals; /* Set of signals we handle */
static void JobDoOutput(Job *, Boolean);
-static void JobInterrupt(int, int) MAKE_ATTR_DEAD;
+static void JobInterrupt(Boolean, int) MAKE_ATTR_DEAD;
static void JobRestartJobs(void);
static void JobSigReset(void);
+static void
+SwitchOutputTo(GNode *gn)
+{
+ /* The node for which output was most recently produced. */
+ static GNode *lastNode = NULL;
+
+ if (gn == lastNode)
+ return;
+ lastNode = gn;
+
+ if (opts.maxJobs != 1 && targPrefix != NULL && targPrefix[0] != '\0')
+ (void)fprintf(stdout, "%s %s ---\n", targPrefix, gn->name);
+}
+
static unsigned
nfds_per_job(void)
{
#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
- if (useMeta)
- return 2;
+ if (useMeta)
+ return 2;
#endif
- return 1;
+ return 1;
+}
+
+void
+Job_FlagsToString(const Job *job, char *buf, size_t bufsize)
+{
+ snprintf(buf, bufsize, "%c%c%c",
+ job->ignerr ? 'i' : '-',
+ !job->echo ? 's' : '-',
+ job->special ? 'S' : '-');
}
static void
job_table_dump(const char *where)
{
- Job *job;
+ Job *job;
+ char flags[4];
- debug_printf("job table @ %s\n", where);
- for (job = job_table; job < job_table_end; job++) {
- debug_printf("job %d, status %d, flags %d, pid %d\n",
- (int)(job - job_table), job->status, job->flags, job->pid);
- }
+ debug_printf("job table @ %s\n", where);
+ for (job = job_table; job < job_table_end; job++) {
+ Job_FlagsToString(job, flags, sizeof flags);
+ debug_printf("job %d, status %d, flags %s, pid %d\n",
+ (int)(job - job_table), job->status, flags, job->pid);
+ }
}
/*
@@ -454,20 +512,20 @@ job_table_dump(const char *where)
static void
JobDeleteTarget(GNode *gn)
{
- const char *file;
-
- if (gn->type & OP_JOIN)
- return;
- if (gn->type & OP_PHONY)
- return;
- if (Targ_Precious(gn))
- return;
- if (opts.noExecute)
- return;
-
- file = GNode_Path(gn);
- if (eunlink(file) != -1)
- Error("*** %s removed", file);
+ const char *file;
+
+ if (gn->type & OP_JOIN)
+ return;
+ if (gn->type & OP_PHONY)
+ return;
+ if (Targ_Precious(gn))
+ return;
+ if (opts.noExecute)
+ return;
+
+ file = GNode_Path(gn);
+ if (eunlink(file) != -1)
+ Error("*** %s removed", file);
}
/*
@@ -476,7 +534,8 @@ JobDeleteTarget(GNode *gn)
* Signal lock routines to get exclusive access. Currently used to
* protect `jobs' and `stoppedJobs' list manipulations.
*/
-static void JobSigLock(sigset_t *omaskp)
+static void
+JobSigLock(sigset_t *omaskp)
{
if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) {
Punt("JobSigLock: sigprocmask: %s", strerror(errno));
@@ -484,7 +543,8 @@ static void JobSigLock(sigset_t *omaskp)
}
}
-static void JobSigUnlock(sigset_t *omaskp)
+static void
+JobSigUnlock(sigset_t *omaskp)
{
(void)sigprocmask(SIG_SETMASK, omaskp, NULL);
}
@@ -492,458 +552,499 @@ static void JobSigUnlock(sigset_t *omaskp)
static void
JobCreatePipe(Job *job, int minfd)
{
- int i, fd, flags;
- int pipe_fds[2];
-
- if (pipe(pipe_fds) == -1)
- Punt("Cannot create pipe: %s", strerror(errno));
-
- for (i = 0; i < 2; i++) {
- /* Avoid using low numbered fds */
- fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
- if (fd != -1) {
- close(pipe_fds[i]);
- pipe_fds[i] = fd;
+ int i, fd, flags;
+ int pipe_fds[2];
+
+ if (pipe(pipe_fds) == -1)
+ Punt("Cannot create pipe: %s", strerror(errno));
+
+ for (i = 0; i < 2; i++) {
+ /* Avoid using low numbered fds */
+ fd = fcntl(pipe_fds[i], F_DUPFD, minfd);
+ if (fd != -1) {
+ close(pipe_fds[i]);
+ pipe_fds[i] = fd;
+ }
}
- }
- job->inPipe = pipe_fds[0];
- job->outPipe = pipe_fds[1];
+ job->inPipe = pipe_fds[0];
+ job->outPipe = pipe_fds[1];
- /* Set close-on-exec flag for both */
- if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
- Punt("Cannot set close-on-exec: %s", strerror(errno));
- if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
- Punt("Cannot set close-on-exec: %s", strerror(errno));
+ /* Set close-on-exec flag for both */
+ if (fcntl(job->inPipe, F_SETFD, FD_CLOEXEC) == -1)
+ Punt("Cannot set close-on-exec: %s", strerror(errno));
+ if (fcntl(job->outPipe, F_SETFD, FD_CLOEXEC) == -1)
+ Punt("Cannot set close-on-exec: %s", strerror(errno));
- /*
- * We mark the input side of the pipe non-blocking; we poll(2) the
- * pipe when we're waiting for a job token, but we might lose the
- * race for the token when a new one becomes available, so the read
- * from the pipe should not block.
- */
- flags = fcntl(job->inPipe, F_GETFL, 0);
- if (flags == -1)
- Punt("Cannot get flags: %s", strerror(errno));
- flags |= O_NONBLOCK;
- if (fcntl(job->inPipe, F_SETFL, flags) == -1)
- Punt("Cannot set flags: %s", strerror(errno));
+ /*
+ * We mark the input side of the pipe non-blocking; we poll(2) the
+ * pipe when we're waiting for a job token, but we might lose the
+ * race for the token when a new one becomes available, so the read
+ * from the pipe should not block.
+ */
+ flags = fcntl(job->inPipe, F_GETFL, 0);
+ if (flags == -1)
+ Punt("Cannot get flags: %s", strerror(errno));
+ flags |= O_NONBLOCK;
+ if (fcntl(job->inPipe, F_SETFL, flags) == -1)
+ Punt("Cannot set flags: %s", strerror(errno));
}
/* Pass the signal to each running job. */
static void
JobCondPassSig(int signo)
{
- Job *job;
+ Job *job;
- DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
+ DEBUG1(JOB, "JobCondPassSig(%d) called.\n", signo);
- for (job = job_table; job < job_table_end; job++) {
- if (job->status != JOB_ST_RUNNING)
- continue;
- DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
- signo, job->pid);
- KILLPG(job->pid, signo);
- }
+ for (job = job_table; job < job_table_end; job++) {
+ if (job->status != JOB_ST_RUNNING)
+ continue;
+ DEBUG2(JOB, "JobCondPassSig passing signal %d to child %d.\n",
+ signo, job->pid);
+ KILLPG(job->pid, signo);
+ }
}
-/* SIGCHLD handler.
+/*
+ * SIGCHLD handler.
*
- * Sends a token on the child exit pipe to wake us up from select()/poll(). */
+ * Sends a token on the child exit pipe to wake us up from select()/poll().
+ */
+/*ARGSUSED*/
static void
JobChildSig(int signo MAKE_ATTR_UNUSED)
{
- while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 && errno == EAGAIN)
- continue;
+ while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 &&
+ errno == EAGAIN)
+ continue;
}
/* Resume all stopped jobs. */
+/*ARGSUSED*/
static void
JobContinueSig(int signo MAKE_ATTR_UNUSED)
{
- /*
- * Defer sending SIGCONT to our stopped children until we return
- * from the signal handler.
- */
- while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
- errno == EAGAIN)
- continue;
+ /*
+ * Defer sending SIGCONT to our stopped children until we return
+ * from the signal handler.
+ */
+ while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 &&
+ errno == EAGAIN)
+ continue;
}
-/* Pass a signal on to all jobs, then resend to ourselves.
- * We die by the same signal. */
+/*
+ * Pass a signal on to all jobs, then resend to ourselves.
+ * We die by the same signal.
+ */
MAKE_ATTR_DEAD static void
JobPassSig_int(int signo)
{
- /* Run .INTERRUPT target then exit */
- JobInterrupt(TRUE, signo);
+ /* Run .INTERRUPT target then exit */
+ JobInterrupt(TRUE, signo);
}
-/* Pass a signal on to all jobs, then resend to ourselves.
- * We die by the same signal. */
+/*
+ * Pass a signal on to all jobs, then resend to ourselves.
+ * We die by the same signal.
+ */
MAKE_ATTR_DEAD static void
JobPassSig_term(int signo)
{
- /* Dont run .INTERRUPT target then exit */
- JobInterrupt(FALSE, signo);
+ /* Dont run .INTERRUPT target then exit */
+ JobInterrupt(FALSE, signo);
}
static void
JobPassSig_suspend(int signo)
{
- sigset_t nmask, omask;
- struct sigaction act;
+ sigset_t nmask, omask;
+ struct sigaction act;
- /* Suppress job started/continued messages */
- make_suspended = TRUE;
+ /* Suppress job started/continued messages */
+ make_suspended = TRUE;
- /* Pass the signal onto every job */
- JobCondPassSig(signo);
+ /* Pass the signal onto every job */
+ JobCondPassSig(signo);
- /*
- * Send ourselves the signal now we've given the message to everyone else.
- * Note we block everything else possible while we're getting the signal.
- * This ensures that all our jobs get continued when we wake up before
- * we take any other signal.
- */
- sigfillset(&nmask);
- sigdelset(&nmask, signo);
- (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
+ /*
+ * Send ourselves the signal now we've given the message to everyone
+ * else. Note we block everything else possible while we're getting
+ * the signal. This ensures that all our jobs get continued when we
+ * wake up before we take any other signal.
+ */
+ sigfillset(&nmask);
+ sigdelset(&nmask, signo);
+ (void)sigprocmask(SIG_SETMASK, &nmask, &omask);
- act.sa_handler = SIG_DFL;
- sigemptyset(&act.sa_mask);
- act.sa_flags = 0;
- (void)sigaction(signo, &act, NULL);
+ act.sa_handler = SIG_DFL;
+ sigemptyset(&act.sa_mask);
+ act.sa_flags = 0;
+ (void)sigaction(signo, &act, NULL);
- if (DEBUG(JOB))
- debug_printf("JobPassSig passing signal %d to self.\n", signo);
+ DEBUG1(JOB, "JobPassSig passing signal %d to self.\n", signo);
- (void)kill(getpid(), signo);
+ (void)kill(getpid(), signo);
- /*
- * We've been continued.
- *
- * A whole host of signals continue to happen!
- * SIGCHLD for any processes that actually suspended themselves.
- * SIGCHLD for any processes that exited while we were alseep.
- * The SIGCONT that actually caused us to wakeup.
- *
- * Since we defer passing the SIGCONT on to our children until
- * the main processing loop, we can be sure that all the SIGCHLD
- * events will have happened by then - and that the waitpid() will
- * collect the child 'suspended' events.
- * For correct sequencing we just need to ensure we process the
- * waitpid() before passing on the SIGCONT.
- *
- * In any case nothing else is needed here.
- */
+ /*
+ * We've been continued.
+ *
+ * A whole host of signals continue to happen!
+ * SIGCHLD for any processes that actually suspended themselves.
+ * SIGCHLD for any processes that exited while we were alseep.
+ * The SIGCONT that actually caused us to wakeup.
+ *
+ * Since we defer passing the SIGCONT on to our children until
+ * the main processing loop, we can be sure that all the SIGCHLD
+ * events will have happened by then - and that the waitpid() will
+ * collect the child 'suspended' events.
+ * For correct sequencing we just need to ensure we process the
+ * waitpid() before passing on the SIGCONT.
+ *
+ * In any case nothing else is needed here.
+ */
- /* Restore handler and signal mask */
- act.sa_handler = JobPassSig_suspend;
- (void)sigaction(signo, &act, NULL);
- (void)sigprocmask(SIG_SETMASK, &omask, NULL);
+ /* Restore handler and signal mask */
+ act.sa_handler = JobPassSig_suspend;
+ (void)sigaction(signo, &act, NULL);
+ (void)sigprocmask(SIG_SETMASK, &omask, NULL);
}
static Job *
JobFindPid(int pid, JobStatus status, Boolean isJobs)
{
- Job *job;
+ Job *job;
- for (job = job_table; job < job_table_end; job++) {
- if (job->status == status && job->pid == pid)
- return job;
- }
- if (DEBUG(JOB) && isJobs)
- job_table_dump("no pid");
- return NULL;
+ for (job = job_table; job < job_table_end; job++) {
+ if (job->status == status && job->pid == pid)
+ return job;
+ }
+ if (DEBUG(JOB) && isJobs)
+ job_table_dump("no pid");
+ return NULL;
}
/* Parse leading '@', '-' and '+', which control the exact execution mode. */
static void
-ParseRunOptions(
- char **pp,
- Boolean *out_shutUp, Boolean *out_errOff, Boolean *out_runAlways)
-{
- char *p = *pp;
- *out_shutUp = FALSE;
- *out_errOff = FALSE;
- *out_runAlways = FALSE;
-
- for (;;) {
- if (*p == '@')
- *out_shutUp = !DEBUG(LOUD);
- else if (*p == '-')
- *out_errOff = TRUE;
- else if (*p == '+')
- *out_runAlways = TRUE;
- else
- break;
- p++;
- }
+ParseCommandFlags(char **pp, CommandFlags *out_cmdFlags)
+{
+ char *p = *pp;
+ out_cmdFlags->echo = TRUE;
+ out_cmdFlags->ignerr = FALSE;
+ out_cmdFlags->always = FALSE;
+
+ for (;;) {
+ if (*p == '@')
+ out_cmdFlags->echo = DEBUG(LOUD);
+ else if (*p == '-')
+ out_cmdFlags->ignerr = TRUE;
+ else if (*p == '+')
+ out_cmdFlags->always = TRUE;
+ else
+ break;
+ p++;
+ }
- pp_skip_whitespace(&p);
+ pp_skip_whitespace(&p);
- *pp = p;
+ *pp = p;
}
/* Escape a string for a double-quoted string literal in sh, csh and ksh. */
static char *
EscapeShellDblQuot(const char *cmd)
{
- size_t i, j;
+ size_t i, j;
+
+ /* Worst that could happen is every char needs escaping. */
+ char *esc = bmake_malloc(strlen(cmd) * 2 + 1);
+ for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
+ if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' ||
+ cmd[i] == '"')
+ esc[j++] = '\\';
+ esc[j] = cmd[i];
+ }
+ esc[j] = '\0';
+
+ return esc;
+}
+
+static void
+ShellWriter_PrintFmt(ShellWriter *wr, const char *fmt, const char *arg)
+{
+ DEBUG1(JOB, fmt, arg);
- /* Worst that could happen is every char needs escaping. */
- char *esc = bmake_malloc(strlen(cmd) * 2 + 1);
- for (i = 0, j = 0; cmd[i] != '\0'; i++, j++) {
- if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' || cmd[i] == '"')
- esc[j++] = '\\';
- esc[j] = cmd[i];
- }
- esc[j] = '\0';
+ (void)fprintf(wr->f, fmt, arg);
+ /* XXX: Is flushing needed in any case, or only if f == stdout? */
+ (void)fflush(wr->f);
+}
- return esc;
+static void
+ShellWriter_Println(ShellWriter *wr, const char *line)
+{
+ ShellWriter_PrintFmt(wr, "%s\n", line);
}
static void
-JobPrintf(Job *job, const char *fmt, const char *arg)
+ShellWriter_EchoOff(ShellWriter *wr)
{
- if (DEBUG(JOB))
- debug_printf(fmt, arg);
+ if (shell->hasEchoCtl)
+ ShellWriter_Println(wr, shell->echoOff);
+}
- (void)fprintf(job->cmdFILE, fmt, arg);
- (void)fflush(job->cmdFILE);
+static void
+ShellWriter_EchoCmd(ShellWriter *wr, const char *escCmd)
+{
+ ShellWriter_PrintFmt(wr, shell->echoTmpl, escCmd);
}
static void
-JobPrintln(Job *job, const char *line)
+ShellWriter_EchoOn(ShellWriter *wr)
{
- JobPrintf(job, "%s\n", line);
+ if (shell->hasEchoCtl)
+ ShellWriter_Println(wr, shell->echoOn);
}
-/*-
- *-----------------------------------------------------------------------
- * JobPrintCommand --
- * Put out another command for the given job. If the command starts
- * with an @ or a - we process it specially. In the former case,
- * so long as the -s and -n flags weren't given to make, we stick
- * a shell-specific echoOff command in the script. In the latter,
- * we ignore errors for the entire job, unless the shell has error
- * control.
- * If the command is just "..." we take all future commands for this
- * job to be commands to be executed once the entire graph has been
- * made and return non-zero to signal that the end of the commands
- * was reached. These commands are later attached to the .END
- * node and executed by Job_End when all things are done.
- *
- * Side Effects:
- * If the command begins with a '-' and the shell has no error control,
- * the JOB_IGNERR flag is set in the job descriptor.
- * numCommands is incremented if the command is actually printed.
- *-----------------------------------------------------------------------
- */
static void
-JobPrintCommand(Job *job, char *cmd)
+ShellWriter_TraceOn(ShellWriter *wr)
{
- const char *const cmdp = cmd;
- Boolean noSpecials; /* true if we shouldn't worry about
- * inserting special commands into
- * the input stream. */
- Boolean shutUp; /* true if we put a no echo command
- * into the command file */
- Boolean errOff; /* true if we turned error checking
- * off before printing the command
- * and need to turn it back on */
- Boolean runAlways;
- const char *cmdTemplate; /* Template to use when printing the
- * command */
- char *cmdStart; /* Start of expanded command */
- char *escCmd = NULL; /* Command with quotes/backticks escaped */
+ if (!wr->xtraced) {
+ ShellWriter_Println(wr, "set -x");
+ wr->xtraced = TRUE;
+ }
+}
- noSpecials = !GNode_ShouldExecute(job->node);
+static void
+ShellWriter_ErrOff(ShellWriter *wr, Boolean echo)
+{
+ if (echo)
+ ShellWriter_EchoOff(wr);
+ ShellWriter_Println(wr, shell->errOff);
+ if (echo)
+ ShellWriter_EchoOn(wr);
+}
- numCommands++;
+static void
+ShellWriter_ErrOn(ShellWriter *wr, Boolean echo)
+{
+ if (echo)
+ ShellWriter_EchoOff(wr);
+ ShellWriter_Println(wr, shell->errOn);
+ if (echo)
+ ShellWriter_EchoOn(wr);
+}
- Var_Subst(cmd, job->node, VARE_WANTRES, &cmd);
- /* TODO: handle errors */
- cmdStart = cmd;
+/*
+ * The shell has no built-in error control, so emulate error control by
+ * enclosing each shell command in a template like "{ %s \n } || exit $?"
+ * (configurable per shell).
+ */
+static void
+JobPrintSpecialsEchoCtl(Job *job, ShellWriter *wr, CommandFlags *inout_cmdFlags,
+ const char *escCmd, const char **inout_cmdTemplate)
+{
+ /* XXX: Why is the job modified at this point? */
+ job->ignerr = TRUE;
- cmdTemplate = "%s\n";
+ if (job->echo && inout_cmdFlags->echo) {
+ ShellWriter_EchoOff(wr);
+ ShellWriter_EchoCmd(wr, escCmd);
- ParseRunOptions(&cmd, &shutUp, &errOff, &runAlways);
+ /*
+ * Leave echoing off so the user doesn't see the commands
+ * for toggling the error checking.
+ */
+ inout_cmdFlags->echo = FALSE;
+ } else {
+ if (inout_cmdFlags->echo)
+ ShellWriter_EchoCmd(wr, escCmd);
+ }
+ *inout_cmdTemplate = shell->runIgnTmpl;
- if (runAlways && noSpecials) {
/*
- * We're not actually executing anything...
- * but this one needs to be - use compat mode just for it.
+ * The template runIgnTmpl already takes care of ignoring errors,
+ * so pretend error checking is still on.
+ * XXX: What effects does this have, and why is it necessary?
*/
- Compat_RunCommand(cmdp, job->node);
- free(cmdStart);
- return;
- }
+ inout_cmdFlags->ignerr = FALSE;
+}
- /*
- * If the shell doesn't have error control the alternate echo'ing will
- * be done (to avoid showing additional error checking code)
- * and this will need the characters '$ ` \ "' escaped
- */
+static void
+JobPrintSpecials(Job *job, ShellWriter *wr, const char *escCmd, Boolean run,
+ CommandFlags *inout_cmdFlags, const char **inout_cmdTemplate)
+{
+ if (!run) {
+ /*
+ * If there is no command to run, there is no need to switch
+ * error checking off and on again for nothing.
+ */
+ inout_cmdFlags->ignerr = FALSE;
+ } else if (shell->hasErrCtl)
+ ShellWriter_ErrOff(wr, job->echo && inout_cmdFlags->echo);
+ else if (shell->runIgnTmpl != NULL && shell->runIgnTmpl[0] != '\0') {
+ JobPrintSpecialsEchoCtl(job, wr, inout_cmdFlags, escCmd,
+ inout_cmdTemplate);
+ } else
+ inout_cmdFlags->ignerr = FALSE;
+}
+
+/*
+ * Put out another command for the given job.
+ *
+ * If the command starts with '@' and neither the -s nor the -n flag was
+ * given to make, we stick a shell-specific echoOff command in the script.
+ *
+ * If the command starts with '-' and the shell has no error control (none
+ * of the predefined shells has that), we ignore errors for the entire job.
+ * XXX: Why ignore errors for the entire job?
+ * XXX: Even ignore errors for the commands before this command?
+ *
+ * If the command is just "...", all further commands of this job are skipped
+ * for now. They are attached to the .END node and will be run by Job_Finish
+ * after all other targets have been made.
+ */
+static void
+JobPrintCommand(Job *job, ShellWriter *wr, StringListNode *ln, const char *ucmd)
+{
+ Boolean run;
- if (!commandShell->hasErrCtl)
- escCmd = EscapeShellDblQuot(cmd);
+ CommandFlags cmdFlags;
+ /* Template for printing a command to the shell file */
+ const char *cmdTemplate;
+ char *xcmd; /* The expanded command */
+ char *xcmdStart;
+ char *escCmd; /* xcmd escaped to be used in double quotes */
- if (shutUp) {
- if (!(job->flags & JOB_SILENT) && !noSpecials &&
- (commandShell->hasEchoCtl)) {
- JobPrintln(job, commandShell->echoOff);
- } else {
- if (commandShell->hasErrCtl)
- shutUp = FALSE;
- }
- }
+ run = GNode_ShouldExecute(job->node);
+
+ Var_Subst(ucmd, job->node, VARE_WANTRES, &xcmd);
+ /* TODO: handle errors */
+ xcmdStart = xcmd;
- if (errOff) {
- if (!noSpecials) {
- if (commandShell->hasErrCtl) {
+ cmdTemplate = "%s\n";
+
+ ParseCommandFlags(&xcmd, &cmdFlags);
+
+ /* The '+' command flag overrides the -n or -N options. */
+ if (cmdFlags.always && !run) {
/*
- * we don't want the error-control commands showing
- * up either, so we turn off echoing while executing
- * them. We could put another field in the shell
- * structure to tell JobDoOutput to look for this
- * string too, but why make it any more complex than
- * it already is?
+ * We're not actually executing anything...
+ * but this one needs to be - use compat mode just for it.
*/
- if (!(job->flags & JOB_SILENT) && !shutUp &&
- (commandShell->hasEchoCtl)) {
- JobPrintln(job, commandShell->echoOff);
- JobPrintln(job, commandShell->errOffOrExecIgnore);
- JobPrintln(job, commandShell->echoOn);
+ Compat_RunCommand(ucmd, job->node, ln);
+ free(xcmdStart);
+ return;
+ }
+
+ /*
+ * If the shell doesn't have error control, the alternate echoing
+ * will be done (to avoid showing additional error checking code)
+ * and this needs some characters escaped.
+ */
+ escCmd = shell->hasErrCtl ? NULL : EscapeShellDblQuot(xcmd);
+
+ if (!cmdFlags.echo) {
+ if (job->echo && run && shell->hasEchoCtl) {
+ ShellWriter_EchoOff(wr);
} else {
- JobPrintln(job, commandShell->errOffOrExecIgnore);
+ if (shell->hasErrCtl)
+ cmdFlags.echo = TRUE;
}
- } else if (commandShell->errOffOrExecIgnore &&
- commandShell->errOffOrExecIgnore[0] != '\0') {
+ }
+
+ if (cmdFlags.ignerr) {
+ JobPrintSpecials(job, wr, escCmd, run, &cmdFlags, &cmdTemplate);
+ } else {
+
/*
- * The shell has no error control, so we need to be
- * weird to get it to ignore any errors from the command.
- * If echoing is turned on, we turn it off and use the
- * errOnOrEcho template to echo the command. Leave echoing
- * off so the user doesn't see the weirdness we go through
- * to ignore errors. Set cmdTemplate to use the weirdness
- * instead of the simple "%s\n" template.
+ * If errors are being checked and the shell doesn't have
+ * error control but does supply an runChkTmpl template, then
+ * set up commands to run through it.
*/
- job->flags |= JOB_IGNERR;
- if (!(job->flags & JOB_SILENT) && !shutUp) {
- if (commandShell->hasEchoCtl) {
- JobPrintln(job, commandShell->echoOff);
- }
- JobPrintf(job, commandShell->errOnOrEcho, escCmd);
- shutUp = TRUE;
- } else {
- if (!shutUp)
- JobPrintf(job, commandShell->errOnOrEcho, escCmd);
+
+ if (!shell->hasErrCtl && shell->runChkTmpl != NULL &&
+ shell->runChkTmpl[0] != '\0') {
+ if (job->echo && cmdFlags.echo) {
+ ShellWriter_EchoOff(wr);
+ ShellWriter_EchoCmd(wr, escCmd);
+ cmdFlags.echo = FALSE;
+ }
+ /*
+ * If it's a comment line or blank, avoid the possible
+ * syntax error generated by "{\n} || exit $?".
+ */
+ cmdTemplate = escCmd[0] == shell->commentChar ||
+ escCmd[0] == '\0'
+ ? shell->runIgnTmpl
+ : shell->runChkTmpl;
+ cmdFlags.ignerr = FALSE;
}
- cmdTemplate = commandShell->errOffOrExecIgnore;
- /*
- * The error ignoration (hee hee) is already taken care
- * of by the errOffOrExecIgnore template, so pretend error
- * checking is still on.
- */
- errOff = FALSE;
- } else {
- errOff = FALSE;
- }
- } else {
- errOff = FALSE;
}
- } else {
- /*
- * If errors are being checked and the shell doesn't have error control
- * but does supply an errExit template, then set up commands to run
- * through it.
- */
+ if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0)
+ ShellWriter_TraceOn(wr);
- if (!commandShell->hasErrCtl && commandShell->errExit &&
- commandShell->errExit[0] != '\0') {
- if (!(job->flags & JOB_SILENT) && !shutUp) {
- if (commandShell->hasEchoCtl)
- JobPrintln(job, commandShell->echoOff);
- JobPrintf(job, commandShell->errOnOrEcho, escCmd);
- shutUp = TRUE;
- }
- /* If it's a comment line or blank, treat as an ignored error */
- if (escCmd[0] == commandShell->commentChar ||
- (escCmd[0] == '\0'))
- cmdTemplate = commandShell->errOffOrExecIgnore;
- else
- cmdTemplate = commandShell->errExit;
- errOff = FALSE;
- }
- }
+ ShellWriter_PrintFmt(wr, cmdTemplate, xcmd);
+ free(xcmdStart);
+ free(escCmd);
- if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 &&
- !(job->flags & JOB_TRACED)) {
- JobPrintln(job, "set -x");
- job->flags |= JOB_TRACED;
- }
+ if (cmdFlags.ignerr)
+ ShellWriter_ErrOn(wr, cmdFlags.echo && job->echo);
- JobPrintf(job, cmdTemplate, cmd);
- free(cmdStart);
- free(escCmd);
- if (errOff) {
- /*
- * If echoing is already off, there's no point in issuing the
- * echoOff command. Otherwise we issue it and pretend it was on
- * for the whole command...
- */
- if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl) {
- JobPrintln(job, commandShell->echoOff);
- shutUp = TRUE;
- }
- JobPrintln(job, commandShell->errOnOrEcho);
- }
- if (shutUp && commandShell->hasEchoCtl)
- JobPrintln(job, commandShell->echoOn);
+ if (!cmdFlags.echo)
+ ShellWriter_EchoOn(wr);
}
-/* Print all commands to the shell file that is later executed.
+/*
+ * Print all commands to the shell file that is later executed.
*
* The special command "..." stops printing and saves the remaining commands
- * to be executed later. */
-static void
+ * to be executed later.
+ *
+ * Return whether at least one command was written to the shell file.
+ */
+static Boolean
JobPrintCommands(Job *job)
{
- StringListNode *ln;
+ StringListNode *ln;
+ Boolean seen = FALSE;
+ ShellWriter wr = { job->cmdFILE, FALSE };
+
+ for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
+ const char *cmd = ln->datum;
- for (ln = job->node->commands->first; ln != NULL; ln = ln->next) {
- const char *cmd = ln->datum;
+ if (strcmp(cmd, "...") == 0) {
+ job->node->type |= OP_SAVE_CMDS;
+ job->tailCmds = ln->next;
+ break;
+ }
- if (strcmp(cmd, "...") == 0) {
- job->node->type |= OP_SAVE_CMDS;
- job->tailCmds = ln->next;
- break;
+ JobPrintCommand(job, &wr, ln, ln->datum);
+ seen = TRUE;
}
- JobPrintCommand(job, ln->datum);
- }
+ return seen;
}
/* Save the delayed commands, to be executed when everything else is done. */
static void
JobSaveCommands(Job *job)
{
- StringListNode *node;
-
- for (node = job->tailCmds; node != NULL; node = node->next) {
- const char *cmd = node->datum;
- char *expanded_cmd;
- /* XXX: This Var_Subst is only intended to expand the dynamic
- * variables such as .TARGET, .IMPSRC. It is not intended to
- * expand the other variables as well; see deptgt-end.mk. */
- (void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
- /* TODO: handle errors */
- Lst_Append(Targ_GetEndNode()->commands, expanded_cmd);
- }
+ StringListNode *ln;
+
+ for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
+ const char *cmd = ln->datum;
+ char *expanded_cmd;
+ /* XXX: This Var_Subst is only intended to expand the dynamic
+ * variables such as .TARGET, .IMPSRC. It is not intended to
+ * expand the other variables as well; see deptgt-end.mk. */
+ (void)Var_Subst(cmd, job->node, VARE_WANTRES, &expanded_cmd);
+ /* TODO: handle errors */
+ Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
+ }
}
@@ -951,21 +1052,81 @@ JobSaveCommands(Job *job)
static void
JobClosePipes(Job *job)
{
- clearfd(job);
- (void)close(job->outPipe);
- job->outPipe = -1;
+ clearfd(job);
+ (void)close(job->outPipe);
+ job->outPipe = -1;
+
+ JobDoOutput(job, TRUE);
+ (void)close(job->inPipe);
+ job->inPipe = -1;
+}
+
+static void
+JobFinishDoneExitedError(Job *job, WAIT_T *inout_status)
+{
+ SwitchOutputTo(job->node);
+#ifdef USE_META
+ if (useMeta) {
+ meta_job_error(job, job->node,
+ job->ignerr, WEXITSTATUS(*inout_status));
+ }
+#endif
+ if (!shouldDieQuietly(job->node, -1)) {
+ (void)printf("*** [%s] Error code %d%s\n",
+ job->node->name, WEXITSTATUS(*inout_status),
+ job->ignerr ? " (ignored)" : "");
+ }
+
+ if (job->ignerr)
+ WAIT_STATUS(*inout_status) = 0;
+ else {
+ if (deleteOnError)
+ JobDeleteTarget(job->node);
+ PrintOnError(job->node, NULL);
+ }
+}
+
+static void
+JobFinishDoneExited(Job *job, WAIT_T *inout_status)
+{
+ DEBUG2(JOB, "Process %d [%s] exited.\n", job->pid, job->node->name);
- JobDoOutput(job, TRUE);
- (void)close(job->inPipe);
- job->inPipe = -1;
+ if (WEXITSTATUS(*inout_status) != 0)
+ JobFinishDoneExitedError(job, inout_status);
+ else if (DEBUG(JOB)) {
+ SwitchOutputTo(job->node);
+ (void)printf("*** [%s] Completed successfully\n",
+ job->node->name);
+ }
}
-/* Do final processing for the given job including updating parent nodes and
+static void
+JobFinishDoneSignaled(Job *job, WAIT_T status)
+{
+ SwitchOutputTo(job->node);
+ (void)printf("*** [%s] Signal %d\n", job->node->name, WTERMSIG(status));
+ if (deleteOnError)
+ JobDeleteTarget(job->node);
+}
+
+static void
+JobFinishDone(Job *job, WAIT_T *inout_status)
+{
+ if (WIFEXITED(*inout_status))
+ JobFinishDoneExited(job, inout_status);
+ else
+ JobFinishDoneSignaled(job, *inout_status);
+
+ (void)fflush(stdout);
+}
+
+/*
+ * Do final processing for the given job including updating parent nodes and
* starting new jobs as available/necessary.
*
* Deferred commands for the job are placed on the .END node.
*
- * If there was a serious error (errors != 0; not an ignored one), no more
+ * If there was a serious error (job_errors != 0; not an ignored one), no more
* jobs will be started.
*
* Input:
@@ -975,203 +1136,155 @@ JobClosePipes(Job *job)
static void
JobFinish (Job *job, WAIT_T status)
{
- Boolean done, return_job_token;
+ Boolean done, return_job_token;
- DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
- job->pid, job->node->name, status);
+ DEBUG3(JOB, "JobFinish: %d [%s], status %d\n",
+ job->pid, job->node->name, status);
- if ((WIFEXITED(status) &&
- ((WEXITSTATUS(status) != 0 && !(job->flags & JOB_IGNERR)))) ||
- WIFSIGNALED(status))
- {
- /*
- * If it exited non-zero and either we're doing things our
- * way or we're not ignoring errors, the job is finished.
- * Similarly, if the shell died because of a signal
- * the job is also finished. In these
- * cases, finish out the job's output before printing the exit
- * status...
- */
- JobClosePipes(job);
- if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
- (void)fclose(job->cmdFILE);
- job->cmdFILE = NULL;
- }
- done = TRUE;
- } else if (WIFEXITED(status)) {
- /*
- * Deal with ignored errors in -B mode. We need to print a message
- * telling of the ignored error as well as to run the next command.
- *
- */
- done = WEXITSTATUS(status) != 0;
- JobClosePipes(job);
- } else {
- /*
- * No need to close things down or anything.
- */
- done = FALSE;
- }
+ if ((WIFEXITED(status) &&
+ ((WEXITSTATUS(status) != 0 && !job->ignerr))) ||
+ WIFSIGNALED(status)) {
+ /* Finished because of an error. */
- if (done) {
- if (WIFEXITED(status)) {
- DEBUG2(JOB, "Process %d [%s] exited.\n",
- job->pid, job->node->name);
- if (WEXITSTATUS(status) != 0) {
- if (job->node != lastNode) {
- MESSAGE(stdout, job->node);
- lastNode = job->node;
- }
-#ifdef USE_META
- if (useMeta) {
- meta_job_error(job, job->node, job->flags, WEXITSTATUS(status));
- }
-#endif
- if (!shouldDieQuietly(job->node, -1))
- (void)printf("*** [%s] Error code %d%s\n",
- job->node->name,
- WEXITSTATUS(status),
- (job->flags & JOB_IGNERR) ? " (ignored)" : "");
- if (job->flags & JOB_IGNERR) {
- WAIT_STATUS(status) = 0;
- } else {
- if (deleteOnError) {
- JobDeleteTarget(job->node);
- }
- PrintOnError(job->node, NULL);
+ JobClosePipes(job);
+ if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
+ (void)fclose(job->cmdFILE);
+ job->cmdFILE = NULL;
}
- } else if (DEBUG(JOB)) {
- if (job->node != lastNode) {
- MESSAGE(stdout, job->node);
- lastNode = job->node;
- }
- (void)printf("*** [%s] Completed successfully\n",
- job->node->name);
- }
+ done = TRUE;
+
+ } else if (WIFEXITED(status)) {
+ /*
+ * Deal with ignored errors in -B mode. We need to print a
+ * message telling of the ignored error as well as to run
+ * the next command.
+ */
+ done = WEXITSTATUS(status) != 0;
+
+ JobClosePipes(job);
+
} else {
- if (job->node != lastNode) {
- MESSAGE(stdout, job->node);
- lastNode = job->node;
- }
- (void)printf("*** [%s] Signal %d\n",
- job->node->name, WTERMSIG(status));
- if (deleteOnError) {
- JobDeleteTarget(job->node);
- }
+ /* No need to close things down or anything. */
+ done = FALSE;
}
- (void)fflush(stdout);
- }
+
+ if (done)
+ JobFinishDone(job, &status);
#ifdef USE_META
- if (useMeta) {
- int meta_status = meta_job_finish(job);
- if (meta_status != 0 && status == 0)
- status = meta_status;
- }
+ if (useMeta) {
+ int meta_status = meta_job_finish(job);
+ if (meta_status != 0 && status == 0)
+ status = meta_status;
+ }
#endif
- return_job_token = FALSE;
+ return_job_token = FALSE;
- Trace_Log(JOBEND, job);
- if (!(job->flags & JOB_SPECIAL)) {
- if (WAIT_STATUS(status) != 0 ||
- (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
- return_job_token = TRUE;
- }
+ Trace_Log(JOBEND, job);
+ if (!job->special) {
+ if (WAIT_STATUS(status) != 0 ||
+ (aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
+ return_job_token = TRUE;
+ }
- if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
- (WAIT_STATUS(status) == 0)) {
- /*
- * As long as we aren't aborting and the job didn't return a non-zero
- * status that we shouldn't ignore, we call Make_Update to update
- * the parents.
- */
- JobSaveCommands(job);
- job->node->made = MADE;
- if (!(job->flags & JOB_SPECIAL))
- return_job_token = TRUE;
- Make_Update(job->node);
- job->status = JOB_ST_FREE;
- } else if (WAIT_STATUS(status)) {
- errors++;
- job->status = JOB_ST_FREE;
- }
+ if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
+ (WAIT_STATUS(status) == 0)) {
+ /*
+ * As long as we aren't aborting and the job didn't return a
+ * non-zero status that we shouldn't ignore, we call
+ * Make_Update to update the parents.
+ */
+ JobSaveCommands(job);
+ job->node->made = MADE;
+ if (!job->special)
+ return_job_token = TRUE;
+ Make_Update(job->node);
+ job->status = JOB_ST_FREE;
+ } else if (status != 0) {
+ job_errors++;
+ job->status = JOB_ST_FREE;
+ }
- if (errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT)
- aborting = ABORT_ERROR; /* Prevent more jobs from getting started. */
+ if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
+ /* Prevent more jobs from getting started. */
+ aborting = ABORT_ERROR;
+ }
- if (return_job_token)
- Job_TokenReturn();
+ if (return_job_token)
+ Job_TokenReturn();
- if (aborting == ABORT_ERROR && jobTokensRunning == 0)
- Finish(errors);
+ if (aborting == ABORT_ERROR && jobTokensRunning == 0)
+ Finish(job_errors);
}
static void
TouchRegular(GNode *gn)
{
- const char *file = GNode_Path(gn);
- struct utimbuf times = { now, now };
- int fd;
- char c;
-
- if (utime(file, &times) >= 0)
- return;
-
- fd = open(file, O_RDWR | O_CREAT, 0666);
- if (fd < 0) {
- (void)fprintf(stderr, "*** couldn't touch %s: %s\n",
- file, strerror(errno));
- (void)fflush(stderr);
- return; /* XXX: What about propagating the error? */
- }
+ const char *file = GNode_Path(gn);
+ struct utimbuf times = { now, now };
+ int fd;
+ char c;
+
+ if (utime(file, &times) >= 0)
+ return;
+
+ fd = open(file, O_RDWR | O_CREAT, 0666);
+ if (fd < 0) {
+ (void)fprintf(stderr, "*** couldn't touch %s: %s\n",
+ file, strerror(errno));
+ (void)fflush(stderr);
+ return; /* XXX: What about propagating the error? */
+ }
- /* Last resort: update the file's time stamps in the traditional way.
- * XXX: This doesn't work for empty files, which are sometimes used
- * as marker files. */
- if (read(fd, &c, 1) == 1) {
- (void)lseek(fd, 0, SEEK_SET);
- while (write(fd, &c, 1) == -1 && errno == EAGAIN)
- continue;
- }
- (void)close(fd); /* XXX: What about propagating the error? */
+ /* Last resort: update the file's time stamps in the traditional way.
+ * XXX: This doesn't work for empty files, which are sometimes used
+ * as marker files. */
+ if (read(fd, &c, 1) == 1) {
+ (void)lseek(fd, 0, SEEK_SET);
+ while (write(fd, &c, 1) == -1 && errno == EAGAIN)
+ continue;
+ }
+ (void)close(fd); /* XXX: What about propagating the error? */
}
-/* Touch the given target. Called by JobStart when the -t flag was given.
+/*
+ * Touch the given target. Called by JobStart when the -t flag was given.
*
* The modification date of the file is changed.
- * If the file did not exist, it is created. */
+ * If the file did not exist, it is created.
+ */
void
-Job_Touch(GNode *gn, Boolean silent)
+Job_Touch(GNode *gn, Boolean echo)
{
- if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL|
- OP_SPECIAL|OP_PHONY)) {
- /* These are "virtual" targets and should not really be created. */
- return;
- }
-
- if (!silent || !GNode_ShouldExecute(gn)) {
- (void)fprintf(stdout, "touch %s\n", gn->name);
- (void)fflush(stdout);
- }
-
- if (!GNode_ShouldExecute(gn))
- return;
+ if (gn->type &
+ (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
+ OP_SPECIAL | OP_PHONY)) {
+ /*
+ * These are "virtual" targets and should not really be
+ * created.
+ */
+ return;
+ }
- if (gn->type & OP_ARCHV) {
- Arch_Touch(gn);
- return;
- }
+ if (echo || !GNode_ShouldExecute(gn)) {
+ (void)fprintf(stdout, "touch %s\n", gn->name);
+ (void)fflush(stdout);
+ }
- if (gn->type & OP_LIB) {
- Arch_TouchLib(gn);
- return;
- }
+ if (!GNode_ShouldExecute(gn))
+ return;
- TouchRegular(gn);
+ if (gn->type & OP_ARCHV)
+ Arch_Touch(gn);
+ else if (gn->type & OP_LIB)
+ Arch_TouchLib(gn);
+ else
+ TouchRegular(gn);
}
-/* Make sure the given node has all the commands it needs.
+/*
+ * Make sure the given node has all the commands it needs.
*
* The node will have commands from the .DEFAULT rule added to it if it
* needs them.
@@ -1186,504 +1299,498 @@ Job_Touch(GNode *gn, Boolean silent)
Boolean
Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
{
- if (GNode_IsTarget(gn))
- return TRUE;
- if (!Lst_IsEmpty(gn->commands))
- return TRUE;
- if ((gn->type & OP_LIB) && !Lst_IsEmpty(gn->children))
- return TRUE;
+ if (GNode_IsTarget(gn))
+ return TRUE;
+ if (!Lst_IsEmpty(&gn->commands))
+ return TRUE;
+ if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
+ return TRUE;
- /*
- * No commands. Look for .DEFAULT rule from which we might infer
- * commands.
- */
- if (defaultNode != NULL && !Lst_IsEmpty(defaultNode->commands) &&
- !(gn->type & OP_SPECIAL)) {
/*
- * The traditional Make only looks for a .DEFAULT if the node was
- * never the target of an operator, so that's what we do too.
- *
- * The .DEFAULT node acts like a transformation rule, in that
- * gn also inherits any attributes or sources attached to
- * .DEFAULT itself.
+ * No commands. Look for .DEFAULT rule from which we might infer
+ * commands.
*/
- Make_HandleUse(defaultNode, gn);
- Var_Set(IMPSRC, GNode_VarTarget(gn), gn);
- return TRUE;
- }
+ if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
+ !(gn->type & OP_SPECIAL)) {
+ /*
+ * The traditional Make only looks for a .DEFAULT if the node
+ * was never the target of an operator, so that's what we do
+ * too.
+ *
+ * The .DEFAULT node acts like a transformation rule, in that
+ * gn also inherits any attributes or sources attached to
+ * .DEFAULT itself.
+ */
+ Make_HandleUse(defaultNode, gn);
+ Var_Set(IMPSRC, GNode_VarTarget(gn), gn);
+ return TRUE;
+ }
- Dir_UpdateMTime(gn, FALSE);
- if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
- return TRUE;
+ Dir_UpdateMTime(gn, FALSE);
+ if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
+ return TRUE;
- /*
- * The node wasn't the target of an operator. We have no .DEFAULT
- * rule to go on and the target doesn't already exist. There's
- * nothing more we can do for this branch. If the -k flag wasn't
- * given, we stop in our tracks, otherwise we just don't update
- * this node's parents so they never get examined.
- */
+ /*
+ * The node wasn't the target of an operator. We have no .DEFAULT
+ * rule to go on and the target doesn't already exist. There's
+ * nothing more we can do for this branch. If the -k flag wasn't
+ * given, we stop in our tracks, otherwise we just don't update
+ * this node's parents so they never get examined.
+ */
- if (gn->flags & FROM_DEPEND) {
- if (!Job_RunTarget(".STALE", gn->fname))
- fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s\n",
- progname, gn->fname, gn->lineno, makeDependfile,
- gn->name);
- return TRUE;
- }
+ if (gn->flags & FROM_DEPEND) {
+ if (!Job_RunTarget(".STALE", gn->fname))
+ fprintf(stdout,
+ "%s: %s, %d: ignoring stale %s for %s\n",
+ progname, gn->fname, gn->lineno, makeDependfile,
+ gn->name);
+ return TRUE;
+ }
- if (gn->type & OP_OPTIONAL) {
- (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
- progname, gn->name, "ignored");
- (void)fflush(stdout);
- return TRUE;
- }
+ if (gn->type & OP_OPTIONAL) {
+ (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
+ progname, gn->name, "ignored");
+ (void)fflush(stdout);
+ return TRUE;
+ }
- if (opts.keepgoing) {
- (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
- progname, gn->name, "continuing");
- (void)fflush(stdout);
- return FALSE;
- }
+ if (opts.keepgoing) {
+ (void)fprintf(stdout, "%s: don't know how to make %s (%s)\n",
+ progname, gn->name, "continuing");
+ (void)fflush(stdout);
+ return FALSE;
+ }
- abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
- return FALSE;
+ abortProc("%s: don't know how to make %s. Stop", progname, gn->name);
+ return FALSE;
}
-/* Execute the shell for the given job.
+/*
+ * Execute the shell for the given job.
*
- * See Job_CatchOutput for handling the output of the shell. */
+ * See Job_CatchOutput for handling the output of the shell.
+ */
static void
JobExec(Job *job, char **argv)
{
- int cpid; /* ID of new child */
- sigset_t mask;
-
- job->flags &= ~JOB_TRACED;
+ int cpid; /* ID of new child */
+ sigset_t mask;
- if (DEBUG(JOB)) {
- int i;
+ if (DEBUG(JOB)) {
+ int i;
- debug_printf("Running %s\n", job->node->name);
- debug_printf("\tCommand: ");
- for (i = 0; argv[i] != NULL; i++) {
- debug_printf("%s ", argv[i]);
+ debug_printf("Running %s\n", job->node->name);
+ debug_printf("\tCommand: ");
+ for (i = 0; argv[i] != NULL; i++) {
+ debug_printf("%s ", argv[i]);
+ }
+ debug_printf("\n");
}
- debug_printf("\n");
- }
- /*
- * Some jobs produce no output and it's disconcerting to have
- * no feedback of their running (since they produce no output, the
- * banner with their name in it never appears). This is an attempt to
- * provide that feedback, even if nothing follows it.
- */
- if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) {
- MESSAGE(stdout, job->node);
- lastNode = job->node;
- }
+ /*
+ * Some jobs produce no output and it's disconcerting to have
+ * no feedback of their running (since they produce no output, the
+ * banner with their name in it never appears). This is an attempt to
+ * provide that feedback, even if nothing follows it.
+ */
+ if (job->echo)
+ SwitchOutputTo(job->node);
- /* No interruptions until this job is on the `jobs' list */
- JobSigLock(&mask);
+ /* No interruptions until this job is on the `jobs' list */
+ JobSigLock(&mask);
+
+ /* Pre-emptively mark job running, pid still zero though */
+ job->status = JOB_ST_RUNNING;
- /* Pre-emptively mark job running, pid still zero though */
- job->status = JOB_ST_RUNNING;
+ Var_ReexportVars();
- cpid = vFork();
- if (cpid == -1)
- Punt("Cannot vfork: %s", strerror(errno));
+ cpid = vFork();
+ if (cpid == -1)
+ Punt("Cannot vfork: %s", strerror(errno));
- if (cpid == 0) {
- /* Child */
- sigset_t tmask;
+ if (cpid == 0) {
+ /* Child */
+ sigset_t tmask;
#ifdef USE_META
- if (useMeta) {
- meta_job_child(job);
- }
+ if (useMeta) {
+ meta_job_child(job);
+ }
#endif
- /*
- * Reset all signal handlers; this is necessary because we also
- * need to unblock signals before we exec(2).
- */
- JobSigReset();
+ /*
+ * Reset all signal handlers; this is necessary because we
+ * also need to unblock signals before we exec(2).
+ */
+ JobSigReset();
- /* Now unblock signals */
- sigemptyset(&tmask);
- JobSigUnlock(&tmask);
+ /* Now unblock signals */
+ sigemptyset(&tmask);
+ JobSigUnlock(&tmask);
- /*
- * Must duplicate the input stream down to the child's input and
- * reset it to the beginning (again). Since the stream was marked
- * close-on-exec, we must clear that bit in the new input.
- */
- if (dup2(fileno(job->cmdFILE), 0) == -1)
- execDie("dup2", "job->cmdFILE");
- if (fcntl(0, F_SETFD, 0) == -1)
- execDie("fcntl clear close-on-exec", "stdin");
- if (lseek(0, 0, SEEK_SET) == -1)
- execDie("lseek to 0", "stdin");
-
- if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
- /*
- * Pass job token pipe to submakes.
- */
- if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
- execDie("clear close-on-exec", "tokenWaitJob.inPipe");
- if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
- execDie("clear close-on-exec", "tokenWaitJob.outPipe");
- }
+ /*
+ * Must duplicate the input stream down to the child's input
+ * and reset it to the beginning (again). Since the stream
+ * was marked close-on-exec, we must clear that bit in the
+ * new input.
+ */
+ if (dup2(fileno(job->cmdFILE), 0) == -1)
+ execDie("dup2", "job->cmdFILE");
+ if (fcntl(0, F_SETFD, 0) == -1)
+ execDie("fcntl clear close-on-exec", "stdin");
+ if (lseek(0, 0, SEEK_SET) == -1)
+ execDie("lseek to 0", "stdin");
+
+ if (job->node->type & (OP_MAKE | OP_SUBMAKE)) {
+ /*
+ * Pass job token pipe to submakes.
+ */
+ if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1)
+ execDie("clear close-on-exec",
+ "tokenWaitJob.inPipe");
+ if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1)
+ execDie("clear close-on-exec",
+ "tokenWaitJob.outPipe");
+ }
- /*
- * Set up the child's output to be routed through the pipe
- * we've created for it.
- */
- if (dup2(job->outPipe, 1) == -1)
- execDie("dup2", "job->outPipe");
+ /*
+ * Set up the child's output to be routed through the pipe
+ * we've created for it.
+ */
+ if (dup2(job->outPipe, 1) == -1)
+ execDie("dup2", "job->outPipe");
- /*
- * The output channels are marked close on exec. This bit was
- * duplicated by the dup2(on some systems), so we have to clear
- * it before routing the shell's error output to the same place as
- * its standard output.
- */
- if (fcntl(1, F_SETFD, 0) == -1)
- execDie("clear close-on-exec", "stdout");
- if (dup2(1, 2) == -1)
- execDie("dup2", "1, 2");
+ /*
+ * The output channels are marked close on exec. This bit
+ * was duplicated by the dup2(on some systems), so we have
+ * to clear it before routing the shell's error output to
+ * the same place as its standard output.
+ */
+ if (fcntl(1, F_SETFD, 0) == -1)
+ execDie("clear close-on-exec", "stdout");
+ if (dup2(1, 2) == -1)
+ execDie("dup2", "1, 2");
- /*
- * We want to switch the child into a different process family so
- * we can kill it and all its descendants in one fell swoop,
- * by killing its process family, but not commit suicide.
- */
+ /*
+ * We want to switch the child into a different process
+ * family so we can kill it and all its descendants in
+ * one fell swoop, by killing its process family, but not
+ * commit suicide.
+ */
#if defined(HAVE_SETPGID)
- (void)setpgid(0, getpid());
+ (void)setpgid(0, getpid());
#else
#if defined(HAVE_SETSID)
- /* XXX: dsl - I'm sure this should be setpgrp()... */
- (void)setsid();
+ /* XXX: dsl - I'm sure this should be setpgrp()... */
+ (void)setsid();
#else
- (void)setpgrp(0, getpid());
+ (void)setpgrp(0, getpid());
#endif
#endif
- Var_ExportVars();
-
- (void)execv(shellPath, argv);
- execDie("exec", shellPath);
- }
+ (void)execv(shellPath, argv);
+ execDie("exec", shellPath);
+ }
- /* Parent, continuing after the child exec */
- job->pid = cpid;
+ /* Parent, continuing after the child exec */
+ job->pid = cpid;
- Trace_Log(JOBSTART, job);
+ Trace_Log(JOBSTART, job);
#ifdef USE_META
- if (useMeta) {
- meta_job_parent(job, cpid);
- }
+ if (useMeta) {
+ meta_job_parent(job, cpid);
+ }
#endif
- /*
- * Set the current position in the buffer to the beginning
- * and mark another stream to watch in the outputs mask
- */
- job->curPos = 0;
+ /*
+ * Set the current position in the buffer to the beginning
+ * and mark another stream to watch in the outputs mask
+ */
+ job->curPos = 0;
- watchfd(job);
+ watchfd(job);
- if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
- (void)fclose(job->cmdFILE);
- job->cmdFILE = NULL;
- }
+ if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
+ (void)fclose(job->cmdFILE);
+ job->cmdFILE = NULL;
+ }
- /*
- * Now the job is actually running, add it to the table.
- */
- if (DEBUG(JOB)) {
- debug_printf("JobExec(%s): pid %d added to jobs table\n",
- job->node->name, job->pid);
- job_table_dump("job started");
- }
- JobSigUnlock(&mask);
+ /*
+ * Now the job is actually running, add it to the table.
+ */
+ if (DEBUG(JOB)) {
+ debug_printf("JobExec(%s): pid %d added to jobs table\n",
+ job->node->name, job->pid);
+ job_table_dump("job started");
+ }
+ JobSigUnlock(&mask);
}
/* Create the argv needed to execute the shell for a given job. */
static void
JobMakeArgv(Job *job, char **argv)
{
- int argc;
- static char args[10]; /* For merged arguments */
+ int argc;
+ static char args[10]; /* For merged arguments */
- argv[0] = UNCONST(shellName);
- argc = 1;
-
- if ((commandShell->exit && commandShell->exit[0] != '-') ||
- (commandShell->echo && commandShell->echo[0] != '-'))
- {
- /*
- * At least one of the flags doesn't have a minus before it, so
- * merge them together. Have to do this because the *(&(@*#*&#$#
- * Bourne shell thinks its second argument is a file to source.
- * Grrrr. Note the ten-character limitation on the combined arguments.
- */
- (void)snprintf(args, sizeof args, "-%s%s",
- ((job->flags & JOB_IGNERR) ? "" :
- (commandShell->exit ? commandShell->exit : "")),
- ((job->flags & JOB_SILENT) ? "" :
- (commandShell->echo ? commandShell->echo : "")));
+ argv[0] = UNCONST(shellName);
+ argc = 1;
- if (args[1]) {
- argv[argc] = args;
- argc++;
- }
- } else {
- if (!(job->flags & JOB_IGNERR) && commandShell->exit) {
- argv[argc] = UNCONST(commandShell->exit);
- argc++;
- }
- if (!(job->flags & JOB_SILENT) && commandShell->echo) {
- argv[argc] = UNCONST(commandShell->echo);
- argc++;
+ if ((shell->errFlag != NULL && shell->errFlag[0] != '-') ||
+ (shell->echoFlag != NULL && shell->echoFlag[0] != '-')) {
+ /*
+ * At least one of the flags doesn't have a minus before it,
+ * so merge them together. Have to do this because the Bourne
+ * shell thinks its second argument is a file to source.
+ * Grrrr. Note the ten-character limitation on the combined
+ * arguments.
+ *
+ * TODO: Research until when the above comments were
+ * practically relevant.
+ */
+ (void)snprintf(args, sizeof args, "-%s%s",
+ (job->ignerr ? "" :
+ (shell->errFlag != NULL ? shell->errFlag : "")),
+ (!job->echo ? "" :
+ (shell->echoFlag != NULL ? shell->echoFlag : "")));
+
+ if (args[1] != '\0') {
+ argv[argc] = args;
+ argc++;
+ }
+ } else {
+ if (!job->ignerr && shell->errFlag != NULL) {
+ argv[argc] = UNCONST(shell->errFlag);
+ argc++;
+ }
+ if (job->echo && shell->echoFlag != NULL) {
+ argv[argc] = UNCONST(shell->echoFlag);
+ argc++;
+ }
}
- }
- argv[argc] = NULL;
+ argv[argc] = NULL;
}
-/*-
- *-----------------------------------------------------------------------
- * JobStart --
- * Start a target-creation process going for the target described
- * by the graph node gn.
- *
- * Input:
- * gn target to create
- * flags flags for the job to override normal ones.
- * previous The previous Job structure for this node, if any.
- *
- * Results:
- * JOB_ERROR if there was an error in the commands, JOB_FINISHED
- * if there isn't actually anything left to do for the job and
- * JOB_RUNNING if the job has been started.
- *
- * Side Effects:
- * A new Job node is created and added to the list of running
- * jobs. PMake is forked and a child shell created.
- *
- * NB: The return value is ignored by everyone.
- *-----------------------------------------------------------------------
- */
-static JobStartResult
-JobStart(GNode *gn, JobFlags flags)
+static void
+JobOpenTmpFile(Job *job, GNode *gn, Boolean cmdsOK, Boolean *out_run)
{
- Job *job; /* new job descriptor */
- char *argv[10]; /* Argument vector to shell */
- Boolean cmdsOK; /* true if the nodes commands were all right */
- Boolean noExec; /* Set true if we decide not to run the job */
- int tfd; /* File descriptor to the temp file */
-
- for (job = job_table; job < job_table_end; job++) {
- if (job->status == JOB_ST_FREE)
- break;
- }
- if (job >= job_table_end)
- Punt("JobStart no job slots vacant");
-
- memset(job, 0, sizeof *job);
- job->node = gn;
- job->tailCmds = NULL;
- job->status = JOB_ST_SET_UP;
-
- if (gn->type & OP_SPECIAL)
- flags |= JOB_SPECIAL;
- if (Targ_Ignore(gn))
- flags |= JOB_IGNERR;
- if (Targ_Silent(gn))
- flags |= JOB_SILENT;
- job->flags = flags;
-
- /*
- * Check the commands now so any attributes from .DEFAULT have a chance
- * to migrate to the node
- */
- cmdsOK = Job_CheckCommands(gn, Error);
-
- job->inPollfd = NULL;
- /*
- * If the -n flag wasn't given, we open up OUR (not the child's)
- * temporary file to stuff commands in it. The thing is rd/wr so we don't
- * need to reopen it to feed it to the shell. If the -n flag *was* given,
- * we just set the file to be stdout. Cute, huh?
- */
- if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
- (!opts.noExecute && !opts.touchFlag)) {
/*
- * tfile is the name of a file into which all shell commands are
- * put. It is removed before the child shell is executed, unless
- * DEBUG(SCRIPT) is set.
+ * tfile is the name of a file into which all shell commands
+ * are put. It is removed before the child shell is executed,
+ * unless DEBUG(SCRIPT) is set.
*/
char *tfile;
sigset_t mask;
+ int tfd; /* File descriptor to the temp file */
+
/*
* We're serious here, but if the commands were bogus, we're
* also dead...
*/
if (!cmdsOK) {
- PrintOnError(gn, NULL); /* provide some clue */
- DieHorribly();
+ PrintOnError(gn, NULL); /* provide some clue */
+ DieHorribly();
}
JobSigLock(&mask);
tfd = mkTempFile(TMPPAT, &tfile);
if (!DEBUG(SCRIPT))
- (void)eunlink(tfile);
+ (void)eunlink(tfile);
JobSigUnlock(&mask);
job->cmdFILE = fdopen(tfd, "w+");
if (job->cmdFILE == NULL)
- Punt("Could not fdopen %s", tfile);
+ Punt("Could not fdopen %s", tfile);
(void)fcntl(fileno(job->cmdFILE), F_SETFD, FD_CLOEXEC);
/*
- * Send the commands to the command file, flush all its buffers then
- * rewind and remove the thing.
+ * Send the commands to the command file, flush all its
+ * buffers then rewind and remove the thing.
*/
- noExec = FALSE;
+ *out_run = TRUE;
#ifdef USE_META
if (useMeta) {
- meta_job_start(job, gn);
- if (Targ_Silent(gn)) /* might have changed */
- job->flags |= JOB_SILENT;
+ meta_job_start(job, gn);
+ if (gn->type & OP_SILENT) /* might have changed */
+ job->echo = FALSE;
}
#endif
- /*
- * We can do all the commands at once. hooray for sanity
- */
- numCommands = 0;
- JobPrintCommands(job);
- /*
- * If we didn't print out any commands to the shell script,
- * there's not much point in executing the shell, is there?
- */
- if (numCommands == 0) {
- noExec = TRUE;
- }
+ /* We can do all the commands at once. hooray for sanity */
+ if (!JobPrintCommands(job))
+ *out_run = FALSE;
free(tfile);
- } else if (!GNode_ShouldExecute(gn)) {
- /*
- * Not executing anything -- just print all the commands to stdout
- * in one fell swoop. This will still set up job->tailCmds correctly.
- */
- if (lastNode != gn) {
- MESSAGE(stdout, gn);
- lastNode = gn;
+}
+
+/*
+ * Start a target-creation process going for the target described by the
+ * graph node gn.
+ *
+ * Input:
+ * gn target to create
+ * flags flags for the job to override normal ones.
+ * previous The previous Job structure for this node, if any.
+ *
+ * Results:
+ * JOB_ERROR if there was an error in the commands, JOB_FINISHED
+ * if there isn't actually anything left to do for the job and
+ * JOB_RUNNING if the job has been started.
+ *
+ * Side Effects:
+ * A new Job node is created and added to the list of running
+ * jobs. PMake is forked and a child shell created.
+ *
+ * NB: The return value is ignored by everyone.
+ */
+static JobStartResult
+JobStart(GNode *gn, Boolean special)
+{
+ Job *job; /* new job descriptor */
+ char *argv[10]; /* Argument vector to shell */
+ Boolean cmdsOK; /* true if the nodes commands were all right */
+ Boolean run;
+
+ for (job = job_table; job < job_table_end; job++) {
+ if (job->status == JOB_ST_FREE)
+ break;
}
- job->cmdFILE = stdout;
- /*
- * Only print the commands if they're ok, but don't die if they're
- * not -- just let the user know they're bad and keep going. It
- * doesn't do any harm in this case and may do some good.
- */
- if (cmdsOK)
- JobPrintCommands(job);
- /*
- * Don't execute the shell, thank you.
- */
- noExec = TRUE;
- } else {
+ if (job >= job_table_end)
+ Punt("JobStart no job slots vacant");
+
+ memset(job, 0, sizeof *job);
+ job->node = gn;
+ job->tailCmds = NULL;
+ job->status = JOB_ST_SET_UP;
+
+ job->special = special || gn->type & OP_SPECIAL;
+ job->ignerr = opts.ignoreErrors || gn->type & OP_IGNORE;
+ job->echo = !(opts.beSilent || gn->type & OP_SILENT);
+
/*
- * Just touch the target and note that no shell should be executed.
- * Set cmdFILE to stdout to make life easier. Check the commands, too,
- * but don't die if they're no good -- it does no harm to keep working
- * up the graph.
+ * Check the commands now so any attributes from .DEFAULT have a
+ * chance to migrate to the node.
*/
- job->cmdFILE = stdout;
- Job_Touch(gn, job->flags & JOB_SILENT);
- noExec = TRUE;
- }
- /* Just in case it isn't already... */
- (void)fflush(job->cmdFILE);
+ cmdsOK = Job_CheckCommands(gn, Error);
- /*
- * If we're not supposed to execute a shell, don't.
- */
- if (noExec) {
- if (!(job->flags & JOB_SPECIAL))
- Job_TokenReturn();
+ job->inPollfd = NULL;
/*
- * Unlink and close the command file if we opened one
+ * If the -n flag wasn't given, we open up OUR (not the child's)
+ * temporary file to stuff commands in it. The thing is rd/wr so
+ * we don't need to reopen it to feed it to the shell. If the -n
+ * flag *was* given, we just set the file to be stdout. Cute, huh?
*/
- if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
- (void)fclose(job->cmdFILE);
- job->cmdFILE = NULL;
+ if (((gn->type & OP_MAKE) && !opts.noRecursiveExecute) ||
+ (!opts.noExecute && !opts.touchFlag)) {
+ JobOpenTmpFile(job, gn, cmdsOK, &run);
+ } else if (!GNode_ShouldExecute(gn)) {
+ /*
+ * Not executing anything -- just print all the commands to
+ * stdout in one fell swoop. This will still set up
+ * job->tailCmds correctly.
+ */
+ SwitchOutputTo(gn);
+ job->cmdFILE = stdout;
+ /*
+ * Only print the commands if they're ok, but don't die if
+ * they're not -- just let the user know they're bad and
+ * keep going. It doesn't do any harm in this case and may
+ * do some good.
+ */
+ if (cmdsOK)
+ JobPrintCommands(job);
+ /* Don't execute the shell, thank you. */
+ run = FALSE;
+ } else {
+ /*
+ * Just touch the target and note that no shell should be
+ * executed. Set cmdFILE to stdout to make life easier.
+ * Check the commands, too, but don't die if they're no
+ * good -- it does no harm to keep working up the graph.
+ */
+ job->cmdFILE = stdout;
+ Job_Touch(gn, job->echo);
+ run = FALSE;
}
+ /* Just in case it isn't already... */
+ (void)fflush(job->cmdFILE);
+
+ /* If we're not supposed to execute a shell, don't. */
+ if (!run) {
+ if (!job->special)
+ Job_TokenReturn();
+ /* Unlink and close the command file if we opened one */
+ if (job->cmdFILE != NULL && job->cmdFILE != stdout) {
+ (void)fclose(job->cmdFILE);
+ job->cmdFILE = NULL;
+ }
- /*
- * We only want to work our way up the graph if we aren't here because
- * the commands for the job were no good.
- */
- if (cmdsOK && aborting == ABORT_NONE) {
- JobSaveCommands(job);
- job->node->made = MADE;
- Make_Update(job->node);
+ /*
+ * We only want to work our way up the graph if we aren't
+ * here because the commands for the job were no good.
+ */
+ if (cmdsOK && aborting == ABORT_NONE) {
+ JobSaveCommands(job);
+ job->node->made = MADE;
+ Make_Update(job->node);
+ }
+ job->status = JOB_ST_FREE;
+ return cmdsOK ? JOB_FINISHED : JOB_ERROR;
}
- job->status = JOB_ST_FREE;
- return cmdsOK ? JOB_FINISHED : JOB_ERROR;
- }
- /*
- * Set up the control arguments to the shell. This is based on the flags
- * set earlier for this job.
- */
- JobMakeArgv(job, argv);
+ /*
+ * Set up the control arguments to the shell. This is based on the
+ * flags set earlier for this job.
+ */
+ JobMakeArgv(job, argv);
- /* Create the pipe by which we'll get the shell's output. */
- JobCreatePipe(job, 3);
+ /* Create the pipe by which we'll get the shell's output. */
+ JobCreatePipe(job, 3);
- JobExec(job, argv);
- return JOB_RUNNING;
+ JobExec(job, argv);
+ return JOB_RUNNING;
}
-/* Print the output of the shell command, skipping the noPrint command of
- * the shell, if any. */
+/*
+ * Print the output of the shell command, skipping the noPrint text of the
+ * shell, if any. The default shell does not have noPrint though, which means
+ * that in all practical cases, handling the output is left to the caller.
+ */
static char *
-JobOutput(Job *job, char *cp, char *endp)
+JobOutput(char *cp, char *endp) /* XXX: should all be const */
{
- char *ecp;
+ char *ecp; /* XXX: should be const */
- if (commandShell->noPrint == NULL || commandShell->noPrint[0] == '\0')
- return cp;
+ if (shell->noPrint == NULL || shell->noPrint[0] == '\0')
+ return cp;
- while ((ecp = strstr(cp, commandShell->noPrint)) != NULL) {
- if (ecp != cp) {
- *ecp = '\0';
- /*
- * The only way there wouldn't be a newline after
- * this line is if it were the last in the buffer.
- * however, since the non-printable comes after it,
- * there must be a newline, so we don't print one.
- */
- (void)fprintf(stdout, "%s", cp);
- (void)fflush(stdout);
- }
- cp = ecp + commandShell->noPrintLen;
- if (cp != endp) {
- /*
- * Still more to print, look again after skipping
- * the whitespace following the non-printable
- * command....
- */
- cp++;
- pp_skip_whitespace(&cp);
- } else {
- return cp;
+ /*
+ * XXX: What happens if shell->noPrint occurs on the boundary of
+ * the buffer? To work correctly in all cases, this should rather
+ * be a proper stream filter instead of doing string matching on
+ * selected chunks of the output.
+ */
+ while ((ecp = strstr(cp, shell->noPrint)) != NULL) {
+ if (ecp != cp) {
+ *ecp = '\0'; /* XXX: avoid writing to the buffer */
+ /*
+ * The only way there wouldn't be a newline after
+ * this line is if it were the last in the buffer.
+ * however, since the noPrint output comes after it,
+ * there must be a newline, so we don't print one.
+ */
+ /* XXX: What about null bytes in the output? */
+ (void)fprintf(stdout, "%s", cp);
+ (void)fflush(stdout);
+ }
+ cp = ecp + shell->noPrintLen;
+ if (cp == endp)
+ break;
+ cp++; /* skip over the (XXX: assumed) newline */
+ pp_skip_whitespace(&cp);
}
- }
- return cp;
+ return cp;
}
/*
@@ -1704,168 +1811,170 @@ JobOutput(Job *job, char *cp, char *endp)
static void
JobDoOutput(Job *job, Boolean finish)
{
- Boolean gotNL = FALSE; /* true if got a newline */
- Boolean fbuf; /* true if our buffer filled up */
- size_t nr; /* number of bytes read */
- size_t i; /* auxiliary index into outBuf */
- size_t max; /* limit for i (end of current data) */
- ssize_t nRead; /* (Temporary) number of bytes read */
-
- /*
- * Read as many bytes as will fit in the buffer.
- */
+ Boolean gotNL; /* true if got a newline */
+ Boolean fbuf; /* true if our buffer filled up */
+ size_t nr; /* number of bytes read */
+ size_t i; /* auxiliary index into outBuf */
+ size_t max; /* limit for i (end of current data) */
+ ssize_t nRead; /* (Temporary) number of bytes read */
+
+ /* Read as many bytes as will fit in the buffer. */
again:
- gotNL = FALSE;
- fbuf = FALSE;
-
- nRead = read(job->inPipe, &job->outBuf[job->curPos],
- JOB_BUFSIZE - job->curPos);
- if (nRead < 0) {
- if (errno == EAGAIN)
- return;
- if (DEBUG(JOB)) {
- perror("JobDoOutput(piperead)");
+ gotNL = FALSE;
+ fbuf = FALSE;
+
+ nRead = read(job->inPipe, &job->outBuf[job->curPos],
+ JOB_BUFSIZE - job->curPos);
+ if (nRead < 0) {
+ if (errno == EAGAIN)
+ return;
+ if (DEBUG(JOB)) {
+ perror("JobDoOutput(piperead)");
+ }
+ nr = 0;
+ } else {
+ nr = (size_t)nRead;
}
- nr = 0;
- } else {
- nr = (size_t)nRead;
- }
-
- /*
- * If we hit the end-of-file (the job is dead), we must flush its
- * remaining output, so pretend we read a newline if there's any
- * output remaining in the buffer.
- * Also clear the 'finish' flag so we stop looping.
- */
- if (nr == 0 && job->curPos != 0) {
- job->outBuf[job->curPos] = '\n';
- nr = 1;
- finish = FALSE;
- } else if (nr == 0) {
- finish = FALSE;
- }
- /*
- * Look for the last newline in the bytes we just got. If there is
- * one, break out of the loop with 'i' as its index and gotNL set
- * TRUE.
- */
- max = job->curPos + nr;
- for (i = job->curPos + nr - 1; i >= job->curPos && i != (size_t)-1; i--) {
- if (job->outBuf[i] == '\n') {
- gotNL = TRUE;
- break;
- } else if (job->outBuf[i] == '\0') {
- /*
- * Why?
- */
- job->outBuf[i] = ' ';
+ /*
+ * If we hit the end-of-file (the job is dead), we must flush its
+ * remaining output, so pretend we read a newline if there's any
+ * output remaining in the buffer.
+ * Also clear the 'finish' flag so we stop looping.
+ */
+ if (nr == 0 && job->curPos != 0) {
+ job->outBuf[job->curPos] = '\n';
+ nr = 1;
+ finish = FALSE;
+ } else if (nr == 0) {
+ finish = FALSE;
}
- }
- if (!gotNL) {
- job->curPos += nr;
- if (job->curPos == JOB_BUFSIZE) {
- /*
- * If we've run out of buffer space, we have no choice
- * but to print the stuff. sigh.
- */
- fbuf = TRUE;
- i = job->curPos;
- }
- }
- if (gotNL || fbuf) {
/*
- * Need to send the output to the screen. Null terminate it
- * first, overwriting the newline character if there was one.
- * So long as the line isn't one we should filter (according
- * to the shell description), we print the line, preceded
- * by a target banner if this target isn't the same as the
- * one for which we last printed something.
- * The rest of the data in the buffer are then shifted down
- * to the start of the buffer and curPos is set accordingly.
+ * Look for the last newline in the bytes we just got. If there is
+ * one, break out of the loop with 'i' as its index and gotNL set
+ * TRUE.
*/
- job->outBuf[i] = '\0';
- if (i >= job->curPos) {
- char *cp;
-
- cp = JobOutput(job, job->outBuf, &job->outBuf[i]);
-
- /*
- * There's still more in that thar buffer. This time, though,
- * we know there's no newline at the end, so we add one of
- * our own free will.
- */
- if (*cp != '\0') {
- if (!opts.beSilent && job->node != lastNode) {
- MESSAGE(stdout, job->node);
- lastNode = job->node;
+ max = job->curPos + nr;
+ for (i = job->curPos + nr - 1;
+ i >= job->curPos && i != (size_t)-1; i--) {
+ if (job->outBuf[i] == '\n') {
+ gotNL = TRUE;
+ break;
+ } else if (job->outBuf[i] == '\0') {
+ /*
+ * Why?
+ */
+ job->outBuf[i] = ' ';
}
-#ifdef USE_META
- if (useMeta) {
- meta_job_output(job, cp, gotNL ? "\n" : "");
+ }
+
+ if (!gotNL) {
+ job->curPos += nr;
+ if (job->curPos == JOB_BUFSIZE) {
+ /*
+ * If we've run out of buffer space, we have no choice
+ * but to print the stuff. sigh.
+ */
+ fbuf = TRUE;
+ i = job->curPos;
}
+ }
+ if (gotNL || fbuf) {
+ /*
+ * Need to send the output to the screen. Null terminate it
+ * first, overwriting the newline character if there was one.
+ * So long as the line isn't one we should filter (according
+ * to the shell description), we print the line, preceded
+ * by a target banner if this target isn't the same as the
+ * one for which we last printed something.
+ * The rest of the data in the buffer are then shifted down
+ * to the start of the buffer and curPos is set accordingly.
+ */
+ job->outBuf[i] = '\0';
+ if (i >= job->curPos) {
+ char *cp;
+
+ cp = JobOutput(job->outBuf, &job->outBuf[i]);
+
+ /*
+ * There's still more in that thar buffer. This time,
+ * though, we know there's no newline at the end, so
+ * we add one of our own free will.
+ */
+ if (*cp != '\0') {
+ if (!opts.beSilent)
+ SwitchOutputTo(job->node);
+#ifdef USE_META
+ if (useMeta) {
+ meta_job_output(job, cp,
+ gotNL ? "\n" : "");
+ }
#endif
- (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : "");
- (void)fflush(stdout);
- }
+ (void)fprintf(stdout, "%s%s", cp,
+ gotNL ? "\n" : "");
+ (void)fflush(stdout);
+ }
+ }
+ /*
+ * max is the last offset still in the buffer. Move any
+ * remaining characters to the start of the buffer and
+ * update the end marker curPos.
+ */
+ if (i < max) {
+ (void)memmove(job->outBuf, &job->outBuf[i + 1],
+ max - (i + 1));
+ job->curPos = max - (i + 1);
+ } else {
+ assert(i == max);
+ job->curPos = 0;
+ }
}
- /*
- * max is the last offset still in the buffer. Move any remaining
- * characters to the start of the buffer and update the end marker
- * curPos.
- */
- if (i < max) {
- (void)memmove(job->outBuf, &job->outBuf[i + 1], max - (i + 1));
- job->curPos = max - (i + 1);
- } else {
- assert(i == max);
- job->curPos = 0;
+ if (finish) {
+ /*
+ * If the finish flag is true, we must loop until we hit
+ * end-of-file on the pipe. This is guaranteed to happen
+ * eventually since the other end of the pipe is now closed
+ * (we closed it explicitly and the child has exited). When
+ * we do get an EOF, finish will be set FALSE and we'll fall
+ * through and out.
+ */
+ goto again;
}
- }
- if (finish) {
- /*
- * If the finish flag is true, we must loop until we hit
- * end-of-file on the pipe. This is guaranteed to happen
- * eventually since the other end of the pipe is now closed
- * (we closed it explicitly and the child has exited). When
- * we do get an EOF, finish will be set FALSE and we'll fall
- * through and out.
- */
- goto again;
- }
}
static void
JobRun(GNode *targ)
{
#if 0
- /*
- * Unfortunately it is too complicated to run .BEGIN, .END, and
- * .INTERRUPT job in the parallel job module. As of 2020-09-25,
- * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
- *
- * Running these jobs in compat mode also guarantees that these
- * jobs do not overlap with other unrelated jobs.
- */
- List *lst = Lst_New();
- Lst_Append(lst, targ);
- (void)Make_Run(lst);
- Lst_Destroy(lst, NULL);
- JobStart(targ, JOB_SPECIAL);
- while (jobTokensRunning) {
- Job_CatchOutput();
- }
+ /*
+ * Unfortunately it is too complicated to run .BEGIN, .END, and
+ * .INTERRUPT job in the parallel job module. As of 2020-09-25,
+ * unit-tests/deptgt-end-jobs.mk hangs in an endless loop.
+ *
+ * Running these jobs in compat mode also guarantees that these
+ * jobs do not overlap with other unrelated jobs.
+ */
+ List *lst = Lst_New();
+ Lst_Append(lst, targ);
+ (void)Make_Run(lst);
+ Lst_Destroy(lst, NULL);
+ JobStart(targ, JOB_SPECIAL);
+ while (jobTokensRunning != 0) {
+ Job_CatchOutput();
+ }
#else
- Compat_Make(targ, targ);
- if (targ->made == ERROR) {
- PrintOnError(targ, "\n\nStop.");
- exit(1);
- }
+ Compat_Make(targ, targ);
+ /* XXX: Replace with GNode_IsError(gn) */
+ if (targ->made == ERROR) {
+ PrintOnError(targ, "\n\nStop.");
+ exit(1);
+ }
#endif
}
-/* Handle the exit of a child. Called from Make_Make.
+/*
+ * Handle the exit of a child. Called from Make_Make.
*
* The job descriptor is removed from the list of children.
*
@@ -1877,20 +1986,18 @@ JobRun(GNode *targ)
void
Job_CatchChildren(void)
{
- int pid; /* pid of dead child */
- WAIT_T status; /* Exit/termination status */
+ int pid; /* pid of dead child */
+ WAIT_T status; /* Exit/termination status */
- /*
- * Don't even bother if we know there's no one around.
- */
- if (jobTokensRunning == 0)
- return;
+ /* Don't even bother if we know there's no one around. */
+ if (jobTokensRunning == 0)
+ return;
- while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) {
- DEBUG2(JOB, "Process %d exited/stopped status %x.\n", pid,
- WAIT_STATUS(status));
- JobReapChild(pid, status, TRUE);
- }
+ while ((pid = waitpid((pid_t)-1, &status, WNOHANG | WUNTRACED)) > 0) {
+ DEBUG2(JOB, "Process %d exited/stopped status %x.\n",
+ pid, WAIT_STATUS(status));
+ JobReapChild(pid, status, TRUE);
+ }
}
/*
@@ -1900,318 +2007,338 @@ Job_CatchChildren(void)
void
JobReapChild(pid_t pid, WAIT_T status, Boolean isJobs)
{
- Job *job; /* job descriptor for dead child */
-
- /*
- * Don't even bother if we know there's no one around.
- */
- if (jobTokensRunning == 0)
- return;
-
- job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
- if (job == NULL) {
- if (isJobs) {
- if (!lurking_children)
- Error("Child (%d) status %x not in table?", pid, status);
+ Job *job; /* job descriptor for dead child */
+
+ /* Don't even bother if we know there's no one around. */
+ if (jobTokensRunning == 0)
+ return;
+
+ job = JobFindPid(pid, JOB_ST_RUNNING, isJobs);
+ if (job == NULL) {
+ if (isJobs) {
+ if (!lurking_children)
+ Error("Child (%d) status %x not in table?",
+ pid, status);
+ }
+ return; /* not ours */
}
- return; /* not ours */
- }
- if (WIFSTOPPED(status)) {
- DEBUG2(JOB, "Process %d (%s) stopped.\n", job->pid, job->node->name);
- if (!make_suspended) {
- switch (WSTOPSIG(status)) {
- case SIGTSTP:
- (void)printf("*** [%s] Suspended\n", job->node->name);
- break;
- case SIGSTOP:
- (void)printf("*** [%s] Stopped\n", job->node->name);
- break;
- default:
- (void)printf("*** [%s] Stopped -- signal %d\n",
- job->node->name, WSTOPSIG(status));
- }
- job->suspended = TRUE;
+ if (WIFSTOPPED(status)) {
+ DEBUG2(JOB, "Process %d (%s) stopped.\n",
+ job->pid, job->node->name);
+ if (!make_suspended) {
+ switch (WSTOPSIG(status)) {
+ case SIGTSTP:
+ (void)printf("*** [%s] Suspended\n",
+ job->node->name);
+ break;
+ case SIGSTOP:
+ (void)printf("*** [%s] Stopped\n",
+ job->node->name);
+ break;
+ default:
+ (void)printf("*** [%s] Stopped -- signal %d\n",
+ job->node->name, WSTOPSIG(status));
+ }
+ job->suspended = TRUE;
+ }
+ (void)fflush(stdout);
+ return;
}
- (void)fflush(stdout);
- return;
- }
- job->status = JOB_ST_FINISHED;
- job->exit_status = WAIT_STATUS(status);
+ job->status = JOB_ST_FINISHED;
+ job->exit_status = WAIT_STATUS(status);
- JobFinish(job, status);
+ JobFinish(job, status);
}
-/* Catch the output from our children, if we're using pipes do so. Otherwise
+/*
+ * Catch the output from our children, if we're using pipes do so. Otherwise
* just block time until we get a signal(most likely a SIGCHLD) since there's
* no point in just spinning when there's nothing to do and the reaping of a
- * child can wait for a while. */
+ * child can wait for a while.
+ */
void
Job_CatchOutput(void)
{
- int nready;
- Job *job;
- unsigned int i;
+ int nready;
+ Job *job;
+ unsigned int i;
- (void)fflush(stdout);
-
- /* The first fd in the list is the job token pipe */
- do {
- nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC);
- } while (nready < 0 && errno == EINTR);
-
- if (nready < 0)
- Punt("poll: %s", strerror(errno));
+ (void)fflush(stdout);
- if (nready > 0 && readyfd(&childExitJob)) {
- char token = 0;
- ssize_t count;
- count = read(childExitJob.inPipe, &token, 1);
- switch (count) {
- case 0:
- Punt("unexpected eof on token pipe");
- case -1:
- Punt("token pipe read: %s", strerror(errno));
- case 1:
- if (token == DO_JOB_RESUME[0])
- /* Complete relay requested from our SIGCONT handler */
- JobRestartJobs();
- break;
- default:
- abort();
- }
- nready--;
- }
+ /* The first fd in the list is the job token pipe */
+ do {
+ nready = poll(fds + 1 - wantToken, nJobs - 1 + wantToken,
+ POLL_MSEC);
+ } while (nready < 0 && errno == EINTR);
+
+ if (nready < 0)
+ Punt("poll: %s", strerror(errno));
+
+ if (nready > 0 && readyfd(&childExitJob)) {
+ char token = 0;
+ ssize_t count;
+ count = read(childExitJob.inPipe, &token, 1);
+ switch (count) {
+ case 0:
+ Punt("unexpected eof on token pipe");
+ /*NOTREACHED*/
+ case -1:
+ Punt("token pipe read: %s", strerror(errno));
+ /*NOTREACHED*/
+ case 1:
+ if (token == DO_JOB_RESUME[0])
+ /*
+ * Complete relay requested from our SIGCONT
+ * handler
+ */
+ JobRestartJobs();
+ break;
+ default:
+ abort();
+ }
+ nready--;
+ }
- Job_CatchChildren();
- if (nready == 0)
- return;
+ Job_CatchChildren();
+ if (nready == 0)
+ return;
- for (i = npseudojobs * nfds_per_job(); i < nfds; i++) {
- if (!fds[i].revents)
- continue;
- job = jobfds[i];
- if (job->status == JOB_ST_RUNNING)
- JobDoOutput(job, FALSE);
+ for (i = npseudojobs * nfds_per_job(); i < nJobs; i++) {
+ if (fds[i].revents == 0)
+ continue;
+ job = allJobs[i];
+ if (job->status == JOB_ST_RUNNING)
+ JobDoOutput(job, FALSE);
#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
- /*
- * With meta mode, we may have activity on the job's filemon
- * descriptor too, which at the moment is any pollfd other than
- * job->inPollfd.
- */
- if (useMeta && job->inPollfd != &fds[i]) {
- if (meta_job_event(job) <= 0) {
- fds[i].events = 0; /* never mind */
- }
- }
+ /*
+ * With meta mode, we may have activity on the job's filemon
+ * descriptor too, which at the moment is any pollfd other
+ * than job->inPollfd.
+ */
+ if (useMeta && job->inPollfd != &fds[i]) {
+ if (meta_job_event(job) <= 0) {
+ fds[i].events = 0; /* never mind */
+ }
+ }
#endif
- if (--nready == 0)
- return;
- }
+ if (--nready == 0)
+ return;
+ }
}
-/* Start the creation of a target. Basically a front-end for JobStart used by
- * the Make module. */
+/*
+ * Start the creation of a target. Basically a front-end for JobStart used by
+ * the Make module.
+ */
void
Job_Make(GNode *gn)
{
- (void)JobStart(gn, JOB_NONE);
+ (void)JobStart(gn, FALSE);
}
-void
-Shell_Init(void)
+static void
+InitShellNameAndPath(void)
{
- if (shellPath == NULL) {
- /*
- * We are using the default shell, which may be an absolute
- * path if DEFSHELL_CUSTOM is defined.
- */
- shellName = commandShell->name;
+ shellName = shell->name;
+
#ifdef DEFSHELL_CUSTOM
- if (*shellName == '/') {
- shellPath = shellName;
- shellName = strrchr(shellPath, '/');
- shellName++;
- } else
+ if (shellName[0] == '/') {
+ shellPath = shellName;
+ shellName = str_basename(shellPath);
+ return;
+ }
#endif
+
shellPath = str_concat3(_PATH_DEFSHELLDIR, "/", shellName);
- }
- Var_SetWithFlags(".SHELL", shellPath, VAR_CMDLINE, VAR_SET_READONLY);
- if (commandShell->exit == NULL) {
- commandShell->exit = "";
- }
- if (commandShell->echo == NULL) {
- commandShell->echo = "";
- }
- if (commandShell->hasErrCtl && commandShell->exit[0] != '\0') {
- if (shellErrFlag &&
- strcmp(commandShell->exit, &shellErrFlag[1]) != 0) {
- free(shellErrFlag);
- shellErrFlag = NULL;
- }
- if (!shellErrFlag) {
- size_t n = strlen(commandShell->exit) + 2;
-
- shellErrFlag = bmake_malloc(n);
- if (shellErrFlag) {
- snprintf(shellErrFlag, n, "-%s", commandShell->exit);
- }
- }
- } else if (shellErrFlag) {
- free(shellErrFlag);
- shellErrFlag = NULL;
- }
}
-/* Return the string literal that is used in the current command shell
- * to produce a newline character. */
+void
+Shell_Init(void)
+{
+ if (shellPath == NULL)
+ InitShellNameAndPath();
+
+ Var_SetWithFlags(".SHELL", shellPath, VAR_CMDLINE, VAR_SET_READONLY);
+ if (shell->errFlag == NULL)
+ shell->errFlag = "";
+ if (shell->echoFlag == NULL)
+ shell->echoFlag = "";
+ if (shell->hasErrCtl && shell->errFlag[0] != '\0') {
+ if (shellErrFlag != NULL &&
+ strcmp(shell->errFlag, &shellErrFlag[1]) != 0) {
+ free(shellErrFlag);
+ shellErrFlag = NULL;
+ }
+ if (shellErrFlag == NULL) {
+ size_t n = strlen(shell->errFlag) + 2;
+
+ shellErrFlag = bmake_malloc(n);
+ if (shellErrFlag != NULL)
+ snprintf(shellErrFlag, n, "-%s",
+ shell->errFlag);
+ }
+ } else if (shellErrFlag != NULL) {
+ free(shellErrFlag);
+ shellErrFlag = NULL;
+ }
+}
+
+/*
+ * Return the string literal that is used in the current command shell
+ * to produce a newline character.
+ */
const char *
Shell_GetNewline(void)
{
- return commandShell->newline;
+ return shell->newline;
}
void
Job_SetPrefix(void)
{
- if (targPrefix) {
- free(targPrefix);
- } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
- Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
- }
+ if (targPrefix != NULL) {
+ free(targPrefix);
+ } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) {
+ Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL);
+ }
- (void)Var_Subst("${" MAKE_JOB_PREFIX "}",
- VAR_GLOBAL, VARE_WANTRES, &targPrefix);
- /* TODO: handle errors */
+ (void)Var_Subst("${" MAKE_JOB_PREFIX "}",
+ VAR_GLOBAL, VARE_WANTRES, &targPrefix);
+ /* TODO: handle errors */
+}
+
+static void
+AddSig(int sig, SignalProc handler)
+{
+ if (bmake_signal(sig, SIG_IGN) != SIG_IGN) {
+ sigaddset(&caught_signals, sig);
+ (void)bmake_signal(sig, handler);
+ }
}
/* Initialize the process module. */
void
Job_Init(void)
{
- Job_SetPrefix();
- /* Allocate space for all the job info */
- job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
- memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
- job_table_end = job_table + opts.maxJobs;
- wantToken = 0;
+ Job_SetPrefix();
+ /* Allocate space for all the job info */
+ job_table = bmake_malloc((size_t)opts.maxJobs * sizeof *job_table);
+ memset(job_table, 0, (size_t)opts.maxJobs * sizeof *job_table);
+ job_table_end = job_table + opts.maxJobs;
+ wantToken = 0;
- aborting = ABORT_NONE;
- errors = 0;
+ aborting = ABORT_NONE;
+ job_errors = 0;
- lastNode = NULL;
-
- /*
- * There is a non-zero chance that we already have children.
- * eg after 'make -f- <<EOF'
- * Since their termination causes a 'Child (pid) not in table' message,
- * Collect the status of any that are already dead, and suppress the
- * error message if there are any undead ones.
- */
- for (;;) {
- int rval, status;
- rval = waitpid((pid_t) -1, &status, WNOHANG);
- if (rval > 0)
- continue;
- if (rval == 0)
- lurking_children = TRUE;
- break;
- }
-
- Shell_Init();
+ /*
+ * There is a non-zero chance that we already have children.
+ * eg after 'make -f- <<EOF'
+ * Since their termination causes a 'Child (pid) not in table'
+ * message, Collect the status of any that are already dead, and
+ * suppress the error message if there are any undead ones.
+ */
+ for (;;) {
+ int rval;
+ WAIT_T status;
+
+ rval = waitpid((pid_t)-1, &status, WNOHANG);
+ if (rval > 0)
+ continue;
+ if (rval == 0)
+ lurking_children = TRUE;
+ break;
+ }
- JobCreatePipe(&childExitJob, 3);
+ Shell_Init();
- /* Preallocate enough for the maximum number of jobs. */
- fds = bmake_malloc(sizeof *fds *
- (npseudojobs + (size_t)opts.maxJobs) * nfds_per_job());
- jobfds = bmake_malloc(sizeof *jobfds *
- (npseudojobs + (size_t)opts.maxJobs) * nfds_per_job());
+ JobCreatePipe(&childExitJob, 3);
- /* These are permanent entries and take slots 0 and 1 */
- watchfd(&tokenWaitJob);
- watchfd(&childExitJob);
+ /* Preallocate enough for the maximum number of jobs. */
+ fds = bmake_malloc(sizeof *fds *
+ (npseudojobs + (size_t)opts.maxJobs) *
+ nfds_per_job());
+ allJobs = bmake_malloc(sizeof *allJobs *
+ (npseudojobs + (size_t)opts.maxJobs) *
+ nfds_per_job());
- sigemptyset(&caught_signals);
- /*
- * Install a SIGCHLD handler.
- */
- (void)bmake_signal(SIGCHLD, JobChildSig);
- sigaddset(&caught_signals, SIGCHLD);
+ /* These are permanent entries and take slots 0 and 1 */
+ watchfd(&tokenWaitJob);
+ watchfd(&childExitJob);
-#define ADDSIG(s,h) \
- if (bmake_signal(s, SIG_IGN) != SIG_IGN) { \
- sigaddset(&caught_signals, s); \
- (void)bmake_signal(s, h); \
- }
-
- /*
- * Catch the four signals that POSIX specifies if they aren't ignored.
- * JobPassSig will take care of calling JobInterrupt if appropriate.
- */
- ADDSIG(SIGINT, JobPassSig_int)
- ADDSIG(SIGHUP, JobPassSig_term)
- ADDSIG(SIGTERM, JobPassSig_term)
- ADDSIG(SIGQUIT, JobPassSig_term)
+ sigemptyset(&caught_signals);
+ /*
+ * Install a SIGCHLD handler.
+ */
+ (void)bmake_signal(SIGCHLD, JobChildSig);
+ sigaddset(&caught_signals, SIGCHLD);
- /*
- * There are additional signals that need to be caught and passed if
- * either the export system wants to be told directly of signals or if
- * we're giving each job its own process group (since then it won't get
- * signals from the terminal driver as we own the terminal)
- */
- ADDSIG(SIGTSTP, JobPassSig_suspend)
- ADDSIG(SIGTTOU, JobPassSig_suspend)
- ADDSIG(SIGTTIN, JobPassSig_suspend)
- ADDSIG(SIGWINCH, JobCondPassSig)
- ADDSIG(SIGCONT, JobContinueSig)
-#undef ADDSIG
+ /*
+ * Catch the four signals that POSIX specifies if they aren't ignored.
+ * JobPassSig will take care of calling JobInterrupt if appropriate.
+ */
+ AddSig(SIGINT, JobPassSig_int);
+ AddSig(SIGHUP, JobPassSig_term);
+ AddSig(SIGTERM, JobPassSig_term);
+ AddSig(SIGQUIT, JobPassSig_term);
- (void)Job_RunTarget(".BEGIN", NULL);
- /* Create the .END node now, even though no code in the unit tests
- * depends on it. See also Targ_GetEndNode in Compat_Run. */
- (void)Targ_GetEndNode();
+ /*
+ * There are additional signals that need to be caught and passed if
+ * either the export system wants to be told directly of signals or if
+ * we're giving each job its own process group (since then it won't get
+ * signals from the terminal driver as we own the terminal)
+ */
+ AddSig(SIGTSTP, JobPassSig_suspend);
+ AddSig(SIGTTOU, JobPassSig_suspend);
+ AddSig(SIGTTIN, JobPassSig_suspend);
+ AddSig(SIGWINCH, JobCondPassSig);
+ AddSig(SIGCONT, JobContinueSig);
+
+ (void)Job_RunTarget(".BEGIN", NULL);
+ /* Create the .END node now, even though no code in the unit tests
+ * depends on it. See also Targ_GetEndNode in Compat_Run. */
+ (void)Targ_GetEndNode();
}
-static void JobSigReset(void)
+static void
+DelSig(int sig)
{
-#define DELSIG(s) \
- if (sigismember(&caught_signals, s)) { \
- (void)bmake_signal(s, SIG_DFL); \
- }
+ if (sigismember(&caught_signals, sig) != 0)
+ (void)bmake_signal(sig, SIG_DFL);
+}
- DELSIG(SIGINT)
- DELSIG(SIGHUP)
- DELSIG(SIGQUIT)
- DELSIG(SIGTERM)
- DELSIG(SIGTSTP)
- DELSIG(SIGTTOU)
- DELSIG(SIGTTIN)
- DELSIG(SIGWINCH)
- DELSIG(SIGCONT)
-#undef DELSIG
- (void)bmake_signal(SIGCHLD, SIG_DFL);
+static void
+JobSigReset(void)
+{
+ DelSig(SIGINT);
+ DelSig(SIGHUP);
+ DelSig(SIGQUIT);
+ DelSig(SIGTERM);
+ DelSig(SIGTSTP);
+ DelSig(SIGTTOU);
+ DelSig(SIGTTIN);
+ DelSig(SIGWINCH);
+ DelSig(SIGCONT);
+ (void)bmake_signal(SIGCHLD, SIG_DFL);
}
/* Find a shell in 'shells' given its name, or return NULL. */
static Shell *
FindShellByName(const char *name)
{
- Shell *sh = shells;
- const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
+ Shell *sh = shells;
+ const Shell *shellsEnd = sh + sizeof shells / sizeof shells[0];
- for (sh = shells; sh < shellsEnd; sh++) {
- if (strcmp(name, sh->name) == 0)
- return sh;
- }
- return NULL;
+ for (sh = shells; sh < shellsEnd; sh++) {
+ if (strcmp(name, sh->name) == 0)
+ return sh;
+ }
+ return NULL;
}
-/*-
- *-----------------------------------------------------------------------
- * Job_ParseShell --
- * Parse a shell specification and set up commandShell, shellPath
- * and shellName appropriately.
+/*
+ * Parse a shell specification and set up 'shell', shellPath and
+ * shellName appropriately.
*
* Input:
* line The shell spec
@@ -2220,9 +2347,9 @@ FindShellByName(const char *name)
* FALSE if the specification was incorrect.
*
* Side Effects:
- * commandShell points to a Shell structure (either predefined or
+ * 'shell' points to a Shell structure (either predefined or
* created from the shell spec), shellPath is the full path of the
- * shell described by commandShell, while shellName is just the
+ * shell described by 'shell', while shellName is just the
* final component of shellPath.
*
* Notes:
@@ -2251,166 +2378,174 @@ FindShellByName(const char *name)
* is TRUE or template of command to execute a
* command so as to ignore any errors it returns if
* hasErrCtl is FALSE.
- *
- *-----------------------------------------------------------------------
*/
Boolean
Job_ParseShell(char *line)
{
- Words wordsList;
- char **words;
- char **argv;
- size_t argc;
- char *path;
- Shell newShell;
- Boolean fullSpec = FALSE;
- Shell *sh;
-
- pp_skip_whitespace(&line);
+ Words wordsList;
+ char **words;
+ char **argv;
+ size_t argc;
+ char *path;
+ Shell newShell;
+ Boolean fullSpec = FALSE;
+ Shell *sh;
- free(shellArgv);
+ /* XXX: don't use line as an iterator variable */
+ pp_skip_whitespace(&line);
- memset(&newShell, 0, sizeof newShell);
+ free(shellArgv);
- /*
- * Parse the specification by keyword
- */
- wordsList = Str_Words(line, TRUE);
- words = wordsList.words;
- argc = wordsList.len;
- path = wordsList.freeIt;
- if (words == NULL) {
- Error("Unterminated quoted string [%s]", line);
- return FALSE;
- }
- shellArgv = path;
-
- for (path = NULL, argv = words; argc != 0; argc--, argv++) {
- char *arg = *argv;
- if (strncmp(arg, "path=", 5) == 0) {
- path = arg + 5;
- } else if (strncmp(arg, "name=", 5) == 0) {
- newShell.name = arg + 5;
- } else {
- if (strncmp(arg, "quiet=", 6) == 0) {
- newShell.echoOff = arg + 6;
- } else if (strncmp(arg, "echo=", 5) == 0) {
- newShell.echoOn = arg + 5;
- } else if (strncmp(arg, "filter=", 7) == 0) {
- newShell.noPrint = arg + 7;
- newShell.noPrintLen = strlen(newShell.noPrint);
- } else if (strncmp(arg, "echoFlag=", 9) == 0) {
- newShell.echo = arg + 9;
- } else if (strncmp(arg, "errFlag=", 8) == 0) {
- newShell.exit = arg + 8;
- } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
- char c = arg[10];
- newShell.hasErrCtl = c == 'Y' || c == 'y' ||
- c == 'T' || c == 't';
- } else if (strncmp(arg, "newline=", 8) == 0) {
- newShell.newline = arg + 8;
- } else if (strncmp(arg, "check=", 6) == 0) {
- newShell.errOnOrEcho = arg + 6;
- } else if (strncmp(arg, "ignore=", 7) == 0) {
- newShell.errOffOrExecIgnore = arg + 7;
- } else if (strncmp(arg, "errout=", 7) == 0) {
- newShell.errExit = arg + 7;
- } else if (strncmp(arg, "comment=", 8) == 0) {
- newShell.commentChar = arg[8];
- } else {
- Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"", arg);
- free(words);
- return FALSE;
- }
- fullSpec = TRUE;
- }
- }
+ memset(&newShell, 0, sizeof newShell);
- if (path == NULL) {
/*
- * If no path was given, the user wants one of the pre-defined shells,
- * yes? So we find the one s/he wants with the help of FindShellByName
- * and set things up the right way. shellPath will be set up by
- * Shell_Init.
+ * Parse the specification by keyword
*/
- if (newShell.name == NULL) {
- Parse_Error(PARSE_FATAL, "Neither path nor name specified");
- free(words);
- return FALSE;
- } else {
- if ((sh = FindShellByName(newShell.name)) == NULL) {
- Parse_Error(PARSE_WARNING, "%s: No matching shell",
- newShell.name);
- free(words);
- return FALSE;
- }
- commandShell = sh;
- shellName = newShell.name;
- if (shellPath) {
- /* Shell_Init has already been called! Do it again. */
- free(UNCONST(shellPath));
- shellPath = NULL;
- Shell_Init();
- }
+ wordsList = Str_Words(line, TRUE);
+ words = wordsList.words;
+ argc = wordsList.len;
+ path = wordsList.freeIt;
+ if (words == NULL) {
+ Error("Unterminated quoted string [%s]", line);
+ return FALSE;
}
- } else {
- /*
- * The user provided a path. If s/he gave nothing else (fullSpec is
- * FALSE), try and find a matching shell in the ones we know of.
- * Else we just take the specification at its word and copy it
- * to a new location. In either case, we need to record the
- * path the user gave for the shell.
- */
- shellPath = path;
- path = strrchr(path, '/');
- if (path == NULL) {
- path = UNCONST(shellPath);
- } else {
- path++;
+ shellArgv = path;
+
+ for (path = NULL, argv = words; argc != 0; argc--, argv++) {
+ char *arg = *argv;
+ if (strncmp(arg, "path=", 5) == 0) {
+ path = arg + 5;
+ } else if (strncmp(arg, "name=", 5) == 0) {
+ newShell.name = arg + 5;
+ } else {
+ if (strncmp(arg, "quiet=", 6) == 0) {
+ newShell.echoOff = arg + 6;
+ } else if (strncmp(arg, "echo=", 5) == 0) {
+ newShell.echoOn = arg + 5;
+ } else if (strncmp(arg, "filter=", 7) == 0) {
+ newShell.noPrint = arg + 7;
+ newShell.noPrintLen = strlen(newShell.noPrint);
+ } else if (strncmp(arg, "echoFlag=", 9) == 0) {
+ newShell.echoFlag = arg + 9;
+ } else if (strncmp(arg, "errFlag=", 8) == 0) {
+ newShell.errFlag = arg + 8;
+ } else if (strncmp(arg, "hasErrCtl=", 10) == 0) {
+ char c = arg[10];
+ newShell.hasErrCtl = c == 'Y' || c == 'y' ||
+ c == 'T' || c == 't';
+ } else if (strncmp(arg, "newline=", 8) == 0) {
+ newShell.newline = arg + 8;
+ } else if (strncmp(arg, "check=", 6) == 0) {
+ /* Before 2020-12-10, these two variables
+ * had been a single variable. */
+ newShell.errOn = arg + 6;
+ newShell.echoTmpl = arg + 6;
+ } else if (strncmp(arg, "ignore=", 7) == 0) {
+ /* Before 2020-12-10, these two variables
+ * had been a single variable. */
+ newShell.errOff = arg + 7;
+ newShell.runIgnTmpl = arg + 7;
+ } else if (strncmp(arg, "errout=", 7) == 0) {
+ newShell.runChkTmpl = arg + 7;
+ } else if (strncmp(arg, "comment=", 8) == 0) {
+ newShell.commentChar = arg[8];
+ } else {
+ Parse_Error(PARSE_FATAL,
+ "Unknown keyword \"%s\"", arg);
+ free(words);
+ return FALSE;
+ }
+ fullSpec = TRUE;
+ }
}
- if (newShell.name != NULL) {
- shellName = newShell.name;
- } else {
- shellName = path;
- }
- if (!fullSpec) {
- if ((sh = FindShellByName(shellName)) == NULL) {
- Parse_Error(PARSE_WARNING, "%s: No matching shell",
- shellName);
- free(words);
- return FALSE;
- }
- commandShell = sh;
+
+ if (path == NULL) {
+ /*
+ * If no path was given, the user wants one of the
+ * pre-defined shells, yes? So we find the one s/he wants
+ * with the help of FindShellByName and set things up the
+ * right way. shellPath will be set up by Shell_Init.
+ */
+ if (newShell.name == NULL) {
+ Parse_Error(PARSE_FATAL,
+ "Neither path nor name specified");
+ free(words);
+ return FALSE;
+ } else {
+ if ((sh = FindShellByName(newShell.name)) == NULL) {
+ Parse_Error(PARSE_WARNING,
+ "%s: No matching shell", newShell.name);
+ free(words);
+ return FALSE;
+ }
+ shell = sh;
+ shellName = newShell.name;
+ if (shellPath != NULL) {
+ /*
+ * Shell_Init has already been called!
+ * Do it again.
+ */
+ free(UNCONST(shellPath));
+ shellPath = NULL;
+ Shell_Init();
+ }
+ }
} else {
- commandShell = bmake_malloc(sizeof *commandShell);
- *commandShell = newShell;
+ /*
+ * The user provided a path. If s/he gave nothing else
+ * (fullSpec is FALSE), try and find a matching shell in the
+ * ones we know of. Else we just take the specification at
+ * its word and copy it to a new location. In either case,
+ * we need to record the path the user gave for the shell.
+ */
+ shellPath = path;
+ path = strrchr(path, '/');
+ if (path == NULL) {
+ path = UNCONST(shellPath);
+ } else {
+ path++;
+ }
+ if (newShell.name != NULL) {
+ shellName = newShell.name;
+ } else {
+ shellName = path;
+ }
+ if (!fullSpec) {
+ if ((sh = FindShellByName(shellName)) == NULL) {
+ Parse_Error(PARSE_WARNING,
+ "%s: No matching shell", shellName);
+ free(words);
+ return FALSE;
+ }
+ shell = sh;
+ } else {
+ shell = bmake_malloc(sizeof *shell);
+ *shell = newShell;
+ }
+ /* this will take care of shellErrFlag */
+ Shell_Init();
}
- /* this will take care of shellErrFlag */
- Shell_Init();
- }
- if (commandShell->echoOn && commandShell->echoOff) {
- commandShell->hasEchoCtl = TRUE;
- }
+ if (shell->echoOn != NULL && shell->echoOff != NULL)
+ shell->hasEchoCtl = TRUE;
- if (!commandShell->hasErrCtl) {
- if (commandShell->errOnOrEcho == NULL) {
- commandShell->errOnOrEcho = "";
- }
- if (commandShell->errOffOrExecIgnore == NULL) {
- commandShell->errOffOrExecIgnore = "%s\n";
+ if (!shell->hasErrCtl) {
+ if (shell->echoTmpl == NULL)
+ shell->echoTmpl = "";
+ if (shell->runIgnTmpl == NULL)
+ shell->runIgnTmpl = "%s\n";
}
- }
- /*
- * Do not free up the words themselves, since they might be in use by the
- * shell specification.
- */
- free(words);
- return TRUE;
+ /*
+ * Do not free up the words themselves, since they might be in use
+ * by the shell specification.
+ */
+ free(words);
+ return TRUE;
}
-/* Handle the receipt of an interrupt.
+/*
+ * Handle the receipt of an interrupt.
*
* All children are killed. Another job will be started if the .INTERRUPT
* target is defined.
@@ -2421,59 +2556,63 @@ Job_ParseShell(char *line)
* signo signal received
*/
static void
-JobInterrupt(int runINTERRUPT, int signo)
+JobInterrupt(Boolean runINTERRUPT, int signo)
{
- Job *job; /* job descriptor in that element */
- GNode *interrupt; /* the node describing the .INTERRUPT target */
- sigset_t mask;
- GNode *gn;
+ Job *job; /* job descriptor in that element */
+ GNode *interrupt; /* the node describing the .INTERRUPT target */
+ sigset_t mask;
+ GNode *gn;
- aborting = ABORT_INTERRUPT;
+ aborting = ABORT_INTERRUPT;
- JobSigLock(&mask);
+ JobSigLock(&mask);
- for (job = job_table; job < job_table_end; job++) {
- if (job->status != JOB_ST_RUNNING)
- continue;
+ for (job = job_table; job < job_table_end; job++) {
+ if (job->status != JOB_ST_RUNNING)
+ continue;
- gn = job->node;
+ gn = job->node;
- JobDeleteTarget(gn);
- if (job->pid) {
- DEBUG2(JOB, "JobInterrupt passing signal %d to child %d.\n",
- signo, job->pid);
- KILLPG(job->pid, signo);
+ JobDeleteTarget(gn);
+ if (job->pid != 0) {
+ DEBUG2(JOB,
+ "JobInterrupt passing signal %d to child %d.\n",
+ signo, job->pid);
+ KILLPG(job->pid, signo);
+ }
}
- }
- JobSigUnlock(&mask);
+ JobSigUnlock(&mask);
- if (runINTERRUPT && !opts.touchFlag) {
- interrupt = Targ_FindNode(".INTERRUPT");
- if (interrupt != NULL) {
- opts.ignoreErrors = FALSE;
- JobRun(interrupt);
+ if (runINTERRUPT && !opts.touchFlag) {
+ interrupt = Targ_FindNode(".INTERRUPT");
+ if (interrupt != NULL) {
+ opts.ignoreErrors = FALSE;
+ JobRun(interrupt);
+ }
}
- }
- Trace_Log(MAKEINTR, NULL);
- exit(signo);
+ Trace_Log(MAKEINTR, NULL);
+ exit(signo); /* XXX: why signo? */
}
-/* Do the final processing, i.e. run the commands attached to the .END target.
+/*
+ * Do the final processing, i.e. run the commands attached to the .END target.
*
- * Return the number of errors reported. */
+ * Return the number of errors reported.
+ */
int
Job_Finish(void)
{
- GNode *endNode = Targ_GetEndNode();
- if (!Lst_IsEmpty(endNode->commands) || !Lst_IsEmpty(endNode->children)) {
- if (errors) {
- Error("Errors reported so .END ignored");
- } else {
- JobRun(endNode);
+ GNode *endNode = Targ_GetEndNode();
+ if (!Lst_IsEmpty(&endNode->commands) ||
+ !Lst_IsEmpty(&endNode->children)) {
+ if (job_errors != 0) {
+ Error("Errors reported so .END ignored");
+ } else {
+ JobRun(endNode);
+ }
}
- }
- return errors;
+ return job_errors;
}
/* Clean up any memory used by the jobs module. */
@@ -2481,344 +2620,369 @@ void
Job_End(void)
{
#ifdef CLEANUP
- free(shellArgv);
+ free(shellArgv);
#endif
}
-/* Waits for all running jobs to finish and returns.
- * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting. */
+/*
+ * Waits for all running jobs to finish and returns.
+ * Sets 'aborting' to ABORT_WAIT to prevent other jobs from starting.
+ */
void
Job_Wait(void)
{
- aborting = ABORT_WAIT;
- while (jobTokensRunning != 0) {
- Job_CatchOutput();
- }
- aborting = ABORT_NONE;
+ aborting = ABORT_WAIT;
+ while (jobTokensRunning != 0) {
+ Job_CatchOutput();
+ }
+ aborting = ABORT_NONE;
}
-/* Abort all currently running jobs without handling output or anything.
+/*
+ * Abort all currently running jobs without handling output or anything.
* This function is to be called only in the event of a major error.
* Most definitely NOT to be called from JobInterrupt.
*
- * All children are killed, not just the firstborn. */
+ * All children are killed, not just the firstborn.
+ */
void
Job_AbortAll(void)
{
- Job *job; /* the job descriptor in that element */
- WAIT_T foo;
-
- aborting = ABORT_ERROR;
-
- if (jobTokensRunning) {
- for (job = job_table; job < job_table_end; job++) {
- if (job->status != JOB_ST_RUNNING)
- continue;
- /*
- * kill the child process with increasingly drastic signals to make
- * darn sure it's dead.
- */
- KILLPG(job->pid, SIGINT);
- KILLPG(job->pid, SIGKILL);
+ Job *job; /* the job descriptor in that element */
+ WAIT_T foo;
+
+ aborting = ABORT_ERROR;
+
+ if (jobTokensRunning != 0) {
+ for (job = job_table; job < job_table_end; job++) {
+ if (job->status != JOB_ST_RUNNING)
+ continue;
+ /*
+ * kill the child process with increasingly drastic
+ * signals to make darn sure it's dead.
+ */
+ KILLPG(job->pid, SIGINT);
+ KILLPG(job->pid, SIGKILL);
+ }
}
- }
- /*
- * Catch as many children as want to report in at first, then give up
- */
- while (waitpid((pid_t) -1, &foo, WNOHANG) > 0)
- continue;
+ /*
+ * Catch as many children as want to report in at first, then give up
+ */
+ while (waitpid((pid_t)-1, &foo, WNOHANG) > 0)
+ continue;
}
-/* Tries to restart stopped jobs if there are slots available.
- * Called in process context in response to a SIGCONT. */
+/*
+ * Tries to restart stopped jobs if there are slots available.
+ * Called in process context in response to a SIGCONT.
+ */
static void
JobRestartJobs(void)
{
- Job *job;
-
- for (job = job_table; job < job_table_end; job++) {
- if (job->status == JOB_ST_RUNNING &&
- (make_suspended || job->suspended)) {
- DEBUG1(JOB, "Restarting stopped job pid %d.\n", job->pid);
- if (job->suspended) {
- (void)printf("*** [%s] Continued\n", job->node->name);
- (void)fflush(stdout);
- }
- job->suspended = FALSE;
- if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
- debug_printf("Failed to send SIGCONT to %d\n", job->pid);
- }
- }
- if (job->status == JOB_ST_FINISHED)
- /* Job exit deferred after calling waitpid() in a signal handler */
- JobFinish(job, job->exit_status);
- }
- make_suspended = FALSE;
+ Job *job;
+
+ for (job = job_table; job < job_table_end; job++) {
+ if (job->status == JOB_ST_RUNNING &&
+ (make_suspended || job->suspended)) {
+ DEBUG1(JOB, "Restarting stopped job pid %d.\n",
+ job->pid);
+ if (job->suspended) {
+ (void)printf("*** [%s] Continued\n",
+ job->node->name);
+ (void)fflush(stdout);
+ }
+ job->suspended = FALSE;
+ if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) {
+ debug_printf("Failed to send SIGCONT to %d\n",
+ job->pid);
+ }
+ }
+ if (job->status == JOB_ST_FINISHED) {
+ /*
+ * Job exit deferred after calling waitpid() in a
+ * signal handler
+ */
+ JobFinish(job, job->exit_status);
+ }
+ }
+ make_suspended = FALSE;
}
static void
watchfd(Job *job)
{
- if (job->inPollfd != NULL)
- Punt("Watching watched job");
-
- fds[nfds].fd = job->inPipe;
- fds[nfds].events = POLLIN;
- jobfds[nfds] = job;
- job->inPollfd = &fds[nfds];
- nfds++;
+ if (job->inPollfd != NULL)
+ Punt("Watching watched job");
+
+ fds[nJobs].fd = job->inPipe;
+ fds[nJobs].events = POLLIN;
+ allJobs[nJobs] = job;
+ job->inPollfd = &fds[nJobs];
+ nJobs++;
#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
- if (useMeta) {
- fds[nfds].fd = meta_job_fd(job);
- fds[nfds].events = fds[nfds].fd == -1 ? 0 : POLLIN;
- jobfds[nfds] = job;
- nfds++;
- }
+ if (useMeta) {
+ fds[nJobs].fd = meta_job_fd(job);
+ fds[nJobs].events = fds[nJobs].fd == -1 ? 0 : POLLIN;
+ allJobs[nJobs] = job;
+ nJobs++;
+ }
#endif
}
static void
clearfd(Job *job)
{
- size_t i;
- if (job->inPollfd == NULL)
- Punt("Unwatching unwatched job");
- i = (size_t)(job->inPollfd - fds);
- nfds--;
+ size_t i;
+ if (job->inPollfd == NULL)
+ Punt("Unwatching unwatched job");
+ i = (size_t)(job->inPollfd - fds);
+ nJobs--;
#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
- if (useMeta) {
+ if (useMeta) {
+ /*
+ * Sanity check: there should be two fds per job, so the job's
+ * pollfd number should be even.
+ */
+ assert(nfds_per_job() == 2);
+ if (i % 2 != 0)
+ Punt("odd-numbered fd with meta");
+ nJobs--;
+ }
+#endif
/*
- * Sanity check: there should be two fds per job, so the job's
- * pollfd number should be even.
+ * Move last job in table into hole made by dead job.
*/
- assert(nfds_per_job() == 2);
- if (i % 2)
- Punt("odd-numbered fd with meta");
- nfds--;
- }
-#endif
- /*
- * Move last job in table into hole made by dead job.
- */
- if (nfds != i) {
- fds[i] = fds[nfds];
- jobfds[i] = jobfds[nfds];
- jobfds[i]->inPollfd = &fds[i];
+ if (nJobs != i) {
+ fds[i] = fds[nJobs];
+ allJobs[i] = allJobs[nJobs];
+ allJobs[i]->inPollfd = &fds[i];
#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV)
- if (useMeta) {
- fds[i + 1] = fds[nfds + 1];
- jobfds[i + 1] = jobfds[nfds + 1];
- }
+ if (useMeta) {
+ fds[i + 1] = fds[nJobs + 1];
+ allJobs[i + 1] = allJobs[nJobs + 1];
+ }
#endif
- }
- job->inPollfd = NULL;
+ }
+ job->inPollfd = NULL;
}
-static int
+static Boolean
readyfd(Job *job)
{
- if (job->inPollfd == NULL)
- Punt("Polling unwatched job");
- return (job->inPollfd->revents & POLLIN) != 0;
+ if (job->inPollfd == NULL)
+ Punt("Polling unwatched job");
+ return (job->inPollfd->revents & POLLIN) != 0;
}
-/* Put a token (back) into the job pipe.
- * This allows a make process to start a build job. */
+/*
+ * Put a token (back) into the job pipe.
+ * This allows a make process to start a build job.
+ */
static void
JobTokenAdd(void)
{
- char tok = JOB_TOKENS[aborting], tok1;
+ char tok = JOB_TOKENS[aborting], tok1;
- /* If we are depositing an error token flush everything else */
- while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
- continue;
+ /* If we are depositing an error token flush everything else */
+ while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1)
+ continue;
- DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
- getpid(), aborting, tok);
- while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
- continue;
+ DEBUG3(JOB, "(%d) aborting %d, deposit token %c\n",
+ getpid(), aborting, tok);
+ while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
+ continue;
}
/* Prep the job token pipe in the root make process. */
void
Job_ServerStart(int max_tokens, int jp_0, int jp_1)
{
- int i;
- char jobarg[64];
-
- if (jp_0 >= 0 && jp_1 >= 0) {
- /* Pipe passed in from parent */
- tokenWaitJob.inPipe = jp_0;
- tokenWaitJob.outPipe = jp_1;
- (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
- (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
- return;
- }
+ int i;
+ char jobarg[64];
+
+ if (jp_0 >= 0 && jp_1 >= 0) {
+ /* Pipe passed in from parent */
+ tokenWaitJob.inPipe = jp_0;
+ tokenWaitJob.outPipe = jp_1;
+ (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC);
+ (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC);
+ return;
+ }
- JobCreatePipe(&tokenWaitJob, 15);
+ JobCreatePipe(&tokenWaitJob, 15);
- snprintf(jobarg, sizeof jobarg, "%d,%d",
+ snprintf(jobarg, sizeof jobarg, "%d,%d",
tokenWaitJob.inPipe, tokenWaitJob.outPipe);
- Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
- Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
+ Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
+ Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL);
- /*
- * Preload the job pipe with one token per job, save the one
- * "extra" token for the primary job.
- *
- * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
- * larger than the write buffer size of the pipe, we will
- * deadlock here.
- */
- for (i = 1; i < max_tokens; i++)
- JobTokenAdd();
+ /*
+ * Preload the job pipe with one token per job, save the one
+ * "extra" token for the primary job.
+ *
+ * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is
+ * larger than the write buffer size of the pipe, we will
+ * deadlock here.
+ */
+ for (i = 1; i < max_tokens; i++)
+ JobTokenAdd();
}
/* Return a withdrawn token to the pool. */
void
Job_TokenReturn(void)
{
- jobTokensRunning--;
- if (jobTokensRunning < 0)
- Punt("token botch");
- if (jobTokensRunning || JOB_TOKENS[aborting] != '+')
- JobTokenAdd();
+ jobTokensRunning--;
+ if (jobTokensRunning < 0)
+ Punt("token botch");
+ if (jobTokensRunning != 0 || JOB_TOKENS[aborting] != '+')
+ JobTokenAdd();
}
-/* Attempt to withdraw a token from the pool.
+/*
+ * Attempt to withdraw a token from the pool.
*
* If pool is empty, set wantToken so that we wake up when a token is
* released.
*
* Returns TRUE if a token was withdrawn, and FALSE if the pool is currently
- * empty. */
+ * empty.
+ */
Boolean
Job_TokenWithdraw(void)
{
- char tok, tok1;
- ssize_t count;
+ char tok, tok1;
+ ssize_t count;
- wantToken = 0;
- DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
- getpid(), aborting, jobTokensRunning);
+ wantToken = 0;
+ DEBUG3(JOB, "Job_TokenWithdraw(%d): aborting %d, running %d\n",
+ getpid(), aborting, jobTokensRunning);
- if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
- return FALSE;
+ if (aborting != ABORT_NONE || (jobTokensRunning >= opts.maxJobs))
+ return FALSE;
- count = read(tokenWaitJob.inPipe, &tok, 1);
- if (count == 0)
- Fatal("eof on job pipe!");
- if (count < 0 && jobTokensRunning != 0) {
- if (errno != EAGAIN) {
- Fatal("job pipe read: %s", strerror(errno));
+ count = read(tokenWaitJob.inPipe, &tok, 1);
+ if (count == 0)
+ Fatal("eof on job pipe!");
+ if (count < 0 && jobTokensRunning != 0) {
+ if (errno != EAGAIN) {
+ Fatal("job pipe read: %s", strerror(errno));
+ }
+ DEBUG1(JOB, "(%d) blocked for token\n", getpid());
+ wantToken = 1;
+ return FALSE;
}
- DEBUG1(JOB, "(%d) blocked for token\n", getpid());
- return FALSE;
- }
- if (count == 1 && tok != '+') {
- /* make being abvorted - remove any other job tokens */
- DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
- while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
- continue;
- /* And put the stopper back */
- while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
- continue;
- if (shouldDieQuietly(NULL, 1))
- exit(2);
- Fatal("A failure has been detected in another branch of the parallel make");
- }
+ if (count == 1 && tok != '+') {
+ /* make being aborted - remove any other job tokens */
+ DEBUG2(JOB, "(%d) aborted by token %c\n", getpid(), tok);
+ while (read(tokenWaitJob.inPipe, &tok1, 1) == 1)
+ continue;
+ /* And put the stopper back */
+ while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
+ errno == EAGAIN)
+ continue;
+ if (shouldDieQuietly(NULL, 1))
+ exit(6); /* we aborted */
+ Fatal("A failure has been detected "
+ "in another branch of the parallel make");
+ }
- if (count == 1 && jobTokensRunning == 0)
- /* We didn't want the token really */
- while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN)
- continue;
+ if (count == 1 && jobTokensRunning == 0)
+ /* We didn't want the token really */
+ while (write(tokenWaitJob.outPipe, &tok, 1) == -1 &&
+ errno == EAGAIN)
+ continue;
- jobTokensRunning++;
- DEBUG1(JOB, "(%d) withdrew token\n", getpid());
- return TRUE;
+ jobTokensRunning++;
+ DEBUG1(JOB, "(%d) withdrew token\n", getpid());
+ return TRUE;
}
-/* Run the named target if found. If a filename is specified, then set that
+/*
+ * Run the named target if found. If a filename is specified, then set that
* to the sources.
*
- * Exits if the target fails. */
+ * Exits if the target fails.
+ */
Boolean
-Job_RunTarget(const char *target, const char *fname) {
- GNode *gn = Targ_FindNode(target);
- if (gn == NULL)
- return FALSE;
+Job_RunTarget(const char *target, const char *fname)
+{
+ GNode *gn = Targ_FindNode(target);
+ if (gn == NULL)
+ return FALSE;
- if (fname)
- Var_Set(ALLSRC, fname, gn);
+ if (fname != NULL)
+ Var_Set(ALLSRC, fname, gn);
- JobRun(gn);
- if (gn->made == ERROR) {
- PrintOnError(gn, "\n\nStop.");
- exit(1);
- }
- return TRUE;
+ JobRun(gn);
+ /* XXX: Replace with GNode_IsError(gn) */
+ if (gn->made == ERROR) {
+ PrintOnError(gn, "\n\nStop.");
+ exit(1);
+ }
+ return TRUE;
}
#ifdef USE_SELECT
int
emul_poll(struct pollfd *fd, int nfd, int timeout)
{
- fd_set rfds, wfds;
- int i, maxfd, nselect, npoll;
- struct timeval tv, *tvp;
- long usecs;
+ fd_set rfds, wfds;
+ int i, maxfd, nselect, npoll;
+ struct timeval tv, *tvp;
+ long usecs;
- FD_ZERO(&rfds);
- FD_ZERO(&wfds);
+ FD_ZERO(&rfds);
+ FD_ZERO(&wfds);
- maxfd = -1;
- for (i = 0; i < nfd; i++) {
- fd[i].revents = 0;
+ maxfd = -1;
+ for (i = 0; i < nfd; i++) {
+ fd[i].revents = 0;
- if (fd[i].events & POLLIN)
- FD_SET(fd[i].fd, &rfds);
+ if (fd[i].events & POLLIN)
+ FD_SET(fd[i].fd, &rfds);
- if (fd[i].events & POLLOUT)
- FD_SET(fd[i].fd, &wfds);
+ if (fd[i].events & POLLOUT)
+ FD_SET(fd[i].fd, &wfds);
- if (fd[i].fd > maxfd)
- maxfd = fd[i].fd;
- }
+ if (fd[i].fd > maxfd)
+ maxfd = fd[i].fd;
+ }
- if (maxfd >= FD_SETSIZE) {
- Punt("Ran out of fd_set slots; "
- "recompile with a larger FD_SETSIZE.");
- }
+ if (maxfd >= FD_SETSIZE) {
+ Punt("Ran out of fd_set slots; "
+ "recompile with a larger FD_SETSIZE.");
+ }
- if (timeout < 0) {
- tvp = NULL;
- } else {
- usecs = timeout * 1000;
- tv.tv_sec = usecs / 1000000;
- tv.tv_usec = usecs % 1000000;
- tvp = &tv;
- }
+ if (timeout < 0) {
+ tvp = NULL;
+ } else {
+ usecs = timeout * 1000;
+ tv.tv_sec = usecs / 1000000;
+ tv.tv_usec = usecs % 1000000;
+ tvp = &tv;
+ }
- nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
+ nselect = select(maxfd + 1, &rfds, &wfds, NULL, tvp);
- if (nselect <= 0)
- return nselect;
+ if (nselect <= 0)
+ return nselect;
- npoll = 0;
- for (i = 0; i < nfd; i++) {
- if (FD_ISSET(fd[i].fd, &rfds))
- fd[i].revents |= POLLIN;
+ npoll = 0;
+ for (i = 0; i < nfd; i++) {
+ if (FD_ISSET(fd[i].fd, &rfds))
+ fd[i].revents |= POLLIN;
- if (FD_ISSET(fd[i].fd, &wfds))
- fd[i].revents |= POLLOUT;
+ if (FD_ISSET(fd[i].fd, &wfds))
+ fd[i].revents |= POLLOUT;
- if (fd[i].revents)
- npoll++;
- }
+ if (fd[i].revents)
+ npoll++;
+ }
- return npoll;
+ return npoll;
}
#endif /* USE_SELECT */
diff --git a/job.h b/job.h
index d48424858201..9bb5f149766f 100644
--- a/job.h
+++ b/job.h
@@ -1,4 +1,4 @@
-/* $NetBSD: job.h,v 1.63 2020/11/14 13:27:01 rillig Exp $ */
+/* $NetBSD: job.h,v 1.71 2020/12/30 10:03:16 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -97,8 +97,8 @@ struct emul_pollfd {
short revents;
};
-#define POLLIN 0x0001
-#define POLLOUT 0x0004
+#define POLLIN 0x0001
+#define POLLOUT 0x0004
int
emul_poll(struct pollfd *fd, int nfd, int timeout);
@@ -118,27 +118,15 @@ struct pollfd;
#endif
typedef enum JobStatus {
- JOB_ST_FREE = 0, /* Job is available */
- JOB_ST_SET_UP = 1, /* Job is allocated but otherwise invalid */
- /* XXX: What about the 2? */
- JOB_ST_RUNNING = 3, /* Job is running, pid valid */
- JOB_ST_FINISHED = 4 /* Job is done (ie after SIGCHILD) */
+ JOB_ST_FREE = 0, /* Job is available */
+ JOB_ST_SET_UP = 1, /* Job is allocated but otherwise invalid */
+ /* XXX: What about the 2? */
+ JOB_ST_RUNNING = 3, /* Job is running, pid valid */
+ JOB_ST_FINISHED = 4 /* Job is done (ie after SIGCHILD) */
} JobStatus;
-typedef enum JobFlags {
- JOB_NONE = 0,
- /* Ignore non-zero exits */
- JOB_IGNERR = 1 << 0,
- /* no output */
- JOB_SILENT = 1 << 1,
- /* Target is a special one. i.e. run it locally
- * if we can't export it and maxLocal is 0 */
- JOB_SPECIAL = 1 << 2,
- /* we've sent 'set -x' */
- JOB_TRACED = 1 << 10
-} JobFlags;
-
-/* A Job manages the shell commands that are run to create a single target.
+/*
+ * A Job manages the shell commands that are run to create a single target.
* Each job is run in a separate subprocess by a shell. Several jobs can run
* in parallel.
*
@@ -148,42 +136,47 @@ typedef enum JobFlags {
*
* When a job is finished, Make_Update updates all parents of the node
* that was just remade, marking them as ready to be made next if all
- * other dependencies are finished as well. */
+ * other dependencies are finished as well.
+ */
typedef struct Job {
- /* The process ID of the shell running the commands */
- int pid;
+ /* The process ID of the shell running the commands */
+ int pid;
- /* The target the child is making */
- GNode *node;
+ /* The target the child is making */
+ GNode *node;
- /* If one of the shell commands is "...", all following commands are
- * delayed until the .END node is made. This list node points to the
- * first of these commands, if any. */
- StringListNode *tailCmds;
+ /* If one of the shell commands is "...", all following commands are
+ * delayed until the .END node is made. This list node points to the
+ * first of these commands, if any. */
+ StringListNode *tailCmds;
- /* When creating the shell script, this is where the commands go.
- * This is only used before the job is actually started. */
- FILE *cmdFILE;
+ /* This is where the shell commands go. */
+ FILE *cmdFILE;
- int exit_status; /* from wait4() in signal handler */
+ int exit_status; /* from wait4() in signal handler */
- JobStatus status;
+ JobStatus status;
- Boolean suspended;
+ Boolean suspended;
- JobFlags flags; /* Flags to control treatment of job */
+ /* Ignore non-zero exits */
+ Boolean ignerr;
+ /* Output the command before or instead of running it. */
+ Boolean echo;
+ /* Target is a special one. */
+ Boolean special;
- int inPipe; /* Pipe for reading output from job */
- int outPipe; /* Pipe for writing control commands */
- struct pollfd *inPollfd; /* pollfd associated with inPipe */
+ int inPipe; /* Pipe for reading output from job */
+ int outPipe; /* Pipe for writing control commands */
+ struct pollfd *inPollfd; /* pollfd associated with inPipe */
#define JOB_BUFSIZE 1024
- /* Buffer for storing the output of the job, line by line. */
- char outBuf[JOB_BUFSIZE + 1];
- size_t curPos; /* Current position in outBuf. */
+ /* Buffer for storing the output of the job, line by line. */
+ char outBuf[JOB_BUFSIZE + 1];
+ size_t curPos; /* Current position in outBuf. */
#ifdef USE_META
- struct BuildMon bm;
+ struct BuildMon bm;
#endif
} Job;
@@ -211,5 +204,6 @@ Boolean Job_TokenWithdraw(void);
void Job_ServerStart(int, int, int);
void Job_SetPrefix(void);
Boolean Job_RunTarget(const char *, const char *);
+void Job_FlagsToString(const Job *, char *, size_t);
#endif /* MAKE_JOB_H */
diff --git a/lst.c b/lst.c
index 71a0b41c1077..8d660b37ff52 100644
--- a/lst.c
+++ b/lst.c
@@ -1,4 +1,4 @@
-/* $NetBSD: lst.c,v 1.92 2020/11/08 01:29:26 rillig Exp $ */
+/* $NetBSD: lst.c,v 1.102 2020/12/30 10:03:16 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990, 1993
@@ -34,278 +34,266 @@
#include "make.h"
-MAKE_RCSID("$NetBSD: lst.c,v 1.92 2020/11/08 01:29:26 rillig Exp $");
-
-#ifdef HAVE_INTTYPES_H
-#include <inttypes.h>
-#elif defined(HAVE_STDINT_H)
-#include <stdint.h>
-#endif
+MAKE_RCSID("$NetBSD: lst.c,v 1.102 2020/12/30 10:03:16 rillig Exp $");
static ListNode *
LstNodeNew(ListNode *prev, ListNode *next, void *datum)
{
- ListNode *ln = bmake_malloc(sizeof *ln);
- ln->prev = prev;
- ln->next = next;
- ln->datum = datum;
- return ln;
+ ListNode *ln = bmake_malloc(sizeof *ln);
+
+ ln->prev = prev;
+ ln->next = next;
+ ln->datum = datum;
+
+ return ln;
}
/* Create and initialize a new, empty list. */
List *
Lst_New(void)
{
- List *list = bmake_malloc(sizeof *list);
+ List *list = bmake_malloc(sizeof *list);
+ Lst_Init(list);
+ return list;
+}
- list->first = NULL;
- list->last = NULL;
+void
+Lst_Done(List *list)
+{
+ ListNode *ln, *next;
+
+ for (ln = list->first; ln != NULL; ln = next) {
+ next = ln->next;
+ free(ln);
+ }
+}
+
+void
+Lst_DoneCall(List *list, LstFreeProc freeProc)
+{
+ ListNode *ln, *next;
- return list;
+ for (ln = list->first; ln != NULL; ln = next) {
+ next = ln->next;
+ freeProc(ln->datum);
+ free(ln);
+ }
}
/* Free a list and all its nodes. The node data are not freed though. */
void
Lst_Free(List *list)
{
- ListNode *ln, *next;
- for (ln = list->first; ln != NULL; ln = next) {
- next = ln->next;
- free(ln);
- }
-
- free(list);
+ Lst_Done(list);
+ free(list);
}
-/* Destroy a list and free all its resources. The freeProc is called with the
- * datum from each node in turn before the node is freed. */
+/*
+ * Destroy a list and free all its resources. The freeProc is called with the
+ * datum from each node in turn before the node is freed.
+ */
void
Lst_Destroy(List *list, LstFreeProc freeProc)
{
- ListNode *ln, *next;
-
- for (ln = list->first; ln != NULL; ln = next) {
- next = ln->next;
- freeProc(ln->datum);
- free(ln);
- }
-
- free(list);
+ Lst_DoneCall(list, freeProc);
+ free(list);
}
/* Insert a new node with the datum before the given node. */
void
Lst_InsertBefore(List *list, ListNode *ln, void *datum)
{
- ListNode *newNode;
+ ListNode *newNode;
- assert(datum != NULL);
+ assert(datum != NULL);
- newNode = LstNodeNew(ln->prev, ln, datum);
+ newNode = LstNodeNew(ln->prev, ln, datum);
- if (ln->prev != NULL)
- ln->prev->next = newNode;
- ln->prev = newNode;
+ if (ln->prev != NULL)
+ ln->prev->next = newNode;
+ ln->prev = newNode;
- if (ln == list->first)
- list->first = newNode;
+ if (ln == list->first)
+ list->first = newNode;
}
/* Add a piece of data at the start of the given list. */
void
Lst_Prepend(List *list, void *datum)
{
- ListNode *ln;
+ ListNode *ln;
- assert(datum != NULL);
+ assert(datum != NULL);
- ln = LstNodeNew(NULL, list->first, datum);
+ ln = LstNodeNew(NULL, list->first, datum);
- if (list->first == NULL) {
- list->first = ln;
- list->last = ln;
- } else {
- list->first->prev = ln;
- list->first = ln;
- }
+ if (list->first == NULL) {
+ list->first = ln;
+ list->last = ln;
+ } else {
+ list->first->prev = ln;
+ list->first = ln;
+ }
}
/* Add a piece of data at the end of the given list. */
void
Lst_Append(List *list, void *datum)
{
- ListNode *ln;
+ ListNode *ln;
- assert(datum != NULL);
+ assert(datum != NULL);
- ln = LstNodeNew(list->last, NULL, datum);
+ ln = LstNodeNew(list->last, NULL, datum);
- if (list->last == NULL) {
- list->first = ln;
- list->last = ln;
- } else {
- list->last->next = ln;
- list->last = ln;
- }
+ if (list->last == NULL) {
+ list->first = ln;
+ list->last = ln;
+ } else {
+ list->last->next = ln;
+ list->last = ln;
+ }
}
-/* Remove the given node from the given list.
- * The datum stored in the node must be freed by the caller, if necessary. */
+/*
+ * Remove the given node from the given list.
+ * The datum stored in the node must be freed by the caller, if necessary.
+ */
void
Lst_Remove(List *list, ListNode *ln)
{
- /* unlink it from its neighbors */
- if (ln->next != NULL)
- ln->next->prev = ln->prev;
- if (ln->prev != NULL)
- ln->prev->next = ln->next;
-
- /* unlink it from the list */
- if (list->first == ln)
- list->first = ln->next;
- if (list->last == ln)
- list->last = ln->prev;
+ /* unlink it from its neighbors */
+ if (ln->next != NULL)
+ ln->next->prev = ln->prev;
+ if (ln->prev != NULL)
+ ln->prev->next = ln->next;
+
+ /* unlink it from the list */
+ if (list->first == ln)
+ list->first = ln->next;
+ if (list->last == ln)
+ list->last = ln->prev;
}
/* Replace the datum in the given node with the new datum. */
void
LstNode_Set(ListNode *ln, void *datum)
{
- assert(datum != NULL);
+ assert(datum != NULL);
- ln->datum = datum;
+ ln->datum = datum;
}
-/* Replace the datum in the given node with NULL.
- * Having NULL values in a list is unusual though. */
+/*
+ * Replace the datum in the given node with NULL.
+ * Having NULL values in a list is unusual though.
+ */
void
LstNode_SetNull(ListNode *ln)
{
- ln->datum = NULL;
+ ln->datum = NULL;
}
-/* Return the first node that contains the given datum, or NULL.
+/*
+ * Return the first node that contains the given datum, or NULL.
*
- * Time complexity: O(length(list)) */
+ * Time complexity: O(length(list))
+ */
ListNode *
Lst_FindDatum(List *list, const void *datum)
{
- ListNode *ln;
-
- assert(datum != NULL);
+ ListNode *ln;
- for (ln = list->first; ln != NULL; ln = ln->next)
- if (ln->datum == datum)
- return ln;
+ assert(datum != NULL);
- return NULL;
-}
+ for (ln = list->first; ln != NULL; ln = ln->next)
+ if (ln->datum == datum)
+ return ln;
-int
-Lst_ForEachUntil(List *list, LstActionUntilProc proc, void *procData)
-{
- ListNode *ln;
- int result = 0;
-
- for (ln = list->first; ln != NULL; ln = ln->next) {
- result = proc(ln->datum, procData);
- if (result != 0)
- break;
- }
- return result;
+ return NULL;
}
-/* Move all nodes from src to the end of dst.
- * The source list is destroyed and freed. */
+/*
+ * Move all nodes from src to the end of dst.
+ * The source list becomes empty but is not freed.
+ */
void
Lst_MoveAll(List *dst, List *src)
{
- if (src->first != NULL) {
- src->first->prev = dst->last;
- if (dst->last != NULL)
- dst->last->next = src->first;
- else
- dst->first = src->first;
-
- dst->last = src->last;
- }
- free(src);
+ if (src->first != NULL) {
+ src->first->prev = dst->last;
+ if (dst->last != NULL)
+ dst->last->next = src->first;
+ else
+ dst->first = src->first;
+
+ dst->last = src->last;
+ }
}
/* Copy the element data from src to the start of dst. */
void
Lst_PrependAll(List *dst, List *src)
{
- ListNode *node;
- for (node = src->last; node != NULL; node = node->prev)
- Lst_Prepend(dst, node->datum);
+ ListNode *ln;
+
+ for (ln = src->last; ln != NULL; ln = ln->prev)
+ Lst_Prepend(dst, ln->datum);
}
/* Copy the element data from src to the end of dst. */
void
Lst_AppendAll(List *dst, List *src)
{
- ListNode *node;
- for (node = src->first; node != NULL; node = node->next)
- Lst_Append(dst, node->datum);
-}
-
-/*
- * for using the list as a queue
- */
+ ListNode *ln;
-/* Add the datum to the tail of the given list. */
-void
-Lst_Enqueue(List *list, void *datum)
-{
- Lst_Append(list, datum);
+ for (ln = src->first; ln != NULL; ln = ln->next)
+ Lst_Append(dst, ln->datum);
}
/* Remove and return the datum at the head of the given list. */
void *
Lst_Dequeue(List *list)
{
- void *datum = list->first->datum;
- Lst_Remove(list, list->first);
- assert(datum != NULL); /* since NULL would mean end of the list */
- return datum;
+ void *datum = list->first->datum;
+ Lst_Remove(list, list->first);
+ assert(datum != NULL); /* since NULL would mean end of the list */
+ return datum;
}
void
Vector_Init(Vector *v, size_t itemSize)
{
- v->len = 0;
- v->priv_cap = 10;
- v->itemSize = itemSize;
- v->items = bmake_malloc(v->priv_cap * v->itemSize);
+ v->len = 0;
+ v->cap = 10;
+ v->itemSize = itemSize;
+ v->items = bmake_malloc(v->cap * v->itemSize);
}
-/* Add space for a new item to the vector and return a pointer to that space.
- * The returned data is valid until the next modifying operation. */
+/*
+ * Add space for a new item to the vector and return a pointer to that space.
+ * The returned data is valid until the next modifying operation.
+ */
void *
Vector_Push(Vector *v)
{
- if (v->len >= v->priv_cap) {
- v->priv_cap *= 2;
- v->items = bmake_realloc(v->items, v->priv_cap * v->itemSize);
- }
- v->len++;
- return Vector_Get(v, v->len - 1);
+ if (v->len >= v->cap) {
+ v->cap *= 2;
+ v->items = bmake_realloc(v->items, v->cap * v->itemSize);
+ }
+ v->len++;
+ return Vector_Get(v, v->len - 1);
}
-/* Return the pointer to the last item in the vector.
- * The returned data is valid until the next modifying operation. */
+/*
+ * Return the pointer to the last item in the vector.
+ * The returned data is valid until the next modifying operation.
+ */
void *
Vector_Pop(Vector *v)
{
- assert(v->len > 0);
- v->len--;
- return Vector_Get(v, v->len);
-}
-
-void
-Vector_Done(Vector *v)
-{
- free(v->items);
+ assert(v->len > 0);
+ v->len--;
+ return Vector_Get(v, v->len);
}
diff --git a/lst.h b/lst.h
index 6965678c1e09..30c28ed7096d 100644
--- a/lst.h
+++ b/lst.h
@@ -1,4 +1,4 @@
-/* $NetBSD: lst.h,v 1.85 2020/11/10 00:32:12 rillig Exp $ */
+/* $NetBSD: lst.h,v 1.95 2021/01/03 21:12:03 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -78,48 +78,62 @@
#ifndef MAKE_LST_H
#define MAKE_LST_H
-#include <sys/param.h>
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#elif defined(HAVE_STDINT_H)
#include <stdint.h>
+#endif
+#ifdef HAVE_STDLIB_H
#include <stdlib.h>
+#endif
/* A doubly-linked list of pointers. */
-typedef struct List List;
+typedef struct List List;
/* A single node in the doubly-linked list. */
-typedef struct ListNode ListNode;
+typedef struct ListNode ListNode;
struct ListNode {
- ListNode *prev; /* previous node in list, or NULL */
- ListNode *next; /* next node in list, or NULL */
- union {
+ ListNode *prev; /* previous node in list, or NULL */
+ ListNode *next; /* next node in list, or NULL */
void *datum; /* datum associated with this element */
- const struct GNode *priv_gnode; /* alias, just for debugging */
- const char *priv_str; /* alias, just for debugging */
- };
};
struct List {
- ListNode *first; /* first node in list */
- ListNode *last; /* last node in list */
+ ListNode *first;
+ ListNode *last;
};
/* Free the datum of a node, called before freeing the node itself. */
typedef void LstFreeProc(void *);
-/* An action for Lst_ForEachUntil and Lst_ForEachUntilConcurrent. */
-typedef int LstActionUntilProc(void *datum, void *args);
/* Create or destroy a list */
/* Create a new list. */
List *Lst_New(void);
+/* Free the list nodes, but not the list itself. */
+void Lst_Done(List *);
+/* Free the list nodes, freeing the node data using the given function. */
+void Lst_DoneCall(List *, LstFreeProc);
/* Free the list, leaving the node data unmodified. */
void Lst_Free(List *);
/* Free the list, freeing the node data using the given function. */
void Lst_Destroy(List *, LstFreeProc);
+#define LST_INIT { NULL, NULL }
+
+/* Initialize a list, without memory allocation. */
+MAKE_INLINE void
+Lst_Init(List *list)
+{
+ list->first = NULL;
+ list->last = NULL;
+}
+
/* Get information about a list */
MAKE_INLINE Boolean
-Lst_IsEmpty(List *list) { return list->first == NULL; }
+Lst_IsEmpty(List *list)
+{ return list->first == NULL; }
/* Find the first node that contains the given datum, or NULL. */
ListNode *Lst_FindDatum(List *, const void *);
@@ -145,43 +159,47 @@ void LstNode_Set(ListNode *, void *);
/* Set the value of the node to NULL. Having NULL in a list is unusual. */
void LstNode_SetNull(ListNode *);
-/* Iterating over a list, using a callback function */
-
-/* Run the action for each datum of the list, until the action returns
- * non-zero.
- *
- * During this iteration, the list must not be modified structurally. */
-int Lst_ForEachUntil(List *, LstActionUntilProc, void *);
-
/* Using the list as a queue */
/* Add a datum at the tail of the queue. */
-void Lst_Enqueue(List *, void *);
+MAKE_INLINE void
+Lst_Enqueue(List *list, void *datum) {
+ Lst_Append(list, datum);
+}
+
/* Remove the head node of the queue and return its datum. */
void *Lst_Dequeue(List *);
-/* A vector is an ordered collection of items, allowing for fast indexed
- * access. */
+/*
+ * A vector is an ordered collection of items, allowing for fast indexed
+ * access.
+ */
typedef struct Vector {
- void *items; /* memory holding the items */
- size_t itemSize; /* size of a single item in bytes */
- size_t len; /* number of actually usable elements */
- size_t priv_cap; /* capacity */
+ void *items; /* memory holding the items */
+ size_t itemSize; /* size of a single item */
+ size_t len; /* number of actually usable elements */
+ size_t cap; /* capacity */
} Vector;
void Vector_Init(Vector *, size_t);
-/* Return the pointer to the given item in the vector.
- * The returned data is valid until the next modifying operation. */
+/*
+ * Return the pointer to the given item in the vector.
+ * The returned data is valid until the next modifying operation.
+ */
MAKE_INLINE void *
Vector_Get(Vector *v, size_t i)
{
- unsigned char *items = v->items;
- return items + i * v->itemSize;
+ unsigned char *items = v->items;
+ return items + i * v->itemSize;
}
void *Vector_Push(Vector *);
void *Vector_Pop(Vector *);
-void Vector_Done(Vector *);
+
+MAKE_INLINE void
+Vector_Done(Vector *v) {
+ free(v->items);
+}
#endif /* MAKE_LST_H */
diff --git a/main.c b/main.c
index 6e97a9a12541..f2813d263c2a 100644
--- a/main.c
+++ b/main.c
@@ -1,4 +1,4 @@
-/* $NetBSD: main.c,v 1.476 2020/11/16 22:08:20 rillig Exp $ */
+/* $NetBSD: main.c,v 1.512 2021/01/10 23:59:53 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990, 1993
@@ -68,7 +68,8 @@
* SUCH DAMAGE.
*/
-/* The main file for this entire program. Exit routines etc. reside here.
+/*
+ * The main file for this entire program. Exit routines etc. reside here.
*
* Utility functions defined in this file:
*
@@ -109,17 +110,13 @@
#include "trace.h"
/* "@(#)main.c 8.3 (Berkeley) 3/19/94" */
-MAKE_RCSID("$NetBSD: main.c,v 1.476 2020/11/16 22:08:20 rillig Exp $");
+MAKE_RCSID("$NetBSD: main.c,v 1.512 2021/01/10 23:59:53 rillig Exp $");
#if defined(MAKE_NATIVE) && !defined(lint)
__COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993 "
"The Regents of the University of California. "
"All rights reserved.");
#endif
-#ifndef DEFMAXLOCAL
-#define DEFMAXLOCAL DEFMAXJOBS
-#endif
-
#ifndef __arraycount
# define __arraycount(__x) (sizeof(__x) / sizeof(__x[0]))
#endif
@@ -133,7 +130,6 @@ Boolean deleteOnError; /* .DELETE_ON_ERROR: set */
static int maxJobTokens; /* -j argument */
Boolean enterFlagObj; /* -w and objdir != srcdir */
-Boolean preserveUndefined;
static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
Boolean doing_depend; /* Set while reading .depend */
static Boolean jobsRunning; /* TRUE if the jobs might be running */
@@ -144,13 +140,13 @@ static void purge_relative_cached_realpaths(void);
static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
char curdir[MAXPATHLEN + 1]; /* Startup directory */
-char *progname; /* the program name */
+const char *progname;
char *makeDependfile;
pid_t myPid;
int makelevel;
Boolean forceJobs = FALSE;
-static int errors = 0;
+static int main_errors = 0;
static HashTable cached_realpaths;
/*
@@ -167,16 +163,16 @@ explode(const char *flags)
if (flags == NULL)
return NULL;
- for (f = flags; *f; f++)
+ for (f = flags; *f != '\0'; f++)
if (!ch_isalpha(*f))
break;
- if (*f)
+ if (*f != '\0')
return bmake_strdup(flags);
len = strlen(flags);
st = nf = bmake_malloc(len * 3 + 1);
- while (*flags) {
+ while (*flags != '\0') {
*nf++ = '-';
*nf++ = *flags++;
*nf++ = ' ';
@@ -251,7 +247,7 @@ parse_debug_options(const char *argvalue)
const char *modules;
DebugFlags debug = opts.debug;
- for (modules = argvalue; *modules; ++modules) {
+ for (modules = argvalue; *modules != '\0'; ++modules) {
switch (*modules) {
case '0': /* undocumented, only intended for tests */
debug = DEBUG_NONE;
@@ -296,7 +292,7 @@ parse_debug_options(const char *argvalue)
debug |= DEBUG_JOB;
break;
case 'L':
- opts.lint = TRUE;
+ opts.strict = TRUE;
break;
case 'l':
debug |= DEBUG_LOUD;
@@ -381,7 +377,7 @@ MainParseArgChdir(const char *argvalue)
if (chdir(argvalue) == -1) {
(void)fprintf(stderr, "%s: chdir %s: %s\n",
progname, argvalue, strerror(errno));
- exit(1);
+ exit(2); /* Not 1 so -q can distinguish error */
}
if (getcwd(curdir, MAXPATHLEN) == NULL) {
(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
@@ -434,7 +430,7 @@ MainParseArgJobs(const char *argvalue)
(void)fprintf(stderr,
"%s: illegal argument to -j -- must be positive integer!\n",
progname);
- exit(1); /* XXX: why not 2? */
+ exit(2); /* Not 1 so -q can distinguish error */
}
Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
@@ -504,7 +500,7 @@ MainParseArg(char c, const char *argvalue)
case 'V':
case 'v':
opts.printVars = c == 'v' ? PVM_EXPANDED : PVM_UNEXPANDED;
- Lst_Append(opts.variables, bmake_strdup(argvalue));
+ Lst_Append(&opts.variables, bmake_strdup(argvalue));
/* XXX: Why always -V? */
Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
@@ -532,7 +528,7 @@ MainParseArg(char c, const char *argvalue)
Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
break;
case 'f':
- Lst_Append(opts.makefiles, bmake_strdup(argvalue));
+ Lst_Append(&opts.makefiles, bmake_strdup(argvalue));
break;
case 'i':
opts.ignoreErrors = TRUE;
@@ -581,13 +577,15 @@ MainParseArg(char c, const char *argvalue)
return TRUE;
}
-/* Parse the given arguments. Called from main() and from
+/*
+ * Parse the given arguments. Called from main() and from
* Main_ParseArgLine() when the .MAKEFLAGS target is used.
*
* The arguments must be treated as read-only and will be freed after the
* call.
*
- * XXX: Deal with command line overriding .MAKEFLAGS in makefile */
+ * XXX: Deal with command line overriding .MAKEFLAGS in makefile
+ */
static void
MainParseArgs(int argc, char **argv)
{
@@ -668,7 +666,7 @@ rearg:
Punt("illegal (null) argument.");
if (argv[1][0] == '-' && !dashDash)
goto rearg;
- Lst_Append(opts.create, bmake_strdup(argv[1]));
+ Lst_Append(&opts.create, bmake_strdup(argv[1]));
}
}
@@ -679,10 +677,12 @@ noarg:
usage();
}
-/* Break a line of arguments into words and parse them.
+/*
+ * Break a line of arguments into words and parse them.
*
* Used when a .MFLAGS or .MAKEFLAGS target is encountered during parsing and
- * by main() when reading the MAKEFLAGS environment variable. */
+ * by main() when reading the MAKEFLAGS environment variable.
+ */
void
Main_ParseArgLine(const char *line)
{
@@ -691,6 +691,7 @@ Main_ParseArgLine(const char *line)
if (line == NULL)
return;
+ /* XXX: don't use line as an iterator variable */
for (; *line == ' '; ++line)
continue;
if (line[0] == '\0')
@@ -711,10 +712,9 @@ Main_ParseArgLine(const char *line)
}
#endif
{
- void *freeIt;
- const char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &freeIt);
- buf = str_concat3(argv0, " ", line);
- free(freeIt);
+ FStr argv0 = Var_Value(".MAKE", VAR_GLOBAL);
+ buf = str_concat3(argv0.str, " ", line);
+ FStr_Done(&argv0);
}
words = Str_Words(buf, TRUE);
@@ -772,34 +772,34 @@ Main_SetObjdir(Boolean writable, const char *fmt, ...)
static Boolean
SetVarObjdir(Boolean writable, const char *var, const char *suffix)
{
- void *path_freeIt;
- const char *path = Var_Value(var, VAR_CMDLINE, &path_freeIt);
- const char *xpath;
- char *xpath_freeIt;
+ FStr path = Var_Value(var, VAR_CMDLINE);
+ FStr xpath;
- if (path == NULL || path[0] == '\0') {
- bmake_free(path_freeIt);
+ if (path.str == NULL || path.str[0] == '\0') {
+ FStr_Done(&path);
return FALSE;
}
/* expand variable substitutions */
- xpath = path;
- xpath_freeIt = NULL;
- if (strchr(path, '$') != 0) {
- (void)Var_Subst(path, VAR_GLOBAL, VARE_WANTRES, &xpath_freeIt);
+ xpath = FStr_InitRefer(path.str);
+ if (strchr(path.str, '$') != 0) {
+ char *expanded;
+ (void)Var_Subst(path.str, VAR_GLOBAL, VARE_WANTRES, &expanded);
/* TODO: handle errors */
- xpath = xpath_freeIt;
+ xpath = FStr_InitOwn(expanded);
}
- (void)Main_SetObjdir(writable, "%s%s", xpath, suffix);
+ (void)Main_SetObjdir(writable, "%s%s", xpath.str, suffix);
- bmake_free(xpath_freeIt);
- bmake_free(path_freeIt);
+ FStr_Done(&xpath);
+ FStr_Done(&path);
return TRUE;
}
-/* Splits str into words, adding them to the list.
- * The string must be kept alive as long as the list. */
+/*
+ * Splits str into words, adding them to the list.
+ * The string must be kept alive as long as the list.
+ */
int
str2Lst_Append(StringList *lp, char *str)
{
@@ -808,7 +808,7 @@ str2Lst_Append(StringList *lp, char *str)
const char *sep = " \t";
- for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
+ for (n = 0, cp = strtok(str, sep); cp != NULL; cp = strtok(NULL, sep)) {
Lst_Append(lp, cp);
n++;
}
@@ -831,39 +831,38 @@ siginfo(int signo MAKE_ATTR_UNUSED)
}
#endif
-/*
- * Allow makefiles some control over the mode we run in.
- */
-void
-MakeMode(const char *mode)
+/* Allow makefiles some control over the mode we run in. */
+static void
+MakeMode(void)
{
- char *mode_freeIt = NULL;
+ FStr mode = FStr_InitRefer(NULL);
- if (mode == NULL) {
+ if (mode.str == NULL) {
+ char *expanded;
(void)Var_Subst("${" MAKE_MODE ":tl}",
- VAR_GLOBAL, VARE_WANTRES, &mode_freeIt);
+ VAR_GLOBAL, VARE_WANTRES, &expanded);
/* TODO: handle errors */
- mode = mode_freeIt;
+ mode = FStr_InitOwn(expanded);
}
- if (mode[0] != '\0') {
- if (strstr(mode, "compat")) {
+ if (mode.str[0] != '\0') {
+ if (strstr(mode.str, "compat") != NULL) {
opts.compatMake = TRUE;
forceJobs = FALSE;
}
#if USE_META
- if (strstr(mode, "meta"))
- meta_mode_init(mode);
+ if (strstr(mode.str, "meta") != NULL)
+ meta_mode_init(mode.str);
#endif
}
- free(mode_freeIt);
+ FStr_Done(&mode);
}
static void
PrintVar(const char *varname, Boolean expandVars)
{
- if (strchr(varname, '$')) {
+ if (strchr(varname, '$') != NULL) {
char *evalue;
(void)Var_Subst(varname, VAR_GLOBAL, VARE_WANTRES, &evalue);
/* TODO: handle errors */
@@ -880,10 +879,9 @@ PrintVar(const char *varname, Boolean expandVars)
bmake_free(evalue);
} else {
- void *freeIt;
- const char *value = Var_Value(varname, VAR_GLOBAL, &freeIt);
- printf("%s\n", value ? value : "");
- bmake_free(freeIt);
+ FStr value = Var_Value(varname, VAR_GLOBAL);
+ printf("%s\n", value.str != NULL ? value.str : "");
+ FStr_Done(&value);
}
}
@@ -922,7 +920,7 @@ doPrintVars(void)
else
expandVars = GetBooleanVar(".MAKE.EXPAND_VARIABLES", FALSE);
- for (ln = opts.variables->first; ln != NULL; ln = ln->next) {
+ for (ln = opts.variables.first; ln != NULL; ln = ln->next) {
const char *varname = ln->datum;
PrintVar(varname, expandVars);
}
@@ -931,7 +929,7 @@ doPrintVars(void)
static Boolean
runTargets(void)
{
- GNodeList *targs; /* target nodes to create */
+ GNodeList targs = LST_INIT; /* target nodes to create */
Boolean outOfDate; /* FALSE if all targets up to date */
/*
@@ -940,10 +938,10 @@ runTargets(void)
* we consult the parsing module to find the main target(s)
* to create.
*/
- if (Lst_IsEmpty(opts.create))
- targs = Parse_MainName();
+ if (Lst_IsEmpty(&opts.create))
+ Parse_MainName(&targs);
else
- targs = Targ_FindList(opts.create);
+ Targ_FindList(&targs, &opts.create);
if (!opts.compatMake) {
/*
@@ -959,16 +957,16 @@ runTargets(void)
}
/* Traverse the graph, checking on all the targets */
- outOfDate = Make_Run(targs);
+ outOfDate = Make_Run(&targs);
} else {
/*
* Compat_Init will take care of creating all the
* targets as well as initializing the module.
*/
- Compat_Run(targs);
+ Compat_Run(&targs);
outOfDate = FALSE;
}
- Lst_Free(targs);
+ Lst_Done(&targs); /* Don't free the nodes. */
return outOfDate;
}
@@ -982,12 +980,12 @@ InitVarTargets(void)
{
StringListNode *ln;
- if (Lst_IsEmpty(opts.create)) {
+ if (Lst_IsEmpty(&opts.create)) {
Var_Set(".TARGETS", "", VAR_GLOBAL);
return;
}
- for (ln = opts.create->first; ln != NULL; ln = ln->next) {
+ for (ln = opts.create.first; ln != NULL; ln = ln->next) {
char *name = ln->datum;
Var_Append(".TARGETS", name, VAR_GLOBAL);
}
@@ -1040,11 +1038,11 @@ InitVarMachineArch(void)
const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
size_t len = sizeof machine_arch_buf;
- if (sysctl(mib, __arraycount(mib), machine_arch_buf,
- &len, NULL, 0) < 0) {
- (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
- strerror(errno));
- exit(2);
+ if (sysctl(mib, (unsigned int)__arraycount(mib),
+ machine_arch_buf, &len, NULL, 0) < 0) {
+ (void)fprintf(stderr, "%s: sysctl failed (%s).\n",
+ progname, strerror(errno));
+ exit(2);
}
return machine_arch_buf;
@@ -1077,21 +1075,20 @@ static void
HandlePWD(const struct stat *curdir_st)
{
char *pwd;
- void *prefix_freeIt, *makeobjdir_freeIt;
- const char *makeobjdir;
+ FStr prefix, makeobjdir;
struct stat pwd_st;
if (ignorePWD || (pwd = getenv("PWD")) == NULL)
return;
- if (Var_Value("MAKEOBJDIRPREFIX", VAR_CMDLINE, &prefix_freeIt) !=
- NULL) {
- bmake_free(prefix_freeIt);
+ prefix = Var_Value("MAKEOBJDIRPREFIX", VAR_CMDLINE);
+ if (prefix.str != NULL) {
+ FStr_Done(&prefix);
return;
}
- makeobjdir = Var_Value("MAKEOBJDIR", VAR_CMDLINE, &makeobjdir_freeIt);
- if (makeobjdir != NULL && strchr(makeobjdir, '$') != NULL)
+ makeobjdir = Var_Value("MAKEOBJDIR", VAR_CMDLINE);
+ if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
goto ignore_pwd;
if (stat(pwd, &pwd_st) == 0 &&
@@ -1100,7 +1097,7 @@ HandlePWD(const struct stat *curdir_st)
(void)strncpy(curdir, pwd, MAXPATHLEN);
ignore_pwd:
- bmake_free(makeobjdir_freeIt);
+ FStr_Done(&makeobjdir);
}
#endif
@@ -1118,7 +1115,7 @@ InitObjdir(const char *machine, const char *machine_arch)
{
Boolean writable;
- Dir_InitDir(curdir);
+ Dir_InitCur(curdir);
writable = GetBooleanVar("MAKE_OBJDIR_CHECK_WRITABLE", TRUE);
(void)Main_SetObjdir(FALSE, "%s", curdir);
@@ -1147,35 +1144,37 @@ UnlimitFiles(void)
static void
CmdOpts_Init(void)
{
- opts.compatMake = FALSE; /* No compat mode */
- opts.debug = 0; /* No debug verbosity, please. */
+ opts.compatMake = FALSE;
+ opts.debug = DEBUG_NONE;
/* opts.debug_file has been initialized earlier */
- opts.lint = FALSE;
+ opts.strict = FALSE;
opts.debugVflag = FALSE;
opts.checkEnvFirst = FALSE;
- opts.makefiles = Lst_New();
+ Lst_Init(&opts.makefiles);
opts.ignoreErrors = FALSE; /* Pay attention to non-zero returns */
- opts.maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
+ opts.maxJobs = 1;
opts.keepgoing = FALSE; /* Stop on error */
opts.noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
opts.noExecute = FALSE; /* Execute all commands */
- opts.queryFlag = FALSE; /* This is not just a check-run */
+ opts.queryFlag = FALSE;
opts.noBuiltins = FALSE; /* Read the built-in rules */
opts.beSilent = FALSE; /* Print commands as executed */
- opts.touchFlag = FALSE; /* Actually update targets */
+ opts.touchFlag = FALSE;
opts.printVars = PVM_NONE;
- opts.variables = Lst_New();
+ Lst_Init(&opts.variables);
opts.parseWarnFatal = FALSE;
opts.enterFlag = FALSE;
opts.varNoExportEnv = FALSE;
- opts.create = Lst_New();
+ Lst_Init(&opts.create);
}
-/* Initialize MAKE and .MAKE to the path of the executable, so that it can be
+/*
+ * Initialize MAKE and .MAKE to the path of the executable, so that it can be
* found by execvp(3) and the shells, even after a chdir.
*
* If it's a relative path and contains a '/', resolve it to an absolute path.
- * Otherwise keep it as is, assuming it will be found in the PATH. */
+ * Otherwise keep it as is, assuming it will be found in the PATH.
+ */
static void
InitVarMake(const char *argv0)
{
@@ -1183,18 +1182,21 @@ InitVarMake(const char *argv0)
if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
char pathbuf[MAXPATHLEN];
- const char *abs = cached_realpath(argv0, pathbuf);
+ const char *abspath = cached_realpath(argv0, pathbuf);
struct stat st;
- if (abs != NULL && abs[0] == '/' && stat(make, &st) == 0)
- make = abs;
+ if (abspath != NULL && abspath[0] == '/' &&
+ stat(make, &st) == 0)
+ make = abspath;
}
Var_Set("MAKE", make, VAR_GLOBAL);
Var_Set(".MAKE", make, VAR_GLOBAL);
}
-/* Add the directories from the colon-separated syspath to defSysIncPath.
- * After returning, the contents of syspath is unspecified. */
+/*
+ * Add the directories from the colon-separated syspath to defSysIncPath.
+ * After returning, the contents of syspath is unspecified.
+ */
static void
InitDefSysIncPath(char *syspath)
{
@@ -1237,25 +1239,25 @@ static void
ReadBuiltinRules(void)
{
StringListNode *ln;
- StringList *sysMkPath = Lst_New();
+ StringList sysMkPath = LST_INIT;
Dir_Expand(_PATH_DEFSYSMK,
Lst_IsEmpty(sysIncPath) ? defSysIncPath : sysIncPath,
- sysMkPath);
- if (Lst_IsEmpty(sysMkPath))
+ &sysMkPath);
+ if (Lst_IsEmpty(&sysMkPath))
Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
- for (ln = sysMkPath->first; ln != NULL; ln = ln->next)
+ for (ln = sysMkPath.first; ln != NULL; ln = ln->next)
if (ReadMakefile(ln->datum) == 0)
break;
if (ln == NULL)
Fatal("%s: cannot open %s.",
- progname, (const char *)sysMkPath->first->datum);
+ progname, (const char *)sysMkPath.first->datum);
/* Free the list but not the actual filenames since these may still
* be used in GNodes. */
- Lst_Free(sysMkPath);
+ Lst_Done(&sysMkPath);
}
static void
@@ -1276,7 +1278,7 @@ InitMaxJobs(void)
"%s: illegal value for .MAKE.JOBS "
"-- must be positive integer!\n",
progname);
- exit(1);
+ exit(2); /* Not 1 so -q can distinguish error */
}
if (n != opts.maxJobs) {
@@ -1315,7 +1317,7 @@ InitVpath(void)
savec = *cp;
*cp = '\0';
/* Add directory to search path */
- (void)Dir_AddDir(dirSearchPath, path);
+ (void)Dir_AddDir(&dirSearchPath, path);
*cp = savec;
path = cp + 1;
} while (savec == ':');
@@ -1348,18 +1350,20 @@ ReadFirstDefaultMakefile(void)
* since these makefiles do not come from the command line. They
* also have different semantics in that only the first file that
* is found is processed. See ReadAllMakefiles. */
- (void)str2Lst_Append(opts.makefiles, prefs);
+ (void)str2Lst_Append(&opts.makefiles, prefs);
- for (ln = opts.makefiles->first; ln != NULL; ln = ln->next)
+ for (ln = opts.makefiles.first; ln != NULL; ln = ln->next)
if (ReadMakefile(ln->datum) == 0)
break;
free(prefs);
}
-/* Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
+/*
+ * Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
* Initialize a few modules.
- * Parse the arguments from MAKEFLAGS and the command line. */
+ * Parse the arguments from MAKEFLAGS and the command line.
+ */
static void
main_Init(int argc, char **argv)
{
@@ -1380,10 +1384,7 @@ main_Init(int argc, char **argv)
InitRandom();
- if ((progname = strrchr(argv[0], '/')) != NULL)
- progname++;
- else
- progname = argv[0];
+ progname = str_basename(argv[0]);
UnlimitFiles();
@@ -1469,6 +1470,10 @@ main_Init(int argc, char **argv)
Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
snprintf(tmp, sizeof tmp, "%u", getppid());
Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
+ snprintf(tmp, sizeof tmp, "%u", getuid());
+ Var_Set(".MAKE.UID", tmp, VAR_GLOBAL);
+ snprintf(tmp, sizeof tmp, "%u", getgid());
+ Var_Set(".MAKE.GID", tmp, VAR_GLOBAL);
}
if (makelevel > 0) {
char pn[1024];
@@ -1545,8 +1550,10 @@ main_Init(int argc, char **argv)
InitDefSysIncPath(syspath);
}
-/* Read the system makefile followed by either makefile, Makefile or the
- * files given by the -f option. Exit on parse errors. */
+/*
+ * Read the system makefile followed by either makefile, Makefile or the
+ * files given by the -f option. Exit on parse errors.
+ */
static void
main_ReadFiles(void)
{
@@ -1554,8 +1561,8 @@ main_ReadFiles(void)
if (!opts.noBuiltins)
ReadBuiltinRules();
- if (!Lst_IsEmpty(opts.makefiles))
- ReadAllMakefiles(opts.makefiles);
+ if (!Lst_IsEmpty(&opts.makefiles))
+ ReadAllMakefiles(&opts.makefiles);
else
ReadFirstDefaultMakefile();
}
@@ -1566,8 +1573,7 @@ main_PrepareMaking(void)
{
/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
- /* ignore /dev/null and anything starting with "no" */
- (void)Var_Subst("${.MAKE.DEPENDFILE:N/dev/null:Nno*:T}",
+ (void)Var_Subst("${.MAKE.DEPENDFILE}",
VAR_CMDLINE, VARE_WANTRES, &makeDependfile);
if (makeDependfile[0] != '\0') {
/* TODO: handle errors */
@@ -1580,13 +1586,12 @@ main_PrepareMaking(void)
if (enterFlagObj)
printf("%s: Entering directory `%s'\n", progname, objdir);
- MakeMode(NULL);
+ MakeMode();
{
- void *freeIt;
- Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &freeIt),
- VAR_GLOBAL);
- bmake_free(freeIt);
+ FStr makeflags = Var_Value(MAKEFLAGS, VAR_GLOBAL);
+ Var_Append("MFLAGS", makeflags.str, VAR_GLOBAL);
+ FStr_Done(&makeflags);
}
InitMaxJobs();
@@ -1624,9 +1629,11 @@ main_PrepareMaking(void)
Targ_PrintGraph(1);
}
-/* Make the targets.
+/*
+ * Make the targets.
* If the -v or -V options are given, print variables instead.
- * Return whether any of the targets is out-of-date. */
+ * Return whether any of the targets is out-of-date.
+ */
static Boolean
main_Run(void)
{
@@ -1644,9 +1651,13 @@ static void
main_CleanUp(void)
{
#ifdef CLEANUP
- Lst_Destroy(opts.variables, free);
- Lst_Free(opts.makefiles); /* don't free, may be used in GNodes */
- Lst_Destroy(opts.create, free);
+ Lst_DoneCall(&opts.variables, free);
+ /*
+ * Don't free the actual strings from opts.makefiles, they may be
+ * used in GNodes.
+ */
+ Lst_Done(&opts.makefiles);
+ Lst_DoneCall(&opts.create, free);
#endif
/* print the graph now it's been processed if the user requested it */
@@ -1677,7 +1688,7 @@ main_CleanUp(void)
static int
main_Exit(Boolean outOfDate)
{
- if (opts.lint && (errors > 0 || Parse_GetFatals() > 0))
+ if (opts.strict && (main_errors > 0 || Parse_GetFatals() > 0))
return 2; /* Not 1 so -q can distinguish error */
return outOfDate ? 1 : 0;
}
@@ -1695,7 +1706,8 @@ main(int argc, char **argv)
return main_Exit(outOfDate);
}
-/* Open and parse the given makefile, with all its side effects.
+/*
+ * Open and parse the given makefile, with all its side effects.
*
* Results:
* 0 if ok. -1 if couldn't open file.
@@ -1776,7 +1788,7 @@ char *
Cmd_Exec(const char *cmd, const char **errfmt)
{
const char *args[4]; /* Args for invoking the shell */
- int fds[2]; /* Pipe streams */
+ int pipefds[2];
int cpid; /* Child PID */
int pid; /* PID from wait() */
int status; /* command exit status */
@@ -1789,7 +1801,7 @@ Cmd_Exec(const char *cmd, const char **errfmt)
*errfmt = NULL;
- if (!shellName)
+ if (shellName == NULL)
Shell_Init();
/*
* Set up arguments for shell
@@ -1802,27 +1814,27 @@ Cmd_Exec(const char *cmd, const char **errfmt)
/*
* Open a pipe for fetching its output
*/
- if (pipe(fds) == -1) {
+ if (pipe(pipefds) == -1) {
*errfmt = "Couldn't create pipe for \"%s\"";
goto bad;
}
+ Var_ReexportVars();
+
/*
* Fork
*/
switch (cpid = vFork()) {
case 0:
- (void)close(fds[0]); /* Close input side of pipe */
+ (void)close(pipefds[0]); /* Close input side of pipe */
/*
* Duplicate the output stream to the shell's output, then
* shut the extra thing down. Note we don't fetch the error
* stream...why not? Why?
*/
- (void)dup2(fds[1], 1);
- (void)close(fds[1]);
-
- Var_ExportVars();
+ (void)dup2(pipefds[1], 1);
+ (void)close(pipefds[1]);
(void)execv(shellPath, UNCONST(args));
_exit(1);
@@ -1833,14 +1845,14 @@ Cmd_Exec(const char *cmd, const char **errfmt)
goto bad;
default:
- (void)close(fds[1]); /* No need for the writing half */
+ (void)close(pipefds[1]); /* No need for the writing half */
savederr = 0;
Buf_Init(&buf);
do {
char result[BUFSIZ];
- bytes_read = read(fds[0], result, sizeof result);
+ bytes_read = read(pipefds[0], result, sizeof result);
if (bytes_read > 0)
Buf_AddBytes(&buf, result, (size_t)bytes_read);
} while (bytes_read > 0 ||
@@ -1848,8 +1860,7 @@ Cmd_Exec(const char *cmd, const char **errfmt)
if (bytes_read == -1)
savederr = errno;
- (void)close(
- fds[0]); /* Close the input side of the pipe. */
+ (void)close(pipefds[0]); /* Close the input side of the pipe. */
/* Wait for the process to exit. */
while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
@@ -1879,10 +1890,12 @@ bad:
return bmake_strdup("");
}
-/* Print a printf-style error message.
+/*
+ * Print a printf-style error message.
*
* In default mode, this error message has no consequences, in particular it
- * does not affect the exit status. Only in lint mode (-dL) it does. */
+ * does not affect the exit status. Only in lint mode (-dL) it does.
+ */
void
Error(const char *fmt, ...)
{
@@ -1904,14 +1917,16 @@ Error(const char *fmt, ...)
break;
err_file = stderr;
}
- errors++;
+ main_errors++;
}
-/* Wait for any running jobs to finish, then produce an error message,
+/*
+ * Wait for any running jobs to finish, then produce an error message,
* finally exit immediately.
*
* Exiting immediately differs from Parse_Error, which exits only after the
- * current top-level makefile has been parsed completely. */
+ * current top-level makefile has been parsed completely.
+ */
void
Fatal(const char *fmt, ...)
{
@@ -1935,8 +1950,10 @@ Fatal(const char *fmt, ...)
exit(2); /* Not 1 so -q can distinguish error */
}
-/* Major exception once jobs are being created.
- * Kills all jobs, prints a message and exits. */
+/*
+ * Major exception once jobs are being created.
+ * Kills all jobs, prints a message and exits.
+ */
void
Punt(const char *fmt, ...)
{
@@ -1964,12 +1981,14 @@ DieHorribly(void)
if (DEBUG(GRAPH2))
Targ_PrintGraph(2);
Trace_Log(MAKEERROR, NULL);
- exit(2); /* Not 1, so -q can distinguish error */
+ exit(2); /* Not 1 so -q can distinguish error */
}
-/* Called when aborting due to errors in child shell to signal abnormal exit.
+/*
+ * Called when aborting due to errors in child shell to signal abnormal exit.
* The program exits.
- * Errors is the number of errors encountered in Make_Make. */
+ * Errors is the number of errors encountered in Make_Make.
+ */
void
Finish(int errs)
{
@@ -2101,7 +2120,7 @@ shouldDieQuietly(GNode *gn, int bf)
else if (bf >= 0)
quietly = bf;
else
- quietly = gn != NULL && (gn->type & OP_MAKE);
+ quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
}
return quietly;
}
@@ -2117,7 +2136,7 @@ SetErrorVars(GNode *gn)
Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
Var_Delete(".ERROR_CMD", VAR_GLOBAL);
- for (ln = gn->commands->first; ln != NULL; ln = ln->next) {
+ for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
const char *cmd = ln->datum;
if (cmd == NULL)
@@ -2126,8 +2145,10 @@ SetErrorVars(GNode *gn)
}
}
-/* Print some helpful information in case of an error.
- * The caller should exit soon after calling this function. */
+/*
+ * Print some helpful information in case of an error.
+ * The caller should exit soon after calling this function.
+ */
void
PrintOnError(GNode *gn, const char *msg)
{
@@ -2138,16 +2159,16 @@ PrintOnError(GNode *gn, const char *msg)
Var_Stats();
}
- /* we generally want to keep quiet if a sub-make died */
- if (shouldDieQuietly(gn, -1))
- return;
+ if (errorNode != NULL)
+ return; /* we've been here! */
if (msg != NULL)
printf("%s", msg);
printf("\n%s: stopped in %s\n", progname, curdir);
- if (errorNode != NULL)
- return; /* we've been here! */
+ /* we generally want to keep quiet if a sub-make died */
+ if (shouldDieQuietly(gn, -1))
+ return;
if (gn != NULL)
SetErrorVars(gn);
@@ -2241,11 +2262,10 @@ mkTempFile(const char *pattern, char **out_fname)
if ((fd = mkstemp(tfile)) < 0)
Punt("Could not create temporary file %s: %s", tfile,
strerror(errno));
- if (out_fname) {
+ if (out_fname != NULL) {
*out_fname = bmake_strdup(tfile);
} else {
- unlink(
- tfile); /* we just want the descriptor */
+ unlink(tfile); /* we just want the descriptor */
}
return fd;
}
diff --git a/make-conf.h b/make-conf.h
index bc3b9e7e4915..dcf5b3162dea 100644
--- a/make-conf.h
+++ b/make-conf.h
@@ -1,4 +1,4 @@
-/* $NetBSD: config.h,v 1.25 2020/10/19 23:43:55 rillig Exp $ */
+/* $NetBSD: config.h,v 1.28 2020/12/11 22:53:08 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
@@ -73,19 +73,6 @@
*/
/*
- * DEFMAXJOBS
- * DEFMAXLOCAL
- * These control the default concurrency. On no occasion will more
- * than DEFMAXJOBS targets be created at once (locally or remotely).
- *
- * DEFMAXLOCAL is the highest number of targets which will be
- * created on the local machine at once. Note that if you set this
- * to 0, nothing will ever happen.
- */
-#define DEFMAXJOBS 4
-#define DEFMAXLOCAL 1
-
-/*
* INCLUDES
* LIBRARIES
* These control the handling of the .INCLUDES and .LIBS variables.
@@ -104,7 +91,7 @@
* Is the suffix used to denote libraries and is used by the Suff module
* to find the search path on which to seek any -l<xx> targets.
*/
-#define LIBSUFF ".a"
+#define LIBSUFF ".a"
/*
* RECHECK
@@ -119,14 +106,13 @@
* On systems that don't have this problem, you should define this.
* Under NFS you probably should not, unless you aren't exporting jobs.
*/
-#define RECHECK
+#define RECHECK
/*
* POSIX
* Adhere to the POSIX 1003.2 draft for the make(1) program.
* - Use MAKEFLAGS instead of MAKE to pick arguments from the
* environment.
- * - Allow empty command lines if starting with tab.
*/
#define POSIX
diff --git a/make.1 b/make.1
index a18c44442b49..c711b38a9731 100644
--- a/make.1
+++ b/make.1
@@ -1,4 +1,4 @@
-.\" $NetBSD: make.1,v 1.292 2020/11/14 22:19:13 rillig Exp $
+.\" $NetBSD: make.1,v 1.295 2020/12/23 13:49:12 rillig Exp $
.\"
.\" Copyright (c) 1990, 1993
.\" The Regents of the University of California. All rights reserved.
@@ -29,7 +29,7 @@
.\"
.\" from: @(#)make.1 8.4 (Berkeley) 3/19/94
.\"
-.Dd November 14, 2020
+.Dd December 22, 2020
.Dt MAKE 1
.Os
.Sh NAME
@@ -1019,6 +1019,12 @@ If set to false,
becomes
.Ql $
per normal evaluation rules.
+.It Va .MAKE.UID
+The user-id running
+.Nm .
+.It Va .MAKE.GID
+The group-id running
+.Nm .
.It Va MAKE_PRINT_VAR_ON_ERROR
When
.Nm
@@ -1097,7 +1103,7 @@ to that directory before executing any targets.
.Pp
Except in the case of an explicit
.Ql Ic .OBJDIR
-target,
+target,
.Nm
will check that the specified directory is writable and ignore it if not.
This check can be skipped by setting the environment variable
@@ -1743,9 +1749,9 @@ The same as
except that variables in the value are not expanded.
.It Ic .info Ar message
The message is printed along with the name of the makefile and line number.
-.It Ic .undef Ar variable
-Un-define the specified global variable.
-Only global variables may be un-defined.
+.It Ic .undef Ar variable ...
+Un-define the specified global variables.
+Only global variables can be un-defined.
.It Ic .unexport Ar variable ...
The opposite of
.Ql .export .
diff --git a/make.c b/make.c
index d0502e80c8ef..7745e038c814 100644
--- a/make.c
+++ b/make.c
@@ -1,4 +1,4 @@
-/* $NetBSD: make.c,v 1.209 2020/11/16 22:31:42 rillig Exp $ */
+/* $NetBSD: make.c,v 1.234 2021/01/10 21:20:46 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990, 1993
@@ -68,7 +68,8 @@
* SUCH DAMAGE.
*/
-/* Examination of targets and their suitability for creation.
+/*
+ * Examination of targets and their suitability for creation.
*
* Interface:
* Make_Run Initialize things for the module. Returns TRUE if
@@ -102,117 +103,122 @@
#include "job.h"
/* "@(#)make.c 8.1 (Berkeley) 6/6/93" */
-MAKE_RCSID("$NetBSD: make.c,v 1.209 2020/11/16 22:31:42 rillig Exp $");
+MAKE_RCSID("$NetBSD: make.c,v 1.234 2021/01/10 21:20:46 rillig Exp $");
/* Sequence # to detect recursion. */
static unsigned int checked_seqno = 1;
-/* The current fringe of the graph.
+/*
+ * The current fringe of the graph.
* These are nodes which await examination by MakeOODate.
- * It is added to by Make_Update and subtracted from by MakeStartJobs */
-static GNodeList *toBeMade;
+ * It is added to by Make_Update and subtracted from by MakeStartJobs
+ */
+static GNodeList toBeMade = LST_INIT;
-static int MakeBuildParent(void *, void *);
void
debug_printf(const char *fmt, ...)
{
- va_list args;
+ va_list args;
- va_start(args, fmt);
- vfprintf(opts.debug_file, fmt, args);
- va_end(args);
+ va_start(args, fmt);
+ vfprintf(opts.debug_file, fmt, args);
+ va_end(args);
}
MAKE_ATTR_DEAD static void
-make_abort(GNode *gn, int line)
+make_abort(GNode *gn, int lineno)
{
- debug_printf("make_abort from line %d\n", line);
- Targ_PrintNode(gn, 2);
- Targ_PrintNodes(toBeMade, 2);
- Targ_PrintGraph(3);
- abort();
+
+ debug_printf("make_abort from line %d\n", lineno);
+ Targ_PrintNode(gn, 2);
+ Targ_PrintNodes(&toBeMade, 2);
+ Targ_PrintGraph(3);
+ abort();
}
ENUM_VALUE_RTTI_8(GNodeMade,
- UNMADE, DEFERRED, REQUESTED, BEINGMADE,
- MADE, UPTODATE, ERROR, ABORTED);
+ UNMADE, DEFERRED, REQUESTED, BEINGMADE,
+ MADE, UPTODATE, ERROR, ABORTED);
ENUM_FLAGS_RTTI_31(GNodeType,
- OP_DEPENDS, OP_FORCE, OP_DOUBLEDEP,
- /* OP_OPMASK is omitted since it combines other flags */
- OP_OPTIONAL, OP_USE, OP_EXEC, OP_IGNORE,
- OP_PRECIOUS, OP_SILENT, OP_MAKE, OP_JOIN,
- OP_MADE, OP_SPECIAL, OP_USEBEFORE, OP_INVISIBLE,
- OP_NOTMAIN, OP_PHONY, OP_NOPATH, OP_WAIT,
- OP_NOMETA, OP_META, OP_NOMETA_CMP, OP_SUBMAKE,
- OP_TRANSFORM, OP_MEMBER, OP_LIB, OP_ARCHV,
- OP_HAS_COMMANDS, OP_SAVE_CMDS, OP_DEPS_FOUND, OP_MARK);
+ OP_DEPENDS, OP_FORCE, OP_DOUBLEDEP,
+/* OP_OPMASK is omitted since it combines other flags */
+ OP_OPTIONAL, OP_USE, OP_EXEC, OP_IGNORE,
+ OP_PRECIOUS, OP_SILENT, OP_MAKE, OP_JOIN,
+ OP_MADE, OP_SPECIAL, OP_USEBEFORE, OP_INVISIBLE,
+ OP_NOTMAIN, OP_PHONY, OP_NOPATH, OP_WAIT,
+ OP_NOMETA, OP_META, OP_NOMETA_CMP, OP_SUBMAKE,
+ OP_TRANSFORM, OP_MEMBER, OP_LIB, OP_ARCHV,
+ OP_HAS_COMMANDS, OP_SAVE_CMDS, OP_DEPS_FOUND, OP_MARK);
ENUM_FLAGS_RTTI_10(GNodeFlags,
- REMAKE, CHILDMADE, FORCE, DONE_WAIT,
- DONE_ORDER, FROM_DEPEND, DONE_ALLSRC, CYCLE,
- DONECYCLE, INTERNAL);
+ REMAKE, CHILDMADE, FORCE, DONE_WAIT,
+ DONE_ORDER, FROM_DEPEND, DONE_ALLSRC, CYCLE,
+ DONECYCLE, INTERNAL);
void
GNode_FprintDetails(FILE *f, const char *prefix, const GNode *gn,
const char *suffix)
{
- char type_buf[GNodeType_ToStringSize];
- char flags_buf[GNodeFlags_ToStringSize];
+ char type_buf[GNodeType_ToStringSize];
+ char flags_buf[GNodeFlags_ToStringSize];
- fprintf(f, "%smade %s, type %s, flags %s%s",
+ fprintf(f, "%smade %s, type %s, flags %s%s",
prefix,
Enum_ValueToString(gn->made, GNodeMade_ToStringSpecs),
Enum_FlagsToString(type_buf, sizeof type_buf,
- gn->type, GNodeType_ToStringSpecs),
+ gn->type, GNodeType_ToStringSpecs),
Enum_FlagsToString(flags_buf, sizeof flags_buf,
- gn->flags, GNodeFlags_ToStringSpecs),
+ gn->flags, GNodeFlags_ToStringSpecs),
suffix);
}
Boolean
GNode_ShouldExecute(GNode *gn)
{
- return !((gn->type & OP_MAKE) ? opts.noRecursiveExecute : opts.noExecute);
+ return !((gn->type & OP_MAKE)
+ ? opts.noRecursiveExecute
+ : opts.noExecute);
}
/* Update the youngest child of the node, according to the given child. */
void
GNode_UpdateYoungestChild(GNode *gn, GNode *cgn)
{
- if (gn->youngestChild == NULL || cgn->mtime > gn->youngestChild->mtime)
- gn->youngestChild = cgn;
+ if (gn->youngestChild == NULL || cgn->mtime > gn->youngestChild->mtime)
+ gn->youngestChild = cgn;
}
static Boolean
IsOODateRegular(GNode *gn)
{
- /* These rules are inherited from the original Make. */
-
- if (gn->youngestChild != NULL) {
- if (gn->mtime < gn->youngestChild->mtime) {
- DEBUG1(MAKE, "modified before source \"%s\"...",
- GNode_Path(gn->youngestChild));
- return TRUE;
+ /* These rules are inherited from the original Make. */
+
+ if (gn->youngestChild != NULL) {
+ if (gn->mtime < gn->youngestChild->mtime) {
+ DEBUG1(MAKE, "modified before source \"%s\"...",
+ GNode_Path(gn->youngestChild));
+ return TRUE;
+ }
+ return FALSE;
}
- return FALSE;
- }
- if (gn->mtime == 0 && !(gn->type & OP_OPTIONAL)) {
- DEBUG0(MAKE, "non-existent and no sources...");
- return TRUE;
- }
+ if (gn->mtime == 0 && !(gn->type & OP_OPTIONAL)) {
+ DEBUG0(MAKE, "nonexistent and no sources...");
+ return TRUE;
+ }
- if (gn->type & OP_DOUBLEDEP) {
- DEBUG0(MAKE, ":: operator and no sources...");
- return TRUE;
- }
+ if (gn->type & OP_DOUBLEDEP) {
+ DEBUG0(MAKE, ":: operator and no sources...");
+ return TRUE;
+ }
- return FALSE;
+ return FALSE;
}
-/* See if the node is out of date with respect to its sources.
+/*
+ * See if the node is out of date with respect to its sources.
*
* Used by Make_Run when deciding which nodes to place on the
* toBeMade queue initially and by Make_Update to screen out .USE and
@@ -226,129 +232,139 @@ IsOODateRegular(GNode *gn)
Boolean
GNode_IsOODate(GNode *gn)
{
- Boolean oodate;
-
- /*
- * Certain types of targets needn't even be sought as their datedness
- * doesn't depend on their modification time...
- */
- if (!(gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC))) {
- Dir_UpdateMTime(gn, TRUE);
- if (DEBUG(MAKE)) {
- if (gn->mtime != 0)
- debug_printf("modified %s...", Targ_FmtTime(gn->mtime));
- else
- debug_printf("non-existent...");
- }
- }
-
- /*
- * A target is remade in one of the following circumstances:
- * its modification time is smaller than that of its youngest child and
- * it would actually be run (has commands or is not GNode_IsTarget)
- * it's the object of a force operator
- * it has no children, was on the lhs of an operator and doesn't exist
- * already.
- *
- * Libraries are only considered out-of-date if the archive module says
- * they are.
- *
- * These weird rules are brought to you by Backward-Compatibility and
- * the strange people who wrote 'Make'.
- */
- if (gn->type & (OP_USE|OP_USEBEFORE)) {
- /*
- * If the node is a USE node it is *never* out of date
- * no matter *what*.
- */
- DEBUG0(MAKE, ".USE node...");
- oodate = FALSE;
- } else if ((gn->type & OP_LIB) && (gn->mtime == 0 || Arch_IsLib(gn))) {
- DEBUG0(MAKE, "library...");
+ Boolean oodate;
/*
- * always out of date if no children and :: target
- * or non-existent.
+ * Certain types of targets needn't even be sought as their datedness
+ * doesn't depend on their modification time...
*/
- oodate = (gn->mtime == 0 || Arch_LibOODate(gn) ||
- (gn->youngestChild == NULL && (gn->type & OP_DOUBLEDEP)));
- } else if (gn->type & OP_JOIN) {
- /*
- * A target with the .JOIN attribute is only considered
- * out-of-date if any of its children was out-of-date.
- */
- DEBUG0(MAKE, ".JOIN node...");
- DEBUG1(MAKE, "source %smade...", gn->flags & CHILDMADE ? "" : "not ");
- oodate = (gn->flags & CHILDMADE) != 0;
- } else if (gn->type & (OP_FORCE|OP_EXEC|OP_PHONY)) {
- /*
- * A node which is the object of the force (!) operator or which has
- * the .EXEC attribute is always considered out-of-date.
- */
- if (DEBUG(MAKE)) {
- if (gn->type & OP_FORCE) {
- debug_printf("! operator...");
- } else if (gn->type & OP_PHONY) {
- debug_printf(".PHONY node...");
- } else {
- debug_printf(".EXEC node...");
- }
+ if (!(gn->type & (OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC))) {
+ Dir_UpdateMTime(gn, TRUE);
+ if (DEBUG(MAKE)) {
+ if (gn->mtime != 0)
+ debug_printf("modified %s...",
+ Targ_FmtTime(gn->mtime));
+ else
+ debug_printf("nonexistent...");
+ }
}
- oodate = TRUE;
- } else if (IsOODateRegular(gn)) {
- oodate = TRUE;
- } else {
+
/*
- * When a non-existing child with no sources
- * (such as a typically used FORCE source) has been made and
- * the target of the child (usually a directory) has the same
- * timestamp as the timestamp just given to the non-existing child
- * after it was considered made.
+ * A target is remade in one of the following circumstances:
+ *
+ * its modification time is smaller than that of its youngest
+ * child and it would actually be run (has commands or is not
+ * GNode_IsTarget)
+ *
+ * it's the object of a force operator
+ *
+ * it has no children, was on the lhs of an operator and doesn't
+ * exist already.
+ *
+ * Libraries are only considered out-of-date if the archive module
+ * says they are.
+ *
+ * These weird rules are brought to you by Backward-Compatibility
+ * and the strange people who wrote 'Make'.
*/
- if (DEBUG(MAKE)) {
- if (gn->flags & FORCE)
- debug_printf("non existing child...");
+ if (gn->type & (OP_USE | OP_USEBEFORE)) {
+ /*
+ * If the node is a USE node it is *never* out of date
+ * no matter *what*.
+ */
+ DEBUG0(MAKE, ".USE node...");
+ oodate = FALSE;
+ } else if ((gn->type & OP_LIB) && (gn->mtime == 0 || Arch_IsLib(gn))) {
+ DEBUG0(MAKE, "library...");
+
+ /*
+ * always out of date if no children and :: target
+ * or nonexistent.
+ */
+ oodate = (gn->mtime == 0 || Arch_LibOODate(gn) ||
+ (gn->youngestChild == NULL &&
+ (gn->type & OP_DOUBLEDEP)));
+ } else if (gn->type & OP_JOIN) {
+ /*
+ * A target with the .JOIN attribute is only considered
+ * out-of-date if any of its children was out-of-date.
+ */
+ DEBUG0(MAKE, ".JOIN node...");
+ DEBUG1(MAKE, "source %smade...",
+ gn->flags & CHILDMADE ? "" : "not ");
+ oodate = (gn->flags & CHILDMADE) != 0;
+ } else if (gn->type & (OP_FORCE | OP_EXEC | OP_PHONY)) {
+ /*
+ * A node which is the object of the force (!) operator or
+ * which has the .EXEC attribute is always considered
+ * out-of-date.
+ */
+ if (DEBUG(MAKE)) {
+ if (gn->type & OP_FORCE) {
+ debug_printf("! operator...");
+ } else if (gn->type & OP_PHONY) {
+ debug_printf(".PHONY node...");
+ } else {
+ debug_printf(".EXEC node...");
+ }
+ }
+ oodate = TRUE;
+ } else if (IsOODateRegular(gn)) {
+ oodate = TRUE;
+ } else {
+ /*
+ * When a nonexistent child with no sources
+ * (such as a typically used FORCE source) has been made and
+ * the target of the child (usually a directory) has the same
+ * timestamp as the timestamp just given to the nonexistent
+ * child after it was considered made.
+ */
+ if (DEBUG(MAKE)) {
+ if (gn->flags & FORCE)
+ debug_printf("non existing child...");
+ }
+ oodate = (gn->flags & FORCE) != 0;
}
- oodate = (gn->flags & FORCE) != 0;
- }
#ifdef USE_META
- if (useMeta) {
- oodate = meta_oodate(gn, oodate);
- }
+ if (useMeta) {
+ oodate = meta_oodate(gn, oodate);
+ }
#endif
- /*
- * If the target isn't out-of-date, the parents need to know its
- * modification time. Note that targets that appear to be out-of-date
- * but aren't, because they have no commands and are GNode_IsTarget,
- * have their mtime stay below their children's mtime to keep parents from
- * thinking they're out-of-date.
- */
- if (!oodate) {
- GNodeListNode *ln;
- for (ln = gn->parents->first; ln != NULL; ln = ln->next)
- GNode_UpdateYoungestChild(ln->datum, gn);
- }
+ /*
+ * If the target isn't out-of-date, the parents need to know its
+ * modification time. Note that targets that appear to be out-of-date
+ * but aren't, because they have no commands and are GNode_IsTarget,
+ * have their mtime stay below their children's mtime to keep parents
+ * from thinking they're out-of-date.
+ */
+ if (!oodate) {
+ GNodeListNode *ln;
+ for (ln = gn->parents.first; ln != NULL; ln = ln->next)
+ GNode_UpdateYoungestChild(ln->datum, gn);
+ }
- return oodate;
+ return oodate;
}
static void
PretendAllChildrenAreMade(GNode *pgn)
{
- GNodeListNode *ln;
+ GNodeListNode *ln;
- for (ln = pgn->children->first; ln != NULL; ln = ln->next) {
- GNode *cgn = ln->datum;
+ for (ln = pgn->children.first; ln != NULL; ln = ln->next) {
+ GNode *cgn = ln->datum;
- Dir_UpdateMTime(cgn, FALSE); /* cgn->path may get updated as well */
- GNode_UpdateYoungestChild(pgn, cgn);
- pgn->unmade--;
- }
+ /* This may also update cgn->path. */
+ Dir_UpdateMTime(cgn, FALSE);
+ GNode_UpdateYoungestChild(pgn, cgn);
+ pgn->unmade--;
+ }
}
-/* Called by Make_Run and SuffApplyTransform on the downward pass to handle
+/*
+ * Called by Make_Run and SuffApplyTransform on the downward pass to handle
* .USE and transformation nodes, by copying the child node's commands, type
* flags and children to the parent node.
*
@@ -364,57 +380,62 @@ PretendAllChildrenAreMade(GNode *pgn)
void
Make_HandleUse(GNode *cgn, GNode *pgn)
{
- GNodeListNode *ln; /* An element in the children list */
+ GNodeListNode *ln; /* An element in the children list */
#ifdef DEBUG_SRC
- if (!(cgn->type & (OP_USE|OP_USEBEFORE|OP_TRANSFORM))) {
- debug_printf("Make_HandleUse: called for plain node %s\n", cgn->name);
- return; /* XXX: debug mode should not affect control flow */
- }
+ if (!(cgn->type & (OP_USE | OP_USEBEFORE | OP_TRANSFORM))) {
+ debug_printf("Make_HandleUse: called for plain node %s\n",
+ cgn->name);
+ /* XXX: debug mode should not affect control flow */
+ return;
+ }
#endif
- if ((cgn->type & (OP_USE|OP_USEBEFORE)) || Lst_IsEmpty(pgn->commands)) {
- if (cgn->type & OP_USEBEFORE) {
- /* .USEBEFORE */
- Lst_PrependAll(pgn->commands, cgn->commands);
- } else {
- /* .USE, or target has no commands */
- Lst_AppendAll(pgn->commands, cgn->commands);
- }
- }
+ if ((cgn->type & (OP_USE | OP_USEBEFORE)) ||
+ Lst_IsEmpty(&pgn->commands)) {
+ if (cgn->type & OP_USEBEFORE) {
+ /* .USEBEFORE */
+ Lst_PrependAll(&pgn->commands, &cgn->commands);
+ } else {
+ /* .USE, or target has no commands */
+ Lst_AppendAll(&pgn->commands, &cgn->commands);
+ }
+ }
- for (ln = cgn->children->first; ln != NULL; ln = ln->next) {
- GNode *gn = ln->datum;
+ for (ln = cgn->children.first; ln != NULL; ln = ln->next) {
+ GNode *gn = ln->datum;
- /*
- * Expand variables in the .USE node's name
- * and save the unexpanded form.
- * We don't need to do this for commands.
- * They get expanded properly when we execute.
- */
- if (gn->uname == NULL) {
- gn->uname = gn->name;
- } else {
- free(gn->name);
- }
- (void)Var_Subst(gn->uname, pgn, VARE_WANTRES, &gn->name);
- /* TODO: handle errors */
- if (gn->uname && strcmp(gn->name, gn->uname) != 0) {
- /* See if we have a target for this node. */
- GNode *tgn = Targ_FindNode(gn->name);
- if (tgn != NULL)
- gn = tgn;
+ /*
+ * Expand variables in the .USE node's name
+ * and save the unexpanded form.
+ * We don't need to do this for commands.
+ * They get expanded properly when we execute.
+ */
+ if (gn->uname == NULL) {
+ gn->uname = gn->name;
+ } else {
+ free(gn->name);
+ }
+ (void)Var_Subst(gn->uname, pgn, VARE_WANTRES, &gn->name);
+ /* TODO: handle errors */
+ if (gn->uname != NULL && strcmp(gn->name, gn->uname) != 0) {
+ /* See if we have a target for this node. */
+ GNode *tgn = Targ_FindNode(gn->name);
+ if (tgn != NULL)
+ gn = tgn;
+ }
+
+ Lst_Append(&pgn->children, gn);
+ Lst_Append(&gn->parents, pgn);
+ pgn->unmade++;
}
- Lst_Append(pgn->children, gn);
- Lst_Append(gn->parents, pgn);
- pgn->unmade++;
- }
-
- pgn->type |= cgn->type & ~(OP_OPMASK|OP_USE|OP_USEBEFORE|OP_TRANSFORM);
+ pgn->type |=
+ cgn->type & ~(OP_OPMASK | OP_USE | OP_USEBEFORE | OP_TRANSFORM);
}
-/* Used by Make_Run on the downward pass to handle .USE nodes. Should be
+/*
+ * Used by Make_Run on the downward pass to handle .USE nodes. Should be
* called before the children are enqueued to be looked at by MakeAddChild.
*
* For a .USE child, the commands, type flags and children are copied to the
@@ -428,113 +449,116 @@ Make_HandleUse(GNode *cgn, GNode *pgn)
static void
MakeHandleUse(GNode *cgn, GNode *pgn, GNodeListNode *ln)
{
- Boolean unmarked;
-
- unmarked = !(cgn->type & OP_MARK);
- cgn->type |= OP_MARK;
-
- if (!(cgn->type & (OP_USE|OP_USEBEFORE)))
- return;
-
- if (unmarked)
- Make_HandleUse(cgn, pgn);
-
- /*
- * This child node is now "made", so we decrement the count of
- * unmade children in the parent... We also remove the child
- * from the parent's list to accurately reflect the number of decent
- * children the parent has. This is used by Make_Run to decide
- * whether to queue the parent or examine its children...
- */
- Lst_Remove(pgn->children, ln);
- pgn->unmade--;
+ Boolean unmarked;
+
+ unmarked = !(cgn->type & OP_MARK);
+ cgn->type |= OP_MARK;
+
+ if (!(cgn->type & (OP_USE | OP_USEBEFORE)))
+ return;
+
+ if (unmarked)
+ Make_HandleUse(cgn, pgn);
+
+ /*
+ * This child node is now "made", so we decrement the count of
+ * unmade children in the parent... We also remove the child
+ * from the parent's list to accurately reflect the number of decent
+ * children the parent has. This is used by Make_Run to decide
+ * whether to queue the parent or examine its children...
+ */
+ Lst_Remove(&pgn->children, ln);
+ pgn->unmade--;
}
static void
HandleUseNodes(GNode *gn)
{
- GNodeListNode *ln, *nln;
- for (ln = gn->children->first; ln != NULL; ln = nln) {
- nln = ln->next;
- MakeHandleUse(ln->datum, gn, ln);
- }
+ GNodeListNode *ln, *nln;
+ for (ln = gn->children.first; ln != NULL; ln = nln) {
+ nln = ln->next;
+ MakeHandleUse(ln->datum, gn, ln);
+ }
}
-/* Check the modification time of a gnode, and update it if necessary.
- * Return 0 if the gnode does not exist, or its filesystem time if it does. */
+/*
+ * Check the modification time of a gnode, and update it if necessary.
+ * Return 0 if the gnode does not exist, or its filesystem time if it does.
+ */
time_t
Make_Recheck(GNode *gn)
{
- time_t mtime;
+ time_t mtime;
- Dir_UpdateMTime(gn, TRUE);
- mtime = gn->mtime;
+ Dir_UpdateMTime(gn, TRUE);
+ mtime = gn->mtime;
#ifndef RECHECK
- /*
- * We can't re-stat the thing, but we can at least take care of rules
- * where a target depends on a source that actually creates the
- * target, but only if it has changed, e.g.
- *
- * parse.h : parse.o
- *
- * parse.o : parse.y
- * yacc -d parse.y
- * cc -c y.tab.c
- * mv y.tab.o parse.o
- * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
- *
- * In this case, if the definitions produced by yacc haven't changed
- * from before, parse.h won't have been updated and gn->mtime will
- * reflect the current modification time for parse.h. This is
- * something of a kludge, I admit, but it's a useful one.
- *
- * XXX: People like to use a rule like "FRC:" to force things that
- * depend on FRC to be made, so we have to check for gn->children
- * being empty as well.
- */
- if (!Lst_IsEmpty(gn->commands) || Lst_IsEmpty(gn->children)) {
- gn->mtime = now;
- }
+ /*
+ * We can't re-stat the thing, but we can at least take care of rules
+ * where a target depends on a source that actually creates the
+ * target, but only if it has changed, e.g.
+ *
+ * parse.h : parse.o
+ *
+ * parse.o : parse.y
+ * yacc -d parse.y
+ * cc -c y.tab.c
+ * mv y.tab.o parse.o
+ * cmp -s y.tab.h parse.h || mv y.tab.h parse.h
+ *
+ * In this case, if the definitions produced by yacc haven't changed
+ * from before, parse.h won't have been updated and gn->mtime will
+ * reflect the current modification time for parse.h. This is
+ * something of a kludge, I admit, but it's a useful one.
+ *
+ * XXX: People like to use a rule like "FRC:" to force things that
+ * depend on FRC to be made, so we have to check for gn->children
+ * being empty as well.
+ */
+ if (!Lst_IsEmpty(gn->commands) || Lst_IsEmpty(gn->children)) {
+ gn->mtime = now;
+ }
#else
- /*
- * This is what Make does and it's actually a good thing, as it
- * allows rules like
- *
- * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
- *
- * to function as intended. Unfortunately, thanks to the stateless
- * nature of NFS (by which I mean the loose coupling of two clients
- * using the same file from a common server), there are times
- * when the modification time of a file created on a remote
- * machine will not be modified before the local stat() implied by
- * the Dir_UpdateMTime occurs, thus leading us to believe that the file
- * is unchanged, wreaking havoc with files that depend on this one.
- *
- * I have decided it is better to make too much than to make too
- * little, so this stuff is commented out unless you're sure it's ok.
- * -- ardeb 1/12/88
- */
- /*
- * Christos, 4/9/92: If we are saving commands, pretend that
- * the target is made now. Otherwise archives with '...' rules
- * don't work!
- */
- if (!GNode_ShouldExecute(gn) || (gn->type & OP_SAVE_CMDS) ||
+ /*
+ * This is what Make does and it's actually a good thing, as it
+ * allows rules like
+ *
+ * cmp -s y.tab.h parse.h || cp y.tab.h parse.h
+ *
+ * to function as intended. Unfortunately, thanks to the stateless
+ * nature of NFS (by which I mean the loose coupling of two clients
+ * using the same file from a common server), there are times when
+ * the modification time of a file created on a remote machine
+ * will not be modified before the local stat() implied by the
+ * Dir_UpdateMTime occurs, thus leading us to believe that the file
+ * is unchanged, wreaking havoc with files that depend on this one.
+ *
+ * I have decided it is better to make too much than to make too
+ * little, so this stuff is commented out unless you're sure it's ok.
+ * -- ardeb 1/12/88
+ */
+ /*
+ * Christos, 4/9/92: If we are saving commands, pretend that
+ * the target is made now. Otherwise archives with '...' rules
+ * don't work!
+ */
+ if (!GNode_ShouldExecute(gn) || (gn->type & OP_SAVE_CMDS) ||
(mtime == 0 && !(gn->type & OP_WAIT))) {
- DEBUG2(MAKE, " recheck(%s): update time from %s to now\n",
- gn->name, Targ_FmtTime(gn->mtime));
- gn->mtime = now;
- } else {
- DEBUG2(MAKE, " recheck(%s): current update time: %s\n",
- gn->name, Targ_FmtTime(gn->mtime));
- }
+ DEBUG2(MAKE, " recheck(%s): update time from %s to now\n",
+ gn->name,
+ gn->mtime == 0 ? "nonexistent" : Targ_FmtTime(gn->mtime));
+ gn->mtime = now;
+ } else {
+ DEBUG2(MAKE, " recheck(%s): current update time: %s\n",
+ gn->name, Targ_FmtTime(gn->mtime));
+ }
#endif
- /* XXX: The returned mtime may differ from gn->mtime.
- * Intentionally? */
- return mtime;
+ /* XXX: The returned mtime may differ from gn->mtime.
+ * Intentionally? */
+ return mtime;
}
/*
@@ -544,39 +568,54 @@ Make_Recheck(GNode *gn)
static void
UpdateImplicitParentsVars(GNode *cgn, const char *cname)
{
- GNodeListNode *ln;
- const char *cpref = GNode_VarPrefix(cgn);
-
- for (ln = cgn->implicitParents->first; ln != NULL; ln = ln->next) {
- GNode *pgn = ln->datum;
- if (pgn->flags & REMAKE) {
- Var_Set(IMPSRC, cname, pgn);
- if (cpref != NULL)
- Var_Set(PREFIX, cpref, pgn);
+ GNodeListNode *ln;
+ const char *cpref = GNode_VarPrefix(cgn);
+
+ for (ln = cgn->implicitParents.first; ln != NULL; ln = ln->next) {
+ GNode *pgn = ln->datum;
+ if (pgn->flags & REMAKE) {
+ Var_Set(IMPSRC, cname, pgn);
+ if (cpref != NULL)
+ Var_Set(PREFIX, cpref, pgn);
+ }
}
- }
}
/* See if a .ORDER rule stops us from building this node. */
static Boolean
IsWaitingForOrder(GNode *gn)
{
- GNodeListNode *ln;
+ GNodeListNode *ln;
+
+ for (ln = gn->order_pred.first; ln != NULL; ln = ln->next) {
+ GNode *ogn = ln->datum;
- for (ln = gn->order_pred->first; ln != NULL; ln = ln->next) {
- GNode *ogn = ln->datum;
+ if (GNode_IsDone(ogn) || !(ogn->flags & REMAKE))
+ continue;
- if (ogn->made >= MADE || !(ogn->flags & REMAKE))
- continue;
+ DEBUG2(MAKE,
+ "IsWaitingForOrder: Waiting for .ORDER node \"%s%s\"\n",
+ ogn->name, ogn->cohort_num);
+ return TRUE;
+ }
+ return FALSE;
+}
- DEBUG2(MAKE, "IsWaitingForOrder: Waiting for .ORDER node \"%s%s\"\n",
- ogn->name, ogn->cohort_num);
- return TRUE;
- }
- return FALSE;
+static int MakeBuildParent(GNode *, GNodeListNode *);
+
+static void
+ScheduleOrderSuccessors(GNode *gn)
+{
+ GNodeListNode *toBeMadeNext = toBeMade.first;
+ GNodeListNode *ln;
+
+ for (ln = gn->order_succ.first; ln != NULL; ln = ln->next)
+ if (MakeBuildParent(ln->datum, toBeMadeNext) != 0)
+ break;
}
-/* Perform update on the parents of a node. Used by JobFinish once
+/*
+ * Perform update on the parents of a node. Used by JobFinish once
* a node has been dealt with and by MakeStartJobs if it finds an
* up-to-date node.
*
@@ -598,149 +637,159 @@ IsWaitingForOrder(GNode *gn)
void
Make_Update(GNode *cgn)
{
- const char *cname; /* the child's name */
- time_t mtime = -1;
- GNodeList *parents;
- GNodeListNode *ln;
- GNode *centurion;
-
- /* It is save to re-examine any nodes again */
- checked_seqno++;
-
- cname = GNode_VarTarget(cgn);
-
- DEBUG2(MAKE, "Make_Update: %s%s\n", cgn->name, cgn->cohort_num);
-
- /*
- * If the child was actually made, see what its modification time is
- * now -- some rules won't actually update the file. If the file still
- * doesn't exist, make its mtime now.
- */
- if (cgn->made != UPTODATE) {
- mtime = Make_Recheck(cgn);
- }
-
- /*
- * If this is a `::' node, we must consult its first instance
- * which is where all parents are linked.
- */
- if ((centurion = cgn->centurion) != NULL) {
- if (!Lst_IsEmpty(cgn->parents))
- Punt("%s%s: cohort has parents", cgn->name, cgn->cohort_num);
- centurion->unmade_cohorts--;
- if (centurion->unmade_cohorts < 0)
- Error("Graph cycles through centurion %s", centurion->name);
- } else {
- centurion = cgn;
- }
- parents = centurion->parents;
-
- /* If this was a .ORDER node, schedule the RHS */
- Lst_ForEachUntil(centurion->order_succ, MakeBuildParent, toBeMade->first);
-
- /* Now mark all the parents as having one less unmade child */
- for (ln = parents->first; ln != NULL; ln = ln->next) {
- GNode *pgn = ln->datum;
+ const char *cname; /* the child's name */
+ time_t mtime = -1;
+ GNodeList *parents;
+ GNodeListNode *ln;
+ GNode *centurion;
- if (DEBUG(MAKE)) {
- debug_printf("inspect parent %s%s: ", pgn->name, pgn->cohort_num);
- GNode_FprintDetails(opts.debug_file, "", pgn, "");
- debug_printf(", unmade %d ", pgn->unmade - 1);
- }
+ /* It is save to re-examine any nodes again */
+ checked_seqno++;
- if (!(pgn->flags & REMAKE)) {
- /* This parent isn't needed */
- DEBUG0(MAKE, "- not needed\n");
- continue;
- }
- if (mtime == 0 && !(cgn->type & OP_WAIT))
- pgn->flags |= FORCE;
+ cname = GNode_VarTarget(cgn);
+
+ DEBUG2(MAKE, "Make_Update: %s%s\n", cgn->name, cgn->cohort_num);
/*
- * If the parent has the .MADE attribute, its timestamp got
- * updated to that of its newest child, and its unmade
- * child count got set to zero in Make_ExpandUse().
- * However other things might cause us to build one of its
- * children - and so we mustn't do any processing here when
- * the child build finishes.
+ * If the child was actually made, see what its modification time is
+ * now -- some rules won't actually update the file. If the file
+ * still doesn't exist, make its mtime now.
*/
- if (pgn->type & OP_MADE) {
- DEBUG0(MAKE, "- .MADE\n");
- continue;
- }
-
- if (!(cgn->type & (OP_EXEC | OP_USE | OP_USEBEF