-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.c
3019 lines (2633 loc) · 72.2 KB
/
parse.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: parse.c,v 1.731 2024/06/15 19:43:56 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.
*/
/*
* Parsing of makefiles.
*
* Parse_File is the main entry point and controls most of the other
* functions in this module.
*
* Interface:
* Parse_Init Initialize the module
*
* Parse_End Clean up the module
*
* Parse_File Parse a top-level makefile. Included files are
* handled by IncludeFile instead.
*
* Parse_VarAssign
* Try to parse the given line as a variable assignment.
* Used by MainParseArgs to determine if an argument is
* a target or a variable assignment. Used internally
* for pretty much the same thing.
*
* Parse_Error Report a parse error, a warning or an informational
* message.
*
* Parse_MainName Populate the list of targets to create.
*/
#include <sys/stat.h>
#include <io.h>
#include "make.h"
#include "dir.h"
#include "job.h"
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
/* "@(#)parse.c 8.3 (Berkeley) 3/19/94" */
/* Detects a multiple-inclusion guard in a makefile. */
typedef enum {
GS_START, /* at the beginning of the file */
GS_COND, /* after the guard condition */
GS_DONE, /* after the closing .endif */
GS_NO /* the file is not guarded */
} GuardState;
/* A file being parsed. */
typedef struct IncludedFile {
FStr name; /* absolute or relative to the cwd */
unsigned lineno; /* 1-based */
unsigned readLines; /* the number of physical lines that have
* been read from the file */
unsigned forHeadLineno; /* 1-based */
unsigned forBodyReadLines; /* the number of physical lines that have
* been read from the file above the body of
* the .for loop */
unsigned int condMinDepth; /* depth of nested 'if' directives, at the
* beginning of the file */
bool depending; /* state of doing_depend on EOF */
Buffer buf; /* the file's content or the body of the .for
* loop; either empty or ends with '\n' */
char *buf_ptr; /* next char to be read from buf */
char *buf_end; /* buf_end[-1] == '\n' */
GuardState guardState;
Guard *guard;
struct ForLoop *forLoop;
} IncludedFile;
/* Special attributes for target nodes. */
typedef enum ParseSpecial {
SP_ATTRIBUTE, /* Generic attribute */
SP_BEGIN, /* .BEGIN */
SP_DEFAULT, /* .DEFAULT */
SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
SP_END, /* .END */
SP_ERROR, /* .ERROR */
SP_IGNORE, /* .IGNORE */
SP_INCLUDES, /* .INCLUDES; not mentioned in the manual page */
SP_INTERRUPT, /* .INTERRUPT */
SP_LIBS, /* .LIBS; not mentioned in the manual page */
SP_MAIN, /* .MAIN and no user-specified targets to make */
SP_META, /* .META */
SP_MFLAGS, /* .MFLAGS or .MAKEFLAGS */
SP_NOMETA, /* .NOMETA */
SP_NOMETA_CMP, /* .NOMETA_CMP */
SP_NOPATH, /* .NOPATH */
SP_NOREADONLY, /* .NOREADONLY */
SP_NOT, /* Not special */
SP_NOTPARALLEL, /* .NOTPARALLEL or .NO_PARALLEL */
SP_NULL, /* .NULL; not mentioned in the manual page */
SP_OBJDIR, /* .OBJDIR */
SP_ORDER, /* .ORDER */
SP_PARALLEL, /* .PARALLEL; not mentioned in the manual page */
SP_PATH, /* .PATH or .PATH.suffix */
SP_PHONY, /* .PHONY */
SP_POSIX, /* .POSIX; not mentioned in the manual page */
SP_PRECIOUS, /* .PRECIOUS */
SP_READONLY, /* .READONLY */
SP_SHELL, /* .SHELL */
SP_SILENT, /* .SILENT */
SP_SINGLESHELL, /* .SINGLESHELL; not mentioned in the manual page */
SP_STALE, /* .STALE */
SP_SUFFIXES, /* .SUFFIXES */
SP_SYSPATH, /* .SYSPATH */
SP_WAIT /* .WAIT */
} ParseSpecial;
typedef List SearchPathList;
typedef ListNode SearchPathListNode;
typedef enum VarAssignOp {
VAR_NORMAL, /* = */
VAR_APPEND, /* += */
VAR_DEFAULT, /* ?= */
VAR_SUBST, /* := */
VAR_SHELL /* != or :sh= */
} VarAssignOp;
typedef struct VarAssign {
char *varname; /* unexpanded */
VarAssignOp op;
const char *value; /* unexpanded */
} VarAssign;
static bool Parse_IsVar(const char *, VarAssign *);
static void Parse_Var(VarAssign *, GNode *);
/*
* The target to be made if no targets are specified in the command line.
* This is the first target defined in any of the makefiles.
*/
GNode *mainNode;
/*
* During parsing, the targets from the left-hand side of the currently
* active dependency line, or NULL if the current line does not belong to a
* dependency line, for example because it is a variable assignment.
*
* See unit-tests/deptgt.mk, keyword "parse.c:targets".
*/
static GNodeList *targets;
#ifdef CLEANUP
/*
* All shell commands for all targets, in no particular order and possibly
* with duplicate values. Kept in a separate list since the commands from
* .USE or .USEBEFORE nodes are shared with other GNodes, thereby giving up
* the easily understandable ownership over the allocated strings.
*/
static StringList targCmds = LST_INIT;
#endif
/*
* Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
* is seen, then set to each successive source on the line.
*/
static GNode *order_pred;
static int parseErrors;
/*
* The include chain of makefiles. At index 0 is the top-level makefile from
* the command line, followed by the included files or .for loops, up to and
* including the current file.
*
* See PrintStackTrace for how to interpret the data.
*/
static Vector /* of IncludedFile */ includes;
SearchPath *parseIncPath; /* directories for "..." includes */
SearchPath *sysIncPath; /* directories for <...> includes */
SearchPath *defSysIncPath; /* default for sysIncPath */
/*
* The parseKeywords table is searched using binary search when deciding
* if a target or source is special.
*/
static const struct {
const char name[17];
ParseSpecial special; /* when used as a target */
GNodeType targetAttr; /* when used as a source */
} parseKeywords[] = {
{ ".BEGIN", SP_BEGIN, OP_NONE },
{ ".DEFAULT", SP_DEFAULT, OP_NONE },
{ ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE },
{ ".END", SP_END, OP_NONE },
{ ".ERROR", SP_ERROR, OP_NONE },
{ ".EXEC", SP_ATTRIBUTE, OP_EXEC },
{ ".IGNORE", SP_IGNORE, OP_IGNORE },
{ ".INCLUDES", SP_INCLUDES, OP_NONE },
{ ".INTERRUPT", SP_INTERRUPT, OP_NONE },
{ ".INVISIBLE", SP_ATTRIBUTE, OP_INVISIBLE },
{ ".JOIN", SP_ATTRIBUTE, OP_JOIN },
{ ".LIBS", SP_LIBS, OP_NONE },
{ ".MADE", SP_ATTRIBUTE, OP_MADE },
{ ".MAIN", SP_MAIN, OP_NONE },
{ ".MAKE", SP_ATTRIBUTE, OP_MAKE },
{ ".MAKEFLAGS", SP_MFLAGS, OP_NONE },
{ ".META", SP_META, OP_META },
{ ".MFLAGS", SP_MFLAGS, OP_NONE },
{ ".NOMETA", SP_NOMETA, OP_NOMETA },
{ ".NOMETA_CMP", SP_NOMETA_CMP, OP_NOMETA_CMP },
{ ".NOPATH", SP_NOPATH, OP_NOPATH },
{ ".NOREADONLY", SP_NOREADONLY, OP_NONE },
{ ".NOTMAIN", SP_ATTRIBUTE, OP_NOTMAIN },
{ ".NOTPARALLEL", SP_NOTPARALLEL, OP_NONE },
{ ".NO_PARALLEL", SP_NOTPARALLEL, OP_NONE },
{ ".NULL", SP_NULL, OP_NONE },
{ ".OBJDIR", SP_OBJDIR, OP_NONE },
{ ".OPTIONAL", SP_ATTRIBUTE, OP_OPTIONAL },
{ ".ORDER", SP_ORDER, OP_NONE },
{ ".PARALLEL", SP_PARALLEL, OP_NONE },
{ ".PATH", SP_PATH, OP_NONE },
{ ".PHONY", SP_PHONY, OP_PHONY },
{ ".POSIX", SP_POSIX, OP_NONE },
{ ".PRECIOUS", SP_PRECIOUS, OP_PRECIOUS },
{ ".READONLY", SP_READONLY, OP_NONE },
{ ".RECURSIVE", SP_ATTRIBUTE, OP_MAKE },
{ ".SHELL", SP_SHELL, OP_NONE },
{ ".SILENT", SP_SILENT, OP_SILENT },
{ ".SINGLESHELL", SP_SINGLESHELL, OP_NONE },
{ ".STALE", SP_STALE, OP_NONE },
{ ".SUFFIXES", SP_SUFFIXES, OP_NONE },
{ ".SYSPATH", SP_SYSPATH, OP_NONE },
{ ".USE", SP_ATTRIBUTE, OP_USE },
{ ".USEBEFORE", SP_ATTRIBUTE, OP_USEBEFORE },
{ ".WAIT", SP_WAIT, OP_NONE },
};
enum PosixState posix_state = PS_NOT_YET;
static HashTable /* full file name -> Guard */ guards;
static List *
Lst_New(void)
{
List *list = bmake_malloc(sizeof *list);
Lst_Init(list);
return list;
}
static void
Lst_Free(List *list)
{
Lst_Done(list);
free(list);
}
static IncludedFile *
GetInclude(size_t i)
{
assert(i < includes.len);
return Vector_Get(&includes, i);
}
/* The makefile or the body of a .for loop that is currently being read. */
static IncludedFile *
CurFile(void)
{
return GetInclude(includes.len - 1);
}
unsigned int
CurFile_CondMinDepth(void)
{
return CurFile()->condMinDepth;
}
static Buffer
LoadFile(const char *path, int fd)
{
int n;
Buffer buf;
size_t bufSize;
struct stat st;
bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
st.st_size > 0 && st.st_size < 1024 * 1024 * 1024
? (size_t)st.st_size : 1024;
Buf_InitSize(&buf, bufSize);
for (;;) {
if (buf.len == buf.cap) {
if (buf.cap >= 512 * 1024 * 1024) {
Error("%s: file too large", path);
exit(2); /* Not 1 so -q can distinguish error */
}
Buf_Expand(&buf);
}
assert(buf.len < buf.cap);
n = read(fd, buf.data + buf.len, buf.cap - buf.len);
if (n < 0) {
Error("%s: read error: %s", path, strerror(errno));
exit(2); /* Not 1 so -q can distinguish error */
}
if (n == 0)
break;
buf.len += (size_t)n;
}
assert(buf.len <= buf.cap);
if (buf.len > 0 && !Buf_EndsWith(&buf, '\n'))
Buf_AddByte(&buf, '\n');
return buf; /* may not be null-terminated */
}
/*
* Print the current chain of .include and .for directives. In Parse_Fatal
* or other functions that already print the location, includingInnermost
* would be redundant, but in other cases like Error or Fatal it needs to be
* included.
*/
void
PrintStackTrace(bool includingInnermost)
{
const IncludedFile *entries;
size_t i, n;
n = includes.len;
if (n == 0)
return;
entries = GetInclude(0);
if (!includingInnermost && entries[n - 1].forLoop == NULL)
n--; /* already in the diagnostic */
for (i = n; i-- > 0;) {
const IncludedFile *entry = entries + i;
const char *fname = entry->name.str;
char dirbuf[MAXPATHLEN + 1];
if (!isAbs(fname) && strcmp(fname, "(stdin)") != 0) {
const char *realPath = _fullpath(dirbuf, fname, MAXPATHLEN);
if (realPath != NULL)
fname = realPath;
}
if (entry->forLoop != NULL) {
char *details = ForLoop_Details(entry->forLoop);
debug_printf("\tin .for loop from %s:%u with %s\n",
fname, entry->forHeadLineno, details);
free(details);
} else if (i + 1 < n && entries[i + 1].forLoop != NULL) {
/* entry->lineno is not a useful line number */
} else
debug_printf("\tin %s:%u\n", fname, entry->lineno);
}
}
/* Check if the current character is escaped on the current line. */
static bool
IsEscaped(const char *line, const char *p)
{
bool escaped = false;
while (p > line && *--p == '\\')
escaped = !escaped;
return escaped;
}
/*
* Remember the location (filename and lineno) where the last command was
* added or where the node was mentioned in a .depend file.
*/
static void
RememberLocation(GNode *gn)
{
IncludedFile *curFile = CurFile();
gn->fname = Str_Intern(curFile->name.str);
gn->lineno = curFile->lineno;
}
/*
* Look in the table of keywords for one matching the given string.
* Return the index of the keyword, or -1 if it isn't there.
*/
static int
FindKeyword(const char *str)
{
int start = 0;
int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
while (start <= end) {
int curr = start + (end - start) / 2;
int diff = strcmp(str, parseKeywords[curr].name);
if (diff == 0)
return curr;
if (diff < 0)
end = curr - 1;
else
start = curr + 1;
}
return -1;
}
void
PrintLocation(FILE *f, bool useVars, const GNode *gn)
{
char dirbuf[MAXPATHLEN + 1];
FStr dir, base;
const char *fname;
unsigned lineno;
if (gn != NULL) {
fname = gn->fname;
lineno = gn->lineno;
} else if (includes.len > 0) {
IncludedFile *curFile = CurFile();
fname = curFile->name.str;
lineno = curFile->lineno;
} else
return;
if (!useVars || isAbs(fname) || strcmp(fname, "(stdin)") == 0) {
(void)fprintf(f, "\"%s\" line %u: ", fname, lineno);
return;
}
dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR");
if (dir.str == NULL)
dir.str = ".";
if (!isAbs(dir.str))
dir.str = _fullpath(dirbuf, dir.str, MAXPATHLEN);
base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE");
if (base.str == NULL)
base.str = str_basename(fname);
(void)fprintf(f, "\"%s\\%s\" line %u: ", dir.str, base.str, lineno);
FStr_Done(&base);
FStr_Done(&dir);
}
static void
ParseVErrorInternal(FILE *f, bool useVars, const GNode *gn,
ParseErrorLevel level, MAKE_ATTR_PRINTFLIKE const char *fmt,
va_list ap)
{
static bool fatal_warning_error_printed = false;
(void)fprintf(f, "%s: ", progname);
PrintLocation(f, useVars, gn);
if (level == PARSE_WARNING)
(void)fprintf(f, "warning: ");
fprintf(f, "%s", EvalStack_Details());
(void)vfprintf(f, fmt, ap);
(void)fprintf(f, "\n");
(void)fflush(f);
if (level == PARSE_FATAL)
parseErrors++;
if (level == PARSE_WARNING && opts.parseWarnFatal) {
if (!fatal_warning_error_printed) {
Error("parsing warnings being treated as errors");
fatal_warning_error_printed = true;
}
parseErrors++;
}
if (DEBUG(PARSE))
PrintStackTrace(false);
}
static void
ParseErrorInternal(const GNode *gn,
ParseErrorLevel level, MAKE_ATTR_PRINTFLIKE const char *fmt, ...)
{
va_list ap;
(void)fflush(stdout);
va_start(ap, fmt);
ParseVErrorInternal(stderr, false, gn, level, fmt, ap);
va_end(ap);
if (opts.debug_file != stdout && opts.debug_file != stderr) {
va_start(ap, fmt);
ParseVErrorInternal(opts.debug_file, false, gn,
level, fmt, ap);
va_end(ap);
}
}
/*
* Print a message, including location information.
*
* If the level is PARSE_FATAL, continue parsing until the end of the
* current top-level makefile, then exit (see Parse_File).
*
* Fmt is given without a trailing newline.
*/
void
Parse_Error(ParseErrorLevel level, MAKE_ATTR_PRINTFLIKE const char *fmt, ...)
{
va_list ap;
(void)fflush(stdout);
va_start(ap, fmt);
ParseVErrorInternal(stderr, true, NULL, level, fmt, ap);
va_end(ap);
if (opts.debug_file != stdout && opts.debug_file != stderr) {
va_start(ap, fmt);
ParseVErrorInternal(opts.debug_file, true, NULL,
level, fmt, ap);
va_end(ap);
}
}
/*
* Handle an .info, .warning or .error directive. For an .error directive,
* exit immediately.
*/
static void
HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg)
{
char *xmsg;
if (umsg[0] == '\0') {
Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"",
levelName);
return;
}
xmsg = Var_Subst(umsg, SCOPE_CMDLINE, VARE_EVAL);
/* TODO: handle errors */
Parse_Error(level, "%s", xmsg);
free(xmsg);
if (level == PARSE_FATAL) {
PrintOnError(NULL, "\n");
exit(1);
}
}
/*
* Add the child to the parent's children, and for non-special targets, vice
* versa.
*/
static void
LinkSource(GNode *pgn, GNode *cgn, bool isSpecial)
{
if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts))
pgn = pgn->cohorts.last->datum;
Lst_Append(&pgn->children, cgn);
pgn->unmade++;
/*
* Special targets like .END do not need to be informed once the child
* target has been made.
*/
if (!isSpecial)
Lst_Append(&cgn->parents, pgn);
if (DEBUG(PARSE)) {
debug_printf("Target \"%s\" depends on \"%s\"\n",
pgn->name, cgn->name);
Targ_PrintNode(pgn, 0);
Targ_PrintNode(cgn, 0);
}
}
/* Add the node to each target from the current dependency group. */
static void
LinkToTargets(GNode *gn, bool isSpecial)
{
GNodeListNode *ln;
for (ln = targets->first; ln != NULL; ln = ln->next)
LinkSource(ln->datum, gn, isSpecial);
}
static bool
TryApplyDependencyOperator(GNode *gn, GNodeType op)
{
/*
* If the node occurred on the left-hand side of a dependency and the
* operator also defines a dependency, they must match.
*/
if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
((op & OP_OPMASK) != (gn->type & OP_OPMASK))) {
Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
gn->name);
return false;
}
if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
/*
* If the node was on the left-hand side of a '::' operator,
* create a new node for the children and commands on this
* dependency line, since each of these dependency groups has
* its own attributes and commands, separate from the others.
*
* The new instance is placed on the 'cohorts' list of the
* initial one (note the initial one is not on its own
* cohorts list) and the new instance is linked to all
* parents of the initial instance.
*/
GNode *cohort;
/*
* Propagate copied bits to the initial node. They'll be
* propagated back to the rest of the cohorts later.
*/
gn->type |= op & (unsigned)~OP_OPMASK;
cohort = Targ_NewInternalNode(gn->name);
if (doing_depend)
RememberLocation(cohort);
/*
* Make the cohort invisible to avoid duplicating it
* into other variables. True, parents of this target won't
* tend to do anything with their local variables, but better
* safe than sorry.
*
* (I think this is pointless now, since the relevant list
* traversals will no longer see this node anyway. -mycroft)
*/
cohort->type = op | OP_INVISIBLE;
Lst_Append(&gn->cohorts, cohort);
cohort->centurion = gn;
gn->unmade_cohorts++;
snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
(unsigned int)gn->unmade_cohorts % 1000000);
} else {
gn->type |= op; /* preserve any previous flags */
}
return true;
}
static void
ApplyDependencyOperator(GNodeType op)
{
GNodeListNode *ln;
for (ln = targets->first; ln != NULL; ln = ln->next)
if (!TryApplyDependencyOperator(ln->datum, op))
break;
}
/*
* Add a .WAIT node in the dependency list. After any dynamic dependencies
* (and filename globbing) have happened, it is given a dependency on each
* previous child, back until the previous .WAIT node. The next child won't
* be scheduled until the .WAIT node is built.
*
* Give each .WAIT node a unique name (mainly for diagnostics).
*/
static void
ApplyDependencySourceWait(bool isSpecial)
{
static unsigned wait_number = 0;
char name[6 + 10 + 1];
GNode *gn;
snprintf(name, sizeof name, ".WAIT_%u", ++wait_number);
gn = Targ_NewInternalNode(name);
if (doing_depend)
RememberLocation(gn);
gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
LinkToTargets(gn, isSpecial);
}
static bool
ApplyDependencySourceKeyword(const char *src, ParseSpecial special)
{
int keywd;
GNodeType targetAttr;
if (*src != '.' || !ch_isupper(src[1]))
return false;
keywd = FindKeyword(src);
if (keywd == -1)
return false;
targetAttr = parseKeywords[keywd].targetAttr;
if (targetAttr != OP_NONE) {
ApplyDependencyOperator(targetAttr);
return true;
}
if (parseKeywords[keywd].special == SP_WAIT) {
ApplyDependencySourceWait(special != SP_NOT);
return true;
}
return false;
}
/*
* In a line like ".MAIN: source1 source2", add all sources to the list of
* things to create, but only if the user didn't specify a target on the
* command line and .MAIN occurs for the first time.
*
* See HandleDependencyTargetSpecial, branch SP_MAIN.
* See unit-tests/cond-func-make-main.mk.
*/
static void
ApplyDependencySourceMain(const char *src)
{
Lst_Append(&opts.create, bmake_strdup(src));
/*
* Add the name to the .TARGETS variable as well, so the user can
* employ that, if desired.
*/
Global_Append(".TARGETS", src);
}
/*
* For the sources of a .ORDER target, create predecessor/successor links
* between the previous source and the current one.
*/
static void
ApplyDependencySourceOrder(const char *src)
{
GNode *gn;
gn = Targ_GetNode(src);
if (doing_depend)
RememberLocation(gn);
if (order_pred != NULL) {
Lst_Append(&order_pred->order_succ, gn);
Lst_Append(&gn->order_pred, order_pred);
if (DEBUG(PARSE)) {
debug_printf(
"# .ORDER forces '%s' to be made before '%s'\n",
order_pred->name, gn->name);
Targ_PrintNode(order_pred, 0);
Targ_PrintNode(gn, 0);
}
}
/* The current source now becomes the predecessor for the next one. */
order_pred = gn;
}
/* The source is not an attribute, so find/create a node for it. */
static void
ApplyDependencySourceOther(const char *src, GNodeType targetAttr,
ParseSpecial special)
{
GNode *gn;
gn = Targ_GetNode(src);
if (doing_depend)
RememberLocation(gn);
if (targetAttr != OP_NONE)
gn->type |= targetAttr;
else
LinkToTargets(gn, special != SP_NOT);
}
/*
* Given the name of a source in a dependency line, figure out if it is an
* attribute (such as .SILENT) and if so, apply it to all targets. Otherwise
* decide if there is some attribute which should be applied *to* the source
* because of some special target (such as .PHONY) and apply it if so.
* Otherwise, make the source a child of the targets.
*/
static void
ApplyDependencySource(GNodeType targetAttr, const char *src,
ParseSpecial special)
{
if (ApplyDependencySourceKeyword(src, special))
return;
if (special == SP_MAIN)
ApplyDependencySourceMain(src);
else if (special == SP_ORDER)
ApplyDependencySourceOrder(src);
else
ApplyDependencySourceOther(src, targetAttr, special);
}
/*
* If we have yet to decide on a main target to make, in the absence of any
* user input, we want the first target on the first dependency line that is
* actually a real target (i.e. isn't a .USE or .EXEC rule) to be made.
*/
static void
MaybeUpdateMainTarget(void)
{
GNodeListNode *ln;
if (mainNode != NULL)
return;
for (ln = targets->first; ln != NULL; ln = ln->next) {
GNode *gn = ln->datum;
if (GNode_IsMainCandidate(gn)) {
DEBUG1(MAKE, "Setting main node to \"%s\"\n",
gn->name);
mainNode = gn;
return;
}
}
}
static void
InvalidLineType(const char *line, const char *unexpanded_line)
{
if (unexpanded_line[0] == '.') {
const char *dirstart = unexpanded_line + 1;
const char *dirend;
cpp_skip_whitespace(&dirstart);
dirend = dirstart;
while (ch_isalnum(*dirend) || *dirend == '-')
dirend++;
Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
(int)(dirend - dirstart), dirstart);
} else if (strcmp(line, unexpanded_line) == 0)
Parse_Error(PARSE_FATAL, "Invalid line '%s'", line);
else
Parse_Error(PARSE_FATAL,
"Invalid line '%s', expanded to '%s'",
unexpanded_line, line);
}
static void
ParseDependencyTargetWord(char **pp, const char *lstart)
{
const char *p = *pp;
while (*p != '\0') {
if ((ch_isspace(*p) || *p == '!' || *p == ':' || *p == '(')
&& !IsEscaped(lstart, p))
break;
if (*p == '$') {
FStr val = Var_Parse(&p, SCOPE_CMDLINE, VARE_PARSE);
/* TODO: handle errors */
FStr_Done(&val);
} else
p++;
}
*pp += p - *pp;
}
/*
* Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
*
* See the tests deptgt-*.mk.
*/
static void
HandleDependencyTargetSpecial(const char *targetName,
ParseSpecial *inout_special,
SearchPathList **inout_paths)
{
switch (*inout_special) {
case SP_PATH:
if (*inout_paths == NULL)
*inout_paths = Lst_New();
Lst_Append(*inout_paths, &dirSearchPath);
break;
case SP_SYSPATH:
if (*inout_paths == NULL)
*inout_paths = Lst_New();
Lst_Append(*inout_paths, sysIncPath);
break;
case SP_MAIN:
/*
* Allow targets from the command line to override the
* .MAIN node.
*/
if (!Lst_IsEmpty(&opts.create))
*inout_special = SP_NOT;
break;
case SP_BEGIN:
case SP_END:
case SP_STALE:
case SP_ERROR:
case SP_INTERRUPT: {
GNode *gn = Targ_GetNode(targetName);
if (doing_depend)
RememberLocation(gn);
gn->type |= OP_NOTMAIN | OP_SPECIAL;
Lst_Append(targets, gn);
break;
}
case SP_DEFAULT: {
/*
* Need to create a node to hang commands on, but we don't
* want it in the graph, nor do we want it to be the Main
* Target. We claim the node is a transformation rule to make
* life easier later, when we'll use Make_HandleUse to
* actually apply the .DEFAULT commands.
*/
GNode *gn = GNode_New(".DEFAULT");
gn->type |= OP_NOTMAIN | OP_TRANSFORM;
Lst_Append(targets, gn);
defaultNode = gn;
break;
}
case SP_DELETE_ON_ERROR:
deleteOnError = true;
break;
case SP_NOTPARALLEL:
opts.maxJobs = 1;
break;
case SP_SINGLESHELL:
opts.compatMake = true;
break;
case SP_ORDER:
order_pred = NULL;
break;
default:
break;
}
}
static bool
HandleDependencyTargetPath(const char *suffixName,
SearchPathList **inout_paths)
{
SearchPath *path;
path = Suff_GetPath(suffixName);