Mon Jul 27 17:41:09 2020 UTC ()
make(1): document API of Var_Value


(rillig)
diff -r1.336 -r1.337 src/usr.bin/make/var.c

cvs diff -r1.336 -r1.337 src/usr.bin/make/var.c (switch to unified diff)

--- src/usr.bin/make/var.c 2020/07/26 23:03:54 1.336
+++ src/usr.bin/make/var.c 2020/07/27 17:41:09 1.337
@@ -1,2040 +1,2040 @@ @@ -1,2040 +1,2040 @@
1/* $NetBSD: var.c,v 1.336 2020/07/26 23:03:54 rillig Exp $ */ 1/* $NetBSD: var.c,v 1.337 2020/07/27 17:41:09 rillig Exp $ */
2 2
3/* 3/*
4 * Copyright (c) 1988, 1989, 1990, 1993 4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved. 5 * The Regents of the University of California. All rights reserved.
6 * 6 *
7 * This code is derived from software contributed to Berkeley by 7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor. 8 * Adam de Boor.
9 * 9 *
10 * Redistribution and use in source and binary forms, with or without 10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions 11 * modification, are permitted provided that the following conditions
12 * are met: 12 * are met:
13 * 1. Redistributions of source code must retain the above copyright 13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer. 14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright 15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the 16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution. 17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors 18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software 19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission. 20 * without specific prior written permission.
21 * 21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE. 32 * SUCH DAMAGE.
33 */ 33 */
34 34
35/* 35/*
36 * Copyright (c) 1989 by Berkeley Softworks 36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved. 37 * All rights reserved.
38 * 38 *
39 * This code is derived from software contributed to Berkeley by 39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor. 40 * Adam de Boor.
41 * 41 *
42 * Redistribution and use in source and binary forms, with or without 42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions 43 * modification, are permitted provided that the following conditions
44 * are met: 44 * are met:
45 * 1. Redistributions of source code must retain the above copyright 45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer. 46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright 47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the 48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution. 49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software 50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement: 51 * must display the following acknowledgement:
52 * This product includes software developed by the University of 52 * This product includes software developed by the University of
53 * California, Berkeley and its contributors. 53 * California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors 54 * 4. Neither the name of the University nor the names of its contributors
55 * may be used to endorse or promote products derived from this software 55 * may be used to endorse or promote products derived from this software
56 * without specific prior written permission. 56 * without specific prior written permission.
57 * 57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE. 68 * SUCH DAMAGE.
69 */ 69 */
70 70
71#ifndef MAKE_NATIVE 71#ifndef MAKE_NATIVE
72static char rcsid[] = "$NetBSD: var.c,v 1.336 2020/07/26 23:03:54 rillig Exp $"; 72static char rcsid[] = "$NetBSD: var.c,v 1.337 2020/07/27 17:41:09 rillig Exp $";
73#else 73#else
74#include <sys/cdefs.h> 74#include <sys/cdefs.h>
75#ifndef lint 75#ifndef lint
76#if 0 76#if 0
77static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94"; 77static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94";
78#else 78#else
79__RCSID("$NetBSD: var.c,v 1.336 2020/07/26 23:03:54 rillig Exp $"); 79__RCSID("$NetBSD: var.c,v 1.337 2020/07/27 17:41:09 rillig Exp $");
80#endif 80#endif
81#endif /* not lint */ 81#endif /* not lint */
82#endif 82#endif
83 83
84/*- 84/*-
85 * var.c -- 85 * var.c --
86 * Variable-handling functions 86 * Variable-handling functions
87 * 87 *
88 * Interface: 88 * Interface:
89 * Var_Set Set the value of a variable in the given 89 * Var_Set Set the value of a variable in the given
90 * context. The variable is created if it doesn't 90 * context. The variable is created if it doesn't
91 * yet exist. 91 * yet exist.
92 * 92 *
93 * Var_Append Append more characters to an existing variable 93 * Var_Append Append more characters to an existing variable
94 * in the given context. The variable needn't 94 * in the given context. The variable needn't
95 * exist already -- it will be created if it doesn't. 95 * exist already -- it will be created if it doesn't.
96 * A space is placed between the old value and the 96 * A space is placed between the old value and the
97 * new one. 97 * new one.
98 * 98 *
99 * Var_Exists See if a variable exists. 99 * Var_Exists See if a variable exists.
100 * 100 *
101 * Var_Value Return the value of a variable in a context or 101 * Var_Value Return the unexpanded value of a variable in a
102 * NULL if the variable is undefined. 102 * context or NULL if the variable is undefined.
103 * 103 *
104 * Var_Subst Substitute either a single variable or all 104 * Var_Subst Substitute either a single variable or all
105 * variables in a string, using the given context. 105 * variables in a string, using the given context.
106 * 106 *
107 * Var_Parse Parse a variable expansion from a string and 107 * Var_Parse Parse a variable expansion from a string and
108 * return the result and the number of characters 108 * return the result and the number of characters
109 * consumed. 109 * consumed.
110 * 110 *
111 * Var_Delete Delete a variable in a context. 111 * Var_Delete Delete a variable in a context.
112 * 112 *
113 * Var_Init Initialize this module. 113 * Var_Init Initialize this module.
114 * 114 *
115 * Debugging: 115 * Debugging:
116 * Var_Dump Print out all variables defined in the given 116 * Var_Dump Print out all variables defined in the given
117 * context. 117 * context.
118 * 118 *
119 * XXX: There's a lot of duplication in these functions. 119 * XXX: There's a lot of duplication in these functions.
120 */ 120 */
121 121
122#include <sys/stat.h> 122#include <sys/stat.h>
123#ifndef NO_REGEX 123#ifndef NO_REGEX
124#include <sys/types.h> 124#include <sys/types.h>
125#include <regex.h> 125#include <regex.h>
126#endif 126#endif
127#include <ctype.h> 127#include <ctype.h>
128#include <inttypes.h> 128#include <inttypes.h>
129#include <limits.h> 129#include <limits.h>
130#include <stdlib.h> 130#include <stdlib.h>
131#include <time.h> 131#include <time.h>
132 132
133#include "make.h" 133#include "make.h"
134#include "buf.h" 134#include "buf.h"
135#include "dir.h" 135#include "dir.h"
136#include "job.h" 136#include "job.h"
137#include "metachar.h" 137#include "metachar.h"
138 138
139#define VAR_DEBUG(fmt, ...) \ 139#define VAR_DEBUG(fmt, ...) \
140 if (!DEBUG(VAR)) \ 140 if (!DEBUG(VAR)) \
141 (void) 0; \ 141 (void) 0; \
142 else \ 142 else \
143 fprintf(debug_file, fmt, __VA_ARGS__) 143 fprintf(debug_file, fmt, __VA_ARGS__)
144 144
145/* 145/*
146 * This lets us tell if we have replaced the original environ 146 * This lets us tell if we have replaced the original environ
147 * (which we cannot free). 147 * (which we cannot free).
148 */ 148 */
149char **savedEnv = NULL; 149char **savedEnv = NULL;
150 150
151/* 151/*
152 * This is a harmless return value for Var_Parse that can be used by Var_Subst 152 * This is a harmless return value for Var_Parse that can be used by Var_Subst
153 * to determine if there was an error in parsing -- easier than returning 153 * to determine if there was an error in parsing -- easier than returning
154 * a flag, as things outside this module don't give a hoot. 154 * a flag, as things outside this module don't give a hoot.
155 */ 155 */
156char var_Error[] = ""; 156char var_Error[] = "";
157 157
158/* 158/*
159 * Similar to var_Error, but returned when the 'VARE_UNDEFERR' flag for 159 * Similar to var_Error, but returned when the 'VARE_UNDEFERR' flag for
160 * Var_Parse is not set. Why not just use a constant? Well, GCC likes 160 * Var_Parse is not set. Why not just use a constant? Well, GCC likes
161 * to condense identical string instances... 161 * to condense identical string instances...
162 */ 162 */
163static char varNoError[] = ""; 163static char varNoError[] = "";
164 164
165/* 165/*
166 * Traditionally we consume $$ during := like any other expansion. 166 * Traditionally we consume $$ during := like any other expansion.
167 * Other make's do not. 167 * Other make's do not.
168 * This knob allows controlling the behavior. 168 * This knob allows controlling the behavior.
169 * FALSE to consume $$ during := assignment. 169 * FALSE to consume $$ during := assignment.
170 * TRUE to preserve $$ during := assignment. 170 * TRUE to preserve $$ during := assignment.
171 */ 171 */
172#define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS" 172#define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
173static Boolean save_dollars = TRUE; 173static Boolean save_dollars = TRUE;
174 174
175/* 175/*
176 * Internally, variables are contained in four different contexts. 176 * Internally, variables are contained in four different contexts.
177 * 1) the environment. They cannot be changed. If an environment 177 * 1) the environment. They cannot be changed. If an environment
178 * variable is appended to, the result is placed in the global 178 * variable is appended to, the result is placed in the global
179 * context. 179 * context.
180 * 2) the global context. Variables set in the Makefile are located in 180 * 2) the global context. Variables set in the Makefile are located in
181 * the global context. 181 * the global context.
182 * 3) the command-line context. All variables set on the command line 182 * 3) the command-line context. All variables set on the command line
183 * are placed in this context. They are UNALTERABLE once placed here. 183 * are placed in this context. They are UNALTERABLE once placed here.
184 * 4) the local context. Each target has associated with it a context 184 * 4) the local context. Each target has associated with it a context
185 * list. On this list are located the structures describing such 185 * list. On this list are located the structures describing such
186 * local variables as $(@) and $(*) 186 * local variables as $(@) and $(*)
187 * The four contexts are searched in the reverse order from which they are 187 * The four contexts are searched in the reverse order from which they are
188 * listed (but see checkEnvFirst). 188 * listed (but see checkEnvFirst).
189 */ 189 */
190GNode *VAR_INTERNAL; /* variables from make itself */ 190GNode *VAR_INTERNAL; /* variables from make itself */
191GNode *VAR_GLOBAL; /* variables from the makefile */ 191GNode *VAR_GLOBAL; /* variables from the makefile */
192GNode *VAR_CMD; /* variables defined on the command-line */ 192GNode *VAR_CMD; /* variables defined on the command-line */
193 193
194typedef enum { 194typedef enum {
195 FIND_CMD = 0x01, /* look in VAR_CMD when searching */ 195 FIND_CMD = 0x01, /* look in VAR_CMD when searching */
196 FIND_GLOBAL = 0x02, /* look in VAR_GLOBAL as well */ 196 FIND_GLOBAL = 0x02, /* look in VAR_GLOBAL as well */
197 FIND_ENV = 0x04 /* look in the environment also */ 197 FIND_ENV = 0x04 /* look in the environment also */
198} VarFindFlags; 198} VarFindFlags;
199 199
200typedef enum { 200typedef enum {
201 VAR_IN_USE = 0x01, /* Variable's value is currently being used 201 VAR_IN_USE = 0x01, /* Variable's value is currently being used
202 * by Var_Parse or Var_Subst. 202 * by Var_Parse or Var_Subst.
203 * Used to avoid endless recursion */ 203 * Used to avoid endless recursion */
204 VAR_FROM_ENV = 0x02, /* Variable comes from the environment */ 204 VAR_FROM_ENV = 0x02, /* Variable comes from the environment */
205 VAR_JUNK = 0x04, /* Variable is a junk variable that 205 VAR_JUNK = 0x04, /* Variable is a junk variable that
206 * should be destroyed when done with 206 * should be destroyed when done with
207 * it. Used by Var_Parse for undefined, 207 * it. Used by Var_Parse for undefined,
208 * modified variables */ 208 * modified variables */
209 VAR_KEEP = 0x08, /* Variable is VAR_JUNK, but we found 209 VAR_KEEP = 0x08, /* Variable is VAR_JUNK, but we found
210 * a use for it in some modifier and 210 * a use for it in some modifier and
211 * the value is therefore valid */ 211 * the value is therefore valid */
212 VAR_EXPORTED = 0x10, /* Variable is exported */ 212 VAR_EXPORTED = 0x10, /* Variable is exported */
213 VAR_REEXPORT = 0x20, /* Indicate if var needs re-export. 213 VAR_REEXPORT = 0x20, /* Indicate if var needs re-export.
214 * This would be true if it contains $'s */ 214 * This would be true if it contains $'s */
215 VAR_FROM_CMD = 0x40 /* Variable came from command line */ 215 VAR_FROM_CMD = 0x40 /* Variable came from command line */
216} Var_Flags; 216} Var_Flags;
217 217
218typedef struct Var { 218typedef struct Var {
219 char *name; /* the variable's name */ 219 char *name; /* the variable's name */
220 Buffer val; /* its value */ 220 Buffer val; /* its value */
221 Var_Flags flags; /* miscellaneous status flags */ 221 Var_Flags flags; /* miscellaneous status flags */
222} Var; 222} Var;
223 223
224/* 224/*
225 * Exporting vars is expensive so skip it if we can 225 * Exporting vars is expensive so skip it if we can
226 */ 226 */
227typedef enum { 227typedef enum {
228 VAR_EXPORTED_NONE, 228 VAR_EXPORTED_NONE,
229 VAR_EXPORTED_YES, 229 VAR_EXPORTED_YES,
230 VAR_EXPORTED_ALL 230 VAR_EXPORTED_ALL
231} VarExportedMode; 231} VarExportedMode;
232static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE; 232static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
233 233
234typedef enum { 234typedef enum {
235 /* 235 /*
236 * We pass this to Var_Export when doing the initial export 236 * We pass this to Var_Export when doing the initial export
237 * or after updating an exported var. 237 * or after updating an exported var.
238 */ 238 */
239 VAR_EXPORT_PARENT = 0x01, 239 VAR_EXPORT_PARENT = 0x01,
240 /* 240 /*
241 * We pass this to Var_Export1 to tell it to leave the value alone. 241 * We pass this to Var_Export1 to tell it to leave the value alone.
242 */ 242 */
243 VAR_EXPORT_LITERAL = 0x02 243 VAR_EXPORT_LITERAL = 0x02
244} VarExportFlags; 244} VarExportFlags;
245 245
246/* Flags for pattern matching in the :S and :C modifiers */ 246/* Flags for pattern matching in the :S and :C modifiers */
247typedef enum { 247typedef enum {
248 VARP_SUB_GLOBAL = 0x01, /* Apply substitution globally */ 248 VARP_SUB_GLOBAL = 0x01, /* Apply substitution globally */
249 VARP_SUB_ONE = 0x02, /* Apply substitution to one word */ 249 VARP_SUB_ONE = 0x02, /* Apply substitution to one word */
250 VARP_SUB_MATCHED = 0x04, /* There was a match */ 250 VARP_SUB_MATCHED = 0x04, /* There was a match */
251 VARP_ANCHOR_START = 0x08, /* Match at start of word */ 251 VARP_ANCHOR_START = 0x08, /* Match at start of word */
252 VARP_ANCHOR_END = 0x10 /* Match at end of word */ 252 VARP_ANCHOR_END = 0x10 /* Match at end of word */
253} VarPatternFlags; 253} VarPatternFlags;
254 254
255typedef enum { 255typedef enum {
256 VAR_NO_EXPORT = 0x01 /* do not export */ 256 VAR_NO_EXPORT = 0x01 /* do not export */
257} VarSet_Flags; 257} VarSet_Flags;
258 258
259#define BROPEN '{' 259#define BROPEN '{'
260#define BRCLOSE '}' 260#define BRCLOSE '}'
261#define PROPEN '(' 261#define PROPEN '('
262#define PRCLOSE ')' 262#define PRCLOSE ')'
263 263
264/*- 264/*-
265 *----------------------------------------------------------------------- 265 *-----------------------------------------------------------------------
266 * VarFind -- 266 * VarFind --
267 * Find the given variable in the given context and any other contexts 267 * Find the given variable in the given context and any other contexts
268 * indicated. 268 * indicated.
269 * 269 *
270 * Input: 270 * Input:
271 * name name to find 271 * name name to find
272 * ctxt context in which to find it 272 * ctxt context in which to find it
273 * flags FIND_GLOBAL look in VAR_GLOBAL as well 273 * flags FIND_GLOBAL look in VAR_GLOBAL as well
274 * FIND_CMD look in VAR_CMD as well 274 * FIND_CMD look in VAR_CMD as well
275 * FIND_ENV look in the environment as well 275 * FIND_ENV look in the environment as well
276 * 276 *
277 * Results: 277 * Results:
278 * A pointer to the structure describing the desired variable or 278 * A pointer to the structure describing the desired variable or
279 * NULL if the variable does not exist. 279 * NULL if the variable does not exist.
280 * 280 *
281 * Side Effects: 281 * Side Effects:
282 * None 282 * None
283 *----------------------------------------------------------------------- 283 *-----------------------------------------------------------------------
284 */ 284 */
285static Var * 285static Var *
286VarFind(const char *name, GNode *ctxt, VarFindFlags flags) 286VarFind(const char *name, GNode *ctxt, VarFindFlags flags)
287{ 287{
288 /* 288 /*
289 * If the variable name begins with a '.', it could very well be one of 289 * If the variable name begins with a '.', it could very well be one of
290 * the local ones. We check the name against all the local variables 290 * the local ones. We check the name against all the local variables
291 * and substitute the short version in for 'name' if it matches one of 291 * and substitute the short version in for 'name' if it matches one of
292 * them. 292 * them.
293 */ 293 */
294 if (*name == '.' && isupper((unsigned char) name[1])) { 294 if (*name == '.' && isupper((unsigned char) name[1])) {
295 switch (name[1]) { 295 switch (name[1]) {
296 case 'A': 296 case 'A':
297 if (strcmp(name, ".ALLSRC") == 0) 297 if (strcmp(name, ".ALLSRC") == 0)
298 name = ALLSRC; 298 name = ALLSRC;
299 if (strcmp(name, ".ARCHIVE") == 0) 299 if (strcmp(name, ".ARCHIVE") == 0)
300 name = ARCHIVE; 300 name = ARCHIVE;
301 break; 301 break;
302 case 'I': 302 case 'I':
303 if (strcmp(name, ".IMPSRC") == 0) 303 if (strcmp(name, ".IMPSRC") == 0)
304 name = IMPSRC; 304 name = IMPSRC;
305 break; 305 break;
306 case 'M': 306 case 'M':
307 if (strcmp(name, ".MEMBER") == 0) 307 if (strcmp(name, ".MEMBER") == 0)
308 name = MEMBER; 308 name = MEMBER;
309 break; 309 break;
310 case 'O': 310 case 'O':
311 if (strcmp(name, ".OODATE") == 0) 311 if (strcmp(name, ".OODATE") == 0)
312 name = OODATE; 312 name = OODATE;
313 break; 313 break;
314 case 'P': 314 case 'P':
315 if (strcmp(name, ".PREFIX") == 0) 315 if (strcmp(name, ".PREFIX") == 0)
316 name = PREFIX; 316 name = PREFIX;
317 break; 317 break;
318 case 'T': 318 case 'T':
319 if (strcmp(name, ".TARGET") == 0) 319 if (strcmp(name, ".TARGET") == 0)
320 name = TARGET; 320 name = TARGET;
321 break; 321 break;
322 } 322 }
323 } 323 }
324 324
325#ifdef notyet 325#ifdef notyet
326 /* for compatibility with gmake */ 326 /* for compatibility with gmake */
327 if (name[0] == '^' && name[1] == '\0') 327 if (name[0] == '^' && name[1] == '\0')
328 name = ALLSRC; 328 name = ALLSRC;
329#endif 329#endif
330 330
331 /* 331 /*
332 * First look for the variable in the given context. If it's not there, 332 * First look for the variable in the given context. If it's not there,
333 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order, 333 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
334 * depending on the FIND_* flags in 'flags' 334 * depending on the FIND_* flags in 'flags'
335 */ 335 */
336 Hash_Entry *var = Hash_FindEntry(&ctxt->context, name); 336 Hash_Entry *var = Hash_FindEntry(&ctxt->context, name);
337 337
338 if (var == NULL && (flags & FIND_CMD) && ctxt != VAR_CMD) { 338 if (var == NULL && (flags & FIND_CMD) && ctxt != VAR_CMD) {
339 var = Hash_FindEntry(&VAR_CMD->context, name); 339 var = Hash_FindEntry(&VAR_CMD->context, name);
340 } 340 }
341 if (!checkEnvFirst && var == NULL && (flags & FIND_GLOBAL) && 341 if (!checkEnvFirst && var == NULL && (flags & FIND_GLOBAL) &&
342 ctxt != VAR_GLOBAL) 342 ctxt != VAR_GLOBAL)
343 { 343 {
344 var = Hash_FindEntry(&VAR_GLOBAL->context, name); 344 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
345 if (var == NULL && ctxt != VAR_INTERNAL) { 345 if (var == NULL && ctxt != VAR_INTERNAL) {
346 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */ 346 /* VAR_INTERNAL is subordinate to VAR_GLOBAL */
347 var = Hash_FindEntry(&VAR_INTERNAL->context, name); 347 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
348 } 348 }
349 } 349 }
350 if (var == NULL && (flags & FIND_ENV)) { 350 if (var == NULL && (flags & FIND_ENV)) {
351 char *env; 351 char *env;
352 352
353 if ((env = getenv(name)) != NULL) { 353 if ((env = getenv(name)) != NULL) {
354 Var *v = bmake_malloc(sizeof(Var)); 354 Var *v = bmake_malloc(sizeof(Var));
355 v->name = bmake_strdup(name); 355 v->name = bmake_strdup(name);
356 356
357 int len = (int)strlen(env); 357 int len = (int)strlen(env);
358 Buf_Init(&v->val, len + 1); 358 Buf_Init(&v->val, len + 1);
359 Buf_AddBytes(&v->val, len, env); 359 Buf_AddBytes(&v->val, len, env);
360 360
361 v->flags = VAR_FROM_ENV; 361 v->flags = VAR_FROM_ENV;
362 return v; 362 return v;
363 } else if (checkEnvFirst && (flags & FIND_GLOBAL) && 363 } else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
364 ctxt != VAR_GLOBAL) 364 ctxt != VAR_GLOBAL)
365 { 365 {
366 var = Hash_FindEntry(&VAR_GLOBAL->context, name); 366 var = Hash_FindEntry(&VAR_GLOBAL->context, name);
367 if (var == NULL && ctxt != VAR_INTERNAL) { 367 if (var == NULL && ctxt != VAR_INTERNAL) {
368 var = Hash_FindEntry(&VAR_INTERNAL->context, name); 368 var = Hash_FindEntry(&VAR_INTERNAL->context, name);
369 } 369 }
370 if (var == NULL) { 370 if (var == NULL) {
371 return NULL; 371 return NULL;
372 } else { 372 } else {
373 return (Var *)Hash_GetValue(var); 373 return (Var *)Hash_GetValue(var);
374 } 374 }
375 } else { 375 } else {
376 return NULL; 376 return NULL;
377 } 377 }
378 } else if (var == NULL) { 378 } else if (var == NULL) {
379 return NULL; 379 return NULL;
380 } else { 380 } else {
381 return (Var *)Hash_GetValue(var); 381 return (Var *)Hash_GetValue(var);
382 } 382 }
383} 383}
384 384
385/*- 385/*-
386 *----------------------------------------------------------------------- 386 *-----------------------------------------------------------------------
387 * VarFreeEnv -- 387 * VarFreeEnv --
388 * If the variable is an environment variable, free it 388 * If the variable is an environment variable, free it
389 * 389 *
390 * Input: 390 * Input:
391 * v the variable 391 * v the variable
392 * destroy true if the value buffer should be destroyed. 392 * destroy true if the value buffer should be destroyed.
393 * 393 *
394 * Results: 394 * Results:
395 * 1 if it is an environment variable 0 ow. 395 * 1 if it is an environment variable 0 ow.
396 * 396 *
397 * Side Effects: 397 * Side Effects:
398 * The variable is free'ed if it is an environent variable. 398 * The variable is free'ed if it is an environent variable.
399 *----------------------------------------------------------------------- 399 *-----------------------------------------------------------------------
400 */ 400 */
401static Boolean 401static Boolean
402VarFreeEnv(Var *v, Boolean destroy) 402VarFreeEnv(Var *v, Boolean destroy)
403{ 403{
404 if (!(v->flags & VAR_FROM_ENV)) 404 if (!(v->flags & VAR_FROM_ENV))
405 return FALSE; 405 return FALSE;
406 free(v->name); 406 free(v->name);
407 Buf_Destroy(&v->val, destroy); 407 Buf_Destroy(&v->val, destroy);
408 free(v); 408 free(v);
409 return TRUE; 409 return TRUE;
410} 410}
411 411
412/*- 412/*-
413 *----------------------------------------------------------------------- 413 *-----------------------------------------------------------------------
414 * VarAdd -- 414 * VarAdd --
415 * Add a new variable of name name and value val to the given context 415 * Add a new variable of name name and value val to the given context
416 * 416 *
417 * Input: 417 * Input:
418 * name name of variable to add 418 * name name of variable to add
419 * val value to set it to 419 * val value to set it to
420 * ctxt context in which to set it 420 * ctxt context in which to set it
421 * 421 *
422 * Side Effects: 422 * Side Effects:
423 * The new variable is placed at the front of the given context 423 * The new variable is placed at the front of the given context
424 * The name and val arguments are duplicated so they may 424 * The name and val arguments are duplicated so they may
425 * safely be freed. 425 * safely be freed.
426 *----------------------------------------------------------------------- 426 *-----------------------------------------------------------------------
427 */ 427 */
428static void 428static void
429VarAdd(const char *name, const char *val, GNode *ctxt) 429VarAdd(const char *name, const char *val, GNode *ctxt)
430{ 430{
431 Var *v = bmake_malloc(sizeof(Var)); 431 Var *v = bmake_malloc(sizeof(Var));
432 432
433 int len = val != NULL ? (int)strlen(val) : 0; 433 int len = val != NULL ? (int)strlen(val) : 0;
434 Buf_Init(&v->val, len + 1); 434 Buf_Init(&v->val, len + 1);
435 Buf_AddBytes(&v->val, len, val); 435 Buf_AddBytes(&v->val, len, val);
436 436
437 v->flags = 0; 437 v->flags = 0;
438 438
439 Hash_Entry *h = Hash_CreateEntry(&ctxt->context, name, NULL); 439 Hash_Entry *h = Hash_CreateEntry(&ctxt->context, name, NULL);
440 Hash_SetValue(h, v); 440 Hash_SetValue(h, v);
441 v->name = h->name; 441 v->name = h->name;
442 if (DEBUG(VAR) && !(ctxt->flags & INTERNAL)) { 442 if (DEBUG(VAR) && !(ctxt->flags & INTERNAL)) {
443 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); 443 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
444 } 444 }
445} 445}
446 446
447/*- 447/*-
448 *----------------------------------------------------------------------- 448 *-----------------------------------------------------------------------
449 * Var_Delete -- 449 * Var_Delete --
450 * Remove a variable from a context. 450 * Remove a variable from a context.
451 * 451 *
452 * Side Effects: 452 * Side Effects:
453 * The Var structure is removed and freed. 453 * The Var structure is removed and freed.
454 * 454 *
455 *----------------------------------------------------------------------- 455 *-----------------------------------------------------------------------
456 */ 456 */
457void 457void
458Var_Delete(const char *name, GNode *ctxt) 458Var_Delete(const char *name, GNode *ctxt)
459{ 459{
460 Hash_Entry *ln; 460 Hash_Entry *ln;
461 char *cp; 461 char *cp;
462 462
463 if (strchr(name, '$') != NULL) { 463 if (strchr(name, '$') != NULL) {
464 cp = Var_Subst(NULL, name, VAR_GLOBAL, VARE_WANTRES); 464 cp = Var_Subst(NULL, name, VAR_GLOBAL, VARE_WANTRES);
465 } else { 465 } else {
466 cp = UNCONST(name); 466 cp = UNCONST(name);
467 } 467 }
468 ln = Hash_FindEntry(&ctxt->context, cp); 468 ln = Hash_FindEntry(&ctxt->context, cp);
469 if (DEBUG(VAR)) { 469 if (DEBUG(VAR)) {
470 fprintf(debug_file, "%s:delete %s%s\n", 470 fprintf(debug_file, "%s:delete %s%s\n",
471 ctxt->name, cp, ln ? "" : " (not found)"); 471 ctxt->name, cp, ln ? "" : " (not found)");
472 } 472 }
473 if (cp != name) 473 if (cp != name)
474 free(cp); 474 free(cp);
475 if (ln != NULL) { 475 if (ln != NULL) {
476 Var *v = (Var *)Hash_GetValue(ln); 476 Var *v = (Var *)Hash_GetValue(ln);
477 if (v->flags & VAR_EXPORTED) 477 if (v->flags & VAR_EXPORTED)
478 unsetenv(v->name); 478 unsetenv(v->name);
479 if (strcmp(MAKE_EXPORTED, v->name) == 0) 479 if (strcmp(MAKE_EXPORTED, v->name) == 0)
480 var_exportedVars = VAR_EXPORTED_NONE; 480 var_exportedVars = VAR_EXPORTED_NONE;
481 if (v->name != ln->name) 481 if (v->name != ln->name)
482 free(v->name); 482 free(v->name);
483 Hash_DeleteEntry(&ctxt->context, ln); 483 Hash_DeleteEntry(&ctxt->context, ln);
484 Buf_Destroy(&v->val, TRUE); 484 Buf_Destroy(&v->val, TRUE);
485 free(v); 485 free(v);
486 } 486 }
487} 487}
488 488
489 489
490/* 490/*
491 * Export a var. 491 * Export a var.
492 * We ignore make internal variables (those which start with '.') 492 * We ignore make internal variables (those which start with '.')
493 * Also we jump through some hoops to avoid calling setenv 493 * Also we jump through some hoops to avoid calling setenv
494 * more than necessary since it can leak. 494 * more than necessary since it can leak.
495 * We only manipulate flags of vars if 'parent' is set. 495 * We only manipulate flags of vars if 'parent' is set.
496 */ 496 */
497static int 497static int
498Var_Export1(const char *name, VarExportFlags flags) 498Var_Export1(const char *name, VarExportFlags flags)
499{ 499{
500 char tmp[BUFSIZ]; 500 char tmp[BUFSIZ];
501 Var *v; 501 Var *v;
502 char *val = NULL; 502 char *val = NULL;
503 int n; 503 int n;
504 VarExportFlags parent = flags & VAR_EXPORT_PARENT; 504 VarExportFlags parent = flags & VAR_EXPORT_PARENT;
505 505
506 if (*name == '.') 506 if (*name == '.')
507 return 0; /* skip internals */ 507 return 0; /* skip internals */
508 if (!name[1]) { 508 if (!name[1]) {
509 /* 509 /*
510 * A single char. 510 * A single char.
511 * If it is one of the vars that should only appear in 511 * If it is one of the vars that should only appear in
512 * local context, skip it, else we can get Var_Subst 512 * local context, skip it, else we can get Var_Subst
513 * into a loop. 513 * into a loop.
514 */ 514 */
515 switch (name[0]) { 515 switch (name[0]) {
516 case '@': 516 case '@':
517 case '%': 517 case '%':
518 case '*': 518 case '*':
519 case '!': 519 case '!':
520 return 0; 520 return 0;
521 } 521 }
522 } 522 }
523 v = VarFind(name, VAR_GLOBAL, 0); 523 v = VarFind(name, VAR_GLOBAL, 0);
524 if (v == NULL) 524 if (v == NULL)
525 return 0; 525 return 0;
526 if (!parent && 526 if (!parent &&
527 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED) { 527 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED) {
528 return 0; /* nothing to do */ 528 return 0; /* nothing to do */
529 } 529 }
530 val = Buf_GetAll(&v->val, NULL); 530 val = Buf_GetAll(&v->val, NULL);
531 if ((flags & VAR_EXPORT_LITERAL) == 0 && strchr(val, '$')) { 531 if ((flags & VAR_EXPORT_LITERAL) == 0 && strchr(val, '$')) {
532 if (parent) { 532 if (parent) {
533 /* 533 /*
534 * Flag this as something we need to re-export. 534 * Flag this as something we need to re-export.
535 * No point actually exporting it now though, 535 * No point actually exporting it now though,
536 * the child can do it at the last minute. 536 * the child can do it at the last minute.
537 */ 537 */
538 v->flags |= (VAR_EXPORTED | VAR_REEXPORT); 538 v->flags |= (VAR_EXPORTED | VAR_REEXPORT);
539 return 1; 539 return 1;
540 } 540 }
541 if (v->flags & VAR_IN_USE) { 541 if (v->flags & VAR_IN_USE) {
542 /* 542 /*
543 * We recursed while exporting in a child. 543 * We recursed while exporting in a child.
544 * This isn't going to end well, just skip it. 544 * This isn't going to end well, just skip it.
545 */ 545 */
546 return 0; 546 return 0;
547 } 547 }
548 n = snprintf(tmp, sizeof(tmp), "${%s}", name); 548 n = snprintf(tmp, sizeof(tmp), "${%s}", name);
549 if (n < (int)sizeof(tmp)) { 549 if (n < (int)sizeof(tmp)) {
550 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES); 550 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES);
551 setenv(name, val, 1); 551 setenv(name, val, 1);
552 free(val); 552 free(val);
553 } 553 }
554 } else { 554 } else {
555 if (parent) 555 if (parent)
556 v->flags &= ~VAR_REEXPORT; /* once will do */ 556 v->flags &= ~VAR_REEXPORT; /* once will do */
557 if (parent || !(v->flags & VAR_EXPORTED)) 557 if (parent || !(v->flags & VAR_EXPORTED))
558 setenv(name, val, 1); 558 setenv(name, val, 1);
559 } 559 }
560 /* 560 /*
561 * This is so Var_Set knows to call Var_Export again... 561 * This is so Var_Set knows to call Var_Export again...
562 */ 562 */
563 if (parent) { 563 if (parent) {
564 v->flags |= VAR_EXPORTED; 564 v->flags |= VAR_EXPORTED;
565 } 565 }
566 return 1; 566 return 1;
567} 567}
568 568
569static void 569static void
570Var_ExportVars_callback(void *entry, void *unused MAKE_ATTR_UNUSED) 570Var_ExportVars_callback(void *entry, void *unused MAKE_ATTR_UNUSED)
571{ 571{
572 Var *var = entry; 572 Var *var = entry;
573 Var_Export1(var->name, 0); 573 Var_Export1(var->name, 0);
574} 574}
575 575
576/* 576/*
577 * This gets called from our children. 577 * This gets called from our children.
578 */ 578 */
579void 579void
580Var_ExportVars(void) 580Var_ExportVars(void)
581{ 581{
582 char tmp[BUFSIZ]; 582 char tmp[BUFSIZ];
583 char *val; 583 char *val;
584 int n; 584 int n;
585 585
586 /* 586 /*
587 * Several make's support this sort of mechanism for tracking 587 * Several make's support this sort of mechanism for tracking
588 * recursion - but each uses a different name. 588 * recursion - but each uses a different name.
589 * We allow the makefiles to update MAKELEVEL and ensure 589 * We allow the makefiles to update MAKELEVEL and ensure
590 * children see a correctly incremented value. 590 * children see a correctly incremented value.
591 */ 591 */
592 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1); 592 snprintf(tmp, sizeof(tmp), "%d", makelevel + 1);
593 setenv(MAKE_LEVEL_ENV, tmp, 1); 593 setenv(MAKE_LEVEL_ENV, tmp, 1);
594 594
595 if (VAR_EXPORTED_NONE == var_exportedVars) 595 if (VAR_EXPORTED_NONE == var_exportedVars)
596 return; 596 return;
597 597
598 if (VAR_EXPORTED_ALL == var_exportedVars) { 598 if (VAR_EXPORTED_ALL == var_exportedVars) {
599 /* Ouch! This is crazy... */ 599 /* Ouch! This is crazy... */
600 Hash_ForEach(&VAR_GLOBAL->context, Var_ExportVars_callback, NULL); 600 Hash_ForEach(&VAR_GLOBAL->context, Var_ExportVars_callback, NULL);
601 return; 601 return;
602 } 602 }
603 /* 603 /*
604 * We have a number of exported vars, 604 * We have a number of exported vars,
605 */ 605 */
606 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}"); 606 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
607 if (n < (int)sizeof(tmp)) { 607 if (n < (int)sizeof(tmp)) {
608 char **av; 608 char **av;
609 char *as; 609 char *as;
610 int ac; 610 int ac;
611 int i; 611 int i;
612 612
613 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES); 613 val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES);
614 if (*val) { 614 if (*val) {
615 av = brk_string(val, &ac, FALSE, &as); 615 av = brk_string(val, &ac, FALSE, &as);
616 for (i = 0; i < ac; i++) 616 for (i = 0; i < ac; i++)
617 Var_Export1(av[i], 0); 617 Var_Export1(av[i], 0);
618 free(as); 618 free(as);
619 free(av); 619 free(av);
620 } 620 }
621 free(val); 621 free(val);
622 } 622 }
623} 623}
624 624
625/* 625/*
626 * This is called when .export is seen or 626 * This is called when .export is seen or
627 * .MAKE.EXPORTED is modified. 627 * .MAKE.EXPORTED is modified.
628 * It is also called when any exported var is modified. 628 * It is also called when any exported var is modified.
629 */ 629 */
630void 630void
631Var_Export(char *str, int isExport) 631Var_Export(char *str, int isExport)
632{ 632{
633 char **av; 633 char **av;
634 char *as; 634 char *as;
635 VarExportFlags flags; 635 VarExportFlags flags;
636 int ac; 636 int ac;
637 int i; 637 int i;
638 638
639 if (isExport && (!str || !str[0])) { 639 if (isExport && (!str || !str[0])) {
640 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */ 640 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
641 return; 641 return;
642 } 642 }
643 643
644 flags = 0; 644 flags = 0;
645 if (strncmp(str, "-env", 4) == 0) { 645 if (strncmp(str, "-env", 4) == 0) {
646 str += 4; 646 str += 4;
647 } else if (strncmp(str, "-literal", 8) == 0) { 647 } else if (strncmp(str, "-literal", 8) == 0) {
648 str += 8; 648 str += 8;
649 flags |= VAR_EXPORT_LITERAL; 649 flags |= VAR_EXPORT_LITERAL;
650 } else { 650 } else {
651 flags |= VAR_EXPORT_PARENT; 651 flags |= VAR_EXPORT_PARENT;
652 } 652 }
653 653
654 char *val = Var_Subst(NULL, str, VAR_GLOBAL, VARE_WANTRES); 654 char *val = Var_Subst(NULL, str, VAR_GLOBAL, VARE_WANTRES);
655 if (*val) { 655 if (*val) {
656 av = brk_string(val, &ac, FALSE, &as); 656 av = brk_string(val, &ac, FALSE, &as);
657 for (i = 0; i < ac; i++) { 657 for (i = 0; i < ac; i++) {
658 const char *name = av[i]; 658 const char *name = av[i];
659 if (!name[1]) { 659 if (!name[1]) {
660 /* 660 /*
661 * A single char. 661 * A single char.
662 * If it is one of the vars that should only appear in 662 * If it is one of the vars that should only appear in
663 * local context, skip it, else we can get Var_Subst 663 * local context, skip it, else we can get Var_Subst
664 * into a loop. 664 * into a loop.
665 */ 665 */
666 switch (name[0]) { 666 switch (name[0]) {
667 case '@': 667 case '@':
668 case '%': 668 case '%':
669 case '*': 669 case '*':
670 case '!': 670 case '!':
671 continue; 671 continue;
672 } 672 }
673 } 673 }
674 if (Var_Export1(name, flags)) { 674 if (Var_Export1(name, flags)) {
675 if (VAR_EXPORTED_ALL != var_exportedVars) 675 if (VAR_EXPORTED_ALL != var_exportedVars)
676 var_exportedVars = VAR_EXPORTED_YES; 676 var_exportedVars = VAR_EXPORTED_YES;
677 if (isExport && (flags & VAR_EXPORT_PARENT)) { 677 if (isExport && (flags & VAR_EXPORT_PARENT)) {
678 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL); 678 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
679 } 679 }
680 } 680 }
681 } 681 }
682 free(as); 682 free(as);
683 free(av); 683 free(av);
684 } 684 }
685 free(val); 685 free(val);
686} 686}
687 687
688 688
689extern char **environ; 689extern char **environ;
690 690
691/* 691/*
692 * This is called when .unexport[-env] is seen. 692 * This is called when .unexport[-env] is seen.
693 */ 693 */
694void 694void
695Var_UnExport(char *str) 695Var_UnExport(char *str)
696{ 696{
697 char tmp[BUFSIZ]; 697 char tmp[BUFSIZ];
698 char *vlist; 698 char *vlist;
699 char *cp; 699 char *cp;
700 Boolean unexport_env; 700 Boolean unexport_env;
701 int n; 701 int n;
702 702
703 if (str == NULL || str[0] == '\0') 703 if (str == NULL || str[0] == '\0')
704 return; /* assert? */ 704 return; /* assert? */
705 705
706 vlist = NULL; 706 vlist = NULL;
707 707
708 str += 8; 708 str += 8;
709 unexport_env = (strncmp(str, "-env", 4) == 0); 709 unexport_env = (strncmp(str, "-env", 4) == 0);
710 if (unexport_env) { 710 if (unexport_env) {
711 char **newenv; 711 char **newenv;
712 712
713 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */ 713 cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
714 if (environ == savedEnv) { 714 if (environ == savedEnv) {
715 /* we have been here before! */ 715 /* we have been here before! */
716 newenv = bmake_realloc(environ, 2 * sizeof(char *)); 716 newenv = bmake_realloc(environ, 2 * sizeof(char *));
717 } else { 717 } else {
718 if (savedEnv) { 718 if (savedEnv) {
719 free(savedEnv); 719 free(savedEnv);
720 savedEnv = NULL; 720 savedEnv = NULL;
721 } 721 }
722 newenv = bmake_malloc(2 * sizeof(char *)); 722 newenv = bmake_malloc(2 * sizeof(char *));
723 } 723 }
724 if (!newenv) 724 if (!newenv)
725 return; 725 return;
726 /* Note: we cannot safely free() the original environ. */ 726 /* Note: we cannot safely free() the original environ. */
727 environ = savedEnv = newenv; 727 environ = savedEnv = newenv;
728 newenv[0] = NULL; 728 newenv[0] = NULL;
729 newenv[1] = NULL; 729 newenv[1] = NULL;
730 if (cp && *cp) 730 if (cp && *cp)
731 setenv(MAKE_LEVEL_ENV, cp, 1); 731 setenv(MAKE_LEVEL_ENV, cp, 1);
732 } else { 732 } else {
733 for (; *str != '\n' && isspace((unsigned char) *str); str++) 733 for (; *str != '\n' && isspace((unsigned char) *str); str++)
734 continue; 734 continue;
735 if (str[0] && str[0] != '\n') { 735 if (str[0] && str[0] != '\n') {
736 vlist = str; 736 vlist = str;
737 } 737 }
738 } 738 }
739 739
740 if (!vlist) { 740 if (!vlist) {
741 /* Using .MAKE.EXPORTED */ 741 /* Using .MAKE.EXPORTED */
742 vlist = Var_Subst(NULL, "${" MAKE_EXPORTED ":O:u}", VAR_GLOBAL, 742 vlist = Var_Subst(NULL, "${" MAKE_EXPORTED ":O:u}", VAR_GLOBAL,
743 VARE_WANTRES); 743 VARE_WANTRES);
744 } 744 }
745 if (vlist) { 745 if (vlist) {
746 Var *v; 746 Var *v;
747 char **av; 747 char **av;
748 char *as; 748 char *as;
749 int ac; 749 int ac;
750 int i; 750 int i;
751 751
752 av = brk_string(vlist, &ac, FALSE, &as); 752 av = brk_string(vlist, &ac, FALSE, &as);
753 for (i = 0; i < ac; i++) { 753 for (i = 0; i < ac; i++) {
754 v = VarFind(av[i], VAR_GLOBAL, 0); 754 v = VarFind(av[i], VAR_GLOBAL, 0);
755 if (!v) 755 if (!v)
756 continue; 756 continue;
757 if (!unexport_env && 757 if (!unexport_env &&
758 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED) 758 (v->flags & (VAR_EXPORTED | VAR_REEXPORT)) == VAR_EXPORTED)
759 unsetenv(v->name); 759 unsetenv(v->name);
760 v->flags &= ~(VAR_EXPORTED | VAR_REEXPORT); 760 v->flags &= ~(VAR_EXPORTED | VAR_REEXPORT);
761 /* 761 /*
762 * If we are unexporting a list, 762 * If we are unexporting a list,
763 * remove each one from .MAKE.EXPORTED. 763 * remove each one from .MAKE.EXPORTED.
764 * If we are removing them all, 764 * If we are removing them all,
765 * just delete .MAKE.EXPORTED below. 765 * just delete .MAKE.EXPORTED below.
766 */ 766 */
767 if (vlist == str) { 767 if (vlist == str) {
768 n = snprintf(tmp, sizeof(tmp), 768 n = snprintf(tmp, sizeof(tmp),
769 "${" MAKE_EXPORTED ":N%s}", v->name); 769 "${" MAKE_EXPORTED ":N%s}", v->name);
770 if (n < (int)sizeof(tmp)) { 770 if (n < (int)sizeof(tmp)) {
771 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES); 771 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARE_WANTRES);
772 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL); 772 Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL);
773 free(cp); 773 free(cp);
774 } 774 }
775 } 775 }
776 } 776 }
777 free(as); 777 free(as);
778 free(av); 778 free(av);
779 if (vlist != str) { 779 if (vlist != str) {
780 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL); 780 Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
781 free(vlist); 781 free(vlist);
782 } 782 }
783 } 783 }
784} 784}
785 785
786static void 786static void
787Var_Set_with_flags(const char *name, const char *val, GNode *ctxt, 787Var_Set_with_flags(const char *name, const char *val, GNode *ctxt,
788 VarSet_Flags flags) 788 VarSet_Flags flags)
789{ 789{
790 Var *v; 790 Var *v;
791 char *expanded_name = NULL; 791 char *expanded_name = NULL;
792 792
793 /* 793 /*
794 * We only look for a variable in the given context since anything set 794 * We only look for a variable in the given context since anything set
795 * here will override anything in a lower context, so there's not much 795 * here will override anything in a lower context, so there's not much
796 * point in searching them all just to save a bit of memory... 796 * point in searching them all just to save a bit of memory...
797 */ 797 */
798 if (strchr(name, '$') != NULL) { 798 if (strchr(name, '$') != NULL) {
799 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES); 799 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES);
800 if (expanded_name[0] == '\0') { 800 if (expanded_name[0] == '\0') {
801 if (DEBUG(VAR)) { 801 if (DEBUG(VAR)) {
802 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) " 802 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
803 "name expands to empty string - ignored\n", 803 "name expands to empty string - ignored\n",
804 name, val); 804 name, val);
805 } 805 }
806 free(expanded_name); 806 free(expanded_name);
807 return; 807 return;
808 } 808 }
809 name = expanded_name; 809 name = expanded_name;
810 } 810 }
811 if (ctxt == VAR_GLOBAL) { 811 if (ctxt == VAR_GLOBAL) {
812 v = VarFind(name, VAR_CMD, 0); 812 v = VarFind(name, VAR_CMD, 0);
813 if (v != NULL) { 813 if (v != NULL) {
814 if ((v->flags & VAR_FROM_CMD)) { 814 if ((v->flags & VAR_FROM_CMD)) {
815 if (DEBUG(VAR)) { 815 if (DEBUG(VAR)) {
816 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val); 816 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
817 } 817 }
818 goto out; 818 goto out;
819 } 819 }
820 VarFreeEnv(v, TRUE); 820 VarFreeEnv(v, TRUE);
821 } 821 }
822 } 822 }
823 v = VarFind(name, ctxt, 0); 823 v = VarFind(name, ctxt, 0);
824 if (v == NULL) { 824 if (v == NULL) {
825 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) { 825 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
826 /* 826 /*
827 * This var would normally prevent the same name being added 827 * This var would normally prevent the same name being added
828 * to VAR_GLOBAL, so delete it from there if needed. 828 * to VAR_GLOBAL, so delete it from there if needed.
829 * Otherwise -V name may show the wrong value. 829 * Otherwise -V name may show the wrong value.
830 */ 830 */
831 Var_Delete(name, VAR_GLOBAL); 831 Var_Delete(name, VAR_GLOBAL);
832 } 832 }
833 VarAdd(name, val, ctxt); 833 VarAdd(name, val, ctxt);
834 } else { 834 } else {
835 Buf_Empty(&v->val); 835 Buf_Empty(&v->val);
836 if (val) 836 if (val)
837 Buf_AddStr(&v->val, val); 837 Buf_AddStr(&v->val, val);
838 838
839 if (DEBUG(VAR)) { 839 if (DEBUG(VAR)) {
840 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); 840 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
841 } 841 }
842 if ((v->flags & VAR_EXPORTED)) { 842 if ((v->flags & VAR_EXPORTED)) {
843 Var_Export1(name, VAR_EXPORT_PARENT); 843 Var_Export1(name, VAR_EXPORT_PARENT);
844 } 844 }
845 } 845 }
846 /* 846 /*
847 * Any variables given on the command line are automatically exported 847 * Any variables given on the command line are automatically exported
848 * to the environment (as per POSIX standard) 848 * to the environment (as per POSIX standard)
849 */ 849 */
850 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) { 850 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
851 if (v == NULL) { 851 if (v == NULL) {
852 /* we just added it */ 852 /* we just added it */
853 v = VarFind(name, ctxt, 0); 853 v = VarFind(name, ctxt, 0);
854 } 854 }
855 if (v != NULL) 855 if (v != NULL)
856 v->flags |= VAR_FROM_CMD; 856 v->flags |= VAR_FROM_CMD;
857 /* 857 /*
858 * If requested, don't export these in the environment 858 * If requested, don't export these in the environment
859 * individually. We still put them in MAKEOVERRIDES so 859 * individually. We still put them in MAKEOVERRIDES so
860 * that the command-line settings continue to override 860 * that the command-line settings continue to override
861 * Makefile settings. 861 * Makefile settings.
862 */ 862 */
863 if (varNoExportEnv != TRUE) 863 if (varNoExportEnv != TRUE)
864 setenv(name, val ? val : "", 1); 864 setenv(name, val ? val : "", 1);
865 865
866 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL); 866 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
867 } 867 }
868 if (name[0] == '.' && strcmp(name, SAVE_DOLLARS) == 0) 868 if (name[0] == '.' && strcmp(name, SAVE_DOLLARS) == 0)
869 save_dollars = s2Boolean(val, save_dollars); 869 save_dollars = s2Boolean(val, save_dollars);
870 870
871out: 871out:
872 free(expanded_name); 872 free(expanded_name);
873 if (v != NULL) 873 if (v != NULL)
874 VarFreeEnv(v, TRUE); 874 VarFreeEnv(v, TRUE);
875} 875}
876 876
877/*- 877/*-
878 *----------------------------------------------------------------------- 878 *-----------------------------------------------------------------------
879 * Var_Set -- 879 * Var_Set --
880 * Set the variable name to the value val in the given context. 880 * Set the variable name to the value val in the given context.
881 * 881 *
882 * Input: 882 * Input:
883 * name name of variable to set 883 * name name of variable to set
884 * val value to give to the variable 884 * val value to give to the variable
885 * ctxt context in which to set it 885 * ctxt context in which to set it
886 * 886 *
887 * Side Effects: 887 * Side Effects:
888 * If the variable doesn't yet exist, a new record is created for it. 888 * If the variable doesn't yet exist, a new record is created for it.
889 * Else the old value is freed and the new one stuck in its place 889 * Else the old value is freed and the new one stuck in its place
890 * 890 *
891 * Notes: 891 * Notes:
892 * The variable is searched for only in its context before being 892 * The variable is searched for only in its context before being
893 * created in that context. I.e. if the context is VAR_GLOBAL, 893 * created in that context. I.e. if the context is VAR_GLOBAL,
894 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only 894 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
895 * VAR_CMD->context is searched. This is done to avoid the literally 895 * VAR_CMD->context is searched. This is done to avoid the literally
896 * thousands of unnecessary strcmp's that used to be done to 896 * thousands of unnecessary strcmp's that used to be done to
897 * set, say, $(@) or $(<). 897 * set, say, $(@) or $(<).
898 * If the context is VAR_GLOBAL though, we check if the variable 898 * If the context is VAR_GLOBAL though, we check if the variable
899 * was set in VAR_CMD from the command line and skip it if so. 899 * was set in VAR_CMD from the command line and skip it if so.
900 *----------------------------------------------------------------------- 900 *-----------------------------------------------------------------------
901 */ 901 */
902void 902void
903Var_Set(const char *name, const char *val, GNode *ctxt) 903Var_Set(const char *name, const char *val, GNode *ctxt)
904{ 904{
905 Var_Set_with_flags(name, val, ctxt, 0); 905 Var_Set_with_flags(name, val, ctxt, 0);
906} 906}
907 907
908/*- 908/*-
909 *----------------------------------------------------------------------- 909 *-----------------------------------------------------------------------
910 * Var_Append -- 910 * Var_Append --
911 * The variable of the given name has the given value appended to it in 911 * The variable of the given name has the given value appended to it in
912 * the given context. 912 * the given context.
913 * 913 *
914 * Input: 914 * Input:
915 * name name of variable to modify 915 * name name of variable to modify
916 * val String to append to it 916 * val String to append to it
917 * ctxt Context in which this should occur 917 * ctxt Context in which this should occur
918 * 918 *
919 * Side Effects: 919 * Side Effects:
920 * If the variable doesn't exist, it is created. Else the strings 920 * If the variable doesn't exist, it is created. Else the strings
921 * are concatenated (with a space in between). 921 * are concatenated (with a space in between).
922 * 922 *
923 * Notes: 923 * Notes:
924 * Only if the variable is being sought in the global context is the 924 * Only if the variable is being sought in the global context is the
925 * environment searched. 925 * environment searched.
926 * XXX: Knows its calling circumstances in that if called with ctxt 926 * XXX: Knows its calling circumstances in that if called with ctxt
927 * an actual target, it will only search that context since only 927 * an actual target, it will only search that context since only
928 * a local variable could be being appended to. This is actually 928 * a local variable could be being appended to. This is actually
929 * a big win and must be tolerated. 929 * a big win and must be tolerated.
930 *----------------------------------------------------------------------- 930 *-----------------------------------------------------------------------
931 */ 931 */
932void 932void
933Var_Append(const char *name, const char *val, GNode *ctxt) 933Var_Append(const char *name, const char *val, GNode *ctxt)
934{ 934{
935 Var *v; 935 Var *v;
936 Hash_Entry *h; 936 Hash_Entry *h;
937 char *expanded_name = NULL; 937 char *expanded_name = NULL;
938 938
939 if (strchr(name, '$') != NULL) { 939 if (strchr(name, '$') != NULL) {
940 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES); 940 expanded_name = Var_Subst(NULL, name, ctxt, VARE_WANTRES);
941 if (expanded_name[0] == '\0') { 941 if (expanded_name[0] == '\0') {
942 if (DEBUG(VAR)) { 942 if (DEBUG(VAR)) {
943 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) " 943 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
944 "name expands to empty string - ignored\n", 944 "name expands to empty string - ignored\n",
945 name, val); 945 name, val);
946 } 946 }
947 free(expanded_name); 947 free(expanded_name);
948 return; 948 return;
949 } 949 }
950 name = expanded_name; 950 name = expanded_name;
951 } 951 }
952 952
953 v = VarFind(name, ctxt, ctxt == VAR_GLOBAL ? (FIND_CMD | FIND_ENV) : 0); 953 v = VarFind(name, ctxt, ctxt == VAR_GLOBAL ? (FIND_CMD | FIND_ENV) : 0);
954 954
955 if (v == NULL) { 955 if (v == NULL) {
956 Var_Set(name, val, ctxt); 956 Var_Set(name, val, ctxt);
957 } else if (ctxt == VAR_CMD || !(v->flags & VAR_FROM_CMD)) { 957 } else if (ctxt == VAR_CMD || !(v->flags & VAR_FROM_CMD)) {
958 Buf_AddByte(&v->val, ' '); 958 Buf_AddByte(&v->val, ' ');
959 Buf_AddStr(&v->val, val); 959 Buf_AddStr(&v->val, val);
960 960
961 if (DEBUG(VAR)) { 961 if (DEBUG(VAR)) {
962 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, 962 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
963 Buf_GetAll(&v->val, NULL)); 963 Buf_GetAll(&v->val, NULL));
964 } 964 }
965 965
966 if (v->flags & VAR_FROM_ENV) { 966 if (v->flags & VAR_FROM_ENV) {
967 /* 967 /*
968 * If the original variable came from the environment, we 968 * If the original variable came from the environment, we
969 * have to install it in the global context (we could place 969 * have to install it in the global context (we could place
970 * it in the environment, but then we should provide a way to 970 * it in the environment, but then we should provide a way to
971 * export other variables...) 971 * export other variables...)
972 */ 972 */
973 v->flags &= ~VAR_FROM_ENV; 973 v->flags &= ~VAR_FROM_ENV;
974 h = Hash_CreateEntry(&ctxt->context, name, NULL); 974 h = Hash_CreateEntry(&ctxt->context, name, NULL);
975 Hash_SetValue(h, v); 975 Hash_SetValue(h, v);
976 } 976 }
977 } 977 }
978 free(expanded_name); 978 free(expanded_name);
979} 979}
980 980
981/*- 981/*-
982 *----------------------------------------------------------------------- 982 *-----------------------------------------------------------------------
983 * Var_Exists -- 983 * Var_Exists --
984 * See if the given variable exists. 984 * See if the given variable exists.
985 * 985 *
986 * Input: 986 * Input:
987 * name Variable to find 987 * name Variable to find
988 * ctxt Context in which to start search 988 * ctxt Context in which to start search
989 * 989 *
990 * Results: 990 * Results:
991 * TRUE if it does, FALSE if it doesn't 991 * TRUE if it does, FALSE if it doesn't
992 * 992 *
993 * Side Effects: 993 * Side Effects:
994 * None. 994 * None.
995 * 995 *
996 *----------------------------------------------------------------------- 996 *-----------------------------------------------------------------------
997 */ 997 */
998Boolean 998Boolean
999Var_Exists(const char *name, GNode *ctxt) 999Var_Exists(const char *name, GNode *ctxt)
1000{ 1000{
1001 Var *v; 1001 Var *v;
1002 char *cp; 1002 char *cp;
1003 1003
1004 if ((cp = strchr(name, '$')) != NULL) 1004 if ((cp = strchr(name, '$')) != NULL)
1005 cp = Var_Subst(NULL, name, ctxt, VARE_WANTRES); 1005 cp = Var_Subst(NULL, name, ctxt, VARE_WANTRES);
1006 v = VarFind(cp ? cp : name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV); 1006 v = VarFind(cp ? cp : name, ctxt, FIND_CMD | FIND_GLOBAL | FIND_ENV);
1007 free(cp); 1007 free(cp);
1008 if (v == NULL) 1008 if (v == NULL)
1009 return FALSE; 1009 return FALSE;
1010 1010
1011 (void)VarFreeEnv(v, TRUE); 1011 (void)VarFreeEnv(v, TRUE);
1012 return TRUE; 1012 return TRUE;
1013} 1013}
1014 1014
1015/*- 1015/*-
1016 *----------------------------------------------------------------------- 1016 *-----------------------------------------------------------------------
1017 * Var_Value -- 1017 * Var_Value --
1018 * Return the value of the named variable in the given context 1018 * Return the unexpanded value of the given variable in the given
 1019 * context.
1019 * 1020 *
1020 * Input: 1021 * Input:
1021 * name name to find 1022 * name name to find
1022 * ctxt context in which to search for it 1023 * ctxt context in which to search for it
1023 * 1024 *
1024 * Results: 1025 * Results:
1025 * The value if the variable exists, NULL if it doesn't 1026 * The value if the variable exists, NULL if it doesn't.
1026 * 1027 * If the returned value is not NULL, the caller must free *freeIt
1027 * Side Effects: 1028 * as soon as the returned value is no longer needed.
1028 * None 
1029 *----------------------------------------------------------------------- 1029 *-----------------------------------------------------------------------
1030 */ 1030 */
1031char * 1031char *
1032Var_Value(const char *name, GNode *ctxt, char **frp) 1032Var_Value(const char *name, GNode *ctxt, char **freeIt)
1033{ 1033{
1034 Var *v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); 1034 Var *v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1035 *frp = NULL; 1035 *freeIt = NULL;
1036 if (v == NULL) 1036 if (v == NULL)
1037 return NULL; 1037 return NULL;
1038 1038
1039 char *p = Buf_GetAll(&v->val, NULL); 1039 char *p = Buf_GetAll(&v->val, NULL);
1040 if (VarFreeEnv(v, FALSE)) 1040 if (VarFreeEnv(v, FALSE))
1041 *frp = p; 1041 *freeIt = p;
1042 return p; 1042 return p;
1043} 1043}
1044 1044
1045 1045
1046/* SepBuf is a string being built from "words", interleaved with separators. */ 1046/* SepBuf is a string being built from "words", interleaved with separators. */
1047typedef struct { 1047typedef struct {
1048 Buffer buf; 1048 Buffer buf;
1049 Boolean needSep; 1049 Boolean needSep;
1050 char sep; 1050 char sep;
1051} SepBuf; 1051} SepBuf;
1052 1052
1053static void 1053static void
1054SepBuf_Init(SepBuf *buf, char sep) 1054SepBuf_Init(SepBuf *buf, char sep)
1055{ 1055{
1056 Buf_Init(&buf->buf, 32 /* bytes */); 1056 Buf_Init(&buf->buf, 32 /* bytes */);
1057 buf->needSep = FALSE; 1057 buf->needSep = FALSE;
1058 buf->sep = sep; 1058 buf->sep = sep;
1059} 1059}
1060 1060
1061static void 1061static void
1062SepBuf_Sep(SepBuf *buf) 1062SepBuf_Sep(SepBuf *buf)
1063{ 1063{
1064 buf->needSep = TRUE; 1064 buf->needSep = TRUE;
1065} 1065}
1066 1066
1067static void 1067static void
1068SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size) 1068SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
1069{ 1069{
1070 if (mem_size == 0) 1070 if (mem_size == 0)
1071 return; 1071 return;
1072 if (buf->needSep && buf->sep != '\0') { 1072 if (buf->needSep && buf->sep != '\0') {
1073 Buf_AddByte(&buf->buf, buf->sep); 1073 Buf_AddByte(&buf->buf, buf->sep);
1074 buf->needSep = FALSE; 1074 buf->needSep = FALSE;
1075 } 1075 }
1076 Buf_AddBytes(&buf->buf, mem_size, mem); 1076 Buf_AddBytes(&buf->buf, mem_size, mem);
1077} 1077}
1078 1078
1079static void 1079static void
1080SepBuf_AddBytesBetween(SepBuf *buf, const char *start, const char *end) 1080SepBuf_AddBytesBetween(SepBuf *buf, const char *start, const char *end)
1081{ 1081{
1082 SepBuf_AddBytes(buf, start, (size_t)(end - start)); 1082 SepBuf_AddBytes(buf, start, (size_t)(end - start));
1083} 1083}
1084 1084
1085static void 1085static void
1086SepBuf_AddStr(SepBuf *buf, const char *str) 1086SepBuf_AddStr(SepBuf *buf, const char *str)
1087{ 1087{
1088 SepBuf_AddBytes(buf, str, strlen(str)); 1088 SepBuf_AddBytes(buf, str, strlen(str));
1089} 1089}
1090 1090
1091static char * 1091static char *
1092SepBuf_Destroy(SepBuf *buf, Boolean free_buf) 1092SepBuf_Destroy(SepBuf *buf, Boolean free_buf)
1093{ 1093{
1094 return Buf_Destroy(&buf->buf, free_buf); 1094 return Buf_Destroy(&buf->buf, free_buf);
1095} 1095}
1096 1096
1097 1097
1098/* This callback for ModifyWords gets a single word from an expression and 1098/* This callback for ModifyWords gets a single word from an expression and
1099 * typically adds a modification of this word to the buffer. It may also do 1099 * typically adds a modification of this word to the buffer. It may also do
1100 * nothing or add several words. */ 1100 * nothing or add several words. */
1101typedef void (*ModifyWordsCallback)(const char *word, SepBuf *buf, void *data); 1101typedef void (*ModifyWordsCallback)(const char *word, SepBuf *buf, void *data);
1102 1102
1103 1103
1104/* Callback for ModifyWords to implement the :H modifier. 1104/* Callback for ModifyWords to implement the :H modifier.
1105 * Add the dirname of the given word to the buffer. */ 1105 * Add the dirname of the given word to the buffer. */
1106static void 1106static void
1107ModifyWord_Head(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED) 1107ModifyWord_Head(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1108{ 1108{
1109 const char *slash = strrchr(word, '/'); 1109 const char *slash = strrchr(word, '/');
1110 if (slash != NULL) 1110 if (slash != NULL)
1111 SepBuf_AddBytesBetween(buf, word, slash); 1111 SepBuf_AddBytesBetween(buf, word, slash);
1112 else 1112 else
1113 SepBuf_AddStr(buf, "."); 1113 SepBuf_AddStr(buf, ".");
1114} 1114}
1115 1115
1116/* Callback for ModifyWords to implement the :T modifier. 1116/* Callback for ModifyWords to implement the :T modifier.
1117 * Add the basename of the given word to the buffer. */ 1117 * Add the basename of the given word to the buffer. */
1118static void 1118static void
1119ModifyWord_Tail(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED) 1119ModifyWord_Tail(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1120{ 1120{
1121 const char *slash = strrchr(word, '/'); 1121 const char *slash = strrchr(word, '/');
1122 const char *base = slash != NULL ? slash + 1 : word; 1122 const char *base = slash != NULL ? slash + 1 : word;
1123 SepBuf_AddStr(buf, base); 1123 SepBuf_AddStr(buf, base);
1124} 1124}
1125 1125
1126/* Callback for ModifyWords to implement the :E modifier. 1126/* Callback for ModifyWords to implement the :E modifier.
1127 * Add the filename suffix of the given word to the buffer, if it exists. */ 1127 * Add the filename suffix of the given word to the buffer, if it exists. */
1128static void 1128static void
1129ModifyWord_Suffix(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED) 1129ModifyWord_Suffix(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1130{ 1130{
1131 const char *dot = strrchr(word, '.'); 1131 const char *dot = strrchr(word, '.');
1132 if (dot != NULL) 1132 if (dot != NULL)
1133 SepBuf_AddStr(buf, dot + 1); 1133 SepBuf_AddStr(buf, dot + 1);
1134} 1134}
1135 1135
1136/* Callback for ModifyWords to implement the :R modifier. 1136/* Callback for ModifyWords to implement the :R modifier.
1137 * Add the basename of the given word to the buffer. */ 1137 * Add the basename of the given word to the buffer. */
1138static void 1138static void
1139ModifyWord_Root(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED) 1139ModifyWord_Root(const char *word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
1140{ 1140{
1141 const char *dot = strrchr(word, '.'); 1141 const char *dot = strrchr(word, '.');
1142 size_t len = dot != NULL ? (size_t)(dot - word) : strlen(word); 1142 size_t len = dot != NULL ? (size_t)(dot - word) : strlen(word);
1143 SepBuf_AddBytes(buf, word, len); 1143 SepBuf_AddBytes(buf, word, len);
1144} 1144}
1145 1145
1146/* Callback for ModifyWords to implement the :M modifier. 1146/* Callback for ModifyWords to implement the :M modifier.
1147 * Place the word in the buffer if it matches the given pattern. */ 1147 * Place the word in the buffer if it matches the given pattern. */
1148static void 1148static void
1149ModifyWord_Match(const char *word, SepBuf *buf, void *data) 1149ModifyWord_Match(const char *word, SepBuf *buf, void *data)
1150{ 1150{
1151 const char *pattern = data; 1151 const char *pattern = data;
1152 if (DEBUG(VAR)) 1152 if (DEBUG(VAR))
1153 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, pattern); 1153 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, pattern);
1154 if (Str_Match(word, pattern)) 1154 if (Str_Match(word, pattern))
1155 SepBuf_AddStr(buf, word); 1155 SepBuf_AddStr(buf, word);
1156} 1156}
1157 1157
1158/* Callback for ModifyWords to implement the :N modifier. 1158/* Callback for ModifyWords to implement the :N modifier.
1159 * Place the word in the buffer if it doesn't match the given pattern. */ 1159 * Place the word in the buffer if it doesn't match the given pattern. */
1160static void 1160static void
1161ModifyWord_NoMatch(const char *word, SepBuf *buf, void *data) 1161ModifyWord_NoMatch(const char *word, SepBuf *buf, void *data)
1162{ 1162{
1163 const char *pattern = data; 1163 const char *pattern = data;
1164 if (!Str_Match(word, pattern)) 1164 if (!Str_Match(word, pattern))
1165 SepBuf_AddStr(buf, word); 1165 SepBuf_AddStr(buf, word);
1166} 1166}
1167 1167
1168#ifdef SYSVVARSUB 1168#ifdef SYSVVARSUB
1169/*- 1169/*-
1170 *----------------------------------------------------------------------- 1170 *-----------------------------------------------------------------------
1171 * Str_SYSVMatch -- 1171 * Str_SYSVMatch --
1172 * Check word against pattern for a match (% is wild), 1172 * Check word against pattern for a match (% is wild),
1173 * 1173 *
1174 * Input: 1174 * Input:
1175 * word Word to examine 1175 * word Word to examine
1176 * pattern Pattern to examine against 1176 * pattern Pattern to examine against
1177 * len Number of characters to substitute 1177 * len Number of characters to substitute
1178 * 1178 *
1179 * Results: 1179 * Results:
1180 * Returns the beginning position of a match or null. The number 1180 * Returns the beginning position of a match or null. The number
1181 * of characters matched is returned in len. 1181 * of characters matched is returned in len.
1182 *----------------------------------------------------------------------- 1182 *-----------------------------------------------------------------------
1183 */ 1183 */
1184static const char * 1184static const char *
1185Str_SYSVMatch(const char *word, const char *pattern, size_t *len, 1185Str_SYSVMatch(const char *word, const char *pattern, size_t *len,
1186 Boolean *hasPercent) 1186 Boolean *hasPercent)
1187{ 1187{
1188 const char *p = pattern; 1188 const char *p = pattern;
1189 const char *w = word; 1189 const char *w = word;
1190 const char *m; 1190 const char *m;
1191 1191
1192 *hasPercent = FALSE; 1192 *hasPercent = FALSE;
1193 if (*p == '\0') { 1193 if (*p == '\0') {
1194 /* Null pattern is the whole string */ 1194 /* Null pattern is the whole string */
1195 *len = strlen(w); 1195 *len = strlen(w);
1196 return w; 1196 return w;
1197 } 1197 }
1198 1198
1199 if ((m = strchr(p, '%')) != NULL) { 1199 if ((m = strchr(p, '%')) != NULL) {
1200 *hasPercent = TRUE; 1200 *hasPercent = TRUE;
1201 if (*w == '\0') { 1201 if (*w == '\0') {
1202 /* empty word does not match pattern */ 1202 /* empty word does not match pattern */
1203 return NULL; 1203 return NULL;
1204 } 1204 }
1205 /* check that the prefix matches */ 1205 /* check that the prefix matches */
1206 for (; p != m && *w && *w == *p; w++, p++) 1206 for (; p != m && *w && *w == *p; w++, p++)
1207 continue; 1207 continue;
1208 1208
1209 if (p != m) 1209 if (p != m)
1210 return NULL; /* No match */ 1210 return NULL; /* No match */
1211 1211
1212 if (*++p == '\0') { 1212 if (*++p == '\0') {
1213 /* No more pattern, return the rest of the string */ 1213 /* No more pattern, return the rest of the string */
1214 *len = strlen(w); 1214 *len = strlen(w);
1215 return w; 1215 return w;
1216 } 1216 }
1217 } 1217 }
1218 1218
1219 m = w; 1219 m = w;
1220 1220
1221 /* Find a matching tail */ 1221 /* Find a matching tail */
1222 do { 1222 do {
1223 if (strcmp(p, w) == 0) { 1223 if (strcmp(p, w) == 0) {
1224 *len = w - m; 1224 *len = w - m;
1225 return m; 1225 return m;
1226 } 1226 }
1227 } while (*w++ != '\0'); 1227 } while (*w++ != '\0');
1228 1228
1229 return NULL; 1229 return NULL;
1230} 1230}
1231 1231
1232 1232
1233/*- 1233/*-
1234 *----------------------------------------------------------------------- 1234 *-----------------------------------------------------------------------
1235 * Str_SYSVSubst -- 1235 * Str_SYSVSubst --
1236 * Substitute '%' on the pattern with len characters from src. 1236 * Substitute '%' on the pattern with len characters from src.
1237 * If the pattern does not contain a '%' prepend len characters 1237 * If the pattern does not contain a '%' prepend len characters
1238 * from src. 1238 * from src.
1239 * 1239 *
1240 * Side Effects: 1240 * Side Effects:
1241 * Places result on buf 1241 * Places result on buf
1242 *----------------------------------------------------------------------- 1242 *-----------------------------------------------------------------------
1243 */ 1243 */
1244static void 1244static void
1245Str_SYSVSubst(SepBuf *buf, const char *pat, const char *src, size_t len, 1245Str_SYSVSubst(SepBuf *buf, const char *pat, const char *src, size_t len,
1246 Boolean lhsHasPercent) 1246 Boolean lhsHasPercent)
1247{ 1247{
1248 const char *m; 1248 const char *m;
1249 1249
1250 if ((m = strchr(pat, '%')) != NULL && lhsHasPercent) { 1250 if ((m = strchr(pat, '%')) != NULL && lhsHasPercent) {
1251 /* Copy the prefix */ 1251 /* Copy the prefix */
1252 SepBuf_AddBytesBetween(buf, pat, m); 1252 SepBuf_AddBytesBetween(buf, pat, m);
1253 /* skip the % */ 1253 /* skip the % */
1254 pat = m + 1; 1254 pat = m + 1;
1255 } 1255 }
1256 if (m != NULL || !lhsHasPercent) { 1256 if (m != NULL || !lhsHasPercent) {
1257 /* Copy the pattern */ 1257 /* Copy the pattern */
1258 SepBuf_AddBytes(buf, src, len); 1258 SepBuf_AddBytes(buf, src, len);
1259 } 1259 }
1260 1260
1261 /* append the rest */ 1261 /* append the rest */
1262 SepBuf_AddStr(buf, pat); 1262 SepBuf_AddStr(buf, pat);
1263} 1263}
1264 1264
1265 1265
1266typedef struct { 1266typedef struct {
1267 GNode *ctx; 1267 GNode *ctx;
1268 const char *lhs; 1268 const char *lhs;
1269 const char *rhs; 1269 const char *rhs;
1270} ModifyWord_SYSVSubstArgs; 1270} ModifyWord_SYSVSubstArgs;
1271 1271
1272/* Callback for ModifyWords to implement the :%.from=%.to modifier. */ 1272/* Callback for ModifyWords to implement the :%.from=%.to modifier. */
1273static void 1273static void
1274ModifyWord_SYSVSubst(const char *word, SepBuf *buf, void *data) 1274ModifyWord_SYSVSubst(const char *word, SepBuf *buf, void *data)
1275{ 1275{
1276 const ModifyWord_SYSVSubstArgs *args = data; 1276 const ModifyWord_SYSVSubstArgs *args = data;
1277 1277
1278 size_t len; 1278 size_t len;
1279 Boolean hasPercent; 1279 Boolean hasPercent;
1280 const char *ptr = Str_SYSVMatch(word, args->lhs, &len, &hasPercent); 1280 const char *ptr = Str_SYSVMatch(word, args->lhs, &len, &hasPercent);
1281 if (ptr != NULL) { 1281 if (ptr != NULL) {
1282 char *varexp = Var_Subst(NULL, args->rhs, args->ctx, VARE_WANTRES); 1282 char *varexp = Var_Subst(NULL, args->rhs, args->ctx, VARE_WANTRES);
1283 Str_SYSVSubst(buf, varexp, ptr, len, hasPercent); 1283 Str_SYSVSubst(buf, varexp, ptr, len, hasPercent);
1284 free(varexp); 1284 free(varexp);
1285 } else { 1285 } else {
1286 SepBuf_AddStr(buf, word); 1286 SepBuf_AddStr(buf, word);
1287 } 1287 }
1288} 1288}
1289#endif 1289#endif
1290 1290
1291 1291
1292typedef struct { 1292typedef struct {
1293 const char *lhs; 1293 const char *lhs;
1294 size_t lhsLen; 1294 size_t lhsLen;
1295 const char *rhs; 1295 const char *rhs;
1296 size_t rhsLen; 1296 size_t rhsLen;
1297 VarPatternFlags pflags; 1297 VarPatternFlags pflags;
1298} ModifyWord_SubstArgs; 1298} ModifyWord_SubstArgs;
1299 1299
1300/* Callback for ModifyWords to implement the :S,from,to, modifier. 1300/* Callback for ModifyWords to implement the :S,from,to, modifier.
1301 * Perform a string substitution on the given word. */ 1301 * Perform a string substitution on the given word. */
1302static void 1302static void
1303ModifyWord_Subst(const char *word, SepBuf *buf, void *data) 1303ModifyWord_Subst(const char *word, SepBuf *buf, void *data)
1304{ 1304{
1305 size_t wordLen = strlen(word); 1305 size_t wordLen = strlen(word);
1306 ModifyWord_SubstArgs *args = data; 1306 ModifyWord_SubstArgs *args = data;
1307 const VarPatternFlags pflags = args->pflags; 1307 const VarPatternFlags pflags = args->pflags;
1308 1308
1309 if ((pflags & VARP_SUB_ONE) && (pflags & VARP_SUB_MATCHED)) 1309 if ((pflags & VARP_SUB_ONE) && (pflags & VARP_SUB_MATCHED))
1310 goto nosub; 1310 goto nosub;
1311 1311
1312 if (args->pflags & VARP_ANCHOR_START) { 1312 if (args->pflags & VARP_ANCHOR_START) {
1313 if (wordLen < args->lhsLen || 1313 if (wordLen < args->lhsLen ||
1314 memcmp(word, args->lhs, args->lhsLen) != 0) 1314 memcmp(word, args->lhs, args->lhsLen) != 0)
1315 goto nosub; 1315 goto nosub;
1316 1316
1317 if (args->pflags & VARP_ANCHOR_END) { 1317 if (args->pflags & VARP_ANCHOR_END) {
1318 if (wordLen != args->lhsLen) 1318 if (wordLen != args->lhsLen)
1319 goto nosub; 1319 goto nosub;
1320 1320
1321 SepBuf_AddBytes(buf, args->rhs, args->rhsLen); 1321 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1322 args->pflags |= VARP_SUB_MATCHED; 1322 args->pflags |= VARP_SUB_MATCHED;
1323 } else { 1323 } else {
1324 SepBuf_AddBytes(buf, args->rhs, args->rhsLen); 1324 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1325 SepBuf_AddBytes(buf, word + args->lhsLen, wordLen - args->lhsLen); 1325 SepBuf_AddBytes(buf, word + args->lhsLen, wordLen - args->lhsLen);
1326 args->pflags |= VARP_SUB_MATCHED; 1326 args->pflags |= VARP_SUB_MATCHED;
1327 } 1327 }
1328 return; 1328 return;
1329 } 1329 }
1330 1330
1331 if (args->pflags & VARP_ANCHOR_END) { 1331 if (args->pflags & VARP_ANCHOR_END) {
1332 if (wordLen < args->lhsLen) 1332 if (wordLen < args->lhsLen)
1333 goto nosub; 1333 goto nosub;
1334 1334
1335 const char *start = word + (wordLen - args->lhsLen); 1335 const char *start = word + (wordLen - args->lhsLen);
1336 if (memcmp(start, args->lhs, args->lhsLen) != 0) 1336 if (memcmp(start, args->lhs, args->lhsLen) != 0)
1337 goto nosub; 1337 goto nosub;
1338 1338
1339 SepBuf_AddBytesBetween(buf, word, start); 1339 SepBuf_AddBytesBetween(buf, word, start);
1340 SepBuf_AddBytes(buf, args->rhs, args->rhsLen); 1340 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1341 args->pflags |= VARP_SUB_MATCHED; 1341 args->pflags |= VARP_SUB_MATCHED;
1342 return; 1342 return;
1343 } 1343 }
1344 1344
1345 /* unanchored */ 1345 /* unanchored */
1346 const char *match; 1346 const char *match;
1347 while ((match = Str_FindSubstring(word, args->lhs)) != NULL) { 1347 while ((match = Str_FindSubstring(word, args->lhs)) != NULL) {
1348 SepBuf_AddBytesBetween(buf, word, match); 1348 SepBuf_AddBytesBetween(buf, word, match);
1349 SepBuf_AddBytes(buf, args->rhs, args->rhsLen); 1349 SepBuf_AddBytes(buf, args->rhs, args->rhsLen);
1350 args->pflags |= VARP_SUB_MATCHED; 1350 args->pflags |= VARP_SUB_MATCHED;
1351 wordLen -= (match - word) + args->lhsLen; 1351 wordLen -= (match - word) + args->lhsLen;
1352 word += (match - word) + args->lhsLen; 1352 word += (match - word) + args->lhsLen;
1353 if (wordLen == 0 || !(args->pflags & VARP_SUB_GLOBAL)) 1353 if (wordLen == 0 || !(args->pflags & VARP_SUB_GLOBAL))
1354 break; 1354 break;
1355 } 1355 }
1356nosub: 1356nosub:
1357 SepBuf_AddBytes(buf, word, wordLen); 1357 SepBuf_AddBytes(buf, word, wordLen);
1358} 1358}
1359 1359
1360#ifndef NO_REGEX 1360#ifndef NO_REGEX
1361/*- 1361/*-
1362 *----------------------------------------------------------------------- 1362 *-----------------------------------------------------------------------
1363 * VarREError -- 1363 * VarREError --
1364 * Print the error caused by a regcomp or regexec call. 1364 * Print the error caused by a regcomp or regexec call.
1365 * 1365 *
1366 * Side Effects: 1366 * Side Effects:
1367 * An error gets printed. 1367 * An error gets printed.
1368 * 1368 *
1369 *----------------------------------------------------------------------- 1369 *-----------------------------------------------------------------------
1370 */ 1370 */
1371static void 1371static void
1372VarREError(int reerr, regex_t *pat, const char *str) 1372VarREError(int reerr, regex_t *pat, const char *str)
1373{ 1373{
1374 char *errbuf; 1374 char *errbuf;
1375 int errlen; 1375 int errlen;
1376 1376
1377 errlen = regerror(reerr, pat, 0, 0); 1377 errlen = regerror(reerr, pat, 0, 0);
1378 errbuf = bmake_malloc(errlen); 1378 errbuf = bmake_malloc(errlen);
1379 regerror(reerr, pat, errbuf, errlen); 1379 regerror(reerr, pat, errbuf, errlen);
1380 Error("%s: %s", str, errbuf); 1380 Error("%s: %s", str, errbuf);
1381 free(errbuf); 1381 free(errbuf);
1382} 1382}
1383 1383
1384typedef struct { 1384typedef struct {
1385 regex_t re; 1385 regex_t re;
1386 int nsub; 1386 int nsub;
1387 char *replace; 1387 char *replace;
1388 VarPatternFlags pflags; 1388 VarPatternFlags pflags;
1389} ModifyWord_SubstRegexArgs; 1389} ModifyWord_SubstRegexArgs;
1390 1390
1391/* Callback for ModifyWords to implement the :C/from/to/ modifier. 1391/* Callback for ModifyWords to implement the :C/from/to/ modifier.
1392 * Perform a regex substitution on the given word. */ 1392 * Perform a regex substitution on the given word. */
1393static void 1393static void
1394ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data) 1394ModifyWord_SubstRegex(const char *word, SepBuf *buf, void *data)
1395{ 1395{
1396 ModifyWord_SubstRegexArgs *args = data; 1396 ModifyWord_SubstRegexArgs *args = data;
1397 int xrv; 1397 int xrv;
1398 const char *wp = word; 1398 const char *wp = word;
1399 char *rp; 1399 char *rp;
1400 int flags = 0; 1400 int flags = 0;
1401 regmatch_t m[10]; 1401 regmatch_t m[10];
1402 1402
1403 if ((args->pflags & VARP_SUB_ONE) && (args->pflags & VARP_SUB_MATCHED)) 1403 if ((args->pflags & VARP_SUB_ONE) && (args->pflags & VARP_SUB_MATCHED))
1404 goto nosub; 1404 goto nosub;
1405 1405
1406tryagain: 1406tryagain:
1407 xrv = regexec(&args->re, wp, args->nsub, m, flags); 1407 xrv = regexec(&args->re, wp, args->nsub, m, flags);
1408 1408
1409 switch (xrv) { 1409 switch (xrv) {
1410 case 0: 1410 case 0:
1411 args->pflags |= VARP_SUB_MATCHED; 1411 args->pflags |= VARP_SUB_MATCHED;
1412 SepBuf_AddBytes(buf, wp, m[0].rm_so); 1412 SepBuf_AddBytes(buf, wp, m[0].rm_so);
1413 1413
1414 for (rp = args->replace; *rp; rp++) { 1414 for (rp = args->replace; *rp; rp++) {
1415 if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) { 1415 if (*rp == '\\' && (rp[1] == '&' || rp[1] == '\\')) {
1416 SepBuf_AddBytes(buf, rp + 1, 1); 1416 SepBuf_AddBytes(buf, rp + 1, 1);
1417 rp++; 1417 rp++;
1418 } else if (*rp == '&' || 1418 } else if (*rp == '&' ||
1419 (*rp == '\\' && isdigit((unsigned char)rp[1]))) { 1419 (*rp == '\\' && isdigit((unsigned char)rp[1]))) {
1420 int n; 1420 int n;
1421 char errstr[3]; 1421 char errstr[3];
1422 1422
1423 if (*rp == '&') { 1423 if (*rp == '&') {
1424 n = 0; 1424 n = 0;
1425 errstr[0] = '&'; 1425 errstr[0] = '&';
1426 errstr[1] = '\0'; 1426 errstr[1] = '\0';
1427 } else { 1427 } else {
1428 n = rp[1] - '0'; 1428 n = rp[1] - '0';
1429 errstr[0] = '\\'; 1429 errstr[0] = '\\';
1430 errstr[1] = rp[1]; 1430 errstr[1] = rp[1];
1431 errstr[2] = '\0'; 1431 errstr[2] = '\0';
1432 rp++; 1432 rp++;
1433 } 1433 }
1434 1434
1435 if (n >= args->nsub) { 1435 if (n >= args->nsub) {
1436 Error("No subexpression %s", errstr); 1436 Error("No subexpression %s", errstr);
1437 } else if (m[n].rm_so == -1 && m[n].rm_eo == -1) { 1437 } else if (m[n].rm_so == -1 && m[n].rm_eo == -1) {
1438 Error("No match for subexpression %s", errstr); 1438 Error("No match for subexpression %s", errstr);
1439 } else { 1439 } else {
1440 SepBuf_AddBytesBetween(buf, wp + m[n].rm_so, 1440 SepBuf_AddBytesBetween(buf, wp + m[n].rm_so,
1441 wp + m[n].rm_eo); 1441 wp + m[n].rm_eo);
1442 } 1442 }
1443 1443
1444 } else { 1444 } else {
1445 SepBuf_AddBytes(buf, rp, 1); 1445 SepBuf_AddBytes(buf, rp, 1);
1446 } 1446 }
1447 } 1447 }
1448 wp += m[0].rm_eo; 1448 wp += m[0].rm_eo;
1449 if (args->pflags & VARP_SUB_GLOBAL) { 1449 if (args->pflags & VARP_SUB_GLOBAL) {
1450 flags |= REG_NOTBOL; 1450 flags |= REG_NOTBOL;
1451 if (m[0].rm_so == 0 && m[0].rm_eo == 0) { 1451 if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
1452 SepBuf_AddBytes(buf, wp, 1); 1452 SepBuf_AddBytes(buf, wp, 1);
1453 wp++; 1453 wp++;
1454 } 1454 }
1455 if (*wp) 1455 if (*wp)
1456 goto tryagain; 1456 goto tryagain;
1457 } 1457 }
1458 if (*wp) { 1458 if (*wp) {
1459 SepBuf_AddStr(buf, wp); 1459 SepBuf_AddStr(buf, wp);
1460 } 1460 }
1461 break; 1461 break;
1462 default: 1462 default:
1463 VarREError(xrv, &args->re, "Unexpected regex error"); 1463 VarREError(xrv, &args->re, "Unexpected regex error");
1464 /* fall through */ 1464 /* fall through */
1465 case REG_NOMATCH: 1465 case REG_NOMATCH:
1466 nosub: 1466 nosub:
1467 SepBuf_AddStr(buf, wp); 1467 SepBuf_AddStr(buf, wp);
1468 break; 1468 break;
1469 } 1469 }
1470} 1470}
1471#endif 1471#endif
1472 1472
1473 1473
1474typedef struct { 1474typedef struct {
1475 GNode *ctx; 1475 GNode *ctx;
1476 char *tvar; /* name of temporary variable */ 1476 char *tvar; /* name of temporary variable */
1477 char *str; /* string to expand */ 1477 char *str; /* string to expand */
1478 VarEvalFlags eflags; 1478 VarEvalFlags eflags;
1479} ModifyWord_LoopArgs; 1479} ModifyWord_LoopArgs;
1480 1480
1481/* Callback for ModifyWords to implement the :@var@...@ modifier of ODE make. */ 1481/* Callback for ModifyWords to implement the :@var@...@ modifier of ODE make. */
1482static void 1482static void
1483ModifyWord_Loop(const char *word, SepBuf *buf, void *data) 1483ModifyWord_Loop(const char *word, SepBuf *buf, void *data)
1484{ 1484{
1485 if (word[0] == '\0') 1485 if (word[0] == '\0')
1486 return; 1486 return;
1487 1487
1488 const ModifyWord_LoopArgs *args = data; 1488 const ModifyWord_LoopArgs *args = data;
1489 Var_Set_with_flags(args->tvar, word, args->ctx, VAR_NO_EXPORT); 1489 Var_Set_with_flags(args->tvar, word, args->ctx, VAR_NO_EXPORT);
1490 char *s = Var_Subst(NULL, args->str, args->ctx, args->eflags); 1490 char *s = Var_Subst(NULL, args->str, args->ctx, args->eflags);
1491 if (DEBUG(VAR)) { 1491 if (DEBUG(VAR)) {
1492 fprintf(debug_file, 1492 fprintf(debug_file,
1493 "ModifyWord_Loop: in \"%s\", replace \"%s\" with \"%s\" " 1493 "ModifyWord_Loop: in \"%s\", replace \"%s\" with \"%s\" "
1494 "to \"%s\"\n", 1494 "to \"%s\"\n",
1495 word, args->tvar, args->str, s ? s : "(null)"); 1495 word, args->tvar, args->str, s ? s : "(null)");
1496 } 1496 }
1497 1497
1498 if (s != NULL && s[0] != '\0') { 1498 if (s != NULL && s[0] != '\0') {
1499 if (s[0] == '\n' || (buf->buf.count > 0 && 1499 if (s[0] == '\n' || (buf->buf.count > 0 &&
1500 buf->buf.buffer[buf->buf.count - 1] == '\n')) 1500 buf->buf.buffer[buf->buf.count - 1] == '\n'))
1501 buf->needSep = FALSE; 1501 buf->needSep = FALSE;
1502 SepBuf_AddStr(buf, s); 1502 SepBuf_AddStr(buf, s);
1503 } 1503 }
1504 free(s); 1504 free(s);
1505} 1505}
1506 1506
1507 1507
1508/*- 1508/*-
1509 * Implements the :[first..last] modifier. 1509 * Implements the :[first..last] modifier.
1510 * This is a special case of ModifyWords since we want to be able 1510 * This is a special case of ModifyWords since we want to be able
1511 * to scan the list backwards if first > last. 1511 * to scan the list backwards if first > last.
1512 */ 1512 */
1513static char * 1513static char *
1514VarSelectWords(Byte sep, Boolean oneBigWord, const char *str, int first, 1514VarSelectWords(Byte sep, Boolean oneBigWord, const char *str, int first,
1515 int last) 1515 int last)
1516{ 1516{
1517 SepBuf buf; 1517 SepBuf buf;
1518 char **av; /* word list */ 1518 char **av; /* word list */
1519 char *as; /* word list memory */ 1519 char *as; /* word list memory */
1520 int ac, i; 1520 int ac, i;
1521 int start, end, step; 1521 int start, end, step;
1522 1522
1523 SepBuf_Init(&buf, sep); 1523 SepBuf_Init(&buf, sep);
1524 1524
1525 if (oneBigWord) { 1525 if (oneBigWord) {
1526 /* fake what brk_string() would do if there were only one word */ 1526 /* fake what brk_string() would do if there were only one word */
1527 ac = 1; 1527 ac = 1;
1528 av = bmake_malloc((ac + 1) * sizeof(char *)); 1528 av = bmake_malloc((ac + 1) * sizeof(char *));
1529 as = bmake_strdup(str); 1529 as = bmake_strdup(str);
1530 av[0] = as; 1530 av[0] = as;
1531 av[1] = NULL; 1531 av[1] = NULL;
1532 } else { 1532 } else {
1533 av = brk_string(str, &ac, FALSE, &as); 1533 av = brk_string(str, &ac, FALSE, &as);
1534 } 1534 }
1535 1535
1536 /* 1536 /*
1537 * Now sanitize seldata. 1537 * Now sanitize seldata.
1538 * If seldata->start or seldata->end are negative, convert them to 1538 * If seldata->start or seldata->end are negative, convert them to
1539 * the positive equivalents (-1 gets converted to argc, -2 gets 1539 * the positive equivalents (-1 gets converted to argc, -2 gets
1540 * converted to (argc-1), etc.). 1540 * converted to (argc-1), etc.).
1541 */ 1541 */
1542 if (first < 0) 1542 if (first < 0)
1543 first += ac + 1; 1543 first += ac + 1;
1544 if (last < 0) 1544 if (last < 0)
1545 last += ac + 1; 1545 last += ac + 1;
1546 1546
1547 /* 1547 /*
1548 * We avoid scanning more of the list than we need to. 1548 * We avoid scanning more of the list than we need to.
1549 */ 1549 */
1550 if (first > last) { 1550 if (first > last) {
1551 start = MIN(ac, first) - 1; 1551 start = MIN(ac, first) - 1;
1552 end = MAX(0, last - 1); 1552 end = MAX(0, last - 1);
1553 step = -1; 1553 step = -1;
1554 } else { 1554 } else {
1555 start = MAX(0, first - 1); 1555 start = MAX(0, first - 1);
1556 end = MIN(ac, last); 1556 end = MIN(ac, last);
1557 step = 1; 1557 step = 1;
1558 } 1558 }
1559 1559
1560 for (i = start; (step < 0) == (i >= end); i += step) { 1560 for (i = start; (step < 0) == (i >= end); i += step) {
1561 SepBuf_AddStr(&buf, av[i]); 1561 SepBuf_AddStr(&buf, av[i]);
1562 SepBuf_Sep(&buf); 1562 SepBuf_Sep(&buf);
1563 } 1563 }
1564 1564
1565 free(as); 1565 free(as);
1566 free(av); 1566 free(av);
1567 1567
1568 return SepBuf_Destroy(&buf, FALSE); 1568 return SepBuf_Destroy(&buf, FALSE);
1569} 1569}
1570 1570
1571 1571
1572/* Callback for ModifyWords to implement the :tA modifier. 1572/* Callback for ModifyWords to implement the :tA modifier.
1573 * Replace each word with the result of realpath() if successful. */ 1573 * Replace each word with the result of realpath() if successful. */
1574static void 1574static void
1575ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED) 1575ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
1576{ 1576{
1577 struct stat st; 1577 struct stat st;
1578 char rbuf[MAXPATHLEN]; 1578 char rbuf[MAXPATHLEN];
1579 1579
1580 const char *rp = cached_realpath(word, rbuf); 1580 const char *rp = cached_realpath(word, rbuf);
1581 if (rp != NULL && *rp == '/' && stat(rp, &st) == 0) 1581 if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
1582 word = rp; 1582 word = rp;
1583 1583
1584 SepBuf_AddStr(buf, word); 1584 SepBuf_AddStr(buf, word);
1585} 1585}
1586 1586
1587/*- 1587/*-
1588 *----------------------------------------------------------------------- 1588 *-----------------------------------------------------------------------
1589 * Modify each of the words of the passed string using the given function. 1589 * Modify each of the words of the passed string using the given function.
1590 * 1590 *
1591 * Input: 1591 * Input:
1592 * str String whose words should be modified 1592 * str String whose words should be modified
1593 * modifyWord Function that modifies a single word 1593 * modifyWord Function that modifies a single word
1594 * data Custom data for modifyWord 1594 * data Custom data for modifyWord
1595 * 1595 *
1596 * Results: 1596 * Results:
1597 * A string of all the words modified appropriately. 1597 * A string of all the words modified appropriately.
1598 *----------------------------------------------------------------------- 1598 *-----------------------------------------------------------------------
1599 */ 1599 */
1600static char * 1600static char *
1601ModifyWords(GNode *ctx, Byte sep, Boolean oneBigWord, 1601ModifyWords(GNode *ctx, Byte sep, Boolean oneBigWord,
1602 const char *str, ModifyWordsCallback modifyWord, void *data) 1602 const char *str, ModifyWordsCallback modifyWord, void *data)
1603{ 1603{
1604 if (oneBigWord) { 1604 if (oneBigWord) {
1605 SepBuf result; 1605 SepBuf result;
1606 SepBuf_Init(&result, sep); 1606 SepBuf_Init(&result, sep);
1607 modifyWord(str, &result, data); 1607 modifyWord(str, &result, data);
1608 return SepBuf_Destroy(&result, FALSE); 1608 return SepBuf_Destroy(&result, FALSE);
1609 } 1609 }
1610 1610
1611 SepBuf result; 1611 SepBuf result;
1612 char **av; /* word list */ 1612 char **av; /* word list */
1613 char *as; /* word list memory */ 1613 char *as; /* word list memory */
1614 int ac, i; 1614 int ac, i;
1615 1615
1616 SepBuf_Init(&result, sep); 1616 SepBuf_Init(&result, sep);
1617 1617
1618 av = brk_string(str, &ac, FALSE, &as); 1618 av = brk_string(str, &ac, FALSE, &as);
1619 1619
1620 if (DEBUG(VAR)) { 1620 if (DEBUG(VAR)) {
1621 fprintf(debug_file, "ModifyWords: split \"%s\" into %d words\n", 1621 fprintf(debug_file, "ModifyWords: split \"%s\" into %d words\n",
1622 str, ac); 1622 str, ac);
1623 } 1623 }
1624 1624
1625 for (i = 0; i < ac; i++) { 1625 for (i = 0; i < ac; i++) {
1626 size_t orig_count = result.buf.count; 1626 size_t orig_count = result.buf.count;
1627 modifyWord(av[i], &result, data); 1627 modifyWord(av[i], &result, data);
1628 size_t count = result.buf.count; 1628 size_t count = result.buf.count;
1629 if (count != orig_count) 1629 if (count != orig_count)
1630 SepBuf_Sep(&result); 1630 SepBuf_Sep(&result);
1631 } 1631 }
1632 1632
1633 free(as); 1633 free(as);
1634 free(av); 1634 free(av);
1635 1635
1636 return SepBuf_Destroy(&result, FALSE); 1636 return SepBuf_Destroy(&result, FALSE);
1637} 1637}
1638 1638
1639 1639
1640static int 1640static int
1641VarWordCompare(const void *a, const void *b) 1641VarWordCompare(const void *a, const void *b)
1642{ 1642{
1643 int r = strcmp(*(const char * const *)a, *(const char * const *)b); 1643 int r = strcmp(*(const char * const *)a, *(const char * const *)b);
1644 return r; 1644 return r;
1645} 1645}
1646 1646
1647static int 1647static int
1648VarWordCompareReverse(const void *a, const void *b) 1648VarWordCompareReverse(const void *a, const void *b)
1649{ 1649{
1650 int r = strcmp(*(const char * const *)b, *(const char * const *)a); 1650 int r = strcmp(*(const char * const *)b, *(const char * const *)a);
1651 return r; 1651 return r;
1652} 1652}
1653 1653
1654/*- 1654/*-
1655 *----------------------------------------------------------------------- 1655 *-----------------------------------------------------------------------
1656 * VarOrder -- 1656 * VarOrder --
1657 * Order the words in the string. 1657 * Order the words in the string.
1658 * 1658 *
1659 * Input: 1659 * Input:
1660 * str String whose words should be sorted. 1660 * str String whose words should be sorted.
1661 * otype How to order: s - sort, x - random. 1661 * otype How to order: s - sort, x - random.
1662 * 1662 *
1663 * Results: 1663 * Results:
1664 * A string containing the words ordered. 1664 * A string containing the words ordered.
1665 * 1665 *
1666 * Side Effects: 1666 * Side Effects:
1667 * None. 1667 * None.
1668 * 1668 *
1669 *----------------------------------------------------------------------- 1669 *-----------------------------------------------------------------------
1670 */ 1670 */
1671static char * 1671static char *
1672VarOrder(const char *str, const char otype) 1672VarOrder(const char *str, const char otype)
1673{ 1673{
1674 Buffer buf; /* Buffer for the new string */ 1674 Buffer buf; /* Buffer for the new string */
1675 char **av; /* word list */ 1675 char **av; /* word list */
1676 char *as; /* word list memory */ 1676 char *as; /* word list memory */
1677 int ac, i; 1677 int ac, i;
1678 1678
1679 Buf_Init(&buf, 0); 1679 Buf_Init(&buf, 0);
1680 1680
1681 av = brk_string(str, &ac, FALSE, &as); 1681 av = brk_string(str, &ac, FALSE, &as);
1682 1682
1683 if (ac > 0) { 1683 if (ac > 0) {
1684 switch (otype) { 1684 switch (otype) {
1685 case 'r': /* reverse sort alphabetically */ 1685 case 'r': /* reverse sort alphabetically */
1686 qsort(av, ac, sizeof(char *), VarWordCompareReverse); 1686 qsort(av, ac, sizeof(char *), VarWordCompareReverse);
1687 break; 1687 break;
1688 case 's': /* sort alphabetically */ 1688 case 's': /* sort alphabetically */
1689 qsort(av, ac, sizeof(char *), VarWordCompare); 1689 qsort(av, ac, sizeof(char *), VarWordCompare);
1690 break; 1690 break;
1691 case 'x': /* randomize */ 1691 case 'x': /* randomize */
1692 /* 1692 /*
1693 * We will use [ac..2] range for mod factors. This will produce 1693 * We will use [ac..2] range for mod factors. This will produce
1694 * random numbers in [(ac-1)..0] interval, and minimal 1694 * random numbers in [(ac-1)..0] interval, and minimal
1695 * reasonable value for mod factor is 2 (the mod 1 will produce 1695 * reasonable value for mod factor is 2 (the mod 1 will produce
1696 * 0 with probability 1). 1696 * 0 with probability 1).
1697 */ 1697 */
1698 for (i = ac - 1; i > 0; i--) { 1698 for (i = ac - 1; i > 0; i--) {
1699 int rndidx = random() % (i + 1); 1699 int rndidx = random() % (i + 1);
1700 char *t = av[i]; 1700 char *t = av[i];
1701 av[i] = av[rndidx]; 1701 av[i] = av[rndidx];
1702 av[rndidx] = t; 1702 av[rndidx] = t;
1703 } 1703 }
1704 } 1704 }
1705 } 1705 }
1706 1706
1707 for (i = 0; i < ac; i++) { 1707 for (i = 0; i < ac; i++) {
1708 if (i != 0) 1708 if (i != 0)
1709 Buf_AddByte(&buf, ' '); 1709 Buf_AddByte(&buf, ' ');
1710 Buf_AddStr(&buf, av[i]); 1710 Buf_AddStr(&buf, av[i]);
1711 } 1711 }
1712 1712
1713 free(as); 1713 free(as);
1714 free(av); 1714 free(av);
1715 1715
1716 return Buf_Destroy(&buf, FALSE); 1716 return Buf_Destroy(&buf, FALSE);
1717} 1717}
1718 1718
1719 1719
1720/* Remove adjacent duplicate words. */ 1720/* Remove adjacent duplicate words. */
1721static char * 1721static char *
1722VarUniq(const char *str) 1722VarUniq(const char *str)
1723{ 1723{
1724 Buffer buf; /* Buffer for new string */ 1724 Buffer buf; /* Buffer for new string */
1725 char **av; /* List of words to affect */ 1725 char **av; /* List of words to affect */
1726 char *as; /* Word list memory */ 1726 char *as; /* Word list memory */
1727 int ac, i, j; 1727 int ac, i, j;
1728 1728
1729 Buf_Init(&buf, 0); 1729 Buf_Init(&buf, 0);
1730 av = brk_string(str, &ac, FALSE, &as); 1730 av = brk_string(str, &ac, FALSE, &as);
1731 1731
1732 if (ac > 1) { 1732 if (ac > 1) {
1733 for (j = 0, i = 1; i < ac; i++) 1733 for (j = 0, i = 1; i < ac; i++)
1734 if (strcmp(av[i], av[j]) != 0 && (++j != i)) 1734 if (strcmp(av[i], av[j]) != 0 && (++j != i))
1735 av[j] = av[i]; 1735 av[j] = av[i];
1736 ac = j + 1; 1736 ac = j + 1;
1737 } 1737 }
1738 1738
1739 for (i = 0; i < ac; i++) { 1739 for (i = 0; i < ac; i++) {
1740 if (i != 0) 1740 if (i != 0)
1741 Buf_AddByte(&buf, ' '); 1741 Buf_AddByte(&buf, ' ');
1742 Buf_AddStr(&buf, av[i]); 1742 Buf_AddStr(&buf, av[i]);
1743 } 1743 }
1744 1744
1745 free(as); 1745 free(as);
1746 free(av); 1746 free(av);
1747 1747
1748 return Buf_Destroy(&buf, FALSE); 1748 return Buf_Destroy(&buf, FALSE);
1749} 1749}
1750 1750
1751/*- 1751/*-
1752 *----------------------------------------------------------------------- 1752 *-----------------------------------------------------------------------
1753 * VarRange -- 1753 * VarRange --
1754 * Return an integer sequence 1754 * Return an integer sequence
1755 * 1755 *
1756 * Input: 1756 * Input:
1757 * str String whose words provide default range 1757 * str String whose words provide default range
1758 * ac range length, if 0 use str words 1758 * ac range length, if 0 use str words
1759 * 1759 *
1760 * Side Effects: 1760 * Side Effects:
1761 * None. 1761 * None.
1762 * 1762 *
1763 *----------------------------------------------------------------------- 1763 *-----------------------------------------------------------------------
1764 */ 1764 */
1765static char * 1765static char *
1766VarRange(const char *str, int ac) 1766VarRange(const char *str, int ac)
1767{ 1767{
1768 Buffer buf; /* Buffer for new string */ 1768 Buffer buf; /* Buffer for new string */
1769 char **av; /* List of words to affect */ 1769 char **av; /* List of words to affect */
1770 char *as; /* Word list memory */ 1770 char *as; /* Word list memory */
1771 int i; 1771 int i;
1772 1772
1773 Buf_Init(&buf, 0); 1773 Buf_Init(&buf, 0);
1774 if (ac > 0) { 1774 if (ac > 0) {
1775 as = NULL; 1775 as = NULL;
1776 av = NULL; 1776 av = NULL;
1777 } else { 1777 } else {
1778 av = brk_string(str, &ac, FALSE, &as); 1778 av = brk_string(str, &ac, FALSE, &as);
1779 } 1779 }
1780 for (i = 0; i < ac; i++) { 1780 for (i = 0; i < ac; i++) {
1781 if (i != 0) 1781 if (i != 0)
1782 Buf_AddByte(&buf, ' '); 1782 Buf_AddByte(&buf, ' ');
1783 Buf_AddInt(&buf, 1 + i); 1783 Buf_AddInt(&buf, 1 + i);
1784 } 1784 }
1785 1785
1786 free(as); 1786 free(as);
1787 free(av); 1787 free(av);
1788 1788
1789 return Buf_Destroy(&buf, FALSE); 1789 return Buf_Destroy(&buf, FALSE);
1790} 1790}
1791 1791
1792 1792
1793/*- 1793/*-
1794 * Parse a text part of a modifier such as the "from" and "to" in :S/from/to/ 1794 * Parse a text part of a modifier such as the "from" and "to" in :S/from/to/
1795 * or the :@ modifier, until the next unescaped delimiter. The delimiter, as 1795 * or the :@ modifier, until the next unescaped delimiter. The delimiter, as
1796 * well as the backslash or the dollar, can be escaped with a backslash. 1796 * well as the backslash or the dollar, can be escaped with a backslash.
1797 * 1797 *
1798 * Return the parsed (and possibly expanded) string, or NULL if no delimiter 1798 * Return the parsed (and possibly expanded) string, or NULL if no delimiter
1799 * was found. 1799 * was found.
1800 * 1800 *
1801 * Nested variables in the text are expanded unless VARE_NOSUBST is set. 1801 * Nested variables in the text are expanded unless VARE_NOSUBST is set.
1802 * 1802 *
1803 * If out_length is specified, store the length of the returned string, just 1803 * If out_length is specified, store the length of the returned string, just
1804 * to save another strlen call. 1804 * to save another strlen call.
1805 * 1805 *
1806 * If out_pflags is specified and the last character of the pattern is a $, 1806 * If out_pflags is specified and the last character of the pattern is a $,
1807 * set the VARP_ANCHOR_END bit of mpflags (for the first part of the :S 1807 * set the VARP_ANCHOR_END bit of mpflags (for the first part of the :S
1808 * modifier). 1808 * modifier).
1809 * 1809 *
1810 * If subst is specified, handle escaped ampersands and replace unescaped 1810 * If subst is specified, handle escaped ampersands and replace unescaped
1811 * ampersands with the lhs of the pattern (for the second part of the :S 1811 * ampersands with the lhs of the pattern (for the second part of the :S
1812 * modifier). 1812 * modifier).
1813 */ 1813 */
1814static char * 1814static char *
1815ParseModifierPart(const char **tstr, int delim, VarEvalFlags eflags, 1815ParseModifierPart(const char **tstr, int delim, VarEvalFlags eflags,
1816 GNode *ctxt, size_t *out_length, 1816 GNode *ctxt, size_t *out_length,
1817 VarPatternFlags *out_pflags, ModifyWord_SubstArgs *subst) 1817 VarPatternFlags *out_pflags, ModifyWord_SubstArgs *subst)
1818{ 1818{
1819 const char *cp; 1819 const char *cp;
1820 char *rstr; 1820 char *rstr;
1821 Buffer buf; 1821 Buffer buf;
1822 VarEvalFlags errnum = eflags & VARE_UNDEFERR; 1822 VarEvalFlags errnum = eflags & VARE_UNDEFERR;
1823 1823
1824 Buf_Init(&buf, 0); 1824 Buf_Init(&buf, 0);
1825 1825
1826 /* 1826 /*
1827 * Skim through until the matching delimiter is found; 1827 * Skim through until the matching delimiter is found;
1828 * pick up variable substitutions on the way. Also allow 1828 * pick up variable substitutions on the way. Also allow
1829 * backslashes to quote the delimiter, $, and \, but don't 1829 * backslashes to quote the delimiter, $, and \, but don't
1830 * touch other backslashes. 1830 * touch other backslashes.
1831 */ 1831 */
1832 for (cp = *tstr; *cp != '\0' && *cp != delim; cp++) { 1832 for (cp = *tstr; *cp != '\0' && *cp != delim; cp++) {
1833 Boolean is_escaped = cp[0] == '\\' && ( 1833 Boolean is_escaped = cp[0] == '\\' && (
1834 cp[1] == delim || cp[1] == '\\' || cp[1] == '$' || 1834 cp[1] == delim || cp[1] == '\\' || cp[1] == '$' ||
1835 (cp[1] == '&' && subst != NULL)); 1835 (cp[1] == '&' && subst != NULL));
1836 if (is_escaped) { 1836 if (is_escaped) {
1837 Buf_AddByte(&buf, cp[1]); 1837 Buf_AddByte(&buf, cp[1]);
1838 cp++; 1838 cp++;
1839 } else if (*cp == '$') { 1839 } else if (*cp == '$') {
1840 if (cp[1] == delim) { /* Unescaped $ at end of pattern */ 1840 if (cp[1] == delim) { /* Unescaped $ at end of pattern */
1841 if (out_pflags != NULL) 1841 if (out_pflags != NULL)
1842 *out_pflags |= VARP_ANCHOR_END; 1842 *out_pflags |= VARP_ANCHOR_END;
1843 else 1843 else
1844 Buf_AddByte(&buf, *cp); 1844 Buf_AddByte(&buf, *cp);
1845 } else { 1845 } else {
1846 if (eflags & VARE_WANTRES) { 1846 if (eflags & VARE_WANTRES) {
1847 const char *cp2; 1847 const char *cp2;
1848 int len; 1848 int len;
1849 void *freeIt; 1849 void *freeIt;
1850 1850
1851 /* 1851 /*
1852 * If unescaped dollar sign not before the 1852 * If unescaped dollar sign not before the
1853 * delimiter, assume it's a variable 1853 * delimiter, assume it's a variable
1854 * substitution and recurse. 1854 * substitution and recurse.
1855 */ 1855 */
1856 cp2 = Var_Parse(cp, ctxt, errnum | (eflags & VARE_WANTRES), 1856 cp2 = Var_Parse(cp, ctxt, errnum | (eflags & VARE_WANTRES),
1857 &len, &freeIt); 1857 &len, &freeIt);
1858 Buf_AddStr(&buf, cp2); 1858 Buf_AddStr(&buf, cp2);
1859 free(freeIt); 1859 free(freeIt);
1860 cp += len - 1; 1860 cp += len - 1;
1861 } else { 1861 } else {
1862 const char *cp2 = &cp[1]; 1862 const char *cp2 = &cp[1];
1863 1863
1864 if (*cp2 == PROPEN || *cp2 == BROPEN) { 1864 if (*cp2 == PROPEN || *cp2 == BROPEN) {
1865 /* 1865 /*
1866 * Find the end of this variable reference 1866 * Find the end of this variable reference
1867 * and suck it in without further ado. 1867 * and suck it in without further ado.
1868 * It will be interpreted later. 1868 * It will be interpreted later.
1869 */ 1869 */
1870 int have = *cp2; 1870 int have = *cp2;
1871 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE; 1871 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
1872 int depth = 1; 1872 int depth = 1;
1873 1873
1874 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) { 1874 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
1875 if (cp2[-1] != '\\') { 1875 if (cp2[-1] != '\\') {
1876 if (*cp2 == have) 1876 if (*cp2 == have)
1877 ++depth; 1877 ++depth;
1878 if (*cp2 == want) 1878 if (*cp2 == want)
1879 --depth; 1879 --depth;
1880 } 1880 }
1881 } 1881 }
1882 Buf_AddBytesBetween(&buf, cp, cp2); 1882 Buf_AddBytesBetween(&buf, cp, cp2);
1883 cp = --cp2; 1883 cp = --cp2;
1884 } else 1884 } else
1885 Buf_AddByte(&buf, *cp); 1885 Buf_AddByte(&buf, *cp);
1886 } 1886 }
1887 } 1887 }
1888 } else if (subst != NULL && *cp == '&') 1888 } else if (subst != NULL && *cp == '&')
1889 Buf_AddBytes(&buf, subst->lhsLen, subst->lhs); 1889 Buf_AddBytes(&buf, subst->lhsLen, subst->lhs);
1890 else 1890 else
1891 Buf_AddByte(&buf, *cp); 1891 Buf_AddByte(&buf, *cp);
1892 } 1892 }
1893 1893
1894 if (*cp != delim) { 1894 if (*cp != delim) {
1895 *tstr = cp; 1895 *tstr = cp;
1896 return NULL; 1896 return NULL;
1897 } 1897 }
1898 1898
1899 *tstr = ++cp; 1899 *tstr = ++cp;
1900 if (out_length != NULL) 1900 if (out_length != NULL)
1901 *out_length = Buf_Size(&buf); 1901 *out_length = Buf_Size(&buf);
1902 rstr = Buf_Destroy(&buf, FALSE); 1902 rstr = Buf_Destroy(&buf, FALSE);
1903 if (DEBUG(VAR)) 1903 if (DEBUG(VAR))
1904 fprintf(debug_file, "Modifier part: \"%s\"\n", rstr); 1904 fprintf(debug_file, "Modifier part: \"%s\"\n", rstr);
1905 return rstr; 1905 return rstr;
1906} 1906}
1907 1907
1908/*- 1908/*-
1909 *----------------------------------------------------------------------- 1909 *-----------------------------------------------------------------------
1910 * VarQuote -- 1910 * VarQuote --
1911 * Quote shell meta-characters and space characters in the string 1911 * Quote shell meta-characters and space characters in the string
1912 * if quoteDollar is set, also quote and double any '$' characters. 1912 * if quoteDollar is set, also quote and double any '$' characters.
1913 * 1913 *
1914 * Results: 1914 * Results:
1915 * The quoted string 1915 * The quoted string
1916 * 1916 *
1917 * Side Effects: 1917 * Side Effects:
1918 * None. 1918 * None.
1919 * 1919 *
1920 *----------------------------------------------------------------------- 1920 *-----------------------------------------------------------------------
1921 */ 1921 */
1922static char * 1922static char *
1923VarQuote(char *str, Boolean quoteDollar) 1923VarQuote(char *str, Boolean quoteDollar)
1924{ 1924{
1925 Buffer buf; 1925 Buffer buf;
1926 Buf_Init(&buf, 0); 1926 Buf_Init(&buf, 0);
1927 1927
1928 for (; *str != '\0'; str++) { 1928 for (; *str != '\0'; str++) {
1929 if (*str == '\n') { 1929 if (*str == '\n') {
1930 const char *newline = Shell_GetNewline(); 1930 const char *newline = Shell_GetNewline();
1931 if (newline == NULL) 1931 if (newline == NULL)
1932 newline = "\\\n"; 1932 newline = "\\\n";
1933 Buf_AddStr(&buf, newline); 1933 Buf_AddStr(&buf, newline);
1934 continue; 1934 continue;
1935 } 1935 }
1936 if (isspace((unsigned char)*str) || ismeta((unsigned char)*str)) 1936 if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
1937 Buf_AddByte(&buf, '\\'); 1937 Buf_AddByte(&buf, '\\');
1938 Buf_AddByte(&buf, *str); 1938 Buf_AddByte(&buf, *str);
1939 if (quoteDollar && *str == '$') 1939 if (quoteDollar && *str == '$')
1940 Buf_AddStr(&buf, "\\$"); 1940 Buf_AddStr(&buf, "\\$");
1941 } 1941 }
1942 1942
1943 str = Buf_Destroy(&buf, FALSE); 1943 str = Buf_Destroy(&buf, FALSE);
1944 if (DEBUG(VAR)) 1944 if (DEBUG(VAR))
1945 fprintf(debug_file, "QuoteMeta: [%s]\n", str); 1945 fprintf(debug_file, "QuoteMeta: [%s]\n", str);
1946 return str; 1946 return str;
1947} 1947}
1948 1948
1949/*- 1949/*-
1950 *----------------------------------------------------------------------- 1950 *-----------------------------------------------------------------------
1951 * VarHash -- 1951 * VarHash --
1952 * Hash the string using the MurmurHash3 algorithm. 1952 * Hash the string using the MurmurHash3 algorithm.
1953 * Output is computed using 32bit Little Endian arithmetic. 1953 * Output is computed using 32bit Little Endian arithmetic.
1954 * 1954 *
1955 * Input: 1955 * Input:
1956 * str String to modify 1956 * str String to modify
1957 * 1957 *
1958 * Results: 1958 * Results:
1959 * Hash value of str, encoded as 8 hex digits. 1959 * Hash value of str, encoded as 8 hex digits.
1960 * 1960 *
1961 * Side Effects: 1961 * Side Effects:
1962 * None. 1962 * None.
1963 * 1963 *
1964 *----------------------------------------------------------------------- 1964 *-----------------------------------------------------------------------
1965 */ 1965 */
1966static char * 1966static char *
1967VarHash(const char *str) 1967VarHash(const char *str)
1968{ 1968{
1969 static const char hexdigits[16] = "0123456789abcdef"; 1969 static const char hexdigits[16] = "0123456789abcdef";
1970 Buffer buf; 1970 Buffer buf;
1971 size_t len, len2; 1971 size_t len, len2;
1972 const unsigned char *ustr = (const unsigned char *)str; 1972 const unsigned char *ustr = (const unsigned char *)str;
1973 uint32_t h, k, c1, c2; 1973 uint32_t h, k, c1, c2;
1974 1974
1975 h = 0x971e137bU; 1975 h = 0x971e137bU;
1976 c1 = 0x95543787U; 1976 c1 = 0x95543787U;
1977 c2 = 0x2ad7eb25U; 1977 c2 = 0x2ad7eb25U;
1978 len2 = strlen(str); 1978 len2 = strlen(str);
1979 1979
1980 for (len = len2; len; ) { 1980 for (len = len2; len; ) {
1981 k = 0; 1981 k = 0;
1982 switch (len) { 1982 switch (len) {
1983 default: 1983 default:
1984 k = ((uint32_t)ustr[3] << 24) | 1984 k = ((uint32_t)ustr[3] << 24) |
1985 ((uint32_t)ustr[2] << 16) | 1985 ((uint32_t)ustr[2] << 16) |
1986 ((uint32_t)ustr[1] << 8) | 1986 ((uint32_t)ustr[1] << 8) |
1987 (uint32_t)ustr[0]; 1987 (uint32_t)ustr[0];
1988 len -= 4; 1988 len -= 4;
1989 ustr += 4; 1989 ustr += 4;
1990 break; 1990 break;
1991 case 3: 1991 case 3:
1992 k |= (uint32_t)ustr[2] << 16; 1992 k |= (uint32_t)ustr[2] << 16;
1993 /* FALLTHROUGH */ 1993 /* FALLTHROUGH */
1994 case 2: 1994 case 2:
1995 k |= (uint32_t)ustr[1] << 8; 1995 k |= (uint32_t)ustr[1] << 8;
1996 /* FALLTHROUGH */ 1996 /* FALLTHROUGH */
1997 case 1: 1997 case 1:
1998 k |= (uint32_t)ustr[0]; 1998 k |= (uint32_t)ustr[0];
1999 len = 0; 1999 len = 0;
2000 } 2000 }
2001 c1 = c1 * 5 + 0x7b7d159cU; 2001 c1 = c1 * 5 + 0x7b7d159cU;
2002 c2 = c2 * 5 + 0x6bce6396U; 2002 c2 = c2 * 5 + 0x6bce6396U;
2003 k *= c1; 2003 k *= c1;
2004 k = (k << 11) ^ (k >> 21); 2004 k = (k << 11) ^ (k >> 21);
2005 k *= c2; 2005 k *= c2;
2006 h = (h << 13) ^ (h >> 19); 2006 h = (h << 13) ^ (h >> 19);
2007 h = h * 5 + 0x52dce729U; 2007 h = h * 5 + 0x52dce729U;
2008 h ^= k; 2008 h ^= k;
2009 } 2009 }
2010 h ^= len2; 2010 h ^= len2;
2011 h *= 0x85ebca6b; 2011 h *= 0x85ebca6b;
2012 h ^= h >> 13; 2012 h ^= h >> 13;
2013 h *= 0xc2b2ae35; 2013 h *= 0xc2b2ae35;
2014 h ^= h >> 16; 2014 h ^= h >> 16;
2015 2015
2016 Buf_Init(&buf, 0); 2016 Buf_Init(&buf, 0);
2017 for (len = 0; len < 8; ++len) { 2017 for (len = 0; len < 8; ++len) {
2018 Buf_AddByte(&buf, hexdigits[h & 15]); 2018 Buf_AddByte(&buf, hexdigits[h & 15]);
2019 h >>= 4; 2019 h >>= 4;
2020 } 2020 }
2021 2021
2022 return Buf_Destroy(&buf, FALSE); 2022 return Buf_Destroy(&buf, FALSE);
2023} 2023}
2024 2024
2025static char * 2025static char *
2026VarStrftime(const char *fmt, int zulu, time_t utc) 2026VarStrftime(const char *fmt, int zulu, time_t utc)
2027{ 2027{
2028 char buf[BUFSIZ]; 2028 char buf[BUFSIZ];
2029 2029
2030 if (!utc) 2030 if (!utc)
2031 time(&utc); 2031 time(&utc);
2032 if (!*fmt) 2032 if (!*fmt)
2033 fmt = "%c"; 2033 fmt = "%c";
2034 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc)); 2034 strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2035 2035
2036 buf[sizeof(buf) - 1] = '\0'; 2036 buf[sizeof(buf) - 1] = '\0';
2037 return bmake_strdup(buf); 2037 return bmake_strdup(buf);
2038} 2038}
2039 2039
2040typedef struct { 2040typedef struct {