-
Notifications
You must be signed in to change notification settings - Fork 0
/
var.c
4861 lines (4212 loc) · 114 KB
/
var.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $NetBSD: var.c,v 1.1121 2024/06/15 22:06:30 rillig Exp $ */
/*
* Copyright (c) 1988, 1989, 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Adam de Boor.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Copyright (c) 1989 by Berkeley Softworks
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Adam de Boor.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Handling of variables and the expressions formed from them.
*
* Variables are set using lines of the form VAR=value. Both the variable
* name and the value can contain references to other variables, by using
* expressions like ${VAR}, ${VAR:Modifiers}, ${${VARNAME}} or ${VAR:${MODS}}.
*
* Interface:
* Var_Init Initialize this module.
*
* Var_End Clean up the module.
*
* Var_Set
* Var_SetExpand Set the value of the variable, creating it if
* necessary.
*
* Var_Append
* Var_AppendExpand
* Append more characters to the variable, creating it if
* necessary. A space is placed between the old value and
* the new one.
*
* Var_Exists
* Var_ExistsExpand
* See if a variable exists.
*
* Var_Value Return the unexpanded value of a variable, or NULL if
* the variable is undefined.
*
* Var_Subst Substitute all expressions in a string.
*
* Var_Parse Parse an expression such as ${VAR:Mpattern}.
*
* Var_Delete Delete a variable.
*
* Var_ReexportVars
* Export some or even all variables to the environment
* of this process and its child processes.
*
* Var_Export Export the variable to the environment of this process
* and its child processes.
*
* Var_UnExport Don't export the variable anymore.
*
* Debugging:
* Var_Stats Print out hashing statistics if in -dh mode.
*
* Var_Dump Print out all variables defined in the given scope.
*/
#include <sys/stat.h>
#include "make.h"
#include <errno.h>
#ifdef HAVE_REGEX_H
#include "tre/tre.h"
#endif
#include <stdint.h>
#include <time.h>
#include "dir.h"
#include "job.h"
/* "@(#)var.c 8.3 (Berkeley) 3/19/94" */
/*
* Variables are defined using one of the VAR=value assignments. Their
* value can be queried by expressions such as $V, ${VAR}, or with modifiers
* such as ${VAR:S,from,to,g:Q}.
*
* There are 3 kinds of variables: scope variables, environment variables,
* undefined variables.
*
* Scope variables are stored in GNode.vars. The only way to undefine
* a scope variable is using the .undef directive. In particular, it must
* not be possible to undefine a variable during the evaluation of an
* expression, or Var.name might point nowhere. (There is another,
* unintended way to undefine a scope variable, see varmod-loop-delete.mk.)
*
* Environment variables are short-lived. They are returned by VarFind, and
* after using them, they must be freed using VarFreeShortLived.
*
* Undefined variables occur during evaluation of expressions such
* as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers.
*/
typedef struct Var {
/*
* The name of the variable, once set, doesn't change anymore.
* For scope variables, it aliases the corresponding HashEntry name.
* For environment and undefined variables, it is allocated.
*/
FStr name;
/* The unexpanded value of the variable. */
Buffer val;
/* The variable came from the command line. */
bool fromCmd:1;
/*
* The variable is short-lived.
* These variables are not registered in any GNode, therefore they
* must be freed after use.
*/
bool shortLived:1;
/*
* The variable comes from the environment.
* Appending to its value depends on the scope, see var-op-append.mk.
*/
bool fromEnvironment:1;
/*
* The variable value cannot be changed anymore, and the variable
* cannot be deleted. Any attempts to do so are silently ignored,
* they are logged with -dv though.
* Use .[NO]READONLY: to adjust.
*
* See VAR_SET_READONLY.
*/
bool readOnly:1;
/*
* The variable is read-only and immune to the .NOREADONLY special
* target. Any attempt to modify it results in an error.
*/
bool readOnlyLoud:1;
/*
* The variable is currently being accessed by Var_Parse or Var_Subst.
* This temporary marker is used to avoid endless recursion.
*/
bool inUse:1;
/*
* The variable is exported to the environment, to be used by child
* processes.
*/
bool exported:1;
/*
* At the point where this variable was exported, it contained an
* unresolved reference to another variable. Before any child
* process is started, it needs to be actually exported, resolving
* the referenced variable just in time.
*/
bool reexport:1;
} Var;
/*
* Exporting variables is expensive and may leak memory, so skip it if we
* can.
*/
typedef enum VarExportedMode {
VAR_EXPORTED_NONE,
VAR_EXPORTED_SOME,
VAR_EXPORTED_ALL
} VarExportedMode;
typedef enum UnexportWhat {
/* Unexport the variables given by name. */
UNEXPORT_NAMED,
/*
* Unexport all globals previously exported, but keep the environment
* inherited from the parent.
*/
UNEXPORT_ALL,
/*
* Unexport all globals previously exported and clear the environment
* inherited from the parent.
*/
UNEXPORT_ENV
} UnexportWhat;
/* Flags for pattern matching in the :S and :C modifiers */
typedef struct PatternFlags {
bool subGlobal:1; /* 'g': replace as often as possible */
bool subOnce:1; /* '1': replace only once */
bool anchorStart:1; /* '^': match only at start of word */
bool anchorEnd:1; /* '$': match only at end of word */
} PatternFlags;
/* SepBuf builds a string from words interleaved with separators. */
typedef struct SepBuf {
Buffer buf;
bool needSep;
/* Usually ' ', but see the ':ts' modifier. */
char sep;
} SepBuf;
typedef enum {
VSK_TARGET,
VSK_VARNAME,
VSK_EXPR
} EvalStackElementKind;
typedef struct {
EvalStackElementKind kind;
const char *str;
} EvalStackElement;
typedef struct {
EvalStackElement *elems;
size_t len;
size_t cap;
Buffer details;
} EvalStack;
/*
* Special return value for Var_Parse, indicating a parse error. It may be
* caused by an undefined variable, a syntax error in a modifier or
* something entirely different.
*/
char var_Error[] = "";
/*
* Special return value for Var_Parse, indicating an undefined variable in
* a case where VARE_EVAL_DEFINED is not set. This undefined variable is
* typically a dynamic variable such as ${.TARGET}, whose expansion needs to
* be deferred until it is defined in an actual target.
*
* See VARE_EVAL_KEEP_UNDEFINED.
*/
static char varUndefined[] = "";
/*
* Traditionally this make consumed $$ during := like any other expansion.
* Other make's do not, and this make follows straight since 2016-01-09.
*
* This knob allows controlling the behavior:
* false to consume $$ during := assignment.
* true to preserve $$ during := assignment.
*/
#define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
static bool save_dollars = false;
/*
* A scope collects variable names and their values.
*
* The main scope is SCOPE_GLOBAL, which contains the variables that are set
* in the makefiles. SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and
* contains some internal make variables. These internal variables can thus
* be overridden, they can also be restored by undefining the overriding
* variable.
*
* SCOPE_CMDLINE contains variables from the command line arguments. These
* override variables from SCOPE_GLOBAL.
*
* There is no scope for environment variables, these are generated on-the-fly
* whenever they are referenced.
*
* Each target has its own scope, containing the 7 target-local variables
* .TARGET, .ALLSRC, etc. Variables set on dependency lines also go in
* this scope.
*/
GNode *SCOPE_CMDLINE;
GNode *SCOPE_GLOBAL;
GNode *SCOPE_INTERNAL;
static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
static const char VarEvalMode_Name[][32] = {
"parse",
"parse-balanced",
"eval",
"eval-defined",
"eval-keep-undefined",
"eval-keep-dollar-and-undefined",
};
static EvalStack evalStack;
static void
EvalStack_Push(EvalStackElementKind kind, const char *str)
{
if (evalStack.len >= evalStack.cap) {
evalStack.cap = 16 + 2 * evalStack.cap;
evalStack.elems = bmake_realloc(evalStack.elems,
evalStack.cap * sizeof(*evalStack.elems));
}
evalStack.elems[evalStack.len].kind = kind;
evalStack.elems[evalStack.len].str = str;
evalStack.len++;
}
static void
EvalStack_Pop(void)
{
assert(evalStack.len > 0);
evalStack.len--;
}
const char *
EvalStack_Details(void)
{
size_t i;
Buffer *buf = &evalStack.details;
buf->len = 0;
for (i = 0; i < evalStack.len; i++) {
EvalStackElement *elem = evalStack.elems + i;
Buf_AddStr(buf,
elem->kind == VSK_TARGET ? "in target \"" :
elem->kind == VSK_EXPR ? "while evaluating \"" :
"while evaluating variable \"");
Buf_AddStr(buf, elem->str);
Buf_AddStr(buf, "\": ");
}
return buf->len > 0 ? buf->data : "";
}
static Var *
VarNew(FStr name, const char *value,
bool shortLived, bool fromEnvironment, bool readOnly)
{
size_t value_len = strlen(value);
Var *var = bmake_malloc(sizeof *var);
var->name = name;
Buf_InitSize(&var->val, value_len + 1);
Buf_AddBytes(&var->val, value, value_len);
var->fromCmd = false;
var->shortLived = shortLived;
var->fromEnvironment = fromEnvironment;
var->readOnly = readOnly;
var->readOnlyLoud = false;
var->inUse = false;
var->exported = false;
var->reexport = false;
return var;
}
static Substring
CanonicalVarname(Substring name)
{
if (!(Substring_Length(name) > 0 && name.start[0] == '.'))
return name;
if (Substring_Equals(name, ".ALLSRC"))
return Substring_InitStr(ALLSRC);
if (Substring_Equals(name, ".ARCHIVE"))
return Substring_InitStr(ARCHIVE);
if (Substring_Equals(name, ".IMPSRC"))
return Substring_InitStr(IMPSRC);
if (Substring_Equals(name, ".MEMBER"))
return Substring_InitStr(MEMBER);
if (Substring_Equals(name, ".OODATE"))
return Substring_InitStr(OODATE);
if (Substring_Equals(name, ".PREFIX"))
return Substring_InitStr(PREFIX);
if (Substring_Equals(name, ".TARGET"))
return Substring_InitStr(TARGET);
/* GNU make has an additional alias $^ == ${.ALLSRC}. */
if (Substring_Equals(name, ".SHELL") && shellPath == NULL)
Shell_Init();
return name;
}
static Var *
GNode_FindVar(GNode *scope, Substring varname, unsigned int hash)
{
return HashTable_FindValueBySubstringHash(&scope->vars, varname, hash);
}
/*
* Find the variable in the scope, and maybe in other scopes as well.
*
* Input:
* name name to find, is not expanded any further
* scope scope in which to look first
* elsewhere true to look in other scopes as well
*
* Results:
* The found variable, or NULL if the variable does not exist.
* If the variable is short-lived (such as environment variables), it
* must be freed using VarFreeShortLived after use.
*/
static Var *
VarFindSubstring(Substring name, GNode *scope, bool elsewhere)
{
Var *var;
unsigned int nameHash;
/* Replace '.TARGET' with '@', likewise for other local variables. */
name = CanonicalVarname(name);
nameHash = Hash_Substring(name);
var = GNode_FindVar(scope, name, nameHash);
if (!elsewhere)
return var;
if (var == NULL && scope != SCOPE_CMDLINE)
var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash);
if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) {
var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
if (var == NULL && scope != SCOPE_INTERNAL) {
/* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */
var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash);
}
}
if (var == NULL) {
FStr envName = Substring_Str(name);
const char *envValue = getenv(envName.str);
if (envValue != NULL)
return VarNew(envName, envValue, true, true, false);
FStr_Done(&envName);
if (opts.checkEnvFirst && scope != SCOPE_GLOBAL) {
var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
if (var == NULL && scope != SCOPE_INTERNAL)
var = GNode_FindVar(SCOPE_INTERNAL, name,
nameHash);
return var;
}
return NULL;
}
return var;
}
static Var *
VarFind(const char *name, GNode *scope, bool elsewhere)
{
return VarFindSubstring(Substring_InitStr(name), scope, elsewhere);
}
/* If the variable is short-lived, free it, including its value. */
static void
VarFreeShortLived(Var *v)
{
if (!v->shortLived)
return;
FStr_Done(&v->name);
Buf_Done(&v->val);
free(v);
}
static const char *
ValueDescription(const char *value)
{
if (value[0] == '\0')
return "# (empty)";
if (ch_isspace(value[strlen(value) - 1]))
return "# (ends with space)";
return "";
}
/* Add a new variable of the given name and value to the given scope. */
static Var *
VarAddS(const char *name, const char *value, GNode *scope, VarSetFlags flags)
{
HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL);
Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value,
false, false, (flags & VAR_SET_READONLY) != 0);
HashEntry_Set(he, v);
DEBUG4(VAR, "%s: %s = %s%s\n",
scope->name, name, value, ValueDescription(value));
return v;
}
/*
* Remove a variable from a scope, freeing all related memory as well.
* The variable name is kept as-is, it is not expanded.
*/
void
Var_Delete(GNode *scope, const char *varname)
{
HashEntry *he = HashTable_FindEntry(&scope->vars, varname);
Var *v;
if (he == NULL) {
DEBUG2(VAR, "%s: ignoring delete '%s' as it is not found\n",
scope->name, varname);
return;
}
v = he->value;
if (v->readOnlyLoud) {
Parse_Error(PARSE_FATAL,
"Cannot delete \"%s\" as it is read-only",
v->name.str);
return;
}
if (v->readOnly) {
DEBUG2(VAR, "%s: ignoring delete '%s' as it is read-only\n",
scope->name, varname);
return;
}
if (v->inUse) {
Parse_Error(PARSE_FATAL,
"Cannot delete variable \"%s\" while it is used",
v->name.str);
return;
}
DEBUG2(VAR, "%s: delete %s\n", scope->name, varname);
if (v->exported)
unsetenv(v->name.str);
if (strcmp(v->name.str, ".MAKE.EXPORTED") == 0)
var_exportedVars = VAR_EXPORTED_NONE;
assert(v->name.freeIt == NULL);
HashTable_DeleteEntry(&scope->vars, he);
Buf_Done(&v->val);
free(v);
}
#ifdef CLEANUP
void
Var_DeleteAll(GNode *scope)
{
HashIter hi;
HashIter_Init(&hi, &scope->vars);
while (HashIter_Next(&hi)) {
Var *v = hi.entry->value;
Buf_Done(&v->val);
free(v);
}
}
#endif
/*
* Undefine one or more variables from the global scope.
* The argument is expanded exactly once and then split into words.
*/
void
Var_Undef(const char *arg)
{
char *expanded;
Words varnames;
size_t i;
if (arg[0] == '\0') {
Parse_Error(PARSE_FATAL,
"The .undef directive requires an argument");
return;
}
expanded = Var_Subst(arg, SCOPE_GLOBAL, VARE_EVAL);
if (expanded == var_Error) {
/* TODO: Make this part of the code reachable. */
Parse_Error(PARSE_FATAL,
"Error in variable names to be undefined");
return;
}
varnames = Str_Words(expanded, false);
if (varnames.len == 1 && varnames.words[0][0] == '\0')
varnames.len = 0;
for (i = 0; i < varnames.len; i++) {
const char *varname = varnames.words[i];
Global_Delete(varname);
}
Words_Free(varnames);
free(expanded);
}
static bool
MayExport(const char *name)
{
if (name[0] == '.')
return false; /* skip internals */
if (name[0] == '-')
return false; /* skip misnamed variables */
if (name[1] == '\0') {
/*
* A single char.
* If it is one of the variables that should only appear in
* local scope, skip it, else we can get Var_Subst
* into a loop.
*/
switch (name[0]) {
case '@':
case '%':
case '*':
case '!':
return false;
}
}
return true;
}
static bool
ExportVarEnv(Var *v, GNode *scope)
{
const char *name = v->name.str;
char *val = v->val.data;
char *expr;
if (v->exported && !v->reexport)
return false; /* nothing to do */
if (strchr(val, '$') == NULL) {
if (!v->exported)
setenv(name, val, 1);
return true;
}
if (v->inUse)
return false; /* see EMPTY_SHELL in directive-export.mk */
/* XXX: name is injected without escaping it */
expr = str_concat3("${", name, "}");
val = Var_Subst(expr, scope, VARE_EVAL);
if (scope != SCOPE_GLOBAL) {
/* we will need to re-export the global version */
v = VarFind(name, SCOPE_GLOBAL, false);
if (v != NULL)
v->exported = false;
}
/* TODO: handle errors */
setenv(name, val, 1);
free(val);
free(expr);
return true;
}
static bool
ExportVarPlain(Var *v)
{
if (strchr(v->val.data, '$') == NULL) {
setenv(v->name.str, v->val.data, 1);
v->exported = true;
v->reexport = false;
return true;
}
/*
* Flag the variable as something we need to re-export.
* No point actually exporting it now though,
* the child process can do it at the last minute.
* Avoid calling setenv more often than necessary since it can leak.
*/
v->exported = true;
v->reexport = true;
return true;
}
static bool
ExportVarLiteral(Var *v)
{
if (v->exported && !v->reexport)
return false;
if (!v->exported)
setenv(v->name.str, v->val.data, 1);
return true;
}
/*
* Mark a single variable to be exported later for subprocesses.
*
* Internal variables are not exported.
*/
static bool
ExportVar(const char *name, GNode *scope, VarExportMode mode)
{
Var *v;
if (!MayExport(name))
return false;
v = VarFind(name, scope, false);
if (v == NULL && scope != SCOPE_GLOBAL)
v = VarFind(name, SCOPE_GLOBAL, false);
if (v == NULL)
return false;
if (mode == VEM_ENV)
return ExportVarEnv(v, scope);
else if (mode == VEM_PLAIN)
return ExportVarPlain(v);
else
return ExportVarLiteral(v);
}
/*
* Actually export the variables that have been marked as needing to be
* re-exported.
*/
void
Var_ReexportVars(GNode *scope)
{
char *xvarnames;
/*
* Several make implementations support this sort of mechanism for
* tracking recursion - but each uses a different name.
* We allow the makefiles to update MAKELEVEL and ensure
* children see a correctly incremented value.
*/
char level_buf[21];
snprintf(level_buf, sizeof level_buf, "%d", makelevel + 1);
setenv(MAKE_LEVEL_ENV, level_buf, 1);
if (var_exportedVars == VAR_EXPORTED_NONE)
return;
if (var_exportedVars == VAR_EXPORTED_ALL) {
HashIter hi;
/* Ouch! Exporting all variables at once is crazy. */
HashIter_Init(&hi, &SCOPE_GLOBAL->vars);
while (HashIter_Next(&hi)) {
Var *var = hi.entry->value;
ExportVar(var->name.str, scope, VEM_ENV);
}
return;
}
xvarnames = Var_Subst("${.MAKE.EXPORTED:O:u}", SCOPE_GLOBAL,
VARE_EVAL);
/* TODO: handle errors */
if (xvarnames[0] != '\0') {
Words varnames = Str_Words(xvarnames, false);
size_t i;
for (i = 0; i < varnames.len; i++)
ExportVar(varnames.words[i], scope, VEM_ENV);
Words_Free(varnames);
}
free(xvarnames);
}
static void
ExportVars(const char *varnames, bool isExport, VarExportMode mode)
/* TODO: try to combine the parameters 'isExport' and 'mode'. */
{
Words words = Str_Words(varnames, false);
size_t i;
if (words.len == 1 && words.words[0][0] == '\0')
words.len = 0;
for (i = 0; i < words.len; i++) {
const char *varname = words.words[i];
if (!ExportVar(varname, SCOPE_GLOBAL, mode))
continue;
if (var_exportedVars == VAR_EXPORTED_NONE)
var_exportedVars = VAR_EXPORTED_SOME;
if (isExport && mode == VEM_PLAIN)
Global_Append(".MAKE.EXPORTED", varname);
}
Words_Free(words);
}
static void
ExportVarsExpand(const char *uvarnames, bool isExport, VarExportMode mode)
{
char *xvarnames = Var_Subst(uvarnames, SCOPE_GLOBAL, VARE_EVAL);
/* TODO: handle errors */
ExportVars(xvarnames, isExport, mode);
free(xvarnames);
}
/* Export the named variables, or all variables. */
void
Var_Export(VarExportMode mode, const char *varnames)
{
if (mode == VEM_ALL) {
var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
return;
} else if (mode == VEM_PLAIN && varnames[0] == '\0') {
Parse_Error(PARSE_WARNING, ".export requires an argument.");
return;
}
ExportVarsExpand(varnames, true, mode);
}
void
Var_ExportVars(const char *varnames)
{
ExportVarsExpand(varnames, false, VEM_PLAIN);
}
static void
ClearEnv(void)
{
const char *level;
char **p;
Buffer tmp;
level = getenv(MAKE_LEVEL_ENV); /* we should preserve this */
/* actually unset every variable */
Buf_Init(&tmp);
for (p = environ; *p != NULL; p++) {
Buf_Clear(&tmp);
Buf_AddBytes(&tmp, *p,
strchr(*p, '=') - *p);
unsetenv(tmp.data);
}
Buf_Done(&tmp);
if (level != NULL && *level != '\0')
setenv(MAKE_LEVEL_ENV, level, 1);
}
static void
GetVarnamesToUnexport(bool isEnv, const char *arg,
FStr *out_varnames, UnexportWhat *out_what)
{
UnexportWhat what;
FStr varnames = FStr_InitRefer("");
if (isEnv) {
if (arg[0] != '\0') {
Parse_Error(PARSE_FATAL,
"The directive .unexport-env does not take "
"arguments");
/* continue anyway */
}
what = UNEXPORT_ENV;
} else {
what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL;
if (what == UNEXPORT_NAMED)
varnames = FStr_InitRefer(arg);
}
if (what != UNEXPORT_NAMED) {
char *expanded = Var_Subst("${.MAKE.EXPORTED:O:u}",
SCOPE_GLOBAL, VARE_EVAL);
/* TODO: handle errors */
varnames = FStr_InitOwn(expanded);
}
*out_varnames = varnames;
*out_what = what;
}
static void
UnexportVar(Substring varname, UnexportWhat what)
{
Var *v = VarFindSubstring(varname, SCOPE_GLOBAL, false);
if (v == NULL) {
DEBUG2(VAR, "Not unexporting \"%.*s\" (not found)\n",
(int)Substring_Length(varname), varname.start);
return;
}
DEBUG2(VAR, "Unexporting \"%.*s\"\n",
(int)Substring_Length(varname), varname.start);
if (what != UNEXPORT_ENV && v->exported && !v->reexport)
unsetenv(v->name.str);
v->exported = false;
v->reexport = false;
if (what == UNEXPORT_NAMED) {
/* Remove the variable names from .MAKE.EXPORTED. */
/* XXX: v->name is injected without escaping it */
char *expr = str_concat3(
"${.MAKE.EXPORTED:N", v->name.str, "}");
char *filtered = Var_Subst(expr, SCOPE_GLOBAL, VARE_EVAL);
/* TODO: handle errors */
Global_Set(".MAKE.EXPORTED", filtered);
free(filtered);
free(expr);
}
}
static void
UnexportVars(FStr *varnames, UnexportWhat what)
{
size_t i;
SubstringWords words;
if (what == UNEXPORT_ENV)
ClearEnv();
words = Substring_Words(varnames->str, false);
for (i = 0; i < words.len; i++)
UnexportVar(words.words[i], what);
SubstringWords_Free(words);
if (what != UNEXPORT_NAMED)
Global_Delete(".MAKE.EXPORTED");
}
/* Handle the .unexport and .unexport-env directives. */
void
Var_UnExport(bool isEnv, const char *arg)
{
UnexportWhat what;
FStr varnames;
GetVarnamesToUnexport(isEnv, arg, &varnames, &what);
UnexportVars(&varnames, what);
FStr_Done(&varnames);
}
/* Set the variable to the value; the name is not expanded. */
void
Var_SetWithFlags(GNode *scope, const char *name, const char *val,
VarSetFlags flags)
{
Var *v;
assert(val != NULL);
if (name[0] == '\0') {
DEBUG3(VAR,
"%s: ignoring '%s = %s' as the variable name is empty\n",
scope->name, name, val);
return;
}
if (scope == SCOPE_GLOBAL
&& VarFind(name, SCOPE_CMDLINE, false) != NULL) {
/*
* The global variable would not be visible anywhere.
* Therefore, there is no point in setting it at all.
*/