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