-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdpmake.c
4084 lines (3692 loc) · 91.6 KB
/
pdpmake.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
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* Check structures for make.
*/
/*
* Include header for make
*/
#define _XOPEN_SOURCE 700
#if defined(__sun__)
# define __EXTENSIONS__
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
extern char **environ;
#define NORETURN __attribute__ ((__noreturn__))
// Resetting getopt(3) is hopelessly platform-dependent. If command
// line options don't work as expected you may need to tweak this.
// The default should work for GNU libc and OpenBSD.
#if defined(__FreeBSD__) || defined(__NetBSD__)
# define GETOPT_RESET() do { \
extern int optreset; \
optind = 1; \
optreset = 1; \
} while (0)
#elif defined(__sun__)
# define GETOPT_RESET() (optind = 1)
#else
# define GETOPT_RESET() (optind = 0)
#endif
// Supported POSIX levels
#define STD_POSIX_2017 0
#define STD_POSIX_2024 1
// If ENABLE_FEATURE_MAKE_EXTENSIONS is non-zero some non-POSIX extensions
// are enabled.
//
#ifndef ENABLE_FEATURE_MAKE_EXTENSIONS
# define ENABLE_FEATURE_MAKE_EXTENSIONS 1
#endif
#ifndef DEFAULT_POSIX_LEVEL
# define DEFAULT_POSIX_LEVEL STD_POSIX_2024
#endif
#if ENABLE_FEATURE_MAKE_EXTENSIONS
# define IF_FEATURE_MAKE_EXTENSIONS(...) __VA_ARGS__
# define IF_NOT_FEATURE_MAKE_EXTENSIONS(...)
# define POSIX_2017 (posix && posix_level == STD_POSIX_2017)
#else
# define IF_FEATURE_MAKE_EXTENSIONS(...)
# define IF_NOT_FEATURE_MAKE_EXTENSIONS(...) __VA_ARGS__
#endif
// IF ENABLE_FEATURE_MAKE_POSIX_2024 is non-zero POSIX 2024 features
// are enabled.
#ifndef ENABLE_FEATURE_MAKE_POSIX_2024
# define ENABLE_FEATURE_MAKE_POSIX_2024 ENABLE_FEATURE_MAKE_EXTENSIONS
#endif
#if ENABLE_FEATURE_MAKE_POSIX_2024
# define IF_FEATURE_MAKE_POSIX_2024(...) __VA_ARGS__
# define IF_NOT_FEATURE_MAKE_POSIX_2024(...)
#else
# define IF_FEATURE_MAKE_POSIX_2024(...)
# define IF_NOT_FEATURE_MAKE_POSIX_2024(...) __VA_ARGS__
#endif
#if ENABLE_FEATURE_MAKE_EXTENSIONS
# define POSIX_2017 (posix && posix_level == STD_POSIX_2017)
#elif ENABLE_FEATURE_MAKE_POSIX_2024
# define POSIX_2017 FALSE
#endif
// If ENABLE_FEATURE_CLEAN_UP is non-zero all allocated structures are
// freed at the end of main(). This isn't necessary but it's a nice test.
#ifndef ENABLE_FEATURE_CLEAN_UP
# define ENABLE_FEATURE_CLEAN_UP 0
#endif
#define TRUE (1)
#define FALSE (0)
#define MAX(a,b) ((a)>(b)?(a):(b))
#if defined(__GLIBC__) && ENABLE_FEATURE_MAKE_EXTENSIONS
// By default GNU libc getopt(3) allows options and non-options to be
// mixed. Turn this off in POSIX mode. The '+' prefix in OPTSTR1 is
// otherwise unused and should be skipped.
# define OPT_OFFSET + !posix
#else
# define OPT_OFFSET
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wstring-plus-int"
#endif
#if ENABLE_FEATURE_MAKE_EXTENSIONS
#define OPTSTR1 "+ehij:knqrsSt"
#elif ENABLE_FEATURE_MAKE_POSIX_2024
#define OPTSTR1 "+eij:knqrsSt"
#else
#define OPTSTR1 "+eiknqrsSt"
#endif
#if ENABLE_FEATURE_MAKE_EXTENSIONS
#define OPTSTR2 "pf:C:x:"
#else
#define OPTSTR2 "pf:"
#endif
enum {
OPTBIT_e = 0,
IF_FEATURE_MAKE_EXTENSIONS(OPTBIT_h,)
OPTBIT_i,
IF_FEATURE_MAKE_POSIX_2024(OPTBIT_j,)
OPTBIT_k,
OPTBIT_n,
OPTBIT_q,
OPTBIT_r,
OPTBIT_s,
OPTBIT_S,
OPTBIT_t,
OPTBIT_p,
OPTBIT_f,
IF_FEATURE_MAKE_EXTENSIONS(OPTBIT_C,)
IF_FEATURE_MAKE_EXTENSIONS(OPTBIT_x,)
OPTBIT_precious,
IF_FEATURE_MAKE_POSIX_2024(OPTBIT_phony,)
IF_FEATURE_MAKE_POSIX_2024(OPTBIT_include,)
IF_FEATURE_MAKE_POSIX_2024(OPTBIT_make,)
OPT_e = (1 << OPTBIT_e),
OPT_h = IF_FEATURE_MAKE_EXTENSIONS((1 << OPTBIT_h)) + 0,
OPT_i = (1 << OPTBIT_i),
OPT_j = IF_FEATURE_MAKE_POSIX_2024((1 << OPTBIT_j)) + 0,
OPT_k = (1 << OPTBIT_k),
OPT_n = (1 << OPTBIT_n),
OPT_q = (1 << OPTBIT_q),
OPT_r = (1 << OPTBIT_r),
OPT_s = (1 << OPTBIT_s),
OPT_S = (1 << OPTBIT_S),
OPT_t = (1 << OPTBIT_t),
// These options aren't allowed in MAKEFLAGS
OPT_p = (1 << OPTBIT_p),
OPT_f = (1 << OPTBIT_f),
OPT_C = IF_FEATURE_MAKE_EXTENSIONS((1 << OPTBIT_C)) + 0,
OPT_x = IF_FEATURE_MAKE_EXTENSIONS((1 << OPTBIT_x)) + 0,
// The following aren't command line options and must be last
OPT_precious = (1 << OPTBIT_precious),
OPT_phony = IF_FEATURE_MAKE_POSIX_2024((1 << OPTBIT_phony)) + 0,
OPT_include = IF_FEATURE_MAKE_POSIX_2024((1 << OPTBIT_include)) + 0,
OPT_make = IF_FEATURE_MAKE_POSIX_2024((1 << OPTBIT_make)) + 0,
};
// Options in OPTSTR1 that aren't included in MAKEFLAGS
#define OPT_MASK (~OPT_S)
#define useenv (opts & OPT_e)
#define ignore (opts & OPT_i)
#define errcont (opts & OPT_k)
#define dryrun (opts & OPT_n)
#define print (opts & OPT_p)
#define quest (opts & OPT_q)
#define norules (opts & OPT_r)
#define silent (opts & OPT_s)
#define dotouch (opts & OPT_t)
#define precious (opts & OPT_precious)
#define doinclude (opts & OPT_include)
#define domake (opts & OPT_make)
// A name. This represents a file, either to be made, or pre-existing.
struct name {
struct name *n_next; // Next in the list of names
char *n_name; // Called
struct rule *n_rule; // Rules to build this (prerequisites/commands)
struct timespec n_tim; // Modification time of this name
uint16_t n_flag; // Info about the name
};
#define N_DOING 0x01 // Name in process of being built
#define N_DONE 0x02 // Name looked at
#define N_TARGET 0x04 // Name is a target
#define N_PRECIOUS 0x08 // Target is precious
#if ENABLE_FEATURE_MAKE_EXTENSIONS
#define N_DOUBLE 0x10 // Double-colon target
#else
#define N_DOUBLE 0x00 // No support for double-colon target
#endif
#define N_SILENT 0x20 // Build target silently
#define N_IGNORE 0x40 // Ignore build errors
#define N_SPECIAL 0x80 // Special target
#if ENABLE_FEATURE_MAKE_EXTENSIONS || ENABLE_FEATURE_MAKE_POSIX_2024
#define N_MARK 0x100 // Mark for deduplication
#endif
#if ENABLE_FEATURE_MAKE_POSIX_2024
#define N_PHONY 0x200 // Name is a phony target
#else
#define N_PHONY 0 // No support for phony targets
#endif
#define N_INFERENCE 0x400 // Inference rule
// List of rules to build a target
struct rule {
struct rule *r_next; // Next rule
struct depend *r_dep; // Prerequisites for this rule
struct cmd *r_cmd; // Commands for this rule
};
// NOTE: the layout of the following two structures must be compatible.
// List of prerequisites for a rule
struct depend {
struct depend *d_next; // Next prerequisite
struct name *d_name; // Name of prerequisite
int d_refcnt; // Reference count
};
// List of commands for a rule
struct cmd {
struct cmd *c_next; // Next command line
char *c_cmd; // Text of command line
int c_refcnt; // Reference count
const char *c_makefile; // Makefile in which command was defined
int c_dispno; // Line number within makefile
};
// Macro storage
struct macro {
struct macro *m_next; // Next variable
char *m_name; // Its name
char *m_val; // Its value
#if ENABLE_FEATURE_MAKE_EXTENSIONS || ENABLE_FEATURE_MAKE_POSIX_2024
bool m_immediate; // Immediate-expansion macro set using ::=
#endif
bool m_flag; // Infinite loop check
uint8_t m_level; // Level at which macro was created
};
// List of file names
struct file {
struct file *f_next;
char *f_name;
};
// Flags passed to setmacro()
#define M_IMMEDIATE 0x08 // immediate-expansion macro is being defined
#define M_VALID 0x10 // assert macro name is valid
#define M_ENVIRON 0x20 // macro imported from environment
#define HTABSIZE 199
// Constants for PRAGMA. Order must match strings in set_pragma().
enum {
BIT_MACRO_NAME = 0,
BIT_TARGET_NAME,
BIT_COMMAND_COMMENT,
BIT_EMPTY_SUFFIX,
#if defined(__CYGWIN__)
BIT_WINDOWS,
#endif
BIT_POSIX_2017,
BIT_POSIX_2024,
BIT_POSIX_202X,
P_MACRO_NAME = (1 << BIT_MACRO_NAME),
P_TARGET_NAME = (1 << BIT_TARGET_NAME),
P_COMMAND_COMMENT = (1 << BIT_COMMAND_COMMENT),
P_EMPTY_SUFFIX = (1 << BIT_EMPTY_SUFFIX),
#if defined(__CYGWIN__)
P_WINDOWS = (1 << BIT_WINDOWS),
#endif
};
// Status of make()
#define MAKE_FAILURE 0x01
#define MAKE_DIDSOMETHING 0x02
extern const char *myname;
extern const char *makefile;
extern struct name *namehead[HTABSIZE];
extern struct macro *macrohead[HTABSIZE];
extern struct name *firstname;
extern struct name *target;
extern uint32_t opts;
extern int lineno;
extern int dispno;
#if ENABLE_FEATURE_MAKE_POSIX_2024
extern char *numjobs;
#endif
#if ENABLE_FEATURE_MAKE_EXTENSIONS
extern bool posix;
extern bool seen_first;
extern unsigned char pragma;
extern unsigned char posix_level;
#endif
// Return TRUE if c is allowed in a POSIX 2017 macro or target name
#define ispname(c) (isalpha(c) || isdigit(c) || c == '.' || c == '_')
// Return TRUE if c is in the POSIX 'portable filename character set'
#define isfname(c) (ispname(c) || c == '-')
void print_details(void);
#if !ENABLE_FEATURE_MAKE_POSIX_2024
#define expand_macros(s, e) expand_macros(s)
#endif
char *expand_macros(const char *str, int except_dollar);
void input(FILE *fd, int ilevel);
struct macro *getmp(const char *name);
void setmacro(const char *name, const char *val, int level);
void freemacros(void);
void remove_target(void);
int make(struct name *np, int level);
char *splitlib(const char *name, char **member);
void modtime(struct name *np);
char *suffix(const char *name);
int is_suffix(const char *s);
struct name *dyndep(struct name *np, struct rule *imprule);
char *getrules(char *s, int size);
struct name *findname(const char *name);
struct name *newname(const char *name);
struct cmd *getcmd(struct name *np);
void freenames(void);
struct depend *newdep(struct name *np, struct depend *dp);
void freedeps(struct depend *dp);
struct cmd *newcmd(char *str, struct cmd *cp);
void freecmds(struct cmd *cp);
void freerules(struct rule *rp);
void set_pragma(const char *name);
void addrule(struct name *np, struct depend *dp, struct cmd *cp, int flag);
void diagnostic(const char *msg, ...);
void error(const char *msg, ...) NORETURN;
void error_unexpected(const char *s) NORETURN;
void error_in_inference_rule(const char *s) NORETURN;
void error_not_allowed(const char *s, const char *t);
void warning(const char *msg, ...);
void *xmalloc(size_t len);
void *xrealloc(void *ptr, size_t len);
char *xconcat3(const char *s1, const char *s2, const char *s3);
char *xstrdup(const char *s);
char *xstrndup(const char *s, size_t n);
char *xappendword(const char *str, const char *word);
unsigned int getbucket(const char *name);
struct file *newfile(char *str, struct file *fphead);
void freefiles(struct file *fp);
int is_valid_target(const char *name);
void pragmas_from_env(void);
void pragmas_to_env(void);
static void
print_name(struct name *np)
{
if (np == firstname)
printf("# default target\n");
printf("%s:", np->n_name);
if ((np->n_flag & N_DOUBLE))
putchar(':');
}
static void
print_prerequisites(struct rule *rp)
{
struct depend *dp;
for (dp = rp->r_dep; dp; dp = dp->d_next)
printf(" %s", dp->d_name->n_name);
}
static void
print_commands(struct rule *rp)
{
struct cmd *cp;
for (cp = rp->r_cmd; cp; cp = cp->c_next)
printf("\t%s\n", cp->c_cmd);
}
void
print_details(void)
{
int i;
struct macro *mp;
struct name *np;
struct rule *rp;
for (i = 0; i < HTABSIZE; i++)
for (mp = macrohead[i]; mp; mp = mp->m_next)
printf("%s = %s\n", mp->m_name, mp->m_val);
putchar('\n');
for (i = 0; i < HTABSIZE; i++) {
for (np = namehead[i]; np; np = np->n_next) {
if (!(np->n_flag & N_DOUBLE)) {
print_name(np);
for (rp = np->n_rule; rp; rp = rp->r_next) {
print_prerequisites(rp);
}
putchar('\n');
for (rp = np->n_rule; rp; rp = rp->r_next) {
print_commands(rp);
}
putchar('\n');
} else {
for (rp = np->n_rule; rp; rp = rp->r_next) {
print_name(np);
print_prerequisites(rp);
putchar('\n');
print_commands(rp);
putchar('\n');
}
}
}
}
}
/*
* Parse a makefile
*/
#include <glob.h>
int lineno; // Physical line number in file
int dispno; // Line number for display purposes
/*
* Return a pointer to the next blank-delimited word or NULL if
* there are none left.
*/
static char *
gettok(char **ptr)
{
char *p;
while (isblank(**ptr)) // Skip blanks
(*ptr)++;
if (**ptr == '\0') // Nothing after blanks
return NULL;
p = *ptr; // Word starts here
while (**ptr != '\0' && !isblank(**ptr))
(*ptr)++; // Find end of word
// Terminate token and move on unless already at end of string
if (**ptr != '\0')
*(*ptr)++ = '\0';
return(p);
}
/*
* Skip over (possibly adjacent or nested) macro expansions.
*/
static char *
skip_macro(const char *s)
{
while (*s && s[0] == '$') {
if (s[1] == '(' || s[1] == '{') {
char end = *++s == '(' ? ')' : '}';
while (*s && *s != end)
s = skip_macro(s + 1);
if (*s == end)
++s;
} else if (s[1] != '\0') {
s += 2;
} else {
break;
}
}
return (char *)s;
}
#if !ENABLE_FEATURE_MAKE_POSIX_2024
# define modify_words(v, m, lf, lr, fp, rp, fs, rs) \
modify_words(v, m, lf, lr, fs, rs)
#endif
/*
* Process each whitespace-separated word in the input string:
*
* - replace paths with their directory or filename part
* - replace prefixes and suffixes
*
* Returns an allocated string or NULL if the input is unmodified.
*/
static char *
modify_words(const char *val, int modifier, size_t lenf, size_t lenr,
const char *find_pref, const char *repl_pref,
const char *find_suff, const char *repl_suff)
{
char *s, *copy, *word, *sep, *newword, *buf = NULL;
#if ENABLE_FEATURE_MAKE_POSIX_2024
size_t find_pref_len = 0, find_suff_len = 0;
#endif
if (!modifier && lenf == 0 && lenr == 0)
return buf;
#if ENABLE_FEATURE_MAKE_POSIX_2024
if (find_pref) {
// get length of find prefix, e.g: src/
find_pref_len = strlen(find_pref);
// get length of find suffix, e.g: .c
find_suff_len = lenf - find_pref_len - 1;
}
#endif
s = copy = xstrdup(val);
while ((word = gettok(&s)) != NULL) {
newword = NULL;
if (modifier) {
sep = strrchr(word, '/');
if (modifier == 'D') {
if (!sep) {
word[0] = '.'; // no '/', return "."
sep = word + 1;
} else if (sep == word) {
// '/' at start of word, return "/"
sep = word + 1;
}
// else terminate at separator
*sep = '\0';
} else if (/* modifier == 'F' && */ sep) {
word = sep + 1;
}
}
if (IF_FEATURE_MAKE_POSIX_2024(find_pref != NULL ||)
lenf != 0 || lenr != 0) {
size_t lenw = strlen(word);
#if ENABLE_FEATURE_MAKE_POSIX_2024
// This code implements pattern macro expansions:
// https://austingroupbugs.net/view.php?id=519
//
// find: <prefix>%<suffix>
// example: src/%.c
//
// For a pattern of the form:
// $(string1:[op]%[os]=[np][%][ns])
// lenf is the length of [op]%[os]. So lenf >= 1.
if (find_pref != NULL && lenw + 1 >= lenf) {
// If prefix and suffix of word match find_pref and
// find_suff, then do substitution.
if (strncmp(word, find_pref, find_pref_len) == 0 &&
strcmp(word + lenw - find_suff_len, find_suff) == 0) {
// replace: <prefix>[%<suffix>]
// example: build/%.o or build/all.o (notice no %)
// If repl_suff is NULL, replace whole word with repl_pref.
if (!repl_suff) {
word = newword = xstrdup(repl_pref);
} else {
word[lenw - find_suff_len] = '\0';
word = newword = xconcat3(repl_pref,
word + find_pref_len, repl_suff);
}
}
} else
#endif
if (lenw >= lenf && strcmp(word + lenw - lenf, find_suff) == 0) {
word[lenw - lenf] = '\0';
word = newword = xconcat3(word, repl_suff, "");
}
}
buf = xappendword(buf, word);
free(newword);
}
free(copy);
return buf;
}
/*
* Return a pointer to the next instance of a given character. Macro
* expansions are skipped so the ':' and '=' in $(VAR:.s1=.s2) aren't
* detected as separators in macro definitions. Some other situations
* also require skipping the internals of a macro expansion.
*/
static char *
find_char(const char *str, int c)
{
const char *s;
for (s = skip_macro(str); *s; s = skip_macro(s + 1)) {
if (*s == c)
return (char *)s;
}
return NULL;
}
#if ENABLE_FEATURE_MAKE_EXTENSIONS && defined(__CYGWIN__)
/*
* Check for a target rule by searching for a colon that isn't
* part of a Windows path. Return a pointer to the colon or NULL.
*/
static char *
find_colon(char *p)
{
char *q;
for (q = p; (q = strchr(q, ':')); ++q) {
if (posix && !(pragma & P_WINDOWS))
break;
if (q == p || !isalpha(q[-1]) || q[1] != '/')
break;
}
return q;
}
#else
# define find_colon(s) strchr(s, ':')
#endif
/*
* Recursively expand any macros in str to an allocated string.
*/
char *
expand_macros(const char *str, int except_dollar)
{
char *exp, *newexp, *s, *t, *p, *q, *name;
char *find, *replace, *modified;
char *expval, *expfind, *find_suff, *repl_suff;
#if ENABLE_FEATURE_MAKE_POSIX_2024
char *find_pref = NULL, *repl_pref = NULL;
#endif
size_t lenf, lenr;
char modifier;
struct macro *mp;
exp = xstrdup(str);
for (t = exp; *t; t++) {
if (*t == '$') {
if (t[1] == '\0') {
break;
}
#if ENABLE_FEATURE_MAKE_POSIX_2024
if (t[1] == '$' && except_dollar) {
t++;
continue;
}
#endif
// Need to expand a macro. Find its extent (s to t inclusive)
// and take a copy of its content.
s = t;
t++;
if (*t == '{' || *t == '(') {
t = find_char(t, *t == '{' ? '}' : ')');
if (t == NULL)
error("unterminated variable '%s'", s);
name = xstrndup(s + 2, t - s - 2);
} else {
name = xmalloc(2);
name[0] = *t;
name[1] = '\0';
}
// Only do suffix replacement or pattern macro expansion
// if both ':' and '=' are found, plus a '%' for the latter.
// Suffix replacement is indicated by
// find_pref == NULL && (lenf != 0 || lenr != 0);
// pattern macro expansion by find_pref != NULL.
expfind = NULL;
find_suff = repl_suff = NULL;
lenf = lenr = 0;
if ((find = find_char(name, ':'))) {
*find++ = '\0';
expfind = expand_macros(find, FALSE);
if ((replace = find_char(expfind, '='))) {
*replace++ = '\0';
lenf = strlen(expfind);
#if ENABLE_FEATURE_MAKE_POSIX_2024
if (!POSIX_2017 && (find_suff = strchr(expfind, '%'))) {
find_pref = expfind;
repl_pref = replace;
*find_suff++ = '\0';
if ((repl_suff = strchr(replace, '%')))
*repl_suff++ = '\0';
} else
#endif
{
if (IF_FEATURE_MAKE_EXTENSIONS(posix &&
!(pragma & P_EMPTY_SUFFIX) &&)
lenf == 0)
error("empty suffix%s",
!ENABLE_FEATURE_MAKE_EXTENSIONS ? "" :
": allow with pragma empty_suffix");
find_suff = expfind;
repl_suff = replace;
lenr = strlen(repl_suff);
}
}
}
p = q = name;
#if ENABLE_FEATURE_MAKE_POSIX_2024
// If not in POSIX mode expand macros in the name.
if (!POSIX_2017) {
char *expname = expand_macros(name, FALSE);
free(name);
name = expname;
} else
#endif
// Skip over nested expansions in name
do {
*q++ = *p;
} while ((p = skip_macro(p + 1)) && *p);
// The internal macros support 'D' and 'F' modifiers
modifier = '\0';
switch (name[0]) {
#if ENABLE_FEATURE_MAKE_POSIX_2024
case '^':
case '+':
if (POSIX_2017)
break;
// fall through
#endif
case '@': case '%': case '?': case '<': case '*':
if ((name[1] == 'D' || name[1] == 'F') && name[2] == '\0') {
modifier = name[1];
name[1] = '\0';
}
break;
}
modified = NULL;
if ((mp = getmp(name))) {
// Recursive expansion
if (mp->m_flag)
error("recursive macro %s", name);
#if ENABLE_FEATURE_MAKE_POSIX_2024
// Note if we've expanded $(MAKE)
if (strcmp(name, "MAKE") == 0)
opts |= OPT_make;
#endif
mp->m_flag = TRUE;
expval = expand_macros(mp->m_val, FALSE);
mp->m_flag = FALSE;
modified = modify_words(expval, modifier, lenf, lenr,
find_pref, repl_pref, find_suff, repl_suff);
if (modified)
free(expval);
else
modified = expval;
}
free(name);
free(expfind);
if (modified && *modified) {
// The text to be replaced by the macro expansion is
// from s to t inclusive.
*s = '\0';
newexp = xconcat3(exp, modified, t + 1);
t = newexp + (s - exp) + strlen(modified) - 1;
free(exp);
exp = newexp;
} else {
// Macro wasn't expanded or expanded to nothing.
// Close the space occupied by the macro reference.
q = t + 1;
t = s - 1;
while ((*s++ = *q++))
continue;
}
free(modified);
}
}
return exp;
}
/*
* Process a non-command line
*/
static void
process_line(char *s)
{
char *t;
// Strip comment
#if ENABLE_FEATURE_MAKE_EXTENSIONS
// don't treat '#' in macro expansion as a comment
// nor '#' outside macro expansion preceded by backslash
if (!posix) {
char *u = s;
while ((t = find_char(u, '#')) && t > u && t[-1] == '\\') {
for (u = t; *u; ++u) {
u[-1] = u[0];
}
*u = '\0';
u = t;
}
} else
#endif
t = strchr(s, '#');
if (t)
*t = '\0';
// Replace escaped newline and any leading white space on the
// following line with a single space. Stop processing at a
// non-escaped newline.
for (t = s; *s && *s != '\n'; ) {
if (s[0] == '\\' && s[1] == '\n') {
s += 2;
while (isspace(*s))
++s;
*t++ = ' ';
} else {
*t++ = *s++;
}
}
*t = '\0';
}
#if ENABLE_FEATURE_MAKE_EXTENSIONS
enum {
INITIAL = 0,
SKIP_LINE = 1 << 0,
EXPECT_ELSE = 1 << 1,
GOT_MATCH = 1 << 2
};
#define IF_MAX 10
static uint8_t clevel = 0;
static uint8_t cstate[IF_MAX + 1] = {INITIAL};
/*
* Extract strings following ifeq/ifneq and compare them.
* Return -1 on error.
*/
static int
compare_strings(char *arg1)
{
char *arg2, *end, term, *t1, *t2;
int ret;
// Get first string terminator.
if (arg1[0] == '(')
term = ',';
else if (arg1[0] == '"' || arg1[0] == '\'')
term = arg1[0];
else
return -1;
arg2 = find_char(++arg1, term);
if (arg2 == NULL)
return -1;
*arg2++ = '\0';
// Get second string terminator.
if (term == ',') {
term = ')';
} else {
// Skip spaces between quoted strings.
while (isspace(arg2[0]))
arg2++;
if (arg2[0] == '"' || arg2[0] == '\'')
term = arg2[0];
else
return -1;
++arg2;
}
end = find_char(arg2, term);
if (end == NULL)
return -1;
*end++ = '\0';
if (gettok(&end) != NULL) {
warning("unexpected text");
}
t1 = expand_macros(arg1, FALSE);
t2 = expand_macros(arg2, FALSE);
ret = strcmp(t1, t2) == 0;
free(t1);
free(t2);
return ret;
}
/*
* Process conditional directives and return TRUE if the current line
* should be skipped.
*/
static int
skip_line(const char *str1)
{
char *copy, *q, *token;
bool new_level = TRUE;
// Default is to return skip flag for current level
int ret = cstate[clevel] & SKIP_LINE;
q = copy = xstrdup(str1);
process_line(copy);
if ((token = gettok(&q)) != NULL) {
if (strcmp(token, "endif") == 0) {
if (gettok(&q) != NULL)
error_unexpected("text");
if (clevel == 0)
error_unexpected(token);
--clevel;
ret = TRUE;
goto end;
} else if (strcmp(token, "else") == 0) {
if (!(cstate[clevel] & EXPECT_ELSE))
error_unexpected(token);
// If an earlier condition matched we'll now skip lines.
// If not we don't, though an 'else if' may override this.
if ((cstate[clevel] & GOT_MATCH))
cstate[clevel] |= SKIP_LINE;
else
cstate[clevel] &= ~SKIP_LINE;
token = gettok(&q);
if (token == NULL) {
// Simple else with no conditional directive
cstate[clevel] &= ~EXPECT_ELSE;
ret = TRUE;
goto end;
} else {
// A conditional directive is now required ('else if').
new_level = FALSE;
}
}
if (strcmp(token, "ifdef") == 0 || strcmp(token, "ifndef") == 0 ||
strcmp(token, "ifeq") == 0 || strcmp(token, "ifneq") == 0) {
int match;
if (token[2] == 'd' || token[3] == 'd') {
// ifdef/ifndef: find out if macro is defined.
char *name = gettok(&q);
if (name != NULL && gettok(&q) == NULL) {
char *t = expand_macros(name, FALSE);
struct macro *mp = getmp(t);
match = mp != NULL && mp->m_val[0] != '\0';
free(t);
} else {
match = -1;
}
} else {
// ifeq/ifneq: compare strings.
match = compare_strings(q);
}
if (match >= 0) {
if (new_level) {
// Start a new level.
if (clevel == IF_MAX)
error("nesting too deep");
++clevel;
cstate[clevel] = EXPECT_ELSE | SKIP_LINE;
// If we were skipping lines at the previous level
// we need to continue doing that unconditionally
// at the new level.
if ((cstate[clevel - 1] & SKIP_LINE))
cstate[clevel] |= GOT_MATCH;
}
if (!(cstate[clevel] & GOT_MATCH)) {
if (token[2] == 'n')
match = !match;
if (match) {
cstate[clevel] &= ~SKIP_LINE;
cstate[clevel] |= GOT_MATCH;
}
}