1 /* $OpenPackages$ */ 2 /* $OpenBSD: var.c,v 1.85 2009/05/13 10:47:54 espie Exp $ */ 3 /* $NetBSD: var.c,v 1.18 1997/03/18 19:24:46 christos Exp $ */ 4 5 /* 6 * Copyright (c) 1999,2000,2007 Marc Espie. 7 * 8 * Extensive code modifications for the OpenBSD project. 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 * 19 * THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBSD 23 * PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 */ 31 /* 32 * Copyright (c) 1988, 1989, 1990, 1993 33 * The Regents of the University of California. All rights reserved. 34 * Copyright (c) 1989 by Berkeley Softworks 35 * All rights reserved. 36 * 37 * This code is derived from software contributed to Berkeley by 38 * Adam de Boor. 39 * 40 * Redistribution and use in source and binary forms, with or without 41 * modification, are permitted provided that the following conditions 42 * are met: 43 * 1. Redistributions of source code must retain the above copyright 44 * notice, this list of conditions and the following disclaimer. 45 * 2. Redistributions in binary form must reproduce the above copyright 46 * notice, this list of conditions and the following disclaimer in the 47 * documentation and/or other materials provided with the distribution. 48 * 3. Neither the name of the University nor the names of its contributors 49 * may be used to endorse or promote products derived from this software 50 * without specific prior written permission. 51 * 52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 62 * SUCH DAMAGE. 63 */ 64 65 #include <assert.h> 66 #include <stddef.h> 67 #include <stdio.h> 68 #include <stdint.h> 69 #include <stdlib.h> 70 #include <string.h> 71 72 #include "config.h" 73 #include "defines.h" 74 #include "buf.h" 75 #include "stats.h" 76 #include "ohash.h" 77 #include "pathnames.h" 78 #include "varmodifiers.h" 79 #include "var.h" 80 #include "varname.h" 81 #include "error.h" 82 #include "str.h" 83 #include "var_int.h" 84 #include "memory.h" 85 #include "symtable.h" 86 #include "gnode.h" 87 88 /* 89 * This is a harmless return value for Var_Parse that can be used by Var_Subst 90 * to determine if there was an error in parsing -- easier than returning 91 * a flag, as things outside this module don't give a hoot. 92 */ 93 char var_Error[] = ""; 94 95 /* 96 * Similar to var_Error, but returned when the 'err' flag for Var_Parse is 97 * set false. Why not just use a constant? Well, gcc likes to condense 98 * identical string instances... 99 */ 100 static char varNoError[] = ""; 101 bool errorIsOkay; 102 static bool checkEnvFirst; /* true if environment should be searched for 103 * variables before the global context */ 104 105 void 106 Var_setCheckEnvFirst(bool yes) 107 { 108 checkEnvFirst = yes; 109 } 110 111 /* 112 * The rules for variable look-up are complicated. 113 * 114 * - Dynamic variables like $@ and $* are special. They always pertain to 115 * a given variable. In this implementation of make, it is an error to 116 * try to affect them manually. They are stored in a local symtable directly 117 * inside the gnode. 118 * 119 * Global variables can be obtained: 120 * - from the command line 121 * - from the environment 122 * - from the Makefile proper. 123 * All of these are stored in a hash global_variables. 124 * 125 * Variables set on the command line override Makefile contents, are 126 * passed to submakes (see Var_AddCmdLine), and are also exported to the 127 * environment. 128 * 129 * Without -e (!checkEnvFirst), make will see variables set in the 130 * Makefile, and default to the environment otherwise. 131 * 132 * With -e (checkEnvFirst), make will see the environment first, and that 133 * will override anything that's set in the Makefile (but not set on 134 * the command line). 135 * 136 * The SHELL variable is very special: it is never obtained from the 137 * environment, and never passed to the environment. 138 */ 139 140 /* definitions pertaining to dynamic variables */ 141 142 /* full names of dynamic variables */ 143 static char *varnames[] = { 144 TARGET, 145 PREFIX, 146 ARCHIVE, 147 MEMBER, 148 OODATE, 149 ALLSRC, 150 IMPSRC, 151 FTARGET, 152 DTARGET, 153 FPREFIX, 154 DPREFIX, 155 FARCHIVE, 156 DARCHIVE, 157 FMEMBER, 158 DMEMBER 159 }; 160 161 /* hashed names of dynamic variables */ 162 #include "varhashconsts.h" 163 164 /* extended indices for System V stuff */ 165 #define FTARGET_INDEX 7 166 #define DTARGET_INDEX 8 167 #define FPREFIX_INDEX 9 168 #define DPREFIX_INDEX 10 169 #define FARCHIVE_INDEX 11 170 #define DARCHIVE_INDEX 12 171 #define FMEMBER_INDEX 13 172 #define DMEMBER_INDEX 14 173 174 #define GLOBAL_INDEX -1 175 176 #define EXTENDED2SIMPLE(i) (((i)-LOCAL_SIZE)/2) 177 #define IS_EXTENDED_F(i) ((i)%2 == 1) 178 179 180 static struct ohash global_variables; 181 182 183 typedef struct Var_ { 184 BUFFER val; /* the variable value */ 185 unsigned int flags; /* miscellaneous status flags */ 186 #define VAR_IN_USE 1 /* Variable's value currently being used. */ 187 /* (Used to avoid recursion) */ 188 #define VAR_DUMMY 2 /* Variable is currently just a name */ 189 /* In particular: BUFFER is invalid */ 190 #define VAR_FROM_CMD 4 /* Special source: command line */ 191 #define VAR_FROM_ENV 8 /* Special source: environment */ 192 #define VAR_SEEN_ENV 16 /* No need to go look up environment again */ 193 #define VAR_SHELL 32 /* Magic behavior */ 194 195 #define POISONS (POISON_NORMAL | POISON_EMPTY | POISON_NOT_DEFINED) 196 /* Defined in var.h */ 197 char name[1]; /* the variable's name */ 198 } Var; 199 200 201 static struct ohash_info var_info = { 202 offsetof(Var, name), 203 NULL, 204 hash_alloc, hash_free, element_alloc 205 }; 206 207 static int classify_var(const char *, const char **, uint32_t *); 208 static Var *find_global_var(const char *, const char *, uint32_t); 209 static Var *find_global_var_without_env(const char *, const char *, uint32_t); 210 static void fill_from_env(Var *); 211 static Var *create_var(const char *, const char *); 212 static void var_set_initial_value(Var *, const char *); 213 static void var_set_value(Var *, const char *); 214 #define var_get_value(v) Buf_Retrieve(&((v)->val)) 215 static void var_append_value(Var *, const char *); 216 static void poison_check(Var *); 217 static void var_set_append(const char *, const char *, const char *, int, bool); 218 static void set_magic_shell_variable(void); 219 220 static void delete_var(Var *); 221 static void print_var(Var *); 222 223 224 static const char *find_rparen(const char *); 225 static const char *find_ket(const char *); 226 typedef const char * (*find_t)(const char *); 227 static find_t find_pos(int); 228 static void push_used(Var *); 229 static void pop_used(Var *); 230 static char *get_expanded_value(const char *, const char *, int, uint32_t, 231 SymTable *, bool, bool *); 232 static bool parse_base_variable_name(const char **, struct Name *, SymTable *); 233 234 235 236 /* Variable lookup function: return idx for dynamic variable, or 237 * GLOBAL_INDEX if name is not dynamic. Set up *pk for further use. 238 */ 239 static int 240 classify_var(const char *name, const char **enamePtr, uint32_t *pk) 241 { 242 size_t len; 243 244 *pk = ohash_interval(name, enamePtr); 245 len = *enamePtr - name; 246 /* substitute short version for long local name */ 247 switch (*pk % MAGICSLOTS1) { /* MAGICSLOTS should be the */ 248 case K_LONGALLSRC % MAGICSLOTS1:/* smallest constant yielding */ 249 /* distinct case values */ 250 if (*pk == K_LONGALLSRC && len == strlen(LONGALLSRC) && 251 strncmp(name, LONGALLSRC, len) == 0) 252 return ALLSRC_INDEX; 253 break; 254 case K_LONGARCHIVE % MAGICSLOTS1: 255 if (*pk == K_LONGARCHIVE && len == strlen(LONGARCHIVE) && 256 strncmp(name, LONGARCHIVE, len) == 0) 257 return ARCHIVE_INDEX; 258 break; 259 case K_LONGIMPSRC % MAGICSLOTS1: 260 if (*pk == K_LONGIMPSRC && len == strlen(LONGIMPSRC) && 261 strncmp(name, LONGIMPSRC, len) == 0) 262 return IMPSRC_INDEX; 263 break; 264 case K_LONGMEMBER % MAGICSLOTS1: 265 if (*pk == K_LONGMEMBER && len == strlen(LONGMEMBER) && 266 strncmp(name, LONGMEMBER, len) == 0) 267 return MEMBER_INDEX; 268 break; 269 case K_LONGOODATE % MAGICSLOTS1: 270 if (*pk == K_LONGOODATE && len == strlen(LONGOODATE) && 271 strncmp(name, LONGOODATE, len) == 0) 272 return OODATE_INDEX; 273 break; 274 case K_LONGPREFIX % MAGICSLOTS1: 275 if (*pk == K_LONGPREFIX && len == strlen(LONGPREFIX) && 276 strncmp(name, LONGPREFIX, len) == 0) 277 return PREFIX_INDEX; 278 break; 279 case K_LONGTARGET % MAGICSLOTS1: 280 if (*pk == K_LONGTARGET && len == strlen(LONGTARGET) && 281 strncmp(name, LONGTARGET, len) == 0) 282 return TARGET_INDEX; 283 break; 284 case K_TARGET % MAGICSLOTS1: 285 if (name[0] == TARGET[0] && len == 1) 286 return TARGET_INDEX; 287 break; 288 case K_OODATE % MAGICSLOTS1: 289 if (name[0] == OODATE[0] && len == 1) 290 return OODATE_INDEX; 291 break; 292 case K_ALLSRC % MAGICSLOTS1: 293 if (name[0] == ALLSRC[0] && len == 1) 294 return ALLSRC_INDEX; 295 break; 296 case K_IMPSRC % MAGICSLOTS1: 297 if (name[0] == IMPSRC[0] && len == 1) 298 return IMPSRC_INDEX; 299 break; 300 case K_PREFIX % MAGICSLOTS1: 301 if (name[0] == PREFIX[0] && len == 1) 302 return PREFIX_INDEX; 303 break; 304 case K_ARCHIVE % MAGICSLOTS1: 305 if (name[0] == ARCHIVE[0] && len == 1) 306 return ARCHIVE_INDEX; 307 break; 308 case K_MEMBER % MAGICSLOTS1: 309 if (name[0] == MEMBER[0] && len == 1) 310 return MEMBER_INDEX; 311 break; 312 case K_FTARGET % MAGICSLOTS1: 313 if (name[0] == FTARGET[0] && name[1] == FTARGET[1] && len == 2) 314 return FTARGET_INDEX; 315 break; 316 case K_DTARGET % MAGICSLOTS1: 317 if (name[0] == DTARGET[0] && name[1] == DTARGET[1] && len == 2) 318 return DTARGET_INDEX; 319 break; 320 case K_FPREFIX % MAGICSLOTS1: 321 if (name[0] == FPREFIX[0] && name[1] == FPREFIX[1] && len == 2) 322 return FPREFIX_INDEX; 323 break; 324 case K_DPREFIX % MAGICSLOTS1: 325 if (name[0] == DPREFIX[0] && name[1] == DPREFIX[1] && len == 2) 326 return DPREFIX_INDEX; 327 break; 328 case K_FARCHIVE % MAGICSLOTS1: 329 if (name[0] == FARCHIVE[0] && name[1] == FARCHIVE[1] && 330 len == 2) 331 return FARCHIVE_INDEX; 332 break; 333 case K_DARCHIVE % MAGICSLOTS1: 334 if (name[0] == DARCHIVE[0] && name[1] == DARCHIVE[1] && 335 len == 2) 336 return DARCHIVE_INDEX; 337 break; 338 case K_FMEMBER % MAGICSLOTS1: 339 if (name[0] == FMEMBER[0] && name[1] == FMEMBER[1] && len == 2) 340 return FMEMBER_INDEX; 341 break; 342 case K_DMEMBER % MAGICSLOTS1: 343 if (name[0] == DMEMBER[0] && name[1] == DMEMBER[1] && len == 2) 344 return DMEMBER_INDEX; 345 break; 346 default: 347 break; 348 } 349 return GLOBAL_INDEX; 350 } 351 352 353 /*** 354 *** Internal handling of variables. 355 ***/ 356 357 358 /* Create a new variable, does not initialize anything except the name. 359 * in particular, buffer is invalid, and flag value is invalid. Accordingly, 360 * must either: 361 * - set flags to VAR_DUMMY 362 * - set flags to !VAR_DUMMY, and initialize buffer, for instance with 363 * var_set_initial_value(). 364 */ 365 static Var * 366 create_var(const char *name, const char *ename) 367 { 368 return ohash_create_entry(&var_info, name, &ename); 369 } 370 371 /* Initial version of var_set_value(), to be called after create_var(). 372 */ 373 static void 374 var_set_initial_value(Var *v, const char *val) 375 { 376 size_t len; 377 378 len = strlen(val); 379 Buf_Init(&(v->val), len+1); 380 Buf_AddChars(&(v->val), len, val); 381 } 382 383 /* Normal version of var_set_value(), to be called after variable is fully 384 * initialized. 385 */ 386 static void 387 var_set_value(Var *v, const char *val) 388 { 389 if ((v->flags & VAR_DUMMY) == 0) { 390 Buf_Reset(&(v->val)); 391 Buf_AddString(&(v->val), val); 392 } else { 393 var_set_initial_value(v, val); 394 v->flags &= ~VAR_DUMMY; 395 } 396 } 397 398 /* Add to a variable, insert a separating space if the variable was already 399 * defined. 400 */ 401 static void 402 var_append_value(Var *v, const char *val) 403 { 404 if ((v->flags & VAR_DUMMY) == 0) { 405 Buf_AddSpace(&(v->val)); 406 Buf_AddString(&(v->val), val); 407 } else { 408 var_set_initial_value(v, val); 409 v->flags &= ~VAR_DUMMY; 410 } 411 } 412 413 414 /* Delete a variable and all the space associated with it. 415 */ 416 static void 417 delete_var(Var *v) 418 { 419 if ((v->flags & VAR_DUMMY) == 0) 420 Buf_Destroy(&(v->val)); 421 free(v); 422 } 423 424 425 426 427 /*** 428 *** Dynamic variable handling. 429 ***/ 430 431 432 433 /* create empty symtable. 434 * XXX: to save space, dynamic variables may be NULL pointers. 435 */ 436 void 437 SymTable_Init(SymTable *ctxt) 438 { 439 static SymTable sym_template; 440 memcpy(ctxt, &sym_template, sizeof(*ctxt)); 441 } 442 443 /* free symtable. 444 */ 445 #ifdef CLEANUP 446 void 447 SymTable_Destroy(SymTable *ctxt) 448 { 449 int i; 450 451 for (i = 0; i < LOCAL_SIZE; i++) 452 if (ctxt->locals[i] != NULL) 453 delete_var(ctxt->locals[i]); 454 } 455 #endif 456 457 /*** 458 *** Global variable handling. 459 ***/ 460 461 /* Create a new global var if necessary, and set it up correctly. 462 * Do not take environment into account. 463 */ 464 static Var * 465 find_global_var_without_env(const char *name, const char *ename, uint32_t k) 466 { 467 unsigned int slot; 468 Var *v; 469 470 slot = ohash_lookup_interval(&global_variables, name, ename, k); 471 v = ohash_find(&global_variables, slot); 472 if (v == NULL) { 473 v = create_var(name, ename); 474 v->flags = VAR_DUMMY; 475 ohash_insert(&global_variables, slot, v); 476 } 477 return v; 478 } 479 480 /* Helper for find_global_var(): grab environment value if needed. 481 */ 482 static void 483 fill_from_env(Var *v) 484 { 485 char *env; 486 487 env = getenv(v->name); 488 if (env == NULL) 489 v->flags |= VAR_SEEN_ENV; 490 else { 491 var_set_value(v, env); 492 v->flags |= VAR_FROM_ENV | VAR_SEEN_ENV; 493 } 494 495 #ifdef STATS_VAR_LOOKUP 496 STAT_VAR_FROM_ENV++; 497 #endif 498 } 499 500 /* Find global var, and obtain its value from the environment if needed. 501 */ 502 static Var * 503 find_global_var(const char *name, const char *ename, uint32_t k) 504 { 505 Var *v; 506 507 v = find_global_var_without_env(name, ename, k); 508 509 if ((v->flags & VAR_SEEN_ENV) == 0) 510 if ((checkEnvFirst && (v->flags & VAR_FROM_CMD) == 0) || 511 (v->flags & VAR_DUMMY) != 0) 512 fill_from_env(v); 513 514 return v; 515 } 516 517 /* mark variable as poisoned, in a given setup. 518 */ 519 void 520 Var_MarkPoisoned(const char *name, const char *ename, unsigned int type) 521 { 522 Var *v; 523 uint32_t k; 524 int idx; 525 idx = classify_var(name, &ename, &k); 526 527 if (idx != GLOBAL_INDEX) { 528 Parse_Error(PARSE_FATAL, 529 "Trying to poison dynamic variable $%s", 530 varnames[idx]); 531 return; 532 } 533 534 v = find_global_var(name, ename, k); 535 v->flags |= type; 536 /* POISON_NORMAL is not lazy: if the variable already exists in 537 * the Makefile, then it's a mistake. 538 */ 539 if (v->flags & POISON_NORMAL) { 540 if (v->flags & VAR_DUMMY) 541 return; 542 if (v->flags & VAR_FROM_ENV) 543 return; 544 Parse_Error(PARSE_FATAL, 545 "Poisoned variable %s is already set\n", v->name); 546 } 547 } 548 549 /* Check if there's any reason not to use the variable in this context. 550 */ 551 static void 552 poison_check(Var *v) 553 { 554 if (v->flags & POISON_NORMAL) { 555 Parse_Error(PARSE_FATAL, 556 "Poisoned variable %s has been referenced\n", v->name); 557 return; 558 } 559 if (v->flags & VAR_DUMMY) { 560 Parse_Error(PARSE_FATAL, 561 "Poisoned variable %s is not defined\n", v->name); 562 return; 563 } 564 if (v->flags & POISON_EMPTY) 565 if (strcmp(var_get_value(v), "") == 0) 566 Parse_Error(PARSE_FATAL, 567 "Poisoned variable %s is empty\n", v->name); 568 } 569 570 /* Delete global variable. 571 */ 572 void 573 Var_Deletei(const char *name, const char *ename) 574 { 575 Var *v; 576 uint32_t k; 577 unsigned int slot; 578 int idx; 579 580 idx = classify_var(name, &ename, &k); 581 if (idx != GLOBAL_INDEX) { 582 Parse_Error(PARSE_FATAL, 583 "Trying to delete dynamic variable $%s", varnames[idx]); 584 return; 585 } 586 slot = ohash_lookup_interval(&global_variables, name, ename, k); 587 v = ohash_find(&global_variables, slot); 588 589 if (v == NULL) 590 return; 591 592 if (checkEnvFirst && (v->flags & VAR_FROM_ENV)) 593 return; 594 595 if (v->flags & VAR_FROM_CMD) 596 return; 597 598 ohash_remove(&global_variables, slot); 599 delete_var(v); 600 } 601 602 /* Set or add a global variable, in VAR_CMD or VAR_GLOBAL context. 603 */ 604 static void 605 var_set_append(const char *name, const char *ename, const char *val, int ctxt, 606 bool append) 607 { 608 Var *v; 609 uint32_t k; 610 int idx; 611 612 idx = classify_var(name, &ename, &k); 613 if (idx != GLOBAL_INDEX) { 614 Parse_Error(PARSE_FATAL, "Trying to %s dynamic variable $%s", 615 append ? "append to" : "set", varnames[idx]); 616 return; 617 } 618 619 v = find_global_var(name, ename, k); 620 if (v->flags & POISON_NORMAL) 621 Parse_Error(PARSE_FATAL, "Trying to %s poisoned variable %s\n", 622 append ? "append to" : "set", v->name); 623 /* so can we write to it ? */ 624 if (ctxt == VAR_CMD) { /* always for command line */ 625 (append ? var_append_value : var_set_value)(v, val); 626 v->flags |= VAR_FROM_CMD; 627 if ((v->flags & VAR_SHELL) == 0) { 628 /* Any variables given on the command line are 629 * automatically exported to the environment, 630 * except for SHELL (as per POSIX standard). 631 */ 632 esetenv(v->name, val); 633 } 634 if (DEBUG(VAR)) 635 printf("command:%s = %s\n", v->name, var_get_value(v)); 636 } else if ((v->flags & VAR_FROM_CMD) == 0 && 637 (!checkEnvFirst || (v->flags & VAR_FROM_ENV) == 0)) { 638 (append ? var_append_value : var_set_value)(v, val); 639 if (DEBUG(VAR)) 640 printf("global:%s = %s\n", v->name, var_get_value(v)); 641 } else if (DEBUG(VAR)) 642 printf("overridden:%s = %s\n", v->name, var_get_value(v)); 643 } 644 645 void 646 Var_Seti_with_ctxt(const char *name, const char *ename, const char *val, 647 int ctxt) 648 { 649 var_set_append(name, ename, val, ctxt, false); 650 } 651 652 void 653 Var_Appendi_with_ctxt(const char *name, const char *ename, const char *val, 654 int ctxt) 655 { 656 var_set_append(name, ename, val, ctxt, true); 657 } 658 659 /* XXX different semantics for Var_Valuei() and Var_Definedi(): 660 * references to poisoned value variables will error out in Var_Valuei(), 661 * but not in Var_Definedi(), so the following construct works: 662 * .poison BINDIR 663 * BINDIR ?= /usr/bin 664 */ 665 char * 666 Var_Valuei(const char *name, const char *ename) 667 { 668 Var *v; 669 uint32_t k; 670 int idx; 671 672 idx = classify_var(name, &ename, &k); 673 if (idx != GLOBAL_INDEX) { 674 Parse_Error(PARSE_FATAL, 675 "Trying to get value of dynamic variable $%s", 676 varnames[idx]); 677 return NULL; 678 } 679 v = find_global_var(name, ename, k); 680 if (v->flags & POISONS) 681 poison_check(v); 682 if ((v->flags & VAR_DUMMY) == 0) 683 return var_get_value(v); 684 else 685 return NULL; 686 } 687 688 bool 689 Var_Definedi(const char *name, const char *ename) 690 { 691 Var *v; 692 uint32_t k; 693 int idx; 694 695 idx = classify_var(name, &ename, &k); 696 /* We don't bother writing an error message for dynamic variables, 697 * these will be caught when getting set later, usually. 698 */ 699 if (idx == GLOBAL_INDEX) { 700 v = find_global_var(name, ename, k); 701 if (v->flags & POISON_NORMAL) 702 poison_check(v); 703 if ((v->flags & VAR_DUMMY) == 0) 704 return true; 705 } 706 return false; 707 } 708 709 710 /*** 711 *** Substitution functions, handling both global and dynamic variables. 712 ***/ 713 714 715 /* All the scanning functions needed to account for all the forms of 716 * variable names that exist: 717 * $A, ${AB}, $(ABC), ${A:mod}, $(A:mod) 718 */ 719 720 static const char * 721 find_rparen(const char *p) 722 { 723 while (*p != '$' && *p != '\0' && *p != ')' && *p != ':') 724 p++; 725 return p; 726 } 727 728 static const char * 729 find_ket(const char *p) 730 { 731 while (*p != '$' && *p != '\0' && *p != '}' && *p != ':') 732 p++; 733 return p; 734 } 735 736 /* Figure out what kind of name we're looking for from a start character. 737 */ 738 static find_t 739 find_pos(int c) 740 { 741 switch(c) { 742 case '(': 743 return find_rparen; 744 case '{': 745 return find_ket; 746 default: 747 Parse_Error(PARSE_FATAL, 748 "Wrong character in variable spec %c (can't happen)"); 749 return find_rparen; 750 } 751 } 752 753 static bool 754 parse_base_variable_name(const char **pstr, struct Name *name, SymTable *ctxt) 755 { 756 const char *str = *pstr; 757 const char *tstr; 758 bool has_modifier = false; 759 760 switch(str[1]) { 761 case '(': 762 case '{': 763 /* Find eventual modifiers in the variable */ 764 tstr = VarName_Get(str+2, name, ctxt, false, find_pos(str[1])); 765 if (*tstr == ':') 766 has_modifier = true; 767 else if (*tstr != '\0') { 768 tstr++; 769 } 770 break; 771 default: 772 name->s = str+1; 773 name->e = str+2; 774 name->tofree = false; 775 tstr = str + 2; 776 break; 777 } 778 *pstr = tstr; 779 return has_modifier; 780 } 781 782 bool 783 Var_ParseSkip(const char **pstr, SymTable *ctxt) 784 { 785 const char *str = *pstr; 786 struct Name name; 787 bool result; 788 bool has_modifier; 789 const char *tstr = str; 790 791 has_modifier = parse_base_variable_name(&tstr, &name, ctxt); 792 VarName_Free(&name); 793 result = true; 794 if (has_modifier) 795 if (VarModifiers_Apply(NULL, NULL, ctxt, true, NULL, &tstr, 796 str[1]) == var_Error) 797 result = false; 798 *pstr = tstr; 799 return result; 800 } 801 802 /* As of now, Var_ParseBuffer is just a wrapper around Var_Parse. For 803 * speed, it may be better to revisit the implementation to do things 804 * directly. */ 805 bool 806 Var_ParseBuffer(Buffer buf, const char *str, SymTable *ctxt, bool err, 807 size_t *lengthPtr) 808 { 809 char *result; 810 bool freeIt; 811 812 result = Var_Parse(str, ctxt, err, lengthPtr, &freeIt); 813 if (result == var_Error) 814 return false; 815 816 Buf_AddString(buf, result); 817 if (freeIt) 818 free(result); 819 return true; 820 } 821 822 /* Helper function for Var_Parse: still recursive, but we tag what variables 823 * we expand for better error messages. 824 */ 825 #define MAX_DEPTH 350 826 static Var *call_trace[MAX_DEPTH]; 827 static int current_depth = 0; 828 829 static void 830 push_used(Var *v) 831 { 832 if (v->flags & VAR_IN_USE) { 833 int i; 834 fprintf(stderr, "Problem with variable expansion chain: "); 835 for (i = 0; 836 i < (current_depth > MAX_DEPTH ? MAX_DEPTH : current_depth); 837 i++) 838 fprintf(stderr, "%s -> ", call_trace[i]->name); 839 fprintf(stderr, "%s\n", v->name); 840 Fatal("\tVariable %s is recursive.", v->name); 841 /*NOTREACHED*/ 842 } 843 844 v->flags |= VAR_IN_USE; 845 if (current_depth < MAX_DEPTH) 846 call_trace[current_depth] = v; 847 current_depth++; 848 } 849 850 static void 851 pop_used(Var *v) 852 { 853 v->flags &= ~VAR_IN_USE; 854 current_depth--; 855 } 856 857 static char * 858 get_expanded_value(const char *name, const char *ename, int idx, uint32_t k, 859 SymTable *ctxt, bool err, bool *freePtr) 860 { 861 char *val; 862 863 /* Before doing any modification, we have to make sure the 864 * value has been fully expanded. If it looks like recursion 865 * might be necessary (there's a dollar sign somewhere in 866 * the variable's value) we just call Var_Subst to do any 867 * other substitutions that are necessary. Note that the 868 * value returned by Var_Subst will have been dynamically 869 * allocated, so it will need freeing when we return. 870 */ 871 if (idx == GLOBAL_INDEX) { 872 Var *v = find_global_var(name, ename, k); 873 874 if (v == NULL) 875 return NULL; 876 877 if ((v->flags & POISONS) != 0) 878 poison_check(v); 879 if ((v->flags & VAR_DUMMY) != 0) 880 return NULL; 881 882 val = var_get_value(v); 883 if (strchr(val, '$') != NULL) { 884 push_used(v); 885 val = Var_Subst(val, ctxt, err); 886 pop_used(v); 887 *freePtr = true; 888 } 889 } else { 890 if (ctxt != NULL) { 891 if (idx < LOCAL_SIZE) 892 val = ctxt->locals[idx]; 893 else 894 val = ctxt->locals[EXTENDED2SIMPLE(idx)]; 895 } else 896 val = NULL; 897 if (val == NULL) 898 return NULL; 899 900 if (idx >= LOCAL_SIZE) { 901 if (IS_EXTENDED_F(idx)) 902 val = Var_GetTail(val); 903 else 904 val = Var_GetHead(val); 905 *freePtr = true; 906 } 907 } 908 return val; 909 } 910 911 char * 912 Var_Parse(const char *str, /* The string to parse */ 913 SymTable *ctxt, /* The context for the variable */ 914 bool err, /* true if undefined variables are an error */ 915 size_t *lengthPtr, /* OUT: The length of the specification */ 916 bool *freePtr) /* OUT: true if caller should free result */ 917 { 918 const char *tstr; 919 struct Name name; 920 char *val; 921 uint32_t k; 922 int idx; 923 bool has_modifier; 924 925 *freePtr = false; 926 927 tstr = str; 928 929 has_modifier = parse_base_variable_name(&tstr, &name, ctxt); 930 931 idx = classify_var(name.s, &name.e, &k); 932 val = get_expanded_value(name.s, name.e, idx, k, ctxt, err, freePtr); 933 if (has_modifier) { 934 val = VarModifiers_Apply(val, &name, ctxt, err, freePtr, 935 &tstr, str[1]); 936 } 937 if (val == NULL) { 938 val = err ? var_Error : varNoError; 939 /* Dynamic source */ 940 if (idx != GLOBAL_INDEX) { 941 /* can't be expanded for now: copy the spec instead. */ 942 if (ctxt == NULL) { 943 *freePtr = true; 944 val = Str_dupi(str, tstr); 945 } else { 946 /* somehow, this should have been expanded already. */ 947 GNode *n; 948 949 /* XXX */ 950 n = (GNode *)(((char *)ctxt) - 951 offsetof(GNode, context)); 952 if (idx >= LOCAL_SIZE) 953 idx = EXTENDED2SIMPLE(idx); 954 switch(idx) { 955 case IMPSRC_INDEX: 956 Fatal( 957 "Using $< in a non-suffix rule context is a GNUmake idiom (line %lu of %s)", 958 n->lineno, n->fname); 959 break; 960 default: 961 Error( 962 "Using undefined dynamic variable $%s (line %lu of %s)", 963 varnames[idx], n->lineno, n->fname); 964 break; 965 } 966 } 967 } 968 } 969 VarName_Free(&name); 970 *lengthPtr = tstr - str; 971 return val; 972 } 973 974 975 char * 976 Var_Subst(const char *str, /* the string in which to substitute */ 977 SymTable *ctxt, /* the context wherein to find variables */ 978 bool undefErr) /* true if undefineds are an error */ 979 { 980 BUFFER buf; /* Buffer for forming things */ 981 static bool errorReported; 982 983 Buf_Init(&buf, MAKE_BSIZE); 984 errorReported = false; 985 986 for (;;) { 987 char *val; /* Value to substitute for a variable */ 988 size_t length; /* Length of the variable invocation */ 989 bool doFree; /* Set true if val should be freed */ 990 const char *cp; 991 992 /* copy uninteresting stuff */ 993 for (cp = str; *str != '\0' && *str != '$'; str++) 994 ; 995 Buf_Addi(&buf, cp, str); 996 if (*str == '\0') 997 break; 998 if (str[1] == '$') { 999 /* A $ may be escaped with another $. */ 1000 Buf_AddChar(&buf, '$'); 1001 str += 2; 1002 continue; 1003 } 1004 val = Var_Parse(str, ctxt, undefErr, &length, &doFree); 1005 /* When we come down here, val should either point to the 1006 * value of this variable, suitably modified, or be NULL. 1007 * Length should be the total length of the potential 1008 * variable invocation (from $ to end character...) */ 1009 if (val == var_Error || val == varNoError) { 1010 /* If errors are not an issue, skip over the variable 1011 * and continue with the substitution. Otherwise, store 1012 * the dollar sign and advance str so we continue with 1013 * the string... */ 1014 if (errorIsOkay) 1015 str += length; 1016 else if (undefErr) { 1017 /* If variable is undefined, complain and 1018 * skip the variable name. The complaint 1019 * will stop us from doing anything when 1020 * the file is parsed. */ 1021 if (!errorReported) 1022 Parse_Error(PARSE_FATAL, 1023 "Undefined variable \"%.*s\"", 1024 length, str); 1025 str += length; 1026 errorReported = true; 1027 } else { 1028 Buf_AddChar(&buf, *str); 1029 str++; 1030 } 1031 } else { 1032 /* We've now got a variable structure to store in. 1033 * But first, advance the string pointer. */ 1034 str += length; 1035 1036 /* Copy all the characters from the variable value 1037 * straight into the new string. */ 1038 Buf_AddString(&buf, val); 1039 if (doFree) 1040 free(val); 1041 } 1042 } 1043 return Buf_Retrieve(&buf); 1044 } 1045 1046 static BUFFER subst_buffer; 1047 1048 /* we would like to subst on intervals, but it's complicated, so we cheat 1049 * by storing the interval in a static buffer. 1050 */ 1051 char * 1052 Var_Substi(const char *str, const char *estr, SymTable *ctxt, bool undefErr) 1053 { 1054 /* delimited string: no need to copy */ 1055 if (estr == NULL || *estr == '\0') 1056 return Var_Subst(str, ctxt, undefErr); 1057 1058 Buf_Reset(&subst_buffer); 1059 Buf_Addi(&subst_buffer, str, estr); 1060 return Var_Subst(Buf_Retrieve(&subst_buffer), ctxt, undefErr); 1061 } 1062 1063 /*** 1064 *** Supplementary support for .for loops. 1065 ***/ 1066 1067 1068 1069 struct LoopVar 1070 { 1071 Var old; /* keep old variable value (before the loop) */ 1072 Var *me; /* the variable we're dealing with */ 1073 }; 1074 1075 1076 struct LoopVar * 1077 Var_NewLoopVar(const char *name, const char *ename) 1078 { 1079 struct LoopVar *l; 1080 uint32_t k; 1081 1082 l = emalloc(sizeof(struct LoopVar)); 1083 1084 /* we obtain a new variable quickly, make a snapshot of its old 1085 * value, and make sure the environment cannot touch us. 1086 */ 1087 /* XXX: should we avoid dynamic variables ? */ 1088 k = ohash_interval(name, &ename); 1089 1090 l->me = find_global_var_without_env(name, ename, k); 1091 l->old = *(l->me); 1092 l->me->flags = VAR_SEEN_ENV | VAR_DUMMY; 1093 return l; 1094 } 1095 1096 char * 1097 Var_LoopVarName(struct LoopVar *v) 1098 { 1099 return v->me->name; 1100 } 1101 1102 void 1103 Var_DeleteLoopVar(struct LoopVar *l) 1104 { 1105 if ((l->me->flags & VAR_DUMMY) == 0) 1106 Buf_Destroy(&(l->me->val)); 1107 *(l->me) = l->old; 1108 free(l); 1109 } 1110 1111 void 1112 Var_SubstVar(Buffer buf, /* To store result */ 1113 const char *str, /* The string in which to substitute */ 1114 struct LoopVar *l, /* Handle */ 1115 const char *val) /* Its value */ 1116 { 1117 const char *var = l->me->name; 1118 1119 var_set_value(l->me, val); 1120 1121 for (;;) { 1122 const char *start; 1123 /* Copy uninteresting stuff */ 1124 for (start = str; *str != '\0' && *str != '$'; str++) 1125 ; 1126 Buf_Addi(buf, start, str); 1127 1128 start = str; 1129 if (*str++ == '\0') 1130 break; 1131 str++; 1132 /* and escaped dollars */ 1133 if (start[1] == '$') { 1134 Buf_Addi(buf, start, start+2); 1135 continue; 1136 } 1137 /* Simple variable, if it's not us, copy. */ 1138 if (start[1] != '(' && start[1] != '{') { 1139 if (start[1] != *var || var[1] != '\0') { 1140 Buf_AddChars(buf, 2, start); 1141 continue; 1142 } 1143 } else { 1144 const char *p; 1145 char paren = start[1]; 1146 1147 1148 /* Find the end of the variable specification. */ 1149 p = find_pos(paren)(str); 1150 /* A variable inside the variable. We don't know how to 1151 * expand the external variable at this point, so we 1152 * try again with the nested variable. */ 1153 if (*p == '$') { 1154 Buf_Addi(buf, start, p); 1155 str = p; 1156 continue; 1157 } 1158 1159 if (strncmp(var, str, p - str) != 0 || 1160 var[p - str] != '\0') { 1161 /* Not the variable we want to expand. */ 1162 Buf_Addi(buf, start, p); 1163 str = p; 1164 continue; 1165 } 1166 if (*p == ':') { 1167 bool doFree; /* should val be freed ? */ 1168 char *newval; 1169 struct Name name; 1170 1171 doFree = false; 1172 name.s = var; 1173 name.e = var + (p-str); 1174 1175 /* val won't be freed since !doFree, but 1176 * VarModifiers_Apply doesn't know that, 1177 * hence the cast. */ 1178 newval = VarModifiers_Apply((char *)val, 1179 &name, NULL, false, &doFree, &p, paren); 1180 Buf_AddString(buf, newval); 1181 if (doFree) 1182 free(newval); 1183 str = p; 1184 continue; 1185 } else 1186 str = p+1; 1187 } 1188 Buf_AddString(buf, val); 1189 } 1190 } 1191 1192 /*** 1193 *** Odds and ends 1194 ***/ 1195 1196 static void 1197 set_magic_shell_variable() 1198 { 1199 const char *name = "SHELL"; 1200 const char *ename = NULL; 1201 uint32_t k; 1202 Var *v; 1203 1204 k = ohash_interval(name, &ename); 1205 v = find_global_var_without_env(name, ename, k); 1206 var_set_value(v, _PATH_BSHELL); 1207 /* XXX the environment shall never affect it */ 1208 v->flags = VAR_SHELL | VAR_SEEN_ENV; 1209 } 1210 1211 /* 1212 * Var_Init 1213 * Initialize the module 1214 */ 1215 void 1216 Var_Init(void) 1217 { 1218 ohash_init(&global_variables, 10, &var_info); 1219 set_magic_shell_variable(); 1220 1221 1222 errorIsOkay = true; 1223 Var_setCheckEnvFirst(false); 1224 1225 VarModifiers_Init(); 1226 Buf_Init(&subst_buffer, MAKE_BSIZE); 1227 } 1228 1229 1230 #ifdef CLEANUP 1231 void 1232 Var_End(void) 1233 { 1234 Var *v; 1235 unsigned int i; 1236 1237 for (v = ohash_first(&global_variables, &i); v != NULL; 1238 v = ohash_next(&global_variables, &i)) 1239 delete_var(v); 1240 } 1241 #endif 1242 1243 static const char *interpret(int); 1244 1245 static const char * 1246 interpret(int f) 1247 { 1248 if (f & VAR_DUMMY) 1249 return "(D)"; 1250 return ""; 1251 } 1252 1253 1254 static void 1255 print_var(Var *v) 1256 { 1257 printf("%-16s%s = %s\n", v->name, interpret(v->flags), 1258 (v->flags & VAR_DUMMY) == 0 ? var_get_value(v) : "(none)"); 1259 } 1260 1261 void 1262 Var_Dump(void) 1263 { 1264 Var *v; 1265 unsigned int i; 1266 1267 printf("#*** Global Variables:\n"); 1268 1269 for (v = ohash_first(&global_variables, &i); v != NULL; 1270 v = ohash_next(&global_variables, &i)) 1271 print_var(v); 1272 } 1273 1274 static const char *quotable = " \t\n\\'\""; 1275 1276 /* POSIX says that variable assignments passed on the command line should be 1277 * propagated to sub makes through MAKEFLAGS. 1278 */ 1279 void 1280 Var_AddCmdline(const char *name) 1281 { 1282 Var *v; 1283 unsigned int i; 1284 BUFFER buf; 1285 char *s; 1286 1287 Buf_Init(&buf, MAKE_BSIZE); 1288 1289 for (v = ohash_first(&global_variables, &i); v != NULL; 1290 v = ohash_next(&global_variables, &i)) { 1291 /* This is not as expensive as it looks: this function is 1292 * called before parsing Makefiles, so there are just a 1293 * few non cmdling variables in there. 1294 */ 1295 if (!(v->flags & VAR_FROM_CMD)) { 1296 continue; 1297 } 1298 /* We assume variable names don't need quoting */ 1299 Buf_AddString(&buf, v->name); 1300 Buf_AddChar(&buf, '='); 1301 for (s = var_get_value(v); *s != '\0'; s++) { 1302 if (strchr(quotable, *s)) 1303 Buf_AddChar(&buf, '\\'); 1304 Buf_AddChar(&buf, *s); 1305 } 1306 Buf_AddSpace(&buf); 1307 } 1308 Var_Append(name, Buf_Retrieve(&buf)); 1309 Buf_Destroy(&buf); 1310 } 1311