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