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