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