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