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