1 /* $NetBSD: var.c,v 1.154 2009/09/08 17:29:20 sjg Exp $ */ 2 3 /* 4 * Copyright (c) 1988, 1989, 1990, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Adam de Boor. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 /* 36 * Copyright (c) 1989 by Berkeley Softworks 37 * All rights reserved. 38 * 39 * This code is derived from software contributed to Berkeley by 40 * Adam de Boor. 41 * 42 * Redistribution and use in source and binary forms, with or without 43 * modification, are permitted provided that the following conditions 44 * are met: 45 * 1. Redistributions of source code must retain the above copyright 46 * notice, this list of conditions and the following disclaimer. 47 * 2. Redistributions in binary form must reproduce the above copyright 48 * notice, this list of conditions and the following disclaimer in the 49 * documentation and/or other materials provided with the distribution. 50 * 3. All advertising materials mentioning features or use of this software 51 * must display the following acknowledgement: 52 * This product includes software developed by the University of 53 * California, Berkeley and its contributors. 54 * 4. Neither the name of the University nor the names of its contributors 55 * may be used to endorse or promote products derived from this software 56 * without specific prior written permission. 57 * 58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 61 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 68 * SUCH DAMAGE. 69 */ 70 71 #ifndef MAKE_NATIVE 72 static char rcsid[] = "$NetBSD: var.c,v 1.154 2009/09/08 17:29:20 sjg Exp $"; 73 #else 74 #include <sys/cdefs.h> 75 #ifndef lint 76 #if 0 77 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94"; 78 #else 79 __RCSID("$NetBSD: var.c,v 1.154 2009/09/08 17:29:20 sjg Exp $"); 80 #endif 81 #endif /* not lint */ 82 #endif 83 84 /*- 85 * var.c -- 86 * Variable-handling functions 87 * 88 * Interface: 89 * Var_Set Set the value of a variable in the given 90 * context. The variable is created if it doesn't 91 * yet exist. The value and variable name need not 92 * be preserved. 93 * 94 * Var_Append Append more characters to an existing variable 95 * in the given context. The variable needn't 96 * exist already -- it will be created if it doesn't. 97 * A space is placed between the old value and the 98 * new one. 99 * 100 * Var_Exists See if a variable exists. 101 * 102 * Var_Value Return the value of a variable in a context or 103 * NULL if the variable is undefined. 104 * 105 * Var_Subst Substitute named variable, or all variables if 106 * NULL in a string using 107 * the given context as the top-most one. If the 108 * third argument is non-zero, Parse_Error is 109 * called if any variables are undefined. 110 * 111 * Var_Parse Parse a variable expansion from a string and 112 * return the result and the number of characters 113 * consumed. 114 * 115 * Var_Delete Delete a variable in a context. 116 * 117 * Var_Init Initialize this module. 118 * 119 * Debugging: 120 * Var_Dump Print out all variables defined in the given 121 * context. 122 * 123 * XXX: There's a lot of duplication in these functions. 124 */ 125 126 #ifndef NO_REGEX 127 #include <sys/types.h> 128 #include <regex.h> 129 #endif 130 #include <ctype.h> 131 #include <stdlib.h> 132 #include <limits.h> 133 134 #include "make.h" 135 #include "buf.h" 136 #include "dir.h" 137 #include "job.h" 138 139 /* 140 * This is a harmless return value for Var_Parse that can be used by Var_Subst 141 * to determine if there was an error in parsing -- easier than returning 142 * a flag, as things outside this module don't give a hoot. 143 */ 144 char var_Error[] = ""; 145 146 /* 147 * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is 148 * set false. Why not just use a constant? Well, gcc likes to condense 149 * identical string instances... 150 */ 151 static char varNoError[] = ""; 152 153 /* 154 * Internally, variables are contained in four different contexts. 155 * 1) the environment. They may not be changed. If an environment 156 * variable is appended-to, the result is placed in the global 157 * context. 158 * 2) the global context. Variables set in the Makefile are located in 159 * the global context. It is the penultimate context searched when 160 * substituting. 161 * 3) the command-line context. All variables set on the command line 162 * are placed in this context. They are UNALTERABLE once placed here. 163 * 4) the local context. Each target has associated with it a context 164 * list. On this list are located the structures describing such 165 * local variables as $(@) and $(*) 166 * The four contexts are searched in the reverse order from which they are 167 * listed. 168 */ 169 GNode *VAR_GLOBAL; /* variables from the makefile */ 170 GNode *VAR_CMD; /* variables defined on the command-line */ 171 172 #define FIND_CMD 0x1 /* look in VAR_CMD when searching */ 173 #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */ 174 #define FIND_ENV 0x4 /* look in the environment also */ 175 176 typedef struct Var { 177 char *name; /* the variable's name */ 178 Buffer val; /* its value */ 179 int flags; /* miscellaneous status flags */ 180 #define VAR_IN_USE 1 /* Variable's value currently being used. 181 * Used to avoid recursion */ 182 #define VAR_FROM_ENV 2 /* Variable comes from the environment */ 183 #define VAR_JUNK 4 /* Variable is a junk variable that 184 * should be destroyed when done with 185 * it. Used by Var_Parse for undefined, 186 * modified variables */ 187 #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found 188 * a use for it in some modifier and 189 * the value is therefore valid */ 190 #define VAR_EXPORTED 16 /* Variable is exported */ 191 #define VAR_REEXPORT 32 /* Indicate if var needs re-export. 192 * This would be true if it contains $'s 193 */ 194 #define VAR_FROM_CMD 64 /* Variable came from command line */ 195 } Var; 196 197 /* 198 * Exporting vars is expensive so skip it if we can 199 */ 200 #define VAR_EXPORTED_NONE 0 201 #define VAR_EXPORTED_YES 1 202 #define VAR_EXPORTED_ALL 2 203 static int var_exportedVars = VAR_EXPORTED_NONE; 204 /* 205 * We pass this to Var_Export when doing the initial export 206 * or after updating an exported var. 207 */ 208 #define VAR_EXPORT_PARENT 1 209 210 /* Var*Pattern flags */ 211 #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */ 212 #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */ 213 #define VAR_SUB_MATCHED 0x04 /* There was a match */ 214 #define VAR_MATCH_START 0x08 /* Match at start of word */ 215 #define VAR_MATCH_END 0x10 /* Match at end of word */ 216 #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */ 217 218 /* Var_Set flags */ 219 #define VAR_NO_EXPORT 0x01 /* do not export */ 220 221 typedef struct { 222 /* 223 * The following fields are set by Var_Parse() when it 224 * encounters modifiers that need to keep state for use by 225 * subsequent modifiers within the same variable expansion. 226 */ 227 Byte varSpace; /* Word separator in expansions */ 228 Boolean oneBigWord; /* TRUE if we will treat the variable as a 229 * single big word, even if it contains 230 * embedded spaces (as opposed to the 231 * usual behaviour of treating it as 232 * several space-separated words). */ 233 } Var_Parse_State; 234 235 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/", 236 * to VarSYSVMatch() for ":lhs=rhs". */ 237 typedef struct { 238 const char *lhs; /* String to match */ 239 int leftLen; /* Length of string */ 240 const char *rhs; /* Replacement string (w/ &'s removed) */ 241 int rightLen; /* Length of replacement */ 242 int flags; 243 } VarPattern; 244 245 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */ 246 typedef struct { 247 GNode *ctxt; /* variable context */ 248 char *tvar; /* name of temp var */ 249 int tvarLen; 250 char *str; /* string to expand */ 251 int strLen; 252 int errnum; /* errnum for not defined */ 253 } VarLoop_t; 254 255 #ifndef NO_REGEX 256 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */ 257 typedef struct { 258 regex_t re; 259 int nsub; 260 regmatch_t *matches; 261 char *replace; 262 int flags; 263 } VarREPattern; 264 #endif 265 266 /* struct passed to VarSelectWords() for ":[start..end]" */ 267 typedef struct { 268 int start; /* first word to select */ 269 int end; /* last word to select */ 270 } VarSelectWords_t; 271 272 static Var *VarFind(const char *, GNode *, int); 273 static void VarAdd(const char *, const char *, GNode *); 274 static Boolean VarHead(GNode *, Var_Parse_State *, 275 char *, Boolean, Buffer *, void *); 276 static Boolean VarTail(GNode *, Var_Parse_State *, 277 char *, Boolean, Buffer *, void *); 278 static Boolean VarSuffix(GNode *, Var_Parse_State *, 279 char *, Boolean, Buffer *, void *); 280 static Boolean VarRoot(GNode *, Var_Parse_State *, 281 char *, Boolean, Buffer *, void *); 282 static Boolean VarMatch(GNode *, Var_Parse_State *, 283 char *, Boolean, Buffer *, void *); 284 #ifdef SYSVVARSUB 285 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *, 286 char *, Boolean, Buffer *, void *); 287 #endif 288 static Boolean VarNoMatch(GNode *, Var_Parse_State *, 289 char *, Boolean, Buffer *, void *); 290 #ifndef NO_REGEX 291 static void VarREError(int, regex_t *, const char *); 292 static Boolean VarRESubstitute(GNode *, Var_Parse_State *, 293 char *, Boolean, Buffer *, void *); 294 #endif 295 static Boolean VarSubstitute(GNode *, Var_Parse_State *, 296 char *, Boolean, Buffer *, void *); 297 static Boolean VarLoopExpand(GNode *, Var_Parse_State *, 298 char *, Boolean, Buffer *, void *); 299 static char *VarGetPattern(GNode *, Var_Parse_State *, 300 int, const char **, int, int *, int *, 301 VarPattern *); 302 static char *VarQuote(char *); 303 static char *VarChangeCase(char *, int); 304 static char *VarModify(GNode *, Var_Parse_State *, 305 const char *, 306 Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *), 307 void *); 308 static char *VarOrder(const char *, const char); 309 static char *VarUniq(const char *); 310 static int VarWordCompare(const void *, const void *); 311 static void VarPrintVar(void *); 312 313 #define BROPEN '{' 314 #define BRCLOSE '}' 315 #define PROPEN '(' 316 #define PRCLOSE ')' 317 318 /*- 319 *----------------------------------------------------------------------- 320 * VarFind -- 321 * Find the given variable in the given context and any other contexts 322 * indicated. 323 * 324 * Input: 325 * name name to find 326 * ctxt context in which to find it 327 * flags FIND_GLOBAL set means to look in the 328 * VAR_GLOBAL context as well. FIND_CMD set means 329 * to look in the VAR_CMD context also. FIND_ENV 330 * set means to look in the environment 331 * 332 * Results: 333 * A pointer to the structure describing the desired variable or 334 * NULL if the variable does not exist. 335 * 336 * Side Effects: 337 * None 338 *----------------------------------------------------------------------- 339 */ 340 static Var * 341 VarFind(const char *name, GNode *ctxt, int flags) 342 { 343 Hash_Entry *var; 344 Var *v; 345 346 /* 347 * If the variable name begins with a '.', it could very well be one of 348 * the local ones. We check the name against all the local variables 349 * and substitute the short version in for 'name' if it matches one of 350 * them. 351 */ 352 if (*name == '.' && isupper((unsigned char) name[1])) 353 switch (name[1]) { 354 case 'A': 355 if (!strcmp(name, ".ALLSRC")) 356 name = ALLSRC; 357 if (!strcmp(name, ".ARCHIVE")) 358 name = ARCHIVE; 359 break; 360 case 'I': 361 if (!strcmp(name, ".IMPSRC")) 362 name = IMPSRC; 363 break; 364 case 'M': 365 if (!strcmp(name, ".MEMBER")) 366 name = MEMBER; 367 break; 368 case 'O': 369 if (!strcmp(name, ".OODATE")) 370 name = OODATE; 371 break; 372 case 'P': 373 if (!strcmp(name, ".PREFIX")) 374 name = PREFIX; 375 break; 376 case 'T': 377 if (!strcmp(name, ".TARGET")) 378 name = TARGET; 379 break; 380 } 381 /* 382 * First look for the variable in the given context. If it's not there, 383 * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order, 384 * depending on the FIND_* flags in 'flags' 385 */ 386 var = Hash_FindEntry(&ctxt->context, name); 387 388 if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) { 389 var = Hash_FindEntry(&VAR_CMD->context, name); 390 } 391 if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) && 392 (ctxt != VAR_GLOBAL)) 393 { 394 var = Hash_FindEntry(&VAR_GLOBAL->context, name); 395 } 396 if ((var == NULL) && (flags & FIND_ENV)) { 397 char *env; 398 399 if ((env = getenv(name)) != NULL) { 400 int len; 401 402 v = bmake_malloc(sizeof(Var)); 403 v->name = bmake_strdup(name); 404 405 len = strlen(env); 406 407 Buf_Init(&v->val, len + 1); 408 Buf_AddBytes(&v->val, len, env); 409 410 v->flags = VAR_FROM_ENV; 411 return (v); 412 } else if (checkEnvFirst && (flags & FIND_GLOBAL) && 413 (ctxt != VAR_GLOBAL)) 414 { 415 var = Hash_FindEntry(&VAR_GLOBAL->context, name); 416 if (var == NULL) { 417 return NULL; 418 } else { 419 return ((Var *)Hash_GetValue(var)); 420 } 421 } else { 422 return NULL; 423 } 424 } else if (var == NULL) { 425 return NULL; 426 } else { 427 return ((Var *)Hash_GetValue(var)); 428 } 429 } 430 431 /*- 432 *----------------------------------------------------------------------- 433 * VarFreeEnv -- 434 * If the variable is an environment variable, free it 435 * 436 * Input: 437 * v the variable 438 * destroy true if the value buffer should be destroyed. 439 * 440 * Results: 441 * 1 if it is an environment variable 0 ow. 442 * 443 * Side Effects: 444 * The variable is free'ed if it is an environent variable. 445 *----------------------------------------------------------------------- 446 */ 447 static Boolean 448 VarFreeEnv(Var *v, Boolean destroy) 449 { 450 if ((v->flags & VAR_FROM_ENV) == 0) 451 return FALSE; 452 free(v->name); 453 Buf_Destroy(&v->val, destroy); 454 free(v); 455 return TRUE; 456 } 457 458 /*- 459 *----------------------------------------------------------------------- 460 * VarAdd -- 461 * Add a new variable of name name and value val to the given context 462 * 463 * Input: 464 * name name of variable to add 465 * val value to set it to 466 * ctxt context in which to set it 467 * 468 * Results: 469 * None 470 * 471 * Side Effects: 472 * The new variable is placed at the front of the given context 473 * The name and val arguments are duplicated so they may 474 * safely be freed. 475 *----------------------------------------------------------------------- 476 */ 477 static void 478 VarAdd(const char *name, const char *val, GNode *ctxt) 479 { 480 Var *v; 481 int len; 482 Hash_Entry *h; 483 484 v = bmake_malloc(sizeof(Var)); 485 486 len = val ? strlen(val) : 0; 487 Buf_Init(&v->val, len+1); 488 Buf_AddBytes(&v->val, len, val); 489 490 v->flags = 0; 491 492 h = Hash_CreateEntry(&ctxt->context, name, NULL); 493 Hash_SetValue(h, v); 494 v->name = h->name; 495 if (DEBUG(VAR)) { 496 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); 497 } 498 } 499 500 /*- 501 *----------------------------------------------------------------------- 502 * Var_Delete -- 503 * Remove a variable from a context. 504 * 505 * Results: 506 * None. 507 * 508 * Side Effects: 509 * The Var structure is removed and freed. 510 * 511 *----------------------------------------------------------------------- 512 */ 513 void 514 Var_Delete(const char *name, GNode *ctxt) 515 { 516 Hash_Entry *ln; 517 518 ln = Hash_FindEntry(&ctxt->context, name); 519 if (DEBUG(VAR)) { 520 fprintf(debug_file, "%s:delete %s%s\n", 521 ctxt->name, name, ln ? "" : " (not found)"); 522 } 523 if (ln != NULL) { 524 Var *v; 525 526 v = (Var *)Hash_GetValue(ln); 527 if ((v->flags & VAR_EXPORTED)) { 528 unsetenv(v->name); 529 } 530 if (v->name != ln->name) 531 free(v->name); 532 Hash_DeleteEntry(&ctxt->context, ln); 533 Buf_Destroy(&v->val, TRUE); 534 free(v); 535 } 536 } 537 538 539 /* 540 * Export a var. 541 * We ignore make internal variables (those which start with '.') 542 * Also we jump through some hoops to avoid calling setenv 543 * more than necessary since it can leak. 544 * We only manipulate flags of vars if 'parent' is set. 545 */ 546 static int 547 Var_Export1(const char *name, int parent) 548 { 549 char tmp[BUFSIZ]; 550 Var *v; 551 char *val = NULL; 552 int n; 553 554 if (*name == '.') 555 return 0; /* skip internals */ 556 if (!name[1]) { 557 /* 558 * A single char. 559 * If it is one of the vars that should only appear in 560 * local context, skip it, else we can get Var_Subst 561 * into a loop. 562 */ 563 switch (name[0]) { 564 case '@': 565 case '%': 566 case '*': 567 case '!': 568 return 0; 569 } 570 } 571 v = VarFind(name, VAR_GLOBAL, 0); 572 if (v == NULL) { 573 return 0; 574 } 575 if (!parent && 576 (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) { 577 return 0; /* nothing to do */ 578 } 579 val = Buf_GetAll(&v->val, NULL); 580 if (strchr(val, '$')) { 581 if (parent) { 582 /* 583 * Flag this as something we need to re-export. 584 * No point actually exporting it now though, 585 * the child can do it at the last minute. 586 */ 587 v->flags |= (VAR_EXPORTED|VAR_REEXPORT); 588 return 1; 589 } 590 n = snprintf(tmp, sizeof(tmp), "${%s}", name); 591 if (n < (int)sizeof(tmp)) { 592 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0); 593 setenv(name, val, 1); 594 free(val); 595 } 596 } else { 597 if (parent) { 598 v->flags &= ~VAR_REEXPORT; /* once will do */ 599 } 600 if (parent || !(v->flags & VAR_EXPORTED)) { 601 setenv(name, val, 1); 602 } 603 } 604 /* 605 * This is so Var_Set knows to call Var_Export again... 606 */ 607 if (parent) { 608 v->flags |= VAR_EXPORTED; 609 } 610 return 1; 611 } 612 613 /* 614 * This gets called from our children. 615 */ 616 void 617 Var_ExportVars(void) 618 { 619 char tmp[BUFSIZ]; 620 Hash_Entry *var; 621 Hash_Search state; 622 Var *v; 623 char *val; 624 int n; 625 626 if (VAR_EXPORTED_NONE == var_exportedVars) 627 return; 628 629 if (VAR_EXPORTED_ALL == var_exportedVars) { 630 /* 631 * Ouch! This is crazy... 632 */ 633 for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state); 634 var != NULL; 635 var = Hash_EnumNext(&state)) { 636 v = (Var *)Hash_GetValue(var); 637 Var_Export1(v->name, 0); 638 } 639 return; 640 } 641 /* 642 * We have a number of exported vars, 643 */ 644 n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}"); 645 if (n < (int)sizeof(tmp)) { 646 char **av; 647 char *as; 648 int ac; 649 int i; 650 651 val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0); 652 av = brk_string(val, &ac, FALSE, &as); 653 for (i = 0; i < ac; i++) { 654 Var_Export1(av[i], 0); 655 } 656 free(val); 657 free(as); 658 free(av); 659 } 660 } 661 662 /* 663 * This is called when .export is seen or 664 * .MAKE.EXPORTED is modified. 665 * It is also called when any exported var is modified. 666 */ 667 void 668 Var_Export(char *str, int isExport) 669 { 670 char *name; 671 char *val; 672 char **av; 673 char *as; 674 int ac; 675 int i; 676 677 if (isExport && (!str || !str[0])) { 678 var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */ 679 return; 680 } 681 682 val = Var_Subst(NULL, str, VAR_GLOBAL, 0); 683 av = brk_string(val, &ac, FALSE, &as); 684 for (i = 0; i < ac; i++) { 685 name = av[i]; 686 if (!name[1]) { 687 /* 688 * A single char. 689 * If it is one of the vars that should only appear in 690 * local context, skip it, else we can get Var_Subst 691 * into a loop. 692 */ 693 switch (name[0]) { 694 case '@': 695 case '%': 696 case '*': 697 case '!': 698 continue; 699 } 700 } 701 if (Var_Export1(name, VAR_EXPORT_PARENT)) { 702 if (VAR_EXPORTED_ALL != var_exportedVars) 703 var_exportedVars = VAR_EXPORTED_YES; 704 if (isExport) { 705 Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL); 706 } 707 } 708 } 709 free(val); 710 free(as); 711 free(av); 712 } 713 714 /*- 715 *----------------------------------------------------------------------- 716 * Var_Set -- 717 * Set the variable name to the value val in the given context. 718 * 719 * Input: 720 * name name of variable to set 721 * val value to give to the variable 722 * ctxt context in which to set it 723 * 724 * Results: 725 * None. 726 * 727 * Side Effects: 728 * If the variable doesn't yet exist, a new record is created for it. 729 * Else the old value is freed and the new one stuck in its place 730 * 731 * Notes: 732 * The variable is searched for only in its context before being 733 * created in that context. I.e. if the context is VAR_GLOBAL, 734 * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only 735 * VAR_CMD->context is searched. This is done to avoid the literally 736 * thousands of unnecessary strcmp's that used to be done to 737 * set, say, $(@) or $(<). 738 * If the context is VAR_GLOBAL though, we check if the variable 739 * was set in VAR_CMD from the command line and skip it if so. 740 *----------------------------------------------------------------------- 741 */ 742 void 743 Var_Set(const char *name, const char *val, GNode *ctxt, int flags) 744 { 745 Var *v; 746 char *expanded_name = NULL; 747 748 /* 749 * We only look for a variable in the given context since anything set 750 * here will override anything in a lower context, so there's not much 751 * point in searching them all just to save a bit of memory... 752 */ 753 if (strchr(name, '$') != NULL) { 754 expanded_name = Var_Subst(NULL, name, ctxt, 0); 755 if (expanded_name[0] == 0) { 756 if (DEBUG(VAR)) { 757 fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) " 758 "name expands to empty string - ignored\n", 759 name, val); 760 } 761 free(expanded_name); 762 return; 763 } 764 name = expanded_name; 765 } 766 if (ctxt == VAR_GLOBAL) { 767 v = VarFind(name, VAR_CMD, 0); 768 if (v != NULL) { 769 if ((v->flags & VAR_FROM_CMD)) { 770 if (DEBUG(VAR)) { 771 fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val); 772 } 773 goto out; 774 } 775 VarFreeEnv(v, TRUE); 776 } 777 } 778 v = VarFind(name, ctxt, 0); 779 if (v == NULL) { 780 VarAdd(name, val, ctxt); 781 } else { 782 Buf_Empty(&v->val); 783 Buf_AddBytes(&v->val, strlen(val), val); 784 785 if (DEBUG(VAR)) { 786 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); 787 } 788 if ((v->flags & VAR_EXPORTED)) { 789 Var_Export1(name, VAR_EXPORT_PARENT); 790 } 791 } 792 /* 793 * Any variables given on the command line are automatically exported 794 * to the environment (as per POSIX standard) 795 */ 796 if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) { 797 if (v == NULL) { 798 /* we just added it */ 799 v = VarFind(name, ctxt, 0); 800 } 801 if (v != NULL) 802 v->flags |= VAR_FROM_CMD; 803 /* 804 * If requested, don't export these in the environment 805 * individually. We still put them in MAKEOVERRIDES so 806 * that the command-line settings continue to override 807 * Makefile settings. 808 */ 809 if (varNoExportEnv != TRUE) 810 setenv(name, val, 1); 811 812 Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL); 813 } 814 /* 815 * Another special case. 816 * Several make's support this sort of mechanism for tracking 817 * recursion - but each uses a different name. 818 * We allow the makefiles to update .MAKE.LEVEL and ensure 819 * children see a correctly incremented value. 820 */ 821 if (ctxt == VAR_GLOBAL && strcmp(MAKE_LEVEL, name) == 0) { 822 char tmp[64]; 823 int level; 824 825 level = atoi(val); 826 snprintf(tmp, sizeof(tmp), "%u", level + 1); 827 setenv(MAKE_LEVEL, tmp, 1); 828 } 829 830 831 out: 832 if (expanded_name != NULL) 833 free(expanded_name); 834 if (v != NULL) 835 VarFreeEnv(v, TRUE); 836 } 837 838 /*- 839 *----------------------------------------------------------------------- 840 * Var_Append -- 841 * The variable of the given name has the given value appended to it in 842 * the given context. 843 * 844 * Input: 845 * name name of variable to modify 846 * val String to append to it 847 * ctxt Context in which this should occur 848 * 849 * Results: 850 * None 851 * 852 * Side Effects: 853 * If the variable doesn't exist, it is created. Else the strings 854 * are concatenated (with a space in between). 855 * 856 * Notes: 857 * Only if the variable is being sought in the global context is the 858 * environment searched. 859 * XXX: Knows its calling circumstances in that if called with ctxt 860 * an actual target, it will only search that context since only 861 * a local variable could be being appended to. This is actually 862 * a big win and must be tolerated. 863 *----------------------------------------------------------------------- 864 */ 865 void 866 Var_Append(const char *name, const char *val, GNode *ctxt) 867 { 868 Var *v; 869 Hash_Entry *h; 870 char *expanded_name = NULL; 871 872 if (strchr(name, '$') != NULL) { 873 expanded_name = Var_Subst(NULL, name, ctxt, 0); 874 if (expanded_name[0] == 0) { 875 if (DEBUG(VAR)) { 876 fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) " 877 "name expands to empty string - ignored\n", 878 name, val); 879 } 880 free(expanded_name); 881 return; 882 } 883 name = expanded_name; 884 } 885 886 v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0); 887 888 if (v == NULL) { 889 VarAdd(name, val, ctxt); 890 } else { 891 Buf_AddByte(&v->val, ' '); 892 Buf_AddBytes(&v->val, strlen(val), val); 893 894 if (DEBUG(VAR)) { 895 fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, 896 Buf_GetAll(&v->val, NULL)); 897 } 898 899 if (v->flags & VAR_FROM_ENV) { 900 /* 901 * If the original variable came from the environment, we 902 * have to install it in the global context (we could place 903 * it in the environment, but then we should provide a way to 904 * export other variables...) 905 */ 906 v->flags &= ~VAR_FROM_ENV; 907 h = Hash_CreateEntry(&ctxt->context, name, NULL); 908 Hash_SetValue(h, v); 909 } 910 } 911 if (expanded_name != NULL) 912 free(expanded_name); 913 } 914 915 /*- 916 *----------------------------------------------------------------------- 917 * Var_Exists -- 918 * See if the given variable exists. 919 * 920 * Input: 921 * name Variable to find 922 * ctxt Context in which to start search 923 * 924 * Results: 925 * TRUE if it does, FALSE if it doesn't 926 * 927 * Side Effects: 928 * None. 929 * 930 *----------------------------------------------------------------------- 931 */ 932 Boolean 933 Var_Exists(const char *name, GNode *ctxt) 934 { 935 Var *v; 936 char *cp; 937 938 if ((cp = strchr(name, '$')) != NULL) { 939 cp = Var_Subst(NULL, name, ctxt, FALSE); 940 } 941 v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV); 942 if (cp != NULL) { 943 free(cp); 944 } 945 if (v == NULL) { 946 return(FALSE); 947 } else { 948 (void)VarFreeEnv(v, TRUE); 949 } 950 return(TRUE); 951 } 952 953 /*- 954 *----------------------------------------------------------------------- 955 * Var_Value -- 956 * Return the value of the named variable in the given context 957 * 958 * Input: 959 * name name to find 960 * ctxt context in which to search for it 961 * 962 * Results: 963 * The value if the variable exists, NULL if it doesn't 964 * 965 * Side Effects: 966 * None 967 *----------------------------------------------------------------------- 968 */ 969 char * 970 Var_Value(const char *name, GNode *ctxt, char **frp) 971 { 972 Var *v; 973 974 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); 975 *frp = NULL; 976 if (v != NULL) { 977 char *p = (Buf_GetAll(&v->val, NULL)); 978 if (VarFreeEnv(v, FALSE)) 979 *frp = p; 980 return p; 981 } else { 982 return NULL; 983 } 984 } 985 986 /*- 987 *----------------------------------------------------------------------- 988 * VarHead -- 989 * Remove the tail of the given word and place the result in the given 990 * buffer. 991 * 992 * Input: 993 * word Word to trim 994 * addSpace True if need to add a space to the buffer 995 * before sticking in the head 996 * buf Buffer in which to store it 997 * 998 * Results: 999 * TRUE if characters were added to the buffer (a space needs to be 1000 * added to the buffer before the next word). 1001 * 1002 * Side Effects: 1003 * The trimmed word is added to the buffer. 1004 * 1005 *----------------------------------------------------------------------- 1006 */ 1007 static Boolean 1008 VarHead(GNode *ctx __unused, Var_Parse_State *vpstate, 1009 char *word, Boolean addSpace, Buffer *buf, 1010 void *dummy) 1011 { 1012 char *slash; 1013 1014 slash = strrchr(word, '/'); 1015 if (slash != NULL) { 1016 if (addSpace && vpstate->varSpace) { 1017 Buf_AddByte(buf, vpstate->varSpace); 1018 } 1019 *slash = '\0'; 1020 Buf_AddBytes(buf, strlen(word), word); 1021 *slash = '/'; 1022 return (TRUE); 1023 } else { 1024 /* 1025 * If no directory part, give . (q.v. the POSIX standard) 1026 */ 1027 if (addSpace && vpstate->varSpace) 1028 Buf_AddByte(buf, vpstate->varSpace); 1029 Buf_AddByte(buf, '.'); 1030 } 1031 return(dummy ? TRUE : TRUE); 1032 } 1033 1034 /*- 1035 *----------------------------------------------------------------------- 1036 * VarTail -- 1037 * Remove the head of the given word and place the result in the given 1038 * buffer. 1039 * 1040 * Input: 1041 * word Word to trim 1042 * addSpace True if need to add a space to the buffer 1043 * before adding the tail 1044 * buf Buffer in which to store it 1045 * 1046 * Results: 1047 * TRUE if characters were added to the buffer (a space needs to be 1048 * added to the buffer before the next word). 1049 * 1050 * Side Effects: 1051 * The trimmed word is added to the buffer. 1052 * 1053 *----------------------------------------------------------------------- 1054 */ 1055 static Boolean 1056 VarTail(GNode *ctx __unused, Var_Parse_State *vpstate, 1057 char *word, Boolean addSpace, Buffer *buf, 1058 void *dummy) 1059 { 1060 char *slash; 1061 1062 if (addSpace && vpstate->varSpace) { 1063 Buf_AddByte(buf, vpstate->varSpace); 1064 } 1065 1066 slash = strrchr(word, '/'); 1067 if (slash != NULL) { 1068 *slash++ = '\0'; 1069 Buf_AddBytes(buf, strlen(slash), slash); 1070 slash[-1] = '/'; 1071 } else { 1072 Buf_AddBytes(buf, strlen(word), word); 1073 } 1074 return (dummy ? TRUE : TRUE); 1075 } 1076 1077 /*- 1078 *----------------------------------------------------------------------- 1079 * VarSuffix -- 1080 * Place the suffix of the given word in the given buffer. 1081 * 1082 * Input: 1083 * word Word to trim 1084 * addSpace TRUE if need to add a space before placing the 1085 * suffix in the buffer 1086 * buf Buffer in which to store it 1087 * 1088 * Results: 1089 * TRUE if characters were added to the buffer (a space needs to be 1090 * added to the buffer before the next word). 1091 * 1092 * Side Effects: 1093 * The suffix from the word is placed in the buffer. 1094 * 1095 *----------------------------------------------------------------------- 1096 */ 1097 static Boolean 1098 VarSuffix(GNode *ctx __unused, Var_Parse_State *vpstate, 1099 char *word, Boolean addSpace, Buffer *buf, 1100 void *dummy) 1101 { 1102 char *dot; 1103 1104 dot = strrchr(word, '.'); 1105 if (dot != NULL) { 1106 if (addSpace && vpstate->varSpace) { 1107 Buf_AddByte(buf, vpstate->varSpace); 1108 } 1109 *dot++ = '\0'; 1110 Buf_AddBytes(buf, strlen(dot), dot); 1111 dot[-1] = '.'; 1112 addSpace = TRUE; 1113 } 1114 return (dummy ? addSpace : addSpace); 1115 } 1116 1117 /*- 1118 *----------------------------------------------------------------------- 1119 * VarRoot -- 1120 * Remove the suffix of the given word and place the result in the 1121 * buffer. 1122 * 1123 * Input: 1124 * word Word to trim 1125 * addSpace TRUE if need to add a space to the buffer 1126 * before placing the root in it 1127 * buf Buffer in which to store it 1128 * 1129 * Results: 1130 * TRUE if characters were added to the buffer (a space needs to be 1131 * added to the buffer before the next word). 1132 * 1133 * Side Effects: 1134 * The trimmed word is added to the buffer. 1135 * 1136 *----------------------------------------------------------------------- 1137 */ 1138 static Boolean 1139 VarRoot(GNode *ctx __unused, Var_Parse_State *vpstate, 1140 char *word, Boolean addSpace, Buffer *buf, 1141 void *dummy) 1142 { 1143 char *dot; 1144 1145 if (addSpace && vpstate->varSpace) { 1146 Buf_AddByte(buf, vpstate->varSpace); 1147 } 1148 1149 dot = strrchr(word, '.'); 1150 if (dot != NULL) { 1151 *dot = '\0'; 1152 Buf_AddBytes(buf, strlen(word), word); 1153 *dot = '.'; 1154 } else { 1155 Buf_AddBytes(buf, strlen(word), word); 1156 } 1157 return (dummy ? TRUE : TRUE); 1158 } 1159 1160 /*- 1161 *----------------------------------------------------------------------- 1162 * VarMatch -- 1163 * Place the word in the buffer if it matches the given pattern. 1164 * Callback function for VarModify to implement the :M modifier. 1165 * 1166 * Input: 1167 * word Word to examine 1168 * addSpace TRUE if need to add a space to the buffer 1169 * before adding the word, if it matches 1170 * buf Buffer in which to store it 1171 * pattern Pattern the word must match 1172 * 1173 * Results: 1174 * TRUE if a space should be placed in the buffer before the next 1175 * word. 1176 * 1177 * Side Effects: 1178 * The word may be copied to the buffer. 1179 * 1180 *----------------------------------------------------------------------- 1181 */ 1182 static Boolean 1183 VarMatch(GNode *ctx __unused, Var_Parse_State *vpstate, 1184 char *word, Boolean addSpace, Buffer *buf, 1185 void *pattern) 1186 { 1187 if (DEBUG(VAR)) 1188 fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern); 1189 if (Str_Match(word, (char *)pattern)) { 1190 if (addSpace && vpstate->varSpace) { 1191 Buf_AddByte(buf, vpstate->varSpace); 1192 } 1193 addSpace = TRUE; 1194 Buf_AddBytes(buf, strlen(word), word); 1195 } 1196 return(addSpace); 1197 } 1198 1199 #ifdef SYSVVARSUB 1200 /*- 1201 *----------------------------------------------------------------------- 1202 * VarSYSVMatch -- 1203 * Place the word in the buffer if it matches the given pattern. 1204 * Callback function for VarModify to implement the System V % 1205 * modifiers. 1206 * 1207 * Input: 1208 * word Word to examine 1209 * addSpace TRUE if need to add a space to the buffer 1210 * before adding the word, if it matches 1211 * buf Buffer in which to store it 1212 * patp Pattern the word must match 1213 * 1214 * Results: 1215 * TRUE if a space should be placed in the buffer before the next 1216 * word. 1217 * 1218 * Side Effects: 1219 * The word may be copied to the buffer. 1220 * 1221 *----------------------------------------------------------------------- 1222 */ 1223 static Boolean 1224 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate, 1225 char *word, Boolean addSpace, Buffer *buf, 1226 void *patp) 1227 { 1228 int len; 1229 char *ptr; 1230 VarPattern *pat = (VarPattern *)patp; 1231 char *varexp; 1232 1233 if (addSpace && vpstate->varSpace) 1234 Buf_AddByte(buf, vpstate->varSpace); 1235 1236 addSpace = TRUE; 1237 1238 if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) { 1239 varexp = Var_Subst(NULL, pat->rhs, ctx, 0); 1240 Str_SYSVSubst(buf, varexp, ptr, len); 1241 free(varexp); 1242 } else { 1243 Buf_AddBytes(buf, strlen(word), word); 1244 } 1245 1246 return(addSpace); 1247 } 1248 #endif 1249 1250 1251 /*- 1252 *----------------------------------------------------------------------- 1253 * VarNoMatch -- 1254 * Place the word in the buffer if it doesn't match the given pattern. 1255 * Callback function for VarModify to implement the :N modifier. 1256 * 1257 * Input: 1258 * word Word to examine 1259 * addSpace TRUE if need to add a space to the buffer 1260 * before adding the word, if it matches 1261 * buf Buffer in which to store it 1262 * pattern Pattern the word must match 1263 * 1264 * Results: 1265 * TRUE if a space should be placed in the buffer before the next 1266 * word. 1267 * 1268 * Side Effects: 1269 * The word may be copied to the buffer. 1270 * 1271 *----------------------------------------------------------------------- 1272 */ 1273 static Boolean 1274 VarNoMatch(GNode *ctx __unused, Var_Parse_State *vpstate, 1275 char *word, Boolean addSpace, Buffer *buf, 1276 void *pattern) 1277 { 1278 if (!Str_Match(word, (char *)pattern)) { 1279 if (addSpace && vpstate->varSpace) { 1280 Buf_AddByte(buf, vpstate->varSpace); 1281 } 1282 addSpace = TRUE; 1283 Buf_AddBytes(buf, strlen(word), word); 1284 } 1285 return(addSpace); 1286 } 1287 1288 1289 /*- 1290 *----------------------------------------------------------------------- 1291 * VarSubstitute -- 1292 * Perform a string-substitution on the given word, placing the 1293 * result in the passed buffer. 1294 * 1295 * Input: 1296 * word Word to modify 1297 * addSpace True if space should be added before 1298 * other characters 1299 * buf Buffer for result 1300 * patternp Pattern for substitution 1301 * 1302 * Results: 1303 * TRUE if a space is needed before more characters are added. 1304 * 1305 * Side Effects: 1306 * None. 1307 * 1308 *----------------------------------------------------------------------- 1309 */ 1310 static Boolean 1311 VarSubstitute(GNode *ctx __unused, Var_Parse_State *vpstate, 1312 char *word, Boolean addSpace, Buffer *buf, 1313 void *patternp) 1314 { 1315 int wordLen; /* Length of word */ 1316 char *cp; /* General pointer */ 1317 VarPattern *pattern = (VarPattern *)patternp; 1318 1319 wordLen = strlen(word); 1320 if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) != 1321 (VAR_SUB_ONE|VAR_SUB_MATCHED)) { 1322 /* 1323 * Still substituting -- break it down into simple anchored cases 1324 * and if none of them fits, perform the general substitution case. 1325 */ 1326 if ((pattern->flags & VAR_MATCH_START) && 1327 (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) { 1328 /* 1329 * Anchored at start and beginning of word matches pattern 1330 */ 1331 if ((pattern->flags & VAR_MATCH_END) && 1332 (wordLen == pattern->leftLen)) { 1333 /* 1334 * Also anchored at end and matches to the end (word 1335 * is same length as pattern) add space and rhs only 1336 * if rhs is non-null. 1337 */ 1338 if (pattern->rightLen != 0) { 1339 if (addSpace && vpstate->varSpace) { 1340 Buf_AddByte(buf, vpstate->varSpace); 1341 } 1342 addSpace = TRUE; 1343 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); 1344 } 1345 pattern->flags |= VAR_SUB_MATCHED; 1346 } else if (pattern->flags & VAR_MATCH_END) { 1347 /* 1348 * Doesn't match to end -- copy word wholesale 1349 */ 1350 goto nosub; 1351 } else { 1352 /* 1353 * Matches at start but need to copy in trailing characters 1354 */ 1355 if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){ 1356 if (addSpace && vpstate->varSpace) { 1357 Buf_AddByte(buf, vpstate->varSpace); 1358 } 1359 addSpace = TRUE; 1360 } 1361 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); 1362 Buf_AddBytes(buf, wordLen - pattern->leftLen, 1363 (word + pattern->leftLen)); 1364 pattern->flags |= VAR_SUB_MATCHED; 1365 } 1366 } else if (pattern->flags & VAR_MATCH_START) { 1367 /* 1368 * Had to match at start of word and didn't -- copy whole word. 1369 */ 1370 goto nosub; 1371 } else if (pattern->flags & VAR_MATCH_END) { 1372 /* 1373 * Anchored at end, Find only place match could occur (leftLen 1374 * characters from the end of the word) and see if it does. Note 1375 * that because the $ will be left at the end of the lhs, we have 1376 * to use strncmp. 1377 */ 1378 cp = word + (wordLen - pattern->leftLen); 1379 if ((cp >= word) && 1380 (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) { 1381 /* 1382 * Match found. If we will place characters in the buffer, 1383 * add a space before hand as indicated by addSpace, then 1384 * stuff in the initial, unmatched part of the word followed 1385 * by the right-hand-side. 1386 */ 1387 if (((cp - word) + pattern->rightLen) != 0) { 1388 if (addSpace && vpstate->varSpace) { 1389 Buf_AddByte(buf, vpstate->varSpace); 1390 } 1391 addSpace = TRUE; 1392 } 1393 Buf_AddBytes(buf, cp - word, word); 1394 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); 1395 pattern->flags |= VAR_SUB_MATCHED; 1396 } else { 1397 /* 1398 * Had to match at end and didn't. Copy entire word. 1399 */ 1400 goto nosub; 1401 } 1402 } else { 1403 /* 1404 * Pattern is unanchored: search for the pattern in the word using 1405 * String_FindSubstring, copying unmatched portions and the 1406 * right-hand-side for each match found, handling non-global 1407 * substitutions correctly, etc. When the loop is done, any 1408 * remaining part of the word (word and wordLen are adjusted 1409 * accordingly through the loop) is copied straight into the 1410 * buffer. 1411 * addSpace is set FALSE as soon as a space is added to the 1412 * buffer. 1413 */ 1414 Boolean done; 1415 int origSize; 1416 1417 done = FALSE; 1418 origSize = Buf_Size(buf); 1419 while (!done) { 1420 cp = Str_FindSubstring(word, pattern->lhs); 1421 if (cp != NULL) { 1422 if (addSpace && (((cp - word) + pattern->rightLen) != 0)){ 1423 Buf_AddByte(buf, vpstate->varSpace); 1424 addSpace = FALSE; 1425 } 1426 Buf_AddBytes(buf, cp-word, word); 1427 Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); 1428 wordLen -= (cp - word) + pattern->leftLen; 1429 word = cp + pattern->leftLen; 1430 if (wordLen == 0) { 1431 done = TRUE; 1432 } 1433 if ((pattern->flags & VAR_SUB_GLOBAL) == 0) { 1434 done = TRUE; 1435 } 1436 pattern->flags |= VAR_SUB_MATCHED; 1437 } else { 1438 done = TRUE; 1439 } 1440 } 1441 if (wordLen != 0) { 1442 if (addSpace && vpstate->varSpace) { 1443 Buf_AddByte(buf, vpstate->varSpace); 1444 } 1445 Buf_AddBytes(buf, wordLen, word); 1446 } 1447 /* 1448 * If added characters to the buffer, need to add a space 1449 * before we add any more. If we didn't add any, just return 1450 * the previous value of addSpace. 1451 */ 1452 return ((Buf_Size(buf) != origSize) || addSpace); 1453 } 1454 return (addSpace); 1455 } 1456 nosub: 1457 if (addSpace && vpstate->varSpace) { 1458 Buf_AddByte(buf, vpstate->varSpace); 1459 } 1460 Buf_AddBytes(buf, wordLen, word); 1461 return(TRUE); 1462 } 1463 1464 #ifndef NO_REGEX 1465 /*- 1466 *----------------------------------------------------------------------- 1467 * VarREError -- 1468 * Print the error caused by a regcomp or regexec call. 1469 * 1470 * Results: 1471 * None. 1472 * 1473 * Side Effects: 1474 * An error gets printed. 1475 * 1476 *----------------------------------------------------------------------- 1477 */ 1478 static void 1479 VarREError(int errnum, regex_t *pat, const char *str) 1480 { 1481 char *errbuf; 1482 int errlen; 1483 1484 errlen = regerror(errnum, pat, 0, 0); 1485 errbuf = bmake_malloc(errlen); 1486 regerror(errnum, pat, errbuf, errlen); 1487 Error("%s: %s", str, errbuf); 1488 free(errbuf); 1489 } 1490 1491 1492 /*- 1493 *----------------------------------------------------------------------- 1494 * VarRESubstitute -- 1495 * Perform a regex substitution on the given word, placing the 1496 * result in the passed buffer. 1497 * 1498 * Results: 1499 * TRUE if a space is needed before more characters are added. 1500 * 1501 * Side Effects: 1502 * None. 1503 * 1504 *----------------------------------------------------------------------- 1505 */ 1506 static Boolean 1507 VarRESubstitute(GNode *ctx __unused, Var_Parse_State *vpstate __unused, 1508 char *word, Boolean addSpace, Buffer *buf, 1509 void *patternp) 1510 { 1511 VarREPattern *pat; 1512 int xrv; 1513 char *wp; 1514 char *rp; 1515 int added; 1516 int flags = 0; 1517 1518 #define MAYBE_ADD_SPACE() \ 1519 if (addSpace && !added) \ 1520 Buf_AddByte(buf, ' '); \ 1521 added = 1 1522 1523 added = 0; 1524 wp = word; 1525 pat = patternp; 1526 1527 if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) == 1528 (VAR_SUB_ONE|VAR_SUB_MATCHED)) 1529 xrv = REG_NOMATCH; 1530 else { 1531 tryagain: 1532 xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags); 1533 } 1534 1535 switch (xrv) { 1536 case 0: 1537 pat->flags |= VAR_SUB_MATCHED; 1538 if (pat->matches[0].rm_so > 0) { 1539 MAYBE_ADD_SPACE(); 1540 Buf_AddBytes(buf, pat->matches[0].rm_so, wp); 1541 } 1542 1543 for (rp = pat->replace; *rp; rp++) { 1544 if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) { 1545 MAYBE_ADD_SPACE(); 1546 Buf_AddByte(buf,rp[1]); 1547 rp++; 1548 } 1549 else if ((*rp == '&') || 1550 ((*rp == '\\') && isdigit((unsigned char)rp[1]))) { 1551 int n; 1552 const char *subbuf; 1553 int sublen; 1554 char errstr[3]; 1555 1556 if (*rp == '&') { 1557 n = 0; 1558 errstr[0] = '&'; 1559 errstr[1] = '\0'; 1560 } else { 1561 n = rp[1] - '0'; 1562 errstr[0] = '\\'; 1563 errstr[1] = rp[1]; 1564 errstr[2] = '\0'; 1565 rp++; 1566 } 1567 1568 if (n > pat->nsub) { 1569 Error("No subexpression %s", &errstr[0]); 1570 subbuf = ""; 1571 sublen = 0; 1572 } else if ((pat->matches[n].rm_so == -1) && 1573 (pat->matches[n].rm_eo == -1)) { 1574 Error("No match for subexpression %s", &errstr[0]); 1575 subbuf = ""; 1576 sublen = 0; 1577 } else { 1578 subbuf = wp + pat->matches[n].rm_so; 1579 sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so; 1580 } 1581 1582 if (sublen > 0) { 1583 MAYBE_ADD_SPACE(); 1584 Buf_AddBytes(buf, sublen, subbuf); 1585 } 1586 } else { 1587 MAYBE_ADD_SPACE(); 1588 Buf_AddByte(buf, *rp); 1589 } 1590 } 1591 wp += pat->matches[0].rm_eo; 1592 if (pat->flags & VAR_SUB_GLOBAL) { 1593 flags |= REG_NOTBOL; 1594 if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) { 1595 MAYBE_ADD_SPACE(); 1596 Buf_AddByte(buf, *wp); 1597 wp++; 1598 1599 } 1600 if (*wp) 1601 goto tryagain; 1602 } 1603 if (*wp) { 1604 MAYBE_ADD_SPACE(); 1605 Buf_AddBytes(buf, strlen(wp), wp); 1606 } 1607 break; 1608 default: 1609 VarREError(xrv, &pat->re, "Unexpected regex error"); 1610 /* fall through */ 1611 case REG_NOMATCH: 1612 if (*wp) { 1613 MAYBE_ADD_SPACE(); 1614 Buf_AddBytes(buf,strlen(wp),wp); 1615 } 1616 break; 1617 } 1618 return(addSpace||added); 1619 } 1620 #endif 1621 1622 1623 1624 /*- 1625 *----------------------------------------------------------------------- 1626 * VarLoopExpand -- 1627 * Implements the :@<temp>@<string>@ modifier of ODE make. 1628 * We set the temp variable named in pattern.lhs to word and expand 1629 * pattern.rhs storing the result in the passed buffer. 1630 * 1631 * Input: 1632 * word Word to modify 1633 * addSpace True if space should be added before 1634 * other characters 1635 * buf Buffer for result 1636 * pattern Datafor substitution 1637 * 1638 * Results: 1639 * TRUE if a space is needed before more characters are added. 1640 * 1641 * Side Effects: 1642 * None. 1643 * 1644 *----------------------------------------------------------------------- 1645 */ 1646 static Boolean 1647 VarLoopExpand(GNode *ctx __unused, Var_Parse_State *vpstate __unused, 1648 char *word, Boolean addSpace, Buffer *buf, 1649 void *loopp) 1650 { 1651 VarLoop_t *loop = (VarLoop_t *)loopp; 1652 char *s; 1653 int slen; 1654 1655 if (word && *word) { 1656 Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT); 1657 s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum); 1658 if (s != NULL && *s != '\0') { 1659 if (addSpace && *s != '\n') 1660 Buf_AddByte(buf, ' '); 1661 Buf_AddBytes(buf, (slen = strlen(s)), s); 1662 addSpace = (slen > 0 && s[slen - 1] != '\n'); 1663 free(s); 1664 } 1665 } 1666 return addSpace; 1667 } 1668 1669 1670 /*- 1671 *----------------------------------------------------------------------- 1672 * VarSelectWords -- 1673 * Implements the :[start..end] modifier. 1674 * This is a special case of VarModify since we want to be able 1675 * to scan the list backwards if start > end. 1676 * 1677 * Input: 1678 * str String whose words should be trimmed 1679 * seldata words to select 1680 * 1681 * Results: 1682 * A string of all the words selected. 1683 * 1684 * Side Effects: 1685 * None. 1686 * 1687 *----------------------------------------------------------------------- 1688 */ 1689 static char * 1690 VarSelectWords(GNode *ctx __unused, Var_Parse_State *vpstate, 1691 const char *str, VarSelectWords_t *seldata) 1692 { 1693 Buffer buf; /* Buffer for the new string */ 1694 Boolean addSpace; /* TRUE if need to add a space to the 1695 * buffer before adding the trimmed 1696 * word */ 1697 char **av; /* word list */ 1698 char *as; /* word list memory */ 1699 int ac, i; 1700 int start, end, step; 1701 1702 Buf_Init(&buf, 0); 1703 addSpace = FALSE; 1704 1705 if (vpstate->oneBigWord) { 1706 /* fake what brk_string() would do if there were only one word */ 1707 ac = 1; 1708 av = bmake_malloc((ac + 1) * sizeof(char *)); 1709 as = bmake_strdup(str); 1710 av[0] = as; 1711 av[1] = NULL; 1712 } else { 1713 av = brk_string(str, &ac, FALSE, &as); 1714 } 1715 1716 /* 1717 * Now sanitize seldata. 1718 * If seldata->start or seldata->end are negative, convert them to 1719 * the positive equivalents (-1 gets converted to argc, -2 gets 1720 * converted to (argc-1), etc.). 1721 */ 1722 if (seldata->start < 0) 1723 seldata->start = ac + seldata->start + 1; 1724 if (seldata->end < 0) 1725 seldata->end = ac + seldata->end + 1; 1726 1727 /* 1728 * We avoid scanning more of the list than we need to. 1729 */ 1730 if (seldata->start > seldata->end) { 1731 start = MIN(ac, seldata->start) - 1; 1732 end = MAX(0, seldata->end - 1); 1733 step = -1; 1734 } else { 1735 start = MAX(0, seldata->start - 1); 1736 end = MIN(ac, seldata->end); 1737 step = 1; 1738 } 1739 1740 for (i = start; 1741 (step < 0 && i >= end) || (step > 0 && i < end); 1742 i += step) { 1743 if (av[i] && *av[i]) { 1744 if (addSpace && vpstate->varSpace) { 1745 Buf_AddByte(&buf, vpstate->varSpace); 1746 } 1747 Buf_AddBytes(&buf, strlen(av[i]), av[i]); 1748 addSpace = TRUE; 1749 } 1750 } 1751 1752 free(as); 1753 free(av); 1754 1755 return Buf_Destroy(&buf, FALSE); 1756 } 1757 1758 /*- 1759 *----------------------------------------------------------------------- 1760 * VarModify -- 1761 * Modify each of the words of the passed string using the given 1762 * function. Used to implement all modifiers. 1763 * 1764 * Input: 1765 * str String whose words should be trimmed 1766 * modProc Function to use to modify them 1767 * datum Datum to pass it 1768 * 1769 * Results: 1770 * A string of all the words modified appropriately. 1771 * 1772 * Side Effects: 1773 * None. 1774 * 1775 *----------------------------------------------------------------------- 1776 */ 1777 static char * 1778 VarModify(GNode *ctx, Var_Parse_State *vpstate, 1779 const char *str, 1780 Boolean (*modProc)(GNode *, Var_Parse_State *, char *, 1781 Boolean, Buffer *, void *), 1782 void *datum) 1783 { 1784 Buffer buf; /* Buffer for the new string */ 1785 Boolean addSpace; /* TRUE if need to add a space to the 1786 * buffer before adding the trimmed 1787 * word */ 1788 char **av; /* word list */ 1789 char *as; /* word list memory */ 1790 int ac, i; 1791 1792 Buf_Init(&buf, 0); 1793 addSpace = FALSE; 1794 1795 if (vpstate->oneBigWord) { 1796 /* fake what brk_string() would do if there were only one word */ 1797 ac = 1; 1798 av = bmake_malloc((ac + 1) * sizeof(char *)); 1799 as = bmake_strdup(str); 1800 av[0] = as; 1801 av[1] = NULL; 1802 } else { 1803 av = brk_string(str, &ac, FALSE, &as); 1804 } 1805 1806 for (i = 0; i < ac; i++) { 1807 addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum); 1808 } 1809 1810 free(as); 1811 free(av); 1812 1813 return Buf_Destroy(&buf, FALSE); 1814 } 1815 1816 1817 static int 1818 VarWordCompare(const void *a, const void *b) 1819 { 1820 int r = strcmp(*(const char * const *)a, *(const char * const *)b); 1821 return r; 1822 } 1823 1824 /*- 1825 *----------------------------------------------------------------------- 1826 * VarOrder -- 1827 * Order the words in the string. 1828 * 1829 * Input: 1830 * str String whose words should be sorted. 1831 * otype How to order: s - sort, x - random. 1832 * 1833 * Results: 1834 * A string containing the words ordered. 1835 * 1836 * Side Effects: 1837 * None. 1838 * 1839 *----------------------------------------------------------------------- 1840 */ 1841 static char * 1842 VarOrder(const char *str, const char otype) 1843 { 1844 Buffer buf; /* Buffer for the new string */ 1845 char **av; /* word list [first word does not count] */ 1846 char *as; /* word list memory */ 1847 int ac, i; 1848 1849 Buf_Init(&buf, 0); 1850 1851 av = brk_string(str, &ac, FALSE, &as); 1852 1853 if (ac > 0) 1854 switch (otype) { 1855 case 's': /* sort alphabetically */ 1856 qsort(av, ac, sizeof(char *), VarWordCompare); 1857 break; 1858 case 'x': /* randomize */ 1859 { 1860 int rndidx; 1861 char *t; 1862 1863 /* 1864 * We will use [ac..2] range for mod factors. This will produce 1865 * random numbers in [(ac-1)..0] interval, and minimal 1866 * reasonable value for mod factor is 2 (the mod 1 will produce 1867 * 0 with probability 1). 1868 */ 1869 for (i = ac-1; i > 0; i--) { 1870 rndidx = random() % (i + 1); 1871 if (i != rndidx) { 1872 t = av[i]; 1873 av[i] = av[rndidx]; 1874 av[rndidx] = t; 1875 } 1876 } 1877 } 1878 } /* end of switch */ 1879 1880 for (i = 0; i < ac; i++) { 1881 Buf_AddBytes(&buf, strlen(av[i]), av[i]); 1882 if (i != ac - 1) 1883 Buf_AddByte(&buf, ' '); 1884 } 1885 1886 free(as); 1887 free(av); 1888 1889 return Buf_Destroy(&buf, FALSE); 1890 } 1891 1892 1893 /*- 1894 *----------------------------------------------------------------------- 1895 * VarUniq -- 1896 * Remove adjacent duplicate words. 1897 * 1898 * Input: 1899 * str String whose words should be sorted 1900 * 1901 * Results: 1902 * A string containing the resulting words. 1903 * 1904 * Side Effects: 1905 * None. 1906 * 1907 *----------------------------------------------------------------------- 1908 */ 1909 static char * 1910 VarUniq(const char *str) 1911 { 1912 Buffer buf; /* Buffer for new string */ 1913 char **av; /* List of words to affect */ 1914 char *as; /* Word list memory */ 1915 int ac, i, j; 1916 1917 Buf_Init(&buf, 0); 1918 av = brk_string(str, &ac, FALSE, &as); 1919 1920 if (ac > 1) { 1921 for (j = 0, i = 1; i < ac; i++) 1922 if (strcmp(av[i], av[j]) != 0 && (++j != i)) 1923 av[j] = av[i]; 1924 ac = j + 1; 1925 } 1926 1927 for (i = 0; i < ac; i++) { 1928 Buf_AddBytes(&buf, strlen(av[i]), av[i]); 1929 if (i != ac - 1) 1930 Buf_AddByte(&buf, ' '); 1931 } 1932 1933 free(as); 1934 free(av); 1935 1936 return Buf_Destroy(&buf, FALSE); 1937 } 1938 1939 1940 /*- 1941 *----------------------------------------------------------------------- 1942 * VarGetPattern -- 1943 * Pass through the tstr looking for 1) escaped delimiters, 1944 * '$'s and backslashes (place the escaped character in 1945 * uninterpreted) and 2) unescaped $'s that aren't before 1946 * the delimiter (expand the variable substitution unless flags 1947 * has VAR_NOSUBST set). 1948 * Return the expanded string or NULL if the delimiter was missing 1949 * If pattern is specified, handle escaped ampersands, and replace 1950 * unescaped ampersands with the lhs of the pattern. 1951 * 1952 * Results: 1953 * A string of all the words modified appropriately. 1954 * If length is specified, return the string length of the buffer 1955 * If flags is specified and the last character of the pattern is a 1956 * $ set the VAR_MATCH_END bit of flags. 1957 * 1958 * Side Effects: 1959 * None. 1960 *----------------------------------------------------------------------- 1961 */ 1962 static char * 1963 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate __unused, 1964 int errnum, const char **tstr, int delim, int *flags, 1965 int *length, VarPattern *pattern) 1966 { 1967 const char *cp; 1968 char *rstr; 1969 Buffer buf; 1970 int junk; 1971 1972 Buf_Init(&buf, 0); 1973 if (length == NULL) 1974 length = &junk; 1975 1976 #define IS_A_MATCH(cp, delim) \ 1977 ((cp[0] == '\\') && ((cp[1] == delim) || \ 1978 (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&')))) 1979 1980 /* 1981 * Skim through until the matching delimiter is found; 1982 * pick up variable substitutions on the way. Also allow 1983 * backslashes to quote the delimiter, $, and \, but don't 1984 * touch other backslashes. 1985 */ 1986 for (cp = *tstr; *cp && (*cp != delim); cp++) { 1987 if (IS_A_MATCH(cp, delim)) { 1988 Buf_AddByte(&buf, cp[1]); 1989 cp++; 1990 } else if (*cp == '$') { 1991 if (cp[1] == delim) { 1992 if (flags == NULL) 1993 Buf_AddByte(&buf, *cp); 1994 else 1995 /* 1996 * Unescaped $ at end of pattern => anchor 1997 * pattern at end. 1998 */ 1999 *flags |= VAR_MATCH_END; 2000 } else { 2001 if (flags == NULL || (*flags & VAR_NOSUBST) == 0) { 2002 char *cp2; 2003 int len; 2004 void *freeIt; 2005 2006 /* 2007 * If unescaped dollar sign not before the 2008 * delimiter, assume it's a variable 2009 * substitution and recurse. 2010 */ 2011 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt); 2012 Buf_AddBytes(&buf, strlen(cp2), cp2); 2013 if (freeIt) 2014 free(freeIt); 2015 cp += len - 1; 2016 } else { 2017 const char *cp2 = &cp[1]; 2018 2019 if (*cp2 == PROPEN || *cp2 == BROPEN) { 2020 /* 2021 * Find the end of this variable reference 2022 * and suck it in without further ado. 2023 * It will be interperated later. 2024 */ 2025 int have = *cp2; 2026 int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE; 2027 int depth = 1; 2028 2029 for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) { 2030 if (cp2[-1] != '\\') { 2031 if (*cp2 == have) 2032 ++depth; 2033 if (*cp2 == want) 2034 --depth; 2035 } 2036 } 2037 Buf_AddBytes(&buf, cp2 - cp, cp); 2038 cp = --cp2; 2039 } else 2040 Buf_AddByte(&buf, *cp); 2041 } 2042 } 2043 } 2044 else if (pattern && *cp == '&') 2045 Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs); 2046 else 2047 Buf_AddByte(&buf, *cp); 2048 } 2049 2050 if (*cp != delim) { 2051 *tstr = cp; 2052 *length = 0; 2053 return NULL; 2054 } 2055 2056 *tstr = ++cp; 2057 *length = Buf_Size(&buf); 2058 rstr = Buf_Destroy(&buf, FALSE); 2059 if (DEBUG(VAR)) 2060 fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr); 2061 return rstr; 2062 } 2063 2064 /*- 2065 *----------------------------------------------------------------------- 2066 * VarQuote -- 2067 * Quote shell meta-characters in the string 2068 * 2069 * Results: 2070 * The quoted string 2071 * 2072 * Side Effects: 2073 * None. 2074 * 2075 *----------------------------------------------------------------------- 2076 */ 2077 static char * 2078 VarQuote(char *str) 2079 { 2080 2081 Buffer buf; 2082 /* This should cover most shells :-( */ 2083 static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~"; 2084 const char *newline; 2085 size_t len, nlen; 2086 2087 if ((newline = Shell_GetNewline()) == NULL) 2088 newline = "\\\n"; 2089 nlen = strlen(newline); 2090 2091 Buf_Init(&buf, 0); 2092 while (*str != '\0') { 2093 if ((len = strcspn(str, meta)) != 0) { 2094 Buf_AddBytes(&buf, len, str); 2095 str += len; 2096 } else if (*str == '\n') { 2097 Buf_AddBytes(&buf, nlen, newline); 2098 ++str; 2099 } else { 2100 Buf_AddByte(&buf, '\\'); 2101 Buf_AddByte(&buf, *str); 2102 ++str; 2103 } 2104 } 2105 str = Buf_Destroy(&buf, FALSE); 2106 if (DEBUG(VAR)) 2107 fprintf(debug_file, "QuoteMeta: [%s]\n", str); 2108 return str; 2109 } 2110 2111 /*- 2112 *----------------------------------------------------------------------- 2113 * VarChangeCase -- 2114 * Change the string to all uppercase or all lowercase 2115 * 2116 * Input: 2117 * str String to modify 2118 * upper TRUE -> uppercase, else lowercase 2119 * 2120 * Results: 2121 * The string with case changed 2122 * 2123 * Side Effects: 2124 * None. 2125 * 2126 *----------------------------------------------------------------------- 2127 */ 2128 static char * 2129 VarChangeCase(char *str, int upper) 2130 { 2131 Buffer buf; 2132 int (*modProc)(int); 2133 2134 modProc = (upper ? toupper : tolower); 2135 Buf_Init(&buf, 0); 2136 for (; *str ; str++) { 2137 Buf_AddByte(&buf, modProc(*str)); 2138 } 2139 return Buf_Destroy(&buf, FALSE); 2140 } 2141 2142 /* 2143 * Now we need to apply any modifiers the user wants applied. 2144 * These are: 2145 * :M<pattern> words which match the given <pattern>. 2146 * <pattern> is of the standard file 2147 * wildcarding form. 2148 * :N<pattern> words which do not match the given <pattern>. 2149 * :S<d><pat1><d><pat2><d>[1gW] 2150 * Substitute <pat2> for <pat1> in the value 2151 * :C<d><pat1><d><pat2><d>[1gW] 2152 * Substitute <pat2> for regex <pat1> in the value 2153 * :H Substitute the head of each word 2154 * :T Substitute the tail of each word 2155 * :E Substitute the extension (minus '.') of 2156 * each word 2157 * :R Substitute the root of each word 2158 * (pathname minus the suffix). 2159 * :O ("Order") Alphabeticaly sort words in variable. 2160 * :Ox ("intermiX") Randomize words in variable. 2161 * :u ("uniq") Remove adjacent duplicate words. 2162 * :tu Converts the variable contents to uppercase. 2163 * :tl Converts the variable contents to lowercase. 2164 * :ts[c] Sets varSpace - the char used to 2165 * separate words to 'c'. If 'c' is 2166 * omitted then no separation is used. 2167 * :tW Treat the variable contents as a single 2168 * word, even if it contains spaces. 2169 * (Mnemonic: one big 'W'ord.) 2170 * :tw Treat the variable contents as multiple 2171 * space-separated words. 2172 * (Mnemonic: many small 'w'ords.) 2173 * :[index] Select a single word from the value. 2174 * :[start..end] Select multiple words from the value. 2175 * :[*] or :[0] Select the entire value, as a single 2176 * word. Equivalent to :tW. 2177 * :[@] Select the entire value, as multiple 2178 * words. Undoes the effect of :[*]. 2179 * Equivalent to :tw. 2180 * :[#] Returns the number of words in the value. 2181 * 2182 * :?<true-value>:<false-value> 2183 * If the variable evaluates to true, return 2184 * true value, else return the second value. 2185 * :lhs=rhs Like :S, but the rhs goes to the end of 2186 * the invocation. 2187 * :sh Treat the current value as a command 2188 * to be run, new value is its output. 2189 * The following added so we can handle ODE makefiles. 2190 * :@<tmpvar>@<newval>@ 2191 * Assign a temporary local variable <tmpvar> 2192 * to the current value of each word in turn 2193 * and replace each word with the result of 2194 * evaluating <newval> 2195 * :D<newval> Use <newval> as value if variable defined 2196 * :U<newval> Use <newval> as value if variable undefined 2197 * :L Use the name of the variable as the value. 2198 * :P Use the path of the node that has the same 2199 * name as the variable as the value. This 2200 * basically includes an implied :L so that 2201 * the common method of refering to the path 2202 * of your dependent 'x' in a rule is to use 2203 * the form '${x:P}'. 2204 * :!<cmd>! Run cmd much the same as :sh run's the 2205 * current value of the variable. 2206 * The ::= modifiers, actually assign a value to the variable. 2207 * Their main purpose is in supporting modifiers of .for loop 2208 * iterators and other obscure uses. They always expand to 2209 * nothing. In a target rule that would otherwise expand to an 2210 * empty line they can be preceded with @: to keep make happy. 2211 * Eg. 2212 * 2213 * foo: .USE 2214 * .for i in ${.TARGET} ${.TARGET:R}.gz 2215 * @: ${t::=$i} 2216 * @echo blah ${t:T} 2217 * .endfor 2218 * 2219 * ::=<str> Assigns <str> as the new value of variable. 2220 * ::?=<str> Assigns <str> as value of variable if 2221 * it was not already set. 2222 * ::+=<str> Appends <str> to variable. 2223 * ::!=<cmd> Assigns output of <cmd> as the new value of 2224 * variable. 2225 */ 2226 2227 static char * 2228 ApplyModifiers(char *nstr, const char *tstr, 2229 int startc, int endc, 2230 Var *v, GNode *ctxt, Boolean errnum, 2231 int *lengthPtr, void **freePtr) 2232 { 2233 const char *start; 2234 const char *cp; /* Secondary pointer into str (place marker 2235 * for tstr) */ 2236 char *newStr; /* New value to return */ 2237 char termc; /* Character which terminated scan */ 2238 int cnt; /* Used to count brace pairs when variable in 2239 * in parens or braces */ 2240 char delim; 2241 int modifier; /* that we are processing */ 2242 Var_Parse_State parsestate; /* Flags passed to helper functions */ 2243 2244 delim = '\0'; 2245 parsestate.oneBigWord = FALSE; 2246 parsestate.varSpace = ' '; /* word separator */ 2247 2248 start = cp = tstr; 2249 2250 while (*tstr && *tstr != endc) { 2251 2252 if (*tstr == '$') { 2253 /* 2254 * We have some complex modifiers in a variable. 2255 */ 2256 void *freeIt; 2257 char *rval; 2258 int rlen; 2259 2260 rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt); 2261 2262 if (DEBUG(VAR)) { 2263 fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n", 2264 rval, rlen, tstr, rlen, tstr + rlen); 2265 } 2266 2267 tstr += rlen; 2268 2269 if (rval != NULL && *rval) { 2270 int used; 2271 2272 nstr = ApplyModifiers(nstr, rval, 2273 0, 0, 2274 v, ctxt, errnum, &used, freePtr); 2275 if (nstr == var_Error 2276 || (nstr == varNoError && errnum == 0) 2277 || strlen(rval) != (size_t) used) { 2278 if (freeIt) 2279 free(freeIt); 2280 goto out; /* error already reported */ 2281 } 2282 } 2283 if (freeIt) 2284 free(freeIt); 2285 if (*tstr == ':') 2286 tstr++; 2287 else if (!*tstr && endc) { 2288 Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name); 2289 goto out; 2290 } 2291 continue; 2292 } 2293 if (DEBUG(VAR)) { 2294 fprintf(debug_file, "Applying :%c to \"%s\"\n", *tstr, nstr); 2295 } 2296 newStr = var_Error; 2297 switch ((modifier = *tstr)) { 2298 case ':': 2299 { 2300 if (tstr[1] == '=' || 2301 (tstr[2] == '=' && 2302 (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) { 2303 /* 2304 * "::=", "::!=", "::+=", or "::?=" 2305 */ 2306 GNode *v_ctxt; /* context where v belongs */ 2307 const char *emsg; 2308 char *sv_name; 2309 VarPattern pattern; 2310 int how; 2311 2312 if (v->name[0] == 0) 2313 goto bad_modifier; 2314 2315 v_ctxt = ctxt; 2316 sv_name = NULL; 2317 ++tstr; 2318 if (v->flags & VAR_JUNK) { 2319 /* 2320 * We need to bmake_strdup() it incase 2321 * VarGetPattern() recurses. 2322 */ 2323 sv_name = v->name; 2324 v->name = bmake_strdup(v->name); 2325 } else if (ctxt != VAR_GLOBAL) { 2326 Var *gv = VarFind(v->name, ctxt, 0); 2327 if (gv == NULL) 2328 v_ctxt = VAR_GLOBAL; 2329 else 2330 VarFreeEnv(gv, TRUE); 2331 } 2332 2333 switch ((how = *tstr)) { 2334 case '+': 2335 case '?': 2336 case '!': 2337 cp = &tstr[2]; 2338 break; 2339 default: 2340 cp = ++tstr; 2341 break; 2342 } 2343 delim = BRCLOSE; 2344 pattern.flags = 0; 2345 2346 pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum, 2347 &cp, delim, NULL, 2348 &pattern.rightLen, 2349 NULL); 2350 if (v->flags & VAR_JUNK) { 2351 /* restore original name */ 2352 free(v->name); 2353 v->name = sv_name; 2354 } 2355 if (pattern.rhs == NULL) 2356 goto cleanup; 2357 2358 termc = *--cp; 2359 delim = '\0'; 2360 2361 switch (how) { 2362 case '+': 2363 Var_Append(v->name, pattern.rhs, v_ctxt); 2364 break; 2365 case '!': 2366 newStr = Cmd_Exec(pattern.rhs, &emsg); 2367 if (emsg) 2368 Error(emsg, nstr); 2369 else 2370 Var_Set(v->name, newStr, v_ctxt, 0); 2371 if (newStr) 2372 free(newStr); 2373 break; 2374 case '?': 2375 if ((v->flags & VAR_JUNK) == 0) 2376 break; 2377 /* FALLTHROUGH */ 2378 default: 2379 Var_Set(v->name, pattern.rhs, v_ctxt, 0); 2380 break; 2381 } 2382 free(UNCONST(pattern.rhs)); 2383 newStr = var_Error; 2384 break; 2385 } 2386 goto default_case; /* "::<unrecognised>" */ 2387 } 2388 case '@': 2389 { 2390 VarLoop_t loop; 2391 int flags = VAR_NOSUBST; 2392 2393 cp = ++tstr; 2394 delim = '@'; 2395 if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum, 2396 &cp, delim, 2397 &flags, &loop.tvarLen, 2398 NULL)) == NULL) 2399 goto cleanup; 2400 2401 if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum, 2402 &cp, delim, 2403 &flags, &loop.strLen, 2404 NULL)) == NULL) 2405 goto cleanup; 2406 2407 termc = *cp; 2408 delim = '\0'; 2409 2410 loop.errnum = errnum; 2411 loop.ctxt = ctxt; 2412 newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand, 2413 &loop); 2414 free(loop.tvar); 2415 free(loop.str); 2416 break; 2417 } 2418 case 'D': 2419 case 'U': 2420 { 2421 Buffer buf; /* Buffer for patterns */ 2422 int wantit; /* want data in buffer */ 2423 2424 /* 2425 * Pass through tstr looking for 1) escaped delimiters, 2426 * '$'s and backslashes (place the escaped character in 2427 * uninterpreted) and 2) unescaped $'s that aren't before 2428 * the delimiter (expand the variable substitution). 2429 * The result is left in the Buffer buf. 2430 */ 2431 Buf_Init(&buf, 0); 2432 for (cp = tstr + 1; 2433 *cp != endc && *cp != ':' && *cp != '\0'; 2434 cp++) { 2435 if ((*cp == '\\') && 2436 ((cp[1] == ':') || 2437 (cp[1] == '$') || 2438 (cp[1] == endc) || 2439 (cp[1] == '\\'))) 2440 { 2441 Buf_AddByte(&buf, cp[1]); 2442 cp++; 2443 } else if (*cp == '$') { 2444 /* 2445 * If unescaped dollar sign, assume it's a 2446 * variable substitution and recurse. 2447 */ 2448 char *cp2; 2449 int len; 2450 void *freeIt; 2451 2452 cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt); 2453 Buf_AddBytes(&buf, strlen(cp2), cp2); 2454 if (freeIt) 2455 free(freeIt); 2456 cp += len - 1; 2457 } else { 2458 Buf_AddByte(&buf, *cp); 2459 } 2460 } 2461 2462 termc = *cp; 2463 2464 if (*tstr == 'U') 2465 wantit = ((v->flags & VAR_JUNK) != 0); 2466 else 2467 wantit = ((v->flags & VAR_JUNK) == 0); 2468 if ((v->flags & VAR_JUNK) != 0) 2469 v->flags |= VAR_KEEP; 2470 if (wantit) { 2471 newStr = Buf_Destroy(&buf, FALSE); 2472 } else { 2473 newStr = nstr; 2474 Buf_Destroy(&buf, TRUE); 2475 } 2476 break; 2477 } 2478 case 'L': 2479 { 2480 if ((v->flags & VAR_JUNK) != 0) 2481 v->flags |= VAR_KEEP; 2482 newStr = bmake_strdup(v->name); 2483 cp = ++tstr; 2484 termc = *tstr; 2485 break; 2486 } 2487 case 'P': 2488 { 2489 GNode *gn; 2490 2491 if ((v->flags & VAR_JUNK) != 0) 2492 v->flags |= VAR_KEEP; 2493 gn = Targ_FindNode(v->name, TARG_NOCREATE); 2494 if (gn == NULL || gn->type & OP_NOPATH) { 2495 newStr = NULL; 2496 } else if (gn->path) { 2497 newStr = bmake_strdup(gn->path); 2498 } else { 2499 newStr = Dir_FindFile(v->name, Suff_FindPath(gn)); 2500 } 2501 if (!newStr) { 2502 newStr = bmake_strdup(v->name); 2503 } 2504 cp = ++tstr; 2505 termc = *tstr; 2506 break; 2507 } 2508 case '!': 2509 { 2510 const char *emsg; 2511 VarPattern pattern; 2512 pattern.flags = 0; 2513 2514 delim = '!'; 2515 2516 cp = ++tstr; 2517 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum, 2518 &cp, delim, 2519 NULL, &pattern.rightLen, 2520 NULL)) == NULL) 2521 goto cleanup; 2522 newStr = Cmd_Exec(pattern.rhs, &emsg); 2523 free(UNCONST(pattern.rhs)); 2524 if (emsg) 2525 Error(emsg, nstr); 2526 termc = *cp; 2527 delim = '\0'; 2528 if (v->flags & VAR_JUNK) { 2529 v->flags |= VAR_KEEP; 2530 } 2531 break; 2532 } 2533 case '[': 2534 { 2535 /* 2536 * Look for the closing ']', recursively 2537 * expanding any embedded variables. 2538 * 2539 * estr is a pointer to the expanded result, 2540 * which we must free(). 2541 */ 2542 char *estr; 2543 2544 cp = tstr+1; /* point to char after '[' */ 2545 delim = ']'; /* look for closing ']' */ 2546 estr = VarGetPattern(ctxt, &parsestate, 2547 errnum, &cp, delim, 2548 NULL, NULL, NULL); 2549 if (estr == NULL) 2550 goto cleanup; /* report missing ']' */ 2551 /* now cp points just after the closing ']' */ 2552 delim = '\0'; 2553 if (cp[0] != ':' && cp[0] != endc) { 2554 /* Found junk after ']' */ 2555 free(estr); 2556 goto bad_modifier; 2557 } 2558 if (estr[0] == '\0') { 2559 /* Found empty square brackets in ":[]". */ 2560 free(estr); 2561 goto bad_modifier; 2562 } else if (estr[0] == '#' && estr[1] == '\0') { 2563 /* Found ":[#]" */ 2564 2565 /* 2566 * We will need enough space for the decimal 2567 * representation of an int. We calculate the 2568 * space needed for the octal representation, 2569 * and add enough slop to cope with a '-' sign 2570 * (which should never be needed) and a '\0' 2571 * string terminator. 2572 */ 2573 int newStrSize = 2574 (sizeof(int) * CHAR_BIT + 2) / 3 + 2; 2575 2576 newStr = bmake_malloc(newStrSize); 2577 if (parsestate.oneBigWord) { 2578 strncpy(newStr, "1", newStrSize); 2579 } else { 2580 /* XXX: brk_string() is a rather expensive 2581 * way of counting words. */ 2582 char **av; 2583 char *as; 2584 int ac; 2585 2586 av = brk_string(nstr, &ac, FALSE, &as); 2587 snprintf(newStr, newStrSize, "%d", ac); 2588 free(as); 2589 free(av); 2590 } 2591 termc = *cp; 2592 free(estr); 2593 break; 2594 } else if (estr[0] == '*' && estr[1] == '\0') { 2595 /* Found ":[*]" */ 2596 parsestate.oneBigWord = TRUE; 2597 newStr = nstr; 2598 termc = *cp; 2599 free(estr); 2600 break; 2601 } else if (estr[0] == '@' && estr[1] == '\0') { 2602 /* Found ":[@]" */ 2603 parsestate.oneBigWord = FALSE; 2604 newStr = nstr; 2605 termc = *cp; 2606 free(estr); 2607 break; 2608 } else { 2609 /* 2610 * We expect estr to contain a single 2611 * integer for :[N], or two integers 2612 * separated by ".." for :[start..end]. 2613 */ 2614 char *ep; 2615 2616 VarSelectWords_t seldata = { 0, 0 }; 2617 2618 seldata.start = strtol(estr, &ep, 0); 2619 if (ep == estr) { 2620 /* Found junk instead of a number */ 2621 free(estr); 2622 goto bad_modifier; 2623 } else if (ep[0] == '\0') { 2624 /* Found only one integer in :[N] */ 2625 seldata.end = seldata.start; 2626 } else if (ep[0] == '.' && ep[1] == '.' && 2627 ep[2] != '\0') { 2628 /* Expecting another integer after ".." */ 2629 ep += 2; 2630 seldata.end = strtol(ep, &ep, 0); 2631 if (ep[0] != '\0') { 2632 /* Found junk after ".." */ 2633 free(estr); 2634 goto bad_modifier; 2635 } 2636 } else { 2637 /* Found junk instead of ".." */ 2638 free(estr); 2639 goto bad_modifier; 2640 } 2641 /* 2642 * Now seldata is properly filled in, 2643 * but we still have to check for 0 as 2644 * a special case. 2645 */ 2646 if (seldata.start == 0 && seldata.end == 0) { 2647 /* ":[0]" or perhaps ":[0..0]" */ 2648 parsestate.oneBigWord = TRUE; 2649 newStr = nstr; 2650 termc = *cp; 2651 free(estr); 2652 break; 2653 } else if (seldata.start == 0 || 2654 seldata.end == 0) { 2655 /* ":[0..N]" or ":[N..0]" */ 2656 free(estr); 2657 goto bad_modifier; 2658 } 2659 /* 2660 * Normal case: select the words 2661 * described by seldata. 2662 */ 2663 newStr = VarSelectWords(ctxt, &parsestate, 2664 nstr, &seldata); 2665 2666 termc = *cp; 2667 free(estr); 2668 break; 2669 } 2670 2671 } 2672 case 't': 2673 { 2674 cp = tstr + 1; /* make sure it is set */ 2675 if (tstr[1] != endc && tstr[1] != ':') { 2676 if (tstr[1] == 's') { 2677 /* 2678 * Use the char (if any) at tstr[2] 2679 * as the word separator. 2680 */ 2681 VarPattern pattern; 2682 2683 if (tstr[2] != endc && 2684 (tstr[3] == endc || tstr[3] == ':')) { 2685 /* ":ts<unrecognised><endc>" or 2686 * ":ts<unrecognised>:" */ 2687 parsestate.varSpace = tstr[2]; 2688 cp = tstr + 3; 2689 } else if (tstr[2] == endc || tstr[2] == ':') { 2690 /* ":ts<endc>" or ":ts:" */ 2691 parsestate.varSpace = 0; /* no separator */ 2692 cp = tstr + 2; 2693 } else if (tstr[2] == '\\') { 2694 switch (tstr[3]) { 2695 case 'n': 2696 parsestate.varSpace = '\n'; 2697 cp = tstr + 4; 2698 break; 2699 case 't': 2700 parsestate.varSpace = '\t'; 2701 cp = tstr + 4; 2702 break; 2703 default: 2704 if (isdigit((unsigned char)tstr[3])) { 2705 char *ep; 2706 2707 parsestate.varSpace = 2708 strtoul(&tstr[3], &ep, 0); 2709 if (*ep != ':' && *ep != endc) 2710 goto bad_modifier; 2711 cp = ep; 2712 } else { 2713 /* 2714 * ":ts<backslash><unrecognised>". 2715 */ 2716 goto bad_modifier; 2717 } 2718 break; 2719 } 2720 } else { 2721 /* 2722 * Found ":ts<unrecognised><unrecognised>". 2723 */ 2724 goto bad_modifier; 2725 } 2726 2727 termc = *cp; 2728 2729 /* 2730 * We cannot be certain that VarModify 2731 * will be used - even if there is a 2732 * subsequent modifier, so do a no-op 2733 * VarSubstitute now to for str to be 2734 * re-expanded without the spaces. 2735 */ 2736 pattern.flags = VAR_SUB_ONE; 2737 pattern.lhs = pattern.rhs = "\032"; 2738 pattern.leftLen = pattern.rightLen = 1; 2739 2740 newStr = VarModify(ctxt, &parsestate, nstr, 2741 VarSubstitute, 2742 &pattern); 2743 } else if (tstr[2] == endc || tstr[2] == ':') { 2744 /* 2745 * Check for two-character options: 2746 * ":tu", ":tl" 2747 */ 2748 if (tstr[1] == 'u' || tstr[1] == 'l') { 2749 newStr = VarChangeCase(nstr, (tstr[1] == 'u')); 2750 cp = tstr + 2; 2751 termc = *cp; 2752 } else if (tstr[1] == 'W' || tstr[1] == 'w') { 2753 parsestate.oneBigWord = (tstr[1] == 'W'); 2754 newStr = nstr; 2755 cp = tstr + 2; 2756 termc = *cp; 2757 } else { 2758 /* Found ":t<unrecognised>:" or 2759 * ":t<unrecognised><endc>". */ 2760 goto bad_modifier; 2761 } 2762 } else { 2763 /* 2764 * Found ":t<unrecognised><unrecognised>". 2765 */ 2766 goto bad_modifier; 2767 } 2768 } else { 2769 /* 2770 * Found ":t<endc>" or ":t:". 2771 */ 2772 goto bad_modifier; 2773 } 2774 break; 2775 } 2776 case 'N': 2777 case 'M': 2778 { 2779 char *pattern; 2780 const char *endpat; /* points just after end of pattern */ 2781 char *cp2; 2782 Boolean copy; /* pattern should be, or has been, copied */ 2783 Boolean needSubst; 2784 int nest; 2785 2786 copy = FALSE; 2787 needSubst = FALSE; 2788 nest = 1; 2789 /* 2790 * In the loop below, ignore ':' unless we are at 2791 * (or back to) the original brace level. 2792 * XXX This will likely not work right if $() and ${} 2793 * are intermixed. 2794 */ 2795 for (cp = tstr + 1; 2796 *cp != '\0' && !(*cp == ':' && nest == 1); 2797 cp++) 2798 { 2799 if (*cp == '\\' && 2800 (cp[1] == ':' || 2801 cp[1] == endc || cp[1] == startc)) { 2802 if (!needSubst) { 2803 copy = TRUE; 2804 } 2805 cp++; 2806 continue; 2807 } 2808 if (*cp == '$') { 2809 needSubst = TRUE; 2810 } 2811 if (*cp == '(' || *cp == '{') 2812 ++nest; 2813 if (*cp == ')' || *cp == '}') { 2814 --nest; 2815 if (nest == 0) 2816 break; 2817 } 2818 } 2819 termc = *cp; 2820 endpat = cp; 2821 if (copy) { 2822 /* 2823 * Need to compress the \:'s out of the pattern, so 2824 * allocate enough room to hold the uncompressed 2825 * pattern (note that cp started at tstr+1, so 2826 * cp - tstr takes the null byte into account) and 2827 * compress the pattern into the space. 2828 */ 2829 pattern = bmake_malloc(cp - tstr); 2830 for (cp2 = pattern, cp = tstr + 1; 2831 cp < endpat; 2832 cp++, cp2++) 2833 { 2834 if ((*cp == '\\') && (cp+1 < endpat) && 2835 (cp[1] == ':' || cp[1] == endc)) { 2836 cp++; 2837 } 2838 *cp2 = *cp; 2839 } 2840 *cp2 = '\0'; 2841 endpat = cp2; 2842 } else { 2843 /* 2844 * Either Var_Subst or VarModify will need a 2845 * nul-terminated string soon, so construct one now. 2846 */ 2847 pattern = bmake_strndup(tstr+1, endpat - (tstr + 1)); 2848 } 2849 if (needSubst) { 2850 /* 2851 * pattern contains embedded '$', so use Var_Subst to 2852 * expand it. 2853 */ 2854 cp2 = pattern; 2855 pattern = Var_Subst(NULL, cp2, ctxt, errnum); 2856 free(cp2); 2857 } 2858 if (DEBUG(VAR)) 2859 fprintf(debug_file, "Pattern for [%s] is [%s]\n", nstr, 2860 pattern); 2861 if (*tstr == 'M') { 2862 newStr = VarModify(ctxt, &parsestate, nstr, VarMatch, 2863 pattern); 2864 } else { 2865 newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch, 2866 pattern); 2867 } 2868 free(pattern); 2869 break; 2870 } 2871 case 'S': 2872 { 2873 VarPattern pattern; 2874 Var_Parse_State tmpparsestate; 2875 2876 pattern.flags = 0; 2877 tmpparsestate = parsestate; 2878 delim = tstr[1]; 2879 tstr += 2; 2880 2881 /* 2882 * If pattern begins with '^', it is anchored to the 2883 * start of the word -- skip over it and flag pattern. 2884 */ 2885 if (*tstr == '^') { 2886 pattern.flags |= VAR_MATCH_START; 2887 tstr += 1; 2888 } 2889 2890 cp = tstr; 2891 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum, 2892 &cp, delim, 2893 &pattern.flags, 2894 &pattern.leftLen, 2895 NULL)) == NULL) 2896 goto cleanup; 2897 2898 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum, 2899 &cp, delim, NULL, 2900 &pattern.rightLen, 2901 &pattern)) == NULL) 2902 goto cleanup; 2903 2904 /* 2905 * Check for global substitution. If 'g' after the final 2906 * delimiter, substitution is global and is marked that 2907 * way. 2908 */ 2909 for (;; cp++) { 2910 switch (*cp) { 2911 case 'g': 2912 pattern.flags |= VAR_SUB_GLOBAL; 2913 continue; 2914 case '1': 2915 pattern.flags |= VAR_SUB_ONE; 2916 continue; 2917 case 'W': 2918 tmpparsestate.oneBigWord = TRUE; 2919 continue; 2920 } 2921 break; 2922 } 2923 2924 termc = *cp; 2925 newStr = VarModify(ctxt, &tmpparsestate, nstr, 2926 VarSubstitute, 2927 &pattern); 2928 2929 /* 2930 * Free the two strings. 2931 */ 2932 free(UNCONST(pattern.lhs)); 2933 free(UNCONST(pattern.rhs)); 2934 delim = '\0'; 2935 break; 2936 } 2937 case '?': 2938 { 2939 VarPattern pattern; 2940 Boolean value; 2941 2942 /* find ':', and then substitute accordingly */ 2943 2944 pattern.flags = 0; 2945 2946 cp = ++tstr; 2947 delim = ':'; 2948 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum, 2949 &cp, delim, NULL, 2950 &pattern.leftLen, 2951 NULL)) == NULL) 2952 goto cleanup; 2953 2954 /* BROPEN or PROPEN */ 2955 delim = endc; 2956 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum, 2957 &cp, delim, NULL, 2958 &pattern.rightLen, 2959 NULL)) == NULL) 2960 goto cleanup; 2961 2962 termc = *--cp; 2963 delim = '\0'; 2964 if (Cond_EvalExpression(NULL, v->name, &value, 0) 2965 == COND_INVALID) { 2966 Error("Bad conditional expression `%s' in %s?%s:%s", 2967 v->name, v->name, pattern.lhs, pattern.rhs); 2968 goto cleanup; 2969 } 2970 2971 if (value) { 2972 newStr = UNCONST(pattern.lhs); 2973 free(UNCONST(pattern.rhs)); 2974 } else { 2975 newStr = UNCONST(pattern.rhs); 2976 free(UNCONST(pattern.lhs)); 2977 } 2978 if (v->flags & VAR_JUNK) { 2979 v->flags |= VAR_KEEP; 2980 } 2981 break; 2982 } 2983 #ifndef NO_REGEX 2984 case 'C': 2985 { 2986 VarREPattern pattern; 2987 char *re; 2988 int error; 2989 Var_Parse_State tmpparsestate; 2990 2991 pattern.flags = 0; 2992 tmpparsestate = parsestate; 2993 delim = tstr[1]; 2994 tstr += 2; 2995 2996 cp = tstr; 2997 2998 if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim, 2999 NULL, NULL, NULL)) == NULL) 3000 goto cleanup; 3001 3002 if ((pattern.replace = VarGetPattern(ctxt, &parsestate, 3003 errnum, &cp, delim, NULL, 3004 NULL, NULL)) == NULL){ 3005 free(re); 3006 goto cleanup; 3007 } 3008 3009 for (;; cp++) { 3010 switch (*cp) { 3011 case 'g': 3012 pattern.flags |= VAR_SUB_GLOBAL; 3013 continue; 3014 case '1': 3015 pattern.flags |= VAR_SUB_ONE; 3016 continue; 3017 case 'W': 3018 tmpparsestate.oneBigWord = TRUE; 3019 continue; 3020 } 3021 break; 3022 } 3023 3024 termc = *cp; 3025 3026 error = regcomp(&pattern.re, re, REG_EXTENDED); 3027 free(re); 3028 if (error) { 3029 *lengthPtr = cp - start + 1; 3030 VarREError(error, &pattern.re, "RE substitution error"); 3031 free(pattern.replace); 3032 goto cleanup; 3033 } 3034 3035 pattern.nsub = pattern.re.re_nsub + 1; 3036 if (pattern.nsub < 1) 3037 pattern.nsub = 1; 3038 if (pattern.nsub > 10) 3039 pattern.nsub = 10; 3040 pattern.matches = bmake_malloc(pattern.nsub * 3041 sizeof(regmatch_t)); 3042 newStr = VarModify(ctxt, &tmpparsestate, nstr, 3043 VarRESubstitute, 3044 &pattern); 3045 regfree(&pattern.re); 3046 free(pattern.replace); 3047 free(pattern.matches); 3048 delim = '\0'; 3049 break; 3050 } 3051 #endif 3052 case 'Q': 3053 if (tstr[1] == endc || tstr[1] == ':') { 3054 newStr = VarQuote(nstr); 3055 cp = tstr + 1; 3056 termc = *cp; 3057 break; 3058 } 3059 goto default_case; 3060 case 'T': 3061 if (tstr[1] == endc || tstr[1] == ':') { 3062 newStr = VarModify(ctxt, &parsestate, nstr, VarTail, 3063 NULL); 3064 cp = tstr + 1; 3065 termc = *cp; 3066 break; 3067 } 3068 goto default_case; 3069 case 'H': 3070 if (tstr[1] == endc || tstr[1] == ':') { 3071 newStr = VarModify(ctxt, &parsestate, nstr, VarHead, 3072 NULL); 3073 cp = tstr + 1; 3074 termc = *cp; 3075 break; 3076 } 3077 goto default_case; 3078 case 'E': 3079 if (tstr[1] == endc || tstr[1] == ':') { 3080 newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix, 3081 NULL); 3082 cp = tstr + 1; 3083 termc = *cp; 3084 break; 3085 } 3086 goto default_case; 3087 case 'R': 3088 if (tstr[1] == endc || tstr[1] == ':') { 3089 newStr = VarModify(ctxt, &parsestate, nstr, VarRoot, 3090 NULL); 3091 cp = tstr + 1; 3092 termc = *cp; 3093 break; 3094 } 3095 goto default_case; 3096 case 'O': 3097 { 3098 char otype; 3099 3100 cp = tstr + 1; /* skip to the rest in any case */ 3101 if (tstr[1] == endc || tstr[1] == ':') { 3102 otype = 's'; 3103 termc = *cp; 3104 } else if ( (tstr[1] == 'x') && 3105 (tstr[2] == endc || tstr[2] == ':') ) { 3106 otype = tstr[1]; 3107 cp = tstr + 2; 3108 termc = *cp; 3109 } else { 3110 goto bad_modifier; 3111 } 3112 newStr = VarOrder(nstr, otype); 3113 break; 3114 } 3115 case 'u': 3116 if (tstr[1] == endc || tstr[1] == ':') { 3117 newStr = VarUniq(nstr); 3118 cp = tstr + 1; 3119 termc = *cp; 3120 break; 3121 } 3122 goto default_case; 3123 #ifdef SUNSHCMD 3124 case 's': 3125 if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) { 3126 const char *emsg; 3127 newStr = Cmd_Exec(nstr, &emsg); 3128 if (emsg) 3129 Error(emsg, nstr); 3130 cp = tstr + 2; 3131 termc = *cp; 3132 break; 3133 } 3134 goto default_case; 3135 #endif 3136 default: 3137 default_case: 3138 { 3139 #ifdef SYSVVARSUB 3140 /* 3141 * This can either be a bogus modifier or a System-V 3142 * substitution command. 3143 */ 3144 VarPattern pattern; 3145 Boolean eqFound; 3146 3147 pattern.flags = 0; 3148 eqFound = FALSE; 3149 /* 3150 * First we make a pass through the string trying 3151 * to verify it is a SYSV-make-style translation: 3152 * it must be: <string1>=<string2>) 3153 */ 3154 cp = tstr; 3155 cnt = 1; 3156 while (*cp != '\0' && cnt) { 3157 if (*cp == '=') { 3158 eqFound = TRUE; 3159 /* continue looking for endc */ 3160 } 3161 else if (*cp == endc) 3162 cnt--; 3163 else if (*cp == startc) 3164 cnt++; 3165 if (cnt) 3166 cp++; 3167 } 3168 if (*cp == endc && eqFound) { 3169 3170 /* 3171 * Now we break this sucker into the lhs and 3172 * rhs. We must null terminate them of course. 3173 */ 3174 delim='='; 3175 cp = tstr; 3176 if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, 3177 errnum, &cp, delim, &pattern.flags, 3178 &pattern.leftLen, NULL)) == NULL) 3179 goto cleanup; 3180 delim = endc; 3181 if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, 3182 errnum, &cp, delim, NULL, &pattern.rightLen, 3183 &pattern)) == NULL) 3184 goto cleanup; 3185 3186 /* 3187 * SYSV modifications happen through the whole 3188 * string. Note the pattern is anchored at the end. 3189 */ 3190 termc = *--cp; 3191 delim = '\0'; 3192 newStr = VarModify(ctxt, &parsestate, nstr, 3193 VarSYSVMatch, 3194 &pattern); 3195 free(UNCONST(pattern.lhs)); 3196 free(UNCONST(pattern.rhs)); 3197 } else 3198 #endif 3199 { 3200 Error("Unknown modifier '%c'", *tstr); 3201 for (cp = tstr+1; 3202 *cp != ':' && *cp != endc && *cp != '\0'; 3203 cp++) 3204 continue; 3205 termc = *cp; 3206 newStr = var_Error; 3207 } 3208 } 3209 } 3210 if (DEBUG(VAR)) { 3211 fprintf(debug_file, "Result of :%c is \"%s\"\n", modifier, newStr); 3212 } 3213 3214 if (newStr != nstr) { 3215 if (*freePtr) { 3216 free(nstr); 3217 *freePtr = NULL; 3218 } 3219 nstr = newStr; 3220 if (nstr != var_Error && nstr != varNoError) { 3221 *freePtr = nstr; 3222 } 3223 } 3224 if (termc == '\0' && endc != '\0') { 3225 Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier); 3226 } else if (termc == ':') { 3227 cp++; 3228 } 3229 tstr = cp; 3230 } 3231 out: 3232 *lengthPtr = tstr - start; 3233 return (nstr); 3234 3235 bad_modifier: 3236 /* "{(" */ 3237 Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr, 3238 v->name); 3239 3240 cleanup: 3241 *lengthPtr = cp - start; 3242 if (delim != '\0') 3243 Error("Unclosed substitution for %s (%c missing)", 3244 v->name, delim); 3245 if (*freePtr) { 3246 free(*freePtr); 3247 *freePtr = NULL; 3248 } 3249 return (var_Error); 3250 } 3251 3252 /*- 3253 *----------------------------------------------------------------------- 3254 * Var_Parse -- 3255 * Given the start of a variable invocation, extract the variable 3256 * name and find its value, then modify it according to the 3257 * specification. 3258 * 3259 * Input: 3260 * str The string to parse 3261 * ctxt The context for the variable 3262 * errnum TRUE if undefined variables are an error 3263 * lengthPtr OUT: The length of the specification 3264 * freePtr OUT: Non-NULL if caller should free *freePtr 3265 * 3266 * Results: 3267 * The (possibly-modified) value of the variable or var_Error if the 3268 * specification is invalid. The length of the specification is 3269 * placed in *lengthPtr (for invalid specifications, this is just 3270 * 2...?). 3271 * If *freePtr is non-NULL then it's a pointer that the caller 3272 * should pass to free() to free memory used by the result. 3273 * 3274 * Side Effects: 3275 * None. 3276 * 3277 *----------------------------------------------------------------------- 3278 */ 3279 /* coverity[+alloc : arg-*4] */ 3280 char * 3281 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr, 3282 void **freePtr) 3283 { 3284 const char *tstr; /* Pointer into str */ 3285 Var *v; /* Variable in invocation */ 3286 Boolean haveModifier;/* TRUE if have modifiers for the variable */ 3287 char endc; /* Ending character when variable in parens 3288 * or braces */ 3289 char startc; /* Starting character when variable in parens 3290 * or braces */ 3291 int vlen; /* Length of variable name */ 3292 const char *start; /* Points to original start of str */ 3293 char *nstr; /* New string, used during expansion */ 3294 Boolean dynamic; /* TRUE if the variable is local and we're 3295 * expanding it in a non-local context. This 3296 * is done to support dynamic sources. The 3297 * result is just the invocation, unaltered */ 3298 Var_Parse_State parsestate; /* Flags passed to helper functions */ 3299 char name[2]; 3300 3301 *freePtr = NULL; 3302 dynamic = FALSE; 3303 start = str; 3304 parsestate.oneBigWord = FALSE; 3305 parsestate.varSpace = ' '; /* word separator */ 3306 3307 startc = str[1]; 3308 if (startc != PROPEN && startc != BROPEN) { 3309 /* 3310 * If it's not bounded by braces of some sort, life is much simpler. 3311 * We just need to check for the first character and return the 3312 * value if it exists. 3313 */ 3314 3315 /* Error out some really stupid names */ 3316 if (startc == '\0' || strchr(")}:$", startc)) { 3317 *lengthPtr = 1; 3318 return var_Error; 3319 } 3320 name[0] = startc; 3321 name[1] = '\0'; 3322 3323 v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); 3324 if (v == NULL) { 3325 *lengthPtr = 2; 3326 3327 if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) { 3328 /* 3329 * If substituting a local variable in a non-local context, 3330 * assume it's for dynamic source stuff. We have to handle 3331 * this specially and return the longhand for the variable 3332 * with the dollar sign escaped so it makes it back to the 3333 * caller. Only four of the local variables are treated 3334 * specially as they are the only four that will be set 3335 * when dynamic sources are expanded. 3336 */ 3337 switch (str[1]) { 3338 case '@': 3339 return UNCONST("$(.TARGET)"); 3340 case '%': 3341 return UNCONST("$(.ARCHIVE)"); 3342 case '*': 3343 return UNCONST("$(.PREFIX)"); 3344 case '!': 3345 return UNCONST("$(.MEMBER)"); 3346 } 3347 } 3348 /* 3349 * Error 3350 */ 3351 return (errnum ? var_Error : varNoError); 3352 } else { 3353 haveModifier = FALSE; 3354 tstr = &str[1]; 3355 endc = str[1]; 3356 } 3357 } else { 3358 Buffer buf; /* Holds the variable name */ 3359 3360 endc = startc == PROPEN ? PRCLOSE : BRCLOSE; 3361 Buf_Init(&buf, 0); 3362 3363 /* 3364 * Skip to the end character or a colon, whichever comes first. 3365 */ 3366 for (tstr = str + 2; 3367 *tstr != '\0' && *tstr != endc && *tstr != ':'; 3368 tstr++) 3369 { 3370 /* 3371 * A variable inside a variable, expand 3372 */ 3373 if (*tstr == '$') { 3374 int rlen; 3375 void *freeIt; 3376 char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt); 3377 if (rval != NULL) { 3378 Buf_AddBytes(&buf, strlen(rval), rval); 3379 } 3380 if (freeIt) 3381 free(freeIt); 3382 tstr += rlen - 1; 3383 } 3384 else 3385 Buf_AddByte(&buf, *tstr); 3386 } 3387 if (*tstr == ':') { 3388 haveModifier = TRUE; 3389 } else if (*tstr != '\0') { 3390 haveModifier = FALSE; 3391 } else { 3392 /* 3393 * If we never did find the end character, return NULL 3394 * right now, setting the length to be the distance to 3395 * the end of the string, since that's what make does. 3396 */ 3397 *lengthPtr = tstr - str; 3398 Buf_Destroy(&buf, TRUE); 3399 return (var_Error); 3400 } 3401 str = Buf_GetAll(&buf, &vlen); 3402 3403 /* 3404 * At this point, str points into newly allocated memory from 3405 * buf, containing only the name of the variable. 3406 * 3407 * start and tstr point into the const string that was pointed 3408 * to by the original value of the str parameter. start points 3409 * to the '$' at the beginning of the string, while tstr points 3410 * to the char just after the end of the variable name -- this 3411 * will be '\0', ':', PRCLOSE, or BRCLOSE. 3412 */ 3413 3414 v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); 3415 /* 3416 * Check also for bogus D and F forms of local variables since we're 3417 * in a local context and the name is the right length. 3418 */ 3419 if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) && 3420 (vlen == 2) && (str[1] == 'F' || str[1] == 'D') && 3421 strchr("@%*!<>", str[0]) != NULL) { 3422 /* 3423 * Well, it's local -- go look for it. 3424 */ 3425 name[0] = *str; 3426 name[1] = '\0'; 3427 v = VarFind(name, ctxt, 0); 3428 3429 if (v != NULL) { 3430 /* 3431 * No need for nested expansion or anything, as we're 3432 * the only one who sets these things and we sure don't 3433 * but nested invocations in them... 3434 */ 3435 nstr = Buf_GetAll(&v->val, NULL); 3436 3437 if (str[1] == 'D') { 3438 nstr = VarModify(ctxt, &parsestate, nstr, VarHead, 3439 NULL); 3440 } else { 3441 nstr = VarModify(ctxt, &parsestate, nstr, VarTail, 3442 NULL); 3443 } 3444 /* 3445 * Resulting string is dynamically allocated, so 3446 * tell caller to free it. 3447 */ 3448 *freePtr = nstr; 3449 *lengthPtr = tstr-start+1; 3450 Buf_Destroy(&buf, TRUE); 3451 VarFreeEnv(v, TRUE); 3452 return nstr; 3453 } 3454 } 3455 3456 if (v == NULL) { 3457 if (((vlen == 1) || 3458 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) && 3459 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL))) 3460 { 3461 /* 3462 * If substituting a local variable in a non-local context, 3463 * assume it's for dynamic source stuff. We have to handle 3464 * this specially and return the longhand for the variable 3465 * with the dollar sign escaped so it makes it back to the 3466 * caller. Only four of the local variables are treated 3467 * specially as they are the only four that will be set 3468 * when dynamic sources are expanded. 3469 */ 3470 switch (*str) { 3471 case '@': 3472 case '%': 3473 case '*': 3474 case '!': 3475 dynamic = TRUE; 3476 break; 3477 } 3478 } else if ((vlen > 2) && (*str == '.') && 3479 isupper((unsigned char) str[1]) && 3480 ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL))) 3481 { 3482 int len; 3483 3484 len = vlen - 1; 3485 if ((strncmp(str, ".TARGET", len) == 0) || 3486 (strncmp(str, ".ARCHIVE", len) == 0) || 3487 (strncmp(str, ".PREFIX", len) == 0) || 3488 (strncmp(str, ".MEMBER", len) == 0)) 3489 { 3490 dynamic = TRUE; 3491 } 3492 } 3493 3494 if (!haveModifier) { 3495 /* 3496 * No modifiers -- have specification length so we can return 3497 * now. 3498 */ 3499 *lengthPtr = tstr - start + 1; 3500 if (dynamic) { 3501 char *pstr = bmake_strndup(start, *lengthPtr); 3502 *freePtr = pstr; 3503 Buf_Destroy(&buf, TRUE); 3504 return(pstr); 3505 } else { 3506 Buf_Destroy(&buf, TRUE); 3507 return (errnum ? var_Error : varNoError); 3508 } 3509 } else { 3510 /* 3511 * Still need to get to the end of the variable specification, 3512 * so kludge up a Var structure for the modifications 3513 */ 3514 v = bmake_malloc(sizeof(Var)); 3515 v->name = UNCONST(str); 3516 Buf_Init(&v->val, 1); 3517 v->flags = VAR_JUNK; 3518 Buf_Destroy(&buf, FALSE); 3519 } 3520 } else 3521 Buf_Destroy(&buf, TRUE); 3522 } 3523 3524 if (v->flags & VAR_IN_USE) { 3525 Fatal("Variable %s is recursive.", v->name); 3526 /*NOTREACHED*/ 3527 } else { 3528 v->flags |= VAR_IN_USE; 3529 } 3530 /* 3531 * Before doing any modification, we have to make sure the value 3532 * has been fully expanded. If it looks like recursion might be 3533 * necessary (there's a dollar sign somewhere in the variable's value) 3534 * we just call Var_Subst to do any other substitutions that are 3535 * necessary. Note that the value returned by Var_Subst will have 3536 * been dynamically-allocated, so it will need freeing when we 3537 * return. 3538 */ 3539 nstr = Buf_GetAll(&v->val, NULL); 3540 if (strchr(nstr, '$') != NULL) { 3541 nstr = Var_Subst(NULL, nstr, ctxt, errnum); 3542 *freePtr = nstr; 3543 } 3544 3545 v->flags &= ~VAR_IN_USE; 3546 3547 if ((nstr != NULL) && haveModifier) { 3548 int used; 3549 /* 3550 * Skip initial colon. 3551 */ 3552 tstr++; 3553 3554 nstr = ApplyModifiers(nstr, tstr, startc, endc, 3555 v, ctxt, errnum, &used, freePtr); 3556 tstr += used; 3557 } 3558 if (*tstr) { 3559 *lengthPtr = tstr - start + 1; 3560 } else { 3561 *lengthPtr = tstr - start; 3562 } 3563 3564 if (v->flags & VAR_FROM_ENV) { 3565 Boolean destroy = FALSE; 3566 3567 if (nstr != Buf_GetAll(&v->val, NULL)) { 3568 destroy = TRUE; 3569 } else { 3570 /* 3571 * Returning the value unmodified, so tell the caller to free 3572 * the thing. 3573 */ 3574 *freePtr = nstr; 3575 } 3576 VarFreeEnv(v, destroy); 3577 } else if (v->flags & VAR_JUNK) { 3578 /* 3579 * Perform any free'ing needed and set *freePtr to NULL so the caller 3580 * doesn't try to free a static pointer. 3581 * If VAR_KEEP is also set then we want to keep str as is. 3582 */ 3583 if (!(v->flags & VAR_KEEP)) { 3584 if (*freePtr) { 3585 free(nstr); 3586 *freePtr = NULL; 3587 } 3588 if (dynamic) { 3589 nstr = bmake_strndup(start, *lengthPtr); 3590 *freePtr = nstr; 3591 } else { 3592 nstr = var_Error; 3593 } 3594 } 3595 if (nstr != Buf_GetAll(&v->val, NULL)) 3596 Buf_Destroy(&v->val, TRUE); 3597 free(v->name); 3598 free(v); 3599 } 3600 return (nstr); 3601 } 3602 3603 /*- 3604 *----------------------------------------------------------------------- 3605 * Var_Subst -- 3606 * Substitute for all variables in the given string in the given context 3607 * If undefErr is TRUE, Parse_Error will be called when an undefined 3608 * variable is encountered. 3609 * 3610 * Input: 3611 * var Named variable || NULL for all 3612 * str the string which to substitute 3613 * ctxt the context wherein to find variables 3614 * undefErr TRUE if undefineds are an error 3615 * 3616 * Results: 3617 * The resulting string. 3618 * 3619 * Side Effects: 3620 * None. The old string must be freed by the caller 3621 *----------------------------------------------------------------------- 3622 */ 3623 char * 3624 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr) 3625 { 3626 Buffer buf; /* Buffer for forming things */ 3627 char *val; /* Value to substitute for a variable */ 3628 int length; /* Length of the variable invocation */ 3629 Boolean trailingBslash; /* variable ends in \ */ 3630 void *freeIt = NULL; /* Set if it should be freed */ 3631 static Boolean errorReported; /* Set true if an error has already 3632 * been reported to prevent a plethora 3633 * of messages when recursing */ 3634 3635 Buf_Init(&buf, 0); 3636 errorReported = FALSE; 3637 trailingBslash = FALSE; 3638 3639 while (*str) { 3640 if (*str == '\n' && trailingBslash) 3641 Buf_AddByte(&buf, ' '); 3642 if (var == NULL && (*str == '$') && (str[1] == '$')) { 3643 /* 3644 * A dollar sign may be escaped either with another dollar sign. 3645 * In such a case, we skip over the escape character and store the 3646 * dollar sign into the buffer directly. 3647 */ 3648 str++; 3649 Buf_AddByte(&buf, *str); 3650 str++; 3651 } else if (*str != '$') { 3652 /* 3653 * Skip as many characters as possible -- either to the end of 3654 * the string or to the next dollar sign (variable invocation). 3655 */ 3656 const char *cp; 3657 3658 for (cp = str++; *str != '$' && *str != '\0'; str++) 3659 continue; 3660 Buf_AddBytes(&buf, str - cp, cp); 3661 } else { 3662 if (var != NULL) { 3663 int expand; 3664 for (;;) { 3665 if (str[1] == '\0') { 3666 /* A trailing $ is kind of a special case */ 3667 Buf_AddByte(&buf, str[0]); 3668 str++; 3669 expand = FALSE; 3670 } else if (str[1] != PROPEN && str[1] != BROPEN) { 3671 if (str[1] != *var || strlen(var) > 1) { 3672 Buf_AddBytes(&buf, 2, str); 3673 str += 2; 3674 expand = FALSE; 3675 } 3676 else 3677 expand = TRUE; 3678 break; 3679 } 3680 else { 3681 const char *p; 3682 3683 /* 3684 * Scan up to the end of the variable name. 3685 */ 3686 for (p = &str[2]; *p && 3687 *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++) 3688 if (*p == '$') 3689 break; 3690 /* 3691 * A variable inside the variable. We cannot expand 3692 * the external variable yet, so we try again with 3693 * the nested one 3694 */ 3695 if (*p == '$') { 3696 Buf_AddBytes(&buf, p - str, str); 3697 str = p; 3698 continue; 3699 } 3700 3701 if (strncmp(var, str + 2, p - str - 2) != 0 || 3702 var[p - str - 2] != '\0') { 3703 /* 3704 * Not the variable we want to expand, scan 3705 * until the next variable 3706 */ 3707 for (;*p != '$' && *p != '\0'; p++) 3708 continue; 3709 Buf_AddBytes(&buf, p - str, str); 3710 str = p; 3711 expand = FALSE; 3712 } 3713 else 3714 expand = TRUE; 3715 break; 3716 } 3717 } 3718 if (!expand) 3719 continue; 3720 } 3721 3722 val = Var_Parse(str, ctxt, undefErr, &length, &freeIt); 3723 3724 /* 3725 * When we come down here, val should either point to the 3726 * value of this variable, suitably modified, or be NULL. 3727 * Length should be the total length of the potential 3728 * variable invocation (from $ to end character...) 3729 */ 3730 if (val == var_Error || val == varNoError) { 3731 /* 3732 * If performing old-time variable substitution, skip over 3733 * the variable and continue with the substitution. Otherwise, 3734 * store the dollar sign and advance str so we continue with 3735 * the string... 3736 */ 3737 if (oldVars) { 3738 str += length; 3739 } else if (undefErr) { 3740 /* 3741 * If variable is undefined, complain and skip the 3742 * variable. The complaint will stop us from doing anything 3743 * when the file is parsed. 3744 */ 3745 if (!errorReported) { 3746 Parse_Error(PARSE_FATAL, 3747 "Undefined variable \"%.*s\"",length,str); 3748 } 3749 str += length; 3750 errorReported = TRUE; 3751 } else { 3752 Buf_AddByte(&buf, *str); 3753 str += 1; 3754 } 3755 } else { 3756 /* 3757 * We've now got a variable structure to store in. But first, 3758 * advance the string pointer. 3759 */ 3760 str += length; 3761 3762 /* 3763 * Copy all the characters from the variable value straight 3764 * into the new string. 3765 */ 3766 length = strlen(val); 3767 Buf_AddBytes(&buf, length, val); 3768 trailingBslash = length > 0 && val[length - 1] == '\\'; 3769 } 3770 if (freeIt) { 3771 free(freeIt); 3772 freeIt = NULL; 3773 } 3774 } 3775 } 3776 3777 return Buf_Destroy(&buf, FALSE); 3778 } 3779 3780 /*- 3781 *----------------------------------------------------------------------- 3782 * Var_GetTail -- 3783 * Return the tail from each of a list of words. Used to set the 3784 * System V local variables. 3785 * 3786 * Input: 3787 * file Filename to modify 3788 * 3789 * Results: 3790 * The resulting string. 3791 * 3792 * Side Effects: 3793 * None. 3794 * 3795 *----------------------------------------------------------------------- 3796 */ 3797 #if 0 3798 char * 3799 Var_GetTail(char *file) 3800 { 3801 return(VarModify(file, VarTail, NULL)); 3802 } 3803 3804 /*- 3805 *----------------------------------------------------------------------- 3806 * Var_GetHead -- 3807 * Find the leading components of a (list of) filename(s). 3808 * XXX: VarHead does not replace foo by ., as (sun) System V make 3809 * does. 3810 * 3811 * Input: 3812 * file Filename to manipulate 3813 * 3814 * Results: 3815 * The leading components. 3816 * 3817 * Side Effects: 3818 * None. 3819 * 3820 *----------------------------------------------------------------------- 3821 */ 3822 char * 3823 Var_GetHead(char *file) 3824 { 3825 return(VarModify(file, VarHead, NULL)); 3826 } 3827 #endif 3828 3829 /*- 3830 *----------------------------------------------------------------------- 3831 * Var_Init -- 3832 * Initialize the module 3833 * 3834 * Results: 3835 * None 3836 * 3837 * Side Effects: 3838 * The VAR_CMD and VAR_GLOBAL contexts are created 3839 *----------------------------------------------------------------------- 3840 */ 3841 void 3842 Var_Init(void) 3843 { 3844 VAR_GLOBAL = Targ_NewGN("Global"); 3845 VAR_CMD = Targ_NewGN("Command"); 3846 3847 } 3848 3849 3850 void 3851 Var_End(void) 3852 { 3853 } 3854 3855 3856 /****************** PRINT DEBUGGING INFO *****************/ 3857 static void 3858 VarPrintVar(void *vp) 3859 { 3860 Var *v = (Var *)vp; 3861 fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL)); 3862 } 3863 3864 /*- 3865 *----------------------------------------------------------------------- 3866 * Var_Dump -- 3867 * print all variables in a context 3868 *----------------------------------------------------------------------- 3869 */ 3870 void 3871 Var_Dump(GNode *ctxt) 3872 { 3873 Hash_Search search; 3874 Hash_Entry *h; 3875 3876 for (h = Hash_EnumFirst(&ctxt->context, &search); 3877 h != NULL; 3878 h = Hash_EnumNext(&search)) { 3879 VarPrintVar(Hash_GetValue(h)); 3880 } 3881 } 3882