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