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