Home | History | Annotate | Line # | Download | only in make
for.c revision 1.156
      1 /*	$NetBSD: for.c,v 1.156 2022/01/07 20:09:58 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
     49  * variable names are replaced with expressions of the form ${:U...}.  After
     50  * 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.156 2022/01/07 20:09:58 rillig Exp $");
     62 
     63 
     64 typedef struct ForLoop {
     65 	Buffer body;		/* Unexpanded body of the loop */
     66 	Vector /* of 'char *' */ vars; /* Iteration variables */
     67 	SubstringWords items;	/* Substitution items */
     68 	unsigned int nextItem;	/* Where to continue iterating */
     69 } ForLoop;
     70 
     71 
     72 static ForLoop *accumFor;	/* Loop being accumulated */
     73 
     74 
     75 static ForLoop *
     76 ForLoop_New(void)
     77 {
     78 	ForLoop *f = bmake_malloc(sizeof *f);
     79 
     80 	Buf_Init(&f->body);
     81 	Vector_Init(&f->vars, sizeof(char *));
     82 	SubstringWords_Init(&f->items);
     83 	f->nextItem = 0;
     84 
     85 	return f;
     86 }
     87 
     88 static void
     89 ForLoop_Free(ForLoop *f)
     90 {
     91 	Buf_Done(&f->body);
     92 
     93 	while (f->vars.len > 0)
     94 		free(*(char **)Vector_Pop(&f->vars));
     95 	Vector_Done(&f->vars);
     96 
     97 	SubstringWords_Free(f->items);
     98 
     99 	free(f);
    100 }
    101 
    102 static bool
    103 ForLoop_ParseVarnames(ForLoop *f, const char **pp)
    104 {
    105 	const char *p = *pp;
    106 
    107 	for (;;) {
    108 		size_t len;
    109 
    110 		cpp_skip_whitespace(&p);
    111 		if (*p == '\0') {
    112 			Parse_Error(PARSE_FATAL, "missing `in' in for");
    113 			return false;
    114 		}
    115 
    116 		/*
    117 		 * XXX: This allows arbitrary variable names;
    118 		 * see directive-for.mk.
    119 		 */
    120 		for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
    121 			continue;
    122 
    123 		if (len == 2 && p[0] == 'i' && p[1] == 'n') {
    124 			p += 2;
    125 			break;
    126 		}
    127 
    128 		*(char **)Vector_Push(&f->vars) = bmake_strldup(p, len);
    129 		p += len;
    130 	}
    131 
    132 	if (f->vars.len == 0) {
    133 		Parse_Error(PARSE_FATAL, "no iteration variables in for");
    134 		return false;
    135 	}
    136 
    137 	*pp = p;
    138 	return true;
    139 }
    140 
    141 static bool
    142 ForLoop_ParseItems(ForLoop *f, const char *p)
    143 {
    144 	char *items;
    145 
    146 	cpp_skip_whitespace(&p);
    147 
    148 	if (Var_Subst(p, SCOPE_GLOBAL, VARE_WANTRES, &items) != VPR_OK) {
    149 		Parse_Error(PARSE_FATAL, "Error in .for loop items");
    150 		return false;
    151 	}
    152 
    153 	f->items = Substring_Words(items, false);
    154 	free(items);
    155 
    156 	if (f->items.len == 1 && Substring_IsEmpty(f->items.words[0]))
    157 		f->items.len = 0;	/* .for var in ${:U} */
    158 
    159 	if (f->items.len != 0 && f->items.len % f->vars.len != 0) {
    160 		Parse_Error(PARSE_FATAL,
    161 		    "Wrong number of words (%u) in .for "
    162 		    "substitution list with %u variables",
    163 		    (unsigned)f->items.len, (unsigned)f->vars.len);
    164 		return false;
    165 	}
    166 
    167 	return true;
    168 }
    169 
    170 static bool
    171 IsFor(const char *p)
    172 {
    173 	return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
    174 }
    175 
    176 static bool
    177 IsEndfor(const char *p)
    178 {
    179 	return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
    180 	       (p[6] == '\0' || ch_isspace(p[6]));
    181 }
    182 
    183 /*
    184  * Evaluate the for loop in the passed line. The line looks like this:
    185  *	.for <varname...> in <value...>
    186  *
    187  * Input:
    188  *	line		Line to parse
    189  *
    190  * Results:
    191  *	0: Not a .for statement, parse the line
    192  *	1: We found a for loop
    193  *	-1: A .for statement with a bad syntax error, discard.
    194  */
    195 int
    196 For_Eval(const char *line)
    197 {
    198 	ForLoop *f;
    199 	const char *p;
    200 
    201 	p = line + 1;		/* skip the '.' */
    202 	cpp_skip_whitespace(&p);
    203 
    204 	if (!IsFor(p)) {
    205 		if (IsEndfor(p)) {
    206 			Parse_Error(PARSE_FATAL, "for-less endfor");
    207 			return -1;
    208 		}
    209 		return 0;
    210 	}
    211 	p += 3;
    212 
    213 	f = ForLoop_New();
    214 
    215 	if (!ForLoop_ParseVarnames(f, &p)) {
    216 		ForLoop_Free(f);
    217 		return -1;
    218 	}
    219 
    220 	if (!ForLoop_ParseItems(f, p)) {
    221 		/* Continue parsing the .for loop, but don't iterate. */
    222 		f->items.len = 0;
    223 	}
    224 
    225 	accumFor = f;
    226 	return 1;
    227 }
    228 
    229 /*
    230  * Add another line to the .for loop that is being built up.
    231  * Returns false when the matching .endfor is reached.
    232  */
    233 bool
    234 For_Accum(const char *line, int *forLevel)
    235 {
    236 	const char *p = line;
    237 
    238 	if (*p == '.') {
    239 		p++;
    240 		cpp_skip_whitespace(&p);
    241 
    242 		if (IsEndfor(p)) {
    243 			DEBUG1(FOR, "For: end for %d\n", *forLevel);
    244 			if (--*forLevel <= 0)
    245 				return false;
    246 		} else if (IsFor(p)) {
    247 			(*forLevel)++;
    248 			DEBUG1(FOR, "For: new loop %d\n", *forLevel);
    249 		}
    250 	}
    251 
    252 	Buf_AddStr(&accumFor->body, line);
    253 	Buf_AddByte(&accumFor->body, '\n');
    254 	return true;
    255 }
    256 
    257 
    258 static size_t
    259 ExprLen(const char *s, const char *e)
    260 {
    261 	char expr_open, expr_close;
    262 	int depth;
    263 	const char *p;
    264 
    265 	if (s == e)
    266 		return 0;	/* just escape the '$' */
    267 
    268 	expr_open = s[0];
    269 	if (expr_open == '(')
    270 		expr_close = ')';
    271 	else if (expr_open == '{')
    272 		expr_close = '}';
    273 	else
    274 		return 1;	/* Single char variable */
    275 
    276 	depth = 1;
    277 	for (p = s + 1; p != e; p++) {
    278 		if (*p == expr_open)
    279 			depth++;
    280 		else if (*p == expr_close && --depth == 0)
    281 			return (size_t)(p + 1 - s);
    282 	}
    283 
    284 	/* Expression end not found, escape the $ */
    285 	return 0;
    286 }
    287 
    288 /*
    289  * The .for loop substitutes the items as ${:U<value>...}, which means
    290  * that characters that break this syntax must be backslash-escaped.
    291  */
    292 static bool
    293 NeedsEscapes(Substring value, char endc)
    294 {
    295 	const char *p;
    296 
    297 	for (p = value.start; p != value.end; p++) {
    298 		if (*p == ':' || *p == '$' || *p == '\\' || *p == endc ||
    299 		    *p == '\n')
    300 			return true;
    301 	}
    302 	return false;
    303 }
    304 
    305 /*
    306  * While expanding the body of a .for loop, write the item in the ${:U...}
    307  * expression, escaping characters as needed.
    308  *
    309  * The result is later unescaped by ApplyModifier_Defined.
    310  */
    311 static void
    312 Buf_AddEscaped(Buffer *cmds, Substring item, char endc)
    313 {
    314 	const char *p;
    315 	char ch;
    316 
    317 	if (!NeedsEscapes(item, endc)) {
    318 		Buf_AddBytesBetween(cmds, item.start, item.end);
    319 		return;
    320 	}
    321 
    322 	/*
    323 	 * Escape ':', '$', '\\' and 'endc' - these will be removed later by
    324 	 * :U processing, see ApplyModifier_Defined.
    325 	 */
    326 	for (p = item.start; p != item.end; p++) {
    327 		ch = *p;
    328 		if (ch == '$') {
    329 			size_t len = ExprLen(p + 1, item.end);
    330 			if (len != 0) {
    331 				/*
    332 				 * XXX: Should a '\' be added here?
    333 				 * See directive-for-escape.mk, ExprLen.
    334 				 */
    335 				Buf_AddBytes(cmds, p, 1 + len);
    336 				p += len;
    337 				continue;
    338 			}
    339 			Buf_AddByte(cmds, '\\');
    340 		} else if (ch == ':' || ch == '\\' || ch == endc)
    341 			Buf_AddByte(cmds, '\\');
    342 		else if (ch == '\n') {
    343 			Parse_Error(PARSE_FATAL, "newline in .for value");
    344 			ch = ' ';	/* prevent newline injection */
    345 		}
    346 		Buf_AddByte(cmds, ch);
    347 	}
    348 }
    349 
    350 /*
    351  * When expanding the body of a .for loop, replace the variable name of an
    352  * expression like ${i} or ${i:...} or $(i) or $(i:...) with ":Uvalue".
    353  */
    354 static void
    355 ForLoop_SubstVarLong(ForLoop *f, Buffer *body, const char **pp,
    356 		     const char *end, char endc, const char **inout_mark)
    357 {
    358 	size_t i;
    359 	const char *start = *pp;
    360 	const char **vars = Vector_Get(&f->vars, 0);
    361 
    362 	for (i = 0; i < f->vars.len; i++) {
    363 		const char *p = start;
    364 		const char *varname = vars[i];
    365 
    366 		while (p < end && *varname != '\0' && *p == *varname)
    367 			p++, varname++;
    368 		if (*varname != '\0')
    369 			continue;
    370 		/* XXX: why test for backslash here? */
    371 		if (*p != ':' && *p != endc && *p != '\\')
    372 			continue;
    373 
    374 		/*
    375 		 * Found a variable match.  Skip over the variable name and
    376 		 * instead add ':U<value>' to the current body.
    377 		 */
    378 		Buf_AddBytesBetween(body, *inout_mark, start);
    379 		Buf_AddStr(body, ":U");
    380 		Buf_AddEscaped(body, f->items.words[f->nextItem + i], endc);
    381 
    382 		*inout_mark = p;
    383 		*pp = p;
    384 		return;
    385 	}
    386 }
    387 
    388 /*
    389  * When expanding the body of a .for loop, replace single-character
    390  * variable expressions like $i with their ${:U...} expansion.
    391  */
    392 static void
    393 ForLoop_SubstVarShort(ForLoop *f, Buffer *body,
    394 		      const char *p, const char **inout_mark)
    395 {
    396 	const char ch = *p;
    397 	const char **vars;
    398 	size_t i;
    399 
    400 	/* Skip $$ and stupid ones. */
    401 	if (ch == '}' || ch == ')' || ch == ':' || ch == '$')
    402 		return;
    403 
    404 	vars = Vector_Get(&f->vars, 0);
    405 	for (i = 0; i < f->vars.len; i++) {
    406 		const char *varname = vars[i];
    407 		if (varname[0] == ch && varname[1] == '\0')
    408 			goto found;
    409 	}
    410 	return;
    411 
    412 found:
    413 	Buf_AddBytesBetween(body, *inout_mark, p);
    414 	*inout_mark = p + 1;
    415 
    416 	/* Replace $<ch> with ${:U<value>} */
    417 	Buf_AddStr(body, "{:U");
    418 	Buf_AddEscaped(body, f->items.words[f->nextItem + i], '}');
    419 	Buf_AddByte(body, '}');
    420 }
    421 
    422 /*
    423  * Compute the body for the current iteration by copying the unexpanded body,
    424  * replacing the expressions for the iteration variables on the way.
    425  *
    426  * Using variable expressions ensures that the .for loop can't generate
    427  * syntax, and that the later parsing will still see a variable.
    428  * This code assumes that the variable with the empty name will never be
    429  * defined, see unit-tests/varname-empty.mk for more details.
    430  *
    431  * The detection of substitutions of the loop control variables is naive.
    432  * Many of the modifiers use '\$' instead of '$$' to escape '$', so it is
    433  * possible to contrive a makefile where an unwanted substitution happens.
    434  */
    435 static void
    436 ForLoop_SubstBody(ForLoop *f, Buffer *body)
    437 {
    438 	const char *p, *end;
    439 	const char *mark;	/* where the last substitution left off */
    440 
    441 	Buf_Empty(body);
    442 
    443 	mark = f->body.data;
    444 	end = f->body.data + f->body.len;
    445 	for (p = mark; (p = strchr(p, '$')) != NULL;) {
    446 		if (p[1] == '{' || p[1] == '(') {
    447 			char endc = p[1] == '{' ? '}' : ')';
    448 			p += 2;
    449 			ForLoop_SubstVarLong(f, body, &p, end, endc, &mark);
    450 		} else if (p[1] != '\0') {
    451 			ForLoop_SubstVarShort(f, body, p + 1, &mark);
    452 			p += 2;
    453 		} else
    454 			break;
    455 	}
    456 
    457 	Buf_AddBytesBetween(body, mark, end);
    458 }
    459 
    460 /*
    461  * Compute the body for the current iteration by copying the unexpanded body,
    462  * replacing the expressions for the iteration variables on the way.
    463  */
    464 bool
    465 For_NextIteration(ForLoop *f, Buffer *body)
    466 {
    467 	if (f->nextItem == f->items.len) {
    468 		/* No more iterations */
    469 		ForLoop_Free(f);
    470 		return false;
    471 	}
    472 
    473 	ForLoop_SubstBody(f, body);
    474 	DEBUG1(FOR, "For: loop body:\n%s", body->data);
    475 	f->nextItem += (unsigned int)f->vars.len;
    476 	return true;
    477 }
    478 
    479 /* Run the .for loop, imitating the actions of an include file. */
    480 void
    481 For_Run(int lineno)
    482 {
    483 	Buffer buf;
    484 	ForLoop *f = accumFor;
    485 	accumFor = NULL;
    486 
    487 	if (f->items.len > 0) {
    488 		Buf_Init(&buf);
    489 		Parse_PushInput(NULL, lineno, buf, f);
    490 	} else
    491 		ForLoop_Free(f);
    492 }
    493