Home | History | Annotate | Line # | Download | only in make
for.c revision 1.52
      1 /*	$NetBSD: for.c,v 1.52 2016/02/18 18:29:14 christos 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 #ifndef MAKE_NATIVE
     33 static char rcsid[] = "$NetBSD: for.c,v 1.52 2016/02/18 18:29:14 christos Exp $";
     34 #else
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)for.c	8.1 (Berkeley) 6/6/93";
     39 #else
     40 __RCSID("$NetBSD: for.c,v 1.52 2016/02/18 18:29:14 christos Exp $");
     41 #endif
     42 #endif /* not lint */
     43 #endif
     44 
     45 /*-
     46  * for.c --
     47  *	Functions to handle loops in a makefile.
     48  *
     49  * Interface:
     50  *	For_Eval 	Evaluate the loop in the passed line.
     51  *	For_Run		Run accumulated loop
     52  *
     53  */
     54 
     55 #include    <assert.h>
     56 #include    <ctype.h>
     57 
     58 #include    "make.h"
     59 #include    "hash.h"
     60 #include    "dir.h"
     61 #include    "buf.h"
     62 #include    "strlist.h"
     63 
     64 #define FOR_SUB_ESCAPE_CHAR  1
     65 #define FOR_SUB_ESCAPE_BRACE 2
     66 #define FOR_SUB_ESCAPE_PAREN 4
     67 
     68 /*
     69  * For statements are of the form:
     70  *
     71  * .for <variable> in <varlist>
     72  * ...
     73  * .endfor
     74  *
     75  * The trick is to look for the matching end inside for for loop
     76  * To do that, we count the current nesting level of the for loops.
     77  * and the .endfor statements, accumulating all the statements between
     78  * the initial .for loop and the matching .endfor;
     79  * then we evaluate the for loop for each variable in the varlist.
     80  *
     81  * Note that any nested fors are just passed through; they get handled
     82  * recursively in For_Eval when we're expanding the enclosing for in
     83  * For_Run.
     84  */
     85 
     86 static int  	  forLevel = 0;  	/* Nesting level	*/
     87 
     88 /*
     89  * State of a for loop.
     90  */
     91 typedef struct _For {
     92     Buffer	  buf;			/* Body of loop		*/
     93     strlist_t     vars;			/* Iteration variables	*/
     94     strlist_t     items;		/* Substitution items */
     95     char          *parse_buf;
     96     int           short_var;
     97     int           sub_next;
     98 } For;
     99 
    100 static For        *accumFor;            /* Loop being accumulated */
    101 
    102 
    103 
    105 static char *
    106 make_str(const char *ptr, int len)
    107 {
    108 	char *new_ptr;
    109 
    110 	new_ptr = bmake_malloc(len + 1);
    111 	memcpy(new_ptr, ptr, len);
    112 	new_ptr[len] = 0;
    113 	return new_ptr;
    114 }
    115 
    116 static void
    117 For_Free(For *arg)
    118 {
    119     Buf_Destroy(&arg->buf, TRUE);
    120     strlist_clean(&arg->vars);
    121     strlist_clean(&arg->items);
    122     free(arg->parse_buf);
    123 
    124     free(arg);
    125 }
    126 
    127 /*-
    128  *-----------------------------------------------------------------------
    129  * For_Eval --
    130  *	Evaluate the for loop in the passed line. The line
    131  *	looks like this:
    132  *	    .for <variable> in <varlist>
    133  *
    134  * Input:
    135  *	line		Line to parse
    136  *
    137  * Results:
    138  *      0: Not a .for statement, parse the line
    139  *	1: We found a for loop
    140  *     -1: A .for statement with a bad syntax error, discard.
    141  *
    142  * Side Effects:
    143  *	None.
    144  *
    145  *-----------------------------------------------------------------------
    146  */
    147 int
    148 For_Eval(char *line)
    149 {
    150     For *new_for;
    151     char *ptr = line, *sub;
    152     int len;
    153     int escapes;
    154     unsigned char ch;
    155     char **words, *word_buf;
    156     int n, nwords;
    157 
    158     /* Skip the '.' and any following whitespace */
    159     for (ptr++; *ptr && isspace((unsigned char) *ptr); ptr++)
    160 	continue;
    161 
    162     /*
    163      * If we are not in a for loop quickly determine if the statement is
    164      * a for.
    165      */
    166     if (ptr[0] != 'f' || ptr[1] != 'o' || ptr[2] != 'r' ||
    167 	    !isspace((unsigned char) ptr[3])) {
    168 	if (ptr[0] == 'e' && strncmp(ptr+1, "ndfor", 5) == 0) {
    169 	    Parse_Error(PARSE_FATAL, "for-less endfor");
    170 	    return -1;
    171 	}
    172 	return 0;
    173     }
    174     ptr += 3;
    175 
    176     /*
    177      * we found a for loop, and now we are going to parse it.
    178      */
    179 
    180     new_for = bmake_malloc(sizeof *new_for);
    181     memset(new_for, 0, sizeof *new_for);
    182 
    183     /* Grab the variables. Terminate on "in". */
    184     for (;; ptr += len) {
    185 	while (*ptr && isspace((unsigned char) *ptr))
    186 	    ptr++;
    187 	if (*ptr == '\0') {
    188 	    Parse_Error(PARSE_FATAL, "missing `in' in for");
    189 	    For_Free(new_for);
    190 	    return -1;
    191 	}
    192 	for (len = 1; ptr[len] && !isspace((unsigned char)ptr[len]); len++)
    193 	    continue;
    194 	if (len == 2 && ptr[0] == 'i' && ptr[1] == 'n') {
    195 	    ptr += 2;
    196 	    break;
    197 	}
    198 	if (len == 1)
    199 	    new_for->short_var = 1;
    200 	strlist_add_str(&new_for->vars, make_str(ptr, len), len);
    201     }
    202 
    203     if (strlist_num(&new_for->vars) == 0) {
    204 	Parse_Error(PARSE_FATAL, "no iteration variables in for");
    205 	For_Free(new_for);
    206 	return -1;
    207     }
    208 
    209     while (*ptr && isspace((unsigned char) *ptr))
    210 	ptr++;
    211 
    212     /*
    213      * Make a list with the remaining words
    214      * The values are substituted as ${:U<value>...} so we must \ escape
    215      * characters that break that syntax.
    216      * Variables are fully expanded - so it is safe for escape $.
    217      * We can't do the escapes here - because we don't know whether
    218      * we are substuting into ${...} or $(...).
    219      */
    220     sub = Var_Subst(NULL, ptr, VAR_GLOBAL, VARF_WANTRES);
    221 
    222     /*
    223      * Split into words allowing for quoted strings.
    224      */
    225     words = brk_string(sub, &nwords, FALSE, &word_buf);
    226 
    227     free(sub);
    228 
    229     if (words != NULL) {
    230 	for (n = 0; n < nwords; n++) {
    231 	    ptr = words[n];
    232 	    if (!*ptr)
    233 		continue;
    234 	    escapes = 0;
    235 	    while ((ch = *ptr++)) {
    236 		switch(ch) {
    237 		case ':':
    238 		case '$':
    239 		case '\\':
    240 		    escapes |= FOR_SUB_ESCAPE_CHAR;
    241 		    break;
    242 		case ')':
    243 		    escapes |= FOR_SUB_ESCAPE_PAREN;
    244 		    break;
    245 		case /*{*/ '}':
    246 		    escapes |= FOR_SUB_ESCAPE_BRACE;
    247 		    break;
    248 		}
    249 	    }
    250 	    /*
    251 	     * We have to dup words[n] to maintain the semantics of
    252 	     * strlist.
    253 	     */
    254 	    strlist_add_str(&new_for->items, bmake_strdup(words[n]), escapes);
    255 	}
    256 
    257 	free(words);
    258 	free(word_buf);
    259 
    260 	if ((len = strlist_num(&new_for->items)) > 0 &&
    261 	    len % (n = strlist_num(&new_for->vars))) {
    262 	    Parse_Error(PARSE_FATAL,
    263 			"Wrong number of words (%d) in .for substitution list"
    264 			" with %d vars", len, n);
    265 	    /*
    266 	     * Return 'success' so that the body of the .for loop is
    267 	     * accumulated.
    268 	     * Remove all items so that the loop doesn't iterate.
    269 	     */
    270 	    strlist_clean(&new_for->items);
    271 	}
    272     }
    273 
    274     Buf_Init(&new_for->buf, 0);
    275     accumFor = new_for;
    276     forLevel = 1;
    277     return 1;
    278 }
    279 
    280 /*
    281  * Add another line to a .for loop.
    282  * Returns 0 when the matching .endfor is reached.
    283  */
    284 
    285 int
    286 For_Accum(char *line)
    287 {
    288     char *ptr = line;
    289 
    290     if (*ptr == '.') {
    291 
    292 	for (ptr++; *ptr && isspace((unsigned char) *ptr); ptr++)
    293 	    continue;
    294 
    295 	if (strncmp(ptr, "endfor", 6) == 0 &&
    296 		(isspace((unsigned char) ptr[6]) || !ptr[6])) {
    297 	    if (DEBUG(FOR))
    298 		(void)fprintf(debug_file, "For: end for %d\n", forLevel);
    299 	    if (--forLevel <= 0)
    300 		return 0;
    301 	} else if (strncmp(ptr, "for", 3) == 0 &&
    302 		 isspace((unsigned char) ptr[3])) {
    303 	    forLevel++;
    304 	    if (DEBUG(FOR))
    305 		(void)fprintf(debug_file, "For: new loop %d\n", forLevel);
    306 	}
    307     }
    308 
    309     Buf_AddBytes(&accumFor->buf, strlen(line), line);
    310     Buf_AddByte(&accumFor->buf, '\n');
    311     return 1;
    312 }
    313 
    314 
    315 /*-
    317  *-----------------------------------------------------------------------
    318  * For_Run --
    319  *	Run the for loop, imitating the actions of an include file
    320  *
    321  * Results:
    322  *	None.
    323  *
    324  * Side Effects:
    325  *	None.
    326  *
    327  *-----------------------------------------------------------------------
    328  */
    329 
    330 static int
    331 for_var_len(const char *var)
    332 {
    333     char ch, var_start, var_end;
    334     int depth;
    335     int len;
    336 
    337     var_start = *var;
    338     if (var_start == 0)
    339 	/* just escape the $ */
    340 	return 0;
    341 
    342     if (var_start == '(')
    343 	var_end = ')';
    344     else if (var_start == '{')
    345 	var_end = '}';
    346     else
    347 	/* Single char variable */
    348 	return 1;
    349 
    350     depth = 1;
    351     for (len = 1; (ch = var[len++]) != 0;) {
    352 	if (ch == var_start)
    353 	    depth++;
    354 	else if (ch == var_end && --depth == 0)
    355 	    return len;
    356     }
    357 
    358     /* Variable end not found, escape the $ */
    359     return 0;
    360 }
    361 
    362 static void
    363 for_substitute(Buffer *cmds, strlist_t *items, unsigned int item_no, char ech)
    364 {
    365     const char *item = strlist_str(items, item_no);
    366     int len;
    367     char ch;
    368 
    369     /* If there were no escapes, or the only escape is the other variable
    370      * terminator, then just substitute the full string */
    371     if (!(strlist_info(items, item_no) &
    372 	    (ech == ')' ? ~FOR_SUB_ESCAPE_BRACE : ~FOR_SUB_ESCAPE_PAREN))) {
    373 	Buf_AddBytes(cmds, strlen(item), item);
    374 	return;
    375     }
    376 
    377     /* Escape ':', '$', '\\' and 'ech' - removed by :U processing */
    378     while ((ch = *item++) != 0) {
    379 	if (ch == '$') {
    380 	    len = for_var_len(item);
    381 	    if (len != 0) {
    382 		Buf_AddBytes(cmds, len + 1, item - 1);
    383 		item += len;
    384 		continue;
    385 	    }
    386 	    Buf_AddByte(cmds, '\\');
    387 	} else if (ch == ':' || ch == '\\' || ch == ech)
    388 	    Buf_AddByte(cmds, '\\');
    389 	Buf_AddByte(cmds, ch);
    390     }
    391 }
    392 
    393 static char *
    394 For_Iterate(void *v_arg, size_t *ret_len)
    395 {
    396     For *arg = v_arg;
    397     int i, len;
    398     char *var;
    399     char *cp;
    400     char *cmd_cp;
    401     char *body_end;
    402     char ch;
    403     Buffer cmds;
    404 
    405     if (arg->sub_next + strlist_num(&arg->vars) > strlist_num(&arg->items)) {
    406 	/* No more iterations */
    407 	For_Free(arg);
    408 	return NULL;
    409     }
    410 
    411     free(arg->parse_buf);
    412     arg->parse_buf = NULL;
    413 
    414     /*
    415      * Scan the for loop body and replace references to the loop variables
    416      * with variable references that expand to the required text.
    417      * Using variable expansions ensures that the .for loop can't generate
    418      * syntax, and that the later parsing will still see a variable.
    419      * We assume that the null variable will never be defined.
    420      *
    421      * The detection of substitions of the loop control variable is naive.
    422      * Many of the modifiers use \ to escape $ (not $) so it is possible
    423      * to contrive a makefile where an unwanted substitution happens.
    424      */
    425 
    426     cmd_cp = Buf_GetAll(&arg->buf, &len);
    427     body_end = cmd_cp + len;
    428     Buf_Init(&cmds, len + 256);
    429     for (cp = cmd_cp; (cp = strchr(cp, '$')) != NULL;) {
    430 	char ech;
    431 	ch = *++cp;
    432 	if ((ch == '(' && (ech = ')')) || (ch == '{' && (ech = '}'))) {
    433 	    cp++;
    434 	    /* Check variable name against the .for loop variables */
    435 	    STRLIST_FOREACH(var, &arg->vars, i) {
    436 		len = strlist_info(&arg->vars, i);
    437 		if (memcmp(cp, var, len) != 0)
    438 		    continue;
    439 		if (cp[len] != ':' && cp[len] != ech && cp[len] != '\\')
    440 		    continue;
    441 		/* Found a variable match. Replace with :U<value> */
    442 		Buf_AddBytes(&cmds, cp - cmd_cp, cmd_cp);
    443 		Buf_AddBytes(&cmds, 2, ":U");
    444 		cp += len;
    445 		cmd_cp = cp;
    446 		for_substitute(&cmds, &arg->items, arg->sub_next + i, ech);
    447 		break;
    448 	    }
    449 	    continue;
    450 	}
    451 	if (ch == 0)
    452 	    break;
    453 	/* Probably a single character name, ignore $$ and stupid ones. {*/
    454 	if (!arg->short_var || strchr("}):$", ch) != NULL) {
    455 	    cp++;
    456 	    continue;
    457 	}
    458 	STRLIST_FOREACH(var, &arg->vars, i) {
    459 	    if (var[0] != ch || var[1] != 0)
    460 		continue;
    461 	    /* Found a variable match. Replace with ${:U<value>} */
    462 	    Buf_AddBytes(&cmds, cp - cmd_cp, cmd_cp);
    463 	    Buf_AddBytes(&cmds, 3, "{:U");
    464 	    cmd_cp = ++cp;
    465 	    for_substitute(&cmds, &arg->items, arg->sub_next + i, /*{*/ '}');
    466 	    Buf_AddBytes(&cmds, 1, "}");
    467 	    break;
    468 	}
    469     }
    470     Buf_AddBytes(&cmds, body_end - cmd_cp, cmd_cp);
    471 
    472     cp = Buf_Destroy(&cmds, FALSE);
    473     if (DEBUG(FOR))
    474 	(void)fprintf(debug_file, "For: loop body:\n%s", cp);
    475 
    476     arg->sub_next += strlist_num(&arg->vars);
    477 
    478     arg->parse_buf = cp;
    479     *ret_len = strlen(cp);
    480     return cp;
    481 }
    482 
    483 void
    484 For_Run(int lineno)
    485 {
    486     For *arg;
    487 
    488     arg = accumFor;
    489     accumFor = NULL;
    490 
    491     if (strlist_num(&arg->items) == 0) {
    492         /* Nothing to expand - possibly due to an earlier syntax error. */
    493         For_Free(arg);
    494         return;
    495     }
    496 
    497     Parse_SetInput(NULL, lineno, -1, For_Iterate, arg);
    498 }
    499