for.c revision 1.98 1 /* $NetBSD: for.c,v 1.98 2020/10/25 13:51:56 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 are of the form:
36 *
37 * .for <varname...> in <value...>
38 * ...
39 * .endfor
40 *
41 * When a .for line is parsed, all following lines are accumulated into a
42 * buffer, up to but excluding the corresponding .endfor line. To find the
43 * corresponding .endfor, the number of nested .for and .endfor directives
44 * are counted.
45 *
46 * During parsing, any nested .for loops are just passed through; they get
47 * handled recursively in For_Eval when the enclosing .for loop is evaluated
48 * in For_Run.
49 *
50 * When the .for loop has been parsed completely, the variable expressions
51 * for the iteration variables are replaced with expressions of the form
52 * ${:Uvalue}, and then this modified body is "included" as a special file.
53 *
54 * Interface:
55 * For_Eval Evaluate the loop in the passed line.
56 *
57 * For_Run Run accumulated loop
58 */
59
60 #include "make.h"
61
62 /* "@(#)for.c 8.1 (Berkeley) 6/6/93" */
63 MAKE_RCSID("$NetBSD: for.c,v 1.98 2020/10/25 13:51:56 rillig Exp $");
64
65 typedef enum ForEscapes {
66 FOR_SUB_ESCAPE_CHAR = 0x0001,
67 FOR_SUB_ESCAPE_BRACE = 0x0002,
68 FOR_SUB_ESCAPE_PAREN = 0x0004
69 } ForEscapes;
70
71 static int forLevel = 0; /* Nesting level */
72
73 /* One of the variables to the left of the "in" in a .for loop. */
74 typedef struct ForVar {
75 char *name;
76 size_t len;
77 } ForVar;
78
79 /* One of the items to the right of the "in" in a .for loop. */
80 typedef struct ForItem {
81 char *value; /* unexpanded */
82 ForEscapes escapes;
83 } ForItem;
84
85 /*
86 * State of a for loop.
87 */
88 typedef struct For {
89 Buffer buf; /* Body of loop */
90 Vector /* of ForVar */ vars;
91 Vector /* of ForItem */ items; /* Substitution items */
92 char *parse_buf;
93 /* Is any of the names 1 character long? If so, when the variable values
94 * are substituted, the parser must handle $V expressions as well, not
95 * only ${V} and $(V). */
96 Boolean short_var;
97 unsigned int sub_next;
98 } For;
99
100 static For *accumFor; /* Loop being accumulated */
101
102 static void
103 ForAddVar(For *f, const char *name, size_t len)
104 {
105 ForVar *var = Vector_Push(&f->vars);
106 var->name = bmake_strldup(name, len);
107 var->len = len;
108 }
109
110 static void
111 ForVarDone(ForVar *var)
112 {
113 free(var->name);
114 }
115
116 static void
117 ForAddItem(For *f, const char *value, ForEscapes escapes)
118 {
119 ForItem *item = Vector_Push(&f->items);
120 item->value = bmake_strdup(value);
121 item->escapes = escapes;
122 }
123
124 static void
125 ForItemDone(ForItem *item)
126 {
127 free(item->value);
128 }
129
130 static void
131 For_Free(For *arg)
132 {
133 Buf_Destroy(&arg->buf, TRUE);
134
135 while (arg->vars.len > 0)
136 ForVarDone(Vector_Pop(&arg->vars));
137 Vector_Done(&arg->vars);
138
139 while (arg->items.len > 0)
140 ForItemDone(Vector_Pop(&arg->items));
141 Vector_Done(&arg->items);
142
143 free(arg->parse_buf);
144
145 free(arg);
146 }
147
148 /* Evaluate the for loop in the passed line. The line looks like this:
149 * .for <varname...> in <value...>
150 *
151 * Input:
152 * line Line to parse
153 *
154 * Results:
155 * 0: Not a .for statement, parse the line
156 * 1: We found a for loop
157 * -1: A .for statement with a bad syntax error, discard.
158 */
159 int
160 For_Eval(const char *line)
161 {
162 For *new_for;
163 const char *ptr;
164 Words words;
165
166 /* Skip the '.' and any following whitespace */
167 ptr = line + 1;
168 cpp_skip_whitespace(&ptr);
169
170 /*
171 * If we are not in a for loop quickly determine if the statement is
172 * a for.
173 */
174 if (ptr[0] != 'f' || ptr[1] != 'o' || ptr[2] != 'r' ||
175 !ch_isspace(ptr[3])) {
176 if (ptr[0] == 'e' && strncmp(ptr + 1, "ndfor", 5) == 0) {
177 Parse_Error(PARSE_FATAL, "for-less endfor");
178 return -1;
179 }
180 return 0;
181 }
182 ptr += 3;
183
184 /*
185 * we found a for loop, and now we are going to parse it.
186 */
187
188 new_for = bmake_malloc(sizeof *new_for);
189 Buf_Init(&new_for->buf, 0);
190 Vector_Init(&new_for->vars, sizeof(ForVar));
191 Vector_Init(&new_for->items, sizeof(ForItem));
192 new_for->parse_buf = NULL;
193 new_for->short_var = FALSE;
194 new_for->sub_next = 0;
195
196 /* Grab the variables. Terminate on "in". */
197 for (;;) {
198 size_t len;
199
200 cpp_skip_whitespace(&ptr);
201 if (*ptr == '\0') {
202 Parse_Error(PARSE_FATAL, "missing `in' in for");
203 For_Free(new_for);
204 return -1;
205 }
206
207 for (len = 1; ptr[len] && !ch_isspace(ptr[len]); len++)
208 continue;
209 if (len == 2 && ptr[0] == 'i' && ptr[1] == 'n') {
210 ptr += 2;
211 break;
212 }
213 if (len == 1)
214 new_for->short_var = TRUE;
215
216 ForAddVar(new_for, ptr, len);
217 ptr += len;
218 }
219
220 if (new_for->vars.len == 0) {
221 Parse_Error(PARSE_FATAL, "no iteration variables in for");
222 For_Free(new_for);
223 return -1;
224 }
225
226 cpp_skip_whitespace(&ptr);
227
228 /*
229 * Make a list with the remaining words.
230 * The values are later substituted as ${:U<value>...} so we must
231 * backslash-escape characters that break that syntax.
232 * Variables are fully expanded - so it is safe for escape $.
233 * We can't do the escapes here - because we don't know whether
234 * we will be substituting into ${...} or $(...).
235 */
236 {
237 char *items;
238 (void)Var_Subst(ptr, VAR_GLOBAL, VARE_WANTRES, &items);
239 /* TODO: handle errors */
240 words = Str_Words(items, FALSE);
241 free(items);
242 }
243
244 {
245 size_t n;
246
247 for (n = 0; n < words.len; n++) {
248 ForEscapes escapes;
249 char ch;
250
251 ptr = words.words[n];
252 if (ptr[0] == '\0')
253 continue;
254 escapes = 0;
255 while ((ch = *ptr++)) {
256 switch (ch) {
257 case ':':
258 case '$':
259 case '\\':
260 escapes |= FOR_SUB_ESCAPE_CHAR;
261 break;
262 case ')':
263 escapes |= FOR_SUB_ESCAPE_PAREN;
264 break;
265 case '}':
266 escapes |= FOR_SUB_ESCAPE_BRACE;
267 break;
268 }
269 }
270 ForAddItem(new_for, words.words[n], escapes);
271 }
272 }
273
274 Words_Free(words);
275
276 {
277 size_t nitems, nvars;
278
279 if ((nitems = new_for->items.len) > 0 &&
280 nitems % (nvars = new_for->vars.len)) {
281 Parse_Error(PARSE_FATAL,
282 "Wrong number of words (%zu) in .for substitution list"
283 " with %zu vars", nitems, nvars);
284 /*
285 * Return 'success' so that the body of the .for loop is
286 * accumulated.
287 * Remove all items so that the loop doesn't iterate.
288 */
289 while (new_for->items.len > 0)
290 ForItemDone(Vector_Pop(&new_for->items));
291 }
292 }
293
294 accumFor = new_for;
295 forLevel = 1;
296 return 1;
297 }
298
299 /*
300 * Add another line to a .for loop.
301 * Returns FALSE when the matching .endfor is reached.
302 */
303 Boolean
304 For_Accum(const char *line)
305 {
306 const char *ptr = line;
307
308 if (*ptr == '.') {
309 ptr++;
310 cpp_skip_whitespace(&ptr);
311
312 if (strncmp(ptr, "endfor", 6) == 0 && (ch_isspace(ptr[6]) || !ptr[6])) {
313 DEBUG1(FOR, "For: end for %d\n", forLevel);
314 if (--forLevel <= 0)
315 return FALSE;
316 } else if (strncmp(ptr, "for", 3) == 0 && ch_isspace(ptr[3])) {
317 forLevel++;
318 DEBUG1(FOR, "For: new loop %d\n", forLevel);
319 }
320 }
321
322 Buf_AddStr(&accumFor->buf, line);
323 Buf_AddByte(&accumFor->buf, '\n');
324 return TRUE;
325 }
326
327
328 static size_t
329 for_var_len(const char *var)
330 {
331 char ch, var_start, var_end;
332 int depth;
333 size_t len;
334
335 var_start = *var;
336 if (var_start == 0)
337 /* just escape the $ */
338 return 0;
339
340 if (var_start == '(')
341 var_end = ')';
342 else if (var_start == '{')
343 var_end = '}';
344 else
345 /* Single char variable */
346 return 1;
347
348 depth = 1;
349 for (len = 1; (ch = var[len++]) != 0;) {
350 if (ch == var_start)
351 depth++;
352 else if (ch == var_end && --depth == 0)
353 return len;
354 }
355
356 /* Variable end not found, escape the $ */
357 return 0;
358 }
359
360 static void
361 for_substitute(Buffer *cmds, ForItem *forItem, char ech)
362 {
363 const char *item = forItem->value;
364 ForEscapes escapes = forItem->escapes;
365 char ch;
366
367 /* If there were no escapes, or the only escape is the other variable
368 * terminator, then just substitute the full string */
369 if (!(escapes & (ech == ')' ? ~(unsigned)FOR_SUB_ESCAPE_BRACE
370 : ~(unsigned)FOR_SUB_ESCAPE_PAREN))) {
371 Buf_AddStr(cmds, item);
372 return;
373 }
374
375 /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
376 * :U processing, see ApplyModifier_Defined. */
377 while ((ch = *item++) != '\0') {
378 if (ch == '$') {
379 size_t len = for_var_len(item);
380 if (len != 0) {
381 Buf_AddBytes(cmds, item - 1, len + 1);
382 item += len;
383 continue;
384 }
385 Buf_AddByte(cmds, '\\');
386 } else if (ch == ':' || ch == '\\' || ch == ech)
387 Buf_AddByte(cmds, '\\');
388 Buf_AddByte(cmds, ch);
389 }
390 }
391
392 static void
393 SubstVarLong(For *arg, const char **inout_cp, const char **inout_cmd_cp,
394 Buffer *cmds, char ech)
395 {
396 size_t i;
397 const char *cp = *inout_cp;
398 const char *cmd_cp = *inout_cmd_cp;
399
400 for (i = 0; i < arg->vars.len; i++) {
401 ForVar *forVar = Vector_Get(&arg->vars, i);
402 char *var = forVar->name;
403 size_t vlen = forVar->len;
404
405 /* XXX: undefined behavior for cp if vlen is longer than cp? */
406 if (memcmp(cp, var, vlen) != 0)
407 continue;
408 /* XXX: why test for backslash here? */
409 if (cp[vlen] != ':' && cp[vlen] != ech && cp[vlen] != '\\')
410 continue;
411
412 /* Found a variable match. Replace with :U<value> */
413 Buf_AddBytesBetween(cmds, cmd_cp, cp);
414 Buf_AddStr(cmds, ":U");
415 cp += vlen;
416 cmd_cp = cp;
417 for_substitute(cmds, Vector_Get(&arg->items, arg->sub_next + i), ech);
418 break;
419 }
420
421 *inout_cp = cp;
422 *inout_cmd_cp = cmd_cp;
423 }
424
425 static void
426 SubstVarShort(For *arg, char const ch,
427 const char **inout_cp, const char **input_cmd_cp, Buffer *cmds)
428 {
429 const char *cp = *inout_cp;
430 const char *cmd_cp = *input_cmd_cp;
431 size_t i;
432
433 /* Probably a single character name, ignore $$ and stupid ones. {*/
434 if (!arg->short_var || strchr("}):$", ch) != NULL) {
435 cp++;
436 *inout_cp = cp;
437 return;
438 }
439
440 for (i = 0; i < arg->vars.len; i++) {
441 ForVar *forVar = Vector_Get(&arg->vars, i);
442 char *var = forVar->name;
443 if (var[0] != ch || var[1] != 0)
444 continue;
445
446 /* Found a variable match. Replace with ${:U<value>} */
447 Buf_AddBytesBetween(cmds, cmd_cp, cp);
448 Buf_AddStr(cmds, "{:U");
449 cmd_cp = ++cp;
450 for_substitute(cmds, Vector_Get(&arg->items, arg->sub_next + i), '}');
451 Buf_AddByte(cmds, '}');
452 break;
453 }
454
455 *inout_cp = cp;
456 *input_cmd_cp = cmd_cp;
457 }
458
459 /*
460 * Scan the for loop body and replace references to the loop variables
461 * with variable references that expand to the required text.
462 *
463 * Using variable expansions ensures that the .for loop can't generate
464 * syntax, and that the later parsing will still see a variable.
465 * We assume that the null variable will never be defined.
466 *
467 * The detection of substitutions of the loop control variable is naive.
468 * Many of the modifiers use \ to escape $ (not $) so it is possible
469 * to contrive a makefile where an unwanted substitution happens.
470 */
471 static char *
472 ForIterate(void *v_arg, size_t *ret_len)
473 {
474 For *arg = v_arg;
475 const char *cp;
476 const char *cmd_cp;
477 const char *body_end;
478 Buffer cmds;
479 char *cmds_str;
480 size_t cmd_len;
481
482 if (arg->sub_next + arg->vars.len > arg->items.len) {
483 /* No more iterations */
484 For_Free(arg);
485 return NULL;
486 }
487
488 free(arg->parse_buf);
489 arg->parse_buf = NULL;
490
491 cmd_cp = Buf_GetAll(&arg->buf, &cmd_len);
492 body_end = cmd_cp + cmd_len;
493 Buf_Init(&cmds, cmd_len + 256);
494 for (cp = cmd_cp; (cp = strchr(cp, '$')) != NULL;) {
495 char ch, ech;
496 ch = *++cp;
497 if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
498 cp++;
499 /* Check variable name against the .for loop variables */
500 SubstVarLong(arg, &cp, &cmd_cp, &cmds, ech);
501 continue;
502 }
503 if (ch == '\0')
504 break;
505
506 SubstVarShort(arg, ch, &cp, &cmd_cp, &cmds);
507 }
508 Buf_AddBytesBetween(&cmds, cmd_cp, body_end);
509
510 *ret_len = Buf_Len(&cmds);
511 cmds_str = Buf_Destroy(&cmds, FALSE);
512 DEBUG1(FOR, "For: loop body:\n%s", cmds_str);
513
514 arg->sub_next += arg->vars.len;
515
516 arg->parse_buf = cmds_str;
517 return cmds_str;
518 }
519
520 /* Run the for loop, imitating the actions of an include file. */
521 void
522 For_Run(int lineno)
523 {
524 For *arg;
525
526 arg = accumFor;
527 accumFor = NULL;
528
529 if (arg->items.len == 0) {
530 /* Nothing to expand - possibly due to an earlier syntax error. */
531 For_Free(arg);
532 return;
533 }
534
535 Parse_SetInput(NULL, lineno, -1, ForIterate, arg);
536 }
537