Home | History | Annotate | Line # | Download | only in make
for.c revision 1.144
      1 /*	$NetBSD: for.c,v 1.144 2021/06/25 16:10:07 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1992, The Regents of the University of California.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Handling of .for/.endfor loops in a makefile.
     34  *
     35  * For loops have the form:
     36  *
     37  *	.for <varname...> in <value...>
     38  *	# the body
     39  *	.endfor
     40  *
     41  * When a .for line is parsed, the following lines are copied to the body of
     42  * the .for loop, until the corresponding .endfor line is reached.  In this
     43  * phase, the body is not yet evaluated.  This also applies to any nested
     44  * .for loops.
     45  *
     46  * After reaching the .endfor, the values from the .for line are grouped
     47  * according to the number of variables.  For each such group, the unexpanded
     48  * body is scanned for variable expressions, and those that match the variable
     49  * names are replaced with expressions of the form ${:U...} or $(:U...).
     50  * After that, the body is treated like a file from an .include directive.
     51  *
     52  * Interface:
     53  *	For_Eval	Evaluate the loop in the passed line.
     54  *
     55  *	For_Run		Run accumulated loop
     56  */
     57 
     58 #include "make.h"
     59 
     60 /*	"@(#)for.c	8.1 (Berkeley) 6/6/93"	*/
     61 MAKE_RCSID("$NetBSD: for.c,v 1.144 2021/06/25 16:10:07 rillig Exp $");
     62 
     63 
     64 /* One of the variables to the left of the "in" in a .for loop. */
     65 typedef struct ForVar {
     66 	char *name;
     67 	size_t nameLen;
     68 } ForVar;
     69 
     70 typedef struct ForLoop {
     71 	Buffer body;		/* Unexpanded body of the loop */
     72 	Vector /* of ForVar */ vars; /* Iteration variables */
     73 	Words items;		/* Substitution items */
     74 	Buffer curBody;		/* Expanded body of the current iteration */
     75 	/* Is any of the names 1 character long? If so, when the variable
     76 	 * values are substituted, the parser must handle $V expressions as
     77 	 * well, not only ${V} and $(V). */
     78 	bool short_var;
     79 	unsigned int sub_next;	/* Where to continue iterating */
     80 } ForLoop;
     81 
     82 
     83 static ForLoop *accumFor;	/* Loop being accumulated */
     84 static int forLevel = 0;	/* Nesting level */
     85 
     86 
     87 static ForLoop *
     88 ForLoop_New(void)
     89 {
     90 	ForLoop *f = bmake_malloc(sizeof *f);
     91 
     92 	Buf_Init(&f->body);
     93 	Vector_Init(&f->vars, sizeof(ForVar));
     94 	f->items.words = NULL;
     95 	f->items.freeIt = NULL;
     96 	Buf_Init(&f->curBody);
     97 	f->short_var = false;
     98 	f->sub_next = 0;
     99 
    100 	return f;
    101 }
    102 
    103 static void
    104 ForLoop_Free(ForLoop *f)
    105 {
    106 	Buf_Done(&f->body);
    107 
    108 	while (f->vars.len > 0) {
    109 		ForVar *var = Vector_Pop(&f->vars);
    110 		free(var->name);
    111 	}
    112 	Vector_Done(&f->vars);
    113 
    114 	Words_Free(f->items);
    115 	Buf_Done(&f->curBody);
    116 
    117 	free(f);
    118 }
    119 
    120 static void
    121 ForLoop_AddVar(ForLoop *f, const char *name, size_t len)
    122 {
    123 	ForVar *var = Vector_Push(&f->vars);
    124 	var->name = bmake_strldup(name, len);
    125 	var->nameLen = len;
    126 }
    127 
    128 static bool
    129 ForLoop_ParseVarnames(ForLoop *f, const char **pp)
    130 {
    131 	const char *p = *pp;
    132 
    133 	for (;;) {
    134 		size_t len;
    135 
    136 		cpp_skip_whitespace(&p);
    137 		if (*p == '\0') {
    138 			Parse_Error(PARSE_FATAL, "missing `in' in for");
    139 			return false;
    140 		}
    141 
    142 		/*
    143 		 * XXX: This allows arbitrary variable names;
    144 		 * see directive-for.mk.
    145 		 */
    146 		for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
    147 			continue;
    148 
    149 		if (len == 2 && p[0] == 'i' && p[1] == 'n') {
    150 			p += 2;
    151 			break;
    152 		}
    153 		if (len == 1)
    154 			f->short_var = true;
    155 
    156 		ForLoop_AddVar(f, p, len);
    157 		p += len;
    158 	}
    159 
    160 	if (f->vars.len == 0) {
    161 		Parse_Error(PARSE_FATAL, "no iteration variables in for");
    162 		return false;
    163 	}
    164 
    165 	*pp = p;
    166 	return true;
    167 }
    168 
    169 static bool
    170 ForLoop_ParseItems(ForLoop *f, const char *p)
    171 {
    172 	char *items;
    173 
    174 	cpp_skip_whitespace(&p);
    175 
    176 	if (Var_Subst(p, SCOPE_GLOBAL, VARE_WANTRES, &items) != VPR_OK) {
    177 		Parse_Error(PARSE_FATAL, "Error in .for loop items");
    178 		return false;
    179 	}
    180 
    181 	f->items = Str_Words(items, false);
    182 	free(items);
    183 
    184 	if (f->items.len == 1 && f->items.words[0][0] == '\0')
    185 		f->items.len = 0; /* .for var in ${:U} */
    186 
    187 	if (f->items.len != 0 && f->items.len % f->vars.len != 0) {
    188 		Parse_Error(PARSE_FATAL,
    189 		    "Wrong number of words (%u) in .for "
    190 		    "substitution list with %u variables",
    191 		    (unsigned)f->items.len, (unsigned)f->vars.len);
    192 		return false;
    193 	}
    194 
    195 	return true;
    196 }
    197 
    198 static bool
    199 IsFor(const char *p)
    200 {
    201 	return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
    202 }
    203 
    204 static bool
    205 IsEndfor(const char *p)
    206 {
    207 	return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
    208 	       (p[6] == '\0' || ch_isspace(p[6]));
    209 }
    210 
    211 /*
    212  * Evaluate the for loop in the passed line. The line looks like this:
    213  *	.for <varname...> in <value...>
    214  *
    215  * Input:
    216  *	line		Line to parse
    217  *
    218  * Results:
    219  *      0: Not a .for statement, parse the line
    220  *	1: We found a for loop
    221  *     -1: A .for statement with a bad syntax error, discard.
    222  */
    223 int
    224 For_Eval(const char *line)
    225 {
    226 	ForLoop *f;
    227 	const char *p;
    228 
    229 	p = line + 1;		/* skip the '.' */
    230 	cpp_skip_whitespace(&p);
    231 
    232 	if (!IsFor(p)) {
    233 		if (IsEndfor(p)) {
    234 			Parse_Error(PARSE_FATAL, "for-less endfor");
    235 			return -1;
    236 		}
    237 		return 0;
    238 	}
    239 	p += 3;
    240 
    241 	f = ForLoop_New();
    242 
    243 	if (!ForLoop_ParseVarnames(f, &p)) {
    244 		ForLoop_Free(f);
    245 		return -1;
    246 	}
    247 
    248 	if (!ForLoop_ParseItems(f, p)) {
    249 		/* Continue parsing the .for loop, but don't iterate. */
    250 		f->items.len = 0;
    251 	}
    252 
    253 	accumFor = f;
    254 	forLevel = 1;
    255 	return 1;
    256 }
    257 
    258 /*
    259  * Add another line to the .for loop that is being built up.
    260  * Returns false when the matching .endfor is reached.
    261  */
    262 bool
    263 For_Accum(const char *line)
    264 {
    265 	const char *p = line;
    266 
    267 	if (*p == '.') {
    268 		p++;
    269 		cpp_skip_whitespace(&p);
    270 
    271 		if (IsEndfor(p)) {
    272 			DEBUG1(FOR, "For: end for %d\n", forLevel);
    273 			if (--forLevel <= 0)
    274 				return false;
    275 		} else if (IsFor(p)) {
    276 			forLevel++;
    277 			DEBUG1(FOR, "For: new loop %d\n", forLevel);
    278 		}
    279 	}
    280 
    281 	Buf_AddStr(&accumFor->body, line);
    282 	Buf_AddByte(&accumFor->body, '\n');
    283 	return true;
    284 }
    285 
    286 
    287 static size_t
    288 for_var_len(const char *var)
    289 {
    290 	char ch, var_start, var_end;
    291 	int depth;
    292 	size_t len;
    293 
    294 	var_start = *var;
    295 	if (var_start == '\0')
    296 		/* just escape the $ */
    297 		return 0;
    298 
    299 	if (var_start == '(')
    300 		var_end = ')';
    301 	else if (var_start == '{')
    302 		var_end = '}';
    303 	else
    304 		return 1;	/* Single char variable */
    305 
    306 	depth = 1;
    307 	for (len = 1; (ch = var[len++]) != '\0';) {
    308 		if (ch == var_start)
    309 			depth++;
    310 		else if (ch == var_end && --depth == 0)
    311 			return len;
    312 	}
    313 
    314 	/* Variable end not found, escape the $ */
    315 	return 0;
    316 }
    317 
    318 /*
    319  * The .for loop substitutes the items as ${:U<value>...}, which means
    320  * that characters that break this syntax must be backslash-escaped.
    321  */
    322 static bool
    323 NeedsEscapes(const char *value, char endc)
    324 {
    325 	const char *p;
    326 
    327 	for (p = value; *p != '\0'; p++) {
    328 		if (*p == ':' || *p == '$' || *p == '\\' || *p == endc ||
    329 		    *p == '\n')
    330 			return true;
    331 	}
    332 	return false;
    333 }
    334 
    335 /*
    336  * While expanding the body of a .for loop, write the item in the ${:U...}
    337  * expression, escaping characters as needed.
    338  *
    339  * The result is later unescaped by ApplyModifier_Defined.
    340  */
    341 static void
    342 Buf_AddEscaped(Buffer *cmds, const char *item, char endc)
    343 {
    344 	char ch;
    345 
    346 	if (!NeedsEscapes(item, endc)) {
    347 		Buf_AddStr(cmds, item);
    348 		return;
    349 	}
    350 
    351 	/* Escape ':', '$', '\\' and 'endc' - these will be removed later by
    352 	 * :U processing, see ApplyModifier_Defined. */
    353 	while ((ch = *item++) != '\0') {
    354 		if (ch == '$') {
    355 			size_t len = for_var_len(item);
    356 			if (len != 0) {
    357 				Buf_AddBytes(cmds, item - 1, len + 1);
    358 				item += len;
    359 				continue;
    360 			}
    361 			Buf_AddByte(cmds, '\\');
    362 		} else if (ch == ':' || ch == '\\' || ch == endc)
    363 			Buf_AddByte(cmds, '\\');
    364 		else if (ch == '\n') {
    365 			Parse_Error(PARSE_FATAL, "newline in .for value");
    366 			ch = ' ';	/* prevent newline injection */
    367 		}
    368 		Buf_AddByte(cmds, ch);
    369 	}
    370 }
    371 
    372 /*
    373  * While expanding the body of a .for loop, replace the variable name of an
    374  * expression like ${i} or ${i:...} or $(i) or $(i:...) with ":Uvalue".
    375  */
    376 static void
    377 ForLoop_SubstVarLong(ForLoop *f, const char **pp, const char *bodyEnd,
    378 		     char endc, const char **inout_mark)
    379 {
    380 	size_t i;
    381 	const char *p = *pp;
    382 
    383 	for (i = 0; i < f->vars.len; i++) {
    384 		const ForVar *forVar = Vector_Get(&f->vars, i);
    385 		const char *varname = forVar->name;
    386 		size_t varnameLen = forVar->nameLen;
    387 
    388 		if (varnameLen >= (size_t)(bodyEnd - p))
    389 			continue;
    390 		if (memcmp(p, varname, varnameLen) != 0)
    391 			continue;
    392 		/* XXX: why test for backslash here? */
    393 		if (p[varnameLen] != ':' && p[varnameLen] != endc &&
    394 		    p[varnameLen] != '\\')
    395 			continue;
    396 
    397 		/*
    398 		 * Found a variable match.  Skip over the variable name and
    399 		 * instead add ':U<value>' to the current body.
    400 		 */
    401 		Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
    402 		Buf_AddStr(&f->curBody, ":U");
    403 		Buf_AddEscaped(&f->curBody,
    404 		    f->items.words[f->sub_next + i], endc);
    405 
    406 		p += varnameLen;
    407 		*inout_mark = p;
    408 		*pp = p;
    409 		return;
    410 	}
    411 }
    412 
    413 /*
    414  * While expanding the body of a .for loop, replace single-character
    415  * variable expressions like $i with their ${:U...} expansion.
    416  */
    417 static void
    418 ForLoop_SubstVarShort(ForLoop *f, const char *p, const char **inout_mark)
    419 {
    420 	const char ch = *p;
    421 	const ForVar *vars;
    422 	size_t i;
    423 
    424 	/* Skip $$ and stupid ones. */
    425 	if (!f->short_var || strchr("}):$", ch) != NULL)
    426 		return;
    427 
    428 	vars = Vector_Get(&f->vars, 0);
    429 	for (i = 0; i < f->vars.len; i++) {
    430 		const char *varname = vars[i].name;
    431 		if (varname[0] == ch && varname[1] == '\0')
    432 			goto found;
    433 	}
    434 	return;
    435 
    436 found:
    437 	/* Replace $<ch> with ${:U<value>} */
    438 	Buf_AddBytesBetween(&f->curBody, *inout_mark, p), *inout_mark = p + 1;
    439 	Buf_AddStr(&f->curBody, "{:U");
    440 	Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], '}');
    441 	Buf_AddByte(&f->curBody, '}');
    442 }
    443 
    444 /*
    445  * Compute the body for the current iteration by copying the unexpanded body,
    446  * replacing the expressions for the iteration variables on the way.
    447  *
    448  * Using variable expressions ensures that the .for loop can't generate
    449  * syntax, and that the later parsing will still see a variable.
    450  * This code assumes that the variable with the empty name will never be
    451  * defined, see unit-tests/varname-empty.mk for more details.
    452  *
    453  * The detection of substitutions of the loop control variables is naive.
    454  * Many of the modifiers use '\' to escape '$' (not '$'), so it is possible
    455  * to contrive a makefile where an unwanted substitution happens.
    456  */
    457 static void
    458 ForLoop_SubstBody(ForLoop *f)
    459 {
    460 	const char *p, *bodyEnd;
    461 	const char *mark;	/* where the last replacement left off */
    462 
    463 	Buf_Empty(&f->curBody);
    464 
    465 	mark = f->body.data;
    466 	bodyEnd = f->body.data + f->body.len;
    467 	for (p = mark; (p = strchr(p, '$')) != NULL;) {
    468 		if (p[1] == '{' || p[1] == '(') {
    469 			p += 2;
    470 			ForLoop_SubstVarLong(f, &p, bodyEnd,
    471 			    p[-1] == '{' ? '}' : ')', &mark);
    472 		} else if (p[1] != '\0') {
    473 			ForLoop_SubstVarShort(f, p + 1, &mark);
    474 			p += 2;
    475 		} else
    476 			break;
    477 	}
    478 
    479 	Buf_AddBytesBetween(&f->curBody, mark, bodyEnd);
    480 }
    481 
    482 /*
    483  * Compute the body for the current iteration by copying the unexpanded body,
    484  * replacing the expressions for the iteration variables on the way.
    485  */
    486 static char *
    487 ForReadMore(void *v_arg, size_t *out_len)
    488 {
    489 	ForLoop *f = v_arg;
    490 
    491 	if (f->sub_next == f->items.len) {
    492 		/* No more iterations */
    493 		ForLoop_Free(f);
    494 		return NULL;
    495 	}
    496 
    497 	ForLoop_SubstBody(f);
    498 	DEBUG1(FOR, "For: loop body:\n%s", f->curBody.data);
    499 	f->sub_next += (unsigned int)f->vars.len;
    500 
    501 	*out_len = f->curBody.len;
    502 	return f->curBody.data;
    503 }
    504 
    505 /* Run the .for loop, imitating the actions of an include file. */
    506 void
    507 For_Run(int lineno)
    508 {
    509 	ForLoop *f = accumFor;
    510 	accumFor = NULL;
    511 
    512 	if (f->items.len == 0) {
    513 		/*
    514 		 * Nothing to expand - possibly due to an earlier syntax
    515 		 * error.
    516 		 */
    517 		ForLoop_Free(f);
    518 		return;
    519 	}
    520 
    521 	Parse_SetInput(NULL, lineno, -1, ForReadMore, f);
    522 }
    523