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