1/*	$NetBSD: make.h,v 1.337 2024/06/01 06:26:36 sjg Exp $	*/
2
3/*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 *	from: @(#)make.h	8.3 (Berkeley) 6/13/95
35 */
36
37/*
38 * Copyright (c) 1989 by Berkeley Softworks
39 * All rights reserved.
40 *
41 * This code is derived from software contributed to Berkeley by
42 * Adam de Boor.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 *    notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 *    notice, this list of conditions and the following disclaimer in the
51 *    documentation and/or other materials provided with the distribution.
52 * 3. All advertising materials mentioning features or use of this software
53 *    must display the following acknowledgement:
54 *	This product includes software developed by the University of
55 *	California, Berkeley and its contributors.
56 * 4. Neither the name of the University nor the names of its contributors
57 *    may be used to endorse or promote products derived from this software
58 *    without specific prior written permission.
59 *
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
71 *
72 *	from: @(#)make.h	8.3 (Berkeley) 6/13/95
73 */
74
75/*
76 * make.h --
77 *	The global definitions for make
78 */
79
80#ifndef MAKE_MAKE_H
81#define MAKE_MAKE_H
82
83#include <sys/types.h>
84#include <sys/param.h>
85#include <sys/stat.h>
86
87#include <assert.h>
88#include <ctype.h>
89#include <fcntl.h>
90#include <stdarg.h>
91#include <stdio.h>
92#include <stdlib.h>
93#include <string.h>
94#include <unistd.h>
95
96#ifdef BSD4_4
97# include <sys/cdefs.h>
98#endif
99
100#ifndef FD_CLOEXEC
101#define FD_CLOEXEC 1
102#endif
103
104#if defined(__GNUC__)
105#define MAKE_GNUC_PREREQ(x, y)						\
106	((__GNUC__ == (x) && __GNUC_MINOR__ >= (y)) ||			\
107	 (__GNUC__ > (x)))
108#else
109#define MAKE_GNUC_PREREQ(x, y)	0
110#endif
111
112#if MAKE_GNUC_PREREQ(2, 7)
113#define MAKE_ATTR_UNUSED	__attribute__((__unused__))
114#else
115#define MAKE_ATTR_UNUSED	/* delete */
116#endif
117
118#if MAKE_GNUC_PREREQ(2, 5)
119#define MAKE_ATTR_DEAD		__attribute__((__noreturn__))
120#elif defined(__GNUC__)
121#define MAKE_ATTR_DEAD		__volatile
122#else
123#define MAKE_ATTR_DEAD		/* delete */
124#endif
125
126#if MAKE_GNUC_PREREQ(2, 7)
127#define MAKE_ATTR_PRINTFLIKE(fmtarg, firstvararg)	\
128	    __attribute__((__format__ (__printf__, fmtarg, firstvararg)))
129#else
130#define MAKE_ATTR_PRINTFLIKE(fmtarg, firstvararg)	/* delete */
131#endif
132
133#if MAKE_GNUC_PREREQ(4, 0)
134#define MAKE_ATTR_USE		__attribute__((__warn_unused_result__))
135#else
136#define MAKE_ATTR_USE		/* delete */
137#endif
138
139#if MAKE_GNUC_PREREQ(8, 0)
140#define MAKE_ATTR_NOINLINE		__attribute__((__noinline__))
141#else
142#define MAKE_ATTR_NOINLINE		/* delete */
143#endif
144
145#if __STDC_VERSION__ >= 199901L || defined(lint)
146#define MAKE_INLINE static inline MAKE_ATTR_UNUSED
147#else
148#define MAKE_INLINE static MAKE_ATTR_UNUSED
149#endif
150
151/* MAKE_STATIC marks a function that may or may not be inlined. */
152#if defined(lint)
153/* As of 2021-07-31, NetBSD lint ignores __attribute__((unused)). */
154#define MAKE_STATIC MAKE_INLINE
155#else
156#define MAKE_STATIC static MAKE_ATTR_UNUSED
157#endif
158
159#if __STDC_VERSION__ >= 199901L || defined(lint) || defined(USE_C99_BOOLEAN)
160#include <stdbool.h>
161#elif defined(__bool_true_false_are_defined)
162/*
163 * All files of make must be compiled with the same definition of bool.
164 * Since one of the files includes <stdbool.h>, that means the header is
165 * available on this platform.  Recompile everything with -DUSE_C99_BOOLEAN.
166 */
167#error "<stdbool.h> is included in pre-C99 mode"
168#elif defined(bool) || defined(true) || defined(false)
169/*
170 * In pre-C99 mode, make does not expect that bool is already defined.
171 * You need to ensure that all translation units use the same definition for
172 * bool.
173 */
174#error "bool/true/false is defined in pre-C99 mode"
175#else
176typedef unsigned char bool;
177#define true	1
178#define false	0
179#endif
180
181#include "lst.h"
182#include "make_malloc.h"
183#include "str.h"
184#include "hash.h"
185#include "config.h"
186#include "buf.h"
187
188/*
189 * The typical flow of states is:
190 *
191 * The direct successful path:
192 * UNMADE -> BEINGMADE -> MADE.
193 *
194 * The direct error path:
195 * UNMADE -> BEINGMADE -> ERROR.
196 *
197 * The successful path when dependencies need to be made first:
198 * UNMADE -> DEFERRED -> REQUESTED -> BEINGMADE -> MADE.
199 *
200 * A node that has dependencies, and one of the dependencies cannot be made:
201 * UNMADE -> DEFERRED -> ABORTED.
202 *
203 * A node that turns out to be up-to-date:
204 * UNMADE -> BEINGMADE -> UPTODATE.
205 */
206typedef enum GNodeMade {
207	/* Not examined yet. */
208	UNMADE,
209	/*
210	 * The node has been examined but is not yet ready since its
211	 * dependencies have to be made first.
212	 */
213	DEFERRED,
214
215	/* The node is on the toBeMade list. */
216	REQUESTED,
217
218	/*
219	 * The node is already being made. Trying to build a node in this
220	 * state indicates a cycle in the graph.
221	 */
222	BEINGMADE,
223
224	/* Was out-of-date and has been made. */
225	MADE,
226	/* Was already up-to-date, does not need to be made. */
227	UPTODATE,
228	/*
229	 * An error occurred while it was being made. Used only in compat
230	 * mode.
231	 */
232	ERROR,
233	/*
234	 * The target was aborted due to an error making a dependency. Used
235	 * only in compat mode.
236	 */
237	ABORTED
238} GNodeMade;
239
240/*
241 * The OP_ constants are used when parsing a dependency line as a way of
242 * communicating to other parts of the program the way in which a target
243 * should be made.
244 *
245 * Some of the OP_ constants can be combined, others cannot.
246 *
247 * See the tests depsrc-*.mk and deptgt-*.mk.
248 */
249typedef enum GNodeType {
250	OP_NONE		= 0,
251
252	/*
253	 * The dependency operator ':' is the most common one.  The commands
254	 * of this node are executed if any child is out-of-date.
255	 */
256	OP_DEPENDS	= 1 << 0,
257	/*
258	 * The dependency operator '!' always executes its commands, even if
259	 * its children are up-to-date.
260	 */
261	OP_FORCE	= 1 << 1,
262	/*
263	 * The dependency operator '::' behaves like ':', except that it
264	 * allows multiple dependency groups to be defined.  Each of these
265	 * groups is executed on its own, independently from the others. Each
266	 * individual dependency group is called a cohort.
267	 */
268	OP_DOUBLEDEP	= 1 << 2,
269
270	/* Matches the dependency operators ':', '!' and '::'. */
271	OP_OPMASK	= OP_DEPENDS | OP_FORCE | OP_DOUBLEDEP,
272
273	/* Don't care if the target doesn't exist and can't be created. */
274	OP_OPTIONAL	= 1 << 3,
275	/* Use associated commands for parents. */
276	OP_USE		= 1 << 4,
277	/*
278	 * Target is never out of date, but always execute commands anyway.
279	 * Its time doesn't matter, so it has none...sort of.
280	 */
281	OP_EXEC		= 1 << 5,
282	/*
283	 * Ignore non-zero exit status from shell commands when creating the
284	 * node.
285	 */
286	OP_IGNORE	= 1 << 6,
287	/* Don't remove the target when interrupted. */
288	OP_PRECIOUS	= 1 << 7,
289	/* Don't echo commands when executed. */
290	OP_SILENT	= 1 << 8,
291	/*
292	 * Target is a recursive make so its commands should always be
293	 * executed when it is out of date, regardless of the state of the -n
294	 * or -t flags.
295	 */
296	OP_MAKE		= 1 << 9,
297	/*
298	 * Target is out-of-date only if any of its children was out-of-date.
299	 */
300	OP_JOIN		= 1 << 10,
301	/* Assume the children of the node have been already made. */
302	OP_MADE		= 1 << 11,
303	/* Special .BEGIN, .END or .INTERRUPT. */
304	OP_SPECIAL	= 1 << 12,
305	/* Like .USE, only prepend commands. */
306	OP_USEBEFORE	= 1 << 13,
307	/*
308	 * The node is invisible to its parents. I.e. it doesn't show up in
309	 * the parents' local variables (.IMPSRC, .ALLSRC).
310	 */
311	OP_INVISIBLE	= 1 << 14,
312	/*
313	 * The node does not become the main target, even if it is the first
314	 * target in the first makefile.
315	 */
316	OP_NOTMAIN	= 1 << 15,
317	/* Not a file target; run always. */
318	OP_PHONY	= 1 << 16,
319	/* Don't search for the file in the path. */
320	OP_NOPATH	= 1 << 17,
321	/*
322	 * In a dependency line "target: source1 .WAIT source2", source1 is
323	 * made first, including its children.  Once that is finished,
324	 * source2 is made, including its children.  The .WAIT keyword may
325	 * appear more than once in a single dependency declaration.
326	 */
327	OP_WAIT		= 1 << 18,
328	/* .NOMETA do not create a .meta file */
329	OP_NOMETA	= 1 << 19,
330	/* .META we _do_ want a .meta file */
331	OP_META		= 1 << 20,
332	/* Do not compare commands in .meta file */
333	OP_NOMETA_CMP	= 1 << 21,
334	/* Possibly a submake node */
335	OP_SUBMAKE	= 1 << 22,
336
337	/* Attributes applied by PMake */
338
339	/* The node is a transformation rule, such as ".c.o". */
340	OP_TRANSFORM	= 1 << 30,
341	/* Target is a member of an archive */
342	/* XXX: How does this differ from OP_ARCHV? */
343	OP_MEMBER	= 1 << 29,
344	/*
345	 * The node is a library, its name has the form "-l<libname>".
346	 */
347	OP_LIB		= 1 << 28,
348	/*
349	 * The node is an archive member, its name has the form
350	 * "archive(member)".
351	 */
352	/* XXX: How does this differ from OP_MEMBER? */
353	OP_ARCHV	= 1 << 27,
354	/*
355	 * Target has all the commands it should. Used when parsing to catch
356	 * multiple command groups for a target.  Only applies to the
357	 * dependency operators ':' and '!', but not to '::'.
358	 */
359	OP_HAS_COMMANDS	= 1 << 26,
360	/*
361	 * The special command "..." has been seen. All further commands from
362	 * this node will be saved on the .END node instead, to be executed
363	 * at the very end.
364	 */
365	OP_SAVE_CMDS	= 1 << 25,
366	/*
367	 * Already processed by Suff_FindDeps, to find dependencies from
368	 * suffix transformation rules.
369	 */
370	OP_DEPS_FOUND	= 1 << 24,
371	/* Node found while expanding .ALLSRC */
372	OP_MARK		= 1 << 23
373} GNodeType;
374
375typedef struct GNodeFlags {
376	/* this target needs to be (re)made */
377	bool remake:1;
378	/* children of this target were made */
379	bool childMade:1;
380	/* children don't exist, and we pretend made */
381	bool force:1;
382	/* Set by Make_ProcessWait() */
383	bool doneWait:1;
384	/* Build requested by .ORDER processing */
385	bool doneOrder:1;
386	/* Node created from .depend */
387	bool fromDepend:1;
388	/* We do it once only */
389	bool doneAllsrc:1;
390	/* Used by MakePrintStatus */
391	bool cycle:1;
392	/* Used by MakePrintStatus */
393	bool doneCycle:1;
394} GNodeFlags;
395
396typedef struct List StringList;
397typedef struct ListNode StringListNode;
398
399typedef struct List GNodeList;
400typedef struct ListNode GNodeListNode;
401
402typedef struct SearchPath {
403	List /* of CachedDir */ dirs;
404} SearchPath;
405
406/*
407 * A graph node represents a target that can possibly be made, including its
408 * relation to other targets.
409 */
410typedef struct GNode {
411	/* The target's name, such as "clean" or "make.c" */
412	char *name;
413	/* The unexpanded name of a .USE node */
414	char *uname;
415	/*
416	 * The full pathname of the file belonging to the target.
417	 *
418	 * XXX: What about .PHONY targets? These don't have an associated
419	 * path.
420	 */
421	char *path;
422
423	/*
424	 * The type of operator used to define the sources (see the OP flags
425	 * below).
426	 *
427	 * XXX: This looks like a wild mixture of type and flags.
428	 */
429	GNodeType type;
430	GNodeFlags flags;
431
432	/* The state of processing on this node */
433	GNodeMade made;
434	/* The number of unmade children */
435	int unmade;
436
437	/*
438	 * The modification time; 0 means the node does not have a
439	 * corresponding file; see GNode_IsOODate.
440	 */
441	time_t mtime;
442	struct GNode *youngestChild;
443
444	/*
445	 * The GNodes for which this node is an implied source. May be empty.
446	 * For example, when there is an inference rule for .c.o, the node
447	 * for file.c has the node for file.o in this list.
448	 */
449	GNodeList implicitParents;
450
451	/*
452	 * The nodes that depend on this one, or in other words, the nodes
453	 * for which this is a source.
454	 */
455	GNodeList parents;
456	/* The nodes on which this one depends. */
457	GNodeList children;
458
459	/*
460	 * .ORDER nodes we need made. The nodes that must be made (if they're
461	 * made) before this node can be made, but that do not enter into the
462	 * datedness of this node.
463	 */
464	GNodeList order_pred;
465	/*
466	 * .ORDER nodes who need us. The nodes that must be made (if they're
467	 * made at all) after this node is made, but that do not depend on
468	 * this node, in the normal sense.
469	 */
470	GNodeList order_succ;
471
472	/*
473	 * Other nodes of the same name, for targets that were defined using
474	 * the '::' dependency operator (OP_DOUBLEDEP).
475	 */
476	GNodeList cohorts;
477	/* The "#n" suffix for this cohort, or "" for other nodes */
478	char cohort_num[8];
479	/* The number of unmade instances on the cohorts list */
480	int unmade_cohorts;
481	/*
482	 * Pointer to the first instance of a '::' node; only set when on a
483	 * cohorts list
484	 */
485	struct GNode *centurion;
486
487	/* Last time (sequence number) we tried to make this node */
488	unsigned int checked_seqno;
489
490	/*
491	 * The "local" variables that are specific to this target and this
492	 * target only, such as $@, $<, $?.
493	 *
494	 * Also used for the global variable scopes SCOPE_GLOBAL,
495	 * SCOPE_CMDLINE, SCOPE_INTERNAL, which contain variables with
496	 * arbitrary names.
497	 */
498	HashTable /* of Var pointer */ vars;
499
500	/* The commands to be given to a shell to create this target. */
501	StringList commands;
502
503	/*
504	 * Suffix for the node (determined by Suff_FindDeps and opaque to
505	 * everyone but the Suff module)
506	 */
507	struct Suffix *suffix;
508
509	/* Filename where the GNode got defined, unlimited lifetime */
510	const char *fname;
511	/* Line number where the GNode got defined, 1-based */
512	unsigned lineno;
513	int exit_status;
514} GNode;
515
516/*
517 * Keep track of whether to include <posix.mk> when parsing the line
518 * '.POSIX:'.
519 */
520extern enum PosixState {
521	PS_NOT_YET,
522	PS_MAYBE_NEXT_LINE,
523	PS_NOW_OR_NEVER,
524	PS_TOO_LATE
525} posix_state;
526
527/* Error levels for diagnostics during parsing. */
528typedef enum ParseErrorLevel {
529	/*
530	 * Exit when the current top-level makefile has been parsed
531	 * completely.
532	 */
533	PARSE_FATAL = 1,
534	/* Print "warning"; may be upgraded to fatal by the -w option. */
535	PARSE_WARNING,
536	/* Informational, mainly used during development of makefiles. */
537	PARSE_INFO
538} ParseErrorLevel;
539
540/*
541 * Values returned by Cond_EvalLine and Cond_EvalCondition.
542 */
543typedef enum CondResult {
544	CR_TRUE,		/* Parse the next lines */
545	CR_FALSE,		/* Skip the next lines */
546	CR_ERROR		/* Unknown directive or parse error */
547} CondResult;
548
549typedef struct {
550	enum GuardKind {
551		GK_VARIABLE,
552		GK_TARGET
553	} kind;
554	char *name;
555} Guard;
556
557/* Names of the variables that are "local" to a specific target. */
558#define TARGET	"@"		/* Target of dependency */
559#define OODATE	"?"		/* All out-of-date sources */
560#define ALLSRC	">"		/* All sources */
561#define IMPSRC	"<"		/* Source implied by transformation */
562#define PREFIX	"*"		/* Common prefix */
563#define ARCHIVE	"!"		/* Archive in "archive(member)" syntax */
564#define MEMBER	"%"		/* Member in "archive(member)" syntax */
565
566/*
567 * Global Variables
568 */
569
570/* True if every target is precious */
571extern bool allPrecious;
572/* True if failed targets should be deleted */
573extern bool deleteOnError;
574/* true while processing .depend */
575extern bool doing_depend;
576/* .DEFAULT rule */
577extern GNode *defaultNode;
578
579/*
580 * Variables defined internally by make which should not override those set
581 * by makefiles.
582 */
583extern GNode *SCOPE_INTERNAL;
584/* Variables defined in a global scope, e.g in the makefile itself. */
585extern GNode *SCOPE_GLOBAL;
586/* Variables defined on the command line. */
587extern GNode *SCOPE_CMDLINE;
588
589/*
590 * Value returned by Var_Parse when an error is encountered. It points to an
591 * empty string, so naive callers needn't worry about it.
592 */
593extern char var_Error[];
594
595/* The time at the start of this whole process */
596extern time_t now;
597
598/*
599 * The list of directories to search when looking for targets (set by the
600 * special target .PATH).
601 */
602extern SearchPath dirSearchPath;
603/* Used for .include "...". */
604extern SearchPath *parseIncPath;
605/*
606 * Used for .include <...>, for the built-in sys.mk and for makefiles from
607 * the command line arguments.
608 */
609extern SearchPath *sysIncPath;
610/* The default for sysIncPath. */
611extern SearchPath *defSysIncPath;
612
613/* Startup directory */
614extern char curdir[];
615/* The basename of the program name, suffixed with [n] for sub-makes.  */
616extern const char *progname;
617extern int makelevel;
618/* Name of the .depend makefile */
619extern char *makeDependfile;
620/* If we replaced environ, this will be non-NULL. */
621extern char **savedEnv;
622extern GNode *mainNode;
623
624extern pid_t myPid;
625
626#define MAKEFLAGS	".MAKEFLAGS"
627#ifndef MAKE_LEVEL_ENV
628# define MAKE_LEVEL_ENV	"MAKELEVEL"
629#endif
630
631typedef struct DebugFlags {
632	bool DEBUG_ARCH:1;
633	bool DEBUG_COND:1;
634	bool DEBUG_CWD:1;
635	bool DEBUG_DIR:1;
636	bool DEBUG_ERROR:1;
637	bool DEBUG_FOR:1;
638	bool DEBUG_GRAPH1:1;
639	bool DEBUG_GRAPH2:1;
640	bool DEBUG_GRAPH3:1;
641	bool DEBUG_HASH:1;
642	bool DEBUG_JOB:1;
643	bool DEBUG_LOUD:1;
644	bool DEBUG_MAKE:1;
645	bool DEBUG_META:1;
646	bool DEBUG_PARSE:1;
647	bool DEBUG_SCRIPT:1;
648	bool DEBUG_SHELL:1;
649	bool DEBUG_SUFF:1;
650	bool DEBUG_TARG:1;
651	bool DEBUG_VAR:1;
652} DebugFlags;
653
654#define CONCAT(a, b) a##b
655
656#define DEBUG(module) (opts.debug.CONCAT(DEBUG_, module))
657
658void debug_printf(const char *, ...) MAKE_ATTR_PRINTFLIKE(1, 2);
659
660#define DEBUG_IMPL(module, args) \
661	do { \
662		if (DEBUG(module)) \
663			debug_printf args; \
664	} while (false)
665
666#define DEBUG0(module, fmt) \
667	DEBUG_IMPL(module, (fmt))
668#define DEBUG1(module, fmt, arg1) \
669	DEBUG_IMPL(module, (fmt, arg1))
670#define DEBUG2(module, fmt, arg1, arg2) \
671	DEBUG_IMPL(module, (fmt, arg1, arg2))
672#define DEBUG3(module, fmt, arg1, arg2, arg3) \
673	DEBUG_IMPL(module, (fmt, arg1, arg2, arg3))
674#define DEBUG4(module, fmt, arg1, arg2, arg3, arg4) \
675	DEBUG_IMPL(module, (fmt, arg1, arg2, arg3, arg4))
676#define DEBUG5(module, fmt, arg1, arg2, arg3, arg4, arg5) \
677	DEBUG_IMPL(module, (fmt, arg1, arg2, arg3, arg4, arg5))
678
679typedef enum PrintVarsMode {
680	PVM_NONE,
681	PVM_UNEXPANDED,
682	PVM_EXPANDED
683} PrintVarsMode;
684
685/* Command line options */
686typedef struct CmdOpts {
687	/* -B: whether to be compatible to traditional make */
688	bool compatMake;
689
690	/*
691	 * -d: debug control: There is one flag per module.  It is up to the
692	 * module what debug information to print.
693	 */
694	DebugFlags debug;
695
696	/* -df: debug output is written here - default stderr */
697	FILE *debug_file;
698
699	/*
700	 * -dL: lint mode
701	 *
702	 * Runs make in strict mode, with additional checks and better error
703	 * handling.
704	 */
705	bool strict;
706
707	/* -dV: for the -V option, print unexpanded variable values */
708	bool debugVflag;
709
710	/* -e: check environment variables before global variables */
711	bool checkEnvFirst;
712
713	/* -f: the makefiles to read */
714	StringList makefiles;
715
716	/* -i: if true, ignore all errors from shell commands */
717	bool ignoreErrors;
718
719	/*
720	 * -j: the maximum number of jobs that can run in parallel; this is
721	 * coordinated with the submakes
722	 */
723	int maxJobs;
724
725	/*
726	 * -k: if true and an error occurs while making a node, continue
727	 * making nodes that do not depend on the erroneous node
728	 */
729	bool keepgoing;
730
731	/* -N: execute no commands from the targets */
732	bool noRecursiveExecute;
733
734	/* -n: execute almost no commands from the targets */
735	bool noExecute;
736
737	/*
738	 * -q: if true, do not really make anything, just see if the targets
739	 * are out-of-date
740	 */
741	bool query;
742
743	/* -r: raw mode, do not load the builtin rules. */
744	bool noBuiltins;
745
746	/* -s: don't echo the shell commands before executing them */
747	bool silent;
748
749	/*
750	 * -t: touch the targets if they are out-of-date, but don't actually
751	 * make them
752	 */
753	bool touch;
754
755	/* -[Vv]: print expanded or unexpanded selected variables */
756	PrintVarsMode printVars;
757	/* -[Vv]: the variables to print */
758	StringList variables;
759
760	/* -W: if true, makefile parsing warnings are treated as errors */
761	bool parseWarnFatal;
762
763	/* -w: print 'Entering' and 'Leaving' for submakes */
764	bool enterFlag;
765
766	/*
767	 * -X: if true, do not export variables set on the command line to
768	 * the environment.
769	 */
770	bool varNoExportEnv;
771
772	/*
773	 * The target names specified on the command line. Used to resolve
774	 * .if make(...) statements.
775	 */
776	StringList create;
777
778	/*
779	 * Randomize the order in which the targets from toBeMade are made,
780	 * to catch undeclared dependencies.
781	 */
782	bool randomizeTargets;
783} CmdOpts;
784
785extern CmdOpts opts;
786extern bool forceJobs;
787extern char **environ;
788
789/* arch.c */
790void Arch_Init(void);
791void Arch_End(void);
792
793bool Arch_ParseArchive(char **, GNodeList *, GNode *);
794void Arch_Touch(GNode *);
795void Arch_TouchLib(GNode *);
796void Arch_UpdateMTime(GNode *);
797void Arch_UpdateMemberMTime(GNode *);
798void Arch_FindLib(GNode *, SearchPath *);
799bool Arch_LibOODate(GNode *) MAKE_ATTR_USE;
800bool Arch_IsLib(GNode *) MAKE_ATTR_USE;
801
802/* compat.c */
803bool Compat_RunCommand(const char *, GNode *, StringListNode *);
804void Compat_MakeAll(GNodeList *);
805void Compat_Make(GNode *, GNode *);
806
807/* cond.c */
808extern unsigned int cond_depth;
809CondResult Cond_EvalCondition(const char *) MAKE_ATTR_USE;
810CondResult Cond_EvalLine(const char *) MAKE_ATTR_USE;
811Guard *Cond_ExtractGuard(const char *) MAKE_ATTR_USE;
812void Cond_EndFile(void);
813
814/* dir.c; see also dir.h */
815
816MAKE_INLINE const char * MAKE_ATTR_USE
817str_basename(const char *pathname)
818{
819	const char *lastSlash = strrchr(pathname, '/');
820	return lastSlash != NULL ? lastSlash + 1 : pathname;
821}
822
823MAKE_INLINE SearchPath * MAKE_ATTR_USE
824SearchPath_New(void)
825{
826	SearchPath *path = bmake_malloc(sizeof *path);
827	Lst_Init(&path->dirs);
828	return path;
829}
830
831void SearchPath_Free(SearchPath *);
832
833/* for.c */
834struct ForLoop;
835int For_Eval(const char *) MAKE_ATTR_USE;
836bool For_Accum(const char *, int *) MAKE_ATTR_USE;
837void For_Run(unsigned, unsigned);
838bool For_NextIteration(struct ForLoop *, Buffer *);
839char *ForLoop_Details(const struct ForLoop *);
840void ForLoop_Free(struct ForLoop *);
841void For_Break(struct ForLoop *);
842
843/* job.c */
844void JobReapChild(pid_t, int, bool);
845
846/* main.c */
847void Main_ParseArgLine(const char *);
848char *Cmd_Exec(const char *, char **) MAKE_ATTR_USE;
849void Error(const char *, ...) MAKE_ATTR_PRINTFLIKE(1, 2);
850void Fatal(const char *, ...) MAKE_ATTR_PRINTFLIKE(1, 2) MAKE_ATTR_DEAD;
851void Punt(const char *, ...) MAKE_ATTR_PRINTFLIKE(1, 2) MAKE_ATTR_DEAD;
852void DieHorribly(void) MAKE_ATTR_DEAD;
853void Finish(int) MAKE_ATTR_DEAD;
854int unlink_file(const char *) MAKE_ATTR_USE;
855void execDie(const char *, const char *);
856char *getTmpdir(void) MAKE_ATTR_USE;
857bool ParseBoolean(const char *, bool) MAKE_ATTR_USE;
858const char *cached_realpath(const char *, char *);
859bool GetBooleanExpr(const char *, bool);
860
861/* parse.c */
862void Parse_Init(void);
863void Parse_End(void);
864
865void PrintLocation(FILE *, bool, const GNode *);
866void PrintStackTrace(bool);
867void Parse_Error(ParseErrorLevel, const char *, ...) MAKE_ATTR_PRINTFLIKE(2, 3);
868bool Parse_VarAssign(const char *, bool, GNode *) MAKE_ATTR_USE;
869void Parse_File(const char *, int);
870void Parse_PushInput(const char *, unsigned, unsigned, Buffer,
871		     struct ForLoop *);
872void Parse_MainName(GNodeList *);
873int Parse_NumErrors(void) MAKE_ATTR_USE;
874unsigned int CurFile_CondMinDepth(void) MAKE_ATTR_USE;
875void Parse_GuardElse(void);
876void Parse_GuardEndif(void);
877
878
879/* suff.c */
880void Suff_Init(void);
881void Suff_End(void);
882
883void Suff_ClearSuffixes(void);
884bool Suff_IsTransform(const char *) MAKE_ATTR_USE;
885GNode *Suff_AddTransform(const char *);
886void Suff_EndTransform(GNode *);
887void Suff_AddSuffix(const char *);
888SearchPath *Suff_GetPath(const char *) MAKE_ATTR_USE;
889void Suff_ExtendPaths(void);
890void Suff_AddInclude(const char *);
891void Suff_AddLib(const char *);
892void Suff_FindDeps(GNode *);
893SearchPath *Suff_FindPath(GNode *) MAKE_ATTR_USE;
894void Suff_SetNull(const char *);
895void Suff_PrintAll(void);
896char *Suff_NamesStr(void) MAKE_ATTR_USE;
897
898/* targ.c */
899void Targ_Init(void);
900void Targ_End(void);
901
902void Targ_Stats(void);
903GNodeList *Targ_List(void) MAKE_ATTR_USE;
904GNode *GNode_New(const char *) MAKE_ATTR_USE;
905GNode *Targ_FindNode(const char *) MAKE_ATTR_USE;
906GNode *Targ_GetNode(const char *) MAKE_ATTR_USE;
907GNode *Targ_NewInternalNode(const char *) MAKE_ATTR_USE;
908GNode *Targ_GetEndNode(void);
909void Targ_FindList(GNodeList *, StringList *);
910void Targ_PrintCmds(GNode *);
911void Targ_PrintNode(GNode *, int);
912void Targ_PrintNodes(GNodeList *, int);
913const char *Targ_FmtTime(time_t) MAKE_ATTR_USE;
914void Targ_PrintType(GNodeType);
915void Targ_PrintGraph(int);
916void Targ_Propagate(void);
917const char *GNodeMade_Name(GNodeMade) MAKE_ATTR_USE;
918#ifdef CLEANUP
919void Parse_RegisterCommand(char *);
920#else
921/* ARGSUSED */
922MAKE_INLINE
923void Parse_RegisterCommand(char *cmd MAKE_ATTR_UNUSED)
924{
925}
926#endif
927
928/* var.c */
929void Var_Init(void);
930void Var_End(void);
931
932typedef enum VarEvalMode {
933
934	/*
935	 * Only parse the expression but don't evaluate any part of it.
936	 *
937	 * TODO: Document what Var_Parse and Var_Subst return in this mode.
938	 *  As of 2021-03-15, they return unspecified, inconsistent results.
939	 */
940	VARE_PARSE_ONLY,
941
942	/*
943	 * Parse text in which '${...}' and '$(...)' are not parsed as
944	 * subexpressions (with all their individual escaping rules) but
945	 * instead simply as text with balanced '${}' or '$()'.  Other '$'
946	 * are copied verbatim.
947	 */
948	VARE_PARSE_BALANCED,
949
950	/* Parse and evaluate the expression. */
951	VARE_WANTRES,
952
953	/*
954	 * Parse and evaluate the expression.  It is an error if a
955	 * subexpression evaluates to undefined.
956	 */
957	VARE_UNDEFERR,
958
959	/*
960	 * Parse and evaluate the expression.  Keep undefined variables as-is
961	 * instead of expanding them to an empty string.
962	 *
963	 * Example for a ':=' assignment:
964	 *	CFLAGS = $(.INCLUDES)
965	 *	CFLAGS := -I.. $(CFLAGS)
966	 *	# If .INCLUDES (an undocumented special variable, by the
967	 *	# way) is still undefined, the updated CFLAGS becomes
968	 *	# "-I.. $(.INCLUDES)".
969	 */
970	VARE_EVAL_KEEP_UNDEF,
971
972	/*
973	 * Parse and evaluate the expression.  Keep '$$' as '$$' and preserve
974	 * undefined subexpressions.
975	 */
976	VARE_KEEP_DOLLAR_UNDEF
977} VarEvalMode;
978
979typedef enum VarSetFlags {
980	VAR_SET_NONE		= 0,
981
982	/* do not export */
983	VAR_SET_NO_EXPORT	= 1 << 0,
984
985	/*
986	 * Make the variable read-only. No further modification is possible,
987	 * except for another call to Var_Set with the same flag. See the
988	 * special targets '.NOREADONLY' and '.READONLY'.
989	 */
990	VAR_SET_READONLY	= 1 << 1,
991	VAR_SET_INTERNAL	= 1 << 2
992} VarSetFlags;
993
994typedef enum VarExportMode {
995	/* .export-all */
996	VEM_ALL,
997	/* .export-env */
998	VEM_ENV,
999	/* .export: Initial export or update an already exported variable. */
1000	VEM_PLAIN,
1001	/* .export-literal: Do not expand the variable value. */
1002	VEM_LITERAL
1003} VarExportMode;
1004
1005void Var_Delete(GNode *, const char *);
1006#ifdef CLEANUP
1007void Var_DeleteAll(GNode *scope);
1008#endif
1009void Var_Undef(const char *);
1010void Var_Set(GNode *, const char *, const char *);
1011void Var_SetExpand(GNode *, const char *, const char *);
1012void Var_SetWithFlags(GNode *, const char *, const char *, VarSetFlags);
1013void Var_Append(GNode *, const char *, const char *);
1014void Var_AppendExpand(GNode *, const char *, const char *);
1015bool Var_Exists(GNode *, const char *) MAKE_ATTR_USE;
1016bool Var_ExistsExpand(GNode *, const char *) MAKE_ATTR_USE;
1017FStr Var_Value(GNode *, const char *) MAKE_ATTR_USE;
1018const char *GNode_ValueDirect(GNode *, const char *) MAKE_ATTR_USE;
1019FStr Var_Parse(const char **, GNode *, VarEvalMode);
1020char *Var_Subst(const char *, GNode *, VarEvalMode);
1021void Var_Expand(FStr *, GNode *, VarEvalMode);
1022void Var_Stats(void);
1023void Var_Dump(GNode *);
1024void Var_ReexportVars(GNode *);
1025void Var_Export(VarExportMode, const char *);
1026void Var_ExportVars(const char *);
1027void Var_UnExport(bool, const char *);
1028void Var_ReadOnly(const char *, bool);
1029
1030void Global_Set(const char *, const char *);
1031void Global_Append(const char *, const char *);
1032void Global_Delete(const char *);
1033void Global_Set_ReadOnly(const char *, const char *);
1034
1035void EvalStack_Push(const char *, const char *, const char *);
1036void EvalStack_Pop(void);
1037const char *EvalStack_Details(void);
1038
1039/* util.c */
1040typedef void (*SignalProc)(int);
1041SignalProc bmake_signal(int, SignalProc);
1042
1043/* make.c */
1044void GNode_UpdateYoungestChild(GNode *, GNode *);
1045bool GNode_IsOODate(GNode *) MAKE_ATTR_USE;
1046void Make_ExpandUse(GNodeList *);
1047time_t Make_Recheck(GNode *) MAKE_ATTR_USE;
1048void Make_HandleUse(GNode *, GNode *);
1049void Make_Update(GNode *);
1050void GNode_SetLocalVars(GNode *);
1051bool Make_Run(GNodeList *);
1052bool shouldDieQuietly(GNode *, int) MAKE_ATTR_USE;
1053void PrintOnError(GNode *, const char *);
1054void Main_ExportMAKEFLAGS(bool);
1055bool Main_SetObjdir(bool, const char *, ...) MAKE_ATTR_PRINTFLIKE(2, 3);
1056int mkTempFile(const char *, char *, size_t) MAKE_ATTR_USE;
1057void AppendWords(StringList *, char *);
1058void GNode_FprintDetails(FILE *, const char *, const GNode *, const char *);
1059bool GNode_ShouldExecute(GNode *gn) MAKE_ATTR_USE;
1060
1061/* See if the node was seen on the left-hand side of a dependency operator. */
1062MAKE_INLINE bool MAKE_ATTR_USE
1063GNode_IsTarget(const GNode *gn)
1064{
1065	return (gn->type & OP_OPMASK) != OP_NONE;
1066}
1067
1068MAKE_INLINE const char * MAKE_ATTR_USE
1069GNode_Path(const GNode *gn)
1070{
1071	return gn->path != NULL ? gn->path : gn->name;
1072}
1073
1074MAKE_INLINE bool MAKE_ATTR_USE
1075GNode_IsWaitingFor(const GNode *gn)
1076{
1077	return gn->flags.remake && gn->made <= REQUESTED;
1078}
1079
1080MAKE_INLINE bool MAKE_ATTR_USE
1081GNode_IsReady(const GNode *gn)
1082{
1083	return gn->made > DEFERRED;
1084}
1085
1086MAKE_INLINE bool MAKE_ATTR_USE
1087GNode_IsDone(const GNode *gn)
1088{
1089	return gn->made >= MADE;
1090}
1091
1092MAKE_INLINE bool MAKE_ATTR_USE
1093GNode_IsError(const GNode *gn)
1094{
1095	return gn->made == ERROR || gn->made == ABORTED;
1096}
1097
1098MAKE_INLINE bool MAKE_ATTR_USE
1099GNode_IsMainCandidate(const GNode *gn)
1100{
1101	return (gn->type & (OP_NOTMAIN | OP_USE | OP_USEBEFORE |
1102			    OP_EXEC | OP_TRANSFORM)) == 0;
1103}
1104
1105/* Return whether the target file should be preserved on interrupt. */
1106MAKE_INLINE bool MAKE_ATTR_USE
1107GNode_IsPrecious(const GNode *gn)
1108{
1109	/* XXX: Why are '::' targets precious? */
1110	return allPrecious || gn->type & (OP_PRECIOUS | OP_DOUBLEDEP);
1111}
1112
1113MAKE_INLINE const char * MAKE_ATTR_USE
1114GNode_VarTarget(GNode *gn) { return GNode_ValueDirect(gn, TARGET); }
1115MAKE_INLINE const char * MAKE_ATTR_USE
1116GNode_VarOodate(GNode *gn) { return GNode_ValueDirect(gn, OODATE); }
1117MAKE_INLINE const char * MAKE_ATTR_USE
1118GNode_VarAllsrc(GNode *gn) { return GNode_ValueDirect(gn, ALLSRC); }
1119MAKE_INLINE const char * MAKE_ATTR_USE
1120GNode_VarImpsrc(GNode *gn) { return GNode_ValueDirect(gn, IMPSRC); }
1121MAKE_INLINE const char * MAKE_ATTR_USE
1122GNode_VarPrefix(GNode *gn) { return GNode_ValueDirect(gn, PREFIX); }
1123MAKE_INLINE const char * MAKE_ATTR_USE
1124GNode_VarArchive(GNode *gn) { return GNode_ValueDirect(gn, ARCHIVE); }
1125MAKE_INLINE const char * MAKE_ATTR_USE
1126GNode_VarMember(GNode *gn) { return GNode_ValueDirect(gn, MEMBER); }
1127
1128MAKE_INLINE void * MAKE_ATTR_USE
1129UNCONST(const void *ptr)
1130{
1131	void *ret;
1132	memcpy(&ret, &ptr, sizeof(ret));
1133	return ret;
1134}
1135
1136/* At least GNU/Hurd systems lack hardcoded MAXPATHLEN/PATH_MAX */
1137#include <limits.h>
1138#ifndef MAXPATHLEN
1139#define MAXPATHLEN	4096
1140#endif
1141#ifndef PATH_MAX
1142#define PATH_MAX	MAXPATHLEN
1143#endif
1144
1145#if defined(SYSV)
1146#define KILLPG(pid, sig) kill(-(pid), (sig))
1147#else
1148#define KILLPG(pid, sig) killpg((pid), (sig))
1149#endif
1150
1151MAKE_INLINE bool MAKE_ATTR_USE
1152ch_isalnum(char ch) { return isalnum((unsigned char)ch) != 0; }
1153MAKE_INLINE bool MAKE_ATTR_USE
1154ch_isalpha(char ch) { return isalpha((unsigned char)ch) != 0; }
1155MAKE_INLINE bool MAKE_ATTR_USE
1156ch_isdigit(char ch) { return isdigit((unsigned char)ch) != 0; }
1157MAKE_INLINE bool MAKE_ATTR_USE
1158ch_islower(char ch) { return islower((unsigned char)ch) != 0; }
1159MAKE_INLINE bool MAKE_ATTR_USE
1160ch_isspace(char ch) { return isspace((unsigned char)ch) != 0; }
1161MAKE_INLINE bool MAKE_ATTR_USE
1162ch_isupper(char ch) { return isupper((unsigned char)ch) != 0; }
1163MAKE_INLINE char MAKE_ATTR_USE
1164ch_tolower(char ch) { return (char)tolower((unsigned char)ch); }
1165MAKE_INLINE char MAKE_ATTR_USE
1166ch_toupper(char ch) { return (char)toupper((unsigned char)ch); }
1167
1168MAKE_INLINE void
1169cpp_skip_whitespace(const char **pp)
1170{
1171	while (ch_isspace(**pp))
1172		(*pp)++;
1173}
1174
1175MAKE_INLINE void
1176cpp_skip_hspace(const char **pp)
1177{
1178	while (**pp == ' ' || **pp == '\t')
1179		(*pp)++;
1180}
1181
1182MAKE_INLINE bool
1183cpp_skip_string(const char **pp, const char *s)
1184{
1185	const char *p = *pp;
1186	while (*p == *s && *s != '\0')
1187		p++, s++;
1188	if (*s == '\0')
1189		*pp = p;
1190	return *s == '\0';
1191}
1192
1193MAKE_INLINE void
1194pp_skip_whitespace(char **pp)
1195{
1196	while (ch_isspace(**pp))
1197		(*pp)++;
1198}
1199
1200MAKE_INLINE void
1201pp_skip_hspace(char **pp)
1202{
1203	while (**pp == ' ' || **pp == '\t')
1204		(*pp)++;
1205}
1206
1207#if defined(lint)
1208void do_not_define_rcsid(void); /* for lint */
1209# define MAKE_RCSID(id) void do_not_define_rcsid(void)
1210#elif defined(MAKE_NATIVE)
1211# include <sys/cdefs.h>
1212# define MAKE_RCSID(id) __RCSID(id)
1213#elif defined(MAKE_ALL_IN_ONE) && defined(__COUNTER__)
1214# define MAKE_RCSID_CONCAT(x, y) CONCAT(x, y)
1215# define MAKE_RCSID(id) static volatile char \
1216	MAKE_RCSID_CONCAT(rcsid_, __COUNTER__)[] = id
1217#elif defined(MAKE_ALL_IN_ONE)
1218# define MAKE_RCSID(id) void do_not_define_rcsid(void)
1219#else
1220# define MAKE_RCSID(id) static volatile char rcsid[] = id
1221#endif
1222
1223#endif
1224