1 /* $OpenPackages$ */ 2 /* $OpenBSD: var.c,v 1.82 2007/11/04 09:31:57 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_any_var(const char *, const char *, SymTable *, int, uint32_t); 209 static Var *find_global_var(const char *, const char *, uint32_t); 210 static Var *find_global_var_without_env(const char *, const char *, uint32_t); 211 static void fill_from_env(Var *); 212 static Var *create_var(const char *, const char *); 213 static void var_set_initial_value(Var *, const char *); 214 static void var_set_value(Var *, const char *); 215 #define var_get_value(v) Buf_Retrieve(&((v)->val)) 216 static void var_append_value(Var *, const char *); 217 static void poison_check(Var *); 218 static void varq_set_append(int, const char *, GNode *, bool); 219 static void var_set_append(const char *, const char *, const char *, int, bool); 220 static void set_magic_shell_variable(void); 221 222 static void delete_var(Var *); 223 static void print_var(Var *); 224 225 226 static const char *find_rparen(const char *); 227 static const char *find_ket(const char *); 228 typedef const char * (*find_t)(const char *); 229 static find_t find_pos(int); 230 static void push_used(Var *); 231 static void pop_used(Var *); 232 static char *get_expanded_value(Var *, int, SymTable *, bool, bool *); 233 static bool parse_base_variable_name(const char **, struct Name *, SymTable *); 234 235 236 237 /* Variable lookup function: return idx for dynamic variable, or 238 * GLOBAL_INDEX if name is not dynamic. Set up *pk for further use. 239 */ 240 static int 241 classify_var(const char *name, const char **enamePtr, uint32_t *pk) 242 { 243 size_t len; 244 245 *pk = ohash_interval(name, enamePtr); 246 len = *enamePtr - name; 247 /* substitute short version for long local name */ 248 switch (*pk % MAGICSLOTS1) { /* MAGICSLOTS should be the */ 249 case K_LONGALLSRC % MAGICSLOTS1:/* smallest constant yielding */ 250 /* distinct case values */ 251 if (*pk == K_LONGALLSRC && len == strlen(LONGALLSRC) && 252 strncmp(name, LONGALLSRC, len) == 0) 253 return ALLSRC_INDEX; 254 break; 255 case K_LONGARCHIVE % MAGICSLOTS1: 256 if (*pk == K_LONGARCHIVE && len == strlen(LONGARCHIVE) && 257 strncmp(name, LONGARCHIVE, len) == 0) 258 return ARCHIVE_INDEX; 259 break; 260 case K_LONGIMPSRC % MAGICSLOTS1: 261 if (*pk == K_LONGIMPSRC && len == strlen(LONGIMPSRC) && 262 strncmp(name, LONGIMPSRC, len) == 0) 263 return IMPSRC_INDEX; 264 break; 265 case K_LONGMEMBER % MAGICSLOTS1: 266 if (*pk == K_LONGMEMBER && len == strlen(LONGMEMBER) && 267 strncmp(name, LONGMEMBER, len) == 0) 268 return MEMBER_INDEX; 269 break; 270 case K_LONGOODATE % MAGICSLOTS1: 271 if (*pk == K_LONGOODATE && len == strlen(LONGOODATE) && 272 strncmp(name, LONGOODATE, len) == 0) 273 return OODATE_INDEX; 274 break; 275 case K_LONGPREFIX % MAGICSLOTS1: 276 if (*pk == K_LONGPREFIX && len == strlen(LONGPREFIX) && 277 strncmp(name, LONGPREFIX, len) == 0) 278 return PREFIX_INDEX; 279 break; 280 case K_LONGTARGET % MAGICSLOTS1: 281 if (*pk == K_LONGTARGET && len == strlen(LONGTARGET) && 282 strncmp(name, LONGTARGET, len) == 0) 283 return TARGET_INDEX; 284 break; 285 case K_TARGET % MAGICSLOTS1: 286 if (name[0] == TARGET[0] && len == 1) 287 return TARGET_INDEX; 288 break; 289 case K_OODATE % MAGICSLOTS1: 290 if (name[0] == OODATE[0] && len == 1) 291 return OODATE_INDEX; 292 break; 293 case K_ALLSRC % MAGICSLOTS1: 294 if (name[0] == ALLSRC[0] && len == 1) 295 return ALLSRC_INDEX; 296 break; 297 case K_IMPSRC % MAGICSLOTS1: 298 if (name[0] == IMPSRC[0] && len == 1) 299 return IMPSRC_INDEX; 300 break; 301 case K_PREFIX % MAGICSLOTS1: 302 if (name[0] == PREFIX[0] && len == 1) 303 return PREFIX_INDEX; 304 break; 305 case K_ARCHIVE % MAGICSLOTS1: 306 if (name[0] == ARCHIVE[0] && len == 1) 307 return ARCHIVE_INDEX; 308 break; 309 case K_MEMBER % MAGICSLOTS1: 310 if (name[0] == MEMBER[0] && len == 1) 311 return MEMBER_INDEX; 312 break; 313 case K_FTARGET % MAGICSLOTS1: 314 if (name[0] == FTARGET[0] && name[1] == FTARGET[1] && len == 2) 315 return FTARGET_INDEX; 316 break; 317 case K_DTARGET % MAGICSLOTS1: 318 if (name[0] == DTARGET[0] && name[1] == DTARGET[1] && len == 2) 319 return DTARGET_INDEX; 320 break; 321 case K_FPREFIX % MAGICSLOTS1: 322 if (name[0] == FPREFIX[0] && name[1] == FPREFIX[1] && len == 2) 323 return FPREFIX_INDEX; 324 break; 325 case K_DPREFIX % MAGICSLOTS1: 326 if (name[0] == DPREFIX[0] && name[1] == DPREFIX[1] && len == 2) 327 return DPREFIX_INDEX; 328 break; 329 case K_FARCHIVE % MAGICSLOTS1: 330 if (name[0] == FARCHIVE[0] && name[1] == FARCHIVE[1] && 331 len == 2) 332 return FARCHIVE_INDEX; 333 break; 334 case K_DARCHIVE % MAGICSLOTS1: 335 if (name[0] == DARCHIVE[0] && name[1] == DARCHIVE[1] && 336 len == 2) 337 return DARCHIVE_INDEX; 338 break; 339 case K_FMEMBER % MAGICSLOTS1: 340 if (name[0] == FMEMBER[0] && name[1] == FMEMBER[1] && len == 2) 341 return FMEMBER_INDEX; 342 break; 343 case K_DMEMBER % MAGICSLOTS1: 344 if (name[0] == DMEMBER[0] && name[1] == DMEMBER[1] && len == 2) 345 return DMEMBER_INDEX; 346 break; 347 default: 348 break; 349 } 350 return GLOBAL_INDEX; 351 } 352 353 354 /*** 355 *** Internal handling of variables. 356 ***/ 357 358 359 /* Create a new variable, does not initialize anything except the name. 360 * in particular, buffer is invalid, and flag value is invalid. Accordingly, 361 * must either: 362 * - set flags to VAR_DUMMY 363 * - set flags to !VAR_DUMMY, and initialize buffer, for instance with 364 * var_set_initial_value(). 365 */ 366 static Var * 367 create_var(const char *name, const char *ename) 368 { 369 return ohash_create_entry(&var_info, name, &ename); 370 } 371 372 /* Initial version of var_set_value(), to be called after create_var(). 373 */ 374 static void 375 var_set_initial_value(Var *v, const char *val) 376 { 377 size_t len; 378 379 len = strlen(val); 380 Buf_Init(&(v->val), len+1); 381 Buf_AddChars(&(v->val), len, val); 382 } 383 384 /* Normal version of var_set_value(), to be called after variable is fully 385 * initialized. 386 */ 387 static void 388 var_set_value(Var *v, const char *val) 389 { 390 if ((v->flags & VAR_DUMMY) == 0) { 391 Buf_Reset(&(v->val)); 392 Buf_AddString(&(v->val), val); 393 } else { 394 var_set_initial_value(v, val); 395 v->flags &= ~VAR_DUMMY; 396 } 397 } 398 399 /* Add to a variable, insert a separating space if the variable was already 400 * defined. 401 */ 402 static void 403 var_append_value(Var *v, const char *val) 404 { 405 if ((v->flags & VAR_DUMMY) == 0) { 406 Buf_AddSpace(&(v->val)); 407 Buf_AddString(&(v->val), val); 408 } else { 409 var_set_initial_value(v, val); 410 v->flags &= ~VAR_DUMMY; 411 } 412 } 413 414 415 /* Delete a variable and all the space associated with it. 416 */ 417 static void 418 delete_var(Var *v) 419 { 420 if ((v->flags & VAR_DUMMY) == 0) 421 Buf_Destroy(&(v->val)); 422 free(v); 423 } 424 425 426 427 428 /*** 429 *** Dynamic variable handling. 430 ***/ 431 432 433 434 /* create empty symtable. 435 * XXX: to save space, dynamic variables may be NULL pointers. 436 */ 437 void 438 SymTable_Init(SymTable *ctxt) 439 { 440 static SymTable sym_template; 441 memcpy(ctxt, &sym_template, sizeof(*ctxt)); 442 } 443 444 /* free symtable. 445 */ 446 #ifdef CLEANUP 447 void 448 SymTable_Destroy(SymTable *ctxt) 449 { 450 int i; 451 452 for (i = 0; i < LOCAL_SIZE; i++) 453 if (ctxt->locals[i] != NULL) 454 delete_var(ctxt->locals[i]); 455 } 456 #endif 457 458 /* set or append to dynamic variable. 459 */ 460 static void 461 varq_set_append(int idx, const char *val, GNode *gn, bool append) 462 { 463 Var *v = gn->context.locals[idx]; 464 465 if (v == NULL) { 466 v = create_var(varnames[idx], NULL); 467 #ifdef STATS_VAR_LOOKUP 468 STAT_VAR_CREATION++; 469 #endif 470 if (val != NULL) 471 var_set_initial_value(v, val); 472 else 473 Buf_Init(&(v->val), 1); 474 v->flags = 0; 475 gn->context.locals[idx] = v; 476 } else { 477 if (append) 478 Buf_AddSpace(&(v->val)); 479 else 480 Buf_Reset(&(v->val)); 481 Buf_AddString(&(v->val), val); 482 } 483 if (DEBUG(VAR)) 484 printf("%s:%s = %s\n", gn->name, varnames[idx], 485 var_get_value(v)); 486 } 487 488 void 489 Varq_Set(int idx, const char *val, GNode *gn) 490 { 491 varq_set_append(idx, val, gn, false); 492 } 493 494 void 495 Varq_Append(int idx, const char *val, GNode *gn) 496 { 497 varq_set_append(idx, val, gn, true); 498 } 499 500 char * 501 Varq_Value(int idx, GNode *gn) 502 { 503 Var *v = gn->context.locals[idx]; 504 505 if (v == NULL) 506 return NULL; 507 else 508 return var_get_value(v); 509 } 510 511 /*** 512 *** Global variable handling. 513 ***/ 514 515 /* Create a new global var if necessary, and set it up correctly. 516 * Do not take environment into account. 517 */ 518 static Var * 519 find_global_var_without_env(const char *name, const char *ename, uint32_t k) 520 { 521 unsigned int slot; 522 Var *v; 523 524 slot = ohash_lookup_interval(&global_variables, name, ename, k); 525 v = ohash_find(&global_variables, slot); 526 if (v == NULL) { 527 v = create_var(name, ename); 528 v->flags = VAR_DUMMY; 529 ohash_insert(&global_variables, slot, v); 530 } 531 return v; 532 } 533 534 /* Helper for find_global_var(): grab environment value if needed. 535 */ 536 static void 537 fill_from_env(Var *v) 538 { 539 char *env; 540 541 env = getenv(v->name); 542 if (env == NULL) 543 v->flags |= VAR_SEEN_ENV; 544 else { 545 var_set_value(v, env); 546 v->flags |= VAR_FROM_ENV | VAR_SEEN_ENV; 547 } 548 549 #ifdef STATS_VAR_LOOKUP 550 STAT_VAR_FROM_ENV++; 551 #endif 552 } 553 554 /* Find global var, and obtain its value from the environment if needed. 555 */ 556 static Var * 557 find_global_var(const char *name, const char *ename, uint32_t k) 558 { 559 Var *v; 560 561 v = find_global_var_without_env(name, ename, k); 562 563 if ((v->flags & VAR_SEEN_ENV) == 0) 564 if ((checkEnvFirst && (v->flags & VAR_FROM_CMD) == 0) || 565 (v->flags & VAR_DUMMY) != 0) 566 fill_from_env(v); 567 568 return v; 569 } 570 571 /* mark variable as poisoned, in a given setup. 572 */ 573 void 574 Var_MarkPoisoned(const char *name, const char *ename, unsigned int type) 575 { 576 Var *v; 577 uint32_t k; 578 int idx; 579 idx = classify_var(name, &ename, &k); 580 581 if (idx != GLOBAL_INDEX) { 582 Parse_Error(PARSE_FATAL, 583 "Trying to poison dynamic variable $%s", 584 varnames[idx]); 585 return; 586 } 587 588 v = find_global_var(name, ename, k); 589 v->flags |= type; 590 /* POISON_NORMAL is not lazy: if the variable already exists in 591 * the Makefile, then it's a mistake. 592 */ 593 if (v->flags & POISON_NORMAL) { 594 if (v->flags & VAR_DUMMY) 595 return; 596 if (v->flags & VAR_FROM_ENV) 597 return; 598 Parse_Error(PARSE_FATAL, 599 "Poisoned variable %s is already set\n", v->name); 600 } 601 } 602 603 /* Check if there's any reason not to use the variable in this context. 604 */ 605 static void 606 poison_check(Var *v) 607 { 608 if (v->flags & POISON_NORMAL) { 609 Parse_Error(PARSE_FATAL, 610 "Poisoned variable %s has been referenced\n", v->name); 611 return; 612 } 613 if (v->flags & VAR_DUMMY) { 614 Parse_Error(PARSE_FATAL, 615 "Poisoned variable %s is not defined\n", v->name); 616 return; 617 } 618 if (v->flags & POISON_EMPTY) 619 if (strcmp(var_get_value(v), "") == 0) 620 Parse_Error(PARSE_FATAL, 621 "Poisoned variable %s is empty\n", v->name); 622 } 623 624 /* Delete global variable. 625 */ 626 void 627 Var_Deletei(const char *name, const char *ename) 628 { 629 Var *v; 630 uint32_t k; 631 unsigned int slot; 632 int idx; 633 634 idx = classify_var(name, &ename, &k); 635 if (idx != GLOBAL_INDEX) { 636 Parse_Error(PARSE_FATAL, 637 "Trying to delete dynamic variable $%s", varnames[idx]); 638 return; 639 } 640 slot = ohash_lookup_interval(&global_variables, name, ename, k); 641 v = ohash_find(&global_variables, slot); 642 643 if (v == NULL) 644 return; 645 646 if (checkEnvFirst && (v->flags & VAR_FROM_ENV)) 647 return; 648 649 if (v->flags & VAR_FROM_CMD) 650 return; 651 652 ohash_remove(&global_variables, slot); 653 delete_var(v); 654 } 655 656 /* Set or add a global variable, in VAR_CMD or VAR_GLOBAL context. 657 */ 658 static void 659 var_set_append(const char *name, const char *ename, const char *val, int ctxt, 660 bool append) 661 { 662 Var *v; 663 uint32_t k; 664 int idx; 665 666 idx = classify_var(name, &ename, &k); 667 if (idx != GLOBAL_INDEX) { 668 Parse_Error(PARSE_FATAL, "Trying to %s dynamic variable $%s", 669 append ? "append to" : "set", varnames[idx]); 670 return; 671 } 672 673 v = find_global_var(name, ename, k); 674 if (v->flags & POISON_NORMAL) 675 Parse_Error(PARSE_FATAL, "Trying to %s poisoned variable %s\n", 676 append ? "append to" : "set", v->name); 677 /* so can we write to it ? */ 678 if (ctxt == VAR_CMD) { /* always for command line */ 679 (append ? var_append_value : var_set_value)(v, val); 680 v->flags |= VAR_FROM_CMD; 681 if ((v->flags & VAR_SHELL) == 0) { 682 /* Any variables given on the command line are 683 * automatically exported to the environment, 684 * except for SHELL (as per POSIX standard). 685 */ 686 esetenv(v->name, val); 687 } 688 if (DEBUG(VAR)) 689 printf("command:%s = %s\n", v->name, var_get_value(v)); 690 } else if ((v->flags & VAR_FROM_CMD) == 0 && 691 (!checkEnvFirst || (v->flags & VAR_FROM_ENV) == 0)) { 692 (append ? var_append_value : var_set_value)(v, val); 693 if (DEBUG(VAR)) 694 printf("global:%s = %s\n", v->name, var_get_value(v)); 695 } else if (DEBUG(VAR)) 696 printf("overriden:%s = %s\n", v->name, var_get_value(v)); 697 } 698 699 void 700 Var_Seti_with_ctxt(const char *name, const char *ename, const char *val, 701 int ctxt) 702 { 703 var_set_append(name, ename, val, ctxt, false); 704 } 705 706 void 707 Var_Appendi_with_ctxt(const char *name, const char *ename, const char *val, 708 int ctxt) 709 { 710 var_set_append(name, ename, val, ctxt, true); 711 } 712 713 /* XXX different semantics for Var_Valuei() and Var_Definedi(): 714 * references to poisoned value variables will error out in Var_Valuei(), 715 * but not in Var_Definedi(), so the following construct works: 716 * .poison BINDIR 717 * BINDIR ?= /usr/bin 718 */ 719 char * 720 Var_Valuei(const char *name, const char *ename) 721 { 722 Var *v; 723 uint32_t k; 724 int idx; 725 726 idx = classify_var(name, &ename, &k); 727 if (idx != GLOBAL_INDEX) { 728 Parse_Error(PARSE_FATAL, 729 "Trying to get value of dynamic variable $%s", 730 varnames[idx]); 731 return NULL; 732 } 733 v = find_global_var(name, ename, k); 734 if (v->flags & POISONS) 735 poison_check(v); 736 if ((v->flags & VAR_DUMMY) == 0) 737 return var_get_value(v); 738 else 739 return NULL; 740 } 741 742 bool 743 Var_Definedi(const char *name, const char *ename) 744 { 745 Var *v; 746 uint32_t k; 747 int idx; 748 749 idx = classify_var(name, &ename, &k); 750 /* We don't bother writing an error message for dynamic variables, 751 * these will be caught when getting set later, usually. 752 */ 753 if (idx == GLOBAL_INDEX) { 754 v = find_global_var(name, ename, k); 755 if (v->flags & POISON_NORMAL) 756 poison_check(v); 757 if ((v->flags & VAR_DUMMY) == 0) 758 return true; 759 } 760 return false; 761 } 762 763 764 /*** 765 *** Substitution functions, handling both global and dynamic variables. 766 ***/ 767 768 769 /* XXX contrary to find_global_var(), find_any_var() can return NULL pointers. 770 */ 771 static Var * 772 find_any_var(const char *name, const char *ename, SymTable *ctxt, 773 int idx, uint32_t k) 774 { 775 /* Handle local variables first */ 776 if (idx != GLOBAL_INDEX) { 777 if (ctxt != NULL) { 778 if (idx < LOCAL_SIZE) 779 return ctxt->locals[idx]; 780 else 781 return ctxt->locals[EXTENDED2SIMPLE(idx)]; 782 } else 783 return NULL; 784 } else { 785 return find_global_var(name, ename, k); 786 } 787 } 788 789 /* All the scanning functions needed to account for all the forms of 790 * variable names that exist: 791 * $A, ${AB}, $(ABC), ${A:mod}, $(A:mod) 792 */ 793 794 static const char * 795 find_rparen(const char *p) 796 { 797 while (*p != '$' && *p != '\0' && *p != ')' && *p != ':') 798 p++; 799 return p; 800 } 801 802 static const char * 803 find_ket(const char *p) 804 { 805 while (*p != '$' && *p != '\0' && *p != '}' && *p != ':') 806 p++; 807 return p; 808 } 809 810 /* Figure out what kind of name we're looking for from a start character. 811 */ 812 static find_t 813 find_pos(int c) 814 { 815 switch(c) { 816 case '(': 817 return find_rparen; 818 case '{': 819 return find_ket; 820 default: 821 Parse_Error(PARSE_FATAL, 822 "Wrong character in variable spec %c (can't happen)"); 823 return find_rparen; 824 } 825 } 826 827 static bool 828 parse_base_variable_name(const char **pstr, struct Name *name, SymTable *ctxt) 829 { 830 const char *str = *pstr; 831 const char *tstr; 832 bool has_modifier = false; 833 834 switch(str[1]) { 835 case '(': 836 case '{': 837 /* Find eventual modifiers in the variable */ 838 tstr = VarName_Get(str+2, name, ctxt, false, find_pos(str[1])); 839 if (*tstr == ':') 840 has_modifier = true; 841 else if (*tstr != '\0') { 842 tstr++; 843 } 844 break; 845 default: 846 name->s = str+1; 847 name->e = str+2; 848 name->tofree = false; 849 tstr = str + 2; 850 break; 851 } 852 *pstr = tstr; 853 return has_modifier; 854 } 855 856 bool 857 Var_ParseSkip(const char **pstr, SymTable *ctxt) 858 { 859 const char *str = *pstr; 860 struct Name name; 861 bool result; 862 bool has_modifier; 863 const char *tstr = str; 864 865 has_modifier = parse_base_variable_name(&tstr, &name, ctxt); 866 VarName_Free(&name); 867 result = true; 868 if (has_modifier) 869 if (VarModifiers_Apply(NULL, NULL, ctxt, true, NULL, &tstr, 870 str[1]) == var_Error) 871 result = false; 872 *pstr = tstr; 873 return result; 874 } 875 876 /* As of now, Var_ParseBuffer is just a wrapper around Var_Parse. For 877 * speed, it may be better to revisit the implementation to do things 878 * directly. */ 879 bool 880 Var_ParseBuffer(Buffer buf, const char *str, SymTable *ctxt, bool err, 881 size_t *lengthPtr) 882 { 883 char *result; 884 bool freeIt; 885 886 result = Var_Parse(str, ctxt, err, lengthPtr, &freeIt); 887 if (result == var_Error) 888 return false; 889 890 Buf_AddString(buf, result); 891 if (freeIt) 892 free(result); 893 return true; 894 } 895 896 /* Helper function for Var_Parse: still recursive, but we tag what variables 897 * we expand for better error messages. 898 */ 899 #define MAX_DEPTH 350 900 static Var *call_trace[MAX_DEPTH]; 901 static int current_depth = 0; 902 903 static void 904 push_used(Var *v) 905 { 906 if (v->flags & VAR_IN_USE) { 907 int i; 908 fprintf(stderr, "Problem with variable expansion chain: "); 909 for (i = 0; 910 i < (current_depth > MAX_DEPTH ? MAX_DEPTH : current_depth); 911 i++) 912 fprintf(stderr, "%s -> ", call_trace[i]->name); 913 fprintf(stderr, "%s\n", v->name); 914 Fatal("\tVariable %s is recursive.", v->name); 915 /*NOTREACHED*/ 916 } 917 918 v->flags |= VAR_IN_USE; 919 if (current_depth < MAX_DEPTH) 920 call_trace[current_depth] = v; 921 current_depth++; 922 } 923 924 static void 925 pop_used(Var *v) 926 { 927 v->flags &= ~VAR_IN_USE; 928 current_depth--; 929 } 930 931 static char * 932 get_expanded_value(Var *v, int idx, SymTable *ctxt, bool err, bool *freePtr) 933 { 934 char *val; 935 936 if (v == NULL) 937 return NULL; 938 939 if ((v->flags & POISONS) != 0) 940 poison_check(v); 941 if ((v->flags & VAR_DUMMY) != 0) 942 return NULL; 943 944 /* Before doing any modification, we have to make sure the 945 * value has been fully expanded. If it looks like recursion 946 * might be necessary (there's a dollar sign somewhere in 947 * the variable's value) we just call Var_Subst to do any 948 * other substitutions that are necessary. Note that the 949 * value returned by Var_Subst will have been dynamically 950 * allocated, so it will need freeing when we return. 951 */ 952 val = var_get_value(v); 953 if (idx == GLOBAL_INDEX) { 954 if (strchr(val, '$') != NULL) { 955 push_used(v); 956 val = Var_Subst(val, ctxt, err); 957 pop_used(v); 958 *freePtr = true; 959 } 960 } else if (idx >= LOCAL_SIZE) { 961 if (IS_EXTENDED_F(idx)) 962 val = Var_GetTail(val); 963 else 964 val = Var_GetHead(val); 965 *freePtr = true; 966 } 967 return val; 968 } 969 970 char * 971 Var_Parse(const char *str, /* The string to parse */ 972 SymTable *ctxt, /* The context for the variable */ 973 bool err, /* true if undefined variables are an error */ 974 size_t *lengthPtr, /* OUT: The length of the specification */ 975 bool *freePtr) /* OUT: true if caller should free result */ 976 { 977 const char *tstr; 978 Var *v; 979 struct Name name; 980 char *val; 981 uint32_t k; 982 int idx; 983 bool has_modifier; 984 985 *freePtr = false; 986 987 tstr = str; 988 989 has_modifier = parse_base_variable_name(&tstr, &name, ctxt); 990 991 idx = classify_var(name.s, &name.e, &k); 992 v = find_any_var(name.s, name.e, ctxt, idx, k); 993 val = get_expanded_value(v, idx, ctxt, err, freePtr); 994 if (has_modifier) { 995 val = VarModifiers_Apply(val, &name, ctxt, err, freePtr, 996 &tstr, str[1]); 997 } 998 if (val == NULL) { 999 val = err ? var_Error : varNoError; 1000 /* Dynamic source */ 1001 if (idx != GLOBAL_INDEX) { 1002 /* can't be expanded for now: copy the spec instead. */ 1003 if (ctxt == NULL) { 1004 *freePtr = true; 1005 val = Str_dupi(str, tstr); 1006 } else { 1007 /* somehow, this should have been expanded already. */ 1008 GNode *n; 1009 1010 /* XXX */ 1011 n = (GNode *)(((char *)ctxt) - 1012 offsetof(GNode, context)); 1013 if (idx >= LOCAL_SIZE) 1014 idx = EXTENDED2SIMPLE(idx); 1015 switch(idx) { 1016 case IMPSRC_INDEX: 1017 Fatal( 1018 "Using $< in a non-suffix rule context is a GNUmake idiom (line %lu of %s)", 1019 n->lineno, n->fname); 1020 break; 1021 default: 1022 Error( 1023 "Using undefined dynamic variable $%s (line %lu of %s)", 1024 varnames[idx], n->lineno, n->fname); 1025 break; 1026 } 1027 } 1028 } 1029 } 1030 VarName_Free(&name); 1031 *lengthPtr = tstr - str; 1032 return val; 1033 } 1034 1035 1036 char * 1037 Var_Subst(const char *str, /* the string in which to substitute */ 1038 SymTable *ctxt, /* the context wherein to find variables */ 1039 bool undefErr) /* true if undefineds are an error */ 1040 { 1041 BUFFER buf; /* Buffer for forming things */ 1042 static bool errorReported; 1043 1044 Buf_Init(&buf, MAKE_BSIZE); 1045 errorReported = false; 1046 1047 for (;;) { 1048 char *val; /* Value to substitute for a variable */ 1049 size_t length; /* Length of the variable invocation */ 1050 bool doFree; /* Set true if val should be freed */ 1051 const char *cp; 1052 1053 /* copy uninteresting stuff */ 1054 for (cp = str; *str != '\0' && *str != '$'; str++) 1055 ; 1056 Buf_Addi(&buf, cp, str); 1057 if (*str == '\0') 1058 break; 1059 if (str[1] == '$') { 1060 /* A $ may be escaped with another $. */ 1061 Buf_AddChar(&buf, '$'); 1062 str += 2; 1063 continue; 1064 } 1065 val = Var_Parse(str, ctxt, undefErr, &length, &doFree); 1066 /* When we come down here, val should either point to the 1067 * value of this variable, suitably modified, or be NULL. 1068 * Length should be the total length of the potential 1069 * variable invocation (from $ to end character...) */ 1070 if (val == var_Error || val == varNoError) { 1071 /* If errors are not an issue, skip over the variable 1072 * and continue with the substitution. Otherwise, store 1073 * the dollar sign and advance str so we continue with 1074 * the string... */ 1075 if (errorIsOkay) 1076 str += length; 1077 else if (undefErr) { 1078 /* If variable is undefined, complain and 1079 * skip the variable name. The complaint 1080 * will stop us from doing anything when 1081 * the file is parsed. */ 1082 if (!errorReported) 1083 Parse_Error(PARSE_FATAL, 1084 "Undefined variable \"%.*s\"", 1085 length, str); 1086 str += length; 1087 errorReported = true; 1088 } else { 1089 Buf_AddChar(&buf, *str); 1090 str++; 1091 } 1092 } else { 1093 /* We've now got a variable structure to store in. 1094 * But first, advance the string pointer. */ 1095 str += length; 1096 1097 /* Copy all the characters from the variable value 1098 * straight into the new string. */ 1099 Buf_AddString(&buf, val); 1100 if (doFree) 1101 free(val); 1102 } 1103 } 1104 return Buf_Retrieve(&buf); 1105 } 1106 1107 static BUFFER subst_buffer; 1108 1109 /* we would like to subst on intervals, but it's complicated, so we cheat 1110 * by storing the interval in a static buffer. 1111 */ 1112 char * 1113 Var_Substi(const char *str, const char *estr, SymTable *ctxt, bool undefErr) 1114 { 1115 /* delimited string: no need to copy */ 1116 if (estr == NULL || *estr == '\0') 1117 return Var_Subst(str, ctxt, undefErr); 1118 1119 Buf_Reset(&subst_buffer); 1120 Buf_Addi(&subst_buffer, str, estr); 1121 return Var_Subst(Buf_Retrieve(&subst_buffer), ctxt, undefErr); 1122 } 1123 1124 /*** 1125 *** Supplementary support for .for loops. 1126 ***/ 1127 1128 1129 1130 struct LoopVar 1131 { 1132 Var old; /* keep old variable value (before the loop) */ 1133 Var *me; /* the variable we're dealing with */ 1134 }; 1135 1136 1137 struct LoopVar * 1138 Var_NewLoopVar(const char *name, const char *ename) 1139 { 1140 struct LoopVar *l; 1141 uint32_t k; 1142 1143 l = emalloc(sizeof(struct LoopVar)); 1144 1145 /* we obtain a new variable quickly, make a snapshot of its old 1146 * value, and make sure the environment cannot touch us. 1147 */ 1148 /* XXX: should we avoid dynamic variables ? */ 1149 k = ohash_interval(name, &ename); 1150 1151 l->me = find_global_var_without_env(name, ename, k); 1152 l->old = *(l->me); 1153 l->me->flags = VAR_SEEN_ENV | VAR_DUMMY; 1154 return l; 1155 } 1156 1157 void 1158 Var_DeleteLoopVar(struct LoopVar *l) 1159 { 1160 if ((l->me->flags & VAR_DUMMY) == 0) 1161 Buf_Destroy(&(l->me->val)); 1162 *(l->me) = l->old; 1163 free(l); 1164 } 1165 1166 void 1167 Var_SubstVar(Buffer buf, /* To store result */ 1168 const char *str, /* The string in which to substitute */ 1169 struct LoopVar *l, /* Handle */ 1170 const char *val) /* Its value */ 1171 { 1172 const char *var = l->me->name; 1173 1174 var_set_value(l->me, val); 1175 1176 for (;;) { 1177 const char *start; 1178 /* Copy uninteresting stuff */ 1179 for (start = str; *str != '\0' && *str != '$'; str++) 1180 ; 1181 Buf_Addi(buf, start, str); 1182 1183 start = str; 1184 if (*str++ == '\0') 1185 break; 1186 str++; 1187 /* and escaped dollars */ 1188 if (start[1] == '$') { 1189 Buf_Addi(buf, start, start+2); 1190 continue; 1191 } 1192 /* Simple variable, if it's not us, copy. */ 1193 if (start[1] != '(' && start[1] != '{') { 1194 if (start[1] != *var || var[1] != '\0') { 1195 Buf_AddChars(buf, 2, start); 1196 continue; 1197 } 1198 } else { 1199 const char *p; 1200 char paren = start[1]; 1201 1202 1203 /* Find the end of the variable specification. */ 1204 p = find_pos(paren)(str); 1205 /* A variable inside the variable. We don't know how to 1206 * expand the external variable at this point, so we 1207 * try again with the nested variable. */ 1208 if (*p == '$') { 1209 Buf_Addi(buf, start, p); 1210 str = p; 1211 continue; 1212 } 1213 1214 if (strncmp(var, str, p - str) != 0 || 1215 var[p - str] != '\0') { 1216 /* Not the variable we want to expand. */ 1217 Buf_Addi(buf, start, p); 1218 str = p; 1219 continue; 1220 } 1221 if (*p == ':') { 1222 bool doFree; /* should val be freed ? */ 1223 char *newval; 1224 struct Name name; 1225 1226 doFree = false; 1227 name.s = var; 1228 name.e = var + (p-str); 1229 1230 /* val won't be freed since !doFree, but 1231 * VarModifiers_Apply doesn't know that, 1232 * hence the cast. */ 1233 newval = VarModifiers_Apply((char *)val, 1234 &name, NULL, false, &doFree, &p, paren); 1235 Buf_AddString(buf, newval); 1236 if (doFree) 1237 free(newval); 1238 str = p; 1239 continue; 1240 } else 1241 str = p+1; 1242 } 1243 Buf_AddString(buf, val); 1244 } 1245 } 1246 1247 /*** 1248 *** Odds and ends 1249 ***/ 1250 1251 static void 1252 set_magic_shell_variable() 1253 { 1254 const char *name = "SHELL"; 1255 const char *ename = NULL; 1256 uint32_t k; 1257 Var *v; 1258 1259 k = ohash_interval(name, &ename); 1260 v = find_global_var_without_env(name, ename, k); 1261 var_set_value(v, _PATH_BSHELL); 1262 /* XXX the environment shall never affect it */ 1263 v->flags = VAR_SHELL | VAR_SEEN_ENV; 1264 } 1265 1266 /* 1267 * Var_Init 1268 * Initialize the module 1269 */ 1270 void 1271 Var_Init(void) 1272 { 1273 ohash_init(&global_variables, 10, &var_info); 1274 set_magic_shell_variable(); 1275 1276 1277 errorIsOkay = true; 1278 Var_setCheckEnvFirst(false); 1279 1280 VarModifiers_Init(); 1281 Buf_Init(&subst_buffer, MAKE_BSIZE); 1282 } 1283 1284 1285 #ifdef CLEANUP 1286 void 1287 Var_End(void) 1288 { 1289 Var *v; 1290 unsigned int i; 1291 1292 for (v = ohash_first(&global_variables, &i); v != NULL; 1293 v = ohash_next(&global_variables, &i)) 1294 delete_var(v); 1295 } 1296 #endif 1297 1298 static const char *interpret(int); 1299 1300 static const char * 1301 interpret(int f) 1302 { 1303 if (f & VAR_DUMMY) 1304 return "(D)"; 1305 return ""; 1306 } 1307 1308 1309 static void 1310 print_var(Var *v) 1311 { 1312 printf("%-16s%s = %s\n", v->name, interpret(v->flags), 1313 (v->flags & VAR_DUMMY) == 0 ? var_get_value(v) : "(none)"); 1314 } 1315 1316 void 1317 Var_Dump(void) 1318 { 1319 Var *v; 1320 unsigned int i; 1321 1322 printf("#*** Global Variables:\n"); 1323 1324 for (v = ohash_first(&global_variables, &i); v != NULL; 1325 v = ohash_next(&global_variables, &i)) 1326 print_var(v); 1327 } 1328 1329 static const char *quotable = " \t\n\\'\""; 1330 1331 /* POSIX says that variable assignments passed on the command line should be 1332 * propagated to sub makes through MAKEFLAGS. 1333 */ 1334 void 1335 Var_AddCmdline(const char *name) 1336 { 1337 Var *v; 1338 unsigned int i; 1339 BUFFER buf; 1340 char *s; 1341 1342 Buf_Init(&buf, MAKE_BSIZE); 1343 1344 for (v = ohash_first(&global_variables, &i); v != NULL; 1345 v = ohash_next(&global_variables, &i)) { 1346 /* This is not as expensive as it looks: this function is 1347 * called before parsing Makefiles, so there are just a 1348 * few non cmdling variables in there. 1349 */ 1350 if (!(v->flags & VAR_FROM_CMD)) { 1351 continue; 1352 } 1353 /* We assume variable names don't need quoting */ 1354 Buf_AddString(&buf, v->name); 1355 Buf_AddChar(&buf, '='); 1356 for (s = var_get_value(v); *s != '\0'; s++) { 1357 if (strchr(quotable, *s)) 1358 Buf_AddChar(&buf, '\\'); 1359 Buf_AddChar(&buf, *s); 1360 } 1361 Buf_AddSpace(&buf); 1362 } 1363 Var_Append(name, Buf_Retrieve(&buf)); 1364 Buf_Destroy(&buf); 1365 } 1366