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