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