aboutsummaryrefslogtreecommitdiff
path: root/miscutils/make.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--miscutils/make.c3540
1 files changed, 3540 insertions, 0 deletions
diff --git a/miscutils/make.c b/miscutils/make.c
new file mode 100644
index 000000000..a165274aa
--- /dev/null
+++ b/miscutils/make.c
@@ -0,0 +1,3540 @@
1/* vi: set sw=4 ts=4: */
2/*
3 * make implementation for BusyBox
4 *
5 * Based on public domain POSIX make: https://frippery.org/make
6 */
7//config:config MAKE
8//config: bool "make (18 kb)"
9//config: default n
10//config: help
11//config: The make command can be used to maintain files that depend on
12//config: other files. Normally it's used to build programs from source
13//config: code but it can be used in other situations too.
14//config:
15//config:config PDPMAKE
16//config: bool "pdpmake (18 kb)"
17//config: default n
18//config: help
19//config: Alias for "make"
20//config:
21//config:config FEATURE_MAKE_POSIX
22//config: bool "Runtime enforcement of POSIX"
23//config: default n
24//config: depends on MAKE || PDPMAKE
25//config: help
26//config: Allow strict enforcement of POSIX compliance at runtime by:
27//config: - .POSIX special target in makefile
28//config: - '--posix' command line option
29//config: - PDPMAKE_POSIXLY_CORRECT environment variable
30//config: Enable this if you want to check whether your makefiles are
31//config: POSIX compliant. This adds about 1.7 kb.
32//config:
33//config:choice
34//config: prompt "Default POSIX level to enforce"
35//config: depends on FEATURE_MAKE_POSIX
36//config: default FEATURE_MAKE_POSIX_2017
37//config:
38//config:config FEATURE_MAKE_POSIX_2017
39//config: bool "2017"
40//config:
41//config:config FEATURE_MAKE_POSIX_2024
42//config: bool "2024"
43//config:
44//config:endchoice
45
46//applet:IF_MAKE(APPLET(make, BB_DIR_USR_BIN, BB_SUID_DROP))
47//applet:IF_PDPMAKE(APPLET_ODDNAME(pdpmake, make, BB_DIR_USR_BIN, BB_SUID_DROP, make))
48
49//kbuild:lib-$(CONFIG_MAKE) += make.o
50//kbuild:lib-$(CONFIG_PDPMAKE) += make.o
51
52//usage:#define make_trivial_usage
53//usage: IF_FEATURE_MAKE_POSIX(
54//usage: "[--posix] [-C DIR] [-f FILE] [-j NUM] [-x PRAG] [-eiknpqrsSt] [MACRO[:[:[:]]]=VAL]... [TARGET]..."
55//usage: )
56//usage: IF_NOT_FEATURE_MAKE_POSIX(
57//usage: "[-C DIR] [-f FILE] [-j NUM] [-eiknpqrsSt] [MACRO[:[:[:]]]=VAL]... [TARGET]..."
58//usage: )
59//usage:#define make_full_usage "\n\n"
60//usage: "Maintain files based on their dependencies\n"
61//usage: IF_FEATURE_MAKE_POSIX(
62//usage: "\n --posix Enforce POSIX mode"
63//usage: )
64//usage: "\n -C DIR Change to DIR"
65//usage: "\n -f FILE Makefile"
66//usage: "\n -j NUM Jobs to run in parallel (not implemented)"
67//usage: IF_FEATURE_MAKE_POSIX(
68//usage: "\n -x PRAG Make POSIX mode less strict"
69//usage: )
70//usage: "\n -e Environment variables override macros in makefiles"
71//usage: "\n -i Ignore exit status"
72//usage: "\n -k Continue on error"
73//usage: "\n -n Dry run"
74//usage: "\n -p Print macros and targets"
75//usage: "\n -q Query target; exit status 1 if not up to date"
76//usage: "\n -r Don't use built-in rules"
77//usage: "\n -s Make silently"
78//usage: "\n -S Stop on error"
79//usage: "\n -t Touch files instead of making them"
80//usage: IF_FEATURE_MAKE_POSIX(
81//usage: "\n\nThis build supports: non-POSIX extensions, POSIX 2024, POSIX 2017"
82//usage: )
83//usage: IF_FEATURE_MAKE_POSIX_2017(
84//usage: "\nIn strict POSIX mode the 2017 standard is enforced by default"
85//usage: )
86//usage: IF_FEATURE_MAKE_POSIX_2024(
87//usage: "\nIn strict POSIX mode the 2024 standard is enforced by default"
88//usage: )
89
90#include "libbb.h"
91#include "bb_archive.h"
92#include "common_bufsiz.h"
93#include <glob.h>
94
95// Supported POSIX levels
96#define STD_POSIX_2017 0
97#define STD_POSIX_2024 1
98
99#define POSIX_2017 (posix && posix_level == STD_POSIX_2017)
100
101#if ENABLE_FEATURE_MAKE_POSIX_2017
102# define DEFAULT_POSIX_LEVEL STD_POSIX_2017
103#else
104# define DEFAULT_POSIX_LEVEL STD_POSIX_2024
105#endif
106
107#define OPTSTR1 "eij:+knqrsSt"
108#if ENABLE_FEATURE_MAKE_POSIX
109#define OPTSTR2 "pf:*C:*x:*"
110#else
111#define OPTSTR2 "pf:*C:*"
112#endif
113
114enum {
115 OPTBIT_e = 0,
116 OPTBIT_i,
117 OPTBIT_j,
118 OPTBIT_k,
119 OPTBIT_n,
120 OPTBIT_q,
121 OPTBIT_r,
122 OPTBIT_s,
123 OPTBIT_S,
124 OPTBIT_t,
125 OPTBIT_p,
126 OPTBIT_f,
127 OPTBIT_C,
128 IF_FEATURE_MAKE_POSIX(OPTBIT_x,)
129 OPTBIT_precious,
130 OPTBIT_phony,
131 OPTBIT_include,
132 OPTBIT_make,
133
134 OPT_e = (1 << OPTBIT_e),
135 OPT_i = (1 << OPTBIT_i),
136 OPT_j = (1 << OPTBIT_j),
137 OPT_k = (1 << OPTBIT_k),
138 OPT_n = (1 << OPTBIT_n),
139 OPT_q = (1 << OPTBIT_q),
140 OPT_r = (1 << OPTBIT_r),
141 OPT_s = (1 << OPTBIT_s),
142 OPT_S = (1 << OPTBIT_S),
143 OPT_t = (1 << OPTBIT_t),
144 // These options aren't allowed in MAKEFLAGS
145 OPT_p = (1 << OPTBIT_p),
146 OPT_f = (1 << OPTBIT_f),
147 OPT_C = (1 << OPTBIT_C),
148 OPT_x = IF_FEATURE_MAKE_POSIX((1 << OPTBIT_x)) + 0,
149 // The following aren't command line options and must be last
150 OPT_precious = (1 << OPTBIT_precious),
151 OPT_phony = (1 << OPTBIT_phony),
152 OPT_include = (1 << OPTBIT_include),
153 OPT_make = (1 << OPTBIT_make),
154};
155
156// Options in OPTSTR1 that aren't included in MAKEFLAGS
157#define OPT_MASK (~OPT_S)
158
159#define useenv (opts & OPT_e)
160#define ignore (opts & OPT_i)
161#define errcont (opts & OPT_k)
162#define dryrun (opts & OPT_n)
163#define print (opts & OPT_p)
164#define quest (opts & OPT_q)
165#define norules (opts & OPT_r)
166#define silent (opts & OPT_s)
167#define dotouch (opts & OPT_t)
168#define precious (opts & OPT_precious)
169#define doinclude (opts & OPT_include)
170#define domake (opts & OPT_make)
171
172// A name. This represents a file, either to be made, or pre-existing.
173struct name {
174 struct name *n_next; // Next in the list of names
175 char *n_name; // Called
176 struct rule *n_rule; // Rules to build this (prerequisites/commands)
177 struct timespec n_tim; // Modification time of this name
178 uint16_t n_flag; // Info about the name
179};
180
181#define N_DOING 0x01 // Name in process of being built
182#define N_DONE 0x02 // Name looked at
183#define N_TARGET 0x04 // Name is a target
184#define N_PRECIOUS 0x08 // Target is precious
185#define N_DOUBLE 0x10 // Double-colon target
186#define N_SILENT 0x20 // Build target silently
187#define N_IGNORE 0x40 // Ignore build errors
188#define N_SPECIAL 0x80 // Special target
189#define N_MARK 0x100 // Mark for deduplication
190#define N_PHONY 0x200 // Name is a phony target
191#define N_INFERENCE 0x400 // Inference rule
192
193// List of rules to build a target
194struct rule {
195 struct rule *r_next; // Next rule
196 struct depend *r_dep; // Prerequisites for this rule
197 struct cmd *r_cmd; // Commands for this rule
198};
199
200// NOTE: the layout of the following two structures must be compatible.
201// Also, their first two members must be compatible with llist_t.
202
203// List of prerequisites for a rule
204struct depend {
205 struct depend *d_next; // Next prerequisite
206 struct name *d_name; // Name of prerequisite
207 int d_refcnt; // Reference count
208};
209
210// List of commands for a rule
211struct cmd {
212 struct cmd *c_next; // Next command line
213 char *c_cmd; // Text of command line
214 int c_refcnt; // Reference count
215 const char *c_makefile; // Makefile in which command was defined
216 int c_dispno; // Line number within makefile
217};
218
219// Macro storage
220struct macro {
221 struct macro *m_next; // Next variable
222 char *m_name; // Its name
223 char *m_val; // Its value
224 bool m_immediate; // Immediate-expansion macro set using ::=
225 bool m_flag; // Infinite loop check
226 uint8_t m_level; // Level at which macro was created
227};
228
229// Flags passed to setmacro()
230#define M_IMMEDIATE 0x08 // immediate-expansion macro is being defined
231#define M_VALID 0x10 // assert macro name is valid
232#define M_ENVIRON 0x20 // macro imported from environment
233
234// Constants for PRAGMA. Order must match strings in set_pragma().
235enum {
236 BIT_MACRO_NAME = 0,
237 BIT_TARGET_NAME,
238 BIT_COMMAND_COMMENT,
239 BIT_EMPTY_SUFFIX,
240#if ENABLE_PLATFORM_MINGW32
241 BIT_WINDOWS,
242#endif
243 BIT_POSIX_2017,
244 BIT_POSIX_2024,
245 BIT_POSIX_202X,
246
247 P_MACRO_NAME = (1 << BIT_MACRO_NAME),
248 P_TARGET_NAME = (1 << BIT_TARGET_NAME),
249 P_COMMAND_COMMENT = (1 << BIT_COMMAND_COMMENT),
250 P_EMPTY_SUFFIX = (1 << BIT_EMPTY_SUFFIX),
251#if ENABLE_PLATFORM_MINGW32
252 P_WINDOWS = (1 << BIT_WINDOWS),
253#endif
254};
255
256// Status of make()
257#define MAKE_FAILURE 0x01
258#define MAKE_DIDSOMETHING 0x02
259
260// Return TRUE if c is allowed in a POSIX 2017 macro or target name
261#define ispname(c) (isalpha(c) || isdigit(c) || c == '.' || c == '_')
262// Return TRUE if c is in the POSIX 'portable filename character set'
263#define isfname(c) (ispname(c) || c == '-')
264
265#define HTABSIZE 39
266
267struct globals {
268 uint32_t opts;
269 const char *makefile;
270 llist_t *makefiles;
271 llist_t *dirs;
272 struct name *namehead[HTABSIZE];
273 struct macro *macrohead[HTABSIZE];
274 struct name *firstname;
275 struct name *target;
276 time_t ar_mtime;
277 int lineno; // Physical line number in file
278 int dispno; // Line number for display purposes
279 const char *rulepos;
280 int rule_idx;
281#define IF_MAX 10
282 uint8_t clevel;
283 uint8_t cstate[IF_MAX + 1];
284 int numjobs;
285#if ENABLE_FEATURE_MAKE_POSIX
286 bool posix;
287 bool seen_first;
288 llist_t *pragmas;
289 unsigned char pragma;
290 unsigned char posix_level;
291#endif
292} FIX_ALIASING;
293
294#define G (*(struct globals*)bb_common_bufsiz1)
295#define INIT_G() do { \
296 setup_common_bufsiz(); \
297} while (0)
298
299#define opts (G.opts)
300#define makefile (G.makefile)
301#define makefiles (G.makefiles)
302#define dirs (G.dirs)
303#define namehead (G.namehead)
304#define macrohead (G.macrohead)
305#define firstname (G.firstname)
306#define target (G.target)
307#define ar_mtime (G.ar_mtime)
308#define lineno (G.lineno)
309#define dispno (G.dispno)
310#define rulepos (G.rulepos)
311#define rule_idx (G.rule_idx)
312#define clevel (G.clevel)
313#define cstate (G.cstate)
314#define numjobs (G.numjobs)
315#if ENABLE_FEATURE_MAKE_POSIX
316#define posix (G.posix)
317#define seen_first (G.seen_first)
318#define pragmas (G.pragmas)
319#define pragma (G.pragma)
320#define posix_level (G.posix_level)
321#else
322#define posix 0
323#define pragma 0
324#define posix_level DEFAULT_POSIX_LEVEL
325#endif
326
327static int make(struct name *np, int level);
328static struct name *dyndep(struct name *np, struct rule *infrule,
329 const char **ptsuff);
330
331/*
332 * Utility functions.
333 */
334
335/*
336 * Print message, with makefile and line number if possible.
337 */
338static void
339vwarning(FILE *stream, const char *msg, va_list list)
340{
341 fprintf(stream, "%s: ", applet_name);
342 if (makefile)
343 fprintf(stream, "(%s:%d): ", makefile, dispno);
344 vfprintf(stream, msg, list);
345 fputc('\n', stream);
346}
347
348/*
349 * Diagnostic handler. Print message to standard error.
350 */
351static void
352diagnostic(const char *msg, ...)
353{
354 va_list list;
355
356 va_start(list, msg);
357 vwarning(stderr, msg, list);
358 va_end(list);
359}
360
361/*
362 * Error handler. Print message and exit.
363 */
364static void error(const char *msg, ...) NORETURN;
365static void
366error(const char *msg, ...)
367{
368 va_list list;
369
370 va_start(list, msg);
371 vwarning(stderr, msg, list);
372 va_end(list);
373 exit(2);
374}
375
376static void error_unexpected(const char *s) NORETURN;
377static void
378error_unexpected(const char *s)
379{
380 error("unexpected %s", s);
381}
382
383static void error_in_inference_rule(const char *s) NORETURN;
384static void
385error_in_inference_rule(const char *s)
386{
387 error("%s in inference rule", s);
388}
389
390static void
391error_not_allowed(const char *s, const char *t)
392{
393 error("%s not allowed for %s", s, t);
394}
395
396static void
397warning(const char *msg, ...)
398{
399 va_list list;
400
401 va_start(list, msg);
402 vwarning(stdout, msg, list);
403 va_end(list);
404}
405
406static char *
407auto_concat(const char *s1, const char *s2)
408{
409 return auto_string(xasprintf("%s%s", s1, s2));
410}
411
412#if !ENABLE_PLATFORM_MINGW32
413/*
414 * Append a word to a space-separated string of words. The first
415 * call should use a NULL pointer for str, subsequent calls should
416 * pass an allocated string which will be freed.
417 */
418static char *
419xappendword(const char *str, const char *word)
420{
421 char *newstr = str ? xasprintf("%s %s", str, word) : xstrdup(word);
422 free((void *)str);
423 return newstr;
424}
425#endif
426
427static unsigned int
428getbucket(const char *name)
429{
430 unsigned int hashval = 0;
431 const unsigned char *p = (unsigned char *)name;
432
433 while (*p)
434 hashval ^= (hashval << 5) + (hashval >> 2) + *p++;
435 return hashval % HTABSIZE;
436}
437
438/*
439 * Add a prerequisite to the end of the supplied list.
440 */
441static void
442newdep(struct depend **dphead, struct name *np)
443{
444 while (*dphead)
445 dphead = &(*dphead)->d_next;
446 *dphead = xzalloc(sizeof(struct depend));
447 /*(*dphead)->d_next = NULL; - xzalloc did it */
448 (*dphead)->d_name = np;
449 /*(*dphead)->d_refcnt = 0; */
450}
451
452static void
453freedeps(struct depend *dp)
454{
455 if (dp && --dp->d_refcnt <= 0)
456 llist_free((llist_t *)dp, NULL);
457}
458
459/*
460 * Add a command to the end of the supplied list of commands.
461 */
462static void
463newcmd(struct cmd **cphead, char *str)
464{
465 while (isspace(*str))
466 str++;
467
468 while (*cphead)
469 cphead = &(*cphead)->c_next;
470 *cphead = xzalloc(sizeof(struct cmd));
471 /*(*cphead)->c_next = NULL; - xzalloc did it */
472 (*cphead)->c_cmd = xstrdup(str);
473 /*(*cphead)->c_refcnt = 0; */
474 (*cphead)->c_makefile = xstrdup(makefile);
475 (*cphead)->c_dispno = dispno;
476}
477
478static void
479freecmds(struct cmd *cp)
480{
481 struct cmd *nextcp;
482
483 if (cp && --cp->c_refcnt <= 0) {
484 for (; cp; cp = nextcp) {
485 nextcp = cp->c_next;
486 free(cp->c_cmd);
487 free((void *)cp->c_makefile);
488 free(cp);
489 }
490 }
491}
492
493static struct name *
494findname(const char *name)
495{
496 struct name *np = namehead[getbucket(name)];
497 return (struct name *)llist_find_str((llist_t *)np, name);
498}
499
500static int
501check_name(const char *name)
502{
503 const char *s;
504
505#if ENABLE_PLATFORM_MINGW32
506 if (!posix || (pragma & P_WINDOWS)) {
507 if (isalpha(name[0]) && name[1] == ':' && name[2] == '/') {
508 name += 3;
509 }
510 }
511#endif
512 if (!posix) {
513 for (s = name; *s; ++s) {
514 if (*s == '=')
515 return FALSE;
516 }
517 return TRUE;
518 }
519
520 for (s = name; *s; ++s) {
521 if ((pragma & P_TARGET_NAME) || !POSIX_2017 ?
522 !(isfname(*s) || *s == '/') : !ispname(*s))
523 return FALSE;
524 }
525 return TRUE;
526}
527
528static char *splitlib(const char *name, char **member);
529
530static int
531is_valid_target(const char *name)
532{
533 char *archive, *member = NULL;
534 int ret;
535
536 /* Names of the form 'lib(member)' are referred to as 'expressions'
537 * in POSIX and are subjected to special treatment. The 'lib'
538 * and 'member' elements must each be a valid target name. */
539 archive = splitlib(name, &member);
540 ret = check_name(archive) && (member == NULL || check_name(member));
541 free(archive);
542
543 return ret;
544}
545
546#if ENABLE_FEATURE_MAKE_POSIX
547static int
548potentially_valid_target(const char *name)
549{
550 int ret = FALSE;
551
552 if (!(pragma & P_TARGET_NAME)) {
553 pragma |= P_TARGET_NAME;
554 ret = is_valid_target(name);
555 pragma &= ~P_TARGET_NAME;
556 }
557 return ret;
558}
559#endif
560
561/*
562 * Intern a name. Return a pointer to the name struct
563 */
564static struct name *
565newname(const char *name)
566{
567 struct name *np = findname(name);
568
569 if (np == NULL) {
570 unsigned int bucket;
571
572 if (!is_valid_target(name))
573#if ENABLE_FEATURE_MAKE_POSIX
574 error("invalid target name '%s'%s", name,
575 potentially_valid_target(name) ?
576 ": allow with pragma target_name" : "");
577#else
578 error("invalid target name '%s'", name);
579#endif
580
581 bucket = getbucket(name);
582 np = xzalloc(sizeof(struct name));
583 np->n_next = namehead[bucket];
584 namehead[bucket] = np;
585 np->n_name = xstrdup(name);
586 /*np->n_rule = NULL; - xzalloc did it */
587 /*np->n_tim = (struct timespec){0, 0}; */
588 /*np->n_flag = 0; */
589 }
590 return np;
591}
592
593/*
594 * Return the commands on the first rule that has them or NULL.
595 */
596static struct cmd *
597getcmd(struct name *np)
598{
599 struct rule *rp;
600
601 if (np == NULL)
602 return NULL;
603
604 for (rp = np->n_rule; rp; rp = rp->r_next)
605 if (rp->r_cmd)
606 return rp->r_cmd;
607 return NULL;
608}
609
610#if ENABLE_FEATURE_CLEAN_UP
611static void
612freenames(void)
613{
614 int i;
615 struct name *np, *nextnp;
616
617 for (i = 0; i < HTABSIZE; i++) {
618 for (np = namehead[i]; np; np = nextnp) {
619 nextnp = np->n_next;
620 free(np->n_name);
621 freerules(np->n_rule);
622 free(np);
623 }
624 }
625}
626#endif
627
628static void
629freerules(struct rule *rp)
630{
631 struct rule *nextrp;
632
633 for (; rp; rp = nextrp) {
634 nextrp = rp->r_next;
635 freedeps(rp->r_dep);
636 freecmds(rp->r_cmd);
637 free(rp);
638 }
639}
640
641static void *
642inc_ref(void *vp)
643{
644 if (vp) {
645 struct depend *dp = vp;
646 if (dp->d_refcnt == INT_MAX)
647 bb_die_memory_exhausted();
648 dp->d_refcnt++;
649 }
650 return vp;
651}
652
653#if ENABLE_FEATURE_MAKE_POSIX
654// Order must match constants above.
655// POSIX levels must be last and in increasing order
656static const char *p_name =
657 "macro_name\0"
658 "target_name\0"
659 "command_comment\0"
660 "empty_suffix\0"
661#if ENABLE_PLATFORM_MINGW32
662 "windows\0"
663#endif
664 "posix_2017\0"
665 "posix_2024\0"
666 "posix_202x\0";
667
668static void
669set_pragma(const char *name)
670{
671 int idx = index_in_strings(p_name, name);
672
673 if (idx != -1) {
674 if (idx >= BIT_POSIX_2017) {
675 // POSIX level is stored in a separate variable.
676 // No bits in 'pragma' are used.
677 if (posix_level == DEFAULT_POSIX_LEVEL) {
678 posix_level = idx - BIT_POSIX_2017;
679 if (posix_level > STD_POSIX_2024)
680 posix_level = STD_POSIX_2024;
681 } else if (posix_level != idx - BIT_POSIX_2017)
682 warning("unable to change POSIX level");
683 } else {
684 pragma |= 1 << idx;
685 }
686 return;
687 }
688 warning("invalid pragma '%s'", name);
689}
690
691static void
692pragmas_to_env(void)
693{
694 int i;
695 char *val = NULL;
696
697 for (i = 0; i < BIT_POSIX_2017; ++i) {
698 if ((pragma & (1 << i)))
699 val = xappendword(val, nth_string(p_name, i));
700 }
701
702 if (posix_level != DEFAULT_POSIX_LEVEL)
703 val = xappendword(val,
704 nth_string(p_name, BIT_POSIX_2017 + posix_level));
705
706 if (val) {
707 setenv("PDPMAKE_PRAGMAS", val, 1);
708 free(val);
709 }
710}
711#endif
712
713/*
714 * Add a new rule to a target. This checks to see if commands already
715 * exist for the target. If flag is TRUE the target can have multiple
716 * rules with commands (double-colon rules).
717 *
718 * i) If the name is a special target and there are no prerequisites
719 * or commands to be added remove all prerequisites and commands.
720 * This is necessary when clearing a built-in inference rule.
721 * ii) If name is a special target and has commands, replace them.
722 * This is for redefining commands for an inference rule.
723 */
724static void
725addrule(struct name *np, struct depend *dp, struct cmd *cp, int flag)
726{
727 struct rule *rp;
728 struct rule **rpp;
729
730 // Can't mix single-colon and double-colon rules
731 if (!posix && (np->n_flag & N_TARGET)) {
732 if (!(np->n_flag & N_DOUBLE) != !flag) // like xor
733 error("inconsistent rules for target %s", np->n_name);
734 }
735
736 // Clear out prerequisites and commands
737 if ((np->n_flag & N_SPECIAL) && !dp && !cp) {
738 if (strcmp(np->n_name, ".PHONY") == 0)
739 return;
740 freerules(np->n_rule);
741 np->n_rule = NULL;
742 return;
743 }
744
745 if (cp && !(np->n_flag & N_DOUBLE) && getcmd(np)) {
746 // Handle the inference rule redefinition case
747 // .DEFAULT rule can also be redefined (as an extension).
748 if ((np->n_flag & N_INFERENCE)
749 && !(posix && (np->n_flag & N_SPECIAL))
750 ) {
751 freerules(np->n_rule);
752 np->n_rule = NULL;
753 } else {
754 error("commands defined twice for target %s", np->n_name);
755 }
756 }
757
758 rpp = &np->n_rule;
759 while (*rpp)
760 rpp = &(*rpp)->r_next;
761
762 *rpp = rp = xzalloc(sizeof(struct rule));
763 /*rp->r_next = NULL; - xzalloc did it */
764 rp->r_dep = inc_ref(dp);
765 rp->r_cmd = inc_ref(cp);
766
767 np->n_flag |= N_TARGET;
768 if (flag)
769 np->n_flag |= N_DOUBLE;
770#if ENABLE_FEATURE_MAKE_POSIX
771 if (strcmp(np->n_name, ".PRAGMA") == 0) {
772 for (; dp; dp = dp->d_next) {
773 set_pragma(dp->d_name->n_name);
774 }
775 pragmas_to_env();
776 }
777#endif
778}
779
780/*
781 * Macro control for make
782 */
783static struct macro *
784getmp(const char *name)
785{
786 struct macro *mp = macrohead[getbucket(name)];
787 return (struct macro *)llist_find_str((llist_t *)mp, name);
788}
789
790static int
791is_valid_macro(const char *name)
792{
793 const char *s;
794 for (s = name; *s; ++s) {
795 // In POSIX mode only a limited set of characters are guaranteed
796 // to be allowed in macro names.
797 if (posix) {
798 // Find the appropriate character set
799 if ((pragma & P_MACRO_NAME) || !POSIX_2017 ?
800 !isfname(*s) : !ispname(*s))
801 return FALSE;
802 }
803 // As an extension allow anything that can get through the
804 // input parser, apart from the following.
805 if (*s == '=' || isblank(*s) || iscntrl(*s))
806 return FALSE;
807 }
808 return TRUE;
809}
810
811#if ENABLE_FEATURE_MAKE_POSIX
812static int
813potentially_valid_macro(const char *name)
814{
815 int ret = FALSE;
816
817 if (!(pragma & P_MACRO_NAME)) {
818 pragma |= P_MACRO_NAME;
819 ret = is_valid_macro(name);
820 pragma &= ~P_MACRO_NAME;
821 }
822 return ret;
823}
824#endif
825
826static void
827setmacro(const char *name, const char *val, int level)
828{
829 struct macro *mp;
830 bool valid = level & M_VALID;
831 bool from_env = level & M_ENVIRON;
832 bool immediate = level & M_IMMEDIATE;
833
834 level &= ~(M_IMMEDIATE | M_VALID | M_ENVIRON);
835 mp = getmp(name);
836 if (mp) {
837 // Don't replace existing macro from a lower level
838 if (level > mp->m_level)
839 return;
840
841 // Replace existing macro
842 free(mp->m_val);
843 } else {
844 // If not defined, allocate space for new
845 unsigned int bucket;
846
847 if (!valid && !is_valid_macro(name)) {
848 // Silently drop invalid names from the environment
849 if (from_env)
850 return;
851#if ENABLE_FEATURE_MAKE_POSIX
852 error("invalid macro name '%s'%s", name,
853 potentially_valid_macro(name) ?
854 ": allow with pragma macro_name" : "");
855#else
856 error("invalid macro name '%s'", name);
857#endif
858 }
859
860 bucket = getbucket(name);
861 mp = xzalloc(sizeof(struct macro));
862 mp->m_next = macrohead[bucket];
863 macrohead[bucket] = mp;
864 /* mp->m_flag = FALSE; - xzalloc did it */
865 mp->m_name = xstrdup(name);
866 }
867 mp->m_immediate = immediate;
868 mp->m_level = level;
869 mp->m_val = xstrdup(val ? val : "");
870}
871
872#if ENABLE_FEATURE_CLEAN_UP
873static void
874freemacros(void)
875{
876 int i;
877 struct macro *mp, *nextmp;
878
879 for (i = 0; i < HTABSIZE; i++) {
880 for (mp = macrohead[i]; mp; mp = nextmp) {
881 nextmp = mp->m_next;
882 free(mp->m_name);
883 free(mp->m_val);
884 free(mp);
885 }
886 }
887}
888#endif
889
890/*
891 * Get modification time of file or archive member
892 */
893static void FAST_FUNC
894record_mtime(const file_header_t *file_header)
895{
896 ar_mtime = file_header->mtime;
897}
898
899static time_t
900artime(const char *archive, const char *member)
901{
902 archive_handle_t *archive_handle;
903
904 ar_mtime = 0;
905 archive_handle = init_handle();
906 archive_handle->src_fd = open(archive, O_RDONLY);
907 if (archive_handle->src_fd != -1) {
908 archive_handle->action_header = record_mtime;
909 archive_handle->filter = filter_accept_list;
910 llist_add_to_end(&archive_handle->accept, (void *)member);
911 unpack_ar_archive(archive_handle);
912 close(archive_handle->src_fd);
913 }
914
915#if ENABLE_FEATURE_AR_LONG_FILENAMES
916 free(archive_handle->ar__long_names);
917#endif
918 llist_free(archive_handle->accept, NULL);
919 free(archive_handle->file_header);
920 free(archive_handle);
921
922 return ar_mtime;
923}
924
925/*
926 * If the name is of the form 'libname(member.o)' split it into its
927 * name and member parts and set the member pointer to point to the
928 * latter. Otherwise just take a copy of the name and don't alter
929 * the member pointer.
930 *
931 * In either case the return value is an allocated string which must
932 * be freed by the caller.
933 */
934static char *
935splitlib(const char *name, char **member)
936{
937 char *s, *t;
938 size_t len;
939
940 t = xstrdup(name);
941 s = strchr(t, '(');
942 if (s) {
943 // We have 'libname(member.o)'
944 *s++ = '\0';
945 len = strlen(s);
946 if (len <= 1 || s[len - 1] != ')' || *t == '\0')
947 error("invalid name '%s'", name);
948 s[len - 1] = '\0';
949 *member = s;
950 }
951 return t;
952}
953
954/*
955 * Get the modification time of a file. Set it to 0 if the file
956 * doesn't exist.
957 */
958static void
959modtime(struct name *np)
960{
961 char *name, *member = NULL;
962 struct stat info;
963
964 name = splitlib(np->n_name, &member);
965 if (member) {
966 // Looks like library(member)
967 np->n_tim.tv_sec = artime(name, member);
968 np->n_tim.tv_nsec = 0;
969 } else if (stat(name, &info) < 0) {
970 if (errno != ENOENT)
971 bb_perror_msg("can't open %s", name);
972 np->n_tim.tv_sec = 0;
973 np->n_tim.tv_nsec = 0;
974 } else {
975 np->n_tim.tv_sec = info.st_mtim.tv_sec;
976 np->n_tim.tv_nsec = info.st_mtim.tv_nsec;
977 }
978 free(name);
979}
980
981/*
982 * Control of the implicit suffix rules
983 */
984
985/*
986 * Return a pointer to the suffix of a name (which may be the
987 * terminating NUL if there's no suffix).
988 */
989static char *
990suffix(const char *name)
991{
992 char *p = strrchr(name, '.');
993 return p ? p : (char *)name + strlen(name);
994}
995
996/*
997 * Search for an inference rule to convert some suffix ('psuff')
998 * to the target suffix 'tsuff'. The basename of the prerequisite
999 * is 'base'.
1000 */
1001static struct name *
1002dyndep0(char *base, const char *tsuff, struct rule *infrule)
1003{
1004 char *psuff;
1005 struct name *xp; // Suffixes
1006 struct name *sp; // Suffix rule
1007 struct rule *rp;
1008 struct depend *dp;
1009 bool chain = FALSE;
1010
1011 xp = newname(".SUFFIXES");
1012 retry:
1013 for (rp = xp->n_rule; rp; rp = rp->r_next) {
1014 for (dp = rp->r_dep; dp; dp = dp->d_next) {
1015 // Generate new suffix rule to try
1016 psuff = dp->d_name->n_name;
1017 sp = findname(auto_concat(psuff, tsuff));
1018 if (sp && sp->n_rule) {
1019 struct name *ip;
1020 int got_ip;
1021
1022 // Has rule already been used in this chain?
1023 if ((sp->n_flag & N_MARK))
1024 continue;
1025 // Generate a name for an implicit prerequisite
1026 ip = newname(auto_concat(base, psuff));
1027 if ((ip->n_flag & N_DOING))
1028 continue;
1029
1030 if (!ip->n_tim.tv_sec)
1031 modtime(ip);
1032
1033 if (!chain) {
1034 got_ip = ip->n_tim.tv_sec || (ip->n_flag & N_TARGET);
1035 } else {
1036 sp->n_flag |= N_MARK;
1037 got_ip = dyndep(ip, NULL, NULL) != NULL;
1038 sp->n_flag &= ~N_MARK;
1039 }
1040
1041 if (got_ip) {
1042 // Prerequisite exists or we know how to make it
1043 if (infrule) {
1044 dp = NULL;
1045 newdep(&dp, ip);
1046 infrule->r_dep = dp;
1047 infrule->r_cmd = sp->n_rule->r_cmd;
1048 }
1049 return ip;
1050 }
1051 }
1052 }
1053 }
1054 // If we didn't find an existing file or an explicit rule try
1055 // again, this time looking for a chained inference rule.
1056 if (!posix && !chain) {
1057 chain = TRUE;
1058 goto retry;
1059 }
1060 return NULL;
1061}
1062
1063/*
1064 * If 'name' ends with 'suffix' return an allocated string containing
1065 * the name with the suffix removed, else return NULL.
1066 */
1067static char *
1068has_suffix(const char *name, const char *suffix)
1069{
1070 ssize_t delta = strlen(name) - strlen(suffix);
1071 char *base = NULL;
1072
1073 if (delta > 0 && strcmp(name + delta, suffix) == 0) {
1074 base = xstrdup(name);
1075 base[delta] = '\0';
1076 }
1077
1078 return base;
1079}
1080
1081/*
1082 * Dynamic dependency. This routine applies the suffix rules
1083 * to try and find a source and a set of rules for a missing
1084 * target. NULL is returned on failure. On success the name of
1085 * the implicit prerequisite is returned and the rule used is
1086 * placed in the infrule structure provided by the caller.
1087 */
1088static struct name *
1089dyndep(struct name *np, struct rule *infrule, const char **ptsuff)
1090{
1091 const char *tsuff;
1092 char *base, *name, *member;
1093 struct name *pp = NULL; // Implicit prerequisite
1094
1095 member = NULL;
1096 name = splitlib(np->n_name, &member);
1097
1098 // POSIX only allows inference rules with one or two periods.
1099 // As an extension this restriction is lifted, but not for
1100 // targets of the form lib.a(member.o).
1101 if (!posix && member == NULL) {
1102 struct name *xp = newname(".SUFFIXES");
1103 int found_suffix = FALSE;
1104
1105 for (struct rule *rp = xp->n_rule; rp; rp = rp->r_next) {
1106 for (struct depend *dp = rp->r_dep; dp; dp = dp->d_next) {
1107 tsuff = dp->d_name->n_name;
1108 base = has_suffix(name, tsuff);
1109 if (base) {
1110 found_suffix = TRUE;
1111 pp = dyndep0(base, tsuff, infrule);
1112 free(base);
1113 if (pp) {
1114 goto done;
1115 }
1116 }
1117 }
1118 }
1119
1120 if (!found_suffix) {
1121 // The name didn't have a known suffix. Try single-suffix rule.
1122 tsuff = "";
1123 pp = dyndep0(name, tsuff, infrule);
1124 if (pp) {
1125 done:
1126 if (ptsuff) {
1127 *ptsuff = tsuff;
1128 }
1129 }
1130 }
1131 } else {
1132 tsuff = xstrdup(suffix(name));
1133 base = member ? member : name;
1134 *suffix(base) = '\0';
1135
1136 pp = dyndep0(base, tsuff, infrule);
1137 free((void *)tsuff);
1138 }
1139 free(name);
1140
1141 return pp;
1142}
1143
1144#define RULES \
1145 ".c.o:\n" \
1146 " $(CC) $(CFLAGS) -c $<\n" \
1147 ".y.o:\n" \
1148 " $(YACC) $(YFLAGS) $<\n" \
1149 " $(CC) $(CFLAGS) -c y.tab.c\n" \
1150 " rm -f y.tab.c\n" \
1151 " mv y.tab.o $@\n" \
1152 ".y.c:\n" \
1153 " $(YACC) $(YFLAGS) $<\n" \
1154 " mv y.tab.c $@\n" \
1155 ".l.o:\n" \
1156 " $(LEX) $(LFLAGS) $<\n" \
1157 " $(CC) $(CFLAGS) -c lex.yy.c\n" \
1158 " rm -f lex.yy.c\n" \
1159 " mv lex.yy.o $@\n" \
1160 ".l.c:\n" \
1161 " $(LEX) $(LFLAGS) $<\n" \
1162 " mv lex.yy.c $@\n" \
1163 ".c.a:\n" \
1164 " $(CC) -c $(CFLAGS) $<\n" \
1165 " $(AR) $(ARFLAGS) $@ $*.o\n" \
1166 " rm -f $*.o\n" \
1167 ".c:\n" \
1168 " $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $<\n" \
1169 ".sh:\n" \
1170 " cp $< $@\n" \
1171 " chmod a+x $@\n"
1172
1173#define RULES_2017 \
1174 ".SUFFIXES:.o .c .y .l .a .sh .f\n" \
1175 ".f.o:\n" \
1176 " $(FC) $(FFLAGS) -c $<\n" \
1177 ".f.a:\n" \
1178 " $(FC) -c $(FFLAGS) $<\n" \
1179 " $(AR) $(ARFLAGS) $@ $*.o\n" \
1180 " rm -f $*.o\n" \
1181 ".f:\n" \
1182 " $(FC) $(FFLAGS) $(LDFLAGS) -o $@ $<\n"
1183
1184#define RULES_2024 \
1185 ".SUFFIXES:.o .c .y .l .a .sh\n"
1186
1187#define MACROS \
1188 "CFLAGS=-O1\n" \
1189 "YACC=yacc\n" \
1190 "YFLAGS=\n" \
1191 "LEX=lex\n" \
1192 "LFLAGS=\n" \
1193 "AR=ar\n" \
1194 "ARFLAGS=-rv\n" \
1195 "LDFLAGS=\n"
1196
1197#define MACROS_2017 \
1198 "CC=c99\n" \
1199 "FC=fort77\n" \
1200 "FFLAGS=-O1\n" \
1201
1202#define MACROS_2024 \
1203 "CC=c17\n"
1204
1205#define MACROS_EXT \
1206 "CC=cc\n"
1207
1208/*
1209 * Read the built-in rules using a fake fgets-like interface.
1210 */
1211static char *
1212getrules(char *s, int size)
1213{
1214 char *r = s;
1215
1216 if (rulepos == NULL || *rulepos == '\0') {
1217 if (rule_idx == 0) {
1218 rulepos = MACROS;
1219 rule_idx++;
1220 } else if (rule_idx == 1) {
1221 if (POSIX_2017)
1222 rulepos = MACROS_2017;
1223 else if (posix)
1224 rulepos = MACROS_2024;
1225 else
1226 rulepos = MACROS_EXT;
1227 rule_idx++;
1228 } else if (!norules) {
1229 if (rule_idx == 2) {
1230 rulepos = POSIX_2017 ? RULES_2017 : RULES_2024;
1231 rule_idx++;
1232 } else if (rule_idx == 3) {
1233 rulepos = RULES;
1234 rule_idx++;
1235 }
1236 }
1237 }
1238
1239 if (*rulepos == '\0')
1240 return NULL;
1241
1242 while (--size) {
1243 if ((*r++ = *rulepos++) == '\n')
1244 break;
1245 }
1246 *r = '\0';
1247 return s;
1248}
1249
1250/*
1251 * Parse a makefile
1252 */
1253
1254/*
1255 * Return a pointer to the next blank-delimited word or NULL if
1256 * there are none left.
1257 */
1258static char *
1259gettok(char **ptr)
1260{
1261 char *p;
1262
1263 while (isblank(**ptr)) // Skip blanks
1264 (*ptr)++;
1265
1266 if (**ptr == '\0') // Nothing after blanks
1267 return NULL;
1268
1269 p = *ptr; // Word starts here
1270
1271 while (**ptr != '\0' && !isblank(**ptr))
1272 (*ptr)++; // Find end of word
1273
1274 // Terminate token and move on unless already at end of string
1275 if (**ptr != '\0')
1276 *(*ptr)++ = '\0';
1277
1278 return(p);
1279}
1280
1281/*
1282 * Skip over (possibly adjacent or nested) macro expansions.
1283 */
1284static char *
1285skip_macro(const char *s)
1286{
1287 while (*s && s[0] == '$') {
1288 if (s[1] == '(' || s[1] == '{') {
1289 char end = *++s == '(' ? ')' : '}';
1290 while (*s && *s != end)
1291 s = skip_macro(s + 1);
1292 if (*s == end)
1293 ++s;
1294 } else if (s[1] != '\0') {
1295 s += 2;
1296 } else {
1297 break;
1298 }
1299 }
1300 return (char *)s;
1301}
1302
1303/*
1304 * Process each whitespace-separated word in the input string:
1305 *
1306 * - replace paths with their directory or filename part
1307 * - replace prefixes and suffixes
1308 *
1309 * Returns an allocated string or NULL if the input is unmodified.
1310 */
1311static char *
1312modify_words(const char *val, int modifier, size_t lenf, size_t lenr,
1313 const char *find_pref, const char *repl_pref,
1314 const char *find_suff, const char *repl_suff)
1315{
1316 char *s, *copy, *word, *sep, *buf = NULL;
1317 size_t find_pref_len = 0, find_suff_len = 0;
1318
1319 if (!modifier && lenf == 0 && lenr == 0)
1320 return buf;
1321
1322 if (find_pref) {
1323 // get length of find prefix, e.g: src/
1324 find_pref_len = strlen(find_pref);
1325 // get length of find suffix, e.g: .c
1326 find_suff_len = lenf - find_pref_len - 1;
1327 }
1328
1329 s = copy = xstrdup(val);
1330 while ((word = gettok(&s)) != NULL) {
1331 if (modifier) {
1332 sep = strrchr(word, '/');
1333 if (modifier == 'D') {
1334 if (!sep) {
1335 word[0] = '.'; // no '/', return "."
1336 sep = word + 1;
1337 } else if (sep == word) {
1338 // '/' at start of word, return "/"
1339 sep = word + 1;
1340 }
1341 // else terminate at separator
1342 *sep = '\0';
1343 } else if (/* modifier == 'F' && */ sep) {
1344 word = sep + 1;
1345 }
1346 }
1347 if (find_pref != NULL || lenf != 0 || lenr != 0) {
1348 size_t lenw = strlen(word);
1349 // This code implements pattern macro expansions:
1350 // https://austingroupbugs.net/view.php?id=519
1351 //
1352 // find: <prefix>%<suffix>
1353 // example: src/%.c
1354 //
1355 // For a pattern of the form:
1356 // $(string1:[op]%[os]=[np][%][ns])
1357 // lenf is the length of [op]%[os]. So lenf >= 1.
1358 if (find_pref != NULL && lenw + 1 >= lenf) {
1359 // If prefix and suffix of word match find_pref and
1360 // find_suff, then do substitution.
1361 if (strncmp(word, find_pref, find_pref_len) == 0 &&
1362 strcmp(word + lenw - find_suff_len, find_suff) == 0) {
1363 // replace: <prefix>[%<suffix>]
1364 // example: build/%.o or build/all.o (notice no %)
1365 // If repl_suff is NULL, replace whole word with repl_pref.
1366 if (!repl_suff) {
1367 word = xstrdup(repl_pref);
1368 } else {
1369 word[lenw - find_suff_len] = '\0';
1370 word = xasprintf("%s%s%s", repl_pref,
1371 word + find_pref_len, repl_suff);
1372 }
1373 word = auto_string(word);
1374 }
1375 } else if (lenw >= lenf &&
1376 strcmp(word + lenw - lenf, find_suff) == 0) {
1377 word[lenw - lenf] = '\0';
1378 word = auto_concat(word, repl_suff);
1379 }
1380 }
1381 buf = xappendword(buf, word);
1382 }
1383 free(copy);
1384 return buf;
1385}
1386
1387/*
1388 * Return a pointer to the next instance of a given character. Macro
1389 * expansions are skipped so the ':' and '=' in $(VAR:.s1=.s2) aren't
1390 * detected as separators in macro definitions. Some other situations
1391 * also require skipping the internals of a macro expansion.
1392 */
1393static char *
1394find_char(const char *str, int c)
1395{
1396 const char *s;
1397
1398 for (s = skip_macro(str); *s; s = skip_macro(s + 1)) {
1399 if (*s == c)
1400 return (char *)s;
1401 }
1402 return NULL;
1403}
1404
1405#if ENABLE_PLATFORM_MINGW32
1406/*
1407 * Check for a target rule by searching for a colon that isn't
1408 * part of a Windows path. Return a pointer to the colon or NULL.
1409 */
1410static char *
1411find_colon(char *p)
1412{
1413 char *q;
1414
1415 for (q = p; (q = strchr(q, ':')); ++q) {
1416 if (posix && !(pragma & P_WINDOWS))
1417 break;
1418 if (q == p || !isalpha(q[-1]) || q[1] != '/')
1419 break;
1420 }
1421 return q;
1422}
1423#else
1424# define find_colon(s) strchr(s, ':')
1425#endif
1426
1427/*
1428 * Recursively expand any macros in str to an allocated string.
1429 */
1430static char *
1431expand_macros(const char *str, int except_dollar)
1432{
1433 char *exp, *newexp, *s, *t, *p, *q, *name;
1434 char *find, *replace, *modified;
1435 char *expval, *expfind, *find_suff, *repl_suff;
1436 char *find_pref = NULL, *repl_pref = NULL;
1437 size_t lenf, lenr;
1438 char modifier;
1439 struct macro *mp;
1440
1441 exp = xstrdup(str);
1442 for (t = exp; *t; t++) {
1443 if (*t == '$') {
1444 if (t[1] == '\0') {
1445 break;
1446 }
1447 if (t[1] == '$' && except_dollar) {
1448 t++;
1449 continue;
1450 }
1451 // Need to expand a macro. Find its extent (s to t inclusive)
1452 // and take a copy of its content.
1453 s = t;
1454 t++;
1455 if (*t == '{' || *t == '(') {
1456 t = find_char(t, *t == '{' ? '}' : ')');
1457 if (t == NULL)
1458 error("unterminated variable '%s'", s);
1459 name = xstrndup(s + 2, t - s - 2);
1460 } else {
1461 name = xzalloc(2);
1462 name[0] = *t;
1463 /*name[1] = '\0'; - xzalloc did it */
1464 }
1465
1466 // Only do suffix replacement or pattern macro expansion
1467 // if both ':' and '=' are found, plus a '%' for the latter.
1468 // Suffix replacement is indicated by
1469 // find_pref == NULL && (lenf != 0 || lenr != 0);
1470 // pattern macro expansion by find_pref != NULL.
1471 expfind = NULL;
1472 find_suff = repl_suff = NULL;
1473 lenf = lenr = 0;
1474 if ((find = find_char(name, ':'))) {
1475 *find++ = '\0';
1476 expfind = expand_macros(find, FALSE);
1477 if ((replace = find_char(expfind, '='))) {
1478 *replace++ = '\0';
1479 lenf = strlen(expfind);
1480 if (!POSIX_2017 && (find_suff = strchr(expfind, '%'))) {
1481 find_pref = expfind;
1482 repl_pref = replace;
1483 *find_suff++ = '\0';
1484 if ((repl_suff = strchr(replace, '%')))
1485 *repl_suff++ = '\0';
1486 } else {
1487 if (posix && !(pragma & P_EMPTY_SUFFIX) && lenf == 0)
1488 error("empty suffix%s",
1489 !ENABLE_FEATURE_MAKE_POSIX ? "" :
1490 ": allow with pragma empty_suffix");
1491 find_suff = expfind;
1492 repl_suff = replace;
1493 lenr = strlen(repl_suff);
1494 }
1495 }
1496 }
1497
1498 p = q = name;
1499 // If not in POSIX mode expand macros in the name.
1500 if (!POSIX_2017) {
1501 char *expname = expand_macros(name, FALSE);
1502 free(name);
1503 name = expname;
1504 } else {
1505 // Skip over nested expansions in name
1506 do {
1507 *q++ = *p;
1508 } while ((p = skip_macro(p + 1)) && *p);
1509 }
1510
1511 // The internal macros support 'D' and 'F' modifiers
1512 modifier = '\0';
1513 switch (name[0]) {
1514 case '^':
1515 case '+':
1516 if (POSIX_2017)
1517 break;
1518 // fall through
1519 case '@': case '%': case '?': case '<': case '*':
1520 if ((name[1] == 'D' || name[1] == 'F') && name[2] == '\0') {
1521 modifier = name[1];
1522 name[1] = '\0';
1523 }
1524 break;
1525 }
1526
1527 modified = NULL;
1528 if ((mp = getmp(name))) {
1529 // Recursive expansion
1530 if (mp->m_flag)
1531 error("recursive macro %s", name);
1532 // Note if we've expanded $(MAKE)
1533 if (strcmp(name, "MAKE") == 0)
1534 opts |= OPT_make;
1535 mp->m_flag = TRUE;
1536 expval = expand_macros(mp->m_val, FALSE);
1537 mp->m_flag = FALSE;
1538 modified = modify_words(expval, modifier, lenf, lenr,
1539 find_pref, repl_pref, find_suff, repl_suff);
1540 if (modified)
1541 free(expval);
1542 else
1543 modified = expval;
1544 }
1545 free(name);
1546 free(expfind);
1547
1548 if (modified && *modified) {
1549 // The text to be replaced by the macro expansion is
1550 // from s to t inclusive.
1551 *s = '\0';
1552 newexp = xasprintf("%s%s%s", exp, modified, t + 1);
1553 t = newexp + (s - exp) + strlen(modified) - 1;
1554 free(exp);
1555 exp = newexp;
1556 } else {
1557 // Macro wasn't expanded or expanded to nothing.
1558 // Close the space occupied by the macro reference.
1559 q = t + 1;
1560 t = s - 1;
1561 while ((*s++ = *q++))
1562 continue;
1563 }
1564 free(modified);
1565 }
1566 }
1567 return exp;
1568}
1569
1570/*
1571 * Process a non-command line
1572 */
1573static void
1574process_line(char *s)
1575{
1576 char *t;
1577
1578 // Strip comment
1579 // don't treat '#' in macro expansion as a comment
1580 // nor '#' outside macro expansion preceded by backslash
1581 if (!posix) {
1582 char *u = s;
1583 while ((t = find_char(u, '#')) && t > u && t[-1] == '\\') {
1584 for (u = t; *u; ++u) {
1585 u[-1] = u[0];
1586 }
1587 *u = '\0';
1588 u = t;
1589 }
1590 } else
1591 t = strchr(s, '#');
1592 if (t)
1593 *t = '\0';
1594
1595 // Replace escaped newline and any leading white space on the
1596 // following line with a single space. Stop processing at a
1597 // non-escaped newline.
1598 for (t = s; *s && *s != '\n'; ) {
1599 if (s[0] == '\\' && s[1] == '\n') {
1600 s += 2;
1601 while (isspace(*s))
1602 ++s;
1603 *t++ = ' ';
1604 } else {
1605 *t++ = *s++;
1606 }
1607 }
1608 *t = '\0';
1609}
1610
1611enum {
1612 INITIAL = 0,
1613 SKIP_LINE = 1 << 0,
1614 EXPECT_ELSE = 1 << 1,
1615 GOT_MATCH = 1 << 2
1616};
1617
1618#define IFDEF 0
1619#define IFNDEF 1
1620#define IFEQ 2
1621#define IFNEQ 3
1622#define ELSE 0
1623#define ENDIF 1
1624
1625/*
1626 * Extract strings following ifeq/ifneq and compare them.
1627 * Return -1 on error.
1628 */
1629static int
1630compare_strings(char *arg1)
1631{
1632 char *arg2, *end, term, *t1, *t2;
1633 int ret;
1634
1635 // Get first string terminator.
1636 if (arg1[0] == '(')
1637 term = ',';
1638 else if (arg1[0] == '"' || arg1[0] == '\'')
1639 term = arg1[0];
1640 else
1641 return -1;
1642
1643 arg2 = find_char(++arg1, term);
1644 if (arg2 == NULL)
1645 return -1;
1646 *arg2++ = '\0';
1647
1648 // Get second string terminator.
1649 if (term == ',') {
1650 term = ')';
1651 } else {
1652 // Skip spaces between quoted strings.
1653 while (isspace(arg2[0]))
1654 arg2++;
1655 if (arg2[0] == '"' || arg2[0] == '\'')
1656 term = arg2[0];
1657 else
1658 return -1;
1659 ++arg2;
1660 }
1661
1662 end = find_char(arg2, term);
1663 if (end == NULL)
1664 return -1;
1665 *end++ = '\0';
1666
1667 if (gettok(&end) != NULL) {
1668 warning("unexpected text");
1669 }
1670
1671 t1 = expand_macros(arg1, FALSE);
1672 t2 = expand_macros(arg2, FALSE);
1673
1674 ret = strcmp(t1, t2) == 0;
1675 free(t1);
1676 free(t2);
1677 return ret;
1678}
1679
1680/*
1681 * Process conditional directives and return TRUE if the current line
1682 * should be skipped.
1683 */
1684static int
1685skip_line(const char *str1)
1686{
1687 char *copy, *q, *token;
1688 bool new_level = TRUE;
1689 // Default is to return skip flag for current level
1690 int ret = cstate[clevel] & SKIP_LINE;
1691 int key;
1692
1693 q = copy = xstrdup(str1);
1694 process_line(copy);
1695 if ((token = gettok(&q)) != NULL) {
1696 switch (index_in_strings("else\0endif\0", token)) {
1697 case ENDIF:
1698 if (gettok(&q) != NULL)
1699 error_unexpected("text");
1700 if (clevel == 0)
1701 error_unexpected(token);
1702 --clevel;
1703 ret = TRUE;
1704 goto end;
1705 case ELSE:
1706 if (!(cstate[clevel] & EXPECT_ELSE))
1707 error_unexpected(token);
1708
1709 // If an earlier condition matched we'll now skip lines.
1710 // If not we don't, though an 'else if' may override this.
1711 if ((cstate[clevel] & GOT_MATCH))
1712 cstate[clevel] |= SKIP_LINE;
1713 else
1714 cstate[clevel] &= ~SKIP_LINE;
1715
1716 token = gettok(&q);
1717 if (token == NULL) {
1718 // Simple else with no conditional directive
1719 cstate[clevel] &= ~EXPECT_ELSE;
1720 ret = TRUE;
1721 goto end;
1722 } else {
1723 // A conditional directive is now required ('else if').
1724 new_level = FALSE;
1725 }
1726 }
1727
1728 key = index_in_strings("ifdef\0ifndef\0ifeq\0ifneq\0", token);
1729 if (key != -1) {
1730 int match;
1731
1732 if (key == IFDEF || key == IFNDEF) {
1733 // ifdef/ifndef: find out if macro is defined.
1734 char *name = gettok(&q);
1735 if (name != NULL && gettok(&q) == NULL) {
1736 char *t = expand_macros(name, FALSE);
1737 struct macro *mp = getmp(t);
1738 match = mp != NULL && mp->m_val[0] != '\0';
1739 free(t);
1740 } else {
1741 match = -1;
1742 }
1743 } else {
1744 // ifeq/ifneq: compare strings.
1745 match = compare_strings(q);
1746 }
1747
1748 if (match >= 0) {
1749 if (new_level) {
1750 // Start a new level.
1751 if (clevel == IF_MAX)
1752 error("nesting too deep");
1753 ++clevel;
1754 cstate[clevel] = EXPECT_ELSE | SKIP_LINE;
1755 // If we were skipping lines at the previous level
1756 // we need to continue doing that unconditionally
1757 // at the new level.
1758 if ((cstate[clevel - 1] & SKIP_LINE))
1759 cstate[clevel] |= GOT_MATCH;
1760 }
1761
1762 if (!(cstate[clevel] & GOT_MATCH)) {
1763 if (key == IFNDEF || key == IFNEQ)
1764 match = !match;
1765 if (match) {
1766 cstate[clevel] &= ~SKIP_LINE;
1767 cstate[clevel] |= GOT_MATCH;
1768 }
1769 }
1770 } else {
1771 error("invalid condition");
1772 }
1773 ret = TRUE;
1774 } else if (!new_level) {
1775 error("missing conditional");
1776 }
1777 }
1778 end:
1779 free(copy);
1780 return ret;
1781}
1782
1783/*
1784 * If fd is NULL read the built-in rules. Otherwise read from the
1785 * specified file descriptor.
1786 */
1787static char *
1788make_fgets(char *s, int size, FILE *fd)
1789{
1790 return fd ? fgets(s, size, fd) : getrules(s, size);
1791}
1792
1793/*
1794 * Read a newline-terminated line into an allocated string.
1795 * Backslash-escaped newlines don't terminate the line.
1796 * Ignore comment lines. Return NULL on EOF.
1797 */
1798static char *
1799readline(FILE *fd, int want_command)
1800{
1801 char *p, *str = NULL;
1802 int pos = 0;
1803 int len = 0;
1804
1805 for (;;) {
1806 // We need room for at least one character and a NUL terminator
1807 if (len - pos > 1 &&
1808 make_fgets(str + pos, len - pos, fd) == NULL) {
1809 if (pos)
1810 return str;
1811 free(str);
1812 return NULL; // EOF
1813 }
1814
1815 if (len - pos < 2 || (p = strchr(str + pos, '\n')) == NULL) {
1816 // Need more room
1817 if (len)
1818 pos = len - 1;
1819 len += 256;
1820 str = xrealloc(str, len);
1821 continue;
1822 }
1823 lineno++;
1824
1825#if ENABLE_PLATFORM_MINGW32
1826 // Remove CR before LF
1827 if (p != str && p[-1] == '\r') {
1828 p[-1] = '\n';
1829 *p-- = '\0';
1830 }
1831#endif
1832 // Keep going if newline has been escaped
1833 if (p != str && p[-1] == '\\') {
1834 pos = p - str + 1;
1835 continue;
1836 }
1837 dispno = lineno;
1838
1839 // Check for lines that are conditionally skipped.
1840 if (posix || !skip_line(str)) {
1841 if (want_command && *str == '\t')
1842 return str;
1843
1844 // Check for comment lines
1845 p = str;
1846 while (isblank(*p))
1847 p++;
1848
1849 if (*p != '\n' && (posix ? *str != '#' : *p != '#'))
1850 return str;
1851 }
1852
1853 pos = 0;
1854 }
1855}
1856
1857/*
1858 * Return a pointer to the suffix name if the argument is a known suffix
1859 * or NULL if it isn't.
1860 */
1861static const char *
1862is_suffix(const char *s)
1863{
1864 struct name *np;
1865 struct rule *rp;
1866 struct depend *dp;
1867
1868 np = newname(".SUFFIXES");
1869 for (rp = np->n_rule; rp; rp = rp->r_next) {
1870 for (dp = rp->r_dep; dp; dp = dp->d_next) {
1871 if (strcmp(s, dp->d_name->n_name) == 0) {
1872 return dp->d_name->n_name;
1873 }
1874 }
1875 }
1876 return NULL;
1877}
1878
1879/*
1880 * Return TRUE if the argument is formed by concatenating two
1881 * known suffixes.
1882 */
1883static int
1884is_inference_target(const char *s)
1885{
1886 struct name *np;
1887 struct rule *rp1, *rp2;
1888 struct depend *dp1, *dp2;
1889
1890 np = newname(".SUFFIXES");
1891 for (rp1 = np->n_rule; rp1; rp1 = rp1->r_next) {
1892 for (dp1 = rp1->r_dep; dp1; dp1 = dp1->d_next) {
1893 const char *suff1 = dp1->d_name->n_name;
1894 size_t len = strlen(suff1);
1895
1896 if (strncmp(s, suff1, len) == 0) {
1897 for (rp2 = np->n_rule; rp2; rp2 = rp2->r_next) {
1898 for (dp2 = rp2->r_dep; dp2; dp2 = dp2->d_next) {
1899 const char *suff2 = dp2->d_name->n_name;
1900 if (strcmp(s + len, suff2) == 0) {
1901 return TRUE;
1902 }
1903 }
1904 }
1905 }
1906 }
1907 }
1908 return FALSE;
1909}
1910
1911enum {
1912 T_NORMAL = 0,
1913 T_SPECIAL = (1 << 0),
1914 T_INFERENCE = (1 << 1), // Inference rule
1915 T_NOPREREQ = (1 << 2), // If set must not have prerequisites
1916 T_COMMAND = (1 << 3), // If set must have commands, if unset must not
1917};
1918
1919/*
1920 * Determine if the argument is a special target and return a set
1921 * of flags indicating its properties.
1922 */
1923static int
1924target_type(char *s)
1925{
1926 int ret;
1927 static const char *s_name =
1928 ".DEFAULT\0"
1929 ".POSIX\0"
1930 ".IGNORE\0"
1931 ".PRECIOUS\0"
1932 ".SILENT\0"
1933 ".SUFFIXES\0"
1934 ".PHONY\0"
1935 ".NOTPARALLEL\0"
1936 ".WAIT\0"
1937#if ENABLE_FEATURE_MAKE_POSIX
1938 ".PRAGMA\0"
1939#endif
1940 ;
1941
1942 static const uint8_t s_type[] = {
1943 T_SPECIAL | T_NOPREREQ | T_COMMAND,
1944 T_SPECIAL | T_NOPREREQ,
1945 T_SPECIAL,
1946 T_SPECIAL,
1947 T_SPECIAL,
1948 T_SPECIAL,
1949 T_SPECIAL,
1950 T_SPECIAL | T_NOPREREQ,
1951 T_SPECIAL | T_NOPREREQ,
1952 T_SPECIAL,
1953 };
1954
1955 // Check for one of the known special targets
1956 ret = index_in_strings(s_name, s);
1957 if (ret >= 0)
1958 return s_type[ret];
1959
1960 // Check for an inference rule
1961 ret = T_NORMAL;
1962 if (!posix) {
1963 if (is_suffix(s) || is_inference_target(s)) {
1964 ret = T_INFERENCE | T_NOPREREQ | T_COMMAND;
1965 }
1966 } else {
1967 // In POSIX inference rule targets must contain one or two dots
1968 char *sfx = suffix(s);
1969 if (*s == '.' && is_suffix(sfx)) {
1970 if (s == sfx) { // Single suffix rule
1971 ret = T_INFERENCE | T_NOPREREQ | T_COMMAND;
1972 } else {
1973 // Suffix is valid, check that prefix is too
1974 *sfx = '\0';
1975 if (is_suffix(s))
1976 ret = T_INFERENCE | T_NOPREREQ | T_COMMAND;
1977 *sfx = '.';
1978 }
1979 }
1980 }
1981 return ret;
1982}
1983
1984static int
1985ends_with_bracket(const char *s)
1986{
1987 return last_char_is(s, ')') != NULL;
1988}
1989
1990/*
1991 * Process a command line
1992 */
1993static char *
1994process_command(char *s)
1995{
1996 char *t, *u;
1997 int len;
1998 char *outside;
1999
2000 if (!(pragma & P_COMMAND_COMMENT) && posix) {
2001 // POSIX strips comments from command lines
2002 t = strchr(s, '#');
2003 if (t) {
2004 *t = '\0';
2005 warning("comment in command removed: keep with pragma command_comment");
2006 }
2007 }
2008
2009 len = strlen(s) + 1;
2010 outside = xzalloc(len);
2011 for (t = skip_macro(s); *t; t = skip_macro(t + 1)) {
2012 outside[t - s] = 1;
2013 }
2014
2015 // Process escaped newlines. Stop at first non-escaped newline.
2016 for (t = u = s; *u && *u != '\n'; ) {
2017 if (u[0] == '\\' && u[1] == '\n') {
2018 if (POSIX_2017 || outside[u - s]) {
2019 // Outside macro: remove tab following escaped newline.
2020 *t++ = *u++;
2021 *t++ = *u++;
2022 u += (*u == '\t');
2023 } else {
2024 // Inside macro: replace escaped newline and any leading
2025 // whitespace on the following line with a single space.
2026 u += 2;
2027 while (isspace(*u))
2028 ++u;
2029 *t++ = ' ';
2030 }
2031 } else {
2032 *t++ = *u++;
2033 }
2034 }
2035 *t = '\0';
2036 free(outside);
2037 return s;
2038}
2039
2040static char *
2041run_command(const char *cmd)
2042{
2043 FILE *fd;
2044 char *s, *val = NULL;
2045 char buf[256];
2046 size_t len = 0, nread;
2047
2048 if ((fd = popen(cmd, "r")) == NULL)
2049 return val;
2050
2051 for (;;) {
2052 nread = fread(buf, 1, sizeof(buf), fd);
2053 if (nread == 0)
2054 break;
2055
2056 val = xrealloc(val, len + nread + 1);
2057 memcpy(val + len, buf, nread);
2058 len += nread;
2059 val[len] = '\0';
2060 }
2061 pclose(fd);
2062
2063 if (val == NULL)
2064 return NULL;
2065
2066 // Strip leading whitespace in POSIX 2024 mode
2067 if (posix) {
2068 s = val;
2069 while (isspace(*s)) {
2070 ++s;
2071 --len;
2072 }
2073
2074 if (len == 0) {
2075 free(val);
2076 return NULL;
2077 }
2078 memmove(val, s, len + 1);
2079 }
2080
2081#if ENABLE_PLATFORM_MINGW32
2082 len = remove_cr(val, len + 1) - 1;
2083 if (len == 0) {
2084 free(val);
2085 return NULL;
2086 }
2087#endif
2088
2089 // Remove one newline from the end (BSD compatibility)
2090 if (val[len - 1] == '\n')
2091 val[len - 1] = '\0';
2092 // Other newlines are changed to spaces
2093 for (s = val; *s; ++s) {
2094 if (*s == '\n')
2095 *s = ' ';
2096 }
2097 return val;
2098}
2099
2100/*
2101 * Check for an unescaped wildcard character
2102 */
2103static int wildchar(const char *p)
2104{
2105 while (*p) {
2106 switch (*p) {
2107 case '?':
2108 case '*':
2109 case '[':
2110 return 1;
2111 case '\\':
2112 if (p[1] != '\0')
2113 ++p;
2114 break;
2115 }
2116 ++p;
2117 }
2118 return 0;
2119}
2120
2121/*
2122 * Expand any wildcards in a pattern. Return TRUE if a match is
2123 * found, in which case the caller should call globfree() on the
2124 * glob_t structure.
2125 */
2126static int
2127wildcard(char *p, glob_t *gd)
2128{
2129 int ret;
2130 char *s;
2131
2132 // Don't call glob() if there are no wildcards.
2133 if (!wildchar(p)) {
2134 nomatch:
2135 // Remove backslashes from the name.
2136 for (s = p; *p; ++p) {
2137 if (*p == '\\' && p[1] != '\0')
2138 continue;
2139 *s++ = *p;
2140 }
2141 *s = '\0';
2142 return 0;
2143 }
2144
2145 memset(gd, 0, sizeof(*gd));
2146 ret = glob(p, GLOB_NOSORT, NULL, gd);
2147 if (ret == GLOB_NOMATCH) {
2148 globfree(gd);
2149 goto nomatch;
2150 } else if (ret != 0) {
2151 error("glob error for '%s'", p);
2152 }
2153 return 1;
2154}
2155
2156#if ENABLE_FEATURE_MAKE_POSIX
2157static void
2158pragmas_from_env(void)
2159{
2160 char *p, *q, *var;
2161 const char *env = getenv("PDPMAKE_PRAGMAS");
2162
2163 if (env == NULL)
2164 return;
2165
2166 q = var = xstrdup(env);
2167 while ((p = gettok(&q)) != NULL)
2168 set_pragma(p);
2169 free(var);
2170}
2171#endif
2172
2173/*
2174 * Determine if a line is a target rule with an inline command.
2175 * Return a pointer to the semicolon separator if it is, else NULL.
2176 */
2177static char *
2178inline_command(char *line)
2179{
2180 char *p = find_char(line, ':');
2181
2182 if (p)
2183 p = strchr(p, ';');
2184 return p;
2185}
2186
2187/*
2188 * Parse input from the makefile and construct a tree structure of it.
2189 */
2190static void
2191input(FILE *fd, int ilevel)
2192{
2193 char *p, *q, *s, *a, *str, *expanded, *copy;
2194 char *str1, *str2;
2195 struct name *np;
2196 struct depend *dp;
2197 struct cmd *cp;
2198 int startno, count;
2199 bool semicolon_cmd, seen_inference;
2200 uint8_t old_clevel = clevel;
2201 bool dbl;
2202 char *lib = NULL;
2203 glob_t gd;
2204 int nfile, i;
2205 char **files;
2206 bool minus;
2207
2208 lineno = 0;
2209 str1 = readline(fd, FALSE);
2210 while (str1) {
2211 str2 = NULL;
2212
2213 // Newlines and comments are handled differently in command lines
2214 // and other types of line. Take a copy of the current line before
2215 // processing it as a non-command line in case it contains a
2216 // rule with a command line. That is, a line of the form:
2217 //
2218 // target: prereq; command
2219 //
2220 copy = xstrdup(str1);
2221 process_line(str1);
2222 str = str1;
2223
2224 // Check for an include line
2225 if (!posix)
2226 while (isblank(*str))
2227 ++str;
2228 minus = !POSIX_2017 && *str == '-';
2229 p = str + minus;
2230 if (strncmp(p, "include", 7) == 0 && isblank(p[7])) {
2231 const char *old_makefile = makefile;
2232 int old_lineno = lineno;
2233
2234 if (ilevel > 16)
2235 error("too many includes");
2236
2237 count = 0;
2238 q = expanded = expand_macros(p + 7, FALSE);
2239 while ((p = gettok(&q)) != NULL) {
2240 FILE *ifd;
2241
2242 ++count;
2243 if (!POSIX_2017) {
2244 // Try to create include file or bring it up-to-date
2245 opts |= OPT_include;
2246 make(newname(p), 1);
2247 opts &= ~OPT_include;
2248 }
2249 if ((ifd = fopen(p, "r")) == NULL) {
2250 if (!minus)
2251 error("can't open include file '%s'", p);
2252 } else {
2253 makefile = p;
2254 input(ifd, ilevel + 1);
2255 fclose(ifd);
2256 makefile = old_makefile;
2257 lineno = old_lineno;
2258 }
2259 if (POSIX_2017)
2260 break;
2261 }
2262 if (POSIX_2017) {
2263 // In POSIX 2017 zero or more than one include file is
2264 // unspecified behaviour.
2265 if (p == NULL || gettok(&q)) {
2266 error("one include file per line");
2267 }
2268 } else if (count == 0) {
2269 // In POSIX 2024 no include file is unspecified behaviour.
2270 if (posix)
2271 error("no include file");
2272 }
2273 goto end_loop;
2274 }
2275
2276 // Check for a macro definition
2277 str = str1;
2278 // POSIX 2024 seems to allow a tab as the first character of
2279 // a macro definition, though most implementations don't.
2280 if (POSIX_2017 && *str == '\t')
2281 error("command not allowed here");
2282 if (find_char(str, '=') != NULL) {
2283 int level = (useenv || fd == NULL) ? 4 : 3;
2284 // Use a copy of the line: we might need the original
2285 // if this turns out to be a target rule.
2286 char *copy2 = xstrdup(str);
2287 char *newq = NULL;
2288 char eq = '\0';
2289 q = find_char(copy2, '='); // q can't be NULL
2290
2291 if (q - 1 > copy2) {
2292 switch (q[-1]) {
2293 case ':':
2294 // '::=' and ':::=' are from POSIX 2024.
2295 if (!POSIX_2017 && q - 2 > copy2 && q[-2] == ':') {
2296 if (q - 3 > copy2 && q[-3] == ':') {
2297 eq = 'B'; // BSD-style ':='
2298 q[-3] = '\0';
2299 } else {
2300 eq = ':'; // GNU-style ':='
2301 q[-2] = '\0';
2302 }
2303 break;
2304 }
2305 // ':=' is a non-POSIX extension.
2306 if (posix)
2307 break;
2308 goto set_eq;
2309 case '+':
2310 case '?':
2311 case '!':
2312 // '+=', '?=' and '!=' are from POSIX 2024.
2313 if (POSIX_2017)
2314 break;
2315 set_eq:
2316 eq = q[-1];
2317 q[-1] = '\0';
2318 break;
2319 }
2320 }
2321 *q++ = '\0'; // Separate name and value
2322 while (isblank(*q))
2323 q++;
2324 if ((p = strrchr(q, '\n')) != NULL)
2325 *p = '\0';
2326
2327 // Expand left-hand side of assignment
2328 p = expanded = expand_macros(copy2, FALSE);
2329 if ((a = gettok(&p)) == NULL)
2330 error("invalid macro assignment");
2331
2332 // If the expanded LHS contains ':' and ';' it can't be a
2333 // macro assignment but it might be a target rule.
2334 if ((s = strchr(a, ':')) != NULL && strchr(s, ';') != NULL) {
2335 free(expanded);
2336 free(copy2);
2337 goto try_target;
2338 }
2339
2340 if (gettok(&p))
2341 error("invalid macro assignment");
2342
2343 if (eq == ':') {
2344 // GNU-style ':='. Expand right-hand side of assignment.
2345 // Macro is of type immediate-expansion.
2346 q = newq = expand_macros(q, FALSE);
2347 level |= M_IMMEDIATE;
2348 }
2349 else if (eq == 'B') {
2350 // BSD-style ':='. Expand right-hand side of assignment,
2351 // though not '$$'. Macro is of type delayed-expansion.
2352 q = newq = expand_macros(q, TRUE);
2353 } else if (eq == '?' && getmp(a) != NULL) {
2354 // Skip assignment if macro is already set
2355 goto end_loop;
2356 } else if (eq == '+') {
2357 // Append to current value
2358 struct macro *mp = getmp(a);
2359 char *rhs;
2360 newq = mp && mp->m_val[0] ? xstrdup(mp->m_val) : NULL;
2361 if (mp && mp->m_immediate) {
2362 // Expand right-hand side of assignment (GNU make
2363 // compatibility)
2364 rhs = expand_macros(q, FALSE);
2365 level |= M_IMMEDIATE;
2366 } else {
2367 rhs = q;
2368 }
2369 newq = xappendword(newq, rhs);
2370 if (rhs != q)
2371 free(rhs);
2372 q = newq;
2373 } else if (eq == '!') {
2374 char *cmd = expand_macros(q, FALSE);
2375 q = newq = run_command(cmd);
2376 free(cmd);
2377 }
2378 setmacro(a, q, level);
2379 free(newq);
2380 free(copy2);
2381 goto end_loop;
2382 }
2383
2384 // If we get here it must be a target rule
2385 try_target:
2386 if (*str == '\t') // Command without target
2387 error("command not allowed here");
2388 p = expanded = expand_macros(str, FALSE);
2389
2390 // Look for colon separator
2391 q = find_colon(p);
2392 if (q == NULL)
2393 error("expected separator");
2394
2395 *q++ = '\0'; // Separate targets and prerequisites
2396
2397 // Double colon
2398 dbl = !posix && *q == ':';
2399 if (dbl)
2400 q++;
2401
2402 // Look for semicolon separator
2403 cp = NULL;
2404 s = strchr(q, ';');
2405 if (s) {
2406 // Retrieve command from original or expanded copy of line
2407 char *copy3 = expand_macros(copy, FALSE);
2408 if ((p = inline_command(copy)) || (p = inline_command(copy3)))
2409 newcmd(&cp, process_command(p + 1));
2410 free(copy3);
2411 *s = '\0';
2412 }
2413 semicolon_cmd = cp != NULL && cp->c_cmd[0] != '\0';
2414
2415 // Create list of prerequisites
2416 dp = NULL;
2417 while (((p = gettok(&q)) != NULL)) {
2418 char *newp = NULL;
2419
2420 if (!posix) {
2421 // Allow prerequisites of form library(member1 member2).
2422 // Leading and trailing spaces in the brackets are skipped.
2423 if (!lib) {
2424 s = strchr(p, '(');
2425 if (s && !ends_with_bracket(s) && strchr(q, ')')) {
2426 // Looks like an unterminated archive member
2427 // with a terminator later on the line.
2428 lib = p;
2429 if (s[1] != '\0') {
2430 p = newp = auto_concat(lib, ")");
2431 s[1] = '\0';
2432 } else {
2433 continue;
2434 }
2435 }
2436 } else if (ends_with_bracket(p)) {
2437 if (*p != ')')
2438 p = newp = auto_concat(lib, p);
2439 lib = NULL;
2440 if (newp == NULL)
2441 continue;
2442 } else {
2443 p = newp = auto_string(xasprintf("%s%s)", lib, p));
2444 }
2445 }
2446
2447 // If not in POSIX mode expand wildcards in the name.
2448 nfile = 1;
2449 files = &p;
2450 if (!posix && wildcard(p, &gd)) {
2451 nfile = gd.gl_pathc;
2452 files = gd.gl_pathv;
2453 }
2454 for (i = 0; i < nfile; ++i) {
2455 if (!POSIX_2017 && strcmp(files[i], ".WAIT") == 0)
2456 continue;
2457 np = newname(files[i]);
2458 newdep(&dp, np);
2459 }
2460 if (files != &p)
2461 globfree(&gd);
2462 free(newp);
2463 }
2464 lib = NULL;
2465
2466 // Create list of commands
2467 startno = dispno;
2468 while ((str2 = readline(fd, TRUE)) && *str2 == '\t') {
2469 newcmd(&cp, process_command(str2));
2470 free(str2);
2471 }
2472 dispno = startno;
2473
2474 // Create target names and attach rule to them
2475 q = expanded;
2476 count = 0;
2477 seen_inference = FALSE;
2478 while ((p = gettok(&q)) != NULL) {
2479 // If not in POSIX mode expand wildcards in the name.
2480 nfile = 1;
2481 files = &p;
2482 if (!posix && wildcard(p, &gd)) {
2483 nfile = gd.gl_pathc;
2484 files = gd.gl_pathv;
2485 }
2486 for (i = 0; i < nfile; ++i) {
2487 int ttype = target_type(files[i]);
2488
2489 np = newname(files[i]);
2490 if (ttype != T_NORMAL) {
2491 // Enforce prerequisites/commands in POSIX mode
2492 if (posix) {
2493 if ((ttype & T_NOPREREQ) && dp)
2494 error_not_allowed("prerequisites", p);
2495 if ((ttype & T_INFERENCE)) {
2496 if (semicolon_cmd)
2497 error_in_inference_rule("'; command'");
2498 seen_inference = TRUE;
2499 }
2500 if ((ttype & T_COMMAND) && !cp &&
2501 !((ttype & T_INFERENCE) && !semicolon_cmd))
2502 error("commands required for %s", p);
2503 if (!(ttype & T_COMMAND) && cp)
2504 error_not_allowed("commands", p);
2505 }
2506
2507 if ((ttype & T_INFERENCE)) {
2508 np->n_flag |= N_INFERENCE;
2509 } else if (strcmp(p, ".DEFAULT") == 0) {
2510 // .DEFAULT rule is a special case
2511 np->n_flag |= N_SPECIAL | N_INFERENCE;
2512 } else {
2513 np->n_flag |= N_SPECIAL;
2514 }
2515 } else if (!firstname) {
2516 firstname = np;
2517 }
2518 addrule(np, dp, cp, dbl);
2519 count++;
2520 }
2521 if (files != &p)
2522 globfree(&gd);
2523 }
2524 if (posix && seen_inference && count != 1)
2525 error_in_inference_rule("multiple targets");
2526
2527 // Prerequisites and commands will be unused if there were
2528 // no targets. Avoid leaking memory.
2529 if (count == 0) {
2530 freedeps(dp);
2531 freecmds(cp);
2532 }
2533
2534 end_loop:
2535 free(str1);
2536 dispno = lineno;
2537 str1 = str2 ? str2 : readline(fd, FALSE);
2538 free(copy);
2539 free(expanded);
2540#if ENABLE_FEATURE_MAKE_POSIX
2541 if (!seen_first && fd) {
2542 if (findname(".POSIX")) {
2543 // The first non-comment line from a real makefile
2544 // defined the .POSIX special target.
2545 setenv("PDPMAKE_POSIXLY_CORRECT", "", 1);
2546 posix = TRUE;
2547 }
2548 seen_first = TRUE;
2549 }
2550#endif
2551 }
2552 // Conditionals aren't allowed to span files
2553 if (clevel != old_clevel)
2554 error("invalid conditional");
2555}
2556
2557static void
2558remove_target(void)
2559{
2560 if (!dryrun && !print && !precious &&
2561 target && !(target->n_flag & (N_PRECIOUS | N_PHONY)) &&
2562 unlink(target->n_name) == 0) {
2563 diagnostic("'%s' removed", target->n_name);
2564 }
2565}
2566
2567/*
2568 * Update the modification time of a file to now.
2569 */
2570static void
2571touch(struct name *np)
2572{
2573 if (dryrun || !silent)
2574 printf("touch %s\n", np->n_name);
2575
2576 if (!dryrun) {
2577 const struct timespec timebuf[2] = {{0, UTIME_NOW}, {0, UTIME_NOW}};
2578
2579 if (utimensat(AT_FDCWD, np->n_name, timebuf, 0) < 0) {
2580 if (errno == ENOENT) {
2581 int fd = open(np->n_name, O_RDWR | O_CREAT, 0666);
2582 if (fd >= 0) {
2583 close(fd);
2584 return;
2585 }
2586 }
2587 warning("touch %s failed", np->n_name);
2588 }
2589 }
2590}
2591
2592/*
2593 * Do commands to make a target
2594 */
2595static int
2596docmds(struct name *np, struct cmd *cp)
2597{
2598 int estat = 0;
2599 char *q, *command;
2600
2601 for (; cp; cp = cp->c_next) {
2602 uint32_t ssilent, signore, sdomake;
2603
2604 // Location of command in makefile (for use in error messages)
2605 makefile = cp->c_makefile;
2606 dispno = cp->c_dispno;
2607 opts &= ~OPT_make; // We want to know if $(MAKE) is expanded
2608 q = command = expand_macros(cp->c_cmd, FALSE);
2609 ssilent = silent || (np->n_flag & N_SILENT) || dotouch;
2610 signore = ignore || (np->n_flag & N_IGNORE);
2611 sdomake = (!dryrun || doinclude || domake) && !dotouch;
2612 for (;;) {
2613 if (*q == '@') // Specific silent
2614 ssilent = TRUE + 1;
2615 else if (*q == '-') // Specific ignore
2616 signore = TRUE;
2617 else if (*q == '+') // Specific domake
2618 sdomake = TRUE + 1;
2619 else
2620 break;
2621 do {
2622 q++;
2623 } while (isblank(*q));
2624 }
2625
2626 if (sdomake > TRUE) {
2627 // '+' must not override '@' or .SILENT
2628 if (ssilent != TRUE + 1 && !(np->n_flag & N_SILENT))
2629 ssilent = FALSE;
2630 } else if (!sdomake)
2631 ssilent = dotouch;
2632
2633 if (!ssilent && *q != '\0') { // Ignore empty commands
2634 puts(q);
2635 fflush_all();
2636 }
2637
2638 if (quest && sdomake != TRUE + 1) {
2639 // MAKE_FAILURE means rebuild is needed
2640 estat |= MAKE_FAILURE | MAKE_DIDSOMETHING;
2641 continue;
2642 }
2643
2644 if (sdomake && *q != '\0') { // Ignore empty commands
2645 // Get the shell to execute it
2646 int status;
2647 char *cmd = !signore && posix ? auto_concat("set -e;", q) : q;
2648
2649 target = np;
2650 status = system(cmd);
2651 // If this command was being run to create an include file
2652 // or bring it up-to-date errors should be ignored and a
2653 // failure status returned.
2654 if (status == -1 && !doinclude) {
2655 error("couldn't execute '%s'", q);
2656 } else if (status != 0 && !signore) {
2657 if (!posix && WIFSIGNALED(status))
2658 remove_target();
2659 if (doinclude) {
2660 warning("failed to build '%s'", np->n_name);
2661 } else {
2662 const char *err_type = NULL;
2663 int err_value = 1;
2664
2665 if (WIFEXITED(status)) {
2666 err_type = "exit";
2667 err_value = WEXITSTATUS(status);
2668 } else if (WIFSIGNALED(status)) {
2669 err_type = "signal";
2670 err_value = WTERMSIG(status);
2671 }
2672
2673 if (!quest || err_value == 127) {
2674 if (err_type)
2675 diagnostic("failed to build '%s' %s %d",
2676 np->n_name, err_type, err_value);
2677 else
2678 diagnostic("failed to build '%s'", np->n_name);
2679 }
2680
2681 if (errcont) {
2682 estat |= MAKE_FAILURE;
2683 free(command);
2684 break;
2685 }
2686 exit(2);
2687 }
2688 }
2689 }
2690 if (sdomake || dryrun)
2691 estat = MAKE_DIDSOMETHING;
2692 free(command);
2693 }
2694
2695 if (dotouch && !(np->n_flag & N_PHONY) && !(estat & MAKE_DIDSOMETHING)) {
2696 touch(np);
2697 estat = MAKE_DIDSOMETHING;
2698 }
2699
2700 makefile = NULL;
2701 return estat;
2702}
2703
2704/*
2705 * Remove the suffix from a name, either the one provided in 'tsuff'
2706 * or, if 'tsuff' is NULL, one of the known suffixes.
2707 */
2708static char *
2709remove_suffix(const char *name, const char *tsuff)
2710{
2711 char *base = NULL;
2712
2713 if (tsuff != NULL) {
2714 base = has_suffix(name, tsuff);
2715 } else {
2716 struct name *xp = newname(".SUFFIXES");
2717 for (struct rule *rp = xp->n_rule; rp; rp = rp->r_next) {
2718 for (struct depend *dp = rp->r_dep; dp; dp = dp->d_next) {
2719 base = has_suffix(name, dp->d_name->n_name);
2720 if (base) {
2721 return base;
2722 }
2723 }
2724 }
2725 }
2726 return base;
2727}
2728
2729static int
2730make1(struct name *np, struct cmd *cp, char *oodate, char *allsrc,
2731 char *dedup, struct name *implicit, const char *tsuff)
2732{
2733 char *name, *member = NULL, *base = NULL, *prereq = NULL;
2734
2735 name = splitlib(np->n_name, &member);
2736 setmacro("?", oodate, 0 | M_VALID);
2737 if (!POSIX_2017) {
2738 setmacro("+", allsrc, 0 | M_VALID);
2739 setmacro("^", dedup, 0 | M_VALID);
2740 }
2741 setmacro("%", member, 0 | M_VALID);
2742 setmacro("@", name, 0 | M_VALID);
2743 if (implicit || !posix) {
2744 char *s;
2745
2746 // As an extension, if we're not dealing with an implicit
2747 // prerequisite set $< to the first out-of-date prerequisite.
2748 if (implicit == NULL) {
2749 if (oodate) {
2750 s = strchr(oodate, ' ');
2751 if (s)
2752 *s = '\0';
2753 prereq = oodate;
2754 }
2755 } else
2756 prereq = implicit->n_name;
2757
2758 if (!posix && member == NULL) {
2759 // As an extension remove a suffix that doesn't necessarily
2760 // start with a period from a target, but not for targets
2761 // of the form lib.a(member.o).
2762 base = remove_suffix(name, tsuff);
2763 if (base) {
2764 free(name);
2765 name = base;
2766 }
2767 } else {
2768 base = member ? member : name;
2769 s = suffix(base);
2770 // As an extension, if we're not dealing with an implicit
2771 // prerequisite and the target ends with a known suffix,
2772 // remove it and set $* to the stem, else to an empty string.
2773 if (implicit == NULL && !is_suffix(s))
2774 base = NULL;
2775 else
2776 *s = '\0';
2777 }
2778 }
2779 setmacro("<", prereq, 0 | M_VALID);
2780 setmacro("*", base, 0 | M_VALID);
2781 free(name);
2782
2783 return docmds(np, cp);
2784}
2785
2786/*
2787 * Determine if the modification time of a target, t, is less than
2788 * that of a prerequisite, p. If the tv_nsec member of either is
2789 * exactly 0 we assume (possibly incorrectly) that the time resolution
2790 * is 1 second and only compare tv_sec values.
2791 */
2792static int
2793timespec_le(const struct timespec *t, const struct timespec *p)
2794{
2795 if (t->tv_nsec == 0 || p->tv_nsec == 0)
2796 return t->tv_sec <= p->tv_sec;
2797 else if (t->tv_sec < p->tv_sec)
2798 return TRUE;
2799 else if (t->tv_sec == p->tv_sec)
2800 return t->tv_nsec <= p->tv_nsec;
2801 return FALSE;
2802}
2803
2804/*
2805 * Return the greater of two struct timespecs
2806 */
2807static const struct timespec *
2808timespec_max(const struct timespec *t, const struct timespec *p)
2809{
2810 return timespec_le(t, p) ? p : t;
2811}
2812
2813/*
2814 * Recursive routine to make a target.
2815 */
2816static int
2817make(struct name *np, int level)
2818{
2819 struct depend *dp;
2820 struct rule *rp;
2821 struct name *impdep = NULL; // implicit prerequisite
2822 struct rule infrule;
2823 struct cmd *sc_cmd = NULL; // commands for single-colon rule
2824 char *oodate = NULL;
2825 char *allsrc = NULL;
2826 char *dedup = NULL;
2827 const char *tsuff = NULL;
2828 struct timespec dtim = {1, 0};
2829 int estat = 0;
2830
2831 if (np->n_flag & N_DONE)
2832 return 0;
2833 if (np->n_flag & N_DOING)
2834 error("circular dependency for %s", np->n_name);
2835 np->n_flag |= N_DOING;
2836
2837 if (!np->n_tim.tv_sec)
2838 modtime(np); // Get modtime of this file
2839
2840 if (!(np->n_flag & N_DOUBLE)) {
2841 // Find the commands needed for a single-colon rule, using
2842 // an inference rule or .DEFAULT rule if necessary (but,
2843 // as an extension, not for phony targets)
2844 sc_cmd = getcmd(np);
2845 if (!sc_cmd && (posix || !(np->n_flag & N_PHONY))) {
2846 impdep = dyndep(np, &infrule, &tsuff);
2847 if (impdep) {
2848 sc_cmd = infrule.r_cmd;
2849 addrule(np, infrule.r_dep, NULL, FALSE);
2850 }
2851 }
2852
2853 // As a last resort check for a default rule
2854 if (!(np->n_flag & N_TARGET) && np->n_tim.tv_sec == 0) {
2855 if (posix || !(np->n_flag & N_PHONY))
2856 sc_cmd = getcmd(findname(".DEFAULT"));
2857 if (!sc_cmd) {
2858 if (doinclude)
2859 return 1;
2860 error("don't know how to make %s", np->n_name);
2861 }
2862 impdep = np;
2863 }
2864 } else {
2865 // If any double-colon rule has no commands we need
2866 // an inference rule.
2867 for (rp = np->n_rule; rp; rp = rp->r_next) {
2868 if (!rp->r_cmd) {
2869 // Phony targets don't need an inference rule.
2870 if (!posix && (np->n_flag & N_PHONY))
2871 continue;
2872 impdep = dyndep(np, &infrule, &tsuff);
2873 if (!impdep) {
2874 if (doinclude)
2875 return 1;
2876 error("don't know how to make %s", np->n_name);
2877 }
2878 break;
2879 }
2880 }
2881 }
2882
2883 // Reset flag to detect duplicate prerequisites
2884 if (!(np->n_flag & N_DOUBLE)) {
2885 for (rp = np->n_rule; rp; rp = rp->r_next) {
2886 for (dp = rp->r_dep; dp; dp = dp->d_next) {
2887 dp->d_name->n_flag &= ~N_MARK;
2888 }
2889 }
2890 }
2891
2892 for (rp = np->n_rule; rp; rp = rp->r_next) {
2893 struct name *locdep = NULL;
2894
2895 // Each double-colon rule is handled separately.
2896 if ((np->n_flag & N_DOUBLE)) {
2897 // If the rule has no commands use the inference rule.
2898 // Unless there isn't one, as allowed for phony targets.
2899 if (!rp->r_cmd) {
2900 if (impdep) {
2901 locdep = impdep;
2902 infrule.r_dep->d_next = rp->r_dep;
2903 rp->r_dep = infrule.r_dep;
2904 rp->r_cmd = infrule.r_cmd;
2905 }
2906 }
2907 // A rule with no prerequisities is executed unconditionally.
2908 if (!rp->r_dep)
2909 dtim = np->n_tim;
2910 // Reset flag to detect duplicate prerequisites
2911 for (dp = rp->r_dep; dp; dp = dp->d_next) {
2912 dp->d_name->n_flag &= ~N_MARK;
2913 }
2914 }
2915 for (dp = rp->r_dep; dp; dp = dp->d_next) {
2916 // Make prerequisite
2917 estat |= make(dp->d_name, level + 1);
2918
2919 // Make strings of out-of-date prerequisites (for $?),
2920 // all prerequisites (for $+) and deduplicated prerequisites
2921 // (for $^).
2922 if (timespec_le(&np->n_tim, &dp->d_name->n_tim)) {
2923 if (posix || !(dp->d_name->n_flag & N_MARK))
2924 oodate = xappendword(oodate, dp->d_name->n_name);
2925 }
2926 allsrc = xappendword(allsrc, dp->d_name->n_name);
2927 if (!(dp->d_name->n_flag & N_MARK))
2928 dedup = xappendword(dedup, dp->d_name->n_name);
2929 dp->d_name->n_flag |= N_MARK;
2930 dtim = *timespec_max(&dtim, &dp->d_name->n_tim);
2931 }
2932 if ((np->n_flag & N_DOUBLE)) {
2933 if (((np->n_flag & N_PHONY) || timespec_le(&np->n_tim, &dtim))) {
2934 if (!(estat & MAKE_FAILURE)) {
2935 estat |= make1(np, rp->r_cmd, oodate, allsrc,
2936 dedup, locdep, tsuff);
2937 dtim = (struct timespec){1, 0};
2938 }
2939 free(oodate);
2940 oodate = NULL;
2941 }
2942 free(allsrc);
2943 free(dedup);
2944 allsrc = dedup = NULL;
2945 if (locdep) {
2946 rp->r_dep = rp->r_dep->d_next;
2947 rp->r_cmd = NULL;
2948 }
2949 }
2950 }
2951 if ((np->n_flag & N_DOUBLE) && impdep)
2952 free(infrule.r_dep);
2953
2954 np->n_flag |= N_DONE;
2955 np->n_flag &= ~N_DOING;
2956
2957 if (!(np->n_flag & N_DOUBLE) &&
2958 ((np->n_flag & N_PHONY) || (timespec_le(&np->n_tim, &dtim)))) {
2959 if (!(estat & MAKE_FAILURE)) {
2960 if (sc_cmd)
2961 estat |= make1(np, sc_cmd, oodate, allsrc, dedup,
2962 impdep, tsuff);
2963 else if (!doinclude && level == 0 && !(estat & MAKE_DIDSOMETHING))
2964 warning("nothing to be done for %s", np->n_name);
2965 } else if (!doinclude && !quest) {
2966 diagnostic("'%s' not built due to errors", np->n_name);
2967 }
2968 free(oodate);
2969 }
2970
2971 if (estat & MAKE_DIDSOMETHING) {
2972 modtime(np);
2973 if (!np->n_tim.tv_sec)
2974 clock_gettime(CLOCK_REALTIME, &np->n_tim);
2975 } else if (!quest && level == 0 && !timespec_le(&np->n_tim, &dtim))
2976 printf("%s: '%s' is up to date\n", applet_name, np->n_name);
2977
2978 free(allsrc);
2979 free(dedup);
2980 return estat;
2981}
2982
2983/*
2984 * Check structures for make.
2985 */
2986
2987static void
2988print_name(struct name *np)
2989{
2990 if (np == firstname)
2991 printf("# default target\n");
2992 printf("%s:", np->n_name);
2993 if ((np->n_flag & N_DOUBLE))
2994 putchar(':');
2995}
2996
2997static void
2998print_prerequisites(struct rule *rp)
2999{
3000 struct depend *dp;
3001
3002 for (dp = rp->r_dep; dp; dp = dp->d_next)
3003 printf(" %s", dp->d_name->n_name);
3004}
3005
3006static void
3007print_commands(struct rule *rp)
3008{
3009 struct cmd *cp;
3010
3011 for (cp = rp->r_cmd; cp; cp = cp->c_next)
3012 printf("\t%s\n", cp->c_cmd);
3013}
3014
3015static void
3016print_details(void)
3017{
3018 int i;
3019 struct macro *mp;
3020 struct name *np;
3021 struct rule *rp;
3022
3023 for (i = 0; i < HTABSIZE; i++)
3024 for (mp = macrohead[i]; mp; mp = mp->m_next)
3025 printf("%s = %s\n", mp->m_name, mp->m_val);
3026 putchar('\n');
3027
3028 for (i = 0; i < HTABSIZE; i++) {
3029 for (np = namehead[i]; np; np = np->n_next) {
3030 if (!(np->n_flag & N_DOUBLE)) {
3031 print_name(np);
3032 for (rp = np->n_rule; rp; rp = rp->r_next) {
3033 print_prerequisites(rp);
3034 }
3035 putchar('\n');
3036
3037 for (rp = np->n_rule; rp; rp = rp->r_next) {
3038 print_commands(rp);
3039 }
3040 putchar('\n');
3041 } else {
3042 for (rp = np->n_rule; rp; rp = rp->r_next) {
3043 print_name(np);
3044 print_prerequisites(rp);
3045 putchar('\n');
3046
3047 print_commands(rp);
3048 putchar('\n');
3049 }
3050 }
3051 }
3052 }
3053}
3054
3055/*
3056 * Process options from an argv array. If from_env is non-zero we're
3057 * handling options from MAKEFLAGS so skip '-C', '-f', '-p' and '-x'.
3058 */
3059static uint32_t
3060process_options(char **argv, int from_env)
3061{
3062 uint32_t flags;
3063
3064 flags = getopt32(argv, "^" OPTSTR1 OPTSTR2 "\0k-S:S-k",
3065 &numjobs, &makefiles, &dirs
3066 IF_FEATURE_MAKE_POSIX(, &pragmas));
3067 if (from_env && (flags & (OPT_C | OPT_f | OPT_p | OPT_x)))
3068 error("invalid MAKEFLAGS");
3069 if (posix && (flags & OPT_C))
3070 error("-C not allowed");
3071
3072 return flags;
3073}
3074
3075/*
3076 * Split the contents of MAKEFLAGS into an argv array. If the return
3077 * value (call it fargv) isn't NULL the caller should free fargv[1] and
3078 * fargv.
3079 */
3080static char **
3081expand_makeflags(void)
3082{
3083 const char *m, *makeflags = getenv("MAKEFLAGS");
3084 char *p, *argstr;
3085 int argc;
3086 char **argv;
3087
3088 if (makeflags == NULL)
3089 return NULL;
3090
3091 while (isblank(*makeflags))
3092 makeflags++;
3093
3094 if (*makeflags == '\0')
3095 return NULL;
3096
3097 p = argstr = xzalloc(strlen(makeflags) + 2);
3098
3099 // If MAKEFLAGS doesn't start with a hyphen, doesn't look like
3100 // a macro definition and only contains valid option characters,
3101 // add a hyphen.
3102 argc = 3;
3103 if (makeflags[0] != '-' && strchr(makeflags, '=') == NULL) {
3104 if (strspn(makeflags, OPTSTR1) != strlen(makeflags))
3105 error("invalid MAKEFLAGS");
3106 *p++ = '-';
3107 } else {
3108 // MAKEFLAGS may need to be split, estimate size of argv array.
3109 for (m = makeflags; *m; ++m) {
3110 if (isblank(*m))
3111 argc++;
3112 }
3113 }
3114
3115 argv = xzalloc(argc * sizeof(char *));
3116 argc = 0;
3117 argv[argc++] = (char *)applet_name;
3118 argv[argc++] = argstr;
3119
3120 // Copy MAKEFLAGS into argstr, splitting at non-escaped blanks.
3121 m = makeflags;
3122 do {
3123 if (*m == '\\' && m[1] != '\0')
3124 m++; // Skip backslash, copy next character unconditionally.
3125 else if (isblank(*m)) {
3126 // Terminate current argument and start a new one.
3127 /* *p = '\0'; - xzalloc did it */
3128 argv[argc++] = ++p;
3129 do {
3130 m++;
3131 } while (isblank(*m));
3132 continue;
3133 }
3134 *p++ = *m++;
3135 } while (*m != '\0');
3136 /* *p = '\0'; - xzalloc did it */
3137 /* argv[argc] = NULL; - and this */
3138
3139 return argv;
3140}
3141
3142// These macros require special treatment
3143#define SPECIAL_MACROS "MAKEFLAGS\0SHELL\0CURDIR\0"
3144#define MAKEFLAGS 0
3145#define SHELL 1
3146#define CURDIR 2
3147
3148/*
3149 * Instantiate all macros in an argv-style array of pointers. Stop
3150 * processing at the first string that doesn't contain an equal sign.
3151 * As an extension, target arguments on the command line (level 1)
3152 * are skipped and will be processed later.
3153 */
3154static char **
3155process_macros(char **argv, int level)
3156{
3157 char *equal;
3158
3159 for (; *argv; argv++) {
3160 char *colon = NULL;
3161 int idx, immediate = 0;
3162 int except_dollar = FALSE;
3163
3164 if (!(equal = strchr(*argv, '='))) {
3165 // Skip targets on the command line
3166 if (!posix && level == 1)
3167 continue;
3168 else
3169 // Stop at first target
3170 break;
3171 }
3172
3173 if (equal - 1 > *argv && equal[-1] == ':') {
3174 if (equal - 2 > *argv && equal[-2] == ':') {
3175 if (POSIX_2017)
3176 error("invalid macro assignment");
3177 if (equal - 3 > *argv && equal[-3] == ':') {
3178 // BSD-style ':='. Expand RHS, but not '$$',
3179 // resulting macro is delayed expansion.
3180 colon = equal - 3;
3181 except_dollar = TRUE;
3182 } else {
3183 // GNU-style ':='. Expand RHS, including '$$',
3184 // resulting macro is immediate expansion.
3185 colon = equal - 2;
3186 immediate = M_IMMEDIATE;
3187 }
3188 *colon = '\0';
3189 } else {
3190 if (posix)
3191 error("invalid macro assignment");
3192 colon = equal - 1;
3193 immediate = M_IMMEDIATE;
3194 *colon = '\0';
3195 }
3196 } else
3197 *equal = '\0';
3198
3199 /* We want to process _most_ macro assignments.
3200 * There are exceptions for particular values from the
3201 * environment. */
3202 idx = index_in_strings(SPECIAL_MACROS, *argv);
3203 if (!((level & M_ENVIRON) &&
3204 (idx == MAKEFLAGS || idx == SHELL ||
3205 (idx == CURDIR && !useenv && !POSIX_2017)))) {
3206 if (colon) {
3207 char *exp = expand_macros(equal + 1, except_dollar);
3208 setmacro(*argv, exp, level | immediate);
3209 free(exp);
3210 } else
3211 setmacro(*argv, equal + 1, level);
3212 }
3213
3214 if (colon)
3215 *colon = ':';
3216 else
3217 *equal = '=';
3218 }
3219 return argv;
3220}
3221
3222/*
3223 * Update the MAKEFLAGS macro and environment variable to include any
3224 * command line options that don't have their default value (apart from
3225 * -f, -p and -S). Also add any macros defined on the command line or
3226 * by the MAKEFLAGS environment variable (apart from MAKEFLAGS itself).
3227 * Add macros that were defined on the command line to the environment.
3228 */
3229static void
3230update_makeflags(void)
3231{
3232 int i;
3233 char optbuf[] = "-?";
3234 char *makeflags = NULL;
3235 char *macro, *s;
3236 const char *t;
3237 struct macro *mp;
3238
3239 t = OPTSTR1;
3240 for (i = 0; *t; t++) {
3241 if (*t == ':' || *t == '+')
3242 continue;
3243 if ((opts & OPT_MASK & (1 << i))) {
3244 optbuf[1] = *t;
3245 makeflags = xappendword(makeflags, optbuf);
3246 if (*t == 'j') {
3247 s = auto_string(xasprintf("%d", numjobs));
3248 makeflags = xappendword(makeflags, s);
3249 }
3250 }
3251 i++;
3252 }
3253
3254 for (i = 0; i < HTABSIZE; ++i) {
3255 for (mp = macrohead[i]; mp; mp = mp->m_next) {
3256 if (mp->m_level == 1 || mp->m_level == 2) {
3257 int idx = index_in_strings(SPECIAL_MACROS, mp->m_name);
3258 if (idx == MAKEFLAGS)
3259 continue;
3260 macro = xzalloc(strlen(mp->m_name) + 2 * strlen(mp->m_val) + 1);
3261 s = stpcpy(macro, mp->m_name);
3262 *s++ = '=';
3263 for (t = mp->m_val; *t; t++) {
3264 if (*t == '\\' || isblank(*t))
3265 *s++ = '\\';
3266 *s++ = *t;
3267 }
3268 /* *s = '\0'; - xzalloc did it */
3269
3270 makeflags = xappendword(makeflags, macro);
3271 free(macro);
3272
3273 // Add command line macro definitions to the environment
3274 if (mp->m_level == 1 && idx != SHELL)
3275 setenv(mp->m_name, mp->m_val, 1);
3276 }
3277 }
3278 }
3279
3280 if (makeflags) {
3281 setmacro("MAKEFLAGS", makeflags, 0);
3282 setenv("MAKEFLAGS", makeflags, 1);
3283 free(makeflags);
3284 }
3285}
3286
3287#if !ENABLE_PLATFORM_MINGW32
3288static void
3289make_handler(int sig)
3290{
3291 signal(sig, SIG_DFL);
3292 remove_target();
3293 kill(getpid(), sig);
3294}
3295
3296static void
3297init_signal(int sig)
3298{
3299 struct sigaction sa, new_action;
3300
3301 sigemptyset(&new_action.sa_mask);
3302 new_action.sa_flags = 0;
3303 new_action.sa_handler = make_handler;
3304
3305 sigaction(sig, NULL, &sa);
3306 if (sa.sa_handler != SIG_IGN)
3307 sigaction_set(sig, &new_action);
3308}
3309#endif
3310
3311/*
3312 * If the global option flag associated with a special target hasn't
3313 * been set mark all prerequisites of the target with a flag. If the
3314 * target had no prerequisites set the global option flag.
3315 */
3316static void
3317mark_special(const char *special, uint32_t oflag, uint16_t nflag)
3318{
3319 struct name *np;
3320 struct rule *rp;
3321 struct depend *dp;
3322 int marked = FALSE;
3323
3324 if (!(opts & oflag) && (np = findname(special))) {
3325 for (rp = np->n_rule; rp; rp = rp->r_next) {
3326 for (dp = rp->r_dep; dp; dp = dp->d_next) {
3327 dp->d_name->n_flag |= nflag;
3328 marked = TRUE;
3329 }
3330 }
3331
3332 if (!marked)
3333 opts |= oflag;
3334 }
3335}
3336
3337int make_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3338int make_main(int argc UNUSED_PARAM, char **argv)
3339{
3340 const char *path, *newpath = NULL;
3341 char **fargv, **fargv0;
3342 const char *dir, *file;
3343#if ENABLE_FEATURE_MAKE_POSIX
3344 const char *prag;
3345#endif
3346 int estat;
3347 bool found_target;
3348 FILE *ifd;
3349
3350 INIT_G();
3351
3352#if ENABLE_FEATURE_MAKE_POSIX
3353 if (argv[1] && strcmp(argv[1], "--posix") == 0) {
3354 argv[1] = argv[0];
3355 ++argv;
3356 --argc;
3357 setenv("PDPMAKE_POSIXLY_CORRECT", "", 1);
3358 posix = TRUE;
3359 } else {
3360 posix = getenv("PDPMAKE_POSIXLY_CORRECT") != NULL;
3361 }
3362 posix_level = DEFAULT_POSIX_LEVEL;
3363 pragmas_from_env();
3364#endif
3365
3366 if (!POSIX_2017) {
3367 path = argv[0];
3368#if ENABLE_PLATFORM_MINGW32
3369 if (has_path(argv[0])) {
3370 // Add extension if necessary, else realpath() will fail
3371 char *p = alloc_ext_space(argv[0]);
3372 add_win32_extension(p);
3373 path = newpath = xmalloc_realpath(p);
3374 free(p);
3375 if (!path) {
3376 if (unix_path(argv[0]))
3377 path = argv[0];
3378 else
3379 bb_perror_msg("can't resolve path for %s", argv[0]);
3380 }
3381 }
3382#else
3383 if (argv[0][0] != '/' && strchr(argv[0], '/')) {
3384 // Make relative path absolute
3385 path = newpath = realpath(argv[0], NULL);
3386 if (!path) {
3387 bb_perror_msg("can't resolve path for %s", argv[0]);
3388 }
3389 }
3390#endif
3391 } else {
3392 path = "make";
3393 }
3394
3395 // Process options from MAKEFLAGS
3396 fargv = fargv0 = expand_makeflags();
3397 if (fargv0) {
3398 opts = process_options(fargv, TRUE);
3399 fargv = fargv0 + optind;
3400 // Reset getopt(3) so we can call it again
3401 GETOPT_RESET();
3402 }
3403
3404 // Process options from the command line
3405 opts |= process_options(argv, FALSE);
3406 argv += optind;
3407
3408 while ((dir = llist_pop(&dirs))) {
3409 if (chdir(dir) == -1) {
3410 bb_perror_msg("can't chdir to %s", dir);
3411 }
3412 }
3413
3414#if ENABLE_FEATURE_MAKE_POSIX
3415 while ((prag = llist_pop(&pragmas)))
3416 set_pragma(prag);
3417 pragmas_to_env();
3418#endif
3419
3420#if !ENABLE_PLATFORM_MINGW32
3421 init_signal(SIGHUP);
3422 init_signal(SIGTERM);
3423#endif
3424
3425 setmacro("$", "$", 0 | M_VALID);
3426
3427 // Process macro definitions from the command line
3428 if (!posix)
3429 process_macros(argv, 1);
3430 else
3431 // In POSIX mode macros must appear before targets.
3432 // argv should now point to targets only.
3433 argv = process_macros(argv, 1);
3434
3435 // Process macro definitions from MAKEFLAGS
3436 if (fargv) {
3437 process_macros(fargv, 2);
3438 free(fargv0[1]);
3439 free(fargv0);
3440 }
3441
3442 // Process macro definitions from the environment
3443 process_macros(environ, 3 | M_ENVIRON);
3444
3445 // Update MAKEFLAGS and environment
3446 update_makeflags();
3447
3448 // Read built-in rules
3449 input(NULL, 0);
3450
3451 setmacro("SHELL", DEFAULT_SHELL, 4);
3452 setmacro("MAKE", path, 4);
3453 if (!POSIX_2017) {
3454 char *cwd = xrealloc_getcwd_or_warn(NULL);
3455
3456 if (cwd) {
3457 if (!useenv) {
3458 // Export cwd to environment, if necessary
3459 char *envcwd = getenv("CURDIR");
3460 if (envcwd && strcmp(cwd, envcwd) != 0)
3461 setenv("CURDIR", cwd, 1);
3462 }
3463 setmacro("CURDIR", cwd, 4);
3464 }
3465 free(cwd);
3466 }
3467 free((void *)newpath);
3468
3469 if (!makefiles) { // Look for a default Makefile
3470 if (!posix && (ifd = fopen("PDPmakefile", "r")) != NULL)
3471 makefile = "PDPmakefile";
3472 else if ((ifd = fopen("PDPmakefile" + 3, "r")) != NULL)
3473 makefile = "PDPmakefile" + 3;
3474#if !ENABLE_PLATFORM_MINGW32
3475 else if ((ifd = fopen("Makefile", "r")) != NULL)
3476 makefile = "Makefile";
3477#endif
3478 else
3479 error("no makefile found");
3480 goto read_makefile;
3481 }
3482
3483 while ((file = llist_pop(&makefiles))) {
3484 if (strcmp(file, "-") == 0) { // Can use stdin as makefile
3485 ifd = stdin;
3486 makefile = "stdin";
3487 } else {
3488 ifd = xfopen_for_read(file);
3489 makefile = file;
3490 }
3491 read_makefile:
3492 input(ifd, 0);
3493 fclose(ifd);
3494 makefile = NULL;
3495 }
3496
3497 if (print)
3498 print_details();
3499
3500 mark_special(".SILENT", OPT_s, N_SILENT);
3501 mark_special(".IGNORE", OPT_i, N_IGNORE);
3502 mark_special(".PRECIOUS", OPT_precious, N_PRECIOUS);
3503 if (!POSIX_2017)
3504 mark_special(".PHONY", OPT_phony, N_PHONY);
3505
3506 if (posix) {
3507 // In POSIX mode only targets should now be in argv.
3508 found_target = FALSE;
3509 for (char **a = argv; *a; a++) {
3510 if (!strchr(*a, '='))
3511 found_target = TRUE;
3512 else if (found_target)
3513 error("macro assignments must precede targets");
3514 }
3515 }
3516
3517 estat = 0;
3518 found_target = FALSE;
3519 for (; *argv; argv++) {
3520 // Skip macro assignments.
3521 if (strchr(*argv, '='))
3522 continue;
3523 found_target = TRUE;
3524 estat |= make(newname(*argv), 0);
3525 }
3526 if (!found_target) {
3527 if (!firstname)
3528 error("no targets defined");
3529 estat = make(firstname, 0);
3530 }
3531
3532#if ENABLE_FEATURE_CLEAN_UP
3533 freenames();
3534 freemacros();
3535 llist_free(makefiles, NULL);
3536 llist_free(dirs, NULL);
3537#endif
3538
3539 return estat & MAKE_FAILURE;
3540}