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