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