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