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