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