/*
* Copyright (c) 1988, 1989, 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Adam de Boor.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Copyright (c) 1989 by Berkeley Softworks
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Adam de Boor.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Handling of variables and the expressions formed from them.
*
* Variables are set using lines of the form VAR=value. Both the variable
* name and the value can contain references to other variables, by using
* expressions like ${VAR}, ${VAR:Modifiers}, ${${VARNAME}} or ${VAR:${MODS}}.
*
* Interface:
* Var_Set
* Var_SetExpand Set the value of the variable, creating it if
* necessary.
*
* Var_Append
* Var_AppendExpand
* Append more characters to the variable, creating it if
* necessary. A space is placed between the old value and
* the new one.
*
* Var_Exists
* Var_ExistsExpand
* See if a variable exists.
*
* Var_Value Return the unexpanded value of a variable, or NULL if
* the variable is undefined.
*
* Var_Subst Substitute all expressions in a string.
*
* Var_Parse Parse an expression such as ${VAR:Mpattern}.
*
* Var_Delete Delete a variable.
*
* Var_ReexportVars
* Export some or even all variables to the environment
* of this process and its child processes.
*
* Var_Export Export the variable to the environment of this process
* and its child processes.
*
* Var_UnExport Don't export the variable anymore.
*
* Debugging:
* Var_Stats Print out hashing statistics if in -dh mode.
*
* Var_Dump Print out all variables defined in the given scope.
*/
/*
* Variables are defined using one of the VAR=value assignments. Their
* value can be queried by expressions such as $V, ${VAR}, or with modifiers
* such as ${VAR:S,from,to,g:Q}.
*
* There are 3 kinds of variables: scope variables, environment variables,
* undefined variables.
*
* Scope variables are stored in GNode.vars. The only way to undefine
* a scope variable is using the .undef directive. In particular, it must
* not be possible to undefine a variable during the evaluation of an
* expression, or Var.name might point nowhere. (There is another,
* unintended way to undefine a scope variable, see varmod-loop-delete.mk.)
*
* Environment variables are short-lived. They are returned by VarFind, and
* after using them, they must be freed using VarFreeShortLived.
*
* Undefined variables occur during evaluation of expressions such
* as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers.
*/
typedef struct Var {
/*
* The name of the variable, once set, doesn't change anymore.
* For scope variables, it aliases the corresponding HashEntry name.
* For environment and undefined variables, it is allocated.
*/
FStr name;
/* The unexpanded value of the variable. */
Buffer val;
/* The variable came from the command line. */
bool fromCmd:1;
/*
* The variable is short-lived.
* These variables are not registered in any GNode, therefore they
* must be freed after use.
*/
bool shortLived:1;
/*
* The variable comes from the environment.
* Appending to its value depends on the scope, see var-op-append.mk.
*/
bool fromEnvironment:1;
/*
* The variable value cannot be changed anymore, and the variable
* cannot be deleted. Any attempts to do so are silently ignored,
* they are logged with -dv though.
* Use .[NO]READONLY: to adjust.
*
* See VAR_SET_READONLY.
*/
bool readOnly:1;
/*
* The variable is read-only and immune to the .NOREADONLY special
* target. Any attempt to modify it results in an error.
*/
bool readOnlyLoud:1;
/*
* The variable is currently being accessed by Var_Parse or Var_Subst.
* This temporary marker is used to avoid endless recursion.
*/
bool inUse:1;
/*
* The variable is exported to the environment, to be used by child
* processes.
*/
bool exported:1;
/*
* At the point where this variable was exported, it contained an
* unresolved reference to another variable. Before any child
* process is started, it needs to be actually exported, resolving
* the referenced variable just in time.
*/
bool reexport:1;
} Var;
/*
* Exporting variables is expensive and may leak memory, so skip it if we
* can.
*/
typedef enum VarExportedMode {
VAR_EXPORTED_NONE,
VAR_EXPORTED_SOME,
VAR_EXPORTED_ALL
} VarExportedMode;
typedef enum UnexportWhat {
/* Unexport the variables given by name. */
UNEXPORT_NAMED,
/*
* Unexport all globals previously exported, but keep the environment
* inherited from the parent.
*/
UNEXPORT_ALL,
/*
* Unexport all globals previously exported and clear the environment
* inherited from the parent.
*/
UNEXPORT_ENV
} UnexportWhat;
/* Flags for pattern matching in the :S and :C modifiers */
typedef struct PatternFlags {
bool subGlobal:1; /* 'g': replace as often as possible */
bool subOnce:1; /* '1': replace only once */
bool anchorStart:1; /* '^': match only at start of word */
bool anchorEnd:1; /* '$': match only at end of word */
} PatternFlags;
/* SepBuf builds a string from words interleaved with separators. */
typedef struct SepBuf {
Buffer buf;
bool needSep;
/* Usually ' ', but see the ':ts' modifier. */
char sep;
} SepBuf;
/* Whether we have replaced the original environ (which we cannot free). */
char **savedEnv = NULL;
/*
* Special return value for Var_Parse, indicating a parse error. It may be
* caused by an undefined variable, a syntax error in a modifier or
* something entirely different.
*/
char var_Error[] = "";
/*
* Special return value for Var_Parse, indicating an undefined variable in
* a case where VARE_EVAL_DEFINED is not set. This undefined variable is
* typically a dynamic variable such as ${.TARGET}, whose expansion needs to
* be deferred until it is defined in an actual target.
*
* See VARE_EVAL_KEEP_UNDEFINED.
*/
static char varUndefined[] = "";
/*
* Traditionally this make consumed $$ during := like any other expansion.
* Other make's do not, and this make follows straight since 2016-01-09.
*
* This knob allows controlling the behavior:
* false to consume $$ during := assignment.
* true to preserve $$ during := assignment.
*/
#define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
static bool save_dollars = true;
/*
* A scope collects variable names and their values.
*
* The main scope is SCOPE_GLOBAL, which contains the variables that are set
* in the makefiles. SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and
* contains some internal make variables. These internal variables can thus
* be overridden, they can also be restored by undefining the overriding
* variable.
*
* SCOPE_CMDLINE contains variables from the command line arguments. These
* override variables from SCOPE_GLOBAL.
*
* There is no scope for environment variables, these are generated on-the-fly
* whenever they are referenced.
*
* Each target has its own scope, containing the 7 target-local variables
* .TARGET, .ALLSRC, etc. Variables set on dependency lines also go in
* this scope.
*/
if (!(Substring_Length(name) > 0 && name.start[0] == '.'))
return name;
if (Substring_Equals(name, ".ALLSRC"))
return Substring_InitStr(ALLSRC);
if (Substring_Equals(name, ".ARCHIVE"))
return Substring_InitStr(ARCHIVE);
if (Substring_Equals(name, ".IMPSRC"))
return Substring_InitStr(IMPSRC);
if (Substring_Equals(name, ".MEMBER"))
return Substring_InitStr(MEMBER);
if (Substring_Equals(name, ".OODATE"))
return Substring_InitStr(OODATE);
if (Substring_Equals(name, ".PREFIX"))
return Substring_InitStr(PREFIX);
if (Substring_Equals(name, ".TARGET"))
return Substring_InitStr(TARGET);
/* GNU make has an additional alias $^ == ${.ALLSRC}. */
if (Substring_Equals(name, ".SHELL") && shellPath == NULL)
Shell_Init();
/*
* Find the variable in the scope, and maybe in other scopes as well.
*
* Input:
* name name to find, is not expanded any further
* scope scope in which to look first
* elsewhere true to look in other scopes as well
*
* Results:
* The found variable, or NULL if the variable does not exist.
* If the variable is short-lived (such as environment variables), it
* must be freed using VarFreeShortLived after use.
*/
static Var *
VarFindSubstring(Substring name, GNode *scope, bool elsewhere)
{
Var *var;
unsigned nameHash;
/* Replace '.TARGET' with '@', likewise for other local variables. */
name = CanonicalVarname(name);
nameHash = Hash_Substring(name);
var = GNode_FindVar(scope, name, nameHash);
if (!elsewhere)
return var;
if (var == NULL && scope != SCOPE_CMDLINE)
var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash);
if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) {
var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
if (var == NULL && scope != SCOPE_INTERNAL) {
/* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */
var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash);
}
}
static const char *
ValueDescription(const char *value)
{
if (value[0] == '\0')
return "# (empty)";
if (ch_isspace(value[strlen(value) - 1]))
return "# (ends with space)";
return "";
}
/* Add a new variable of the given name and value to the given scope. */
static Var *
VarAdd(const char *name, const char *value, GNode *scope, VarSetFlags flags)
{
HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL);
Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value,
false, false, (flags & VAR_SET_READONLY) != 0);
HashEntry_Set(he, v);
DEBUG4(VAR, "%s: %s = %s%s\n",
scope->name, name, value, ValueDescription(value));
return v;
}
/*
* Remove a variable from a scope, freeing all related memory as well.
* The variable name is kept as-is, it is not expanded.
*/
void
Var_Delete(GNode *scope, const char *varname)
{
HashEntry *he = HashTable_FindEntry(&scope->vars, varname);
Var *v;
if (he == NULL) {
DEBUG2(VAR, "%s: ignoring delete '%s' as it is not found\n",
scope->name, varname);
return;
}
v = he->value;
if (v->readOnlyLoud) {
Parse_Error(PARSE_FATAL,
"Cannot delete \"%s\" as it is read-only",
v->name.str);
return;
}
if (v->readOnly) {
DEBUG2(VAR, "%s: ignoring delete '%s' as it is read-only\n",
scope->name, varname);
return;
}
if (v->inUse) {
Parse_Error(PARSE_FATAL,
"Cannot delete variable \"%s\" while it is used",
v->name.str);
return;
}
DEBUG2(VAR, "%s: delete %s\n", scope->name, varname);
if (v->exported)
unsetenv(v->name.str);
if (strcmp(v->name.str, ".MAKE.EXPORTED") == 0)
var_exportedVars = VAR_EXPORTED_NONE;
/*
* Undefine one or more variables from the global scope.
* The argument is expanded exactly once and then split into words.
*/
void
Var_Undef(const char *arg)
{
char *expanded;
Words varnames;
size_t i;
if (arg[0] == '\0') {
Parse_Error(PARSE_FATAL,
"The .undef directive requires an argument");
return;
}
expanded = Var_Subst(arg, SCOPE_GLOBAL, VARE_EVAL);
if (expanded == var_Error) {
/* TODO: Make this part of the code reachable. */
Parse_Error(PARSE_FATAL,
"Error in variable names to be undefined");
return;
}
for (i = 0; i < varnames.len; i++) {
const char *varname = varnames.words[i];
Global_Delete(varname);
}
Words_Free(varnames);
free(expanded);
}
static bool
MayExport(const char *name)
{
if (name[0] == '.')
return false; /* skip internals */
if (name[0] == '-')
return false; /* skip misnamed variables */
if (name[1] == '\0') {
/*
* A single char.
* If it is one of the variables that should only appear in
* local scope, skip it, else we can get Var_Subst
* into a loop.
*/
switch (name[0]) {
case '@':
case '%':
case '*':
case '!':
return false;
}
}
return true;
}
if (v->exported && !v->reexport)
return false; /* nothing to do */
if (strchr(val, '$') == NULL) {
if (!v->exported)
setenv(name, val, 1);
return true;
}
if (v->inUse)
return false; /* see EMPTY_SHELL in directive-export.mk */
/* XXX: name is injected without escaping it */
expr = str_concat3("${", name, "}");
val = Var_Subst(expr, scope, VARE_EVAL);
if (scope != SCOPE_GLOBAL) {
/* we will need to re-export the global version */
v = VarFind(name, SCOPE_GLOBAL, false);
if (v != NULL)
v->exported = false;
}
/* TODO: handle errors */
setenv(name, val, 1);
free(val);
free(expr);
return true;
}
/*
* Flag the variable as something we need to re-export.
* No point actually exporting it now though,
* the child process can do it at the last minute.
* Avoid calling setenv more often than necessary since it can leak.
*/
v->exported = true;
v->reexport = true;
return true;
}
if (!v->exported)
setenv(v->name.str, v->val.data, 1);
return true;
}
/*
* Mark a single variable to be exported later for subprocesses.
*
* Internal variables are not exported.
*/
static bool
ExportVar(const char *name, GNode *scope, VarExportMode mode)
{
Var *v;
if (!MayExport(name))
return false;
v = VarFind(name, scope, false);
if (v == NULL && scope != SCOPE_GLOBAL)
v = VarFind(name, SCOPE_GLOBAL, false);
if (v == NULL)
return false;
if (mode == VEM_ENV)
return ExportVarEnv(v, scope);
else if (mode == VEM_PLAIN)
return ExportVarPlain(v);
else
return ExportVarLiteral(v);
}
/*
* Actually export the variables that have been marked as needing to be
* re-exported.
*/
void
Var_ReexportVars(GNode *scope)
{
char *xvarnames;
/*
* Several make implementations support this sort of mechanism for
* tracking recursion - but each uses a different name.
* We allow the makefiles to update MAKELEVEL and ensure
* children see a correctly incremented value.
*/
char level_buf[21];
snprintf(level_buf, sizeof level_buf, "%d", makelevel + 1);
setenv(MAKE_LEVEL_ENV, level_buf, 1);
if (var_exportedVars == VAR_EXPORTED_NONE)
return;
if (var_exportedVars == VAR_EXPORTED_ALL) {
HashIter hi;
/* Ouch! Exporting all variables at once is crazy. */
HashIter_Init(&hi, &SCOPE_GLOBAL->vars);
while (HashIter_Next(&hi)) {
Var *var = hi.entry->value;
ExportVar(var->name.str, scope, VEM_ENV);
}
return;
}
if (isEnv) {
if (arg[0] != '\0') {
Parse_Error(PARSE_FATAL,
"The directive .unexport-env does not take "
"arguments");
/* continue anyway */
}
what = UNEXPORT_ENV;
} else {
what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL;
if (what == UNEXPORT_NAMED)
varnames = FStr_InitRefer(arg);
}
/* Set the variable to the value; the name is not expanded. */
void
Var_SetWithFlags(GNode *scope, const char *name, const char *val,
VarSetFlags flags)
{
Var *v;
assert(val != NULL);
if (name[0] == '\0') {
DEBUG3(VAR,
"%s: ignoring '%s = %s' as the variable name is empty\n",
scope->name, name, val);
return;
}
if (scope == SCOPE_GLOBAL
&& VarFind(name, SCOPE_CMDLINE, false) != NULL) {
/*
* The global variable would not be visible anywhere.
* Therefore, there is no point in setting it at all.
*/
DEBUG3(VAR,
"%s: ignoring '%s = %s' "
"due to a command line variable of the same name\n",
scope->name, name, val);
return;
}
/*
* Only look for a variable in the given scope since anything set
* here will override anything in a lower scope, so there's not much
* point in searching them all.
*/
v = VarFind(name, scope, false);
if (v == NULL) {
if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT)) {
/*
* This variable would normally prevent the same name
* being added to SCOPE_GLOBAL, so delete it from
* there if needed. Otherwise -V name may show the
* wrong value.
*
* See ExistsInCmdline.
*/
Var *gl = VarFind(name, SCOPE_GLOBAL, false);
if (gl != NULL && strcmp(gl->val.data, val) == 0) {
DEBUG3(VAR,
"%s: ignoring to override the global "
"'%s = %s' from a command line variable "
"as the value wouldn't change\n",
scope->name, name, val);
} else if (gl != NULL && gl->readOnlyLoud)
Parse_Error(PARSE_FATAL,
"Cannot override "
"read-only global variable \"%s\" "
"with a command line variable", name);
else
Var_Delete(SCOPE_GLOBAL, name);
}
if (strcmp(name, ".SUFFIXES") == 0) {
/* special: treat as read-only */
DEBUG3(VAR,
"%s: ignoring '%s = %s' as it is read-only\n",
scope->name, name, val);
return;
}
v = VarAdd(name, val, scope, flags);
} else {
if (v->readOnlyLoud) {
Parse_Error(PARSE_FATAL,
"Cannot overwrite \"%s\" as it is read-only",
name);
return;
}
if (v->readOnly && !(flags & VAR_SET_READONLY)) {
DEBUG3(VAR,
"%s: ignoring '%s = %s' as it is read-only\n",
scope->name, name, val);
return;
}
Buf_Clear(&v->val);
Buf_AddStr(&v->val, val);
/*
* Any variables given on the command line are automatically
* exported to the environment (as per POSIX standard), except
* for internals.
*/
if (!(flags & VAR_SET_NO_EXPORT)) {
/*
* If requested, don't export these in the
* environment individually. We still put
* them in .MAKEOVERRIDES so that the
* command-line settings continue to override
* Makefile settings.
*/
if (!opts.varNoExportEnv && name[0] != '.')
setenv(name, val, 1);
if (!(flags & VAR_SET_INTERNAL))
Global_Append(".MAKEOVERRIDES", name);
}
}
/*
* In the scope, expand the variable name once, then create the variable or
* replace its value.
*/
void
Var_SetExpand(GNode *scope, const char *name, const char *val)
{
FStr varname = FStr_InitRefer(name);
assert(val != NULL);
Var_Expand(&varname, scope, VARE_EVAL);
if (varname.str[0] == '\0') {
DEBUG4(VAR,
"%s: ignoring '%s = %s' "
"as the variable name '%s' expands to empty\n",
scope->name, varname.str, val, name);
} else
Var_SetWithFlags(scope, varname.str, val, VAR_SET_NONE);
/*
* Append the value to the named variable.
*
* If the variable doesn't exist, it is created. Otherwise a single space
* and the given value are appended.
*/
void
Var_Append(GNode *scope, const char *name, const char *val)
{
Var *v;
v = VarFind(name, scope, scope == SCOPE_GLOBAL);
if (v == NULL) {
Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
} else if (v->readOnlyLoud) {
Parse_Error(PARSE_FATAL,
"Cannot append to \"%s\" as it is read-only", name);
return;
} else if (v->readOnly) {
DEBUG3(VAR, "%s: ignoring '%s += %s' as it is read-only\n",
scope->name, name, val);
} else if (scope == SCOPE_CMDLINE || !v->fromCmd) {
Buf_AddByte(&v->val, ' ');
Buf_AddStr(&v->val, val);
/*
* In the scope, expand the variable name once. If the variable exists in the
* scope, add a space and the value, otherwise set the variable to the value.
*
* Appending to an environment variable only works in the global scope, that
* is, for variable assignments in makefiles, but not inside conditions or the
* commands of a target.
*/
void
Var_AppendExpand(GNode *scope, const char *name, const char *val)
{
FStr xname = FStr_InitRefer(name);
assert(val != NULL);
Var_Expand(&xname, scope, VARE_EVAL);
if (xname.str != name && xname.str[0] == '\0')
DEBUG4(VAR,
"%s: ignoring '%s += %s' "
"as the variable name '%s' expands to empty\n",
scope->name, xname.str, val, name);
else
Var_Append(scope, xname.str, val);
bool
Var_Exists(GNode *scope, const char *name)
{
Var *v = VarFind(name, scope, true);
if (v == NULL)
return false;
VarFreeShortLived(v);
return true;
}
/*
* See if the given variable exists, in the given scope or in other
* fallback scopes.
*
* Input:
* scope scope in which to start search
* name name of the variable to find, is expanded once
*/
bool
Var_ExistsExpand(GNode *scope, const char *name)
{
FStr varname = FStr_InitRefer(name);
bool exists;
/*
* Return the unexpanded value of the given variable in the given scope,
* falling back to the command, global and environment scopes, in this order,
* but see the -e option.
*
* Input:
* name the name to find, is not expanded any further
*
* Results:
* The value if the variable exists, NULL if it doesn't.
* The value is valid until the next modification to any variable.
*/
FStr
Var_Value(GNode *scope, const char *name)
{
Var *v = VarFind(name, scope, true);
char *value;
if (v == NULL)
return FStr_InitRefer(NULL);
if (!v->shortLived)
return FStr_InitRefer(v->val.data);
value = v->val.data;
v->val.data = NULL;
VarFreeShortLived(v);
return FStr_InitOwn(value);
}
/* Set or clear the read-only attribute of the variable if it exists. */
void
Var_ReadOnly(const char *name, bool bf)
{
Var *v;
v = VarFind(name, SCOPE_GLOBAL, false);
if (v == NULL) {
DEBUG1(VAR, "Var_ReadOnly: %s not found\n", name);
return;
}
v->readOnly = bf;
DEBUG2(VAR, "Var_ReadOnly: %s %s\n", name, bf ? "true" : "false");
}
/*
* Return the unexpanded variable value from this node, without trying to look
* up the variable in any other scope.
*/
const char *
GNode_ValueDirect(GNode *gn, const char *name)
{
Var *v = VarFind(name, gn, false);
return v != NULL ? v->val.data : NULL;
}
/*
* This callback for ModifyWords gets a single word from an expression
* and typically adds a modification of this word to the buffer. It may also
* do nothing or add several words.
*
* For example, when evaluating the modifier ':M*b' in ${:Ua b c:M*b}, the
* callback is called 3 times, once for "a", "b" and "c".
*
* Some ModifyWord functions assume that they are always passed a
* null-terminated substring, which is currently guaranteed but may change in
* the future.
*/
typedef void (*ModifyWordProc)(Substring word, SepBuf *buf, void *data);
/* unanchored case, may match more than once */
while ((match = Substring_Find(word, args->lhs)) != NULL) {
SepBuf_AddRange(buf, word.start, match);
SepBuf_AddSubstring(buf, args->rhs);
args->matched = true;
word.start = match + lhsLen;
if (Substring_IsEmpty(word) || !args->pflags.subGlobal)
break;
}
nosub:
SepBuf_AddSubstring(buf, word);
}
/* Print the error caused by a regcomp or regexec call. */
static void
RegexError(int reerr, const regex_t *pat, const char *str)
{
size_t errlen = regerror(reerr, pat, NULL, 0);
char *errbuf = bmake_malloc(errlen);
regerror(reerr, pat, errbuf, errlen);
Parse_Error(PARSE_FATAL, "%s: %s", str, errbuf);
free(errbuf);
}
/* In the modifier ':C', replace a backreference from \0 to \9. */
static void
RegexReplaceBackref(char ref, SepBuf *buf, const char *wp,
const regmatch_t *m, size_t nsub)
{
unsigned n = (unsigned)ref - '0';
if (n >= nsub)
Parse_Error(PARSE_FATAL, "No subexpression \\%u", n);
else if (m[n].rm_so == -1) {
if (opts.strict)
Error("No match for subexpression \\%u", n);
} else {
SepBuf_AddRange(buf,
wp + (size_t)m[n].rm_so,
wp + (size_t)m[n].rm_eo);
}
}
/*
* The regular expression matches the word; now add the replacement to the
* buffer, taking back-references from 'wp'.
*/
static void
RegexReplace(Substring replace, SepBuf *buf, const char *wp,
const regmatch_t *m, size_t nsub)
{
const char *rp;
for (rp = replace.start; rp != replace.end; rp++) {
if (*rp == '\\' && rp + 1 != replace.end &&
(rp[1] == '&' || rp[1] == '\\'))
SepBuf_AddBytes(buf, ++rp, 1);
else if (*rp == '\\' && rp + 1 != replace.end &&
ch_isdigit(rp[1]))
RegexReplaceBackref(*++rp, buf, wp, m, nsub);
else if (*rp == '&') {
SepBuf_AddRange(buf,
wp + (size_t)m[0].rm_so,
wp + (size_t)m[0].rm_eo);
} else
SepBuf_AddBytes(buf, rp, 1);
}
}
/*
* The :[first..last] modifier selects words from the expression.
* It can also reverse the words.
*/
static char *
VarSelectWords(const char *str, int first, int last,
char sep, bool oneBigWord)
{
SubstringWords words;
int len, start, end, step;
int i;
SepBuf buf;
SepBuf_Init(&buf, sep);
if (oneBigWord) {
/* fake what Substring_Words() would do */
words.len = 1;
words.words = bmake_malloc(sizeof(words.words[0]));
words.freeIt = NULL;
words.words[0] = Substring_InitStr(str); /* no need to copy */
} else {
words = Substring_Words(str, false);
}
/* Convert -1 to len, -2 to (len - 1), etc. */
len = (int)words.len;
if (first < 0)
first += len + 1;
if (last < 0)
last += len + 1;
if (first > last) {
start = (first > len ? len : first) - 1;
end = last < 1 ? 0 : last - 1;
step = -1;
} else {
start = first < 1 ? 0 : first - 1;
end = last > len ? len : last;
step = 1;
}
for (i = start; (step < 0) == (i >= end); i += step) {
SepBuf_AddSubstring(&buf, words.words[i]);
SepBuf_Sep(&buf);
}
SubstringWords_Free(words);
return SepBuf_DoneData(&buf);
}
static void
ModifyWord_Realpath(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
{
struct stat st;
char rbuf[MAXPATHLEN];
const char *rp;
for (i = 0; i < words.len; i++) {
if (i != 0) {
/*
* XXX: Use ch->sep instead of ' ', for consistency.
*/
Buf_AddByte(&buf, ' ');
}
Buf_AddRange(&buf, words.words[i].start, words.words[i].end);
}
SubstringWords_Free(words);
return Buf_DoneData(&buf);
}
/*
* Quote shell meta-characters and space characters in the string.
* If quoteDollar is set, also quote and double any '$' characters.
*/
static void
QuoteShell(const char *str, bool quoteDollar, LazyBuf *buf)
{
const char *p;
LazyBuf_Init(buf, str);
for (p = str; *p != '\0'; p++) {
if (*p == '\n') {
const char *newline = Shell_GetNewline();
if (newline == NULL)
newline = "\\\n";
LazyBuf_AddStr(buf, newline);
continue;
}
if (ch_isspace(*p) || ch_is_shell_meta(*p))
LazyBuf_Add(buf, '\\');
LazyBuf_Add(buf, *p);
if (quoteDollar && *p == '$')
LazyBuf_AddStr(buf, "\\$");
}
}
/*
* Compute the 32-bit hash of the given string, using the MurmurHash3
* algorithm. Output is encoded as 8 hex digits, in Little Endian order.
*/
static char *
Hash(const char *str)
{
static const char hexdigits[16] = "0123456789abcdef";
const unsigned char *ustr = (const unsigned char *)str;
/*
* The ApplyModifier functions take an expression that is being evaluated.
* Their task is to apply a single modifier to the expression. This involves
* parsing the modifier, evaluating it and finally updating the value of the
* expression.
*
* Parsing the modifier
*
* If parsing succeeds, the parsing position *pp is updated to point to the
* first character following the modifier, which typically is either ':' or
* ch->endc. The modifier doesn't have to check for this delimiter character,
* this is done by ApplyModifiers.
*
* XXX: As of 2020-11-15, some modifiers such as :S, :C, :P, :L do not
* need to be followed by a ':' or endc; this was an unintended mistake.
*
* If parsing fails because of a missing delimiter after a modifier part (as
* in the :S, :C or :@ modifiers), return AMR_CLEANUP.
*
* If parsing fails because the modifier is unknown, return AMR_UNKNOWN to
* try the SysV modifier ':from=to' as fallback. This should only be
* done as long as there have been no side effects from evaluating nested
* variables, to avoid evaluating them more than once. In this case, the
* parsing position may or may not be updated. (XXX: Why not? The original
* parsing position is well-known in ApplyModifiers.)
*
* If parsing fails and the SysV modifier ${VAR:from=to} should not be used
* as a fallback, issue an error message using Parse_Error (preferred over
* Error) and then return AMR_CLEANUP, which stops processing the expression.
* (XXX: As of 2020-08-23, evaluation of the string continues nevertheless
* after skipping a few bytes, which results in garbage.)
*
* Evaluating the modifier
*
* After parsing, the modifier is evaluated. The side effects from evaluating
* nested expressions in the modifier text often already happen
* during parsing though. For most modifiers this doesn't matter since their
* only noticeable effect is that they update the value of the expression.
* Some modifiers such as ':sh' or '::=' have noticeable side effects though.
*
* Evaluating the modifier usually takes the current value of the
* expression from ch->expr->value, or the variable name from ch->var->name,
* and stores the result back in ch->expr->value via Expr_SetValueOwn or
* Expr_SetValueRefer.
*
* Some modifiers such as :D and :U turn undefined expressions into defined
* expressions using Expr_Define.
*/
typedef enum ExprDefined {
/* The expression is based on a regular, defined variable. */
DEF_REGULAR,
/* The expression is based on an undefined variable. */
DEF_UNDEF,
/*
* The expression started as an undefined expression, but one
* of the modifiers (such as ':D' or ':U') has turned the expression
* from undefined to defined.
*/
DEF_DEFINED
} ExprDefined;
#if __STDC_VERSION__ >= 199901L
#define const_member const
#else
#define const_member /* no const possible */
#endif
/* An expression based on a variable, such as $@ or ${VAR:Mpattern:Q}. */
typedef struct Expr {
const char *name;
FStr value;
VarEvalMode const_member emode;
GNode *const_member scope;
ExprDefined defined;
} Expr;
/*
* The status of applying a chain of modifiers to an expression.
*
* The modifiers of an expression are broken into chains of modifiers,
* starting a new nested chain whenever an indirect modifier starts. There
* are at most 2 nesting levels: the outer one for the direct modifiers, and
* the inner one for the indirect modifiers.
*
* For example, the expression ${VAR:M*:${IND1}:${IND2}:O:u} has 3 chains of
* modifiers:
*
* Chain 1 starts with the single modifier ':M*'.
* Chain 2 starts with all modifiers from ${IND1}.
* Chain 2 ends at the ':' between ${IND1} and ${IND2}.
* Chain 3 starts with all modifiers from ${IND2}.
* Chain 3 ends at the ':' after ${IND2}.
* Chain 1 continues with the 2 modifiers ':O' and ':u'.
* Chain 1 ends at the final '}' of the expression.
*
* After such a chain ends, its properties no longer have any effect.
*
* See varmod-indirect.mk.
*/
typedef struct ModChain {
Expr *expr;
/* '\0' or '{' or '(' */
char const_member startc;
/* '\0' or '}' or ')' */
char const_member endc;
/* Separator when joining words (see the :ts modifier). */
char sep;
/*
* Whether some modifiers that otherwise split the variable value
* into words, like :S and :C, treat the variable value as a single
* big word, possibly containing spaces.
*/
bool oneBigWord;
} ModChain;
typedef enum ApplyModifierResult {
/* Continue parsing */
AMR_OK,
/* Not a match, try the ':from=to' modifier as well. */
AMR_UNKNOWN,
/* Error out without further error message. */
AMR_CLEANUP
} ApplyModifierResult;
/*
* Allow backslashes to escape the delimiter, $, and \, but don't touch other
* backslashes.
*/
static bool
IsEscapedModifierPart(const char *p, char delim,
struct ModifyWord_SubstArgs *subst)
{
if (p[0] != '\\' || p[1] == '\0')
return false;
if (p[1] == delim || p[1] == '\\' || p[1] == '$')
return true;
return p[1] == '&' && subst != NULL;
}
/*
* In a part of a modifier, parse a subexpression and evaluate it.
*/
static void
ParseModifierPartExpr(const char **pp, LazyBuf *part, const ModChain *ch,
VarEvalMode emode)
{
const char *p = *pp;
FStr nested_val = Var_Parse(&p, ch->expr->scope,
VarEvalMode_WithoutKeepDollar(emode));
/* TODO: handle errors */
if (VarEvalMode_ShouldEval(emode))
LazyBuf_AddStr(part, nested_val.str);
else
LazyBuf_AddSubstring(part, Substring_Init(*pp, p));
FStr_Done(&nested_val);
*pp = p;
}
/*
* In a part of a modifier, parse some text that looks like a subexpression.
* If the text starts with '$(', any '(' and ')' must be balanced.
* If the text starts with '${', any '{' and '}' must be balanced.
* If the text starts with '$', that '$' is copied verbatim, it is not parsed
* as a short-name expression.
*/
static void
ParseModifierPartBalanced(const char **pp, LazyBuf *part)
{
const char *p = *pp;
if (p[1] == '(' || p[1] == '{') {
char startc = p[1];
int endc = startc == '(' ? ')' : '}';
int depth = 1;
for (p += 2; *p != '\0' && depth > 0; p++) {
if (p[-1] != '\\') {
if (*p == startc)
depth++;
if (*p == endc)
depth--;
}
}
LazyBuf_AddSubstring(part, Substring_Init(*pp, p));
*pp = p;
} else {
LazyBuf_Add(part, *p);
*pp = p + 1;
}
}
/*
* Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
* the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
* including the next unescaped delimiter. The delimiter, as well as the
* backslash or the dollar, can be escaped with a backslash.
*
* Return true if parsing succeeded, together with the parsed (and possibly
* expanded) part. In that case, pp points right after the delimiter. The
* delimiter is not included in the part though.
*/
static bool
ParseModifierPart(
/* The parsing position, updated upon return */
const char **pp,
char end1,
char end2,
/* Mode for evaluating nested expressions. */
VarEvalMode emode,
ModChain *ch,
LazyBuf *part,
/*
* For the first part of the ':S' modifier, set anchorEnd if the last
* character of the pattern is a $.
*/
PatternFlags *out_pflags,
/*
* For the second part of the ':S' modifier, allow ampersands to be
* escaped and replace unescaped ampersands with subst->lhs.
*/
struct ModifyWord_SubstArgs *subst
)
{
const char *p = *pp;
LazyBuf_Init(part, p);
while (*p != '\0' && *p != end1 && *p != end2) {
if (IsEscapedModifierPart(p, end2, subst)) {
LazyBuf_Add(part, p[1]);
p += 2;
} else if (*p != '$') { /* Unescaped, simple text */
if (subst != NULL && *p == '&')
LazyBuf_AddSubstring(part, subst->lhs);
else
LazyBuf_Add(part, *p);
p++;
} else if (p[1] == end2) { /* Unescaped '$' at end */
if (out_pflags != NULL)
out_pflags->anchorEnd = true;
else
LazyBuf_Add(part, *p);
p++;
} else if (emode == VARE_PARSE_BALANCED)
ParseModifierPartBalanced(&p, part);
else
ParseModifierPartExpr(&p, part, ch, emode);
}
errno = 0;
n = strtoul(*pp, &end, 10);
if (n == ULONG_MAX && errno == ERANGE)
return false;
if (n > SIZE_MAX)
return false;
*pp = end;
*out_num = (size_t)n;
return true;
}
static bool
TryParseChar(const char **pp, int base, char *out_ch)
{
char *end;
unsigned long n;
if (!ch_isalnum(**pp))
return false;
errno = 0;
n = strtoul(*pp, &end, base);
if (n == ULONG_MAX && errno == ERANGE)
return false;
if (n > UCHAR_MAX)
return false;
*pp = end;
*out_ch = (char)n;
return true;
}
/*
* Modify each word of the expression using the given function and place the
* result back in the expression.
*/
static void
ModifyWords(ModChain *ch,
ModifyWordProc modifyWord, void *modifyWord_args,
bool oneBigWord)
{
Expr *expr = ch->expr;
const char *val = Expr_Str(expr);
SepBuf result;
SubstringWords words;
size_t i;
Substring word;
SepBuf_Init(&result, ch->sep);
for (i = 0; i < words.len; i++) {
modifyWord(words.words[i], &result, modifyWord_args);
if (result.buf.len > 0)
SepBuf_Sep(&result);
}
(*pp)++; /* Skip the first '@' */
if (!ParseModifierPart(pp, '@', '@', VARE_PARSE,
ch, &tvarBuf, NULL, NULL))
return AMR_CLEANUP;
tvar = LazyBuf_DoneGet(&tvarBuf);
args.var = tvar.str;
if (strchr(args.var, '$') != NULL) {
Parse_Error(PARSE_FATAL,
"In the :@ modifier, the variable name \"%s\" "
"must not contain a dollar",
args.var);
goto cleanup_tvar;
}
p = *pp + 1;
LazyBuf_Init(buf, p);
while (!IsDelimiter(*p, ch)) {
/*
* XXX: This code is similar to the one in Var_Parse. See if
* the code can be merged. See also ParseModifier_Match and
* ParseModifierPart.
*/
/* See Buf_AddEscaped in for.c for the counterpart. */
if (*p == '\\') {
char c = p[1];
if ((IsDelimiter(c, ch) && c != '\0') ||
c == '$' || c == '\\') {
if (shouldEval)
LazyBuf_Add(buf, c);
p += 2;
continue;
}
}
if (*p == '$') {
FStr val = Var_Parse(&p, ch->expr->scope,
shouldEval ? ch->expr->emode : VARE_PARSE);
/* TODO: handle errors */
if (shouldEval)
LazyBuf_AddStr(buf, val.str);
FStr_Done(&val);
continue;
}
if (shouldEval)
LazyBuf_Add(buf, *p);
p++;
}
*pp = p;
}
/*
* The :range modifier generates an integer sequence as long as the words.
* The :range=7 modifier generates an integer sequence from 1 to 7.
*/
static ApplyModifierResult
ApplyModifier_Range(const char **pp, ModChain *ch)
{
size_t n;
Buffer buf;
size_t i;
if (mod[5] == '=') {
const char *p = mod + 6;
if (!TryParseSize(&p, &n)) {
Parse_Error(PARSE_FATAL,
"Invalid number \"%s\" for ':range' modifier",
mod + 6);
return AMR_CLEANUP;
}
*pp = p;
} else {
n = 0;
*pp = mod + 5;
}
if (!ModChain_ShouldEval(ch))
return AMR_OK;
if (n == 0) {
SubstringWords words = Expr_Words(ch->expr);
n = words.len;
SubstringWords_Free(words);
}
Buf_Init(&buf);
for (i = 0; i < n; i++) {
if (i != 0) {
/*
* XXX: Use ch->sep instead of ' ', for consistency.
*/
Buf_AddByte(&buf, ' ');
}
Buf_AddInt(&buf, 1 + (int)i);
}
/* Parse a ':M' or ':N' modifier. */
static char *
ParseModifier_Match(const char **pp, const ModChain *ch)
{
const char *mod = *pp;
Expr *expr = ch->expr;
bool copy = false; /* pattern should be, or has been, copied */
bool needSubst = false;
const char *endpat;
char *pattern;
/*
* In the loop below, ignore ':' unless we are at (or back to) the
* original brace level.
* XXX: This will likely not work right if $() and ${} are intermixed.
*/
/*
* XXX: This code is similar to the one in Var_Parse.
* See if the code can be merged.
* See also ApplyModifier_Defined.
*/
int depth = 0;
const char *p;
for (p = mod + 1; *p != '\0' && !(*p == ':' && depth == 0); p++) {
if (*p == '\\' && p[1] != '\0' &&
(IsDelimiter(p[1], ch) || p[1] == ch->startc)) {
if (!needSubst)
copy = true;
p++;
continue;
}
if (*p == '$')
needSubst = true;
if (*p == '(' || *p == '{')
depth++;
if (*p == ')' || *p == '}') {
depth--;
if (depth < 0)
break;
}
}
*pp = p;
endpat = p;
if (copy) {
char *dst;
const char *src;
/* Compress the \:'s out of the pattern. */
pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
dst = pattern;
src = mod + 1;
for (; src < endpat; src++, dst++) {
if (src[0] == '\\' && src + 1 < endpat &&
/* XXX: ch->startc is missing here; see above */
IsDelimiter(src[1], ch))
src++;
*dst = *src;
}
*dst = '\0';
} else {
pattern = bmake_strsedup(mod + 1, endpat);
}
if (needSubst) {
char *old_pattern = pattern;
/*
* XXX: Contrary to ParseModifierPart, a dollar in a ':M' or
* ':N' modifier must be escaped as '$$', not as '\$'.
*/
pattern = Var_Subst(pattern, expr->scope, expr->emode);
/* TODO: handle errors */
free(old_pattern);
}
DEBUG2(VAR, "Pattern for ':%c' is \"%s\"\n", mod[0], pattern);
/*
* Even in parse-only mode, apply the side effects, since the side
* effects are neither observable nor is there a performance penalty.
* Checking for VARE_EVAL for every single piece of code in here
* would make the code in this function too hard to read.
*/
/* ":ts\x40" or ":ts\100" */
{
const char *p = sep + 1;
int base = 8; /* assume octal */
if (sep[1] == 'x') {
base = 16;
p++;
} else if (!ch_isdigit(sep[1]))
return AMR_UNKNOWN; /* ":ts\..." */
if (!TryParseChar(&p, base, &ch->sep)) {
Parse_Error(PARSE_FATAL,
"Invalid character number at \"%s\"", p);
return AMR_CLEANUP;
}
if (!IsDelimiter(*p, ch))
return AMR_UNKNOWN;
val = PARSE_NUM_TYPE(s.start, &ep, 0);
if (ep != s.start) {
switch (*ep) {
case 'K':
case 'k':
val <<= 10;
break;
case 'M':
case 'm':
val <<= 20;
break;
case 'G':
case 'g':
val <<= 30;
break;
}
}
return val;
}
static int
SubNumAsc(const void *sa, const void *sb)
{
NUM_TYPE a, b;
a = num_val(*((const Substring *)sa));
b = num_val(*((const Substring *)sb));
return a > b ? 1 : b > a ? -1 : 0;
}
/*
* The ::= modifiers are special in that they do not read the variable value
* but instead assign to that variable. They always expand to an empty
* string.
*
* Their main purpose is in supporting .for loops that generate shell commands
* since an ordinary variable assignment at that point would terminate the
* dependency group for these targets. For example:
*
* list-targets: .USE
* .for i in ${.TARGET} ${.TARGET:R}.gz
* @${t::=$i}
* @echo 'The target is ${t:T}.'
* .endfor
*
* ::=<str> Assigns <str> as the new value of variable.
* ::?=<str> Assigns <str> as value of variable if
* it was not already set.
* ::+=<str> Appends <str> to variable.
* ::!=<cmd> Assigns output of <cmd> as the new value of
* variable.
*/
static ApplyModifierResult
ApplyModifier_Assign(const char **pp, ModChain *ch)
{
Expr *expr = ch->expr;
GNode *scope;
FStr val;
LazyBuf buf;
if (!ModMatchEq(mod, "_", ch))
return AMR_UNKNOWN;
name = FStr_InitRefer("_");
if (mod[1] == '=') {
/*
* XXX: This ad-hoc call to strcspn deviates from the usual
* behavior defined in ParseModifierPart. This creates an
* unnecessary and undocumented inconsistency in make.
*/
const char *arg = mod + 2;
size_t argLen = strcspn(arg, ":)}");
*pp = arg + argLen;
name = FStr_InitOwn(bmake_strldup(arg, argLen));
} else
*pp = mod + 1;
if (Expr_ShouldEval(expr))
Var_Set(SCOPE_GLOBAL, name.str, Expr_Str(expr));
FStr_Done(&name);
return AMR_OK;
}
/*
* Apply the given function to each word of the variable value,
* for a single-letter modifier such as :H, :T.
*/
static ApplyModifierResult
ApplyModifier_WordFunc(const char **pp, ModChain *ch,
ModifyWordProc modifyWord)
{
if (!IsDelimiter((*pp)[1], ch))
return AMR_UNKNOWN;
(*pp)++;
typedef enum ApplyModifiersIndirectResult {
/* The indirect modifiers have been applied successfully. */
AMIR_CONTINUE,
/* Fall back to the SysV modifier. */
AMIR_SYSV,
/* Error out. */
AMIR_OUT
} ApplyModifiersIndirectResult;
/*
* While expanding an expression, expand and apply indirect modifiers,
* such as in ${VAR:${M_indirect}}.
*
* All indirect modifiers of a group must come from a single
* expression. ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
*
* Multiple groups of indirect modifiers can be chained by separating them
* with colons. ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
*
* If the expression is not followed by ch->endc or ':', fall
* back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
*/
static ApplyModifiersIndirectResult
ApplyModifiersIndirect(ModChain *ch, const char **pp)
{
Expr *expr = ch->expr;
const char *p = *pp;
FStr mods = Var_Parse(&p, expr->scope, expr->emode);
/* TODO: handle errors */
if (posix_state == PS_SET)
res = ApplyModifier_SysV(&p, ch);
else
res = AMR_UNKNOWN;
if (res == AMR_UNKNOWN)
res = ApplyModifier(&p, ch);
if (res == AMR_UNKNOWN && posix_state != PS_SET) {
assert(p == mod);
res = ApplyModifier_SysV(&p, ch);
}
if (res == AMR_UNKNOWN) {
/*
* Guess the end of the current modifier.
* XXX: Skipping the rest of the modifier hides
* errors and leads to wrong results.
* Parsing should rather stop here.
*/
for (p++; !IsDelimiter(*p, ch); p++)
continue;
Parse_Error(PARSE_FATAL, "Unknown modifier \":%.*s\"",
(int)(p - mod), mod);
Expr_SetValueRefer(ch->expr, var_Error);
res = AMR_CLEANUP;
}
if (res != AMR_OK) {
*pp = p;
return res;
}
if (*p == '$') {
/*
* TODO: Only evaluate the expression once, no matter
* whether it's an indirect modifier or the initial
* part of a SysV modifier.
*/
ApplyModifiersIndirectResult amir =
ApplyModifiersIndirect(&ch, &p);
if (amir == AMIR_CONTINUE)
continue;
if (amir == AMIR_OUT)
break;
}
res = ApplySingleModifier(&p, &ch);
if (res == AMR_CLEANUP)
goto cleanup;
}
*pp = p;
assert(Expr_Str(expr) != NULL); /* Use var_Error or varUndefined. */
return;
cleanup:
/*
* TODO: Use p + strlen(p) instead, to stop parsing immediately.
*
* In the unit tests, this generates a few shell commands with
* unbalanced quotes. Instead of producing these incomplete strings,
* commands with evaluation errors should not be run at all.
*
* To make that happen, Var_Subst must report the actual errors
* instead of returning the resulting string unconditionally.
*/
*pp = p;
Expr_SetValueRefer(expr, var_Error);
}
/*
* Only 4 of the 7 built-in local variables are treated specially as they are
* the only ones that will be set when dynamic sources are expanded.
*/
static bool
VarnameIsDynamic(Substring varname)
{
const char *name;
size_t len;
name = varname.start;
len = Substring_Length(varname);
if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
switch (name[0]) {
case '@':
case '%':
case '*':
case '!':
return true;
}
return false;
}
static const char *
UndefinedShortVarValue(char varname, const GNode *scope)
{
if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
/*
* If substituting a local variable in a non-local scope,
* assume it's for dynamic source stuff. We have to handle
* this specially and return the longhand for the variable
* with the dollar sign escaped so it makes it back to the
* caller. Only four of the local variables are treated
* specially as they are the only four that will be set
* when dynamic sources are expanded.
*/
switch (varname) {
case '@':
return "$(.TARGET)";
case '%':
return "$(.MEMBER)";
case '*':
return "$(.PREFIX)";
case '!':
return "$(.ARCHIVE)";
}
}
return NULL;
}
/*
* Parse a variable name, until the end character or a colon, whichever
* comes first.
*/
static void
ParseVarname(const char **pp, char startc, char endc,
GNode *scope, VarEvalMode emode,
LazyBuf *buf)
{
const char *p = *pp;
int depth = 0;
LazyBuf_Init(buf, p);
while (*p != '\0') {
if ((*p == endc || *p == ':') && depth == 0)
break;
if (*p == startc)
depth++;
if (*p == endc)
depth--;
if (!opts.strict)
return false; /* XXX: Missing error message */
if (varname == '$' && save_dollars)
Parse_Error(PARSE_FATAL,
"To escape a dollar, use \\$, not $$, at \"%s\"", start);
else if (varname == '\0')
Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
else if (save_dollars)
Parse_Error(PARSE_FATAL,
"Invalid variable name '%c', at \"%s\"", varname, start);
return false;
}
/*
* Parse a single-character variable name such as in $V or $@.
* Return whether to continue parsing.
*/
static bool
ParseVarnameShort(char varname, const char **pp, GNode *scope,
VarEvalMode emode,
const char **out_false_val,
Var **out_true_var)
{
char name[2];
Var *v;
const char *val;
if (!IsShortVarnameValid(varname, *pp)) {
(*pp)++; /* only skip the '$' */
*out_false_val = var_Error;
return false;
}
name[0] = varname;
name[1] = '\0';
v = VarFind(name, scope, true);
if (v != NULL) {
/* No need to advance *pp, the calling code handles this. */
*out_true_var = v;
return true;
}
*pp += 2;
val = UndefinedShortVarValue(varname, scope);
if (val == NULL)
val = emode == VARE_EVAL_DEFINED
|| emode == VARE_EVAL_DEFINED_LOUD
? var_Error : varUndefined;
if ((opts.strict || emode == VARE_EVAL_DEFINED_LOUD)
&& val == var_Error) {
Parse_Error(PARSE_FATAL,
"Variable \"%s\" is undefined", name);
}
*out_false_val = val;
return false;
}
/* Find variables like @F or <D. */
static Var *
FindLocalLegacyVar(Substring varname, GNode *scope,
const char **out_extraModifiers)
{
Var *v;
/* Only resolve these variables if scope is a "real" target. */
if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
return NULL;
if (Substring_Length(varname) != 2)
return NULL;
if (varname.start[1] != 'F' && varname.start[1] != 'D')
return NULL;
if (strchr("@%?*!<>", varname.start[0]) == NULL)
return NULL;
v = VarFindSubstring(Substring_Init(varname.start, varname.start + 1),
scope, false);
if (v == NULL)
return NULL;
for (p = name.start; p < name.end; p++) {
if (ch_isspace(*p))
break;
}
if (p < name.end) {
Parse_Error(PARSE_WARNING,
ch_isprint(*p)
? "Invalid character \"%c\" in variable name \"%.*s\""
: "Invalid character \"\\x%02x\" in variable name \"%.*s\"",
(int)(*p),
(int)Substring_Length(name), name.start);
}
}
/*
* Parse a long variable name enclosed in braces or parentheses such as $(VAR)
* or ${VAR}, up to the closing brace or parenthesis, or in the case of
* ${VAR:Modifiers}, up to the ':' that starts the modifiers.
* Return whether to continue parsing.
*/
static bool
ParseVarnameLong(
const char **pp,
char startc,
GNode *scope,
VarEvalMode emode,
VarEvalMode nested_emode,
int parseErrorsBefore,
/*
* At this point, p points just after the variable name, either at
* ':' or at endc.
*/
if (v == NULL && Substring_Equals(name, ".SUFFIXES")) {
char *suffixes = Suff_NamesStr();
v = VarNew(FStr_InitRefer(".SUFFIXES"), suffixes,
true, false, true);
free(suffixes);
} else if (v == NULL)
v = FindLocalLegacyVar(name, scope, out_true_extraModifiers);
if (v == NULL) {
/*
* Defer expansion of dynamic variables if they appear in
* non-local scope since they are not defined there.
*/
dynamic = VarnameIsDynamic(name) &&
(scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
/*
* The expression is based on an undefined variable.
* Nevertheless it needs a Var, for modifiers that access the
* variable name, such as :L or :?.
*
* Most modifiers leave this expression in the "undefined"
* state (DEF_UNDEF), only a few modifiers like :D, :U, :L,
* :P turn this undefined expression into a defined
* expression (DEF_DEFINED).
*
* In the end, after applying all modifiers, if the expression
* is still undefined, Var_Parse will return an empty string
* instead of the actually computed value.
*/
v = VarNew(LazyBuf_DoneGet(&varname), "",
true, false, false);
*out_true_exprDefined = DEF_UNDEF;
} else
LazyBuf_Done(&varname);
/*
* Expressions of the form ${:U...} with a trivial value are often generated
* by .for loops and are boring, so evaluate them without debug logging.
*/
static bool
Var_Parse_U(const char **pp, VarEvalMode emode, FStr *out_value)
{
const char *p;
/*
* Given the start of an expression (such as $v, $(VAR), ${VAR:Mpattern}),
* extract the variable name and the modifiers, if any. While parsing, apply
* the modifiers to the value of the expression.
*
* Input:
* *pp The string to parse.
* When called from CondParser_FuncCallEmpty, it can
* also point to the "y" of "empty(VARNAME:Modifiers)".
* scope The scope for finding variables.
* emode Controls the exact details of parsing and evaluation.
*
* Output:
* *pp The position where to continue parsing.
* TODO: After a parse error, the value of *pp is
* unspecified. It may not have been updated at all,
* point to some random character in the string, to the
* location of the parse error, or at the end of the
* string.
* return The value of the expression, never NULL.
* return var_Error if there was a parse error.
* return var_Error if the base variable of the expression was
* undefined, emode is VARE_EVAL_DEFINED, and none of
* the modifiers turned the undefined expression into a
* defined expression.
* XXX: It is not guaranteed that an error message has
* been printed.
* return varUndefined if the base variable of the expression
* was undefined, emode was not VARE_EVAL_DEFINED,
* and none of the modifiers turned the undefined
* expression into a defined expression.
*/
FStr
Var_Parse(const char **pp, GNode *scope, VarEvalMode emode)
{
const char *start, *p;
bool haveModifier; /* true for ${VAR:...}, false for ${VAR} */
char startc; /* the actual '{' or '(' or '\0' */
char endc; /* the expected '}' or ')' or '\0' */
/*
* true if the expression is based on one of the 7 predefined
* variables that are local to a target, and the expression is
* expanded in a non-local scope. The result is the text of the
* expression, unaltered. This is needed to support dynamic sources.
*/
bool dynamic;
const char *extramodifiers;
Var *v;
Expr expr = Expr_Init(NULL, FStr_InitRefer(NULL),
emode == VARE_EVAL_DEFINED || emode == VARE_EVAL_DEFINED_LOUD
? VARE_EVAL : emode,
scope, DEF_REGULAR);
FStr val;
int parseErrorsBefore = parseErrors;
expr.name = v->name.str;
if (v->inUse && VarEvalMode_ShouldEval(emode)) {
Parse_Error(PARSE_FATAL, "Variable %s is recursive.",
v->name.str);
FStr_Done(&val);
if (*p != '\0')
p++;
*pp = p;
return FStr_InitRefer(var_Error);
}
/*
* FIXME: This assignment creates an alias to the current value of the
* variable. This means that as long as the value of the expression
* stays the same, the value of the variable must not change, and the
* variable must not be deleted. Using the ':@' modifier, it is
* possible (since var.c 1.212 from 2017-02-01) to delete the variable
* while its value is still being used:
*
* VAR= value
* _:= ${VAR:${:U:@VAR@@}:S,^,prefix,}
*
* The same effect might be achievable using the '::=' or the ':_'
* modifiers.
*
* At the bottom of this function, the resulting value is compared to
* the then-current value of the variable. This might also invoke
* undefined behavior.
*/
expr.value = FStr_InitRefer(v->val.data);
if (!VarEvalMode_ShouldEval(emode))
EvalStack_Push(VSK_EXPR_PARSE, start, NULL);
else if (expr.name[0] != '\0')
EvalStack_Push(VSK_VARNAME, expr.name, &expr.value);
else
EvalStack_Push(VSK_EXPR, start, &expr.value);
/*
* Before applying any modifiers, expand any nested expressions from
* the variable value.
*/
if (VarEvalMode_ShouldEval(emode) &&
strchr(Expr_Str(&expr), '$') != NULL) {
char *expanded;
v->inUse = true;
expanded = Var_Subst(Expr_Str(&expr), scope, expr.emode);
v->inUse = false;
/* TODO: handle errors */
Expr_SetValueOwn(&expr, expanded);
}
static void
VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
{
/* A dollar sign may be escaped with another dollar sign. */
if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
Buf_AddByte(res, '$');
Buf_AddByte(res, '$');
*pp += 2;
}
if (val.str == var_Error || val.str == varUndefined) {
if (!VarEvalMode_ShouldKeepUndef(emode)
|| val.str == var_Error) {
p = nested_p;
} else {
/*
* Copy the initial '$' of the undefined expression,
* thereby deferring expansion of the expression, but
* expand nested expressions if already possible. See
* unit-tests/varparse-undef-partial.mk.
*/
Buf_AddByte(buf, *p);
p++;
}
} else {
p = nested_p;
Buf_AddStr(buf, val.str);
}
FStr_Done(&val);
*pp = p;
}
/*
* Skip as many characters as possible -- either to the end of the string,
* or to the next dollar sign, which may start an expression.
*/
static void
VarSubstPlain(const char **pp, Buffer *res)
{
const char *p = *pp;
const char *start = p;
/*
* Expand all expressions like $V, ${VAR}, $(VAR:Modifiers) in the
* given string.
*
* Input:
* str The string in which the expressions are expanded.
* scope The scope in which to start searching for variables.
* The other scopes are searched as well.
* emode The mode for parsing or evaluating subexpressions.
*/
char *
Var_Subst(const char *str, GNode *scope, VarEvalMode emode)
{
const char *p = str;
Buffer res;
Buf_Init(&res);
while (*p != '\0') {
if (p[0] == '$' && p[1] == '$')
VarSubstDollarDollar(&p, &res, emode);
else if (p[0] == '$')
VarSubstExpr(&p, &res, scope, emode);
else
VarSubstPlain(&p, &res);
}