Index: stable/12/contrib/bmake/ChangeLog =================================================================== --- stable/12/contrib/bmake/ChangeLog (revision 361673) +++ stable/12/contrib/bmake/ChangeLog (revision 361674) @@ -1,2209 +1,2378 @@ +2020-05-17 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200517 + Merge with NetBSD make, pick up + o modified dollar tests to avoid shell dependencies + o new tests for .INCLUDEFROM + +2020-05-16 Simon J Gerraty + + * unit-tests/dollar.mk: tweak '1 dollar literal' test + to not depend so much on shell behavior + +2020-05-10 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200510 + Merge with NetBSD make, pick up + o unit test for dollar handling + +2020-05-06 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200506 + Merge with NetBSD make, pick up + o str.c: empty string does not match % pattern + plus unit-test changes + +2020-05-04 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200504 + May the 4th be with you + Merge with NetBSD make, pick up + o var.c: import handling of old sysV style modifier using '%' + o str.c: refactor brk_string + o unit-tests: add test case for lazy conditions + +2020-04-18 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200418 + + * configure.in: use_makefile=no for cygwin et al. + case insensitive filesystems just don't work if both + makefile and Makefile exist. + NOTE: bmake does not support cygwin and likely never will, + but if brave souls want to try it - help them out. + +2020-04-02 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200402 + Merge with NetBSD make, pick up + o meta.c: meta_oodate, CHECK_VALID_META is too aggressive for CMD + a blank command is perfectly valid. + +2020-03-30 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200330 + Merge with NetBSD make, pick up + o make.h: extern debug_file + +2020-03-18 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200318 + Merge with NetBSD make, pick up + o meta.c: meta_oodate, check for corrupted meta file + earlier and more often. + +2020-02-20 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200220 + +2020-02-19 Simon J Gerraty + + * boot-strap: unset MAKEFLAGS + +2020-02-12 Simon J Gerraty + + * VERSION (_MAKE_VERSION): 20200212 + * meta.c: meta_compat_parent check for USE_FILEMON + patch from Soeren Tempel + +2020-02-05 Simon J Gerraty + + * VERSION: 20200205 + Merge with NetBSD make, pick up + o meta.c: fix compat mode, need to call meta_job_output() + o job.c: extra fds for meta mode not needed if using filemon_dev + +2020-01-22 Simon J Gerraty + + * VERSION: 20200122 + Merge with NetBSD make, pick up + o meta.c: avoid passing NULL to filemon_*() when meta_needed() + returns FALSE. + +2020-01-21 Simon J Gerraty + + * VERSION: 20200121 + Merge with NetBSD make, pick up + o filemon/filemon_{dev,ktrace}.c: allow selection of + filemon implementation. filemon_dev.c uses the kernel module + while filemon_ktrace.c leverages the fktrace api available in + NetBSD. filemon_ktrace.c can hopefully form the basis for + adding support for other tracing mechanisms such as strace on + Linux. + o meta.c: when target is out-of-date per normal make rules + record value of .OODATE in meta file. + +2019-09-26 Simon J Gerraty + + * VERSION: 20190926 + Merge with NetBSD make, pick up + o parse.c: don't pass NULL to realpath(3) + some versions cannot handle it. + +2019-04-09 Simon J Gerraty + + * VERSION: 20190409 + Merge with NetBSD make, pick up + o parse.c: ParseDoDependency: free paths rather than assert + +2018-12-22 Simon J Gerraty + + * VERSION: 20181222 + + * configure.in: add --without-makefile to avoid generating + makefile and make-bootstrap.sh + + * include Makefile.inc if it exists + + * Use Makefile and Makefile.config.in in unit-tests + so we can use just: make obj && make && make test + when bmake is already available. + We add --without-makefile to CONFIGURE_ARGS in this case. + + * tweak bsd.after-import.mk (captures Makefile.config etc + after import to FreeBSD for example) to cope with all the above. + +2018-12-21 Simon J Gerraty + + * VERSION: 20181221 + Merge with NetBSD make, pick up + o parse.c: ParseVErrorInternal use .PARSEDIR + and apply if relative, and then use .PARSEFILE + for consistent result. + +2018-12-20 Simon J Gerraty + + * VERSION: 20181220 + Merge with NetBSD make, pick up + o parse.c: ParseVErrorInternal use .CURDIR if .PARSEDIR + is relative + o var.c: avoid SEGFAULT in .unexport-env + when MAKELEVEL is not set + +2018-12-16 Simon J Gerraty + + * VERSION: 20181216 + Merge with NetBSD make, pick up + o fix for unit-tests/varquote.mk on Debian + +2018-09-21 Simon J. Gerraty + + * VERSION: 20180919 + Merge with NetBSD make, pick up + o var.c: add :q + o dir.c: cleanup caching of stats + +2018-09-21 Simon J Gerraty + + * Makefile.config.in: use += where it makes sense. + 2018-05-12 Simon J. Gerraty * VERSION: 20180512 Merge with NetBSD make, pick up o job.c: skip polling job token pipe 2018-04-05 Simon J. Gerraty * VERSION: 20180405 Merge with NetBSD make, pick up o parse.c: be more cautious about detecting depenency line rather than sysV style include. 2018-02-22 Simon J. Gerraty * VERSION: 20180222 Merge with NetBSD make, pick up o parse.c: avoid calling sysconf for every call to loadfile 2018-02-18 Simon J. Gerraty * VERSION: 20180218 Merge with NetBSD make, pick up o var.c: Var_Set handle NULL value anytime. 2018-02-12 Simon J. Gerraty * VERSION: 20180212 Merge with NetBSD make, pick up o parse.c: do not treat .info as warning with -W 2017-12-07 Simon J. Gerraty * VERSION: 20171207 Merge with NetBSD make, pick up o var.c: Var_Append use Var_Set if var not previously set so that VAR_CMD is handled correctly. Add a suitable unit-test. 2017-11-26 Simon J. Gerraty * VERSION (_MAKE_VERSION): 20171126 * aclocal.m4: use AC_LINK_IFELSE for AC_C___ATTRIBUTE__ since AC_TRY_COMPILE puts input inside main() which upsets modern compilers. 2017-11-18 Simon J. Gerraty * VERSION: 20171118 Merge with NetBSD make, pick up o var.c: do not append to variable set on command line add unit-test to catch this. 2017-10-28 Simon J. Gerraty * VERSION: 20171028 Merge with NetBSD make, pick up o main.c: ignore empty MAKEOBJDIR * Makefile.config.in: make @prefix@ @machine*@ and @default_sys_path@ defaults. 2017-10-05 Simon J. Gerraty * VERSION: 20171005 * unit-tests/dotwait.mk: redirect stderr through pipe for more consistent result on some platforms. 2017-08-13 Simon J. Gerraty * machine.sh: entry for AIX 2017-08-12 Simon J. Gerraty * VERSION (_MAKE_VERSION): Move the setting of _MAKE_VERSION to a file that can be included by configure as well as make. This allows configure to set set _MAKE_VERSION in make-bootstrap.sh 2017-08-10 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170810 Merge with NetBSD make, pick up o meta.c: if target is in subdir we only need subdir name in meta_name. 2017-07-20 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170720 Merge with NetBSD make, pick up o compat.c: pass SIGINT etc onto child and wait for it to exit before we self-terminate. 2017-07-11 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170711 forgot to update after merge on 20170708 ;-) o main.c: refactor to reduce size of main function. add -v option to always fully expand values. o meta.c: ensure command output in meta file has ending newline even when filemon not being used. When matching ${.MAKE.META.IGNORE_PATTERNS} do not use pathname via ':L' since any ':' in pathname breaks that. Instead set a '${.p.}' to pathname in the target context and use that. 2017-05-10 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170510 Merge with NetBSD make, pick up o main.c: Main_SetObjdir: ensure buf2 is in scope 2017-05-08 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170505 see mk/ChangeLog 2017-05-05 Simon J. Gerraty * parse.c: not everyone has stdint.h 2017-05-01 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170501 see mk/ChangeLog 2017-04-21 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170421 Merge with NetBSD make, pick up o str.c: Str_Match: fix closure tests for [^] and add unit-test. 2017-04-20 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170420 Merge with NetBSD make, pick up o main.c: only use -C arg "as is" if it contains no relative component. 2017-04-18 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170418 Merge with NetBSD make, pick up o main.c: fix Main_SetObjdir() for relative paths (eg obj). 2017-04-17 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170417 Merge with NetBSD make, pick up o fixes a number of coverity complaints - check return value of fseek, fcntl - plug memory leak in Dir_FindFile, Var_LoopExpand, JobPrintCommand, ParseTraditionalInclude - use bmake_malloc() where NULL is not tollerated - use MAKE_ATTR_UNUSED rather that kludges like return(unused ? 0 : 0) - use purge_cached_realpaths() rather than abuse cached_realpath() 2017-04-13 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170413 Merge with NetBSD make, pick up o main.c: when setting .OBJDIR ignore '$' in paths. * job.c: use MALLOC_OPTIONS to set malloc_options. 2017-04-11 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170411 Merge with NetBSD make, pick up o str.c: Str_Match: allow [^a-z] to behave as expected. 2017-03-26 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170326 Merge with NetBSD make, pick up o main.c: purge relative paths from realpath cache when .OBJDIR is changed. 2017-03-11 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170311 Merge with NetBSD make, pick up o main.c: only use -C arg "as is" if it starts with '/'. 2017-03-01 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170301 Merge with NetBSD make, pick up o main.c: use -C arg "as is" rather than getcwd() if they identify the same directory. o parse.c: ensure loadfile buffer is \n terminated in non-mmap case 2017-02-01 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170201 Merge with NetBSD make, pick up o var.c: allow :_=var and avoid use of special context. 2017-01-30 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170130 Merge with NetBSD make, pick up o var.c: add :range and :_ o main.c: partially initialize Dir_* before MainParseArgs() can be called. If -V, skip Main_ExportMAKEFLAGS() 2017-01-14 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20170114 Merge with NetBSD make, pick up o var.c: allow specifying the utc value used by :{gm,local}time 2016-12-12 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20161212 Merge with NetBSD make, pick up o main.c: look for obj.${MACHINE}-${MACHINE_ARCH} too. 2016-12-09 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20161209 Merge with NetBSD make, pick up o main.c: cleanup setting of .OBJDIR o parse.c: avoid coredump from (var)=val 2016-11-26 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20161126 Merge with NetBSD make, pick up o make.c: Make_OODate: report src node name if path not set 2016-09-26 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160926 Merge with NetBSD make, pick up o support for .DELETE_ON_ERROR: (remove targets that fail) 2016-09-26 Simon J. Gerraty * Makefile MAN: tweak .Dt to match ${PROG} 2016-08-18 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160818 its a neater number; pick up whitespace fixes to man page. 2016-08-17 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160817 Merge with NetBSD make, pick up o meta.c: move handling of .MAKE.META.IGNORE_* to meta_ignore() so we can call it before adding entries to missingFiles. Thus we do not track files we have been told to ignore. 2016-08-15 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160815 Merge with NetBSD make, pick up o meta_oodate: apply .MAKE.META.IGNORE_FILTER (if defined) to pathnames, and skip if the expansion is empty. Useful for dirdeps.mk when checking DIRDEPS_CACHE. 2016-08-12 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160812 Merge with NetBSD make, pick up o meta.c: remove all missingFiles entries that match a deleted dir. o main.c: set .ERROR_CMD if possible. 2016-06-06 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160606 Merge with NetBSD make, pick up o dir.c: extend mtimes cache to others via cached_stat() 2016-06-04 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160604 Merge with NetBSD make, pick up o meta.c: missing filemon data is only relevant if we read a meta file. Also do not return oodate for a missing metafile if gn->path points to .CURDIR 2016-06-02 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160602 Merge with NetBSD make, pick up o cached_realpath(): avoid hitting filesystem more than necessary. o meta.c: refactor need_meta decision, add knobs for missing meta file and filemon data wrt out-of-datedness. 2016-05-28 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160528 * boot-strap, make-bootstrap.sh.in: Makefile now uses _MAKE_VERSION 2016-05-12 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160512 Merge with NetBSD make, pick up o meta.c: ignore paths that match .MAKE.META.IGNORE_PATTERNS this is useful for gcov builds. o propagate errors from filemon(4). 2016-05-09 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160509 Merge with NetBSD make, pick up o remove use of non-standard types u_int etc. o meta.c: apply realpath() before matching against metaIgnorePaths 2016-04-04 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160404 Merge with NetBSD make, pick up o allow makefile to set .MAKE.JOBS * Makefile (PROG_NAME): use ${_MAKE_VERSION} 2016-03-15 Simon J. Gerraty * Makefile (_MAKE_VERSION): 20160315 Merge with NetBSD make, pick up o fix handling of archive members 2016-03-13 Simon J. Gerraty * Makefile (_MAKE_VERSION): rename variable to avoid interference with checks for ${MAKE_VERSION} 2016-03-10 Simon J. Gerraty * Makefile (MAKE_VERSION): 20160310 Merge with NetBSD make, pick up o meta.c: treat missing Read file same as Write, incase we Delete it. 2016-03-07 Simon J. Gerraty * Makefile (MAKE_VERSION): 20160307 Merge with NetBSD make, pick up o var.c: fix :ts\nnn to be octal by default. o meta.c: meta_finish() to cleanup memory. 2016-02-26 Simon J. Gerraty * Makefile (MAKE_VERSION): 20160226 Merge with NetBSD make, pick up o meta.c: allow meta file for makeDepend if makefiles want it. 2016-02-19 Simon J. Gerraty * var.c: default .MAKE.SAVE_DOLLARS to FALSE for backwards compatability. * Makefile (MAKE_VERSION): 20160220 Merge with NetBSD make, pick up o var.c: add knob to control handling of '$$' in := 2016-02-18 Simon J. Gerraty * Makefile (MAKE_VERSION): 20160218 Merge with NetBSD make, pick up o var.c: add .export-literal allows us to fix sys.clean-env.mk post the changes to Var_Subst. Var_Subst now takes flags, and does not consume '$$' in := 2016-02-17 Simon J. Gerraty * Makefile (MAKE_VERSION): 20160217 Merge with NetBSD make, pick up o var.c: preserve '$$' in := o parse.c: add .dinclude for handling included makefile like .depend 2015-12-20 Simon J. Gerraty * Makefile (MAKE_VERSION): 20151220 Merge with NetBSD make, pick up o suff.c: re-initialize suffNull when clearing suffixes. 2015-12-01 Simon J. Gerraty * Makefile (MAKE_VERSION): 20151201 Merge with NetBSD make, pick up o cond.c: CondCvtArg: avoid access beyond end of empty buffer. o meta.c: meta_oodate: use lstat(2) for checking link target in case it is a symlink. o var.c: avoid calling brk_string and Var_Export1 with empty strings. 2015-11-26 Simon J. Gerraty * Makefile (MAKE_VERSION): 20151126 Merge with NetBSD make, pick up o parse.c: ParseTrackInput don't access beyond end of old value. 2015-10-22 Simon J. Gerraty * Makefile (MAKE_VERSION): 20151022 * Add support for BSD/OS which lacks inttypes.h and really needs sys/param.h for sys/sysctl.h also 'type' is not a shell builtin. * var.c: eliminate uint32_t and need for inttypes.h * main.c: PrintOnError flush stdout before run .ERROR * parse.c: cope with _SC_PAGESIZE not being defined. 2015-10-20 Simon J. Gerraty * Makefile (MAKE_VERSION): 20151020 Merge with NetBSD make, pick up o var.c: fix uninitialized var 2015-10-12 Simon J. Gerraty * var.c: the conditional expressions used with ':?' can be expensive, if already discarding do not evaluate or expand anything. 2015-10-10 Simon J. Gerraty * Makefile (MAKE_VERSION): 20151010 Merge with NetBSD make, pick up o Add Boolean wantit flag to Var_Subst and Var_Parse when FALSE we know we are discarding the result and can skip operations like Cmd_Exec. 2015-10-09 Simon J. Gerraty * Makefile (MAKE_VERSION): 20151009 Merge with NetBSD make, pick up o var.c: don't check for NULL before free() o meta.c: meta_oodate, do not hard code ignore of makeDependfile 2015-09-10 Simon J. Gerraty * Makefile (MAKE_VERSION): 20150910 Merge with NetBSD make, pick up o main.c: with -w print Enter/Leaving messages for objdir too if necessary. o centralize shell metachar handling * FILES: add metachar.[ch] 2015-06-06 Simon J. Gerraty * Makefile (MAKE_VERSION): 20150606 Merge with NetBSD make, pick up o make.1: document .OBJDIR target 2015-05-05 Simon J. Gerraty * Makefile (MAKE_VERSION): 20150505 Merge with NetBSD make, pick up o cond.c: be strict about lhs of comparison when evaluating .if but less so when called from variable expansion. o unit-tests/cond2.mk: test various error conditions 2015-05-04 Simon J. Gerraty * machine.sh (MACHINE): Add Bitrig patch from joerg@netbsd.org 2015-04-18 Simon J. Gerraty * Makefile (MAKE_VERSION): 20150418 Merge with NetBSD make, pick up o job.c: use memmove() rather than memcpy() * unit-tests/varshell.mk: SunOS cannot handle the TERMINATED_BY_SIGNAL case, so skip it. 2015-04-11 Simon J. Gerraty * Makefile (MAKE_VERSION): 20150411 bump version - only mk/ changes. 2015-04-10 Simon J. Gerraty * Makefile (MAKE_VERSION): 20150410 Merge with NetBSD make, pick up o document different handling of '-' in jobs mode vs compat o fix jobs mode so that '-' only applies to whole job when shell lacks hasErrCtl o meta.c: use separate vars to track lcwd and latestdir (read) per process 2015-04-01 Simon J. Gerraty * Makefile (MAKE_VERSION): 20150401 Merge with NetBSD make, pick up o meta.c: close meta file in child * Makefile: use BINDIR.bmake if set. Same for MANDIR and SHAREDIR Handy for testing release candidates in various environments. 2015-03-26 Simon J. Gerraty * move initialization of savederr to block where it is used to avoid spurious warning from gcc5 2014-11-11 Simon J. Gerraty * Makefile (MAKE_VERSION): 20141111 just a cooler number 2014-11-05 Simon J. Gerraty * Makefile (MAKE_VERSION): 20141105 Merge with NetBSD make, pick up o revert major overhaul of suffix handling and POSIX compliance - too much breakage and impossible to make backwards compatible. o we still have the new unit test structure which is ok. o meta.c ensure "-- filemon" is at start of line. 2014-09-17 Simon J. Gerraty * configure.in: test that result of getconf PATH_MAX is numeric and discard if not. Apparently needed for Hurd. 2014-08-30 Simon J. Gerraty * Makefile (MAKE_VERSION): 20140830 Merge with NetBSD make, pick up o major overhaul of suffix handling o improved POSIX compliance o overhauled unit-tests 2014-06-20 Simon J. Gerraty * Makefile (MAKE_VERSION): 20140620 Merge with NetBSD make, pick up o var.c return varNoError rather than var_Error for ::= modifiers. 2014-05-22 Simon J. Gerraty * Makefile (MAKE_VERSION): 20140522 Merge with NetBSD make, pick up o var.c detect some parse errors. 2014-04-05 Simon J. Gerraty * Fix spelling errors - patch from Pedro Giffuni 2014-02-14 Simon J. Gerraty * Makefile (MAKE_VERSION): 20140214 Merge with NetBSD make, pick up o .INCLUDEFROM* o use Var_Value to get MAKEOBJDIR[PREFIX] o reduced realloc'ign in brk_string. * configure.in: add a check for compiler supporting __func__ 2014-01-03 Simon J. Gerraty * boot-strap: ignore mksrc=none 2014-01-02 Simon J. Gerraty * Makefile (DEFAULT_SYS_PATH?): use just ${prefix}/share/mk 2014-01-01 Simon J. Gerraty * Makefile (MAKE_VERSION): 20140101 * configure.in: set bmake_path_max to min(_SC_PATH_MAX,1024) * Makefile.config: defined BMAKE_PATH_MAX to bmake_path_max * make.h: use BMAKE_PATH_MAX if MAXPATHLEN not defined (needed for Hurd) * configure.in: Add AC_PREREQ and check for sysctl; patch from Andrew Shadura andrewsh at debian.org 2013-10-16 Simon J. Gerraty * Makefile (MAKE_VERSION): 20131010 * lose the const from arg to systcl to avoid problems on older BSDs. 2013-10-01 Simon J. Gerraty * Makefile (MAKE_VERSION): 20131001 Merge with NetBSD make, pick up o main.c: for NATIVE build sysctl to get MACHINE_ARCH from hw.machine_arch if necessary. o meta.c: meta_oodate - need to look at src of Link and target of Move as well. * main.c: check that CTL_HW and HW_MACHINE_ARCH exist. provide __arraycount() if needed. 2013-09-04 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130904 Merge with NetBSD make, pick up o Add VAR_INTERNAL context, so that internal setting of MAKEFILE does not override value set by makefiles. 2013-09-02 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130902 Merge with NetBSD make, pick up o CompatRunCommand: only apply shellErrFlag when errCheck is true 2013-08-28 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130828 Merge with NetBSD make, pick up o Fix VAR :sh = syntax from Will Andrews at freebsd.org o Call Job_SetPrefix() from Job_Init() so makefiles have opportunity to set .MAKE.JOB.PREFIX 2013-07-30 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130730 Merge with NetBSD make, pick up o Allow suppression of --- job -- tokens by setting .MAKE.JOB.PREFIX empty. 2013-07-16 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130716 Merge with NetBSD make, pick up o number of gmake compatibility tweaks -w for gmake style entering/leaving messages if .MAKE.LEVEL > 0 indicate it in progname "make[1]" etc. handle MAKEFLAGS containing only letters. o when overriding a GLOBAL variable on the command line, delete it from GLOBAL context so -V doesn't show the wrong value. 2013-07-06 Simon J. Gerraty * configure.in: We don't need MAKE_LEVEL_SAFE anymore. * Makefile (MAKE_VERSION): 20130706 Merge with NetBSD make, pick up o Shell_Init(): export shellErrFlag if commandShell hasErrCtl is true so that CompatRunCommand() can use it, to ensure consistent behavior with jobs mode. o use MAKE_LEVEL_ENV to define the variable to propagate .MAKE.LEVEL - currently set to MAKELEVEL (same as gmake). o meta.c: use .MAKE.META.IGNORE_PATHS to allow customization of paths to ignore. 2013-06-04 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130604 Merge with NetBSD make, pick up o job.c: JobCreatePipe: do fcntl() after any tweaking of fd's to avoid leaking descriptors. 2013-05-28 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130528 Merge with NetBSD make, pick up o var.c: cleanup some left-overs in VarHash() 2013-05-20 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130520 generate manifest from component FILES rather than have to update FILES when mk/FILES changes. 2013-05-18 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130518 Merge with NetBSD make, pick up o suff.c: don't skip all processsing for .PHONY targets else wildcard srcs do not get expanded. o var.c: expand name of variable to delete if necessary. 2013-03-30 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130330 Merge with NetBSD make, pick up o meta.c: refine the handling of .OODATE in commands. Rather than suppress command comparison for the entire script as though .NOMETA_CMP had been used, only suppress it for the one command line. This allows something like ${.OODATE:M.NOMETA_CMP} to be used to suppress comparison of a command without otherwise affecting it. o make.1: document that 2013-03-22 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130321 yes, not quite right but its a cooler number. Merge with NetBSD make, pick up o parse.c: fix ParseGmakeExport to be portable and add a unit-test. * meta.c: call meta_init() before makefiles are read and if built with filemon support set .MAKE.PATH_FILEMON to _PATH_FILEMON this let's makefiles test for support. Call meta_mode_init() to process .MAKE.MODE. 2013-03-13 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130305 Merge with NetBSD make, pick up o run .STALE: target when a dependency from .depend is missing. o job.c: add Job_RunTarget() for the above and .BEGIN 2013-03-03 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130303 Merge with NetBSD make, pick up o main.c: set .MAKE.OS to utsname.sysname o job.c: more checks for read and poll errors o var.c: lose VarChangeCase() saves 4% time 2013-03-02 Simon J. Gerraty * boot-strap: remove MAKEOBJDIRPREFIX from environment since we want to use MAKEOBJDIR 2013-01-27 Simon J. Gerraty * Merge with NetBSD make, pick up o make.1: more info on how shell commands are handled. o job.c,main.c: detect write errors to job pipes. 2013-01-25 Simon J. Gerraty * Makefile (MAKE_VERSION): 20130123 Merge with NetBSD make, pick up o meta.c: if script uses .OODATE and meta_oodate() decides rebuild is needed, .OODATE will be empty - set it to .ALLSRC. o var.c: in debug output indicate which variabale modifiers apply to. o remove Check_Cwd logic the makefiles have been fixed. 2012-12-12 Simon J. Gerraty * makefile.in: add a simple makefile for folk who insist on ./configure; make; make install it just runs boot-strap * include mk/* to accommodate the above * boot-strap: re-work to accommodate the above mksrc defaults to $Mydir/mk allow op={configure,build,install,clean,all} add options to facilitate install * Makefile.config.in: just the bits set by configure * Makefile: bump version to 20121212 abandon Makefile.in (NetBSD Makefile) leverage mk/* instead * configure.in: ensure srcdir is absolute 2012-11-11 Simon J. Gerraty * Makefile.in (MAKE_VERSION): 20121111 fix generation of bmake.cat1 2012-11-09 Simon J. Gerraty * Makefile.in (MAKE_VERSION): 20121109 Merge with NetBSD make, pick up o make.c: MakeBuildChild: return 0 so search continues if a .ORDER dependency is detected. o unit-tests/order: test the above 2012-11-02 Simon J. Gerraty * Makefile.in (MAKE_VERSION): 20121102 Merge with NetBSD make, pick up o cond.c: allow cond_state[] to grow. In meta mode with a very large tree, we can hit the limit while processing dirdeps. 2012-10-25 Simon J. Gerraty * Makefile.in: we need to use ${srcdir} not ${.CURDIR} 2012-10-10 Simon J. Gerraty * Makefile.in (MAKE_VERSION): 20121010 o protect syntax that only bmake parses correctly. o remove auto setting of FORCE_MACHINE, use configure's --with-force-machine=whatever if that is desired. 2012-10-08 Simon J. Gerraty * Makefile.in: do not lose history from make.1 when generating bmake.1 2012-10-07 Simon J. Gerraty * Makefile.in (MAKE_VERSION): 20121007 Merge with NetBSD make, pick up o compat.c: ignore empty commands - same as jobs mode. o make.1: document meta chars that cause use of shell 2012-09-11 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120911 * bsd.after-import.mk: include Makefile.inc early and allow it to override PROG 2012-08-31 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120831 Merge with NetBSD make, pick up o cast sizeof() to int for comparison o minor make.1 tweak 2012-08-30 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120830 Merge with NetBSD make, pick up o .MAKE.EXPAND_VARIABLES knob can control default behavior of -V o debug flag -dV causes -V to show raw value regardless. 2012-07-05 Simon J. Gerraty * bsd.after-import.mk (after-import): ensure unit-tests/Makefile gets SRCTOP set. 2012-07-04 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120704 Merge with NetBSD make, pick up o Job_ParseShell should call Shell_Init if it has been previously called. * Makefile.in: set USE_META based on configure result. also .PARSEDIR is safer indicator of bmake. 2012-06-26 Simon J. Gerraty * Makefile.in: bump version to 20120626 ensure CPPFLAGS is in CFLAGS * meta.c: avoid nested externs * bsd.after-import.mk: avoid ${.CURDIR}/Makefile as target 2012-06-20 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120620 Merge with NetBSD make, pick up o make_malloc.c: avoid including make_malloc.h again * Makefile.in: avoid bmake only syntax or protect with .if defined(.MAKE.LEVEL) * bsd.after-import.mk: replace .-include with .sinclude ensure? SRCTOP gets a value * configure.in: look for filemon.h in /usr/include/dev/filemon first. 2012-06-19 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120612 Merge with NetBSD make, pick up o use MAKE_ATTR_* rather than those defined by cdefs.h or compiler for greater portability. o unit-tests/forloop: check that .for works as expected wrt number of times and with "quoted strings". 2012-06-06 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120606 Merge with NetBSD make, pick up o compat.c: use kill(2) rather than raise(3). * configure.in: look for sys/dev/filemon * bsd.after-import.mk: add a .-include "Makefile.inc" to Makefile and pass BOOTSTRAP_XTRAS to boot-strap. 2012-06-04 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120604 Merge with NetBSD make, pick up o util.c and var.c share same var for tracking if environ has been reallocated. o util.c provide getenv with setenv. * Add MAKE_LEVEL_SAFE as an alternate means of passing MAKE_LEVEL when the shell actively strips .MAKE.* from the environment. We still refer to the variable always as .MAKE.LEVEL * util.c fix bug in findenv() was finding prefix of name. * compat.c: re-raising SIGINT etc after running .INTERRUPT results in more reliable termination of all activity on many platforms. 2012-06-02 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120602 Merge with NetBSD make, pick up o for.c: handle quoted items in .for list 2012-05-30 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120530 Merge with NetBSD make, pick up o compat.c: ignore empty command. 2012-05-24 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120524 * FILES: add bsd.after-import.mk: A simple means of integrating bmake into a BSD build system. 2012-05-20 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120520 Merge with NetBSD make, pick up o increased limit for nested conditionals. 2012-05-18 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120518 Merge with NetBSD make, pick up o use _exit(2) in signal hanlder o Don't use the [dir] cache when building nodes that might have changed since the last exec. o Avoid nested extern declaration warnings. 2012-04-27 Simon J. Gerraty * meta.c (fgetLine): avoid %z - not portable. * parse.c: Since we moved include of sys/mman.h and def's of MAP_COPY etc. we got dups from a merge. 2012-04-24 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120420 Merge with NetBSD make, pick up o restore duplicate supression in .MAKE.MAKEFILES runtime saving can be significant. o Var_Subst() uses Buf_DestroyCompact() to reduce memory consumption up to 20%. 2012-04-20 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120420 Merge with NetBSD make, pick up o remove duplicate supression in .MAKE.MAKEFILES o improved dir cache behavior o gmake'ish export command 2012-03-25 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20120325 Merge with NetBSD make, pick up o fix parsing of :[#] in conditionals. 2012-02-10 Simon J. Gerraty * Makefile.in: replace use of .Nx in bmake.1 with NetBSD since some systems cannot cope with .Nx 2011-11-14 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20111111 Merge with NetBSD make, pick up o debug output for .PARSEDIR and .PARSEFILE 2011-10-10 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20111010 2011-10-09 Simon J. Gerraty * boot-strap: check for an expected file in the dirs we look for. * make-bootstrap.sh: pass on LDSTATIC 2011-10-01 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20111001 Merge with NetBSD make, pick up o ensure .PREFIX is set for .PHONY and .TARGET set for .PHONY run via .END o __dead used consistently 2011-09-10 Simon J. Gerraty * Makefile.in (MAKE_VERSION): 20110909 is a better number ;-) 2011-09-05 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110905 Merge with NetBSD make, pick up o meta_oodate: ignore makeDependfile 2011-08-28 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110828 Merge with NetBSD make, pick up o silent=yes in .MAKE.MODE causes meta mode to mark targets as SILENT if a .meta file is created 2011-08-18 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110818 Merge with NetBSD make, pick up o in meta mode, if target flagged .META a missing .meta file means target is out-of-date o fixes for gcc 4.5 warnings o simplify job printing code 2011-08-09 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110808 Merge with NetBSD make, pick up o do not touch OP_SPECIAL targets when doing make -t 2011-06-22 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110622 Merge with NetBSD make, pick up o meta_oodate detect corrupted .meta file and declare oodate. * configure.in: add check for setsid 2011-06-07 Simon J. Gerraty * Merge with NetBSD make, pick up o unit-tests/modts now works on MirBSD 2011-06-04 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110606 Merge with NetBSD make, pick up o ApplyModifiers: when we parse a variable which is not the entire modifier string, or not followed by ':', do not consider it as containing modifiers. o loadfile: ensure newline at end of mapped file. 2011-05-05 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110505 Merge with NetBSD make, pick up o .MAKE.META.BAILIWICK - list of prefixes which define the scope of make's control. In meta mode, any generated file within said bailiwick, which is found to be missing, causes current target to be out-of-date. 2011-04-11 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110411 Merge with NetBSD make, pick up o when long modifiers fail to match, check sysV style. - add a test case 2011-04-10 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110410 Merge with NetBSD make, pick up o :hash - cheap 32bit hash of value o :localtime, :gmtime - use value as format string for strftime. 2011-03-30 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110330 mostly because its a cooler version. Merge with NetBSD make, pick up o NetBSD tags for meta.[ch] o job.c call meta_job_finish() after meta_job_error(). o meta_job_error() should call meta_job_finish() to ensure .meta file is closed, and safe to copy - if .ERROR target wants. meta_job_finish() is safe to call repeatedly. 2011-03-29 Simon J. Gerraty * unit-tests/modts: use printf if it is a builtin, to save us from MirBSD * Makefile.in (MAKE_VERSION): bump version to 20110329 Merge with NetBSD make, pick up o fix for use after free() in CondDoExists(). o meta_oodate() report extra commands and return earlier. 2011-03-27 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110327 Merge with NetBSD make, pick up o meta.c, if .MAKE.MODE contains curdirOk=yes allow creating .meta files in .CURDIR * boot-strap (TOOL_DIFF): aparently at least on linux distro formats the output of 'type' differently - so eat any "()" 2011-03-06 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110306 Merge with NetBSD make, pick up o meta.c, only do getcwd() once 2011-03-05 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110305 Merge with NetBSD make, pick up o correct sysV substitution handling of empty lhs and variable o correct exists() check for dir with trailing / o correct handling of modifiers for non-existant variables during evaluation of conditionals. o ensure MAP_FILE is defined. o meta.c use curdir[] now exported by main.c 2011-02-25 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110225 Merge with NetBSD make, pick up o fix for incorrect .PARSEDIR when .OBJDIR is re-computed after makefiles have been read. o fix example of :? modifier in man page. 2011-02-13 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110214 Merge with NetBSD make, pick up o meta.c handle realpath() failing when generating meta file name. * sigcompat.c: convert to ansi so we can use higher warning levels. 2011-02-07 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110207 Merge with NetBSD make, pick up o fix for bug in meta mode. 2011-01-03 Simon J. Gerraty * parse.c: SunOS 5.8 at least does not have MAP_FILE 2011-01-01 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20110101 Merge with NetBSD make, pick up o use mmap(2) if available, for reading makefiles 2010-12-15 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20101215 Merge with NetBSD make, pick up o ensure meta_job_error() does not report a previous .meta file as being culprit. 2010-12-10 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20101210 Merge with NetBSD make, pick up o meta_oodate: track cwd per process, and only consider target out-of-date if missing file is outside make's CWD. Ignore files in /tmp/ etc. o to ensure unit-tests results match, need to control LC_ALL as well as LANG. o fix for parsing bug in var.c 2010-11-26 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20101126 Merge with NetBSD make, pick up o if stale dependency is an IMPSRC, search via .PATH o meta_oodate: if a referenced file is missing, target is out-of-date. o meta_oodate: if a target uses .OODATE in its commands, it (.OODATE) needs to be recomputed. o keep a pointer to youngest child node, rather than just its mtime. 2010-11-02 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20101101 2010-10-16 Simon J. Gerraty * machine.sh: like os.sh, allow for uname -p producing useless drivel 2010-09-13 Simon J. Gerraty * boot-strap: document configure knobs for meta and filemon. * Makefile.in (MAKE_VERSION): bump version to 20100911 Merge with NetBSD make, pick up o meta.c - meta mode * make-bootstrap.sh.in: handle meta.c * configure.in: add knobs for use_meta and filemon_h also, look for dirname, str[e]sep and strlcpy * util.c: add simple err[x] and warn[x] 2010-08-08 Simon J. Gerraty * boot-strap (TOOL_DIFF): set this to ensure tests use the same version of diff that configure tested * Makefile.in (MAKE_VERSION): bump version to 20100808 Merge with NetBSD make, pick up o in jobs mode, when we discover we cannot make something, call PrintOnError before exit. 2010-08-06 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100806 Merge with NetBSD make, pick up o formatting fixes for ignored errors o ensure jobs are cleaned up regardless of where wait() was called. 2010-06-28 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100618 * os.sh (MACHINE_ARCH): watch out for drivel from uname -p 2010-06-16 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100616 Merge with NetBSD make, pick up o man page update o call PrintOnError from JobFinish when we detect an error we are not ignoring. 2010-06-06 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100606 Merge with NetBSD make, pick up o man page update 2010-06-05 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100605 Merge with NetBSD make, pick up o use bmake_signal() which is a wrapper around sigaction() in place of signal() o add .export-env to allow exporting variables to environment without tracking (so no re-export when the internal value is changed). 2010-05-24 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100524 Merge with NetBSD make, pick up o fix for .info et al being greedy. 2010-05-23 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100520 Merge with NetBSD make, pick up o back to using realpath on argv[0] but only if contains '/' and does not start with '/'. 2010-05-10 Simon J. Gerraty * boot-strap: use absolute path for bmake when running tests. * Makefile.in (MAKE_VERSION): bump version to 20100510 Merge with NetBSD make, pick up o revert use of realpath on argv[0] too many corner cases. o print MAKE_PRINT_VAR_ON_ERROR before running .ERROR target. 2010-05-05 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100505 Merge with NetBSD make, pick up o fix for missed SIGCHLD when compiled with SunPRO actually for bmake, defining FORCE_POSIX_SIGNALS would have done the job. 2010-04-30 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100430 Merge with NetBSD make, pick up o fflush stdout before writing to stdout 2010-04-23 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100423 Merge with NetBSD make, pick up o updated unit tests for Haiku (this time for sure). * boot-strap: based on patch from joerg honor --with-default-sys-path better. * boot-strap: remove mention of --with-prefix-sys-path 2010-04-22 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100422 * Merge with NetBSD make, pick up o fix for vfork() on Darwin. o fix for bogus $TMPDIR. o set .MAKE.MODE=compat for -B o set .MAKE.JOBS=max_jobs for -j max_jobs o allow unit-tests to run without any *.mk o unit-tests/modmisc be more conservative in dirs presumed to exist. * boot-strap: ignore /usr/share/mk except on NetBSD. * unit-tests/Makefile.in: set LANG=C when running unit-tests to ensure sort(1) behaves as expected. 2010-04-21 Simon J. Gerraty * boot-strap: add FindHereOrAbove so we can use -m .../mk 2010-04-20 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100420 * Merge with NetBSD make, pick up o fix for variable realpath() behavior. we have to stat(2) the result to be sure. o fix for .export (all) when nested vars use :sh 2010-04-14 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100414 * Merge with NetBSD make, pick up o use realpath to resolve argv[0] (for .MAKE) if needed. o add realpath from libc. o add :tA to resolve variable via realpath(3) if possible. 2010-04-08 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100408 * Merge with NetBSD make, pick up o unit tests for .ERROR, .error o fix for .ERROR to ensure it cannot be default target. 2010-04-06 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100406 * Merge with NetBSD make, pick up o fix for compat mode "Error code" going to debug_file. o fix for .ALLSRC being populated twice. o support for .info, .warning and .error directives o .MAKE.MODE to control make's operational mode o .MAKE.MAKEFILE_PREFERENCE to control the preferred makefile name(s). o .MAKE.DEPENDFILE to control the name of the depend file o .ERROR target - run on failure. 2010-03-18 Simon J. Gerraty * make-bootstrap.sh.in: extract MAKE_VERSION from Makefile * os.sh,arch.c: patch for Haiku from joerg at netbsd 2010-03-17 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100222 * Merge with NetBSD make, pick up o better error msg for .for with mutiple inter vars * boot-strap: o use make-bootstrap.sh from joerg at netbsd to avoid the need for a native make when bootstrapping. o add "" everywhere ;-) o if /usr/share/tmac/andoc.tmac exists install nroff bmake.1 otherwise the pre-formated version. 2010-01-04 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20100102 * Merge with NetBSD make, pick up: o fix for -m .../ 2009-11-18 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20091118 * Merge with NetBSD make, pick up: o .unexport o report lines that start with '.' and should have ':' (catch typo's of .el*if). 2009-10-30 Simon J. Gerraty * configure.in: Ensure that srcdir and mksrc are absolute paths. 2009-10-09 Simon J. Gerraty * Makefile.in (MAKE_VERSION): fix version to 20091007 2009-10-07 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 200910007 * Merge with NetBSD make, pick up: o fix for parsing of :S;...;...; applied to .for loop iterator appearing in a dependency line. 2009-09-09 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20090909 * Merge with NetBSD make, pick up: o fix for -C, .CURDIR and .OBJDIR * boot-strap: o allow share_dir to be set independent of prefix. o select default share_dir better when prefix ends in $HOST_TARGET o if FORCE_BSD_MK etc were set, include them in the suggested install-mk command. 2009-09-08 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20090908 * Merge with NetBSD make, pick up: o .MAKE.LEVEL for recursion tracking o fix for :M scanning \: 2009-09-03 Simon J. Gerraty * configure.in: Don't -D__EXTENSIONS__ if AC_USE_SYSTEM_EXTENSIONS says "no". 2009-08-26 Simon J. Gerraty * Makefile.in (MAKE_VERSION): bump version to 20090826 Simplify MAKE_VERSION to just the bare date. * Merge with NetBSD make, pick up: o -C directory support. o support for SIGINFO o use $TMPDIR for temp files. o child of vfork should be careful about modifying parent's state. 2009-03-26 Simon J. Gerraty * Appy some patches for MiNT from David Brownlee 2009-02-26 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20090222 * Merge with NetBSD make, pick up: o Possible null pointer de-ref in Var_Set. 2009-02-08 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20090204 * Merge with NetBSD make, pick up: o bmake_malloc et al moved to their own .c o Count both () and {} when looking for the end of a :M pattern o Change 'Buffer' so that it is the actual struct, not a pointer to it. o strlist.c - functions for processing extendable arrays of pointers to strings. o ClientData replaced with void *, so const void * can be used. o New debug flag C for DEBUG_CWD 2008-11-11 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20081111 Apply patch from Joerg Sonnenberge to configure.in: o remove some redundant checks o check for emlloc etc only in libutil and require the whole family. util.c: o remove [v]asprintf which is no longer used. 2008-11-04 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20081101 * Merge with NetBSD make, pick up: o util.c: avoid use of putenv() - christos 2008-10-30 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20081030 pick up man page tweaks. 2008-10-29 Simon J. Gerraty * Makefile.in: move processing of LIBOBJS to after is definition! thus we'll have getenv.c in SRCS only if needed. * make.1: add examples of how to use :? * Makefile.in (BMAKE_VERSION): bump version to 20081029 * Merge with NetBSD make, pick up: o fix for .END processing with -j o segfault from Parse_Error when no makefile is open o handle numeric expressions in any variable expansion o debug output now defaults to stderr, -dF to change it - apb o make now uses bmake_malloc etc so that it can build natively on A/UX - wasn't an issue for bmake, but we want to keep in sync. 2008-09-27 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20080808 * Merge with NetBSD make, pick up: o fix for PR/38840: Pierre Pronchery: make crashes while parsing long lines in Makefiles o optimizations for VarQuote by joerg o fix for PR/38756: dominik: make dumps core on invalid makefile 2008-05-15 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20080515 * Merge with NetBSD make, pick up: o fix skip setting vars in VAR_GLOBAL context, to handle cases where VAR_CMD is used for other than command line vars. 2008-05-14 Simon J. Gerraty * boot-strap (make_version): we may need to look in $prefix/share/mk for sys.mk * Makefile.in (BMAKE_VERSION): bump version to 20080514 * Merge with NetBSD make, pick up: o skip setting vars in VAR_GLOBAL context, when already set in VAR_CMD which takes precedence. 2008-03-30 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20080330 * Merge with NetBSD make, pick up: o fix for ?= when LHS contains variable reference. 2008-02-15 Simon J. Gerraty * merge some patches from NetBSD pkgsrc. * makefile.boot.in (BOOTSTRAP_SYS_PATH): Allow better control of the MAKSYSPATH used during bootstrap. * Makefile.in (BMAKE_VERSION): bump version to 20080215 * Merge with NetBSD make, pick up: o warn if non-space chars follow 'empty' in a conditional. 2008-01-18 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20080118 * Merge with NetBSD make, pick up: o consider dependencies read from .depend as optional - dsl o remember when buffer for reading makefile grows - dsl o add -dl (aka LOUD) - David O'Brien 2007-10-22 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20071022 * Merge with NetBSD make, pick up: o Allow .PATH to be used for .include "" * boot-strap: source default settings from .bmake-boot-strap.rc 2007-10-16 Simon J. Gerraty * Makefile.in: fix maninstall on various systems provided that our man.mk is used. For non-BSD systems we install the preformatted page into $MANDIR/cat1 2007-10-15 Simon J. Gerraty * boot-strap: make bmake.1 too, so maninstall works. 2007-10-14 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20071014 * Merge with NetBSD make, pick up: o revamped handling of defshell - configure no longer needs to know the content of the shells array - apb o stop Var_Subst modifying its input - apb o avoid calling ParseTrackInput too often - dsl 2007-10-11 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20071011 * Merge with NetBSD make, pick up: o fix Shell_Init for case that _BASENAME_DEFSHELL is absolute path. * sigcompat.c: some tweaks for HP-UX 11.x based on patch from Tobias Nygren * configure.in: update handling of --with-defshell to match new make behavior. --with-defshell=/usr/xpg4/bin/sh will now do what one might hope - provided the chosen shell behaves enough like sh. 2007-10-08 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20071008 * Merge with NetBSD make, pick up: o .MAKE.JOB.PREFIX - control the token output before jobs - sjg o .export/.MAKE.EXPORTED - export of variables - sjg o .MAKE.MAKEFILES - track all makefiles read - sjg o performance improvements - dsl o revamp parallel job scheduling - dsl 2006-07-28 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20060728 * Merge with NetBSD make, pick up: o extra debug info during variable and cond processing - sjg o shell definition now covers newline - rillig o minor mem leak in PrintOnError - sjg 2006-05-11 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20060511 * Merge with NetBSD make, pick up: o more memory leaks - coverity o possible overflow in ArchFindMember - coverity o extract variable modifier code out of Var_Parse() so it can be called recursively - sjg o unit-tests/moderrs - sjg 2006-04-12 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20060412 * Merge with NetBSD make, pick up: o fixes for some memory leaks - coverity o only read first sys.mk etc when searching sysIncPath - sjg * main.c (ReadMakefile): remove hack for __INTERIX that prevented setting ${MAKEFILE} - OBATA Akio 2006-03-18 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20060318 * Merge with NetBSD make, pick up: o cleanup of job.c to remove remote handling, distcc is more useful and this code was likely bit-rotting - dsl o fix for :P modifier - sjg * boot-strap: set default prefix to something reasonable (for me anyway). 2006-03-01 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20060301 * Merge with NetBSD make, pick up: o make .WAIT apply recursively, document and test case - apb o allow variable modifiers in a variable appear anywhere in modifier list, document and test case - sjg 2006-02-22 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20060222 * Merge with NetBSD make, pick up: o improved job token handling - dsl o SIG_DFL the correct signal before exec - dsl o more debug info during parsing - dsl o allow variable modifiers to be specified via variable - sjg * boot-strap: explain why we died if no mksrc 2005-11-05 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20051105 * configure.in: always set default_sys_path default is ${prefix}/share/mk - remove prefix_sys_path, anyone wanting more than above needs to set it manually. 2005-11-04 Simon J. Gerraty * boot-strap: make this a bit easier for pkgsrc folk. bootstrap still fails on IRIX64 since MACHINE_ARCH gets set to 'mips' while pkgsrc wants 'mipseb' or 'mipsel' 2005-11-02 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20051102 * job.c (JobFinish): fix likely ancient merge lossage fix from Todd Vierling. * boot-strap (srcdir): allow setting mksrc=none 2005-10-31 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20051031 * ranlib.h: skip on OSF too. (NetBSD PR 31864) 2005-10-10 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20051002 fix a silly typo 2005-10-09 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20051001 support for UnixWare and some other systems, based on patches from pkgsrc/bootstrap 2005-09-03 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20050901 * Merge with NetBSD make, pick up: o possible parse error causing us to wander off. 2005-06-06 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20050606 * Merge with NetBSD make, pick up: o :0x modifier for randomizing a list o fixes for a number of -Wuninitialized issues. 2005-05-30 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20050530 * Merge with NetBSD make, pick up: o Handle dependencies for .BEGIN, .END and .INTERRUPT * README: was seriously out of date. 2005-03-22 Simon J. Gerraty * Important to use .MAKE rather than MAKE. 2005-03-15 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20050315 * Merge with NetBSD make, pick up: o don't mistake .elsefoo for .else o use suffix-specific search path correctly o bunch of style nits 2004-05-11 Simon J. Gerraty * boot-strap: o ensure that args to --src and --with-mksrc are resolved before giving them to configure. o add -o "objdir" so that builder can control it, default is $OS as determined by os.sh o add -q to suppress all the install instructions. 2004-05-08 Simon J. Gerraty * Remove __IDSTRING() * Makefile.in (BMAKE_VERSION): bump to 20040508 * Merge with NetBSD make, pick up: o posix fixes - remove '-e' from compat mode - add support for '+' command-line prefix. o fix for handling '--' on command-line. o fix include in lst.lib/lstInt.h to simplify '-I's o we also picked up replacement of MAKE_BOOTSTRAP with !MAKE_NATIVE which is a noop, but possibly confusing. 2004-04-14 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20040414 * Merge with NetBSD make, pick up: o allow quoted strings on lhs of conditionals o issue warning when extra .else is seen o print line numer when errors encountered during parsing from string. 2004-02-20 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20040220 * Merge with NetBSD make, pick up: o fix for old :M parsing bug. o re-jigged unit-tests 2004-02-15 Simon J. Gerraty * Makefile.in (accept test): use ${.MAKE:S,^./,${.CURDIR}/,} so that './bmake -f Makefile test' works. 2004-02-14 Simon J. Gerraty * Makefile.in: (BMAKE_VERSION): bump to 20040214 * Merge with NetBSD make, pick up: o search upwards for *.mk o fix for double free of var substitution buffers o use of getopt replaced with custom code, since the usage (re-scanning) isn't posix compatible. 2004-02-12 Simon J. Gerraty * arch.c: don't include ranlib.h on ELF systems (thanks to Chuck Cranor ). 2004-01-18 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump to 20040118 * boot-strap (while): export vars we assign to on cmdline * unit-test/Makefile.in: ternary is .PHONY 2004-01-08 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20040108 * Merge with NetBSD make, pick up: o fix for ternary modifier 2004-01-06 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20040105 * Merge with NetBSD make, pick up: o fix for cond.c to handle compound expressions better o variable expansion within sysV style replacements 2003-12-22 Simon J. Gerraty * Make portable snprintf safer - output to /dev/null first to check space needed. * Makefile.in (BMAKE_VERSION): bump version to 20031222 * Merge with NetBSD make, pick up: o -dg3 to show input graph when things go wrong. o explicitly look for makefiles in objdir if not found in curdir so that errors in .depend etc will be reported accurarely. o avoid use of -e in shell scripts in jobs mode, use '|| exit $?' instead as it more accurately reflects the expected behavior and is more consistently implemented. o avoid use of asprintf. 2003-09-28 Simon J. Gerraty * util.c: Add asprintf and vasprintf. * Makefile.in (BMAKE_VERSION): bump version to 20030928 * Merge with NetBSD make, pick up: :[] modifier - allows picking words from a variable. :tW modifier - allows treating value as one big word. W flag for :C and :S - allows treating value as one big word. 2003-09-12 Simon J. Gerraty * Merge with NetBSD make pick up -de flag to enable printing failed command. don't skip 1st two dir entries (normally . and ..) since coda does not have them. 2003-09-09 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20030909 * Merge with NetBSD make, pick up: - changes for -V '${VAR}' to print fully expanded value cf. -V VAR - CompatRunCommand now prints the command that failed. - several files got updated 3 clause Berkeley license. 2003-08-02 Simon J. Gerraty * boot-strap: Allow setting configure args on command line. 2003-07-31 Simon J. Gerraty * configure.in: add --with-defshell to allow sh or ksh to be selected as default shell. * Makefile.in: bump version to 20030731 * Merge with NetBSD make Pick up .SHELL spec for ksh and associate man page changes. Also compat mode now uses the same shell specs. 2003-07-29 Simon J. Gerraty * var.c (Var_Parse): ensure delim is initialized. * unit-tests/Makefile.in: use single quotes to avoid problems from some shells. * makefile.boot.in: Run the unit-tests as part of the bootstrap procedure. 2003-07-28 Simon J. Gerraty * unit-tests/Makefile.in: always force complaints from ${TEST_MAKE} to be from 'make'. * configure.in: add check for 'diff -u' also fix some old autoconf'isms * Makefile.in (BMAKE_VERSION): bump version to 20030728. if using GCC add -Wno-cast-qual to CFLAGS for var.o * Merge with NetBSD make Pick up fix for :ts parsing error in some cases. Pick unit-tests. 2003-07-23 Simon J. Gerraty * Makefile.in (BMAKE_VERSION): bump version to 20030723. * var.c (Var_Parse): fix bug in :ts modifier, after const correctness fixes, must pass nstr to VarModify. 2003-07-14 Simon J. Gerraty * Makefile.in: BMAKE_VERSION switch to a date based version. We'll generally use the date of last import from NetBSD. * Merge with NetBSD make Pick up fixes for const-correctness, now passes WARNS=3 on NetBSD. Pick up :ts modifier, allows controlling the separator used between words in variable expansion. 2003-07-11 Simon J. Gerraty * FILES: include boot-strap and os.sh * Makefile.in: only set WARNS if we are NetBSD, the effect on FreeBSD is known to be bad. * makefile.boot.in (bootstrap): make this the default target. * Makefile.in: bump version to 3.1.19 * machine.sh: avoid A-Z with tr as it is bound to lose. 2003-07-10 Simon J. Gerraty * Merge with NetBSD make Pick up fix for PR/19781 - unhelpful error msg on unclosed ${var:foo Plus some doc fixes. 2003-04-27 Simon J. Gerraty * Merge with NetBSD make Pick up fix for PR/1523 - don't count a library as built, if there is no way to build it * Bump version to 3.1.18 2003-03-23 Simon J. Gerraty * Merge with NetBSD make Pick up fix for ParseDoSpecialSrc - we only use it if .WAIT appears in src list. 2003-03-21 Simon J. Gerraty * Merge with NetBSD make (mmm 10th anniversary!) pick up fix for .WAIT in srcs that refer to $@ or $* (PR#20828) pick up -X which tells us to not export VAR=val via setenv if we are already doing so via MAKEFLAGS. This saves valuable env space on systems like Darwin. set MAKE_VERSION to 3.1.17 * parse.c: pix up fix for suffix rules 2003-03-06 Simon J. Gerraty * Merge with NetBSD make. pick up fix for propagating -B via MAKEFLAGS. set MAKE_VERSION to 3.1.16 * Apply some patches from pkgsrc-bootstrap/bmake Originally by Grant Beattie I may have missed some - since they are based on bmake-3.1.12 2002-12-03 Simon J. Gerraty * makefile.boot.in (bmake): update install targets for those that use them, also clear MAKEFLAGS when invoking bmake.boot to avoid havoc from gmake -w. Thanks to Harlan Stenn . * bmake.cat1: update the pre-formatted man page! 2002-11-30 Simon J. Gerraty * Merge with NetBSD make. pick up fix for premature free of pointer used in call to Dir_InitCur(). set MAKE_VERSION to 3.1.15 2002-11-26 Simon J. Gerraty * configure.in: determine suitable value for MKSRC. override using --with-mksrc=PATH. * machine.sh: use `uname -p` for MACHINE_ARCH on modern SunOS systems. configs(8) will use 'sun4' as an alias for 'sparc'. 2002-11-25 Simon J. Gerraty * Merge with NetBSD make. pick up ${.PATH} pick up fix for finding ../cat.c via .PATH when .CURDIR=.. set MAKE_VERSION to 3.1.14 add configure checks for killpg and sys/socket.h 2002-09-16 Simon J. Gerraty * tag bmake-3-1-13 * makefile.boot.in (bmake): use install-mk Also setup ./mk before trying to invoke bmake.boot incase we needed install-mk to create a sys.mk for us. * configure.in: If we need to add -I${srcdir}/missing, make it an absolute path so that it works for lst.lib too. * make.h: always include sys/cdefs.h since we provide one if the host does not. * Makefile.in (install-mk): use MKSRC/install-mk which will do the right thing. use uname -p for ARCH if possible. since install-mk will setup links bsd.prog.mk -> prog.mk if needed, just .include bsd.prog.mk * Merge with NetBSD make (NetBSD-1.6) Code is ansi-C only now. Bug in handling of dotLast is fixed. Can now assign .OBJDIR and make will reset its notions of life. New modifiers :tu :tl for toUpper and toLower. Tue Oct 16 12:18:42 2001 Simon J. Gerraty * Merge with NetBSD make pick up fix for .END failure in compat mode. pick up fix for extra va_end() in ParseVErrorInternal. Thu Oct 11 13:20:06 2001 Simon J. Gerraty * configure.in: for systems that have sys/cdefs.h check if it is compatible. If not, include the one under missing, but tell it to include the native one too - necessary on Linux. * missing/sys/cdefs.h: if NEED_HOST_CDEFS_H is defined, use include_next (for gcc) to get the native sys/cdefs.h Tue Aug 21 02:29:34 2001 Simon J. Gerraty * job.c (JobFinish): Fix an earlier merge bug that resulted in leaking descriptors when using -jN. * job.c (JobPrintCommand): See if "curdir" exists before attempting to chdir(). Doing the chdir directly in make (when in compat mode) fails silently, so let the -jN version do the same. This can happen when building kernels in an object tree and playing clever games to reset .CURDIR. * Merged with NetBSD make pick up .USEBEFORE Tue Jun 26 23:45:11 2001 Simon J. Gerraty * makefile.boot.in: Give bmake.boot a MAKESYSPATH that might work. Tue Jun 12 16:48:57 2001 Simon J. Gerraty * var.c (Var_Set): Add 4th (flags) arg so VarLoopExpand can tell us not to export the iterator variable when using VAR_CMD context. Sun Jun 10 21:55:21 2001 Simon J. Gerraty * job.c (Job_CatchChildren): don't call Job_CatchOutput() here, its the wrong "fix". Sat Jun 9 00:11:24 2001 Simon J. Gerraty * Redesigned export of VAR_CMD's via MAKEFLAGS. We now simply append the variable names to .MAKEOVERRIDES, and handle duplicate suppression and quoting in ExportMAKEFLAGS using: ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@} Apart from fixing quoting bugs in previous version, this allows us to export vars to the environment by simply doing: .MAKEOVERRIDES+= PATH Merged again with NetBSD make, but the above is the only change. * configure.in: added --disable-pwd-override disable $PWD overriding getcwd() --disable-check-make-chdir disable make trying to guess when it should automatically cd ${.CURDIR} * Merge with NetBSD make, changes include: parse.c (ParseDoDependency): Spot that the syntax error is caused by an unresolved cvs/rcs conflict and say so. var.c: most of Var* functions now take a ctxt as 1st arg. now does variable substituion on rhs of sysv style modifiers. * var.c (Var_Set): exporting of command line variables (VAR_CMD) is now done here. We append the name='value' to .MAKEOVERRIDES rather than directly into MAKEFLAGS as this allows a Makefile to use .MAKEOVERRIDES= to disable this behaviour. GNU make uses a very similar mechanism. Note that in adding name='value' to .MAKEOVERRIDES we do the moral equivalent of: .MAKEOVERRIDES:= ${.MAKEOVERRIDES:Nname=*} name='val' Fri Jun 1 14:08:02 2001 Simon J. Gerraty * make-conf.h (USE_IOVEC): make it conditional on HAVE_SYS_UIO_H * Merged with NetBSD make make -dx can now be used to run commands via sh -x better error messages on exec failures. Thu May 31 01:44:54 2001 Simon J. Gerraty * Makefile.in (main.o): depends on ${SRCS} ${MAKEFILE} so that MAKE_VERSION gets updated. Also don't use ?= for MAKE_VERSION, MACHINE etc otherwise they propagate from the previous bmake. * configure.in (machine): allow --with-machine=generic to make configure use machine.sh to set MACHINE. * job.c (JobInterrupt): convert to using WAIT_T and friends. * Makefile.in: mention in bmake.1 that we use autoconf. * make.1: mention MAKE_PRINT_VAR_ON_ERROR. Wed May 30 23:17:18 2001 Simon J. Gerraty * main.c (ReadMakefile): don't set MAKEFILE if reading ".depend" as that rather defeats the usefulness of ${MAKEFILE}. * main.c (MainParseArgs): append command line variable assignments to MAKEFLAGS so that they get propagated to child make's. Apparently this is required POSIX behaviour? Its useful anyway. Tue May 29 02:20:07 2001 Simon J. Gerraty * compat.c (CompatRunCommand): don't use perror() since stdio may cause problems in child of vfork(). * compat.c, main.c: Call PrintOnError() when we are going to bail. This routine prints out the .curdir where we stopped and will also display any vars listed in ${MAKE_PRINT_VAR_ON_ERROR}. * main.c: add ${.newline} to hold a "\n" - sometimes handy in :@ expansion. * var.c: VarLoopExpand: ignore addSpace if a \n is present. * Added RCSid's for the files we've touched. Thu May 24 15:41:37 2001 Simon J. Gerraty * configure.in: Thanks to some clues from mdb@juniper.net, added autoconf magic to control setting of MACHINE, MACHINE_ARCH as well as what ends up in _PATH_DEFSYSPATH. We now have: --with-machine=MACHINE explicitly set MACHINE --with-force-machine=MACHINE set FORCE_MACHINE --with-machine_arch=MACHINE_ARCH explicitly set MACHINE_ARCH --with-default-sys-path=PATH:DIR:LIST use an explicit _PATH_DEFSYSPATH --with-prefix-sys-path=PATH:DIR:LIST prefix _PATH_PREFIX_SYSPATH --with-path-objdirprefix=PATH override _PATH_OBJDIRPREFIX If _PATH_OBJDIRPREFIX is set to "no" we won't define it. * makefile: added a pathetically simple makefile to drive bootstrapping. Running configure by hand is more useful. * Makefile.in: added MAKE_VERSION, and reworked things to be less dependent on NetBSD bsd.*.mk * pathnames.h: allow NO_PATH_OBJDIRPREFIX to stop us defining _PATH_OBJDIRPREFIX for those that don't want a default. construct _PATH_DEFSYSPATH from the info we get from configure. * main.c: allow for no _PATH_OBJDIRPREFIX, set ${MAKE_VERSION} if MAKE_VERSION is defined. * compat.c: when we bail, print out the .CURDIR we were in. Sat May 12 00:34:12 2001 Simon J. Gerraty * Merged with NetBSD make * var.c: fixed a bug in the handling of the modifier :P if the node as found but the path was null, we segfault trying to duplicate it. Mon Mar 5 16:20:33 2001 Simon J. Gerraty * Merged with NetBSD make * make.c: Make_OODate's test for a library out of date was using cmtime where it should have used mtime (my bug). * compat.c: Use perror() to tell us what really went wrong when we cannot exec a command. Fri Dec 15 10:11:08 2000 Simon J. Gerraty * Merged with NetBSD make Sat Jun 10 10:11:08 2000 Simon J. Gerraty * Merged with NetBSD make Thu Jun 1 10:11:08 2000 Simon J. Gerraty * Merged with NetBSD make Tue May 30 10:11:08 2000 Simon J. Gerraty * Merged with NetBSD make Thu Apr 27 00:07:47 2000 Simon J. Gerraty * util.c: don't provide signal() since we use sigcompat.c * Makefile.in: added a build target. * var.c (Var_Parse): added ODE modifiers :U, :D, :L, :P, :@ and :! These allow some quite clever magic. * main.c (main): added support for getenv(MAKESYSPATH). Mon Apr 2 16:25:13 2000 Simon J. Gerraty * Disable $PWD overriding getcwd() if MAKEOBJDIRPREFIX is set. This avoids objdir having a different value depending on how a directory was reached (via command line, or subdir.mk). * If FORCE_MACHINE is defined, ignore getenv("MACHINE"). Mon Apr 2 23:15:31 2000 Simon J. Gerraty * Do a chdir(${.CURDIR}) before invoking ${.MAKE} or ${.MAKE:T} if MAKEOBJDIRPREFIX is set and NOCHECKMAKECHDIR is not. I've been testing this in NetBSD's make for some weeks. * Turn Makefile into Makefile.in and make it useful. Tue Feb 29 22:08:00 2000 Simon J. Gerraty * Imported NetBSD's -current make(1) and resolve conflicts. * Applied autoconf patches from bmake v2 * Imported clean code base from NetBSD-1.0 Index: stable/12/contrib/bmake/FILES =================================================================== --- stable/12/contrib/bmake/FILES (revision 361673) +++ stable/12/contrib/bmake/FILES (revision 361674) @@ -1,170 +1,186 @@ ChangeLog FILES Makefile Makefile.config.in PSD.doc/Makefile PSD.doc/tutorial.ms README VERSION aclocal.m4 arch.c bmake.1 bmake.cat1 boot-strap bsd.after-import.mk buf.c buf.h compat.c cond.c config.h.in configure configure.in dir.c dir.h dirname.c +filemon/filemon.h +filemon/filemon_dev.c +filemon/filemon_ktrace.c find_lib.sh for.c getopt.c hash.c hash.h install-sh job.c job.h lst.h lst.lib/Makefile lst.lib/lstAppend.c lst.lib/lstAtEnd.c lst.lib/lstAtFront.c lst.lib/lstClose.c lst.lib/lstConcat.c lst.lib/lstDatum.c lst.lib/lstDeQueue.c lst.lib/lstDestroy.c lst.lib/lstDupl.c lst.lib/lstEnQueue.c lst.lib/lstFind.c lst.lib/lstFindFrom.c lst.lib/lstFirst.c lst.lib/lstForEach.c lst.lib/lstForEachFrom.c lst.lib/lstInit.c lst.lib/lstInsert.c lst.lib/lstInt.h lst.lib/lstIsAtEnd.c lst.lib/lstIsEmpty.c lst.lib/lstLast.c lst.lib/lstMember.c lst.lib/lstNext.c lst.lib/lstOpen.c lst.lib/lstPrev.c lst.lib/lstRemove.c lst.lib/lstReplace.c lst.lib/lstSucc.c machine.sh main.c make-bootstrap.sh.in make-conf.h make.1 make.c make.h make_malloc.c make_malloc.h makefile.in meta.c meta.h metachar.c metachar.h missing/sys/cdefs.h mkdeps.sh nonints.h os.sh parse.c pathnames.h ranlib.h realpath.c setenv.c sigcompat.c sprite.h str.c stresep.c strlcpy.c strlist.c strlist.h suff.c targ.c trace.c trace.h -unit-tests/Makefile.in +unit-tests/Makefile +unit-tests/Makefile.config.in unit-tests/comment.exp unit-tests/comment.mk unit-tests/cond1.exp unit-tests/cond1.mk unit-tests/cond2.exp unit-tests/cond2.mk +unit-tests/cond-late.mk +unit-tests/cond-late.exp +unit-tests/dollar.exp +unit-tests/dollar.mk unit-tests/doterror.exp unit-tests/doterror.mk unit-tests/dotwait.exp unit-tests/dotwait.mk unit-tests/error.exp unit-tests/error.mk unit-tests/escape.exp unit-tests/escape.mk unit-tests/export-all.exp unit-tests/export-all.mk unit-tests/export-env.exp unit-tests/export-env.mk unit-tests/export.exp unit-tests/export.mk unit-tests/forloop.exp unit-tests/forloop.mk unit-tests/forsubst.exp unit-tests/forsubst.mk unit-tests/hash.exp unit-tests/hash.mk unit-tests/impsrc.exp unit-tests/impsrc.mk +unit-tests/include-main.exp +unit-tests/include-main.mk +unit-tests/include-sub.mk +unit-tests/include-subsub.mk unit-tests/misc.exp unit-tests/misc.mk unit-tests/moderrs.exp unit-tests/moderrs.mk unit-tests/modmatch.exp unit-tests/modmatch.mk unit-tests/modmisc.exp unit-tests/modmisc.mk unit-tests/modorder.exp unit-tests/modorder.mk unit-tests/modts.exp unit-tests/modts.mk unit-tests/modword.exp unit-tests/modword.mk unit-tests/order.exp unit-tests/order.mk unit-tests/phony-end.exp unit-tests/phony-end.mk unit-tests/posix.exp unit-tests/posix.mk unit-tests/posix1.exp unit-tests/posix1.mk unit-tests/qequals.exp unit-tests/qequals.mk unit-tests/suffixes.exp unit-tests/suffixes.mk unit-tests/sunshcmd.exp unit-tests/sunshcmd.mk unit-tests/sysv.exp unit-tests/sysv.mk unit-tests/ternary.exp unit-tests/ternary.mk unit-tests/unexport-env.exp unit-tests/unexport-env.mk unit-tests/unexport.exp unit-tests/unexport.mk unit-tests/varcmd.exp unit-tests/varcmd.mk unit-tests/varmisc.exp unit-tests/varmisc.mk +unit-tests/varmod-edge.exp +unit-tests/varmod-edge.mk +unit-tests/varquote.exp +unit-tests/varquote.mk unit-tests/varshell.exp unit-tests/varshell.mk util.c var.c wait.h Index: stable/12/contrib/bmake/Makefile =================================================================== --- stable/12/contrib/bmake/Makefile (revision 361673) +++ stable/12/contrib/bmake/Makefile (revision 361674) @@ -1,226 +1,241 @@ -# $Id: Makefile,v 1.99 2017/08/13 20:12:53 sjg Exp $ +# $Id: Makefile,v 1.104 2020/02/06 01:33:54 sjg Exp $ PROG= bmake SRCS= \ arch.c \ buf.c \ compat.c \ cond.c \ dir.c \ for.c \ hash.c \ job.c \ main.c \ make.c \ make_malloc.c \ meta.c \ metachar.c \ parse.c \ str.c \ strlist.c \ suff.c \ targ.c \ trace.c \ util.c \ var.c # from lst.lib/ SRCS+= \ lstAppend.c \ lstAtEnd.c \ lstAtFront.c \ lstClose.c \ lstConcat.c \ lstDatum.c \ lstDeQueue.c \ lstDestroy.c \ lstDupl.c \ lstEnQueue.c \ lstFind.c \ lstFindFrom.c \ lstFirst.c \ lstForEach.c \ lstForEachFrom.c \ lstInit.c \ lstInsert.c \ lstIsAtEnd.c \ lstIsEmpty.c \ lstLast.c \ lstMember.c \ lstNext.c \ lstOpen.c \ lstPrev.c \ lstRemove.c \ lstReplace.c \ lstSucc.c .-include "VERSION" +.-include "Makefile.inc" # this file gets generated by configure .-include "Makefile.config" .if !empty(LIBOBJS) SRCS+= ${LIBOBJS:T:.o=.c} .endif # just in case prefix?= /usr srcdir?= ${.CURDIR} DEFAULT_SYS_PATH?= ${prefix}/share/mk CPPFLAGS+= -DUSE_META CFLAGS+= ${CPPFLAGS} CFLAGS+= -D_PATH_DEFSYSPATH=\"${DEFAULT_SYS_PATH}\" CFLAGS+= -I. -I${srcdir} ${XDEFS} -DMAKE_NATIVE CFLAGS+= ${COPTS.${.ALLSRC:M*.c:T:u}} COPTS.main.c+= "-DMAKE_VERSION=\"${_MAKE_VERSION}\"" -# meta mode can be useful even without filemon +# meta mode can be useful even without filemon +# should be set by now +USE_FILEMON ?= no +.if ${USE_FILEMON:tl} != "no" +.PATH: ${.CURDIR}/filemon +SRCS+= filemon_${USE_FILEMON}.c +COPTS.meta.c+= -DUSE_FILEMON -DUSE_FILEMON_${USE_FILEMON:tu} +COPTS.job.c+= ${COPTS.meta.c} + +.if ${USE_FILEMON} == "dev" FILEMON_H ?= /usr/include/dev/filemon/filemon.h .if exists(${FILEMON_H}) && ${FILEMON_H:T} == "filemon.h" -COPTS.meta.c += -DHAVE_FILEMON_H -I${FILEMON_H:H} +COPTS.filemon_dev.c += -DHAVE_FILEMON_H -I${FILEMON_H:H} .endif +.endif # USE_FILEMON == dev +.endif # USE_FILEMON + .PATH: ${srcdir} .PATH: ${srcdir}/lst.lib .if make(obj) || make(clean) SUBDIR+= unit-tests .endif # start-delete1 for bsd.after-import.mk # we skip a lot of this when building as part of FreeBSD etc. # list of OS's which are derrived from BSD4.4 BSD44_LIST= NetBSD FreeBSD OpenBSD DragonFly MirBSD Bitrig # we are... OS!= uname -s # are we 4.4BSD ? isBSD44:=${BSD44_LIST:M${OS}} .if ${isBSD44} == "" MANTARGET= cat INSTALL?=${srcdir}/install-sh .if (${MACHINE} == "sun386") # even I don't have one of these anymore :-) CFLAGS+= -DPORTAR .elif (${MACHINE} != "sunos") SRCS+= sigcompat.c CFLAGS+= -DSIGNAL_FLAGS=SA_RESTART .endif .else MANTARGET?= man .endif # turn this on by default - ignored if we are root WITH_INSTALL_AS_USER= # suppress with -DWITHOUT_* OPTIONS_DEFAULT_YES+= \ AUTOCONF_MK \ INSTALL_MK \ PROG_LINK OPTIONS_DEFAULT_NO+= \ PROG_VERSION # process options now .include .if ${MK_PROG_VERSION} == "yes" PROG_NAME= ${PROG}-${_MAKE_VERSION} .if ${MK_PROG_LINK} == "yes" SYMLINKS+= ${PROG_NAME} ${BINDIR}/${PROG} .endif .endif EXTRACT_MAN=no # end-delete1 MAN= ${PROG}.1 MAN1= ${MAN} .if (${PROG} != "make") CLEANFILES+= my.history .if make(${MAN}) || !exists(${srcdir}/${MAN}) my.history: ${MAKEFILE} @(echo ".Nm"; \ echo "is derived from NetBSD"; \ echo ".Xr make 1 ."; \ echo "It uses autoconf to facilitate portability to other platforms."; \ echo ".Pp") > $@ .NOPATH: ${MAN} ${MAN}: make.1 my.history @echo making $@ @sed \ -e '/^.Dt/s/MAKE/${PROG:tu}/' \ -e 's/^.Nx/NetBSD/' \ -e '/^.Nm/s/make/${PROG}/' \ -e '/^.Sh HISTORY/rmy.history' \ -e '/^.Sh HISTORY/,$$s,^.Nm,make,' ${srcdir}/make.1 > $@ all beforeinstall: ${MAN} _mfromdir=. .endif .endif MANTARGET?= cat MANDEST?= ${MANDIR}/${MANTARGET}1 .if ${MANTARGET} == "cat" _mfromdir=${srcdir} .endif .include CPPFLAGS+= -DMAKE_NATIVE -DHAVE_CONFIG_H COPTS.var.c += -Wno-cast-qual COPTS.job.c += -Wno-format-nonliteral COPTS.parse.c += -Wno-format-nonliteral COPTS.var.c += -Wno-format-nonliteral # Force these SHAREDIR= ${SHAREDIR.bmake:U${prefix}/share} BINDIR= ${BINDIR.bmake:U${prefix}/bin} MANDIR= ${MANDIR.bmake:U${SHAREDIR}/man} .if !exists(.depend) ${OBJS}: config.h .endif # start-delete2 for bsd.after-import.mk # make sure that MAKE_VERSION gets updated. main.o: ${SRCS} ${.CURDIR}/VERSION .if ${MK_AUTOCONF_MK} == "yes" CONFIGURE_DEPS += ${.CURDIR}/VERSION +# we do not need or want the generated makefile +CONFIGURE_ARGS += --without-makefile .include .endif SHARE_MK?=${SHAREDIR}/mk MKSRC=${srcdir}/mk INSTALL?=${srcdir}/install-sh .if ${MK_INSTALL_MK} == "yes" install: install-mk .endif beforeinstall: test -d ${DESTDIR}${BINDIR} || ${INSTALL} -m 775 -d ${DESTDIR}${BINDIR} test -d ${DESTDIR}${MANDEST} || ${INSTALL} -m 775 -d ${DESTDIR}${MANDEST} install-mk: .if exists(${MKSRC}/install-mk) test -d ${DESTDIR}${SHARE_MK} || ${INSTALL} -m 775 -d ${DESTDIR}${SHARE_MK} sh ${MKSRC}/install-mk -v -m 644 ${DESTDIR}${SHARE_MK} .else @echo need to unpack mk.tar.gz under ${srcdir} or set MKSRC; false .endif # end-delete2 # A simple unit-test driver to help catch regressions accept test: cd ${.CURDIR}/unit-tests && MAKEFLAGS= ${.MAKE} -r -m / TEST_MAKE=${TEST_MAKE:U${.OBJDIR}/${PROG:T}} ${.TARGET} Index: stable/12/contrib/bmake/Makefile.config.in =================================================================== --- stable/12/contrib/bmake/Makefile.config.in (revision 361673) +++ stable/12/contrib/bmake/Makefile.config.in (revision 361674) @@ -1,21 +1,22 @@ # things set by configure -_MAKE_VERSION=@_MAKE_VERSION@ +_MAKE_VERSION?=@_MAKE_VERSION@ prefix?= @prefix@ srcdir= @srcdir@ CC?= @CC@ MACHINE?= @machine@ MACHINE_ARCH?= @machine_arch@ DEFAULT_SYS_PATH?= @default_sys_path@ CPPFLAGS+= @CPPFLAGS@ CFLAGS+= ${CPPFLAGS} @DEFS@ -LDFLAGS= @LDFLAGS@ -LIBOBJS= @LIBOBJS@ -LDADD= @LIBS@ -USE_META= @use_meta@ +LDFLAGS+= @LDFLAGS@ +LIBOBJS+= @LIBOBJS@ +LDADD+= @LIBS@ +USE_META?= @use_meta@ +USE_FILEMON?= @use_filemon@ FILEMON_H?= @filemon_h@ BMAKE_PATH_MAX?= @bmake_path_max@ # used if MAXPATHLEN not defined CPPFLAGS+= -DBMAKE_PATH_MAX=${BMAKE_PATH_MAX} Index: stable/12/contrib/bmake/VERSION =================================================================== --- stable/12/contrib/bmake/VERSION (revision 361673) +++ stable/12/contrib/bmake/VERSION (revision 361674) @@ -1,2 +1,2 @@ # keep this compatible with sh and make -_MAKE_VERSION=20180512 +_MAKE_VERSION=20200517 Index: stable/12/contrib/bmake/arch.c =================================================================== --- stable/12/contrib/bmake/arch.c (revision 361673) +++ stable/12/contrib/bmake/arch.c (revision 361674) @@ -1,1416 +1,1416 @@ -/* $NetBSD: arch.c,v 1.70 2017/04/16 20:49:09 riastradh Exp $ */ +/* $NetBSD: arch.c,v 1.71 2019/10/05 23:35:57 mrg Exp $ */ /* * Copyright (c) 1988, 1989, 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MAKE_NATIVE -static char rcsid[] = "$NetBSD: arch.c,v 1.70 2017/04/16 20:49:09 riastradh Exp $"; +static char rcsid[] = "$NetBSD: arch.c,v 1.71 2019/10/05 23:35:57 mrg Exp $"; #else #include #ifndef lint #if 0 static char sccsid[] = "@(#)arch.c 8.2 (Berkeley) 1/2/94"; #else -__RCSID("$NetBSD: arch.c,v 1.70 2017/04/16 20:49:09 riastradh Exp $"); +__RCSID("$NetBSD: arch.c,v 1.71 2019/10/05 23:35:57 mrg Exp $"); #endif #endif /* not lint */ #endif /*- * arch.c -- * Functions to manipulate libraries, archives and their members. * * Once again, cacheing/hashing comes into play in the manipulation * of archives. The first time an archive is referenced, all of its members' * headers are read and hashed and the archive closed again. All hashed * archives are kept on a list which is searched each time an archive member * is referenced. * * The interface to this module is: * Arch_ParseArchive Given an archive specification, return a list * of GNode's, one for each member in the spec. * FAILURE is returned if the specification is * invalid for some reason. * * Arch_Touch Alter the modification time of the archive * member described by the given node to be * the current time. * * Arch_TouchLib Update the modification time of the library * described by the given node. This is special * because it also updates the modification time * of the library's table of contents. * * Arch_MTime Find the modification time of a member of * an archive *in the archive*. The time is also * placed in the member's GNode. Returns the * modification time. * * Arch_MemTime Find the modification time of a member of * an archive. Called when the member doesn't * already exist. Looks in the archive for the * modification time. Returns the modification * time. * * Arch_FindLib Search for a library along a path. The * library name in the GNode should be in * -l format. * * Arch_LibOODate Special function to decide if a library node * is out-of-date. * * Arch_Init Initialize this module. * * Arch_End Cleanup this module. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include #include #include #include #ifdef HAVE_AR_H #include #else struct ar_hdr { char ar_name[16]; /* name */ char ar_date[12]; /* modification time */ char ar_uid[6]; /* user id */ char ar_gid[6]; /* group id */ char ar_mode[8]; /* octal file permissions */ char ar_size[10]; /* size in bytes */ #ifndef ARFMAG #define ARFMAG "`\n" #endif char ar_fmag[2]; /* consistency check */ }; #endif #if defined(HAVE_RANLIB_H) && !(defined(__ELF__) || defined(NO_RANLIB)) #include #endif #include #include #ifdef HAVE_UTIME_H #include #endif #include "make.h" #include "hash.h" #include "dir.h" #ifdef TARGET_MACHINE #undef MAKE_MACHINE #define MAKE_MACHINE TARGET_MACHINE #endif #ifdef TARGET_MACHINE_ARCH #undef MAKE_MACHINE_ARCH #define MAKE_MACHINE_ARCH TARGET_MACHINE_ARCH #endif static Lst archives; /* Lst of archives we've already examined */ typedef struct Arch { char *name; /* Name of archive */ Hash_Table members; /* All the members of the archive described * by key/value pairs */ char *fnametab; /* Extended name table strings */ size_t fnamesize; /* Size of the string table */ } Arch; static int ArchFindArchive(const void *, const void *); #ifdef CLEANUP static void ArchFree(void *); #endif static struct ar_hdr *ArchStatMember(char *, char *, Boolean); static FILE *ArchFindMember(char *, char *, struct ar_hdr *, const char *); #if defined(__svr4__) || defined(__SVR4) || defined(__ELF__) #define SVR4ARCHIVES static int ArchSVR4Entry(Arch *, char *, size_t, FILE *); #endif #if defined(_AIX) # define AR_NAME _ar_name.ar_name # define AR_FMAG _ar_name.ar_fmag # define SARMAG SAIAMAG # define ARMAG AIAMAG # define ARFMAG AIAFMAG #endif #ifndef AR_NAME # define AR_NAME ar_name #endif #ifndef AR_DATE # define AR_DATE ar_date #endif #ifndef AR_SIZE # define AR_SIZE ar_size #endif #ifndef AR_FMAG # define AR_FMAG ar_fmag #endif #ifndef ARMAG # define ARMAG "!\n" #endif #ifndef SARMAG # define SARMAG 8 #endif #define AR_MAX_NAME_LEN (sizeof(arh.AR_NAME)-1) #ifdef CLEANUP /*- *----------------------------------------------------------------------- * ArchFree -- * Free memory used by an archive * * Results: * None. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static void ArchFree(void *ap) { Arch *a = (Arch *)ap; Hash_Search search; Hash_Entry *entry; /* Free memory from hash entries */ for (entry = Hash_EnumFirst(&a->members, &search); entry != NULL; entry = Hash_EnumNext(&search)) free(Hash_GetValue(entry)); free(a->name); free(a->fnametab); Hash_DeleteTable(&a->members); free(a); } #endif /*- *----------------------------------------------------------------------- * Arch_ParseArchive -- * Parse the archive specification in the given line and find/create * the nodes for the specified archive members, placing their nodes * on the given list. * * Input: * linePtr Pointer to start of specification * nodeLst Lst on which to place the nodes * ctxt Context in which to expand variables * * Results: * SUCCESS if it was a valid specification. The linePtr is updated * to point to the first non-space after the archive spec. The * nodes for the members are placed on the given list. * * Side Effects: * Some nodes may be created. The given list is extended. * *----------------------------------------------------------------------- */ ReturnStatus Arch_ParseArchive(char **linePtr, Lst nodeLst, GNode *ctxt) { char *cp; /* Pointer into line */ GNode *gn; /* New node */ char *libName; /* Library-part of specification */ char *memName; /* Member-part of specification */ char *nameBuf; /* temporary place for node name */ char saveChar; /* Ending delimiter of member-name */ Boolean subLibName; /* TRUE if libName should have/had * variable substitution performed on it */ libName = *linePtr; subLibName = FALSE; for (cp = libName; *cp != '(' && *cp != '\0'; cp++) { if (*cp == '$') { /* * Variable spec, so call the Var module to parse the puppy * so we can safely advance beyond it... */ int length; void *freeIt; char *result; result = Var_Parse(cp, ctxt, VARF_UNDEFERR|VARF_WANTRES, &length, &freeIt); free(freeIt); if (result == var_Error) { return(FAILURE); } else { subLibName = TRUE; } cp += length-1; } } *cp++ = '\0'; if (subLibName) { libName = Var_Subst(NULL, libName, ctxt, VARF_UNDEFERR|VARF_WANTRES); } for (;;) { /* * First skip to the start of the member's name, mark that * place and skip to the end of it (either white-space or * a close paren). */ Boolean doSubst = FALSE; /* TRUE if need to substitute in memName */ while (*cp != '\0' && *cp != ')' && isspace ((unsigned char)*cp)) { cp++; } memName = cp; while (*cp != '\0' && *cp != ')' && !isspace ((unsigned char)*cp)) { if (*cp == '$') { /* * Variable spec, so call the Var module to parse the puppy * so we can safely advance beyond it... */ int length; void *freeIt; char *result; result = Var_Parse(cp, ctxt, VARF_UNDEFERR|VARF_WANTRES, &length, &freeIt); free(freeIt); if (result == var_Error) { return(FAILURE); } else { doSubst = TRUE; } cp += length; } else { cp++; } } /* * If the specification ends without a closing parenthesis, * chances are there's something wrong (like a missing backslash), * so it's better to return failure than allow such things to happen */ if (*cp == '\0') { printf("No closing parenthesis in archive specification\n"); return (FAILURE); } /* * If we didn't move anywhere, we must be done */ if (cp == memName) { break; } saveChar = *cp; *cp = '\0'; /* * XXX: This should be taken care of intelligently by * SuffExpandChildren, both for the archive and the member portions. */ /* * If member contains variables, try and substitute for them. * This will slow down archive specs with dynamic sources, of course, * since we'll be (non-)substituting them three times, but them's * the breaks -- we need to do this since SuffExpandChildren calls * us, otherwise we could assume the thing would be taken care of * later. */ if (doSubst) { char *buf; char *sacrifice; char *oldMemName = memName; size_t sz; memName = Var_Subst(NULL, memName, ctxt, VARF_UNDEFERR|VARF_WANTRES); /* * Now form an archive spec and recurse to deal with nested * variables and multi-word variable values.... The results * are just placed at the end of the nodeLst we're returning. */ sz = strlen(memName)+strlen(libName)+3; buf = sacrifice = bmake_malloc(sz); snprintf(buf, sz, "%s(%s)", libName, memName); if (strchr(memName, '$') && strcmp(memName, oldMemName) == 0) { /* * Must contain dynamic sources, so we can't deal with it now. * Just create an ARCHV node for the thing and let * SuffExpandChildren handle it... */ gn = Targ_FindNode(buf, TARG_CREATE); if (gn == NULL) { free(buf); return(FAILURE); } else { gn->type |= OP_ARCHV; (void)Lst_AtEnd(nodeLst, gn); } } else if (Arch_ParseArchive(&sacrifice, nodeLst, ctxt)!=SUCCESS) { /* * Error in nested call -- free buffer and return FAILURE * ourselves. */ free(buf); return(FAILURE); } /* * Free buffer and continue with our work. */ free(buf); } else if (Dir_HasWildcards(memName)) { Lst members = Lst_Init(FALSE); char *member; size_t sz = MAXPATHLEN, nsz; nameBuf = bmake_malloc(sz); Dir_Expand(memName, dirSearchPath, members); while (!Lst_IsEmpty(members)) { member = (char *)Lst_DeQueue(members); nsz = strlen(libName) + strlen(member) + 3; if (sz > nsz) nameBuf = bmake_realloc(nameBuf, sz = nsz * 2); snprintf(nameBuf, sz, "%s(%s)", libName, member); free(member); gn = Targ_FindNode(nameBuf, TARG_CREATE); if (gn == NULL) { free(nameBuf); return (FAILURE); } else { /* * We've found the node, but have to make sure the rest of * the world knows it's an archive member, without having * to constantly check for parentheses, so we type the * thing with the OP_ARCHV bit before we place it on the * end of the provided list. */ gn->type |= OP_ARCHV; (void)Lst_AtEnd(nodeLst, gn); } } Lst_Destroy(members, NULL); free(nameBuf); } else { size_t sz = strlen(libName) + strlen(memName) + 3; nameBuf = bmake_malloc(sz); snprintf(nameBuf, sz, "%s(%s)", libName, memName); gn = Targ_FindNode(nameBuf, TARG_CREATE); free(nameBuf); if (gn == NULL) { return (FAILURE); } else { /* * We've found the node, but have to make sure the rest of the * world knows it's an archive member, without having to * constantly check for parentheses, so we type the thing with * the OP_ARCHV bit before we place it on the end of the * provided list. */ gn->type |= OP_ARCHV; (void)Lst_AtEnd(nodeLst, gn); } } if (doSubst) { free(memName); } *cp = saveChar; } /* * If substituted libName, free it now, since we need it no longer. */ if (subLibName) { free(libName); } /* * We promised the pointer would be set up at the next non-space, so * we must advance cp there before setting *linePtr... (note that on * entrance to the loop, cp is guaranteed to point at a ')') */ do { cp++; } while (*cp != '\0' && isspace ((unsigned char)*cp)); *linePtr = cp; return (SUCCESS); } /*- *----------------------------------------------------------------------- * ArchFindArchive -- * See if the given archive is the one we are looking for. Called * From ArchStatMember and ArchFindMember via Lst_Find. * * Input: * ar Current list element * archName Name we want * * Results: * 0 if it is, non-zero if it isn't. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static int ArchFindArchive(const void *ar, const void *archName) { return (strcmp(archName, ((const Arch *)ar)->name)); } /*- *----------------------------------------------------------------------- * ArchStatMember -- * Locate a member of an archive, given the path of the archive and * the path of the desired member. * * Input: * archive Path to the archive * member Name of member. If it is a path, only the last * component is used. * hash TRUE if archive should be hashed if not already so. * * Results: * A pointer to the current struct ar_hdr structure for the member. Note * That no position is returned, so this is not useful for touching * archive members. This is mostly because we have no assurances that * The archive will remain constant after we read all the headers, so * there's not much point in remembering the position... * * Side Effects: * *----------------------------------------------------------------------- */ static struct ar_hdr * ArchStatMember(char *archive, char *member, Boolean hash) { FILE * arch; /* Stream to archive */ int size; /* Size of archive member */ char *cp; /* Useful character pointer */ char magic[SARMAG]; LstNode ln; /* Lst member containing archive descriptor */ Arch *ar; /* Archive descriptor */ Hash_Entry *he; /* Entry containing member's description */ struct ar_hdr arh; /* archive-member header for reading archive */ char memName[MAXPATHLEN+1]; /* Current member name while hashing. */ /* * Because of space constraints and similar things, files are archived * using their final path components, not the entire thing, so we need * to point 'member' to the final component, if there is one, to make * the comparisons easier... */ cp = strrchr(member, '/'); if (cp != NULL) { member = cp + 1; } ln = Lst_Find(archives, archive, ArchFindArchive); if (ln != NULL) { ar = (Arch *)Lst_Datum(ln); he = Hash_FindEntry(&ar->members, member); if (he != NULL) { return ((struct ar_hdr *)Hash_GetValue(he)); } else { /* Try truncated name */ char copy[AR_MAX_NAME_LEN+1]; size_t len = strlen(member); if (len > AR_MAX_NAME_LEN) { len = AR_MAX_NAME_LEN; strncpy(copy, member, AR_MAX_NAME_LEN); copy[AR_MAX_NAME_LEN] = '\0'; } if ((he = Hash_FindEntry(&ar->members, copy)) != NULL) return ((struct ar_hdr *)Hash_GetValue(he)); return NULL; } } if (!hash) { /* * Caller doesn't want the thing hashed, just use ArchFindMember * to read the header for the member out and close down the stream * again. Since the archive is not to be hashed, we assume there's * no need to allocate extra room for the header we're returning, * so just declare it static. */ static struct ar_hdr sarh; arch = ArchFindMember(archive, member, &sarh, "r"); if (arch == NULL) { return NULL; } else { fclose(arch); return (&sarh); } } /* * We don't have this archive on the list yet, so we want to find out * everything that's in it and cache it so we can get at it quickly. */ arch = fopen(archive, "r"); if (arch == NULL) { return NULL; } /* * We use the ARMAG string to make sure this is an archive we * can handle... */ if ((fread(magic, SARMAG, 1, arch) != 1) || (strncmp(magic, ARMAG, SARMAG) != 0)) { fclose(arch); return NULL; } ar = bmake_malloc(sizeof(Arch)); ar->name = bmake_strdup(archive); ar->fnametab = NULL; ar->fnamesize = 0; Hash_InitTable(&ar->members, -1); memName[AR_MAX_NAME_LEN] = '\0'; while (fread((char *)&arh, sizeof(struct ar_hdr), 1, arch) == 1) { if (strncmp( arh.AR_FMAG, ARFMAG, sizeof(arh.AR_FMAG)) != 0) { /* * The header is bogus, so the archive is bad * and there's no way we can recover... */ goto badarch; } else { /* * We need to advance the stream's pointer to the start of the * next header. Files are padded with newlines to an even-byte * boundary, so we need to extract the size of the file from the * 'size' field of the header and round it up during the seek. */ arh.AR_SIZE[sizeof(arh.AR_SIZE)-1] = '\0'; size = (int)strtol(arh.AR_SIZE, NULL, 10); - (void)strncpy(memName, arh.AR_NAME, sizeof(arh.AR_NAME)); + memcpy(memName, arh.AR_NAME, sizeof(arh.AR_NAME)); for (cp = &memName[AR_MAX_NAME_LEN]; *cp == ' '; cp--) { continue; } cp[1] = '\0'; #ifdef SVR4ARCHIVES /* * svr4 names are slash terminated. Also svr4 extended AR format. */ if (memName[0] == '/') { /* * svr4 magic mode; handle it */ switch (ArchSVR4Entry(ar, memName, size, arch)) { case -1: /* Invalid data */ goto badarch; case 0: /* List of files entry */ continue; default: /* Got the entry */ break; } } else { if (cp[0] == '/') cp[0] = '\0'; } #endif #ifdef AR_EFMT1 /* * BSD 4.4 extended AR format: #1/, with name as the * first bytes of the file */ if (strncmp(memName, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0 && isdigit((unsigned char)memName[sizeof(AR_EFMT1) - 1])) { unsigned int elen = atoi(&memName[sizeof(AR_EFMT1)-1]); if (elen > MAXPATHLEN) goto badarch; if (fread(memName, elen, 1, arch) != 1) goto badarch; memName[elen] = '\0'; if (fseek(arch, -elen, SEEK_CUR) != 0) goto badarch; if (DEBUG(ARCH) || DEBUG(MAKE)) { fprintf(debug_file, "ArchStat: Extended format entry for %s\n", memName); } } #endif he = Hash_CreateEntry(&ar->members, memName, NULL); Hash_SetValue(he, bmake_malloc(sizeof(struct ar_hdr))); memcpy(Hash_GetValue(he), &arh, sizeof(struct ar_hdr)); } if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0) goto badarch; } fclose(arch); (void)Lst_AtEnd(archives, ar); /* * Now that the archive has been read and cached, we can look into * the hash table to find the desired member's header. */ he = Hash_FindEntry(&ar->members, member); if (he != NULL) { return ((struct ar_hdr *)Hash_GetValue(he)); } else { return NULL; } badarch: fclose(arch); Hash_DeleteTable(&ar->members); free(ar->fnametab); free(ar); return NULL; } #ifdef SVR4ARCHIVES /*- *----------------------------------------------------------------------- * ArchSVR4Entry -- * Parse an SVR4 style entry that begins with a slash. * If it is "//", then load the table of filenames * If it is "/", then try to substitute the long file name * from offset of a table previously read. * * Results: * -1: Bad data in archive * 0: A table was loaded from the file * 1: Name was successfully substituted from table * 2: Name was not successfully substituted from table * * Side Effects: * If a table is read, the file pointer is moved to the next archive * member * *----------------------------------------------------------------------- */ static int ArchSVR4Entry(Arch *ar, char *name, size_t size, FILE *arch) { #define ARLONGNAMES1 "//" #define ARLONGNAMES2 "/ARFILENAMES" size_t entry; char *ptr, *eptr; if (strncmp(name, ARLONGNAMES1, sizeof(ARLONGNAMES1) - 1) == 0 || strncmp(name, ARLONGNAMES2, sizeof(ARLONGNAMES2) - 1) == 0) { if (ar->fnametab != NULL) { if (DEBUG(ARCH)) { fprintf(debug_file, "Attempted to redefine an SVR4 name table\n"); } return -1; } /* * This is a table of archive names, so we build one for * ourselves */ ar->fnametab = bmake_malloc(size); ar->fnamesize = size; if (fread(ar->fnametab, size, 1, arch) != 1) { if (DEBUG(ARCH)) { fprintf(debug_file, "Reading an SVR4 name table failed\n"); } return -1; } eptr = ar->fnametab + size; for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++) switch (*ptr) { case '/': entry++; *ptr = '\0'; break; case '\n': break; default: break; } if (DEBUG(ARCH)) { fprintf(debug_file, "Found svr4 archive name table with %lu entries\n", (unsigned long)entry); } return 0; } if (name[1] == ' ' || name[1] == '\0') return 2; entry = (size_t)strtol(&name[1], &eptr, 0); if ((*eptr != ' ' && *eptr != '\0') || eptr == &name[1]) { if (DEBUG(ARCH)) { fprintf(debug_file, "Could not parse SVR4 name %s\n", name); } return 2; } if (entry >= ar->fnamesize) { if (DEBUG(ARCH)) { fprintf(debug_file, "SVR4 entry offset %s is greater than %lu\n", name, (unsigned long)ar->fnamesize); } return 2; } if (DEBUG(ARCH)) { fprintf(debug_file, "Replaced %s with %s\n", name, &ar->fnametab[entry]); } (void)strncpy(name, &ar->fnametab[entry], MAXPATHLEN); name[MAXPATHLEN] = '\0'; return 1; } #endif /*- *----------------------------------------------------------------------- * ArchFindMember -- * Locate a member of an archive, given the path of the archive and * the path of the desired member. If the archive is to be modified, * the mode should be "r+", if not, it should be "r". * * Input: * archive Path to the archive * member Name of member. If it is a path, only the last * component is used. * arhPtr Pointer to header structure to be filled in * mode The mode for opening the stream * * Results: * An FILE *, opened for reading and writing, positioned at the * start of the member's struct ar_hdr, or NULL if the member was * nonexistent. The current struct ar_hdr for member. * * Side Effects: * The passed struct ar_hdr structure is filled in. * *----------------------------------------------------------------------- */ static FILE * ArchFindMember(char *archive, char *member, struct ar_hdr *arhPtr, const char *mode) { FILE * arch; /* Stream to archive */ int size; /* Size of archive member */ char *cp; /* Useful character pointer */ char magic[SARMAG]; size_t len, tlen; arch = fopen(archive, mode); if (arch == NULL) { return NULL; } /* * We use the ARMAG string to make sure this is an archive we * can handle... */ if ((fread(magic, SARMAG, 1, arch) != 1) || (strncmp(magic, ARMAG, SARMAG) != 0)) { fclose(arch); return NULL; } /* * Because of space constraints and similar things, files are archived * using their final path components, not the entire thing, so we need * to point 'member' to the final component, if there is one, to make * the comparisons easier... */ cp = strrchr(member, '/'); if (cp != NULL) { member = cp + 1; } len = tlen = strlen(member); if (len > sizeof(arhPtr->AR_NAME)) { tlen = sizeof(arhPtr->AR_NAME); } while (fread((char *)arhPtr, sizeof(struct ar_hdr), 1, arch) == 1) { if (strncmp(arhPtr->AR_FMAG, ARFMAG, sizeof(arhPtr->AR_FMAG) ) != 0) { /* * The header is bogus, so the archive is bad * and there's no way we can recover... */ fclose(arch); return NULL; } else if (strncmp(member, arhPtr->AR_NAME, tlen) == 0) { /* * If the member's name doesn't take up the entire 'name' field, * we have to be careful of matching prefixes. Names are space- * padded to the right, so if the character in 'name' at the end * of the matched string is anything but a space, this isn't the * member we sought. */ if (tlen != sizeof(arhPtr->AR_NAME) && arhPtr->AR_NAME[tlen] != ' '){ goto skip; } else { /* * To make life easier, we reposition the file at the start * of the header we just read before we return the stream. * In a more general situation, it might be better to leave * the file at the actual member, rather than its header, but * not here... */ if (fseek(arch, -sizeof(struct ar_hdr), SEEK_CUR) != 0) { fclose(arch); return NULL; } return (arch); } } else #ifdef AR_EFMT1 /* * BSD 4.4 extended AR format: #1/, with name as the * first bytes of the file */ if (strncmp(arhPtr->AR_NAME, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0 && isdigit((unsigned char)arhPtr->AR_NAME[sizeof(AR_EFMT1) - 1])) { unsigned int elen = atoi(&arhPtr->AR_NAME[sizeof(AR_EFMT1)-1]); char ename[MAXPATHLEN + 1]; if (elen > MAXPATHLEN) { fclose(arch); return NULL; } if (fread(ename, elen, 1, arch) != 1) { fclose(arch); return NULL; } ename[elen] = '\0'; if (DEBUG(ARCH) || DEBUG(MAKE)) { fprintf(debug_file, "ArchFind: Extended format entry for %s\n", ename); } if (strncmp(ename, member, len) == 0) { /* Found as extended name */ if (fseek(arch, -sizeof(struct ar_hdr) - elen, SEEK_CUR) != 0) { fclose(arch); return NULL; } return (arch); } if (fseek(arch, -elen, SEEK_CUR) != 0) { fclose(arch); return NULL; } goto skip; } else #endif { skip: /* * This isn't the member we're after, so we need to advance the * stream's pointer to the start of the next header. Files are * padded with newlines to an even-byte boundary, so we need to * extract the size of the file from the 'size' field of the * header and round it up during the seek. */ arhPtr->AR_SIZE[sizeof(arhPtr->AR_SIZE)-1] = '\0'; size = (int)strtol(arhPtr->AR_SIZE, NULL, 10); if (fseek(arch, (size + 1) & ~1, SEEK_CUR) != 0) { fclose(arch); return NULL; } } } /* * We've looked everywhere, but the member is not to be found. Close the * archive and return NULL -- an error. */ fclose(arch); return NULL; } /*- *----------------------------------------------------------------------- * Arch_Touch -- * Touch a member of an archive. * * Input: * gn Node of member to touch * * Results: * The 'time' field of the member's header is updated. * * Side Effects: * The modification time of the entire archive is also changed. * For a library, this could necessitate the re-ranlib'ing of the * whole thing. * *----------------------------------------------------------------------- */ void Arch_Touch(GNode *gn) { FILE * arch; /* Stream open to archive, positioned properly */ struct ar_hdr arh; /* Current header describing member */ char *p1, *p2; arch = ArchFindMember(Var_Value(ARCHIVE, gn, &p1), Var_Value(MEMBER, gn, &p2), &arh, "r+"); free(p1); free(p2); snprintf(arh.AR_DATE, sizeof(arh.AR_DATE), "%-12ld", (long) now); if (arch != NULL) { (void)fwrite((char *)&arh, sizeof(struct ar_hdr), 1, arch); fclose(arch); } } /*- *----------------------------------------------------------------------- * Arch_TouchLib -- * Given a node which represents a library, touch the thing, making * sure that the table of contents also is touched. * * Input: * gn The node of the library to touch * * Results: * None. * * Side Effects: * Both the modification time of the library and of the RANLIBMAG * member are set to 'now'. * *----------------------------------------------------------------------- */ void #if !defined(RANLIBMAG) Arch_TouchLib(GNode *gn MAKE_ATTR_UNUSED) #else Arch_TouchLib(GNode *gn) #endif { #ifdef RANLIBMAG FILE * arch; /* Stream open to archive */ struct ar_hdr arh; /* Header describing table of contents */ struct utimbuf times; /* Times for utime() call */ arch = ArchFindMember(gn->path, UNCONST(RANLIBMAG), &arh, "r+"); snprintf(arh.AR_DATE, sizeof(arh.AR_DATE), "%-12ld", (long) now); if (arch != NULL) { (void)fwrite((char *)&arh, sizeof(struct ar_hdr), 1, arch); fclose(arch); times.actime = times.modtime = now; utime(gn->path, ×); } #endif } /*- *----------------------------------------------------------------------- * Arch_MTime -- * Return the modification time of a member of an archive. * * Input: * gn Node describing archive member * * Results: * The modification time(seconds). * * Side Effects: * The mtime field of the given node is filled in with the value * returned by the function. * *----------------------------------------------------------------------- */ time_t Arch_MTime(GNode *gn) { struct ar_hdr *arhPtr; /* Header of desired member */ time_t modTime; /* Modification time as an integer */ char *p1, *p2; arhPtr = ArchStatMember(Var_Value(ARCHIVE, gn, &p1), Var_Value(MEMBER, gn, &p2), TRUE); free(p1); free(p2); if (arhPtr != NULL) { modTime = (time_t)strtol(arhPtr->AR_DATE, NULL, 10); } else { modTime = 0; } gn->mtime = modTime; return (modTime); } /*- *----------------------------------------------------------------------- * Arch_MemMTime -- * Given a non-existent archive member's node, get its modification * time from its archived form, if it exists. * * Results: * The modification time. * * Side Effects: * The mtime field is filled in. * *----------------------------------------------------------------------- */ time_t Arch_MemMTime(GNode *gn) { LstNode ln; GNode *pgn; char *nameStart, *nameEnd; if (Lst_Open(gn->parents) != SUCCESS) { gn->mtime = 0; return (0); } while ((ln = Lst_Next(gn->parents)) != NULL) { pgn = (GNode *)Lst_Datum(ln); if (pgn->type & OP_ARCHV) { /* * If the parent is an archive specification and is being made * and its member's name matches the name of the node we were * given, record the modification time of the parent in the * child. We keep searching its parents in case some other * parent requires this child to exist... */ nameStart = strchr(pgn->name, '(') + 1; nameEnd = strchr(nameStart, ')'); if ((pgn->flags & REMAKE) && strncmp(nameStart, gn->name, nameEnd - nameStart) == 0) { gn->mtime = Arch_MTime(pgn); } } else if (pgn->flags & REMAKE) { /* * Something which isn't a library depends on the existence of * this target, so it needs to exist. */ gn->mtime = 0; break; } } Lst_Close(gn->parents); return (gn->mtime); } /*- *----------------------------------------------------------------------- * Arch_FindLib -- * Search for a library along the given search path. * * Input: * gn Node of library to find * path Search path * * Results: * None. * * Side Effects: * The node's 'path' field is set to the found path (including the * actual file name, not -l...). If the system can handle the -L * flag when linking (or we cannot find the library), we assume that * the user has placed the .LIBRARIES variable in the final linking * command (or the linker will know where to find it) and set the * TARGET variable for this node to be the node's name. Otherwise, * we set the TARGET variable to be the full path of the library, * as returned by Dir_FindFile. * *----------------------------------------------------------------------- */ void Arch_FindLib(GNode *gn, Lst path) { char *libName; /* file name for archive */ size_t sz = strlen(gn->name) + 6 - 2; libName = bmake_malloc(sz); snprintf(libName, sz, "lib%s.a", &gn->name[2]); gn->path = Dir_FindFile(libName, path); free(libName); #ifdef LIBRARIES Var_Set(TARGET, gn->name, gn, 0); #else Var_Set(TARGET, gn->path == NULL ? gn->name : gn->path, gn, 0); #endif /* LIBRARIES */ } /*- *----------------------------------------------------------------------- * Arch_LibOODate -- * Decide if a node with the OP_LIB attribute is out-of-date. Called * from Make_OODate to make its life easier. * * There are several ways for a library to be out-of-date that are * not available to ordinary files. In addition, there are ways * that are open to regular files that are not available to * libraries. A library that is only used as a source is never * considered out-of-date by itself. This does not preclude the * library's modification time from making its parent be out-of-date. * A library will be considered out-of-date for any of these reasons, * given that it is a target on a dependency line somewhere: * Its modification time is less than that of one of its * sources (gn->mtime < gn->cmgn->mtime). * Its modification time is greater than the time at which the * make began (i.e. it's been modified in the course * of the make, probably by archiving). * The modification time of one of its sources is greater than * the one of its RANLIBMAG member (i.e. its table of contents * is out-of-date). We don't compare of the archive time * vs. TOC time because they can be too close. In my * opinion we should not bother with the TOC at all since * this is used by 'ar' rules that affect the data contents * of the archive, not by ranlib rules, which affect the * TOC. * * Input: * gn The library's graph node * * Results: * TRUE if the library is out-of-date. FALSE otherwise. * * Side Effects: * The library will be hashed if it hasn't been already. * *----------------------------------------------------------------------- */ Boolean Arch_LibOODate(GNode *gn) { Boolean oodate; if (gn->type & OP_PHONY) { oodate = TRUE; } else if (OP_NOP(gn->type) && Lst_IsEmpty(gn->children)) { oodate = FALSE; } else if ((!Lst_IsEmpty(gn->children) && gn->cmgn == NULL) || (gn->mtime > now) || (gn->cmgn != NULL && gn->mtime < gn->cmgn->mtime)) { oodate = TRUE; } else { #ifdef RANLIBMAG struct ar_hdr *arhPtr; /* Header for __.SYMDEF */ int modTimeTOC; /* The table-of-contents's mod time */ arhPtr = ArchStatMember(gn->path, UNCONST(RANLIBMAG), FALSE); if (arhPtr != NULL) { modTimeTOC = (int)strtol(arhPtr->AR_DATE, NULL, 10); if (DEBUG(ARCH) || DEBUG(MAKE)) { fprintf(debug_file, "%s modified %s...", RANLIBMAG, Targ_FmtTime(modTimeTOC)); } oodate = (gn->cmgn == NULL || gn->cmgn->mtime > modTimeTOC); } else { /* * A library w/o a table of contents is out-of-date */ if (DEBUG(ARCH) || DEBUG(MAKE)) { fprintf(debug_file, "No t.o.c...."); } oodate = TRUE; } #else oodate = FALSE; #endif } return (oodate); } /*- *----------------------------------------------------------------------- * Arch_Init -- * Initialize things for this module. * * Results: * None. * * Side Effects: * The 'archives' list is initialized. * *----------------------------------------------------------------------- */ void Arch_Init(void) { archives = Lst_Init(FALSE); } /*- *----------------------------------------------------------------------- * Arch_End -- * Cleanup things for this module. * * Results: * None. * * Side Effects: * The 'archives' list is freed * *----------------------------------------------------------------------- */ void Arch_End(void) { #ifdef CLEANUP Lst_Destroy(archives, ArchFree); #endif } /*- *----------------------------------------------------------------------- * Arch_IsLib -- * Check if the node is a library * * Results: * True or False. * * Side Effects: * None. * *----------------------------------------------------------------------- */ int Arch_IsLib(GNode *gn) { static const char armag[] = "!\n"; char buf[sizeof(armag)-1]; int fd; if ((fd = open(gn->path, O_RDONLY)) == -1) return FALSE; if (read(fd, buf, sizeof(buf)) != sizeof(buf)) { (void)close(fd); return FALSE; } (void)close(fd); return memcmp(buf, armag, sizeof(buf)) == 0; } Index: stable/12/contrib/bmake/bmake.1 =================================================================== --- stable/12/contrib/bmake/bmake.1 (revision 361673) +++ stable/12/contrib/bmake/bmake.1 (revision 361674) @@ -1,2412 +1,2419 @@ -.\" $NetBSD: make.1,v 1.272 2018/04/02 04:26:17 dholland Exp $ +.\" $NetBSD: make.1,v 1.273 2018/05/27 01:14:51 christos Exp $ .\" .\" Copyright (c) 1990, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" from: @(#)make.1 8.4 (Berkeley) 3/19/94 .\" -.Dd June 22, 2017 +.Dd May 26, 2018 .Dt BMAKE 1 .Os .Sh NAME .Nm bmake .Nd maintain program dependencies .Sh SYNOPSIS .Nm .Op Fl BeikNnqrstWwX .Op Fl C Ar directory .Op Fl D Ar variable .Op Fl d Ar flags .Op Fl f Ar makefile .Op Fl I Ar directory .Op Fl J Ar private .Op Fl j Ar max_jobs .Op Fl m Ar directory .Op Fl T Ar file .Op Fl V Ar variable .Op Fl v Ar variable .Op Ar variable=value .Op Ar target ... .Sh DESCRIPTION .Nm is a program designed to simplify the maintenance of other programs. Its input is a list of specifications as to the files upon which programs and other files depend. If no .Fl f Ar makefile makefile option is given, .Nm will try to open .Ql Pa makefile then .Ql Pa Makefile in order to find the specifications. If the file .Ql Pa .depend exists, it is read (see .Xr mkdep 1 ) . .Pp This manual page is intended as a reference document only. For a more thorough description of .Nm and makefiles, please refer to .%T "PMake \- A Tutorial" . .Pp .Nm will prepend the contents of the .Va MAKEFLAGS environment variable to the command line arguments before parsing them. .Pp The options are as follows: .Bl -tag -width Ds .It Fl B Try to be backwards compatible by executing a single shell per command and by executing the commands to make the sources of a dependency line in sequence. .It Fl C Ar directory Change to .Ar directory before reading the makefiles or doing anything else. If multiple .Fl C options are specified, each is interpreted relative to the previous one: .Fl C Pa / Fl C Pa etc is equivalent to .Fl C Pa /etc . .It Fl D Ar variable Define .Ar variable to be 1, in the global context. .It Fl d Ar [-]flags Turn on debugging, and specify which portions of .Nm are to print debugging information. Unless the flags are preceded by .Ql \- they are added to the .Va MAKEFLAGS environment variable and will be processed by any child make processes. By default, debugging information is printed to standard error, but this can be changed using the .Ar F debugging flag. The debugging output is always unbuffered; in addition, if debugging is enabled but debugging output is not directed to standard output, then the standard output is line buffered. .Ar Flags is one or more of the following: .Bl -tag -width Ds .It Ar A Print all possible debugging information; equivalent to specifying all of the debugging flags. .It Ar a Print debugging information about archive searching and caching. .It Ar C Print debugging information about current working directory. .It Ar c Print debugging information about conditional evaluation. .It Ar d Print debugging information about directory searching and caching. .It Ar e Print debugging information about failed commands and targets. .It Ar F Ns Oo Sy \&+ Oc Ns Ar filename Specify where debugging output is written. This must be the last flag, because it consumes the remainder of the argument. If the character immediately after the .Ql F flag is .Ql \&+ , then the file will be opened in append mode; otherwise the file will be overwritten. If the file name is .Ql stdout or .Ql stderr then debugging output will be written to the standard output or standard error output file descriptors respectively (and the .Ql \&+ option has no effect). Otherwise, the output will be written to the named file. If the file name ends .Ql .%d then the .Ql %d is replaced by the pid. .It Ar f Print debugging information about loop evaluation. .It Ar "g1" Print the input graph before making anything. .It Ar "g2" Print the input graph after making everything, or before exiting on error. .It Ar "g3" Print the input graph before exiting on error. .It Ar j Print debugging information about running multiple shells. .It Ar l Print commands in Makefiles regardless of whether or not they are prefixed by .Ql @ or other "quiet" flags. Also known as "loud" behavior. .It Ar M Print debugging information about "meta" mode decisions about targets. .It Ar m Print debugging information about making targets, including modification dates. .It Ar n Don't delete the temporary command scripts created when running commands. These temporary scripts are created in the directory referred to by the .Ev TMPDIR environment variable, or in .Pa /tmp if .Ev TMPDIR is unset or set to the empty string. The temporary scripts are created by .Xr mkstemp 3 , and have names of the form .Pa makeXXXXXX . .Em NOTE : This can create many files in .Ev TMPDIR or .Pa /tmp , so use with care. .It Ar p Print debugging information about makefile parsing. .It Ar s Print debugging information about suffix-transformation rules. .It Ar t Print debugging information about target list maintenance. .It Ar V Force the .Fl V option to print raw values of variables, overriding the default behavior set via .Va .MAKE.EXPAND_VARIABLES . .It Ar v Print debugging information about variable assignment. .It Ar x Run shell commands with .Fl x so the actual commands are printed as they are executed. .El .It Fl e Specify that environment variables override macro assignments within makefiles. .It Fl f Ar makefile Specify a makefile to read instead of the default .Ql Pa makefile . If .Ar makefile is .Ql Fl , standard input is read. Multiple makefiles may be specified, and are read in the order specified. .It Fl I Ar directory Specify a directory in which to search for makefiles and included makefiles. The system makefile directory (or directories, see the .Fl m option) is automatically included as part of this list. .It Fl i Ignore non-zero exit of shell commands in the makefile. Equivalent to specifying .Ql Fl before each command line in the makefile. .It Fl J Ar private This option should .Em not be specified by the user. .Pp When the .Ar j option is in use in a recursive build, this option is passed by a make to child makes to allow all the make processes in the build to cooperate to avoid overloading the system. .It Fl j Ar max_jobs Specify the maximum number of jobs that .Nm may have running at any one time. The value is saved in .Va .MAKE.JOBS . Turns compatibility mode off, unless the .Ar B flag is also specified. When compatibility mode is off, all commands associated with a target are executed in a single shell invocation as opposed to the traditional one shell invocation per line. This can break traditional scripts which change directories on each command invocation and then expect to start with a fresh environment on the next line. It is more efficient to correct the scripts rather than turn backwards compatibility on. .It Fl k Continue processing after errors are encountered, but only on those targets that do not depend on the target whose creation caused the error. .It Fl m Ar directory Specify a directory in which to search for sys.mk and makefiles included via the .Ao Ar file Ac Ns -style include statement. The .Fl m option can be used multiple times to form a search path. This path will override the default system include path: /usr/share/mk. Furthermore the system include path will be appended to the search path used for .Qo Ar file Qc Ns -style include statements (see the .Fl I option). .Pp If a file or directory name in the .Fl m argument (or the .Ev MAKESYSPATH environment variable) starts with the string .Qq \&.../ then .Nm will search for the specified file or directory named in the remaining part of the argument string. The search starts with the current directory of the Makefile and then works upward towards the root of the file system. If the search is successful, then the resulting directory replaces the .Qq \&.../ specification in the .Fl m argument. If used, this feature allows .Nm to easily search in the current source tree for customized sys.mk files (e.g., by using .Qq \&.../mk/sys.mk as an argument). .It Fl n Display the commands that would have been executed, but do not actually execute them unless the target depends on the .MAKE special source (see below). .It Fl N Display the commands which would have been executed, but do not actually execute any of them; useful for debugging top-level makefiles without descending into subdirectories. .It Fl q Do not execute any commands, but exit 0 if the specified targets are up-to-date and 1, otherwise. .It Fl r Do not use the built-in rules specified in the system makefile. .It Fl s Do not echo any commands as they are executed. Equivalent to specifying .Ql Ic @ before each command line in the makefile. .It Fl T Ar tracefile When used with the .Fl j flag, append a trace record to .Ar tracefile for each job started and completed. .It Fl t Rather than re-building a target as specified in the makefile, create it or update its modification time to make it appear up-to-date. .It Fl V Ar variable Print the value of .Ar variable . Do not build any targets. Multiple instances of this option may be specified; the variables will be printed one per line, with a blank line for each null or undefined variable. The value printed is extracted from the global context after all makefiles have been read. By default, the raw variable contents (which may include additional unexpanded variable references) are shown. If .Ar variable contains a .Ql \&$ then the value will be recursively expanded to its complete resultant text before printing. The expanded value will also be printed if .Va .MAKE.EXPAND_VARIABLES is set to true and the .Fl dV option has not been used to override it. Note that loop-local and target-local variables, as well as values taken temporarily by global variables during makefile processing, are not accessible via this option. The .Fl dv debug mode can be used to see these at the cost of generating substantial extraneous output. .It Fl v Ar variable Like .Fl V but the variable is always expanded to its complete value. .It Fl W Treat any warnings during makefile parsing as errors. .It Fl w Print entering and leaving directory messages, pre and post processing. .It Fl X Don't export variables passed on the command line to the environment individually. Variables passed on the command line are still exported via the .Va MAKEFLAGS environment variable. This option may be useful on systems which have a small limit on the size of command arguments. .It Ar variable=value Set the value of the variable .Ar variable to .Ar value . Normally, all values passed on the command line are also exported to sub-makes in the environment. The .Fl X flag disables this behavior. Variable assignments should follow options for POSIX compatibility but no ordering is enforced. .El .Pp There are seven different types of lines in a makefile: file dependency specifications, shell commands, variable assignments, include statements, conditional directives, for loops, and comments. .Pp In general, lines may be continued from one line to the next by ending them with a backslash .Pq Ql \e . The trailing newline character and initial whitespace on the following line are compressed into a single space. .Sh FILE DEPENDENCY SPECIFICATIONS Dependency lines consist of one or more targets, an operator, and zero or more sources. This creates a relationship where the targets .Dq depend on the sources and are usually created from them. The exact relationship between the target and the source is determined by the operator that separates them. The three operators are as follows: .Bl -tag -width flag .It Ic \&: A target is considered out-of-date if its modification time is less than those of any of its sources. Sources for a target accumulate over dependency lines when this operator is used. The target is removed if .Nm is interrupted. .It Ic \&! Targets are always re-created, but not until all sources have been examined and re-created as necessary. Sources for a target accumulate over dependency lines when this operator is used. The target is removed if .Nm is interrupted. .It Ic \&:: If no sources are specified, the target is always re-created. Otherwise, a target is considered out-of-date if any of its sources has been modified more recently than the target. Sources for a target do not accumulate over dependency lines when this operator is used. The target will not be removed if .Nm is interrupted. .El .Pp Targets and sources may contain the shell wildcard values .Ql \&? , .Ql * , .Ql [] , and .Ql {} . The values .Ql \&? , .Ql * , and .Ql [] may only be used as part of the final component of the target or source, and must be used to describe existing files. The value .Ql {} need not necessarily be used to describe existing files. Expansion is in directory order, not alphabetically as done in the shell. .Sh SHELL COMMANDS Each target may have associated with it one or more lines of shell commands, normally used to create the target. Each of the lines in this script .Em must be preceded by a tab. (For historical reasons, spaces are not accepted.) While targets can appear in many dependency lines if desired, by default only one of these rules may be followed by a creation script. If the .Ql Ic \&:: operator is used, however, all rules may include scripts and the scripts are executed in the order found. .Pp Each line is treated as a separate shell command, unless the end of line is escaped with a backslash .Pq Ql \e in which case that line and the next are combined. .\" The escaped newline is retained and passed to the shell, which .\" normally ignores it. .\" However, the tab at the beginning of the following line is removed. If the first characters of the command are any combination of .Ql Ic @ , .Ql Ic + , or .Ql Ic \- , the command is treated specially. A .Ql Ic @ causes the command not to be echoed before it is executed. A .Ql Ic + causes the command to be executed even when .Fl n is given. This is similar to the effect of the .MAKE special source, except that the effect can be limited to a single line of a script. A .Ql Ic \- in compatibility mode causes any non-zero exit status of the command line to be ignored. .Pp When .Nm is run in jobs mode with .Fl j Ar max_jobs , the entire script for the target is fed to a single instance of the shell. In compatibility (non-jobs) mode, each command is run in a separate process. If the command contains any shell meta characters .Pq Ql #=|^(){};&<>*?[]:$`\e\en it will be passed to the shell; otherwise .Nm will attempt direct execution. If a line starts with .Ql Ic \- and the shell has ErrCtl enabled then failure of the command line will be ignored as in compatibility mode. Otherwise .Ql Ic \- affects the entire job; the script will stop at the first command line that fails, but the target will not be deemed to have failed. .Pp Makefiles should be written so that the mode of .Nm operation does not change their behavior. For example, any command which needs to use .Dq cd or .Dq chdir without potentially changing the directory for subsequent commands should be put in parentheses so it executes in a subshell. To force the use of one shell, escape the line breaks so as to make the whole script one command. For example: .Bd -literal -offset indent avoid-chdir-side-effects: @echo Building $@ in `pwd` @(cd ${.CURDIR} && ${MAKE} $@) @echo Back in `pwd` ensure-one-shell-regardless-of-mode: @echo Building $@ in `pwd`; \e (cd ${.CURDIR} && ${MAKE} $@); \e echo Back in `pwd` .Ed .Pp Since .Nm will .Xr chdir 2 to .Ql Va .OBJDIR before executing any targets, each child process starts with that as its current working directory. .Sh VARIABLE ASSIGNMENTS Variables in make are much like variables in the shell, and, by tradition, consist of all upper-case letters. .Ss Variable assignment modifiers The five operators that can be used to assign values to variables are as follows: .Bl -tag -width Ds .It Ic \&= Assign the value to the variable. Any previous value is overridden. .It Ic \&+= Append the value to the current value of the variable. .It Ic \&?= Assign the value to the variable if it is not already defined. .It Ic \&:= Assign with expansion, i.e. expand the value before assigning it to the variable. Normally, expansion is not done until the variable is referenced. .Em NOTE : References to undefined variables are .Em not expanded. This can cause problems when variable modifiers are used. .It Ic \&!= Expand the value and pass it to the shell for execution and assign the result to the variable. Any newlines in the result are replaced with spaces. .El .Pp Any white-space before the assigned .Ar value is removed; if the value is being appended, a single space is inserted between the previous contents of the variable and the appended value. .Pp Variables are expanded by surrounding the variable name with either curly braces .Pq Ql {} or parentheses .Pq Ql () and preceding it with a dollar sign .Pq Ql \&$ . If the variable name contains only a single letter, the surrounding braces or parentheses are not required. This shorter form is not recommended. .Pp If the variable name contains a dollar, then the name itself is expanded first. This allows almost arbitrary variable names, however names containing dollar, braces, parenthesis, or whitespace are really best avoided! .Pp If the result of expanding a variable contains a dollar sign .Pq Ql \&$ the string is expanded again. .Pp Variable substitution occurs at three distinct times, depending on where the variable is being used. .Bl -enum .It Variables in dependency lines are expanded as the line is read. .It Variables in shell commands are expanded when the shell command is executed. .It .Dq .for loop index variables are expanded on each loop iteration. Note that other variables are not expanded inside loops so the following example code: .Bd -literal -offset indent .Dv .for i in 1 2 3 a+= ${i} j= ${i} b+= ${j} .Dv .endfor all: @echo ${a} @echo ${b} .Ed will print: .Bd -literal -offset indent 1 2 3 3 3 3 .Ed Because while ${a} contains .Dq 1 2 3 after the loop is executed, ${b} contains .Dq ${j} ${j} ${j} which expands to .Dq 3 3 3 since after the loop completes ${j} contains .Dq 3 . .El .Ss Variable classes The four different classes of variables (in order of increasing precedence) are: .Bl -tag -width Ds .It Environment variables Variables defined as part of .Nm Ns 's environment. .It Global variables Variables defined in the makefile or in included makefiles. .It Command line variables Variables defined as part of the command line. .It Local variables Variables that are defined specific to a certain target. .El .Pp Local variables are all built in and their values vary magically from target to target. It is not currently possible to define new local variables. The seven local variables are as follows: .Bl -tag -width ".ARCHIVE" -offset indent .It Va .ALLSRC The list of all sources for this target; also known as .Ql Va \&> . .It Va .ARCHIVE The name of the archive file; also known as .Ql Va \&! . .It Va .IMPSRC In suffix-transformation rules, the name/path of the source from which the target is to be transformed (the .Dq implied source); also known as .Ql Va \&< . It is not defined in explicit rules. .It Va .MEMBER The name of the archive member; also known as .Ql Va % . .It Va .OODATE The list of sources for this target that were deemed out-of-date; also known as .Ql Va \&? . .It Va .PREFIX The file prefix of the target, containing only the file portion, no suffix or preceding directory components; also known as .Ql Va * . The suffix must be one of the known suffixes declared with .Ic .SUFFIXES or it will not be recognized. .It Va .TARGET The name of the target; also known as .Ql Va @ . For compatibility with other makes this is an alias for .Ic .ARCHIVE in archive member rules. .El .Pp The shorter forms .Ql ( Va > , .Ql Va \&! , .Ql Va < , .Ql Va % , .Ql Va \&? , .Ql Va * , and .Ql Va @ ) are permitted for backward compatibility with historical makefiles and legacy POSIX make and are not recommended. .Pp Variants of these variables with the punctuation followed immediately by .Ql D or .Ql F , e.g. .Ql Va $(@D) , are legacy forms equivalent to using the .Ql :H and .Ql :T modifiers. These forms are accepted for compatibility with .At V makefiles and POSIX but are not recommended. .Pp Four of the local variables may be used in sources on dependency lines because they expand to the proper value for each target on the line. These variables are .Ql Va .TARGET , .Ql Va .PREFIX , .Ql Va .ARCHIVE , and .Ql Va .MEMBER . .Ss Additional built-in variables In addition, .Nm sets or knows about the following variables: .Bl -tag -width .MAKEOVERRIDES .It Va \&$ A single dollar sign .Ql \&$ , i.e. .Ql \&$$ expands to a single dollar sign. .It Va .ALLTARGETS The list of all targets encountered in the Makefile. If evaluated during Makefile parsing, lists only those targets encountered thus far. .It Va .CURDIR A path to the directory where .Nm was executed. Refer to the description of .Ql Ev PWD for more details. .It Va .INCLUDEDFROMDIR The directory of the file this Makefile was included from. .It Va .INCLUDEDFROMFILE The filename of the file this Makefile was included from. .It Ev MAKE The name that .Nm was executed with .Pq Va argv[0] . For compatibility .Nm also sets .Va .MAKE with the same value. The preferred variable to use is the environment variable .Ev MAKE because it is more compatible with other versions of .Nm and cannot be confused with the special target with the same name. .It Va .MAKE.DEPENDFILE Names the makefile (default .Ql Pa .depend ) from which generated dependencies are read. .It Va .MAKE.EXPAND_VARIABLES A boolean that controls the default behavior of the .Fl V option. If true, variable values printed with .Fl V are fully expanded; if false, the raw variable contents (which may include additional unexpanded variable references) are shown. .It Va .MAKE.EXPORTED The list of variables exported by .Nm . .It Va .MAKE.JOBS The argument to the .Fl j option. .It Va .MAKE.JOB.PREFIX If .Nm is run with .Ar j then output for each target is prefixed with a token .Ql --- target --- the first part of which can be controlled via .Va .MAKE.JOB.PREFIX . If .Va .MAKE.JOB.PREFIX is empty, no token is printed. .br For example: .Li .MAKE.JOB.PREFIX=${.newline}---${.MAKE:T}[${.MAKE.PID}] would produce tokens like .Ql ---make[1234] target --- making it easier to track the degree of parallelism being achieved. .It Ev MAKEFLAGS The environment variable .Ql Ev MAKEFLAGS may contain anything that may be specified on .Nm Ns 's command line. Anything specified on .Nm Ns 's command line is appended to the .Ql Ev MAKEFLAGS variable which is then entered into the environment for all programs which .Nm executes. .It Va .MAKE.LEVEL The recursion depth of .Nm . The initial instance of .Nm will be 0, and an incremented value is put into the environment to be seen by the next generation. This allows tests like: .Li .if ${.MAKE.LEVEL} == 0 to protect things which should only be evaluated in the initial instance of .Nm . .It Va .MAKE.MAKEFILE_PREFERENCE The ordered list of makefile names (default .Ql Pa makefile , .Ql Pa Makefile ) that .Nm will look for. .It Va .MAKE.MAKEFILES The list of makefiles read by .Nm , which is useful for tracking dependencies. Each makefile is recorded only once, regardless of the number of times read. .It Va .MAKE.MODE Processed after reading all makefiles. Can affect the mode that .Nm runs in. It can contain a number of keywords: .Bl -hang -width missing-filemon=bf. .It Pa compat Like .Fl B , puts .Nm into "compat" mode. .It Pa meta Puts .Nm into "meta" mode, where meta files are created for each target to capture the command run, the output generated and if .Xr filemon 4 is available, the system calls which are of interest to .Nm . The captured output can be very useful when diagnosing errors. .It Pa curdirOk= Ar bf Normally .Nm will not create .meta files in .Ql Va .CURDIR . This can be overridden by setting .Va bf to a value which represents True. .It Pa missing-meta= Ar bf If .Va bf is True, then a missing .meta file makes the target out-of-date. .It Pa missing-filemon= Ar bf If .Va bf is True, then missing filemon data makes the target out-of-date. .It Pa nofilemon Do not use .Xr filemon 4 . .It Pa env For debugging, it can be useful to include the environment in the .meta file. .It Pa verbose If in "meta" mode, print a clue about the target being built. This is useful if the build is otherwise running silently. The message printed the value of: .Va .MAKE.META.PREFIX . .It Pa ignore-cmd Some makefiles have commands which are simply not stable. This keyword causes them to be ignored for determining whether a target is out of date in "meta" mode. See also .Ic .NOMETA_CMP . .It Pa silent= Ar bf If .Va bf is True, when a .meta file is created, mark the target .Ic .SILENT . .El .It Va .MAKE.META.BAILIWICK In "meta" mode, provides a list of prefixes which match the directories controlled by .Nm . If a file that was generated outside of .Va .OBJDIR but within said bailiwick is missing, the current target is considered out-of-date. .It Va .MAKE.META.CREATED In "meta" mode, this variable contains a list of all the meta files updated. If not empty, it can be used to trigger processing of .Va .MAKE.META.FILES . .It Va .MAKE.META.FILES In "meta" mode, this variable contains a list of all the meta files used (updated or not). This list can be used to process the meta files to extract dependency information. .It Va .MAKE.META.IGNORE_PATHS Provides a list of path prefixes that should be ignored; because the contents are expected to change over time. The default list includes: .Ql Pa /dev /etc /proc /tmp /var/run /var/tmp .It Va .MAKE.META.IGNORE_PATTERNS Provides a list of patterns to match against pathnames. Ignore any that match. .It Va .MAKE.META.IGNORE_FILTER Provides a list of variable modifiers to apply to each pathname. Ignore if the expansion is an empty string. .It Va .MAKE.META.PREFIX Defines the message printed for each meta file updated in "meta verbose" mode. The default value is: .Dl Building ${.TARGET:H:tA}/${.TARGET:T} .It Va .MAKEOVERRIDES This variable is used to record the names of variables assigned to on the command line, so that they may be exported as part of .Ql Ev MAKEFLAGS . This behavior can be disabled by assigning an empty value to .Ql Va .MAKEOVERRIDES within a makefile. Extra variables can be exported from a makefile by appending their names to .Ql Va .MAKEOVERRIDES . .Ql Ev MAKEFLAGS is re-exported whenever .Ql Va .MAKEOVERRIDES is modified. .It Va .MAKE.PATH_FILEMON If .Nm was built with .Xr filemon 4 support, this is set to the path of the device node. This allows makefiles to test for this support. .It Va .MAKE.PID The process-id of .Nm . .It Va .MAKE.PPID The parent process-id of .Nm . .It Va .MAKE.SAVE_DOLLARS value should be a boolean that controls whether .Ql $$ are preserved when doing .Ql := assignments. The default is false, for backwards compatibility. Set to true for compatability with other makes. If set to false, .Ql $$ becomes .Ql $ per normal evaluation rules. .It Va MAKE_PRINT_VAR_ON_ERROR When .Nm stops due to an error, it sets .Ql Va .ERROR_TARGET to the name of the target that failed, .Ql Va .ERROR_CMD to the commands of the failed target, and in "meta" mode, it also sets .Ql Va .ERROR_CWD to the .Xr getcwd 3 , and .Ql Va .ERROR_META_FILE to the path of the meta file (if any) describing the failed target. It then prints its name and the value of .Ql Va .CURDIR as well as the value of any variables named in .Ql Va MAKE_PRINT_VAR_ON_ERROR . .It Va .newline This variable is simply assigned a newline character as its value. This allows expansions using the .Cm \&:@ modifier to put a newline between iterations of the loop rather than a space. For example, the printing of .Ql Va MAKE_PRINT_VAR_ON_ERROR could be done as ${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'${.newline}@}. .It Va .OBJDIR A path to the directory where the targets are built. Its value is determined by trying to .Xr chdir 2 to the following directories in order and using the first match: .Bl -enum .It .Ev ${MAKEOBJDIRPREFIX}${.CURDIR} .Pp (Only if .Ql Ev MAKEOBJDIRPREFIX is set in the environment or on the command line.) .It .Ev ${MAKEOBJDIR} .Pp (Only if .Ql Ev MAKEOBJDIR is set in the environment or on the command line.) .It .Ev ${.CURDIR} Ns Pa /obj. Ns Ev ${MACHINE} .It .Ev ${.CURDIR} Ns Pa /obj .It .Pa /usr/obj/ Ns Ev ${.CURDIR} .It .Ev ${.CURDIR} .El .Pp Variable expansion is performed on the value before it's used, so expressions such as .Dl ${.CURDIR:S,^/usr/src,/var/obj,} may be used. This is especially useful with .Ql Ev MAKEOBJDIR . .Pp .Ql Va .OBJDIR may be modified in the makefile via the special target .Ql Ic .OBJDIR . In all cases, .Nm will .Xr chdir 2 to the specified directory if it exists, and set .Ql Va .OBJDIR and .Ql Ev PWD to that directory before executing any targets. . .It Va .PARSEDIR A path to the directory of the current .Ql Pa Makefile being parsed. .It Va .PARSEFILE The basename of the current .Ql Pa Makefile being parsed. This variable and .Ql Va .PARSEDIR are both set only while the .Ql Pa Makefiles are being parsed. If you want to retain their current values, assign them to a variable using assignment with expansion: .Pq Ql Cm \&:= . .It Va .PATH A variable that represents the list of directories that .Nm will search for files. The search list should be updated using the target .Ql Va .PATH rather than the variable. .It Ev PWD Alternate path to the current directory. .Nm normally sets .Ql Va .CURDIR to the canonical path given by .Xr getcwd 3 . However, if the environment variable .Ql Ev PWD is set and gives a path to the current directory, then .Nm sets .Ql Va .CURDIR to the value of .Ql Ev PWD instead. This behavior is disabled if .Ql Ev MAKEOBJDIRPREFIX is set or .Ql Ev MAKEOBJDIR contains a variable transform. .Ql Ev PWD is set to the value of .Ql Va .OBJDIR for all programs which .Nm executes. .It Ev .TARGETS The list of targets explicitly specified on the command line, if any. .It Ev VPATH Colon-separated .Pq Dq \&: lists of directories that .Nm will search for files. The variable is supported for compatibility with old make programs only, use .Ql Va .PATH instead. .El .Ss Variable modifiers Variable expansion may be modified to select or modify each word of the variable (where a .Dq word is white-space delimited sequence of characters). The general format of a variable expansion is as follows: .Pp .Dl ${variable[:modifier[:...]]} .Pp Each modifier begins with a colon, which may be escaped with a backslash .Pq Ql \e . .Pp A set of modifiers can be specified via a variable, as follows: .Pp .Dl modifier_variable=modifier[:...] .Dl ${variable:${modifier_variable}[:...]} .Pp In this case the first modifier in the modifier_variable does not start with a colon, since that must appear in the referencing variable. If any of the modifiers in the modifier_variable contain a dollar sign .Pq Ql $ , these must be doubled to avoid early expansion. .Pp The supported modifiers are: .Bl -tag -width EEE .It Cm \&:E Replaces each word in the variable with its suffix. .It Cm \&:H Replaces each word in the variable with everything but the last component. .It Cm \&:M Ns Ar pattern Select only those words that match .Ar pattern . The standard shell wildcard characters .Pf ( Ql * , .Ql \&? , and .Ql Oo Oc ) may be used. The wildcard characters may be escaped with a backslash .Pq Ql \e . As a consequence of the way values are split into words, matched, and then joined, a construct like .Dl ${VAR:M*} will normalize the inter-word spacing, removing all leading and trailing space, and converting multiple consecutive spaces to single spaces. . .It Cm \&:N Ns Ar pattern This is identical to .Ql Cm \&:M , but selects all words which do not match .Ar pattern . .It Cm \&:O Order every word in variable alphabetically. To sort words in reverse order use the .Ql Cm \&:O:[-1..1] combination of modifiers. .It Cm \&:Ox Randomize words in variable. The results will be different each time you are referring to the modified variable; use the assignment with expansion .Pq Ql Cm \&:= to prevent such behavior. For example, .Bd -literal -offset indent LIST= uno due tre quattro RANDOM_LIST= ${LIST:Ox} STATIC_RANDOM_LIST:= ${LIST:Ox} all: @echo "${RANDOM_LIST}" @echo "${RANDOM_LIST}" @echo "${STATIC_RANDOM_LIST}" @echo "${STATIC_RANDOM_LIST}" .Ed may produce output similar to: .Bd -literal -offset indent quattro due tre uno tre due quattro uno due uno quattro tre due uno quattro tre .Ed .It Cm \&:Q Quotes every shell meta-character in the variable, so that it can be passed +safely to the shell. +.It Cm \&:q +Quotes every shell meta-character in the variable, and also doubles +.Sq $ +characters so that it can be passed safely through recursive invocations of .Nm . +This is equivalent to: +.Sq \&:S/\e\&$/&&/g:Q . .It Cm \&:R Replaces each word in the variable with everything but its suffix. .It Cm \&:range[=count] The value is an integer sequence representing the words of the original value, or the supplied .Va count . .It Cm \&:gmtime[=utc] The value is a format string for .Xr strftime 3 , using .Xr gmtime 3 . If a .Va utc value is not provided or is 0, the current time is used. .It Cm \&:hash Compute a 32-bit hash of the value and encode it as hex digits. .It Cm \&:localtime[=utc] The value is a format string for .Xr strftime 3 , using .Xr localtime 3 . If a .Va utc value is not provided or is 0, the current time is used. .It Cm \&:tA Attempt to convert variable to an absolute path using .Xr realpath 3 , if that fails, the value is unchanged. .It Cm \&:tl Converts variable to lower-case letters. .It Cm \&:ts Ns Ar c Words in the variable are normally separated by a space on expansion. This modifier sets the separator to the character .Ar c . If .Ar c is omitted, then no separator is used. The common escapes (including octal numeric codes), work as expected. .It Cm \&:tu Converts variable to upper-case letters. .It Cm \&:tW Causes the value to be treated as a single word (possibly containing embedded white space). See also .Ql Cm \&:[*] . .It Cm \&:tw Causes the value to be treated as a sequence of words delimited by white space. See also .Ql Cm \&:[@] . .Sm off .It Cm \&:S No \&/ Ar old_string No \&/ Ar new_string No \&/ Op Cm 1gW .Sm on Modify the first occurrence of .Ar old_string in the variable's value, replacing it with .Ar new_string . If a .Ql g is appended to the last slash of the pattern, all occurrences in each word are replaced. If a .Ql 1 is appended to the last slash of the pattern, only the first word is affected. If a .Ql W is appended to the last slash of the pattern, then the value is treated as a single word (possibly containing embedded white space). If .Ar old_string begins with a caret .Pq Ql ^ , .Ar old_string is anchored at the beginning of each word. If .Ar old_string ends with a dollar sign .Pq Ql \&$ , it is anchored at the end of each word. Inside .Ar new_string , an ampersand .Pq Ql & is replaced by .Ar old_string (without any .Ql ^ or .Ql \&$ ) . Any character may be used as a delimiter for the parts of the modifier string. The anchoring, ampersand and delimiter characters may be escaped with a backslash .Pq Ql \e . .Pp Variable expansion occurs in the normal fashion inside both .Ar old_string and .Ar new_string with the single exception that a backslash is used to prevent the expansion of a dollar sign .Pq Ql \&$ , not a preceding dollar sign as is usual. .Sm off .It Cm \&:C No \&/ Ar pattern No \&/ Ar replacement No \&/ Op Cm 1gW .Sm on The .Cm \&:C modifier is just like the .Cm \&:S modifier except that the old and new strings, instead of being simple strings, are an extended regular expression (see .Xr regex 3 ) string .Ar pattern and an .Xr ed 1 Ns \-style string .Ar replacement . Normally, the first occurrence of the pattern .Ar pattern in each word of the value is substituted with .Ar replacement . The .Ql 1 modifier causes the substitution to apply to at most one word; the .Ql g modifier causes the substitution to apply to as many instances of the search pattern .Ar pattern as occur in the word or words it is found in; the .Ql W modifier causes the value to be treated as a single word (possibly containing embedded white space). Note that .Ql 1 and .Ql g are orthogonal; the former specifies whether multiple words are potentially affected, the latter whether multiple substitutions can potentially occur within each affected word. .Pp As for the .Cm \&:S modifier, the .Ar pattern and .Ar replacement are subjected to variable expansion before being parsed as regular expressions. .It Cm \&:T Replaces each word in the variable with its last component. .It Cm \&:u Remove adjacent duplicate words (like .Xr uniq 1 ) . .Sm off .It Cm \&:\&? Ar true_string Cm \&: Ar false_string .Sm on If the variable name (not its value), when parsed as a .if conditional expression, evaluates to true, return as its value the .Ar true_string , otherwise return the .Ar false_string . Since the variable name is used as the expression, \&:\&? must be the first modifier after the variable name itself - which will, of course, usually contain variable expansions. A common error is trying to use expressions like .Dl ${NUMBERS:M42:?match:no} which actually tests defined(NUMBERS), to determine is any words match "42" you need to use something like: .Dl ${"${NUMBERS:M42}" != \&"\&":?match:no} . .It Ar :old_string=new_string This is the .At V style variable substitution. It must be the last modifier specified. If .Ar old_string or .Ar new_string do not contain the pattern matching character .Ar % then it is assumed that they are anchored at the end of each word, so only suffixes or entire words may be replaced. Otherwise .Ar % is the substring of .Ar old_string to be replaced in .Ar new_string . .Pp Variable expansion occurs in the normal fashion inside both .Ar old_string and .Ar new_string with the single exception that a backslash is used to prevent the expansion of a dollar sign .Pq Ql \&$ , not a preceding dollar sign as is usual. .Sm off .It Cm \&:@ Ar temp Cm @ Ar string Cm @ .Sm on This is the loop expansion mechanism from the OSF Development Environment (ODE) make. Unlike .Cm \&.for loops expansion occurs at the time of reference. Assign .Ar temp to each word in the variable and evaluate .Ar string . The ODE convention is that .Ar temp should start and end with a period. For example. .Dl ${LINKS:@.LINK.@${LN} ${TARGET} ${.LINK.}@} .Pp However a single character variable is often more readable: .Dl ${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'${.newline}@} .It Cm \&:_[=var] Save the current variable value in .Ql $_ or the named .Va var for later reference. Example usage: .Bd -literal -offset indent M_cmpv.units = 1 1000 1000000 M_cmpv = S,., ,g:_:range:@i@+ $${_:[-$$i]} \&\\ \\* $${M_cmpv.units:[$$i]}@:S,^,expr 0 ,1:sh .Dv .if ${VERSION:${M_cmpv}} < ${3.1.12:L:${M_cmpv}} .Ed Here .Ql $_ is used to save the result of the .Ql :S modifier which is later referenced using the index values from .Ql :range . .It Cm \&:U Ns Ar newval If the variable is undefined .Ar newval is the value. If the variable is defined, the existing value is returned. This is another ODE make feature. It is handy for setting per-target CFLAGS for instance: .Dl ${_${.TARGET:T}_CFLAGS:U${DEF_CFLAGS}} If a value is only required if the variable is undefined, use: .Dl ${VAR:D:Unewval} .It Cm \&:D Ns Ar newval If the variable is defined .Ar newval is the value. .It Cm \&:L The name of the variable is the value. .It Cm \&:P The path of the node which has the same name as the variable is the value. If no such node exists or its path is null, then the name of the variable is used. In order for this modifier to work, the name (node) must at least have appeared on the rhs of a dependency. .Sm off .It Cm \&:\&! Ar cmd Cm \&! .Sm on The output of running .Ar cmd is the value. .It Cm \&:sh If the variable is non-empty it is run as a command and the output becomes the new value. .It Cm \&::= Ns Ar str The variable is assigned the value .Ar str after substitution. This modifier and its variations are useful in obscure situations such as wanting to set a variable when shell commands are being parsed. These assignment modifiers always expand to nothing, so if appearing in a rule line by themselves should be preceded with something to keep .Nm happy. .Pp The .Ql Cm \&:: helps avoid false matches with the .At V style .Cm \&:= modifier and since substitution always occurs the .Cm \&::= form is vaguely appropriate. .It Cm \&::?= Ns Ar str As for .Cm \&::= but only if the variable does not already have a value. .It Cm \&::+= Ns Ar str Append .Ar str to the variable. .It Cm \&::!= Ns Ar cmd Assign the output of .Ar cmd to the variable. .It Cm \&:\&[ Ns Ar range Ns Cm \&] Selects one or more words from the value, or performs other operations related to the way in which the value is divided into words. .Pp Ordinarily, a value is treated as a sequence of words delimited by white space. Some modifiers suppress this behavior, causing a value to be treated as a single word (possibly containing embedded white space). An empty value, or a value that consists entirely of white-space, is treated as a single word. For the purposes of the .Ql Cm \&:[] modifier, the words are indexed both forwards using positive integers (where index 1 represents the first word), and backwards using negative integers (where index \-1 represents the last word). .Pp The .Ar range is subjected to variable expansion, and the expanded result is then interpreted as follows: .Bl -tag -width index .\" :[n] .It Ar index Selects a single word from the value. .\" :[start..end] .It Ar start Ns Cm \&.. Ns Ar end Selects all words from .Ar start to .Ar end , inclusive. For example, .Ql Cm \&:[2..-1] selects all words from the second word to the last word. If .Ar start is greater than .Ar end , then the words are output in reverse order. For example, .Ql Cm \&:[-1..1] selects all the words from last to first. .\" :[*] .It Cm \&* Causes subsequent modifiers to treat the value as a single word (possibly containing embedded white space). Analogous to the effect of \&"$*\&" in Bourne shell. .\" :[0] .It 0 Means the same as .Ql Cm \&:[*] . .\" :[*] .It Cm \&@ Causes subsequent modifiers to treat the value as a sequence of words delimited by white space. Analogous to the effect of \&"$@\&" in Bourne shell. .\" :[#] .It Cm \&# Returns the number of words in the value. .El \" :[range] .El .Sh INCLUDE STATEMENTS, CONDITIONALS AND FOR LOOPS Makefile inclusion, conditional structures and for loops reminiscent of the C programming language are provided in .Nm . All such structures are identified by a line beginning with a single dot .Pq Ql \&. character. Files are included with either .Cm \&.include Aq Ar file or .Cm \&.include Pf \*q Ar file Ns \*q . Variables between the angle brackets or double quotes are expanded to form the file name. If angle brackets are used, the included makefile is expected to be in the system makefile directory. If double quotes are used, the including makefile's directory and any directories specified using the .Fl I option are searched before the system makefile directory. For compatibility with other versions of .Nm .Ql include file ... is also accepted. .Pp If the include statement is written as .Cm .-include or as .Cm .sinclude then errors locating and/or opening include files are ignored. .Pp If the include statement is written as .Cm .dinclude not only are errors locating and/or opening include files ignored, but stale dependencies within the included file will be ignored just like .Va .MAKE.DEPENDFILE . .Pp Conditional expressions are also preceded by a single dot as the first character of a line. The possible conditionals are as follows: .Bl -tag -width Ds .It Ic .error Ar message The message is printed along with the name of the makefile and line number, then .Nm will exit. .It Ic .export Ar variable ... Export the specified global variable. If no variable list is provided, all globals are exported except for internal variables (those that start with .Ql \&. ) . This is not affected by the .Fl X flag, so should be used with caution. For compatibility with other .Nm programs .Ql export variable=value is also accepted. .Pp Appending a variable name to .Va .MAKE.EXPORTED is equivalent to exporting a variable. .It Ic .export-env Ar variable ... The same as .Ql .export , except that the variable is not appended to .Va .MAKE.EXPORTED . This allows exporting a value to the environment which is different from that used by .Nm internally. .It Ic .export-literal Ar variable ... The same as .Ql .export-env , except that variables in the value are not expanded. .It Ic .info Ar message The message is printed along with the name of the makefile and line number. .It Ic .undef Ar variable Un-define the specified global variable. Only global variables may be un-defined. .It Ic .unexport Ar variable ... The opposite of .Ql .export . The specified global .Va variable will be removed from .Va .MAKE.EXPORTED . If no variable list is provided, all globals are unexported, and .Va .MAKE.EXPORTED deleted. .It Ic .unexport-env Unexport all globals previously exported and clear the environment inherited from the parent. This operation will cause a memory leak of the original environment, so should be used sparingly. Testing for .Va .MAKE.LEVEL being 0, would make sense. Also note that any variables which originated in the parent environment should be explicitly preserved if desired. For example: .Bd -literal -offset indent .Li .if ${.MAKE.LEVEL} == 0 PATH := ${PATH} .Li .unexport-env .Li .export PATH .Li .endif .Pp .Ed Would result in an environment containing only .Ql Ev PATH , which is the minimal useful environment. Actually .Ql Ev .MAKE.LEVEL will also be pushed into the new environment. .It Ic .warning Ar message The message prefixed by .Ql Pa warning: is printed along with the name of the makefile and line number. .It Ic \&.if Oo \&! Oc Ns Ar expression Op Ar operator expression ... Test the value of an expression. .It Ic .ifdef Oo \&! Oc Ns Ar variable Op Ar operator variable ... Test the value of a variable. .It Ic .ifndef Oo \&! Oc Ns Ar variable Op Ar operator variable ... Test the value of a variable. .It Ic .ifmake Oo \&! Oc Ns Ar target Op Ar operator target ... Test the target being built. .It Ic .ifnmake Oo \&! Ns Oc Ar target Op Ar operator target ... Test the target being built. .It Ic .else Reverse the sense of the last conditional. .It Ic .elif Oo \&! Ns Oc Ar expression Op Ar operator expression ... A combination of .Ql Ic .else followed by .Ql Ic .if . .It Ic .elifdef Oo \&! Oc Ns Ar variable Op Ar operator variable ... A combination of .Ql Ic .else followed by .Ql Ic .ifdef . .It Ic .elifndef Oo \&! Oc Ns Ar variable Op Ar operator variable ... A combination of .Ql Ic .else followed by .Ql Ic .ifndef . .It Ic .elifmake Oo \&! Oc Ns Ar target Op Ar operator target ... A combination of .Ql Ic .else followed by .Ql Ic .ifmake . .It Ic .elifnmake Oo \&! Oc Ns Ar target Op Ar operator target ... A combination of .Ql Ic .else followed by .Ql Ic .ifnmake . .It Ic .endif End the body of the conditional. .El .Pp The .Ar operator may be any one of the following: .Bl -tag -width "Cm XX" .It Cm \&|\&| Logical OR. .It Cm \&&& Logical .Tn AND ; of higher precedence than .Dq \&|\&| . .El .Pp As in C, .Nm will only evaluate a conditional as far as is necessary to determine its value. Parentheses may be used to change the order of evaluation. The boolean operator .Ql Ic \&! may be used to logically negate an entire conditional. It is of higher precedence than .Ql Ic \&&& . .Pp The value of .Ar expression may be any of the following: .Bl -tag -width defined .It Ic defined Takes a variable name as an argument and evaluates to true if the variable has been defined. .It Ic make Takes a target name as an argument and evaluates to true if the target was specified as part of .Nm Ns 's command line or was declared the default target (either implicitly or explicitly, see .Va .MAIN ) before the line containing the conditional. .It Ic empty Takes a variable, with possible modifiers, and evaluates to true if the expansion of the variable would result in an empty string. .It Ic exists Takes a file name as an argument and evaluates to true if the file exists. The file is searched for on the system search path (see .Va .PATH ) . .It Ic target Takes a target name as an argument and evaluates to true if the target has been defined. .It Ic commands Takes a target name as an argument and evaluates to true if the target has been defined and has commands associated with it. .El .Pp .Ar Expression may also be an arithmetic or string comparison. Variable expansion is performed on both sides of the comparison, after which the integral values are compared. A value is interpreted as hexadecimal if it is preceded by 0x, otherwise it is decimal; octal numbers are not supported. The standard C relational operators are all supported. If after variable expansion, either the left or right hand side of a .Ql Ic == or .Ql Ic "!=" operator is not an integral value, then string comparison is performed between the expanded variables. If no relational operator is given, it is assumed that the expanded variable is being compared against 0 or an empty string in the case of a string comparison. .Pp When .Nm is evaluating one of these conditional expressions, and it encounters a (white-space separated) word it doesn't recognize, either the .Dq make or .Dq defined expression is applied to it, depending on the form of the conditional. If the form is .Ql Ic .ifdef , .Ql Ic .ifndef , or .Ql Ic .if the .Dq defined expression is applied. Similarly, if the form is .Ql Ic .ifmake or .Ql Ic .ifnmake , the .Dq make expression is applied. .Pp If the conditional evaluates to true the parsing of the makefile continues as before. If it evaluates to false, the following lines are skipped. In both cases this continues until a .Ql Ic .else or .Ql Ic .endif is found. .Pp For loops are typically used to apply a set of rules to a list of files. The syntax of a for loop is: .Pp .Bl -tag -compact -width Ds .It Ic \&.for Ar variable Oo Ar variable ... Oc Ic in Ar expression .It Aq make-rules .It Ic \&.endfor .El .Pp After the for .Ic expression is evaluated, it is split into words. On each iteration of the loop, one word is taken and assigned to each .Ic variable , in order, and these .Ic variables are substituted into the .Ic make-rules inside the body of the for loop. The number of words must come out even; that is, if there are three iteration variables, the number of words provided must be a multiple of three. .Sh COMMENTS Comments begin with a hash .Pq Ql \&# character, anywhere but in a shell command line, and continue to the end of an unescaped new line. .Sh SPECIAL SOURCES (ATTRIBUTES) .Bl -tag -width .IGNOREx .It Ic .EXEC Target is never out of date, but always execute commands anyway. .It Ic .IGNORE Ignore any errors from the commands associated with this target, exactly as if they all were preceded by a dash .Pq Ql \- . .\" .It Ic .INVISIBLE .\" XXX .\" .It Ic .JOIN .\" XXX .It Ic .MADE Mark all sources of this target as being up-to-date. .It Ic .MAKE Execute the commands associated with this target even if the .Fl n or .Fl t options were specified. Normally used to mark recursive .Nm Ns s . .It Ic .META Create a meta file for the target, even if it is flagged as .Ic .PHONY , .Ic .MAKE , or .Ic .SPECIAL . Usage in conjunction with .Ic .MAKE is the most likely case. In "meta" mode, the target is out-of-date if the meta file is missing. .It Ic .NOMETA Do not create a meta file for the target. Meta files are also not created for .Ic .PHONY , .Ic .MAKE , or .Ic .SPECIAL targets. .It Ic .NOMETA_CMP Ignore differences in commands when deciding if target is out of date. This is useful if the command contains a value which always changes. If the number of commands change, though, the target will still be out of date. The same effect applies to any command line that uses the variable .Va .OODATE , which can be used for that purpose even when not otherwise needed or desired: .Bd -literal -offset indent skip-compare-for-some: @echo this will be compared @echo this will not ${.OODATE:M.NOMETA_CMP} @echo this will also be compared .Ed The .Cm \&:M pattern suppresses any expansion of the unwanted variable. .It Ic .NOPATH Do not search for the target in the directories specified by .Ic .PATH . .It Ic .NOTMAIN Normally .Nm selects the first target it encounters as the default target to be built if no target was specified. This source prevents this target from being selected. .It Ic .OPTIONAL If a target is marked with this attribute and .Nm can't figure out how to create it, it will ignore this fact and assume the file isn't needed or already exists. .It Ic .PHONY The target does not correspond to an actual file; it is always considered to be out of date, and will not be created with the .Fl t option. Suffix-transformation rules are not applied to .Ic .PHONY targets. .It Ic .PRECIOUS When .Nm is interrupted, it normally removes any partially made targets. This source prevents the target from being removed. .It Ic .RECURSIVE Synonym for .Ic .MAKE . .It Ic .SILENT Do not echo any of the commands associated with this target, exactly as if they all were preceded by an at sign .Pq Ql @ . .It Ic .USE Turn the target into .Nm Ns 's version of a macro. When the target is used as a source for another target, the other target acquires the commands, sources, and attributes (except for .Ic .USE ) of the source. If the target already has commands, the .Ic .USE target's commands are appended to them. .It Ic .USEBEFORE Exactly like .Ic .USE , but prepend the .Ic .USEBEFORE target commands to the target. .It Ic .WAIT If .Ic .WAIT appears in a dependency line, the sources that precede it are made before the sources that succeed it in the line. Since the dependents of files are not made until the file itself could be made, this also stops the dependents being built unless they are needed for another branch of the dependency tree. So given: .Bd -literal x: a .WAIT b echo x a: echo a b: b1 echo b b1: echo b1 .Ed the output is always .Ql a , .Ql b1 , .Ql b , .Ql x . .br The ordering imposed by .Ic .WAIT is only relevant for parallel makes. .El .Sh SPECIAL TARGETS Special targets may not be included with other targets, i.e. they must be the only target specified. .Bl -tag -width .BEGINx .It Ic .BEGIN Any command lines attached to this target are executed before anything else is done. .It Ic .DEFAULT This is sort of a .Ic .USE rule for any target (that was used only as a source) that .Nm can't figure out any other way to create. Only the shell script is used. The .Ic .IMPSRC variable of a target that inherits .Ic .DEFAULT Ns 's commands is set to the target's own name. .It Ic .DELETE_ON_ERROR If this target is present in the makefile, it globally causes make to delete targets whose commands fail. (By default, only targets whose commands are interrupted during execution are deleted. This is the historical behavior.) This setting can be used to help prevent half-finished or malformed targets from being left around and corrupting future rebuilds. .It Ic .END Any command lines attached to this target are executed after everything else is done. .It Ic .ERROR Any command lines attached to this target are executed when another target fails. The .Ic .ERROR_TARGET variable is set to the target that failed. See also .Ic MAKE_PRINT_VAR_ON_ERROR . .It Ic .IGNORE Mark each of the sources with the .Ic .IGNORE attribute. If no sources are specified, this is the equivalent of specifying the .Fl i option. .It Ic .INTERRUPT If .Nm is interrupted, the commands for this target will be executed. .It Ic .MAIN If no target is specified when .Nm is invoked, this target will be built. .It Ic .MAKEFLAGS This target provides a way to specify flags for .Nm when the makefile is used. The flags are as if typed to the shell, though the .Fl f option will have no effect. .\" XXX: NOT YET!!!! .\" .It Ic .NOTPARALLEL .\" The named targets are executed in non parallel mode. .\" If no targets are .\" specified, then all targets are executed in non parallel mode. .It Ic .NOPATH Apply the .Ic .NOPATH attribute to any specified sources. .It Ic .NOTPARALLEL Disable parallel mode. .It Ic .NO_PARALLEL Synonym for .Ic .NOTPARALLEL , for compatibility with other pmake variants. .It Ic .OBJDIR The source is a new value for .Ql Va .OBJDIR . If it exists, .Nm will .Xr chdir 2 to it and update the value of .Ql Va .OBJDIR . .It Ic .ORDER The named targets are made in sequence. This ordering does not add targets to the list of targets to be made. Since the dependents of a target do not get built until the target itself could be built, unless .Ql a is built by another part of the dependency graph, the following is a dependency loop: .Bd -literal \&.ORDER: b a b: a .Ed .Pp The ordering imposed by .Ic .ORDER is only relevant for parallel makes. .\" XXX: NOT YET!!!! .\" .It Ic .PARALLEL .\" The named targets are executed in parallel mode. .\" If no targets are .\" specified, then all targets are executed in parallel mode. .It Ic .PATH The sources are directories which are to be searched for files not found in the current directory. If no sources are specified, any previously specified directories are deleted. If the source is the special .Ic .DOTLAST target, then the current working directory is searched last. .It Ic .PATH. Ns Va suffix Like .Ic .PATH but applies only to files with a particular suffix. The suffix must have been previously declared with .Ic .SUFFIXES . .It Ic .PHONY Apply the .Ic .PHONY attribute to any specified sources. .It Ic .PRECIOUS Apply the .Ic .PRECIOUS attribute to any specified sources. If no sources are specified, the .Ic .PRECIOUS attribute is applied to every target in the file. .It Ic .SHELL Sets the shell that .Nm will use to execute commands. The sources are a set of .Ar field=value pairs. .Bl -tag -width hasErrCtls .It Ar name This is the minimal specification, used to select one of the built-in shell specs; .Ar sh , .Ar ksh , and .Ar csh . .It Ar path Specifies the path to the shell. .It Ar hasErrCtl Indicates whether the shell supports exit on error. .It Ar check The command to turn on error checking. .It Ar ignore The command to disable error checking. .It Ar echo The command to turn on echoing of commands executed. .It Ar quiet The command to turn off echoing of commands executed. .It Ar filter The output to filter after issuing the .Ar quiet command. It is typically identical to .Ar quiet . .It Ar errFlag The flag to pass the shell to enable error checking. .It Ar echoFlag The flag to pass the shell to enable command echoing. .It Ar newline The string literal to pass the shell that results in a single newline character when used outside of any quoting characters. .El Example: .Bd -literal \&.SHELL: name=ksh path=/bin/ksh hasErrCtl=true \e check="set \-e" ignore="set +e" \e echo="set \-v" quiet="set +v" filter="set +v" \e echoFlag=v errFlag=e newline="'\en'" .Ed .It Ic .SILENT Apply the .Ic .SILENT attribute to any specified sources. If no sources are specified, the .Ic .SILENT attribute is applied to every command in the file. .It Ic .STALE This target gets run when a dependency file contains stale entries, having .Va .ALLSRC set to the name of that dependency file. .It Ic .SUFFIXES Each source specifies a suffix to .Nm . If no sources are specified, any previously specified suffixes are deleted. It allows the creation of suffix-transformation rules. .Pp Example: .Bd -literal \&.SUFFIXES: .o \&.c.o: cc \-o ${.TARGET} \-c ${.IMPSRC} .Ed .El .Sh ENVIRONMENT .Nm uses the following environment variables, if they exist: .Ev MACHINE , .Ev MACHINE_ARCH , .Ev MAKE , .Ev MAKEFLAGS , .Ev MAKEOBJDIR , .Ev MAKEOBJDIRPREFIX , .Ev MAKESYSPATH , .Ev PWD , and .Ev TMPDIR . .Pp .Ev MAKEOBJDIRPREFIX and .Ev MAKEOBJDIR may only be set in the environment or on the command line to .Nm and not as makefile variables; see the description of .Ql Va .OBJDIR for more details. .Sh FILES .Bl -tag -width /usr/share/mk -compact .It .depend list of dependencies .It Makefile list of dependencies .It makefile list of dependencies .It sys.mk system makefile .It /usr/share/mk system makefile directory .El .Sh COMPATIBILITY The basic make syntax is compatible between different versions of make; however the special variables, variable modifiers and conditionals are not. .Ss Older versions An incomplete list of changes in older versions of .Nm : .Pp The way that .for loop variables are substituted changed after NetBSD 5.0 so that they still appear to be variable expansions. In particular this stops them being treated as syntax, and removes some obscure problems using them in .if statements. .Pp The way that parallel makes are scheduled changed in NetBSD 4.0 so that .ORDER and .WAIT apply recursively to the dependent nodes. The algorithms used may change again in the future. .Ss Other make dialects Other make dialects (GNU make, SVR4 make, POSIX make, etc.) do not support most of the features of .Nm as described in this manual. Most notably: .Bl -bullet -offset indent .It The .Ic .WAIT and .Ic .ORDER declarations and most functionality pertaining to parallelization. (GNU make supports parallelization but lacks these features needed to control it effectively.) .It Directives, including for loops and conditionals and most of the forms of include files. (GNU make has its own incompatible and less powerful syntax for conditionals.) .It All built-in variables that begin with a dot. .It Most of the special sources and targets that begin with a dot, with the notable exception of .Ic .PHONY , .Ic .PRECIOUS , and .Ic .SUFFIXES . .It Variable modifiers, except for the .Dl :old=new string substitution, which does not portably support globbing with .Ql % and historically only works on declared suffixes. .It The .Ic $> variable even in its short form; most makes support this functionality but its name varies. .El .Pp Some features are somewhat more portable, such as assignment with .Ic += , .Ic ?= , and .Ic != . The .Ic .PATH functionality is based on an older feature .Ic VPATH found in GNU make and many versions of SVR4 make; however, historically its behavior is too ill-defined (and too buggy) to rely upon. .Pp The .Ic $@ and .Ic $< variables are more or less universally portable, as is the .Ic $(MAKE) variable. Basic use of suffix rules (for files only in the current directory, not trying to chain transformations together, etc.) is also reasonably portable. .Sh SEE ALSO .Xr mkdep 1 .Sh HISTORY .Nm is derived from NetBSD .Xr make 1 . It uses autoconf to facilitate portability to other platforms. .Pp A make command appeared in .At v7 . This make implementation is based on Adam De Boor's pmake program which was written for Sprite at Berkeley. It was designed to be a parallel distributed make running jobs on different machines using a daemon called .Dq customs . .Pp Historically the target/dependency .Dq FRC has been used to FoRCe rebuilding (since the target/dependency does not exist... unless someone creates an .Dq FRC file). .Sh BUGS The make syntax is difficult to parse without actually acting of the data. For instance finding the end of a variable use should involve scanning each the modifiers using the correct terminator for each field. In many places make just counts {} and () in order to find the end of a variable expansion. .Pp There is no way of escaping a space character in a filename. Index: stable/12/contrib/bmake/boot-strap =================================================================== --- stable/12/contrib/bmake/boot-strap (revision 361673) +++ stable/12/contrib/bmake/boot-strap (revision 361674) @@ -1,469 +1,475 @@ : # NAME: # boot-strap # # SYNOPSIS: # boot-strap ["options"] # boot-strap --prefix=/opt --install # boot-strap --prefix=$HOME --install-host-target -DWITH_PROG_VERSION # boot-strap ["options"] op=build # boot-strap ["options"] op=install # # DESCRIPTION: # This script is used to configure/build bmake it builds for # each host-target in a different subdir to keep the src clean. # There is no requirement for an existing make(1). # # On successful completion if no '--install' flag is given, # it echos a command to do installation. # # The variable "op" defaults to 'all', and is affected by # '--install' flag as above. # Other values include: # # configure # Just run 'configure' # # build # If 'configure' has not been done, do it, then # run the build script, and finally 'test'. # # install # If 'build' has not been done, do it, 'test' then # install. # # clean # attempt to clean up # # test # run the unit-tests. Done automatically after 'build' # and before 'install'. # # The above are leveraged by a trivial makefile for the benefit # of those that have './configure; make; make install' baked # into them. # # Options: # # -c "rc" # Pick up settings from "rc". # We look for '.bmake-boot-strap.rc' before processing # options (unless SKIP_RC is set in environment). # # --share "share_dir" # Where to put man pages and mk files. # If $prefix ends in $HOST_TARGET, and $prefix/../share # exits, the default will be that rather than $prefix/share. # # --mksrc "mksrc" # Indicate where the mk files can be found. # Default is $Mydir/mk # # --install # If build and test work, run bmake install. # BINDIR=$prefix/bin # SHAREDIR=$prefix/share # # --install-host-target # As for '--install' but BINDIR=$prefix/$HOST_TARGET/bin # This is useful when $prefix/ is shared by multiple # machines. # # Flags relevant when installing: # # -DWITHOUT_INSTALL_MK # Skip installing mk files. # By default they will be installed to $prefix/share/mk # # -DWITH_PROG_VERSION # Install 'bmake' as 'bmake-$MAKE_VERSION' # A symlink will be made as 'bmake' unless # -DWITHOUT_PROG_LINK is set. # # Possibly useful configure_args: # # --without-meta # disable use of meta mode. # # --without-filemon # disable use of filemon(9) which is currently only # available for NetBSD and FreeBSD. # +# --with-filemon=ktrace +# on NetBSD or others with fktrace(2), use ktrace +# version of filemon. +# # --with-filemon="path/to/filemon.h" # enables use of filemon(9) by meta mode. # # --with-machine="machine" # set "machine" to override that determined by # machine.sh # # --with-force-machine="machine" # force "machine" even if uname(3) provides a value. # # --with-machine_arch="machine_arch" # set "machine_arch" to override that determined by # machine.sh # # --with-default-sys-path="syspath" # set an explicit default "syspath" which is where bmake # will look for sys.mk and friends. # # AUTHOR: # Simon J. Gerraty # RCSid: -# $Id: boot-strap,v 1.49 2016/05/29 00:09:14 sjg Exp $ +# $Id: boot-strap,v 1.51 2020/02/19 16:46:23 sjg Exp $ # # @(#) Copyright (c) 2001 Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # Mydir=`dirname $0` . "$Mydir/os.sh" case "$Mydir" in /*) ;; *) Mydir=`cd "$Mydir" && 'pwd'`;; esac Usage() { [ "$1" ] && echo "ERROR: $@" >&2 echo "Usage:" >&2 echo "$0 [-- ...][][--install]" >&2 exit 1 } Error() { echo "ERROR: $@" >&2 exit 1 } source_rc() { rc="$1"; shift for d in ${*:-""} do r="${d:+$d/}$rc" [ -f "$r" -a -s "$r" ] || continue echo "NOTE: reading $r" . "$r" break done } cmd_args="$@" # clear some things from the environment that we care about unset MAKEOBJDIR MAKEOBJDIRPREFIX +# or that might be incompatible +unset MAKE MAKEFLAGS # --install[-host-target] will set this INSTALL_PREFIX= # other things we pass to install step INSTALL_ARGS= CONFIGURE_ARGS= MAKESYSPATH= # pick a useful default prefix (for me at least ;-) for prefix in /opt/$HOST_TARGET "$HOME/$HOST_TARGET" /usr/pkg /usr/local "" do [ -d "${prefix:-.}" ] || continue case "$prefix" in */$HOST_TARGET) p=`dirname $prefix` if [ -d $p/share ]; then INSTALL_BIN=$HOST_TARGET/bin prefix=$p fi ;; esac echo "NOTE: default prefix=$prefix ${INSTALL_BIN:+INSTALL_BIN=$INSTALL_BIN}" break done srcdir=$Mydir mksrc=$Mydir/mk objdir= quiet=: ${SKIP_RC:+:} source_rc .bmake-boot-strap.rc . "$Mydir/.." "$HOME" get_optarg() { expr "x$1" : "x[^=]*=\\(.*\\)" } here=`'pwd'` if [ $here = $Mydir ]; then # avoid pollution OBJROOT=../ fi op=all BMAKE= while : do case "$1" in --) shift; break;; --help) sed -n -e "1d;/RCSid/,\$d" -e '/^#\.[a-z]/d' -e '/^#/s,^# *,,p' $0; exit 0;; --prefix) prefix="$2"; shift;; --prefix=*) prefix=`get_optarg "$1"`;; --src=*) srcdir=`get_optarg "$1"`;; --with-mksrc=*|--mksrc=*) mksrc=`get_optarg "$1"`;; --share=*) share_dir=`get_optarg "$1"`;; --share) share_dir="$2"; shift;; --with-default-sys-path=*) CONFIGURE_ARGS="$1";; --with-default-sys-path) CONFIGURE_ARGS="$1 $2";; --install) INSTALL_PREFIX=${INSTALL_PREFIX:-$prefix};; --install-host-target) INSTALL_PREFIX=${INSTALL_PREFIX:-$prefix} INSTALL_BIN=$HOST_TARGET/bin;; --install-destdir=*) INSTALL_DESTDIR=`get_optarg "$1"`;; --install-prefix=*) INSTALL_PREFIX=`get_optarg "$1"`;; -DWITH*) INSTALL_ARGS="$INSTALL_ARGS $1";; -s|--src) srcdir="$2"; shift;; -m|--mksrc) mksrc="$2"; shift;; -o|--objdir) objdir="$2"; shift;; -q) quiet=;; -c) source_rc "$2"; shift;; --*) CONFIGURE_ARGS="$CONFIGURE_ARGS $1";; *=*) eval "$1"; export `expr "x$1" : "x\\(.[^=]*\\)=.*"`;; *) break;; esac shift done AddConfigure() { case " $CONFIGURE_ARGS " in *" $1"*) ;; *) CONFIGURE_ARGS="$CONFIGURE_ARGS $1$2";; esac } GetDir() { match="$1" shift fmatch="$1" shift for dir in $* do [ -d "$dir" ] || continue case "/$dir/" in *$match*) ;; *) continue;; esac case "$fmatch" in .) ;; *) [ -s $dir/$fmatch ] || continue;; esac case "$dir/" in *./*) cd "$dir" && 'pwd';; /*) echo $dir;; *) cd "$dir" && 'pwd';; esac break done } FindHereOrAbove() { ( _t=-s while : do case "$1" in -C) cd "$2"; shift; shift;; -?) _t=$1; shift;; *) break;; esac done case "$1" in /*) # we shouldn't be here [ $_t "$1" ] && echo "$1" return ;; .../*) want=`echo "$1" | sed 's,^.../*,,'`;; *) want="$1";; esac here=`'pwd'` while : do if [ $_t "./$want" ]; then echo "$here/$want" return fi cd .. here=`'pwd'` case "$here" in /) return;; esac done ) } # is $1 missing from $2 (or PATH) ? no_path() { eval "__p=\$${2:-PATH}" case ":$__p:" in *:"$1":*) return 1;; *) return 0;; esac } # if $1 exists and is not in path, append it add_path () { case "$1" in -?) t=$1; shift;; *) t=-d;; esac case "$2,$1" in MAKESYSPATH,.../*) ;; *) [ $t ${1:-.} ] || return;; esac no_path $* && eval ${2:-PATH}="$__p${__p:+:}$1" } srcdir=`GetDir /bmake make-bootstrap.sh.in "$srcdir" "$2" "$Mydir" ./bmake* "$Mydir"/../bmake*` [ -d "${srcdir:-/dev/null}" ] || Usage case "$mksrc" in none|-) # we ignore this now mksrc=$Mydir/mk ;; .../*) # find here or above mksrc=`FindHereOrAbove -C "$Mydir" -s "$mksrc/sys.mk"` # that found a file mksrc=`dirname $mksrc` ;; *) # guess we want mksrc... mksrc=`GetDir /mk sys.mk "$mksrc" "$3" ./mk* "$srcdir"/mk* "$srcdir"/../mk*` [ -d "${mksrc:-/dev/null}" ] || Usage "Use '-m none' to build without mksrc" ;; esac # Ok, get to work... objdir="${objdir:-$OBJROOT$HOST_TARGET}" [ -d "$objdir" ] || mkdir -p "$objdir" [ -d "$objdir" ] || mkdir "$objdir" cd "$objdir" || exit 1 # make it absolute objdir=`'pwd'` ShareDir() { case "/$1" in /) [ -d /share ] || return;; */$HOST_TARGET) if [ -d "$1/../share" ]; then echo `dirname "$1"`/share return fi ;; esac echo $1/share } # make it easy to force prefix to use $HOST_TARGET : looking at "$prefix" case "$prefix" in */host?target) prefix=`echo "$prefix" | sed "s,host.target,${HOST_TARGET},"`;; esac share_dir="${share_dir:-`ShareDir $prefix`}" AddConfigure --prefix= "$prefix" case "$CONFIGURE_ARGS" in *--with-*-sys-path*) ;; # skip *) [ "$share_dir" ] && AddConfigure --with-default-sys-path= "$share_dir/mk";; esac if [ "$mksrc" ]; then AddConfigure --with-mksrc= "$mksrc" # not all cc's support this CFLAGS_MF= CFLAGS_MD= export CFLAGS_MF CFLAGS_MD fi # this makes it easy to run the bmake we just built # the :tA dance is needed because 'pwd' and even /bin/pwd # may not give the same result as realpath(). Bmake() { ( cd $Mydir && MAKESYSPATH=$mksrc SRCTOP=$Mydir OBJTOP=$objdir \ MAKEOBJDIR='${.CURDIR:S,${SRCTOP:tA},${OBJTOP:tA},}' \ ${BMAKE:-$objdir/bmake} -f $Mydir/Makefile "$@" ) } # there is actually a shell where type is not a builtin # if type is missing, which(1) had better exists! if (type cat) > /dev/null 2>&1; then which() { type "$@" | sed 's,[()],,g;s,^[^/][^/]*,,;q' } fi # make sure test below uses the same diff that configure did TOOL_DIFF=`which diff` export TOOL_DIFF op_configure() { $srcdir/configure $CONFIGURE_ARGS || exit 1 } op_build() { [ -s make-bootstrap.sh ] || op_configure chmod 755 make-bootstrap.sh || exit 1 ./make-bootstrap.sh || exit 1 case "$op" in build) op_test;; esac } op_test() { [ -x bmake ] || op_build Bmake test || exit 1 } op_clean() { if [ -x bmake ]; then ln bmake bmake$$ BMAKE=$objdir/bmake$$ Bmake clean rm -f bmake$$ elif [ $objdir != $srcdir ]; then rm -rf * fi } op_install() { op_test case "$INSTALL_PREFIX,$INSTALL_BIN,$prefix" in ,$HOST_TARGET/bin,*/$HOST_TARGET) INSTALL_PREFIX=`dirname $prefix` ;; esac INSTALL_PREFIX=${INSTALL_PREFIX:-$prefix} Bmake install prefix=$INSTALL_PREFIX BINDIR=$INSTALL_PREFIX/${INSTALL_BIN:-bin} ${INSTALL_DESTDIR:+DESTDIR=$INSTALL_DESTDIR} $INSTALL_ARGS || exit 1 } op_all() { rm -f make-bootstrap.sh bmake *.o if [ -n "$INSTALL_PREFIX" ]; then op_install else op_test MAKE_VERSION=`sed -n '/^_MAKE_VERSION/ { s,.*= *,,;p; }' $srcdir/Makefile` echo You can install by running: echo echo $0 $cmd_args op=install echo echo "Use --install-prefix=/something to install somewhere other than $prefix" echo "Use --install-destdir=/somewhere to set DESTDIR during install" echo "Use --install-host-target to use INSTALL_BIN=$HOST_TARGET/bin" echo "Use -DWITH_PROG_VERSION to install as bmake-$MAKE_VERSION" echo "Use -DWITHOUT_PROG_LINK to suppress bmake -> bmake-$MAKE_VERSION symlink" echo "Use -DWITHOUT_INSTALL_MK to skip installing files to $prefix/share/mk" fi } op_$op exit 0 Index: stable/12/contrib/bmake/bsd.after-import.mk =================================================================== --- stable/12/contrib/bmake/bsd.after-import.mk (revision 361673) +++ stable/12/contrib/bmake/bsd.after-import.mk (revision 361674) @@ -1,112 +1,111 @@ -# $Id: bsd.after-import.mk,v 1.13 2017/08/13 00:56:10 sjg Exp $ +# $Id: bsd.after-import.mk,v 1.15 2018/12/30 17:14:24 sjg Exp $ # This makefile is for use when integrating bmake into a BSD build # system. Use this makefile after importing bmake. # It will bootstrap the new version, # capture the generated files we need, and add an after-import # target to allow the process to be easily repeated. # The goal is to allow the benefits of autoconf without # the overhead of running configure. all: _makefile all: after-import # we rely on bmake .if !defined(.PARSEDIR) .error this makefile requires bmake .endif _this := ${MAKEFILE:tA} BMAKE_SRC := ${.PARSEDIR} # it helps to know where the top of the tree is. .if !defined(SRCTOP) srctop := ${.MAKE.MAKEFILES:M*src/share/mk/sys.mk:H:H:H} .if empty(srctop) # likely locations? .for d in contrib/bmake external/bsd/bmake/dist .if ${BMAKE_SRC:M*/$d} != "" srctop := ${BMAKE_SRC:tA:S,/$d,,} .endif .endfor .endif .if !empty(srctop) SRCTOP := ${srctop} .endif .endif # This lets us match what boot-strap does .if !defined(HOST_OS) HOST_OS!= uname .endif BOOTSTRAP_ARGS = \ --prefix /usr \ --share /usr/share .if !empty(DEFAULT_SYS_PATH) BOOTSTRAP_ARGS += --with-default-sys-path='${DEFAULT_SYS_PATH}' .endif # run boot-strap with minimal influence bootstrap: ${BMAKE_SRC}/boot-strap ${MAKEFILE} HOME=/ ${BMAKE_SRC}/boot-strap -o ${HOST_OS} ${BOOTSTRAP_ARGS} ${BOOTSTRAP_XTRAS} touch ${.TARGET} # Makefiles need a little more tweaking than say config.h MAKEFILE_SED = sed -e '/^MACHINE/d' \ -e '/include.*VERSION/d' \ -e '/^PROG/ { s,=,?=,;s,bmake,$${.CURDIR:T},; }' \ -e 's,^.-include,.sinclude,' \ -e '/^\..*include * ${.CURDIR}/$f .endfor .for f in ${configured_files:M*Makefile*} @echo Capturing $f @mkdir -p ${${.CURDIR}/$f:L:H} @(echo '# This is a generated file, do NOT edit!'; \ echo '# See ${_this:S,${SRCTOP}/,,}'; \ echo '#'; echo '# $$${HOST_OS}$$'; echo; \ echo 'SRCTOP?= $${.CURDIR:${${.CURDIR}/$f:L:H:S,${SRCTOP}/,,:C,[^/]+,H,g:S,/,:,g}}'; echo; \ ${MAKEFILE_SED} ${HOST_OS}/$f ) > ${.CURDIR}/$f .endfor # this needs the most work _makefile: bootstrap ${MAKEFILE} @echo Generating ${.CURDIR}/Makefile @(echo '# This is a generated file, do NOT edit!'; \ echo '# See ${_this:S,${SRCTOP}/,,}'; \ echo '#'; echo '# $$${HOST_OS}$$'; \ - echo; echo '.sinclude "Makefile.inc"'; \ echo; echo 'SRCTOP?= $${.CURDIR:${.CURDIR:S,${SRCTOP}/,,:C,[^/]+,H,g:S,/,:,g}}'; \ echo; echo '# look here first for config.h'; \ echo 'CFLAGS+= -I$${.CURDIR}'; echo; \ echo '# for after-import'; \ echo 'CLEANDIRS+= ${HOST_OS}'; \ echo 'CLEANFILES+= bootstrap'; echo; \ ${MAKEFILE_SED} \ ${1 2:L:@n@-e '/start-delete$n/,/end-delete$n/d'@} \ ${BMAKE_SRC}/Makefile; \ echo; echo '# override some simple things'; \ echo 'BINDIR= /usr/bin'; \ echo 'MANDIR= ${MANDIR:U/usr/share/man}'; \ echo; echo '# make sure we get this'; \ echo 'CFLAGS+= $${COPTS.$${.IMPSRC:T}}'; \ echo; echo 'after-import: ${_this:S,${SRCTOP},\${SRCTOP},}'; \ echo ' cd $${.CURDIR} && $${.MAKE} -f ${_this:S,${SRCTOP},\${SRCTOP},}'; \ echo ) > ${.TARGET} @cmp -s ${.TARGET} ${.CURDIR}/Makefile || \ mv ${.TARGET} ${.CURDIR}/Makefile .include Index: stable/12/contrib/bmake/compat.c =================================================================== --- stable/12/contrib/bmake/compat.c (revision 361673) +++ stable/12/contrib/bmake/compat.c (revision 361674) @@ -1,781 +1,781 @@ -/* $NetBSD: compat.c,v 1.107 2017/07/20 19:29:54 sjg Exp $ */ +/* $NetBSD: compat.c,v 1.110 2020/01/19 19:42:32 riastradh Exp $ */ /* * Copyright (c) 1988, 1989, 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 1988, 1989 by Adam de Boor * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MAKE_NATIVE -static char rcsid[] = "$NetBSD: compat.c,v 1.107 2017/07/20 19:29:54 sjg Exp $"; +static char rcsid[] = "$NetBSD: compat.c,v 1.110 2020/01/19 19:42:32 riastradh Exp $"; #else #include #ifndef lint #if 0 static char sccsid[] = "@(#)compat.c 8.2 (Berkeley) 3/19/94"; #else -__RCSID("$NetBSD: compat.c,v 1.107 2017/07/20 19:29:54 sjg Exp $"); +__RCSID("$NetBSD: compat.c,v 1.110 2020/01/19 19:42:32 riastradh Exp $"); #endif #endif /* not lint */ #endif /*- * compat.c -- * The routines in this file implement the full-compatibility * mode of PMake. Most of the special functionality of PMake * is available in this mode. Things not supported: * - different shells. * - friendly variable substitution. * * Interface: * Compat_Run Initialize things for this module and recreate * thems as need creatin' */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include #include #include "wait.h" #include #include #include #include #include "make.h" #include "hash.h" #include "dir.h" #include "job.h" #include "metachar.h" #include "pathnames.h" static GNode *curTarg = NULL; static GNode *ENDNode; static void CompatInterrupt(int); static pid_t compatChild; static int compatSigno; /* * CompatDeleteTarget -- delete a failed, interrupted, or otherwise * duffed target if not inhibited by .PRECIOUS. */ static void CompatDeleteTarget(GNode *gn) { if ((gn != NULL) && !Targ_Precious (gn)) { char *p1; char *file = Var_Value(TARGET, gn, &p1); if (!noExecute && eunlink(file) != -1) { Error("*** %s removed", file); } free(p1); } } /*- *----------------------------------------------------------------------- * CompatInterrupt -- * Interrupt the creation of the current target and remove it if * it ain't precious. * * Results: * None. * * Side Effects: * The target is removed and the process exits. If .INTERRUPT exists, * its commands are run first WITH INTERRUPTS IGNORED.. * * XXX: is .PRECIOUS supposed to inhibit .INTERRUPT? I doubt it, but I've * left the logic alone for now. - dholland 20160826 * *----------------------------------------------------------------------- */ static void CompatInterrupt(int signo) { GNode *gn; CompatDeleteTarget(curTarg); if ((curTarg != NULL) && !Targ_Precious (curTarg)) { /* * Run .INTERRUPT only if hit with interrupt signal */ if (signo == SIGINT) { gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE); if (gn != NULL) { Compat_Make(gn, gn); } } } if (signo == SIGQUIT) _exit(signo); /* * If there is a child running, pass the signal on * we will exist after it has exited. */ compatSigno = signo; if (compatChild > 0) { KILLPG(compatChild, signo); } else { bmake_signal(signo, SIG_DFL); kill(myPid, signo); } } /*- *----------------------------------------------------------------------- * CompatRunCommand -- * Execute the next command for a target. If the command returns an * error, the node's made field is set to ERROR and creation stops. * * Input: * cmdp Command to execute * gnp Node from which the command came * * Results: * 0 if the command succeeded, 1 if an error occurred. * * Side Effects: * The node's 'made' field may be set to ERROR. * *----------------------------------------------------------------------- */ int CompatRunCommand(void *cmdp, void *gnp) { char *cmdStart; /* Start of expanded command */ char *cp, *bp; Boolean silent, /* Don't print command */ doIt; /* Execute even if -n */ volatile Boolean errCheck; /* Check errors */ WAIT_T reason; /* Reason for child's death */ int status; /* Description of child's death */ pid_t cpid; /* Child actually found */ pid_t retstat; /* Result of wait */ LstNode cmdNode; /* Node where current command is located */ const char ** volatile av; /* Argument vector for thing to exec */ char ** volatile mav;/* Copy of the argument vector for freeing */ int argc; /* Number of arguments in av or 0 if not * dynamically allocated */ Boolean local; /* TRUE if command should be executed * locally */ Boolean useShell; /* TRUE if command should be executed * using a shell */ char * volatile cmd = (char *)cmdp; GNode *gn = (GNode *)gnp; silent = gn->type & OP_SILENT; errCheck = !(gn->type & OP_IGNORE); doIt = FALSE; cmdNode = Lst_Member(gn->commands, cmd); cmdStart = Var_Subst(NULL, cmd, gn, VARF_WANTRES); /* * brk_string will return an argv with a NULL in av[0], thus causing * execvp to choke and die horribly. Besides, how can we execute a null * command? In any case, we warn the user that the command expanded to * nothing (is this the right thing to do?). */ if (*cmdStart == '\0') { free(cmdStart); return(0); } cmd = cmdStart; Lst_Replace(cmdNode, cmdStart); if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) { (void)Lst_AtEnd(ENDNode->commands, cmdStart); return(0); } if (strcmp(cmdStart, "...") == 0) { gn->type |= OP_SAVE_CMDS; return(0); } while ((*cmd == '@') || (*cmd == '-') || (*cmd == '+')) { switch (*cmd) { case '@': silent = DEBUG(LOUD) ? FALSE : TRUE; break; case '-': errCheck = FALSE; break; case '+': doIt = TRUE; if (!shellName) /* we came here from jobs */ Shell_Init(); break; } cmd++; } while (isspace((unsigned char)*cmd)) cmd++; /* * If we did not end up with a command, just skip it. */ if (!*cmd) return (0); #if !defined(MAKE_NATIVE) /* * In a non-native build, the host environment might be weird enough * that it's necessary to go through a shell to get the correct * behaviour. Or perhaps the shell has been replaced with something * that does extra logging, and that should not be bypassed. */ useShell = TRUE; #else /* * Search for meta characters in the command. If there are no meta * characters, there's no need to execute a shell to execute the * command. * * Additionally variable assignments and empty commands * go to the shell. Therefore treat '=' and ':' like shell * meta characters as documented in make(1). */ useShell = needshell(cmd, FALSE); #endif /* * Print the command before echoing if we're not supposed to be quiet for * this one. We also print the command if -n given. */ if (!silent || NoExecute(gn)) { printf("%s\n", cmd); fflush(stdout); } /* * If we're not supposed to execute any commands, this is as far as * we go... */ if (!doIt && NoExecute(gn)) { return (0); } if (DEBUG(JOB)) fprintf(debug_file, "Execute: '%s'\n", cmd); again: if (useShell) { /* * We need to pass the command off to the shell, typically * because the command contains a "meta" character. */ static const char *shargv[5]; int shargc; shargc = 0; shargv[shargc++] = shellPath; /* * The following work for any of the builtin shell specs. */ if (errCheck && shellErrFlag) { shargv[shargc++] = shellErrFlag; } if (DEBUG(SHELL)) shargv[shargc++] = "-xc"; else shargv[shargc++] = "-c"; shargv[shargc++] = cmd; shargv[shargc++] = NULL; av = shargv; argc = 0; bp = NULL; mav = NULL; } else { /* * No meta-characters, so no need to exec a shell. Break the command * into words to form an argument vector we can execute. */ mav = brk_string(cmd, &argc, TRUE, &bp); if (mav == NULL) { useShell = 1; goto again; } av = (void *)mav; } local = TRUE; #ifdef USE_META if (useMeta) { meta_compat_start(); } #endif /* * Fork and execute the single command. If the fork fails, we abort. */ compatChild = cpid = vFork(); if (cpid < 0) { Fatal("Could not fork"); } if (cpid == 0) { Var_ExportVars(); #ifdef USE_META if (useMeta) { meta_compat_child(); } #endif if (local) (void)execvp(av[0], (char *const *)UNCONST(av)); else (void)execv(av[0], (char *const *)UNCONST(av)); execError("exec", av[0]); _exit(1); } free(mav); free(bp); Lst_Replace(cmdNode, NULL); #ifdef USE_META if (useMeta) { - meta_compat_parent(); + meta_compat_parent(cpid); } #endif /* * The child is off and running. Now all we can do is wait... */ while (1) { while ((retstat = wait(&reason)) != cpid) { if (retstat > 0) JobReapChild(retstat, reason, FALSE); /* not ours? */ if (retstat == -1 && errno != EINTR) { break; } } if (retstat > -1) { if (WIFSTOPPED(reason)) { status = WSTOPSIG(reason); /* stopped */ } else if (WIFEXITED(reason)) { status = WEXITSTATUS(reason); /* exited */ #if defined(USE_META) && defined(USE_FILEMON_ONCE) if (useMeta) { meta_cmd_finish(NULL); } #endif if (status != 0) { if (DEBUG(ERROR)) { fprintf(debug_file, "\n*** Failed target: %s\n*** Failed command: ", gn->name); for (cp = cmd; *cp; ) { if (isspace((unsigned char)*cp)) { fprintf(debug_file, " "); while (isspace((unsigned char)*cp)) cp++; } else { fprintf(debug_file, "%c", *cp); cp++; } } fprintf(debug_file, "\n"); } printf("*** Error code %d", status); } } else { status = WTERMSIG(reason); /* signaled */ printf("*** Signal %d", status); } if (!WIFEXITED(reason) || (status != 0)) { if (errCheck) { #ifdef USE_META if (useMeta) { meta_job_error(NULL, gn, 0, status); } #endif gn->made = ERROR; if (keepgoing) { /* * Abort the current target, but let others * continue. */ printf(" (continuing)\n"); } else { printf("\n"); } if (deleteOnError) { CompatDeleteTarget(gn); } } else { /* * Continue executing commands for this target. * If we return 0, this will happen... */ printf(" (ignored)\n"); status = 0; } } break; } else { Fatal("error in wait: %d: %s", retstat, strerror(errno)); /*NOTREACHED*/ } } free(cmdStart); compatChild = 0; if (compatSigno) { bmake_signal(compatSigno, SIG_DFL); kill(myPid, compatSigno); } return (status); } /*- *----------------------------------------------------------------------- * Compat_Make -- * Make a target. * * Input: * gnp The node to make * pgnp Parent to abort if necessary * * Results: * 0 * * Side Effects: * If an error is detected and not being ignored, the process exits. * *----------------------------------------------------------------------- */ int Compat_Make(void *gnp, void *pgnp) { GNode *gn = (GNode *)gnp; GNode *pgn = (GNode *)pgnp; if (!shellName) /* we came here from jobs */ Shell_Init(); if (gn->made == UNMADE && (gn == pgn || (pgn->type & OP_MADE) == 0)) { /* * First mark ourselves to be made, then apply whatever transformations * the suffix module thinks are necessary. Once that's done, we can * descend and make all our children. If any of them has an error * but the -k flag was given, our 'make' field will be set FALSE again. * This is our signal to not attempt to do anything but abort our * parent as well. */ gn->flags |= REMAKE; gn->made = BEINGMADE; if ((gn->type & OP_MADE) == 0) Suff_FindDeps(gn); Lst_ForEach(gn->children, Compat_Make, gn); if ((gn->flags & REMAKE) == 0) { gn->made = ABORTED; pgn->flags &= ~REMAKE; goto cohorts; } if (Lst_Member(gn->iParents, pgn) != NULL) { char *p1; Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn, 0); free(p1); } /* * All the children were made ok. Now cmgn->mtime contains the * modification time of the newest child, we need to find out if we * exist and when we were modified last. The criteria for datedness * are defined by the Make_OODate function. */ if (DEBUG(MAKE)) { fprintf(debug_file, "Examining %s...", gn->name); } if (! Make_OODate(gn)) { gn->made = UPTODATE; if (DEBUG(MAKE)) { fprintf(debug_file, "up-to-date.\n"); } goto cohorts; } else if (DEBUG(MAKE)) { fprintf(debug_file, "out-of-date.\n"); } /* * If the user is just seeing if something is out-of-date, exit now * to tell him/her "yes". */ if (queryFlag) { exit(1); } /* * We need to be re-made. We also have to make sure we've got a $? * variable. To be nice, we also define the $> variable using * Make_DoAllVar(). */ Make_DoAllVar(gn); /* * Alter our type to tell if errors should be ignored or things * should not be printed so CompatRunCommand knows what to do. */ if (Targ_Ignore(gn)) { gn->type |= OP_IGNORE; } if (Targ_Silent(gn)) { gn->type |= OP_SILENT; } if (Job_CheckCommands(gn, Fatal)) { /* * Our commands are ok, but we still have to worry about the -t * flag... */ if (!touchFlag || (gn->type & OP_MAKE)) { curTarg = gn; #ifdef USE_META if (useMeta && !NoExecute(gn)) { meta_job_start(NULL, gn); } #endif Lst_ForEach(gn->commands, CompatRunCommand, gn); curTarg = NULL; } else { Job_Touch(gn, gn->type & OP_SILENT); } } else { gn->made = ERROR; } #ifdef USE_META if (useMeta && !NoExecute(gn)) { if (meta_job_finish(NULL) != 0) gn->made = ERROR; } #endif if (gn->made != ERROR) { /* * If the node was made successfully, mark it so, update * its modification time and timestamp all its parents. Note * that for .ZEROTIME targets, the timestamping isn't done. * This is to keep its state from affecting that of its parent. */ gn->made = MADE; pgn->flags |= Make_Recheck(gn) == 0 ? FORCE : 0; if (!(gn->type & OP_EXEC)) { pgn->flags |= CHILDMADE; Make_TimeStamp(pgn, gn); } } else if (keepgoing) { pgn->flags &= ~REMAKE; } else { PrintOnError(gn, "\nStop."); exit(1); } } else if (gn->made == ERROR) { /* * Already had an error when making this beastie. Tell the parent * to abort. */ pgn->flags &= ~REMAKE; } else { if (Lst_Member(gn->iParents, pgn) != NULL) { char *p1; Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), pgn, 0); free(p1); } switch(gn->made) { case BEINGMADE: Error("Graph cycles through %s", gn->name); gn->made = ERROR; pgn->flags &= ~REMAKE; break; case MADE: if ((gn->type & OP_EXEC) == 0) { pgn->flags |= CHILDMADE; Make_TimeStamp(pgn, gn); } break; case UPTODATE: if ((gn->type & OP_EXEC) == 0) { Make_TimeStamp(pgn, gn); } break; default: break; } } cohorts: Lst_ForEach(gn->cohorts, Compat_Make, pgnp); return (0); } /*- *----------------------------------------------------------------------- * Compat_Run -- * Initialize this mode and start making. * * Input: * targs List of target nodes to re-create * * Results: * None. * * Side Effects: * Guess what? * *----------------------------------------------------------------------- */ void Compat_Run(Lst targs) { GNode *gn = NULL;/* Current root target */ int errors; /* Number of targets not remade due to errors */ if (!shellName) Shell_Init(); if (bmake_signal(SIGINT, SIG_IGN) != SIG_IGN) { bmake_signal(SIGINT, CompatInterrupt); } if (bmake_signal(SIGTERM, SIG_IGN) != SIG_IGN) { bmake_signal(SIGTERM, CompatInterrupt); } if (bmake_signal(SIGHUP, SIG_IGN) != SIG_IGN) { bmake_signal(SIGHUP, CompatInterrupt); } if (bmake_signal(SIGQUIT, SIG_IGN) != SIG_IGN) { bmake_signal(SIGQUIT, CompatInterrupt); } ENDNode = Targ_FindNode(".END", TARG_CREATE); ENDNode->type = OP_SPECIAL; /* * If the user has defined a .BEGIN target, execute the commands attached * to it. */ if (!queryFlag) { gn = Targ_FindNode(".BEGIN", TARG_NOCREATE); if (gn != NULL) { Compat_Make(gn, gn); if (gn->made == ERROR) { PrintOnError(gn, "\nStop."); exit(1); } } } /* * Expand .USE nodes right now, because they can modify the structure * of the tree. */ Make_ExpandUse(targs); /* * For each entry in the list of targets to create, call Compat_Make on * it to create the thing. Compat_Make will leave the 'made' field of gn * in one of several states: * UPTODATE gn was already up-to-date * MADE gn was recreated successfully * ERROR An error occurred while gn was being created * ABORTED gn was not remade because one of its inferiors * could not be made due to errors. */ errors = 0; while (!Lst_IsEmpty (targs)) { gn = (GNode *)Lst_DeQueue(targs); Compat_Make(gn, gn); if (gn->made == UPTODATE) { printf("`%s' is up to date.\n", gn->name); } else if (gn->made == ABORTED) { printf("`%s' not remade because of errors.\n", gn->name); errors += 1; } } /* * If the user has defined a .END target, run its commands. */ if (errors == 0) { Compat_Make(ENDNode, ENDNode); if (gn->made == ERROR) { PrintOnError(gn, "\nStop."); exit(1); } } } Index: stable/12/contrib/bmake/config.h.in =================================================================== --- stable/12/contrib/bmake/config.h.in (revision 361673) +++ stable/12/contrib/bmake/config.h.in (revision 361674) @@ -1,344 +1,344 @@ /* config.h.in. Generated from configure.in by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* Path of default shell */ #undef DEFSHELL_CUSTOM /* Shell spec to use by default */ #undef DEFSHELL_INDEX /* Define to 1 if you have the header file. */ #undef HAVE_AR_H /* Define to 1 if you have the declaration of `sys_siglist', and to 0 if you don't. */ #undef HAVE_DECL_SYS_SIGLIST /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_DIRENT_H /* Define to 1 if you have the `dirname' function. */ #undef HAVE_DIRNAME /* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ #undef HAVE_DOPRNT /* Define to 1 if you have the `err' function. */ #undef HAVE_ERR /* Define to 1 if you have the `errx' function. */ #undef HAVE_ERRX /* Define to 1 if you have the header file. */ #undef HAVE_ERR_H /* Define to 1 if you have the header file. */ #undef HAVE_FCNTL_H /* Define to 1 if you have the `fork' function. */ #undef HAVE_FORK /* Define to 1 if you have the `getcwd' function. */ #undef HAVE_GETCWD /* Define to 1 if you have the `getenv' function. */ #undef HAVE_GETENV /* Define to 1 if you have the `getopt' function. */ #undef HAVE_GETOPT /* Define to 1 if you have the `getwd' function. */ #undef HAVE_GETWD /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `killpg' function. */ #undef HAVE_KILLPG /* Define to 1 if you have the header file. */ #undef HAVE_LIBGEN_H /* Define to 1 if you have the header file. */ #undef HAVE_LIMITS_H /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the `mmap' function. */ #undef HAVE_MMAP /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_NDIR_H /* Define to 1 if you have the header file. */ #undef HAVE_PATHS_H /* Define to 1 if you have the header file. */ #undef HAVE_POLL_H /* Define to 1 if you have the `putenv' function. */ #undef HAVE_PUTENV /* Define to 1 if you have the header file. */ #undef HAVE_RANLIB_H /* Define to 1 if you have the `realpath' function. */ #undef HAVE_REALPATH /* Define to 1 if you have the `select' function. */ #undef HAVE_SELECT /* Define to 1 if you have the `setenv' function. */ #undef HAVE_SETENV /* Define to 1 if you have the `setpgid' function. */ #undef HAVE_SETPGID /* Define to 1 if you have the `setsid' function. */ #undef HAVE_SETSID /* Define to 1 if you have the `sigaction' function. */ #undef HAVE_SIGACTION /* Define to 1 if you have the `sigvec' function. */ #undef HAVE_SIGVEC /* Define to 1 if you have the `snprintf' function. */ #undef HAVE_SNPRINTF /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the `strerror' function. */ #undef HAVE_STRERROR /* Define to 1 if you have the `stresep' function. */ #undef HAVE_STRESEP /* Define to 1 if you have the `strftime' function. */ #undef HAVE_STRFTIME /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the `strlcpy' function. */ #undef HAVE_STRLCPY /* Define to 1 if you have the `strsep' function. */ #undef HAVE_STRSEP /* Define to 1 if you have the `strtod' function. */ #undef HAVE_STRTOD /* Define to 1 if you have the `strtol' function. */ #undef HAVE_STRTOL -/* Define to 1 if `struct stat' is a member of `st_rdev'. */ +/* Define to 1 if `st_rdev' is a member of `struct stat'. */ #undef HAVE_STRUCT_STAT_ST_RDEV /* Define to 1 if your `struct stat' has `st_rdev'. Deprecated, use `HAVE_STRUCT_STAT_ST_RDEV' instead. */ #undef HAVE_ST_RDEV /* Define to 1 if you have the `sysctl' function. */ #undef HAVE_SYSCTL /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_DIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_MMAN_H /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_NDIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_PARAM_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SELECT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKET_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SYSCTL_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TIME_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_UIO_H /* Define to 1 if you have that is POSIX.1 compatible. */ #undef HAVE_SYS_WAIT_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the `unsetenv' function. */ #undef HAVE_UNSETENV /* Define to 1 if you have the header file. */ #undef HAVE_UTIME_H /* Define to 1 if you have the `vfork' function. */ #undef HAVE_VFORK /* Define to 1 if you have the header file. */ #undef HAVE_VFORK_H /* Define to 1 if you have the `vprintf' function. */ #undef HAVE_VPRINTF /* Define to 1 if you have the `vsnprintf' function. */ #undef HAVE_VSNPRINTF /* Define to 1 if you have the `wait3' function. */ #undef HAVE_WAIT3 /* Define to 1 if you have the `wait4' function. */ #undef HAVE_WAIT4 /* Define to 1 if you have the `waitpid' function. */ #undef HAVE_WAITPID /* Define to 1 if you have the `warn' function. */ #undef HAVE_WARN /* Define to 1 if you have the `warnx' function. */ #undef HAVE_WARNX /* Define to 1 if `fork' works. */ #undef HAVE_WORKING_FORK /* Define to 1 if `vfork' works. */ #undef HAVE_WORKING_VFORK /* define if your compiler has __attribute__ */ #undef HAVE___ATTRIBUTE__ /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define as the return type of signal handlers (`int' or `void'). */ #undef RETSIGTYPE /* Define to 1 if the `S_IS*' macros in do not work properly. */ #undef STAT_MACROS_BROKEN /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Define to 1 if you can safely include both and . */ #undef TIME_WITH_SYS_TIME /* Define to 1 if your declares `struct tm'. */ #undef TM_IN_SYS_TIME /* Enable extensions on AIX 3, Interix. */ #ifndef _ALL_SOURCE # undef _ALL_SOURCE #endif /* Enable GNU extensions on systems that have them. */ #ifndef _GNU_SOURCE # undef _GNU_SOURCE #endif /* Enable threading extensions on Solaris. */ #ifndef _POSIX_PTHREAD_SEMANTICS # undef _POSIX_PTHREAD_SEMANTICS #endif /* Enable extensions on HP NonStop. */ #ifndef _TANDEM_SOURCE # undef _TANDEM_SOURCE #endif /* Enable general extensions on Solaris. */ #ifndef __EXTENSIONS__ # undef __EXTENSIONS__ #endif /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define to 1 if on MINIX. */ #undef _MINIX /* Define to 2 if the system does not provide POSIX.1 features except with this defined. */ #undef _POSIX_1_SOURCE /* Define to 1 if you need to in order for `stat' and other things to work. */ #undef _POSIX_SOURCE /* Define for Solaris 2.5.1 so the uint32_t typedef from , , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ #undef _UINT32_T /* C99 function name */ #undef __func__ /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `int' if does not define. */ #undef mode_t /* Define to `long int' if does not define. */ #undef off_t /* Define to `int' if does not define. */ #undef pid_t /* Define to `unsigned int' if does not define. */ #undef size_t /* Define to the type of an unsigned integer type of width exactly 32 bits if such a type exists and the standard includes do not define it. */ #undef uint32_t /* Define as `fork' if `vfork' does not work. */ #undef vfork Index: stable/12/contrib/bmake/configure =================================================================== Cannot display: file marked as a binary type. svn:mime-type = application/x-shellscript Index: stable/12/contrib/bmake/configure.in =================================================================== --- stable/12/contrib/bmake/configure.in (revision 361673) +++ stable/12/contrib/bmake/configure.in (revision 361674) @@ -1,403 +1,430 @@ dnl dnl RCSid: -dnl $Id: configure.in,v 1.59 2017/11/26 22:39:20 sjg Exp $ +dnl $Id: configure.in,v 1.63 2020/04/19 05:17:57 sjg Exp $ dnl dnl Process this file with autoconf to produce a configure script dnl AC_PREREQ(2.50) -AC_INIT([bmake], [20171126], [sjg@NetBSD.org]) +AC_INIT([bmake], [20200418], [sjg@NetBSD.org]) AC_CONFIG_HEADERS(config.h) dnl make srcdir absolute case "$srcdir" in /*) ;; *) srcdir=`cd $srcdir && pwd`;; esac dnl get _MAKE_VERSION . $srcdir/VERSION +OS=`uname -s` dnl AC_ARG_WITH(defshell, [ --with-defshell=SHELL use SHELL by default - must be sh compatible, use sh or ksh to pick the internal definitions], [case "${withval}" in yes) AC_MSG_ERROR(bad value ${withval} given for bmake DEFSHELL) ;; no) ;; *) case "$with_defshell" in sh) DEFSHELL_INDEX=DEFSHELL_INDEX_SH;; # it's the default anyway ksh) DEFSHELL_INDEX=DEFSHELL_INDEX_KSH;; csh) DEFSHELL_INDEX=DEFSHELL_INDEX_CSH;; # kidding right? *) defshell_path=$with_defshell;; # better be sh compatible! esac ;; esac]) dnl +case "$OS" in +CYGWIN*|MINGW*) use_makefile=no;; +*) use_makefile=yes;; +esac +AC_ARG_WITH(makefile, +[ --without-makefile dissable use of generated makefile], +[case "${withval}" in +yes|no) use_makefile=${withval};; +*) AC_MSG_ERROR(bad value ${withval} given for makefile) ;; +esac]) +dnl use_meta=yes AC_ARG_WITH(meta, [ --without-meta dissable use of meta-mode], [case "${withval}" in yes|no) use_meta=${withval};; *) AC_MSG_ERROR(bad value ${withval} given for meta) ;; esac]) dnl AC_ARG_WITH(filemon, -[ --with-filemon=path/filemon.h indicate path to filemon.h for meta-mode], +[ --with-filemon={no,dev,ktrace,path/filemon.h} indicate filemon method for meta-mode. Path to filemon.h implies dev], [ case "/${withval}" in -/no|*/filemon.h) filemon_h="${withval}";; +/no) use_filemon=no;; +/*trace) filemon_h=no use_filemon="${withval}";; +*/filemon.h) filemon_h="${withval}";; */filemon*) filemon_h="${withval}/filemon.h";; *) AC_MSG_ERROR(bad value ${withval} given for filemon) ;; esac], [ -OS=`uname -s` -for d in "/usr/include/dev/filemon" "$prefix/include/dev/filemon" "$srcdir/filemon" "$srcdir/../filemon" "$srcdir/../../sys/dev/filemon" -do - for x in "/$OS" "" - do - filemon_h="$d$x/filemon.h" - test -s "$filemon_h" && break - done - test -s "$filemon_h" && break -done -test -s "${filemon_h:-/dev/null}" || filemon_h=no +case "$OS" in +NetBSD) filemon_h=no use_filemon=ktrace;; +*) + for d in "/usr/include/dev/filemon" "$prefix/include/dev/filemon" "$srcdir/../../sys/dev/filemon" + do + for x in "/$OS" "" + do + filemon_h="$d$x/filemon.h" + test -s "$filemon_h" && break + done + test -s "$filemon_h" && { use_filemon=dev; break; } + done + ;; +esac +use_filemon=${use_filemon:-no} +case "$use_filemon" in +dev) ;; +*) filemon_h=no;; +esac ]) -dnl echo "Note: use_meta=$use_meta filemon_h=$filemon_h" >&6 +dnl echo "Note: use_meta=$use_meta use_filemon=$use_filemon filemon_h=$filemon_h" >&6 case "$use_meta" in yes) - case "$filemon_h" in - *.h) echo "Using: filemon=$filemon_h" >&6;; + case "$use_filemon" in + no) ;; + *) echo "Using: filemon_${use_filemon}.c" >&6;; esac ;; esac dnl dnl Check for OS problems dnl Solaris's signal.h only privides sigset_t etc if one of dnl _EXTENSIONS_ _POSIX_C_SOURCE or _XOPEN_SOURCE are defined. dnl The later two seem to cause more problems than they solve so if we dnl see _EXTENSIONS_ we use it. AC_USE_SYSTEM_EXTENSIONS dnl Checks for programs. AC_PROG_CC AC_PROG_GCC_TRADITIONAL AC_PROG_INSTALL dnl Executable suffix - normally empty; .exe on os2. AC_SUBST(ac_exe_suffix)dnl dnl dnl Hurd refuses to define PATH_MAX or MAXPATHLEN if test -x /usr/bin/getconf; then bmake_path_max=`getconf PATH_MAX / 2> /dev/null` # only a numeric response is useful test ${bmake_path_max:-0} -gt 0 2> /dev/null || bmake_path_max= fi bmake_path_max=${bmake_path_max:-1024} if test $bmake_path_max -gt 1024; then # this is all we expect bmake_path_max=1024 fi echo "Using: BMAKE_PATH_MAX=$bmake_path_max" >&6 AC_SUBST(bmake_path_max)dnl dnl dnl AC_C_CROSS dnl dnl Checks for header files. AC_HEADER_STDC AC_HEADER_SYS_WAIT AC_HEADER_DIRENT dnl Keep this list sorted AC_CHECK_HEADERS(sys/param.h) dnl On BSDi at least we really need sys/param.h for sys/sysctl.h AC_CHECK_HEADERS([sys/sysctl.h], [], [], [#ifdef HAVE_SYS_PARAM_H # include # endif ]) AC_CHECK_HEADERS( \ ar.h \ err.h \ fcntl.h \ libgen.h \ limits.h \ paths.h \ poll.h \ ranlib.h \ string.h \ sys/mman.h \ sys/select.h \ sys/socket.h \ sys/time.h \ sys/uio.h \ unistd.h \ utime.h \ ) dnl Both *BSD and Linux have sys/cdefs.h, most do not. dnl If it is missing, we add -I${srcdir}/missing to CFLAGS dnl also if sys/cdefs.h does not have __RCSID we need to use ours dnl but we need to include the host's one too *sigh* AC_CHECK_HEADER(sys/cdefs.h, echo $ECHO_N "checking whether sys/cdefs.h is compatible... $ECHO_C" >&6 AC_EGREP_CPP(yes, [#include #ifdef __RCSID yes #endif ], echo yes >&6, echo no >&6; CPPFLAGS="${CPPFLAGS} -I`cd ${srcdir}/missing && pwd` -DNEED_HOST_CDEFS_H"), CPPFLAGS="${CPPFLAGS} -I`cd ${srcdir}/missing && pwd`") dnl Checks for typedefs, structures, and compiler characteristics. AC_C___ATTRIBUTE__ AC_C_BIGENDIAN AC_C_CONST AC_TYPE_MODE_T AC_TYPE_OFF_T AC_TYPE_PID_T AC_TYPE_SIZE_T AC_TYPE_UINT32_T AC_DECL_SYS_SIGLIST AC_HEADER_TIME AC_STRUCT_TM dnl Checks for library functions. AC_TYPE_SIGNAL AC_FUNC_VFORK AC_FUNC_VPRINTF AC_FUNC_WAIT3 dnl Keep this list sorted AC_CHECK_FUNCS( \ err \ errx \ getcwd \ getenv \ getopt \ getwd \ killpg \ mmap \ putenv \ select \ setenv \ setpgid \ setsid \ sigaction \ sigvec \ snprintf \ strerror \ strftime \ strsep \ strtod \ strtol \ sysctl \ unsetenv \ vsnprintf \ wait3 \ wait4 \ waitpid \ warn \ warnx \ ) dnl functions which we may need to provide AC_REPLACE_FUNCS( \ realpath \ dirname \ stresep \ strlcpy \ ) AC_CHECK_LIB([util], [emalloc], [ AC_CHECK_LIB([util], [erealloc], [ AC_CHECK_LIB([util], [estrdup], [ AC_CHECK_LIB([util], [estrndup], [ LIBS="$LIBS -lutil" CPPFLAGS="$CPPFLAGS -DUSE_EMALLOC" ])])])]) dnl dnl Structures dnl AC_HEADER_STAT AC_STRUCT_ST_RDEV dnl echo "checking if compiler supports __func__" >&6 AC_LANG(C) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[[const char *func = __func__;]])],, AC_DEFINE(__func__, __FUNCTION__, C99 function name)) dnl dnl we want this for unit-tests/Makefile echo $ECHO_N "checking if diff -u works... $ECHO_C" >&6 if diff -u /dev/null /dev/null > /dev/null 2>&1; then diff_u=-u echo yes >&6 else diff_u= echo no >&6 fi dnl dnl AC_* don't quite cut it. dnl echo "checking for MACHINE & MACHINE_ARCH..." >&6 cat > conftest.$ac_ext < #ifdef MACHINE machine=MACHINE #endif #ifdef MACHINE_ARCH machine_arch=MACHINE_ARCH #endif EOF default_machine=`(eval "$ac_cpp conftest.$ac_ext") 2>&5 | egrep machine= | tr -d ' "'` rm -rf conftest* if test "$default_machine"; then eval "$default_machine" fi machine=${machine:-`$srcdir/machine.sh`} machine_arch=${machine_arch:-`$srcdir/machine.sh arch`} echo "defaults: MACHINE=$machine, MACHINE_ARCH=$machine_arch" 1>&6 dnl dnl now allow overrides dnl AC_ARG_WITH(machine, [ --with-machine=MACHINE explicitly set MACHINE], [case "${withval}" in yes) AC_MSG_ERROR(bad value ${withval} given for bmake MACHINE) ;; no) ;; generic) machine=`$srcdir/machine.sh`;; *) machine=$with_machine;; esac]) force_machine= AC_ARG_WITH(force_machine, [ --with-force-machine=MACHINE set FORCE_MACHINE], [case "${withval}" in yes) force_machine=FORCE_;; no) ;; *) force_machine=FORCE_; machine=$with_force_machine;; esac]) dnl force_machine_arch= AC_ARG_WITH(force_machine_arch, [ --with-force-machine-arch=MACHINE set FORCE_MACHINE_ARCH], [case "${withval}" in yes) force_machine_arch=FORCE_;; no) ;; *) force_machine_arch=FORCE_; machine_arch=$with_force_machine;; esac]) dnl AC_ARG_WITH(machine_arch, [ --with-machine_arch=MACHINE_ARCH explicitly set MACHINE_ARCH], [case "${withval}" in yes) AC_MSG_ERROR(bad value ${withval} given for bmake MACHINE_ARCH) ;; no) ;; *) machine_arch=$with_machine_arch;; esac]) dnl dnl Tell them what we ended up with dnl echo "Using: ${force_machine}MACHINE=$machine, MACHINE_ARCH=$machine_arch" 1>&6 dnl dnl Allow folk to control _PATH_DEFSYSPATH dnl default_sys_path=\${prefix}/share/mk AC_ARG_WITH(default-sys-path, [ --with-default-sys-path=PATH:DIR:LIST use an explicit _PATH_DEFSYSPATH MAKESYSPATH is a ':' separated list of directories that bmake will search for system .mk files. _PATH_DEFSYSPATH is its default value.], [case "${withval}" in yes) AC_MSG_ERROR(bad value ${withval} given for bmake _PATH_DEFSYSPATH) ;; no) ;; *) default_sys_path="$with_default_sys_path" ;; esac]) dnl dnl Some folk don't like this one dnl AC_ARG_WITH(path-objdirprefix, [ --with-path-objdirprefix=PATH override _PATH_OBJDIRPREFIX], [case "${withval}" in yes) AC_MSG_ERROR(bad value ${withval} given for bmake _PATH_OBJDIRPREFIX) ;; no) CPPFLAGS="$CPPFLAGS -DNO_PATH_OBJDIRPREFIX" ;; *) CPPFLAGS="$CPPFLAGS \"-D_PATH_OBJDIRPREFIX=\\\"$with_path-objdir\\\"\"" ;; esac]) dnl dnl And this can be handy to do with out. dnl AC_ARG_ENABLE(pwd-override, [ --disable-pwd-override disable \$PWD overriding getcwd()], [case "${enableval}" in yes) ;; no) CPPFLAGS="$CPPFLAGS -DNO_PWD_OVERRIDE" ;; *) AC_MSG_ERROR(bad value ${enableval} given for pwd-override option) ;; esac]) dnl dnl Just for grins dnl AC_ARG_ENABLE(check-make-chdir, [ --disable-check-make-chdir disable make trying to guess when it should automatically cd \${.CURDIR}], [case "${enableval}" in yes) ;; no) CPPFLAGS="$CPPFLAGS -DNO_CHECK_MAKE_CHDIR" ;; *) AC_MSG_ERROR(bad value ${enableval} given for check-make-chdir option) ;; esac]) dnl dnl On non-BSD systems, bootstrap won't work without mk dnl AC_ARG_WITH(mksrc, [ --with-mksrc=PATH tell makefile.boot where to find mk src], [case "${withval}" in ""|yes|no) ;; *) test -s $withval/install-mk && mksrc=$withval || AC_MSG_ERROR(bad value ${withval} given for mksrc cannot find install-mk) ;; esac ]) dnl dnl Now make sure we have a value dnl srcdir=`cd $srcdir && pwd` for mksrc in $mksrc $srcdir/mk $srcdir/../mk mk do test -s $mksrc/install-mk || continue mksrc=`cd $mksrc && pwd` break done mksrc=`echo $mksrc | sed "s,$srcdir,\\\${srcdir},"` echo "Using: MKSRC=$mksrc" 1>&6 dnl On some systems we want a different default shell by default if test -x /usr/xpg4/bin/sh; then defshell_path=${defshell_path:-/usr/xpg4/bin/sh} fi if test -n "$defshell_path"; then echo "Using: SHELL=$defshell_path" >&6 AC_DEFINE_UNQUOTED(DEFSHELL_CUSTOM, "$defshell_path", Path of default shell) fi if test -n "$DEFSHELL_INDEX"; then AC_DEFINE_UNQUOTED(DEFSHELL_INDEX, $DEFSHELL_INDEX, Shell spec to use by default) fi dnl AC_SUBST(machine) AC_SUBST(force_machine) AC_SUBST(machine_arch) AC_SUBST(mksrc) AC_SUBST(default_sys_path) AC_SUBST(INSTALL) AC_SUBST(GCC) AC_SUBST(diff_u) AC_SUBST(use_meta) +AC_SUBST(use_filemon) AC_SUBST(filemon_h) AC_SUBST(_MAKE_VERSION) -AC_OUTPUT(makefile Makefile.config make-bootstrap.sh unit-tests/Makefile) - +bm_outfiles="Makefile.config unit-tests/Makefile.config make-bootstrap.sh" +if test $use_makefile = yes; then + bm_outfiles="makefile $bm_outfiles" +fi +AC_OUTPUT($bm_outfiles) cat < #ifndef lint #if 0 static char sccsid[] = "@(#)dir.c 8.2 (Berkeley) 1/2/94"; #else -__RCSID("$NetBSD: dir.c,v 1.71 2017/04/16 21:14:47 riastradh Exp $"); +__RCSID("$NetBSD: dir.c,v 1.73 2018/07/12 18:03:31 christos Exp $"); #endif #endif /* not lint */ #endif /*- * dir.c -- * Directory searching using wildcards and/or normal names... * Used both for source wildcarding in the Makefile and for finding * implicit sources. * * The interface for this module is: * Dir_Init Initialize the module. * * Dir_InitCur Set the cur Path. * * Dir_InitDot Set the dot Path. * * Dir_End Cleanup the module. * * Dir_SetPATH Set ${.PATH} to reflect state of dirSearchPath. * * Dir_HasWildcards Returns TRUE if the name given it needs to * be wildcard-expanded. * * Dir_Expand Given a pattern and a path, return a Lst of names * which match the pattern on the search path. * * Dir_FindFile Searches for a file on a given search path. * If it exists, the entire path is returned. * Otherwise NULL is returned. * * Dir_FindHereOrAbove Search for a path in the current directory and * then all the directories above it in turn until * the path is found or we reach the root ("/"). * * Dir_MTime Return the modification time of a node. The file * is searched for along the default search path. * The path and mtime fields of the node are filled * in. * * Dir_AddDir Add a directory to a search path. * * Dir_MakeFlags Given a search path and a command flag, create * a string with each of the directories in the path * preceded by the command flag and all of them * separated by a space. * * Dir_Destroy Destroy an element of a search path. Frees up all * things that can be freed for the element as long * as the element is no longer referenced by any other * search path. * Dir_ClearPath Resets a search path to the empty list. * * For debugging: * Dir_PrintDirectories Print stats about the directory cache. */ #include #include #include #include #include #include "make.h" #include "hash.h" #include "dir.h" #include "job.h" /* * A search path consists of a Lst of Path structures. A Path structure * has in it the name of the directory and a hash table of all the files * in the directory. This is used to cut down on the number of system * calls necessary to find implicit dependents and their like. Since * these searches are made before any actions are taken, we need not * worry about the directory changing due to creation commands. If this * hampers the style of some makefiles, they must be changed. * * A list of all previously-read directories is kept in the * openDirectories Lst. This list is checked first before a directory * is opened. * * The need for the caching of whole directories is brought about by * the multi-level transformation code in suff.c, which tends to search * for far more files than regular make does. In the initial * implementation, the amount of time spent performing "stat" calls was * truly astronomical. The problem with hashing at the start is, * of course, that pmake doesn't then detect changes to these directories * during the course of the make. Three possibilities suggest themselves: * * 1) just use stat to test for a file's existence. As mentioned * above, this is very inefficient due to the number of checks * engendered by the multi-level transformation code. * 2) use readdir() and company to search the directories, keeping * them open between checks. I have tried this and while it * didn't slow down the process too much, it could severely * affect the amount of parallelism available as each directory * open would take another file descriptor out of play for * handling I/O for another job. Given that it is only recently * that UNIX OS's have taken to allowing more than 20 or 32 * file descriptors for a process, this doesn't seem acceptable * to me. * 3) record the mtime of the directory in the Path structure and * verify the directory hasn't changed since the contents were * hashed. This will catch the creation or deletion of files, * but not the updating of files. However, since it is the * creation and deletion that is the problem, this could be * a good thing to do. Unfortunately, if the directory (say ".") * were fairly large and changed fairly frequently, the constant * rehashing could seriously degrade performance. It might be * good in such cases to keep track of the number of rehashes * and if the number goes over a (small) limit, resort to using * stat in its place. * * An additional thing to consider is that pmake is used primarily * to create C programs and until recently pcc-based compilers refused * to allow you to specify where the resulting object file should be * placed. This forced all objects to be created in the current * directory. This isn't meant as a full excuse, just an explanation of * some of the reasons for the caching used here. * * One more note: the location of a target's file is only performed * on the downward traversal of the graph and then only for terminal * nodes in the graph. This could be construed as wrong in some cases, * but prevents inadvertent modification of files when the "installed" * directory for a file is provided in the search path. * * Another data structure maintained by this module is an mtime * cache used when the searching of cached directories fails to find * a file. In the past, Dir_FindFile would simply perform an access() * call in such a case to determine if the file could be found using * just the name given. When this hit, however, all that was gained * was the knowledge that the file existed. Given that an access() is * essentially a stat() without the copyout() call, and that the same * filesystem overhead would have to be incurred in Dir_MTime, it made * sense to replace the access() with a stat() and record the mtime * in a cache for when Dir_MTime was actually called. */ Lst dirSearchPath; /* main search path */ static Lst openDirectories; /* the list of all open directories */ /* * Variables for gathering statistics on the efficiency of the hashing * mechanism. */ static int hits, /* Found in directory cache */ misses, /* Sad, but not evil misses */ nearmisses, /* Found under search path */ bigmisses; /* Sought by itself */ static Path *dot; /* contents of current directory */ static Path *cur; /* contents of current directory, if not dot */ static Path *dotLast; /* a fake path entry indicating we need to * look for . last */ static Hash_Table mtimes; /* Results of doing a last-resort stat in * Dir_FindFile -- if we have to go to the * system to find the file, we might as well * have its mtime on record. XXX: If this is done * way early, there's a chance other rules will * have already updated the file, in which case * we'll update it again. Generally, there won't * be two rules to update a single file, so this * should be ok, but... */ static Hash_Table lmtimes; /* same as mtimes but for lstat */ static int DirFindName(const void *, const void *); static int DirMatchFiles(const char *, Path *, Lst); static void DirExpandCurly(const char *, const char *, Lst, Lst); static void DirExpandInt(const char *, Lst, Lst); static int DirPrintWord(void *, void *); static int DirPrintDir(void *, void *); static char *DirLookup(Path *, const char *, const char *, Boolean); static char *DirLookupSubdir(Path *, const char *); static char *DirFindDot(Boolean, const char *, const char *); static char *DirLookupAbs(Path *, const char *, const char *); /* * We use stat(2) a lot, cache the results * mtime and mode are all we care about. */ struct cache_st { time_t mtime; mode_t mode; }; /* minimize changes below */ -static time_t -Hash_GetTimeValue(Hash_Entry *entry) -{ - struct cache_st *cst; - - cst = entry->clientPtr; - return cst->mtime; -} - #define CST_LSTAT 1 #define CST_UPDATE 2 static int cached_stats(Hash_Table *htp, const char *pathname, struct stat *st, int flags) { Hash_Entry *entry; struct cache_st *cst; int rc; if (!pathname || !pathname[0]) return -1; entry = Hash_FindEntry(htp, pathname); if (entry && (flags & CST_UPDATE) == 0) { cst = entry->clientPtr; memset(st, 0, sizeof(*st)); st->st_mtime = cst->mtime; st->st_mode = cst->mode; + if (DEBUG(DIR)) { + fprintf(debug_file, "Using cached time %s for %s\n", + Targ_FmtTime(st->st_mtime), pathname); + } return 0; } rc = (flags & CST_LSTAT) ? lstat(pathname, st) : stat(pathname, st); if (rc == -1) return -1; if (st->st_mtime == 0) st->st_mtime = 1; /* avoid confusion with missing file */ if (!entry) entry = Hash_CreateEntry(htp, pathname, NULL); if (!entry->clientPtr) entry->clientPtr = bmake_malloc(sizeof(*cst)); cst = entry->clientPtr; cst->mtime = st->st_mtime; cst->mode = st->st_mode; + if (DEBUG(DIR)) { + fprintf(debug_file, " Caching %s for %s\n", + Targ_FmtTime(st->st_mtime), pathname); + } return 0; } int cached_stat(const char *pathname, void *st) { return cached_stats(&mtimes, pathname, st, 0); } int cached_lstat(const char *pathname, void *st) { return cached_stats(&lmtimes, pathname, st, CST_LSTAT); } /*- *----------------------------------------------------------------------- * Dir_Init -- * initialize things for this module * * Results: * none * * Side Effects: * some directories may be opened. *----------------------------------------------------------------------- */ void Dir_Init(const char *cdname) { if (!cdname) { dirSearchPath = Lst_Init(FALSE); openDirectories = Lst_Init(FALSE); Hash_InitTable(&mtimes, 0); Hash_InitTable(&lmtimes, 0); return; } Dir_InitCur(cdname); dotLast = bmake_malloc(sizeof(Path)); dotLast->refCount = 1; dotLast->hits = 0; dotLast->name = bmake_strdup(".DOTLAST"); Hash_InitTable(&dotLast->files, -1); } /* * Called by Dir_Init() and whenever .CURDIR is assigned to. */ void Dir_InitCur(const char *cdname) { Path *p; if (cdname != NULL) { /* * Our build directory is not the same as our source directory. * Keep this one around too. */ if ((p = Dir_AddDir(NULL, cdname))) { p->refCount += 1; if (cur && cur != p) { /* * We've been here before, cleanup. */ cur->refCount -= 1; Dir_Destroy(cur); } cur = p; } } } /*- *----------------------------------------------------------------------- * Dir_InitDot -- * (re)initialize "dot" (current/object directory) path hash * * Results: * none * * Side Effects: * some directories may be opened. *----------------------------------------------------------------------- */ void Dir_InitDot(void) { if (dot != NULL) { LstNode ln; /* Remove old entry from openDirectories, but do not destroy. */ ln = Lst_Member(openDirectories, dot); (void)Lst_Remove(openDirectories, ln); } dot = Dir_AddDir(NULL, "."); if (dot == NULL) { Error("Cannot open `.' (%s)", strerror(errno)); exit(1); } /* * We always need to have dot around, so we increment its reference count * to make sure it's not destroyed. */ dot->refCount += 1; Dir_SetPATH(); /* initialize */ } /*- *----------------------------------------------------------------------- * Dir_End -- * cleanup things for this module * * Results: * none * * Side Effects: * none *----------------------------------------------------------------------- */ void Dir_End(void) { #ifdef CLEANUP if (cur) { cur->refCount -= 1; Dir_Destroy(cur); } dot->refCount -= 1; dotLast->refCount -= 1; Dir_Destroy(dotLast); Dir_Destroy(dot); Dir_ClearPath(dirSearchPath); Lst_Destroy(dirSearchPath, NULL); Dir_ClearPath(openDirectories); Lst_Destroy(openDirectories, NULL); Hash_DeleteTable(&mtimes); #endif } /* * We want ${.PATH} to indicate the order in which we will actually * search, so we rebuild it after any .PATH: target. * This is the simplest way to deal with the effect of .DOTLAST. */ void Dir_SetPATH(void) { LstNode ln; /* a list element */ Path *p; Boolean hasLastDot = FALSE; /* true we should search dot last */ Var_Delete(".PATH", VAR_GLOBAL); if (Lst_Open(dirSearchPath) == SUCCESS) { if ((ln = Lst_First(dirSearchPath)) != NULL) { p = (Path *)Lst_Datum(ln); if (p == dotLast) { hasLastDot = TRUE; Var_Append(".PATH", dotLast->name, VAR_GLOBAL); } } if (!hasLastDot) { if (dot) Var_Append(".PATH", dot->name, VAR_GLOBAL); if (cur) Var_Append(".PATH", cur->name, VAR_GLOBAL); } while ((ln = Lst_Next(dirSearchPath)) != NULL) { p = (Path *)Lst_Datum(ln); if (p == dotLast) continue; if (p == dot && hasLastDot) continue; Var_Append(".PATH", p->name, VAR_GLOBAL); } if (hasLastDot) { if (dot) Var_Append(".PATH", dot->name, VAR_GLOBAL); if (cur) Var_Append(".PATH", cur->name, VAR_GLOBAL); } Lst_Close(dirSearchPath); } } /*- *----------------------------------------------------------------------- * DirFindName -- * See if the Path structure describes the same directory as the * given one by comparing their names. Called from Dir_AddDir via * Lst_Find when searching the list of open directories. * * Input: * p Current name * dname Desired name * * Results: * 0 if it is the same. Non-zero otherwise * * Side Effects: * None *----------------------------------------------------------------------- */ static int DirFindName(const void *p, const void *dname) { return (strcmp(((const Path *)p)->name, dname)); } /*- *----------------------------------------------------------------------- * Dir_HasWildcards -- * see if the given name has any wildcard characters in it * be careful not to expand unmatching brackets or braces. * XXX: This code is not 100% correct. ([^]] fails etc.) * I really don't think that make(1) should be expanding * patterns, because then you have to set a mechanism for * escaping the expansion! * * Input: * name name to check * * Results: * returns TRUE if the word should be expanded, FALSE otherwise * * Side Effects: * none *----------------------------------------------------------------------- */ Boolean Dir_HasWildcards(char *name) { char *cp; int wild = 0, brace = 0, bracket = 0; for (cp = name; *cp; cp++) { switch(*cp) { case '{': brace++; wild = 1; break; case '}': brace--; break; case '[': bracket++; wild = 1; break; case ']': bracket--; break; case '?': case '*': wild = 1; break; default: break; } } return wild && bracket == 0 && brace == 0; } /*- *----------------------------------------------------------------------- * DirMatchFiles -- * Given a pattern and a Path structure, see if any files * match the pattern and add their names to the 'expansions' list if * any do. This is incomplete -- it doesn't take care of patterns like * src / *src / *.c properly (just *.c on any of the directories), but it * will do for now. * * Input: * pattern Pattern to look for * p Directory to search * expansion Place to store the results * * Results: * Always returns 0 * * Side Effects: * File names are added to the expansions lst. The directory will be * fully hashed when this is done. *----------------------------------------------------------------------- */ static int DirMatchFiles(const char *pattern, Path *p, Lst expansions) { Hash_Search search; /* Index into the directory's table */ Hash_Entry *entry; /* Current entry in the table */ Boolean isDot; /* TRUE if the directory being searched is . */ isDot = (*p->name == '.' && p->name[1] == '\0'); for (entry = Hash_EnumFirst(&p->files, &search); entry != NULL; entry = Hash_EnumNext(&search)) { /* * See if the file matches the given pattern. Note we follow the UNIX * convention that dot files will only be found if the pattern * begins with a dot (note also that as a side effect of the hashing * scheme, .* won't match . or .. since they aren't hashed). */ if (Str_Match(entry->name, pattern) && ((entry->name[0] != '.') || (pattern[0] == '.'))) { (void)Lst_AtEnd(expansions, (isDot ? bmake_strdup(entry->name) : str_concat(p->name, entry->name, STR_ADDSLASH))); } } return (0); } /*- *----------------------------------------------------------------------- * DirExpandCurly -- * Expand curly braces like the C shell. Does this recursively. * Note the special case: if after the piece of the curly brace is * done there are no wildcard characters in the result, the result is * placed on the list WITHOUT CHECKING FOR ITS EXISTENCE. * * Input: * word Entire word to expand * brace First curly brace in it * path Search path to use * expansions Place to store the expansions * * Results: * None. * * Side Effects: * The given list is filled with the expansions... * *----------------------------------------------------------------------- */ static void DirExpandCurly(const char *word, const char *brace, Lst path, Lst expansions) { const char *end; /* Character after the closing brace */ const char *cp; /* Current position in brace clause */ const char *start; /* Start of current piece of brace clause */ int bracelevel; /* Number of braces we've seen. If we see a * right brace when this is 0, we've hit the * end of the clause. */ char *file; /* Current expansion */ int otherLen; /* The length of the other pieces of the * expansion (chars before and after the * clause in 'word') */ char *cp2; /* Pointer for checking for wildcards in * expansion before calling Dir_Expand */ start = brace+1; /* * Find the end of the brace clause first, being wary of nested brace * clauses. */ for (end = start, bracelevel = 0; *end != '\0'; end++) { if (*end == '{') { bracelevel++; } else if ((*end == '}') && (bracelevel-- == 0)) { break; } } if (*end == '\0') { Error("Unterminated {} clause \"%s\"", start); return; } else { end++; } otherLen = brace - word + strlen(end); for (cp = start; cp < end; cp++) { /* * Find the end of this piece of the clause. */ bracelevel = 0; while (*cp != ',') { if (*cp == '{') { bracelevel++; } else if ((*cp == '}') && (bracelevel-- <= 0)) { break; } cp++; } /* * Allocate room for the combination and install the three pieces. */ file = bmake_malloc(otherLen + cp - start + 1); if (brace != word) { strncpy(file, word, brace-word); } if (cp != start) { strncpy(&file[brace-word], start, cp-start); } strcpy(&file[(brace-word)+(cp-start)], end); /* * See if the result has any wildcards in it. If we find one, call * Dir_Expand right away, telling it to place the result on our list * of expansions. */ for (cp2 = file; *cp2 != '\0'; cp2++) { switch(*cp2) { case '*': case '?': case '{': case '[': Dir_Expand(file, path, expansions); goto next; } } if (*cp2 == '\0') { /* * Hit the end w/o finding any wildcards, so stick the expansion * on the end of the list. */ (void)Lst_AtEnd(expansions, file); } else { next: free(file); } start = cp+1; } } /*- *----------------------------------------------------------------------- * DirExpandInt -- * Internal expand routine. Passes through the directories in the * path one by one, calling DirMatchFiles for each. NOTE: This still * doesn't handle patterns in directories... * * Input: * word Word to expand * path Path on which to look * expansions Place to store the result * * Results: * None. * * Side Effects: * Things are added to the expansions list. * *----------------------------------------------------------------------- */ static void DirExpandInt(const char *word, Lst path, Lst expansions) { LstNode ln; /* Current node */ Path *p; /* Directory in the node */ if (Lst_Open(path) == SUCCESS) { while ((ln = Lst_Next(path)) != NULL) { p = (Path *)Lst_Datum(ln); DirMatchFiles(word, p, expansions); } Lst_Close(path); } } /*- *----------------------------------------------------------------------- * DirPrintWord -- * Print a word in the list of expansions. Callback for Dir_Expand * when DEBUG(DIR), via Lst_ForEach. * * Results: * === 0 * * Side Effects: * The passed word is printed, followed by a space. * *----------------------------------------------------------------------- */ static int DirPrintWord(void *word, void *dummy MAKE_ATTR_UNUSED) { fprintf(debug_file, "%s ", (char *)word); return 0; } /*- *----------------------------------------------------------------------- * Dir_Expand -- * Expand the given word into a list of words by globbing it looking * in the directories on the given search path. * * Input: * word the word to expand * path the list of directories in which to find the * resulting files * expansions the list on which to place the results * * Results: * A list of words consisting of the files which exist along the search * path matching the given pattern. * * Side Effects: * Directories may be opened. Who knows? *----------------------------------------------------------------------- */ void Dir_Expand(const char *word, Lst path, Lst expansions) { const char *cp; if (DEBUG(DIR)) { fprintf(debug_file, "Expanding \"%s\"... ", word); } cp = strchr(word, '{'); if (cp) { DirExpandCurly(word, cp, path, expansions); } else { cp = strchr(word, '/'); if (cp) { /* * The thing has a directory component -- find the first wildcard * in the string. */ for (cp = word; *cp; cp++) { if (*cp == '?' || *cp == '[' || *cp == '*' || *cp == '{') { break; } } if (*cp == '{') { /* * This one will be fun. */ DirExpandCurly(word, cp, path, expansions); return; } else if (*cp != '\0') { /* * Back up to the start of the component */ char *dirpath; while (cp > word && *cp != '/') { cp--; } if (cp != word) { char sc; /* * If the glob isn't in the first component, try and find * all the components up to the one with a wildcard. */ sc = cp[1]; ((char *)UNCONST(cp))[1] = '\0'; dirpath = Dir_FindFile(word, path); ((char *)UNCONST(cp))[1] = sc; /* * dirpath is null if can't find the leading component * XXX: Dir_FindFile won't find internal components. * i.e. if the path contains ../Etc/Object and we're * looking for Etc, it won't be found. Ah well. * Probably not important. */ if (dirpath != NULL) { char *dp = &dirpath[strlen(dirpath) - 1]; if (*dp == '/') *dp = '\0'; path = Lst_Init(FALSE); (void)Dir_AddDir(path, dirpath); DirExpandInt(cp+1, path, expansions); Lst_Destroy(path, NULL); } } else { /* * Start the search from the local directory */ DirExpandInt(word, path, expansions); } } else { /* * Return the file -- this should never happen. */ DirExpandInt(word, path, expansions); } } else { /* * First the files in dot */ DirMatchFiles(word, dot, expansions); /* * Then the files in every other directory on the path. */ DirExpandInt(word, path, expansions); } } if (DEBUG(DIR)) { Lst_ForEach(expansions, DirPrintWord, NULL); fprintf(debug_file, "\n"); } } /*- *----------------------------------------------------------------------- * DirLookup -- * Find if the file with the given name exists in the given path. * * Results: * The path to the file or NULL. This path is guaranteed to be in a * different part of memory than name and so may be safely free'd. * * Side Effects: * None. *----------------------------------------------------------------------- */ static char * DirLookup(Path *p, const char *name MAKE_ATTR_UNUSED, const char *cp, Boolean hasSlash MAKE_ATTR_UNUSED) { char *file; /* the current filename to check */ if (DEBUG(DIR)) { fprintf(debug_file, " %s ...\n", p->name); } if (Hash_FindEntry(&p->files, cp) == NULL) return NULL; file = str_concat(p->name, cp, STR_ADDSLASH); if (DEBUG(DIR)) { fprintf(debug_file, " returning %s\n", file); } p->hits += 1; hits += 1; return file; } /*- *----------------------------------------------------------------------- * DirLookupSubdir -- * Find if the file with the given name exists in the given path. * * Results: * The path to the file or NULL. This path is guaranteed to be in a * different part of memory than name and so may be safely free'd. * * Side Effects: * If the file is found, it is added in the modification times hash * table. *----------------------------------------------------------------------- */ static char * DirLookupSubdir(Path *p, const char *name) { struct stat stb; /* Buffer for stat, if necessary */ char *file; /* the current filename to check */ if (p != dot) { file = str_concat(p->name, name, STR_ADDSLASH); } else { /* * Checking in dot -- DON'T put a leading ./ on the thing. */ file = bmake_strdup(name); } if (DEBUG(DIR)) { fprintf(debug_file, "checking %s ...\n", file); } if (cached_stat(file, &stb) == 0) { - /* - * Save the modification time so if it's needed, we don't have - * to fetch it again. - */ - if (DEBUG(DIR)) { - fprintf(debug_file, " Caching %s for %s\n", Targ_FmtTime(stb.st_mtime), - file); - } nearmisses += 1; return (file); } free(file); return NULL; } /*- *----------------------------------------------------------------------- * DirLookupAbs -- * Find if the file with the given name exists in the given path. * * Results: * The path to the file, the empty string or NULL. If the file is * the empty string, the search should be terminated. * This path is guaranteed to be in a different part of memory * than name and so may be safely free'd. * * Side Effects: * None. *----------------------------------------------------------------------- */ static char * DirLookupAbs(Path *p, const char *name, const char *cp) { char *p1; /* pointer into p->name */ const char *p2; /* pointer into name */ if (DEBUG(DIR)) { fprintf(debug_file, " %s ...\n", p->name); } /* * If the file has a leading path component and that component * exactly matches the entire name of the current search * directory, we can attempt another cache lookup. And if we don't * have a hit, we can safely assume the file does not exist at all. */ for (p1 = p->name, p2 = name; *p1 && *p1 == *p2; p1++, p2++) { continue; } if (*p1 != '\0' || p2 != cp - 1) { return NULL; } if (Hash_FindEntry(&p->files, cp) == NULL) { if (DEBUG(DIR)) { fprintf(debug_file, " must be here but isn't -- returning\n"); } /* Return empty string: terminates search */ return bmake_strdup(""); } p->hits += 1; hits += 1; if (DEBUG(DIR)) { fprintf(debug_file, " returning %s\n", name); } return (bmake_strdup(name)); } /*- *----------------------------------------------------------------------- * DirFindDot -- * Find the file given on "." or curdir * * Results: * The path to the file or NULL. This path is guaranteed to be in a * different part of memory than name and so may be safely free'd. * * Side Effects: * Hit counts change *----------------------------------------------------------------------- */ static char * DirFindDot(Boolean hasSlash MAKE_ATTR_UNUSED, const char *name, const char *cp) { if (Hash_FindEntry(&dot->files, cp) != NULL) { if (DEBUG(DIR)) { fprintf(debug_file, " in '.'\n"); } hits += 1; dot->hits += 1; return (bmake_strdup(name)); } if (cur && Hash_FindEntry(&cur->files, cp) != NULL) { if (DEBUG(DIR)) { fprintf(debug_file, " in ${.CURDIR} = %s\n", cur->name); } hits += 1; cur->hits += 1; return str_concat(cur->name, cp, STR_ADDSLASH); } return NULL; } /*- *----------------------------------------------------------------------- * Dir_FindFile -- * Find the file with the given name along the given search path. * * Input: * name the file to find * path the Lst of directories to search * * Results: * The path to the file or NULL. This path is guaranteed to be in a * different part of memory than name and so may be safely free'd. * * Side Effects: * If the file is found in a directory which is not on the path * already (either 'name' is absolute or it is a relative path * [ dir1/.../dirn/file ] which exists below one of the directories * already on the search path), its directory is added to the end * of the path on the assumption that there will be more files in * that directory later on. Sometimes this is true. Sometimes not. *----------------------------------------------------------------------- */ char * Dir_FindFile(const char *name, Lst path) { LstNode ln; /* a list element */ char *file; /* the current filename to check */ Path *p; /* current path member */ const char *cp; /* Terminal name of file */ Boolean hasLastDot = FALSE; /* true we should search dot last */ Boolean hasSlash; /* true if 'name' contains a / */ struct stat stb; /* Buffer for stat, if necessary */ - Hash_Entry *entry; /* Entry for mtimes table */ const char *trailing_dot = "."; /* * Find the final component of the name and note whether it has a * slash in it (the name, I mean) */ cp = strrchr(name, '/'); if (cp) { hasSlash = TRUE; cp += 1; } else { hasSlash = FALSE; cp = name; } if (DEBUG(DIR)) { fprintf(debug_file, "Searching for %s ...", name); } if (Lst_Open(path) == FAILURE) { if (DEBUG(DIR)) { fprintf(debug_file, "couldn't open path, file not found\n"); } misses += 1; return NULL; } if ((ln = Lst_First(path)) != NULL) { p = (Path *)Lst_Datum(ln); if (p == dotLast) { hasLastDot = TRUE; if (DEBUG(DIR)) fprintf(debug_file, "[dot last]..."); } } if (DEBUG(DIR)) { fprintf(debug_file, "\n"); } /* * If there's no leading directory components or if the leading * directory component is exactly `./', consult the cached contents * of each of the directories on the search path. */ if (!hasSlash || (cp - name == 2 && *name == '.')) { /* * We look through all the directories on the path seeking one which * contains the final component of the given name. If such a beast * is found, we concatenate the directory name and the final * component and return the resulting string. If we don't find any * such thing, we go on to phase two... * * No matter what, we always look for the file in the current * directory before anywhere else (unless we found the magic * DOTLAST path, in which case we search it last) and we *do not* * add the ./ to it if it exists. * This is so there are no conflicts between what the user * specifies (fish.c) and what pmake finds (./fish.c). */ if (!hasLastDot && (file = DirFindDot(hasSlash, name, cp)) != NULL) { Lst_Close(path); return file; } while ((ln = Lst_Next(path)) != NULL) { p = (Path *)Lst_Datum(ln); if (p == dotLast) continue; if ((file = DirLookup(p, name, cp, hasSlash)) != NULL) { Lst_Close(path); return file; } } if (hasLastDot && (file = DirFindDot(hasSlash, name, cp)) != NULL) { Lst_Close(path); return file; } } Lst_Close(path); /* * We didn't find the file on any directory in the search path. * If the name doesn't contain a slash, that means it doesn't exist. * If it *does* contain a slash, however, there is still hope: it * could be in a subdirectory of one of the members of the search * path. (eg. /usr/include and sys/types.h. The above search would * fail to turn up types.h in /usr/include, but it *is* in * /usr/include/sys/types.h). * [ This no longer applies: If we find such a beast, we assume there * will be more (what else can we assume?) and add all but the last * component of the resulting name onto the search path (at the * end).] * This phase is only performed if the file is *not* absolute. */ if (!hasSlash) { if (DEBUG(DIR)) { fprintf(debug_file, " failed.\n"); } misses += 1; return NULL; } if (*cp == '\0') { /* we were given a trailing "/" */ cp = trailing_dot; } if (name[0] != '/') { Boolean checkedDot = FALSE; if (DEBUG(DIR)) { fprintf(debug_file, " Trying subdirectories...\n"); } if (!hasLastDot) { if (dot) { checkedDot = TRUE; if ((file = DirLookupSubdir(dot, name)) != NULL) return file; } if (cur && (file = DirLookupSubdir(cur, name)) != NULL) return file; } (void)Lst_Open(path); while ((ln = Lst_Next(path)) != NULL) { p = (Path *)Lst_Datum(ln); if (p == dotLast) continue; if (p == dot) { if (checkedDot) continue; checkedDot = TRUE; } if ((file = DirLookupSubdir(p, name)) != NULL) { Lst_Close(path); return file; } } Lst_Close(path); if (hasLastDot) { if (dot && !checkedDot) { checkedDot = TRUE; if ((file = DirLookupSubdir(dot, name)) != NULL) return file; } if (cur && (file = DirLookupSubdir(cur, name)) != NULL) return file; } if (checkedDot) { /* * Already checked by the given name, since . was in the path, * so no point in proceeding... */ if (DEBUG(DIR)) { fprintf(debug_file, " Checked . already, returning NULL\n"); } return NULL; } } else { /* name[0] == '/' */ /* * For absolute names, compare directory path prefix against the * the directory path of each member on the search path for an exact * match. If we have an exact match on any member of the search path, * use the cached contents of that member to lookup the final file * component. If that lookup fails we can safely assume that the * file does not exist at all. This is signified by DirLookupAbs() * returning an empty string. */ if (DEBUG(DIR)) { fprintf(debug_file, " Trying exact path matches...\n"); } if (!hasLastDot && cur && ((file = DirLookupAbs(cur, name, cp)) != NULL)) { if (file[0] == '\0') { free(file); return NULL; } return file; } (void)Lst_Open(path); while ((ln = Lst_Next(path)) != NULL) { p = (Path *)Lst_Datum(ln); if (p == dotLast) continue; if ((file = DirLookupAbs(p, name, cp)) != NULL) { Lst_Close(path); if (file[0] == '\0') { free(file); return NULL; } return file; } } Lst_Close(path); if (hasLastDot && cur && ((file = DirLookupAbs(cur, name, cp)) != NULL)) { if (file[0] == '\0') { free(file); return NULL; } return file; } } /* * Didn't find it that way, either. Sigh. Phase 3. Add its directory * onto the search path in any case, just in case, then look for the * thing in the hash table. If we find it, grand. We return a new * copy of the name. Otherwise we sadly return a NULL pointer. Sigh. * Note that if the directory holding the file doesn't exist, this will * do an extra search of the final directory on the path. Unless something * weird happens, this search won't succeed and life will be groovy. * * Sigh. We cannot add the directory onto the search path because * of this amusing case: * $(INSTALLDIR)/$(FILE): $(FILE) * * $(FILE) exists in $(INSTALLDIR) but not in the current one. * When searching for $(FILE), we will find it in $(INSTALLDIR) * b/c we added it here. This is not good... */ #ifdef notdef if (cp == traling_dot) { cp = strrchr(name, '/'); cp += 1; } cp[-1] = '\0'; (void)Dir_AddDir(path, name); cp[-1] = '/'; bigmisses += 1; ln = Lst_Last(path); if (ln == NULL) { return NULL; } else { p = (Path *)Lst_Datum(ln); } if (Hash_FindEntry(&p->files, cp) != NULL) { return (bmake_strdup(name)); } else { return NULL; } #else /* !notdef */ if (DEBUG(DIR)) { fprintf(debug_file, " Looking for \"%s\" ...\n", name); } bigmisses += 1; - entry = Hash_FindEntry(&mtimes, name); - if (entry != NULL) { - if (DEBUG(DIR)) { - fprintf(debug_file, " got it (in mtime cache)\n"); - } - return(bmake_strdup(name)); - } else if (cached_stat(name, &stb) == 0) { - if (DEBUG(DIR)) { - fprintf(debug_file, " Caching %s for %s\n", Targ_FmtTime(stb.st_mtime), - name); - } + if (cached_stat(name, &stb) == 0) { return (bmake_strdup(name)); - } else { - if (DEBUG(DIR)) { - fprintf(debug_file, " failed. Returning NULL\n"); - } - return NULL; } + + if (DEBUG(DIR)) { + fprintf(debug_file, " failed. Returning NULL\n"); + } + return NULL; #endif /* notdef */ } /*- *----------------------------------------------------------------------- * Dir_FindHereOrAbove -- * search for a path starting at a given directory and then working * our way up towards the root. * * Input: * here starting directory * search_path the path we are looking for * result the result of a successful search is placed here * rlen the length of the result buffer * (typically MAXPATHLEN + 1) * * Results: * 0 on failure, 1 on success [in which case the found path is put * in the result buffer]. * * Side Effects: *----------------------------------------------------------------------- */ int Dir_FindHereOrAbove(char *here, char *search_path, char *result, int rlen) { struct stat st; char dirbase[MAXPATHLEN + 1], *db_end; char try[MAXPATHLEN + 1], *try_end; /* copy out our starting point */ snprintf(dirbase, sizeof(dirbase), "%s", here); db_end = dirbase + strlen(dirbase); /* loop until we determine a result */ while (1) { /* try and stat(2) it ... */ snprintf(try, sizeof(try), "%s/%s", dirbase, search_path); if (cached_stat(try, &st) != -1) { /* * success! if we found a file, chop off * the filename so we return a directory. */ if ((st.st_mode & S_IFMT) != S_IFDIR) { try_end = try + strlen(try); while (try_end > try && *try_end != '/') try_end--; if (try_end > try) *try_end = 0; /* chop! */ } /* * done! */ snprintf(result, rlen, "%s", try); return(1); } /* * nope, we didn't find it. if we used up dirbase we've * reached the root and failed. */ if (db_end == dirbase) break; /* failed! */ /* * truncate dirbase from the end to move up a dir */ while (db_end > dirbase && *db_end != '/') db_end--; *db_end = 0; /* chop! */ } /* while (1) */ /* * we failed... */ return(0); } /*- *----------------------------------------------------------------------- * Dir_MTime -- * Find the modification time of the file described by gn along the * search path dirSearchPath. * * Input: * gn the file whose modification time is desired * * Results: * The modification time or 0 if it doesn't exist * * Side Effects: * The modification time is placed in the node's mtime slot. * If the node didn't have a path entry before, and Dir_FindFile * found one for it, the full name is placed in the path slot. *----------------------------------------------------------------------- */ int Dir_MTime(GNode *gn, Boolean recheck) { char *fullName; /* the full pathname of name */ struct stat stb; /* buffer for finding the mod time */ - Hash_Entry *entry; if (gn->type & OP_ARCHV) { return Arch_MTime(gn); } else if (gn->type & OP_PHONY) { gn->mtime = 0; return 0; } else if (gn->path == NULL) { if (gn->type & OP_NOPATH) fullName = NULL; else { fullName = Dir_FindFile(gn->name, Suff_FindPath(gn)); if (fullName == NULL && gn->flags & FROM_DEPEND && !Lst_IsEmpty(gn->iParents)) { char *cp; cp = strrchr(gn->name, '/'); if (cp) { /* * This is an implied source, and it may have moved, * see if we can find it via the current .PATH */ cp++; fullName = Dir_FindFile(cp, Suff_FindPath(gn)); if (fullName) { /* * Put the found file in gn->path * so that we give that to the compiler. */ gn->path = bmake_strdup(fullName); if (!Job_RunTarget(".STALE", gn->fname)) fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s, " "found %s\n", progname, gn->fname, gn->lineno, makeDependfile, gn->name, fullName); } } } if (DEBUG(DIR)) fprintf(debug_file, "Found '%s' as '%s'\n", gn->name, fullName ? fullName : "(not found)" ); } } else { fullName = gn->path; } if (fullName == NULL) { fullName = bmake_strdup(gn->name); } - if (!recheck) - entry = Hash_FindEntry(&mtimes, fullName); - else - entry = NULL; - if (entry != NULL) { - stb.st_mtime = Hash_GetTimeValue(entry); - if (DEBUG(DIR)) { - fprintf(debug_file, "Using cached time %s for %s\n", - Targ_FmtTime(stb.st_mtime), fullName); - } - } else if (cached_stats(&mtimes, fullName, &stb, recheck ? CST_UPDATE : 0) < 0) { + if (cached_stats(&mtimes, fullName, &stb, recheck ? CST_UPDATE : 0) < 0) { if (gn->type & OP_MEMBER) { if (fullName != gn->path) free(fullName); return Arch_MemMTime(gn); } else { stb.st_mtime = 0; } } if (fullName && gn->path == NULL) { gn->path = fullName; } gn->mtime = stb.st_mtime; return (gn->mtime); } /*- *----------------------------------------------------------------------- * Dir_AddDir -- * Add the given name to the end of the given path. The order of * the arguments is backwards so ParseDoDependency can do a * Lst_ForEach of its list of paths... * * Input: * path the path to which the directory should be * added * name the name of the directory to add * * Results: * none * * Side Effects: * A structure is added to the list and the directory is * read and hashed. *----------------------------------------------------------------------- */ Path * Dir_AddDir(Lst path, const char *name) { LstNode ln = NULL; /* node in case Path structure is found */ Path *p = NULL; /* pointer to new Path structure */ DIR *d; /* for reading directory */ struct dirent *dp; /* entry in directory */ if (strcmp(name, ".DOTLAST") == 0) { ln = Lst_Find(path, name, DirFindName); if (ln != NULL) return (Path *)Lst_Datum(ln); else { dotLast->refCount += 1; (void)Lst_AtFront(path, dotLast); } } if (path) ln = Lst_Find(openDirectories, name, DirFindName); if (ln != NULL) { p = (Path *)Lst_Datum(ln); if (path && Lst_Member(path, p) == NULL) { p->refCount += 1; (void)Lst_AtEnd(path, p); } } else { if (DEBUG(DIR)) { fprintf(debug_file, "Caching %s ...", name); } if ((d = opendir(name)) != NULL) { p = bmake_malloc(sizeof(Path)); p->name = bmake_strdup(name); p->hits = 0; p->refCount = 1; Hash_InitTable(&p->files, -1); while ((dp = readdir(d)) != NULL) { #if defined(sun) && defined(d_ino) /* d_ino is a sunos4 #define for d_fileno */ /* * The sun directory library doesn't check for a 0 inode * (0-inode slots just take up space), so we have to do * it ourselves. */ if (dp->d_fileno == 0) { continue; } #endif /* sun && d_ino */ (void)Hash_CreateEntry(&p->files, dp->d_name, NULL); } (void)closedir(d); (void)Lst_AtEnd(openDirectories, p); if (path != NULL) (void)Lst_AtEnd(path, p); } if (DEBUG(DIR)) { fprintf(debug_file, "done\n"); } } return p; } /*- *----------------------------------------------------------------------- * Dir_CopyDir -- * Callback function for duplicating a search path via Lst_Duplicate. * Ups the reference count for the directory. * * Results: * Returns the Path it was given. * * Side Effects: * The refCount of the path is incremented. * *----------------------------------------------------------------------- */ void * Dir_CopyDir(void *p) { ((Path *)p)->refCount += 1; return (p); } /*- *----------------------------------------------------------------------- * Dir_MakeFlags -- * Make a string by taking all the directories in the given search * path and preceding them by the given flag. Used by the suffix * module to create variables for compilers based on suffix search * paths. * * Input: * flag flag which should precede each directory * path list of directories * * Results: * The string mentioned above. Note that there is no space between * the given flag and each directory. The empty string is returned if * Things don't go well. * * Side Effects: * None *----------------------------------------------------------------------- */ char * Dir_MakeFlags(const char *flag, Lst path) { char *str; /* the string which will be returned */ char *s1, *s2;/* the current directory preceded by 'flag' */ LstNode ln; /* the node of the current directory */ Path *p; /* the structure describing the current directory */ str = bmake_strdup(""); if (Lst_Open(path) == SUCCESS) { while ((ln = Lst_Next(path)) != NULL) { p = (Path *)Lst_Datum(ln); s2 = str_concat(flag, p->name, 0); str = str_concat(s1 = str, s2, STR_ADDSPACE); free(s1); free(s2); } Lst_Close(path); } return (str); } /*- *----------------------------------------------------------------------- * Dir_Destroy -- * Nuke a directory descriptor, if possible. Callback procedure * for the suffixes module when destroying a search path. * * Input: * pp The directory descriptor to nuke * * Results: * None. * * Side Effects: * If no other path references this directory (refCount == 0), * the Path and all its data are freed. * *----------------------------------------------------------------------- */ void Dir_Destroy(void *pp) { Path *p = (Path *)pp; p->refCount -= 1; if (p->refCount == 0) { LstNode ln; ln = Lst_Member(openDirectories, p); (void)Lst_Remove(openDirectories, ln); Hash_DeleteTable(&p->files); free(p->name); free(p); } } /*- *----------------------------------------------------------------------- * Dir_ClearPath -- * Clear out all elements of the given search path. This is different * from destroying the list, notice. * * Input: * path Path to clear * * Results: * None. * * Side Effects: * The path is set to the empty list. * *----------------------------------------------------------------------- */ void Dir_ClearPath(Lst path) { Path *p; while (!Lst_IsEmpty(path)) { p = (Path *)Lst_DeQueue(path); Dir_Destroy(p); } } /*- *----------------------------------------------------------------------- * Dir_Concat -- * Concatenate two paths, adding the second to the end of the first. * Makes sure to avoid duplicates. * * Input: * path1 Dest * path2 Source * * Results: * None * * Side Effects: * Reference counts for added dirs are upped. * *----------------------------------------------------------------------- */ void Dir_Concat(Lst path1, Lst path2) { LstNode ln; Path *p; for (ln = Lst_First(path2); ln != NULL; ln = Lst_Succ(ln)) { p = (Path *)Lst_Datum(ln); if (Lst_Member(path1, p) == NULL) { p->refCount += 1; (void)Lst_AtEnd(path1, p); } } } /********** DEBUG INFO **********/ void Dir_PrintDirectories(void) { LstNode ln; Path *p; fprintf(debug_file, "#*** Directory Cache:\n"); fprintf(debug_file, "# Stats: %d hits %d misses %d near misses %d losers (%d%%)\n", hits, misses, nearmisses, bigmisses, (hits+bigmisses+nearmisses ? hits * 100 / (hits + bigmisses + nearmisses) : 0)); fprintf(debug_file, "# %-20s referenced\thits\n", "directory"); if (Lst_Open(openDirectories) == SUCCESS) { while ((ln = Lst_Next(openDirectories)) != NULL) { p = (Path *)Lst_Datum(ln); fprintf(debug_file, "# %-20s %10d\t%4d\n", p->name, p->refCount, p->hits); } Lst_Close(openDirectories); } } static int DirPrintDir(void *p, void *dummy MAKE_ATTR_UNUSED) { fprintf(debug_file, "%s ", ((Path *)p)->name); return 0; } void Dir_PrintPath(Lst path) { Lst_ForEach(path, DirPrintDir, NULL); } Index: stable/12/contrib/bmake/dirname.c =================================================================== --- stable/12/contrib/bmake/dirname.c (revision 361673) +++ stable/12/contrib/bmake/dirname.c (revision 361674) @@ -1,120 +1,126 @@ -/* $NetBSD: dirname.c,v 1.13 2014/07/16 10:52:26 christos Exp $ */ +/* $NetBSD: dirname.c,v 1.14 2018/09/27 00:45:34 kre Exp $ */ /*- * Copyright (c) 1997, 2002 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Klaus Klein and Jason R. Thorpe. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H # include #endif #ifndef HAVE_DIRNAME #include +#if defined(LIBC_SCCS) && !defined(lint) +__RCSID("$NetBSD: dirname.c,v 1.14 2018/09/27 00:45:34 kre Exp $"); +#endif /* !LIBC_SCCS && !lint */ + +#include "namespace.h" #include #ifdef HAVE_LIBGEN_H #include #endif #ifdef HAVE_LIMITS_H #include #endif #ifdef HAVE_STRING_H #include #endif #ifndef PATH_MAX # define PATH_MAX 1024 #endif #ifndef MIN # define MIN(a, b) ((a < b) ? a : b) #endif static size_t xdirname_r(const char *path, char *buf, size_t buflen) { const char *endp; size_t len; /* * If `path' is a null pointer or points to an empty string, * return a pointer to the string ".". */ if (path == NULL || *path == '\0') { path = "."; len = 1; goto out; } /* Strip trailing slashes, if any. */ endp = path + strlen(path) - 1; while (endp != path && *endp == '/') endp--; /* Find the start of the dir */ while (endp > path && *endp != '/') endp--; if (endp == path) { path = *endp == '/' ? "/" : "."; len = 1; goto out; } do endp--; while (endp > path && *endp == '/'); len = endp - path + 1; out: if (buf != NULL && buflen != 0) { buflen = MIN(len, buflen - 1); - memcpy(buf, path, buflen); + if (buf != path) + memcpy(buf, path, buflen); buf[buflen] = '\0'; } return len; } char * dirname(char *path) { static char result[PATH_MAX]; (void)xdirname_r(path, result, sizeof(result)); return result; } #ifdef MAIN #include #include int main(int argc, char *argv[]) { printf("%s\n", dirname(argv[1])); exit(0); } #endif #endif Index: stable/12/contrib/bmake/filemon/filemon.h =================================================================== --- stable/12/contrib/bmake/filemon/filemon.h (nonexistent) +++ stable/12/contrib/bmake/filemon/filemon.h (revision 361674) @@ -0,0 +1,53 @@ +/* $NetBSD: filemon.h,v 1.2 2020/01/22 22:10:36 sjg Exp $ */ + +/*- + * Copyright (c) 2019 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Taylor R. Campbell. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef FILEMON_H_ +#define FILEMON_H_ + +#include + +struct filemon; + +const char * + filemon_path(void); + +struct filemon * + filemon_open(void); +int filemon_close(struct filemon *); + +int filemon_setfd(struct filemon *, int); +void filemon_setpid_parent(struct filemon *, pid_t); +int filemon_setpid_child(const struct filemon *, pid_t); + +int filemon_readfd(const struct filemon *); +int filemon_process(struct filemon *); + +#endif /* FILEMON_H_ */ Property changes on: stable/12/contrib/bmake/filemon/filemon.h ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/filemon/filemon_dev.c =================================================================== --- stable/12/contrib/bmake/filemon/filemon_dev.c (nonexistent) +++ stable/12/contrib/bmake/filemon/filemon_dev.c (revision 361674) @@ -0,0 +1,151 @@ +/* $NetBSD: filemon_dev.c,v 1.1 2020/01/19 19:49:37 riastradh Exp $ */ + +/*- + * Copyright (c) 2020 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Taylor R. Campbell. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "filemon.h" + +#include + +#include +#include +#include +#include + +#ifdef HAVE_FILEMON_H +# include +#endif + +#ifndef _PATH_FILEMON +#define _PATH_FILEMON "/dev/filemon" +#endif + +struct filemon { + int fd; +}; + +const char * +filemon_path(void) +{ + + return _PATH_FILEMON; +} + +struct filemon * +filemon_open(void) +{ + struct filemon *F; + unsigned i; + int error; + + /* Allocate and zero a struct filemon object. */ + F = calloc(1, sizeof(*F)); + if (F == NULL) + return NULL; + + /* Try opening /dev/filemon, up to six times (cargo cult!). */ + for (i = 0; (F->fd = open(_PATH_FILEMON, O_RDWR)) == -1; i++) { + if (i == 5) { + error = errno; + goto fail0; + } + } + + /* Success! */ + return F; + +fail0: free(F); + errno = error; + return NULL; +} + +int +filemon_setfd(struct filemon *F, int fd) +{ + + /* Point the kernel at this file descriptor. */ + if (ioctl(F->fd, FILEMON_SET_FD, &fd) == -1) + return -1; + + /* No need for it in userland any more; close it. */ + (void)close(fd); + + /* Success! */ + return 0; +} + +void +filemon_setpid_parent(struct filemon *F, pid_t pid) +{ + /* Nothing to do! */ +} + +int +filemon_setpid_child(const struct filemon *F, pid_t pid) +{ + + /* Just pass it on to the kernel. */ + return ioctl(F->fd, FILEMON_SET_PID, &pid); +} + +int +filemon_close(struct filemon *F) +{ + int error = 0; + + /* Close the filemon device fd. */ + if (close(F->fd) == -1 && error == 0) + error = errno; + + /* Free the filemon descriptor. */ + free(F); + + /* Set errno and return -1 if anything went wrong. */ + if (error) { + errno = error; + return -1; + } + + /* Success! */ + return 0; +} + +int +filemon_readfd(const struct filemon *F) +{ + + return -1; +} + +int +filemon_process(struct filemon *F) +{ + + return 0; +} Property changes on: stable/12/contrib/bmake/filemon/filemon_dev.c ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/filemon/filemon_ktrace.c =================================================================== --- stable/12/contrib/bmake/filemon/filemon_ktrace.c (nonexistent) +++ stable/12/contrib/bmake/filemon/filemon_ktrace.c (revision 361674) @@ -0,0 +1,878 @@ +/* $NetBSD: filemon_ktrace.c,v 1.2 2020/01/19 20:22:57 riastradh Exp $ */ + +/*- + * Copyright (c) 2019 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Taylor R. Campbell. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#define _KERNTYPES /* register_t */ + +#include "filemon.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_CWD +#define AT_CWD -1 +#endif + +struct filemon; +struct filemon_key; +struct filemon_state; + +typedef struct filemon_state *filemon_syscall_t(struct filemon *, + const struct filemon_key *, const struct ktr_syscall *); + +static filemon_syscall_t filemon_sys_chdir; +static filemon_syscall_t filemon_sys_execve; +static filemon_syscall_t filemon_sys_exit; +static filemon_syscall_t filemon_sys_fork; +static filemon_syscall_t filemon_sys_link; +static filemon_syscall_t filemon_sys_open; +static filemon_syscall_t filemon_sys_openat; +static filemon_syscall_t filemon_sys_symlink; +static filemon_syscall_t filemon_sys_unlink; +static filemon_syscall_t filemon_sys_rename; + +static filemon_syscall_t *const filemon_syscalls[] = { + [SYS_chdir] = &filemon_sys_chdir, + [SYS_execve] = &filemon_sys_execve, + [SYS_exit] = &filemon_sys_exit, + [SYS_fork] = &filemon_sys_fork, + [SYS_link] = &filemon_sys_link, + [SYS_open] = &filemon_sys_open, + [SYS_openat] = &filemon_sys_openat, + [SYS_symlink] = &filemon_sys_symlink, + [SYS_unlink] = &filemon_sys_unlink, + [SYS_rename] = &filemon_sys_rename, +}; + +struct filemon { + int ktrfd; /* kernel writes ktrace events here */ + FILE *in; /* we read ktrace events from here */ + FILE *out; /* we write filemon events to here */ + rb_tree_t active; + pid_t child; + + /* I/O state machine. */ + enum { + FILEMON_START = 0, + FILEMON_HEADER, + FILEMON_PAYLOAD, + FILEMON_ERROR, + } state; + unsigned char *p; + size_t resid; + + /* I/O buffer. */ + struct ktr_header hdr; + union { + struct ktr_syscall syscall; + struct ktr_sysret sysret; + char namei[PATH_MAX]; + unsigned char buf[4096]; + } payload; +}; + +struct filemon_state { + struct filemon_key { + pid_t pid; + lwpid_t lid; + } key; + struct rb_node node; + int syscode; + void (*show)(struct filemon *, const struct filemon_state *, + const struct ktr_sysret *); + unsigned i; + unsigned npath; + char *path[/*npath*/]; +}; + +static int +compare_filemon_states(void *cookie, const void *na, const void *nb) +{ + const struct filemon_state *Sa = na; + const struct filemon_state *Sb = nb; + + if (Sa->key.pid < Sb->key.pid) + return -1; + if (Sa->key.pid > Sb->key.pid) + return +1; + if (Sa->key.lid < Sb->key.lid) + return -1; + if (Sa->key.lid > Sb->key.lid) + return +1; + return 0; +} + +static int +compare_filemon_key(void *cookie, const void *n, const void *k) +{ + const struct filemon_state *S = n; + const struct filemon_key *key = k; + + if (S->key.pid < key->pid) + return -1; + if (S->key.pid > key->pid) + return +1; + if (S->key.lid < key->lid) + return -1; + if (S->key.lid > key->lid) + return +1; + return 0; +} + +static const rb_tree_ops_t filemon_rb_ops = { + .rbto_compare_nodes = &compare_filemon_states, + .rbto_compare_key = &compare_filemon_key, + .rbto_node_offset = offsetof(struct filemon_state, node), + .rbto_context = NULL, +}; + +/* + * filemon_path() + * + * Return a pointer to a constant string denoting the `path' of + * the filemon. + */ +const char * +filemon_path(void) +{ + + return "ktrace"; +} + +/* + * filemon_open() + * + * Allocate a filemon descriptor. Returns NULL and sets errno on + * failure. + */ +struct filemon * +filemon_open(void) +{ + struct filemon *F; + int ktrpipe[2]; + int error; + + /* Allocate and zero a struct filemon object. */ + F = calloc(1, sizeof(*F)); + if (F == NULL) + return NULL; + + /* Create a pipe for ktrace events. */ + if (pipe2(ktrpipe, O_CLOEXEC|O_NONBLOCK) == -1) { + error = errno; + goto fail0; + } + + /* Create a file stream for reading the ktrace events. */ + if ((F->in = fdopen(ktrpipe[0], "r")) == NULL) { + error = errno; + goto fail1; + } + ktrpipe[0] = -1; /* claimed by fdopen */ + + /* + * Set the fd for writing ktrace events and initialize the + * rbtree. The rest can be safely initialized to zero. + */ + F->ktrfd = ktrpipe[1]; + rb_tree_init(&F->active, &filemon_rb_ops); + + /* Success! */ + return F; + +fail2: __unused + (void)fclose(F->in); +fail1: (void)close(ktrpipe[0]); + (void)close(ktrpipe[1]); +fail0: free(F); + errno = error; + return NULL; +} + +/* + * filemon_closefd(F) + * + * Internal subroutine to try to flush and close the output file. + * If F is not open for output, do nothing. Never leaves F open + * for output even on failure. Returns 0 on success; sets errno + * and return -1 on failure. + */ +static int +filemon_closefd(struct filemon *F) +{ + int error = 0; + + /* If we're not open, nothing to do. */ + if (F->out == NULL) + return 0; + + /* + * Flush it, close it, and null it unconditionally, but be + * careful to return the earliest error in errno. + */ + if (fflush(F->out) == EOF && error == 0) + error = errno; + if (fclose(F->out) == EOF && error == 0) + error = errno; + F->out = NULL; + + /* Set errno and return -1 if anything went wrong. */ + if (error) { + errno = error; + return -1; + } + + /* Success! */ + return 0; +} + +/* + * filemon_setfd(F, fd) + * + * Cause filemon activity on F to be sent to fd. Claims ownership + * of fd; caller should not use fd afterward, and any duplicates + * of fd may see their file positions changed. + */ +int +filemon_setfd(struct filemon *F, int fd) +{ + + /* + * Close an existing output file if done. Fail now if there's + * an error closing. + */ + if ((filemon_closefd(F)) == -1) + return -1; + assert(F->out == NULL); + + /* Open a file stream and claim ownership of the fd. */ + if ((F->out = fdopen(fd, "a")) == NULL) + return -1; + + /* + * Print the opening output. Any failure will be deferred + * until closing. For hysterical raisins, we show the parent + * pid, not the child pid. + */ + fprintf(F->out, "# filemon version 4\n"); + fprintf(F->out, "# Target pid %jd\n", (intmax_t)getpid()); + fprintf(F->out, "V 4\n"); + + /* Success! */ + return 0; +} + +/* + * filemon_setpid_parent(F, pid) + * + * Set the traced pid, from the parent. Never fails. + */ +void +filemon_setpid_parent(struct filemon *F, pid_t pid) +{ + + F->child = pid; +} + +/* + * filemon_setpid_child(F, pid) + * + * Set the traced pid, from the child. Returns 0 on success; sets + * errno and returns -1 on failure. + */ +int +filemon_setpid_child(const struct filemon *F, pid_t pid) +{ + int ops, trpoints; + + ops = KTROP_SET|KTRFLAG_DESCEND; + trpoints = KTRFACv2; + trpoints |= KTRFAC_SYSCALL|KTRFAC_NAMEI|KTRFAC_SYSRET; + trpoints |= KTRFAC_INHERIT; + if (fktrace(F->ktrfd, ops, trpoints, pid) == -1) + return -1; + + return 0; +} + +/* + * filemon_close(F) + * + * Close F for output if necessary, and free a filemon descriptor. + * Returns 0 on success; sets errno and returns -1 on failure, but + * frees the filemon descriptor either way; + */ +int +filemon_close(struct filemon *F) +{ + struct filemon_state *S; + int error = 0; + + /* Close for output. */ + if (filemon_closefd(F) == -1 && error == 0) + error = errno; + + /* Close the ktrace pipe. */ + if (fclose(F->in) == EOF && error == 0) + error = errno; + if (close(F->ktrfd) == -1 && error == 0) + error = errno; + + /* Free any active records. */ + while ((S = RB_TREE_MIN(&F->active)) != NULL) { + rb_tree_remove_node(&F->active, S); + free(S); + } + + /* Free the filemon descriptor. */ + free(F); + + /* Set errno and return -1 if anything went wrong. */ + if (error) { + errno = error; + return -1; + } + + /* Success! */ + return 0; +} + +/* + * filemon_readfd(F) + * + * Returns a file descriptor which will select/poll ready for read + * when there are filemon events to be processed by + * filemon_process, or -1 if anything has gone wrong. + */ +int +filemon_readfd(const struct filemon *F) +{ + + if (F->state == FILEMON_ERROR) + return -1; + return fileno(F->in); +} + +/* + * filemon_dispatch(F) + * + * Internal subroutine to dispatch a filemon ktrace event. + * Silently ignore events that we don't recognize. + */ +static void +filemon_dispatch(struct filemon *F) +{ + const struct filemon_key key = { + .pid = F->hdr.ktr_pid, + .lid = F->hdr.ktr_lid, + }; + struct filemon_state *S; + + switch (F->hdr.ktr_type) { + case KTR_SYSCALL: { + struct ktr_syscall *call = &F->payload.syscall; + struct filemon_state *S1; + + /* Validate the syscall code. */ + if (call->ktr_code < 0 || + (size_t)call->ktr_code >= __arraycount(filemon_syscalls) || + filemon_syscalls[call->ktr_code] == NULL) + break; + + /* + * Invoke the syscall-specific logic to create a new + * active state. + */ + S = (*filemon_syscalls[call->ktr_code])(F, &key, call); + if (S == NULL) + break; + + /* + * Insert the active state, or ignore it if there + * already is one. + * + * Collisions shouldn't happen because the states are + * keyed by , in which syscalls should happen + * sequentially in CALL/RET pairs, but let's be + * defensive. + */ + S1 = rb_tree_insert_node(&F->active, S); + if (S1 != S) { + /* XXX Which one to drop? */ + free(S); + break; + } + break; + } + case KTR_NAMEI: + /* Find an active syscall state, or drop it. */ + S = rb_tree_find_node(&F->active, &key); + if (S == NULL) + break; + /* Find the position of the next path, or drop it. */ + if (S->i >= S->npath) + break; + /* Record the path. */ + S->path[S->i++] = strndup(F->payload.namei, + sizeof F->payload.namei); + break; + case KTR_SYSRET: { + struct ktr_sysret *ret = &F->payload.sysret; + unsigned i; + + /* Find and remove an active syscall state, or drop it. */ + S = rb_tree_find_node(&F->active, &key); + if (S == NULL) + break; + rb_tree_remove_node(&F->active, S); + + /* + * If the active syscall state matches this return, + * invoke the syscall-specific logic to show a filemon + * event. + */ + /* XXX What to do if syscall code doesn't match? */ + if (S->i == S->npath && S->syscode == ret->ktr_code) + (*S->show)(F, S, ret); + + /* Free the state now that it is no longer active. */ + for (i = 0; i < S->i; i++) + free(S->path[i]); + free(S); + break; + } + default: + /* Ignore all other ktrace events. */ + break; + } +} + +/* + * filemon_process(F) + * + * Process all pending events after filemon_readfd(F) has + * selected/polled ready for read. + * + * Returns -1 on failure, 0 on end of events, and anything else if + * there may be more events. + * + * XXX What about fairness to other activities in the event loop? + * If we stop while there's events buffered in F->in, then select + * or poll may not return ready even though there's work queued up + * in the buffer of F->in, but if we don't stop then ktrace events + * may overwhelm all other activity in the event loop. + */ +int +filemon_process(struct filemon *F) +{ + size_t nread; + +top: /* If the child has exited, nothing to do. */ + /* XXX What if one thread calls exit while another is running? */ + if (F->child == 0) + return 0; + + /* If we're waiting for input, read some. */ + if (F->resid) { + nread = fread(F->p, 1, F->resid, F->in); + if (nread == 0) { + if (feof(F->in)) + return 0; + assert(ferror(F->in)); + /* + * If interrupted or would block, there may be + * more events. Otherwise fail. + */ + if (errno == EAGAIN || errno == EINTR) + return 1; + F->state = FILEMON_ERROR; + F->p = NULL; + F->resid = 0; + return -1; + } + assert(nread <= F->resid); + F->p += nread; + F->resid -= nread; + if (F->resid) /* may be more events */ + return 1; + } + + /* Process a state transition now that we've read a buffer. */ + switch (F->state) { + case FILEMON_START: /* just started filemon; read header next */ + F->state = FILEMON_HEADER; + F->p = (void *)&F->hdr; + F->resid = sizeof F->hdr; + goto top; + case FILEMON_HEADER: /* read header */ + /* Sanity-check ktrace header; then read payload. */ + if (F->hdr.ktr_len < 0 || + (size_t)F->hdr.ktr_len > sizeof F->payload) { + F->state = FILEMON_ERROR; + F->p = NULL; + F->resid = 0; + errno = EIO; + return -1; + } + F->state = FILEMON_PAYLOAD; + F->p = (void *)&F->payload; + F->resid = (size_t)F->hdr.ktr_len; + goto top; + case FILEMON_PAYLOAD: /* read header and payload */ + /* Dispatch ktrace event; then read next header. */ + filemon_dispatch(F); + F->state = FILEMON_HEADER; + F->p = (void *)&F->hdr; + F->resid = sizeof F->hdr; + goto top; + default: /* paranoia */ + F->state = FILEMON_ERROR; + /*FALLTHROUGH*/ + case FILEMON_ERROR: /* persistent error indicator */ + F->p = NULL; + F->resid = 0; + errno = EIO; + return -1; + } +} + +static struct filemon_state * +syscall_enter(struct filemon *F, + const struct filemon_key *key, const struct ktr_syscall *call, + unsigned npath, + void (*show)(struct filemon *, const struct filemon_state *, + const struct ktr_sysret *)) +{ + struct filemon_state *S; + unsigned i; + + S = calloc(1, offsetof(struct filemon_state, path[npath])); + if (S == NULL) + return NULL; + S->key = *key; + S->show = show; + S->syscode = call->ktr_code; + S->i = 0; + S->npath = npath; + for (i = 0; i < npath; i++) + S->path[i] = NULL; /* paranoia */ + + return S; +} + +static void +show_paths(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret, const char *prefix) +{ + unsigned i; + + /* Caller must ensure all paths have been specified. */ + assert(S->i == S->npath); + + /* + * Ignore it if it failed or yielded EJUSTRETURN (-2), or if + * we're not producing output. + */ + if (ret->ktr_error && ret->ktr_error != -2) + return; + if (F->out == NULL) + return; + + /* + * Print the prefix, pid, and paths -- with the paths quoted if + * there's more than one. + */ + fprintf(F->out, "%s %jd", prefix, (intmax_t)S->key.pid); + for (i = 0; i < S->npath; i++) { + const char *q = S->npath > 1 ? "'" : ""; + fprintf(F->out, " %s%s%s", q, S->path[i], q); + } + fprintf(F->out, "\n"); +} + +static void +show_retval(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret, const char *prefix) +{ + + /* + * Ignore it if it failed or yielded EJUSTRETURN (-2), or if + * we're not producing output. + */ + if (ret->ktr_error && ret->ktr_error != -2) + return; + if (F->out == NULL) + return; + + fprintf(F->out, "%s %jd %jd\n", prefix, (intmax_t)S->key.pid, + (intmax_t)ret->ktr_retval); +} + +static void +show_chdir(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "C"); +} + +static void +show_execve(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + return show_paths(F, S, ret, "E"); +} + +static void +show_fork(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_retval(F, S, ret, "F"); +} + +static void +show_link(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "L"); /* XXX same as symlink */ +} + +static void +show_open_read(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "R"); +} + +static void +show_open_write(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "W"); +} + +static void +show_open_readwrite(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "R"); + show_paths(F, S, ret, "W"); +} + +static void +show_openat_read(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + if (S->path[0][0] != '/') + show_paths(F, S, ret, "A"); + show_paths(F, S, ret, "R"); +} + +static void +show_openat_write(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + if (S->path[0][0] != '/') + show_paths(F, S, ret, "A"); + show_paths(F, S, ret, "W"); +} + +static void +show_openat_readwrite(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + if (S->path[0][0] != '/') + show_paths(F, S, ret, "A"); + show_paths(F, S, ret, "R"); + show_paths(F, S, ret, "W"); +} + +static void +show_symlink(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "L"); /* XXX same as link */ +} + +static void +show_unlink(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "D"); +} + +static void +show_rename(struct filemon *F, const struct filemon_state *S, + const struct ktr_sysret *ret) +{ + show_paths(F, S, ret, "M"); +} + +static struct filemon_state * +filemon_sys_chdir(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + return syscall_enter(F, key, call, 1, &show_chdir); +} + +static struct filemon_state * +filemon_sys_execve(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + return syscall_enter(F, key, call, 1, &show_execve); +} + +static struct filemon_state * +filemon_sys_exit(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + const register_t *args = (const void *)&call[1]; + int status = args[0]; + + if (F->out) { + fprintf(F->out, "X %jd %d\n", (intmax_t)key->pid, status); + if (key->pid == F->child) { + fprintf(F->out, "# Bye bye\n"); + F->child = 0; + } + } + return NULL; +} + +static struct filemon_state * +filemon_sys_fork(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + return syscall_enter(F, key, call, 0, &show_fork); +} + +static struct filemon_state * +filemon_sys_link(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + return syscall_enter(F, key, call, 2, &show_link); +} + +static struct filemon_state * +filemon_sys_open(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + const register_t *args = (const void *)&call[1]; + int flags; + + if (call->ktr_argsize < 2) + return NULL; + flags = args[1]; + + if ((flags & O_RDWR) == O_RDWR) + return syscall_enter(F, key, call, 1, &show_open_readwrite); + else if ((flags & O_WRONLY) == O_WRONLY) + return syscall_enter(F, key, call, 1, &show_open_write); + else if ((flags & O_RDONLY) == O_RDONLY) + return syscall_enter(F, key, call, 1, &show_open_read); + else + return NULL; /* XXX Do we care if no read or write? */ +} + +static struct filemon_state * +filemon_sys_openat(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + const register_t *args = (const void *)&call[1]; + int flags, fd; + + if (call->ktr_argsize < 3) + return NULL; + fd = args[0]; + flags = args[2]; + + if (fd == AT_CWD) { + if ((flags & O_RDWR) == O_RDWR) + return syscall_enter(F, key, call, 1, + &show_open_readwrite); + else if ((flags & O_WRONLY) == O_WRONLY) + return syscall_enter(F, key, call, 1, + &show_open_write); + else if ((flags & O_RDONLY) == O_RDONLY) + return syscall_enter(F, key, call, 1, &show_open_read); + else + return NULL; + } else { + if ((flags & O_RDWR) == O_RDWR) + return syscall_enter(F, key, call, 1, + &show_openat_readwrite); + else if ((flags & O_WRONLY) == O_WRONLY) + return syscall_enter(F, key, call, 1, + &show_openat_write); + else if ((flags & O_RDONLY) == O_RDONLY) + return syscall_enter(F, key, call, 1, + &show_openat_read); + else + return NULL; + } +} + +static struct filemon_state * +filemon_sys_symlink(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + return syscall_enter(F, key, call, 2, &show_symlink); +} + +static struct filemon_state * +filemon_sys_unlink(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + return syscall_enter(F, key, call, 1, &show_unlink); +} + +static struct filemon_state * +filemon_sys_rename(struct filemon *F, const struct filemon_key *key, + const struct ktr_syscall *call) +{ + return syscall_enter(F, key, call, 2, &show_rename); +} Property changes on: stable/12/contrib/bmake/filemon/filemon_ktrace.c ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/job.c =================================================================== --- stable/12/contrib/bmake/job.c (revision 361673) +++ stable/12/contrib/bmake/job.c (revision 361674) @@ -1,3118 +1,3176 @@ -/* $NetBSD: job.c,v 1.195 2018/05/13 22:13:28 sjg Exp $ */ +/* $NetBSD: job.c,v 1.197 2020/02/06 01:13:19 sjg Exp $ */ /* * Copyright (c) 1988, 1989, 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 1988, 1989 by Adam de Boor * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MAKE_NATIVE -static char rcsid[] = "$NetBSD: job.c,v 1.195 2018/05/13 22:13:28 sjg Exp $"; +static char rcsid[] = "$NetBSD: job.c,v 1.197 2020/02/06 01:13:19 sjg Exp $"; #else #include #ifndef lint #if 0 static char sccsid[] = "@(#)job.c 8.2 (Berkeley) 3/19/94"; #else -__RCSID("$NetBSD: job.c,v 1.195 2018/05/13 22:13:28 sjg Exp $"); +__RCSID("$NetBSD: job.c,v 1.197 2020/02/06 01:13:19 sjg Exp $"); #endif #endif /* not lint */ #endif /*- * job.c -- * handle the creation etc. of our child processes. * * Interface: * Job_Make Start the creation of the given target. * * Job_CatchChildren Check for and handle the termination of any * children. This must be called reasonably * frequently to keep the whole make going at * a decent clip, since job table entries aren't * removed until their process is caught this way. * * Job_CatchOutput Print any output our children have produced. * Should also be called fairly frequently to * keep the user informed of what's going on. * If no output is waiting, it will block for * a time given by the SEL_* constants, below, * or until output is ready. * * Job_Init Called to initialize this module. in addition, * any commands attached to the .BEGIN target * are executed before this function returns. * Hence, the makefile must have been parsed * before this function is called. * * Job_End Cleanup any memory used. * * Job_ParseShell Given the line following a .SHELL target, parse * the line as a shell specification. Returns * FAILURE if the spec was incorrect. * * Job_Finish Perform any final processing which needs doing. * This includes the execution of any commands * which have been/were attached to the .END * target. It should only be called when the * job table is empty. * * Job_AbortAll Abort all currently running jobs. It doesn't * handle output or do anything for the jobs, * just kills them. It should only be called in * an emergency, as it were. * * Job_CheckCommands Verify that the commands for a target are * ok. Provide them if necessary and possible. * * Job_Touch Update a target without really updating it. * * Job_Wait Wait for all currently-running jobs to finish. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include #include #include #include #include "wait.h" #include #include #if !defined(USE_SELECT) && defined(HAVE_POLL_H) #include #else #ifndef USE_SELECT /* no poll.h */ # define USE_SELECT #endif #if defined(HAVE_SYS_SELECT_H) # include #endif #endif #include #include #include #include #if defined(HAVE_SYS_SOCKET_H) # include #endif #include "make.h" #include "hash.h" #include "dir.h" #include "job.h" #include "pathnames.h" #include "trace.h" # define STATIC static /* * FreeBSD: traditionally .MAKE is not required to * pass jobs queue to sub-makes. * Use .MAKE.ALWAYS_PASS_JOB_QUEUE=no to disable. */ #define MAKE_ALWAYS_PASS_JOB_QUEUE ".MAKE.ALWAYS_PASS_JOB_QUEUE" static int Always_pass_job_queue = TRUE; /* * FreeBSD: aborting entire parallel make isn't always * desired. When doing tinderbox for example, failure of * one architecture should not stop all. * We still want to bail on interrupt though. */ #define MAKE_JOB_ERROR_TOKEN "MAKE_JOB_ERROR_TOKEN" static int Job_error_token = TRUE; /* * error handling variables */ static int errors = 0; /* number of errors reported */ static int aborting = 0; /* why is the make aborting? */ #define ABORT_ERROR 1 /* Because of an error */ #define ABORT_INTERRUPT 2 /* Because it was interrupted */ #define ABORT_WAIT 3 /* Waiting for jobs to finish */ #define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */ /* * this tracks the number of tokens currently "out" to build jobs. */ int jobTokensRunning = 0; int not_parallel = 0; /* set if .NOT_PARALLEL */ /* * XXX: Avoid SunOS bug... FILENO() is fp->_file, and file * is a char! So when we go above 127 we turn negative! */ #define FILENO(a) ((unsigned) fileno(a)) /* * post-make command processing. The node postCommands is really just the * .END target but we keep it around to avoid having to search for it * all the time. */ static GNode *postCommands = NULL; /* node containing commands to execute when * everything else is done */ static int numCommands; /* The number of commands actually printed * for a target. Should this number be * 0, no shell will be executed. */ /* * Return values from JobStart. */ #define JOB_RUNNING 0 /* Job is running */ #define JOB_ERROR 1 /* Error in starting the job */ #define JOB_FINISHED 2 /* The job is already finished */ /* * Descriptions for various shells. * * The build environment may set DEFSHELL_INDEX to one of * DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to * select one of the prefedined shells as the default shell. * * Alternatively, the build environment may set DEFSHELL_CUSTOM to the * name or the full path of a sh-compatible shell, which will be used as * the default shell. * * ".SHELL" lines in Makefiles can choose the default shell from the # set defined here, or add additional shells. */ #ifdef DEFSHELL_CUSTOM #define DEFSHELL_INDEX_CUSTOM 0 #define DEFSHELL_INDEX_SH 1 #define DEFSHELL_INDEX_KSH 2 #define DEFSHELL_INDEX_CSH 3 #else /* !DEFSHELL_CUSTOM */ #define DEFSHELL_INDEX_SH 0 #define DEFSHELL_INDEX_KSH 1 #define DEFSHELL_INDEX_CSH 2 #endif /* !DEFSHELL_CUSTOM */ #ifndef DEFSHELL_INDEX #define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */ #endif /* !DEFSHELL_INDEX */ static Shell shells[] = { #ifdef DEFSHELL_CUSTOM /* * An sh-compatible shell with a non-standard name. * * Keep this in sync with the "sh" description below, but avoid * non-portable features that might not be supplied by all * sh-compatible shells. */ { DEFSHELL_CUSTOM, FALSE, "", "", "", 0, FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#', "", "", }, #endif /* DEFSHELL_CUSTOM */ /* * SH description. Echo control is also possible and, under * sun UNIX anyway, one can even control error checking. */ { "sh", FALSE, "", "", "", 0, FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#', #if defined(MAKE_NATIVE) && defined(__NetBSD__) "q", #else "", #endif "", }, /* * KSH description. */ { "ksh", TRUE, "set +v", "set -v", "set +v", 6, FALSE, "echo \"%s\"\n", "%s\n", "{ %s \n} || exit $?\n", "'\n'", '#', "v", "", }, /* * CSH description. The csh can do echo control by playing * with the setting of the 'echo' shell variable. Sadly, * however, it is unable to do error control nicely. */ { "csh", TRUE, "unset verbose", "set verbose", "unset verbose", 10, FALSE, "echo \"%s\"\n", "csh -c \"%s || exit 0\"\n", "", "'\\\n'", '#', "v", "e", }, /* * UNKNOWN. */ { NULL, FALSE, NULL, NULL, NULL, 0, FALSE, NULL, NULL, NULL, NULL, 0, NULL, NULL, } }; static Shell *commandShell = &shells[DEFSHELL_INDEX]; /* this is the shell to * which we pass all * commands in the Makefile. * It is set by the * Job_ParseShell function */ const char *shellPath = NULL, /* full pathname of * executable image */ *shellName = NULL; /* last component of shell */ char *shellErrFlag = NULL; static const char *shellArgv = NULL; /* Custom shell args */ STATIC Job *job_table; /* The structures that describe them */ STATIC Job *job_table_end; /* job_table + maxJobs */ static int wantToken; /* we want a token */ static int lurking_children = 0; static int make_suspended = 0; /* non-zero if we've seen a SIGTSTP (etc) */ /* * Set of descriptors of pipes connected to * the output channels of children */ static struct pollfd *fds = NULL; static Job **jobfds = NULL; static int nfds = 0; static void watchfd(Job *); static void clearfd(Job *); static int readyfd(Job *); STATIC GNode *lastNode; /* The node for which output was most recently * produced. */ static char *targPrefix = NULL; /* What we print at the start of TARG_FMT */ static Job tokenWaitJob; /* token wait pseudo-job */ static Job childExitJob; /* child exit pseudo-job */ #define CHILD_EXIT "." #define DO_JOB_RESUME "R" +static const int npseudojobs = 2; /* number of pseudo-jobs */ + #define TARG_FMT "%s %s ---\n" /* Default format */ #define MESSAGE(fp, gn) \ if (maxJobs != 1 && targPrefix && *targPrefix) \ (void)fprintf(fp, TARG_FMT, targPrefix, gn->name) static sigset_t caught_signals; /* Set of signals we handle */ static void JobChildSig(int); static void JobContinueSig(int); static Job *JobFindPid(int, int, Boolean); static int JobPrintCommand(void *, void *); static int JobSaveCommand(void *, void *); static void JobClose(Job *); static void JobExec(Job *, char **); static void JobMakeArgv(Job *, char **); static int JobStart(GNode *, int); static char *JobOutput(Job *, char *, char *, int); static void JobDoOutput(Job *, Boolean); static Shell *JobMatchShell(const char *); static void JobInterrupt(int, int) MAKE_ATTR_DEAD; static void JobRestartJobs(void); static void JobTokenAdd(void); static void JobSigLock(sigset_t *); static void JobSigUnlock(sigset_t *); static void JobSigReset(void); #if !defined(MALLOC_OPTIONS) # define MALLOC_OPTIONS "A" #endif const char *malloc_options= MALLOC_OPTIONS; +static unsigned +nfds_per_job(void) +{ +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + if (useMeta) + return 2; +#endif + return 1; +} + static void job_table_dump(const char *where) { Job *job; fprintf(debug_file, "job table @ %s\n", where); for (job = job_table; job < job_table_end; job++) { fprintf(debug_file, "job %d, status %d, flags %d, pid %d\n", (int)(job - job_table), job->job_state, job->flags, job->pid); } } /* * Delete the target of a failed, interrupted, or otherwise * unsuccessful job unless inhibited by .PRECIOUS. */ static void JobDeleteTarget(GNode *gn) { if ((gn->type & (OP_JOIN|OP_PHONY)) == 0 && !Targ_Precious(gn)) { char *file = (gn->path == NULL ? gn->name : gn->path); if (!noExecute && eunlink(file) != -1) { Error("*** %s removed", file); } } } /* * JobSigLock/JobSigUnlock * * Signal lock routines to get exclusive access. Currently used to * protect `jobs' and `stoppedJobs' list manipulations. */ static void JobSigLock(sigset_t *omaskp) { if (sigprocmask(SIG_BLOCK, &caught_signals, omaskp) != 0) { Punt("JobSigLock: sigprocmask: %s", strerror(errno)); sigemptyset(omaskp); } } static void JobSigUnlock(sigset_t *omaskp) { (void)sigprocmask(SIG_SETMASK, omaskp, NULL); } static void JobCreatePipe(Job *job, int minfd) { int i, fd, flags; if (pipe(job->jobPipe) == -1) Punt("Cannot create pipe: %s", strerror(errno)); for (i = 0; i < 2; i++) { /* Avoid using low numbered fds */ fd = fcntl(job->jobPipe[i], F_DUPFD, minfd); if (fd != -1) { close(job->jobPipe[i]); job->jobPipe[i] = fd; } } /* Set close-on-exec flag for both */ if (fcntl(job->jobPipe[0], F_SETFD, FD_CLOEXEC) == -1) Punt("Cannot set close-on-exec: %s", strerror(errno)); if (fcntl(job->jobPipe[1], F_SETFD, FD_CLOEXEC) == -1) Punt("Cannot set close-on-exec: %s", strerror(errno)); /* * We mark the input side of the pipe non-blocking; we poll(2) the * pipe when we're waiting for a job token, but we might lose the * race for the token when a new one becomes available, so the read * from the pipe should not block. */ flags = fcntl(job->jobPipe[0], F_GETFL, 0); if (flags == -1) Punt("Cannot get flags: %s", strerror(errno)); flags |= O_NONBLOCK; if (fcntl(job->jobPipe[0], F_SETFL, flags) == -1) Punt("Cannot set flags: %s", strerror(errno)); } /*- *----------------------------------------------------------------------- * JobCondPassSig -- * Pass a signal to a job * * Input: * signop Signal to send it * * Side Effects: * None, except the job may bite it. * *----------------------------------------------------------------------- */ static void JobCondPassSig(int signo) { Job *job; if (DEBUG(JOB)) { (void)fprintf(debug_file, "JobCondPassSig(%d) called.\n", signo); } for (job = job_table; job < job_table_end; job++) { if (job->job_state != JOB_ST_RUNNING) continue; if (DEBUG(JOB)) { (void)fprintf(debug_file, "JobCondPassSig passing signal %d to child %d.\n", signo, job->pid); } KILLPG(job->pid, signo); } } /*- *----------------------------------------------------------------------- * JobChldSig -- * SIGCHLD handler. * * Input: * signo The signal number we've received * * Results: * None. * * Side Effects: * Sends a token on the child exit pipe to wake us up from * select()/poll(). * *----------------------------------------------------------------------- */ static void JobChildSig(int signo MAKE_ATTR_UNUSED) { while (write(childExitJob.outPipe, CHILD_EXIT, 1) == -1 && errno == EAGAIN) continue; } /*- *----------------------------------------------------------------------- * JobContinueSig -- * Resume all stopped jobs. * * Input: * signo The signal number we've received * * Results: * None. * * Side Effects: * Jobs start running again. * *----------------------------------------------------------------------- */ static void JobContinueSig(int signo MAKE_ATTR_UNUSED) { /* * Defer sending to SIGCONT to our stopped children until we return * from the signal handler. */ while (write(childExitJob.outPipe, DO_JOB_RESUME, 1) == -1 && errno == EAGAIN) continue; } /*- *----------------------------------------------------------------------- * JobPassSig -- * Pass a signal on to all jobs, then resend to ourselves. * * Input: * signo The signal number we've received * * Results: * None. * * Side Effects: * We die by the same signal. * *----------------------------------------------------------------------- */ MAKE_ATTR_DEAD static void JobPassSig_int(int signo) { /* Run .INTERRUPT target then exit */ JobInterrupt(TRUE, signo); } MAKE_ATTR_DEAD static void JobPassSig_term(int signo) { /* Dont run .INTERRUPT target then exit */ JobInterrupt(FALSE, signo); } static void JobPassSig_suspend(int signo) { sigset_t nmask, omask; struct sigaction act; /* Suppress job started/continued messages */ make_suspended = 1; /* Pass the signal onto every job */ JobCondPassSig(signo); /* * Send ourselves the signal now we've given the message to everyone else. * Note we block everything else possible while we're getting the signal. * This ensures that all our jobs get continued when we wake up before * we take any other signal. */ sigfillset(&nmask); sigdelset(&nmask, signo); (void)sigprocmask(SIG_SETMASK, &nmask, &omask); act.sa_handler = SIG_DFL; sigemptyset(&act.sa_mask); act.sa_flags = 0; (void)sigaction(signo, &act, NULL); if (DEBUG(JOB)) { (void)fprintf(debug_file, "JobPassSig passing signal %d to self.\n", signo); } (void)kill(getpid(), signo); /* * We've been continued. * * A whole host of signals continue to happen! * SIGCHLD for any processes that actually suspended themselves. * SIGCHLD for any processes that exited while we were alseep. * The SIGCONT that actually caused us to wakeup. * * Since we defer passing the SIGCONT on to our children until * the main processing loop, we can be sure that all the SIGCHLD * events will have happened by then - and that the waitpid() will * collect the child 'suspended' events. * For correct sequencing we just need to ensure we process the * waitpid() before passign on the SIGCONT. * * In any case nothing else is needed here. */ /* Restore handler and signal mask */ act.sa_handler = JobPassSig_suspend; (void)sigaction(signo, &act, NULL); (void)sigprocmask(SIG_SETMASK, &omask, NULL); } /*- *----------------------------------------------------------------------- * JobFindPid -- * Compare the pid of the job with the given pid and return 0 if they * are equal. This function is called from Job_CatchChildren * to find the job descriptor of the finished job. * * Input: * job job to examine * pid process id desired * * Results: * Job with matching pid * * Side Effects: * None *----------------------------------------------------------------------- */ static Job * JobFindPid(int pid, int status, Boolean isJobs) { Job *job; for (job = job_table; job < job_table_end; job++) { if ((job->job_state == status) && job->pid == pid) return job; } if (DEBUG(JOB) && isJobs) job_table_dump("no pid"); return NULL; } /*- *----------------------------------------------------------------------- * JobPrintCommand -- * Put out another command for the given job. If the command starts * with an @ or a - we process it specially. In the former case, * so long as the -s and -n flags weren't given to make, we stick * a shell-specific echoOff command in the script. In the latter, * we ignore errors for the entire job, unless the shell has error * control. * If the command is just "..." we take all future commands for this * job to be commands to be executed once the entire graph has been * made and return non-zero to signal that the end of the commands * was reached. These commands are later attached to the postCommands * node and executed by Job_End when all things are done. * This function is called from JobStart via Lst_ForEach. * * Input: * cmdp command string to print * jobp job for which to print it * * Results: * Always 0, unless the command was "..." * * Side Effects: * If the command begins with a '-' and the shell has no error control, * the JOB_IGNERR flag is set in the job descriptor. * If the command is "..." and we're not ignoring such things, * tailCmds is set to the successor node of the cmd. * numCommands is incremented if the command is actually printed. *----------------------------------------------------------------------- */ static int JobPrintCommand(void *cmdp, void *jobp) { Boolean noSpecials; /* true if we shouldn't worry about * inserting special commands into * the input stream. */ Boolean shutUp = FALSE; /* true if we put a no echo command * into the command file */ Boolean errOff = FALSE; /* true if we turned error checking * off before printing the command * and need to turn it back on */ const char *cmdTemplate; /* Template to use when printing the * command */ char *cmdStart; /* Start of expanded command */ char *escCmd = NULL; /* Command with quotes/backticks escaped */ char *cmd = (char *)cmdp; Job *job = (Job *)jobp; int i, j; noSpecials = NoExecute(job->node); if (strcmp(cmd, "...") == 0) { job->node->type |= OP_SAVE_CMDS; if ((job->flags & JOB_IGNDOTS) == 0) { job->tailCmds = Lst_Succ(Lst_Member(job->node->commands, cmd)); return 1; } return 0; } #define DBPRINTF(fmt, arg) if (DEBUG(JOB)) { \ (void)fprintf(debug_file, fmt, arg); \ } \ (void)fprintf(job->cmdFILE, fmt, arg); \ (void)fflush(job->cmdFILE); numCommands += 1; cmdStart = cmd = Var_Subst(NULL, cmd, job->node, VARF_WANTRES); cmdTemplate = "%s\n"; /* * Check for leading @' and -'s to control echoing and error checking. */ while (*cmd == '@' || *cmd == '-' || (*cmd == '+')) { switch (*cmd) { case '@': shutUp = DEBUG(LOUD) ? FALSE : TRUE; break; case '-': errOff = TRUE; break; case '+': if (noSpecials) { /* * We're not actually executing anything... * but this one needs to be - use compat mode just for it. */ CompatRunCommand(cmdp, job->node); free(cmdStart); return 0; } break; } cmd++; } while (isspace((unsigned char) *cmd)) cmd++; /* * If the shell doesn't have error control the alternate echo'ing will * be done (to avoid showing additional error checking code) * and this will need the characters '$ ` \ "' escaped */ if (!commandShell->hasErrCtl) { /* Worst that could happen is every char needs escaping. */ escCmd = bmake_malloc((strlen(cmd) * 2) + 1); for (i = 0, j= 0; cmd[i] != '\0'; i++, j++) { if (cmd[i] == '$' || cmd[i] == '`' || cmd[i] == '\\' || cmd[i] == '"') escCmd[j++] = '\\'; escCmd[j] = cmd[i]; } escCmd[j] = 0; } if (shutUp) { if (!(job->flags & JOB_SILENT) && !noSpecials && commandShell->hasEchoCtl) { DBPRINTF("%s\n", commandShell->echoOff); } else { if (commandShell->hasErrCtl) shutUp = FALSE; } } if (errOff) { if (!noSpecials) { if (commandShell->hasErrCtl) { /* * we don't want the error-control commands showing * up either, so we turn off echoing while executing * them. We could put another field in the shell * structure to tell JobDoOutput to look for this * string too, but why make it any more complex than * it already is? */ if (!(job->flags & JOB_SILENT) && !shutUp && commandShell->hasEchoCtl) { DBPRINTF("%s\n", commandShell->echoOff); DBPRINTF("%s\n", commandShell->ignErr); DBPRINTF("%s\n", commandShell->echoOn); } else { DBPRINTF("%s\n", commandShell->ignErr); } } else if (commandShell->ignErr && (*commandShell->ignErr != '\0')) { /* * The shell has no error control, so we need to be * weird to get it to ignore any errors from the command. * If echoing is turned on, we turn it off and use the * errCheck template to echo the command. Leave echoing * off so the user doesn't see the weirdness we go through * to ignore errors. Set cmdTemplate to use the weirdness * instead of the simple "%s\n" template. */ job->flags |= JOB_IGNERR; if (!(job->flags & JOB_SILENT) && !shutUp) { if (commandShell->hasEchoCtl) { DBPRINTF("%s\n", commandShell->echoOff); } DBPRINTF(commandShell->errCheck, escCmd); shutUp = TRUE; } else { if (!shutUp) { DBPRINTF(commandShell->errCheck, escCmd); } } cmdTemplate = commandShell->ignErr; /* * The error ignoration (hee hee) is already taken care * of by the ignErr template, so pretend error checking * is still on. */ errOff = FALSE; } else { errOff = FALSE; } } else { errOff = FALSE; } } else { /* * If errors are being checked and the shell doesn't have error control * but does supply an errOut template, then setup commands to run * through it. */ if (!commandShell->hasErrCtl && commandShell->errOut && (*commandShell->errOut != '\0')) { if (!(job->flags & JOB_SILENT) && !shutUp) { if (commandShell->hasEchoCtl) { DBPRINTF("%s\n", commandShell->echoOff); } DBPRINTF(commandShell->errCheck, escCmd); shutUp = TRUE; } /* If it's a comment line or blank, treat as an ignored error */ if ((escCmd[0] == commandShell->commentChar) || (escCmd[0] == 0)) cmdTemplate = commandShell->ignErr; else cmdTemplate = commandShell->errOut; errOff = FALSE; } } if (DEBUG(SHELL) && strcmp(shellName, "sh") == 0 && (job->flags & JOB_TRACED) == 0) { DBPRINTF("set -%s\n", "x"); job->flags |= JOB_TRACED; } DBPRINTF(cmdTemplate, cmd); free(cmdStart); free(escCmd); if (errOff) { /* * If echoing is already off, there's no point in issuing the * echoOff command. Otherwise we issue it and pretend it was on * for the whole command... */ if (!shutUp && !(job->flags & JOB_SILENT) && commandShell->hasEchoCtl){ DBPRINTF("%s\n", commandShell->echoOff); shutUp = TRUE; } DBPRINTF("%s\n", commandShell->errCheck); } if (shutUp && commandShell->hasEchoCtl) { DBPRINTF("%s\n", commandShell->echoOn); } return 0; } /*- *----------------------------------------------------------------------- * JobSaveCommand -- * Save a command to be executed when everything else is done. * Callback function for JobFinish... * * Results: * Always returns 0 * * Side Effects: * The command is tacked onto the end of postCommands's commands list. * *----------------------------------------------------------------------- */ static int JobSaveCommand(void *cmd, void *gn) { cmd = Var_Subst(NULL, (char *)cmd, (GNode *)gn, VARF_WANTRES); (void)Lst_AtEnd(postCommands->commands, cmd); return(0); } /*- *----------------------------------------------------------------------- * JobClose -- * Called to close both input and output pipes when a job is finished. * * Results: * Nada * * Side Effects: * The file descriptors associated with the job are closed. * *----------------------------------------------------------------------- */ static void JobClose(Job *job) { clearfd(job); (void)close(job->outPipe); job->outPipe = -1; JobDoOutput(job, TRUE); (void)close(job->inPipe); job->inPipe = -1; } /*- *----------------------------------------------------------------------- * JobFinish -- * Do final processing for the given job including updating * parents and starting new jobs as available/necessary. Note * that we pay no attention to the JOB_IGNERR flag here. * This is because when we're called because of a noexecute flag * or something, jstat.w_status is 0 and when called from * Job_CatchChildren, the status is zeroed if it s/b ignored. * * Input: * job job to finish * status sub-why job went away * * Results: * None * * Side Effects: * Final commands for the job are placed on postCommands. * * If we got an error and are aborting (aborting == ABORT_ERROR) and * the job list is now empty, we are done for the day. * If we recognized an error (errors !=0), we set the aborting flag * to ABORT_ERROR so no more jobs will be started. *----------------------------------------------------------------------- */ /*ARGSUSED*/ static void JobFinish (Job *job, WAIT_T status) { Boolean done, return_job_token; if (DEBUG(JOB)) { fprintf(debug_file, "Jobfinish: %d [%s], status %d\n", job->pid, job->node->name, status); } if ((WIFEXITED(status) && (((WEXITSTATUS(status) != 0) && !(job->flags & JOB_IGNERR)))) || WIFSIGNALED(status)) { /* * If it exited non-zero and either we're doing things our * way or we're not ignoring errors, the job is finished. * Similarly, if the shell died because of a signal * the job is also finished. In these * cases, finish out the job's output before printing the exit * status... */ JobClose(job); if (job->cmdFILE != NULL && job->cmdFILE != stdout) { (void)fclose(job->cmdFILE); job->cmdFILE = NULL; } done = TRUE; } else if (WIFEXITED(status)) { /* * Deal with ignored errors in -B mode. We need to print a message * telling of the ignored error as well as setting status.w_status * to 0 so the next command gets run. To do this, we set done to be * TRUE if in -B mode and the job exited non-zero. */ done = WEXITSTATUS(status) != 0; /* * Old comment said: "Note we don't * want to close down any of the streams until we know we're at the * end." * But we do. Otherwise when are we going to print the rest of the * stuff? */ JobClose(job); } else { /* * No need to close things down or anything. */ done = FALSE; } if (done) { if (WIFEXITED(status)) { if (DEBUG(JOB)) { (void)fprintf(debug_file, "Process %d [%s] exited.\n", job->pid, job->node->name); } if (WEXITSTATUS(status) != 0) { if (job->node != lastNode) { MESSAGE(stdout, job->node); lastNode = job->node; } #ifdef USE_META if (useMeta) { meta_job_error(job, job->node, job->flags, WEXITSTATUS(status)); } #endif (void)printf("*** [%s] Error code %d%s\n", job->node->name, WEXITSTATUS(status), (job->flags & JOB_IGNERR) ? " (ignored)" : ""); if (job->flags & JOB_IGNERR) { WAIT_STATUS(status) = 0; } else { if (deleteOnError) { JobDeleteTarget(job->node); } PrintOnError(job->node, NULL); } } else if (DEBUG(JOB)) { if (job->node != lastNode) { MESSAGE(stdout, job->node); lastNode = job->node; } (void)printf("*** [%s] Completed successfully\n", job->node->name); } } else { if (job->node != lastNode) { MESSAGE(stdout, job->node); lastNode = job->node; } (void)printf("*** [%s] Signal %d\n", job->node->name, WTERMSIG(status)); if (deleteOnError) { JobDeleteTarget(job->node); } } (void)fflush(stdout); } #ifdef USE_META if (useMeta) { int x; if ((x = meta_job_finish(job)) != 0 && status == 0) { status = x; } } #endif return_job_token = FALSE; Trace_Log(JOBEND, job); if (!(job->flags & JOB_SPECIAL)) { if ((WAIT_STATUS(status) != 0) || (aborting == ABORT_ERROR) || (aborting == ABORT_INTERRUPT)) return_job_token = TRUE; } if ((aborting != ABORT_ERROR) && (aborting != ABORT_INTERRUPT) && (WAIT_STATUS(status) == 0)) { /* * As long as we aren't aborting and the job didn't return a non-zero * status that we shouldn't ignore, we call Make_Update to update * the parents. In addition, any saved commands for the node are placed * on the .END target. */ if (job->tailCmds != NULL) { Lst_ForEachFrom(job->node->commands, job->tailCmds, JobSaveCommand, job->node); } job->node->made = MADE; if (!(job->flags & JOB_SPECIAL)) return_job_token = TRUE; Make_Update(job->node); job->job_state = JOB_ST_FREE; } else if (WAIT_STATUS(status)) { errors += 1; job->job_state = JOB_ST_FREE; } /* * Set aborting if any error. */ if (errors && !keepgoing && (aborting != ABORT_INTERRUPT)) { /* * If we found any errors in this batch of children and the -k flag * wasn't given, we set the aborting flag so no more jobs get * started. */ aborting = ABORT_ERROR; } if (return_job_token) Job_TokenReturn(); if (aborting == ABORT_ERROR && jobTokensRunning == 0) { /* * If we are aborting and the job table is now empty, we finish. */ Finish(errors); } } /*- *----------------------------------------------------------------------- * Job_Touch -- * Touch the given target. Called by JobStart when the -t flag was * given * * Input: * gn the node of the file to touch * silent TRUE if should not print message * * Results: * None * * Side Effects: * The data modification of the file is changed. In addition, if the * file did not exist, it is created. *----------------------------------------------------------------------- */ void Job_Touch(GNode *gn, Boolean silent) { int streamID; /* ID of stream opened to do the touch */ struct utimbuf times; /* Times for utime() call */ if (gn->type & (OP_JOIN|OP_USE|OP_USEBEFORE|OP_EXEC|OP_OPTIONAL| OP_SPECIAL|OP_PHONY)) { /* * .JOIN, .USE, .ZEROTIME and .OPTIONAL targets are "virtual" targets * and, as such, shouldn't really be created. */ return; } if (!silent || NoExecute(gn)) { (void)fprintf(stdout, "touch %s\n", gn->name); (void)fflush(stdout); } if (NoExecute(gn)) { return; } if (gn->type & OP_ARCHV) { Arch_Touch(gn); } else if (gn->type & OP_LIB) { Arch_TouchLib(gn); } else { char *file = gn->path ? gn->path : gn->name; times.actime = times.modtime = now; if (utime(file, ×) < 0){ streamID = open(file, O_RDWR | O_CREAT, 0666); if (streamID >= 0) { char c; /* * Read and write a byte to the file to change the * modification time, then close the file. */ if (read(streamID, &c, 1) == 1) { (void)lseek(streamID, (off_t)0, SEEK_SET); while (write(streamID, &c, 1) == -1 && errno == EAGAIN) continue; } (void)close(streamID); } else { (void)fprintf(stdout, "*** couldn't touch %s: %s", file, strerror(errno)); (void)fflush(stdout); } } } } /*- *----------------------------------------------------------------------- * Job_CheckCommands -- * Make sure the given node has all the commands it needs. * * Input: * gn The target whose commands need verifying * abortProc Function to abort with message * * Results: * TRUE if the commands list is/was ok. * * Side Effects: * The node will have commands from the .DEFAULT rule added to it * if it needs them. *----------------------------------------------------------------------- */ Boolean Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...)) { if (OP_NOP(gn->type) && Lst_IsEmpty(gn->commands) && ((gn->type & OP_LIB) == 0 || Lst_IsEmpty(gn->children))) { /* * No commands. Look for .DEFAULT rule from which we might infer * commands */ if ((DEFAULT != NULL) && !Lst_IsEmpty(DEFAULT->commands) && (gn->type & OP_SPECIAL) == 0) { char *p1; /* * Make only looks for a .DEFAULT if the node was never the * target of an operator, so that's what we do too. If * a .DEFAULT was given, we substitute its commands for gn's * commands and set the IMPSRC variable to be the target's name * The DEFAULT node acts like a transformation rule, in that * gn also inherits any attributes or sources attached to * .DEFAULT itself. */ Make_HandleUse(DEFAULT, gn); Var_Set(IMPSRC, Var_Value(TARGET, gn, &p1), gn, 0); free(p1); } else if (Dir_MTime(gn, 0) == 0 && (gn->type & OP_SPECIAL) == 0) { /* * The node wasn't the target of an operator we have no .DEFAULT * rule to go on and the target doesn't already exist. There's * nothing more we can do for this branch. If the -k flag wasn't * given, we stop in our tracks, otherwise we just don't update * this node's parents so they never get examined. */ static const char msg[] = ": don't know how to make"; if (gn->flags & FROM_DEPEND) { if (!Job_RunTarget(".STALE", gn->fname)) fprintf(stdout, "%s: %s, %d: ignoring stale %s for %s\n", progname, gn->fname, gn->lineno, makeDependfile, gn->name); return TRUE; } if (gn->type & OP_OPTIONAL) { (void)fprintf(stdout, "%s%s %s (ignored)\n", progname, msg, gn->name); (void)fflush(stdout); } else if (keepgoing) { (void)fprintf(stdout, "%s%s %s (continuing)\n", progname, msg, gn->name); (void)fflush(stdout); return FALSE; } else { (*abortProc)("%s%s %s. Stop", progname, msg, gn->name); return FALSE; } } } return TRUE; } /*- *----------------------------------------------------------------------- * JobExec -- * Execute the shell for the given job. Called from JobStart * * Input: * job Job to execute * * Results: * None. * * Side Effects: * A shell is executed, outputs is altered and the Job structure added * to the job table. * *----------------------------------------------------------------------- */ static void JobExec(Job *job, char **argv) { int cpid; /* ID of new child */ sigset_t mask; job->flags &= ~JOB_TRACED; if (DEBUG(JOB)) { int i; (void)fprintf(debug_file, "Running %s %sly\n", job->node->name, "local"); (void)fprintf(debug_file, "\tCommand: "); for (i = 0; argv[i] != NULL; i++) { (void)fprintf(debug_file, "%s ", argv[i]); } (void)fprintf(debug_file, "\n"); } /* * Some jobs produce no output and it's disconcerting to have * no feedback of their running (since they produce no output, the * banner with their name in it never appears). This is an attempt to * provide that feedback, even if nothing follows it. */ if ((lastNode != job->node) && !(job->flags & JOB_SILENT)) { MESSAGE(stdout, job->node); lastNode = job->node; } /* No interruptions until this job is on the `jobs' list */ JobSigLock(&mask); /* Pre-emptively mark job running, pid still zero though */ job->job_state = JOB_ST_RUNNING; cpid = vFork(); if (cpid == -1) Punt("Cannot vfork: %s", strerror(errno)); if (cpid == 0) { /* Child */ sigset_t tmask; #ifdef USE_META if (useMeta) { meta_job_child(job); } #endif /* * Reset all signal handlers; this is necessary because we also * need to unblock signals before we exec(2). */ JobSigReset(); /* Now unblock signals */ sigemptyset(&tmask); JobSigUnlock(&tmask); /* * Must duplicate the input stream down to the child's input and * reset it to the beginning (again). Since the stream was marked * close-on-exec, we must clear that bit in the new input. */ if (dup2(FILENO(job->cmdFILE), 0) == -1) { execError("dup2", "job->cmdFILE"); _exit(1); } if (fcntl(0, F_SETFD, 0) == -1) { execError("fcntl clear close-on-exec", "stdin"); _exit(1); } if (lseek(0, (off_t)0, SEEK_SET) == -1) { execError("lseek to 0", "stdin"); _exit(1); } if (Always_pass_job_queue || (job->node->type & (OP_MAKE | OP_SUBMAKE))) { /* * Pass job token pipe to submakes. */ if (fcntl(tokenWaitJob.inPipe, F_SETFD, 0) == -1) { execError("clear close-on-exec", "tokenWaitJob.inPipe"); _exit(1); } if (fcntl(tokenWaitJob.outPipe, F_SETFD, 0) == -1) { execError("clear close-on-exec", "tokenWaitJob.outPipe"); _exit(1); } } /* * Set up the child's output to be routed through the pipe * we've created for it. */ if (dup2(job->outPipe, 1) == -1) { execError("dup2", "job->outPipe"); _exit(1); } /* * The output channels are marked close on exec. This bit was * duplicated by the dup2(on some systems), so we have to clear * it before routing the shell's error output to the same place as * its standard output. */ if (fcntl(1, F_SETFD, 0) == -1) { execError("clear close-on-exec", "stdout"); _exit(1); } if (dup2(1, 2) == -1) { execError("dup2", "1, 2"); _exit(1); } /* * We want to switch the child into a different process family so * we can kill it and all its descendants in one fell swoop, * by killing its process family, but not commit suicide. */ #if defined(HAVE_SETPGID) (void)setpgid(0, getpid()); #else #if defined(HAVE_SETSID) /* XXX: dsl - I'm sure this should be setpgrp()... */ (void)setsid(); #else (void)setpgrp(0, getpid()); #endif #endif Var_ExportVars(); (void)execv(shellPath, argv); execError("exec", shellPath); _exit(1); } /* Parent, continuing after the child exec */ job->pid = cpid; Trace_Log(JOBSTART, job); +#ifdef USE_META + if (useMeta) { + meta_job_parent(job, cpid); + } +#endif + /* * Set the current position in the buffer to the beginning * and mark another stream to watch in the outputs mask */ job->curPos = 0; watchfd(job); if (job->cmdFILE != NULL && job->cmdFILE != stdout) { (void)fclose(job->cmdFILE); job->cmdFILE = NULL; } /* * Now the job is actually running, add it to the table. */ if (DEBUG(JOB)) { fprintf(debug_file, "JobExec(%s): pid %d added to jobs table\n", job->node->name, job->pid); job_table_dump("job started"); } JobSigUnlock(&mask); } /*- *----------------------------------------------------------------------- * JobMakeArgv -- * Create the argv needed to execute the shell for a given job. * * * Results: * * Side Effects: * *----------------------------------------------------------------------- */ static void JobMakeArgv(Job *job, char **argv) { int argc; static char args[10]; /* For merged arguments */ argv[0] = UNCONST(shellName); argc = 1; if ((commandShell->exit && (*commandShell->exit != '-')) || (commandShell->echo && (*commandShell->echo != '-'))) { /* * At least one of the flags doesn't have a minus before it, so * merge them together. Have to do this because the *(&(@*#*&#$# * Bourne shell thinks its second argument is a file to source. * Grrrr. Note the ten-character limitation on the combined arguments. */ (void)snprintf(args, sizeof(args), "-%s%s", ((job->flags & JOB_IGNERR) ? "" : (commandShell->exit ? commandShell->exit : "")), ((job->flags & JOB_SILENT) ? "" : (commandShell->echo ? commandShell->echo : ""))); if (args[1]) { argv[argc] = args; argc++; } } else { if (!(job->flags & JOB_IGNERR) && commandShell->exit) { argv[argc] = UNCONST(commandShell->exit); argc++; } if (!(job->flags & JOB_SILENT) && commandShell->echo) { argv[argc] = UNCONST(commandShell->echo); argc++; } } argv[argc] = NULL; } /*- *----------------------------------------------------------------------- * JobStart -- * Start a target-creation process going for the target described * by the graph node gn. * * Input: * gn target to create * flags flags for the job to override normal ones. * e.g. JOB_SPECIAL or JOB_IGNDOTS * previous The previous Job structure for this node, if any. * * Results: * JOB_ERROR if there was an error in the commands, JOB_FINISHED * if there isn't actually anything left to do for the job and * JOB_RUNNING if the job has been started. * * Side Effects: * A new Job node is created and added to the list of running * jobs. PMake is forked and a child shell created. * * NB: I'm fairly sure that this code is never called with JOB_SPECIAL set * JOB_IGNDOTS is never set (dsl) * Also the return value is ignored by everyone. *----------------------------------------------------------------------- */ static int JobStart(GNode *gn, int flags) { Job *job; /* new job descriptor */ char *argv[10]; /* Argument vector to shell */ Boolean cmdsOK; /* true if the nodes commands were all right */ Boolean noExec; /* Set true if we decide not to run the job */ int tfd; /* File descriptor to the temp file */ for (job = job_table; job < job_table_end; job++) { if (job->job_state == JOB_ST_FREE) break; } if (job >= job_table_end) Punt("JobStart no job slots vacant"); memset(job, 0, sizeof *job); job->job_state = JOB_ST_SETUP; if (gn->type & OP_SPECIAL) flags |= JOB_SPECIAL; job->node = gn; job->tailCmds = NULL; /* * Set the initial value of the flags for this job based on the global * ones and the node's attributes... Any flags supplied by the caller * are also added to the field. */ job->flags = 0; if (Targ_Ignore(gn)) { job->flags |= JOB_IGNERR; } if (Targ_Silent(gn)) { job->flags |= JOB_SILENT; } job->flags |= flags; /* * Check the commands now so any attributes from .DEFAULT have a chance * to migrate to the node */ cmdsOK = Job_CheckCommands(gn, Error); job->inPollfd = NULL; /* * If the -n flag wasn't given, we open up OUR (not the child's) * temporary file to stuff commands in it. The thing is rd/wr so we don't * need to reopen it to feed it to the shell. If the -n flag *was* given, * we just set the file to be stdout. Cute, huh? */ if (((gn->type & OP_MAKE) && !(noRecursiveExecute)) || (!noExecute && !touchFlag)) { /* * tfile is the name of a file into which all shell commands are * put. It is removed before the child shell is executed, unless * DEBUG(SCRIPT) is set. */ char *tfile; sigset_t mask; /* * We're serious here, but if the commands were bogus, we're * also dead... */ if (!cmdsOK) { PrintOnError(gn, NULL); /* provide some clue */ DieHorribly(); } JobSigLock(&mask); tfd = mkTempFile(TMPPAT, &tfile); if (!DEBUG(SCRIPT)) (void)eunlink(tfile); JobSigUnlock(&mask); job->cmdFILE = fdopen(tfd, "w+"); if (job->cmdFILE == NULL) { Punt("Could not fdopen %s", tfile); } (void)fcntl(FILENO(job->cmdFILE), F_SETFD, FD_CLOEXEC); /* * Send the commands to the command file, flush all its buffers then * rewind and remove the thing. */ noExec = FALSE; #ifdef USE_META if (useMeta) { meta_job_start(job, gn); if (Targ_Silent(gn)) { /* might have changed */ job->flags |= JOB_SILENT; } } #endif /* * We can do all the commands at once. hooray for sanity */ numCommands = 0; Lst_ForEach(gn->commands, JobPrintCommand, job); /* * If we didn't print out any commands to the shell script, * there's not much point in executing the shell, is there? */ if (numCommands == 0) { noExec = TRUE; } free(tfile); } else if (NoExecute(gn)) { /* * Not executing anything -- just print all the commands to stdout * in one fell swoop. This will still set up job->tailCmds correctly. */ if (lastNode != gn) { MESSAGE(stdout, gn); lastNode = gn; } job->cmdFILE = stdout; /* * Only print the commands if they're ok, but don't die if they're * not -- just let the user know they're bad and keep going. It * doesn't do any harm in this case and may do some good. */ if (cmdsOK) { Lst_ForEach(gn->commands, JobPrintCommand, job); } /* * Don't execute the shell, thank you. */ noExec = TRUE; } else { /* * Just touch the target and note that no shell should be executed. * Set cmdFILE to stdout to make life easier. Check the commands, too, * but don't die if they're no good -- it does no harm to keep working * up the graph. */ job->cmdFILE = stdout; Job_Touch(gn, job->flags&JOB_SILENT); noExec = TRUE; } /* Just in case it isn't already... */ (void)fflush(job->cmdFILE); /* * If we're not supposed to execute a shell, don't. */ if (noExec) { if (!(job->flags & JOB_SPECIAL)) Job_TokenReturn(); /* * Unlink and close the command file if we opened one */ if (job->cmdFILE != stdout) { if (job->cmdFILE != NULL) { (void)fclose(job->cmdFILE); job->cmdFILE = NULL; } } /* * We only want to work our way up the graph if we aren't here because * the commands for the job were no good. */ if (cmdsOK && aborting == 0) { if (job->tailCmds != NULL) { Lst_ForEachFrom(job->node->commands, job->tailCmds, JobSaveCommand, job->node); } job->node->made = MADE; Make_Update(job->node); } job->job_state = JOB_ST_FREE; return cmdsOK ? JOB_FINISHED : JOB_ERROR; } /* * Set up the control arguments to the shell. This is based on the flags * set earlier for this job. */ JobMakeArgv(job, argv); /* Create the pipe by which we'll get the shell's output. */ JobCreatePipe(job, 3); JobExec(job, argv); return(JOB_RUNNING); } static char * JobOutput(Job *job, char *cp, char *endp, int msg) { char *ecp; if (commandShell->noPrint) { ecp = Str_FindSubstring(cp, commandShell->noPrint); while (ecp != NULL) { if (cp != ecp) { *ecp = '\0'; if (!beSilent && msg && job->node != lastNode) { MESSAGE(stdout, job->node); lastNode = job->node; } /* * The only way there wouldn't be a newline after * this line is if it were the last in the buffer. * however, since the non-printable comes after it, * there must be a newline, so we don't print one. */ (void)fprintf(stdout, "%s", cp); (void)fflush(stdout); } cp = ecp + commandShell->noPLen; if (cp != endp) { /* * Still more to print, look again after skipping * the whitespace following the non-printable * command.... */ cp++; while (*cp == ' ' || *cp == '\t' || *cp == '\n') { cp++; } ecp = Str_FindSubstring(cp, commandShell->noPrint); } else { return cp; } } } return cp; } /*- *----------------------------------------------------------------------- * JobDoOutput -- * This function is called at different times depending on * whether the user has specified that output is to be collected * via pipes or temporary files. In the former case, we are called * whenever there is something to read on the pipe. We collect more * output from the given job and store it in the job's outBuf. If * this makes up a line, we print it tagged by the job's identifier, * as necessary. * If output has been collected in a temporary file, we open the * file and read it line by line, transfering it to our own * output channel until the file is empty. At which point we * remove the temporary file. * In both cases, however, we keep our figurative eye out for the * 'noPrint' line for the shell from which the output came. If * we recognize a line, we don't print it. If the command is not * alone on the line (the character after it is not \0 or \n), we * do print whatever follows it. * * Input: * job the job whose output needs printing * finish TRUE if this is the last time we'll be called * for this job * * Results: * None * * Side Effects: * curPos may be shifted as may the contents of outBuf. *----------------------------------------------------------------------- */ STATIC void JobDoOutput(Job *job, Boolean finish) { Boolean gotNL = FALSE; /* true if got a newline */ Boolean fbuf; /* true if our buffer filled up */ int nr; /* number of bytes read */ int i; /* auxiliary index into outBuf */ int max; /* limit for i (end of current data) */ int nRead; /* (Temporary) number of bytes read */ /* * Read as many bytes as will fit in the buffer. */ end_loop: gotNL = FALSE; fbuf = FALSE; nRead = read(job->inPipe, &job->outBuf[job->curPos], JOB_BUFSIZE - job->curPos); if (nRead < 0) { if (errno == EAGAIN) return; if (DEBUG(JOB)) { perror("JobDoOutput(piperead)"); } nr = 0; } else { nr = nRead; } /* * If we hit the end-of-file (the job is dead), we must flush its * remaining output, so pretend we read a newline if there's any * output remaining in the buffer. * Also clear the 'finish' flag so we stop looping. */ if ((nr == 0) && (job->curPos != 0)) { job->outBuf[job->curPos] = '\n'; nr = 1; finish = FALSE; } else if (nr == 0) { finish = FALSE; } /* * Look for the last newline in the bytes we just got. If there is * one, break out of the loop with 'i' as its index and gotNL set * TRUE. */ max = job->curPos + nr; for (i = job->curPos + nr - 1; i >= job->curPos; i--) { if (job->outBuf[i] == '\n') { gotNL = TRUE; break; } else if (job->outBuf[i] == '\0') { /* * Why? */ job->outBuf[i] = ' '; } } if (!gotNL) { job->curPos += nr; if (job->curPos == JOB_BUFSIZE) { /* * If we've run out of buffer space, we have no choice * but to print the stuff. sigh. */ fbuf = TRUE; i = job->curPos; } } if (gotNL || fbuf) { /* * Need to send the output to the screen. Null terminate it * first, overwriting the newline character if there was one. * So long as the line isn't one we should filter (according * to the shell description), we print the line, preceded * by a target banner if this target isn't the same as the * one for which we last printed something. * The rest of the data in the buffer are then shifted down * to the start of the buffer and curPos is set accordingly. */ job->outBuf[i] = '\0'; if (i >= job->curPos) { char *cp; cp = JobOutput(job, job->outBuf, &job->outBuf[i], FALSE); /* * There's still more in that thar buffer. This time, though, * we know there's no newline at the end, so we add one of * our own free will. */ if (*cp != '\0') { if (!beSilent && job->node != lastNode) { MESSAGE(stdout, job->node); lastNode = job->node; } #ifdef USE_META if (useMeta) { meta_job_output(job, cp, gotNL ? "\n" : ""); } #endif (void)fprintf(stdout, "%s%s", cp, gotNL ? "\n" : ""); (void)fflush(stdout); } } /* * max is the last offset still in the buffer. Move any remaining * characters to the start of the buffer and update the end marker * curPos. */ if (i < max) { (void)memmove(job->outBuf, &job->outBuf[i + 1], max - (i + 1)); job->curPos = max - (i + 1); } else { assert(i == max); job->curPos = 0; } } if (finish) { /* * If the finish flag is true, we must loop until we hit * end-of-file on the pipe. This is guaranteed to happen * eventually since the other end of the pipe is now closed * (we closed it explicitly and the child has exited). When * we do get an EOF, finish will be set FALSE and we'll fall * through and out. */ goto end_loop; } } static void JobRun(GNode *targ) { #ifdef notyet /* * Unfortunately it is too complicated to run .BEGIN, .END, * and .INTERRUPT job in the parallel job module. This has * the nice side effect that it avoids a lot of other problems. */ Lst lst = Lst_Init(FALSE); Lst_AtEnd(lst, targ); (void)Make_Run(lst); Lst_Destroy(lst, NULL); JobStart(targ, JOB_SPECIAL); while (jobTokensRunning) { Job_CatchOutput(); } #else Compat_Make(targ, targ); if (targ->made == ERROR) { PrintOnError(targ, "\n\nStop."); exit(1); } #endif } /*- *----------------------------------------------------------------------- * Job_CatchChildren -- * Handle the exit of a child. Called from Make_Make. * * Input: * block TRUE if should block on the wait * * Results: * none. * * Side Effects: * The job descriptor is removed from the list of children. * * Notes: * We do waits, blocking or not, according to the wisdom of our * caller, until there are no more children to report. For each * job, call JobFinish to finish things off. * *----------------------------------------------------------------------- */ void Job_CatchChildren(void) { int pid; /* pid of dead child */ WAIT_T status; /* Exit/termination status */ /* * Don't even bother if we know there's no one around. */ if (jobTokensRunning == 0) return; while ((pid = waitpid((pid_t) -1, &status, WNOHANG | WUNTRACED)) > 0) { if (DEBUG(JOB)) { (void)fprintf(debug_file, "Process %d exited/stopped status %x.\n", pid, WAIT_STATUS(status)); } JobReapChild(pid, status, TRUE); } } /* * It is possible that wait[pid]() was called from elsewhere, * this lets us reap jobs regardless. */ void JobReapChild(pid_t pid, WAIT_T status, Boolean isJobs) { Job *job; /* job descriptor for dead child */ /* * Don't even bother if we know there's no one around. */ if (jobTokensRunning == 0) return; job = JobFindPid(pid, JOB_ST_RUNNING, isJobs); if (job == NULL) { if (isJobs) { if (!lurking_children) Error("Child (%d) status %x not in table?", pid, status); } return; /* not ours */ } if (WIFSTOPPED(status)) { if (DEBUG(JOB)) { (void)fprintf(debug_file, "Process %d (%s) stopped.\n", job->pid, job->node->name); } if (!make_suspended) { switch (WSTOPSIG(status)) { case SIGTSTP: (void)printf("*** [%s] Suspended\n", job->node->name); break; case SIGSTOP: (void)printf("*** [%s] Stopped\n", job->node->name); break; default: (void)printf("*** [%s] Stopped -- signal %d\n", job->node->name, WSTOPSIG(status)); } job->job_suspended = 1; } (void)fflush(stdout); return; } job->job_state = JOB_ST_FINISHED; job->exit_status = WAIT_STATUS(status); JobFinish(job, status); } /*- *----------------------------------------------------------------------- * Job_CatchOutput -- * Catch the output from our children, if we're using * pipes do so. Otherwise just block time until we get a * signal(most likely a SIGCHLD) since there's no point in * just spinning when there's nothing to do and the reaping * of a child can wait for a while. * * Results: * None * * Side Effects: * Output is read from pipes if we're piping. * ----------------------------------------------------------------------- */ void Job_CatchOutput(void) { int nready; Job *job; int i; (void)fflush(stdout); /* The first fd in the list is the job token pipe */ do { nready = poll(fds + 1 - wantToken, nfds - 1 + wantToken, POLL_MSEC); } while (nready < 0 && errno == EINTR); if (nready < 0) Punt("poll: %s", strerror(errno)); if (nready > 0 && readyfd(&childExitJob)) { char token = 0; ssize_t count; count = read(childExitJob.inPipe, &token, 1); switch (count) { case 0: Punt("unexpected eof on token pipe"); case -1: Punt("token pipe read: %s", strerror(errno)); case 1: if (token == DO_JOB_RESUME[0]) /* Complete relay requested from our SIGCONT handler */ JobRestartJobs(); break; default: abort(); } --nready; } Job_CatchChildren(); if (nready == 0) return; - for (i = 2; i < nfds; i++) { + for (i = npseudojobs*nfds_per_job(); i < nfds; i++) { if (!fds[i].revents) continue; job = jobfds[i]; if (job->job_state == JOB_ST_RUNNING) JobDoOutput(job, FALSE); +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + /* + * With meta mode, we may have activity on the job's filemon + * descriptor too, which at the moment is any pollfd other than + * job->inPollfd. + */ + if (useMeta && job->inPollfd != &fds[i]) { + if (meta_job_event(job) <= 0) { + fds[i].events = 0; /* never mind */ + } + } +#endif if (--nready == 0) return; } } /*- *----------------------------------------------------------------------- * Job_Make -- * Start the creation of a target. Basically a front-end for * JobStart used by the Make module. * * Results: * None. * * Side Effects: * Another job is started. * *----------------------------------------------------------------------- */ void Job_Make(GNode *gn) { (void)JobStart(gn, 0); } void Shell_Init(void) { if (shellPath == NULL) { /* * We are using the default shell, which may be an absolute * path if DEFSHELL_CUSTOM is defined. */ shellName = commandShell->name; #ifdef DEFSHELL_CUSTOM if (*shellName == '/') { shellPath = shellName; shellName = strrchr(shellPath, '/'); shellName++; } else #endif shellPath = str_concat(_PATH_DEFSHELLDIR, shellName, STR_ADDSLASH); } if (commandShell->exit == NULL) { commandShell->exit = ""; } if (commandShell->echo == NULL) { commandShell->echo = ""; } if (commandShell->hasErrCtl && *commandShell->exit) { if (shellErrFlag && strcmp(commandShell->exit, &shellErrFlag[1]) != 0) { free(shellErrFlag); shellErrFlag = NULL; } if (!shellErrFlag) { int n = strlen(commandShell->exit) + 2; shellErrFlag = bmake_malloc(n); if (shellErrFlag) { snprintf(shellErrFlag, n, "-%s", commandShell->exit); } } } else if (shellErrFlag) { free(shellErrFlag); shellErrFlag = NULL; } } /*- * Returns the string literal that is used in the current command shell * to produce a newline character. */ const char * Shell_GetNewline(void) { return commandShell->newline; } void Job_SetPrefix(void) { if (targPrefix) { free(targPrefix); } else if (!Var_Exists(MAKE_JOB_PREFIX, VAR_GLOBAL)) { Var_Set(MAKE_JOB_PREFIX, "---", VAR_GLOBAL, 0); } targPrefix = Var_Subst(NULL, "${" MAKE_JOB_PREFIX "}", VAR_GLOBAL, VARF_WANTRES); } /*- *----------------------------------------------------------------------- * Job_Init -- * Initialize the process module * * Input: * * Results: * none * * Side Effects: * lists and counters are initialized *----------------------------------------------------------------------- */ void Job_Init(void) { Job_SetPrefix(); /* Allocate space for all the job info */ job_table = bmake_malloc(maxJobs * sizeof *job_table); memset(job_table, 0, maxJobs * sizeof *job_table); job_table_end = job_table + maxJobs; wantToken = 0; aborting = 0; errors = 0; lastNode = NULL; Always_pass_job_queue = getBoolean(MAKE_ALWAYS_PASS_JOB_QUEUE, Always_pass_job_queue); Job_error_token = getBoolean(MAKE_JOB_ERROR_TOKEN, Job_error_token); /* * There is a non-zero chance that we already have children. * eg after 'make -f- < 0) continue; if (rval == 0) lurking_children = 1; break; } Shell_Init(); JobCreatePipe(&childExitJob, 3); - /* We can only need to wait for tokens, children and output from each job */ - fds = bmake_malloc(sizeof (*fds) * (2 + maxJobs)); - jobfds = bmake_malloc(sizeof (*jobfds) * (2 + maxJobs)); + /* Preallocate enough for the maximum number of jobs. */ + fds = bmake_malloc(sizeof(*fds) * + (npseudojobs + maxJobs) * nfds_per_job()); + jobfds = bmake_malloc(sizeof(*jobfds) * + (npseudojobs + maxJobs) * nfds_per_job()); /* These are permanent entries and take slots 0 and 1 */ watchfd(&tokenWaitJob); watchfd(&childExitJob); sigemptyset(&caught_signals); /* * Install a SIGCHLD handler. */ (void)bmake_signal(SIGCHLD, JobChildSig); sigaddset(&caught_signals, SIGCHLD); #define ADDSIG(s,h) \ if (bmake_signal(s, SIG_IGN) != SIG_IGN) { \ sigaddset(&caught_signals, s); \ (void)bmake_signal(s, h); \ } /* * Catch the four signals that POSIX specifies if they aren't ignored. * JobPassSig will take care of calling JobInterrupt if appropriate. */ ADDSIG(SIGINT, JobPassSig_int) ADDSIG(SIGHUP, JobPassSig_term) ADDSIG(SIGTERM, JobPassSig_term) ADDSIG(SIGQUIT, JobPassSig_term) /* * There are additional signals that need to be caught and passed if * either the export system wants to be told directly of signals or if * we're giving each job its own process group (since then it won't get * signals from the terminal driver as we own the terminal) */ ADDSIG(SIGTSTP, JobPassSig_suspend) ADDSIG(SIGTTOU, JobPassSig_suspend) ADDSIG(SIGTTIN, JobPassSig_suspend) ADDSIG(SIGWINCH, JobCondPassSig) ADDSIG(SIGCONT, JobContinueSig) #undef ADDSIG (void)Job_RunTarget(".BEGIN", NULL); postCommands = Targ_FindNode(".END", TARG_CREATE); } static void JobSigReset(void) { #define DELSIG(s) \ if (sigismember(&caught_signals, s)) { \ (void)bmake_signal(s, SIG_DFL); \ } DELSIG(SIGINT) DELSIG(SIGHUP) DELSIG(SIGQUIT) DELSIG(SIGTERM) DELSIG(SIGTSTP) DELSIG(SIGTTOU) DELSIG(SIGTTIN) DELSIG(SIGWINCH) DELSIG(SIGCONT) #undef DELSIG (void)bmake_signal(SIGCHLD, SIG_DFL); } /*- *----------------------------------------------------------------------- * JobMatchShell -- * Find a shell in 'shells' given its name. * * Results: * A pointer to the Shell structure. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static Shell * JobMatchShell(const char *name) { Shell *sh; for (sh = shells; sh->name != NULL; sh++) { if (strcmp(name, sh->name) == 0) return (sh); } return NULL; } /*- *----------------------------------------------------------------------- * Job_ParseShell -- * Parse a shell specification and set up commandShell, shellPath * and shellName appropriately. * * Input: * line The shell spec * * Results: * FAILURE if the specification was incorrect. * * Side Effects: * commandShell points to a Shell structure (either predefined or * created from the shell spec), shellPath is the full path of the * shell described by commandShell, while shellName is just the * final component of shellPath. * * Notes: * A shell specification consists of a .SHELL target, with dependency * operator, followed by a series of blank-separated words. Double * quotes can be used to use blanks in words. A backslash escapes * anything (most notably a double-quote and a space) and * provides the functionality it does in C. Each word consists of * keyword and value separated by an equal sign. There should be no * unnecessary spaces in the word. The keywords are as follows: * name Name of shell. * path Location of shell. * quiet Command to turn off echoing. * echo Command to turn echoing on * filter Result of turning off echoing that shouldn't be * printed. * echoFlag Flag to turn echoing on at the start * errFlag Flag to turn error checking on at the start * hasErrCtl True if shell has error checking control * newline String literal to represent a newline char * check Command to turn on error checking if hasErrCtl * is TRUE or template of command to echo a command * for which error checking is off if hasErrCtl is * FALSE. * ignore Command to turn off error checking if hasErrCtl * is TRUE or template of command to execute a * command so as to ignore any errors it returns if * hasErrCtl is FALSE. * *----------------------------------------------------------------------- */ ReturnStatus Job_ParseShell(char *line) { char **words; char **argv; int argc; char *path; Shell newShell; Boolean fullSpec = FALSE; Shell *sh; while (isspace((unsigned char)*line)) { line++; } free(UNCONST(shellArgv)); memset(&newShell, 0, sizeof(newShell)); /* * Parse the specification by keyword */ words = brk_string(line, &argc, TRUE, &path); if (words == NULL) { Error("Unterminated quoted string [%s]", line); return FAILURE; } shellArgv = path; for (path = NULL, argv = words; argc != 0; argc--, argv++) { if (strncmp(*argv, "path=", 5) == 0) { path = &argv[0][5]; } else if (strncmp(*argv, "name=", 5) == 0) { newShell.name = &argv[0][5]; } else { if (strncmp(*argv, "quiet=", 6) == 0) { newShell.echoOff = &argv[0][6]; } else if (strncmp(*argv, "echo=", 5) == 0) { newShell.echoOn = &argv[0][5]; } else if (strncmp(*argv, "filter=", 7) == 0) { newShell.noPrint = &argv[0][7]; newShell.noPLen = strlen(newShell.noPrint); } else if (strncmp(*argv, "echoFlag=", 9) == 0) { newShell.echo = &argv[0][9]; } else if (strncmp(*argv, "errFlag=", 8) == 0) { newShell.exit = &argv[0][8]; } else if (strncmp(*argv, "hasErrCtl=", 10) == 0) { char c = argv[0][10]; newShell.hasErrCtl = !((c != 'Y') && (c != 'y') && (c != 'T') && (c != 't')); } else if (strncmp(*argv, "newline=", 8) == 0) { newShell.newline = &argv[0][8]; } else if (strncmp(*argv, "check=", 6) == 0) { newShell.errCheck = &argv[0][6]; } else if (strncmp(*argv, "ignore=", 7) == 0) { newShell.ignErr = &argv[0][7]; } else if (strncmp(*argv, "errout=", 7) == 0) { newShell.errOut = &argv[0][7]; } else if (strncmp(*argv, "comment=", 8) == 0) { newShell.commentChar = argv[0][8]; } else { Parse_Error(PARSE_FATAL, "Unknown keyword \"%s\"", *argv); free(words); return(FAILURE); } fullSpec = TRUE; } } if (path == NULL) { /* * If no path was given, the user wants one of the pre-defined shells, * yes? So we find the one s/he wants with the help of JobMatchShell * and set things up the right way. shellPath will be set up by * Shell_Init. */ if (newShell.name == NULL) { Parse_Error(PARSE_FATAL, "Neither path nor name specified"); free(words); return(FAILURE); } else { if ((sh = JobMatchShell(newShell.name)) == NULL) { Parse_Error(PARSE_WARNING, "%s: No matching shell", newShell.name); free(words); return(FAILURE); } commandShell = sh; shellName = newShell.name; if (shellPath) { /* Shell_Init has already been called! Do it again. */ free(UNCONST(shellPath)); shellPath = NULL; Shell_Init(); } } } else { /* * The user provided a path. If s/he gave nothing else (fullSpec is * FALSE), try and find a matching shell in the ones we know of. * Else we just take the specification at its word and copy it * to a new location. In either case, we need to record the * path the user gave for the shell. */ shellPath = path; path = strrchr(path, '/'); if (path == NULL) { path = UNCONST(shellPath); } else { path += 1; } if (newShell.name != NULL) { shellName = newShell.name; } else { shellName = path; } if (!fullSpec) { if ((sh = JobMatchShell(shellName)) == NULL) { Parse_Error(PARSE_WARNING, "%s: No matching shell", shellName); free(words); return(FAILURE); } commandShell = sh; } else { commandShell = bmake_malloc(sizeof(Shell)); *commandShell = newShell; } /* this will take care of shellErrFlag */ Shell_Init(); } if (commandShell->echoOn && commandShell->echoOff) { commandShell->hasEchoCtl = TRUE; } if (!commandShell->hasErrCtl) { if (commandShell->errCheck == NULL) { commandShell->errCheck = ""; } if (commandShell->ignErr == NULL) { commandShell->ignErr = "%s\n"; } } /* * Do not free up the words themselves, since they might be in use by the * shell specification. */ free(words); return SUCCESS; } /*- *----------------------------------------------------------------------- * JobInterrupt -- * Handle the receipt of an interrupt. * * Input: * runINTERRUPT Non-zero if commands for the .INTERRUPT target * should be executed * signo signal received * * Results: * None * * Side Effects: * All children are killed. Another job will be started if the * .INTERRUPT target was given. *----------------------------------------------------------------------- */ static void JobInterrupt(int runINTERRUPT, int signo) { Job *job; /* job descriptor in that element */ GNode *interrupt; /* the node describing the .INTERRUPT target */ sigset_t mask; GNode *gn; aborting = ABORT_INTERRUPT; JobSigLock(&mask); for (job = job_table; job < job_table_end; job++) { if (job->job_state != JOB_ST_RUNNING) continue; gn = job->node; JobDeleteTarget(gn); if (job->pid) { if (DEBUG(JOB)) { (void)fprintf(debug_file, "JobInterrupt passing signal %d to child %d.\n", signo, job->pid); } KILLPG(job->pid, signo); } } JobSigUnlock(&mask); if (runINTERRUPT && !touchFlag) { interrupt = Targ_FindNode(".INTERRUPT", TARG_NOCREATE); if (interrupt != NULL) { ignoreErrors = FALSE; JobRun(interrupt); } } Trace_Log(MAKEINTR, 0); exit(signo); } /* *----------------------------------------------------------------------- * Job_Finish -- * Do final processing such as the running of the commands * attached to the .END target. * * Results: * Number of errors reported. * * Side Effects: * None. *----------------------------------------------------------------------- */ int Job_Finish(void) { if (postCommands != NULL && (!Lst_IsEmpty(postCommands->commands) || !Lst_IsEmpty(postCommands->children))) { if (errors) { Error("Errors reported so .END ignored"); } else { JobRun(postCommands); } } return(errors); } /*- *----------------------------------------------------------------------- * Job_End -- * Cleanup any memory used by the jobs module * * Results: * None. * * Side Effects: * Memory is freed *----------------------------------------------------------------------- */ void Job_End(void) { #ifdef CLEANUP free(shellArgv); #endif } /*- *----------------------------------------------------------------------- * Job_Wait -- * Waits for all running jobs to finish and returns. Sets 'aborting' * to ABORT_WAIT to prevent other jobs from starting. * * Results: * None. * * Side Effects: * Currently running jobs finish. * *----------------------------------------------------------------------- */ void Job_Wait(void) { aborting = ABORT_WAIT; while (jobTokensRunning != 0) { Job_CatchOutput(); } aborting = 0; } /*- *----------------------------------------------------------------------- * Job_AbortAll -- * Abort all currently running jobs without handling output or anything. * This function is to be called only in the event of a major * error. Most definitely NOT to be called from JobInterrupt. * * Results: * None * * Side Effects: * All children are killed, not just the firstborn *----------------------------------------------------------------------- */ void Job_AbortAll(void) { Job *job; /* the job descriptor in that element */ WAIT_T foo; aborting = ABORT_ERROR; if (jobTokensRunning) { for (job = job_table; job < job_table_end; job++) { if (job->job_state != JOB_ST_RUNNING) continue; /* * kill the child process with increasingly drastic signals to make * darn sure it's dead. */ KILLPG(job->pid, SIGINT); KILLPG(job->pid, SIGKILL); } } /* * Catch as many children as want to report in at first, then give up */ while (waitpid((pid_t) -1, &foo, WNOHANG) > 0) continue; } /*- *----------------------------------------------------------------------- * JobRestartJobs -- * Tries to restart stopped jobs if there are slots available. * Called in process context in response to a SIGCONT. * * Results: * None. * * Side Effects: * Resumes jobs. * *----------------------------------------------------------------------- */ static void JobRestartJobs(void) { Job *job; for (job = job_table; job < job_table_end; job++) { if (job->job_state == JOB_ST_RUNNING && (make_suspended || job->job_suspended)) { if (DEBUG(JOB)) { (void)fprintf(debug_file, "Restarting stopped job pid %d.\n", job->pid); } if (job->job_suspended) { (void)printf("*** [%s] Continued\n", job->node->name); (void)fflush(stdout); } job->job_suspended = 0; if (KILLPG(job->pid, SIGCONT) != 0 && DEBUG(JOB)) { fprintf(debug_file, "Failed to send SIGCONT to %d\n", job->pid); } } if (job->job_state == JOB_ST_FINISHED) /* Job exit deferred after calling waitpid() in a signal handler */ JobFinish(job, job->exit_status); } make_suspended = 0; } static void watchfd(Job *job) { if (job->inPollfd != NULL) Punt("Watching watched job"); fds[nfds].fd = job->inPipe; fds[nfds].events = POLLIN; jobfds[nfds] = job; job->inPollfd = &fds[nfds]; nfds++; +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + if (useMeta) { + fds[nfds].fd = meta_job_fd(job); + fds[nfds].events = fds[nfds].fd == -1 ? 0 : POLLIN; + jobfds[nfds] = job; + nfds++; + } +#endif } static void clearfd(Job *job) { int i; if (job->inPollfd == NULL) Punt("Unwatching unwatched job"); i = job->inPollfd - fds; nfds--; +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + if (useMeta) { + /* + * Sanity check: there should be two fds per job, so the job's + * pollfd number should be even. + */ + assert(nfds_per_job() == 2); + if (i % 2) + Punt("odd-numbered fd with meta"); + nfds--; + } +#endif /* * Move last job in table into hole made by dead job. */ if (nfds != i) { fds[i] = fds[nfds]; jobfds[i] = jobfds[nfds]; jobfds[i]->inPollfd = &fds[i]; +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + if (useMeta) { + fds[i + 1] = fds[nfds + 1]; + jobfds[i + 1] = jobfds[nfds + 1]; + } +#endif } job->inPollfd = NULL; } static int readyfd(Job *job) { if (job->inPollfd == NULL) Punt("Polling unwatched job"); return (job->inPollfd->revents & POLLIN) != 0; } /*- *----------------------------------------------------------------------- * JobTokenAdd -- * Put a token into the job pipe so that some make process can start * another job. * * Side Effects: * Allows more build jobs to be spawned somewhere. * *----------------------------------------------------------------------- */ static void JobTokenAdd(void) { char tok = JOB_TOKENS[aborting], tok1; if (!Job_error_token && aborting == ABORT_ERROR) { if (jobTokensRunning == 0) return; tok = '+'; /* no error token */ } /* If we are depositing an error token flush everything else */ while (tok != '+' && read(tokenWaitJob.inPipe, &tok1, 1) == 1) continue; if (DEBUG(JOB)) fprintf(debug_file, "(%d) aborting %d, deposit token %c\n", getpid(), aborting, tok); while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN) continue; } /*- *----------------------------------------------------------------------- * Job_ServerStartTokenAdd -- * Prep the job token pipe in the root make process. * *----------------------------------------------------------------------- */ void Job_ServerStart(int max_tokens, int jp_0, int jp_1) { int i; char jobarg[64]; if (jp_0 >= 0 && jp_1 >= 0) { /* Pipe passed in from parent */ tokenWaitJob.inPipe = jp_0; tokenWaitJob.outPipe = jp_1; (void)fcntl(jp_0, F_SETFD, FD_CLOEXEC); (void)fcntl(jp_1, F_SETFD, FD_CLOEXEC); return; } JobCreatePipe(&tokenWaitJob, 15); snprintf(jobarg, sizeof(jobarg), "%d,%d", tokenWaitJob.inPipe, tokenWaitJob.outPipe); Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL); Var_Append(MAKEFLAGS, jobarg, VAR_GLOBAL); /* * Preload the job pipe with one token per job, save the one * "extra" token for the primary job. * * XXX should clip maxJobs against PIPE_BUF -- if max_tokens is * larger than the write buffer size of the pipe, we will * deadlock here. */ for (i = 1; i < max_tokens; i++) JobTokenAdd(); } /*- *----------------------------------------------------------------------- * Job_TokenReturn -- * Return a withdrawn token to the pool. * *----------------------------------------------------------------------- */ void Job_TokenReturn(void) { jobTokensRunning--; if (jobTokensRunning < 0) Punt("token botch"); if (jobTokensRunning || JOB_TOKENS[aborting] != '+') JobTokenAdd(); } /*- *----------------------------------------------------------------------- * Job_TokenWithdraw -- * Attempt to withdraw a token from the pool. * * Results: * Returns TRUE if a token was withdrawn, and FALSE if the pool * is currently empty. * * Side Effects: * If pool is empty, set wantToken so that we wake up * when a token is released. * *----------------------------------------------------------------------- */ Boolean Job_TokenWithdraw(void) { char tok, tok1; int count; wantToken = 0; if (DEBUG(JOB)) fprintf(debug_file, "Job_TokenWithdraw(%d): aborting %d, running %d\n", getpid(), aborting, jobTokensRunning); if (aborting || (jobTokensRunning >= maxJobs)) return FALSE; count = read(tokenWaitJob.inPipe, &tok, 1); if (count == 0) Fatal("eof on job pipe!"); if (count < 0 && jobTokensRunning != 0) { if (errno != EAGAIN) { Fatal("job pipe read: %s", strerror(errno)); } if (DEBUG(JOB)) fprintf(debug_file, "(%d) blocked for token\n", getpid()); return FALSE; } if (count == 1 && tok != '+') { /* make being abvorted - remove any other job tokens */ if (DEBUG(JOB)) fprintf(debug_file, "(%d) aborted by token %c\n", getpid(), tok); while (read(tokenWaitJob.inPipe, &tok1, 1) == 1) continue; /* And put the stopper back */ while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN) continue; Fatal("A failure has been detected in another branch of the parallel make"); } if (count == 1 && jobTokensRunning == 0) /* We didn't want the token really */ while (write(tokenWaitJob.outPipe, &tok, 1) == -1 && errno == EAGAIN) continue; jobTokensRunning++; if (DEBUG(JOB)) fprintf(debug_file, "(%d) withdrew token\n", getpid()); return TRUE; } /*- *----------------------------------------------------------------------- * Job_RunTarget -- * Run the named target if found. If a filename is specified, then * set that to the sources. * * Results: * None * * Side Effects: * exits if the target fails. * *----------------------------------------------------------------------- */ Boolean Job_RunTarget(const char *target, const char *fname) { GNode *gn = Targ_FindNode(target, TARG_NOCREATE); if (gn == NULL) return FALSE; if (fname) Var_Set(ALLSRC, fname, gn, 0); JobRun(gn); if (gn->made == ERROR) { PrintOnError(gn, "\n\nStop."); exit(1); } return TRUE; } #ifdef USE_SELECT int emul_poll(struct pollfd *fd, int nfd, int timeout) { fd_set rfds, wfds; int i, maxfd, nselect, npoll; struct timeval tv, *tvp; long usecs; FD_ZERO(&rfds); FD_ZERO(&wfds); maxfd = -1; for (i = 0; i < nfd; i++) { fd[i].revents = 0; if (fd[i].events & POLLIN) FD_SET(fd[i].fd, &rfds); if (fd[i].events & POLLOUT) FD_SET(fd[i].fd, &wfds); if (fd[i].fd > maxfd) maxfd = fd[i].fd; } if (maxfd >= FD_SETSIZE) { Punt("Ran out of fd_set slots; " "recompile with a larger FD_SETSIZE."); } if (timeout < 0) { tvp = NULL; } else { usecs = timeout * 1000; tv.tv_sec = usecs / 1000000; tv.tv_usec = usecs % 1000000; tvp = &tv; } nselect = select(maxfd + 1, &rfds, &wfds, 0, tvp); if (nselect <= 0) return nselect; npoll = 0; for (i = 0; i < nfd; i++) { if (FD_ISSET(fd[i].fd, &rfds)) fd[i].revents |= POLLIN; if (FD_ISSET(fd[i].fd, &wfds)) fd[i].revents |= POLLOUT; if (fd[i].revents) npoll++; } return npoll; } #endif /* USE_SELECT */ Index: stable/12/contrib/bmake/make-bootstrap.sh.in =================================================================== --- stable/12/contrib/bmake/make-bootstrap.sh.in (revision 361673) +++ stable/12/contrib/bmake/make-bootstrap.sh.in (revision 361674) @@ -1,84 +1,101 @@ #!/bin/sh set -e srcdir=@srcdir@ DEFAULT_SYS_PATH="@default_sys_path@" case "@use_meta@" in yes) XDEFS="-DUSE_META ${XDEFS}";; esac CC="@CC@" CFLAGS="@CFLAGS@ -I. -I${srcdir} @DEFS@ @CPPFLAGS@ -DMAKE_NATIVE ${XDEFS} -DBMAKE_PATH_MAX=@bmake_path_max@" MAKE_VERSION=@_MAKE_VERSION@ MDEFS="-DMAKE_VERSION=\"$MAKE_VERSION\" \ -D@force_machine@MACHINE=\"@machine@\" -DMACHINE_ARCH=\"@machine_arch@\" \ -D_PATH_DEFSYSPATH=\"${DEFAULT_SYS_PATH}\"" LDFLAGS="@LDFLAGS@" LIBS="@LIBS@" +toUpper() { + ${TR:-tr} abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ +} + do_compile2() { obj="$1"; shift src="$1"; shift echo ${CC} -c ${CFLAGS} "$@" -o "$obj" "$src" ${CC} -c ${CFLAGS} "$@" -o "$obj" "$src" } do_compile() { obj="$1"; shift - src=`basename "$obj" .o`.c + case "$1" in + *.c) src=$1; shift;; + *) src=`basename "$obj" .o`.c;; + esac for d in "$srcdir" "$srcdir/lst.lib" do test -s "$d/$src" || continue do_compile2 "$obj" "$d/$src" "$@" || exit 1 return done echo "Unknown object file '$obj'" >&2 exit 1 } do_link() { output="$1"; shift echo ${CC} ${LDSTATIC} ${LDFLAGS} -o "$output" "$@" ${LIBS} ${CC} ${LDSTATIC} ${LDFLAGS} -o "$output" "$@" ${LIBS} } BASE_OBJECTS="arch.o buf.o compat.o cond.o dir.o for.o getopt hash.o \ -job.o make.o make_malloc.o metachar.o parse.o sigcompat.o str.o strlist.o \ +make.o make_malloc.o metachar.o parse.o sigcompat.o str.o strlist.o \ suff.o targ.o trace.o var.o util.o" LST_OBJECTS="lstAppend.o lstDupl.o lstInit.o lstOpen.o \ lstAtEnd.o lstEnQueue.o lstInsert.o lstAtFront.o lstIsAtEnd.o \ lstClose.o lstFind.o lstIsEmpty.o lstRemove.o lstConcat.o \ lstFindFrom.o lstLast.o lstReplace.o lstFirst.o lstDatum.o \ lstForEach.o lstMember.o lstSucc.o lstDeQueue.o lstForEachFrom.o \ lstDestroy.o lstNext.o lstPrev.o" LIB_OBJECTS="@LIBOBJS@" do_compile main.o ${MDEFS} for o in ${BASE_OBJECTS} ${LST_OBJECTS} ${LIB_OBJECTS} do do_compile "$o" done case "@use_meta@" in yes) - case "@filemon_h@" in - */filemon.h) FDEFS="-DHAVE_FILEMON_H -I`dirname @filemon_h@`";; + case "@use_filemon@" in + no) MDEFS=;; + *) + MDEFS="-DUSE_FILEMON -DUSE_FILEMON_`echo @use_filemon@ | toUpper`" + case "@use_filemon@,@filemon_h@" in + dev,*/filemon.h) FDEFS="-DHAVE_FILEMON_H -I`dirname @filemon_h@`";; + *) FDEFS=;; + esac + do_compile filemon_@use_filemon@.o filemon/filemon_@use_filemon@.c ${FDEFS} + BASE_OBJECTS="filemon_@use_filemon@.o $BASE_OBJECTS" + ;; esac - do_compile meta.o ${FDEFS} - BASE_OBJECTS="meta.o ${BASE_OBJECTS}" - ;; + do_compile meta.o ${MDEFS} + BASE_OBJECTS="meta.o ${BASE_OBJECTS}" + ;; esac +do_compile job.o ${MDEFS} -do_link bmake main.o ${BASE_OBJECTS} ${LST_OBJECTS} ${LIB_OBJECTS} +do_link bmake main.o job.o ${BASE_OBJECTS} ${LST_OBJECTS} ${LIB_OBJECTS} Index: stable/12/contrib/bmake/make.1 =================================================================== --- stable/12/contrib/bmake/make.1 (revision 361673) +++ stable/12/contrib/bmake/make.1 (revision 361674) @@ -1,2419 +1,2449 @@ -.\" $NetBSD: make.1,v 1.272 2018/04/02 04:26:17 dholland Exp $ +.\" $NetBSD: make.1,v 1.280 2020/04/27 20:03:08 christos Exp $ .\" .\" Copyright (c) 1990, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" from: @(#)make.1 8.4 (Berkeley) 3/19/94 .\" -.Dd September 27, 2018 +.Dd April 27, 2020 .Dt MAKE 1 .Os .Sh NAME .Nm make .Nd maintain program dependencies .Sh SYNOPSIS .Nm .Op Fl BeikNnqrstWwX .Op Fl C Ar directory .Op Fl D Ar variable .Op Fl d Ar flags .Op Fl f Ar makefile .Op Fl I Ar directory .Op Fl J Ar private .Op Fl j Ar max_jobs .Op Fl m Ar directory .Op Fl T Ar file .Op Fl V Ar variable .Op Fl v Ar variable .Op Ar variable=value .Op Ar target ... .Sh DESCRIPTION .Nm is a program designed to simplify the maintenance of other programs. Its input is a list of specifications as to the files upon which programs and other files depend. If no .Fl f Ar makefile makefile option is given, .Nm will try to open .Ql Pa makefile then .Ql Pa Makefile in order to find the specifications. If the file .Ql Pa .depend exists, it is read (see .Xr mkdep 1 ) . .Pp This manual page is intended as a reference document only. For a more thorough description of .Nm and makefiles, please refer to .%T "PMake \- A Tutorial" . .Pp .Nm will prepend the contents of the .Va MAKEFLAGS environment variable to the command line arguments before parsing them. .Pp The options are as follows: .Bl -tag -width Ds .It Fl B Try to be backwards compatible by executing a single shell per command and by executing the commands to make the sources of a dependency line in sequence. .It Fl C Ar directory Change to .Ar directory before reading the makefiles or doing anything else. If multiple .Fl C options are specified, each is interpreted relative to the previous one: .Fl C Pa / Fl C Pa etc is equivalent to .Fl C Pa /etc . .It Fl D Ar variable Define .Ar variable to be 1, in the global context. .It Fl d Ar [-]flags Turn on debugging, and specify which portions of .Nm are to print debugging information. Unless the flags are preceded by .Ql \- they are added to the .Va MAKEFLAGS environment variable and will be processed by any child make processes. By default, debugging information is printed to standard error, but this can be changed using the .Ar F debugging flag. The debugging output is always unbuffered; in addition, if debugging is enabled but debugging output is not directed to standard output, then the standard output is line buffered. .Ar Flags is one or more of the following: .Bl -tag -width Ds .It Ar A Print all possible debugging information; equivalent to specifying all of the debugging flags. .It Ar a Print debugging information about archive searching and caching. .It Ar C Print debugging information about current working directory. .It Ar c Print debugging information about conditional evaluation. .It Ar d Print debugging information about directory searching and caching. .It Ar e Print debugging information about failed commands and targets. .It Ar F Ns Oo Sy \&+ Oc Ns Ar filename Specify where debugging output is written. This must be the last flag, because it consumes the remainder of the argument. If the character immediately after the .Ql F flag is .Ql \&+ , then the file will be opened in append mode; otherwise the file will be overwritten. If the file name is .Ql stdout or .Ql stderr then debugging output will be written to the standard output or standard error output file descriptors respectively (and the .Ql \&+ option has no effect). Otherwise, the output will be written to the named file. If the file name ends .Ql .%d then the .Ql %d is replaced by the pid. .It Ar f Print debugging information about loop evaluation. .It Ar "g1" Print the input graph before making anything. .It Ar "g2" Print the input graph after making everything, or before exiting on error. .It Ar "g3" Print the input graph before exiting on error. .It Ar j Print debugging information about running multiple shells. .It Ar l Print commands in Makefiles regardless of whether or not they are prefixed by .Ql @ or other "quiet" flags. Also known as "loud" behavior. .It Ar M Print debugging information about "meta" mode decisions about targets. .It Ar m Print debugging information about making targets, including modification dates. .It Ar n Don't delete the temporary command scripts created when running commands. These temporary scripts are created in the directory referred to by the .Ev TMPDIR environment variable, or in .Pa /tmp if .Ev TMPDIR is unset or set to the empty string. The temporary scripts are created by .Xr mkstemp 3 , and have names of the form .Pa makeXXXXXX . .Em NOTE : This can create many files in .Ev TMPDIR or .Pa /tmp , so use with care. .It Ar p Print debugging information about makefile parsing. .It Ar s Print debugging information about suffix-transformation rules. .It Ar t Print debugging information about target list maintenance. .It Ar V Force the .Fl V option to print raw values of variables, overriding the default behavior set via .Va .MAKE.EXPAND_VARIABLES . .It Ar v Print debugging information about variable assignment. .It Ar x Run shell commands with .Fl x so the actual commands are printed as they are executed. .El .It Fl e Specify that environment variables override macro assignments within makefiles. .It Fl f Ar makefile Specify a makefile to read instead of the default .Ql Pa makefile . If .Ar makefile is .Ql Fl , standard input is read. Multiple makefiles may be specified, and are read in the order specified. .It Fl I Ar directory Specify a directory in which to search for makefiles and included makefiles. The system makefile directory (or directories, see the .Fl m option) is automatically included as part of this list. .It Fl i Ignore non-zero exit of shell commands in the makefile. Equivalent to specifying .Ql Fl before each command line in the makefile. .It Fl J Ar private This option should .Em not be specified by the user. .Pp When the .Ar j option is in use in a recursive build, this option is passed by a make to child makes to allow all the make processes in the build to cooperate to avoid overloading the system. .It Fl j Ar max_jobs Specify the maximum number of jobs that .Nm may have running at any one time. The value is saved in .Va .MAKE.JOBS . Turns compatibility mode off, unless the .Ar B flag is also specified. When compatibility mode is off, all commands associated with a target are executed in a single shell invocation as opposed to the traditional one shell invocation per line. This can break traditional scripts which change directories on each command invocation and then expect to start with a fresh environment on the next line. It is more efficient to correct the scripts rather than turn backwards compatibility on. .It Fl k Continue processing after errors are encountered, but only on those targets that do not depend on the target whose creation caused the error. .It Fl m Ar directory Specify a directory in which to search for sys.mk and makefiles included via the -.Ao Ar file Ac Ns -style +.Li \&< Ns Ar file Ns Li \&> Ns -style include statement. The .Fl m option can be used multiple times to form a search path. This path will override the default system include path: /usr/share/mk. Furthermore the system include path will be appended to the search path used for -.Qo Ar file Qc Ns -style +.Li \*q Ns Ar file Ns Li \*q Ns -style include statements (see the .Fl I option). .Pp If a file or directory name in the .Fl m argument (or the .Ev MAKESYSPATH environment variable) starts with the string .Qq \&.../ then .Nm will search for the specified file or directory named in the remaining part of the argument string. The search starts with the current directory of the Makefile and then works upward towards the root of the file system. If the search is successful, then the resulting directory replaces the .Qq \&.../ specification in the .Fl m argument. If used, this feature allows .Nm to easily search in the current source tree for customized sys.mk files (e.g., by using .Qq \&.../mk/sys.mk as an argument). .It Fl n Display the commands that would have been executed, but do not actually execute them unless the target depends on the .MAKE special source (see below). .It Fl N Display the commands which would have been executed, but do not actually execute any of them; useful for debugging top-level makefiles without descending into subdirectories. .It Fl q Do not execute any commands, but exit 0 if the specified targets are up-to-date and 1, otherwise. .It Fl r Do not use the built-in rules specified in the system makefile. .It Fl s Do not echo any commands as they are executed. Equivalent to specifying .Ql Ic @ before each command line in the makefile. .It Fl T Ar tracefile When used with the .Fl j flag, append a trace record to .Ar tracefile for each job started and completed. .It Fl t Rather than re-building a target as specified in the makefile, create it or update its modification time to make it appear up-to-date. .It Fl V Ar variable Print the value of .Ar variable . Do not build any targets. Multiple instances of this option may be specified; the variables will be printed one per line, with a blank line for each null or undefined variable. The value printed is extracted from the global context after all makefiles have been read. By default, the raw variable contents (which may include additional unexpanded variable references) are shown. If .Ar variable contains a .Ql \&$ then the value will be recursively expanded to its complete resultant text before printing. The expanded value will also be printed if .Va .MAKE.EXPAND_VARIABLES is set to true and the .Fl dV option has not been used to override it. Note that loop-local and target-local variables, as well as values taken temporarily by global variables during makefile processing, are not accessible via this option. The .Fl dv debug mode can be used to see these at the cost of generating substantial extraneous output. .It Fl v Ar variable Like .Fl V but the variable is always expanded to its complete value. .It Fl W Treat any warnings during makefile parsing as errors. .It Fl w Print entering and leaving directory messages, pre and post processing. .It Fl X Don't export variables passed on the command line to the environment individually. Variables passed on the command line are still exported via the .Va MAKEFLAGS environment variable. This option may be useful on systems which have a small limit on the size of command arguments. .It Ar variable=value Set the value of the variable .Ar variable to .Ar value . Normally, all values passed on the command line are also exported to sub-makes in the environment. The .Fl X flag disables this behavior. Variable assignments should follow options for POSIX compatibility but no ordering is enforced. .El .Pp There are seven different types of lines in a makefile: file dependency specifications, shell commands, variable assignments, include statements, conditional directives, for loops, and comments. .Pp In general, lines may be continued from one line to the next by ending them with a backslash .Pq Ql \e . The trailing newline character and initial whitespace on the following line are compressed into a single space. .Sh FILE DEPENDENCY SPECIFICATIONS Dependency lines consist of one or more targets, an operator, and zero or more sources. This creates a relationship where the targets .Dq depend on the sources and are usually created from them. The exact relationship between the target and the source is determined by the operator that separates them. The three operators are as follows: .Bl -tag -width flag .It Ic \&: A target is considered out-of-date if its modification time is less than those of any of its sources. Sources for a target accumulate over dependency lines when this operator is used. The target is removed if .Nm is interrupted. .It Ic \&! Targets are always re-created, but not until all sources have been examined and re-created as necessary. Sources for a target accumulate over dependency lines when this operator is used. The target is removed if .Nm is interrupted. .It Ic \&:: If no sources are specified, the target is always re-created. Otherwise, a target is considered out-of-date if any of its sources has been modified more recently than the target. Sources for a target do not accumulate over dependency lines when this operator is used. The target will not be removed if .Nm is interrupted. .El .Pp Targets and sources may contain the shell wildcard values .Ql \&? , .Ql * , .Ql [] , and .Ql {} . The values .Ql \&? , .Ql * , and .Ql [] may only be used as part of the final component of the target or source, and must be used to describe existing files. The value .Ql {} need not necessarily be used to describe existing files. Expansion is in directory order, not alphabetically as done in the shell. .Sh SHELL COMMANDS Each target may have associated with it one or more lines of shell commands, normally used to create the target. Each of the lines in this script .Em must be preceded by a tab. (For historical reasons, spaces are not accepted.) While targets can appear in many dependency lines if desired, by default only one of these rules may be followed by a creation script. If the .Ql Ic \&:: operator is used, however, all rules may include scripts and the scripts are executed in the order found. .Pp Each line is treated as a separate shell command, unless the end of line is escaped with a backslash .Pq Ql \e in which case that line and the next are combined. .\" The escaped newline is retained and passed to the shell, which .\" normally ignores it. .\" However, the tab at the beginning of the following line is removed. If the first characters of the command are any combination of .Ql Ic @ , .Ql Ic + , or .Ql Ic \- , the command is treated specially. A .Ql Ic @ causes the command not to be echoed before it is executed. A .Ql Ic + causes the command to be executed even when .Fl n is given. This is similar to the effect of the .MAKE special source, except that the effect can be limited to a single line of a script. A .Ql Ic \- in compatibility mode causes any non-zero exit status of the command line to be ignored. .Pp When .Nm is run in jobs mode with .Fl j Ar max_jobs , the entire script for the target is fed to a single instance of the shell. In compatibility (non-jobs) mode, each command is run in a separate process. If the command contains any shell meta characters .Pq Ql #=|^(){};&<>*?[]:$`\e\en it will be passed to the shell; otherwise .Nm will attempt direct execution. If a line starts with .Ql Ic \- and the shell has ErrCtl enabled then failure of the command line will be ignored as in compatibility mode. Otherwise .Ql Ic \- affects the entire job; the script will stop at the first command line that fails, but the target will not be deemed to have failed. .Pp Makefiles should be written so that the mode of .Nm operation does not change their behavior. For example, any command which needs to use .Dq cd or .Dq chdir without potentially changing the directory for subsequent commands should be put in parentheses so it executes in a subshell. To force the use of one shell, escape the line breaks so as to make the whole script one command. For example: .Bd -literal -offset indent avoid-chdir-side-effects: @echo Building $@ in `pwd` @(cd ${.CURDIR} && ${MAKE} $@) @echo Back in `pwd` ensure-one-shell-regardless-of-mode: @echo Building $@ in `pwd`; \e (cd ${.CURDIR} && ${MAKE} $@); \e echo Back in `pwd` .Ed .Pp Since .Nm will .Xr chdir 2 to .Ql Va .OBJDIR before executing any targets, each child process starts with that as its current working directory. .Sh VARIABLE ASSIGNMENTS Variables in make are much like variables in the shell, and, by tradition, consist of all upper-case letters. .Ss Variable assignment modifiers The five operators that can be used to assign values to variables are as follows: .Bl -tag -width Ds .It Ic \&= Assign the value to the variable. Any previous value is overridden. .It Ic \&+= Append the value to the current value of the variable. .It Ic \&?= Assign the value to the variable if it is not already defined. .It Ic \&:= Assign with expansion, i.e. expand the value before assigning it to the variable. Normally, expansion is not done until the variable is referenced. .Em NOTE : References to undefined variables are .Em not expanded. This can cause problems when variable modifiers are used. .It Ic \&!= Expand the value and pass it to the shell for execution and assign the result to the variable. Any newlines in the result are replaced with spaces. .El .Pp Any white-space before the assigned .Ar value is removed; if the value is being appended, a single space is inserted between the previous contents of the variable and the appended value. .Pp Variables are expanded by surrounding the variable name with either curly braces .Pq Ql {} or parentheses .Pq Ql () and preceding it with a dollar sign .Pq Ql \&$ . If the variable name contains only a single letter, the surrounding braces or parentheses are not required. This shorter form is not recommended. .Pp If the variable name contains a dollar, then the name itself is expanded first. This allows almost arbitrary variable names, however names containing dollar, braces, parenthesis, or whitespace are really best avoided! .Pp If the result of expanding a variable contains a dollar sign .Pq Ql \&$ the string is expanded again. .Pp Variable substitution occurs at three distinct times, depending on where the variable is being used. .Bl -enum .It Variables in dependency lines are expanded as the line is read. .It Variables in shell commands are expanded when the shell command is executed. .It .Dq .for loop index variables are expanded on each loop iteration. Note that other variables are not expanded inside loops so the following example code: .Bd -literal -offset indent .Dv .for i in 1 2 3 a+= ${i} j= ${i} b+= ${j} .Dv .endfor all: @echo ${a} @echo ${b} .Ed will print: .Bd -literal -offset indent 1 2 3 3 3 3 .Ed Because while ${a} contains .Dq 1 2 3 after the loop is executed, ${b} contains .Dq ${j} ${j} ${j} which expands to .Dq 3 3 3 since after the loop completes ${j} contains .Dq 3 . .El .Ss Variable classes The four different classes of variables (in order of increasing precedence) are: .Bl -tag -width Ds .It Environment variables Variables defined as part of .Nm Ns 's environment. .It Global variables Variables defined in the makefile or in included makefiles. .It Command line variables Variables defined as part of the command line. .It Local variables Variables that are defined specific to a certain target. .El .Pp Local variables are all built in and their values vary magically from target to target. It is not currently possible to define new local variables. The seven local variables are as follows: .Bl -tag -width ".ARCHIVE" -offset indent .It Va .ALLSRC The list of all sources for this target; also known as .Ql Va \&> . .It Va .ARCHIVE The name of the archive file; also known as .Ql Va \&! . .It Va .IMPSRC In suffix-transformation rules, the name/path of the source from which the target is to be transformed (the .Dq implied source); also known as .Ql Va \&< . It is not defined in explicit rules. .It Va .MEMBER The name of the archive member; also known as .Ql Va % . .It Va .OODATE The list of sources for this target that were deemed out-of-date; also known as .Ql Va \&? . .It Va .PREFIX The file prefix of the target, containing only the file portion, no suffix or preceding directory components; also known as .Ql Va * . The suffix must be one of the known suffixes declared with .Ic .SUFFIXES or it will not be recognized. .It Va .TARGET The name of the target; also known as .Ql Va @ . For compatibility with other makes this is an alias for .Ic .ARCHIVE in archive member rules. .El .Pp The shorter forms .Ql ( Va > , .Ql Va \&! , .Ql Va < , .Ql Va % , .Ql Va \&? , .Ql Va * , and .Ql Va @ ) are permitted for backward compatibility with historical makefiles and legacy POSIX make and are not recommended. .Pp Variants of these variables with the punctuation followed immediately by .Ql D or .Ql F , e.g. .Ql Va $(@D) , are legacy forms equivalent to using the .Ql :H and .Ql :T modifiers. These forms are accepted for compatibility with .At V makefiles and POSIX but are not recommended. .Pp Four of the local variables may be used in sources on dependency lines because they expand to the proper value for each target on the line. These variables are .Ql Va .TARGET , .Ql Va .PREFIX , .Ql Va .ARCHIVE , and .Ql Va .MEMBER . .Ss Additional built-in variables In addition, .Nm sets or knows about the following variables: .Bl -tag -width .MAKEOVERRIDES .It Va \&$ A single dollar sign .Ql \&$ , i.e. .Ql \&$$ expands to a single dollar sign. .It Va .ALLTARGETS The list of all targets encountered in the Makefile. If evaluated during Makefile parsing, lists only those targets encountered thus far. .It Va .CURDIR A path to the directory where .Nm was executed. Refer to the description of .Ql Ev PWD for more details. .It Va .INCLUDEDFROMDIR The directory of the file this Makefile was included from. .It Va .INCLUDEDFROMFILE The filename of the file this Makefile was included from. .It Ev MAKE The name that .Nm was executed with .Pq Va argv[0] . For compatibility .Nm also sets .Va .MAKE with the same value. The preferred variable to use is the environment variable .Ev MAKE because it is more compatible with other versions of .Nm and cannot be confused with the special target with the same name. .It Va .MAKE.ALWAYS_PASS_JOB_QUEUE Tells .Nm whether to pass the descriptors of the job token queue even if the target is not tagged with .Ic .MAKE The default is .Ql Pa yes for backwards compatability with .Fx 9.0 and earlier. .It Va .MAKE.DEPENDFILE Names the makefile (default .Ql Pa .depend ) from which generated dependencies are read. .It Va .MAKE.EXPAND_VARIABLES A boolean that controls the default behavior of the .Fl V option. If true, variable values printed with .Fl V are fully expanded; if false, the raw variable contents (which may include additional unexpanded variable references) are shown. .It Va .MAKE.EXPORTED The list of variables exported by .Nm . .It Va .MAKE.JOBS The argument to the .Fl j option. .It Va .MAKE.JOB.PREFIX If .Nm is run with .Ar j then output for each target is prefixed with a token .Ql --- target --- the first part of which can be controlled via .Va .MAKE.JOB.PREFIX . If .Va .MAKE.JOB.PREFIX is empty, no token is printed. .br For example: .Li .MAKE.JOB.PREFIX=${.newline}---${.MAKE:T}[${.MAKE.PID}] would produce tokens like .Ql ---make[1234] target --- making it easier to track the degree of parallelism being achieved. .It Ev MAKEFLAGS The environment variable .Ql Ev MAKEFLAGS may contain anything that may be specified on .Nm Ns 's command line. Anything specified on .Nm Ns 's command line is appended to the .Ql Ev MAKEFLAGS variable which is then entered into the environment for all programs which .Nm executes. .It Va .MAKE.LEVEL The recursion depth of .Nm . The initial instance of .Nm will be 0, and an incremented value is put into the environment to be seen by the next generation. This allows tests like: .Li .if ${.MAKE.LEVEL} == 0 to protect things which should only be evaluated in the initial instance of .Nm . .It Va .MAKE.MAKEFILE_PREFERENCE The ordered list of makefile names (default .Ql Pa makefile , .Ql Pa Makefile ) that .Nm will look for. .It Va .MAKE.MAKEFILES The list of makefiles read by .Nm , which is useful for tracking dependencies. Each makefile is recorded only once, regardless of the number of times read. .It Va .MAKE.MODE Processed after reading all makefiles. Can affect the mode that .Nm runs in. It can contain a number of keywords: .Bl -hang -width missing-filemon=bf. .It Pa compat Like .Fl B , puts .Nm into "compat" mode. .It Pa meta Puts .Nm into "meta" mode, where meta files are created for each target to capture the command run, the output generated and if .Xr filemon 4 is available, the system calls which are of interest to .Nm . The captured output can be very useful when diagnosing errors. .It Pa curdirOk= Ar bf Normally .Nm will not create .meta files in .Ql Va .CURDIR . This can be overridden by setting .Va bf to a value which represents True. .It Pa missing-meta= Ar bf If .Va bf is True, then a missing .meta file makes the target out-of-date. .It Pa missing-filemon= Ar bf If .Va bf is True, then missing filemon data makes the target out-of-date. .It Pa nofilemon Do not use .Xr filemon 4 . .It Pa env For debugging, it can be useful to include the environment in the .meta file. .It Pa verbose If in "meta" mode, print a clue about the target being built. This is useful if the build is otherwise running silently. The message printed the value of: .Va .MAKE.META.PREFIX . .It Pa ignore-cmd Some makefiles have commands which are simply not stable. This keyword causes them to be ignored for determining whether a target is out of date in "meta" mode. See also .Ic .NOMETA_CMP . .It Pa silent= Ar bf If .Va bf is True, when a .meta file is created, mark the target .Ic .SILENT . .El .It Va .MAKE.META.BAILIWICK In "meta" mode, provides a list of prefixes which match the directories controlled by .Nm . If a file that was generated outside of .Va .OBJDIR but within said bailiwick is missing, the current target is considered out-of-date. .It Va .MAKE.META.CREATED In "meta" mode, this variable contains a list of all the meta files updated. If not empty, it can be used to trigger processing of .Va .MAKE.META.FILES . .It Va .MAKE.META.FILES In "meta" mode, this variable contains a list of all the meta files used (updated or not). This list can be used to process the meta files to extract dependency information. .It Va .MAKE.META.IGNORE_PATHS Provides a list of path prefixes that should be ignored; because the contents are expected to change over time. The default list includes: .Ql Pa /dev /etc /proc /tmp /var/run /var/tmp .It Va .MAKE.META.IGNORE_PATTERNS Provides a list of patterns to match against pathnames. Ignore any that match. .It Va .MAKE.META.IGNORE_FILTER Provides a list of variable modifiers to apply to each pathname. Ignore if the expansion is an empty string. .It Va .MAKE.META.PREFIX Defines the message printed for each meta file updated in "meta verbose" mode. The default value is: .Dl Building ${.TARGET:H:tA}/${.TARGET:T} .It Va .MAKEOVERRIDES This variable is used to record the names of variables assigned to on the command line, so that they may be exported as part of .Ql Ev MAKEFLAGS . This behavior can be disabled by assigning an empty value to .Ql Va .MAKEOVERRIDES within a makefile. Extra variables can be exported from a makefile by appending their names to .Ql Va .MAKEOVERRIDES . .Ql Ev MAKEFLAGS is re-exported whenever .Ql Va .MAKEOVERRIDES is modified. .It Va .MAKE.PATH_FILEMON If .Nm was built with .Xr filemon 4 support, this is set to the path of the device node. This allows makefiles to test for this support. .It Va .MAKE.PID The process-id of .Nm . .It Va .MAKE.PPID The parent process-id of .Nm . .It Va .MAKE.SAVE_DOLLARS value should be a boolean that controls whether .Ql $$ are preserved when doing .Ql := assignments. The default is false, for backwards compatibility. Set to true for compatability with other makes. If set to false, .Ql $$ becomes .Ql $ per normal evaluation rules. .It Va MAKE_PRINT_VAR_ON_ERROR When .Nm stops due to an error, it sets .Ql Va .ERROR_TARGET to the name of the target that failed, .Ql Va .ERROR_CMD to the commands of the failed target, and in "meta" mode, it also sets .Ql Va .ERROR_CWD to the .Xr getcwd 3 , and .Ql Va .ERROR_META_FILE to the path of the meta file (if any) describing the failed target. It then prints its name and the value of .Ql Va .CURDIR as well as the value of any variables named in .Ql Va MAKE_PRINT_VAR_ON_ERROR . .It Va .newline This variable is simply assigned a newline character as its value. This allows expansions using the .Cm \&:@ modifier to put a newline between iterations of the loop rather than a space. For example, the printing of .Ql Va MAKE_PRINT_VAR_ON_ERROR could be done as ${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'${.newline}@}. .It Va .OBJDIR A path to the directory where the targets are built. Its value is determined by trying to .Xr chdir 2 to the following directories in order and using the first match: .Bl -enum .It .Ev ${MAKEOBJDIRPREFIX}${.CURDIR} .Pp (Only if .Ql Ev MAKEOBJDIRPREFIX is set in the environment or on the command line.) .It .Ev ${MAKEOBJDIR} .Pp (Only if .Ql Ev MAKEOBJDIR is set in the environment or on the command line.) .It .Ev ${.CURDIR} Ns Pa /obj. Ns Ev ${MACHINE} .It .Ev ${.CURDIR} Ns Pa /obj .It .Pa /usr/obj/ Ns Ev ${.CURDIR} .It .Ev ${.CURDIR} .El .Pp Variable expansion is performed on the value before it's used, so expressions such as .Dl ${.CURDIR:S,^/usr/src,/var/obj,} may be used. This is especially useful with .Ql Ev MAKEOBJDIR . .Pp .Ql Va .OBJDIR may be modified in the makefile via the special target .Ql Ic .OBJDIR . In all cases, .Nm will .Xr chdir 2 to the specified directory if it exists, and set .Ql Va .OBJDIR and .Ql Ev PWD to that directory before executing any targets. . .It Va .PARSEDIR A path to the directory of the current .Ql Pa Makefile being parsed. .It Va .PARSEFILE The basename of the current .Ql Pa Makefile being parsed. This variable and .Ql Va .PARSEDIR are both set only while the .Ql Pa Makefiles are being parsed. If you want to retain their current values, assign them to a variable using assignment with expansion: .Pq Ql Cm \&:= . .It Va .PATH A variable that represents the list of directories that .Nm will search for files. The search list should be updated using the target .Ql Va .PATH rather than the variable. .It Ev PWD Alternate path to the current directory. .Nm normally sets .Ql Va .CURDIR to the canonical path given by .Xr getcwd 3 . However, if the environment variable .Ql Ev PWD is set and gives a path to the current directory, then .Nm sets .Ql Va .CURDIR to the value of .Ql Ev PWD instead. This behavior is disabled if .Ql Ev MAKEOBJDIRPREFIX is set or .Ql Ev MAKEOBJDIR contains a variable transform. .Ql Ev PWD is set to the value of .Ql Va .OBJDIR for all programs which .Nm executes. .It Ev .TARGETS The list of targets explicitly specified on the command line, if any. .It Ev VPATH Colon-separated .Pq Dq \&: lists of directories that .Nm will search for files. The variable is supported for compatibility with old make programs only, use .Ql Va .PATH instead. .El .Ss Variable modifiers Variable expansion may be modified to select or modify each word of the variable (where a .Dq word is white-space delimited sequence of characters). The general format of a variable expansion is as follows: .Pp .Dl ${variable[:modifier[:...]]} .Pp Each modifier begins with a colon, which may be escaped with a backslash .Pq Ql \e . .Pp A set of modifiers can be specified via a variable, as follows: .Pp .Dl modifier_variable=modifier[:...] .Dl ${variable:${modifier_variable}[:...]} .Pp In this case the first modifier in the modifier_variable does not start with a colon, since that must appear in the referencing variable. If any of the modifiers in the modifier_variable contain a dollar sign .Pq Ql $ , these must be doubled to avoid early expansion. .Pp The supported modifiers are: .Bl -tag -width EEE .It Cm \&:E Replaces each word in the variable with its suffix. .It Cm \&:H Replaces each word in the variable with everything but the last component. .It Cm \&:M Ns Ar pattern Select only those words that match .Ar pattern . The standard shell wildcard characters .Pf ( Ql * , .Ql \&? , and .Ql Oo Oc ) may be used. The wildcard characters may be escaped with a backslash .Pq Ql \e . As a consequence of the way values are split into words, matched, and then joined, a construct like .Dl ${VAR:M*} will normalize the inter-word spacing, removing all leading and trailing space, and converting multiple consecutive spaces to single spaces. . .It Cm \&:N Ns Ar pattern This is identical to .Ql Cm \&:M , but selects all words which do not match .Ar pattern . .It Cm \&:O Order every word in variable alphabetically. To sort words in reverse order use the .Ql Cm \&:O:[-1..1] combination of modifiers. .It Cm \&:Ox Randomize words in variable. The results will be different each time you are referring to the modified variable; use the assignment with expansion .Pq Ql Cm \&:= to prevent such behavior. For example, .Bd -literal -offset indent LIST= uno due tre quattro RANDOM_LIST= ${LIST:Ox} STATIC_RANDOM_LIST:= ${LIST:Ox} all: @echo "${RANDOM_LIST}" @echo "${RANDOM_LIST}" @echo "${STATIC_RANDOM_LIST}" @echo "${STATIC_RANDOM_LIST}" .Ed may produce output similar to: .Bd -literal -offset indent quattro due tre uno tre due quattro uno due uno quattro tre due uno quattro tre .Ed .It Cm \&:Q Quotes every shell meta-character in the variable, so that it can be passed +safely to the shell. +.It Cm \&:q +Quotes every shell meta-character in the variable, and also doubles +.Sq $ +characters so that it can be passed safely through recursive invocations of .Nm . +This is equivalent to: +.Sq \&:S/\e\&$/&&/g:Q . .It Cm \&:R Replaces each word in the variable with everything but its suffix. .It Cm \&:range[=count] The value is an integer sequence representing the words of the original value, or the supplied .Va count . .It Cm \&:gmtime[=utc] The value is a format string for .Xr strftime 3 , using .Xr gmtime 3 . If a .Va utc value is not provided or is 0, the current time is used. .It Cm \&:hash Compute a 32-bit hash of the value and encode it as hex digits. .It Cm \&:localtime[=utc] The value is a format string for .Xr strftime 3 , using .Xr localtime 3 . If a .Va utc value is not provided or is 0, the current time is used. .It Cm \&:tA Attempt to convert variable to an absolute path using .Xr realpath 3 , if that fails, the value is unchanged. .It Cm \&:tl Converts variable to lower-case letters. .It Cm \&:ts Ns Ar c Words in the variable are normally separated by a space on expansion. This modifier sets the separator to the character .Ar c . If .Ar c is omitted, then no separator is used. The common escapes (including octal numeric codes), work as expected. .It Cm \&:tu Converts variable to upper-case letters. .It Cm \&:tW Causes the value to be treated as a single word (possibly containing embedded white space). See also .Ql Cm \&:[*] . .It Cm \&:tw Causes the value to be treated as a sequence of words delimited by white space. See also .Ql Cm \&:[@] . .Sm off .It Cm \&:S No \&/ Ar old_string No \&/ Ar new_string No \&/ Op Cm 1gW .Sm on Modify the first occurrence of .Ar old_string in the variable's value, replacing it with .Ar new_string . If a .Ql g is appended to the last slash of the pattern, all occurrences in each word are replaced. If a .Ql 1 is appended to the last slash of the pattern, only the first word is affected. If a .Ql W is appended to the last slash of the pattern, then the value is treated as a single word (possibly containing embedded white space). If .Ar old_string begins with a caret .Pq Ql ^ , .Ar old_string is anchored at the beginning of each word. If .Ar old_string ends with a dollar sign .Pq Ql \&$ , it is anchored at the end of each word. Inside .Ar new_string , an ampersand .Pq Ql & is replaced by .Ar old_string (without any .Ql ^ or .Ql \&$ ) . Any character may be used as a delimiter for the parts of the modifier string. The anchoring, ampersand and delimiter characters may be escaped with a backslash .Pq Ql \e . .Pp Variable expansion occurs in the normal fashion inside both .Ar old_string and .Ar new_string with the single exception that a backslash is used to prevent the expansion of a dollar sign .Pq Ql \&$ , not a preceding dollar sign as is usual. .Sm off .It Cm \&:C No \&/ Ar pattern No \&/ Ar replacement No \&/ Op Cm 1gW .Sm on The .Cm \&:C modifier is just like the .Cm \&:S modifier except that the old and new strings, instead of being simple strings, are an extended regular expression (see .Xr regex 3 ) string .Ar pattern and an .Xr ed 1 Ns \-style string .Ar replacement . Normally, the first occurrence of the pattern .Ar pattern in each word of the value is substituted with .Ar replacement . The .Ql 1 modifier causes the substitution to apply to at most one word; the .Ql g modifier causes the substitution to apply to as many instances of the search pattern .Ar pattern as occur in the word or words it is found in; the .Ql W modifier causes the value to be treated as a single word (possibly containing embedded white space). Note that .Ql 1 and .Ql g are orthogonal; the former specifies whether multiple words are potentially affected, the latter whether multiple substitutions can potentially occur within each affected word. .Pp As for the .Cm \&:S modifier, the .Ar pattern and .Ar replacement are subjected to variable expansion before being parsed as regular expressions. .It Cm \&:T Replaces each word in the variable with its last component. .It Cm \&:u Remove adjacent duplicate words (like .Xr uniq 1 ) . .Sm off .It Cm \&:\&? Ar true_string Cm \&: Ar false_string .Sm on If the variable name (not its value), when parsed as a .if conditional expression, evaluates to true, return as its value the .Ar true_string , otherwise return the .Ar false_string . Since the variable name is used as the expression, \&:\&? must be the first modifier after the variable name itself - which will, of course, usually contain variable expansions. A common error is trying to use expressions like .Dl ${NUMBERS:M42:?match:no} which actually tests defined(NUMBERS), to determine is any words match "42" you need to use something like: .Dl ${"${NUMBERS:M42}" != \&"\&":?match:no} . .It Ar :old_string=new_string This is the .At V style variable substitution. It must be the last modifier specified. If .Ar old_string or .Ar new_string do not contain the pattern matching character .Ar % then it is assumed that they are anchored at the end of each word, so only suffixes or entire words may be replaced. Otherwise .Ar % is the substring of .Ar old_string to be replaced in .Ar new_string . +If only +.Ar old_string +contains the pattern matching character +.Ar % , +and +.Ar old_string +matches, then the result is the +.Ar new_string . +If only the +.Ar new_string +contains the pattern matching character +.Ar % , +then it is not treated specially and it is printed as a literal +.Ar % +on match. +If there is more than one pattern matching character +.Ar ( % ) +in either the +.Ar new_string +or +.Ar old_string , +only the first instance is treated specially (as the pattern character); +all subsequent instances are treated as regular characters .Pp Variable expansion occurs in the normal fashion inside both .Ar old_string and .Ar new_string with the single exception that a backslash is used to prevent the expansion of a dollar sign .Pq Ql \&$ , not a preceding dollar sign as is usual. .Sm off .It Cm \&:@ Ar temp Cm @ Ar string Cm @ .Sm on This is the loop expansion mechanism from the OSF Development Environment (ODE) make. Unlike .Cm \&.for loops expansion occurs at the time of reference. Assign .Ar temp to each word in the variable and evaluate .Ar string . The ODE convention is that .Ar temp should start and end with a period. For example. .Dl ${LINKS:@.LINK.@${LN} ${TARGET} ${.LINK.}@} .Pp However a single character variable is often more readable: .Dl ${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'${.newline}@} .It Cm \&:_[=var] Save the current variable value in .Ql $_ or the named .Va var for later reference. Example usage: .Bd -literal -offset indent M_cmpv.units = 1 1000 1000000 M_cmpv = S,., ,g:_:range:@i@+ $${_:[-$$i]} \&\\ \\* $${M_cmpv.units:[$$i]}@:S,^,expr 0 ,1:sh .Dv .if ${VERSION:${M_cmpv}} < ${3.1.12:L:${M_cmpv}} .Ed Here .Ql $_ is used to save the result of the .Ql :S modifier which is later referenced using the index values from .Ql :range . .It Cm \&:U Ns Ar newval If the variable is undefined .Ar newval is the value. If the variable is defined, the existing value is returned. This is another ODE make feature. It is handy for setting per-target CFLAGS for instance: .Dl ${_${.TARGET:T}_CFLAGS:U${DEF_CFLAGS}} If a value is only required if the variable is undefined, use: .Dl ${VAR:D:Unewval} .It Cm \&:D Ns Ar newval If the variable is defined .Ar newval is the value. .It Cm \&:L The name of the variable is the value. .It Cm \&:P The path of the node which has the same name as the variable is the value. If no such node exists or its path is null, then the name of the variable is used. In order for this modifier to work, the name (node) must at least have appeared on the rhs of a dependency. .Sm off .It Cm \&:\&! Ar cmd Cm \&! .Sm on The output of running .Ar cmd is the value. .It Cm \&:sh If the variable is non-empty it is run as a command and the output becomes the new value. .It Cm \&::= Ns Ar str The variable is assigned the value .Ar str after substitution. This modifier and its variations are useful in obscure situations such as wanting to set a variable when shell commands are being parsed. These assignment modifiers always expand to nothing, so if appearing in a rule line by themselves should be preceded with something to keep .Nm happy. .Pp The .Ql Cm \&:: helps avoid false matches with the .At V style .Cm \&:= modifier and since substitution always occurs the .Cm \&::= form is vaguely appropriate. .It Cm \&::?= Ns Ar str As for .Cm \&::= but only if the variable does not already have a value. .It Cm \&::+= Ns Ar str Append .Ar str to the variable. .It Cm \&::!= Ns Ar cmd Assign the output of .Ar cmd to the variable. .It Cm \&:\&[ Ns Ar range Ns Cm \&] Selects one or more words from the value, or performs other operations related to the way in which the value is divided into words. .Pp Ordinarily, a value is treated as a sequence of words delimited by white space. Some modifiers suppress this behavior, causing a value to be treated as a single word (possibly containing embedded white space). An empty value, or a value that consists entirely of white-space, is treated as a single word. For the purposes of the .Ql Cm \&:[] modifier, the words are indexed both forwards using positive integers (where index 1 represents the first word), and backwards using negative integers (where index \-1 represents the last word). .Pp The .Ar range is subjected to variable expansion, and the expanded result is then interpreted as follows: .Bl -tag -width index .\" :[n] .It Ar index Selects a single word from the value. .\" :[start..end] .It Ar start Ns Cm \&.. Ns Ar end Selects all words from .Ar start to .Ar end , inclusive. For example, .Ql Cm \&:[2..-1] selects all words from the second word to the last word. If .Ar start is greater than .Ar end , then the words are output in reverse order. For example, .Ql Cm \&:[-1..1] selects all the words from last to first. .\" :[*] .It Cm \&* Causes subsequent modifiers to treat the value as a single word (possibly containing embedded white space). Analogous to the effect of \&"$*\&" in Bourne shell. .\" :[0] .It 0 Means the same as .Ql Cm \&:[*] . .\" :[*] .It Cm \&@ Causes subsequent modifiers to treat the value as a sequence of words delimited by white space. Analogous to the effect of \&"$@\&" in Bourne shell. .\" :[#] .It Cm \&# Returns the number of words in the value. .El \" :[range] .El .Sh INCLUDE STATEMENTS, CONDITIONALS AND FOR LOOPS Makefile inclusion, conditional structures and for loops reminiscent of the C programming language are provided in .Nm . All such structures are identified by a line beginning with a single dot .Pq Ql \&. character. Files are included with either -.Cm \&.include Aq Ar file +.Cm \&.include \&< Ns Ar file Ns Cm \&> or -.Cm \&.include Pf \*q Ar file Ns \*q . +.Cm \&.include \&\*q Ns Ar file Ns Cm \&\*q . Variables between the angle brackets or double quotes are expanded to form the file name. If angle brackets are used, the included makefile is expected to be in the system makefile directory. If double quotes are used, the including makefile's directory and any directories specified using the .Fl I option are searched before the system makefile directory. For compatibility with other versions of .Nm .Ql include file ... is also accepted. .Pp If the include statement is written as .Cm .-include or as .Cm .sinclude then errors locating and/or opening include files are ignored. .Pp If the include statement is written as .Cm .dinclude not only are errors locating and/or opening include files ignored, but stale dependencies within the included file will be ignored just like .Va .MAKE.DEPENDFILE . .Pp Conditional expressions are also preceded by a single dot as the first character of a line. The possible conditionals are as follows: .Bl -tag -width Ds .It Ic .error Ar message The message is printed along with the name of the makefile and line number, then .Nm will exit. .It Ic .export Ar variable ... Export the specified global variable. If no variable list is provided, all globals are exported except for internal variables (those that start with .Ql \&. ) . This is not affected by the .Fl X flag, so should be used with caution. For compatibility with other .Nm programs .Ql export variable=value is also accepted. .Pp Appending a variable name to .Va .MAKE.EXPORTED is equivalent to exporting a variable. .It Ic .export-env Ar variable ... The same as .Ql .export , except that the variable is not appended to .Va .MAKE.EXPORTED . This allows exporting a value to the environment which is different from that used by .Nm internally. .It Ic .export-literal Ar variable ... The same as .Ql .export-env , except that variables in the value are not expanded. .It Ic .info Ar message The message is printed along with the name of the makefile and line number. .It Ic .undef Ar variable Un-define the specified global variable. Only global variables may be un-defined. .It Ic .unexport Ar variable ... The opposite of .Ql .export . The specified global .Va variable will be removed from .Va .MAKE.EXPORTED . If no variable list is provided, all globals are unexported, and .Va .MAKE.EXPORTED deleted. .It Ic .unexport-env Unexport all globals previously exported and clear the environment inherited from the parent. This operation will cause a memory leak of the original environment, so should be used sparingly. Testing for .Va .MAKE.LEVEL being 0, would make sense. Also note that any variables which originated in the parent environment should be explicitly preserved if desired. For example: .Bd -literal -offset indent .Li .if ${.MAKE.LEVEL} == 0 PATH := ${PATH} .Li .unexport-env .Li .export PATH .Li .endif .Pp .Ed Would result in an environment containing only .Ql Ev PATH , which is the minimal useful environment. Actually .Ql Ev .MAKE.LEVEL will also be pushed into the new environment. .It Ic .warning Ar message The message prefixed by .Ql Pa warning: is printed along with the name of the makefile and line number. .It Ic \&.if Oo \&! Oc Ns Ar expression Op Ar operator expression ... Test the value of an expression. .It Ic .ifdef Oo \&! Oc Ns Ar variable Op Ar operator variable ... Test the value of a variable. .It Ic .ifndef Oo \&! Oc Ns Ar variable Op Ar operator variable ... Test the value of a variable. .It Ic .ifmake Oo \&! Oc Ns Ar target Op Ar operator target ... Test the target being built. .It Ic .ifnmake Oo \&! Ns Oc Ar target Op Ar operator target ... Test the target being built. .It Ic .else Reverse the sense of the last conditional. .It Ic .elif Oo \&! Ns Oc Ar expression Op Ar operator expression ... A combination of .Ql Ic .else followed by .Ql Ic .if . .It Ic .elifdef Oo \&! Oc Ns Ar variable Op Ar operator variable ... A combination of .Ql Ic .else followed by .Ql Ic .ifdef . .It Ic .elifndef Oo \&! Oc Ns Ar variable Op Ar operator variable ... A combination of .Ql Ic .else followed by .Ql Ic .ifndef . .It Ic .elifmake Oo \&! Oc Ns Ar target Op Ar operator target ... A combination of .Ql Ic .else followed by .Ql Ic .ifmake . .It Ic .elifnmake Oo \&! Oc Ns Ar target Op Ar operator target ... A combination of .Ql Ic .else followed by .Ql Ic .ifnmake . .It Ic .endif End the body of the conditional. .El .Pp The .Ar operator may be any one of the following: .Bl -tag -width "Cm XX" .It Cm \&|\&| Logical OR. .It Cm \&&& Logical .Tn AND ; of higher precedence than .Dq \&|\&| . .El .Pp As in C, .Nm will only evaluate a conditional as far as is necessary to determine its value. Parentheses may be used to change the order of evaluation. The boolean operator .Ql Ic \&! may be used to logically negate an entire conditional. It is of higher precedence than .Ql Ic \&&& . .Pp The value of .Ar expression may be any of the following: .Bl -tag -width defined .It Ic defined Takes a variable name as an argument and evaluates to true if the variable has been defined. .It Ic make Takes a target name as an argument and evaluates to true if the target was specified as part of .Nm Ns 's command line or was declared the default target (either implicitly or explicitly, see .Va .MAIN ) before the line containing the conditional. .It Ic empty Takes a variable, with possible modifiers, and evaluates to true if the expansion of the variable would result in an empty string. .It Ic exists Takes a file name as an argument and evaluates to true if the file exists. The file is searched for on the system search path (see .Va .PATH ) . .It Ic target Takes a target name as an argument and evaluates to true if the target has been defined. .It Ic commands Takes a target name as an argument and evaluates to true if the target has been defined and has commands associated with it. .El .Pp .Ar Expression may also be an arithmetic or string comparison. Variable expansion is performed on both sides of the comparison, after which the integral values are compared. A value is interpreted as hexadecimal if it is preceded by 0x, otherwise it is decimal; octal numbers are not supported. The standard C relational operators are all supported. If after variable expansion, either the left or right hand side of a .Ql Ic == or .Ql Ic "!=" operator is not an integral value, then string comparison is performed between the expanded variables. If no relational operator is given, it is assumed that the expanded variable is being compared against 0 or an empty string in the case of a string comparison. .Pp When .Nm is evaluating one of these conditional expressions, and it encounters a (white-space separated) word it doesn't recognize, either the .Dq make or .Dq defined expression is applied to it, depending on the form of the conditional. If the form is .Ql Ic .ifdef , .Ql Ic .ifndef , or .Ql Ic .if the .Dq defined expression is applied. Similarly, if the form is .Ql Ic .ifmake or .Ql Ic .ifnmake , the .Dq make expression is applied. .Pp If the conditional evaluates to true the parsing of the makefile continues as before. If it evaluates to false, the following lines are skipped. In both cases this continues until a .Ql Ic .else or .Ql Ic .endif is found. .Pp For loops are typically used to apply a set of rules to a list of files. The syntax of a for loop is: .Pp .Bl -tag -compact -width Ds .It Ic \&.for Ar variable Oo Ar variable ... Oc Ic in Ar expression .It Aq make-rules .It Ic \&.endfor .El .Pp After the for .Ic expression is evaluated, it is split into words. On each iteration of the loop, one word is taken and assigned to each .Ic variable , in order, and these .Ic variables are substituted into the .Ic make-rules inside the body of the for loop. The number of words must come out even; that is, if there are three iteration variables, the number of words provided must be a multiple of three. .Sh COMMENTS Comments begin with a hash .Pq Ql \&# character, anywhere but in a shell command line, and continue to the end of an unescaped new line. .Sh SPECIAL SOURCES (ATTRIBUTES) .Bl -tag -width .IGNOREx .It Ic .EXEC Target is never out of date, but always execute commands anyway. .It Ic .IGNORE Ignore any errors from the commands associated with this target, exactly as if they all were preceded by a dash .Pq Ql \- . .\" .It Ic .INVISIBLE .\" XXX .\" .It Ic .JOIN .\" XXX .It Ic .MADE Mark all sources of this target as being up-to-date. .It Ic .MAKE Execute the commands associated with this target even if the .Fl n or .Fl t options were specified. Normally used to mark recursive .Nm Ns s . .It Ic .META Create a meta file for the target, even if it is flagged as .Ic .PHONY , .Ic .MAKE , or .Ic .SPECIAL . Usage in conjunction with .Ic .MAKE is the most likely case. In "meta" mode, the target is out-of-date if the meta file is missing. .It Ic .NOMETA Do not create a meta file for the target. Meta files are also not created for .Ic .PHONY , .Ic .MAKE , or .Ic .SPECIAL targets. .It Ic .NOMETA_CMP Ignore differences in commands when deciding if target is out of date. This is useful if the command contains a value which always changes. If the number of commands change, though, the target will still be out of date. The same effect applies to any command line that uses the variable .Va .OODATE , which can be used for that purpose even when not otherwise needed or desired: .Bd -literal -offset indent skip-compare-for-some: @echo this will be compared @echo this will not ${.OODATE:M.NOMETA_CMP} @echo this will also be compared .Ed The .Cm \&:M pattern suppresses any expansion of the unwanted variable. .It Ic .NOPATH Do not search for the target in the directories specified by .Ic .PATH . .It Ic .NOTMAIN Normally .Nm selects the first target it encounters as the default target to be built if no target was specified. This source prevents this target from being selected. .It Ic .OPTIONAL If a target is marked with this attribute and .Nm can't figure out how to create it, it will ignore this fact and assume the file isn't needed or already exists. .It Ic .PHONY The target does not correspond to an actual file; it is always considered to be out of date, and will not be created with the .Fl t option. Suffix-transformation rules are not applied to .Ic .PHONY targets. .It Ic .PRECIOUS When .Nm is interrupted, it normally removes any partially made targets. This source prevents the target from being removed. .It Ic .RECURSIVE Synonym for .Ic .MAKE . .It Ic .SILENT Do not echo any of the commands associated with this target, exactly as if they all were preceded by an at sign .Pq Ql @ . .It Ic .USE Turn the target into .Nm Ns 's version of a macro. When the target is used as a source for another target, the other target acquires the commands, sources, and attributes (except for .Ic .USE ) of the source. If the target already has commands, the .Ic .USE target's commands are appended to them. .It Ic .USEBEFORE Exactly like .Ic .USE , but prepend the .Ic .USEBEFORE target commands to the target. .It Ic .WAIT If .Ic .WAIT appears in a dependency line, the sources that precede it are made before the sources that succeed it in the line. Since the dependents of files are not made until the file itself could be made, this also stops the dependents being built unless they are needed for another branch of the dependency tree. So given: .Bd -literal x: a .WAIT b echo x a: echo a b: b1 echo b b1: echo b1 .Ed the output is always .Ql a , .Ql b1 , .Ql b , .Ql x . .br The ordering imposed by .Ic .WAIT is only relevant for parallel makes. .El .Sh SPECIAL TARGETS Special targets may not be included with other targets, i.e. they must be the only target specified. .Bl -tag -width .BEGINx .It Ic .BEGIN Any command lines attached to this target are executed before anything else is done. .It Ic .DEFAULT This is sort of a .Ic .USE rule for any target (that was used only as a source) that .Nm can't figure out any other way to create. Only the shell script is used. The .Ic .IMPSRC variable of a target that inherits .Ic .DEFAULT Ns 's commands is set to the target's own name. .It Ic .DELETE_ON_ERROR If this target is present in the makefile, it globally causes make to delete targets whose commands fail. (By default, only targets whose commands are interrupted during execution are deleted. This is the historical behavior.) This setting can be used to help prevent half-finished or malformed targets from being left around and corrupting future rebuilds. .It Ic .END Any command lines attached to this target are executed after everything else is done. .It Ic .ERROR Any command lines attached to this target are executed when another target fails. The .Ic .ERROR_TARGET variable is set to the target that failed. See also .Ic MAKE_PRINT_VAR_ON_ERROR . .It Ic .IGNORE Mark each of the sources with the .Ic .IGNORE attribute. If no sources are specified, this is the equivalent of specifying the .Fl i option. .It Ic .INTERRUPT If .Nm is interrupted, the commands for this target will be executed. .It Ic .MAIN If no target is specified when .Nm is invoked, this target will be built. .It Ic .MAKEFLAGS This target provides a way to specify flags for .Nm when the makefile is used. The flags are as if typed to the shell, though the .Fl f option will have no effect. .\" XXX: NOT YET!!!! .\" .It Ic .NOTPARALLEL .\" The named targets are executed in non parallel mode. .\" If no targets are .\" specified, then all targets are executed in non parallel mode. .It Ic .NOPATH Apply the .Ic .NOPATH attribute to any specified sources. .It Ic .NOTPARALLEL Disable parallel mode. .It Ic .NO_PARALLEL Synonym for .Ic .NOTPARALLEL , for compatibility with other pmake variants. .It Ic .OBJDIR The source is a new value for .Ql Va .OBJDIR . If it exists, .Nm will .Xr chdir 2 to it and update the value of .Ql Va .OBJDIR . .It Ic .ORDER The named targets are made in sequence. This ordering does not add targets to the list of targets to be made. Since the dependents of a target do not get built until the target itself could be built, unless .Ql a is built by another part of the dependency graph, the following is a dependency loop: .Bd -literal \&.ORDER: b a b: a .Ed .Pp The ordering imposed by .Ic .ORDER is only relevant for parallel makes. .\" XXX: NOT YET!!!! .\" .It Ic .PARALLEL .\" The named targets are executed in parallel mode. .\" If no targets are .\" specified, then all targets are executed in parallel mode. .It Ic .PATH The sources are directories which are to be searched for files not found in the current directory. If no sources are specified, any previously specified directories are deleted. If the source is the special .Ic .DOTLAST target, then the current working directory is searched last. .It Ic .PATH. Ns Va suffix Like .Ic .PATH but applies only to files with a particular suffix. The suffix must have been previously declared with .Ic .SUFFIXES . .It Ic .PHONY Apply the .Ic .PHONY attribute to any specified sources. .It Ic .PRECIOUS Apply the .Ic .PRECIOUS attribute to any specified sources. If no sources are specified, the .Ic .PRECIOUS attribute is applied to every target in the file. .It Ic .SHELL Sets the shell that .Nm will use to execute commands. The sources are a set of .Ar field=value pairs. .Bl -tag -width hasErrCtls .It Ar name This is the minimal specification, used to select one of the built-in shell specs; .Ar sh , .Ar ksh , and .Ar csh . .It Ar path Specifies the path to the shell. .It Ar hasErrCtl Indicates whether the shell supports exit on error. .It Ar check The command to turn on error checking. .It Ar ignore The command to disable error checking. .It Ar echo The command to turn on echoing of commands executed. .It Ar quiet The command to turn off echoing of commands executed. .It Ar filter The output to filter after issuing the .Ar quiet command. It is typically identical to .Ar quiet . .It Ar errFlag The flag to pass the shell to enable error checking. .It Ar echoFlag The flag to pass the shell to enable command echoing. .It Ar newline The string literal to pass the shell that results in a single newline character when used outside of any quoting characters. .El Example: .Bd -literal \&.SHELL: name=ksh path=/bin/ksh hasErrCtl=true \e check="set \-e" ignore="set +e" \e echo="set \-v" quiet="set +v" filter="set +v" \e echoFlag=v errFlag=e newline="'\en'" .Ed .It Ic .SILENT Apply the .Ic .SILENT attribute to any specified sources. If no sources are specified, the .Ic .SILENT attribute is applied to every command in the file. .It Ic .STALE This target gets run when a dependency file contains stale entries, having .Va .ALLSRC set to the name of that dependency file. .It Ic .SUFFIXES Each source specifies a suffix to .Nm . If no sources are specified, any previously specified suffixes are deleted. It allows the creation of suffix-transformation rules. .Pp Example: .Bd -literal \&.SUFFIXES: .o \&.c.o: cc \-o ${.TARGET} \-c ${.IMPSRC} .Ed .El .Sh ENVIRONMENT .Nm uses the following environment variables, if they exist: .Ev MACHINE , .Ev MACHINE_ARCH , .Ev MAKE , .Ev MAKEFLAGS , .Ev MAKEOBJDIR , .Ev MAKEOBJDIRPREFIX , .Ev MAKESYSPATH , .Ev PWD , and .Ev TMPDIR . .Pp .Ev MAKEOBJDIRPREFIX and .Ev MAKEOBJDIR may only be set in the environment or on the command line to .Nm and not as makefile variables; see the description of .Ql Va .OBJDIR for more details. .Sh FILES .Bl -tag -width /usr/share/mk -compact .It .depend list of dependencies .It Makefile list of dependencies .It makefile list of dependencies .It sys.mk system makefile .It /usr/share/mk system makefile directory .El .Sh COMPATIBILITY The basic make syntax is compatible between different versions of make; however the special variables, variable modifiers and conditionals are not. .Ss Older versions An incomplete list of changes in older versions of .Nm : .Pp The way that .for loop variables are substituted changed after .Nx 5.0 so that they still appear to be variable expansions. In particular this stops them being treated as syntax, and removes some obscure problems using them in .if statements. .Pp The way that parallel makes are scheduled changed in .Nx 4.0 so that .ORDER and .WAIT apply recursively to the dependent nodes. The algorithms used may change again in the future. .Ss Other make dialects Other make dialects (GNU make, SVR4 make, POSIX make, etc.) do not support most of the features of .Nm as described in this manual. Most notably: .Bl -bullet -offset indent .It The .Ic .WAIT and .Ic .ORDER declarations and most functionality pertaining to parallelization. (GNU make supports parallelization but lacks these features needed to control it effectively.) .It Directives, including for loops and conditionals and most of the forms of include files. (GNU make has its own incompatible and less powerful syntax for conditionals.) .It All built-in variables that begin with a dot. .It Most of the special sources and targets that begin with a dot, with the notable exception of .Ic .PHONY , .Ic .PRECIOUS , and .Ic .SUFFIXES . .It Variable modifiers, except for the .Dl :old=new string substitution, which does not portably support globbing with .Ql % and historically only works on declared suffixes. .It The .Ic $> variable even in its short form; most makes support this functionality but its name varies. .El .Pp Some features are somewhat more portable, such as assignment with .Ic += , .Ic ?= , and .Ic != . The .Ic .PATH functionality is based on an older feature .Ic VPATH found in GNU make and many versions of SVR4 make; however, historically its behavior is too ill-defined (and too buggy) to rely upon. .Pp The .Ic $@ and .Ic $< variables are more or less universally portable, as is the .Ic $(MAKE) variable. Basic use of suffix rules (for files only in the current directory, not trying to chain transformations together, etc.) is also reasonably portable. .Sh SEE ALSO .Xr mkdep 1 , .Xr style.Makefile 5 .Sh HISTORY A .Nm command appeared in .At v7 . This .Nm implementation is based on Adam De Boor's pmake program which was written for Sprite at Berkeley. It was designed to be a parallel distributed make running jobs on different machines using a daemon called .Dq customs . .Pp Historically the target/dependency .Dq FRC has been used to FoRCe rebuilding (since the target/dependency does not exist... unless someone creates an .Dq FRC file). .Sh BUGS The .Nm -syntax is difficult to parse without actually acting of the data. -For instance finding the end of a variable use should involve scanning each -the modifiers using the correct terminator for each field. +syntax is difficult to parse without actually acting on the data. +For instance, finding the end of a variable's use should involve scanning +each of the modifiers, using the correct terminator for each field. In many places .Nm just counts {} and () in order to find the end of a variable expansion. .Pp There is no way of escaping a space character in a filename. Index: stable/12/contrib/bmake/make.h =================================================================== --- stable/12/contrib/bmake/make.h (revision 361673) +++ stable/12/contrib/bmake/make.h (revision 361674) @@ -1,553 +1,553 @@ -/* $NetBSD: make.h,v 1.105 2020/03/30 02:41:06 sjg Exp $ */ +/* $NetBSD: make.h,v 1.107 2020/04/03 03:35:16 sjg Exp $ */ /* * Copyright (c) 1988, 1989, 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)make.h 8.3 (Berkeley) 6/13/95 */ /* * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)make.h 8.3 (Berkeley) 6/13/95 */ /*- * make.h -- * The global definitions for pmake */ #ifndef _MAKE_H_ #define _MAKE_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include #include #include #include #include #include #ifdef HAVE_STRING_H #include #else #include #endif #include #include #ifndef FD_CLOEXEC #define FD_CLOEXEC 1 #endif #if defined(__GNUC__) #define MAKE_GNUC_PREREQ(x, y) \ ((__GNUC__ == (x) && __GNUC_MINOR__ >= (y)) || \ (__GNUC__ > (x))) #else /* defined(__GNUC__) */ #define MAKE_GNUC_PREREQ(x, y) 0 #endif /* defined(__GNUC__) */ #if MAKE_GNUC_PREREQ(2, 7) #define MAKE_ATTR_UNUSED __attribute__((__unused__)) #else #define MAKE_ATTR_UNUSED /* delete */ #endif #if MAKE_GNUC_PREREQ(2, 5) #define MAKE_ATTR_DEAD __attribute__((__noreturn__)) #elif defined(__GNUC__) #define MAKE_ATTR_DEAD __volatile #else #define MAKE_ATTR_DEAD /* delete */ #endif #if MAKE_GNUC_PREREQ(2, 7) #define MAKE_ATTR_PRINTFLIKE(fmtarg, firstvararg) \ __attribute__((__format__ (__printf__, fmtarg, firstvararg))) #else #define MAKE_ATTR_PRINTFLIKE(fmtarg, firstvararg) /* delete */ #endif #include "sprite.h" #include "lst.h" #include "hash.h" #include "make-conf.h" #include "buf.h" #include "make_malloc.h" /* * some vendors don't have this --sjg */ #if defined(S_IFDIR) && !defined(S_ISDIR) # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #endif #if defined(sun) && (defined(__svr4__) || defined(__SVR4)) #define POSIX_SIGNALS #endif /*- * The structure for an individual graph node. Each node has several * pieces of data associated with it. * 1) the name of the target it describes * 2) the location of the target file in the file system. * 3) the type of operator used to define its sources (qv. parse.c) * 4) whether it is involved in this invocation of make * 5) whether the target has been remade * 6) whether any of its children has been remade * 7) the number of its children that are, as yet, unmade * 8) its modification time * 9) the modification time of its youngest child (qv. make.c) * 10) a list of nodes for which this is a source (parents) * 11) a list of nodes on which this depends (children) * 12) a list of nodes that depend on this, as gleaned from the * transformation rules (iParents) * 13) a list of ancestor nodes, which includes parents, iParents, * and recursive parents of parents * 14) a list of nodes of the same name created by the :: operator * 15) a list of nodes that must be made (if they're made) before * this node can be, but that do not enter into the datedness of * this node. * 16) a list of nodes that must be made (if they're made) before * this node or any child of this node can be, but that do not * enter into the datedness of this node. * 17) a list of nodes that must be made (if they're made) after * this node is, but that do not depend on this node, in the * normal sense. * 18) a Lst of ``local'' variables that are specific to this target * and this target only (qv. var.c [$@ $< $?, etc.]) * 19) a Lst of strings that are commands to be given to a shell * to create this target. */ typedef struct GNode { char *name; /* The target's name */ char *uname; /* The unexpanded name of a .USE node */ char *path; /* The full pathname of the file */ int type; /* Its type (see the OP flags, below) */ int flags; #define REMAKE 0x1 /* this target needs to be (re)made */ #define CHILDMADE 0x2 /* children of this target were made */ #define FORCE 0x4 /* children don't exist, and we pretend made */ #define DONE_WAIT 0x8 /* Set by Make_ProcessWait() */ #define DONE_ORDER 0x10 /* Build requested by .ORDER processing */ #define FROM_DEPEND 0x20 /* Node created from .depend */ #define DONE_ALLSRC 0x40 /* We do it once only */ #define CYCLE 0x1000 /* Used by MakePrintStatus */ #define DONECYCLE 0x2000 /* Used by MakePrintStatus */ #define INTERNAL 0x4000 /* Internal use only */ enum enum_made { UNMADE, DEFERRED, REQUESTED, BEINGMADE, MADE, UPTODATE, ERROR, ABORTED } made; /* Set to reflect the state of processing * on this node: * UNMADE - Not examined yet * DEFERRED - Examined once (building child) * REQUESTED - on toBeMade list * BEINGMADE - Target is already being made. * Indicates a cycle in the graph. * MADE - Was out-of-date and has been made * UPTODATE - Was already up-to-date * ERROR - An error occurred while it was being * made (used only in compat mode) * ABORTED - The target was aborted due to * an error making an inferior (compat). */ int unmade; /* The number of unmade children */ time_t mtime; /* Its modification time */ struct GNode *cmgn; /* The youngest child */ Lst iParents; /* Links to parents for which this is an * implied source, if any */ Lst cohorts; /* Other nodes for the :: operator */ Lst parents; /* Nodes that depend on this one */ Lst children; /* Nodes on which this one depends */ Lst order_pred; /* .ORDER nodes we need made */ Lst order_succ; /* .ORDER nodes who need us */ char cohort_num[8]; /* #n for this cohort */ int unmade_cohorts;/* # of unmade instances on the cohorts list */ struct GNode *centurion; /* Pointer to the first instance of a :: node; only set when on a cohorts list */ unsigned int checked; /* Last time we tried to makle this node */ Hash_Table context; /* The local variables */ Lst commands; /* Creation commands */ struct _Suff *suffix; /* Suffix for the node (determined by * Suff_FindDeps and opaque to everyone * but the Suff module) */ const char *fname; /* filename where the GNode got defined */ int lineno; /* line number where the GNode got defined */ } GNode; /* * The OP_ constants are used when parsing a dependency line as a way of * communicating to other parts of the program the way in which a target * should be made. These constants are bitwise-OR'ed together and * placed in the 'type' field of each node. Any node that has * a 'type' field which satisfies the OP_NOP function was never never on * the lefthand side of an operator, though it may have been on the * righthand side... */ #define OP_DEPENDS 0x00000001 /* Execution of commands depends on * kids (:) */ #define OP_FORCE 0x00000002 /* Always execute commands (!) */ #define OP_DOUBLEDEP 0x00000004 /* Execution of commands depends on kids * per line (::) */ #define OP_OPMASK (OP_DEPENDS|OP_FORCE|OP_DOUBLEDEP) #define OP_OPTIONAL 0x00000008 /* Don't care if the target doesn't * exist and can't be created */ #define OP_USE 0x00000010 /* Use associated commands for parents */ #define OP_EXEC 0x00000020 /* Target is never out of date, but always * execute commands anyway. Its time * doesn't matter, so it has none...sort * of */ #define OP_IGNORE 0x00000040 /* Ignore errors when creating the node */ #define OP_PRECIOUS 0x00000080 /* Don't remove the target when * interrupted */ #define OP_SILENT 0x00000100 /* Don't echo commands when executed */ #define OP_MAKE 0x00000200 /* Target is a recursive make so its * commands should always be executed when * it is out of date, regardless of the * state of the -n or -t flags */ #define OP_JOIN 0x00000400 /* Target is out-of-date only if any of its * children was out-of-date */ #define OP_MADE 0x00000800 /* Assume the children of the node have * been already made */ #define OP_SPECIAL 0x00001000 /* Special .BEGIN, .END, .INTERRUPT */ #define OP_USEBEFORE 0x00002000 /* Like .USE, only prepend commands */ #define OP_INVISIBLE 0x00004000 /* The node is invisible to its parents. * I.e. it doesn't show up in the parents's * local variables. */ #define OP_NOTMAIN 0x00008000 /* The node is exempt from normal 'main * target' processing in parse.c */ #define OP_PHONY 0x00010000 /* Not a file target; run always */ #define OP_NOPATH 0x00020000 /* Don't search for file in the path */ #define OP_WAIT 0x00040000 /* .WAIT phony node */ #define OP_NOMETA 0x00080000 /* .NOMETA do not create a .meta file */ #define OP_META 0x00100000 /* .META we _do_ want a .meta file */ #define OP_NOMETA_CMP 0x00200000 /* Do not compare commands in .meta file */ #define OP_SUBMAKE 0x00400000 /* Possibly a submake node */ /* Attributes applied by PMake */ #define OP_TRANSFORM 0x80000000 /* The node is a transformation rule */ #define OP_MEMBER 0x40000000 /* Target is a member of an archive */ #define OP_LIB 0x20000000 /* Target is a library */ #define OP_ARCHV 0x10000000 /* Target is an archive construct */ #define OP_HAS_COMMANDS 0x08000000 /* Target has all the commands it should. * Used when parsing to catch multiple * commands for a target */ #define OP_SAVE_CMDS 0x04000000 /* Saving commands on .END (Compat) */ #define OP_DEPS_FOUND 0x02000000 /* Already processed by Suff_FindDeps */ #define OP_MARK 0x01000000 /* Node found while expanding .ALLSRC */ #define NoExecute(gn) ((gn->type & OP_MAKE) ? noRecursiveExecute : noExecute) /* * OP_NOP will return TRUE if the node with the given type was not the * object of a dependency operator */ #define OP_NOP(t) (((t) & OP_OPMASK) == 0x00000000) #define OP_NOTARGET (OP_NOTMAIN|OP_USE|OP_EXEC|OP_TRANSFORM) /* * The TARG_ constants are used when calling the Targ_FindNode and * Targ_FindList functions in targ.c. They simply tell the functions what to * do if the desired node(s) is (are) not found. If the TARG_CREATE constant * is given, a new, empty node will be created for the target, placed in the * table of all targets and its address returned. If TARG_NOCREATE is given, * a NULL pointer will be returned. */ #define TARG_NOCREATE 0x00 /* don't create it */ #define TARG_CREATE 0x01 /* create node if not found */ #define TARG_NOHASH 0x02 /* don't look in/add to hash table */ /* * These constants are all used by the Str_Concat function to decide how the * final string should look. If STR_ADDSPACE is given, a space will be * placed between the two strings. If STR_ADDSLASH is given, a '/' will * be used instead of a space. If neither is given, no intervening characters * will be placed between the two strings in the final output. If the * STR_DOFREE bit is set, the two input strings will be freed before * Str_Concat returns. */ #define STR_ADDSPACE 0x01 /* add a space when Str_Concat'ing */ #define STR_ADDSLASH 0x02 /* add a slash when Str_Concat'ing */ /* * Error levels for parsing. PARSE_FATAL means the process cannot continue * once the makefile has been parsed. PARSE_WARNING means it can. Passed * as the first argument to Parse_Error. */ #define PARSE_INFO 3 #define PARSE_WARNING 2 #define PARSE_FATAL 1 /* * Values returned by Cond_Eval. */ #define COND_PARSE 0 /* Parse the next lines */ #define COND_SKIP 1 /* Skip the next lines */ #define COND_INVALID 2 /* Not a conditional statement */ /* * Definitions for the "local" variables. Used only for clarity. */ #define TARGET "@" /* Target of dependency */ #define OODATE "?" /* All out-of-date sources */ #define ALLSRC ">" /* All sources */ #define IMPSRC "<" /* Source implied by transformation */ #define PREFIX "*" /* Common prefix */ #define ARCHIVE "!" /* Archive in "archive(member)" syntax */ #define MEMBER "%" /* Member in "archive(member)" syntax */ #define FTARGET "@F" /* file part of TARGET */ #define DTARGET "@D" /* directory part of TARGET */ #define FIMPSRC " b) ? a : b) #endif /* At least GNU/Hurd systems lack hardcoded MAXPATHLEN/PATH_MAX */ #ifdef HAVE_LIMITS_H #include #endif #ifndef MAXPATHLEN #define MAXPATHLEN BMAKE_PATH_MAX #endif #ifndef PATH_MAX #define PATH_MAX MAXPATHLEN #endif #if defined(SYSV) #define KILLPG(pid, sig) kill(-(pid), (sig)) #else #define KILLPG(pid, sig) killpg((pid), (sig)) #endif #endif /* _MAKE_H_ */ Index: stable/12/contrib/bmake/meta.c =================================================================== --- stable/12/contrib/bmake/meta.c (revision 361673) +++ stable/12/contrib/bmake/meta.c (revision 361674) @@ -1,1645 +1,1743 @@ -/* $NetBSD: meta.c,v 1.70 2018/02/13 19:37:30 sjg Exp $ */ +/* $NetBSD: meta.c,v 1.81 2020/04/03 03:32:28 sjg Exp $ */ /* * Implement 'meta' mode. * Adapted from John Birrell's patches to FreeBSD make. * --sjg */ /* * Copyright (c) 2009-2016, Juniper Networks, Inc. * Portions Copyright (c) 2009, John Birrell. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined(USE_META) #ifdef HAVE_CONFIG_H # include "config.h" #endif #include -#include #ifdef HAVE_LIBGEN_H #include #elif !defined(HAVE_DIRNAME) char * dirname(char *); #endif #include #if !defined(HAVE_CONFIG_H) || defined(HAVE_ERR_H) #include #endif #include "make.h" #include "job.h" -#ifdef HAVE_FILEMON_H -# include +#ifdef USE_FILEMON +#include "filemon/filemon.h" #endif -#if !defined(USE_FILEMON) && defined(FILEMON_SET_FD) -# define USE_FILEMON -#endif static BuildMon Mybm; /* for compat */ static Lst metaBailiwick; /* our scope of control */ static char *metaBailiwickStr; /* string storage for the list */ static Lst metaIgnorePaths; /* paths we deliberately ignore */ static char *metaIgnorePathsStr; /* string storage for the list */ #ifndef MAKE_META_IGNORE_PATHS #define MAKE_META_IGNORE_PATHS ".MAKE.META.IGNORE_PATHS" #endif #ifndef MAKE_META_IGNORE_PATTERNS #define MAKE_META_IGNORE_PATTERNS ".MAKE.META.IGNORE_PATTERNS" #endif #ifndef MAKE_META_IGNORE_FILTER #define MAKE_META_IGNORE_FILTER ".MAKE.META.IGNORE_FILTER" #endif Boolean useMeta = FALSE; static Boolean useFilemon = FALSE; static Boolean writeMeta = FALSE; static Boolean metaMissing = FALSE; /* oodate if missing */ static Boolean filemonMissing = FALSE; /* oodate if missing */ static Boolean metaEnv = FALSE; /* don't save env unless asked */ static Boolean metaVerbose = FALSE; static Boolean metaIgnoreCMDs = FALSE; /* ignore CMDs in .meta files */ static Boolean metaIgnorePatterns = FALSE; /* do we need to do pattern matches */ static Boolean metaIgnoreFilter = FALSE; /* do we have more complex filtering? */ static Boolean metaCurdirOk = FALSE; /* write .meta in .CURDIR Ok? */ static Boolean metaSilent = FALSE; /* if we have a .meta be SILENT */ extern Boolean forceJobs; extern Boolean comatMake; extern char **environ; #define MAKE_META_PREFIX ".MAKE.META.PREFIX" #ifndef N2U # define N2U(n, u) (((n) + ((u) - 1)) / (u)) #endif #ifndef ROUNDUP # define ROUNDUP(n, u) (N2U((n), (u)) * (u)) #endif #if !defined(HAVE_STRSEP) # define strsep(s, d) stresep((s), (d), 0) #endif /* * Filemon is a kernel module which snoops certain syscalls. * * C chdir * E exec * F [v]fork * L [sym]link * M rename * R read * W write * S stat * * See meta_oodate below - we mainly care about 'E' and 'R'. * * We can still use meta mode without filemon, but * the benefits are more limited. */ #ifdef USE_FILEMON -# ifndef _PATH_FILEMON -# define _PATH_FILEMON "/dev/filemon" -# endif /* * Open the filemon device. */ static void -filemon_open(BuildMon *pbm) +meta_open_filemon(BuildMon *pbm) { - int retry; - - pbm->mon_fd = pbm->filemon_fd = -1; - if (!useFilemon) + int dupfd; + + pbm->mon_fd = -1; + pbm->filemon = NULL; + if (!useFilemon || !pbm->mfp) return; - for (retry = 5; retry >= 0; retry--) { - if ((pbm->filemon_fd = open(_PATH_FILEMON, O_RDWR)) >= 0) - break; - } - - if (pbm->filemon_fd < 0) { + pbm->filemon = filemon_open(); + if (pbm->filemon == NULL) { useFilemon = FALSE; - warn("Could not open %s", _PATH_FILEMON); + warn("Could not open filemon %s", filemon_path()); return; } /* * We use a file outside of '.' * to avoid a FreeBSD kernel bug where unlink invalidates * cwd causing getcwd to do a lot more work. * We only care about the descriptor. */ pbm->mon_fd = mkTempFile("filemon.XXXXXX", NULL); - if (ioctl(pbm->filemon_fd, FILEMON_SET_FD, &pbm->mon_fd) < 0) { + if ((dupfd = dup(pbm->mon_fd)) == -1) { + err(1, "Could not dup filemon output!"); + } + (void)fcntl(dupfd, F_SETFD, FD_CLOEXEC); + if (filemon_setfd(pbm->filemon, dupfd) == -1) { err(1, "Could not set filemon file descriptor!"); } /* we don't need these once we exec */ (void)fcntl(pbm->mon_fd, F_SETFD, FD_CLOEXEC); - (void)fcntl(pbm->filemon_fd, F_SETFD, FD_CLOEXEC); } /* * Read the build monitor output file and write records to the target's * metadata file. */ static int filemon_read(FILE *mfp, int fd) { char buf[BUFSIZ]; int n; int error; /* Check if we're not writing to a meta data file.*/ if (mfp == NULL) { if (fd >= 0) close(fd); /* not interested */ return 0; } /* rewind */ (void)lseek(fd, (off_t)0, SEEK_SET); error = 0; fprintf(mfp, "\n-- filemon acquired metadata --\n"); while ((n = read(fd, buf, sizeof(buf))) > 0) { if ((int)fwrite(buf, 1, n, mfp) < n) error = EIO; } fflush(mfp); if (close(fd) < 0) error = errno; return error; } #endif /* * when realpath() fails, * we use this, to clean up ./ and ../ */ static void eat_dots(char *buf, size_t bufsz, int dots) { char *cp; char *cp2; const char *eat; size_t eatlen; switch (dots) { case 1: eat = "/./"; eatlen = 2; break; case 2: eat = "/../"; eatlen = 3; break; default: return; } do { cp = strstr(buf, eat); if (cp) { cp2 = cp + eatlen; if (dots == 2 && cp > buf) { do { cp--; } while (cp > buf && *cp != '/'); } if (*cp == '/') { strlcpy(cp, cp2, bufsz - (cp - buf)); } else { return; /* can't happen? */ } } } while (cp); } static char * meta_name(char *mname, size_t mnamelen, const char *dname, const char *tname, const char *cwd) { char buf[MAXPATHLEN]; char *rp; char *cp; char *tp; char *dtp; size_t ldname; /* * Weed out relative paths from the target file name. * We have to be careful though since if target is a * symlink, the result will be unstable. * So we use realpath() just to get the dirname, and leave the * basename as given to us. */ if ((cp = strrchr(tname, '/'))) { if (cached_realpath(tname, buf)) { if ((rp = strrchr(buf, '/'))) { rp++; cp++; if (strcmp(cp, rp) != 0) strlcpy(rp, cp, sizeof(buf) - (rp - buf)); } tname = buf; } else { /* * We likely have a directory which is about to be made. * We pretend realpath() succeeded, to have a chance * of generating the same meta file name that we will * next time through. */ if (tname[0] == '/') { strlcpy(buf, tname, sizeof(buf)); } else { snprintf(buf, sizeof(buf), "%s/%s", cwd, tname); } eat_dots(buf, sizeof(buf), 1); /* ./ */ eat_dots(buf, sizeof(buf), 2); /* ../ */ tname = buf; } } /* on some systems dirname may modify its arg */ tp = bmake_strdup(tname); dtp = dirname(tp); if (strcmp(dname, dtp) == 0) snprintf(mname, mnamelen, "%s.meta", tname); else { ldname = strlen(dname); if (strncmp(dname, dtp, ldname) == 0 && dtp[ldname] == '/') snprintf(mname, mnamelen, "%s/%s.meta", dname, &tname[ldname+1]); else snprintf(mname, mnamelen, "%s/%s.meta", dname, tname); /* * Replace path separators in the file name after the * current object directory path. */ cp = mname + strlen(dname) + 1; while (*cp != '\0') { if (*cp == '/') *cp = '_'; cp++; } } free(tp); return (mname); } /* * Return true if running ${.MAKE} * Bypassed if target is flagged .MAKE */ static int is_submake(void *cmdp, void *gnp) { static char *p_make = NULL; static int p_len; char *cmd = cmdp; GNode *gn = gnp; char *mp = NULL; char *cp; char *cp2; int rc = 0; /* keep looking */ if (!p_make) { p_make = Var_Value(".MAKE", gn, &cp); p_len = strlen(p_make); } cp = strchr(cmd, '$'); if ((cp)) { mp = Var_Subst(NULL, cmd, gn, VARF_WANTRES); cmd = mp; } cp2 = strstr(cmd, p_make); if ((cp2)) { switch (cp2[p_len]) { case '\0': case ' ': case '\t': case '\n': rc = 1; break; } if (cp2 > cmd && rc > 0) { switch (cp2[-1]) { case ' ': case '\t': case '\n': break; default: rc = 0; /* no match */ break; } } } free(mp); return (rc); } typedef struct meta_file_s { FILE *fp; GNode *gn; } meta_file_t; static int printCMD(void *cmdp, void *mfpp) { meta_file_t *mfp = mfpp; char *cmd = cmdp; char *cp = NULL; if (strchr(cmd, '$')) { cmd = cp = Var_Subst(NULL, cmd, mfp->gn, VARF_WANTRES); } fprintf(mfp->fp, "CMD %s\n", cmd); free(cp); return 0; } /* * Certain node types never get a .meta file */ #define SKIP_META_TYPE(_type) do { \ if ((gn->type & __CONCAT(OP_, _type))) { \ if (verbose) { \ fprintf(debug_file, "Skipping meta for %s: .%s\n", \ gn->name, __STRING(_type)); \ } \ return FALSE; \ } \ } while (0) /* * Do we need/want a .meta file ? */ static Boolean meta_needed(GNode *gn, const char *dname, char *objdir, int verbose) { struct stat fs; if (verbose) verbose = DEBUG(META); /* This may be a phony node which we don't want meta data for... */ /* Skip .meta for .BEGIN, .END, .ERROR etc as well. */ /* Or it may be explicitly flagged as .NOMETA */ SKIP_META_TYPE(NOMETA); /* Unless it is explicitly flagged as .META */ if (!(gn->type & OP_META)) { SKIP_META_TYPE(PHONY); SKIP_META_TYPE(SPECIAL); SKIP_META_TYPE(MAKE); } /* Check if there are no commands to execute. */ if (Lst_IsEmpty(gn->commands)) { if (verbose) fprintf(debug_file, "Skipping meta for %s: no commands\n", gn->name); return FALSE; } if ((gn->type & (OP_META|OP_SUBMAKE)) == OP_SUBMAKE) { /* OP_SUBMAKE is a bit too aggressive */ if (Lst_ForEach(gn->commands, is_submake, gn)) { if (DEBUG(META)) fprintf(debug_file, "Skipping meta for %s: .SUBMAKE\n", gn->name); return FALSE; } } /* The object directory may not exist. Check it.. */ if (cached_stat(dname, &fs) != 0) { if (verbose) fprintf(debug_file, "Skipping meta for %s: no .OBJDIR\n", gn->name); return FALSE; } /* make sure these are canonical */ if (cached_realpath(dname, objdir)) dname = objdir; /* If we aren't in the object directory, don't create a meta file. */ if (!metaCurdirOk && strcmp(curdir, dname) == 0) { if (verbose) fprintf(debug_file, "Skipping meta for %s: .OBJDIR == .CURDIR\n", gn->name); return FALSE; } return TRUE; } static FILE * meta_create(BuildMon *pbm, GNode *gn) { meta_file_t mf; char buf[MAXPATHLEN]; char objdir[MAXPATHLEN]; char **ptr; const char *dname; const char *tname; char *fname; const char *cp; - char *p[4]; /* >= possible uses */ + char *p[5]; /* >= possible uses */ int i; mf.fp = NULL; i = 0; dname = Var_Value(".OBJDIR", gn, &p[i++]); tname = Var_Value(TARGET, gn, &p[i++]); /* if this succeeds objdir is realpath of dname */ if (!meta_needed(gn, dname, objdir, TRUE)) goto out; dname = objdir; if (metaVerbose) { char *mp; /* Describe the target we are building */ mp = Var_Subst(NULL, "${" MAKE_META_PREFIX "}", gn, VARF_WANTRES); if (*mp) fprintf(stdout, "%s\n", mp); free(mp); } /* Get the basename of the target */ if ((cp = strrchr(tname, '/')) == NULL) { cp = tname; } else { cp++; } fflush(stdout); if (!writeMeta) /* Don't create meta data. */ goto out; fname = meta_name(pbm->meta_fname, sizeof(pbm->meta_fname), dname, tname, objdir); #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_create: %s\n", fname); #endif if ((mf.fp = fopen(fname, "w")) == NULL) err(1, "Could not open meta file '%s'", fname); fprintf(mf.fp, "# Meta data file %s\n", fname); mf.gn = gn; Lst_ForEach(gn->commands, printCMD, &mf); fprintf(mf.fp, "CWD %s\n", getcwd(buf, sizeof(buf))); fprintf(mf.fp, "TARGET %s\n", tname); - + cp = Var_Value(".OODATE", gn, &p[i++]); + if (cp && *cp) { + fprintf(mf.fp, "OODATE %s\n", cp); + } if (metaEnv) { for (ptr = environ; *ptr != NULL; ptr++) fprintf(mf.fp, "ENV %s\n", *ptr); } fprintf(mf.fp, "-- command output --\n"); fflush(mf.fp); Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL); Var_Append(".MAKE.META.CREATED", fname, VAR_GLOBAL); gn->type |= OP_META; /* in case anyone wants to know */ if (metaSilent) { gn->type |= OP_SILENT; } out: for (i--; i >= 0; i--) { free(p[i]); } return (mf.fp); } static Boolean boolValue(char *s) { switch(*s) { case '0': case 'N': case 'n': case 'F': case 'f': return FALSE; } return TRUE; } /* * Initialization we need before reading makefiles. */ void meta_init(void) { #ifdef USE_FILEMON /* this allows makefiles to test if we have filemon support */ - Var_Set(".MAKE.PATH_FILEMON", _PATH_FILEMON, VAR_GLOBAL, 0); + Var_Set(".MAKE.PATH_FILEMON", filemon_path(), VAR_GLOBAL, 0); #endif } #define get_mode_bf(bf, token) \ if ((cp = strstr(make_mode, token))) \ bf = boolValue(&cp[sizeof(token) - 1]) /* * Initialization we need after reading makefiles. */ void meta_mode_init(const char *make_mode) { static int once = 0; char *cp; useMeta = TRUE; useFilemon = TRUE; writeMeta = TRUE; if (make_mode) { if (strstr(make_mode, "env")) metaEnv = TRUE; if (strstr(make_mode, "verb")) metaVerbose = TRUE; if (strstr(make_mode, "read")) writeMeta = FALSE; if (strstr(make_mode, "nofilemon")) useFilemon = FALSE; if (strstr(make_mode, "ignore-cmd")) metaIgnoreCMDs = TRUE; if (useFilemon) get_mode_bf(filemonMissing, "missing-filemon="); get_mode_bf(metaCurdirOk, "curdirok="); get_mode_bf(metaMissing, "missing-meta="); get_mode_bf(metaSilent, "silent="); } if (metaVerbose && !Var_Exists(MAKE_META_PREFIX, VAR_GLOBAL)) { /* * The default value for MAKE_META_PREFIX * prints the absolute path of the target. * This works be cause :H will generate '.' if there is no / * and :tA will resolve that to cwd. */ Var_Set(MAKE_META_PREFIX, "Building ${.TARGET:H:tA}/${.TARGET:T}", VAR_GLOBAL, 0); } if (once) return; once = 1; memset(&Mybm, 0, sizeof(Mybm)); /* * We consider ourselves master of all within ${.MAKE.META.BAILIWICK} */ metaBailiwick = Lst_Init(FALSE); metaBailiwickStr = Var_Subst(NULL, "${.MAKE.META.BAILIWICK:O:u:tA}", VAR_GLOBAL, VARF_WANTRES); if (metaBailiwickStr) { str2Lst_Append(metaBailiwick, metaBailiwickStr, NULL); } /* * We ignore any paths that start with ${.MAKE.META.IGNORE_PATHS} */ metaIgnorePaths = Lst_Init(FALSE); Var_Append(MAKE_META_IGNORE_PATHS, "/dev /etc /proc /tmp /var/run /var/tmp ${TMPDIR}", VAR_GLOBAL); metaIgnorePathsStr = Var_Subst(NULL, "${" MAKE_META_IGNORE_PATHS ":O:u:tA}", VAR_GLOBAL, VARF_WANTRES); if (metaIgnorePathsStr) { str2Lst_Append(metaIgnorePaths, metaIgnorePathsStr, NULL); } /* * We ignore any paths that match ${.MAKE.META.IGNORE_PATTERNS} */ cp = NULL; if (Var_Value(MAKE_META_IGNORE_PATTERNS, VAR_GLOBAL, &cp)) { metaIgnorePatterns = TRUE; free(cp); } cp = NULL; if (Var_Value(MAKE_META_IGNORE_FILTER, VAR_GLOBAL, &cp)) { metaIgnoreFilter = TRUE; free(cp); } } /* * In each case below we allow for job==NULL */ void meta_job_start(Job *job, GNode *gn) { BuildMon *pbm; if (job != NULL) { pbm = &job->bm; } else { pbm = &Mybm; } pbm->mfp = meta_create(pbm, gn); #ifdef USE_FILEMON_ONCE /* compat mode we open the filemon dev once per command */ if (job == NULL) return; #endif #ifdef USE_FILEMON if (pbm->mfp != NULL && useFilemon) { - filemon_open(pbm); + meta_open_filemon(pbm); } else { - pbm->mon_fd = pbm->filemon_fd = -1; + pbm->mon_fd = -1; + pbm->filemon = NULL; } #endif } /* * The child calls this before doing anything. * It does not disturb our state. */ void meta_job_child(Job *job) { #ifdef USE_FILEMON BuildMon *pbm; if (job != NULL) { pbm = &job->bm; } else { pbm = &Mybm; } if (pbm->mfp != NULL) { close(fileno(pbm->mfp)); - if (useFilemon) { + if (useFilemon && pbm->filemon) { pid_t pid; pid = getpid(); - if (ioctl(pbm->filemon_fd, FILEMON_SET_PID, &pid) < 0) { + if (filemon_setpid_child(pbm->filemon, pid) == -1) { err(1, "Could not set filemon pid!"); } } } #endif } void +meta_job_parent(Job *job, pid_t pid) +{ +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + BuildMon *pbm; + + if (job != NULL) { + pbm = &job->bm; + } else { + pbm = &Mybm; + } + if (useFilemon && pbm->filemon) { + filemon_setpid_parent(pbm->filemon, pid); + } +#endif +} + +int +meta_job_fd(Job *job) +{ +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + BuildMon *pbm; + + if (job != NULL) { + pbm = &job->bm; + } else { + pbm = &Mybm; + } + if (useFilemon && pbm->filemon) { + return filemon_readfd(pbm->filemon); + } +#endif + return -1; +} + +int +meta_job_event(Job *job) +{ +#if defined(USE_FILEMON) && !defined(USE_FILEMON_DEV) + BuildMon *pbm; + + if (job != NULL) { + pbm = &job->bm; + } else { + pbm = &Mybm; + } + if (useFilemon && pbm->filemon) { + return filemon_process(pbm->filemon); + } +#endif + return 0; +} + +void meta_job_error(Job *job, GNode *gn, int flags, int status) { char cwd[MAXPATHLEN]; BuildMon *pbm; if (job != NULL) { pbm = &job->bm; if (!gn) gn = job->node; } else { pbm = &Mybm; } if (pbm->mfp != NULL) { fprintf(pbm->mfp, "\n*** Error code %d%s\n", status, (flags & JOB_IGNERR) ? "(ignored)" : ""); } if (gn) { Var_Set(".ERROR_TARGET", gn->path ? gn->path : gn->name, VAR_GLOBAL, 0); } getcwd(cwd, sizeof(cwd)); Var_Set(".ERROR_CWD", cwd, VAR_GLOBAL, 0); if (pbm->meta_fname[0]) { Var_Set(".ERROR_META_FILE", pbm->meta_fname, VAR_GLOBAL, 0); } meta_job_finish(job); } void meta_job_output(Job *job, char *cp, const char *nl) { BuildMon *pbm; if (job != NULL) { pbm = &job->bm; } else { pbm = &Mybm; } if (pbm->mfp != NULL) { if (metaVerbose) { static char *meta_prefix = NULL; static int meta_prefix_len; if (!meta_prefix) { char *cp2; meta_prefix = Var_Subst(NULL, "${" MAKE_META_PREFIX "}", VAR_GLOBAL, VARF_WANTRES); if ((cp2 = strchr(meta_prefix, '$'))) meta_prefix_len = cp2 - meta_prefix; else meta_prefix_len = strlen(meta_prefix); } if (strncmp(cp, meta_prefix, meta_prefix_len) == 0) { cp = strchr(cp+1, '\n'); if (!cp++) return; } } fprintf(pbm->mfp, "%s%s", cp, nl); } } int meta_cmd_finish(void *pbmp) { int error = 0; BuildMon *pbm = pbmp; #ifdef USE_FILEMON int x; #endif if (!pbm) pbm = &Mybm; #ifdef USE_FILEMON - if (pbm->filemon_fd >= 0) { - if (close(pbm->filemon_fd) < 0) + if (pbm->filemon) { + while (filemon_process(pbm->filemon) > 0) + continue; + if (filemon_close(pbm->filemon) == -1) error = errno; x = filemon_read(pbm->mfp, pbm->mon_fd); if (error == 0 && x != 0) error = x; - pbm->filemon_fd = pbm->mon_fd = -1; + pbm->mon_fd = -1; + pbm->filemon = NULL; } else #endif fprintf(pbm->mfp, "\n"); /* ensure end with newline */ return error; } int meta_job_finish(Job *job) { BuildMon *pbm; int error = 0; int x; if (job != NULL) { pbm = &job->bm; } else { pbm = &Mybm; } if (pbm->mfp != NULL) { error = meta_cmd_finish(pbm); x = fclose(pbm->mfp); if (error == 0 && x != 0) error = errno; pbm->mfp = NULL; pbm->meta_fname[0] = '\0'; } return error; } void meta_finish(void) { Lst_Destroy(metaBailiwick, NULL); free(metaBailiwickStr); Lst_Destroy(metaIgnorePaths, NULL); free(metaIgnorePathsStr); } /* * Fetch a full line from fp - growing bufp if needed * Return length in bufp. */ static int fgetLine(char **bufp, size_t *szp, int o, FILE *fp) { char *buf = *bufp; size_t bufsz = *szp; struct stat fs; int x; if (fgets(&buf[o], bufsz - o, fp) != NULL) { check_newline: x = o + strlen(&buf[o]); if (buf[x - 1] == '\n') return x; /* * We need to grow the buffer. * The meta file can give us a clue. */ if (fstat(fileno(fp), &fs) == 0) { size_t newsz; char *p; newsz = ROUNDUP((fs.st_size / 2), BUFSIZ); if (newsz <= bufsz) newsz = ROUNDUP(fs.st_size, BUFSIZ); if (newsz <= bufsz) return x; /* truncated */ if (DEBUG(META)) fprintf(debug_file, "growing buffer %u -> %u\n", (unsigned)bufsz, (unsigned)newsz); p = bmake_realloc(buf, newsz); if (p) { *bufp = buf = p; *szp = bufsz = newsz; /* fetch the rest */ if (!fgets(&buf[x], bufsz - x, fp)) return x; /* truncated! */ goto check_newline; } } } return 0; } /* Lst_ForEach wants 1 to stop search */ static int prefix_match(void *p, void *q) { const char *prefix = p; const char *path = q; size_t n = strlen(prefix); return (0 == strncmp(path, prefix, n)); } /* * looking for exact or prefix/ match to * Lst_Find wants 0 to stop search */ static int path_match(const void *p, const void *q) { const char *prefix = q; const char *path = p; size_t n = strlen(prefix); int rc; if ((rc = strncmp(path, prefix, n)) == 0) { switch (path[n]) { case '\0': case '/': break; default: rc = 1; break; } } return rc; } /* Lst_Find wants 0 to stop search */ static int string_match(const void *p, const void *q) { const char *p1 = p; const char *p2 = q; return strcmp(p1, p2); } static int meta_ignore(GNode *gn, const char *p) { char fname[MAXPATHLEN]; if (p == NULL) return TRUE; if (*p == '/') { cached_realpath(p, fname); /* clean it up */ if (Lst_ForEach(metaIgnorePaths, prefix_match, fname)) { #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_oodate: ignoring path: %s\n", p); #endif return TRUE; } } if (metaIgnorePatterns) { char *pm; Var_Set(".p.", p, gn, 0); pm = Var_Subst(NULL, "${" MAKE_META_IGNORE_PATTERNS ":@m@${.p.:M$m}@}", gn, VARF_WANTRES); if (*pm) { #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_oodate: ignoring pattern: %s\n", p); #endif free(pm); return TRUE; } free(pm); } if (metaIgnoreFilter) { char *fm; /* skip if filter result is empty */ snprintf(fname, sizeof(fname), "${%s:L:${%s:ts:}}", p, MAKE_META_IGNORE_FILTER); fm = Var_Subst(NULL, fname, gn, VARF_WANTRES); if (*fm == '\0') { #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_oodate: ignoring filtered: %s\n", p); #endif free(fm); return TRUE; } free(fm); } return FALSE; } /* * When running with 'meta' functionality, a target can be out-of-date * if any of the references in its meta data file is more recent. * We have to track the latestdir on a per-process basis. */ #define LCWD_VNAME_FMT ".meta.%d.lcwd" #define LDIR_VNAME_FMT ".meta.%d.ldir" /* * It is possible that a .meta file is corrupted, * if we detect this we want to reproduce it. * Setting oodate TRUE will have that effect. */ #define CHECK_VALID_META(p) if (!(p && *p)) { \ warnx("%s: %d: malformed", fname, lineno); \ oodate = TRUE; \ continue; \ } #define DEQUOTE(p) if (*p == '\'') { \ char *ep; \ p++; \ if ((ep = strchr(p, '\''))) \ *ep = '\0'; \ } Boolean meta_oodate(GNode *gn, Boolean oodate) { static char *tmpdir = NULL; static char cwd[MAXPATHLEN]; char lcwd_vname[64]; char ldir_vname[64]; char lcwd[MAXPATHLEN]; char latestdir[MAXPATHLEN]; char fname[MAXPATHLEN]; char fname1[MAXPATHLEN]; char fname2[MAXPATHLEN]; char fname3[MAXPATHLEN]; const char *dname; const char *tname; char *p; char *cp; char *link_src; char *move_target; static size_t cwdlen = 0; static size_t tmplen = 0; FILE *fp; Boolean needOODATE = FALSE; Lst missingFiles; char *pa[4]; /* >= possible uses */ int i; int have_filemon = FALSE; if (oodate) return oodate; /* we're done */ i = 0; dname = Var_Value(".OBJDIR", gn, &pa[i++]); tname = Var_Value(TARGET, gn, &pa[i++]); /* if this succeeds fname3 is realpath of dname */ if (!meta_needed(gn, dname, fname3, FALSE)) goto oodate_out; dname = fname3; missingFiles = Lst_Init(FALSE); /* * We need to check if the target is out-of-date. This includes * checking if the expanded command has changed. This in turn * requires that all variables are set in the same way that they * would be if the target needs to be re-built. */ Make_DoAllVar(gn); meta_name(fname, sizeof(fname), dname, tname, dname); #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_oodate: %s\n", fname); #endif if ((fp = fopen(fname, "r")) != NULL) { static char *buf = NULL; static size_t bufsz; int lineno = 0; int lastpid = 0; int pid; int x; LstNode ln; struct stat fs; if (!buf) { bufsz = 8 * BUFSIZ; buf = bmake_malloc(bufsz); } if (!cwdlen) { if (getcwd(cwd, sizeof(cwd)) == NULL) err(1, "Could not get current working directory"); cwdlen = strlen(cwd); } strlcpy(lcwd, cwd, sizeof(lcwd)); strlcpy(latestdir, cwd, sizeof(latestdir)); if (!tmpdir) { tmpdir = getTmpdir(); tmplen = strlen(tmpdir); } /* we want to track all the .meta we read */ Var_Append(".MAKE.META.FILES", fname, VAR_GLOBAL); ln = Lst_First(gn->commands); while (!oodate && (x = fgetLine(&buf, &bufsz, 0, fp)) > 0) { lineno++; if (buf[x - 1] == '\n') buf[x - 1] = '\0'; else { warnx("%s: %d: line truncated at %u", fname, lineno, x); oodate = TRUE; break; } link_src = NULL; move_target = NULL; /* Find the start of the build monitor section. */ if (!have_filemon) { if (strncmp(buf, "-- filemon", 10) == 0) { have_filemon = TRUE; continue; } if (strncmp(buf, "# buildmon", 10) == 0) { have_filemon = TRUE; continue; } } /* Delimit the record type. */ p = buf; #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "%s: %d: %s\n", fname, lineno, buf); #endif strsep(&p, " "); if (have_filemon) { /* * We are in the 'filemon' output section. * Each record from filemon follows the general form: * * * * Where: * is a single letter, denoting the syscall. * is the process that made the syscall. * is the arguments (of interest). */ switch(buf[0]) { case '#': /* comment */ case 'V': /* version */ break; default: /* * We need to track pathnames per-process. * * Each process run by make, starts off in the 'CWD' * recorded in the .meta file, if it chdirs ('C') * elsewhere we need to track that - but only for * that process. If it forks ('F'), we initialize * the child to have the same cwd as its parent. * * We also need to track the 'latestdir' of * interest. This is usually the same as cwd, but * not if a process is reading directories. * * Each time we spot a different process ('pid') * we save the current value of 'latestdir' in a * variable qualified by 'lastpid', and * re-initialize 'latestdir' to any pre-saved * value for the current 'pid' and 'CWD' if none. */ CHECK_VALID_META(p); pid = atoi(p); if (pid > 0 && pid != lastpid) { char *ldir; char *tp; if (lastpid > 0) { /* We need to remember these. */ Var_Set(lcwd_vname, lcwd, VAR_GLOBAL, 0); Var_Set(ldir_vname, latestdir, VAR_GLOBAL, 0); } snprintf(lcwd_vname, sizeof(lcwd_vname), LCWD_VNAME_FMT, pid); snprintf(ldir_vname, sizeof(ldir_vname), LDIR_VNAME_FMT, pid); lastpid = pid; ldir = Var_Value(ldir_vname, VAR_GLOBAL, &tp); if (ldir) { strlcpy(latestdir, ldir, sizeof(latestdir)); free(tp); } ldir = Var_Value(lcwd_vname, VAR_GLOBAL, &tp); if (ldir) { strlcpy(lcwd, ldir, sizeof(lcwd)); free(tp); } } /* Skip past the pid. */ if (strsep(&p, " ") == NULL) continue; #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "%s: %d: %d: %c: cwd=%s lcwd=%s ldir=%s\n", fname, lineno, pid, buf[0], cwd, lcwd, latestdir); #endif break; } CHECK_VALID_META(p); /* Process according to record type. */ switch (buf[0]) { case 'X': /* eXit */ Var_Delete(lcwd_vname, VAR_GLOBAL); Var_Delete(ldir_vname, VAR_GLOBAL); lastpid = 0; /* no need to save ldir_vname */ break; case 'F': /* [v]Fork */ { char cldir[64]; int child; child = atoi(p); if (child > 0) { snprintf(cldir, sizeof(cldir), LCWD_VNAME_FMT, child); Var_Set(cldir, lcwd, VAR_GLOBAL, 0); snprintf(cldir, sizeof(cldir), LDIR_VNAME_FMT, child); Var_Set(cldir, latestdir, VAR_GLOBAL, 0); #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "%s: %d: %d: cwd=%s lcwd=%s ldir=%s\n", fname, lineno, child, cwd, lcwd, latestdir); #endif } } break; case 'C': /* Chdir */ /* Update lcwd and latest directory. */ strlcpy(latestdir, p, sizeof(latestdir)); strlcpy(lcwd, p, sizeof(lcwd)); Var_Set(lcwd_vname, lcwd, VAR_GLOBAL, 0); Var_Set(ldir_vname, lcwd, VAR_GLOBAL, 0); #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "%s: %d: cwd=%s ldir=%s\n", fname, lineno, cwd, lcwd); #endif break; case 'M': /* renaMe */ /* * For 'M'oves we want to check * the src as for 'R'ead * and the target as for 'W'rite. */ cp = p; /* save this for a second */ /* now get target */ if (strsep(&p, " ") == NULL) continue; CHECK_VALID_META(p); move_target = p; p = cp; /* 'L' and 'M' put single quotes around the args */ DEQUOTE(p); DEQUOTE(move_target); /* FALLTHROUGH */ case 'D': /* unlink */ if (*p == '/' && !Lst_IsEmpty(missingFiles)) { /* remove any missingFiles entries that match p */ if ((ln = Lst_Find(missingFiles, p, path_match)) != NULL) { LstNode nln; char *tp; do { nln = Lst_FindFrom(missingFiles, Lst_Succ(ln), p, path_match); tp = Lst_Datum(ln); Lst_Remove(missingFiles, ln); free(tp); } while ((ln = nln) != NULL); } } if (buf[0] == 'M') { /* the target of the mv is a file 'W'ritten */ #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_oodate: M %s -> %s\n", p, move_target); #endif p = move_target; goto check_write; } break; case 'L': /* Link */ /* * For 'L'inks check * the src as for 'R'ead * and the target as for 'W'rite. */ link_src = p; /* now get target */ if (strsep(&p, " ") == NULL) continue; CHECK_VALID_META(p); /* 'L' and 'M' put single quotes around the args */ DEQUOTE(p); DEQUOTE(link_src); #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_oodate: L %s -> %s\n", link_src, p); #endif /* FALLTHROUGH */ case 'W': /* Write */ check_write: /* * If a file we generated within our bailiwick * but outside of .OBJDIR is missing, * we need to do it again. */ /* ignore non-absolute paths */ if (*p != '/') break; if (Lst_IsEmpty(metaBailiwick)) break; /* ignore cwd - normal dependencies handle those */ if (strncmp(p, cwd, cwdlen) == 0) break; if (!Lst_ForEach(metaBailiwick, prefix_match, p)) break; /* tmpdir might be within */ if (tmplen > 0 && strncmp(p, tmpdir, tmplen) == 0) break; /* ignore anything containing the string "tmp" */ if ((strstr("tmp", p))) break; if ((link_src != NULL && cached_lstat(p, &fs) < 0) || (link_src == NULL && cached_stat(p, &fs) < 0)) { if (!meta_ignore(gn, p)) { if (Lst_Find(missingFiles, p, string_match) == NULL) Lst_AtEnd(missingFiles, bmake_strdup(p)); } } break; check_link_src: p = link_src; link_src = NULL; #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "meta_oodate: L src %s\n", p); #endif /* FALLTHROUGH */ case 'R': /* Read */ case 'E': /* Exec */ /* * Check for runtime files that can't * be part of the dependencies because * they are _expected_ to change. */ if (meta_ignore(gn, p)) break; /* * The rest of the record is the file name. * Check if it's not an absolute path. */ { char *sdirs[4]; char **sdp; int sdx = 0; int found = 0; if (*p == '/') { sdirs[sdx++] = p; /* done */ } else { if (strcmp(".", p) == 0) continue; /* no point */ /* Check vs latestdir */ snprintf(fname1, sizeof(fname1), "%s/%s", latestdir, p); sdirs[sdx++] = fname1; if (strcmp(latestdir, lcwd) != 0) { /* Check vs lcwd */ snprintf(fname2, sizeof(fname2), "%s/%s", lcwd, p); sdirs[sdx++] = fname2; } if (strcmp(lcwd, cwd) != 0) { /* Check vs cwd */ snprintf(fname3, sizeof(fname3), "%s/%s", cwd, p); sdirs[sdx++] = fname3; } } sdirs[sdx++] = NULL; for (sdp = sdirs; *sdp && !found; sdp++) { #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "%s: %d: looking for: %s\n", fname, lineno, *sdp); #endif if (cached_stat(*sdp, &fs) == 0) { found = 1; p = *sdp; } } if (found) { #ifdef DEBUG_META_MODE if (DEBUG(META)) fprintf(debug_file, "%s: %d: found: %s\n", fname, lineno, p); #endif if (!S_ISDIR(fs.st_mode) && fs.st_mtime > gn->mtime) { if (DEBUG(META)) fprintf(debug_file, "%s: %d: file '%s' is newer than the target...\n", fname, lineno, p); oodate = TRUE; } else if (S_ISDIR(fs.st_mode)) { /* Update the latest directory. */ cached_realpath(p, latestdir); } } else if (errno == ENOENT && *p == '/' && strncmp(p, cwd, cwdlen) != 0) { /* * A referenced file outside of CWD is missing. * We cannot catch every eventuality here... */ if (Lst_Find(missingFiles, p, string_match) == NULL) Lst_AtEnd(missingFiles, bmake_strdup(p)); } } if (buf[0] == 'E') { /* previous latestdir is no longer relevant */ strlcpy(latestdir, lcwd, sizeof(latestdir)); } break; default: break; } if (!oodate && buf[0] == 'L' && link_src != NULL) goto check_link_src; } else if (strcmp(buf, "CMD") == 0) { /* * Compare the current command with the one in the * meta data file. */ if (ln == NULL) { if (DEBUG(META)) fprintf(debug_file, "%s: %d: there were more build commands in the meta data file than there are now...\n", fname, lineno); oodate = TRUE; } else { char *cmd = (char *)Lst_Datum(ln); Boolean hasOODATE = FALSE; if (strstr(cmd, "$?")) hasOODATE = TRUE; else if ((cp = strstr(cmd, ".OODATE"))) { /* check for $[{(].OODATE[:)}] */ if (cp > cmd + 2 && cp[-2] == '$') hasOODATE = TRUE; } if (hasOODATE) { needOODATE = TRUE; if (DEBUG(META)) fprintf(debug_file, "%s: %d: cannot compare command using .OODATE\n", fname, lineno); } cmd = Var_Subst(NULL, cmd, gn, VARF_WANTRES|VARF_UNDEFERR); if ((cp = strchr(cmd, '\n'))) { int n; /* * This command contains newlines, we need to * fetch more from the .meta file before we * attempt a comparison. */ /* first put the newline back at buf[x - 1] */ buf[x - 1] = '\n'; do { /* now fetch the next line */ if ((n = fgetLine(&buf, &bufsz, x, fp)) <= 0) break; x = n; lineno++; if (buf[x - 1] != '\n') { warnx("%s: %d: line truncated at %u", fname, lineno, x); break; } cp = strchr(++cp, '\n'); } while (cp); if (buf[x - 1] == '\n') buf[x - 1] = '\0'; } - if (!hasOODATE && + if (p && + !hasOODATE && !(gn->type & OP_NOMETA_CMP) && strcmp(p, cmd) != 0) { if (DEBUG(META)) fprintf(debug_file, "%s: %d: a build command has changed\n%s\nvs\n%s\n", fname, lineno, p, cmd); if (!metaIgnoreCMDs) oodate = TRUE; } free(cmd); ln = Lst_Succ(ln); } } else if (strcmp(buf, "CWD") == 0) { /* * Check if there are extra commands now * that weren't in the meta data file. */ if (!oodate && ln != NULL) { if (DEBUG(META)) fprintf(debug_file, "%s: %d: there are extra build commands now that weren't in the meta data file\n", fname, lineno); oodate = TRUE; } + CHECK_VALID_META(p); if (strcmp(p, cwd) != 0) { if (DEBUG(META)) fprintf(debug_file, "%s: %d: the current working directory has changed from '%s' to '%s'\n", fname, lineno, p, curdir); oodate = TRUE; } } } fclose(fp); if (!Lst_IsEmpty(missingFiles)) { if (DEBUG(META)) fprintf(debug_file, "%s: missing files: %s...\n", fname, (char *)Lst_Datum(Lst_First(missingFiles))); oodate = TRUE; } if (!oodate && !have_filemon && filemonMissing) { if (DEBUG(META)) fprintf(debug_file, "%s: missing filemon data\n", fname); oodate = TRUE; } } else { if (writeMeta && metaMissing) { cp = NULL; /* if target is in .CURDIR we do not need a meta file */ if (gn->path && (cp = strrchr(gn->path, '/')) && cp > gn->path) { if (strncmp(curdir, gn->path, (cp - gn->path)) != 0) { cp = NULL; /* not in .CURDIR */ } } if (!cp) { if (DEBUG(META)) fprintf(debug_file, "%s: required but missing\n", fname); oodate = TRUE; needOODATE = TRUE; /* assume the worst */ } } } Lst_Destroy(missingFiles, (FreeProc *)free); if (oodate && needOODATE) { /* * Target uses .OODATE which is empty; or we wouldn't be here. * We have decided it is oodate, so .OODATE needs to be set. * All we can sanely do is set it to .ALLSRC. */ Var_Delete(OODATE, gn); Var_Set(OODATE, Var_Value(ALLSRC, gn, &cp), gn, 0); free(cp); } oodate_out: for (i--; i >= 0; i--) { free(pa[i]); } return oodate; } /* support for compat mode */ static int childPipe[2]; void meta_compat_start(void) { #ifdef USE_FILEMON_ONCE /* * We need to re-open filemon for each cmd. */ BuildMon *pbm = &Mybm; if (pbm->mfp != NULL && useFilemon) { - filemon_open(pbm); + meta_open_filemon(pbm); } else { - pbm->mon_fd = pbm->filemon_fd = -1; + pbm->mon_fd = -1; + pbm->filemon = NULL; } #endif if (pipe(childPipe) < 0) Punt("Cannot create pipe: %s", strerror(errno)); /* Set close-on-exec flag for both */ (void)fcntl(childPipe[0], F_SETFD, FD_CLOEXEC); (void)fcntl(childPipe[1], F_SETFD, FD_CLOEXEC); } void meta_compat_child(void) { meta_job_child(NULL); if (dup2(childPipe[1], 1) < 0 || dup2(1, 2) < 0) { execError("dup2", "pipe"); _exit(1); } } void -meta_compat_parent(void) +meta_compat_parent(pid_t child) { - FILE *fp; - char buf[BUFSIZ]; - + int outfd, metafd, maxfd, nfds; + char buf[BUFSIZ+1]; + fd_set readfds; + + meta_job_parent(NULL, child); close(childPipe[1]); /* child side */ - fp = fdopen(childPipe[0], "r"); - while (fgets(buf, sizeof(buf), fp)) { - meta_job_output(NULL, buf, ""); - printf("%s", buf); - fflush(stdout); + outfd = childPipe[0]; +#ifdef USE_FILEMON + metafd = Mybm.filemon ? filemon_readfd(Mybm.filemon) : -1; +#else + metafd = -1; +#endif + maxfd = -1; + if (outfd > maxfd) + maxfd = outfd; + if (metafd > maxfd) + maxfd = metafd; + + while (outfd != -1 || metafd != -1) { + FD_ZERO(&readfds); + if (outfd != -1) { + FD_SET(outfd, &readfds); + } + if (metafd != -1) { + FD_SET(metafd, &readfds); + } + nfds = select(maxfd + 1, &readfds, NULL, NULL, NULL); + if (nfds == -1) { + if (errno == EINTR) + continue; + err(1, "select"); + } + + if (outfd != -1 && FD_ISSET(outfd, &readfds)) do { + /* XXX this is not line-buffered */ + ssize_t nread = read(outfd, buf, sizeof(buf) - 1); + if (nread == -1) + err(1, "read"); + if (nread == 0) { + close(outfd); + outfd = -1; + break; + } + fwrite(buf, 1, (size_t)nread, stdout); + fflush(stdout); + buf[nread] = '\0'; + meta_job_output(NULL, buf, ""); + } while (0); + if (metafd != -1 && FD_ISSET(metafd, &readfds)) { + if (meta_job_event(NULL) <= 0) + metafd = -1; + } } - fclose(fp); } #endif /* USE_META */ Index: stable/12/contrib/bmake/meta.h =================================================================== --- stable/12/contrib/bmake/meta.h (revision 361673) +++ stable/12/contrib/bmake/meta.h (revision 361674) @@ -1,56 +1,59 @@ -/* $NetBSD: meta.h,v 1.5 2016/05/12 20:28:34 sjg Exp $ */ +/* $NetBSD: meta.h,v 1.6 2020/01/19 19:42:32 riastradh Exp $ */ /* * Things needed for 'meta' mode. */ /* * Copyright (c) 2009-2010, Juniper Networks, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ typedef struct BuildMon { char meta_fname[MAXPATHLEN]; - int filemon_fd; + struct filemon *filemon; int mon_fd; FILE *mfp; } BuildMon; extern Boolean useMeta; struct Job; /* not defined yet */ void meta_init(void); void meta_finish(void); void meta_mode_init(const char *); void meta_job_start(struct Job *, GNode *); void meta_job_child(struct Job *); +void meta_job_parent(struct Job *, pid_t); +int meta_job_fd(struct Job *); +int meta_job_event(struct Job *); void meta_job_error(struct Job *, GNode *, int, int); void meta_job_output(struct Job *, char *, const char *); int meta_cmd_finish(void *); int meta_job_finish(struct Job *); Boolean meta_oodate(GNode *, Boolean); void meta_compat_start(void); void meta_compat_child(void); -void meta_compat_parent(void); +void meta_compat_parent(pid_t); Index: stable/12/contrib/bmake/mk/ChangeLog =================================================================== --- stable/12/contrib/bmake/mk/ChangeLog (revision 361673) +++ stable/12/contrib/bmake/mk/ChangeLog (revision 361674) @@ -1,1435 +1,1540 @@ +2020-05-15 Simon J Gerraty + + * install-mk (MK_VERSION): 20200515 + + * dirdeps.mk: set _debug_* earlier and allow passing -d* + flags to submake when building DIRDEPS_CACHE + +2020-05-09 Simon J Gerraty + + * whats.mk: more easily extensible + +2020-05-02 Simon J Gerraty + + * whats.mk: greatly simplify by adding what.c to SRCS + +2020-05-01 Simon J Gerraty + + * whats.mk: for libs take care how we add to *OBJS + + * lib.mk: : works better with whats.mk + +2020-04-25 Simon J Gerraty + + * install-mk (MK_VERSION): 20200420 + + * meta.stage.mk: it is not a STAGE_CONFLICT if some-target.dirdep + contains the same ${RELDIR} and a prefix match for our ${TARGET_SPEC} + +2020-04-16 Simon J Gerraty + + * install-mk (MK_VERSION): 20200416 + + * sys/*.mk: set MAKE_SHELL rather than SHELL so as not to + interfere with user env. + + * sys.mk: default MAKE_SHELL to sh and SHELL to MAKE_SHELL + + * autodep.mk: use MAKE_SHELL. + +2019-11-21 Simon J Gerraty + + * gendirdeps.mk: clear .SUFFIXES to avoid a lot of + wasted effort, and unexport _meta_files when no longer needed as + it consumes space we need for command line. + +2019-11-11 Simon J Gerraty + + * dirdeps.mk _DIRDEP_USE: use DIRDEP_DIR and add + DIRDEP_USE_PRELUDE at start - facilitates job distribution + +2019-10-04 Simon J Gerraty + + * dirdeps-targets.mk: Use TARGET_SPEC_LAST_LIST + defaults to ${${TARGET_SPEC_VARS:[-1]}_LIST} to match valid + TARGET_SPEC qualified depend files. + +2019-10-02 Simon J Gerraty + + * dirdeps-targets.mk: encapsulate logic for finding top-level + targets to set initial DIRDEPS for DIRDEPS_BUILD + +2019-09-27 Simon J Gerraty + + * install-mk (MK_VERSION): 20190911 + + * compiler.mk: set COMPILER_TYPE + +2019-07-17 Simon J Gerraty + + * install-mk (MK_VERSION): 20190704 + + * sys/Darwin.mk: support for Objective-C and clang + +2019-05-30 Simon J Gerraty + + * dirdeps.mk: avoid insanely long command line when generating cache + +2019-05-23 Simon J Gerraty + + * install-mk (MK_VERSION): 20190505 + + * whats.mk: handle corner case SHLIB defined but not LIB + +2018-09-19 Simon J Gerraty + + * install-mk (MK_VERSION): 20180919 + + * dirdeps-options.mk: .undef cannot handle var that expands to + more than one var. + +2018-07-08 Simon J Gerraty + + * meta.stage.mk: allow wildcards in STAGE_FILES.* etc. + +2018-06-01 Simon J Gerraty + + * meta.autodep.mk: export META_FILES to avoid command line limit + * gendirdeps.mk: if we have lots of .meta files put them in + an @list + +2018-05-28 Simon J Gerraty + + * dirdeps-options.mk: use local.dirdeps-options.mk + not local.dirdeps-option.mk + 2018-04-20 Simon J Gerraty * install-mk (MK_VERSION): 20180420 * dirdeps.mk: include local.dirdeps-build.mk when .MAKE.LEVEL > 0 ie. we are building something. 2018-04-14 Simon J Gerraty * FILES: add dirdeps-options.mk to deal with optional DIRDEPS. 2018-04-05 Simon J Gerraty * install-mk (MK_VERSION): 20180405 * ldorder.mk: describe how to use LDORDER_EXTERN_BARRIER if needed. 2018-01-18 Simon J Gerraty * install-mk (MK_VERSION): 20180118 * ldorder.mk: let make compute correct link order 2017-12-12 Simon J Gerraty * install-mk (MK_VERSION): 20171212 * gendirdeps.mk: guard against bogus entries in GENDIRDEPS_FILTER 2017-11-14 Simon J. Gerraty * install-mk (MK_VERSION): 20171111 * lib.mk: ensure META_NOECHO is set 2017-10-25 Simon J. Gerraty * Allow for host32 on rare occasions. 2017-10-18 Simon J. Gerraty * install-mk (MK_VERSION): 20171018 * whats.mk: include what_thing in what_uuid to avoid problem when building multiple apps in the same directory. 2017-08-12 Simon J. Gerraty * install-mk (MK_VERSION): 20170812 * autoconf.mk: Use CONFIGURE_DEPS so Makefile can add dependencies for config.recheck and config.gen 2017-06-30 Simon J. Gerraty * install-mk (MK_VERSION): 20170630 * meta.stage.mk: avoid triggering stage_* targets with nothing to do. 2017-05-23 Simon J. Gerraty * meta2deps.py: take special care of '..' 2017-05-15 Simon J. Gerraty * install-mk (MK_VERSION): 20170515 * dirdeps.mk (DEP_EXPORT_VARS): on rare occasions it is useful/necessary for a Makefile.depend file to export some knobs. This is complicated when we are doing DIRDEPS_CACHE, so we will handle export of any variables listed in DEP_EXPORT_VARS. 2017-05-08 Simon J. Gerraty * install-mk (MK_VERSION): 20170505 * meta2deps.py: fix botched indenation. 2017-05-05 Simon J. Gerraty * sys/*.mk: Remove setting of MAKE it is unnecessary and in many cases wrong (basname rather than full path) * scripts.mk (SCRIPTSGROUPS): make this more like files.mk and inc.mk * init.mk: define realbuild to simplify logic in {lib,prog}.mk etc 2017-05-01 Simon J. Gerraty * install-mk (MK_VERSION): 20170501 * doc.mk: fix typo in DOC_INSTALL_OWN * inc.mk: handle INCGROUPS similar to freebsd * files.mk: add something for files too * add staging logic to lib.mk prog.mk etc. 2017-04-24 Simon J. Gerraty * install-mk (MK_VERSION): 20170424 * dirdeps.mk: set NO_DIRDEPS when bootstrapping. also target of bootstrap-this when sed is needed should be ${_want:T} 2017-04-18 Simon J. Gerraty * install-mk (MK_VERSION): 20170418 * auto.obj.mk: if using MAKEOBJDIRPREFIX check if it is a prefix match for .CURDIR - in which case .CURDIR *is* __objdir. 2017-04-01 Simon J. Gerraty * install-mk (MK_VERSION): 20170401 * meta2deps.py: add is_src so we can check if obj dependency is also a src dependency. 2017-03-26 Simon J. Gerraty * install-mk (MK_VERSION): 20170326 * meta.stage.mk: do nothing if NO_STAGING is defined. 2017-03-24 Simon J. Gerraty * auto.obj.mk: handle the case of __objdir=obj or obj.${MACHINE} etc. 2017-03-18 Simon J. Gerraty * mkopt.sh: treat WITH_*=NO like no; ie. WITHOUT_* 2017-03-01 Simon J. Gerraty * install-mk (MK_VERSION): 20170301 * dirdeps.mk (_build_all_dirs): update this outside test for empty DIRDEPS. * meta.stage.mk: allow multiple inclusion to the extent it makes sense. 2017-02-14 Simon J. Gerraty * prog.mk (install_links): depends on realinstall 2017-02-12 Simon J. Gerraty * install-mk (MK_VERSION): 20170212 * dpadd.mk: avoid applying :T:R twice to DPLIBS entries 2017-01-30 Simon J. Gerraty * install-mk (MK_VERSION): 20170130 * dirdeps.mk: use :range if we can. * sys.vars.mk: provide M_cmpv if MAKE_VERSION >= 20170130 * meta2deps.py: clean paths without using realpath() where possible. fix sort_unique. 2016-12-12 Simon J. Gerraty * install-mk (MK_VERSION): 20161212 * meta2deps.py: set pid_cwd[pid] when we process 'C'hdir, rather than when we detect pid change. 2016-12-07 Simon J. Gerraty * install-mk (MK_VERSION): 20161207 * meta.stage.mk: add stage_as_and_symlink for staging packages. We build foo.tgz stage_as foo-${VERSION}.tgz but want to be able to use foo.tgz to reference the latest staged version - so we make foo.tgz a symlink to it. Using a target to do both operations ensures we stay in sync. 2016-11-26 Simon J. Gerraty * install-mk (MK_VERSION): 20161126 * dirdeps.mk: set DIRDEPS_CACHE before we include local.dirdeps.mk so it can add dependencies. 2016-10-10 Simon J. Gerraty * dirdeps.mk: set DEP_* before we expand .MAKE.DEPENDFILE_PREFERENCE do that they can influence the result correctly. * dirdeps.mk (${DIRDEPS_CACHE}): make sure we pass on TARGET_SPEC * dirdeps.mk: Add ONLY_TARGET_SPEC_LIST and NOT_TARGET_SPEC_LIST similar to ONLY_MACHINE_LIST and NOT_MACHINE_LIST 2016-10-05 Simon J. Gerraty * dirdeps.mk: remove dependence on jot (normal situations anyway). Before we read another Makefile.depend* set DEP_* vars from _DEP_TARGET_SPEC in case it uses any of them with := When bootstrapping, trim any ,* from extention of chosen _src Makefile.depend* to get the machine value we subst for. 2016-09-30 Simon J. Gerraty * dirdeps.mk: use TARGET_SPEC_VARS to qualify components added to DEP_SKIP_DIR and DEP_DIRDEPS_FILTER * sys.mk: extract some bits to sys.{debug,vars}.mk for easier re-use by others. 2016-09-23 Simon Gerraty * lib.mk: Use ${PICO} for extension for PIC objects. default to .pico (like NetBSD) safe on case insensitive filesystem. 2016-08-19 Simon J. Gerraty * meta.sys.mk (META_COOKIE_TOUCH): use ${.OBJDIR}/${.TARGET:T} as default 2016-08-15 Simon J. Gerraty * install-mk (MK_VERSION): 20160815 * dirdeps.mk (.MAKE.META.IGNORE_FILTER): set filter to only consider Makefile.depend* when checking if DIRDEPS_CACHE is up-to-date. 2016-08-13 Simon J. Gerraty * meta.sys.mk (.MAKE.META.IGNORE_PATHS): in meta mode we can ignore the mtime of makefiles 2016-08-02 Simon J. Gerraty * install-mk (MK_VERSION): 20160802 * lib.mk (libinstall): depends on beforinstall * prog.mk (proginstall): depends on beforinstall patch from Lauri Tirkkonen * dirdeps.mk (bootstrap): When bootstrapping; creat .MAKE.DEPENDFILE_DEFAULT and allow additional filtering via .MAKE.DEPENDFILE_BOOTSTRAP_SED * dirdeps.mk: move some comments to where they make sense. 2016-07-27 Simon J. Gerraty * dirdeps.mk (DIRDEPS_CACHE): no dirname. 2016-06-02 Simon J. Gerraty * install-mk (MK_VERSION): 20160602 * meta.autodep.mk: when passing META_FILES to gendirdeps.mk do not apply :T to META_XTRAS patch from Bryan Drewery at FreeBSD.org. 2016-05-30 Simon J. Gerraty * install-mk (MK_VERSION): 20160530 * meta.stage.mk: we assume ${CLEANFILES} gets .NOPATH make it so. 2016-05-12 Simon J. Gerraty * install-mk (MK_VERSION): 20160512 * dpadd.mk: always include local.dpadd.mk if it exists remove some things that better belong in local.dpadd.mk skip INCLUDES_* for staged libs unless SRC_* defined. * own.mk: add INCLUDEDIR 2016-04-18 Simon J. Gerraty * dirdeps.mk: when doing -f dirdeps.mk if target suppies no TARGET_MACHINE - :E will be empty or match part of path, use ${MACHINE} 2016-04-07 Simon J. Gerraty * meta.autodep.mk: issue a warning if UPDATE_DEPENDFILE=NO due to NO_FILEMON_COOKIE * dirdeps.mk: move the logic that allows for make -f dirdeps.mk some/dir.${TARGET_SPEC} inside the check for !target(_DIRDEP_USE) 2016-04-04 Simon J. Gerraty * Use <> when including local*.mk and others which may exist elsewhere so that user can better control what they get. * meta.autodep.mk (NO_FILEMON_COOKIE): create a cookie if we ever build dir with nofilemon so that UPDATE_DEPENDFILE will be forced to NO until cleaned. 2016-04-01 Simon J. Gerraty * install-mk (MK_VERSION): 20160401 * meta2deps.py: fix old print statement when debugging. * gendirdeps.mk: META2DEPS_CMD append M2D_EXCLUDES with -X patch from Bryan Drewery 2016-03-22 Simon J. Gerraty * install-mk (MK_VERSION): 20160317 (St. Pats) * warnings.mk: g++ does not like -Wimplicit * sys.mk sys/*.mk lib.mk prog.mk: use CXX_SUFFIXES to handle the pelthora of common suffixes for C++ * lib.mk: use .So for shared objects 2016-03-15 Simon J. Gerraty * install-mk (MK_VERSION): 20160315 * meta.stage.mk (LN_CP_SCRIPT): do not ln(1) if we have to chmod(1) normally only applies to scripts. * dirdeps.mk: NO_DIRDEPS_BELOW to supress DIRDEPS below RELDIR as well as outside it. 2016-03-10 Simon J. Gerraty * install-mk (MK_VERSION): 20160310 * dirdeps.mk: use targets rather than a list to track DIRDEPS that we have processed; the list gets very inefficient as number of DIRDEPS gets large. * sys.dependfile.mk: fix comment wrt MACHINE * meta.autodep.mk: ignore staged DPADDs when bootstrapping. patch from Bryan Drewery 2016-03-02 Simon J. Gerraty * meta2deps.sh: don't ignore subdirs. patch from Bryan Drewery 2016-02-26 Simon J. Gerraty * install-mk (MK_VERSION): 20160226 * gendirdeps.mk: mark _DEPENDFILE .NOMETA 2016-02-20 Simon J. Gerraty * dirdeps.mk: we shouldn't normally include .depend but if we do use .dinclude if we can. 2016-02-18 Simon J. Gerraty * install-mk (MK_VERSION): 20160218 * sys.clean-env.mk: with recent change to Var_Subst() we cannot use the '$$' trick, but .export-literal does the job we need. * auto.dep.mk: make use .dinclude if we can. 2016-02-05 Simon J. Gerraty * dirdeps.mk: Add _build_all_dirs such that local.dirdeps.mk can add fully qualified dirs to it. These will be built normally but the current DEP_RELDIR will not depend on then (to avoid cycles). This makes it easy to hook things like unit-tests into build. 2016-01-21 Simon J. Gerraty * dirdeps.mk: add bootstrap-empty 2015-12-12 Simon J. Gerraty * install-mk (MK_VERSION): 20151212 * auto.obj.mk: do not require MAKEOBJDIRPREFIX to exist. only apply :tA to __objdir when comparing to .OBJDIR 2015-11-14 Simon J. Gerraty * install-mk (MK_VERSION): 20151111 * meta.sys.mk: include sys.dependfile.mk * sys.mk (OPTIONS_DEFAULT_NO): use options.mk to set MK_AUTO_OBJ and MK_DIRDEPS_BUILD include local.sys.env.mk early include local.sys.mk later * own.mk (OPTIONS_DEFAULT_NO): AUTO_OBJ etc moved to sys.mk 2015-11-13 Simon J. Gerraty * meta.sys.mk (META_COOKIE_TOUCH): add ${META_COOKIE_TOUCH} to the end of scripts to touch cookie * meta.stage.mk: stage_libs should ignore SYMLINKS. 2015-10-23 Simon J. Gerraty * install-mk (MK_VERSION): 20151022 * sys.mk: BSD/OS does not have 'type' as a shell builtin. 2015-10-20 Simon J. Gerraty * install-mk (MK_VERSION): 20151020 * dirdeps.mk: Add logic for make -f dirdeps.mk some/dir.${TARGET_SPEC} 2015-10-14 Simon J. Gerraty * install-mk (MK_VERSION): 20151010 2015-10-02 Simon J. Gerraty * meta.stage.mk: use staging: ${STAGE_TARGETS:... to have stage_lins run last in non-jobs mode. Use .ORDER only for jobs mode. 2015-09-02 Simon J. Gerraty * rst2htm.mk: allow for per target flags etc. 2015-09-01 Simon J. Gerraty * install-mk (MK_VERSION): 20150901 * doc.mk: create dir if needed use DOC_INSTALL_OWN 2015-06-15 Simon J. Gerraty * install-mk (MK_VERSION): 20150615 * auto.obj.mk: allow use of MAKEOBJDIRPREFIX too. Follow make's normal precedence rules. * gendirdeps.mk: allow customization of the header. eg. for FreeBSD: GENDIRDEPS_HEADER= echo '\# ${FreeBSD:L:@v@$$$v$$ @:M*F*}'; * meta.autodep.mk: ignore dirdeps.cache* * meta.stage.mk: when bootstrapping options it can be handy to throw warnings rather than errors for staging conflicts. * meta.sys.mk: include local.meta.sys.mk for customization 2015-06-06 Simon J. Gerraty * install-mk (MK_VERSION): 20150606 * dirdeps.mk: don't rely on manually maintained Makefile.depend to set DEP_RELDIR and reset DIRDEPS. By setting DEP_RELDIR ourselves we can skip :tA * gendirdeps.mk: skip setting DEP_RELDIR. 2015-05-24 Simon J. Gerraty * dirdeps.mk: avoid wildcards like make(bootstrap*) 2015-05-20 Simon J. Gerraty * install-mk (MK_VERSION): 20150520 * dirdeps.mk: when we are building dirdeps cache file we *want* meta_oodate to look at all the Makefile.depend files, so set .MAKE.DEPENDFILE to something that won't match. * meta.stage.mk: for STAGE_AS_* basename of file may not be unique so first use absolute path as key. Also skip staging at level 0. 2015-04-30 Simon J. Gerraty * install-mk (MK_VERSION): 20150430 * dirdeps.mk: fix _count_dirdeps for non-cache case. 2015-04-16 Simon J. Gerraty * install-mk (MK_VERSION): 20150411 bump version * own.mk: put AUTO_OBJ in OPTIONS_DEFAULT_NO rather than YES. it is here mainly for documentation purposes, since if using auto.obj.mk it is better done via sys.mk 2015-04-01 Simon J. Gerraty * install-mk (MK_VERSION): 20150401 * meta2deps.sh: support @list * meta2deps.py: updates from Juniper o add EXCLUDES o skip bogus input files. o treat 'M' and 'L' as both an 'R' and a 'W' 2015-03-03 Simon J. Gerraty * install-mk (MK_VERSION): 20150303 * dirdeps.mk: if MK_DIRDEPS_CACHE is yes, use dirdeps-cache which is built via sub-make so we have a .meta file to tell if it is out-of-date. The dirdeps-cache contains the same dependency rules that we normaly construct on the fly. This adds a few seconds overhead when the cache is out of date, but for a large target, the savings can be significant (10-20min). 2014-11-18 Simon J. Gerraty * install-mk (MK_VERSION): 20141118 * meta.stage.mk: add stale_staged * dirdeps.mk (_DIRDEP_USE_LEVEL): allow this to be tweaked only useful under very rare conditions such as FreeBSD's make universe. * auto.obj.mk: Allow MK_AUTO_OBJ to set MKOBJDIRS=auto 2014-11-11 Simon J. Gerraty * install-mk (MK_VERSION): 20141111 * mkopt.sh: use consistent semantics for _mk_opt and _mk_opts 2014-11-09 Simon J. Gerraty * FILES: include mkopt.sh which allows handling options in shell scripts in a manner compatible with options.mk 2014-10-12 Simon J. Gerraty * meta.stage.mk: ensure only _STAGED_DIRS under objroot are used for GENDIRDEPS_FILTER to avoid surprises. 2014-10-10 Simon J. Gerraty * dirdeps.mk (NSkipHostDir): this needs SRCTOP prepended since by the time it is applied to __depdirs they have. * dirdeps.mk fix filtering of _machines since M_dep_qual_fixes expects patterns like *.${MACHINE} * cython.mk (pyprefix?): use pyprefix to find python bits since prefix might be something else (where we install our stuff) 2014-09-11 Simon J. Gerraty * install-mk (MK_VERSION): 20140911 * dirdeps.mk: add bootstrap target to simplify adding support for new MACHINE. 2014-09-01 Simon J. Gerraty * gendirdeps.mk: Add handling of GENDIRDEPS_FILTER_DIR_VARS and GENDIRDEPS_FILTER_VARS to make it easier to produce sharable Makefile.depend files. 2014-08-28 Simon J. Gerraty * install-mk (MK_VERSION): 20140828 * cython.mk: capture logic for building python extension modules with Cython. 2014-08-08 Simon J. Gerraty * meta.stage.mk (_STAGE_AS_BASENAME_USE): Add StageAs variant 2014-08-02 Simon J. Gerraty * install-mk (MK_VERSION): 20140801 * dep.mk: use explicit MKDEP_MK rather than overload MKDEP to identify the autodep.mk variant. * sys.dependfile.mk: delete .MAKE.DEPENDFILE if its initial value does not match .MAKE.DEPENDFILE_PREFIX * meta.autodep.mk: if _bootstrap_dirdeps add RELDIR to DIRDEPS 2014-05-22 Simon J. Gerraty * install-mk (MK_VERSION): 20140522 * lib.mk: use CC to link shlib for linux too patch from Brendan MacDonell 2014-05-05 Simon J. Gerraty * meta.autodep.mk: add _reldir_{finish,failed} for gathering stats if WITH_META_STATS is defined. 2014-05-02 Simon J. Gerraty * dirdeps.mk: accept -DWITHOUT_DIRDEPS (same a as -DNO_DIRDEPS) to supress dirdeps outside of .CURDIR. 2014-04-05 Simon J. Gerraty * Fix spelling errors - patch from Pedro Giffuni 2014-03-14 Simon J. Gerraty * install-mk (MK_VERSION): 20140314 * dirdeps.mk (beforedirdeps): a handy hook * dirdeps.mk (DIRDEP_MAKE): allow the actual command we run to visit leaf dirs to be intercepted (eg. for distributed build). * dirdeps.mk (__depdirs): ensure // don't sneak in * gendirdeps.mk (DIRDEPS): ensure // don't sneak in 2014-02-21 Simon J. Gerraty * rst2htm.mk (RST2PDF): add support for rst2pdf 2014-02-14 Simon J. Gerraty * install-mk (MK_VERSION): bump version * dirdeps.mk (_last_dependfile): use .INCLUDEDFROMFILE if available. 2014-02-10 Simon J. Gerraty * options.mk: avoid :U so this isn't bmake dependent 2014-02-09 Simon J. Gerraty * options.mk: cleanup and simplify semanitcs NO_* dominates all, if both WITH_* and WITHOUT_* are defined then result is DOMINATE_* which defaults to "no". Ie. WITHOUT_ normally wins. 2013-12-12 Simon J. Gerraty * install-mk (MK_VERSION): bump version * meta2deps.py: convert to print function for python3 compat. we also need to open files with mode 'r' rather than 'rb' otherwise we get bytes instead of strings. 2013-10-10 Simon J. Gerraty * install-mk (MK_VERSION): bump version * dirdeps.mk: when TARGET_SPEC_VARS is more than just MACHINE apply the same filtering (M_dep_qual_fixes) when setting _machines as _build_dirs. Also fix the filtering of Makefile.depend files - for reporting what we are looking for (M_dep_qual_fixes can get confused by Makefile.depend) Add some more debug info. 2013-09-04 Simon J. Gerraty * gendirdeps.mk (_objtops): fix typo also while processing M2D_OBJROOTS to gather qualdir_list qualify $ql with loop iterator to ensure correct results. 2013-08-01 Simon J. Gerraty * install-mk (MK_VERSION): 20130801 * libs.mk: update to match progs.mk 2013-07-26 Simon J. Gerraty * install-mk (MK_VERSION): 20130726 some updates from Juniper and FreeBSD o meta2deps.py: indicate file and line number when we hit parse errors also allow @file to provide huge list of .meta files. * meta2deps.py: add try_parse() to cleanup the above. 2013-07-16 Simon J. Gerraty * install-mk (MK_VERSION): 20130716 * own.mk: add GPROG as an option * prog.mk: honor MK_GPROF==yes 2013-05-10 Simon J. Gerraty * install-mk (MK_VERSION): 20130505 * gendirdeps.mk, meta2deps.py, meta2deps.sh: handle $TARGET_SPEC for when $MACHINE isn't enough for objdir distinction. Bring meta2deps.sh closer to par with meta2deps.py. 2013-04-18 Simon J. Gerraty * meta.stage.mk: set INSTALL to STAGE_INSTALL when making 'all' also if the target 'beforeinstall' exists, make it depend on .dirdep (incase it uses STAGE_INSTALL). 2013-04-17 Simon J. Gerraty * install-mk (MK_VERSION): 20130401 ;-) * meta.stage.mk (STAGE_INSTALL_SH): add stage-install.sh as wrapper around install(1). * options.mk (OPTION_PREFIX): Allow a prefix other than MK_ 2013-03-30 Simon J. Gerraty * meta2deps.py (MetaFile.__init__): ensure self.cwd is initialized. * install-mk (MK_VERSION): bump version 2013-03-21 Simon J. Gerraty * install-mk (MK_VERSION): bump version * gendirdeps.mk: do not apply :tA to DPADD entries, since we lose any trailing /., rather apply :tA only when needed. * gendirdeps.mk: better mimic meta2deps handling of .dirdep files. * meta.stage.mk (LN_CP_SCRIPT): Add LnCp to do the ln||cp dance consistently. * dirdeps.mk: better describe the dance in sys.mk for TARGET_SPEC. 2013-03-18 Simon J. Gerraty * gendirdeps.mk: revert the dance around .MAKE.DEPENDFILE_DEFAULT it is simpler to just not update when say building for "host" (where we know we apply filters to DIRDEPS), and using a non-machine qualified dependfile. 2013-03-16 Simon J. Gerraty * dirdeps.mk: improve DIRDEPS filtering by allowing DEP_SKIP_DIR and DEP_DIRDEPS_FILTER to vary by DEP_MACHINE and DEP_TARGET_SPEC * gendirdeps.mk: ensure _objroot has trailing / if it needs it. * meta2deps.py: if machine is "host", then also trim self.host_target from any OBJROOTS. 2013-03-11 Simon J. Gerraty * gendirdeps.mk: if .MAKE.DEPENDFILE_DEFAULT is not machine qualified but _DEPENDFILE is, and .MAKE.DEPENDFILE_DEFAULT exists but _DEPENDFILE does not, compare the new _DEPENDFILE against .MAKE.DEPENDFILE_DEFAULT and discard if the same. 2013-03-08 Simon J. Gerraty * meta.stage.mk: use STAGE_TARGETS to control .ORDER and hook to all: via staging: 2013-03-07 Simon J. Gerraty * sys.dependfile.mk (.MAKE.DEPENDFILE_DEFAULT): use a separate variable for the default .MAKE.DEPENDFILE value so that it can be controlled independently of .MAKE.DEPENDFILE_PREFERENCE * meta.stage.mk: throw error if cp fails etc. Stage*() return early if passed no args. .ORDER stage_* 2013-03-03 Simon J. Gerraty * install-mk (MK_VERSION): bump version * gendirdeps.mk: handle multiple M2D_OBJROOTS better. 2013-02-10 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20130210 * import latest dirdeps.mk, gendirdeps.mk and meta2deps.py from Juniper. o dirdeps.mk now fully supports TARGET_SPEC consisting of more than just MACHINE. o no longer use DEP_MACHINE from Makefile.depend* so remove it. 2013-01-23 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20130123 * meta.stage.mk: add stage_links (hard links). if doing hard links, we add dest to link as well. Default the stage dir for [sym]links to STAGE_OBJTOP since these are typically specified as absolute paths. Add -m "mode" flag to StageFiles and StageAs. 2012-11-11 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20121111 * autoconf.mk: avoid meta mode seeing changed commands for config.status * meta.autodep.mk: pass resolved MAKESYSPATH to gendirdeps in case we were found via .../mk * sys.clean-env.mk: move it from examples, we and others use it "as is". * FILES: add srctop.mk and options.mk * own.mk: convert to using options.mk which is modeled after FreeBSD's handling of MK_* but more flexible. This allows MK_* for boolean knobs to not be confused with MK* which can be commands. * examples/sys.clean-env.mk: add WITH[OUT]_ to MAKE_ENV_SAVE_PREFIX_LIST. Mention that HOME=/var/empty might be a good idea. 2012-11-08 Simon J. Gerraty * sys.dependfile.mk: if not depend file exists, $MACHINE specific ones are supported but not the default, check if any exist and follow suit. 2012-11-06 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20121106 2012-11-05 Simon J. Gerraty * import latest dirdeps.mk and meta2deps.py from Juniper. * progs.mk: add MAN and CXXFLAGS to PROG_VARS also add PROGS_TARGETS and pass on PROG_CXX if it seems appropriate. 2012-11-04 Simon J. Gerraty * meta.stage.mk: update CLEANFILES remove redundant cp of .dirdep from STAGE_AS_SCRIPT. * progs.mk: Add LDADD to PROG_VARS 2012-10-12 Simon J. Gerraty * meta.stage.mk (STAGE_DIR_FILTER): track dirs we stage to in _STAGED_DIRS so that these can be turned into filters for GENDIRDEPS_FILTER. 2012-10-10 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20121010 * meta.stage.mk (STAGE_DIRDEP_SCRIPT): check that an existing target.dirdep matches .dirdep 2012-08-08 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20120808 * import latest meta2deps.py from Juniper. 2012-07-11 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20120711 * dep.mk: add explicit dependencies on SRCS after applying SRCS_DEP_FILTER * meta.autodep.mk: add explicit dependencies on SRCS after applying SRCS_DEP_FILTER * meta.autodep.mk: ensure GENDIRDEPS_FILTER is exported if needed. 2012-06-26 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20120626 * meta.sys.mk: ignore PYTHON if it does not exist compare ${.MAKE.DEPENDFILE:E} against ${MACHINE} is more reliable. * meta.stage.mk: examine .MAKE.DEPENDFILE_PREFERENCE for any entries ending in .${MACHINE} to decide if qualified _dirdep is needed. * gendirdeps.mk: only produce unqualified deps if no .MAKE.DEPENDFILE_PREFERENCE ends in .${MACHINE} * meta.subdir.mk: apply SUBDIRDEPS_FILTER 2012-04-20 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20120420 * add sys.dependfile.mk so we can experiment with .MAKE.DEPENDFILE_PREFERENCE * meta.autodep.mk: _DEPENDFILE is precious! 2012-03-15 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20120315 * install-new.mk: avoid being interrupted 2012-02-26 Simon J. Gerraty * man.mk: MAN might have multiple values so be careful with exists(). 2012-01-19 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20120112 * fix examples/sys.clean-env.mk so that MAKEOBJDIR is handled as: MAKEOBJDIR='${.CURDIR:S,${SRCTOP},${OBJTOP},}' 2011-12-03 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20111201 * import dirdeps.mk from Juniper sjg@ o more consistent handling of DEP_MACHINE, especially when dealing with an odd Makefile.depend, when normally using Makefile.depend.${MACHINE} 2011-11-22 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20111122 * meta.autodep.mk: add some debug output, be more crisp about updating. Use ${.ALLTARGETS:M*.o} as a clue for .depend 2011-11-13 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20111111 it's too cool to miss * import meta* updates from Juniper sjg@ o dirdeps.mk set DEP_MACHINE for Makefile.depend (when we are normally using Makefile.depend.${MACHINE}), handy for read-only manually maintained dependencies. o meta2deps.py add a clear 'ERROR:' token if an exception is raised. o gendirdeps.mk if ERROR: from meta2deps.py do not update anything. 2011-10-30 Simon J. Gerraty * install-new.mk separate the cmp and copy logic to its own function. 2011-10-28 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20111028 * sys.mk: include auto.obj.mk if MKOBJDIRS is set to auto * subdir.mk: ensure _SUBDIRUSE is provided * meta.autodep.mk: remove dependency of gendirdeps.mk on auto.obj.mk * meta.subdir.mk: always allow for Makefile.depend 2011-10-10 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20111010 o minor tweak to *dirdeps.mk from Juniper sjg@ 2011-10-01 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20111001 o add meta2deps.py from Juniper sjg@ o tweak gendirdeps.mk to work with meta2deps.py when not cross-building * autoconf.mk: add autoconf-input as a hook for regenerating AUTOCONF_INPUTS (configure). 2011-08-24 Simon J. Gerraty * meta.autodep.mk: if we do not have OBJS, .depend isn't a useful trigger for updating Makefile.depend* 2011-08-08 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20110808 * obj.mk: minor cleanup * auto.obj.mk: improve description of Mkdirs and honor NO_OBJ too. 2011-08-01 Simon J. Gerraty * auto.obj.mk (.OBJDIR): throw an error if we cannot use the specified dir. 2011-06-28 Simon J. Gerraty * meta.autodep.mk: if XMAKE_META_FILE is set the makefile uses a foreign make, and so dependencies can only be gathered from a clean tree build. 2011-06-24 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20110622 * meta.autodep.mk: improve bootstraping 2011-06-10 Simon J. Gerraty * yacc.mk: handle the corner case of .c being removed while .h remains. 2011-06-08 Simon J. Gerraty * yacc.mk: do .y.h and .y.c separately 2011-06-04 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20110606 * don't store SRC_DIRDEPS in Makefile.depend* by default not everyone needs it. 2011-05-04 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20110505 first release including meta mode makefiles 2011-05-02 Simon J. Gerraty * meta.stage.mk: add STAGE_AS_SETS and stage_as for things that need to be staged with different names. 2011-05-01 Simon J. Gerraty * meta.stage.mk: add notion of STAGE_SETS so a makefile can stage to multiple dirs 2011-04-03 Simon J. Gerraty * rst2htm.mk: convert rst to s5 (slides) or plain html depending on target name. 2011-03-30 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20110330 2011-03-29 Simon J. Gerraty * sys.mk (_DEBUG_MAKE_FLAGS): use indirection so that DEBUG_MAKE_FLAGS0 can be used to debug level 0 only and DEBUG_MAKE_FLAGS for the rest. * sys.mk: re-define M_whence in terms of M_type. M_type is useful for checking if something is a builtin. 2011-03-16 Simon J. Gerraty * meta.stage.mk: add stage_symlinks and leverage StageLinks for stage_libs 2011-03-10 Simon J. Gerraty * dirdeps.mk: correct value for _depdir_files depends on .MAKE.DEPENDFILE Add our copyright - just to make it clear we have frobbed this quite a bit. DEP_MACHINE needs to be set to MACHINE each time, if using only Makefile.depend (cf. Makefile.depend.${MACHINE}) * meta.stage.mk: meta mode version of staging * init.mk, final.mk: include local.*.mk to simplify customization 2011-03-03 Simon J. Gerraty * auto.obj.mk: just because we are doing mk destroy, we should still set .OBJDIR correctly if it exists. * install-mk (mksrc): do not exclude meta.sys.mk 2011-03-01 Simon J. Gerraty * host-target.mk: set/export _HOST_ARCH etc separately, catch junk resulting from uname -p, so we can find sys/Linux.mk correctly. 2011-02-18 Simon J. Gerraty * meta.sys.mk: throw an error if /dev/filemon is missing and we expected to be updating Makefile.depend* 2011-02-14 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20110214 * meta.subdir.mk: add support for -DBOOTSTRAP_DEPENDFILES 2010-09-25 Simon J. Gerraty * meta.sys.mk: not valid for older bmake 2010-09-24 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100919 include dirdeps.mk et al from Juniper Networks, for meta mode - requires filemon(9). * sys.mk, subdir.mk: Add hooks for meta mode. we do this as meta.sys.mk, meta.autodep.mk and meta.subdir.mk to make turning it on/off simple. 2010-06-16 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100616 * fix typo in sys.mk 2010-06-12 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100612 * lib.mk: remove duplicate addition to SOBJS 2010-06-10 Simon J. Gerraty * sys.mk: Add a means of selectively turning on debug flags. Eg. DEBUG_MAKE_FLAGS=-dv DEBUG_MAKE_DIRS="*lib/sjg" will act as if we did make -dv if .CURDIR ends in lib/sjg DEBUG_MAKE_SYS_DIRS does the same thing, but we set the flags at the start of sys.mk rather than the end. This only makes sense for leaf dirs, so we check that .MAKE.LEVEL > 0 2010-06-09 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100608 * sys.mk: include sys.env.mk later so it can use M_ListToSkip et al. * examples/sys.clean-env.mk: require MAKE_VERIONS >= 20100606 also make it easier for folk to tweak 2010-06-08 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100606 do not install examples/* * FILES: add examples/sys.clean-env.mk * examples/sys.clean-env.mk: use .export-env to handle MAKEOBJDIR this requires bmake-20100606 or later to work. 2010-05-13 Simon J. Gerraty * sys.mk (M_tA): better simulate the result of :tA if not available. 2010-05-04 Simon J. Gerraty * sys.mk: canonicalize MAKE_VERSION old versions reported bmake- build- whereas we only care about 2010-04-25 Simon J. Gerraty * install-mk: just warn about FORCE_{BSD,SYS}_MK being ignored * lib.mk: we only build the shared lib if SHLIB_FULLVERSION is !empty 2010-04-22 Simon J. Gerraty * dpadd.mk: use LDADD_* if defined. 2010-04-21 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100420 * sys/NetBSD.mk: add MACHINE_CPU to keep netbsd makefiles happy * autoconf.mk allow AUTO_AUTOCONF 2010-04-19 Simon J. Gerraty * obj.mk: add objwarn to keep freebsd makefiles happy * auto.obj.mk: ensure Mkdirs is available. * FILES: add auto.dep.mk - a simpler version of autodep.mk * dep.mk: auto.dep.mk does not do 'make depend' so ignore it if asked to do that. fix/simplify the tests for when to run mkdep. * auto.dep.mk: add some explanation of how/what we do. * autodep.mk: skip the .OPTIONAL frobbing of .depend bmake's FROM_DEPEND flag makes it redundant. 2010-04-13 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100404 * subdir.mk: protect from multiple inclusion using _SUBDIRUSE. * obj.mk: protect from multiple inclusion even as bsd.obj.mk Also create a target _SUBDIRUSE so that we can be used without subdir.mk 2010-04-12 Simon J. Gerraty * dep.mk: use <> when .including so can override. 2010-01-11 Simon J. Gerraty * lib.mk (SHLIB_LINKS): ensure a string comparison. 2010-01-04 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20100102 * own.mk: ensure PRINTOBJDIR works * autoconf.mk: pass on CONFIGURE_ARGS * init.mk: handle COPTS.${.IMPSRC:T} etc. * lib.mk: allow sys.mk to control SHLIB_FULLVERSION fix handling of symlinks for darwin * libnames.mk: add DSHLIBEXT for libs which only exist as shared. * man.mk: suppress chown when not root. * rst2htm.mk: allow srcs from multiple locations. * sys.mk: M_whence, stop after 1st line of output. * sys/Darwin.mk: Use .dylib for DSHLIBEXT and HOST_LIBEXT * sys/SunOS.mk: we need to export PATH 2009-12-23 Simon J. Gerraty * install-mk (MK_VERSION): bump version include rst2htm.mk 2009-12-17 Simon J. Gerraty * sys.mk,libnames.mk add .-include this allows local customization without the need to edit the distributed files. 2009-12-14 Simon J. Gerraty * dpadd.mk (__dpadd_libdirs): order -L's to avoid picking up older versions already installed. 2009-12-13 Simon J. Gerraty * stage.mk (.stage-install): generalize lib.mk's .libinstall * rules.mk rules for generic Makefile. * inc.mk install for includes. 2009-12-11 Simon J. Gerraty * sys/NetBSD.mk (MAKE_VERSION): some of our *.mk want to check this, so provide it if using native make. 2009-12-10 Simon J. Gerraty * FILES: move all the platform *.sys.mk files to sys/*.mk * Rename Generic.sys.mk to sys.mk - we always want it. 2009-11-17 Simon J. Gerraty * install-mk (MK_VERSION): bump version * host-target.mk: only export the expensive stuff * Generic.sys.mk (sys_mk): for SunOS we need to look for ${HOST_OS}.${HOST_OSMAJOR} too! 2009-11-07 Simon J. Gerraty * install-mk (MK_VERSION): bump version * lib.mk: if sys.mk doesn't give us an lorder, don't use it. based on patch from Greg Olszewski. * Generic.sys.mk: if we have nothing to work with set LORDER etc only if we can find it. 2009-09-08 Simon J. Gerraty * install-mk (MK_VERSION): bump version * man.mk: cleanman: remove CLEANMAN if defined. 2009-09-04 Simon J. Gerraty * SunOS.5.sys.mk (CC): Use ?= like the other *sys.mk 2009-07-17 Simon J. Gerraty * install-mk (MK_VERSION): bump version include auto.obj.mk 2009-03-26 Simon J. Gerraty * prog.mk,lib.mk: ensure test of USE_DPADD_MK doesn't fail. 2008-11-11 Simon J. Gerraty * install-mk (MK_VERSION): bump version man.mk: ensure we generate *.cat1 etc in . 2008-07-16 Simon J. Gerraty * install-mk (MK_VERSION): bump version add prlist.mk 2007-11-25 Simon J. Gerraty * Generic.sys.mk: Allow os specific sys.mk to be in a subdir of ${.PARSEDIR} 2007-11-22 Simon J. Gerraty * install-mk (MK_VERSION): bump version * general cleanup * dpadd.mk introduce DPMAGIC_LIBS_* 2007-04-30 Simon J. Gerraty * install-mk (MK_VERSION): bump version * libs.mk, progs.mk, autodep.mk: allow for per lib/prog depend files and ensure clean is called for each lib/prog. 2007-03-27 Simon J. Gerraty * autodep.mk (.depend): delete lines that do not start with space and do not contain ':' 2007-02-16 Simon J. Gerraty * autodep.mk (.depend): gcc may wrap lines if pathnames are long so make sure the transform for .OPTIONAL copes. 2007-02-03 Simon J. Gerraty * install-mk (MK_VERSION): bump version * own.mk: make sure RM and LN are defined. * obj.mk: fix a typo, and objlink target. 2006-12-30 Simon J. Gerraty * install-mk (MK_VERSION): bump version * added libs.mk - analogous to progs.mk make both of them always inlcude {lib,prog}.mk 2006-12-28 Simon J. Gerraty * progs.mk: add a means of building multiple apps in one dir. 2006-11-26 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20061126 * warnings.mk: detect invalid WARNINGS_SET * warnings.mk: use ${.TARGET:T:R}.o when looking for target specific warnings. * For .cc sources, turn off warnings that g++ vomits on. 2006-11-08 Simon J. Gerraty * own.mk: if __initialized__ target doesn't exist and we are FreeBSD we got here directly from sys.mk 2006-11-06 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20061106 add scripts.mk 2006-03-18 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20060318 * autodep.mk: avoid := when modifying OBJS into __dependsrcs 2006-03-02 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20060302 * autodep.mk: use -MF et al to help gcc+ccache DTRT. 2006-03-01 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20060301 * autodep.mk (.depend): if MAKE_VERSION is newer than 20050530 we can make .END depend on .depend and make .depend depend on __depsrcs that exist. * dpadd.mk: add SRC_PATHADD 2005-11-04 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20051104 * prog.mk: remove all the LIBC?= junk, use .-include libnames.mk instead (none by default). also if USE_DPADD_MK is set, include that. 2005-10-09 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20051001 Add UnixWare.sys.mk from Klaus Heinz. 2005-04-05 Simon J. Gerraty * install-mk: always install *.sys.mk and if need be symlink one to sys.mk 2005-03-22 Simon J. Gerraty * subdir.mk, own.mk: use .MAKE rather than MAKE 2004-02-15 Simon J. Gerraty * own.mk: don't use NetBSD's _SRC_TOP_ it can cause confusion. Also don't take just 'mk' as a srctop indicator. 2004-02-14 Simon J. Gerraty * warnings.mk: overhauled, now very powerful. 2004-02-03 Simon J. Gerraty * Generic.sys.mk: need to use ${.PARSEDIR} with exists(). 2004-02-01 Simon J. Gerraty * install-mk (MK_VERSION): bump version to 20040201 * extract HOST_TARGET stuff to host-target.mk so own.mk and Generic.sys.mk can share. * fix typo in autodep.mk _SUBDIRUSE not _SUBDIR. 2003-09-30 Simon J. Gerraty * install-mk (MK_VERSION): 20030930 * rename generic.sys.mk to Generic.sys.mk so that it does not get installed (unless being used as sys.mk) * set OS and ROOT_GROUP for those that we know the value. for others (eg. Generic.sys.mk) wrap the != in an .ifndef so we don't do it again for each sub-make. 2003-09-28 Simon J. Gerraty * install-mk (MK_VERSION): 20030928 Add some extra *.sys.mk from bootstrap-pkgsrc some of these likely still need work. Make everything default to root:wheel ownership, sys.mk can set ROOT_GROUP accordingly. 2003-08-07 Simon J. Gerraty * install-mk: if FORCE_BSD_MK={cp,ln} use the ones in SYS_MK_DIR not the portable ones. 2003-07-31 Simon J. Gerraty * install-mk: add ability to use cp -f when updating destination .mk files. Also now possible to play games with FORCE_SYS_MK=ln etc on *BSD machines to link /usr/share/mk/sys.mk into dest - not recommended unless you seriously want to. 2003-07-28 Simon J. Gerraty * own.mk (IMPFLAGS): add support for COPTS.${IMPSRC:T} etc for semi-compatability with NetBSD. 2003-07-23 Simon J. Gerraty * install-mk: add a version indicator 2003-07-22 Simon J. Gerraty * prog.mk: don't try and use ${LIBCRT0} if its /dev/null * install-mk: Allow FORCE_SYS_MK to come from env Index: stable/12/contrib/bmake/mk/FILES =================================================================== --- stable/12/contrib/bmake/mk/FILES (revision 361673) +++ stable/12/contrib/bmake/mk/FILES (revision 361674) @@ -1,70 +1,72 @@ ChangeLog FILES README auto.obj.mk autoconf.mk autodep.mk auto.dep.mk +compiler.mk cython.mk dep.mk doc.mk dpadd.mk files.mk final.mk host-target.mk host.libnames.mk inc.mk init.mk install-mk java.mk ldorder.mk lib.mk libnames.mk libs.mk links.mk man.mk manifest.mk mk-files.txt mkopt.sh nls.mk obj.mk options.mk own.mk prlist.mk prog.mk progs.mk rst2htm.mk scripts.mk srctop.mk stage-install.sh subdir.mk sys.mk sys.clean-env.mk sys.debug.mk sys.dependfile.mk sys.vars.mk sys/AIX.mk sys/Darwin.mk sys/Generic.mk sys/HP-UX.mk sys/IRIX.mk sys/Linux.mk sys/NetBSD.mk sys/OSF1.mk sys/OpenBSD.mk sys/SunOS.mk sys/UnixWare.mk target-flags.mk warnings.mk whats.mk yacc.mk dirdeps.mk dirdeps-options.mk +dirdeps-targets.mk gendirdeps.mk install-new.mk meta2deps.py meta2deps.sh meta.sys.mk meta.autodep.mk meta.stage.mk meta.subdir.mk Index: stable/12/contrib/bmake/mk/autodep.mk =================================================================== --- stable/12/contrib/bmake/mk/autodep.mk (revision 361673) +++ stable/12/contrib/bmake/mk/autodep.mk (revision 361674) @@ -1,218 +1,219 @@ # # RCSid: -# $Id: autodep.mk,v 1.36 2016/04/05 15:58:37 sjg Exp $ +# $Id: autodep.mk,v 1.37 2020/04/17 21:08:17 sjg Exp $ # # @(#) Copyright (c) 1999-2010, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # This module provides automagic dependency generation along the # lines suggested in the GNU make.info # The depend target is mainly for backwards compatibility, # dependencies are normally updated as part of compilation. .if !target(__${.PARSEFILE}__) __${.PARSEFILE}__: DEPENDFILE?= .depend .for d in ${DEPENDFILE:N.depend} # bmake only groks .depend .if ${MAKE_VERSION} < 20160218 .-include <$d> .else .dinclude <$d> .endif .endfor # it does nothing if SRCS is not defined or is empty .if defined(SRCS) && !empty(SRCS) DEPSRCS?=${SRCS} __depsrcs=${DEPSRCS:M*.c} __depsrcs+=${DEPSRCS:M*.y} __depsrcs+=${DEPSRCS:M*.l} __depsrcs+=${DEPSRCS:M*.s} __depsrcs+=${DEPSRCS:M*.S} __depsrcs+=${DEPSRCS:M*.cc} __depsrcs+=${DEPSRCS:M*.cpp} __depsrcs+=${DEPSRCS:M*.C} __depsrcs+=${DEPSRCS:M*.cxx} __depsrcs+=${DEPSRCS:M*.pc} .for s in ${__depsrcs} ${s:T:R}.d: $s .endfor __depsrcs:=${__depsrcs:T:R:S/$/.d/g} # we also need to handle makefiles where the .d's from __depsrcs # don't match those from OBJS # we avoid using := here, since the modifier applied to OBJS # can cause trouble if there are any undefined vars in OBJS. __dependsrcsx?= ${__depsrcs} ${OBJS:S/.o/.d/} __dependsrcs= ${__dependsrcsx:O:u} # clean up any .c files we may have generated #__gensrcs:= ${DEPSRCS:M*.y} ${DEPSRCS:M*.l} #CLEANFILES+= ${__gensrcs:T:R:S/$/.c/g} # set this to -MMD to ignore /usr/include # actually it ignores <> so may not be a great idea CFLAGS_MD?=-MD # -MF etc not available on all gcc versions. # we "fix" the .o later CFLAGS_MF?=-MF ${.TARGET:T:R}.d -MT ${.TARGET:T:R}.o CFLAGS+= ${CFLAGS_MD} ${CFLAGS_MF} RM?= rm +MAKE_SHELL?= sh # watch out for people who don't use CPPFLAGS CPPFLAGS_MD=${CFLAGS:M-[IUD]*} ${CPPFLAGS} CXXFLAGS_MD=${CXXFLAGS:M-[IUD]*} ${CPPFLAGS} # just in case these need to be different CC_MD?=${CC} CXX_MD?=${CXX} # should have been set by sys.mk CXX_SUFFIXES?= .cc .cpp .cxx .C # so we can do an explicit make depend, but not otherwise .if make(depend) .SUFFIXES: .d .if empty(CFLAGS_MD) .y.d: @echo updating dependencies for $< @${YACC} ${YFLAGS} $< - @${SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} y.tab.c | sed '/:/s/^/$@ /' > $@" || { ${RM} -f y.tab.c $@; false; } + @${MAKE_SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} y.tab.c | sed '/:/s/^/$@ /' > $@" || { ${RM} -f y.tab.c $@; false; } @${RM} -f y.tab.c .l.d: @echo updating dependencies for $< ${LEX} ${LFLAGS} $< - @${SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} lex.yy.c | sed '/:/s/^/$@ /' > $@" || { ${RM} -f lex.yy.c $@; false; } + @${MAKE_SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} lex.yy.c | sed '/:/s/^/$@ /' > $@" || { ${RM} -f lex.yy.c $@; false; } @${RM} -f lex.yy.c .c.d: @echo updating dependencies for $< - @${SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} $< | sed '/:/s/^/$@ /' > $@" || { ${RM} -f $@; false; } + @${MAKE_SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} $< | sed '/:/s/^/$@ /' > $@" || { ${RM} -f $@; false; } .s.d .S.d: @echo updating dependencies for $< - @${SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} ${AINC} $< | sed '/:/s/^/$@ /' > $@" || { ${RM} -f $@; false; } + @${MAKE_SHELL} -ec "${CC_MD} -M ${CPPFLAGS_MD} ${AINC} $< | sed '/:/s/^/$@ /' > $@" || { ${RM} -f $@; false; } ${CXX_SUFFIXES:%=%.d}: @echo updating dependencies for $< - @${SHELL} -ec "${CXX_MD} -M ${CXXFLAGS_MD} $< | sed '/:/s/^/$@ /' > $@" || { ${RM} -f $@; false; } + @${MAKE_SHELL} -ec "${CXX_MD} -M ${CXXFLAGS_MD} $< | sed '/:/s/^/$@ /' > $@" || { ${RM} -f $@; false; } .else .y.d: ${YACC} ${YFLAGS} $< ${CC_MD} ${CFLAGS_MD:S/D//} ${CPPFLAGS_MD} y.tab.c > $@ || { ${RM} -f y.tab.c $@; false; } ${RM} -f y.tab.c .l.d: ${LEX} ${LFLAGS} $< ${CC_MD} ${CFLAGS_MD:S/D//} ${CPPFLAGS_MD} lex.yy.c > $@ || { ${RM} -f lex.yy.c $@; false; } ${RM} -f lex.yy.c .c.d: ${CC_MD} ${CFLAGS_MD:S/D//} ${CPPFLAGS_MD} $< > $@ || { ${RM} -f $@; false; } .s.d .S.d: ${CC_MD} ${CFLAGS_MD:S/D//} ${CPPFLAGS_MD} ${AINC} $< > $@ || { ${RM} -f $@; false; } ${CXX_SUFFIXES:%=%.d}: ${CXX_MD} ${CFLAGS_MD:S/D//} ${CXXFLAGS_MD} $< > $@ || { ${RM} -f $@; false; } .endif .if !target(depend) depend: beforedepend ${DEPENDFILE} afterdepend _SUBDIRUSE ${DEPENDFILE}: ${DEPSRCS} ${__dependsrcs} .NOPATH: ${__dependsrcs} .OPTIONAL: ${__dependsrcs} .endif .endif # make(depend) .if empty(CFLAGS_MD) # make sure the .d's are generated/updated ${PROG} ${_LIBS}: ${DEPENDFILE} .endif .ORDER: beforedepend ${DEPENDFILE} afterdepend .if ${.OBJDIR} != ${.CURDIR} __depfiles= *.d .else __depfiles= ${__dependsrcs} .endif DEPCLEANFILES= ${DEPENDFILE} ${__depfiles} y.tab.d *.tmp.d cleandir: cleanautodepend cleanautodepend: ${RM} -f ${DEPCLEANFILES} CLEANFILES+= ${DEPCLEANFILES} .if defined(__dependsrcs) && !empty(__dependsrcs) .if make(depend) || !(make(clean*) || make(destroy*) || make(obj) || make(*install) || make(install-*)) # this ensures we do the right thing if only building a shared or # profiled lib OBJ_EXTENSIONS?=.o .po .so .So MDLIB_SED= -e '/:/s,^\([^\.:]*\)\.[psS]*o,${OBJ_EXTENSIONS:S,^,\1,},' .ifdef NOMD_SED .ifdef LIB MD_SED=sed ${MDLIB_SED} .else MD_SED=cat .endif .else # arrange to put some variable names into ${DEPENDFILE} .ifdef LIB MD_SED=sed ${MDLIB_SED} .else MD_SED=sed .endif SUBST_DEPVARS+= SB TOP BACKING SRC SRCDIR BASE BASEDIR .for v in ${SUBST_DEPVARS} .if defined(${v}) && !empty(${v}) MD_SED+= -e 's,${$v},$${$v},' .endif .endfor .endif .if (${MD_SED} == "sed") MD_SED=cat .endif # this will be done whenever make finishes successfully .if ${MAKE_VERSION:U0:[1]:C/.*-//} < 20050530 .END: .else .END: ${DEPENDFILE} # we do not want to trigger building .d's just use them if they exist ${DEPENDFILE}: ${__dependsrcs:@d@${exists($d):?$d:}@} .endif -@${MD_SED} ${__depfiles} > ${DEPENDFILE}.new 2> /dev/null && \ test -s ${DEPENDFILE}.new && mv ${DEPENDFILE}.new ${DEPENDFILE}; \ ${RM} -f ${DEPENDFILE}.new .endif .endif .else depend: beforedepend afterdepend _SUBDIRUSE .endif .if !target(beforedepend) beforedepend: .endif .if !target(afterdepend) afterdepend: .endif .endif Index: stable/12/contrib/bmake/mk/compiler.mk =================================================================== --- stable/12/contrib/bmake/mk/compiler.mk (nonexistent) +++ stable/12/contrib/bmake/mk/compiler.mk (revision 361674) @@ -0,0 +1,43 @@ +# $Id: compiler.mk,v 1.6 2019/09/28 17:12:00 sjg Exp $ +# +# @(#) Copyright (c) 2019, Simon J. Gerraty +# +# This file is provided in the hope that it will +# be of use. There is absolutely NO WARRANTY. +# Permission to copy, redistribute or otherwise +# use this file is hereby granted provided that +# the above copyright notice and this notice are +# left intact. +# +# Please send copies of changes and bug-fixes to: +# sjg@crufty.net +# + +.if !target(__${.PARSEFILE}__) +__${.PARSEFILE}__: + +.if ${MACHINE} == "common" +COMPILER_TYPE = none +COMPILER_VERSION = 0 +.endif +.if empty(COMPILER_TYPE) || empty(COMPILER_VERSION) +# gcc does not always say gcc +_v != ${CC} --version 2> /dev/null | \ + egrep -i 'clang|cc|[1-9]\.[0-9]|Free Software Foundation' +.if empty(COMPILER_TYPE) +.if ${_v:Mclang} != "" +COMPILER_TYPE = clang +.elif ${_v:M[Gg][Cc][Cc]} != "" || ${_v:MFoundation*} != "" +COMPILER_TYPE = gcc +.endif +.endif +.if empty(COMPILER_VERSION) +COMPILER_VERSION != echo "${_v:M[1-9].[0-9]*}:[1]" | \ + awk -F. '{print $$1 * 10000 + $$2 * 100 + $$3;}' +.endif +.undef _v +.endif +# just in case we don't recognize compiler +COMPILER_TYPE ?= unknown +COMPILER_VERSION ?= 0 +.endif Property changes on: stable/12/contrib/bmake/mk/compiler.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/mk/dirdeps-options.mk =================================================================== --- stable/12/contrib/bmake/mk/dirdeps-options.mk (revision 361673) +++ stable/12/contrib/bmake/mk/dirdeps-options.mk (revision 361674) @@ -1,70 +1,73 @@ -# $Id: dirdeps-options.mk,v 1.5 2018/04/18 15:53:57 sjg Exp $ +# $Id: dirdeps-options.mk,v 1.9 2018/09/20 00:07:19 sjg Exp $ # # @(#) Copyright (c) 2018, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # ## # # This makefile is used to deal with optional DIRDEPS. # # It is to be included by Makefile.depend.options in a # directory which has DIRDEPS affected by optional features. # Makefile.depend.options should set DIRDEPS_OPTIONS and # may also set specific DIRDEPS.* for those options. # # If a Makefile.depend.options file exists, it will be included by # dirdeps.mk and meta.autodep.mk # -# We include local.dirdeps-option.mk which may also define DIRDEPS.* +# We include local.dirdeps-options.mk which may also define DIRDEPS.* # for options. # # Thus a directory, that is affected by an option FOO would have # a Makefile.depend.options that sets # DIRDEPS_OPTIONS= FOO # It can also set either/both of # DIRDEPS.FOO.yes # DIRDEPS.FOO.no # to whatever applies for that dir, or it can rely on globals -# set in local.dirdeps-option.mk +# set in local.dirdeps-options.mk # Either way, we will .undef DIRDEPS.* when done. # This should have been set by Makefile.depend.options # before including us DIRDEPS_OPTIONS ?= # pickup any DIRDEPS.* we need -.-include +.-include .if ${.MAKE.LEVEL} == 0 # :U below avoids potential errors when we := .for o in ${DIRDEPS_OPTIONS:tu} DIRDEPS += ${DIRDEPS.$o.${MK_$o:U}:U} .endfor DIRDEPS := ${DIRDEPS:O:u} # avoid cross contamination -.undef ${DIRDEPS_OPTIONS:tu:@o@DIRDEPS.$o.yes DIRDEPS.$o.no@} +.for o in ${DIRDEPS_OPTIONS:tu} +.undef DIRDEPS.$o.yes +.undef DIRDEPS.$o.no +.endfor .else # whether options are enabled or not, # we want to filter out the relevant DIRDEPS.* # we should only be included by meta.autodep.mk # if dependencies are to be updated .for o in ${DIRDEPS_OPTIONS:tu} .for d in ${DIRDEPS.$o.yes} ${DIRDEPS.$o.no} .if exists(${SRCTOP}/$d) GENDIRDEPS_FILTER += N$d* .elif exists(${SRCTOP}/${d:R}) GENDIRDEPS_FILTER += N${d:R}* .endif .endfor .endfor .endif Index: stable/12/contrib/bmake/mk/dirdeps-targets.mk =================================================================== --- stable/12/contrib/bmake/mk/dirdeps-targets.mk (nonexistent) +++ stable/12/contrib/bmake/mk/dirdeps-targets.mk (revision 361674) @@ -0,0 +1,133 @@ +# RCSid: +# $Id: dirdeps-targets.mk,v 1.9 2019/10/06 20:07:50 sjg Exp $ +# +# @(#) Copyright (c) 2019 Simon J. Gerraty +# +# This file is provided in the hope that it will +# be of use. There is absolutely NO WARRANTY. +# Permission to copy, redistribute or otherwise +# use this file is hereby granted provided that +# the above copyright notice and this notice are +# left intact. +# +# Please send copies of changes and bug-fixes to: +# sjg@crufty.net +# + +## +# This makefile is used to set initial DIRDEPS for top-level build +# targets. +# +# The basic idea is that we have a list of directories in +# DIRDEPS_TARGETS_DIRS which are relative to SRCTOP. +# When asked to make 'foo' we look for any directory named 'foo' +# under DIRDEPS_TARGETS_DIRS. +# We then search those dirs for any Makefile.depend* +# Finally we select any that match conditions like REQUESTED_MACHINE +# or TARGET_SPEC and initialize DIRDEPS accordingly. +# + +.if ${.MAKE.LEVEL} == 0 +# pickup customizations +.-include + +# for DIRDEPS_BUILD this is how we prime the pump +DIRDEPS_TARGETS_DIRS ?= targets targets/pseudo +# these prefixes can modify how we behave +# they need to be stripped when looking for target dirs +DIRDEPS_TARGETS_PREFIX_LIST ?= pkg- build- + +# matching target dirs if any +tdirs := ${.TARGETS:Nall:${DIRDEPS_TARGETS_PREFIX_LIST:@p@S,^$p,,@:ts:}:@t@${DIRDEPS_TARGETS_DIRS:@d@$d/$t@}@:@d@${exists(${SRCTOP}/$d):?$d:}@} + +.if !empty(DEBUG_DIRDEPS_TARGETS) +.info tdirs=${tdirs} +.endif + +.if !empty(tdirs) +# some things we know we want to ignore +DIRDEPS_TARGETS_SKIP_LIST += \ + *~ \ + *.bak \ + *.inc \ + *.old \ + *.options \ + *.orig \ + *.rej \ + +# the list of MACHINEs we consider +DIRDEPS_TARGETS_MACHINE_LIST += \ + ${ALL_MACHINE_LIST:U} \ + ${PSEUDO_MACHINE_LIST:Ucommon host host32} \ + ${TARGET_MACHINE_LIST} + +DIRDEPS_TARGETS_MACHINE_LIST := ${DIRDEPS_TARGETS_MACHINE_LIST:O:u} + +# raw Makefile.depend* list +tdeps != 'cd' ${SRCTOP} && 'ls' -1 ${tdirs:O:u:@d@$d/${.MAKE.DEPENDFILE_PREFIX}*@} 2> /dev/null; echo +.if ${DEBUG_DIRDEPS_TARGETS:U:Mdep*} != "" +.info tdeps=${tdeps} +.endif +# remove things we know we don't want +tdeps := ${tdeps:${DIRDEPS_TARGETS_SKIP_LIST:${M_ListToSkip}}} +.if ${DEBUG_DIRDEPS_TARGETS:U:Mdep*} != "" +.info tdeps=${tdeps} +.endif + +# plain entries (no qualifiers) these apply to any TARGET_SPEC +ptdeps := ${tdeps:M*${.MAKE.DEPENDFILE_PREFIX}:S,/${.MAKE.DEPENDFILE_PREFIX},,} + +# MACHINE qualified entries +mqtdeps := ${DIRDEPS_TARGETS_MACHINE_LIST:@m@${tdeps:M*.$m}@:S,/${.MAKE.DEPENDFILE_PREFIX},,} + +tqtdeps = +.if ${TARGET_SPEC_VARS:[#]} > 1 +# TARGET_SPEC qualified entries +.if !empty(TARGET_SPEC_LIST) +# we have a list of valid TARGET_SPECS; use it +tqtdeps := ${TARGET_SPEC_LIST:U:O:u:@t@${tdeps:M*.$t}@:S,/${.MAKE.DEPENDFILE_PREFIX},,} +.else +# do we have a list of valid tuple members for at least +# the last tupple element? if so match on that +TARGET_SPEC_LAST_LIST ?= ${${TARGET_SPEC_VARS:[-1]}_LIST} +.if !empty(TARGET_SPEC_LAST_LIST) +tqtdeps := ${TARGET_SPEC_LAST_LIST:U:O:u:@t@${tdeps:M*,$t}@:S,/${.MAKE.DEPENDFILE_PREFIX},,} +.else +# this is sub-optimal match MACHINE, +tqtdeps := ${DIRDEPS_TARGETS_MACHINE_LIST:@m@${tdeps:M*.$m,*}@:S,/${.MAKE.DEPENDFILE_PREFIX},,} +.endif +.endif +.endif + +# now work out what we want in DIRDEPS +.if empty(REQUESTED_MACHINE) +# we want them all just as found +DIRDEPS = ${ptdeps} ${mqtdeps} ${tqtdeps} +.else +# we only want those that match REQUESTED_MACHINE/REQUESTED_TARGET_SPEC +# or REQUESTED_TARGET_SPEC (TARGET_SPEC) +DIRDEPS = \ + ${ptdeps:@d@$d.${REQUESTED_TARGET_SPEC:U${TARGET_SPEC:U${REQUESTED_MACHINE}}}@} \ + ${mqtdeps:M*.${REQUESTED_MACHINE}} \ + ${tqtdeps:M*.${REQUESTED_TARGET_SPEC:U${TARGET_SPEC}}} +.endif +# clean up +DIRDEPS := ${DIRDEPS:O:u} + +.if !empty(DEBUG_DIRDEPS_TARGETS) +.for x in tdeps ptdeps mqtdeps tqtdeps DIRDEPS +.info $x=${$x} +.endfor +.endif +.endif +# if we got DIRDEPS get to work +.if !empty(DIRDEPS) +.include + +DIRDEPS_TARGETS_SKIP += all clean* destroy* + +.for t in ${.TARGETS:${DIRDEPS_TARGETS_SKIP:${M_ListToSkip}}} +$t: dirdeps +.endfor +.endif +.endif Property changes on: stable/12/contrib/bmake/mk/dirdeps-targets.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/mk/dirdeps.mk =================================================================== --- stable/12/contrib/bmake/mk/dirdeps.mk (revision 361673) +++ stable/12/contrib/bmake/mk/dirdeps.mk (revision 361674) @@ -1,815 +1,834 @@ -# $Id: dirdeps.mk,v 1.95 2018/04/23 17:53:56 sjg Exp $ +# $Id: dirdeps.mk,v 1.104 2020/05/16 23:21:48 sjg Exp $ -# Copyright (c) 2010-2013, Juniper Networks, Inc. +# Copyright (c) 2010-2020, Simon J. Gerraty +# Copyright (c) 2010-2018, Juniper Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Much of the complexity here is for supporting cross-building. # If a tree does not support that, simply using plain Makefile.depend # should provide sufficient clue. # Otherwise the recommendation is to use Makefile.depend.${MACHINE} # as expected below. # Note: this file gets multiply included. # This is what we do with DIRDEPS # DIRDEPS: # This is a list of directories - relative to SRCTOP, it is # normally only of interest to .MAKE.LEVEL 0. # In some cases the entry may be qualified with a . # or . suffix (see TARGET_SPEC_VARS below), # for example to force building something for the pseudo # machines "host" or "common" regardless of current ${MACHINE}. # # All unqualified entries end up being qualified with .${TARGET_SPEC} # and partially qualified (if TARGET_SPEC_VARS has multiple # entries) are also expanded to a full .. # The _DIRDEP_USE target uses the suffix to set TARGET_SPEC # correctly when visiting each entry. # # The fully qualified directory entries are used to construct a # dependency graph that will drive the build later. # # Also, for each fully qualified directory target, we will search # using ${.MAKE.DEPENDFILE_PREFERENCE} to find additional # dependencies. We use Makefile.depend (default value for # .MAKE.DEPENDFILE_PREFIX) to refer to these makefiles to # distinguish them from others. # # Before each Makefile.depend file is read, we set # DEP_RELDIR to be the RELDIR (path relative to SRCTOP) for # its directory, and DEP_MACHINE etc according to the . # represented by the suffix of the corresponding target. # # Since each Makefile.depend file includes dirdeps.mk, this # processing is recursive and results in .MAKE.LEVEL 0 learning the # dependencies of the tree wrt the initial directory (_DEP_RELDIR). # # BUILD_AT_LEVEL0 # Indicates whether .MAKE.LEVEL 0 builds anything: # if "no" sub-makes are used to build everything, # if "yes" sub-makes are only used to build for other machines. # It is best to use "no", but this can require fixing some # makefiles to not do anything at .MAKE.LEVEL 0. # # TARGET_SPEC_VARS # The default value is just MACHINE, and for most environments # this is sufficient. The _DIRDEP_USE target actually sets # both MACHINE and TARGET_SPEC to the suffix of the current # target so that in the general case TARGET_SPEC can be ignored. # # If more than MACHINE is needed then sys.mk needs to decompose # TARGET_SPEC and set the relevant variables accordingly. # It is important that MACHINE be included in and actually be # the first member of TARGET_SPEC_VARS. This allows other # variables to be considered optional, and some of the treatment # below relies on MACHINE being the first entry. # Note: TARGET_SPEC cannot contain any '.'s so the target # triple used by compiler folk won't work (directly anyway). # # For example: # # # Always list MACHINE first, # # other variables might be optional. # TARGET_SPEC_VARS = MACHINE TARGET_OS # .if ${TARGET_SPEC:Uno:M*,*} != "" # _tspec := ${TARGET_SPEC:S/,/ /g} # MACHINE := ${_tspec:[1]} # TARGET_OS := ${_tspec:[2]} # # etc. # # We need to stop that TARGET_SPEC affecting any submakes # # and deal with MACHINE=${TARGET_SPEC} in the environment. # TARGET_SPEC = # # export but do not track # .export-env TARGET_SPEC # .export ${TARGET_SPEC_VARS} # .for v in ${TARGET_SPEC_VARS:O:u} # .if empty($v) # .undef $v # .endif # .endfor # .endif # # make sure we know what TARGET_SPEC is # # as we may need it to find Makefile.depend* # TARGET_SPEC = ${TARGET_SPEC_VARS:@v@${$v:U}@:ts,} # # The following variables can influence the initial DIRDEPS # computation with regard to the TARGET_SPECs that will be # built. # Most should also be considered by init.mk # # ONLY_TARGET_SPEC_LIST # Defines a list of TARGET_SPECs for which the current # directory can be built. # If ALL_MACHINES is defined, we build for all the # TARGET_SPECs listed. # # ONLY_MACHINE_LIST # As for ONLY_TARGET_SPEC_LIST but only specifies # MACHINEs. # # NOT_TARGET_SPEC_LIST # A list of TARGET_SPECs for which the current # directory should not be built. # # NOT_MACHINE_LIST # A list of MACHINEs the current directory should not be # built for. # .if !target(bootstrap) && (make(bootstrap) || \ make(bootstrap-this) || \ make(bootstrap-recurse) || \ make(bootstrap-empty)) # disable most of below .MAKE.LEVEL = 1 .endif # touch this at your peril _DIRDEP_USE_LEVEL?= 0 .if ${.MAKE.LEVEL} == ${_DIRDEP_USE_LEVEL} # only the first instance is interested in all this .if !target(_DIRDEP_USE) # do some setup we only need once _CURDIR ?= ${.CURDIR} _OBJDIR ?= ${.OBJDIR} now_utc = ${%s:L:gmtime} .if !defined(start_utc) start_utc := ${now_utc} .endif .if ${MAKEFILE:T} == ${.PARSEFILE} && empty(DIRDEPS) && ${.TARGETS:Uall:M*/*} != "" # This little trick let's us do # # mk -f dirdeps.mk some/dir.${TARGET_SPEC} # all: ${.TARGETS:Nall}: all DIRDEPS := ${.TARGETS:M*[/.]*} # so that -DNO_DIRDEPS works DEP_RELDIR := ${DIRDEPS:[1]:R} # this will become DEP_MACHINE below TARGET_MACHINE := ${DIRDEPS:[1]:E:C/,.*//} .if ${TARGET_MACHINE:N*/*} == "" TARGET_MACHINE := ${MACHINE} .endif # disable DIRDEPS_CACHE as it does not like this trick MK_DIRDEPS_CACHE = no .endif # make sure we get the behavior we expect .MAKE.SAVE_DOLLARS = no # make sure these are empty to start with _DEP_TARGET_SPEC = # If TARGET_SPEC_VARS is other than just MACHINE # it should be set by sys.mk or similar by now. # TARGET_SPEC must not contain any '.'s. TARGET_SPEC_VARS ?= MACHINE # this is what we started with TARGET_SPEC = ${TARGET_SPEC_VARS:@v@${$v:U}@:ts,} # this is what we mostly use below DEP_TARGET_SPEC = ${TARGET_SPEC_VARS:S,^,DEP_,:@v@${$v:U}@:ts,} # make sure we have defaults .for v in ${TARGET_SPEC_VARS} DEP_$v ?= ${$v} .endfor .if ${TARGET_SPEC_VARS:[#]} > 1 # Ok, this gets more complex (putting it mildly). # In order to stay sane, we need to ensure that all the build_dirs # we compute below are fully qualified wrt DEP_TARGET_SPEC. # The makefiles may only partially specify (eg. MACHINE only), # so we need to construct a set of modifiers to fill in the gaps. .if ${MAKE_VERSION} >= 20170130 _tspec_x := ${TARGET_SPEC_VARS:range} .elif ${TARGET_SPEC_VARS:[#]} > 10 # seriously? better have jot(1) or equivalent to produce suitable sequence _tspec_x := ${${JOT:Ujot} ${TARGET_SPEC_VARS:[#]}:L:sh} .else # we can provide the sequence ourselves _tspec_x := ${1 2 3 4 5 6 7 8 9 10:L:[1..${TARGET_SPEC_VARS:[#]}]} .endif # this handles unqualified entries M_dep_qual_fixes = C;(/[^/.,]+)$$;\1.$${DEP_TARGET_SPEC}; # there needs to be at least one item missing for these to make sense .for i in ${_tspec_x:[2..-1]} _tspec_m$i := ${TARGET_SPEC_VARS:[2..$i]:@w@[^,]+@:ts,} _tspec_a$i := ,${TARGET_SPEC_VARS:[$i..-1]:@v@$$$${DEP_$v}@:ts,} M_dep_qual_fixes += C;(\.${_tspec_m$i})$$;\1${_tspec_a$i}; .endfor .else # A harmless? default. M_dep_qual_fixes = U .endif .if !defined(.MAKE.DEPENDFILE_PREFERENCE) # .MAKE.DEPENDFILE_PREFERENCE makes the logic below neater? # you really want this set by sys.mk or similar .MAKE.DEPENDFILE_PREFERENCE = ${_CURDIR}/${.MAKE.DEPENDFILE:T} .if ${.MAKE.DEPENDFILE:E} == "${TARGET_SPEC}" .if ${TARGET_SPEC} != ${MACHINE} .MAKE.DEPENDFILE_PREFERENCE += ${_CURDIR}/${.MAKE.DEPENDFILE:T:R}.$${MACHINE} .endif .MAKE.DEPENDFILE_PREFERENCE += ${_CURDIR}/${.MAKE.DEPENDFILE:T:R} .endif .endif _default_dependfile := ${.MAKE.DEPENDFILE_PREFERENCE:[1]:T} _machine_dependfiles := ${.MAKE.DEPENDFILE_PREFERENCE:T:M*${MACHINE}*} # for machine specific dependfiles we require ${MACHINE} to be at the end # also for the sake of sanity we require a common prefix .if !defined(.MAKE.DEPENDFILE_PREFIX) # knowing .MAKE.DEPENDFILE_PREFIX helps .if !empty(_machine_dependfiles) .MAKE.DEPENDFILE_PREFIX := ${_machine_dependfiles:[1]:T:R} .else .MAKE.DEPENDFILE_PREFIX := ${_default_dependfile:T} .endif .endif # this is how we identify non-machine specific dependfiles N_notmachine := ${.MAKE.DEPENDFILE_PREFERENCE:E:N*${MACHINE}*:${M_ListToSkip}} .endif # !target(_DIRDEP_USE) # First off, we want to know what ${MACHINE} to build for. # This can be complicated if we are using a mixture of ${MACHINE} specific # and non-specific Makefile.depend* # if we were included recursively _DEP_TARGET_SPEC should be valid. .if empty(_DEP_TARGET_SPEC) # we may or may not have included a dependfile yet .if defined(.INCLUDEDFROMFILE) _last_dependfile := ${.INCLUDEDFROMFILE:M${.MAKE.DEPENDFILE_PREFIX}*} .else _last_dependfile := ${.MAKE.MAKEFILES:M*/${.MAKE.DEPENDFILE_PREFIX}*:[-1]} .endif .if ${_debug_reldir:U0} .info ${DEP_RELDIR}.${DEP_TARGET_SPEC}: _last_dependfile='${_last_dependfile}' .endif .if empty(_last_dependfile) || ${_last_dependfile:E:${N_notmachine}} == "" # this is all we have to work with DEP_MACHINE = ${TARGET_MACHINE:U${MACHINE}} _DEP_TARGET_SPEC := ${DEP_TARGET_SPEC} .else _DEP_TARGET_SPEC = ${_last_dependfile:${M_dep_qual_fixes:ts:}:E} .endif .if !empty(_last_dependfile) # record that we've read dependfile for this _dirdeps_checked.${_CURDIR}.${TARGET_SPEC}: .endif .endif # by now _DEP_TARGET_SPEC should be set, parse it. .if ${TARGET_SPEC_VARS:[#]} > 1 # we need to parse DEP_MACHINE may or may not contain more info _tspec := ${_DEP_TARGET_SPEC:S/,/ /g} .for i in ${_tspec_x} DEP_${TARGET_SPEC_VARS:[$i]} := ${_tspec:[$i]} .endfor .for v in ${TARGET_SPEC_VARS:O:u} .if empty(DEP_$v) .undef DEP_$v .endif .endfor .else DEP_MACHINE := ${_DEP_TARGET_SPEC} .endif # reset each time through _build_all_dirs = # the first time we are included the _DIRDEP_USE target will not be defined # we can use this as a clue to do initialization and other one time things. .if !target(_DIRDEP_USE) # make sure this target exists dirdeps: beforedirdeps .WAIT beforedirdeps: # We normally expect to be included by Makefile.depend.* # which sets the DEP_* macros below. DEP_RELDIR ?= ${RELDIR} # this can cause lots of output! # set to a set of glob expressions that might match RELDIR DEBUG_DIRDEPS ?= no # remember the initial value of DEP_RELDIR - we test for it below. _DEP_RELDIR := ${DEP_RELDIR} .endif # DIRDEPS_CACHE can be very handy for debugging. # Also if repeatedly building the same target, # we can avoid the overhead of re-computing the tree dependencies. MK_DIRDEPS_CACHE ?= no BUILD_DIRDEPS_CACHE ?= no BUILD_DIRDEPS ?= yes .if ${MK_DIRDEPS_CACHE} == "yes" # this is where we will cache all our work DIRDEPS_CACHE ?= ${_OBJDIR:tA}/dirdeps.cache${.TARGETS:Nall:O:u:ts-:S,/,_,g:S,^,.,:N.} .endif +.if ${DEBUG_DIRDEPS:@x@${DEP_RELDIR:M$x}${${DEP_RELDIR}.${DEP_MACHINE}:L:M$x}@} != "" +_debug_reldir = 1 +.else +_debug_reldir = 0 +.endif +.if ${DEBUG_DIRDEPS:@x@${DEP_RELDIR:M$x}${${DEP_RELDIR}.depend:L:M$x}@} != "" +_debug_search = 1 +.else +_debug_search = 0 +.endif + # pickup customizations # as below you can use !target(_DIRDEP_USE) to protect things # which should only be done once. .-include .if !target(_DIRDEP_USE) # things we skip for host tools SKIP_HOSTDIR ?= NSkipHostDir = ${SKIP_HOSTDIR:N*.host*:S,$,.host*,:N.host*:S,^,${SRCTOP}/,:${M_ListToSkip}} # things we always skip # SKIP_DIRDEPS allows for adding entries on command line. SKIP_DIR += .host *.WAIT ${SKIP_DIRDEPS} SKIP_DIR.host += ${SKIP_HOSTDIR} DEP_SKIP_DIR = ${SKIP_DIR} \ ${SKIP_DIR.${DEP_TARGET_SPEC}:U} \ ${TARGET_SPEC_VARS:@v@${SKIP_DIR.${DEP_$v}:U}@} \ ${SKIP_DIRDEPS.${DEP_TARGET_SPEC}:U} \ ${TARGET_SPEC_VARS:@v@${SKIP_DIRDEPS.${DEP_$v}:U}@} NSkipDir = ${DEP_SKIP_DIR:${M_ListToSkip}} .if defined(NODIRDEPS) || defined(WITHOUT_DIRDEPS) NO_DIRDEPS = .elif defined(WITHOUT_DIRDEPS_BELOW) NO_DIRDEPS_BELOW = .endif .if defined(NO_DIRDEPS) # confine ourselves to the original dir and below. DIRDEPS_FILTER += M${_DEP_RELDIR}* .elif defined(NO_DIRDEPS_BELOW) DIRDEPS_FILTER += M${_DEP_RELDIR} .endif # this is what we run below -DIRDEP_MAKE?= ${.MAKE} +DIRDEP_MAKE ?= ${.MAKE} +DIRDEP_DIR ?= ${.TARGET:R} # we suppress SUBDIR when visiting the leaves # we assume sys.mk will set MACHINE_ARCH # you can add extras to DIRDEP_USE_ENV # if there is no makefile in the target directory, we skip it. _DIRDEP_USE: .USE .MAKE @for m in ${.MAKE.MAKEFILE_PREFERENCE}; do \ test -s ${.TARGET:R}/$$m || continue; \ echo "${TRACER}Checking ${.TARGET:R} for ${.TARGET:E} ..."; \ + ${DIRDEP_USE_PRELUDE} \ MACHINE_ARCH= NO_SUBDIR=1 ${DIRDEP_USE_ENV} \ TARGET_SPEC=${.TARGET:E} \ MACHINE=${.TARGET:E} \ - ${DIRDEP_MAKE} -C ${.TARGET:R} || exit 1; \ + ${DIRDEP_MAKE} -C ${DIRDEP_DIR} || exit 1; \ break; \ done .ifdef ALL_MACHINES # this is how you limit it to only the machines we have been built for # previously. .if empty(ONLY_TARGET_SPEC_LIST) && empty(ONLY_MACHINE_LIST) .if !empty(ALL_MACHINE_LIST) # ALL_MACHINE_LIST is the list of all legal machines - ignore anything else _machine_list != cd ${_CURDIR} && 'ls' -1 ${ALL_MACHINE_LIST:O:u:@m@${.MAKE.DEPENDFILE:T:R}.$m@} 2> /dev/null; echo .else _machine_list != 'ls' -1 ${_CURDIR}/${.MAKE.DEPENDFILE_PREFIX}.* 2> /dev/null; echo .endif _only_machines := ${_machine_list:${NIgnoreFiles:UN*.bak}:E:O:u} .else _only_machines := ${ONLY_TARGET_SPEC_LIST:U} ${ONLY_MACHINE_LIST:U} .endif .if empty(_only_machines) # we must be boot-strapping _only_machines := ${TARGET_MACHINE:U${ALL_MACHINE_LIST:U${DEP_MACHINE}}} .endif .else # ! ALL_MACHINES # if ONLY_TARGET_SPEC_LIST or ONLY_MACHINE_LIST is set, we are limited to that. # Note that ONLY_TARGET_SPEC_LIST should be fully qualified. # if TARGET_MACHINE is set - it is really the same as ONLY_MACHINE_LIST # otherwise DEP_MACHINE is it - so DEP_MACHINE will match. _only_machines := ${ONLY_TARGET_SPEC_LIST:U:M${DEP_MACHINE},*} .if empty(_only_machines) _only_machines := ${ONLY_MACHINE_LIST:U${TARGET_MACHINE:U${DEP_MACHINE}}:M${DEP_MACHINE}} .endif .endif .if !empty(NOT_MACHINE_LIST) _only_machines := ${_only_machines:${NOT_MACHINE_LIST:${M_ListToSkip}}} .endif .if !empty(NOT_TARGET_SPEC_LIST) # we must first qualify _dm := ${DEP_MACHINE} _only_machines := ${_only_machines:M*,*} ${_only_machines:N*,*:@DEP_MACHINE@${DEP_TARGET_SPEC}@:S,^,.,:${M_dep_qual_fixes:ts:}:O:u:S,^.,,} DEP_MACHINE := ${_dm} _only_machines := ${_only_machines:${NOT_TARGET_SPEC_LIST:${M_ListToSkip}}} .endif # clean up _only_machines := ${_only_machines:O:u} # make sure we have a starting place? DIRDEPS ?= ${RELDIR} .endif # target .if !defined(NO_DIRDEPS) && !defined(NO_DIRDEPS_BELOW) .if ${MK_DIRDEPS_CACHE} == "yes" # just ensure this exists build-dirdeps: M_oneperline = @x@\\${.newline} $$x@ .if ${BUILD_DIRDEPS_CACHE} == "no" .if !target(dirdeps-cached) # we do this via sub-make BUILD_DIRDEPS = no # ignore anything but these .MAKE.META.IGNORE_FILTER = M*/${.MAKE.DEPENDFILE_PREFIX}* dirdeps: dirdeps-cached dirdeps-cached: ${DIRDEPS_CACHE} .MAKE @echo "${TRACER}Using ${DIRDEPS_CACHE}" @MAKELEVEL=${.MAKE.LEVEL} ${.MAKE} -C ${_CURDIR} -f ${DIRDEPS_CACHE} \ dirdeps MK_DIRDEPS_CACHE=no BUILD_DIRDEPS=no # these should generally do BUILD_DIRDEPS_MAKEFILE ?= ${MAKEFILE} BUILD_DIRDEPS_TARGETS ?= ${.TARGETS} # we need the .meta file to ensure we update if # any of the Makefile.depend* changed. # We do not want to compare the command line though. ${DIRDEPS_CACHE}: .META .NOMETA_CMP +@{ echo '# Autogenerated - do NOT edit!'; echo; \ echo 'BUILD_DIRDEPS=no'; echo; \ - echo '.include '; \ + echo '.include '; echo; \ } > ${.TARGET}.new +@MAKELEVEL=${.MAKE.LEVEL} DIRDEPS_CACHE=${DIRDEPS_CACHE} \ DIRDEPS="${DIRDEPS}" \ TARGET_SPEC=${TARGET_SPEC} \ MAKEFLAGS= ${.MAKE} -C ${_CURDIR} -f ${BUILD_DIRDEPS_MAKEFILE} \ ${BUILD_DIRDEPS_TARGETS} BUILD_DIRDEPS_CACHE=yes \ .MAKE.DEPENDFILE=.none \ ${.MAKEFLAGS:tW:S,-D ,-D,g:tw:M*WITH*} \ + ${.MAKEFLAGS:tW:S,-d ,-d,g:tw:M-d*} \ 3>&1 1>&2 | sed 's,${SRCTOP},$${SRCTOP},g' >> ${.TARGET}.new && \ mv ${.TARGET}.new ${.TARGET} .endif .elif !target(_count_dirdeps) # we want to capture the dirdeps count in the cache .END: _count_dirdeps _count_dirdeps: .NOMETA @echo '.info $${.newline}$${TRACER}Makefiles read: total=${.MAKE.MAKEFILES:[#]} depend=${.MAKE.MAKEFILES:M*depend*:[#]} dirdeps=${.ALLTARGETS:M${SRCTOP}*:O:u:[#]}' >&3 .endif .elif !make(dirdeps) && !target(_count_dirdeps) beforedirdeps: _count_dirdeps _count_dirdeps: .NOMETA @echo "${TRACER}Makefiles read: total=${.MAKE.MAKEFILES:[#]} depend=${.MAKE.MAKEFILES:M*depend*:[#]} dirdeps=${.ALLTARGETS:M${SRCTOP}*:O:u:[#]} seconds=`expr ${now_utc} - ${start_utc}`" .endif .endif .if ${BUILD_DIRDEPS} == "yes" -.if ${DEBUG_DIRDEPS:@x@${DEP_RELDIR:M$x}${${DEP_RELDIR}.${DEP_MACHINE}:L:M$x}@} != "" -_debug_reldir = 1 -.else -_debug_reldir = 0 -.endif -.if ${DEBUG_DIRDEPS:@x@${DEP_RELDIR:M$x}${${DEP_RELDIR}.depend:L:M$x}@} != "" -_debug_search = 1 -.else -_debug_search = 0 -.endif # the rest is done repeatedly for every Makefile.depend we read. # if we are anything but the original dir we care only about the # machine type we were included for.. .if ${DEP_RELDIR} == "." _this_dir := ${SRCTOP} .else _this_dir := ${SRCTOP}/${DEP_RELDIR} .endif # on rare occasions, there can be a need for extra help _dep_hack := ${_this_dir}/${.MAKE.DEPENDFILE_PREFIX}.inc .-include <${_dep_hack}> .-include <${_dep_hack:R}.options> .if ${DEP_RELDIR} != ${_DEP_RELDIR} || ${DEP_TARGET_SPEC} != ${TARGET_SPEC} # this should be all _machines := ${DEP_MACHINE} .else # this is the machine list we actually use below _machines := ${_only_machines} .if defined(HOSTPROG) || ${DEP_MACHINE:Nhost*} == "" # we need to build this guy's dependencies for host as well. .if ${DEP_MACHINE:Nhost*} == "" _machines += ${DEP_MACHINE} .else _machines += host .endif .endif _machines := ${_machines:O:u} .endif .if ${TARGET_SPEC_VARS:[#]} > 1 # we need to tweak _machines _dm := ${DEP_MACHINE} # apply the same filtering that we do when qualifying DIRDEPS. # M_dep_qual_fixes expects .${MACHINE}* so add (and remove) '.' # Again we expect that any already qualified machines are fully qualified. _machines := ${_machines:M*,*} ${_machines:N*,*:@DEP_MACHINE@${DEP_TARGET_SPEC}@:S,^,.,:${M_dep_qual_fixes:ts:}:O:u:S,^.,,} DEP_MACHINE := ${_dm} _machines := ${_machines:O:u} .endif # reset each time through _build_dirs = .if ${DEP_RELDIR} == ${_DEP_RELDIR} # pickup other machines for this dir if necessary .if ${BUILD_AT_LEVEL0:Uyes} == "no" _build_dirs += ${_machines:@m@${_CURDIR}.$m@} .else _build_dirs += ${_machines:N${DEP_TARGET_SPEC}:@m@${_CURDIR}.$m@} .if ${DEP_TARGET_SPEC} == ${TARGET_SPEC} # pickup local dependencies now .if ${MAKE_VERSION} < 20160220 .-include <.depend> .else .dinclude <.depend> .endif .endif .endif .endif .if ${_debug_reldir} .info ${DEP_RELDIR}.${DEP_TARGET_SPEC}: DIRDEPS='${DIRDEPS}' .info ${DEP_RELDIR}.${DEP_TARGET_SPEC}: _machines='${_machines}' .endif .if !empty(DIRDEPS) # these we reset each time through as they can depend on DEP_MACHINE DEP_DIRDEPS_FILTER = \ ${DIRDEPS_FILTER.${DEP_TARGET_SPEC}:U} \ ${TARGET_SPEC_VARS:@v@${DIRDEPS_FILTER.${DEP_$v}:U}@} \ ${DIRDEPS_FILTER:U} .if empty(DEP_DIRDEPS_FILTER) # something harmless DEP_DIRDEPS_FILTER = U .endif # this is what we start with __depdirs := ${DIRDEPS:${NSkipDir}:${DEP_DIRDEPS_FILTER:ts:}:C,//+,/,g:O:u:@d@${SRCTOP}/$d@} # some entries may be qualified with . # the :M*/*/*.* just tries to limit the dirs we check to likely ones. # the ${d:E:M*/*} ensures we don't consider junos/usr.sbin/mgd __qual_depdirs := ${__depdirs:M*/*/*.*:@d@${exists($d):?:${"${d:E:M*/*}":?:${exists(${d:R}):?$d:}}}@} __unqual_depdirs := ${__depdirs:${__qual_depdirs:Uno:${M_ListToSkip}}} .if ${DEP_RELDIR} == ${_DEP_RELDIR} # if it was called out - we likely need it. __hostdpadd := ${DPADD:U.:M${HOST_OBJTOP}/*:S,${HOST_OBJTOP}/,,:H:${NSkipDir}:${DIRDEPS_FILTER:ts:}:S,$,.host,:N.*:@d@${SRCTOP}/$d@} \ ${DPADD:U.:M${HOST_OBJTOP32:Uno}/*:S,${HOST_OBJTOP32:Uno}/,,:H:${NSkipDir}:${DIRDEPS_FILTER:ts:}:S,$,.host32,:N.*:@d@${SRCTOP}/$d@} __qual_depdirs += ${__hostdpadd} .endif .if ${_debug_reldir} .info depdirs=${__depdirs} .info qualified=${__qual_depdirs} .info unqualified=${__unqual_depdirs} .endif # _build_dirs is what we will feed to _DIRDEP_USE _build_dirs += \ ${__qual_depdirs:M*.host:${NSkipHostDir}:N.host} \ ${__qual_depdirs:N*.host} \ ${_machines:Mhost*:@m@${__unqual_depdirs:@d@$d.$m@}@:${NSkipHostDir}:N.host} \ ${_machines:Nhost*:@m@${__unqual_depdirs:@d@$d.$m@}@} # qualify everything now _build_dirs := ${_build_dirs:${M_dep_qual_fixes:ts:}:O:u} .endif # empty DIRDEPS _build_all_dirs += ${_build_dirs} _build_all_dirs := ${_build_all_dirs:O:u} # Normally if doing make -V something, # we do not want to waste time chasing DIRDEPS # but if we want to count the number of Makefile.depend* read, we do. .if ${.MAKEFLAGS:M-V${_V_READ_DIRDEPS}} == "" .if !empty(_build_all_dirs) .if ${BUILD_DIRDEPS_CACHE} == "yes" -x!= { echo; echo '\# ${DEP_RELDIR}.${DEP_TARGET_SPEC}'; \ - echo 'dirdeps: ${_build_all_dirs:${M_oneperline}}'; echo; } >&3; echo -x!= { ${_build_all_dirs:@x@${target($x):?:echo '$x: _DIRDEP_USE';}@} echo; } >&3; echo +# guard against _build_all_dirs being too big for a single command line +# first get list of dirs that need _DIRDEP_USE +# then export that and _build_all_dirs +_new_dirdeps := ${_build_all_dirs:@x@${target($x):?:$x}@} +.export _new_dirdeps _build_all_dirs +x!= echo; { echo '\# ${DEP_RELDIR}.${DEP_TARGET_SPEC}'; \ + echo "dirdeps: \\"; \ + for x in $$_build_all_dirs; do echo " $$x \\"; done; echo; \ + for x in $$_new_dirdeps; do echo "$$x: _DIRDEP_USE"; done; echo; } >&3 .if !empty(DEP_EXPORT_VARS) # Discouraged, but there are always exceptions. # Handle it here rather than explain how. x!= { echo; ${DEP_EXPORT_VARS:@v@echo '$v=${$v}';@} echo '.export ${DEP_EXPORT_VARS}'; echo; } >&3; echo .endif .else # this makes it all happen dirdeps: ${_build_all_dirs} .endif ${_build_all_dirs}: _DIRDEP_USE .if ${_debug_reldir} .info ${DEP_RELDIR}.${DEP_TARGET_SPEC}: needs: ${_build_dirs} .endif .if !empty(DEP_EXPORT_VARS) .export ${DEP_EXPORT_VARS} DEP_EXPORT_VARS= .endif # this builds the dependency graph .for m in ${_machines} # it would be nice to do :N${.TARGET} .if !empty(__qual_depdirs) .for q in ${__qual_depdirs:${M_dep_qual_fixes:ts:}:E:O:u:N$m} .if ${_debug_reldir} || ${DEBUG_DIRDEPS:@x@${${DEP_RELDIR}.$m:L:M$x}${${DEP_RELDIR}.$q:L:M$x}@} != "" .info ${DEP_RELDIR}.$m: graph: ${_build_dirs:M*.$q} .endif .if ${BUILD_DIRDEPS_CACHE} == "yes" -x!= { echo; echo '${_this_dir}.$m: ${_build_dirs:M*.$q:${M_oneperline}}'; echo; } >&3; echo +_cache_deps := ${_build_dirs:M*.$q} +.export _cache_deps +x!= echo; { echo "${_this_dir}.$m: \\"; \ + for x in $$_cache_deps; do echo " $$x \\"; done; echo; } >&3 .else ${_this_dir}.$m: ${_build_dirs:M*.$q} .endif .endfor .endif .if ${_debug_reldir} .info ${DEP_RELDIR}.$m: graph: ${_build_dirs:M*.$m:N${_this_dir}.$m} .endif .if ${BUILD_DIRDEPS_CACHE} == "yes" -x!= { echo; echo '${_this_dir}.$m: ${_build_dirs:M*.$m:N${_this_dir}.$m:${M_oneperline}}'; echo; } >&3; echo +_cache_deps := ${_build_dirs:M*.$m:N${_this_dir}.$m} +.export _cache_deps +x!= echo; { echo "${_this_dir}.$m: \\"; \ + for x in $$_cache_deps; do echo " $$x \\"; done; echo; } >&3 .else ${_this_dir}.$m: ${_build_dirs:M*.$m:N${_this_dir}.$m} .endif .endfor .endif # Now find more dependencies - and recurse. .for d in ${_build_all_dirs} .if !target(_dirdeps_checked.$d) # once only _dirdeps_checked.$d: .if ${_debug_search} .info checking $d .endif # Note: _build_all_dirs is fully qualifed so d:R is always the directory .if exists(${d:R}) # we pass _DEP_TARGET_SPEC to tell the next step what we want _DEP_TARGET_SPEC := ${d:E} # some makefiles may still look at this _DEP_MACHINE := ${d:E:C/,.*//} # set these too in case Makefile.depend* uses them .if ${TARGET_SPEC_VARS:[#]} > 1 _dtspec := ${_DEP_TARGET_SPEC:S/,/ /g} .for i in ${_tspec_x} DEP_${TARGET_SPEC_VARS:[$i]} := ${_dtspec:[$i]} .endfor .else DEP_MACHINE := ${_DEP_MACHINE} .endif # Warning: there is an assumption here that MACHINE is always # the first entry in TARGET_SPEC_VARS. # If TARGET_SPEC and MACHINE are insufficient, you have a problem. _m := ${.MAKE.DEPENDFILE_PREFERENCE:T:S;${TARGET_SPEC}$;${d:E};:S;${MACHINE};${d:E:C/,.*//};:@m@${exists(${d:R}/$m):?${d:R}/$m:}@:[1]} .if !empty(_m) # M_dep_qual_fixes isn't geared to Makefile.depend _qm := ${_m:C;(\.depend)$;\1.${d:E};:${M_dep_qual_fixes:ts:}} .if ${_debug_search} .info Looking for ${_qm} .endif # set this "just in case" # we can skip :tA since we computed the path above DEP_RELDIR := ${_m:H:S,${SRCTOP}/,,} # and reset this DIRDEPS = .if ${_debug_reldir} && ${_qm} != ${_m} .info loading ${_m} for ${d:E} .endif .include <${_m}> +.else +.-include .endif .endif .endif .endfor .endif # -V .endif # BUILD_DIRDEPS .elif ${.MAKE.LEVEL} > 42 .error You should have stopped recursing by now. .else # we are building something DEP_RELDIR := ${RELDIR} _DEP_RELDIR := ${RELDIR} # Since we are/should be included by .MAKE.DEPENDFILE -# is is a final opportunity to add/hook global rules. +# This is a final opportunity to add/hook global rules. .-include # pickup local dependencies .if ${MAKE_VERSION} < 20160220 .-include <.depend> .else .dinclude <.depend> .endif .endif # bootstrapping new dependencies made easy? .if !target(bootstrap) && (make(bootstrap) || \ make(bootstrap-this) || \ make(bootstrap-recurse) || \ make(bootstrap-empty)) # if we are bootstrapping create the default _want = ${.CURDIR}/${.MAKE.DEPENDFILE_DEFAULT:T} .if exists(${_want}) # stop here ${.TARGETS:Mboot*}: .elif !make(bootstrap-empty) # find a Makefile.depend to use as _src _src != cd ${.CURDIR} && for m in ${.MAKE.DEPENDFILE_PREFERENCE:T:S,${MACHINE},*,}; do test -s $$m || continue; echo $$m; break; done; echo .if empty(_src) .error cannot find any of ${.MAKE.DEPENDFILE_PREFERENCE:T}${.newline}Use: bootstrap-empty .endif _src?= ${.MAKE.DEPENDFILE} .MAKE.DEPENDFILE_BOOTSTRAP_SED+= -e 's/${_src:E:C/,.*//}/${MACHINE}/g' # just create Makefile.depend* for this dir bootstrap-this: .NOTMAIN @echo Bootstrapping ${RELDIR}/${_want:T} from ${_src:T}; \ echo You need to build ${RELDIR} to correctly populate it. .if ${_src:T} != ${.MAKE.DEPENDFILE_PREFIX:T} (cd ${.CURDIR} && sed ${.MAKE.DEPENDFILE_BOOTSTRAP_SED} ${_src} > ${_want:T}) .else cp ${.CURDIR}/${_src:T} ${_want} .endif # create Makefile.depend* for this dir and its dependencies bootstrap: bootstrap-recurse bootstrap-recurse: bootstrap-this _mf := ${.PARSEFILE} bootstrap-recurse: .NOTMAIN .MAKE @cd ${SRCTOP} && \ for d in `cd ${RELDIR} && ${.MAKE} -B -f ${"${.MAKEFLAGS:M-n}":?${_src}:${.MAKE.DEPENDFILE:T}} -V DIRDEPS`; do \ test -d $$d || d=$${d%.*}; \ test -d $$d || continue; \ echo "Checking $$d for bootstrap ..."; \ (cd $$d && ${.MAKE} -f ${_mf} bootstrap-recurse); \ done .endif # create an empty Makefile.depend* to get the ball rolling. bootstrap-empty: .NOTMAIN .NOMETA @echo Creating empty ${RELDIR}/${_want:T}; \ echo You need to build ${RELDIR} to correctly populate it. @{ echo DIRDEPS=; echo ".include "; } > ${_want} .endif Index: stable/12/contrib/bmake/mk/doc.mk =================================================================== --- stable/12/contrib/bmake/mk/doc.mk (revision 361673) +++ stable/12/contrib/bmake/mk/doc.mk (revision 361674) @@ -1,65 +1,64 @@ -# $Id: doc.mk,v 1.6 2017/05/01 21:24:10 sjg Exp $ +# $Id: doc.mk,v 1.7 2019/06/09 16:22:08 sjg Exp $ .if !target(__${.PARSEFILE}__) __${.PARSEFILE}__: +.include + BIB?= bib EQN?= eqn GREMLIN?= grn GRIND?= vgrind -f INDXBIB?= indxbib PIC?= pic REFER?= refer ROFF?= groff -M/usr/share/tmac ${MACROS} ${PAGES} SOELIM?= soelim TBL?= tbl .PATH: ${.CURDIR} -.if !target(all) -.MAIN: all -all: paper.ps +.if !defined(_SKIP_BUILD) +realbuild: paper.ps .endif .if !target(paper.ps) paper.ps: ${SRCS} ${ROFF} ${SRCS} > ${.TARGET} .endif .if !target(print) print: paper.ps lpr -P${PRINTER} paper.ps .endif .if !target(manpages) manpages: .endif .if !target(obj) obj: .endif clean cleandir: rm -f paper.* [eE]rrs mklog ${CLEANFILES} .if ${MK_DOC} == "no" install: .else FILES?= ${SRCS} install: test -d ${DESTDIR}${DOCDIR}/${DIR} || \ ${INSTALL} -d ${DOC_INSTALL_OWN} -m ${DIRMODE} ${DESTDIR}${DOCDIR}/${DIR} ${INSTALL} ${COPY} ${DOC_INSTALL_OWN} -m ${DOCMODE} \ Makefile ${FILES} ${EXTRA} ${DESTDIR}${DOCDIR}/${DIR} .endif spell: ${SRCS} spell ${SRCS} | sort | comm -23 - spell.ok > paper.spell - -.include .if !empty(DOCOWN) DOC_INSTALL_OWN?= -o ${DOCOWN} -g ${DOCGRP} .endif .endif Index: stable/12/contrib/bmake/mk/dpadd.mk =================================================================== --- stable/12/contrib/bmake/mk/dpadd.mk (revision 361673) +++ stable/12/contrib/bmake/mk/dpadd.mk (revision 361674) @@ -1,276 +1,339 @@ -# $Id: dpadd.mk,v 1.26 2018/02/12 21:54:26 sjg Exp $ +# $Id: dpadd.mk,v 1.27 2019/05/17 13:58:53 sjg Exp $ # # @(#) Copyright (c) 2004, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # +## +# DESCRIPTION: +# This makefile manages a number of variables that simplify +# dealing with libs in a build. +# +# Primary inputs are DPLIBS, DPADD and SRC_LIBS: +# +# DPLIBS +# List of LIB* that we will actually link with +# should be in correct link order. +# DPLIBS is a short-cut to ensure that DPADD and LDADD are +# kept in sync. +# +# DPADD List of LIB* that should already be built. +# +# SRC_LIBS +# List of LIB* that we want headers from, we do *not* +# require that such libs have been built. +# +# The above all get added to DPMAGIC_LIBS which is what we +# process. +# +# We expect LIB* to be set to absolute path of a library - +# suitable for putting in DPADD. +# eg. +# +# LIBC ?= ${OBJTOP}/lib/libc/libc.a +# +# From such a path we can derrive a number of other variables +# for which we can supply sensible default values. +# We name all these variables for the basename of the library +# (libc in our example above -- ${__lib:T:R} in below): +# +# LDADD_${__lib:T:R}: +# What should be added to LDADD (eg -lc) +# +# OBJ_${__lib:T:R}: +# This is trivial - just the dirname of the built library. +# +# SRC_${__lib:T:R}: +# Where the src for ${__lib} is, if LIB* is set as above +# we can simply substitute ${SRCTOP} for ${OBJTOP} in +# the dirname. +# +# INCLUDES_${__lib:T:R}: +# What should be added to CFLAGS +# +# If the directory ${SRC_${__lib:T:R}}/h exists we will +# only add -I${SRC_${__lib:T:R}}/h on the basis that +# this is where the public api is kept. +# +# Otherwise default will be -I${OBJ_${__lib:T:R}} +# -I${SRC_${__lib:T:R}} +# +# Note much of the above is skipped for staged libs +# eg. +# LIBC ?= ${STAGE_OBJTOP}/usr/lib/libc.a +# +# Since we can safely assume that -I${STAGE_OBJTOP}/usr/include +# and -L${STAGE_OBJTOP}/usr/lib are sufficient, and we should +# have no need of anything else. +# + .if !target(__${.PARSEFILE}__) __${.PARSEFILE}__: # sometimes we play games with .CURDIR etc # _* hold the original values of .* _OBJDIR?= ${.OBJDIR} _CURDIR?= ${.CURDIR} .if ${_CURDIR} == ${SRCTOP} RELDIR=. RELTOP=. .else RELDIR?= ${_CURDIR:S,${SRCTOP}/,,} .if ${RELDIR} == ${_CURDIR} RELDIR?= ${_OBJDIR:S,${OBJTOP}/,,} .endif RELTOP?= ${RELDIR:C,[^/]+,..,g} .endif RELOBJTOP?= ${OBJTOP} RELSRCTOP?= ${SRCTOP} # we get included just about everywhere so this is handy... # C*DEBUG_XTRA are for defining on cmd line etc # so do not use in makefiles. .ifdef CFLAGS_DEBUG_XTRA CFLAGS_LAST += ${CFLAGS_DEBUG_XTRA} .endif .ifdef CXXFLAGS_DEBUG_XTRA CXXFLAGS_LAST += ${CXXFLAGS_DEBUG_XTRA} .endif .-include # DPLIBS helps us ensure we keep DPADD and LDADD in sync DPLIBS+= ${DPLIBS_LAST} DPADD+= ${DPLIBS:N-*} .for __lib in ${DPLIBS} -.if "${_lib:M-*}" != "" +.if "${__lib:M-*}" != "" LDADD += ${__lib} .else LDADD += ${LDADD_${__lib:T:R}:U${__lib:T:R:S/lib/-l/:C/\.so.*//}} .endif .endfor # DPADD can contain things other than libs __dpadd_libs := ${DPADD:M*/lib*} .if defined(PROG) && ${MK_PROG_LDORDER_MK:Uno} != "no" # some libs have dependencies... # DPLIBS_* allows bsd.libnames.mk to flag libs which must be included # in DPADD for a given library. # Gather all such dependencies into __ldadd_all_xtras # dups will be dealt with later. # Note: libfoo_pic uses DPLIBS_libfoo __ldadd_all_xtras= .for __lib in ${__dpadd_libs:@d@${DPLIBS_${d:T:R:S,_pic,,}}@} __ldadd_all_xtras+= ${LDADD_${__lib}:U${__lib:T:R:S/lib/-l/:C/\.so.*//}} .if "${DPADD:M${__lib}}" == "" DPADD+= ${__lib} .endif .endfor .endif # Last of all... for libc and libgcc DPADD+= ${DPADD_LAST} # de-dupuplicate __ldadd_all_xtras into __ldadd_xtras # in reverse order so that libs end up listed after all that needed them. __ldadd_xtras= .for __lib in ${__ldadd_all_xtras:[-1..1]} .if "${__ldadd_xtras:M${__lib}}" == "" || ${NEED_IMPLICIT_LDADD:tl:Uno} != "no" __ldadd_xtras+= ${__lib} .endif .endfor .if !empty(__ldadd_xtras) # now back to the original order __ldadd_xtras:= ${__ldadd_xtras:[-1..1]} LDADD+= ${__ldadd_xtras} .endif # Convert DPADD into -I and -L options and add them to CPPFLAGS and LDADD # For the -I's convert the path to a relative one. For separate objdirs # the DPADD paths will be to the obj tree so we need to subst anyway. # update this __dpadd_libs := ${DPADD:M*/lib*} # Order -L's to search ours first. # Avoids picking up old versions already installed. __dpadd_libdirs := ${__dpadd_libs:R:H:S/^/-L/g:O:u:N-L} LDADD += ${__dpadd_libdirs:M-L${OBJTOP}/*} LDADD += ${__dpadd_libdirs:N-L${OBJTOP}/*:N-L${HOST_LIBDIR:U/usr/lib}} .if defined(HOST_LIBDIR) && ${HOST_LIBDIR} != "/usr/lib" LDADD+= -L${HOST_LIBDIR} .endif .if !make(dpadd) .ifdef LIB # Each lib is its own src_lib, we want to include it in SRC_LIBS # so that the correct INCLUDES_* will be picked up automatically. SRC_LIBS+= ${_OBJDIR}/lib${LIB}.a .endif .endif # # This little bit of magic, assumes that SRC_libfoo will be # set if it cannot be correctly derrived from ${LIBFOO} # Note that SRC_libfoo and INCLUDES_libfoo should be named for the # actual library name not the variable name that might refer to it. # 99% of the time the two are the same, but the DPADD logic # only has the library name available, so stick to that. # SRC_LIBS?= # magic_libs includes those we want to link with # as well as those we might look at __dpadd_magic_libs += ${__dpadd_libs} ${SRC_LIBS} DPMAGIC_LIBS += ${__dpadd_magic_libs} \ ${__dpadd_magic_libs:@d@${DPMAGIC_LIBS_${d:T:R}}@} # we skip this for staged libs .for __lib in ${DPMAGIC_LIBS:O:u:N${STAGE_OBJTOP:Unot}*/lib/*} # # if SRC_libfoo is not set, then we assume that the srcdir corresponding # to where we found the library is correct. # SRC_${__lib:T:R} ?= ${__lib:H:S,${OBJTOP},${RELSRCTOP},} # # This is a no-brainer but just to be complete... # OBJ_${__lib:T:R} ?= ${__lib:H:S,${OBJTOP},${RELOBJTOP},} # # If INCLUDES_libfoo is not set, then we'll use ${SRC_libfoo}/h if it exists, # else just ${SRC_libfoo}. # INCLUDES_${__lib:T:R}?= -I${exists(${SRC_${__lib:T:R}}/h):?${SRC_${__lib:T:R}}/h:${SRC_${__lib:T:R}}} .endfor # even for staged libs we sometimes # need to allow direct -I to avoid cicular dependencies .for __lib in ${DPMAGIC_LIBS:O:u:T:R} .if !empty(SRC_${__lib}) && empty(INCLUDES_${__lib}) # must be a staged lib .if exists(${SRC_${__lib}}/h) INCLUDES_${__lib} = -I${SRC_${__lib}}/h .else INCLUDES_${__lib} = -I${SRC_${__lib}} .endif .endif .endfor # when linking a shared lib, avoid non pic libs SHLDADD+= ${LDADD:N-[lL]*} .for __lib in ${__dpadd_libs:u} .if defined(SHLIB_NAME) && ${LDADD:M-l${__lib:T:R:S,lib,,}} != "" .if ${__lib:T:N*_pic.a:N*.so} == "" || exists(${__lib:R}.so) SHLDADD+= -l${__lib:T:R:S,lib,,} .elif exists(${__lib:R}_pic.a) SHLDADD+= -l${__lib:T:R:S,lib,,}_pic .else .warning ${RELDIR}.${TARGET_SPEC} needs ${__lib:T:R}_pic.a SHLDADD+= -l${__lib:T:R:S,lib,,} .endif SHLDADD+= -L${__lib:H} .endif .endfor # Now for the bits we actually need __dpadd_incs= .for __lib in ${__dpadd_libs:u} .if (make(${PROG}_p) || defined(NEED_GPROF)) && exists(${__lib:R}_p.a) __ldadd=-l${__lib:T:R:S,lib,,} LDADD := ${LDADD:S,^${__ldadd}$,${__ldadd}_p,g} .endif .endfor # # We take care of duplicate suppression later. # don't apply :T:R too early __dpadd_incs += ${__dpadd_magic_libs:u:@x@${INCLUDES_${x:T:R}}@} __dpadd_incs += ${__dpadd_magic_libs:O:u:@s@${SRC_LIBS_${s:T:R}:U}@:@x@${INCLUDES_${x:T:R}}@} __dpadd_last_incs += ${__dpadd_magic_libs:u:@x@${INCLUDES_LAST_${x:T:R}}@} __dpadd_last_incs += ${__dpadd_magic_libs:O:u:@s@${SRC_LIBS_${s:T:R}:U}@:@x@${INCLUDES_LAST_${x:T:R}}@} .if defined(HOSTPROG) || ${MACHINE:Nhost*} == "" # we want any -I/usr/* last __dpadd_last_incs := \ ${__dpadd_last_incs:N-I/usr/*} \ ${__dpadd_incs:M-I/usr/*} \ ${__dpadd_last_incs:M-I/usr/*} __dpadd_incs := ${__dpadd_incs:N-I/usr/*} .endif # # eliminate any duplicates - but don't mess with the order # force evaluation now - to avoid giving make a headache # .for t in CFLAGS CXXFLAGS # avoid duplicates __$t_incs:=${$t:M-I*:O:u} .for i in ${__dpadd_incs} .if "${__$t_incs:M$i}" == "" $t+= $i __$t_incs+= $i .endif .endfor .endfor .for t in CFLAGS_LAST CXXFLAGS_LAST # avoid duplicates __$t_incs:=${$t:M-I*:u} .for i in ${__dpadd_last_incs} .if "${__$t_incs:M$i}" == "" $t+= $i __$t_incs+= $i .endif .endfor .endfor # This target is used to gather a list of # dir: ${DPADD} # entries .if make(*dpadd*) .if !target(dpadd) dpadd: .NOTMAIN .if defined(DPADD) && ${DPADD} != "" @echo "${RELDIR}: ${DPADD:S,${OBJTOP}/,,}" .endif .endif .endif .ifdef SRC_PATHADD # We don't want to assume that we need to .PATH every element of # SRC_LIBS, but the Makefile cannot do # .PATH: ${SRC_libfoo} # since the value of SRC_libfoo must be available at the time .PATH: # is read - and we only just worked it out. # Further, they can't wait until after include of {lib,prog}.mk as # the .PATH is needed before then. # So we let the Makefile do # SRC_PATHADD+= ${SRC_libfoo} # and we defer the .PATH: until now so that SRC_libfoo will be available. .PATH: ${SRC_PATHADD} .endif # after all that, if doing -n we don't care .if ${.MAKEFLAGS:Ux:M-n} != "" DPADD = .elif ${.MAKE.MODE:Mmeta*} != "" && exists(${.MAKE.DEPENDFILE}) DPADD_CLEAR_DPADD ?= yes .if ${DPADD_CLEAR_DPADD} == "yes" # save this __dpadd_libs := ${__dpadd_libs} # we have made what use of it we can of DPADD DPADD = .endif .endif .endif Index: stable/12/contrib/bmake/mk/gendirdeps.mk =================================================================== --- stable/12/contrib/bmake/mk/gendirdeps.mk (revision 361673) +++ stable/12/contrib/bmake/mk/gendirdeps.mk (revision 361674) @@ -1,359 +1,383 @@ -# $Id: gendirdeps.mk,v 1.38 2018/03/10 00:53:52 sjg Exp $ +# $Id: gendirdeps.mk,v 1.42 2020/05/16 23:21:48 sjg Exp $ -# Copyright (c) 2010-2013, Juniper Networks, Inc. +# Copyright (c) 2011-2020, Simon J. Gerraty +# Copyright (c) 2010-2018, Juniper Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # This makefile [re]generates ${.MAKE.DEPENDFILE} # .include # Assumptions: # RELDIR is the relative path from ${SRCTOP} to ${_CURDIR} # (SRCTOP is ${SB}/src) # _CURDIR is the absolute version of ${.CURDIR} # _OBJDIR is the absolute version of ${.OBJDIR} # _objroot is realpath of ${_OBJTOP} without ${MACHINE} # this may be different from _OBJROOT if $SB/obj is a # symlink to another filesystem. # _objroot must be a prefix match for _objtop .MAIN: all # keep this simple .MAKE.MODE = compat all: _CURDIR ?= ${.CURDIR} _OBJDIR ?= ${.OBJDIR} _OBJTOP ?= ${OBJTOP} _OBJROOT ?= ${OBJROOT:U${_OBJTOP}} .if ${_OBJROOT:M*/} _slash=/ .else _slash= .endif _objroot ?= ${_OBJROOT:tA}${_slash} _this = ${.PARSEDIR}/${.PARSEFILE} # remember what to make _DEPENDFILE := ${_CURDIR}/${.MAKE.DEPENDFILE:T} # We do _not_ want to read our own output! .MAKE.DEPENDFILE = /dev/null # caller should have set this META_FILES ?= ${.MAKE.META.FILES} .if !empty(META_FILES) .if ${.MAKE.LEVEL} > 0 && !empty(GENDIRDEPS_FILTER) # so we can compare below .-include <${_DEPENDFILE}> # yes, I mean :U with no value _DIRDEPS := ${DIRDEPS:U:O:u} .endif META_FILES := ${META_FILES:T:O:u} -.export META_FILES # pickup customizations .-include # these are actually prefixes that we'll skip # they should all be absolute paths SKIP_GENDIRDEPS ?= .if !empty(SKIP_GENDIRDEPS) _skip_gendirdeps = egrep -v '^(${SKIP_GENDIRDEPS:O:u:ts|})' | .else _skip_gendirdeps = .endif # Below we will turn _{VAR} into ${VAR} which keeps this simple # GENDIRDEPS_FILTER_DIR_VARS is a list of dirs to be substiuted for. # GENDIRDEPS_FILTER_VARS is more general. # In each case order matters. .if !empty(GENDIRDEPS_FILTER_DIR_VARS) GENDIRDEPS_FILTER += ${GENDIRDEPS_FILTER_DIR_VARS:@v@S,${$v},_{${v}},@} .endif .if !empty(GENDIRDEPS_FILTER_VARS) GENDIRDEPS_FILTER += ${GENDIRDEPS_FILTER_VARS:@v@S,/${$v}/,/_{${v}}/,@:NS,//,*:u} .endif # this (*should* be set in meta.sys.mk) # is the script that extracts what we want. META2DEPS ?= ${.PARSEDIR}/meta2deps.sh META2DEPS := ${META2DEPS} .if ${DEBUG_GENDIRDEPS:Uno:@x@${RELDIR:M$x}@} != "" && ${DEBUG_GENDIRDEPS:Uno:Mmeta2d*} != "" _time = time _sh_x = sh -x _py_d = -ddd .else _time = _sh_x = _py_d = .endif .if ${META2DEPS:E} == "py" # we can afford to do this all the time. DPDEPS ?= no META2DEPS_CMD = ${_time} ${PYTHON} ${META2DEPS} ${_py_d} .if ${DPDEPS:tl} != "no" META2DEPS_CMD += -D ${DPDEPS} .endif META2DEPS_FILTER = sed 's,^src:,${SRCTOP}/,;s,^\([^/]\),${OBJTOP}/\1,' | .elif ${META2DEPS:E} == "sh" META2DEPS_CMD = ${_time} ${_sh_x} ${META2DEPS} OBJTOP=${_OBJTOP} .else META2DEPS_CMD ?= ${META2DEPS} .endif .if ${TARGET_OBJ_SPEC:U${MACHINE}} != ${MACHINE} META2DEPS_CMD += -T ${TARGET_OBJ_SPEC} .endif META2DEPS_CMD += \ -R ${RELDIR} -H ${HOST_TARGET} \ ${M2D_OBJROOTS:O:u:@o@-O $o@} \ ${M2D_EXCLUDES:O:u:@o@-X $o@} \ M2D_OBJROOTS += ${OBJTOP} ${_OBJROOT} ${_objroot} .if defined(SB_OBJROOT) M2D_OBJROOTS += ${SB_OBJROOT} .endif .if defined(STAGE_ROOT) M2D_OBJROOTS += ${STAGE_ROOT} .endif .if ${.MAKE.DEPENDFILE_PREFERENCE:U${.MAKE.DEPENDFILE}:M*.${MACHINE}} == "" # meta2deps.py only groks objroot # so we need to give it what it expects # and tell it not to add machine qualifiers META2DEPS_ARGS += MACHINE=none .endif .if defined(SB_BACKING_SB) META2DEPS_CMD += -S ${SB_BACKING_SB}/src M2D_OBJROOTS += ${SB_BACKING_SB}/${SB_OBJPREFIX} .endif GENDIRDEPS_SEDCMDS += \ -e 's,//*$$,,;s,\.${HOST_TARGET:Uhost}$$,.host,' \ -e 's,\.${HOST_TARGET32:Uhost32}$$,.host32,' \ -e 's,\.${MACHINE}$$,,' \ -e 's:\.${TARGET_SPEC:U${MACHINE}}$$::' # we are only interested in the dirs # specifically those we read something from. # we canonicalize them to keep things simple # if we are using a split-fs sandbox, it gets a little messier. _objtop := ${_OBJTOP:tA} + +# some people put *.meta in META_XTRAS to make sure we get here +_meta_files := ${META_FILES:N\*.meta:O:u} +# assume a big list +_meta_files_arg= @meta.list +.if empty(_meta_files) && ${META_FILES:M\*.meta} != "" +# XXX this should be considered a bad idea, +# since we cannot ignore stale .meta +x != cd ${_OBJDIR} && find . -name '*.meta' -print -o \( -type d ! -name . -prune \) | sed 's,^./,,' > meta.list; echo +.elif ${_meta_files:[#]} > 500 +.export _meta_files +x != echo; for m in $$_meta_files; do echo $$m; done > meta.list +# _meta_files is consuming a lot of env space +# that can impact command line length, +# and we do not need it any more +.undef _meta_files +.unexport _meta_files +.else +_meta_files_arg:= ${_meta_files} +.endif + dir_list != cd ${_OBJDIR} && \ ${META2DEPS_CMD} MACHINE=${MACHINE} \ SRCTOP=${SRCTOP} RELDIR=${RELDIR} CURDIR=${_CURDIR} \ ${META2DEPS_ARGS} \ - ${META_FILES:O:u} | ${META2DEPS_FILTER} ${_skip_gendirdeps} \ + ${_meta_files_arg} | ${META2DEPS_FILTER} ${_skip_gendirdeps} \ sed ${GENDIRDEPS_SEDCMDS} .if ${dir_list:M*ERROR\:*} != "" .warning ${dir_list:tW:C,.*(ERROR),\1,} .warning Skipping ${_DEPENDFILE:S,${SRCTOP}/,,} # we are not going to update anything .else dpadd_dir_list= .if !empty(DPADD) _nonlibs := ${DPADD:T:Nlib*:N*include} .if !empty(_nonlibs) ddep_list = .for f in ${_nonlibs:@x@${DPADD:M*/$x}@} .if exists($f.dirdep) ddep_list += $f.dirdep .elif exists(${f:H}.dirdep) ddep_list += ${f:H}.dirdep .else dir_list += ${f:H:tA} dpadd_dir_list += ${f:H:tA} .endif .endfor .if !empty(ddep_list) ddeps != cat ${ddep_list:O:u} | ${META2DEPS_FILTER} ${_skip_gendirdeps} \ sed ${GENDIRDEPS_SEDCMDS} .if ${DEBUG_GENDIRDEPS:Uno:@x@${RELDIR:M$x}@} != "" .info ${RELDIR}: raw_dir_list='${dir_list}' .info ${RELDIR}: ddeps='${ddeps}' .endif dir_list += ${ddeps} .endif .endif .endif # DIRDEPS represent things that had to have been built first # so they should all be undir OBJTOP. # Note that ${_OBJTOP}/bsd/include/machine will get reported # to us as $SRCTOP/bsd/sys/$MACHINE_ARCH/include meaning we # will want to visit bsd/include # so we add # ${"${dir_list:M*bsd/sys/${MACHINE_ARCH}/include}":?bsd/include:} # to GENDIRDEPS_DIR_LIST_XTRAS _objtops = ${OBJTOP} ${_OBJTOP} ${_objtop} _objtops := ${_objtops:O:u} dirdep_list = \ ${_objtops:@o@${dir_list:M$o*/*:C,$o[^/]*/,,}@} \ ${GENDIRDEPS_DIR_LIST_XTRAS} # sort longest first M2D_OBJROOTS := ${M2D_OBJROOTS:O:u:[-1..1]} # anything we use from an object dir other than ours # needs to be qualified with its . suffix # (we used the pseudo machine "host" for the HOST_TARGET). skip_ql= ${SRCTOP}* ${_objtops:@o@$o*@} .for o in ${M2D_OBJROOTS:${skip_ql:${M_ListToSkip}}} # we need := so only skip_ql to this point applies ql.$o := ${dir_list:${skip_ql:${M_ListToSkip}}:M$o*/*/*:C,$o([^/]+)/(.*),\2.\1,:S,.${HOST_TARGET},.host,} qualdir_list += ${ql.$o} .if ${DEBUG_GENDIRDEPS:Uno:@x@${RELDIR:M$x}@} != "" .info ${RELDIR}: o=$o ${ql.$o qualdir_list:L:@v@$v=${$v}@} .endif skip_ql+= $o* .endfor dirdep_list := ${dirdep_list:O:u} qualdir_list := ${qualdir_list:N*.${MACHINE}:O:u} DIRDEPS = \ ${dirdep_list:N${RELDIR}:N${RELDIR}/*} \ ${qualdir_list:N${RELDIR}.*:N${RELDIR}/*} # We only consider things below $RELDIR/ if they have a makefile. # This is the same test that _DIRDEP_USE applies. # We have do a double test with dirdep_list as it _may_ contain # qualified dirs - if we got anything from a stage dir. # qualdir_list we know are all qualified. # It would be nice do peform this check for all of DIRDEPS, # but we cannot assume that all of the tree is present, # in fact we can only assume that RELDIR is. DIRDEPS += \ ${dirdep_list:M${RELDIR}/*:@d@${.MAKE.MAKEFILE_PREFERENCE:@m@${exists(${SRCTOP}/$d/$m):?$d:${exists(${SRCTOP}/${d:R}/$m):?$d:}}@}@} \ ${qualdir_list:M${RELDIR}/*:@d@${.MAKE.MAKEFILE_PREFERENCE:@m@${exists(${SRCTOP}/${d:R}/$m):?$d:}@}@} # what modifiers do we allow in GENDIRDEPS_FILTER GENDIRDEPS_FILTER_MASK += @CMNS DIRDEPS := ${DIRDEPS:${GENDIRDEPS_FILTER:UNno:M[${GENDIRDEPS_FILTER_MASK:O:u:ts}]*:ts:}:C,//+,/,g:O:u} .if ${DEBUG_GENDIRDEPS:Uno:@x@${RELDIR:M$x}@} != "" .info ${RELDIR}: M2D_OBJROOTS=${M2D_OBJROOTS} .info ${RELDIR}: M2D_EXCLUDES=${M2D_EXCLUDES} .info ${RELDIR}: dir_list='${dir_list}' .info ${RELDIR}: dpadd_dir_list='${dpadd_dir_list}' .info ${RELDIR}: dirdep_list='${dirdep_list}' .info ${RELDIR}: qualdir_list='${qualdir_list}' .info ${RELDIR}: SKIP_GENDIRDEPS='${SKIP_GENDIRDEPS}' .info ${RELDIR}: GENDIRDEPS_FILTER='${GENDIRDEPS_FILTER}' .info ${RELDIR}: FORCE_DPADD='${DPADD}' .info ${RELDIR}: DIRDEPS='${DIRDEPS}' .endif # SRC_DIRDEPS is for checkout logic src_dirdep_list = \ ${dir_list:M${SRCTOP}/*:S,${SRCTOP}/,,} SRC_DIRDEPS = \ ${src_dirdep_list:N${RELDIR}:N${RELDIR}/*:C,(/h)/.*,,} SRC_DIRDEPS := ${SRC_DIRDEPS:${GENDIRDEPS_SRC_FILTER:UN/*:ts:}:C,//+,/,g:O:u} # if you want to capture SRC_DIRDEPS in .MAKE.DEPENDFILE put # SRC_DIRDEPS_FILE = ${_DEPENDFILE} # in local.gendirdeps.mk .if ${SRC_DIRDEPS_FILE:Uno:tl} != "no" ECHO_SRC_DIRDEPS = echo 'SRC_DIRDEPS = \'; echo '${SRC_DIRDEPS:@d@ $d \\${.newline}@}'; echo; .if ${SRC_DIRDEPS_FILE:T} == ${_DEPENDFILE:T} _include_src_dirdeps = ${ECHO_SRC_DIRDEPS} .else all: ${SRC_DIRDEPS_FILE} .if !target(${SRC_DIRDEPS_FILE}) ${SRC_DIRDEPS_FILE}: ${META_FILES} ${_this} ${META2DEPS} @(${ECHO_SRC_DIRDEPS}) > $@ .endif .endif .endif _include_src_dirdeps ?= all: ${_DEPENDFILE} # if this is going to exist it would be there by now .if !exists(.depend) CAT_DEPEND = /dev/null .endif CAT_DEPEND ?= .depend .if !empty(_DIRDEPS) && ${DIRDEPS} != ${_DIRDEPS} # we may have changed a filter .PHONY: ${_DEPENDFILE} .endif # 'cat .depend' should suffice, but if we are mixing build modes # .depend may contain things we don't want. # The sed command at the end of the stream, allows for the filters # to output _{VAR} tokens which we will turn into proper ${VAR} references. ${_DEPENDFILE}: .NOMETA ${CAT_DEPEND:M.depend} ${META_FILES:O:u:@m@${exists($m):?$m:}@} ${_this} ${META2DEPS} @(${GENDIRDEPS_HEADER} echo '# Autogenerated - do NOT edit!'; echo; \ echo 'DIRDEPS = \'; \ echo '${DIRDEPS:@d@ $d \\${.newline}@}'; echo; \ ${_include_src_dirdeps} \ echo '.include '; \ echo; \ echo '.if $${DEP_RELDIR} == $${_DEP_RELDIR}'; \ echo '# local dependencies - needed for -jN in clean tree'; \ [ -s ${CAT_DEPEND} ] && { grep : ${CAT_DEPEND} | grep -v '[/\\]'; }; \ echo '.endif' ) | sed 's,_\([{(]\),$$\1,g' > $@.new${.MAKE.PID} @${InstallNew}; InstallNew -s $@.new${.MAKE.PID} .endif # meta2deps failed .elif !empty(SUBDIR) DIRDEPS := ${SUBDIR:S,^,${RELDIR}/,:O:u} all: ${_DEPENDFILE} ${_DEPENDFILE}: .NOMETA ${MAKEFILE} ${_this} @(${GENDIRDEPS_HEADER} echo '# Autogenerated - do NOT edit!'; echo; \ echo 'DIRDEPS = \'; \ echo '${DIRDEPS:@d@ $d \\${.newline}@}'; echo; \ echo '.include '; \ echo ) | sed 's,_\([{(]\),$$\1,g' > $@.new @${InstallNew}; InstallNew $@.new .else # nothing to do all ${_DEPENDFILE}: .endif ${_DEPENDFILE}: .PRECIOUS + +# don't waste time looking for ways to make .meta files +.SUFFIXES: Index: stable/12/contrib/bmake/mk/init.mk =================================================================== --- stable/12/contrib/bmake/mk/init.mk (revision 361673) +++ stable/12/contrib/bmake/mk/init.mk (revision 361674) @@ -1,69 +1,70 @@ -# $Id: init.mk,v 1.15 2017/05/07 20:27:54 sjg Exp $ +# $Id: init.mk,v 1.16 2019/09/28 16:54:02 sjg Exp $ # # @(#) Copyright (c) 2002, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # .if !target(__${.PARSEFILE}__) __${.PARSEFILE}__: .if ${MAKE_VERSION:U0} > 20100408 _this_mk_dir := ${.PARSEDIR:tA} .else _this_mk_dir := ${.PARSEDIR} .endif .-include .-include <${.CURDIR:H}/Makefile.inc> .include +.include .MAIN: all # should have been set by sys.mk CXX_SUFFIXES?= .cc .cpp .cxx .C .if !empty(WARNINGS_SET) || !empty(WARNINGS_SET_${MACHINE_ARCH}) .include .endif -COPTS += ${COPTS.${.IMPSRC:T}} -CPPFLAGS += ${CPPFLAGS.${.IMPSRC:T}} -CPUFLAGS += ${CPUFLAGS.${.IMPSRC:T}} +.for x in COPTS CPPFLAGS CPUFLAGS LDFLAGS +$x += ${$x.${COMPILER_TYPE}:U} ${$x.${.IMPSRC:T}:U} +.endfor CC_PG?= -pg CXX_PG?= ${CC_PG} CC_PIC?= -DPIC CXX_PIC?= ${CC_PIC} PROFFLAGS?= -DGPROF -DPROF .if ${.MAKE.LEVEL:U1} == 0 && ${BUILD_AT_LEVEL0:Uyes:tl} == "no" # this tells lib.mk and prog.mk to not actually build anything _SKIP_BUILD = not building at level 0 .endif .if !defined(.PARSEDIR) # no-op is the best we can do if not bmake. .WAIT: .endif # define this once for consistency .if empty(_SKIP_BUILD) # beforebuild is a hook for things that must be done early all: beforebuild .WAIT realbuild .else all: .PHONY .warning ${_SKIP_BUILD} .endif beforebuild: realbuild: .endif Index: stable/12/contrib/bmake/mk/install-mk =================================================================== --- stable/12/contrib/bmake/mk/install-mk (revision 361673) +++ stable/12/contrib/bmake/mk/install-mk (revision 361674) @@ -1,185 +1,185 @@ : # NAME: # install-mk - install mk files # # SYNOPSIS: # install-mk [options] [var=val] [dest] # # DESCRIPTION: # This tool installs mk files in a semi-intelligent manner into # "dest". # # Options: # # -n just say what we want to do, but don't touch anything. # # -f use -f when copying sys,mk. # # -v be verbose # # -q be quiet # # -m "mode" # Use "mode" for installed files (444). # # -o "owner" # Use "owner" for installed files. # # -g "group" # Use "group" for installed files. # # var=val # Set "var" to "val". See below. # # All our *.mk files are copied to "dest" with appropriate # ownership and permissions. # # By default if a sys.mk can be found in a standard location # (that bmake will find) then no sys.mk will be put in "dest". # # SKIP_SYS_MK: # If set, we will avoid installing our 'sys.mk' # This is probably a bad idea. # # SKIP_BSD_MK: # If set, we will skip making bsd.*.mk links to *.mk # # sys.mk: # # By default (and provided we are not installing to the system # mk dir - '/usr/share/mk') we install our own 'sys.mk' which # includes a sys specific file, or a generic one. # # # AUTHOR: # Simon J. Gerraty # RCSid: -# $Id: install-mk,v 1.156 2018/04/22 04:42:47 sjg Exp $ +# $Id: install-mk,v 1.170 2020/05/15 21:40:24 sjg Exp $ # # @(#) Copyright (c) 1994 Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # -MK_VERSION=20180420 +MK_VERSION=20200515 OWNER= GROUP= MODE=444 BINMODE=555 ECHO=: SKIP= cp_f=-f while : do case "$1" in *=*) eval "$1"; shift;; +f) cp_f=; shift;; -f) cp_f=-f; shift;; -m) MODE=$2; shift 2;; -o) OWNER=$2; shift 2;; -g) GROUP=$2; shift 2;; -v) ECHO=echo; shift;; -q) ECHO=:; shift;; -n) ECHO=echo SKIP=:; shift;; --) shift; break;; *) break;; esac done case $# in 0) echo "$0 [options] []" echo "eg." echo "$0 -o bin -g bin -m 444 /usr/local/share/mk" exit 1 ;; esac dest=$1 os=${2:-`uname`} osrel=${3:-`uname -r`} Do() { $ECHO "$@" $SKIP "$@" } Error() { echo "ERROR: $@" >&2 exit 1 } Warning() { echo "WARNING: $@" >&2 } [ "$FORCE_SYS_MK" ] && Warning "ignoring: FORCE_{BSD,SYS}_MK (no longer supported)" SYS_MK_DIR=${SYS_MK_DIR:-/usr/share/mk} SYS_MK=${SYS_MK:-$SYS_MK_DIR/sys.mk} realpath() { [ -d $1 ] && cd $1 && 'pwd' && return echo $1 } if [ -s $SYS_MK -a -d $dest ]; then # if this is a BSD system we don't want to touch $SYS_MK dest=`realpath $dest` sys_mk_dir=`realpath $SYS_MK_DIR` if [ $dest = $sys_mk_dir ]; then case "$os" in *BSD*) SKIP_SYS_MK=: SKIP_BSD_MK=: ;; *) # could be fake? if [ ! -d $dest/sys -a ! -s $dest/Generic.sys.mk ]; then SKIP_SYS_MK=: # play safe SKIP_BSD_MK=: fi ;; esac fi fi [ -d $dest/sys ] || Do mkdir -p $dest/sys [ -d $dest/sys ] || Do mkdir $dest/sys || exit 1 [ -z "$SKIP" ] && dest=`realpath $dest` cd `dirname $0` mksrc=`'pwd'` if [ $mksrc = $dest ]; then SKIP_MKFILES=: else # we do not install the examples mk_files=`grep '^[a-z].*\.mk' FILES | egrep -v '(examples/|^sys\.mk|sys/)'` mk_scripts=`egrep '^[a-z].*\.(sh|py)' FILES | egrep -v '/'` sys_mk_files=`grep 'sys/.*\.mk' FILES` SKIP_MKFILES= [ -z "$SKIP_SYS_MK" ] && mk_files="sys.mk $mk_files" fi $SKIP_MKFILES Do cp $cp_f $mk_files $dest $SKIP_MKFILES Do cp $cp_f $sys_mk_files $dest/sys $SKIP_MKFILES Do cp $cp_f $mk_scripts $dest $SKIP cd $dest $SKIP_MKFILES Do chmod $MODE $mk_files $sys_mk_files $SKIP_MKFILES Do chmod $BINMODE $mk_scripts [ "$GROUP" ] && $SKIP_MKFILES Do chgrp $GROUP $mk_files $sys_mk_files [ "$OWNER" ] && $SKIP_MKFILES Do chown $OWNER $mk_files $sys_mk_files # if this is a BSD system the bsd.*.mk should exist and be used. if [ -z "$SKIP_BSD_MK" ]; then for f in dep doc files inc init lib links man nls obj own prog subdir do b=bsd.$f.mk [ -s $b ] || Do ln -s $f.mk $b done fi exit 0 Index: stable/12/contrib/bmake/mk/lib.mk =================================================================== --- stable/12/contrib/bmake/mk/lib.mk (revision 361673) +++ stable/12/contrib/bmake/mk/lib.mk (revision 361674) @@ -1,607 +1,609 @@ -# $Id: lib.mk,v 1.68 2018/01/26 20:08:16 sjg Exp $ +# $Id: lib.mk,v 1.70 2020/05/02 02:10:20 sjg Exp $ .if !target(__${.PARSEFILE}__) __${.PARSEFILE}__: .include .if ${OBJECT_FMT} == "ELF" NEED_SOLINKS?= yes .endif SHLIB_VERSION_FILE?= ${.CURDIR}/shlib_version .if !defined(SHLIB_MAJOR) && exists(${SHLIB_VERSION_FILE}) SHLIB_MAJOR != . ${SHLIB_VERSION_FILE} ; echo $$major SHLIB_MINOR != . ${SHLIB_VERSION_FILE} ; echo $$minor SHLIB_TEENY != . ${SHLIB_VERSION_FILE} ; echo $$teeny .endif .for x in major minor teeny print-shlib-$x: .if defined(SHLIB_${x:tu}) && ${MK_PIC} != "no" @echo ${SHLIB_${x:tu}} .else @false .endif .endfor SHLIB_FULLVERSION ?= ${${SHLIB_MAJOR} ${SHLIB_MINOR} ${SHLIB_TEENY}:L:ts.} SHLIB_FULLVERSION := ${SHLIB_FULLVERSION} # add additional suffixes not exported. # .po is used for profiling object files. # ${PICO} is used for PIC object files. PICO?= .pico .SUFFIXES: .out .a .ln ${PICO} .po .o .s .S .c .cc .C .m .F .f .r .y .l .cl .p .h .SUFFIXES: .sh .m4 .m CFLAGS+= ${COPTS} META_NOECHO?= echo # Originally derrived from NetBSD-1.6 # Set PICFLAGS to cc flags for producing position-independent code, # if not already set. Includes -DPIC, if required. # Data-driven table using make variables to control how shared libraries # are built for different platforms and object formats. # OBJECT_FMT: currently either "ELF" or "a.out", from # SHLIB_SOVERSION: version number to be compiled into a shared library # via -soname. Usually ${SHLIB_MAJOR} on ELF. # NetBSD/pmax used to use ${SHLIB_MAJOR}[.${SHLIB_MINOR} # [.${SHLIB_TEENY}]] # SHLIB_SHFLAGS: Flags to tell ${LD} to emit shared library. # with ELF, also set shared-lib version for ld.so. # SHLIB_LDSTARTFILE: support .o file, call C++ file-level constructors # SHLIB_LDENDFILE: support .o file, call C++ file-level destructors # FPICFLAGS: flags for ${FC} to compile .[fF] files to ${PICO} objects. # CPPICFLAGS: flags for ${CPP} to preprocess .[sS] files for ${AS} # CPICFLAGS: flags for ${CC} to compile .[cC] files to ${PICO} objects. # CAPICFLAGS flags for {$CC} to compiling .[Ss] files # (usually just ${CPPPICFLAGS} ${CPICFLAGS}) # APICFLAGS: flags for ${AS} to assemble .[sS] to ${PICO} objects. .if ${TARGET_OSNAME} == "NetBSD" .if ${MACHINE_ARCH} == "alpha" # Alpha-specific shared library flags FPICFLAGS ?= -fPIC CPICFLAGS ?= -fPIC -DPIC CPPPICFLAGS?= -DPIC CAPICFLAGS?= ${CPPPICFLAGS} ${CPICFLAGS} APICFLAGS ?= .elif ${MACHINE_ARCH} == "mipsel" || ${MACHINE_ARCH} == "mipseb" # mips-specific shared library flags # On mips, all libs are compiled with ABIcalls, not just sharedlibs. MKPICLIB= no # so turn shlib PIC flags on for ${AS}. AINC+=-DABICALLS AFLAGS+= -fPIC AS+= -KPIC .elif ${MACHINE_ARCH} == "vax" && ${OBJECT_FMT} == "ELF" # On the VAX, all object are PIC by default, not just sharedlibs. MKPICLIB= no .elif (${MACHINE_ARCH} == "sparc" || ${MACHINE_ARCH} == "sparc64") && \ ${OBJECT_FMT} == "ELF" # If you use -fPIC you need to define BIGPIC to turn on 32-bit # relocations in asm code FPICFLAGS ?= -fPIC CPICFLAGS ?= -fPIC -DPIC CPPPICFLAGS?= -DPIC -DBIGPIC CAPICFLAGS?= ${CPPPICFLAGS} ${CPICFLAGS} APICFLAGS ?= -KPIC .else # Platform-independent flags for NetBSD a.out shared libraries SHLIB_SOVERSION=${SHLIB_FULLVERSION} SHLIB_SHFLAGS= FPICFLAGS ?= -fPIC CPICFLAGS?= -fPIC -DPIC CPPPICFLAGS?= -DPIC CAPICFLAGS?= ${CPPPICFLAGS} ${CPICFLAGS} APICFLAGS?= -k .endif # Platform-independent linker flags for ELF shared libraries .if ${OBJECT_FMT} == "ELF" SHLIB_SOVERSION= ${SHLIB_MAJOR} SHLIB_SHFLAGS= -soname lib${LIB}.so.${SHLIB_SOVERSION} SHLIB_LDSTARTFILE?= /usr/lib/crtbeginS.o SHLIB_LDENDFILE?= /usr/lib/crtendS.o .endif # for compatibility with the following CC_PIC?= ${CPICFLAGS} LD_shared=${SHLIB_SHFLAGS} .endif # NetBSD .if ${TARGET_OSNAME} == "FreeBSD" .if ${OBJECT_FMT} == "ELF" SHLIB_SOVERSION= ${SHLIB_MAJOR} SHLIB_SHFLAGS= -soname lib${LIB}.so.${SHLIB_SOVERSION} .else SHLIB_SHFLAGS= -assert pure-text .endif SHLIB_LDSTARTFILE= SHLIB_LDENDFILE= CC_PIC?= -fpic LD_shared=${SHLIB_SHFLAGS} .endif # FreeBSD MKPICLIB?= yes # sys.mk can override these LD_X?=-X LD_x?=-x LD_r?=-r # Non BSD machines will be using bmake. .if ${TARGET_OSNAME} == "SunOS" LD_shared=-assert pure-text .if ${OBJECT_FMT} == "ELF" || ${MACHINE} == "solaris" # Solaris LD_shared=-h lib${LIB}.so.${SHLIB_MAJOR} -G .endif .elif ${TARGET_OSNAME} == "HP-UX" LD_shared=-b LD_so=sl DLLIB= # HPsUX lorder does not grok anything but .o LD_sobjs=`${LORDER} ${OBJS} | ${TSORT} | sed 's,\.o,${PICO},'` LD_pobjs=`${LORDER} ${OBJS} | ${TSORT} | sed 's,\.o,.po,'` .elif ${TARGET_OSNAME} == "OSF1" LD_shared= -msym -shared -expect_unresolved '*' LD_solib= -all lib${LIB}_pic.a DLLIB= # lorder does not grok anything but .o LD_sobjs=`${LORDER} ${OBJS} | ${TSORT} | sed 's,\.o,${PICO},'` LD_pobjs=`${LORDER} ${OBJS} | ${TSORT} | sed 's,\.o,.po,'` AR_cq= -cqs .elif ${TARGET_OSNAME} == "FreeBSD" LD_solib= lib${LIB}_pic.a .elif ${TARGET_OSNAME} == "Linux" SHLIB_LD = ${CC} # this is ambiguous of course -LD_shared=-shared -Wl,"-h lib${LIB}.so.${SHLIB_MAJOR}" +LD_shared=-shared -Wl,"-soname lib${LIB}.so.${SHLIB_MAJOR}" LD_solib= -Wl,--whole-archive lib${LIB}_pic.a -Wl,--no-whole-archive +.if ${COMPILER_TYPE} == "gcc" # Linux uses GNU ld, which is a multi-pass linker # so we don't need to use lorder or tsort LD_objs = ${OBJS} LD_pobjs = ${POBJS} LD_sobjs = ${SOBJS} +.endif .elif ${TARGET_OSNAME} == "Darwin" SHLIB_LD = ${CC} SHLIB_INSTALL_VERSION ?= ${SHLIB_MAJOR} SHLIB_COMPATABILITY_VERSION ?= ${SHLIB_MAJOR}.${SHLIB_MINOR:U0} SHLIB_COMPATABILITY ?= \ -compatibility_version ${SHLIB_COMPATABILITY_VERSION} \ -current_version ${SHLIB_FULLVERSION} LD_shared = -dynamiclib \ -flat_namespace -undefined suppress \ -install_name ${LIBDIR}/lib${LIB}.${SHLIB_INSTALL_VERSION}.${LD_solink} \ ${SHLIB_COMPATABILITY} SHLIB_LINKS = .for v in ${SHLIB_COMPATABILITY_VERSION} ${SHLIB_INSTALL_VERSION} .if "$v" != "${SHLIB_FULLVERSION}" SHLIB_LINKS += lib${LIB}.$v.${LD_solink} .endif .endfor .if ${MK_LINKLIB} != "no" SHLIB_LINKS += lib${LIB}.${LD_solink} .endif LD_so = ${SHLIB_FULLVERSION}.dylib LD_sobjs = ${SOBJS:O:u} LD_solib = ${LD_sobjs} SOLIB = ${LD_sobjs} LD_solink = dylib .if ${MACHINE_ARCH} == "i386" PICFLAG ?= -fPIC .else PICFLAG ?= -fPIC -fno-common .endif RANLIB = : .endif SHLIB_LD ?= ${LD} .if !empty(SHLIB_MAJOR) .if ${NEED_SOLINKS} && empty(SHLIB_LINKS) .if ${MK_LINKLIB} != "no" SHLIB_LINKS = lib${LIB}.${LD_solink} .endif .if "${SHLIB_FULLVERSION}" != "${SHLIB_MAJOR}" SHLIB_LINKS += lib${LIB}.${LD_solink}.${SHLIB_MAJOR} .endif .endif .endif LIBTOOL?=libtool LD_shared ?= -Bshareable -Bforcearchive LD_so ?= so.${SHLIB_FULLVERSION} LD_solink ?= so .if empty(LORDER) LD_objs ?= ${OBJS} LD_pobjs ?= ${POBJS} LD_sobjs ?= ${SOBJS} .else LD_objs ?= `${LORDER} ${OBJS} | ${TSORT}` LD_sobjs ?= `${LORDER} ${SOBJS} | ${TSORT}` LD_pobjs ?= `${LORDER} ${POBJS} | ${TSORT}` .endif LD_solib ?= ${LD_sobjs} AR_cq ?= cq .if exists(/netbsd) && exists(${DESTDIR}/usr/lib/libdl.so) DLLIB ?= -ldl .endif # some libs have lots of objects, and scanning all .o, .po and ${PICO} meta files # is a waste of time, this tells meta.autodep.mk to just pick one # (typically ${PICO}) # yes, 42 is a random number. .if ${MK_DIRDEPS_BUILD} == "yes" && ${SRCS:Uno:[\#]} > 42 OPTIMIZE_OBJECT_META_FILES ?= yes .endif .if ${MK_LIBTOOL} == "yes" # because libtool is so fascist about naming the object files, # we cannot (yet) build profiled libs MK_PROFILE=no _LIBS=lib${LIB}.a .if exists(${.CURDIR}/shlib_version) SHLIB_AGE != . ${.CURDIR}/shlib_version ; echo $$age .endif .else # for the normal .a we do not want to strip symbols .c.o: ${COMPILE.c} ${.IMPSRC} # for the normal .a we do not want to strip symbols ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} .S.o .s.o: ${COMPILE.S} ${CFLAGS:M-[ID]*} ${AINC} ${.IMPSRC} .if (${LD_X} == "") .c.po: ${COMPILE.c} ${CC_PG} ${PROFFLAGS} ${.IMPSRC} -o ${.TARGET} ${CXX_SUFFIXES:%=%.po}: ${COMPILE.cc} -pg ${.IMPSRC} -o ${.TARGET} .S${PICO} .s${PICO}: ${COMPILE.S} ${PICFLAG} ${CC_PIC} ${CFLAGS:M-[ID]*} ${AINC} ${.IMPSRC} -o ${.TARGET} .else .c.po: ${COMPILE.c} ${CC_PG} ${PROFFLAGS} ${.IMPSRC} -o ${.TARGET}.o @${LD} ${LD_X} ${LD_r} ${.TARGET}.o -o ${.TARGET} @rm -f ${.TARGET}.o ${CXX_SUFFIXES:%=%.po}: ${COMPILE.cc} ${CXX_PG} ${.IMPSRC} -o ${.TARGET}.o ${LD} ${LD_X} ${LD_r} ${.TARGET}.o -o ${.TARGET} @rm -f ${.TARGET}.o .S${PICO} .s${PICO}: ${COMPILE.S} ${PICFLAG} ${CC_PIC} ${CFLAGS:M-[ID]*} ${AINC} ${.IMPSRC} -o ${.TARGET}.o ${LD} ${LD_x} ${LD_r} ${.TARGET}.o -o ${.TARGET} @rm -f ${.TARGET}.o .endif .if (${LD_x} == "") .c${PICO}: ${COMPILE.c} ${PICFLAG} ${CC_PIC} ${.IMPSRC} -o ${.TARGET} ${CXX_SUFFIXES:%=%${PICO}}: ${COMPILE.cc} ${PICFLAG} ${CC_PIC} ${.IMPSRC} -o ${.TARGET} .S.po .s.po: ${COMPILE.S} ${PROFFLAGS} ${CFLAGS:M-[ID]*} ${AINC} ${.IMPSRC} -o ${.TARGET} .else .c${PICO}: ${COMPILE.c} ${PICFLAG} ${CC_PIC} ${.IMPSRC} -o ${.TARGET}.o ${LD} ${LD_x} ${LD_r} ${.TARGET}.o -o ${.TARGET} @rm -f ${.TARGET}.o ${CXX_SUFFIXES:%=%${PICO}}: ${COMPILE.cc} ${PICFLAG} ${CC_PIC} ${.IMPSRC} -o ${.TARGET}.o ${LD} ${LD_x} ${LD_r} ${.TARGET}.o -o ${.TARGET} @rm -f ${.TARGET}.o .S.po .s.po: ${COMPILE.S} ${PROFFLAGS} ${CFLAGS:M-[ID]*} ${AINC} ${.IMPSRC} -o ${.TARGET}.o ${LD} ${LD_X} ${LD_r} ${.TARGET}.o -o ${.TARGET} @rm -f ${.TARGET}.o .endif .endif .c.ln: ${LINT} ${LINTFLAGS} ${CFLAGS:M-[IDU]*} -i ${.IMPSRC} .if ${MK_LIBTOOL} != "yes" .if !defined(PICFLAG) PICFLAG=-fpic .endif _LIBS= .if ${MK_ARCHIVE} != "no" _LIBS += lib${LIB}.a .endif .if ${MK_PROFILE} != "no" _LIBS+=lib${LIB}_p.a POBJS+=${OBJS:.o=.po} .endif .if ${MK_PIC} != "no" .if ${MK_PICLIB} == "no" SOLIB ?= lib${LIB}.a .else SOLIB=lib${LIB}_pic.a _LIBS+=${SOLIB} .endif .if !empty(SHLIB_FULLVERSION) _LIBS+=lib${LIB}.${LD_so} .endif .endif .if ${MK_LINT} != "no" _LIBS+=llib-l${LIB}.ln .endif # here is where you can define what LIB* are .-include .if ${MK_DPADD_MK} == "yes" # lots of cool magic, but might not suit everyone. .include .endif .if empty(LIB) _LIBS= .elif ${MK_LDORDER_MK} != "no" # Record any libs that we need to be linked with _LIBS+= ${libLDORDER_INC} .include .endif .if !defined(_SKIP_BUILD) realbuild: ${_LIBS} .endif all: _SUBDIRUSE .for s in ${SRCS:N*.h:M*/*} ${.o ${PICO} .po .lo:L:@o@${s:T:R}$o@}: $s .endfor OBJS+= ${SRCS:T:N*.h:R:S/$/.o/g} .NOPATH: ${OBJS} .if ${MK_LIBTOOL} == "yes" .if ${MK_PIC} == "no" LT_STATIC=-static .else LT_STATIC= .endif SHLIB_AGE?=0 # .lo's are created as a side effect .s.o .S.o .c.o: ${LIBTOOL} --mode=compile ${CC} ${LT_STATIC} ${CFLAGS} ${CPPFLAGS} ${IMPFLAGS} -c ${.IMPSRC} # can't really do profiled libs with libtool - its too fascist about # naming the output... -lib${LIB}.a:: ${OBJS} +lib${LIB}.a: ${OBJS} @rm -f ${.TARGET} ${LIBTOOL} --mode=link ${CC} ${LT_STATIC} -o ${.TARGET:.a=.la} ${OBJS:.o=.lo} -rpath ${SHLIBDIR}:/usr/lib -version-info ${SHLIB_MAJOR}:${SHLIB_MINOR}:${SHLIB_AGE} @ln .libs/${.TARGET} . -lib${LIB}.${LD_so}:: lib${LIB}.a +lib${LIB}.${LD_so}: lib${LIB}.a @[ -s ${.TARGET}.${SHLIB_AGE} ] || { ln -s .libs/lib${LIB}.${LD_so}* . 2>/dev/null; : } @[ -s ${.TARGET} ] || ln -s ${.TARGET}.${SHLIB_AGE} ${.TARGET} .else # MK_LIBTOOL=yes -lib${LIB}.a:: ${OBJS} +lib${LIB}.a: ${OBJS} @${META_NOECHO} building standard ${LIB} library @rm -f ${.TARGET} @${AR} ${AR_cq} ${.TARGET} ${LD_objs} ${RANLIB} ${.TARGET} POBJS+= ${OBJS:.o=.po} .NOPATH: ${POBJS} -lib${LIB}_p.a:: ${POBJS} +lib${LIB}_p.a: ${POBJS} @${META_NOECHO} building profiled ${LIB} library @rm -f ${.TARGET} @${AR} ${AR_cq} ${.TARGET} ${LD_pobjs} ${RANLIB} ${.TARGET} SOBJS+= ${OBJS:.o=${PICO}} .NOPATH: ${SOBJS} -lib${LIB}_pic.a:: ${SOBJS} +lib${LIB}_pic.a: ${SOBJS} @${META_NOECHO} building shared object ${LIB} library @rm -f ${.TARGET} @${AR} ${AR_cq} ${.TARGET} ${LD_sobjs} ${RANLIB} ${.TARGET} #SHLIB_LDADD?= ${LDADD} # bound to be non-portable... # this is known to work for NetBSD 1.6 and FreeBSD 4.2 lib${LIB}.${LD_so}: ${SOLIB} ${DPADD} @${META_NOECHO} building shared ${LIB} library \(version ${SHLIB_FULLVERSION}\) @rm -f ${.TARGET} .if ${TARGET_OSNAME} == "NetBSD" || ${TARGET_OSNAME} == "FreeBSD" .if ${OBJECT_FMT} == "ELF" ${SHLIB_LD} -x -shared ${SHLIB_SHFLAGS} -o ${.TARGET} \ ${SHLIB_LDSTARTFILE} \ --whole-archive ${SOLIB} --no-whole-archive ${SHLIB_LDADD} \ ${SHLIB_LDENDFILE} .else ${SHLIB_LD} ${LD_x} ${LD_shared} \ -o ${.TARGET} ${SOLIB} ${SHLIB_LDADD} .endif .else ${SHLIB_LD} -o ${.TARGET} ${LD_shared} ${LD_solib} ${DLLIB} ${SHLIB_LDADD} .endif .endif .if !empty(SHLIB_LINKS) rm -f ${SHLIB_LINKS}; ${SHLIB_LINKS:O:u:@x@ln -s ${.TARGET} $x;@} .endif LOBJS+= ${LSRCS:.c=.ln} ${SRCS:M*.c:.c=.ln} .NOPATH: ${LOBJS} LLIBS?= -lc llib-l${LIB}.ln: ${LOBJS} @${META_NOECHO} building llib-l${LIB}.ln @rm -f llib-l${LIB}.ln @${LINT} -C${LIB} ${LOBJS} ${LLIBS} .if !target(clean) cleanlib: .PHONY rm -f a.out [Ee]rrs mklog core *.core ${CLEANFILES} rm -f lib${LIB}.a ${OBJS} rm -f lib${LIB}_p.a ${POBJS} rm -f lib${LIB}_pic.a lib${LIB}.so.*.* ${SOBJS} rm -f llib-l${LIB}.ln ${LOBJS} .if !empty(SHLIB_LINKS) rm -f ${SHLIB_LINKS} .endif clean: _SUBDIRUSE cleanlib cleandir: _SUBDIRUSE cleanlib .else cleandir: _SUBDIRUSE clean .endif .if defined(SRCS) && (!defined(MKDEP) || ${MKDEP} != autodep) afterdepend: .depend @(TMP=/tmp/_depend$$$$; \ sed -e 's/^\([^\.]*\).o[ ]*:/\1.o \1.po \1${PICO} \1.ln:/' \ < .depend > $$TMP; \ mv $$TMP .depend) .endif .if !target(install) .if !target(beforeinstall) beforeinstall: .endif .if !empty(LIBOWN) LIB_INSTALL_OWN ?= -o ${LIBOWN} -g ${LIBGRP} .endif .include .if !target(libinstall) && !empty(LIB) realinstall: libinstall libinstall: [ -d ${DESTDIR}/${LIBDIR} ] || \ ${INSTALL} -d ${LIB_INSTALL_OWN} -m 775 ${DESTDIR}${LIBDIR} .if ${MK_ARCHIVE} != "no" ${INSTALL} ${COPY} ${LIB_INSTALL_OWN} -m 644 lib${LIB}.a \ ${DESTDIR}${LIBDIR} ${RANLIB} ${DESTDIR}${LIBDIR}/lib${LIB}.a chmod ${LIBMODE} ${DESTDIR}${LIBDIR}/lib${LIB}.a .endif .if ${MK_PROFILE} != "no" ${INSTALL} ${COPY} ${LIB_INSTALL_OWN} -m 644 \ lib${LIB}_p.a ${DESTDIR}${LIBDIR} ${RANLIB} ${DESTDIR}${LIBDIR}/lib${LIB}_p.a chmod ${LIBMODE} ${DESTDIR}${LIBDIR}/lib${LIB}_p.a .endif .if ${MK_LDORDER_MK} != "no" ${INSTALL} ${COPY} ${LIB_INSTALL_OWN} -m 644 \ lib${LIB}.ldorder.inc ${DESTDIR}${LIBDIR} .endif .if ${MK_PIC} != "no" .if ${MK_PICLIB} != "no" ${INSTALL} ${COPY} ${LIB_INSTALL_OWN} -m 644 \ lib${LIB}_pic.a ${DESTDIR}${LIBDIR} ${RANLIB} ${DESTDIR}${LIBDIR}/lib${LIB}_pic.a chmod ${LIBMODE} ${DESTDIR}${LIBDIR}/lib${LIB}_pic.a .endif .if !empty(SHLIB_MAJOR) ${INSTALL} ${COPY} ${LIB_INSTALL_OWN} -m ${LIBMODE} \ lib${LIB}.${LD_so} ${DESTDIR}${LIBDIR} .if !empty(SHLIB_LINKS) (cd ${DESTDIR}${LIBDIR} && { rm -f ${SHLIB_LINKS}; ${SHLIB_LINKS:O:u:@x@ln -s lib${LIB}.${LD_so} $x;@} }) .endif .endif .endif .if ${MK_LINT} != "no" && ${MK_LINKLIB} != "no" && !empty(LOBJS) ${INSTALL} ${COPY} ${LIB_INSTALL_OWN} -m ${LIBMODE} \ llib-l${LIB}.ln ${DESTDIR}${LINTLIBDIR} .endif .if defined(LINKS) && !empty(LINKS) @set ${LINKS}; ${_LINKS_SCRIPT} .endif .endif .if ${MK_MAN} != "no" install: maninstall _SUBDIRUSE maninstall: afterinstall .endif afterinstall: realinstall libinstall: beforeinstall realinstall: beforeinstall .endif .if defined(FILES) || defined(FILESGROUPS) .include .endif .if ${MK_MAN} != "no" .include .endif .if ${MK_NLS} != "no" .include .endif .include .include .include .include .endif # during building we usually need/want to install libs somewhere central # note that we do NOT ch{own,grp} as that would likely fail at this point. # otherwise it is the same as realinstall # Note that we don't need this when using dpadd.mk .libinstall: ${_LIBS} test -d ${DESTDIR}${LIBDIR} || ${INSTALL} -d -m775 ${DESTDIR}${LIBDIR} .for _lib in ${_LIBS:M*.a} ${INSTALL} ${COPY} -m 644 ${_lib} ${DESTDIR}${LIBDIR} ${RANLIB} ${DESTDIR}${LIBDIR}/${_lib} .endfor .for _lib in ${_LIBS:M*.${LD_solink}*:O:u} ${INSTALL} ${COPY} -m ${LIBMODE} ${_lib} ${DESTDIR}${LIBDIR} .if !empty(SHLIB_LINKS) (cd ${DESTDIR}${LIBDIR} && { ${SHLIB_LINKS:O:u:@x@ln -sf ${_lib} $x;@}; }) .endif .endfor @touch ${.TARGET} .if !empty(LIB) STAGE_LIBDIR?= ${STAGE_OBJTOP}${LIBDIR} stage_libs: ${_LIBS} .endif .include .endif Index: stable/12/contrib/bmake/mk/meta.autodep.mk =================================================================== --- stable/12/contrib/bmake/mk/meta.autodep.mk (revision 361673) +++ stable/12/contrib/bmake/mk/meta.autodep.mk (revision 361674) @@ -1,316 +1,320 @@ -# $Id: meta.autodep.mk,v 1.48 2018/04/15 06:30:04 sjg Exp $ +# $Id: meta.autodep.mk,v 1.50 2018/06/08 01:25:31 sjg Exp $ # # @(#) Copyright (c) 2010, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # _this ?= ${.PARSEFILE} .if !target(__${_this}__) __${_this}__: .NOTMAIN .-include +PICO?= .pico + .if defined(SRCS) # it would be nice to be able to query .SUFFIXES -OBJ_EXTENSIONS+= .o .po .lo .So +OBJ_EXTENSIONS+= .o .po .lo ${PICO} # explicit dependencies help short-circuit .SUFFIX searches SRCS_DEP_FILTER+= N*.[hly] .for s in ${SRCS:${SRCS_DEP_FILTER:O:u:ts:}} .for e in ${OBJ_EXTENSIONS:O:u} .if !target(${s:T:R}$e) ${s:T:R}$e: $s .endif .endfor .endfor .endif .if make(gendirdeps) # you are supposed to know what you are doing! UPDATE_DEPENDFILE = yes .elif !empty(.TARGETS) && !make(all) # do not update the *depend* files # unless we are building the entire directory or the default target. # NO means don't update .depend - or Makefile.depend* # no means update .depend but not Makefile.depend* UPDATE_DEPENDFILE = NO .elif ${.MAKEFLAGS:M-k} != "" # it is a bad idea to update anything UPDATE_DEPENDFILE = NO .endif _CURDIR ?= ${.CURDIR} _OBJDIR ?= ${.OBJDIR} _OBJTOP ?= ${OBJTOP} _OBJROOT ?= ${OBJROOT:U${_OBJTOP}} _DEPENDFILE := ${_CURDIR}/${.MAKE.DEPENDFILE:T} .if ${.MAKE.LEVEL} > 0 || ${BUILD_AT_LEVEL0:Uyes:tl} == "yes" # do not allow auto update if we ever built this dir without filemon NO_FILEMON_COOKIE = .nofilemon CLEANFILES += ${NO_FILEMON_COOKIE} .if ${.MAKE.MODE:Uno:Mnofilemon} != "" UPDATE_DEPENDFILE = NO all: ${NO_FILEMON_COOKIE} ${NO_FILEMON_COOKIE}: .NOMETA @echo UPDATE_DEPENDFILE=NO > ${.TARGET} .elif exists(${NO_FILEMON_COOKIE}) UPDATE_DEPENDFILE = NO .warning ${RELDIR} built with nofilemon; UPDATE_DEPENDFILE=NO .endif .endif .if ${.MAKE.LEVEL} == 0 .if ${BUILD_AT_LEVEL0:Uyes:tl} == "no" UPDATE_DEPENDFILE = NO .endif .endif .if !exists(${_DEPENDFILE}) _bootstrap_dirdeps = yes .endif _bootstrap_dirdeps ?= no UPDATE_DEPENDFILE ?= yes .if ${DEBUG_AUTODEP:Uno:@m@${RELDIR:M$m}@} != "" .info ${_DEPENDFILE:S,${SRCTOP}/,,} update=${UPDATE_DEPENDFILE} .endif .if !empty(XMAKE_META_FILE) .if exists(${.OBJDIR}/${XMAKE_META_FILE}) # we cannot get accurate dependencies from an update build UPDATE_DEPENDFILE = NO .else META_XTRAS += ${XMAKE_META_FILE} .endif .endif .if ${_bootstrap_dirdeps} == "yes" || exists(${_DEPENDFILE}) # if it isn't supposed to be touched by us the Makefile should have # UPDATE_DEPENDFILE = no WANT_UPDATE_DEPENDFILE ?= yes .endif .if ${WANT_UPDATE_DEPENDFILE:Uno:tl} != "no" .if ${.MAKE.MODE:Uno:Mmeta*} == "" || ${.MAKE.MODE:Uno:M*read*} != "" UPDATE_DEPENDFILE = no .endif .if ${DEBUG_AUTODEP:Uno:@m@${RELDIR:M$m}@} != "" .info ${_DEPENDFILE:S,${SRCTOP}/,,} update=${UPDATE_DEPENDFILE} .endif .if ${UPDATE_DEPENDFILE:tl} == "yes" # sometimes we want .meta files generated to aid debugging/error detection # but do not want to consider them for dependencies # for example the result of running configure # just make sure this is not empty META_FILE_FILTER ?= N.meta # never consider these META_FILE_FILTER += Ndirdeps.cache* .if !empty(DPADD) # if we have any non-libs in DPADD, # they probably need to be paid attention to .if !empty(DPLIBS) FORCE_DPADD = ${DPADD:${DPLIBS:${M_ListToSkip}}:${DPADD_LAST:${M_ListToSkip}}} .else _nonlibs := ${DPADD:T:Nlib*:N*include} .if !empty(_nonlibs) FORCE_DPADD += ${_nonlibs:@x@${DPADD:M*/$x}@} .endif .endif .endif .if !make(gendirdeps) .END: gendirdeps .endif # if we don't have OBJS, then .depend isn't useful .if !target(.depend) && (!empty(OBJS) || ${.ALLTARGETS:M*.o} != "") # some makefiles and/or targets contain # circular dependencies if you dig too deep # (as meta mode is apt to do) # so we provide a means of suppressing them. # the input to the loop below is target: dependency # with just one dependency per line. # Also some targets are not really local, or use random names. # Use local.autodep.mk to provide local additions! SUPPRESS_DEPEND += \ ${SB:S,/,_,g}* \ *:y.tab.c \ *.c:*.c \ *.h:*.h .NOPATH: .depend # we use ${.MAKE.META.CREATED} to trigger an update but # we process using ${.MAKE.META.FILES} # the double $$ defers initial evaluation # if necessary, we fake .po dependencies, just so the result # in Makefile.depend* is stable # The current objdir may be referred to in various ways OBJDIR_REFS += ${.OBJDIR} ${.OBJDIR:tA} ${_OBJDIR} ${RELOBJTOP}/${RELDIR} _depend = .depend # it would be nice to be able to get .SUFFIXES as ${.SUFFIXES} # we actually only care about the .SUFFIXES of files that might be # generated by tools like yacc. DEPEND_SUFFIXES += .c .h .cpp .hpp .cxx .hxx .cc .hh .depend: .NOMETA $${.MAKE.META.CREATED} ${_this} @echo "Updating $@: ${.OODATE:T:[1..8]}" @egrep -i '^R .*\.(${DEPEND_SUFFIXES:tl:O:u:S,^.,,:ts|})$$' /dev/null ${.MAKE.META.FILES:T:O:u:${META_FILE_FILTER:ts:}:M*o.meta} | \ sed -e 's, \./, ,${OBJDIR_REFS:O:u:@d@;s, $d/, ,@};/\//d' \ -e 's,^\([^/][^/]*\).meta...[0-9]* ,\1: ,' | \ sort -u | \ while read t d; do \ case "$$d:" in $$t) continue;; esac; \ case "$$t$$d" in ${SUPPRESS_DEPEND:U.:O:u:ts|}) continue;; esac; \ echo $$t $$d; \ done > $@.${.MAKE.PID} @case "${.MAKE.META.FILES:T:M*.po.*}" in \ *.po.*) mv $@.${.MAKE.PID} $@;; \ *) { cat $@.${.MAKE.PID}; \ - sed 's,\.So:,.o:,;s,\.o:,.po:,' $@.${.MAKE.PID}; } | sort -u > $@; \ + sed 's,\${PICO}:,.o:,;s,\.o:,.po:,' $@.${.MAKE.PID}; } | sort -u > $@; \ rm -f $@.${.MAKE.PID};; \ esac .else # make sure this exists .depend: # do _not_ assume that .depend is in any fit state for us to use CAT_DEPEND = /dev/null .if ${.MAKE.LEVEL} > 0 .export CAT_DEPEND .endif _depend = .endif .if ${DEBUG_AUTODEP:Uno:@m@${RELDIR:M$m}@} != "" .info ${_DEPENDFILE:S,${SRCTOP}/,,} _depend=${_depend} .endif .if ${UPDATE_DEPENDFILE} == "yes" gendirdeps: ${_DEPENDFILE} .endif .if !target(${_DEPENDFILE}) .if ${_bootstrap_dirdeps} == "yes" # We are boot-strapping a new directory # Use DPADD to seed DIRDEPS .if !empty(DPADD) # anything which matches ${_OBJROOT}* but not ${_OBJTOP}* # needs to be qualified in DIRDEPS # The pseudo machine "host" is used for HOST_TARGET DIRDEPS += \ ${DPADD:M${_OBJTOP}*:H:C,${_OBJTOP}[^/]*/,,:N.:O:u} \ ${DPADD:M${_OBJROOT}*:N${_OBJTOP}*:N${STAGE_ROOT:U${_OBJTOP}}/*:H:S,${_OBJROOT},,:C,^([^/]+)/(.*),\2.\1,:S,${HOST_TARGET}$,host,:N.*:O:u} .endif .endif _gendirdeps_mutex = .if defined(NEED_GENDIRDEPS_MUTEX) # If a src dir gets built with multiple object dirs, # we need a mutex. Obviously, this is best avoided. # Note if .MAKE.DEPENDFILE is common for all ${MACHINE} # you either need to mutex, or ensure only one machine builds at a time! # lockf is an example of a suitable tool LOCKF ?= /usr/bin/lockf .if exists(${LOCKF}) GENDIRDEPS_MUTEXER ?= ${LOCKF} -k .endif .if empty(GENDIRDEPS_MUTEXER) .error NEED_GENDIRDEPS_MUTEX defined, but GENDIRDEPS_MUTEXER not set .else _gendirdeps_mutex = ${GENDIRDEPS_MUTEXER} ${GENDIRDEPS_MUTEX:U${_CURDIR}/Makefile} .endif .endif # If we have META_XTRAS we most likely did not create them # but we need to behave as if we did. # Avoid adding glob patterns to .MAKE.META.CREATED though. .MAKE.META.CREATED += ${META_XTRAS:N*\**:O:u} .if make(gendirdeps) META_FILES = *.meta .elif ${OPTIMIZE_OBJECT_META_FILES:Uno:tl} == "no" META_FILES = ${.MAKE.META.FILES:T:N.depend*:O:u} .else -# if we have 1000's of .o.meta, .So.meta etc we need only look at one set +# if we have 1000's of .o.meta, ${PICO}.meta etc we need only look at one set # it is left as an exercise for the reader to work out what this does META_FILES = ${.MAKE.META.FILES:T:N.depend*:N*o.meta:O:u} \ ${.MAKE.META.FILES:T:M*.${.MAKE.META.FILES:M*o.meta:R:E:O:u:[1]}.meta:O:u} .endif .if ${DEBUG_AUTODEP:Uno:@m@${RELDIR:M$m}@} != "" .info ${_DEPENDFILE:S,${SRCTOP}/,,}: ${_depend} ${.PARSEDIR}/gendirdeps.mk ${META2DEPS} xtras=${META_XTRAS} .endif .if ${.MAKE.LEVEL} > 0 .if ${UPDATE_DEPENDFILE} == "yes" .-include <${.CURDIR}/${.MAKE.DEPENDFILE_PREFIX}.options> .endif .if !empty(GENDIRDEPS_FILTER) .export GENDIRDEPS_FILTER .endif +# export to avoid blowing command line limit +META_FILES := ${META_XTRAS:U:O:u} ${META_FILES:U:T:O:u:${META_FILE_FILTER:ts:}} +.export META_FILES .endif # we might have .../ in MAKESYSPATH _makesyspath:= ${_PARSEDIR} ${_DEPENDFILE}: ${_depend} ${.PARSEDIR}/gendirdeps.mk ${META2DEPS} $${.MAKE.META.CREATED} @echo Checking $@: ${.OODATE:T:[1..8]} @(cd . && ${GENDIRDEPS_ENV} \ SKIP_GENDIRDEPS='${SKIP_GENDIRDEPS:O:u}' \ DPADD='${FORCE_DPADD:O:u}' ${_gendirdeps_mutex} \ MAKESYSPATH=${_makesyspath} \ - ${.MAKE} -f gendirdeps.mk RELDIR=${RELDIR} _DEPENDFILE=${_DEPENDFILE} \ - META_FILES='${META_XTRAS:O:u} ${META_FILES:T:O:u:${META_FILE_FILTER:ts:}}') + ${.MAKE} -f gendirdeps.mk RELDIR=${RELDIR} _DEPENDFILE=${_DEPENDFILE}) @test -s $@ && touch $@; : .endif .endif .endif .if ${_bootstrap_dirdeps} == "yes" .if ${BUILD_AT_LEVEL0:Uno} == "no" DIRDEPS+= ${RELDIR}.${TARGET_SPEC:U${MACHINE}} .endif # make sure this is included at least once .include .else ${_DEPENDFILE}: .PRECIOUS .endif CLEANFILES += *.meta filemon.* *.db # these make it easy to gather some stats now_utc = ${%s:L:gmtime} start_utc := ${now_utc} meta_stats= meta=${empty(.MAKE.META.FILES):?0:${.MAKE.META.FILES:[#]}} \ created=${empty(.MAKE.META.CREATED):?0:${.MAKE.META.CREATED:[#]}} #.END: _reldir_finish .if target(gendirdeps) _reldir_finish: gendirdeps .endif _reldir_finish: .NOMETA @echo "${TIME_STAMP} Finished ${RELDIR}.${TARGET_SPEC} seconds=$$(( ${now_utc} - ${start_utc} )) ${meta_stats}" #.ERROR: _reldir_failed _reldir_failed: .NOMETA @echo "${TIME_STAMP} Failed ${RELDIR}.${TARGET_SPEC} seconds=$$(( ${now_utc} - ${start_utc} )) ${meta_stats}" .if defined(WITH_META_STATS) && ${.MAKE.LEVEL} > 0 .END: _reldir_finish .ERROR: _reldir_failed .endif .endif Index: stable/12/contrib/bmake/mk/meta.stage.mk =================================================================== --- stable/12/contrib/bmake/mk/meta.stage.mk (revision 361673) +++ stable/12/contrib/bmake/mk/meta.stage.mk (revision 361674) @@ -1,362 +1,366 @@ -# $Id: meta.stage.mk,v 1.55 2017/10/27 01:17:09 sjg Exp $ +# $Id: meta.stage.mk,v 1.59 2020/04/25 18:18:27 sjg Exp $ # # @(#) Copyright (c) 2011-2017, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # .ifndef NO_STAGING .if !target(__${.PARSEFILE}__) # the guard target is defined later +.-include + .if ${.MAKE.DEPENDFILE_PREFERENCE:U${.MAKE.DEPENDFILE}:M*.${MACHINE}} != "" # this is generally safer anyway -_dirdep ?= ${RELDIR}.${MACHINE} +_dirdep ?= ${RELDIR}.${TARGET_SPEC:U${MACHINE}} .else _dirdep ?= ${RELDIR} .endif CLEANFILES+= .dirdep # this allows us to trace dependencies back to their src dir .dirdep: .NOPATH @echo '${_dirdep}' > $@ .if defined(NO_POSIX_SHELL) || ${type printf:L:sh:Mbuiltin} == "" _stage_file_basename = `basename $$f` _stage_target_dirname = `dirname $$t` .else _stage_file_basename = $${f\#\#*/} _stage_target_dirname = $${t%/*} .endif _OBJROOT ?= ${OBJROOT:U${OBJTOP:H}} .if ${_OBJROOT:M*/} != "" _objroot ?= ${_OBJROOT:tA}/ .else _objroot ?= ${_OBJROOT:tA} .endif # make sure this is global _STAGED_DIRS ?= .export _STAGED_DIRS # add each dir we stage to to _STAGED_DIRS # and make sure we have absolute paths so that bmake # will match against .MAKE.META.BAILIWICK STAGE_DIR_FILTER = tA:@d@$${_STAGED_DIRS::+=$$d}$$d@ # convert _STAGED_DIRS into suitable filters GENDIRDEPS_FILTER += Nnot-empty-is-important \ ${_STAGED_DIRS:O:u:M${OBJTOP}*:S,${OBJTOP}/,N,} \ ${_STAGED_DIRS:O:u:M${_objroot}*:N${OBJTOP}*:S,${_objroot},,:C,^([^/]+)/(.*),N\2.\1,:S,${HOST_TARGET},.host,} LN_CP_SCRIPT = LnCp() { \ rm -f $$2 2> /dev/null; \ { [ -z "$$mode" ] && ${LN:Uln} $$1 $$2 2> /dev/null; } || \ cp -p $$1 $$2; } # a staging conflict should cause an error # a warning is handy when bootstapping different options. STAGE_CONFLICT?= ERROR .if ${STAGE_CONFLICT:tl} == "error" -STAGE_CONFLICT_ACTION= exit 1; +STAGE_CONFLICT_ACTION= exit 1 .else STAGE_CONFLICT_ACTION= .endif # it is an error for more than one src dir to try and stage # the same file STAGE_DIRDEP_SCRIPT = ${LN_CP_SCRIPT}; StageDirdep() { \ t=$$1; \ if [ -s $$t.dirdep ]; then \ cmp -s .dirdep $$t.dirdep && return; \ - echo "${STAGE_CONFLICT}: $$t installed by `cat $$t.dirdep` not ${_dirdep}" >&2; \ - ${STAGE_CONFLICT_ACTION} \ + x=`cat $$t.dirdep`; \ + case "${RELDIR}:${_dirdep}" in $${x%.*}:$${x}*) ;; \ + *) echo "${STAGE_CONFLICT}: $$t installed by $$x not ${_dirdep}" >&2; \ + ${STAGE_CONFLICT_ACTION} ;; esac; \ fi; \ LnCp .dirdep $$t.dirdep || exit 1; } # common logic for staging files # this all relies on RELDIR being set to a subdir of SRCTOP # we use ln(1) if we can, else cp(1) STAGE_FILE_SCRIPT = ${STAGE_DIRDEP_SCRIPT}; StageFiles() { \ case "$$1" in "") return;; -m) mode=$$2; shift 2;; *) mode=;; esac; \ dest=$$1; shift; \ mkdir -p $$dest; \ [ -s .dirdep ] || echo '${_dirdep}' > .dirdep; \ for f in "$$@"; do \ case "$$f" in */*) t=$$dest/${_stage_file_basename};; *) t=$$dest/$$f;; esac; \ StageDirdep $$t; \ LnCp $$f $$t || exit 1; \ [ -z "$$mode" ] || chmod $$mode $$t; \ done; :; } STAGE_LINKS_SCRIPT = ${STAGE_DIRDEP_SCRIPT}; StageLinks() { \ case "$$1" in "") return;; --) shift;; -*) ldest= lnf=$$1; shift;; /*) ldest=$$1/;; esac; \ dest=$$1; shift; \ mkdir -p $$dest; \ [ -s .dirdep ] || echo '${_dirdep}' > .dirdep; \ while test $$\# -ge 2; do \ l=$$ldest$$1; shift; \ t=$$dest/$$1; \ case "$$1" in */*) mkdir -p ${_stage_target_dirname};; esac; \ shift; \ StageDirdep $$t; \ rm -f $$t 2>/dev/null; \ ln $$lnf $$l $$t || exit 1; \ done; :; } STAGE_AS_SCRIPT = ${STAGE_DIRDEP_SCRIPT}; StageAs() { \ case "$$1" in "") return;; -m) mode=$$2; shift 2;; *) mode=;; esac; \ dest=$$1; shift; \ mkdir -p $$dest; \ [ -s .dirdep ] || echo '${_dirdep}' > .dirdep; \ while test $$\# -ge 2; do \ s=$$1; shift; \ t=$$dest/$$1; \ case "$$1" in */*) mkdir -p ${_stage_target_dirname};; esac; \ shift; \ StageDirdep $$t; \ LnCp $$s $$t || exit 1; \ [ -z "$$mode" ] || chmod $$mode $$t; \ done; :; } # this is simple, a list of the "staged" files depends on this, _STAGE_BASENAME_USE: .USE .dirdep ${.TARGET:T} @${STAGE_FILE_SCRIPT}; StageFiles ${.TARGET:H:${STAGE_DIR_FILTER}} ${.TARGET:T} _STAGE_AS_BASENAME_USE: .USE .dirdep ${.TARGET:T} @${STAGE_AS_SCRIPT}; StageAs ${.TARGET:H:${STAGE_DIR_FILTER}} ${.TARGET:T} ${STAGE_AS_${.TARGET:T}:U${.TARGET:T}} .endif # first time .if !empty(STAGE_INCSDIR) .if !empty(STAGE_INCS) -stage_incs: ${STAGE_INCS} +stage_incs: ${STAGE_INCS:N*\**} .endif .if target(stage_incs) || !empty(.ALLTARGETS:Mstage_includes) STAGE_TARGETS += stage_incs STAGE_INCS ?= ${.ALLSRC:N.dirdep:Nstage_*} stage_includes: stage_incs stage_incs: .dirdep @${STAGE_FILE_SCRIPT}; StageFiles ${STAGE_INCSDIR:${STAGE_DIR_FILTER}} ${STAGE_INCS} @touch $@ .endif .endif .if !empty(STAGE_LIBDIR) .if !empty(STAGE_LIBS) -stage_libs: ${STAGE_LIBS} +stage_libs: ${STAGE_LIBS:N*\**} .endif .if target(stage_libs) STAGE_TARGETS += stage_libs STAGE_LIBS ?= ${.ALLSRC:N.dirdep:Nstage_*} stage_libs: .dirdep @${STAGE_FILE_SCRIPT}; StageFiles ${STAGE_LIBDIR:${STAGE_DIR_FILTER}} ${STAGE_LIBS} .if !defined(NO_SHLIB_LINKS) .if !empty(SHLIB_LINKS) @${STAGE_LINKS_SCRIPT}; StageLinks -s ${STAGE_LIBDIR:${STAGE_DIR_FILTER}} \ ${SHLIB_LINKS:@t@${STAGE_LIBS:T:M$t.*} $t@} .elif !empty(SHLIB_LINK) && !empty(SHLIB_NAME) @${STAGE_LINKS_SCRIPT}; StageLinks -s ${STAGE_LIBDIR:${STAGE_DIR_FILTER}} ${SHLIB_NAME} ${SHLIB_LINK} .endif .endif @touch $@ .endif .endif .if !empty(STAGE_DIR) STAGE_SETS += _default STAGE_DIR._default = ${STAGE_DIR} STAGE_LINKS_DIR._default = ${STAGE_LINKS_DIR:U${STAGE_OBJTOP}} STAGE_SYMLINKS_DIR._default = ${STAGE_SYMLINKS_DIR:U${STAGE_OBJTOP}} STAGE_FILES._default = ${STAGE_FILES} STAGE_LINKS._default = ${STAGE_LINKS} STAGE_SYMLINKS._default = ${STAGE_SYMLINKS} .endif .if !empty(STAGE_SETS) CLEANFILES += ${STAGE_SETS:@s@stage*$s@} # some makefiles need to populate multiple directories .for s in ${STAGE_SETS:O:u} .if !empty(STAGE_FILES.$s) -stage_files.$s: ${STAGE_FILES.$s} +stage_files.$s: ${STAGE_FILES.$s:N*\**} .endif .if target(stage_files.$s) || target(stage_files${s:S,^,.,:N._default}) STAGE_TARGETS += stage_files STAGE_FILES.$s ?= ${.ALLSRC:N.dirdep:Nstage_*} .if !target(.stage_files.$s) .stage_files.$s: .if $s != "_default" stage_files: stage_files.$s stage_files.$s: .dirdep .else STAGE_FILES ?= ${.ALLSRC:N.dirdep:Nstage_*} stage_files: .dirdep .endif - @${STAGE_FILE_SCRIPT}; StageFiles ${FLAGS.$@} ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_FILES.$s} + @${STAGE_FILE_SCRIPT}; StageFiles ${FLAGS.$@} ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_FILES.$s:O} @touch $@ .endif .endif .if !empty(STAGE_LINKS.$s) stage_links.$s: .endif .if target(stage_links.$s) || target(stage_links${s:S,^,.,:N._default}) STAGE_LINKS_DIR.$s ?= ${STAGE_OBJTOP} STAGE_TARGETS += stage_links .if !target(.stage_links.$s) .stage_links.$s: .if $s != "_default" stage_links: stage_links.$s stage_links.$s: .dirdep .else stage_links: .dirdep .endif @${STAGE_LINKS_SCRIPT}; StageLinks ${STAGE_LINKS_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_LINKS.$s} @touch $@ .endif .endif .if !empty(STAGE_SYMLINKS.$s) stage_symlinks.$s: .endif .if target(stage_symlinks.$s) || target(stage_symlinks${s:S,^,.,:N._default}) STAGE_SYMLINKS_DIR.$s ?= ${STAGE_OBJTOP} STAGE_TARGETS += stage_symlinks .if !target(.stage_symlinks.$s) .stage_symlinks.$s: .if $s != "_default" stage_symlinks: stage_symlinks.$s stage_symlinks.$s: .dirdep .else stage_symlinks: .dirdep .endif @${STAGE_LINKS_SCRIPT}; StageLinks -s ${STAGE_SYMLINKS_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_SYMLINKS.$s} @touch $@ .endif .endif .endfor .endif .if !empty(STAGE_AS_SETS) CLEANFILES += ${STAGE_AS_SETS:@s@stage*$s@} # sometimes things need to be renamed as they are staged # each ${file} will be staged as ${STAGE_AS_${file:T}} # one could achieve the same with SYMLINKS # stage_as_and_symlink makes the original name a symlink to the new name # it is the same as using stage_as and stage_symlinks but ensures # both operations happen together .for s in ${STAGE_AS_SETS:O:u} .if !empty(STAGE_AS.$s) -stage_as.$s: ${STAGE_AS.$s} +stage_as.$s: ${STAGE_AS.$s:N*\**} .endif .if target(stage_as.$s) STAGE_TARGETS += stage_as STAGE_AS.$s ?= ${.ALLSRC:N.dirdep:Nstage_*} .if !target(.stage_as.$s) .stage_as.$s: stage_as: stage_as.$s stage_as.$s: .dirdep - @${STAGE_AS_SCRIPT}; StageAs ${FLAGS.$@} ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_AS.$s:@f@$f ${STAGE_AS_${f:tA}:U${STAGE_AS_${f:T}:U${f:T}}}@} + @${STAGE_AS_SCRIPT}; StageAs ${FLAGS.$@} ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_AS.$s:O:@f@$f ${STAGE_AS_${f:tA}:U${STAGE_AS_${f:T}:U${f:T}}}@} @touch $@ .endif .endif .if !empty(STAGE_AS_AND_SYMLINK.$s) -stage_as_and_symlink.$s: ${STAGE_AS_AND_SYMLINK.$s} +stage_as_and_symlink.$s: ${STAGE_AS_AND_SYMLINK.$s:N*\**} .endif .if target(stage_as_and_symlink.$s) STAGE_TARGETS += stage_as_and_symlink STAGE_AS_AND_SYMLINK.$s ?= ${.ALLSRC:N.dirdep:Nstage_*} .if !target(.stage_as_and_symlink.$s) .stage_as_and_symlink.$s: stage_as_and_symlink: stage_as_and_symlink.$s stage_as_and_symlink.$s: .dirdep - @${STAGE_AS_SCRIPT}; StageAs ${FLAGS.$@} ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_AS_AND_SYMLINK.$s:@f@$f ${STAGE_AS_${f:tA}:U${STAGE_AS_${f:T}:U${f:T}}}@} - @${STAGE_LINKS_SCRIPT}; StageLinks -s ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_AS_AND_SYMLINK.$s:@f@${STAGE_AS_${f:tA}:U${STAGE_AS_${f:T}:U${f:T}}} $f@} + @${STAGE_AS_SCRIPT}; StageAs ${FLAGS.$@} ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_AS_AND_SYMLINK.$s:O:@f@$f ${STAGE_AS_${f:tA}:U${STAGE_AS_${f:T}:U${f:T}}}@} + @${STAGE_LINKS_SCRIPT}; StageLinks -s ${STAGE_FILES_DIR.$s:U${STAGE_DIR.$s}:${STAGE_DIR_FILTER}} ${STAGE_AS_AND_SYMLINK.$s:O:@f@${STAGE_AS_${f:tA}:U${STAGE_AS_${f:T}:U${f:T}}} $f@} @touch $@ .endif .endif .endfor .endif CLEANFILES += ${STAGE_TARGETS} stage_incs stage_includes # this lot also only makes sense the first time... .if !target(__${.PARSEFILE}__) __${.PARSEFILE}__: # stage_*links usually needs to follow any others. # for non-jobs mode the order here matters staging: ${STAGE_TARGETS:N*_links} ${STAGE_TARGETS:M*_links} .if ${.MAKE.JOBS:U0} > 0 && ${STAGE_TARGETS:U:M*_links} != "" # the above isn't sufficient .for t in ${STAGE_TARGETS:N*links:O:u} .ORDER: $t stage_links .endfor .endif # generally we want staging to wait until everything else is done STAGING_WAIT ?= .WAIT .if ${.MAKE.LEVEL} > 0 all: ${STAGING_WAIT} staging .endif .if exists(${.PARSEDIR}/stage-install.sh) && !defined(STAGE_INSTALL) # this will run install(1) and then followup with .dirdep files. STAGE_INSTALL := sh ${.PARSEDIR:tA}/stage-install.sh INSTALL="${INSTALL}" OBJDIR=${.OBJDIR:tA} .endif # if ${INSTALL} gets run during 'all' assume it is for staging? .if ${.TARGETS:Nall} == "" && defined(STAGE_INSTALL) INSTALL := ${STAGE_INSTALL} .if target(beforeinstall) beforeinstall: .dirdep .endif .endif .NOPATH: ${STAGE_FILES} .if !empty(STAGE_TARGETS) # for backwards compat make sure they exist ${STAGE_TARGETS}: .NOPATH: ${CLEANFILES} MK_STALE_STAGED?= no .if ${MK_STALE_STAGED} == "yes" all: stale_staged # get a list of paths that we have just staged # get a list of paths that we have previously staged to those same dirs # anything in the 2nd list but not the first is stale - remove it. stale_staged: staging .NOMETA @egrep '^[WL] .*${STAGE_OBJTOP}' /dev/null ${.MAKE.META.FILES:M*stage_*} | \ sed "/\.dirdep/d;s,.* '*\(${STAGE_OBJTOP}/[^ '][^ ']*\).*,\1," | \ sort > ${.TARGET}.staged1 @grep -l '${_dirdep}' /dev/null ${_STAGED_DIRS:M${STAGE_OBJTOP}*:O:u:@d@$d/*.dirdep@} | \ sed 's,\.dirdep,,' | sort > ${.TARGET}.staged2 @comm -13 ${.TARGET}.staged1 ${.TARGET}.staged2 > ${.TARGET}.stale @test ! -s ${.TARGET}.stale || { \ echo "Removing stale staged files..."; \ sed 's,.*,& &.dirdep,' ${.TARGET}.stale | xargs rm -f; } .endif .endif .endif .endif Index: stable/12/contrib/bmake/mk/meta.sys.mk =================================================================== --- stable/12/contrib/bmake/mk/meta.sys.mk (revision 361673) +++ stable/12/contrib/bmake/mk/meta.sys.mk (revision 361674) @@ -1,169 +1,173 @@ -# $Id: meta.sys.mk,v 1.32 2017/06/11 03:24:04 sjg Exp $ +# $Id: meta.sys.mk,v 1.36 2020/05/16 23:21:48 sjg Exp $ # -# @(#) Copyright (c) 2010, Simon J. Gerraty +# @(#) Copyright (c) 2010-2020, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # # include this if you want to enable meta mode # for maximum benefit, requires filemon(4) driver. .if ${MAKE_VERSION:U0} > 20100901 .if !target(.ERROR) .-include -# absoulte path to what we are reading. +# absolute path to what we are reading. _PARSEDIR = ${.PARSEDIR:tA} .if !defined(SYS_MK_DIR) SYS_MK_DIR := ${_PARSEDIR} .endif META_MODE += meta verbose .MAKE.MODE ?= ${META_MODE} .if ${.MAKE.LEVEL} == 0 _make_mode := ${.MAKE.MODE} ${META_MODE} .if ${_make_mode:M*read*} != "" || ${_make_mode:M*nofilemon*} != "" # tell everyone we are not updating Makefile.depend* UPDATE_DEPENDFILE = NO .export UPDATE_DEPENDFILE .endif .if ${UPDATE_DEPENDFILE:Uyes:tl} == "no" && !exists(/dev/filemon) # we should not get upset META_MODE += nofilemon .export META_MODE .endif .endif .if !defined(NO_SILENT) .if ${MAKE_VERSION} > 20110818 # only be silent when we have a .meta file META_MODE += silent=yes .else .SILENT: .endif .endif # we use the pseudo machine "host" for the build host. # this should be taken care of before we get here .if ${OBJTOP:Ua} == ${HOST_OBJTOP:Ub} MACHINE = host .endif -.if ${.MAKE.LEVEL} == 0 +.if !defined(MACHINE0) # it can be handy to know which MACHINE kicked off the build # for example, if using Makefild.depend for multiple machines, # allowing only MACHINE0 to update can keep things simple. MACHINE0 := ${MACHINE} .export MACHINE0 +.endif +.if !defined(META2DEPS) .if defined(PYTHON) && exists(${PYTHON}) # we prefer the python version of this - it is much faster META2DEPS ?= ${.PARSEDIR}/meta2deps.py .else META2DEPS ?= ${.PARSEDIR}/meta2deps.sh .endif META2DEPS := ${META2DEPS} .export META2DEPS .endif MAKE_PRINT_VAR_ON_ERROR += \ .ERROR_TARGET \ .ERROR_META_FILE \ .MAKE.LEVEL \ MAKEFILE \ .MAKE.MODE .if !defined(SB) && defined(SRCTOP) SB = ${SRCTOP:H} .endif ERROR_LOGDIR ?= ${SB}/error meta_error_log = ${ERROR_LOGDIR}/meta-${.MAKE.PID}.log # we are not interested in make telling us a failure happened elsewhere .ERROR: _metaError _metaError: .NOMETA .NOTMAIN -@[ "${.ERROR_META_FILE}" ] && { \ grep -q 'failure has been detected in another branch' ${.ERROR_META_FILE} && exit 0; \ mkdir -p ${meta_error_log:H}; \ cp ${.ERROR_META_FILE} ${meta_error_log}; \ echo "ERROR: log ${meta_error_log}" >&2; }; : .endif # Are we, after all, in meta mode? .if ${.MAKE.MODE:Uno:Mmeta*} != "" MKDEP_MK = meta.autodep.mk .if ${.MAKE.MAKEFILES:M*sys.dependfile.mk} == "" # this does all the smarts of setting .MAKE.DEPENDFILE .-include # check if we got anything sane .if ${.MAKE.DEPENDFILE} == ".depend" .undef .MAKE.DEPENDFILE .endif .MAKE.DEPENDFILE ?= Makefile.depend .endif # we can afford to use cookies to prevent some targets # re-running needlessly META_COOKIE_TOUCH?= touch ${COOKIE.${.TARGET}:U${.OBJDIR}/${.TARGET:T}} META_NOPHONY= META_NOECHO= : # some targets involve old pre-built targets # ignore mtime of shell # and mtime of makefiles does not matter in meta mode .MAKE.META.IGNORE_PATHS += \ - ${MAKEFILE} \ - ${SHELL} \ - ${SYS_MK_DIR} + ${MAKEFILE} \ + ${MAKE_SHELL} \ + ${SHELL} \ + ${SYS_MK_DIR} \ + .if ${UPDATE_DEPENDFILE:Uyes:tl} != "no" .if ${.MAKEFLAGS:Uno:M-k} != "" # make this more obvious .warning Setting UPDATE_DEPENDFILE=NO due to -k UPDATE_DEPENDFILE= NO .export UPDATE_DEPENDFILE .elif !exists(/dev/filemon) .error ${.newline}ERROR: The filemon module (/dev/filemon) is not loaded. .endif .endif .if ${.MAKE.LEVEL} == 0 # make sure dirdeps target exists and do it first all: dirdeps .WAIT dirdeps: .NOPATH: dirdeps .if defined(ALL_MACHINES) # the first .MAIN: is what counts # by default dirdeps is all we want at level0 .MAIN: dirdeps # tell dirdeps.mk what we want BUILD_AT_LEVEL0 = no .endif .if ${.TARGETS:Nall} == "" # it works best if we do everything via sub-makes BUILD_AT_LEVEL0 ?= no .endif .endif .else META_COOKIE_TOUCH= # some targets need to be .PHONY in non-meta mode META_NOPHONY= .PHONY META_NOECHO= echo .endif .endif Index: stable/12/contrib/bmake/mk/meta2deps.py =================================================================== --- stable/12/contrib/bmake/mk/meta2deps.py (revision 361673) +++ stable/12/contrib/bmake/mk/meta2deps.py (revision 361674) @@ -1,754 +1,755 @@ #!/usr/bin/env python from __future__ import print_function """ This script parses each "meta" file and extracts the information needed to deduce build and src dependencies. It works much the same as the original shell script, but is *much* more efficient. The parsing work is handled by the class MetaFile. We only pay attention to a subset of the information in the "meta" files. Specifically: 'CWD' to initialize our notion. 'C' to track chdir(2) on a per process basis 'R' files read are what we really care about. directories read, provide a clue to resolving subsequent relative paths. That is if we cannot find them relative to 'cwd', we check relative to the last dir read. 'W' files opened for write or read-write, for filemon V3 and earlier. 'E' files executed. 'L' files linked 'V' the filemon version, this record is used as a clue that we have reached the interesting bit. """ """ RCSid: - $Id: meta2deps.py,v 1.27 2017/05/24 00:04:04 sjg Exp $ + $Id: meta2deps.py,v 1.28 2020/05/16 23:21:48 sjg Exp $ - Copyright (c) 2011-2013, Juniper Networks, Inc. + Copyright (c) 2011-2019, Simon J. Gerraty + Copyright (c) 2011-2017, Juniper Networks, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import os, re, sys def getv(dict, key, d=None): """Lookup key in dict and return value or the supplied default.""" if key in dict: return dict[key] return d def resolve(path, cwd, last_dir=None, debug=0, debug_out=sys.stderr): """ Return an absolute path, resolving via cwd or last_dir if needed. """ if path.endswith('/.'): path = path[0:-2] if len(path) > 0 and path[0] == '/': return path if path == '.': return cwd if path.startswith('./'): return cwd + path[1:] if last_dir == cwd: last_dir = None for d in [last_dir, cwd]: if not d: continue if path == '..': dw = d.split('/') p = '/'.join(dw[:-1]) if not p: p = '/' return p p = '/'.join([d,path]) if debug > 2: print("looking for:", p, end=' ', file=debug_out) if not os.path.exists(p): if debug > 2: print("nope", file=debug_out) p = None continue if debug > 2: print("found:", p, file=debug_out) return p return None def cleanpath(path): """cleanup path without using realpath(3)""" if path.startswith('/'): r = '/' else: r = '' p = [] w = path.split('/') for d in w: if not d or d == '.': continue if d == '..': try: p.pop() continue except: break p.append(d) return r + '/'.join(p) def abspath(path, cwd, last_dir=None, debug=0, debug_out=sys.stderr): """ Return an absolute path, resolving via cwd or last_dir if needed. this gets called a lot, so we try to avoid calling realpath. """ rpath = resolve(path, cwd, last_dir, debug, debug_out) if rpath: path = rpath if (path.find('/') < 0 or path.find('./') > 0 or path.endswith('/..')): path = cleanpath(path) return path def sort_unique(list, cmp=None, key=None, reverse=False): list.sort(cmp, key, reverse) nl = [] le = None for e in list: if e == le: continue le = e nl.append(e) return nl def add_trims(x): return ['/' + x + '/', '/' + x, x + '/', x] class MetaFile: """class to parse meta files generated by bmake.""" conf = None dirdep_re = None host_target = None srctops = [] objroots = [] excludes = [] seen = {} obj_deps = [] src_deps = [] file_deps = [] def __init__(self, name, conf={}): """if name is set we will parse it now. conf can have the follwing keys: SRCTOPS list of tops of the src tree(s). CURDIR the src directory 'bmake' was run from. RELDIR the relative path from SRCTOP to CURDIR MACHINE the machine we built for. set to 'none' if we are not cross-building. More specifically if machine cannot be deduced from objdirs. TARGET_SPEC Sometimes MACHINE isn't enough. HOST_TARGET when we build for the pseudo machine 'host' the object tree uses HOST_TARGET rather than MACHINE. OBJROOTS a list of the common prefix for all obj dirs it might end in '/' or '-'. DPDEPS names an optional file to which per file dependencies will be appended. For example if 'some/path/foo.h' is read from SRCTOP then 'DPDEPS_some/path/foo.h +=' "RELDIR" is output. This can allow 'bmake' to learn all the dirs within the tree that depend on 'foo.h' EXCLUDES A list of paths to ignore. ccache(1) can otherwise be trouble. debug desired debug level debug_out open file to send debug output to (sys.stderr) """ self.name = name self.debug = getv(conf, 'debug', 0) self.debug_out = getv(conf, 'debug_out', sys.stderr) self.machine = getv(conf, 'MACHINE', '') self.machine_arch = getv(conf, 'MACHINE_ARCH', '') self.target_spec = getv(conf, 'TARGET_SPEC', '') self.curdir = getv(conf, 'CURDIR') self.reldir = getv(conf, 'RELDIR') self.dpdeps = getv(conf, 'DPDEPS') self.line = 0 if not self.conf: # some of the steps below we want to do only once self.conf = conf self.host_target = getv(conf, 'HOST_TARGET') for srctop in getv(conf, 'SRCTOPS', []): if srctop[-1] != '/': srctop += '/' if not srctop in self.srctops: self.srctops.append(srctop) _srctop = os.path.realpath(srctop) if _srctop[-1] != '/': _srctop += '/' if not _srctop in self.srctops: self.srctops.append(_srctop) trim_list = add_trims(self.machine) if self.machine == 'host': trim_list += add_trims(self.host_target) if self.target_spec: trim_list += add_trims(self.target_spec) for objroot in getv(conf, 'OBJROOTS', []): for e in trim_list: if objroot.endswith(e): # this is not what we want - fix it objroot = objroot[0:-len(e)] if objroot[-1] != '/': objroot += '/' if not objroot in self.objroots: self.objroots.append(objroot) _objroot = os.path.realpath(objroot) if objroot[-1] == '/': _objroot += '/' if not _objroot in self.objroots: self.objroots.append(_objroot) # we want the longest match self.srctops.sort(reverse=True) self.objroots.sort(reverse=True) self.excludes = getv(conf, 'EXCLUDES', []) if self.debug: print("host_target=", self.host_target, file=self.debug_out) print("srctops=", self.srctops, file=self.debug_out) print("objroots=", self.objroots, file=self.debug_out) print("excludes=", self.excludes, file=self.debug_out) self.dirdep_re = re.compile(r'([^/]+)/(.+)') if self.dpdeps and not self.reldir: if self.debug: print("need reldir:", end=' ', file=self.debug_out) if self.curdir: srctop = self.find_top(self.curdir, self.srctops) if srctop: self.reldir = self.curdir.replace(srctop,'') if self.debug: print(self.reldir, file=self.debug_out) if not self.reldir: self.dpdeps = None # we cannot do it? self.cwd = os.getcwd() # make sure this is initialized self.last_dir = self.cwd if name: self.try_parse() def reset(self): """reset state if we are being passed meta files from multiple directories.""" self.seen = {} self.obj_deps = [] self.src_deps = [] self.file_deps = [] def dirdeps(self, sep='\n'): """return DIRDEPS""" return sep.strip() + sep.join(self.obj_deps) def src_dirdeps(self, sep='\n'): """return SRC_DIRDEPS""" return sep.strip() + sep.join(self.src_deps) def file_depends(self, out=None): """Append DPDEPS_${file} += ${RELDIR} for each file we saw, to the output file.""" if not self.reldir: return None for f in sort_unique(self.file_deps): print('DPDEPS_%s += %s' % (f, self.reldir), file=out) # these entries provide for reverse DIRDEPS lookup for f in self.obj_deps: print('DEPDIRS_%s += %s' % (f, self.reldir), file=out) def seenit(self, dir): """rememer that we have seen dir.""" self.seen[dir] = 1 def add(self, list, data, clue=''): """add data to list if it isn't already there.""" if data not in list: list.append(data) if self.debug: print("%s: %sAdd: %s" % (self.name, clue, data), file=self.debug_out) def find_top(self, path, list): """the logical tree may be split across multiple trees""" for top in list: if path.startswith(top): if self.debug > 2: print("found in", top, file=self.debug_out) return top return None def find_obj(self, objroot, dir, path, input): """return path within objroot, taking care of .dirdep files""" ddep = None for ddepf in [path + '.dirdep', dir + '/.dirdep']: if not ddep and os.path.exists(ddepf): ddep = open(ddepf, 'r').readline().strip('# \n') if self.debug > 1: print("found %s: %s\n" % (ddepf, ddep), file=self.debug_out) if ddep.endswith(self.machine): ddep = ddep[0:-(1+len(self.machine))] elif self.target_spec and ddep.endswith(self.target_spec): ddep = ddep[0:-(1+len(self.target_spec))] if not ddep: # no .dirdeps, so remember that we've seen the raw input self.seenit(input) self.seenit(dir) if self.machine == 'none': if dir.startswith(objroot): return dir.replace(objroot,'') return None m = self.dirdep_re.match(dir.replace(objroot,'')) if m: ddep = m.group(2) dmachine = m.group(1) if dmachine != self.machine: if not (self.machine == 'host' and dmachine == self.host_target): if self.debug > 2: print("adding .%s to %s" % (dmachine, ddep), file=self.debug_out) ddep += '.' + dmachine return ddep def try_parse(self, name=None, file=None): """give file and line number causing exception""" try: self.parse(name, file) except: # give a useful clue print('{}:{}: '.format(self.name, self.line), end=' ', file=sys.stderr) raise def parse(self, name=None, file=None): """A meta file looks like: # Meta data file "path" CMD "command-line" CWD "cwd" TARGET "target" -- command output -- -- filemon acquired metadata -- # buildmon version 3 V 3 C "pid" "cwd" E "pid" "path" F "pid" "child" R "pid" "path" W "pid" "path" X "pid" "status" D "pid" "path" L "pid" "src" "target" M "pid" "old" "new" S "pid" "path" # Bye bye We go to some effort to avoid processing a dependency more than once. Of the above record types only C,E,F,L,R,V and W are of interest. """ version = 0 # unknown if name: self.name = name; if file: f = file cwd = self.last_dir = self.cwd else: f = open(self.name, 'r') skip = True pid_cwd = {} pid_last_dir = {} last_pid = 0 self.line = 0 if self.curdir: self.seenit(self.curdir) # we ignore this interesting = 'CEFLRV' for line in f: self.line += 1 # ignore anything we don't care about if not line[0] in interesting: continue if self.debug > 2: print("input:", line, end=' ', file=self.debug_out) w = line.split() if skip: if w[0] == 'V': skip = False version = int(w[1]) """ if version < 4: # we cannot ignore 'W' records # as they may be 'rw' interesting += 'W' """ elif w[0] == 'CWD': self.cwd = cwd = self.last_dir = w[1] self.seenit(cwd) # ignore this if self.debug: print("%s: CWD=%s" % (self.name, cwd), file=self.debug_out) continue pid = int(w[1]) if pid != last_pid: if last_pid: pid_last_dir[last_pid] = self.last_dir cwd = getv(pid_cwd, pid, self.cwd) self.last_dir = getv(pid_last_dir, pid, self.cwd) last_pid = pid # process operations if w[0] == 'F': npid = int(w[2]) pid_cwd[npid] = cwd pid_last_dir[npid] = cwd last_pid = npid continue elif w[0] == 'C': cwd = abspath(w[2], cwd, None, self.debug, self.debug_out) if cwd.endswith('/.'): cwd = cwd[0:-2] self.last_dir = pid_last_dir[pid] = cwd pid_cwd[pid] = cwd if self.debug > 1: print("cwd=", cwd, file=self.debug_out) continue if w[2] in self.seen: if self.debug > 2: print("seen:", w[2], file=self.debug_out) continue # file operations if w[0] in 'ML': # these are special, tread src as read and # target as write self.parse_path(w[1].strip("'"), cwd, 'R', w) self.parse_path(w[2].strip("'"), cwd, 'W', w) continue elif w[0] in 'ERWS': path = w[2] self.parse_path(path, cwd, w[0], w) if not file: f.close() def is_src(self, base, dir, rdir): """is base in srctop""" for dir in [dir,rdir]: if not dir: continue path = '/'.join([dir,base]) srctop = self.find_top(path, self.srctops) if srctop: if self.dpdeps: self.add(self.file_deps, path.replace(srctop,''), 'file') self.add(self.src_deps, dir.replace(srctop,''), 'src') self.seenit(dir) return True return False def parse_path(self, path, cwd, op=None, w=[]): """look at a path for the op specified""" if not op: op = w[0] # we are never interested in .dirdep files as dependencies if path.endswith('.dirdep'): return for p in self.excludes: if p and path.startswith(p): if self.debug > 2: print("exclude:", p, path, file=self.debug_out) return # we don't want to resolve the last component if it is # a symlink path = resolve(path, cwd, self.last_dir, self.debug, self.debug_out) if not path: return dir,base = os.path.split(path) if dir in self.seen: if self.debug > 2: print("seen:", dir, file=self.debug_out) return # we can have a path in an objdir which is a link # to the src dir, we may need to add dependencies for each rdir = dir dir = abspath(dir, cwd, self.last_dir, self.debug, self.debug_out) rdir = os.path.realpath(dir) if rdir == dir: rdir = None # now put path back together path = '/'.join([dir,base]) if self.debug > 1: print("raw=%s rdir=%s dir=%s path=%s" % (w[2], rdir, dir, path), file=self.debug_out) if op in 'RWS': if path in [self.last_dir, cwd, self.cwd, self.curdir]: if self.debug > 1: print("skipping:", path, file=self.debug_out) return if os.path.isdir(path): if op in 'RW': self.last_dir = path; if self.debug > 1: print("ldir=", self.last_dir, file=self.debug_out) return if op in 'ERW': # finally, we get down to it if dir == self.cwd or dir == self.curdir: return if self.is_src(base, dir, rdir): self.seenit(w[2]) if not rdir: return objroot = None for dir in [dir,rdir]: if not dir: continue objroot = self.find_top(dir, self.objroots) if objroot: break if objroot: ddep = self.find_obj(objroot, dir, path, w[2]) if ddep: self.add(self.obj_deps, ddep, 'obj') if self.dpdeps and objroot.endswith('/stage/'): sp = '/'.join(path.replace(objroot,'').split('/')[1:]) self.add(self.file_deps, sp, 'file') else: # don't waste time looking again self.seenit(w[2]) self.seenit(dir) def main(argv, klass=MetaFile, xopts='', xoptf=None): """Simple driver for class MetaFile. Usage: script [options] [key=value ...] "meta" ... Options and key=value pairs contribute to the dictionary passed to MetaFile. -S "SRCTOP" add "SRCTOP" to the "SRCTOPS" list. -C "CURDIR" -O "OBJROOT" add "OBJROOT" to the "OBJROOTS" list. -m "MACHINE" -a "MACHINE_ARCH" -H "HOST_TARGET" -D "DPDEPS" -d bumps debug level """ import getopt # import Psyco if we can # it can speed things up quite a bit have_psyco = 0 try: import psyco psyco.full() have_psyco = 1 except: pass conf = { 'SRCTOPS': [], 'OBJROOTS': [], 'EXCLUDES': [], } try: machine = os.environ['MACHINE'] if machine: conf['MACHINE'] = machine machine_arch = os.environ['MACHINE_ARCH'] if machine_arch: conf['MACHINE_ARCH'] = machine_arch srctop = os.environ['SB_SRC'] if srctop: conf['SRCTOPS'].append(srctop) objroot = os.environ['SB_OBJROOT'] if objroot: conf['OBJROOTS'].append(objroot) except: pass debug = 0 output = True opts, args = getopt.getopt(argv[1:], 'a:dS:C:O:R:m:D:H:qT:X:' + xopts) for o, a in opts: if o == '-a': conf['MACHINE_ARCH'] = a elif o == '-d': debug += 1 elif o == '-q': output = False elif o == '-H': conf['HOST_TARGET'] = a elif o == '-S': if a not in conf['SRCTOPS']: conf['SRCTOPS'].append(a) elif o == '-C': conf['CURDIR'] = a elif o == '-O': if a not in conf['OBJROOTS']: conf['OBJROOTS'].append(a) elif o == '-R': conf['RELDIR'] = a elif o == '-D': conf['DPDEPS'] = a elif o == '-m': conf['MACHINE'] = a elif o == '-T': conf['TARGET_SPEC'] = a elif o == '-X': if a not in conf['EXCLUDES']: conf['EXCLUDES'].append(a) elif xoptf: xoptf(o, a, conf) conf['debug'] = debug # get any var=val assignments eaten = [] for a in args: if a.find('=') > 0: k,v = a.split('=') if k in ['SRCTOP','OBJROOT','SRCTOPS','OBJROOTS']: if k == 'SRCTOP': k = 'SRCTOPS' elif k == 'OBJROOT': k = 'OBJROOTS' if v not in conf[k]: conf[k].append(v) else: conf[k] = v eaten.append(a) continue break for a in eaten: args.remove(a) debug_out = getv(conf, 'debug_out', sys.stderr) if debug: print("config:", file=debug_out) print("psyco=", have_psyco, file=debug_out) for k,v in list(conf.items()): print("%s=%s" % (k,v), file=debug_out) m = None for a in args: if a.endswith('.meta'): if not os.path.exists(a): continue m = klass(a, conf) elif a.startswith('@'): # there can actually multiple files per line for line in open(a[1:]): for f in line.strip().split(): if not os.path.exists(f): continue m = klass(f, conf) if output and m: print(m.dirdeps()) print(m.src_dirdeps('\nsrc:')) dpdeps = getv(conf, 'DPDEPS') if dpdeps: m.file_depends(open(dpdeps, 'wb')) return m if __name__ == '__main__': try: main(sys.argv) except: # yes, this goes to stdout print("ERROR: ", sys.exc_info()[1]) raise Index: stable/12/contrib/bmake/mk/mk-files.txt =================================================================== --- stable/12/contrib/bmake/mk/mk-files.txt (revision 361673) +++ stable/12/contrib/bmake/mk/mk-files.txt (revision 361674) @@ -1,481 +1,503 @@ mk-files ******** The term ``mk-files`` refers to a collection of ``*.mk`` files. You need bmake_ or a *recent* NetBSD_ make. If in doubt use bmake_. Introduction ============ Many years ago, when building large software projects, I used GNU make (or my own patched version of it), and had developed a set of macros to simplify developing complex build trees. Since the early 90's my main development machines, run BSD (NetBSD_ to be precise), and the BSD source tree is good example of a large software project. It quickly became clear that ``/usr/share/mk/*.mk`` were a great model, but were quite tightly linked to building the BSD tree. Much as I liked using NetBSD, my customers were more likely to be using SunOS, HP-UX etc, so I started on bmake_ and a portable collection of mk-files (mk.tar.gz_). NetBSD provided much of the original structure. Since then I've added a lot of features to NetBSD's make and hence to bmake which is kept closely in sync. The mk-files however have -diverged quite a bit, though ideas are still picked up from NetBSD. +diverged quite a bit, though ideas are still picked up from NetBSD +and FreeBSD. Basics ------ The BSD build model is very simple. A directory produces one component, which is generally either a library or a program. Library makefiles include ``lib.mk`` and programs include ``prog.mk`` and they *do the right thing*. A simple library makefile might look like:: LIB = sig SRCS = \ sigaction.c \ sigcompat.c \ sighdl.c .include a simple program makefile:: PROG = cat SRCS = cat.c .include in such cases even the ``SRCS`` line is unnecessary as ``prog.mk`` will default it to ``${PROG}.c``. It is the sensible use of defaults and the plethora of macro modifiers provided by bmake_ that allow simple makefiles such as the above *just work* on many different systems. mk-files ======== This section provides a brief description of some of the ``*.mk`` files. sys.mk ------ When bmake starts, it looks for ``sys.mk`` and reads it before doing anything else. Thus, this is the place to setup the environment for everyone else. In this distribution, sys.mk avoids doing anything platform dependent. It is quite short, and includes a number of other files (which may or may not exists) sys.env.mk If it exists, is expected to do things like conditioning the environment. Since it will only be included by the initial instance of bmake, it should ``.export`` anything that sub-makes might need. examples/sys.clean-env.mk An example of how to clean the environment. See the file for all the details:: .if ${MAKE_VERSION} >= 20100606 && ${.MAKE.LEVEL} == 0 # we save any env var that starts with these MAKE_SAVE_ENV_PREFIX += SB MK MAKE MACHINE NEED_ CCACHE DISTCC USE_ SSH MAKE_SAVE_ENV_VARS += \ PATH HOME USER LOGNAME \ SRCTOP OBJTOP OBJROOT \ ${_env_vars} _env_vars != env | egrep '^(${MAKE_SAVE_ENV_PREFIX:ts|})' | sed 's,=.*,,'; echo _export_list = .for v in ${MAKE_SAVE_ENV_VARS:O:u} .if !empty($v) _export_list += $v $v := ${$v} .endif .endfor # now clobber the environment .unexport-env # list of vars that we handle specially below _tricky_env_vars = MAKEOBJDIR # export our selection - sans tricky ones .export ${_export_list:${_tricky_env_vars:${M_ListToSkip}}} # this next bit may need tweaking .if defined(MAKEOBJDIR) srctop := ${SRCTOP:U${SB_SRC:U${SB}/src}} objroot := ${OBJROOT:U${SB_OBJROOT:U${SB}/${SB_OBJPREFIX}}} # we'll take care of MACHINE below objtop := ${OBJTOP:U${objroot}${MACHINE}} .if !empty(objtop) # we would normally want something like (/bin/sh): # MAKEOBJDIR="\${.CURDIR:S,${SRCTOP},${OBJROOT}\${MACHINE},}" # the $$ below is how we achieve the same result here. # since everything saved from the environment above # has run through := we need to compensate for ${MACHINE} MAKEOBJDIR = $${.CURDIR:S,${srctop},${objtop:S,${MACHINE},\${MACHINE},},} # export these as-is, and do not track... .export-env ${_tricky_env_vars} # now evaluate for ourselves .for v in ${_tricky_env_vars} $v := ${$v} .endfor .endif .endif .endif host-target.mk Is used to set macros like ``HOST_TARGET``, ``HOST_OS`` and ``host_os`` which are used to find the next step. sys/\*.mk Platform specific additions, such as ``Darwin.mk`` or ``SunOS.mk`` set things like ``HOST_LIBEXT = .dylib`` for Darwin or ``SHLIB_FULLVERSION = ${SHLIB_MAJOR}`` for SunOS 5. If there is no OS specific file, ``sys/Generic.mk`` is used. local.sys.mk Any ``local.*.mk`` file is not part of the distribution. This provides a hook for sites to do extra setup without having to edit the distributed files. The above arrangement makes it easy for the mk files to be part of a src tree on an NFS volume and to allow building on multiple platforms. lib.mk ------ This file is used to build a number of different libraries from the same SRCS. lib${LIB}.a An archive lib of ``.o`` files, this is the default lib${LIB}_p.a A profiled lib of ``.po`` files. Still an archive lib, but all the objects are built with profiling in mind - hence the different extension. It is skipped if ``MKPROFILE`` is "no". lib${LIB}_pic.a An archive of ``.so`` objects compiled for relocation. On NetBSD this is the input to ``lib${LIB}.${LD_so}``, it is skipped if ``MKPICLIB`` is "no". lib${LIB}.${LD_so} A shared library. The value of ``LD_so`` is very platform specific. For example:: # SunOS 5 and most other ELF systems libsslfd.so.1 # Darwin libsslfd.1.dylib This library will only be built if ``SHLIB_MAJOR`` has a value, and ``MKPIC`` is not set to "no". There is a lot of platform specific tweaking in ``lib.mk``, largely the result of the original distributions trying to avoid interfering with the system's ``sys.mk``. libnames.mk ----------- This is included by both ``prog.mk`` and ``lib.mk`` and tries to include ``*.libnames.mk`` of which: local.libnames.mk does not exist unless you create it. It is a handy way for you to customize without touching the distributed files. For example, on a test machine I needed to build openssl but not install it, so put the following in ``local.libnames.mk``:: .if ${host_os} == "sunos" LIBCRYPTO = ${OBJTOP}/openssl/lib/crypto/libcrypto${DLIBEXT} LIBSSL = ${OBJTOP}/openssl/lib/ssl/libssl${DLIBEXT} INCLUDES_libcrypto = -I${OBJ_libcrypto} .endif The makefile created an openssl dir in ``${OBJ_libcrypto}`` to gather all the headers. dpadd.mk_ did the rest. sjg.libnames.mk not part of the mk-files distribution. host.libnames.mk contains logic to find any libs named in ``HOST_LIBS`` in ``HOST_LIBDIRS``. Each file above gets an opportunity to define things like:: LIBSSLFD ?= ${OBJTOP}/ssl/lib/sslfd/libsslfd${DLIBEXT} INCLUDES_libsslfd = -I${SRC_libsslfd}/h -I${OBJ_libslfd} these are used by dpadd.mk_ and will be explained below. dpadd.mk -------- This file looks like line noise, and is best considered read-only. However it provides some very useful functionality, which simplifies the build. Makefiles can use the LIB* macros defined via libnames.mk_ or anywhere else in various ways:: # indicate that we need to include headers from LIBCRYPTO # this would result in ${INCLUDES_libcrypto} being added to CFLAGS. SRC_LIBS += ${LIBCRYPTO} # indicate that libsslfd must be built already. # it also has the same effect as SRC_LIBS DPADD += ${LIBSSLFD} # indicate that not only must libsslfd be built, # but that we need to link with it. # this is almost exactly equivalent to # DPADD += ${LIBSSLFD} # LDADD += -L${LIBSSLFD:H} -lsslfd # and mostly serves to ensure that DPADD and LDADD are in sync. DPLIBS += ${LIBSSLFD} Any library (referenced by its full path) in any of the above, is added to ``DPMAGIC_LIBS`` with the following results, for each lib *foo*. SRC_libfoo Is set to indicate where the src for libfoo is. By default it is derived from ``LIBFOO`` by replacing ``${OBJTOP}`` with ``${SRCTOP}``. OBJ_libfoo Not very exciting, is just the dir where libfoo lives. INCLUDES_libfoo What to add to ``CFLAGS`` to find the public headers. The default varies. If ``${SRC_libfoo}/h`` exists, it is assumed to be the home of all public headers and thus the default is ``-I${SRC_libfoo}/h`` Otherwise we make no assumptions and the default is ``-I${SRC_libfoo} -I${OBJ_libfoo}`` LDADD_libfoo This only applies to libs reference via ``DPLIBS``. The default is ``-lfoo``, ``LDADD_*`` provides a hook to instantiate other linker flags at the appropriate point without losing the benfits of ``DPLIBS``. prog.mk ------- Compiles the specified SRCS and links them and the nominated libraries into a program. Prog makefiles usually need to list the libraries that need to be linked. We prefer use of ``DPLIBS`` but the more traditional ``DPADD`` and ``LDADD`` work just as well. That is:: DPLIBS += ${LIBCRYPTO} is equivalent to:: DPADD += ${LIBCRYPTO} LDADD += -lcrypto obj.mk ------ One of the cool aspects of BSD make, is its support for separating object files from the src tree. This is also the source of much confusion to some. Traditionally one had to do a separate ``make obj`` pass through the tree. If ``MKOBJDIRS`` is "auto", we include auto.obj.mk_. auto.obj.mk ----------- This leverages the ``.OBJDIR`` target introduced some years ago to NetBSD make, to automatically create the desired object dir. subdir.mk --------- This is the traditional means of walking the tree. A makefile sets ``SUBDIR`` to the list of sub-dirs to visit. If ``SUBDIR_MUST_EXIST`` is set, missing directories cause an error, otherwise a warning is issued. If you don't even want the warning, set ``MISSING_DIR=continue``. Traditionally, ``subdir.mk`` prints clue as it visits each subdir:: ===> ssl ===> ssl/lib ===> ssl/lib/sslfd you can suppress that - or enhance it by setting ``ECHO_DIR``:: # suppress subdir noise ECHO_DIR=: # print time stamps ECHO_DIR=echo @ `date "+%s [%Y-%m-%d %T] "` links.mk -------- Provides rules for processing lists of ``LINKS`` and ``SYMLINKS``. Each is expected to be a list of ``link`` and ``target`` pairs (``link`` -> ``target``). The logic is generally in a ``_*_SCRIPT`` which is referenced in a ``_*_USE`` (``.USE``) target. The ``_BUILD_*`` forms are identical, but do not use ``${DESTDIR}`` and so are useful for creating symlinks during the build phase. For example:: SYMLINKS += ${.CURDIR}/${MACHINE_ARCH}/include machine header_links: _BUILD_SYMLINKS_USE md.o: header_links would create a symlink called ``machine`` in ``${.OBJDIR}`` pointing to ``${.CURDIR}/${MACHINE_ARCH}/include`` before compiling ``md.o`` autoconf.mk ----------- Deals with running (or generating) GNU autoconf ``configure`` scripts. dep.mk ------ Deals with collecting dependencies. Another useful feature of BSD make is the separation of this sort of information into a ``.depend`` file. ``MKDEP`` needs to point to a suitable tool (like mkdeps.sh_) If ``USE_AUTODEP_MK`` is "yes" includes autodep.mk_ autodep.mk ---------- Leverages the ``-MD`` feature of recent GCC to collect dependency information as a side effect of compilation. With this GCC puts dependency info into a ``.d`` file. Unfortunately GCC bases the name of the ``.d`` file on the name of the input rather than the output file, which causes problems when the same source is compiled different ways. The latest GCC supports ``-MF`` to name the ``.d`` file and ``-MT`` to control the name to put as the dependent. Recent bmake allows dependencies for the ``.END`` target (run at the end if everything was successful), and ``autodep.mk`` uses this to post process the ``.d`` files into ``.depend``. auto.dep.mk ----------- A much simpler implementation than autodep.mk_ it uses ``-MF ${.TARGET:T}.d`` to avoid possible conflicts during parallel builds. This precludes the use of suffix rules to drive ``make depend``, so dep.mk_ handles that if specifically requested. +options.mk +---------- + +Inspired by FreeBSD's ``bsd.own.mk`` more flexible. +FreeBSD now have similar functionality in ``bsd.mkopt.mk``. + +It allows users to express their intent with respect to options +``MK_*`` by setting ``WITH_*`` or ``WITHOUT_*``. + +Note: ``WITHOUT_*`` wins if both are set, and makefiles can set +``NO_*`` to say they cannot handle that option, or even ``MK_*`` if +they really need to. + + own.mk ------ Normally included by ``init.mk`` (included by ``lib.mk`` and ``prog.mk`` etc), sets macros for default ownership etc. It includes ``${MAKECONF}`` if it is defined and exists. +ldorder.mk +---------- + +Leverages ``bmake`` to compute optimal link order for libraries. +This works nicely and makes refactoring a breeze - so long as you +have not (or few) cicular dependencies between libraries. + man.mk ------ Deals with man pages. warnings.mk ----------- This provides a means of fine grained control over warnings on a per ``${MACHINE}`` or even file basis. A makefile sets ``WARNINGS_SET`` to name a list of warnings and individual ``W_*`` macros can be used to tweak them. For example:: WARNINGS_SET = HIGH W_unused_sparc = -Wno-unused would add all the warnings in ``${HIGH_WARNINGS}`` to CFLAGS, but on sparc, ``-Wno-unused`` would replace ``-Wunused``. You should never need to edit ``warnings.mk``, it will include ``warnings-sets.mk`` if it exists and you use that to make any local customizations. rst2htm.mk ---------- Logic to simplify generating HTML (and PDF) documents from ReStructuredText. cython.mk --------- Logic to build Python C interface modules using Cython_ .. _Cython: http://www.cython.org/ Meta mode ========= The 20110505 and later versions of ``mk-files`` include a number of makefiles contributed by Juniper Networks, Inc. These allow the latest version of bmake_ to run in `meta mode`_ see `dirdeps.mk`_ .. _`dirdeps.mk`: /help/sjg/dirdeps.htm .. _`meta mode`: bmake-meta-mode.htm Install ======= You can use the content of mk.tar.gz_ without installing at all. The script ``install-mk`` takes care of copying ``*.mk`` into a destination directory, and unless told not to, create ``bsd.*.mk`` links for ``lib.mk`` etc. If you just want to create the ``bsd.*.mk`` links in the directory where you unpacked the tar file, you can:: ./mk/install-mk ./mk ------ .. _bmake: bmake.htm .. _NetBSD: http://www.netbsd.org/ .. _mkdeps.sh: http://www.crufty.net/ftp/pub/sjg/mkdeps.sh .. _mk.tar.gz: http://www.crufty.net/ftp/pub/sjg/mk.tar.gz :Author: sjg@crufty.net -:Revision: $Id: mk-files.txt,v 1.16 2014/09/05 04:41:16 sjg Exp $ +:Revision: $Id: mk-files.txt,v 1.18 2018/12/08 07:27:15 sjg Exp $ :Copyright: Crufty.NET Index: stable/12/contrib/bmake/mk/options.mk =================================================================== --- stable/12/contrib/bmake/mk/options.mk (revision 361673) +++ stable/12/contrib/bmake/mk/options.mk (revision 361674) @@ -1,79 +1,80 @@ -# $Id: options.mk,v 1.10 2014/02/11 18:34:48 sjg Exp $ +# $Id: options.mk,v 1.11 2020/05/02 21:23:52 sjg Exp $ # # @(#) Copyright (c) 2012, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # # Inspired by FreeBSD bsd.own.mk, but intentionally simpler and more flexible. # Options are normally listed in either OPTIONS_DEFAULT_{YES,NO} # We convert these to ${OPTION}/{yes,no} in OPTIONS_DEFAULT_VALUES. # We add the OPTIONS_DEFAULT_NO first so they take precedence. # This allows override of an OPTIONS_DEFAULT_YES by adding it to # OPTIONS_DEFAULT_NO or adding ${OPTION}/no to OPTIONS_DEFAULT_VALUES. # An OPTIONS_DEFAULT_NO option can only be overridden by putting # ${OPTION}/yes in OPTIONS_DEFAULT_VALUES. # A makefile may set NO_* (or NO*) to indicate it cannot do something. # User sets WITH_* and WITHOUT_* to indicate what they want. # We set ${OPTION_PREFIX:UMK_}* which is then all we need care about. OPTIONS_DEFAULT_VALUES += \ ${OPTIONS_DEFAULT_NO:O:u:S,$,/no,} \ ${OPTIONS_DEFAULT_YES:O:u:S,$,/yes,} OPTION_PREFIX ?= MK_ # NO_* takes precedence # If both WITH_* and WITHOUT_* are defined, WITHOUT_ wins unless # DOMINANT_* is set to "yes" # Otherwise WITH_* and WITHOUT_* override the default. .for o in ${OPTIONS_DEFAULT_VALUES:M*/*} .if defined(NO_${o:H}) || defined(NO${o:H}) # we cannot do it ${OPTION_PREFIX}${o:H} ?= no .elif defined(WITH_${o:H}) && defined(WITHOUT_${o:H}) # normally WITHOUT_ wins DOMINANT_${o:H} ?= no ${OPTION_PREFIX}${o:H} ?= ${DOMINANT_${o:H}} .elif ${o:T:tl} == "no" .if defined(WITH_${o:H}) ${OPTION_PREFIX}${o:H} ?= yes .else ${OPTION_PREFIX}${o:H} ?= no .endif .else .if defined(WITHOUT_${o:H}) ${OPTION_PREFIX}${o:H} ?= no .else ${OPTION_PREFIX}${o:H} ?= yes .endif .endif .endfor # OPTIONS_DEFAULT_DEPENDENT += FOO_UTILS/FOO # If neither WITH[OUT]_FOO_UTILS is set, (see rules above) # use the value of ${OPTION_PREFIX}FOO .for o in ${OPTIONS_DEFAULT_DEPENDENT:M*/*:O:u} .if defined(NO_${o:H}) || defined(NO${o:H}) # we cannot do it ${OPTION_PREFIX}${o:H} ?= no .elif defined(WITH_${o:H}) && defined(WITHOUT_${o:H}) # normally WITHOUT_ wins DOMINANT_${o:H} ?= no ${OPTION_PREFIX}${o:H} ?= ${DOMINANT_${o:H}} .elif defined(WITH_${o:H}) ${OPTION_PREFIX}${o:H} ?= yes .elif defined(WITHOUT_${o:H}) ${OPTION_PREFIX}${o:H} ?= no .else ${OPTION_PREFIX}${o:H} ?= ${${OPTION_PREFIX}${o:T}} .endif .endfor +.undef OPTIONS_DEFAULT_VALUES OPTIONS_DEFAULT_NO OPTIONS_DEFAULT_YES Index: stable/12/contrib/bmake/mk/sys/AIX.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/AIX.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/AIX.mk (revision 361674) @@ -1,186 +1,184 @@ # $NetBSD: sys.mk,v 1.19.2.1 1994/07/26 19:58:31 cgd Exp $ # @(#)sys.mk 5.11 (Berkeley) 3/13/91 OS= AIX unix= We run ${OS}. ROOT_GROUP= system # This needs a lot of work yet... NOPIC=no # no shared libs? .SUFFIXES: .out .a .ln .o .c ${CXX_SUFFIXES} .F .f .r .y .l .s .S .cl .p .h .sh .m4 .LIBS: .a AR= ar ARFLAGS= rl RANLIB= ranlib AS= as AFLAGS= COMPILE.s= ${AS} ${AFLAGS} LINK.s= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S= ${CC} ${AFLAGS} ${CPPFLAGS} -c LINK.S= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} .if exists(/usr/local/bin/gcc) CC= gcc DBG= -O -g STATIC?= -static .else CC= cc DBG= -g STATIC= .endif CFLAGS= ${DBG} COMPILE.c= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX= g++ CXXFLAGS= ${CFLAGS} COMPILE.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP= cpp .if defined(DESTDIR) CPPFLAGS+= -nostdinc -idirafter ${DESTDIR}/usr/include .endif MK_DEP= mkdeps.sh -N FC= f77 FFLAGS= -O RFLAGS= COMPILE.f= ${FC} ${FFLAGS} -c LINK.f= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} LEX= lex LFLAGS= LEX.l= ${LEX} ${LFLAGS} LD= ld LDFLAGS= LINT= lint LINTFLAGS= -chapbx PC= pc PFLAGS= COMPILE.p= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} -SHELL= sh - YACC= yacc YFLAGS= -d YACC.y= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} -o ${.TARGET} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/Darwin.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/Darwin.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/Darwin.mk (revision 361674) @@ -1,209 +1,222 @@ # $NetBSD: Darwin.sys.mk,v 1.3 2003/02/16 09:44:41 grant Exp $ # @(#)sys.mk 8.2 (Berkeley) 3/21/94 OS= Darwin unix?= We run ${OS}. -.SUFFIXES: .out .a .ln .o .s .S .c ${CXX_SUFFIXES} .F .f .r .y .l .cl .p .h +.SUFFIXES: .out .a .ln .o .s .S .c .m ${CXX_SUFFIXES} .F .f .r .y .l .cl .p .h .SUFFIXES: .sh .m4 .dylib .LIBS: .a .dylib SHLIBEXT = .dylib HOST_LIBEXT = .dylib DSHLIBEXT = .dylib AR?= ar ARFLAGS?= rl RANLIB = AS?= as AFLAGS?= COMPILE.s?= ${AS} ${AFLAGS} LINK.s?= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S?= ${CC} ${AFLAGS} ${CPPFLAGS} -c LINK.S?= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} -.if exists(/usr/bin/gcc) -CC?= gcc -pipe +PIPE?= -pipe + +.if exists(/usr/bin/clang) +CC?= cc ${PIPE} +CXX?= c++ +.elif exists(/usr/bin/gcc) +CC?= gcc ${PIPE} .else -CC?= cc -pipe +CC?= cc ${PIPE} .endif DBG?= -O2 CFLAGS?= ${DBG} COMPILE.c?= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c?= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} .if exists(/usr/bin/g++) CXX?= g++ .else CXX?= c++ .endif CXXFLAGS?= ${CFLAGS} COMPILE.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} OBJC?= ${CC} OBJCFLAGS?= ${CFLAGS} COMPILE.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} -c LINK.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP?= cpp NOLINT= 1 CPPFLAGS?= -MK_DEP?= mkdeps.sh -N +MK_DEP?= mkdep FC?= f77 FFLAGS?= -O RFLAGS?= COMPILE.f?= ${FC} ${FFLAGS} -c LINK.f?= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F?= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F?= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r?= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r?= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} INSTALL?= install LEX?= lex LFLAGS?= LEX.l?= ${LEX} ${LFLAGS} LD?= ld LDFLAGS?= SHLIB_TEENY = 0 SHLIB_MINOR = 0 MKPICLIB = no LIBEXT = .dylib LINT?= lint LINTFLAGS?= -chapbx LORDER?= lorder NM?= nm PC?= pc PFLAGS?= COMPILE.p?= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p?= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} -SHELL?= sh - SIZE?= size TSORT?= tsort -q YACC?= bison -y YFLAGS?= -d YACC.y?= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} + ${AR} ${ARFLAGS} $@ $*.o + rm -f $*.o + +# Objective-C +.m: + ${LINK.m} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} +.m.o: + ${COMPILE.m} ${.IMPSRC} +.m.a: + ${COMPILE.m} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} -o ${.TARGET} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/Generic.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/Generic.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/Generic.mk (revision 361674) @@ -1,206 +1,204 @@ -# $Id: Generic.mk,v 1.13 2017/05/05 18:02:16 sjg Exp $ +# $Id: Generic.mk,v 1.14 2020/04/17 21:08:17 sjg Exp $ # # some reasonable defaults .SUFFIXES: .out .a .ln .o .s .S .c ${CXX_SUFFIXES} .F .f .r .y .l .cl .p .h .SUFFIXES: .sh .m4 .LIBS: .a tools = \ ar \ lorder \ ranlib \ tsort .for t in ${tools} ${t:tu} := ${t:${M_whence}} .endfor # need to make sure this is set MACHINE_ARCH.${MACHINE} ?= ${MACHINE} .if empty(MACHINE_ARCH) MACHINE_ARCH = ${MACHINE_ARCH.${MACHINE}} .endif .if !empty(TSORT) TSORT += -q .endif ARFLAGS?= rl AS?= as AFLAGS?= .if ${MACHINE_ARCH} == "sparc64" AFLAGS+= -Wa,-Av9a .endif COMPILE.s?= ${CC} ${AFLAGS} -c LINK.s?= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S?= ${CC} ${AFLAGS} ${CPPFLAGS} -c -traditional-cpp LINK.S?= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} CC?= cc DBG?= -O2 CFLAGS?= ${DBG} COMPILE.c?= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c?= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX?= c++ CXXFLAGS?= ${CFLAGS} COMPILE.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} OBJC?= ${CC} OBJCFLAGS?= ${CFLAGS} COMPILE.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} -c LINK.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP?= cpp CPPFLAGS?= FC?= f77 FFLAGS?= -O RFLAGS?= COMPILE.f?= ${FC} ${FFLAGS} -c LINK.f?= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F?= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F?= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r?= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r?= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} INSTALL?= install LEX?= lex LFLAGS?= LEX.l?= ${LEX} ${LFLAGS} LD?= ld LDFLAGS?= LINT?= lint LINTFLAGS?= -chapbxzF NM?= nm PC?= pc PFLAGS?= COMPILE.p?= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p?= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} - -SHELL?= sh SIZE?= size YACC?= yacc YFLAGS?= YACC.y?= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .c.ln: ${LINT} ${LINTFLAGS} ${CPPFLAGS:M-[IDU]*} -i ${.IMPSRC} # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/HP-UX.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/HP-UX.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/HP-UX.mk (revision 361674) @@ -1,226 +1,226 @@ -# $Id: HP-UX.mk,v 1.11 2017/05/05 18:02:16 sjg Exp $ +# $Id: HP-UX.mk,v 1.12 2020/04/17 21:08:17 sjg Exp $ # $NetBSD: sys.mk,v 1.19.2.1 1994/07/26 19:58:31 cgd Exp $ # @(#)sys.mk 5.11 (Berkeley) 3/13/91 OS= HP-UX ROOT_GROUP= root unix?= We run ${OS}. # HP-UX's cc does not provide any clues as to wether this is 9.x or 10.x # nor does sys/param.h, so we'll use the existence of /hp-ux .if exists("/hp-ux") OSMAJOR?=9 .endif OSMAJOR?=10 __HPUX_VERSION?=${OSMAJOR} .SUFFIXES: .out .a .ln .o .c ${CXX_SUFFIXES} .F .f .r .y .l .s .S .cl .p .h .sh .m4 LIBMODE= 755 LIBCRT0= /lib/crt0.o .LIBS: .a # +b is needed to stop the binaries from insisting on having # the build tree available :-) # +s tells the dynamic loader to use SHLIB_PATH if set LD_bpath?=-Wl,+b/lib:/usr/lib:/usr/local/lib LD_spath?=-Wl,+s LDADD+= ${LD_bpath} ${LD_spath} .if exists(/usr/lib/end.o) LDADD+= /usr/lib/end.o .endif AR= ar ARFLAGS= rl RANLIB= : AFLAGS= COMPILE.s= ${AS} ${AFLAGS} LINK.s= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S= ${CC} ${AFLAGS} ${CPPFLAGS} -c LINK.S= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} .if exists(/usr/local/bin/gcc) PIPE?= -pipe CC?= gcc ${PIPE} AS= gas DBG?= -O -g STATIC?= -static .if defined(DESTDIR) CPPFLAGS+= -nostdinc -idirafter ${DESTDIR}/usr/include .endif .else # HP's bundled compiler knows not -g or -O AS= as CC= cc .if exists(/opt/ansic/bin/cc) CCMODE?=-Ae +ESlit PICFLAG?= +z LD_x= DBG?=-g -O .endif DBG?= STATIC?= -Wl,-a,archive .endif .if (${__HPUX_VERSION} == "10") CCSOURCE_FLAGS?= -D_HPUX_SOURCE .else CCSOURCE_FLAGS?= -D_HPUX_SOURCE -D_INCLUDE_POSIX_SOURCE -D_INCLUDE_XOPEN_SOURCE -D_INCLUDE_XOPEN_SOURCE_EXTENDED .endif CFLAGS= ${DBG} CFLAGS+= ${CCMODE} -D__hpux__ -D__HPUX_VERSION=${__HPUX_VERSION} ${CCSOURCE_FLAGS} COMPILE.c= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX= g++ CXXFLAGS= ${CFLAGS} COMPILE.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP= cpp MK_DEP= mkdeps.sh -N FC= f77 FFLAGS= -O RFLAGS= COMPILE.f= ${FC} ${FFLAGS} -c LINK.f= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} LEX= lex LFLAGS= LEX.l= ${LEX} ${LFLAGS} LD= ld LDFLAGS= LINT= lint LINTFLAGS= -chapbx PC= pc PFLAGS= COMPILE.p= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} # HP's sh sucks ENV= -SHELL= /bin/ksh +MAKE_SHELL= /bin/ksh .if exists(/usr/local/bin/bison) YACC= bison -y .else YACC= yacc .endif YFLAGS= -d YACC.y= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} -o ${.TARGET} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/IRIX.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/IRIX.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/IRIX.mk (revision 361674) @@ -1,197 +1,195 @@ # $NetBSD: IRIX.sys.mk,v 1.2 2002/12/24 23:03:27 jschauma Exp $ # @(#)sys.mk 8.2 (Berkeley) 3/21/94 .if ${.PARSEFILE} == "sys.mk" .ifndef ROOT_GROUP OS!= uname -s ROOT_GROUP!= sed -n /:0:/s/:.*//p /etc/group .MAKEOVERRIDES+= OS ROOT_GROUP .endif unix?= We run ${OS}. .endif .SUFFIXES: .out .a .ln .o .s .S .c ${CXX_SUFFIXES} .F .f .r .y .l .cl .p .h .SUFFIXES: .sh .m4 .LIBS: .a AR?= ar ARFLAGS?= rl RANLIB?= ranlib AS?= as AFLAGS?= COMPILE.s?= ${CC} ${AFLAGS} -c LINK.s?= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S?= ${CC} ${AFLAGS} ${CPPFLAGS} -c -traditional-cpp LINK.S?= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} CC?= cc NOGCCERROR?= # defined DBG?= -O2 CFLAGS?= ${DBG} COMPILE.c?= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c?= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX?= CC CXXFLAGS?= ${CFLAGS} COMPILE.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} OBJC?= ${CC} OBJCFLAGS?= ${CFLAGS} COMPILE.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} -c LINK.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP?= CC CPPFLAGS?= FC?= f77 FFLAGS?= -O RFLAGS?= COMPILE.f?= ${FC} ${FFLAGS} -c LINK.f?= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F?= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F?= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r?= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r?= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} INSTALL?= ${PREFIX}/bin/install-sh LEX?= lex LFLAGS?= LEX.l?= ${LEX} ${LFLAGS} LD?= ld LDFLAGS?= LINT?= lint LINTFLAGS?= -chapbxzF LORDER?= lorder NM?= nm PC?= pc PFLAGS?= COMPILE.p?= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p?= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} -SHELL?= sh - SIZE?= size TSORT?= tsort -q YACC?= yacc YFLAGS?= YACC.y?= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .c.ln: ${LINT} ${LINTFLAGS} ${CPPFLAGS:M-[IDU]*} -i ${.IMPSRC} # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/Linux.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/Linux.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/Linux.mk (revision 361674) @@ -1,189 +1,187 @@ -# $Id: Linux.mk,v 1.9 2017/05/05 18:02:16 sjg Exp $ +# $Id: Linux.mk,v 1.10 2020/04/17 21:08:17 sjg Exp $ # $NetBSD: sys.mk,v 1.19.2.1 1994/07/26 19:58:31 cgd Exp $ # @(#)sys.mk 5.11 (Berkeley) 3/13/91 OS?= Linux unix?= We run ${OS}. ROOT_GROUP= root # would be better to work out where it is... LIBCRT0= /dev/null NEED_SOLINKS=yes .SUFFIXES: .out .a .ln .o .c ${CXX_SUFFIXES} .F .f .r .y .l .s .S .cl .p .h .sh .m4 .LIBS: .a AR= ar ARFLAGS= rl RANLIB= ranlib AS= as AFLAGS= COMPILE.s= ${AS} ${AFLAGS} LINK.s= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S= ${CC} ${AFLAGS} ${CPPFLAGS} -c LINK.S= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} .if exists(/usr/local/bin/gcc) CC= gcc -pipe DBG= -O -g STATIC?= -static .else CC= cc -pipe DBG= -g STATIC= -Bstatic .endif CFLAGS= ${DBG} COMPILE.c= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX= g++ CXXFLAGS= ${CFLAGS} COMPILE.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP= cpp .if defined(DESTDIR) CPPFLAGS+= -nostdinc -idirafter ${DESTDIR}/usr/include .endif MK_DEP= mkdeps.sh -N FC= f77 FFLAGS= -O RFLAGS= COMPILE.f= ${FC} ${FFLAGS} -c LINK.f= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} LEX= lex LFLAGS= LEX.l= ${LEX} ${LFLAGS} LD= ld LDFLAGS= LINT= lint LINTFLAGS= -chapbx PC= pc PFLAGS= COMPILE.p= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} - -SHELL= sh YACC= yacc YFLAGS= -d YACC.y= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} -o ${.TARGET} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/NetBSD.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/NetBSD.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/NetBSD.mk (revision 361674) @@ -1,232 +1,230 @@ # $NetBSD: sys.mk,v 1.66.2.1 2002/06/05 03:31:01 lukem Exp $ # @(#)sys.mk 8.2 (Berkeley) 3/21/94 OS= NetBSD unix?= We run ${OS}. .if !defined(MAKE_VERSION) # we are running native make # which defined MAKE_VERSION between 20010609 and 20090324 # so we can make a rough guess .if defined(.MAKE.LEVEL) MAKE_VERSION = 20090908 .elif defined(.MAKE.MAKEFILES) # introduced 20071008 MAKE_VERSION = 20090324 .else # this just before when MAKE_VERSION was introduced MAKE_VERSION = 20010606 .endif .endif .SUFFIXES: .out .a .ln .o .s .S .c ${CXX_SUFFIXES} .F .f .r .y .l .cl .p .h .SUFFIXES: .sh .m4 .LIBS: .a AR?= ar ARFLAGS?= rl RANLIB?= ranlib AS?= as AFLAGS?= COMPILE.s?= ${CC} ${AFLAGS} -c LINK.s?= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S?= ${CC} ${AFLAGS} ${CPPFLAGS} -c -traditional-cpp LINK.S?= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} CC?= cc # need to make sure this is set MACHINE_ARCH.${MACHINE} ?= ${MACHINE} .if empty(MACHINE_ARCH) MACHINE_ARCH = ${MACHINE_ARCH.${MACHINE}} .endif # # CPU model, derived from MACHINE_ARCH # MACHINE_CPU= ${MACHINE_ARCH:C/mipse[bl]/mips/:C/mips64e[bl]/mips/:C/sh3e[bl]/sh3/:S/m68000/m68k/:S/armeb/arm/} .if ${MACHINE_CPU} == "alpha" || \ ${MACHINE_CPU} == "arm" || \ ${MACHINE_CPU} == "i386" || \ ${MACHINE_CPU} == "m68k" || \ ${MACHINE_CPU} == "mips" || \ ${MACHINE_CPU} == "powerpc" || \ ${MACHINE_CPU} == "sparc" || \ ${MACHINE_CPU} == "vax" DBG?= -O2 .elif ${MACHINE_ARCH} == "x86_64" DBG?= .elif ${MACHINE_ARCH} == "sparc64" DBG?= -O -ffixed-g4 #Hack for embedany memory model compatibility .else DBG?= -O .endif CFLAGS?= ${DBG} COMPILE.c?= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c?= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX?= c++ CXXFLAGS?= ${CFLAGS} COMPILE.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} OBJC?= ${CC} OBJCFLAGS?= ${CFLAGS} COMPILE.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} -c LINK.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP?= cpp CPPFLAGS?= FC?= f77 FFLAGS?= -O RFLAGS?= COMPILE.f?= ${FC} ${FFLAGS} -c LINK.f?= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F?= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F?= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r?= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r?= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} INSTALL?= install LEX?= lex LFLAGS?= LEX.l?= ${LEX} ${LFLAGS} LD?= ld LDFLAGS?= LINT?= lint LINTFLAGS?= -chapbxzF LORDER?= lorder NM?= nm PC?= pc PFLAGS?= COMPILE.p?= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p?= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} -SHELL?= sh - SIZE?= size TSORT?= tsort -q YACC?= yacc YFLAGS?= YACC.y?= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .c.ln: ${LINT} ${LINTFLAGS} ${CPPFLAGS:M-[IDU]*} -i ${.IMPSRC} # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/OSF1.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/OSF1.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/OSF1.mk (revision 361674) @@ -1,200 +1,198 @@ -# $Id: OSF1.mk,v 1.8 2017/05/05 18:02:16 sjg Exp $ +# $Id: OSF1.mk,v 1.9 2020/04/17 21:08:17 sjg Exp $ # $NetBSD: sys.mk,v 1.19.2.1 1994/07/26 19:58:31 cgd Exp $ # @(#)sys.mk 5.11 (Berkeley) 3/13/91 OS?= OSF1 unix?= We run ${OS}. ROOT_GROUP= system # can't fine one anywhere, so just stop the dependency LIBCRT0= /dev/null PATH=/usr/sbin:/usr/bin:/usr/ucb:/opt/gnu/bin:/usr/ccs/bin .SUFFIXES: .out .a .ln .o .c ${CXX_SUFFIXES} .F .f .r .y .l .s .S .cl .p .h .sh .m4 .LIBS: .a # no -X LD_X= LD_x= -x LD_r= -r AR= ar ARFLAGS= rl RANLIB= ranlib AS= as AS_STDIN= - AFLAGS= COMPILE.s= ${AS} ${AFLAGS} LINK.s= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S= ${CC} ${AFLAGS} ${CPPFLAGS} -c LINK.S= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} .if exists(/opt/gnu/bin/gcc) || exists(/usr/local/bin/gcc) CC?= gcc .else CC?= cc -std .endif .if (${CC:T} == "gcc") DBG= -O -g STATIC= -static DBG= -g STATIC= -non_shared .endif CFLAGS= ${DBG} COMPILE.c= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX= g++ CXXFLAGS= ${CFLAGS} COMPILE.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP= /usr/ccs/lib/cpp .if defined(DESTDIR) CPPFLAGS+= -nostdinc -idirafter ${DESTDIR}/usr/include .endif MK_DEP= mkdeps.sh -N FC= f77 FFLAGS= -O RFLAGS= COMPILE.f= ${FC} ${FFLAGS} -c LINK.f= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} LEX= lex LFLAGS= LEX.l= ${LEX} ${LFLAGS} LD= ld LDFLAGS= LINT= lint LINTFLAGS= -chapbx PC= pc PFLAGS= COMPILE.p= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} - -SHELL= sh .if exists(/usr/local/bin/bison) || exists(/opt/gnu/bin/bison) YACC= bison -y .else YACC= yacc .endif YFLAGS= -d YACC.y= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/OpenBSD.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/OpenBSD.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/OpenBSD.mk (revision 361674) @@ -1,207 +1,205 @@ # $NetBSD: OpenBSD.sys.mk,v 1.1 2002/11/17 09:18:00 cjep Exp $ # @(#)sys.mk 8.2 (Berkeley) 3/21/94 OS= OpenBSD unix?= We run ${OS}. .SUFFIXES: .out .a .ln .o .s .S .c ${CXX_SUFFIXES} .F .f .r .y .l .cl .p .h .SUFFIXES: .sh .m4 .LIBS: .a # need to make sure this is set MACHINE_ARCH.${MACHINE} ?= ${MACHINE} .if empty(MACHINE_ARCH) MACHINE_ARCH = ${MACHINE_ARCH.${MACHINE}} .endif AR?= ar ARFLAGS?= rl RANLIB?= ranlib AS?= as AFLAGS?= .if ${MACHINE_ARCH} == "sparc64" AFLAGS+= -Wa,-Av9a .endif COMPILE.s?= ${CC} ${AFLAGS} -c LINK.s?= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S?= ${CC} ${AFLAGS} ${CPPFLAGS} -c -traditional-cpp LINK.S?= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} CC?= cc .if ${MACHINE_ARCH} == "alpha" || \ ${MACHINE_ARCH} == "i386" || \ ${MACHINE_ARCH} == "m68k" || \ ${MACHINE_ARCH} == "sparc" || \ ${MACHINE_ARCH} == "vax" DBG?= -O2 .else DBG?= -O .endif CFLAGS?= ${DBG} COMPILE.c?= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c?= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX?= c++ CXXFLAGS?= ${CFLAGS} COMPILE.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} OBJC?= ${CC} OBJCFLAGS?= ${CFLAGS} COMPILE.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} -c LINK.m?= ${OBJC} ${OBJCFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP?= cpp CPPFLAGS?= FC?= f77 FFLAGS?= -O RFLAGS?= COMPILE.f?= ${FC} ${FFLAGS} -c LINK.f?= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F?= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F?= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r?= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r?= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} INSTALL?= install LEX?= lex LFLAGS?= LEX.l?= ${LEX} ${LFLAGS} LD?= ld LDFLAGS?= LINT?= lint LINTFLAGS?= -chapbxzF LORDER?= lorder NM?= nm PC?= pc PFLAGS?= COMPILE.p?= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p?= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} -SHELL?= sh - SIZE?= size TSORT?= tsort -q YACC?= yacc YFLAGS?= YACC.y?= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .c.ln: ${LINT} ${LINTFLAGS} ${CPPFLAGS:M-[IDU]*} -i ${.IMPSRC} # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/SunOS.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/SunOS.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/SunOS.mk (revision 361674) @@ -1,221 +1,219 @@ -# $Id: SunOS.mk,v 1.8 2017/05/05 18:02:17 sjg Exp $ +# $Id: SunOS.mk,v 1.9 2020/04/17 21:08:17 sjg Exp $ .if ${.PARSEFILE} == "sys.mk" .include OS?= SunOS.${HOST_OSMAJOR} unix?= We run ${OS}. .endif .if ${HOST_OSMAJOR} > 4 ROOT_GROUP= root SHLIB_FULLVERSION = ${SHLIB_MAJOR} # suppress the dependency LIBCRT0= /dev/null .ifndef CC # the PATH below may find an ancient gcc CC := ${gcc:L:${M_whence}} .export CC .endif # the stuff in /usr/xpg4/bin is usually more sane. PATH=/usr/xpg4/bin:/usr/sbin:/usr/bin:/usr/ucb:/usr/sfw/bin:/opt/gnu/bin:/usr/ccs/bin:/usr/local/bin .export PATH DSHLIBEXT = .so HOST_LIBDIRS = /usr/lib /lib /usr/sfw/lib # no -X LD_X= LD_x= RANLIB= : CPP= /usr/ccs/lib/cpp .else ROOT_GROUP= wheel RANLIB= ranlib CPP= cpp .endif # the rest is common .SUFFIXES: .out .a .ln .o .c ${CXX_SUFFIXES} .F .f .r .y .l .s .S .cl .p .h .sh .m4 .LIBS: .a AR= ar ARFLAGS= rl AS= as AS_STDIN= - AFLAGS= COMPILE.s= ${AS} ${AFLAGS} LINK.s= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S= ${CC} ${AFLAGS} ${CPPFLAGS} -c LINK.S= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} .if exists(/opt/gnu/bin/gcc) || exists(/usr/local/bin/gcc) CC ?= gcc -pipe DBG= -O -g STATIC= -static .else CC ?= cc DBG= -g STATIC= -Bstatic .endif CFLAGS= ${DBG} COMPILE.c= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} CXX= g++ CXXFLAGS= ${CFLAGS} COMPILE.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} .if defined(DESTDIR) CPPFLAGS+= -nostdinc -idirafter ${DESTDIR}/usr/include .endif MK_DEP= mkdeps.sh -N FC= f77 FFLAGS= -O RFLAGS= COMPILE.f= ${FC} ${FFLAGS} -c LINK.f= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} LEX= lex LFLAGS= LEX.l= ${LEX} ${LFLAGS} LD= ld LDFLAGS= LINT= lint LINTFLAGS= -chapbx PC= pc PFLAGS= COMPILE.p= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} - -SHELL= sh .if exists(/usr/local/bin/bison) || exists(/opt/gnu/bin/bison) YACC= bison -y .else YACC= yacc .endif YFLAGS= -d YACC.y= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys/UnixWare.mk =================================================================== --- stable/12/contrib/bmake/mk/sys/UnixWare.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys/UnixWare.mk (revision 361674) @@ -1,243 +1,241 @@ -# $Id: UnixWare.mk,v 1.3 2017/05/05 18:02:17 sjg Exp $ +# $Id: UnixWare.mk,v 1.4 2020/04/17 21:08:17 sjg Exp $ # based on "Id: SunOS.5.sys.mk,v 1.6 2003/09/30 16:42:23 sjg Exp " # $NetBSD: sys.mk,v 1.19.2.1 1994/07/26 19:58:31 cgd Exp $ # @(#)sys.mk 5.11 (Berkeley) 3/13/91 OS?= UnixWare unix?= We run ${OS}. ROOT_GROUP= root # can't fine one anywhere, so just stop the dependency LIBCRT0= /dev/null PATH=/usr/sbin:/usr/bin:/usr/ccs/bin:/usr/ccs/lib:/usr/ucb:/usr/local/bin .SUFFIXES: .out .a .ln .o .c ${CXX_SUFFIXES} .F .f .r .y .l .s .S .cl .p .h .sh .m4 .LIBS: .a # no -X LD_X= LD_x= AR?= ar ARFLAGS?= rl RANLIB?= : AS?= as AS_STDIN?= - AFLAGS?= COMPILE.s?= ${AS} ${AFLAGS} LINK.s?= ${CC} ${AFLAGS} ${LDFLAGS} COMPILE.S?= ${CC} ${AFLAGS} ${CPPFLAGS} -c LINK.S?= ${CC} ${AFLAGS} ${CPPFLAGS} ${LDFLAGS} # at least gcc 2.95 on UnixWare has no internal macro to identify the system .if exists(/usr/local/bin/gcc) CC?= gcc -pipe -DUNIXWARE DBG?= -O -g STATIC?= -static .else CC?= cc DBG?= -g STATIC?= -Bstatic # XXX: don't know about UDK compilers .endif CFLAGS?= ${DBG} COMPILE.c?= ${CC} ${CFLAGS} ${CPPFLAGS} -c LINK.c?= ${CC} ${CFLAGS} ${CPPFLAGS} ${LDFLAGS} .if exists(/usr/local/bin/g++) CXX?= g++ -DUNIXWARE .else CXX?= c++ # XXX: don't know about UDK compilers .endif CXXFLAGS?= ${CFLAGS} COMPILE.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} -c LINK.cc?= ${CXX} ${CXXFLAGS} ${CPPFLAGS} ${LDFLAGS} CPP?= /usr/ccs/lib/cpp .if defined(DESTDIR) CPPFLAGS+= -nostdinc -idirafter ${DESTDIR}/usr/include .endif MK_DEP?= mkdeps.sh -N .if exists(/usr/local/bin/g77) FC?= g77 .else FC?= f77 # XXX: don't know about UDK compilers .endif FFLAGS?= -O RFLAGS?= COMPILE.f?= ${FC} ${FFLAGS} -c LINK.f?= ${FC} ${FFLAGS} ${LDFLAGS} COMPILE.F?= ${FC} ${FFLAGS} ${CPPFLAGS} -c LINK.F?= ${FC} ${FFLAGS} ${CPPFLAGS} ${LDFLAGS} COMPILE.r?= ${FC} ${FFLAGS} ${RFLAGS} -c LINK.r?= ${FC} ${FFLAGS} ${RFLAGS} ${LDFLAGS} INSTALL?= /usr/ucb/install # BSD install LEX?= lex LFLAGS?= LEX.l?= ${LEX} ${LFLAGS} LD?= ld LDFLAGS?= LIBC?= ${DESTDIR}/usr/ccs/lib/libc.a LIBCOMPAT?= LIBCRYPT?= ${DESTDIR}/usr/lib/libcrypt.a LIBCURSES?= ${DESTDIR}/usr/ccs/lib/libcurses.a LIBDBM?= LIBDES?= LIBEDIT?= LIBGCC?= LIBKDB?= LIBKRB?= LIBKVM?= LIBL?= ${DESTDIR}/usr/ccs/lib/libl.a LIBM?= ${DESTDIR}/usr/ccs/lib/libm.a LIBMP?= LIBPC?= LIBPCAP?= LIBPLOT?= LIBRESOLV?= LIBRPCSVC?= ${DESTDIR}/usr/lib/librpcsvc.a LIBSKEY?= ${DESTDIR}/usr/lib/libskey.a LIBTERMCAP?= ${DESTDIR}/usr/ccs/lib/libtermcap.a LIBUTIL?= LIBWRAP?= LIBY?= ${DESTDIR}/usr/ccs/lib/liby.a LIBZ?= LINT?= lint LINTFLAGS?= -pF LORDER?= lorder NM?= nm PC?= pc # XXX: UDK probably does not have pc PFLAGS?= COMPILE.p?= ${PC} ${PFLAGS} ${CPPFLAGS} -c LINK.p?= ${PC} ${PFLAGS} ${CPPFLAGS} ${LDFLAGS} - -SHELL?= sh SIZE?= size TSORT?= tsort .if exists(/usr/local/bin/bison) YACC?= bison -y .else YACC?= yacc .endif YFLAGS?= -d YACC.y?= ${YACC} ${YFLAGS} # C .c: ${LINK.c} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .c.o: ${COMPILE.c} ${.IMPSRC} .c.a: ${COMPILE.c} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # C++ ${CXX_SUFFIXES}: ${LINK.cc} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} ${CXX_SUFFIXES:%=%.o}: ${COMPILE.cc} ${.IMPSRC} ${CXX_SUFFIXES:%=%.a}: ${COMPILE.cc} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Fortran/Ratfor .f: ${LINK.f} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .f.o: ${COMPILE.f} ${.IMPSRC} .f.a: ${COMPILE.f} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .F: ${LINK.F} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .F.o: ${COMPILE.F} ${.IMPSRC} .F.a: ${COMPILE.F} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .r: ${LINK.r} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .r.o: ${COMPILE.r} ${.IMPSRC} .r.a: ${COMPILE.r} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Pascal .p: ${LINK.p} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .p.o: ${COMPILE.p} ${.IMPSRC} .p.a: ${COMPILE.p} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Assembly .s: ${LINK.s} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .s.o: ${COMPILE.s} ${.IMPSRC} .s.a: ${COMPILE.s} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o .S: ${LINK.S} -o ${.TARGET} ${.IMPSRC} ${LDLIBS} .S.o: ${COMPILE.S} ${.IMPSRC} .S.a: ${COMPILE.S} ${.IMPSRC} ${AR} ${ARFLAGS} $@ $*.o rm -f $*.o # Lex .l: ${LEX.l} ${.IMPSRC} ${LINK.c} -o ${.TARGET} lex.yy.c ${LDLIBS} -ll rm -f lex.yy.c .l.c: ${LEX.l} ${.IMPSRC} mv lex.yy.c ${.TARGET} .l.o: ${LEX.l} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} lex.yy.c rm -f lex.yy.c # Yacc .y: ${YACC.y} ${.IMPSRC} ${LINK.c} -o ${.TARGET} y.tab.c ${LDLIBS} rm -f y.tab.c .y.c: ${YACC.y} ${.IMPSRC} mv y.tab.c ${.TARGET} .y.o: ${YACC.y} ${.IMPSRC} ${COMPILE.c} -o ${.TARGET} y.tab.c rm -f y.tab.c # Shell .sh: rm -f ${.TARGET} cp ${.IMPSRC} ${.TARGET} Index: stable/12/contrib/bmake/mk/sys.mk =================================================================== --- stable/12/contrib/bmake/mk/sys.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys.mk (revision 361674) @@ -1,151 +1,155 @@ -# $Id: sys.mk,v 1.46 2017/11/15 22:59:23 sjg Exp $ +# $Id: sys.mk,v 1.47 2020/04/17 21:08:17 sjg Exp $ # # @(#) Copyright (c) 2003-2009, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # # Avoid putting anything platform specific in here. # _DEBUG_MAKE_FLAGS etc. .include .if !empty(_DEBUG_MAKE_FLAGS) .if ${_DEBUG_MAKE_SYS_DIRS:Uno:@x@${.CURDIR:M$x}@} != "" .MAKEFLAGS: ${_DEBUG_MAKE_FLAGS} .endif .endif # useful modifiers .include # we expect a recent bmake .if !defined(_TARGETS) # some things we do only once _TARGETS := ${.TARGETS} .-include .endif # we need HOST_TARGET etc below. .include # early customizations .-include # Popular suffixes for C++ CXX_SUFFIXES += .cc .cpp .cxx .C CXX_SUFFIXES := ${CXX_SUFFIXES:O:u} # find the OS specifics .if defined(SYS_OS_MK) .include <${SYS_OS_MK}> .else _sys_mk = .for x in ${HOST_OSTYPE} ${HOST_TARGET} ${HOST_OS} ${MACHINE} Generic .if empty(_sys_mk) .-include _sys_mk := ${.MAKE.MAKEFILES:M*/$x.mk} .if !empty(_sys_mk) _sys_mk := sys/${_sys_mk:T} .endif .endif .if empty(_sys_mk) # might be an old style .-include <$x.sys.mk> _sys_mk := ${.MAKE.MAKEFILES:M*/$x.sys.mk:T} .endif .endfor SYS_OS_MK := ${_sys_mk} .export SYS_OS_MK .endif # some options we need to know early OPTIONS_DEFAULT_NO += \ DIRDEPS_BUILD \ DIRDEPS_CACHE OPTIONS_DEFAULT_DEPENDENT += \ AUTO_OBJ/DIRDEPS_BUILD \ META_MODE/DIRDEPS_BUILD \ STAGING/DIRDEPS_BUILD \ .-include .if ${MK_DIRDEPS_BUILD:Uno} == "yes" MK_META_MODE = yes .-include .elif ${MK_META_MODE:Uno} == "yes" .MAKE.MODE = meta verbose ${META_MODE} .endif # make sure we have a harmless value .MAKE.MODE ?= normal # if you want objdirs make them automatic # and do it early before we compute .PATH .if ${MK_AUTO_OBJ:Uno} == "yes" || ${MKOBJDIRS:Uno} == "auto" .include .endif .if !empty(SRCTOP) .if ${.CURDIR} == ${SRCTOP} RELDIR = . .elif ${.CURDIR:M${SRCTOP}/*} RELDIR := ${.CURDIR:S,${SRCTOP}/,,} .endif .endif MACHINE_ARCH.host ?= ${_HOST_ARCH} MACHINE_ARCH.${MACHINE} ?= ${MACHINE} .if empty(MACHINE_ARCH) MACHINE_ARCH = ${MACHINE_ARCH.${MACHINE}} .endif .ifndef ROOT_GROUP ROOT_GROUP != sed -n /:0:/s/:.*//p /etc/group .export ROOT_GROUP .endif unix ?= We run ${_HOST_OSNAME}. + +# We need a Bourne/POSIX shell +MAKE_SHELL ?= sh +SHELL ?= ${MAKE_SHELL} # A race condition in mkdir, means that it can bail if another # process made a dir that mkdir expected to. # We repeat the mkdir -p a number of times to try and work around this. # We stop looping as soon as the dir exists. # If we get to the end of the loop, a plain mkdir will issue an error. Mkdirs= Mkdirs() { \ for d in $$*; do \ for i in 1 2 3 4 5 6; do \ mkdir -p $$d; \ test -d $$d && return 0; \ done; \ mkdir $$d || exit $$?; \ done; } # this often helps with debugging .SUFFIXES: .cpp-out .c.cpp-out: @${COMPILE.c:N-c} -E ${.IMPSRC} | grep -v '^[ ]*$$' ${CXX_SUFFIXES:%=%.cpp-out}: @${COMPILE.cc:N-c} -E ${.IMPSRC} | grep -v '^[ ]*$$' # late customizations .-include # if .CURDIR is matched by any entry in DEBUG_MAKE_DIRS we # will apply DEBUG_MAKE_FLAGS, now. .if !empty(_DEBUG_MAKE_FLAGS) .if ${_DEBUG_MAKE_DIRS:Uno:@x@${.CURDIR:M$x}@} != "" .MAKEFLAGS: ${_DEBUG_MAKE_FLAGS} .endif .endif Index: stable/12/contrib/bmake/mk/sys.vars.mk =================================================================== --- stable/12/contrib/bmake/mk/sys.vars.mk (revision 361673) +++ stable/12/contrib/bmake/mk/sys.vars.mk (revision 361674) @@ -1,80 +1,85 @@ -# $Id: sys.vars.mk,v 1.3 2018/02/06 00:51:53 sjg Exp $ +# $Id: sys.vars.mk,v 1.4 2019/05/27 20:22:52 sjg Exp $ # # @(#) Copyright (c) 2003-2009, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # # We use the following paradigm for preventing multiple inclusion. # It relies on the fact that conditionals and dependencies are resolved # at the time they are read. # # _this ?= ${.PARSEFILE} # .if !target(__${_this}__) # __${_this}__: # .if ${MAKE_VERSION:U0} > 20100408 _this = ${.PARSEDIR:tA}/${.PARSEFILE} .else _this = ${.PARSEDIR}/${.PARSEFILE} .endif # if this is an ancient version of bmake MAKE_VERSION ?= 0 .if ${MAKE_VERSION:M*make-*} # turn it into what we want - just the date MAKE_VERSION := ${MAKE_VERSION:[1]:C,.*-,,} .endif # some useful modifiers # A useful trick for testing multiple :M's against something # :L says to use the variable's name as its value - ie. literal # got = ${clean* destroy:${M_ListToMatch:S,V,.TARGETS,}} M_ListToMatch = L:@m@$${V:M$$m}@ # match against our initial targets (see above) M_L_TARGETS = ${M_ListToMatch:S,V,_TARGETS,} # turn a list into a set of :N modifiers # NskipFoo = ${Foo:${M_ListToSkip}} M_ListToSkip= O:u:S,^,N,:ts: # type should be a builtin in any sh since about 1980, # but sadly there are exceptions! .if ${.MAKE.OS:Unknown:NBSD/OS} == "" _type_sh = which .endif # AUTOCONF := ${autoconf:L:${M_whence}} M_type = @x@(${_type_sh:Utype} $$x) 2> /dev/null; echo;@:sh:[0]:N* found*:[@]:C,[()],,g M_whence = ${M_type}:M/*:[1] # convert a path to a valid shell variable M_P2V = tu:C,[./-],_,g # convert path to absolute .if ${MAKE_VERSION:U0} > 20100408 M_tA = tA .else M_tA = C,.*,('cd' & \&\& 'pwd') 2> /dev/null || echo &,:sh .endif .if ${MAKE_VERSION:U0} >= 20170130 # M_cmpv allows comparing dotted versions like 3.1.2 # ${3.1.2:L:${M_cmpv}} -> 3001002 # we use big jumps to handle 3 digits per dot: # ${123.456.789:L:${M_cmpv}} -> 123456789 M_cmpv.units = 1 1000 1000000 M_cmpv = S,., ,g:_:range:@i@+ $${_:[-$$i]} \* $${M_cmpv.units:[$$i]}@:S,^,expr 0 ,1:sh .endif # absoulte path to what we are reading. _PARSEDIR = ${.PARSEDIR:${M_tA}} + +# many projects use MAJOR MINOR PATCH versioning +# ${OPENSSL:${M_M.M.P_VERSION}} is equivalent to +# ${OPENSSL_MAJOR_VERSION}.${OPENSSL_MINOR_VERSION}.${OPENSSL_PATCH_VERSION} +M_M.M.P_VERSION = L:@v@$${MAJOR MINOR PATCH:L:@t@$${$$v_$$t_VERSION:U0}@}@:ts. Index: stable/12/contrib/bmake/mk/whats.mk =================================================================== --- stable/12/contrib/bmake/mk/whats.mk (revision 361673) +++ stable/12/contrib/bmake/mk/whats.mk (revision 361674) @@ -1,64 +1,69 @@ -# $Id: whats.mk,v 1.3 2017/10/19 06:09:14 sjg Exp $ +# $Id: whats.mk,v 1.9 2020/05/09 19:48:53 sjg Exp $ # -# @(#) Copyright (c) 2014, Simon J. Gerraty +# @(#) Copyright (c) 2014-2020, Simon J. Gerraty # # This file is provided in the hope that it will # be of use. There is absolutely NO WARRANTY. # Permission to copy, redistribute or otherwise # use this file is hereby granted provided that # the above copyright notice and this notice are # left intact. # # Please send copies of changes and bug-fixes to: # sjg@crufty.net # -.if ${MK_WHATSTRING:Uno} != "no" -what_build_exts?= o +.if ${MK_WHATSTRING:Uno} == "yes" # it can be useful to embed a what(1) string in binaries # so that the build location can be seen from a core file. -.if defined(PROG) && ${.MAKE.MAKEFILES:M*prog.mk} != "" -what_thing?= ${PROGNAME:U${PROG}} -what_build_thing?= ${PROG} -.elif defined(LIB) && ${.MAKE.MAKEFILES:M*lib.mk} != "" -# probably only makes sense for shared libs -# and the plumbing needed varies depending on *lib.mk -what_thing?= lib${LIB} -.if !empty(SOBJS) -_soe:= ${SOBJS:E:[1]} -what_build_exts= ${_soe} -SOBJS+= ${what_uuid}.${_soe} +.if defined(KMOD) +what_thing ?= ${KMOD} +.elif defined(LIB) +what_thing ?= lib${LIB} +.elif defined(PROG) +what_thing ?= ${PROG} +SRCS ?= ${PROG}.c +.elif defined(SHLIB) +what_thing ?= lib${SHLIB} .endif -.elif defined(KMOD) && ${.MAKE.MAKEFILES:M*kmod.mk} != "" -what_thing?= ${KMOD} -what_build_thing?= ${KMOD}.ko -.endif .if !empty(what_thing) # a unique name that won't conflict with anything what_uuid = what_${what_thing}_${.CURDIR:T:hash} what_var = what_${.CURDIR:T:hash} -.if !empty(what_build_thing) -${what_build_thing}: ${what_build_exts:@e@${what_uuid}.$e@} -.endif -OBJS+= ${what_uuid}.o -CLEANFILES+= ${what_uuid}.c - +SRCS += ${what_uuid}.c +CLEANFILES += ${what_uuid}.c # we do not need to capture this -SUPPRESS_DEPEND+= *${what_uuid}.c +SUPPRESS_DEPEND += *${what_uuid}.c -SB?= ${SRCTOP:H} -SB_LOCATION?= ${HOST}:${SB} -what_location:= ${.OBJDIR:S,${SB},${SB_LOCATION},} +SB ?= ${SRCTOP:H} +SB_LOCATION ?= ${HOST}:${SB} +# make customization easy +WHAT_LOCATION ?= ${.OBJDIR:S,${SB},${SB_LOCATION},} +WHAT_1 ?= ${what_thing:tu} built ${%Y%m%d:L:localtime} by ${USER} +WHAT_2 ?= ${what_location} +WHAT_LINE_IDS ?= 1 2 +WHAT_NOCMP_LINE_IDS ?= 1 +# you can add other WHAT_* just be sure to set WHAT_LINE_IDS +# and WHAT_NOCMP_LINE_IDS accordingly # this works with clang and gcc -_what_t= const char __attribute__ ((section(".data"))) -_what1:= @(\#)${what_thing:tu} built ${%Y%m%d:L:localtime} by ${USER} -_what2:= @(\#)${what_location} +what_t = const char __attribute__ ((section(".data"))) +what_location := ${WHAT_LOCATION} +# this script is done in multiple lines so we can +# use the token ${.OODATE:MNO_META_CMP} +# to prevent the variable parts making this constantly out-of-date ${what_uuid}.c: - echo '${_what_t} ${what_var}1[] = "${_what1}";' > $@ ${.OODATE:MNO_META_CMP} - echo '${_what_t} ${what_var}2[] = "${_what2}";' >> $@ + echo 'extern const char ${WHAT_LINE_IDS:@i@${what_var}_$i[]@:ts,};' > $@ +.for i in ${WHAT_LINE_IDS} +.if ${WHAT_NOCMP_LINE_IDS:M$i} != "" + echo '${what_t} ${what_var}_$i[] = "@(#)${WHAT_$i}";' >> $@ ${.OODATE:MNO_META_CMP} +.else + echo '${what_t} ${what_var}_$i[] = "@(#)${WHAT_$i}";' >> $@ +.endif +.endfor + .endif .endif Index: stable/12/contrib/bmake/nonints.h =================================================================== --- stable/12/contrib/bmake/nonints.h (revision 361673) +++ stable/12/contrib/bmake/nonints.h (revision 361674) @@ -1,205 +1,205 @@ -/* $NetBSD: nonints.h,v 1.74 2016/09/05 00:40:29 sevan Exp $ */ +/* $NetBSD: nonints.h,v 1.75 2020/04/25 18:20:57 christos Exp $ */ /*- * Copyright (c) 1988, 1989, 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)nonints.h 8.3 (Berkeley) 3/19/94 */ /*- * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: @(#)nonints.h 8.3 (Berkeley) 3/19/94 */ /* arch.c */ ReturnStatus Arch_ParseArchive(char **, Lst, GNode *); void Arch_Touch(GNode *); void Arch_TouchLib(GNode *); time_t Arch_MTime(GNode *); time_t Arch_MemMTime(GNode *); void Arch_FindLib(GNode *, Lst); Boolean Arch_LibOODate(GNode *); void Arch_Init(void); void Arch_End(void); int Arch_IsLib(GNode *); /* compat.c */ int CompatRunCommand(void *, void *); void Compat_Run(Lst); int Compat_Make(void *, void *); /* cond.c */ struct If; int Cond_EvalExpression(const struct If *, char *, Boolean *, int, Boolean); int Cond_Eval(char *); void Cond_restore_depth(unsigned int); unsigned int Cond_save_depth(void); /* for.c */ int For_Eval(char *); int For_Accum(char *); void For_Run(int); /* job.c */ #ifdef WAIT_T void JobReapChild(pid_t, WAIT_T, Boolean); #endif /* main.c */ void Main_ParseArgLine(const char *); void MakeMode(const char *); char *Cmd_Exec(const char *, const char **); void Error(const char *, ...) MAKE_ATTR_PRINTFLIKE(1, 2); void Fatal(const char *, ...) MAKE_ATTR_PRINTFLIKE(1, 2) MAKE_ATTR_DEAD; void Punt(const char *, ...) MAKE_ATTR_PRINTFLIKE(1, 2) MAKE_ATTR_DEAD; void DieHorribly(void) MAKE_ATTR_DEAD; int PrintAddr(void *, void *); void Finish(int) MAKE_ATTR_DEAD; int eunlink(const char *); void execError(const char *, const char *); char *getTmpdir(void); Boolean s2Boolean(const char *, Boolean); Boolean getBoolean(const char *, Boolean); char *cached_realpath(const char *, char *); /* parse.c */ void Parse_Error(int, const char *, ...) MAKE_ATTR_PRINTFLIKE(2, 3); Boolean Parse_AnyExport(void); Boolean Parse_IsVar(char *); void Parse_DoVar(char *, GNode *); void Parse_AddIncludeDir(char *); void Parse_File(const char *, int); void Parse_Init(void); void Parse_End(void); void Parse_SetInput(const char *, int, int, char *(*)(void *, size_t *), void *); Lst Parse_MainName(void); /* str.c */ char *str_concat(const char *, const char *, int); char **brk_string(const char *, int *, Boolean, char **); char *Str_FindSubstring(const char *, const char *); int Str_Match(const char *, const char *); -char *Str_SYSVMatch(const char *, const char *, int *len); -void Str_SYSVSubst(Buffer *, char *, char *, int); +char *Str_SYSVMatch(const char *, const char *, size_t *, Boolean *); +void Str_SYSVSubst(Buffer *, char *, char *, size_t, Boolean); #ifndef HAVE_STRLCPY /* strlcpy.c */ size_t strlcpy(char *, const char *, size_t); #endif /* suff.c */ void Suff_ClearSuffixes(void); Boolean Suff_IsTransform(char *); GNode *Suff_AddTransform(char *); int Suff_EndTransform(void *, void *); void Suff_AddSuffix(char *, GNode **); Lst Suff_GetPath(char *); void Suff_DoPaths(void); void Suff_AddInclude(char *); void Suff_AddLib(char *); void Suff_FindDeps(GNode *); Lst Suff_FindPath(GNode *); void Suff_SetNull(char *); void Suff_Init(void); void Suff_End(void); void Suff_PrintAll(void); /* targ.c */ void Targ_Init(void); void Targ_End(void); Lst Targ_List(void); GNode *Targ_NewGN(const char *); GNode *Targ_FindNode(const char *, int); Lst Targ_FindList(Lst, int); Boolean Targ_Ignore(GNode *); Boolean Targ_Silent(GNode *); Boolean Targ_Precious(GNode *); void Targ_SetMain(GNode *); int Targ_PrintCmd(void *, void *); int Targ_PrintNode(void *, void *); char *Targ_FmtTime(time_t); void Targ_PrintType(int); void Targ_PrintGraph(int); void Targ_Propagate(void); void Targ_Propagate_Wait(void); /* var.c */ void Var_Delete(const char *, GNode *); void Var_Set(const char *, const char *, GNode *, int); void Var_Append(const char *, const char *, GNode *); Boolean Var_Exists(const char *, GNode *); char *Var_Value(const char *, GNode *, char **); char *Var_Parse(const char *, GNode *, int, int *, void **); char *Var_Subst(const char *, const char *, GNode *, int); char *Var_GetTail(const char *); char *Var_GetHead(const char *); void Var_Init(void); void Var_End(void); void Var_Dump(GNode *); void Var_ExportVars(void); void Var_Export(char *, int); void Var_UnExport(char *); /* util.c */ void (*bmake_signal(int, void (*)(int)))(int); Index: stable/12/contrib/bmake/parse.c =================================================================== --- stable/12/contrib/bmake/parse.c (revision 361673) +++ stable/12/contrib/bmake/parse.c (revision 361674) @@ -1,3361 +1,3372 @@ -/* $NetBSD: parse.c,v 1.229 2018/04/05 16:31:54 christos Exp $ */ +/* $NetBSD: parse.c,v 1.233 2019/09/26 21:09:55 sjg Exp $ */ /* * Copyright (c) 1988, 1989, 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MAKE_NATIVE -static char rcsid[] = "$NetBSD: parse.c,v 1.229 2018/04/05 16:31:54 christos Exp $"; +static char rcsid[] = "$NetBSD: parse.c,v 1.233 2019/09/26 21:09:55 sjg Exp $"; #else #include #ifndef lint #if 0 static char sccsid[] = "@(#)parse.c 8.3 (Berkeley) 3/19/94"; #else -__RCSID("$NetBSD: parse.c,v 1.229 2018/04/05 16:31:54 christos Exp $"); +__RCSID("$NetBSD: parse.c,v 1.233 2019/09/26 21:09:55 sjg Exp $"); #endif #endif /* not lint */ #endif /*- * parse.c -- * Functions to parse a makefile. * * One function, Parse_Init, must be called before any functions * in this module are used. After that, the function Parse_File is the * main entry point and controls most of the other functions in this * module. * * Most important structures are kept in Lsts. Directories for * the .include "..." function are kept in the 'parseIncPath' Lst, while * those for the .include <...> are kept in the 'sysIncPath' Lst. The * targets currently being defined are kept in the 'targets' Lst. * * The variables 'fname' and 'lineno' are used to track the name * of the current file and the line number in that file so that error * messages can be more meaningful. * * Interface: * Parse_Init Initialization function which must be * called before anything else in this module * is used. * * Parse_End Cleanup the module * * Parse_File Function used to parse a makefile. It must * be given the name of the file, which should * already have been opened, and a function * to call to read a character from the file. * * Parse_IsVar Returns TRUE if the given line is a * variable assignment. Used by MainParseArgs * to determine if an argument is a target * or a variable assignment. Used internally * for pretty much the same thing... * * Parse_Error Function called when an error occurs in * parsing. Used by the variable and * conditional modules. * Parse_MainName Returns a Lst of the main target to create. */ #include #include #include #include #include #include #include #include "make.h" #include "hash.h" #include "dir.h" #include "job.h" #include "buf.h" #include "pathnames.h" #ifdef HAVE_STDINT_H #include #endif #ifdef HAVE_MMAP #include #ifndef MAP_COPY #define MAP_COPY MAP_PRIVATE #endif #ifndef MAP_FILE #define MAP_FILE 0 #endif #endif //////////////////////////////////////////////////////////// // types and constants /* * Structure for a file being read ("included file") */ typedef struct IFile { char *fname; /* name of file */ int lineno; /* current line number in file */ int first_lineno; /* line number of start of text */ int cond_depth; /* 'if' nesting when file opened */ Boolean depending; /* state of doing_depend on EOF */ char *P_str; /* point to base of string buffer */ char *P_ptr; /* point to next char of string buffer */ char *P_end; /* point to the end of string buffer */ char *(*nextbuf)(void *, size_t *); /* Function to get more data */ void *nextbuf_arg; /* Opaque arg for nextbuf() */ struct loadedfile *lf; /* loadedfile object, if any */ } IFile; /* * These values are returned by ParseEOF to tell Parse_File whether to * CONTINUE parsing, i.e. it had only reached the end of an include file, * or if it's DONE. */ #define CONTINUE 1 #define DONE 0 /* * Tokens for target attributes */ typedef enum { Begin, /* .BEGIN */ Default, /* .DEFAULT */ DeleteOnError, /* .DELETE_ON_ERROR */ End, /* .END */ dotError, /* .ERROR */ Ignore, /* .IGNORE */ Includes, /* .INCLUDES */ Interrupt, /* .INTERRUPT */ Libs, /* .LIBS */ Meta, /* .META */ MFlags, /* .MFLAGS or .MAKEFLAGS */ Main, /* .MAIN and we don't have anything user-specified to * make */ NoExport, /* .NOEXPORT */ NoMeta, /* .NOMETA */ NoMetaCmp, /* .NOMETA_CMP */ NoPath, /* .NOPATH */ Not, /* Not special */ NotParallel, /* .NOTPARALLEL */ Null, /* .NULL */ ExObjdir, /* .OBJDIR */ Order, /* .ORDER */ Parallel, /* .PARALLEL */ ExPath, /* .PATH */ Phony, /* .PHONY */ #ifdef POSIX Posix, /* .POSIX */ #endif Precious, /* .PRECIOUS */ ExShell, /* .SHELL */ Silent, /* .SILENT */ SingleShell, /* .SINGLESHELL */ Stale, /* .STALE */ Suffixes, /* .SUFFIXES */ Wait, /* .WAIT */ Attribute /* Generic attribute */ } ParseSpecial; /* * Other tokens */ #define LPAREN '(' #define RPAREN ')' //////////////////////////////////////////////////////////// // result data /* * The main target to create. This is the first target on the first * dependency line in the first makefile. */ static GNode *mainNode; //////////////////////////////////////////////////////////// // eval state /* targets we're working on */ static Lst targets; #ifdef CLEANUP /* command lines for targets */ static Lst targCmds; #endif /* * specType contains the SPECial TYPE of the current target. It is * Not if the target is unspecial. If it *is* special, however, the children * are linked as children of the parent but not vice versa. This variable is * set in ParseDoDependency */ static ParseSpecial specType; /* * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER * seen, then set to each successive source on the line. */ static GNode *predecessor; //////////////////////////////////////////////////////////// // parser state /* true if currently in a dependency line or its commands */ static Boolean inLine; /* number of fatal errors */ static int fatals = 0; /* * Variables for doing includes */ /* current file being read */ static IFile *curFile; /* stack of IFiles generated by .includes */ static Lst includes; /* include paths (lists of directories) */ Lst parseIncPath; /* dirs for "..." includes */ Lst sysIncPath; /* dirs for <...> includes */ Lst defIncPath; /* default for sysIncPath */ //////////////////////////////////////////////////////////// // parser tables /* * The parseKeywords table is searched using binary search when deciding * if a target or source is special. The 'spec' field is the ParseSpecial * type of the keyword ("Not" if the keyword isn't special as a target) while * the 'op' field is the operator to apply to the list of targets if the * keyword is used as a source ("0" if the keyword isn't special as a source) */ static const struct { const char *name; /* Name of keyword */ ParseSpecial spec; /* Type when used as a target */ int op; /* Operator when used as a source */ } parseKeywords[] = { { ".BEGIN", Begin, 0 }, { ".DEFAULT", Default, 0 }, { ".DELETE_ON_ERROR", DeleteOnError, 0 }, { ".END", End, 0 }, { ".ERROR", dotError, 0 }, { ".EXEC", Attribute, OP_EXEC }, { ".IGNORE", Ignore, OP_IGNORE }, { ".INCLUDES", Includes, 0 }, { ".INTERRUPT", Interrupt, 0 }, { ".INVISIBLE", Attribute, OP_INVISIBLE }, { ".JOIN", Attribute, OP_JOIN }, { ".LIBS", Libs, 0 }, { ".MADE", Attribute, OP_MADE }, { ".MAIN", Main, 0 }, { ".MAKE", Attribute, OP_MAKE }, { ".MAKEFLAGS", MFlags, 0 }, { ".META", Meta, OP_META }, { ".MFLAGS", MFlags, 0 }, { ".NOMETA", NoMeta, OP_NOMETA }, { ".NOMETA_CMP", NoMetaCmp, OP_NOMETA_CMP }, { ".NOPATH", NoPath, OP_NOPATH }, { ".NOTMAIN", Attribute, OP_NOTMAIN }, { ".NOTPARALLEL", NotParallel, 0 }, { ".NO_PARALLEL", NotParallel, 0 }, { ".NULL", Null, 0 }, { ".OBJDIR", ExObjdir, 0 }, { ".OPTIONAL", Attribute, OP_OPTIONAL }, { ".ORDER", Order, 0 }, { ".PARALLEL", Parallel, 0 }, { ".PATH", ExPath, 0 }, { ".PHONY", Phony, OP_PHONY }, #ifdef POSIX { ".POSIX", Posix, 0 }, #endif { ".PRECIOUS", Precious, OP_PRECIOUS }, { ".RECURSIVE", Attribute, OP_MAKE }, { ".SHELL", ExShell, 0 }, { ".SILENT", Silent, OP_SILENT }, { ".SINGLESHELL", SingleShell, 0 }, { ".STALE", Stale, 0 }, { ".SUFFIXES", Suffixes, 0 }, { ".USE", Attribute, OP_USE }, { ".USEBEFORE", Attribute, OP_USEBEFORE }, { ".WAIT", Wait, 0 }, }; //////////////////////////////////////////////////////////// // local functions static int ParseIsEscaped(const char *, const char *); static void ParseErrorInternal(const char *, size_t, int, const char *, ...) MAKE_ATTR_PRINTFLIKE(4,5); static void ParseVErrorInternal(FILE *, const char *, size_t, int, const char *, va_list) MAKE_ATTR_PRINTFLIKE(5, 0); static int ParseFindKeyword(const char *); static int ParseLinkSrc(void *, void *); static int ParseDoOp(void *, void *); static void ParseDoSrc(int, const char *); static int ParseFindMain(void *, void *); static int ParseAddDir(void *, void *); static int ParseClearPath(void *, void *); static void ParseDoDependency(char *); static int ParseAddCmd(void *, void *); static void ParseHasCommands(void *); static void ParseDoInclude(char *); static void ParseSetParseFile(const char *); static void ParseSetIncludedFile(void); #ifdef GMAKEEXPORT static void ParseGmakeExport(char *); #endif static int ParseEOF(void); static char *ParseReadLine(void); static void ParseFinishLine(void); static void ParseMark(GNode *); //////////////////////////////////////////////////////////// // file loader struct loadedfile { const char *path; /* name, for error reports */ char *buf; /* contents buffer */ size_t len; /* length of contents */ size_t maplen; /* length of mmap area, or 0 */ Boolean used; /* XXX: have we used the data yet */ }; /* * Constructor/destructor for loadedfile */ static struct loadedfile * loadedfile_create(const char *path) { struct loadedfile *lf; lf = bmake_malloc(sizeof(*lf)); lf->path = (path == NULL ? "(stdin)" : path); lf->buf = NULL; lf->len = 0; lf->maplen = 0; lf->used = FALSE; return lf; } static void loadedfile_destroy(struct loadedfile *lf) { if (lf->buf != NULL) { if (lf->maplen > 0) { #ifdef HAVE_MMAP munmap(lf->buf, lf->maplen); #endif } else { free(lf->buf); } } free(lf); } /* * nextbuf() operation for loadedfile, as needed by the weird and twisted * logic below. Once that's cleaned up, we can get rid of lf->used... */ static char * loadedfile_nextbuf(void *x, size_t *len) { struct loadedfile *lf = x; if (lf->used) { return NULL; } lf->used = TRUE; *len = lf->len; return lf->buf; } /* * Try to get the size of a file. */ static ReturnStatus load_getsize(int fd, size_t *ret) { struct stat st; if (fstat(fd, &st) < 0) { return FAILURE; } if (!S_ISREG(st.st_mode)) { return FAILURE; } /* * st_size is an off_t, which is 64 bits signed; *ret is * size_t, which might be 32 bits unsigned or 64 bits * unsigned. Rather than being elaborate, just punt on * files that are more than 2^31 bytes. We should never * see a makefile that size in practice... * * While we're at it reject negative sizes too, just in case. */ if (st.st_size < 0 || st.st_size > 0x7fffffff) { return FAILURE; } *ret = (size_t) st.st_size; return SUCCESS; } /* * Read in a file. * * Until the path search logic can be moved under here instead of * being in the caller in another source file, we need to have the fd * passed in already open. Bleh. * * If the path is NULL use stdin and (to insure against fd leaks) * assert that the caller passed in -1. */ static struct loadedfile * loadfile(const char *path, int fd) { struct loadedfile *lf; #ifdef HAVE_MMAP static long pagesize = 0; #endif ssize_t result; size_t bufpos; lf = loadedfile_create(path); if (path == NULL) { assert(fd == -1); fd = STDIN_FILENO; } else { #if 0 /* notyet */ fd = open(path, O_RDONLY); if (fd < 0) { ... Error("%s: %s", path, strerror(errno)); exit(1); } #endif } #ifdef HAVE_MMAP if (load_getsize(fd, &lf->len) == SUCCESS) { /* found a size, try mmap */ #ifdef _SC_PAGESIZE if (pagesize == 0) pagesize = sysconf(_SC_PAGESIZE); #endif if (pagesize <= 0) { pagesize = 0x1000; } /* round size up to a page */ lf->maplen = pagesize * ((lf->len + pagesize - 1)/pagesize); /* * XXX hack for dealing with empty files; remove when * we're no longer limited by interfacing to the old * logic elsewhere in this file. */ if (lf->maplen == 0) { lf->maplen = pagesize; } /* * FUTURE: remove PROT_WRITE when the parser no longer * needs to scribble on the input. */ lf->buf = mmap(NULL, lf->maplen, PROT_READ|PROT_WRITE, MAP_FILE|MAP_COPY, fd, 0); if (lf->buf != MAP_FAILED) { /* succeeded */ if (lf->len == lf->maplen && lf->buf[lf->len - 1] != '\n') { char *b = bmake_malloc(lf->len + 1); b[lf->len] = '\n'; memcpy(b, lf->buf, lf->len++); munmap(lf->buf, lf->maplen); lf->maplen = 0; lf->buf = b; } goto done; } } #endif /* cannot mmap; load the traditional way */ lf->maplen = 0; lf->len = 1024; lf->buf = bmake_malloc(lf->len); bufpos = 0; while (1) { assert(bufpos <= lf->len); if (bufpos == lf->len) { if (lf->len > SIZE_MAX/2) { errno = EFBIG; Error("%s: file too large", path); exit(1); } lf->len *= 2; lf->buf = bmake_realloc(lf->buf, lf->len); } assert(bufpos < lf->len); result = read(fd, lf->buf + bufpos, lf->len - bufpos); if (result < 0) { Error("%s: read error: %s", path, strerror(errno)); exit(1); } if (result == 0) { break; } bufpos += result; } assert(bufpos <= lf->len); lf->len = bufpos; /* truncate malloc region to actual length (maybe not useful) */ if (lf->len > 0) { /* as for mmap case, ensure trailing \n */ if (lf->buf[lf->len - 1] != '\n') lf->len++; lf->buf = bmake_realloc(lf->buf, lf->len); lf->buf[lf->len - 1] = '\n'; } #ifdef HAVE_MMAP done: #endif if (path != NULL) { close(fd); } return lf; } //////////////////////////////////////////////////////////// // old code /*- *---------------------------------------------------------------------- * ParseIsEscaped -- * Check if the current character is escaped on the current line * * Results: * 0 if the character is not backslash escaped, 1 otherwise * * Side Effects: * None *---------------------------------------------------------------------- */ static int ParseIsEscaped(const char *line, const char *c) { int active = 0; for (;;) { if (line == c) return active; if (*--c != '\\') return active; active = !active; } } /*- *---------------------------------------------------------------------- * ParseFindKeyword -- * Look in the table of keywords for one matching the given string. * * Input: * str String to find * * Results: * The index of the keyword, or -1 if it isn't there. * * Side Effects: * None *---------------------------------------------------------------------- */ static int ParseFindKeyword(const char *str) { int start, end, cur; int diff; start = 0; end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1; do { cur = start + ((end - start) / 2); diff = strcmp(str, parseKeywords[cur].name); if (diff == 0) { return (cur); } else if (diff < 0) { end = cur - 1; } else { start = cur + 1; } } while (start <= end); return (-1); } /*- * ParseVErrorInternal -- * Error message abort function for parsing. Prints out the context * of the error (line number and file) as well as the message with * two optional arguments. * * Results: * None * * Side Effects: * "fatals" is incremented if the level is PARSE_FATAL. */ /* VARARGS */ static void ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type, const char *fmt, va_list ap) { static Boolean fatal_warning_error_printed = FALSE; + char dirbuf[MAXPATHLEN+1]; (void)fprintf(f, "%s: ", progname); if (cfname != NULL) { (void)fprintf(f, "\""); if (*cfname != '/' && strcmp(cfname, "(stdin)") != 0) { - char *cp; - const char *dir; + char *cp, *cp2; + const char *dir, *fname; /* * Nothing is more annoying than not knowing - * which Makefile is the culprit. + * which Makefile is the culprit; we try ${.PARSEDIR} + * and apply realpath(3) if not absolute. */ dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp); - if (dir == NULL || *dir == '\0' || - (*dir == '.' && dir[1] == '\0')) - dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp); if (dir == NULL) dir = "."; - - (void)fprintf(f, "%s/%s", dir, cfname); + if (*dir != '/') { + dir = realpath(dir, dirbuf); + } + fname = Var_Value(".PARSEFILE", VAR_GLOBAL, &cp2); + if (fname == NULL) { + if ((fname = strrchr(cfname, '/'))) + fname++; + else + fname = cfname; + } + (void)fprintf(f, "%s/%s", dir, fname); + free(cp2); + free(cp); } else (void)fprintf(f, "%s", cfname); (void)fprintf(f, "\" line %d: ", (int)clineno); } if (type == PARSE_WARNING) (void)fprintf(f, "warning: "); (void)vfprintf(f, fmt, ap); (void)fprintf(f, "\n"); (void)fflush(f); if (type == PARSE_INFO) return; if (type == PARSE_FATAL || parseWarnFatal) fatals += 1; if (parseWarnFatal && !fatal_warning_error_printed) { Error("parsing warnings being treated as errors"); fatal_warning_error_printed = TRUE; } } /*- * ParseErrorInternal -- * Error function * * Results: * None * * Side Effects: * None */ /* VARARGS */ static void ParseErrorInternal(const char *cfname, size_t clineno, int type, const char *fmt, ...) { va_list ap; va_start(ap, fmt); (void)fflush(stdout); ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap); va_end(ap); if (debug_file != stderr && debug_file != stdout) { va_start(ap, fmt); ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap); va_end(ap); } } /*- * Parse_Error -- * External interface to ParseErrorInternal; uses the default filename * Line number. * * Results: * None * * Side Effects: * None */ /* VARARGS */ void Parse_Error(int type, const char *fmt, ...) { va_list ap; const char *fname; size_t lineno; if (curFile == NULL) { fname = NULL; lineno = 0; } else { fname = curFile->fname; lineno = curFile->lineno; } va_start(ap, fmt); (void)fflush(stdout); ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap); va_end(ap); if (debug_file != stderr && debug_file != stdout) { va_start(ap, fmt); ParseVErrorInternal(debug_file, fname, lineno, type, fmt, ap); va_end(ap); } } /* * ParseMessage * Parse a .info .warning or .error directive * * The input is the line minus the ".". We substitute * variables, print the message and exit(1) (for .error) or just print * a warning if the directive is malformed. */ static Boolean ParseMessage(char *line) { int mtype; switch(*line) { case 'i': mtype = PARSE_INFO; break; case 'w': mtype = PARSE_WARNING; break; case 'e': mtype = PARSE_FATAL; break; default: Parse_Error(PARSE_WARNING, "invalid syntax: \".%s\"", line); return FALSE; } while (isalpha((unsigned char)*line)) line++; if (!isspace((unsigned char)*line)) return FALSE; /* not for us */ while (isspace((unsigned char)*line)) line++; line = Var_Subst(NULL, line, VAR_CMD, VARF_WANTRES); Parse_Error(mtype, "%s", line); free(line); if (mtype == PARSE_FATAL) { /* Terminate immediately. */ exit(1); } return TRUE; } /*- *--------------------------------------------------------------------- * ParseLinkSrc -- * Link the parent node to its new child. Used in a Lst_ForEach by * ParseDoDependency. If the specType isn't 'Not', the parent * isn't linked as a parent of the child. * * Input: * pgnp The parent node * cgpn The child node * * Results: * Always = 0 * * Side Effects: * New elements are added to the parents list of cgn and the * children list of cgn. the unmade field of pgn is updated * to reflect the additional child. *--------------------------------------------------------------------- */ static int ParseLinkSrc(void *pgnp, void *cgnp) { GNode *pgn = (GNode *)pgnp; GNode *cgn = (GNode *)cgnp; if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts)) pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts)); (void)Lst_AtEnd(pgn->children, cgn); if (specType == Not) (void)Lst_AtEnd(cgn->parents, pgn); pgn->unmade += 1; if (DEBUG(PARSE)) { fprintf(debug_file, "# %s: added child %s - %s\n", __func__, pgn->name, cgn->name); Targ_PrintNode(pgn, 0); Targ_PrintNode(cgn, 0); } return (0); } /*- *--------------------------------------------------------------------- * ParseDoOp -- * Apply the parsed operator to the given target node. Used in a * Lst_ForEach call by ParseDoDependency once all targets have * been found and their operator parsed. If the previous and new * operators are incompatible, a major error is taken. * * Input: * gnp The node to which the operator is to be applied * opp The operator to apply * * Results: * Always 0 * * Side Effects: * The type field of the node is altered to reflect any new bits in * the op. *--------------------------------------------------------------------- */ static int ParseDoOp(void *gnp, void *opp) { GNode *gn = (GNode *)gnp; int op = *(int *)opp; /* * If the dependency mask of the operator and the node don't match and * the node has actually had an operator applied to it before, and * the operator actually has some dependency information in it, complain. */ if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) && !OP_NOP(gn->type) && !OP_NOP(op)) { Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name); return (1); } if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) { /* * If the node was the object of a :: operator, we need to create a * new instance of it for the children and commands on this dependency * line. The new instance is placed on the 'cohorts' list of the * initial one (note the initial one is not on its own cohorts list) * and the new instance is linked to all parents of the initial * instance. */ GNode *cohort; /* * Propagate copied bits to the initial node. They'll be propagated * back to the rest of the cohorts later. */ gn->type |= op & ~OP_OPMASK; cohort = Targ_FindNode(gn->name, TARG_NOHASH); if (doing_depend) ParseMark(cohort); /* * Make the cohort invisible as well to avoid duplicating it into * other variables. True, parents of this target won't tend to do * anything with their local variables, but better safe than * sorry. (I think this is pointless now, since the relevant list * traversals will no longer see this node anyway. -mycroft) */ cohort->type = op | OP_INVISIBLE; (void)Lst_AtEnd(gn->cohorts, cohort); cohort->centurion = gn; gn->unmade_cohorts += 1; snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d", gn->unmade_cohorts); } else { /* * We don't want to nuke any previous flags (whatever they were) so we * just OR the new operator into the old */ gn->type |= op; } return (0); } /*- *--------------------------------------------------------------------- * ParseDoSrc -- * Given the name of a source, figure out if it is an attribute * and apply it to the targets if it is. Else decide if there is * some attribute which should be applied *to* the source because * of some special target and apply it if so. Otherwise, make the * source be a child of the targets in the list 'targets' * * Input: * tOp operator (if any) from special targets * src name of the source to handle * * Results: * None * * Side Effects: * Operator bits may be added to the list of targets or to the source. * The targets may have a new source added to their lists of children. *--------------------------------------------------------------------- */ static void ParseDoSrc(int tOp, const char *src) { GNode *gn = NULL; static int wait_number = 0; char wait_src[16]; if (*src == '.' && isupper ((unsigned char)src[1])) { int keywd = ParseFindKeyword(src); if (keywd != -1) { int op = parseKeywords[keywd].op; if (op != 0) { Lst_ForEach(targets, ParseDoOp, &op); return; } if (parseKeywords[keywd].spec == Wait) { /* * We add a .WAIT node in the dependency list. * After any dynamic dependencies (and filename globbing) * have happened, it is given a dependency on the each * previous child back to and previous .WAIT node. * The next child won't be scheduled until the .WAIT node * is built. * We give each .WAIT node a unique name (mainly for diag). */ snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number); gn = Targ_FindNode(wait_src, TARG_NOHASH); if (doing_depend) ParseMark(gn); gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN; Lst_ForEach(targets, ParseLinkSrc, gn); return; } } } switch (specType) { case Main: /* * If we have noted the existence of a .MAIN, it means we need * to add the sources of said target to the list of things * to create. The string 'src' is likely to be free, so we * must make a new copy of it. Note that this will only be * invoked if the user didn't specify a target on the command * line. This is to allow #ifmake's to succeed, or something... */ (void)Lst_AtEnd(create, bmake_strdup(src)); /* * Add the name to the .TARGETS variable as well, so the user can * employ that, if desired. */ Var_Append(".TARGETS", src, VAR_GLOBAL); return; case Order: /* * Create proper predecessor/successor links between the previous * source and the current one. */ gn = Targ_FindNode(src, TARG_CREATE); if (doing_depend) ParseMark(gn); if (predecessor != NULL) { (void)Lst_AtEnd(predecessor->order_succ, gn); (void)Lst_AtEnd(gn->order_pred, predecessor); if (DEBUG(PARSE)) { fprintf(debug_file, "# %s: added Order dependency %s - %s\n", __func__, predecessor->name, gn->name); Targ_PrintNode(predecessor, 0); Targ_PrintNode(gn, 0); } } /* * The current source now becomes the predecessor for the next one. */ predecessor = gn; break; default: /* * If the source is not an attribute, we need to find/create * a node for it. After that we can apply any operator to it * from a special target or link it to its parents, as * appropriate. * * In the case of a source that was the object of a :: operator, * the attribute is applied to all of its instances (as kept in * the 'cohorts' list of the node) or all the cohorts are linked * to all the targets. */ /* Find/create the 'src' node and attach to all targets */ gn = Targ_FindNode(src, TARG_CREATE); if (doing_depend) ParseMark(gn); if (tOp) { gn->type |= tOp; } else { Lst_ForEach(targets, ParseLinkSrc, gn); } break; } } /*- *----------------------------------------------------------------------- * ParseFindMain -- * Find a real target in the list and set it to be the main one. * Called by ParseDoDependency when a main target hasn't been found * yet. * * Input: * gnp Node to examine * * Results: * 0 if main not found yet, 1 if it is. * * Side Effects: * mainNode is changed and Targ_SetMain is called. * *----------------------------------------------------------------------- */ static int ParseFindMain(void *gnp, void *dummy MAKE_ATTR_UNUSED) { GNode *gn = (GNode *)gnp; if ((gn->type & OP_NOTARGET) == 0) { mainNode = gn; Targ_SetMain(gn); return 1; } else { return 0; } } /*- *----------------------------------------------------------------------- * ParseAddDir -- * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going * * Results: * === 0 * * Side Effects: * See Dir_AddDir. * *----------------------------------------------------------------------- */ static int ParseAddDir(void *path, void *name) { (void)Dir_AddDir((Lst) path, (char *)name); return(0); } /*- *----------------------------------------------------------------------- * ParseClearPath -- * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going * * Results: * === 0 * * Side Effects: * See Dir_ClearPath * *----------------------------------------------------------------------- */ static int ParseClearPath(void *path, void *dummy MAKE_ATTR_UNUSED) { Dir_ClearPath((Lst) path); return 0; } /*- *--------------------------------------------------------------------- * ParseDoDependency -- * Parse the dependency line in line. * * Input: * line the line to parse * * Results: * None * * Side Effects: * The nodes of the sources are linked as children to the nodes of the * targets. Some nodes may be created. * * We parse a dependency line by first extracting words from the line and * finding nodes in the list of all targets with that name. This is done * until a character is encountered which is an operator character. Currently * these are only ! and :. At this point the operator is parsed and the * pointer into the line advanced until the first source is encountered. * The parsed operator is applied to each node in the 'targets' list, * which is where the nodes found for the targets are kept, by means of * the ParseDoOp function. * The sources are read in much the same way as the targets were except * that now they are expanded using the wildcarding scheme of the C-Shell * and all instances of the resulting words in the list of all targets * are found. Each of the resulting nodes is then linked to each of the * targets as one of its children. * Certain targets are handled specially. These are the ones detailed * by the specType variable. * The storing of transformation rules is also taken care of here. * A target is recognized as a transformation rule by calling * Suff_IsTransform. If it is a transformation rule, its node is gotten * from the suffix module via Suff_AddTransform rather than the standard * Targ_FindNode in the target module. *--------------------------------------------------------------------- */ static void ParseDoDependency(char *line) { char *cp; /* our current position */ GNode *gn = NULL; /* a general purpose temporary node */ int op; /* the operator on the line */ char savec; /* a place to save a character */ Lst paths; /* List of search paths to alter when parsing * a list of .PATH targets */ int tOp; /* operator from special target */ Lst sources; /* list of archive source names after * expansion */ Lst curTargs; /* list of target names to be found and added * to the targets list */ char *lstart = line; if (DEBUG(PARSE)) fprintf(debug_file, "ParseDoDependency(%s)\n", line); tOp = 0; specType = Not; paths = NULL; curTargs = Lst_Init(FALSE); /* * First, grind through the targets. */ do { /* * Here LINE points to the beginning of the next word, and * LSTART points to the actual beginning of the line. */ /* Find the end of the next word. */ for (cp = line; *cp && (ParseIsEscaped(lstart, cp) || !(isspace((unsigned char)*cp) || *cp == '!' || *cp == ':' || *cp == LPAREN)); cp++) { if (*cp == '$') { /* * Must be a dynamic source (would have been expanded * otherwise), so call the Var module to parse the puppy * so we can safely advance beyond it...There should be * no errors in this, as they would have been discovered * in the initial Var_Subst and we wouldn't be here. */ int length; void *freeIt; (void)Var_Parse(cp, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES, &length, &freeIt); free(freeIt); cp += length-1; } } /* * If the word is followed by a left parenthesis, it's the * name of an object file inside an archive (ar file). */ if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) { /* * Archives must be handled specially to make sure the OP_ARCHV * flag is set in their 'type' field, for one thing, and because * things like "archive(file1.o file2.o file3.o)" are permissible. * Arch_ParseArchive will set 'line' to be the first non-blank * after the archive-spec. It creates/finds nodes for the members * and places them on the given list, returning SUCCESS if all * went well and FAILURE if there was an error in the * specification. On error, line should remain untouched. */ if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) { Parse_Error(PARSE_FATAL, "Error in archive specification: \"%s\"", line); goto out; } else { /* Done with this word; on to the next. */ cp = line; continue; } } if (!*cp) { /* * We got to the end of the line while we were still * looking at targets. * * Ending a dependency line without an operator is a Bozo * no-no. As a heuristic, this is also often triggered by * undetected conflicts from cvs/rcs merges. */ if ((strncmp(line, "<<<<<<", 6) == 0) || (strncmp(line, "======", 6) == 0) || (strncmp(line, ">>>>>>", 6) == 0)) Parse_Error(PARSE_FATAL, "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts"); else Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive" : "Need an operator"); goto out; } /* Insert a null terminator. */ savec = *cp; *cp = '\0'; /* * Got the word. See if it's a special target and if so set * specType to match it. */ if (*line == '.' && isupper ((unsigned char)line[1])) { /* * See if the target is a special target that must have it * or its sources handled specially. */ int keywd = ParseFindKeyword(line); if (keywd != -1) { if (specType == ExPath && parseKeywords[keywd].spec != ExPath) { Parse_Error(PARSE_FATAL, "Mismatched special targets"); goto out; } specType = parseKeywords[keywd].spec; tOp = parseKeywords[keywd].op; /* * Certain special targets have special semantics: * .PATH Have to set the dirSearchPath * variable too * .MAIN Its sources are only used if * nothing has been specified to * create. * .DEFAULT Need to create a node to hang * commands on, but we don't want * it in the graph, nor do we want * it to be the Main Target, so we * create it, set OP_NOTMAIN and * add it to the list, setting * DEFAULT to the new node for * later use. We claim the node is * A transformation rule to make * life easier later, when we'll * use Make_HandleUse to actually * apply the .DEFAULT commands. * .PHONY The list of targets * .NOPATH Don't search for file in the path * .STALE * .BEGIN * .END * .ERROR * .DELETE_ON_ERROR * .INTERRUPT Are not to be considered the * main target. * .NOTPARALLEL Make only one target at a time. * .SINGLESHELL Create a shell for each command. * .ORDER Must set initial predecessor to NULL */ switch (specType) { case ExPath: if (paths == NULL) { paths = Lst_Init(FALSE); } (void)Lst_AtEnd(paths, dirSearchPath); break; case Main: if (!Lst_IsEmpty(create)) { specType = Not; } break; case Begin: case End: case Stale: case dotError: case Interrupt: gn = Targ_FindNode(line, TARG_CREATE); if (doing_depend) ParseMark(gn); gn->type |= OP_NOTMAIN|OP_SPECIAL; (void)Lst_AtEnd(targets, gn); break; case Default: gn = Targ_NewGN(".DEFAULT"); gn->type |= (OP_NOTMAIN|OP_TRANSFORM); (void)Lst_AtEnd(targets, gn); DEFAULT = gn; break; case DeleteOnError: deleteOnError = TRUE; break; case NotParallel: maxJobs = 1; break; case SingleShell: compatMake = TRUE; break; case Order: predecessor = NULL; break; default: break; } } else if (strncmp(line, ".PATH", 5) == 0) { /* * .PATH has to be handled specially. * Call on the suffix module to give us a path to * modify. */ Lst path; specType = ExPath; path = Suff_GetPath(&line[5]); if (path == NULL) { Parse_Error(PARSE_FATAL, "Suffix '%s' not defined (yet)", &line[5]); goto out; } else { if (paths == NULL) { paths = Lst_Init(FALSE); } (void)Lst_AtEnd(paths, path); } } } /* * Have word in line. Get or create its node and stick it at * the end of the targets list */ if ((specType == Not) && (*line != '\0')) { if (Dir_HasWildcards(line)) { /* * Targets are to be sought only in the current directory, * so create an empty path for the thing. Note we need to * use Dir_Destroy in the destruction of the path as the * Dir module could have added a directory to the path... */ Lst emptyPath = Lst_Init(FALSE); Dir_Expand(line, emptyPath, curTargs); Lst_Destroy(emptyPath, Dir_Destroy); } else { /* * No wildcards, but we want to avoid code duplication, * so create a list with the word on it. */ (void)Lst_AtEnd(curTargs, line); } /* Apply the targets. */ while(!Lst_IsEmpty(curTargs)) { char *targName = (char *)Lst_DeQueue(curTargs); if (!Suff_IsTransform (targName)) { gn = Targ_FindNode(targName, TARG_CREATE); } else { gn = Suff_AddTransform(targName); } if (doing_depend) ParseMark(gn); (void)Lst_AtEnd(targets, gn); } } else if (specType == ExPath && *line != '.' && *line != '\0') { Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line); } /* Don't need the inserted null terminator any more. */ *cp = savec; /* * If it is a special type and not .PATH, it's the only target we * allow on this line... */ if (specType != Not && specType != ExPath) { Boolean warning = FALSE; while (*cp && (ParseIsEscaped(lstart, cp) || ((*cp != '!') && (*cp != ':')))) { if (ParseIsEscaped(lstart, cp) || (*cp != ' ' && *cp != '\t')) { warning = TRUE; } cp++; } if (warning) { Parse_Error(PARSE_WARNING, "Extra target ignored"); } } else { while (*cp && isspace ((unsigned char)*cp)) { cp++; } } line = cp; } while (*line && (ParseIsEscaped(lstart, line) || ((*line != '!') && (*line != ':')))); /* * Don't need the list of target names anymore... */ Lst_Destroy(curTargs, NULL); curTargs = NULL; if (!Lst_IsEmpty(targets)) { switch(specType) { default: Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored"); break; case Default: case Stale: case Begin: case End: case dotError: case Interrupt: /* * These four create nodes on which to hang commands, so * targets shouldn't be empty... */ case Not: /* * Nothing special here -- targets can be empty if it wants. */ break; } } /* * Have now parsed all the target names. Must parse the operator next. The * result is left in op . */ if (*cp == '!') { op = OP_FORCE; } else if (*cp == ':') { if (cp[1] == ':') { op = OP_DOUBLEDEP; cp++; } else { op = OP_DEPENDS; } } else { Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive" : "Missing dependency operator"); goto out; } /* Advance beyond the operator */ cp++; /* * Apply the operator to the target. This is how we remember which * operator a target was defined with. It fails if the operator * used isn't consistent across all references. */ Lst_ForEach(targets, ParseDoOp, &op); /* * Onward to the sources. * * LINE will now point to the first source word, if any, or the * end of the string if not. */ while (*cp && isspace ((unsigned char)*cp)) { cp++; } line = cp; /* * Several special targets take different actions if present with no * sources: * a .SUFFIXES line with no sources clears out all old suffixes * a .PRECIOUS line makes all targets precious * a .IGNORE line ignores errors for all targets * a .SILENT line creates silence when making all targets * a .PATH removes all directories from the search path(s). */ if (!*line) { switch (specType) { case Suffixes: Suff_ClearSuffixes(); break; case Precious: allPrecious = TRUE; break; case Ignore: ignoreErrors = TRUE; break; case Silent: beSilent = TRUE; break; case ExPath: Lst_ForEach(paths, ParseClearPath, NULL); Dir_SetPATH(); break; #ifdef POSIX case Posix: Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0); break; #endif default: break; } } else if (specType == MFlags) { /* * Call on functions in main.c to deal with these arguments and * set the initial character to a null-character so the loop to * get sources won't get anything */ Main_ParseArgLine(line); *line = '\0'; } else if (specType == ExShell) { if (Job_ParseShell(line) != SUCCESS) { Parse_Error(PARSE_FATAL, "improper shell specification"); goto out; } *line = '\0'; } else if ((specType == NotParallel) || (specType == SingleShell) || (specType == DeleteOnError)) { *line = '\0'; } /* * NOW GO FOR THE SOURCES */ if ((specType == Suffixes) || (specType == ExPath) || (specType == Includes) || (specType == Libs) || (specType == Null) || (specType == ExObjdir)) { while (*line) { /* * If the target was one that doesn't take files as its sources * but takes something like suffixes, we take each * space-separated word on the line as a something and deal * with it accordingly. * * If the target was .SUFFIXES, we take each source as a * suffix and add it to the list of suffixes maintained by the * Suff module. * * If the target was a .PATH, we add the source as a directory * to search on the search path. * * If it was .INCLUDES, the source is taken to be the suffix of * files which will be #included and whose search path should * be present in the .INCLUDES variable. * * If it was .LIBS, the source is taken to be the suffix of * files which are considered libraries and whose search path * should be present in the .LIBS variable. * * If it was .NULL, the source is the suffix to use when a file * has no valid suffix. * * If it was .OBJDIR, the source is a new definition for .OBJDIR, * and will cause make to do a new chdir to that path. */ while (*cp && !isspace ((unsigned char)*cp)) { cp++; } savec = *cp; *cp = '\0'; switch (specType) { case Suffixes: Suff_AddSuffix(line, &mainNode); break; case ExPath: Lst_ForEach(paths, ParseAddDir, line); break; case Includes: Suff_AddInclude(line); break; case Libs: Suff_AddLib(line); break; case Null: Suff_SetNull(line); break; case ExObjdir: Main_SetObjdir("%s", line); break; default: break; } *cp = savec; if (savec != '\0') { cp++; } while (*cp && isspace ((unsigned char)*cp)) { cp++; } line = cp; } if (paths) { Lst_Destroy(paths, NULL); paths = NULL; } if (specType == ExPath) Dir_SetPATH(); } else { assert(paths == NULL); while (*line) { /* * The targets take real sources, so we must beware of archive * specifications (i.e. things with left parentheses in them) * and handle them accordingly. */ for (; *cp && !isspace ((unsigned char)*cp); cp++) { if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) { /* * Only stop for a left parenthesis if it isn't at the * start of a word (that'll be for variable changes * later) and isn't preceded by a dollar sign (a dynamic * source). */ break; } } if (*cp == LPAREN) { sources = Lst_Init(FALSE); if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) { Parse_Error(PARSE_FATAL, "Error in source archive spec \"%s\"", line); goto out; } while (!Lst_IsEmpty (sources)) { gn = (GNode *)Lst_DeQueue(sources); ParseDoSrc(tOp, gn->name); } Lst_Destroy(sources, NULL); cp = line; } else { if (*cp) { *cp = '\0'; cp += 1; } ParseDoSrc(tOp, line); } while (*cp && isspace ((unsigned char)*cp)) { cp++; } line = cp; } } if (mainNode == NULL) { /* * If we have yet to decide on a main target to make, in the * absence of any user input, we want the first target on * the first dependency line that is actually a real target * (i.e. isn't a .USE or .EXEC rule) to be made. */ Lst_ForEach(targets, ParseFindMain, NULL); } out: - assert(paths == NULL); + if (paths) + Lst_Destroy(paths, NULL); if (curTargs) Lst_Destroy(curTargs, NULL); } /*- *--------------------------------------------------------------------- * Parse_IsVar -- * Return TRUE if the passed line is a variable assignment. A variable * assignment consists of a single word followed by optional whitespace * followed by either a += or an = operator. * This function is used both by the Parse_File function and main when * parsing the command-line arguments. * * Input: * line the line to check * * Results: * TRUE if it is. FALSE if it ain't * * Side Effects: * none *--------------------------------------------------------------------- */ Boolean Parse_IsVar(char *line) { Boolean wasSpace = FALSE; /* set TRUE if found a space */ char ch; int level = 0; #define ISEQOPERATOR(c) \ (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!')) /* * Skip to variable name */ for (;(*line == ' ') || (*line == '\t'); line++) continue; /* Scan for one of the assignment operators outside a variable expansion */ while ((ch = *line++) != 0) { if (ch == '(' || ch == '{') { level++; continue; } if (ch == ')' || ch == '}') { level--; continue; } if (level != 0) continue; while (ch == ' ' || ch == '\t') { ch = *line++; wasSpace = TRUE; } #ifdef SUNSHCMD if (ch == ':' && strncmp(line, "sh", 2) == 0) { line += 2; continue; } #endif if (ch == '=') return TRUE; if (*line == '=' && ISEQOPERATOR(ch)) return TRUE; if (wasSpace) return FALSE; } return FALSE; } /*- *--------------------------------------------------------------------- * Parse_DoVar -- * Take the variable assignment in the passed line and do it in the * global context. * * Note: There is a lexical ambiguity with assignment modifier characters * in variable names. This routine interprets the character before the = * as a modifier. Therefore, an assignment like * C++=/usr/bin/CC * is interpreted as "C+ +=" instead of "C++ =". * * Input: * line a line guaranteed to be a variable assignment. * This reduces error checks * ctxt Context in which to do the assignment * * Results: * none * * Side Effects: * the variable structure of the given variable name is altered in the * global context. *--------------------------------------------------------------------- */ void Parse_DoVar(char *line, GNode *ctxt) { char *cp; /* pointer into line */ enum { VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL } type; /* Type of assignment */ char *opc; /* ptr to operator character to * null-terminate the variable name */ Boolean freeCp = FALSE; /* TRUE if cp needs to be freed, * i.e. if any variable expansion was * performed */ int depth; /* * Skip to variable name */ while ((*line == ' ') || (*line == '\t')) { line++; } /* * Skip to operator character, nulling out whitespace as we go * XXX Rather than counting () and {} we should look for $ and * then expand the variable. */ for (depth = 0, cp = line + 1; depth > 0 || *cp != '='; cp++) { if (*cp == '(' || *cp == '{') { depth++; continue; } if (*cp == ')' || *cp == '}') { depth--; continue; } if (depth == 0 && isspace ((unsigned char)*cp)) { *cp = '\0'; } } opc = cp-1; /* operator is the previous character */ *cp++ = '\0'; /* nuke the = */ /* * Check operator type */ switch (*opc) { case '+': type = VAR_APPEND; *opc = '\0'; break; case '?': /* * If the variable already has a value, we don't do anything. */ *opc = '\0'; if (Var_Exists(line, ctxt)) { return; } else { type = VAR_NORMAL; } break; case ':': type = VAR_SUBST; *opc = '\0'; break; case '!': type = VAR_SHELL; *opc = '\0'; break; default: #ifdef SUNSHCMD while (opc > line && *opc != ':') opc--; if (strncmp(opc, ":sh", 3) == 0) { type = VAR_SHELL; *opc = '\0'; break; } #endif type = VAR_NORMAL; break; } while (isspace ((unsigned char)*cp)) { cp++; } if (type == VAR_APPEND) { Var_Append(line, cp, ctxt); } else if (type == VAR_SUBST) { /* * Allow variables in the old value to be undefined, but leave their * invocation alone -- this is done by forcing oldVars to be false. * XXX: This can cause recursive variables, but that's not hard to do, * and this allows someone to do something like * * CFLAGS = $(.INCLUDES) * CFLAGS := -I.. $(CFLAGS) * * And not get an error. */ Boolean oldOldVars = oldVars; oldVars = FALSE; /* * make sure that we set the variable the first time to nothing * so that it gets substituted! */ if (!Var_Exists(line, ctxt)) Var_Set(line, "", ctxt, 0); cp = Var_Subst(NULL, cp, ctxt, VARF_WANTRES|VARF_ASSIGN); oldVars = oldOldVars; freeCp = TRUE; Var_Set(line, cp, ctxt, 0); } else if (type == VAR_SHELL) { char *res; const char *error; if (strchr(cp, '$') != NULL) { /* * There's a dollar sign in the command, so perform variable * expansion on the whole thing. The resulting string will need * freeing when we're done, so set freeCmd to TRUE. */ cp = Var_Subst(NULL, cp, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES); freeCp = TRUE; } res = Cmd_Exec(cp, &error); Var_Set(line, res, ctxt, 0); free(res); if (error) Parse_Error(PARSE_WARNING, error, cp); } else { /* * Normal assignment -- just do it. */ Var_Set(line, cp, ctxt, 0); } if (strcmp(line, MAKEOVERRIDES) == 0) Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */ else if (strcmp(line, ".CURDIR") == 0) { /* * Somone is being (too?) clever... * Let's pretend they know what they are doing and * re-initialize the 'cur' Path. */ Dir_InitCur(cp); Dir_SetPATH(); } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) { Job_SetPrefix(); } else if (strcmp(line, MAKE_EXPORTED) == 0) { Var_Export(cp, 0); } if (freeCp) free(cp); } /* * ParseMaybeSubMake -- * Scan the command string to see if it a possible submake node * Input: * cmd the command to scan * Results: * TRUE if the command is possibly a submake, FALSE if not. */ static Boolean ParseMaybeSubMake(const char *cmd) { size_t i; static struct { const char *name; size_t len; } vals[] = { #define MKV(A) { A, sizeof(A) - 1 } MKV("${MAKE}"), MKV("${.MAKE}"), MKV("$(MAKE)"), MKV("$(.MAKE)"), MKV("make"), }; for (i = 0; i < sizeof(vals)/sizeof(vals[0]); i++) { char *ptr; if ((ptr = strstr(cmd, vals[i].name)) == NULL) continue; if ((ptr == cmd || !isalnum((unsigned char)ptr[-1])) && !isalnum((unsigned char)ptr[vals[i].len])) return TRUE; } return FALSE; } /*- * ParseAddCmd -- * Lst_ForEach function to add a command line to all targets * * Input: * gnp the node to which the command is to be added * cmd the command to add * * Results: * Always 0 * * Side Effects: * A new element is added to the commands list of the node, * and the node can be marked as a submake node if the command is * determined to be that. */ static int ParseAddCmd(void *gnp, void *cmd) { GNode *gn = (GNode *)gnp; /* Add to last (ie current) cohort for :: targets */ if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts)) gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts)); /* if target already supplied, ignore commands */ if (!(gn->type & OP_HAS_COMMANDS)) { (void)Lst_AtEnd(gn->commands, cmd); if (ParseMaybeSubMake(cmd)) gn->type |= OP_SUBMAKE; ParseMark(gn); } else { #ifdef notyet /* XXX: We cannot do this until we fix the tree */ (void)Lst_AtEnd(gn->commands, cmd); Parse_Error(PARSE_WARNING, "overriding commands for target \"%s\"; " "previous commands defined at %s: %d ignored", gn->name, gn->fname, gn->lineno); #else Parse_Error(PARSE_WARNING, "duplicate script for target \"%s\" ignored", gn->name); ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING, "using previous script for \"%s\" defined here", gn->name); #endif } return(0); } /*- *----------------------------------------------------------------------- * ParseHasCommands -- * Callback procedure for Parse_File when destroying the list of * targets on the last dependency line. Marks a target as already * having commands if it does, to keep from having shell commands * on multiple dependency lines. * * Input: * gnp Node to examine * * Results: * None * * Side Effects: * OP_HAS_COMMANDS may be set for the target. * *----------------------------------------------------------------------- */ static void ParseHasCommands(void *gnp) { GNode *gn = (GNode *)gnp; if (!Lst_IsEmpty(gn->commands)) { gn->type |= OP_HAS_COMMANDS; } } /*- *----------------------------------------------------------------------- * Parse_AddIncludeDir -- * Add a directory to the path searched for included makefiles * bracketed by double-quotes. Used by functions in main.c * * Input: * dir The name of the directory to add * * Results: * None. * * Side Effects: * The directory is appended to the list. * *----------------------------------------------------------------------- */ void Parse_AddIncludeDir(char *dir) { (void)Dir_AddDir(parseIncPath, dir); } /*- *--------------------------------------------------------------------- * ParseDoInclude -- * Push to another file. * * The input is the line minus the `.'. A file spec is a string * enclosed in <> or "". The former is looked for only in sysIncPath. * The latter in . and the directories specified by -I command line * options * * Results: * None * * Side Effects: * A structure is added to the includes Lst and readProc, lineno, * fname and curFILE are altered for the new file *--------------------------------------------------------------------- */ static void Parse_include_file(char *file, Boolean isSystem, Boolean depinc, int silent) { struct loadedfile *lf; char *fullname; /* full pathname of file */ char *newName; char *prefEnd, *incdir; int fd; int i; /* * Now we know the file's name and its search path, we attempt to * find the durn thing. A return of NULL indicates the file don't * exist. */ fullname = file[0] == '/' ? bmake_strdup(file) : NULL; if (fullname == NULL && !isSystem) { /* * Include files contained in double-quotes are first searched for * relative to the including file's location. We don't want to * cd there, of course, so we just tack on the old file's * leading path components and call Dir_FindFile to see if * we can locate the beast. */ incdir = bmake_strdup(curFile->fname); prefEnd = strrchr(incdir, '/'); if (prefEnd != NULL) { *prefEnd = '\0'; /* Now do lexical processing of leading "../" on the filename */ for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) { prefEnd = strrchr(incdir + 1, '/'); if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0) break; *prefEnd = '\0'; } newName = str_concat(incdir, file + i, STR_ADDSLASH); fullname = Dir_FindFile(newName, parseIncPath); if (fullname == NULL) fullname = Dir_FindFile(newName, dirSearchPath); free(newName); } free(incdir); if (fullname == NULL) { /* * Makefile wasn't found in same directory as included makefile. * Search for it first on the -I search path, * then on the .PATH search path, if not found in a -I directory. * If we have a suffix specific path we should use that. */ char *suff; Lst suffPath = NULL; if ((suff = strrchr(file, '.'))) { suffPath = Suff_GetPath(suff); if (suffPath != NULL) { fullname = Dir_FindFile(file, suffPath); } } if (fullname == NULL) { fullname = Dir_FindFile(file, parseIncPath); if (fullname == NULL) { fullname = Dir_FindFile(file, dirSearchPath); } } } } /* Looking for a system file or file still not found */ if (fullname == NULL) { /* * Look for it on the system path */ fullname = Dir_FindFile(file, Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath); } if (fullname == NULL) { if (!silent) Parse_Error(PARSE_FATAL, "Could not find %s", file); return; } /* Actually open the file... */ fd = open(fullname, O_RDONLY); if (fd == -1) { if (!silent) Parse_Error(PARSE_FATAL, "Cannot open %s", fullname); free(fullname); return; } /* load it */ lf = loadfile(fullname, fd); ParseSetIncludedFile(); /* Start reading from this file next */ Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf); curFile->lf = lf; if (depinc) doing_depend = depinc; /* only turn it on */ } static void ParseDoInclude(char *line) { char endc; /* the character which ends the file spec */ char *cp; /* current position in file spec */ int silent = (*line != 'i') ? 1 : 0; char *file = &line[7 + silent]; /* Skip to delimiter character so we know where to look */ while (*file == ' ' || *file == '\t') file++; if (*file != '"' && *file != '<') { Parse_Error(PARSE_FATAL, ".include filename must be delimited by '\"' or '<'"); return; } /* * Set the search path on which to find the include file based on the * characters which bracket its name. Angle-brackets imply it's * a system Makefile while double-quotes imply it's a user makefile */ if (*file == '<') { endc = '>'; } else { endc = '"'; } /* Skip to matching delimiter */ for (cp = ++file; *cp && *cp != endc; cp++) continue; if (*cp != endc) { Parse_Error(PARSE_FATAL, "Unclosed %cinclude filename. '%c' expected", '.', endc); return; } *cp = '\0'; /* * Substitute for any variables in the file name before trying to * find the thing. */ file = Var_Subst(NULL, file, VAR_CMD, VARF_WANTRES); Parse_include_file(file, endc == '>', (*line == 'd'), silent); free(file); } /*- *--------------------------------------------------------------------- * ParseSetIncludedFile -- * Set the .INCLUDEDFROMFILE variable to the contents of .PARSEFILE * and the .INCLUDEDFROMDIR variable to the contents of .PARSEDIR * * Results: * None * * Side Effects: * The .INCLUDEDFROMFILE variable is overwritten by the contents * of .PARSEFILE and the .INCLUDEDFROMDIR variable is overwriten * by the contents of .PARSEDIR *--------------------------------------------------------------------- */ static void ParseSetIncludedFile(void) { char *pf, *fp = NULL; char *pd, *dp = NULL; pf = Var_Value(".PARSEFILE", VAR_GLOBAL, &fp); Var_Set(".INCLUDEDFROMFILE", pf, VAR_GLOBAL, 0); pd = Var_Value(".PARSEDIR", VAR_GLOBAL, &dp); Var_Set(".INCLUDEDFROMDIR", pd, VAR_GLOBAL, 0); if (DEBUG(PARSE)) fprintf(debug_file, "%s: ${.INCLUDEDFROMDIR} = `%s' " "${.INCLUDEDFROMFILE} = `%s'\n", __func__, pd, pf); free(fp); free(dp); } /*- *--------------------------------------------------------------------- * ParseSetParseFile -- * Set the .PARSEDIR and .PARSEFILE variables to the dirname and * basename of the given filename * * Results: * None * * Side Effects: * The .PARSEDIR and .PARSEFILE variables are overwritten by the * dirname and basename of the given filename. *--------------------------------------------------------------------- */ static void ParseSetParseFile(const char *filename) { char *slash, *dirname; const char *pd, *pf; int len; slash = strrchr(filename, '/'); if (slash == NULL) { Var_Set(".PARSEDIR", pd = curdir, VAR_GLOBAL, 0); Var_Set(".PARSEFILE", pf = filename, VAR_GLOBAL, 0); dirname= NULL; } else { len = slash - filename; dirname = bmake_malloc(len + 1); memcpy(dirname, filename, len); dirname[len] = '\0'; Var_Set(".PARSEDIR", pd = dirname, VAR_GLOBAL, 0); Var_Set(".PARSEFILE", pf = slash + 1, VAR_GLOBAL, 0); } if (DEBUG(PARSE)) fprintf(debug_file, "%s: ${.PARSEDIR} = `%s' ${.PARSEFILE} = `%s'\n", __func__, pd, pf); free(dirname); } /* * Track the makefiles we read - so makefiles can * set dependencies on them. * Avoid adding anything more than once. */ static void ParseTrackInput(const char *name) { char *old; char *ep; char *fp = NULL; size_t name_len = strlen(name); old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp); if (old) { ep = old + strlen(old) - name_len; /* does it contain name? */ for (; old != NULL; old = strchr(old, ' ')) { if (*old == ' ') old++; if (old >= ep) break; /* cannot contain name */ if (memcmp(old, name, name_len) == 0 && (old[name_len] == 0 || old[name_len] == ' ')) goto cleanup; } } Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL); cleanup: if (fp) { free(fp); } } /*- *--------------------------------------------------------------------- * Parse_setInput -- * Start Parsing from the given source * * Results: * None * * Side Effects: * A structure is added to the includes Lst and readProc, lineno, * fname and curFile are altered for the new file *--------------------------------------------------------------------- */ void Parse_SetInput(const char *name, int line, int fd, char *(*nextbuf)(void *, size_t *), void *arg) { char *buf; size_t len; if (name == NULL) name = curFile->fname; else ParseTrackInput(name); if (DEBUG(PARSE)) fprintf(debug_file, "%s: file %s, line %d, fd %d, nextbuf %p, arg %p\n", __func__, name, line, fd, nextbuf, arg); if (fd == -1 && nextbuf == NULL) /* sanity */ return; if (curFile != NULL) /* Save exiting file info */ Lst_AtFront(includes, curFile); /* Allocate and fill in new structure */ curFile = bmake_malloc(sizeof *curFile); /* * Once the previous state has been saved, we can get down to reading * the new file. We set up the name of the file to be the absolute * name of the include file so error messages refer to the right * place. */ curFile->fname = bmake_strdup(name); curFile->lineno = line; curFile->first_lineno = line; curFile->nextbuf = nextbuf; curFile->nextbuf_arg = arg; curFile->lf = NULL; curFile->depending = doing_depend; /* restore this on EOF */ assert(nextbuf != NULL); /* Get first block of input data */ buf = curFile->nextbuf(curFile->nextbuf_arg, &len); if (buf == NULL) { /* Was all a waste of time ... */ if (curFile->fname) free(curFile->fname); free(curFile); return; } curFile->P_str = buf; curFile->P_ptr = buf; curFile->P_end = buf+len; curFile->cond_depth = Cond_save_depth(); ParseSetParseFile(name); } /*- *----------------------------------------------------------------------- * IsInclude -- * Check if the line is an include directive * * Results: * TRUE if it is. * * Side Effects: * None * *----------------------------------------------------------------------- */ static Boolean IsInclude(const char *line, Boolean sysv) { static const char inc[] = "include"; static const size_t inclen = sizeof(inc) - 1; // 'd' is not valid for sysv int o = strchr(&("ds-"[sysv]), *line) != NULL; if (strncmp(line + o, inc, inclen) != 0) return FALSE; // Space is not mandatory for BSD .include return !sysv || isspace((unsigned char)line[inclen + o]); } #ifdef SYSVINCLUDE /*- *----------------------------------------------------------------------- * IsSysVInclude -- * Check if the line is a SYSV include directive * * Results: * TRUE if it is. * * Side Effects: * None * *----------------------------------------------------------------------- */ static Boolean IsSysVInclude(const char *line) { const char *p; if (!IsInclude(line, TRUE)) return FALSE; /* Avoid interpeting a dependency line as an include */ for (p = line; (p = strchr(p, ':')) != NULL;) { if (*++p == '\0') { /* end of line -> dependency */ return FALSE; } if (*p == ':' || isspace((unsigned char)*p)) { /* :: operator or ': ' -> dependency */ return FALSE; } } return TRUE; } /*- *--------------------------------------------------------------------- * ParseTraditionalInclude -- * Push to another file. * * The input is the current line. The file name(s) are * following the "include". * * Results: * None * * Side Effects: * A structure is added to the includes Lst and readProc, lineno, * fname and curFILE are altered for the new file *--------------------------------------------------------------------- */ static void ParseTraditionalInclude(char *line) { char *cp; /* current position in file spec */ int done = 0; int silent = (line[0] != 'i') ? 1 : 0; char *file = &line[silent + 7]; char *all_files; if (DEBUG(PARSE)) { fprintf(debug_file, "%s: %s\n", __func__, file); } /* * Skip over whitespace */ while (isspace((unsigned char)*file)) file++; /* * Substitute for any variables in the file name before trying to * find the thing. */ all_files = Var_Subst(NULL, file, VAR_CMD, VARF_WANTRES); if (*file == '\0') { Parse_Error(PARSE_FATAL, "Filename missing from \"include\""); goto out; } for (file = all_files; !done; file = cp + 1) { /* Skip to end of line or next whitespace */ for (cp = file; *cp && !isspace((unsigned char) *cp); cp++) continue; if (*cp) *cp = '\0'; else done = 1; Parse_include_file(file, FALSE, FALSE, silent); } out: free(all_files); } #endif #ifdef GMAKEEXPORT /*- *--------------------------------------------------------------------- * ParseGmakeExport -- * Parse export = * * And set the environment with it. * * Results: * None * * Side Effects: * None *--------------------------------------------------------------------- */ static void ParseGmakeExport(char *line) { char *variable = &line[6]; char *value; if (DEBUG(PARSE)) { fprintf(debug_file, "%s: %s\n", __func__, variable); } /* * Skip over whitespace */ while (isspace((unsigned char)*variable)) variable++; for (value = variable; *value && *value != '='; value++) continue; if (*value != '=') { Parse_Error(PARSE_FATAL, "Variable/Value missing from \"export\""); return; } *value++ = '\0'; /* terminate variable */ /* * Expand the value before putting it in the environment. */ value = Var_Subst(NULL, value, VAR_CMD, VARF_WANTRES); setenv(variable, value, 1); free(value); } #endif /*- *--------------------------------------------------------------------- * ParseEOF -- * Called when EOF is reached in the current file. If we were reading * an include file, the includes stack is popped and things set up * to go back to reading the previous file at the previous location. * * Results: * CONTINUE if there's more to do. DONE if not. * * Side Effects: * The old curFILE, is closed. The includes list is shortened. * lineno, curFILE, and fname are changed if CONTINUE is returned. *--------------------------------------------------------------------- */ static int ParseEOF(void) { char *ptr; size_t len; assert(curFile->nextbuf != NULL); doing_depend = curFile->depending; /* restore this */ /* get next input buffer, if any */ ptr = curFile->nextbuf(curFile->nextbuf_arg, &len); curFile->P_ptr = ptr; curFile->P_str = ptr; curFile->P_end = ptr + len; curFile->lineno = curFile->first_lineno; if (ptr != NULL) { /* Iterate again */ return CONTINUE; } /* Ensure the makefile (or loop) didn't have mismatched conditionals */ Cond_restore_depth(curFile->cond_depth); if (curFile->lf != NULL) { loadedfile_destroy(curFile->lf); curFile->lf = NULL; } /* Dispose of curFile info */ /* Leak curFile->fname because all the gnodes have pointers to it */ free(curFile->P_str); free(curFile); curFile = Lst_DeQueue(includes); if (curFile == NULL) { /* We've run out of input */ Var_Delete(".PARSEDIR", VAR_GLOBAL); Var_Delete(".PARSEFILE", VAR_GLOBAL); Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL); Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL); return DONE; } if (DEBUG(PARSE)) fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n", curFile->fname, curFile->lineno); /* Restore the PARSEDIR/PARSEFILE variables */ ParseSetParseFile(curFile->fname); return (CONTINUE); } #define PARSE_RAW 1 #define PARSE_SKIP 2 static char * ParseGetLine(int flags, int *length) { IFile *cf = curFile; char *ptr; char ch; char *line; char *line_end; char *escaped; char *comment; char *tp; /* Loop through blank lines and comment lines */ for (;;) { cf->lineno++; line = cf->P_ptr; ptr = line; line_end = line; escaped = NULL; comment = NULL; for (;;) { if (cf->P_end != NULL && ptr == cf->P_end) { /* end of buffer */ ch = 0; break; } ch = *ptr; if (ch == 0 || (ch == '\\' && ptr[1] == 0)) { if (cf->P_end == NULL) /* End of string (aka for loop) data */ break; /* see if there is more we can parse */ while (ptr++ < cf->P_end) { if ((ch = *ptr) == '\n') { if (ptr > line && ptr[-1] == '\\') continue; Parse_Error(PARSE_WARNING, "Zero byte read from file, skipping rest of line."); break; } } if (cf->nextbuf != NULL) { /* * End of this buffer; return EOF and outer logic * will get the next one. (eww) */ break; } Parse_Error(PARSE_FATAL, "Zero byte read from file"); return NULL; } if (ch == '\\') { /* Don't treat next character as special, remember first one */ if (escaped == NULL) escaped = ptr; if (ptr[1] == '\n') cf->lineno++; ptr += 2; line_end = ptr; continue; } if (ch == '#' && comment == NULL) { /* Remember first '#' for comment stripping */ /* Unless previous char was '[', as in modifier :[#] */ if (!(ptr > line && ptr[-1] == '[')) comment = line_end; } ptr++; if (ch == '\n') break; if (!isspace((unsigned char)ch)) /* We are not interested in trailing whitespace */ line_end = ptr; } /* Save next 'to be processed' location */ cf->P_ptr = ptr; /* Check we have a non-comment, non-blank line */ if (line_end == line || comment == line) { if (ch == 0) /* At end of file */ return NULL; /* Parse another line */ continue; } /* We now have a line of data */ *line_end = 0; if (flags & PARSE_RAW) { /* Leave '\' (etc) in line buffer (eg 'for' lines) */ *length = line_end - line; return line; } if (flags & PARSE_SKIP) { /* Completely ignore non-directives */ if (line[0] != '.') continue; /* We could do more of the .else/.elif/.endif checks here */ } break; } /* Brutally ignore anything after a non-escaped '#' in non-commands */ if (comment != NULL && line[0] != '\t') { line_end = comment; *line_end = 0; } /* If we didn't see a '\\' then the in-situ data is fine */ if (escaped == NULL) { *length = line_end - line; return line; } /* Remove escapes from '\n' and '#' */ tp = ptr = escaped; escaped = line; for (; ; *tp++ = ch) { ch = *ptr++; if (ch != '\\') { if (ch == 0) break; continue; } ch = *ptr++; if (ch == 0) { /* Delete '\\' at end of buffer */ tp--; break; } if (ch == '#' && line[0] != '\t') /* Delete '\\' from before '#' on non-command lines */ continue; if (ch != '\n') { /* Leave '\\' in buffer for later */ *tp++ = '\\'; /* Make sure we don't delete an escaped ' ' from the line end */ escaped = tp + 1; continue; } /* Escaped '\n' replace following whitespace with a single ' ' */ while (ptr[0] == ' ' || ptr[0] == '\t') ptr++; ch = ' '; } /* Delete any trailing spaces - eg from empty continuations */ while (tp > escaped && isspace((unsigned char)tp[-1])) tp--; *tp = 0; *length = tp - line; return line; } /*- *--------------------------------------------------------------------- * ParseReadLine -- * Read an entire line from the input file. Called only by Parse_File. * * Results: * A line w/o its newline * * Side Effects: * Only those associated with reading a character *--------------------------------------------------------------------- */ static char * ParseReadLine(void) { char *line; /* Result */ int lineLength; /* Length of result */ int lineno; /* Saved line # */ int rval; for (;;) { line = ParseGetLine(0, &lineLength); if (line == NULL) return NULL; if (line[0] != '.') return line; /* * The line might be a conditional. Ask the conditional module * about it and act accordingly */ switch (Cond_Eval(line)) { case COND_SKIP: /* Skip to next conditional that evaluates to COND_PARSE. */ do { line = ParseGetLine(PARSE_SKIP, &lineLength); } while (line && Cond_Eval(line) != COND_PARSE); if (line == NULL) break; continue; case COND_PARSE: continue; case COND_INVALID: /* Not a conditional line */ /* Check for .for loops */ rval = For_Eval(line); if (rval == 0) /* Not a .for line */ break; if (rval < 0) /* Syntax error - error printed, ignore line */ continue; /* Start of a .for loop */ lineno = curFile->lineno; /* Accumulate loop lines until matching .endfor */ do { line = ParseGetLine(PARSE_RAW, &lineLength); if (line == NULL) { Parse_Error(PARSE_FATAL, "Unexpected end of file in for loop."); break; } } while (For_Accum(line)); /* Stash each iteration as a new 'input file' */ For_Run(lineno); /* Read next line from for-loop buffer */ continue; } return (line); } } /*- *----------------------------------------------------------------------- * ParseFinishLine -- * Handle the end of a dependency group. * * Results: * Nothing. * * Side Effects: * inLine set FALSE. 'targets' list destroyed. * *----------------------------------------------------------------------- */ static void ParseFinishLine(void) { if (inLine) { Lst_ForEach(targets, Suff_EndTransform, NULL); Lst_Destroy(targets, ParseHasCommands); targets = NULL; inLine = FALSE; } } /*- *--------------------------------------------------------------------- * Parse_File -- * Parse a file into its component parts, incorporating it into the * current dependency graph. This is the main function and controls * almost every other function in this module * * Input: * name the name of the file being read * fd Open file to makefile to parse * * Results: * None * * Side Effects: * closes fd. * Loads. Nodes are added to the list of all targets, nodes and links * are added to the dependency graph. etc. etc. etc. *--------------------------------------------------------------------- */ void Parse_File(const char *name, int fd) { char *cp; /* pointer into the line */ char *line; /* the line we're working on */ struct loadedfile *lf; lf = loadfile(name, fd); inLine = FALSE; fatals = 0; if (name == NULL) { name = "(stdin)"; } Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf); curFile->lf = lf; do { for (; (line = ParseReadLine()) != NULL; ) { if (DEBUG(PARSE)) fprintf(debug_file, "ParseReadLine (%d): '%s'\n", curFile->lineno, line); if (*line == '.') { /* * Lines that begin with the special character may be * include or undef directives. * On the other hand they can be suffix rules (.c.o: ...) * or just dependencies for filenames that start '.'. */ for (cp = line + 1; isspace((unsigned char)*cp); cp++) { continue; } if (IsInclude(cp, FALSE)) { ParseDoInclude(cp); continue; } if (strncmp(cp, "undef", 5) == 0) { char *cp2; for (cp += 5; isspace((unsigned char) *cp); cp++) continue; for (cp2 = cp; !isspace((unsigned char) *cp2) && (*cp2 != '\0'); cp2++) continue; *cp2 = '\0'; Var_Delete(cp, VAR_GLOBAL); continue; } else if (strncmp(cp, "export", 6) == 0) { for (cp += 6; isspace((unsigned char) *cp); cp++) continue; Var_Export(cp, 1); continue; } else if (strncmp(cp, "unexport", 8) == 0) { Var_UnExport(cp); continue; } else if (strncmp(cp, "info", 4) == 0 || strncmp(cp, "error", 5) == 0 || strncmp(cp, "warning", 7) == 0) { if (ParseMessage(cp)) continue; } } if (*line == '\t') { /* * If a line starts with a tab, it can only hope to be * a creation command. */ cp = line + 1; shellCommand: for (; isspace ((unsigned char)*cp); cp++) { continue; } if (*cp) { if (!inLine) Parse_Error(PARSE_FATAL, "Unassociated shell command \"%s\"", cp); /* * So long as it's not a blank line and we're actually * in a dependency spec, add the command to the list of * commands of all targets in the dependency spec */ if (targets) { cp = bmake_strdup(cp); Lst_ForEach(targets, ParseAddCmd, cp); #ifdef CLEANUP Lst_AtEnd(targCmds, cp); #endif } } continue; } #ifdef SYSVINCLUDE if (IsSysVInclude(line)) { /* * It's an S3/S5-style "include". */ ParseTraditionalInclude(line); continue; } #endif #ifdef GMAKEEXPORT if (strncmp(line, "export", 6) == 0 && isspace((unsigned char) line[6]) && strchr(line, ':') == NULL) { /* * It's a Gmake "export". */ ParseGmakeExport(line); continue; } #endif if (Parse_IsVar(line)) { ParseFinishLine(); Parse_DoVar(line, VAR_GLOBAL); continue; } #ifndef POSIX /* * To make life easier on novices, if the line is indented we * first make sure the line has a dependency operator in it. * If it doesn't have an operator and we're in a dependency * line's script, we assume it's actually a shell command * and add it to the current list of targets. */ cp = line; if (isspace((unsigned char) line[0])) { while ((*cp != '\0') && isspace((unsigned char) *cp)) cp++; while (*cp && (ParseIsEscaped(line, cp) || (*cp != ':') && (*cp != '!'))) { cp++; } if (*cp == '\0') { if (inLine) { Parse_Error(PARSE_WARNING, "Shell command needs a leading tab"); goto shellCommand; } } } #endif ParseFinishLine(); /* * For some reason - probably to make the parser impossible - * a ';' can be used to separate commands from dependencies. * Attempt to avoid ';' inside substitution patterns. */ { int level = 0; for (cp = line; *cp != 0; cp++) { if (*cp == '\\' && cp[1] != 0) { cp++; continue; } if (*cp == '$' && (cp[1] == '(' || cp[1] == '{')) { level++; continue; } if (level > 0) { if (*cp == ')' || *cp == '}') { level--; continue; } } else if (*cp == ';') { break; } } } if (*cp != 0) /* Terminate the dependency list at the ';' */ *cp++ = 0; else cp = NULL; /* * We now know it's a dependency line so it needs to have all * variables expanded before being parsed. Tell the variable * module to complain if some variable is undefined... */ line = Var_Subst(NULL, line, VAR_CMD, VARF_UNDEFERR|VARF_WANTRES); /* * Need a non-circular list for the target nodes */ if (targets) Lst_Destroy(targets, NULL); targets = Lst_Init(FALSE); inLine = TRUE; ParseDoDependency(line); free(line); /* If there were commands after a ';', add them now */ if (cp != NULL) { goto shellCommand; } } /* * Reached EOF, but it may be just EOF of an include file... */ } while (ParseEOF() == CONTINUE); if (fatals) { (void)fflush(stdout); (void)fprintf(stderr, "%s: Fatal errors encountered -- cannot continue", progname); PrintOnError(NULL, NULL); exit(1); } } /*- *--------------------------------------------------------------------- * Parse_Init -- * initialize the parsing module * * Results: * none * * Side Effects: * the parseIncPath list is initialized... *--------------------------------------------------------------------- */ void Parse_Init(void) { mainNode = NULL; parseIncPath = Lst_Init(FALSE); sysIncPath = Lst_Init(FALSE); defIncPath = Lst_Init(FALSE); includes = Lst_Init(FALSE); #ifdef CLEANUP targCmds = Lst_Init(FALSE); #endif } void Parse_End(void) { #ifdef CLEANUP Lst_Destroy(targCmds, (FreeProc *)free); if (targets) Lst_Destroy(targets, NULL); Lst_Destroy(defIncPath, Dir_Destroy); Lst_Destroy(sysIncPath, Dir_Destroy); Lst_Destroy(parseIncPath, Dir_Destroy); Lst_Destroy(includes, NULL); /* Should be empty now */ #endif } /*- *----------------------------------------------------------------------- * Parse_MainName -- * Return a Lst of the main target to create for main()'s sake. If * no such target exists, we Punt with an obnoxious error message. * * Results: * A Lst of the single node to create. * * Side Effects: * None. * *----------------------------------------------------------------------- */ Lst Parse_MainName(void) { Lst mainList; /* result list */ mainList = Lst_Init(FALSE); if (mainNode == NULL) { Punt("no target to make."); /*NOTREACHED*/ } else if (mainNode->type & OP_DOUBLEDEP) { (void)Lst_AtEnd(mainList, mainNode); Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW); } else (void)Lst_AtEnd(mainList, mainNode); Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL); return (mainList); } /*- *----------------------------------------------------------------------- * ParseMark -- * Add the filename and lineno to the GNode so that we remember * where it was first defined. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static void ParseMark(GNode *gn) { gn->fname = curFile->fname; gn->lineno = curFile->lineno; } Index: stable/12/contrib/bmake/str.c =================================================================== --- stable/12/contrib/bmake/str.c (revision 361673) +++ stable/12/contrib/bmake/str.c (revision 361674) @@ -1,526 +1,540 @@ -/* $NetBSD: str.c,v 1.38 2017/04/21 22:15:44 sjg Exp $ */ +/* $NetBSD: str.c,v 1.42 2020/05/06 02:30:10 christos Exp $ */ /*- * Copyright (c) 1988, 1989, 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MAKE_NATIVE -static char rcsid[] = "$NetBSD: str.c,v 1.38 2017/04/21 22:15:44 sjg Exp $"; +static char rcsid[] = "$NetBSD: str.c,v 1.42 2020/05/06 02:30:10 christos Exp $"; #else #include #ifndef lint #if 0 static char sccsid[] = "@(#)str.c 5.8 (Berkeley) 6/1/90"; #else -__RCSID("$NetBSD: str.c,v 1.38 2017/04/21 22:15:44 sjg Exp $"); +__RCSID("$NetBSD: str.c,v 1.42 2020/05/06 02:30:10 christos Exp $"); #endif #endif /* not lint */ #endif #include "make.h" /*- * str_concat -- * concatenate the two strings, inserting a space or slash between them, * freeing them if requested. * * returns -- * the resulting string in allocated space. */ char * str_concat(const char *s1, const char *s2, int flags) { int len1, len2; char *result; /* get the length of both strings */ len1 = strlen(s1); len2 = strlen(s2); /* allocate length plus separator plus EOS */ result = bmake_malloc((unsigned int)(len1 + len2 + 2)); /* copy first string into place */ memcpy(result, s1, len1); /* add separator character */ if (flags & STR_ADDSPACE) { result[len1] = ' '; ++len1; } else if (flags & STR_ADDSLASH) { result[len1] = '/'; ++len1; } /* copy second string plus EOS into place */ memcpy(result + len1, s2, len2 + 1); return(result); } /*- * brk_string -- * Fracture a string into an array of words (as delineated by tabs or * spaces) taking quotation marks into account. Leading tabs/spaces * are ignored. * * If expand is TRUE, quotes are removed and escape sequences * such as \r, \t, etc... are expanded. * * returns -- * Pointer to the array of pointers to the words. - * Memory containing the actual words in *buffer. + * Memory containing the actual words in *store_words_buf. * Both of these must be free'd by the caller. - * Number of words in *store_argc. + * Number of words in *store_words_len. */ char ** -brk_string(const char *str, int *store_argc, Boolean expand, char **buffer) +brk_string(const char *str, int *store_words_len, Boolean expand, + char **store_words_buf) { - int argc, ch; - char inquote, *start, *t; - const char *p; - int len; - int argmax = 50, curlen = 0; - char **argv; + char inquote; + const char *str_p; + size_t str_len; + char **words; + int words_len; + int words_cap = 50; + char *words_buf, *word_start, *word_end; /* skip leading space chars. */ for (; *str == ' ' || *str == '\t'; ++str) continue; - /* allocate room for a copy of the string */ - if ((len = strlen(str) + 1) > curlen) - *buffer = bmake_malloc(curlen = len); + /* words_buf holds the words, separated by '\0'. */ + str_len = strlen(str); + words_buf = bmake_malloc(strlen(str) + 1); - /* - * initial argmax based on len - */ - argmax = MAX((len / 5), 50); - argv = bmake_malloc((argmax + 1) * sizeof(char *)); + words_cap = MAX((str_len / 5), 50); + words = bmake_malloc((words_cap + 1) * sizeof(char *)); /* * copy the string; at the same time, parse backslashes, - * quotes and build the argument list. + * quotes and build the word list. */ - argc = 0; + words_len = 0; inquote = '\0'; - for (p = str, start = t = *buffer;; ++p) { - switch(ch = *p) { + word_start = word_end = words_buf; + for (str_p = str;; ++str_p) { + char ch = *str_p; + switch(ch) { case '"': case '\'': if (inquote) { if (inquote == ch) inquote = '\0'; else break; } else { inquote = (char) ch; /* Don't miss "" or '' */ - if (start == NULL && p[1] == inquote) { + if (word_start == NULL && str_p[1] == inquote) { if (!expand) { - start = t; - *t++ = ch; + word_start = word_end; + *word_end++ = ch; } else - start = t + 1; - p++; + word_start = word_end + 1; + str_p++; inquote = '\0'; break; } } if (!expand) { - if (!start) - start = t; - *t++ = ch; + if (word_start == NULL) + word_start = word_end; + *word_end++ = ch; } continue; case ' ': case '\t': case '\n': if (inquote) break; - if (!start) + if (word_start == NULL) continue; /* FALLTHROUGH */ case '\0': /* - * end of a token -- make sure there's enough argv + * end of a token -- make sure there's enough words * space and save off a pointer. */ - if (!start) + if (word_start == NULL) goto done; - *t++ = '\0'; - if (argc == argmax) { - argmax *= 2; /* ramp up fast */ - argv = (char **)bmake_realloc(argv, - (argmax + 1) * sizeof(char *)); + *word_end++ = '\0'; + if (words_len == words_cap) { + words_cap *= 2; /* ramp up fast */ + words = (char **)bmake_realloc(words, + (words_cap + 1) * sizeof(char *)); } - argv[argc++] = start; - start = NULL; + words[words_len++] = word_start; + word_start = NULL; if (ch == '\n' || ch == '\0') { if (expand && inquote) { - free(argv); - free(*buffer); - *buffer = NULL; + free(words); + free(words_buf); + *store_words_buf = NULL; return NULL; } goto done; } continue; case '\\': if (!expand) { - if (!start) - start = t; - *t++ = '\\'; - if (*(p+1) == '\0') /* catch '\' at end of line */ + if (word_start == NULL) + word_start = word_end; + *word_end++ = '\\'; + /* catch '\' at end of line */ + if (str_p[1] == '\0') continue; - ch = *++p; + ch = *++str_p; break; } - switch (ch = *++p) { + switch (ch = *++str_p) { case '\0': case '\n': /* hmmm; fix it up as best we can */ ch = '\\'; - --p; + --str_p; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; } break; } - if (!start) - start = t; - *t++ = (char) ch; + if (word_start == NULL) + word_start = word_end; + *word_end++ = ch; } -done: argv[argc] = NULL; - *store_argc = argc; - return(argv); +done: words[words_len] = NULL; + *store_words_len = words_len; + *store_words_buf = words_buf; + return words; } /* * Str_FindSubstring -- See if a string contains a particular substring. * * Input: * string String to search. * substring Substring to find in string. * * Results: If string contains substring, the return value is the location of * the first matching instance of substring in string. If string doesn't * contain substring, the return value is NULL. Matching is done on an exact * character-for-character basis with no wildcards or special characters. * * Side effects: None. */ char * Str_FindSubstring(const char *string, const char *substring) { const char *a, *b; /* * First scan quickly through the two strings looking for a single- * character match. When it's found, then compare the rest of the * substring. */ for (b = substring; *string != 0; string += 1) { if (*string != *b) continue; a = string; for (;;) { if (*b == 0) return UNCONST(string); if (*a++ != *b++) break; } b = substring; } return NULL; } /* * Str_Match -- * * See if a particular string matches a particular pattern. * * Results: Non-zero is returned if string matches pattern, 0 otherwise. The * matching operation permits the following special characters in the * pattern: *?\[] (see the man page for details on what these mean). * * XXX this function does not detect or report malformed patterns. * * Side effects: None. */ int Str_Match(const char *string, const char *pattern) { char c2; for (;;) { /* * See if we're at the end of both the pattern and the * string. If, we succeeded. If we're at the end of the * pattern but not at the end of the string, we failed. */ if (*pattern == 0) return(!*string); if (*string == 0 && *pattern != '*') return(0); /* * Check for a "*" as the next pattern character. It matches * any substring. We handle this by calling ourselves * recursively for each postfix of string, until either we * match or we reach the end of the string. */ if (*pattern == '*') { pattern += 1; if (*pattern == 0) return(1); while (*string != 0) { if (Str_Match(string, pattern)) return(1); ++string; } return(0); } /* * Check for a "?" as the next pattern character. It matches * any single character. */ if (*pattern == '?') goto thisCharOK; /* * Check for a "[" as the next pattern character. It is * followed by a list of characters that are acceptable, or * by a range (two characters separated by "-"). */ if (*pattern == '[') { int nomatch; ++pattern; if (*pattern == '^') { ++pattern; nomatch = 1; } else nomatch = 0; for (;;) { if ((*pattern == ']') || (*pattern == 0)) { if (nomatch) break; return(0); } if (*pattern == *string) break; if (pattern[1] == '-') { c2 = pattern[2]; if (c2 == 0) return(nomatch); if ((*pattern <= *string) && (c2 >= *string)) break; if ((*pattern >= *string) && (c2 <= *string)) break; pattern += 2; } ++pattern; } if (nomatch && (*pattern != ']') && (*pattern != 0)) return 0; while ((*pattern != ']') && (*pattern != 0)) ++pattern; + if (*pattern == 0) + --pattern; goto thisCharOK; } /* * If the next pattern character is '/', just strip off the * '/' so we do exact matching on the character that follows. */ if (*pattern == '\\') { ++pattern; if (*pattern == 0) return(0); } /* * There's no special character. Just make sure that the * next characters of each string match. */ if (*pattern != *string) return(0); thisCharOK: ++pattern; ++string; } } /*- *----------------------------------------------------------------------- * Str_SYSVMatch -- * Check word against pattern for a match (% is wild), * * Input: * word Word to examine * pattern Pattern to examine against * len Number of characters to substitute * * Results: * Returns the beginning position of a match or null. The number * of characters matched is returned in len. * * Side Effects: * None * *----------------------------------------------------------------------- */ char * -Str_SYSVMatch(const char *word, const char *pattern, int *len) +Str_SYSVMatch(const char *word, const char *pattern, size_t *len, + Boolean *hasPercent) { const char *p = pattern; const char *w = word; const char *m; + *hasPercent = FALSE; if (*p == '\0') { /* Null pattern is the whole string */ *len = strlen(w); return UNCONST(w); } if ((m = strchr(p, '%')) != NULL) { + *hasPercent = TRUE; + if (*w == '\0') { + /* empty word does not match pattern */ + return NULL; + } /* check that the prefix matches */ for (; p != m && *w && *w == *p; w++, p++) continue; if (p != m) return NULL; /* No match */ if (*++p == '\0') { /* No more pattern, return the rest of the string */ *len = strlen(w); return UNCONST(w); } } m = w; /* Find a matching tail */ do if (strcmp(p, w) == 0) { *len = w - m; return UNCONST(m); } while (*w++ != '\0'); return NULL; } /*- *----------------------------------------------------------------------- * Str_SYSVSubst -- * Substitute '%' on the pattern with len characters from src. * If the pattern does not contain a '%' prepend len characters * from src. * * Results: * None * * Side Effects: * Places result on buf * *----------------------------------------------------------------------- */ void -Str_SYSVSubst(Buffer *buf, char *pat, char *src, int len) +Str_SYSVSubst(Buffer *buf, char *pat, char *src, size_t len, + Boolean lhsHasPercent) { char *m; - if ((m = strchr(pat, '%')) != NULL) { + if ((m = strchr(pat, '%')) != NULL && lhsHasPercent) { /* Copy the prefix */ Buf_AddBytes(buf, m - pat, pat); /* skip the % */ pat = m + 1; } - - /* Copy the pattern */ - Buf_AddBytes(buf, len, src); + if (m != NULL || !lhsHasPercent) { + /* Copy the pattern */ + Buf_AddBytes(buf, len, src); + } /* append the rest */ Buf_AddBytes(buf, strlen(pat), pat); } Index: stable/12/contrib/bmake/unit-tests/Makefile.in =================================================================== --- stable/12/contrib/bmake/unit-tests/Makefile.in (revision 361673) +++ stable/12/contrib/bmake/unit-tests/Makefile.in (nonexistent) @@ -1,151 +0,0 @@ -# $Id: Makefile.in,v 1.48 2015/12/07 04:06:29 sjg Exp $ -# -# $NetBSD: Makefile,v 1.52 2015/05/05 21:51:09 sjg Exp $ -# -# Unit tests for make(1) -# The main targets are: -# -# all: run all the tests -# test: run 'all', and compare to expected results -# accept: move generated output to expected results -# -# Adding a test case. -# Each feature should get its own set of tests in its own suitably -# named makefile (*.mk), with its own set of expected results (*.exp), -# and it should be added to the TESTNAMES list. -# - -srcdir= @srcdir@ - -.MAIN: all - -UNIT_TESTS:= ${srcdir} -.PATH: ${UNIT_TESTS} - -# Each test is in a sub-makefile. -# Keep the list sorted. -TESTNAMES= \ - comment \ - cond1 \ - cond2 \ - error \ - export \ - export-all \ - export-env \ - doterror \ - dotwait \ - forloop \ - forsubst \ - hash \ - misc \ - moderrs \ - modmatch \ - modmisc \ - modorder \ - modts \ - modword \ - order \ - posix \ - qequals \ - sunshcmd \ - sysv \ - ternary \ - unexport \ - unexport-env \ - varcmd \ - varmisc \ - varshell - -# these tests were broken by referting POSIX chanegs -STRICT_POSIX_TESTS = \ - escape \ - impsrc \ - phony-end \ - posix1 \ - suffixes - -# Override make flags for certain tests -flags.doterror= -flags.order=-j1 - -OUTFILES= ${TESTNAMES:S/$/.out/} - -all: ${OUTFILES} - -CLEANFILES += *.rawout *.out *.status *.tmp *.core *.tmp -CLEANFILES += obj*.[och] lib*.a # posix1.mk -CLEANFILES += issue* .[ab]* # suffixes.mk -CLEANRECURSIVE += dir dummy # posix1.mk - -clean: - rm -f ${CLEANFILES} -.if !empty(CLEANRECURSIVE) - rm -rf ${CLEANRECURSIVE} -.endif - -TEST_MAKE?= ${.MAKE} -TOOL_SED?= sed -TOOL_TR?= tr -TOOL_DIFF?= diff -DIFF_FLAGS?= @diff_u@ - -.if defined(.PARSEDIR) -# ensure consistent results from sort(1) -LC_ALL= C -LANG= C -.export LANG LC_ALL -.endif - -# some tests need extra post-processing -SED_CMDS.varshell = -e 's,^[a-z]*sh: ,,' \ - -e '/command/s,No such.*,not found,' - -# the tests are actually done with sub-makes. -.SUFFIXES: .mk .rawout .out -.mk.rawout: - @echo ${TEST_MAKE} ${flags.${.TARGET:R}:U-k} -f ${.IMPSRC} - -@cd ${.OBJDIR} && \ - { ${TEST_MAKE} ${flags.${.TARGET:R}:U-k} -f ${.IMPSRC} \ - 2>&1 ; echo $$? >${.TARGET:R}.status ; } > ${.TARGET}.tmp - @mv ${.TARGET}.tmp ${.TARGET} - -# We always pretend .MAKE was called 'make' -# and strip ${.CURDIR}/ from the output -# and replace anything after 'stopped in' with unit-tests -# so the results can be compared. -.rawout.out: - @echo postprocess ${.TARGET} - @${TOOL_SED} -e 's,^${TEST_MAKE:T:C/\./\\\./g}[][0-9]*:,make:,' \ - -e 's,${TEST_MAKE:C/\./\\\./g},make,' \ - -e '/stopped/s, /.*, unit-tests,' \ - -e 's,${.CURDIR:C/\./\\\./g}/,,g' \ - -e 's,${UNIT_TESTS:C/\./\\\./g}/,,g' ${SED_CMDS.${.TARGET:T:R}} \ - < ${.IMPSRC} > ${.TARGET}.tmp - @echo "exit status `cat ${.TARGET:R}.status`" >> ${.TARGET}.tmp - @mv ${.TARGET}.tmp ${.TARGET} - -# Compare all output files -test: ${OUTFILES} .PHONY - @failed= ; \ - for test in ${TESTNAMES}; do \ - ${TOOL_DIFF} ${DIFF_FLAGS} ${UNIT_TESTS}/$${test}.exp $${test}.out \ - || failed="$${failed}$${failed:+ }$${test}" ; \ - done ; \ - if [ -n "$${failed}" ]; then \ - echo "Failed tests: $${failed}" ; false ; \ - else \ - echo "All tests passed" ; \ - fi - -accept: - @for test in ${TESTNAMES}; do \ - cmp -s ${UNIT_TESTS}/$${test}.exp $${test}.out \ - || { echo "Replacing $${test}.exp" ; \ - cp $${test}.out ${UNIT_TESTS}/$${test}.exp ; } \ - done - -.if exists(${TEST_MAKE}) -${TESTNAMES:S/$/.rawout/}: ${TEST_MAKE} -.endif - -.-include Property changes on: stable/12/contrib/bmake/unit-tests/Makefile.in ___________________________________________________________________ Deleted: svn:eol-style ## -1 +0,0 ## -native \ No newline at end of property Deleted: svn:keywords ## -1 +0,0 ## -FreeBSD=%H \ No newline at end of property Deleted: svn:mime-type ## -1 +0,0 ## -text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/Makefile =================================================================== --- stable/12/contrib/bmake/unit-tests/Makefile (nonexistent) +++ stable/12/contrib/bmake/unit-tests/Makefile (revision 361674) @@ -0,0 +1,155 @@ +# $Id: Makefile,v 1.54 2020/05/17 17:26:14 sjg Exp $ +# +# $NetBSD: Makefile,v 1.58 2020/05/17 12:36:26 rillig Exp $ +# +# Unit tests for make(1) +# The main targets are: +# +# all: run all the tests +# test: run 'all', and compare to expected results +# accept: move generated output to expected results +# +# Adding a test case. +# Each feature should get its own set of tests in its own suitably +# named makefile (*.mk), with its own set of expected results (*.exp), +# and it should be added to the TESTNAMES list. +# + +.MAIN: all + +.-include "Makefile.config" + +UNIT_TESTS:= ${.PARSEDIR} +.PATH: ${UNIT_TESTS} + +# Each test is in a sub-makefile. +# Keep the list sorted. +TESTNAMES= \ + comment \ + cond-late \ + cond1 \ + cond2 \ + dollar \ + doterror \ + dotwait \ + error \ + export \ + export-all \ + export-env \ + forloop \ + forsubst \ + hash \ + include-main \ + misc \ + moderrs \ + modmatch \ + modmisc \ + modorder \ + modts \ + modword \ + order \ + posix \ + qequals \ + sunshcmd \ + sysv \ + ternary \ + unexport \ + unexport-env \ + varcmd \ + varmisc \ + varmod-edge \ + varquote \ + varshell + +# these tests were broken by referting POSIX chanegs +STRICT_POSIX_TESTS = \ + escape \ + impsrc \ + phony-end \ + posix1 \ + suffixes + +# Override make flags for certain tests +flags.doterror= +flags.order=-j1 + +OUTFILES= ${TESTNAMES:S/$/.out/} + +all: ${OUTFILES} + +CLEANFILES += *.rawout *.out *.status *.tmp *.core *.tmp +CLEANFILES += obj*.[och] lib*.a # posix1.mk +CLEANFILES += issue* .[ab]* # suffixes.mk +CLEANRECURSIVE += dir dummy # posix1.mk + +clean: + rm -f ${CLEANFILES} +.if !empty(CLEANRECURSIVE) + rm -rf ${CLEANRECURSIVE} +.endif + +TEST_MAKE?= ${.MAKE} +TOOL_SED?= sed +TOOL_TR?= tr +TOOL_DIFF?= diff + +.if defined(.PARSEDIR) +# ensure consistent results from sort(1) +LC_ALL= C +LANG= C +.export LANG LC_ALL +.endif + +# some tests need extra post-processing +SED_CMDS.varshell = -e 's,^[a-z]*sh: ,,' \ + -e '/command/s,No such.*,not found,' + +# the tests are actually done with sub-makes. +.SUFFIXES: .mk .rawout .out +.mk.rawout: + @echo ${TEST_MAKE} ${flags.${.TARGET:R}:U-k} -f ${.IMPSRC} + -@cd ${.OBJDIR} && \ + { ${TEST_MAKE} ${flags.${.TARGET:R}:U-k} -f ${.IMPSRC} \ + 2>&1 ; echo $$? >${.TARGET:R}.status ; } > ${.TARGET}.tmp + @mv ${.TARGET}.tmp ${.TARGET} + +# We always pretend .MAKE was called 'make' +# and strip ${.CURDIR}/ from the output +# and replace anything after 'stopped in' with unit-tests +# so the results can be compared. +.rawout.out: + @echo postprocess ${.TARGET} + @${TOOL_SED} -e 's,^${TEST_MAKE:T:C/\./\\\./g}[][0-9]*:,make:,' \ + -e 's,${TEST_MAKE:C/\./\\\./g},make,' \ + -e '/stopped/s, /.*, unit-tests,' \ + -e 's,${.CURDIR:C/\./\\\./g}/,,g' \ + -e 's,${UNIT_TESTS:C/\./\\\./g}/,,g' ${SED_CMDS.${.TARGET:T:R}} \ + < ${.IMPSRC} > ${.TARGET}.tmp + @echo "exit status `cat ${.TARGET:R}.status`" >> ${.TARGET}.tmp + @mv ${.TARGET}.tmp ${.TARGET} + +# Compare all output files +test: ${OUTFILES} .PHONY + @failed= ; \ + for test in ${TESTNAMES}; do \ + ${TOOL_DIFF} ${DIFF_FLAGS} ${UNIT_TESTS}/$${test}.exp $${test}.out \ + || failed="$${failed}$${failed:+ }$${test}" ; \ + done ; \ + if [ -n "$${failed}" ]; then \ + echo "Failed tests: $${failed}" ; false ; \ + else \ + echo "All tests passed" ; \ + fi + +accept: + @for test in ${TESTNAMES}; do \ + cmp -s ${UNIT_TESTS}/$${test}.exp $${test}.out \ + || { echo "Replacing $${test}.exp" ; \ + cp $${test}.out ${UNIT_TESTS}/$${test}.exp ; } \ + done + +.if exists(${TEST_MAKE}) +${TESTNAMES:S/$/.rawout/}: ${TEST_MAKE} +.endif + +.-include Property changes on: stable/12/contrib/bmake/unit-tests/Makefile ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/Makefile.config.in =================================================================== --- stable/12/contrib/bmake/unit-tests/Makefile.config.in (nonexistent) +++ stable/12/contrib/bmake/unit-tests/Makefile.config.in (revision 361674) @@ -0,0 +1,4 @@ +# $Id: Makefile.config.in,v 1.1 2018/12/30 17:14:24 sjg Exp $ + +srcdir= @srcdir@ +DIFF_FLAGS?= @diff_u@ Property changes on: stable/12/contrib/bmake/unit-tests/Makefile.config.in ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/cond-late.exp =================================================================== --- stable/12/contrib/bmake/unit-tests/cond-late.exp (nonexistent) +++ stable/12/contrib/bmake/unit-tests/cond-late.exp (revision 361674) @@ -0,0 +1,3 @@ +yes +no +exit status 0 Index: stable/12/contrib/bmake/unit-tests/cond-late.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/cond-late.mk (nonexistent) +++ stable/12/contrib/bmake/unit-tests/cond-late.mk (revision 361674) @@ -0,0 +1,23 @@ +# $NetBSD: cond-late.mk,v 1.1 2020/04/29 23:15:21 rillig Exp $ +# +# Using the :? modifier, variable expressions can contain conditional +# expressions that are evaluated late. Any variables appearing in these +# conditions are expanded before parsing the condition. This is +# different from many other places. +# +# Because of this, variables that are used in these lazy conditions +# should not contain double-quotes, or the parser will probably fail. +# +# They should also not contain operators like == or <, since these are +# actually interpreted as these operators. This is demonstrated below. +# +# If the order of evaluation were to change to first parse the condition +# and then expand the variables, the output would change from the +# current "yes no" to "yes yes", since both variables are non-empty. + +COND.true= "yes" == "yes" +COND.false= "yes" != "yes" + +all: + @echo ${ ${COND.true} :?yes:no} + @echo ${ ${COND.false} :?yes:no} Property changes on: stable/12/contrib/bmake/unit-tests/cond-late.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/dollar.exp =================================================================== --- stable/12/contrib/bmake/unit-tests/dollar.exp (nonexistent) +++ stable/12/contrib/bmake/unit-tests/dollar.exp (revision 361674) @@ -0,0 +1,51 @@ + +Printing dollar from literals and variables + +To survive the parser, a dollar character must be doubled. + 1 dollar literal => + 1 dollar literal eol => <> + 2 dollar literal => <$> + 4 dollar literal => <$$> +Some hungry part of make eats all the dollars after a :U modifier. + 1 dollar default => <> + 2 dollar default => <> + 4 dollar default => <> +This works as expected. + 1 dollar variable => <> + 2 dollar variable => <$> + 4 dollar variable => <$$> +Some hungry part of make eats all the dollars after a :U modifier. + 1 dollar var-default => <> + 2 dollar var-default => <$> + 4 dollar var-default => <$$> + +Dollar in :S pattern + + S,$,word, => <$XYword> + S,$X,word, => <$XY> + S,$$X,word, => <$XY> + S,$$$X,word, => <$XY> + S,$X,replaced, => + S,$$X,replaced, => + S,$$$X,replaced, => + +Dollar in :C character class + +The A is replaced because the $$ is reduced to a single $, +which is then resolved to the variable X with the value VAR_X. +The effective character class becomes [VAR_XY]. + C,[$$XY],<&>,g => <$> + +Dollar in :C pattern + +For some reason, multiple dollars are folded into one. + C,$,dollar,g => <> + C,$$,dollar,g => <> + +Dollar in :S replacement + +For some reason, multiple dollars are folded into one. + S,word,a$Xo, => + S,word,a$$Xo, => + S,word,a$$$Xo, => +exit status 0 Index: stable/12/contrib/bmake/unit-tests/dollar.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/dollar.mk (nonexistent) +++ stable/12/contrib/bmake/unit-tests/dollar.mk (revision 361674) @@ -0,0 +1,81 @@ +# $NetBSD: dollar.mk,v 1.3 2020/05/17 09:37:48 rillig Exp $ +# +# Test the various places where a dollar character can appear and +# see what happens. There are lots of surprises here. +# + +LIST= plain 'single' "double" 'mix'"ed" back\ slashed +WORD= word + +DOLLAR1= $ +DOLLAR2= $$ +DOLLAR4= $$$$ + +X= VAR_X +DOLLAR_XY= $$XY +DOLLAR_AXY= $$AXY + +H= @header() { printf '\n%s\n\n' "$$*"; }; header +T= @testcase() { printf '%23s => <%s>\n' "$$@"; }; testcase +C= @comment() { printf '%s\n' "$$*"; }; comment + +# These variable values are not accessed. +# The trailing dollar in the '1 dollar literal eol' test case accesses +# the empty variable instead, which is always guaranteed to be empty. +${:U }= space-var-value +${:U${.newline}}= newline-var-value +# But this one is accessed. +${:U'}= single-quote-var-value' + +all: + $H 'Printing dollar from literals and variables' + + $C 'To survive the parser, a dollar character must be doubled.' + $T '1 dollar literal' '$' + $T '1 dollar literal eol' ''$ + $T '2 dollar literal' '$$' + $T '4 dollar literal' '$$$$' + + $C 'Some hungry part of make eats all the dollars after a :U modifier.' + $T '1 dollar default' ''${:U$:Q} + $T '2 dollar default' ''${:U$$:Q} + $T '4 dollar default' ''${:U$$$$:Q} + + $C 'This works as expected.' + $T '1 dollar variable' ''${DOLLAR1:Q} + $T '2 dollar variable' ''${DOLLAR2:Q} + $T '4 dollar variable' ''${DOLLAR4:Q} + + $C 'Some hungry part of make eats all the dollars after a :U modifier.' + $T '1 dollar var-default' ''${:U${DOLLAR1}:Q} + $T '2 dollar var-default' ''${:U${DOLLAR2}:Q} + $T '4 dollar var-default' ''${:U${DOLLAR4}:Q} + + $H 'Dollar in :S pattern' + + $T 'S,$$,word,' ''${DOLLAR_XY:S,$,word,:Q} + $T 'S,$$X,word,' ''${DOLLAR_XY:S,$X,word,:Q} + $T 'S,$$$$X,word,' ''${DOLLAR_XY:S,$$X,word,:Q} + $T 'S,$$$$$$X,word,' ''${DOLLAR_XY:S,$$$X,word,:Q} + + $T 'S,$$X,replaced,' ''${X:S,$X,replaced,:Q} + $T 'S,$$$$X,replaced,' ''${X:S,$$X,replaced,:Q} + $T 'S,$$$$$$X,replaced,' ''${X:S,$$$X,replaced,:Q} + + $H 'Dollar in :C character class' + + $C 'The A is replaced because the $$$$ is reduced to a single $$,' + $C 'which is then resolved to the variable X with the value VAR_X.' + $C 'The effective character class becomes [VAR_XY].' + $T 'C,[$$$$XY],<&>,g' ''${DOLLAR_AXY:C,[$$XY],<&>,g:Q} + + $H 'Dollar in :C pattern' + $C 'For some reason, multiple dollars are folded into one.' + $T 'C,$$,dollar,g' ''${DOLLAR:C,$,dollar,g:Q} + $T 'C,$$$$,dollar,g' ''${DOLLAR:C,$$,dollar,g:Q} + + $H 'Dollar in :S replacement' + $C 'For some reason, multiple dollars are folded into one.' + $T 'S,word,a$$Xo,' ''${WORD:S,word,a$Xo,:Q} + $T 'S,word,a$$$$Xo,' ''${WORD:S,word,a$$Xo,:Q} + $T 'S,word,a$$$$$$Xo,' ''${WORD:S,word,a$$$Xo,:Q} Property changes on: stable/12/contrib/bmake/unit-tests/dollar.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/escape.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/escape.mk (revision 361673) +++ stable/12/contrib/bmake/unit-tests/escape.mk (revision 361674) @@ -1,246 +1,246 @@ -# $Id: escape.mk,v 1.1.1.2 2014/11/06 01:40:37 sjg Exp $ +# $Id: escape.mk,v 1.1.1.3 2020/01/22 01:07:14 sjg Exp $ # # Test backslash escaping. # Extracts from the POSIX 2008 specification # : # # Comments start with a ( '#' ) and continue until an # unescaped is reached. # # When an escaped (one preceded by a ) is found # anywhere in the makefile except in a command line, an include # line, or a line immediately preceding an include line, it shall # be replaced, along with any leading white space on the following # line, with a single . # # When an escaped is found in a command line in a # makefile, the command line shall contain the , the # , and the next line, except that the first character of # the next line shall not be included if it is a . # # When an escaped is found in an include line or in a # line immediately preceding an include line, the behavior is # unspecified. # # Notice that the behaviour of or # is not mentioned. I think # this implies that should be taken literally everywhere # except before . # # Our practice, despite what POSIX might say, is that "\#" # in a variable assignment stores "#" as part of the value. # The "\" is not taken literally, and the "#" does not begin a comment. # # Also, our practice is that an even number of backslashes before a # newline in a variable assignment simply stores the backslashes as part # of the value, and treats the newline as though it was not escaped. -# Similarly, ann even number of backslashes before a newline in a -# command simply uses the backslashes as part of the command test, but +# Similarly, an even number of backslashes before a newline in a +# command simply uses the backslashes as part of the command, but # does not escape the newline. This is compatible with GNU make. all: .PHONY # We will add dependencies like "all: yet-another-test" later. # Some variables to be expanded in tests # a = aaa A = ${a} # Backslash at end of line in a comment\ should continue the comment. \ # This is also tested in comment.mk. __printvars: .USE .MADE @echo ${.TARGET} ${.ALLSRC:@v@ printf "%s=:%s:\n" ${v:Q} ${${v}:Q}; @} # Embedded backslash in variable should be taken literally. # VAR1BS = 111\111 VAR1BSa = 111\${a} VAR1BSA = 111\${A} VAR1BSda = 111\$${a} VAR1BSdA = 111\$${A} VAR1BSc = 111\# backslash escapes comment char, so this is part of the value VAR1BSsc = 111\ # This is a comment. Value ends with all: var-1bs var-1bs: .PHONY __printvars VAR1BS VAR1BSa VAR1BSA VAR1BSda VAR1BSdA \ VAR1BSc VAR1BSsc # Double backslash in variable should be taken as two literal backslashes. # VAR2BS = 222\\222 VAR2BSa = 222\\${a} VAR2BSA = 222\\${A} VAR2BSda = 222\\$${a} VAR2BSdA = 222\\$${A} VAR2BSc = 222\\# backslash does not escape comment char, so this is a comment VAR2BSsc = 222\\ # This is a comment. Value ends with all: var-2bs var-2bs: .PHONY __printvars VAR2BS VAR2BSa VAR2BSA VAR2BSda VAR2BSdA \ VAR2BSc VAR2BSsc # Backslash-newline in a variable setting is replaced by a single space. # VAR1BSNL = 111\ 111 VAR1BSNLa = 111\ ${a} VAR1BSNLA = 111\ ${A} VAR1BSNLda = 111\ $${a} VAR1BSNLdA = 111\ $${A} VAR1BSNLc = 111\ # this should be processed as a comment VAR1BSNLsc = 111\ # this should be processed as a comment all: var-1bsnl var-1bsnl: .PHONY var-1bsnl: .PHONY __printvars \ VAR1BSNL VAR1BSNLa VAR1BSNLA VAR1BSNLda VAR1BSNLdA \ VAR1BSNLc VAR1BSNLsc # Double-backslash-newline in a variable setting. # Both backslashes should be taken literally, and the newline is NOT escaped. # # The second lines below each end with '=' so that they will not # generate syntax errors regardless of whether or not they are # treated as part of the value. # VAR2BSNL = 222\\ 222= VAR2BSNLa = 222\\ ${a}= VAR2BSNLA = 222\\ ${A}= VAR2BSNLda = 222\\ $${a}= VAR2BSNLdA = 222\\ $${A}= VAR2BSNLc = 222\\ # this should be processed as a comment VAR2BSNLsc = 222\\ # this should be processed as a comment all: var-2bsnl var-2bsnl: .PHONY __printvars \ VAR2BSNL VAR2BSNLa VAR2BSNLA VAR2BSNLda VAR2BSNLdA \ VAR2BSNLc VAR2BSNLsc # Triple-backslash-newline in a variable setting. # First two should be taken literally, and last should escape the newline. # # The second lines below each end with '=' so that they will not # generate syntax errors regardless of whether or not they are # treated as part of the value. # VAR3BSNL = 333\\\ 333= VAR3BSNLa = 333\\\ ${a}= VAR3BSNLA = 333\\\ ${A}= VAR3BSNLda = 333\\\ $${a}= VAR3BSNLdA = 333\\\ $${A}= VAR3BSNLc = 333\\\ # this should be processed as a comment VAR3BSNLsc = 333\\\ # this should be processed as a comment all: var-3bsnl var-3bsnl: .PHONY __printvars \ VAR3BSNL VAR3BSNLa VAR3BSNLA VAR3BSNLda VAR3BSNLdA \ VAR3BSNLc VAR3BSNLsc # Backslash-newline in a variable setting, plus any amount of white space # on the next line, is replaced by a single space. # VAR1BSNL00= first line\ # above line is entirely empty, and this is a comment VAR1BSNL0= first line\ no space on second line VAR1BSNLs= first line\ one space on second line VAR1BSNLss= first line\ two spaces on second line VAR1BSNLt= first line\ one tab on second line VAR1BSNLtt= first line\ two tabs on second line VAR1BSNLxx= first line\ many spaces and tabs [ ] on second line all: var-1bsnl-space var-1bsnl-space: .PHONY __printvars \ VAR1BSNL00 VAR1BSNL0 VAR1BSNLs VAR1BSNLss VAR1BSNLt VAR1BSNLtt \ VAR1BSNLxx # Backslash-newline in a command is retained. # # The "#" in "# second line without space" makes it a comment instead # of a syntax error if the preceding line is parsed incorretly. # The ":" in "third line':" makes it look like the start of a # target instead of a syntax error if the first line is parsed incorrectly. # all: cmd-1bsnl cmd-1bsnl: .PHONY @echo ${.TARGET} echo :'first line\ #second line without space\ third line': echo :'first line\ second line spaces should be retained': echo :'first line\ second line tab should be elided': echo :'first line\ only one tab should be elided, second tab remains' # When backslash-newline appears at the end of a command script, # both the backslash and the newline should be passed to the shell. # The shell should elide the backslash-newline. # all: cmd-1bsnl-eof cmd-1bsnl-eof: @echo ${.TARGET} echo :'command ending with backslash-newline'; \ # above line must be blank # Double-backslash-newline in a command. # Both backslashes are retained, but the newline is not escaped. # XXX: This may differ from POSIX, but matches gmake. # # When make passes two backslashes to the shell, the shell will pass one # backslash to the echo commant. # all: cmd-2bsnl cmd-2bsnl: .PHONY @echo ${.TARGET} echo take one\\ # this should be a comment echo take two\\ echo take three\\ # Triple-backslash-newline in a command is retained. # all: cmd-3bsnl cmd-3bsnl: .PHONY @echo ${.TARGET} echo :'first line\\\ #second line without space\\\ third line': echo :'first line\\\ second line spaces should be retained': echo :'first line\\\ second line tab should be elided': echo :'first line\\\ only one tab should be elided, second tab remains' Index: stable/12/contrib/bmake/unit-tests/forloop.exp =================================================================== --- stable/12/contrib/bmake/unit-tests/forloop.exp (revision 361673) +++ stable/12/contrib/bmake/unit-tests/forloop.exp (revision 361674) @@ -1,19 +1,20 @@ x=one x="two and three" x=four x="five" x=-I/this x=-I"This or that" x=-Ithat x="-DTHIS=\"this and that\"" cfl=-I/this -I"This or that" -Ithat "-DTHIS=\"this and that\"" +newline-item=(a) a=one b="two and three" a=four b="five" a=ONE b="TWO AND THREE" a=FOUR b="FIVE" We expect an error next: -make: "forloop.mk" line 38: Wrong number of words (9) in .for substitution list with 2 vars +make: "forloop.mk" line 46: Wrong number of words (9) in .for substitution list with 2 vars make: Fatal errors encountered -- cannot continue make: stopped in unit-tests OK exit status 0 Index: stable/12/contrib/bmake/unit-tests/forloop.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/forloop.mk (revision 361673) +++ stable/12/contrib/bmake/unit-tests/forloop.mk (revision 361674) @@ -1,45 +1,53 @@ -# $Id: forloop.mk,v 1.1.1.1 2014/08/30 18:57:18 sjg Exp $ +# $Id: forloop.mk,v 1.1.1.2 2020/05/05 00:54:40 sjg Exp $ all: for-loop LIST = one "two and three" four "five" .if make(for-fail) for-fail: XTRA_LIST = xtra .else .for x in ${LIST} X!= echo 'x=$x' >&2; echo .endfor CFL = -I/this -I"This or that" -Ithat "-DTHIS=\"this and that\"" cfl= .for x in ${CFL} X!= echo 'x=$x' >&2; echo .if empty(cfl) cfl= $x .else cfl+= $x .endif .endfor X!= echo 'cfl=${cfl}' >&2; echo .if ${cfl} != ${CFL} .error ${.newline}'${cfl}' != ${.newline}'${CFL}' .endif .for a b in ${EMPTY} X!= echo 'a=$a b=$b' >&2; echo .endfor -.endif + +# Since at least 1993, iteration stops at the first newline. +# Back then, the .newline variable didn't exist, therefore it was unlikely +# that a newline ever occured. +.for var in a${.newline}b${.newline}c +X!= echo 'newline-item=('${var:Q}')' 1>&2; echo +.endfor + +.endif # for-fail .for a b in ${LIST} ${LIST:tu} ${XTRA_LIST} X!= echo 'a=$a b=$b' >&2; echo .endfor for-loop: @echo We expect an error next: @(cd ${.CURDIR} && ${.MAKE} -f ${MAKEFILE} for-fail) && \ { echo "Oops that should have failed!"; exit 1; } || echo OK Index: stable/12/contrib/bmake/unit-tests/include-main.exp =================================================================== --- stable/12/contrib/bmake/unit-tests/include-main.exp (nonexistent) +++ stable/12/contrib/bmake/unit-tests/include-main.exp (revision 361674) @@ -0,0 +1,6 @@ +main-before-ok +sub-before-ok +subsub-ok +sub-after-fail(include-sub.mk) +main-after-fail(include-sub.mk) +exit status 0 Index: stable/12/contrib/bmake/unit-tests/include-main.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/include-main.mk (nonexistent) +++ stable/12/contrib/bmake/unit-tests/include-main.mk (revision 361674) @@ -0,0 +1,30 @@ +# $NetBSD: include-main.mk,v 1.1 2020/05/17 12:36:26 rillig Exp $ +# +# Demonstrates that the .INCLUDEDFROMFILE magic variable does not behave +# as described in the manual page. +# +# The manual page says that it is the "filename of the file this Makefile +# was included from", while in reality it is the "filename in which the +# latest .include happened". +# + +.if !defined(.INCLUDEDFROMFILE) +LOG+= main-before-ok +.else +. for f in ${.INCLUDEDFROMFILE} +LOG+= main-before-fail\(${f:Q}\) +. endfor +.endif + +.include "include-sub.mk" + +.if !defined(.INCLUDEDFROMFILE) +LOG+= main-after-ok +.else +. for f in ${.INCLUDEDFROMFILE} +LOG+= main-after-fail\(${f:Q}\) +. endfor +.endif + +all: + @printf '%s\n' ${LOG} Property changes on: stable/12/contrib/bmake/unit-tests/include-main.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/include-sub.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/include-sub.mk (nonexistent) +++ stable/12/contrib/bmake/unit-tests/include-sub.mk (revision 361674) @@ -0,0 +1,17 @@ +# $NetBSD: include-sub.mk,v 1.1 2020/05/17 12:36:26 rillig Exp $ + +.if ${.INCLUDEDFROMFILE} == "include-main.mk" +LOG+= sub-before-ok +.else +LOG+= sub-before-fail +.endif + +.include "include-subsub.mk" + +.if ${.INCLUDEDFROMFILE} == "include-main.mk" +LOG+= sub-after-ok +.else +. for f in ${.INCLUDEDFROMFILE} +LOG+= sub-after-fail\(${f:Q}\) +. endfor +.endif Property changes on: stable/12/contrib/bmake/unit-tests/include-sub.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/include-subsub.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/include-subsub.mk (nonexistent) +++ stable/12/contrib/bmake/unit-tests/include-subsub.mk (revision 361674) @@ -0,0 +1,7 @@ +# $NetBSD: include-subsub.mk,v 1.1 2020/05/17 12:36:26 rillig Exp $ + +.if ${.INCLUDEDFROMFILE:T} == "include-sub.mk" +LOG+= subsub-ok +.else +LOG+= subsub-fail +.endif Property changes on: stable/12/contrib/bmake/unit-tests/include-subsub.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/modorder.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/modorder.mk (revision 361673) +++ stable/12/contrib/bmake/unit-tests/modorder.mk (revision 361674) @@ -1,22 +1,23 @@ -# $NetBSD: modorder.mk,v 1.1 2014/08/21 13:44:51 apb Exp $ +# $NetBSD: modorder.mk,v 1.2 2020/01/07 22:42:14 rillig Exp $ LIST= one two three four five six seven eight nine ten LISTX= ${LIST:Ox} LISTSX:= ${LIST:Ox} TEST_RESULT= && echo Ok || echo Failed # unit-tests have to produce the same results on each run # so we cannot actually include :Ox output. all: @echo "LIST = ${LIST}" @echo "LIST:O = ${LIST:O}" # Note that 1 in every 10! trials two independently generated # randomized orderings will be the same. The test framework doesn't - # support checking probabilistic output, so we accept that the test - # will incorrectly fail with probability 2.8E-7. + # support checking probabilistic output, so we accept that each of the + # 3 :Ox tests will incorrectly fail with probability 2.756E-7, which + # lets the whole test fail once in 1.209.600 runs, on average. @echo "LIST:Ox = `test '${LIST:Ox}' != '${LIST:Ox}' ${TEST_RESULT}`" @echo "LIST:O:Ox = `test '${LIST:O:Ox}' != '${LIST:O:Ox}' ${TEST_RESULT}`" @echo "LISTX = `test '${LISTX}' != '${LISTX}' ${TEST_RESULT}`" @echo "LISTSX = `test '${LISTSX}' = '${LISTSX}' ${TEST_RESULT}`" @echo "BADMOD 1 = ${LIST:OX}" @echo "BADMOD 2 = ${LIST:OxXX}" Index: stable/12/contrib/bmake/unit-tests/sysv.exp =================================================================== --- stable/12/contrib/bmake/unit-tests/sysv.exp (revision 361673) +++ stable/12/contrib/bmake/unit-tests/sysv.exp (revision 361674) @@ -1,7 +1,15 @@ FOOBAR = FOOBAR = foobar fubar fun fun fun In the Sun +acme +aam.d +sam.c +a%.c +asam.c.c +asam.c +a.c.c + exit status 0 Index: stable/12/contrib/bmake/unit-tests/sysv.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/sysv.mk (revision 361673) +++ stable/12/contrib/bmake/unit-tests/sysv.mk (revision 361674) @@ -1,26 +1,43 @@ -# $Id: sysv.mk,v 1.2 2014/08/30 22:25:14 sjg Exp $ +# $Id: sysv.mk,v 1.4 2020/05/07 01:17:51 sjg Exp $ FOO ?= FOOBAR = ${FOO:=bar} _this := ${.PARSEDIR}/${.PARSEFILE} B = /b S = / FUN = ${B}${S}fun SUN = the Sun # we expect nothing when FOO is empty -all: foo fun +all: foo fun sam bla foo: @echo FOOBAR = ${FOOBAR} .if empty(FOO) @FOO="foo fu" ${.MAKE} -f ${_this} foo .endif fun: @echo ${FUN:T} @echo ${FUN:${B}${S}fun=fun} @echo ${FUN:${B}${S}%=%} @echo ${In:L:%=% ${SUN}} + + +SAM=sam.c + +sam: + @echo ${SAM:s%.c=acme} + @echo ${SAM:s%.c=a%.d} + @echo ${SAM:s.c=a%.d} + @echo ${SAM:sam.c=a%.c} + @echo ${SAM:%=a%.c} + @echo ${SAM:%.c=a%.c} + @echo ${SAM:sam%=a%.c} + +BLA= + +bla: + @echo $(BLA:%=foo/%x) Index: stable/12/contrib/bmake/unit-tests/varmod-edge.exp =================================================================== --- stable/12/contrib/bmake/unit-tests/varmod-edge.exp (nonexistent) +++ stable/12/contrib/bmake/unit-tests/varmod-edge.exp (revision 361674) @@ -0,0 +1,17 @@ +make: Unclosed variable specification (expecting '}') for "" (value "*)") modifier U +make: Unclosed substitution for INP.eq-esc (= missing) +ok M-paren +ok M-mixed +ok M-unescape +ok M-nest-mix +ok M-nest-brk +ok M-pat-err +ok M-bsbs +ok M-bs1-par +ok M-bs2-par +ok M-128 +ok eq-ext +ok eq-q +ok eq-bs +ok eq-esc +exit status 0 Index: stable/12/contrib/bmake/unit-tests/varmod-edge.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/varmod-edge.mk (nonexistent) +++ stable/12/contrib/bmake/unit-tests/varmod-edge.mk (revision 361674) @@ -0,0 +1,162 @@ +# $NetBSD: varmod-edge.mk,v 1.7 2020/04/27 14:07:22 christos Exp $ +# +# Tests for edge cases in variable modifiers. +# +# These tests demonstrate the current implementation in small examples. +# They may contain surprising behavior. +# +# Each test consists of: +# - INP, the input to the test +# - MOD, the expression for testing the modifier +# - EXP, the expected output + +TESTS+= M-paren +INP.M-paren= (parentheses) {braces} (opening closing) () +MOD.M-paren= ${INP.M-paren:M(*)} +EXP.M-paren= (parentheses) () + +# The first closing brace matches the opening parenthesis. +# The second closing brace actually ends the variable expression. +# +# XXX: This is unexpected but rarely occurs in practice. +TESTS+= M-mixed +INP.M-mixed= (paren-brace} ( +MOD.M-mixed= ${INP.M-mixed:M(*}} +EXP.M-mixed= (paren-brace} + +# After the :M modifier has parsed the pattern, only the closing brace +# and the colon are unescaped. The other characters are left as-is. +# To actually see this effect, the backslashes in the :M modifier need +# to be doubled since single backslashes would simply be unescaped by +# Str_Match. +# +# XXX: This is unexpected. The opening brace should also be unescaped. +TESTS+= M-unescape +INP.M-unescape= ({}): \(\{\}\)\: \(\{}\): +MOD.M-unescape= ${INP.M-unescape:M\\(\\{\\}\\)\\:} +EXP.M-unescape= \(\{}\): + +# When the :M and :N modifiers are parsed, the pattern finishes as soon +# as open_parens + open_braces == closing_parens + closing_braces. This +# means that ( and } form a matching pair. +# +# Nested variable expressions are not parsed as such. Instead, only the +# parentheses and braces are counted. This leads to a parse error since +# the nested expression is not "${:U*)}" but only "${:U*)", which is +# missing the closing brace. The expression is evaluated anyway. +# The final brace in the output comes from the end of M.nest-mix. +# +# XXX: This is unexpected but rarely occurs in practice. +TESTS+= M-nest-mix +INP.M-nest-mix= (parentheses) +MOD.M-nest-mix= ${INP.M-nest-mix:M${:U*)}} +EXP.M-nest-mix= (parentheses)} +# make: Unclosed variable specification (expecting '}') for "" (value "*)") modifier U + +# In contrast to parentheses and braces, the brackets are not counted +# when the :M modifier is parsed since Makefile variables only take the +# ${VAR} or $(VAR) forms, but not $[VAR]. +# +# The final ] in the pattern is needed to close the character class. +TESTS+= M-nest-brk +INP.M-nest-brk= [ [[ [[[ +MOD.M-nest-brk= ${INP.M-nest-brk:M${:U[[[[[]}} +EXP.M-nest-brk= [ + +# The pattern in the nested variable has an unclosed character class. +# No error is reported though, and the pattern is closed implicitly. +# +# XXX: It is unexpected that no error is reported. +# See str.c, function Str_Match. +# +# Before 2019-12-02, this test case triggered an out-of-bounds read +# in Str_Match. +TESTS+= M-pat-err +INP.M-pat-err= [ [[ [[[ +MOD.M-pat-err= ${INP.M-pat-err:M${:U[[}} +EXP.M-pat-err= [ + +# The first backslash does not escape the second backslash. +# Therefore, the second backslash escapes the parenthesis. +# This means that the pattern ends there. +# The final } in the output comes from the end of MOD.M-bsbs. +# +# If the first backslash were to escape the second backslash, the first +# closing brace would match the opening parenthesis (see M-mixed), and +# the second closing brace would be needed to close the variable. +# After that, the remaining backslash would escape the parenthesis in +# the pattern, therefore (} would match. +TESTS+= M-bsbs +INP.M-bsbs= (} \( \(} +MOD.M-bsbs= ${INP.M-bsbs:M\\(}} +EXP.M-bsbs= \(} +#EXP.M-bsbs= (} # If the first backslash were to escape ... + +# The backslash in \( does not escape the parenthesis, therefore it +# counts for the nesting level and matches with the first closing brace. +# The second closing brace closes the variable, and the third is copied +# literally. +# +# The second :M in the pattern is nested between ( and }, therefore it +# does not start a new modifier. +TESTS+= M-bs1-par +INP.M-bs1-par= ( (:M (:M} \( \(:M \(:M} +MOD.M-bs1-par= ${INP.M-bs1-par:M\(:M*}}} +EXP.M-bs1-par= (:M}} + +# The double backslash is passed verbatim to the pattern matcher. +# The Str_Match pattern is \\(:M*}, and there the backslash is unescaped. +# Again, the ( takes place in the nesting level, and there is no way to +# prevent this, no matter how many backslashes are used. +TESTS+= M-bs2-par +INP.M-bs2-par= ( (:M (:M} \( \(:M \(:M} +MOD.M-bs2-par= ${INP.M-bs2-par:M\\(:M*}}} +EXP.M-bs2-par= \(:M}} + +# Str_Match uses a recursive algorithm for matching the * patterns. +# Make sure that it survives patterns with 128 asterisks. +# That should be enough for all practical purposes. +# To produce a stack overflow, just add more :Qs below. +TESTS+= M-128 +INP.M-128= ${:U\\:Q:Q:Q:Q:Q:Q:Q:S,\\,x,g} +PAT.M-128= ${:U\\:Q:Q:Q:Q:Q:Q:Q:S,\\,*,g} +MOD.M-128= ${INP.M-128:M${PAT.M-128}} +EXP.M-128= ${INP.M-128} + +# This is the normal SysV substitution. Nothing surprising here. +TESTS+= eq-ext +INP.eq-ext= file.c file.cc +MOD.eq-ext= ${INP.eq-ext:%.c=%.o} +EXP.eq-ext= file.o file.cc + +# The SysV := modifier is greedy and consumes all the modifier text +# up until the closing brace or parenthesis. The :Q may look like a +# modifier, but it really isn't, that's why it appears in the output. +TESTS+= eq-q +INP.eq-q= file.c file.cc +MOD.eq-q= ${INP.eq-q:%.c=%.o:Q} +EXP.eq-q= file.o:Q file.cc + +# The = in the := modifier can be escaped. +TESTS+= eq-bs +INP.eq-bs= file.c file.c=%.o +MOD.eq-bs= ${INP.eq-bs:%.c\=%.o=%.ext} +EXP.eq-bs= file.c file.ext + +# Having only an escaped = results in a parse error. +# The call to "pattern.lhs = VarGetPattern" fails. +TESTS+= eq-esc +INP.eq-esc= file.c file... +MOD.eq-esc= ${INP.eq-esc:a\=b} +EXP.eq-esc= # empty +# make: Unclosed substitution for INP.eq-esc (= missing) + +all: +.for test in ${TESTS} +. if ${MOD.${test}} == ${EXP.${test}} + @printf 'ok %s\n' ${test:Q}'' +. else + @printf 'error in %s: expected %s, got %s\n' \ + ${test:Q}'' ${EXP.${test}:Q}'' ${MOD.${test}:Q}'' +. endif +.endfor Property changes on: stable/12/contrib/bmake/unit-tests/varmod-edge.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/unit-tests/varquote.exp =================================================================== --- stable/12/contrib/bmake/unit-tests/varquote.exp (nonexistent) +++ stable/12/contrib/bmake/unit-tests/varquote.exp (revision 361674) @@ -0,0 +1,3 @@ +-fdebug-prefix-map=$NETBSDSRCDIR=/usr/src -fdebug-regex-map=/usr/src/(.*)/obj$=/usr/obj/\1 +-fdebug-prefix-map=$NETBSDSRCDIR=/usr/src -fdebug-regex-map=/usr/src/(.*)/obj$=/usr/obj/\1 +exit status 0 Index: stable/12/contrib/bmake/unit-tests/varquote.mk =================================================================== --- stable/12/contrib/bmake/unit-tests/varquote.mk (nonexistent) +++ stable/12/contrib/bmake/unit-tests/varquote.mk (revision 361674) @@ -0,0 +1,14 @@ +# $NetBSD: varquote.mk,v 1.4 2018/12/16 18:53:34 christos Exp $ +# +# Test VAR:q modifier + +.if !defined(REPROFLAGS) +REPROFLAGS+= -fdebug-prefix-map=\$$NETBSDSRCDIR=/usr/src +REPROFLAGS+= -fdebug-regex-map='/usr/src/(.*)/obj$$=/usr/obj/\1' +all: + @${MAKE} -f ${MAKEFILE} REPROFLAGS=${REPROFLAGS:S/\$/&&/g:Q} + @${MAKE} -f ${MAKEFILE} REPROFLAGS=${REPROFLAGS:q} +.else +all: + @printf "%s %s\n" ${REPROFLAGS} +.endif Property changes on: stable/12/contrib/bmake/unit-tests/varquote.mk ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: stable/12/contrib/bmake/util.c =================================================================== --- stable/12/contrib/bmake/util.c (revision 361673) +++ stable/12/contrib/bmake/util.c (revision 361674) @@ -1,622 +1,596 @@ -/* $NetBSD: util.c,v 1.54 2013/11/26 13:44:41 joerg Exp $ */ +/* $NetBSD: util.c,v 1.55 2020/01/07 21:24:16 rillig Exp $ */ /* * Missing stuff from OS's * - * $Id: util.c,v 1.33 2014/01/02 02:29:49 sjg Exp $ + * $Id: util.c,v 1.34 2020/01/22 01:19:25 sjg Exp $ */ #if defined(__MINT__) || defined(__linux__) #include #endif #include "make.h" #ifndef MAKE_NATIVE -static char rcsid[] = "$NetBSD: util.c,v 1.54 2013/11/26 13:44:41 joerg Exp $"; +static char rcsid[] = "$NetBSD: util.c,v 1.55 2020/01/07 21:24:16 rillig Exp $"; #else #ifndef lint -__RCSID("$NetBSD: util.c,v 1.54 2013/11/26 13:44:41 joerg Exp $"); +__RCSID("$NetBSD: util.c,v 1.55 2020/01/07 21:24:16 rillig Exp $"); #endif #endif #include #include #include #if !defined(HAVE_STRERROR) extern int errno, sys_nerr; extern char *sys_errlist[]; char * strerror(int e) { static char buf[100]; if (e < 0 || e >= sys_nerr) { snprintf(buf, sizeof(buf), "Unknown error %d", e); return buf; } else return sys_errlist[e]; } #endif #if !defined(HAVE_GETENV) || !defined(HAVE_SETENV) || !defined(HAVE_UNSETENV) extern char **environ; static char * findenv(const char *name, int *offset) { size_t i, len; char *p, *q; len = strlen(name); for (i = 0; (q = environ[i]); i++) { p = strchr(q, '='); if (p == NULL || p - q != len) continue; if (strncmp(name, q, len) == 0) { *offset = i; return q + len + 1; } } *offset = i; return NULL; } char * getenv(const char *name) { int offset; return(findenv(name, &offset)); } int unsetenv(const char *name) { char **p; int offset; if (name == NULL || *name == '\0' || strchr(name, '=') != NULL) { errno = EINVAL; return -1; } while (findenv(name, &offset)) { /* if set multiple times */ for (p = &environ[offset];; ++p) if (!(*p = *(p + 1))) break; } return 0; } int setenv(const char *name, const char *value, int rewrite) { char *c, **newenv; const char *cc; size_t l_value, size; int offset; if (name == NULL || value == NULL) { errno = EINVAL; return -1; } if (*value == '=') /* no `=' in value */ ++value; l_value = strlen(value); /* find if already exists */ if ((c = findenv(name, &offset))) { if (!rewrite) return 0; if (strlen(c) >= l_value) /* old larger; copy over */ goto copy; } else { /* create new slot */ size = sizeof(char *) * (offset + 2); if (savedEnv == environ) { /* just increase size */ if ((newenv = realloc(savedEnv, size)) == NULL) return -1; savedEnv = newenv; } else { /* get new space */ /* * We don't free here because we don't know if * the first allocation is valid on all OS's */ if ((savedEnv = malloc(size)) == NULL) return -1; (void)memcpy(savedEnv, environ, size - sizeof(char *)); } environ = savedEnv; environ[offset + 1] = NULL; } for (cc = name; *cc && *cc != '='; ++cc) /* no `=' in name */ continue; size = cc - name; /* name + `=' + value */ if ((environ[offset] = malloc(size + l_value + 2)) == NULL) return -1; c = environ[offset]; (void)memcpy(c, name, size); c += size; *c++ = '='; copy: (void)memcpy(c, value, l_value + 1); return 0; } #ifdef TEST int main(int argc, char *argv[]) { setenv(argv[1], argv[2], 0); printf("%s\n", getenv(argv[1])); unsetenv(argv[1]); printf("%s\n", getenv(argv[1])); return 0; } #endif #endif #if defined(__hpux__) || defined(__hpux) /* strrcpy(): * Like strcpy, going backwards and returning the new pointer */ static char * strrcpy(char *ptr, char *str) { int len = strlen(str); while (len) *--ptr = str[--len]; return (ptr); } /* end strrcpy */ char *sys_siglist[] = { "Signal 0", "Hangup", /* SIGHUP */ "Interrupt", /* SIGINT */ "Quit", /* SIGQUIT */ "Illegal instruction", /* SIGILL */ "Trace/BPT trap", /* SIGTRAP */ "IOT trap", /* SIGIOT */ "EMT trap", /* SIGEMT */ "Floating point exception", /* SIGFPE */ "Killed", /* SIGKILL */ "Bus error", /* SIGBUS */ "Segmentation fault", /* SIGSEGV */ "Bad system call", /* SIGSYS */ "Broken pipe", /* SIGPIPE */ "Alarm clock", /* SIGALRM */ "Terminated", /* SIGTERM */ "User defined signal 1", /* SIGUSR1 */ "User defined signal 2", /* SIGUSR2 */ "Child exited", /* SIGCLD */ "Power-fail restart", /* SIGPWR */ "Virtual timer expired", /* SIGVTALRM */ "Profiling timer expired", /* SIGPROF */ "I/O possible", /* SIGIO */ "Window size changes", /* SIGWINDOW */ "Stopped (signal)", /* SIGSTOP */ "Stopped", /* SIGTSTP */ "Continued", /* SIGCONT */ "Stopped (tty input)", /* SIGTTIN */ "Stopped (tty output)", /* SIGTTOU */ "Urgent I/O condition", /* SIGURG */ "Remote lock lost (NFS)", /* SIGLOST */ "Signal 31", /* reserved */ "DIL signal" /* SIGDIL */ }; #endif /* __hpux__ || __hpux */ #if defined(__hpux__) || defined(__hpux) #include #include #include #include #include #include #include int killpg(int pid, int sig) { return kill(-pid, sig); } - -#if !defined(__hpux__) && !defined(__hpux) -void -srandom(long seed) -{ - srand48(seed); -} - -long -random(void) -{ - return lrand48(); -} -#endif - -#if !defined(__hpux__) && !defined(__hpux) -int -utimes(char *file, struct timeval tvp[2]) -{ - struct utimbuf t; - - t.actime = tvp[0].tv_sec; - t.modtime = tvp[1].tv_sec; - return(utime(file, &t)); -} -#endif #if !defined(BSD) && !defined(d_fileno) # define d_fileno d_ino #endif #ifndef DEV_DEV_COMPARE # define DEV_DEV_COMPARE(a, b) ((a) == (b)) #endif #define ISDOT(c) ((c)[0] == '.' && (((c)[1] == '\0') || ((c)[1] == '/'))) #define ISDOTDOT(c) ((c)[0] == '.' && ISDOT(&((c)[1]))) char * getwd(char *pathname) { DIR *dp; struct dirent *d; extern int errno; struct stat st_root, st_cur, st_next, st_dotdot; char pathbuf[MAXPATHLEN], nextpathbuf[MAXPATHLEN * 2]; char *pathptr, *nextpathptr, *cur_name_add; /* find the inode of root */ if (stat("/", &st_root) == -1) { (void)sprintf(pathname, "getwd: Cannot stat \"/\" (%s)", strerror(errno)); return NULL; } pathbuf[MAXPATHLEN - 1] = '\0'; pathptr = &pathbuf[MAXPATHLEN - 1]; nextpathbuf[MAXPATHLEN - 1] = '\0'; cur_name_add = nextpathptr = &nextpathbuf[MAXPATHLEN - 1]; /* find the inode of the current directory */ if (lstat(".", &st_cur) == -1) { (void)sprintf(pathname, "getwd: Cannot stat \".\" (%s)", strerror(errno)); return NULL; } nextpathptr = strrcpy(nextpathptr, "../"); /* Descend to root */ for (;;) { /* look if we found root yet */ if (st_cur.st_ino == st_root.st_ino && DEV_DEV_COMPARE(st_cur.st_dev, st_root.st_dev)) { (void)strcpy(pathname, *pathptr != '/' ? "/" : pathptr); return (pathname); } /* open the parent directory */ if (stat(nextpathptr, &st_dotdot) == -1) { (void)sprintf(pathname, "getwd: Cannot stat directory \"%s\" (%s)", nextpathptr, strerror(errno)); return NULL; } if ((dp = opendir(nextpathptr)) == NULL) { (void)sprintf(pathname, "getwd: Cannot open directory \"%s\" (%s)", nextpathptr, strerror(errno)); return NULL; } /* look in the parent for the entry with the same inode */ if (DEV_DEV_COMPARE(st_dotdot.st_dev, st_cur.st_dev)) { /* Parent has same device. No need to stat every member */ for (d = readdir(dp); d != NULL; d = readdir(dp)) if (d->d_fileno == st_cur.st_ino) break; } else { /* * Parent has a different device. This is a mount point so we * need to stat every member */ for (d = readdir(dp); d != NULL; d = readdir(dp)) { if (ISDOT(d->d_name) || ISDOTDOT(d->d_name)) continue; (void)strcpy(cur_name_add, d->d_name); if (lstat(nextpathptr, &st_next) == -1) { (void)sprintf(pathname, "getwd: Cannot stat \"%s\" (%s)", d->d_name, strerror(errno)); (void)closedir(dp); return NULL; } /* check if we found it yet */ if (st_next.st_ino == st_cur.st_ino && DEV_DEV_COMPARE(st_next.st_dev, st_cur.st_dev)) break; } } if (d == NULL) { (void)sprintf(pathname, "getwd: Cannot find \".\" in \"..\""); (void)closedir(dp); return NULL; } st_cur = st_dotdot; pathptr = strrcpy(pathptr, d->d_name); pathptr = strrcpy(pathptr, "/"); nextpathptr = strrcpy(nextpathptr, "../"); (void)closedir(dp); *cur_name_add = '\0'; } } /* end getwd */ #endif /* __hpux */ #if !defined(HAVE_GETCWD) char * getcwd(path, sz) char *path; int sz; { return getwd(path); } #endif /* force posix signals */ void (* bmake_signal(int s, void (*a)(int)))(int) { struct sigaction sa, osa; sa.sa_handler = a; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(s, &sa, &osa) == -1) return SIG_ERR; else return osa.sa_handler; } #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_VASPRINTF) #include #endif #if !defined(HAVE_VSNPRINTF) #if !defined(__osf__) #ifdef _IOSTRG #define STRFLAG (_IOSTRG|_IOWRT) /* no _IOWRT: avoid stdio bug */ #else #if 0 #define STRFLAG (_IOREAD) /* XXX: Assume svr4 stdio */ #endif #endif /* _IOSTRG */ #endif /* __osf__ */ int vsnprintf(char *s, size_t n, const char *fmt, va_list args) { #ifdef STRFLAG FILE fakebuf; fakebuf._flag = STRFLAG; /* * Some os's are char * _ptr, others are unsigned char *_ptr... * We cast to void * to make everyone happy. */ fakebuf._ptr = (void *)s; fakebuf._cnt = n-1; fakebuf._file = -1; _doprnt(fmt, args, &fakebuf); fakebuf._cnt++; putc('\0', &fakebuf); if (fakebuf._cnt<0) fakebuf._cnt = 0; return (n-fakebuf._cnt-1); #else #ifndef _PATH_DEVNULL # define _PATH_DEVNULL "/dev/null" #endif /* * Rats... we don't want to clobber anything... * do a printf to /dev/null to see how much space we need. */ static FILE *nullfp; int need = 0; /* XXX what's a useful error return? */ if (!nullfp) nullfp = fopen(_PATH_DEVNULL, "w"); if (nullfp) { need = vfprintf(nullfp, fmt, args); if (need < n) (void)vsprintf(s, fmt, args); } return need; #endif } #endif #if !defined(HAVE_SNPRINTF) int snprintf(char *s, size_t n, const char *fmt, ...) { va_list ap; int rv; va_start(ap, fmt); rv = vsnprintf(s, n, fmt, ap); va_end(ap); return rv; } #endif #if !defined(HAVE_STRFTIME) size_t strftime(char *buf, size_t len, const char *fmt, const struct tm *tm) { static char months[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; size_t s; char *b = buf; while (*fmt) { if (len == 0) return buf - b; if (*fmt != '%') { *buf++ = *fmt++; len--; continue; } switch (*fmt++) { case '%': *buf++ = '%'; len--; if (len == 0) return buf - b; /*FALLTHROUGH*/ case '\0': *buf = '%'; s = 1; break; case 'k': s = snprintf(buf, len, "%d", tm->tm_hour); break; case 'M': s = snprintf(buf, len, "%02d", tm->tm_min); break; case 'S': s = snprintf(buf, len, "%02d", tm->tm_sec); break; case 'b': if (tm->tm_mon >= 12) return buf - b; s = snprintf(buf, len, "%s", months[tm->tm_mon]); break; case 'd': s = snprintf(buf, len, "%02d", tm->tm_mday); break; case 'Y': s = snprintf(buf, len, "%d", 1900 + tm->tm_year); break; default: s = snprintf(buf, len, "Unsupported format %c", fmt[-1]); break; } buf += s; len -= s; } } #endif #if !defined(HAVE_KILLPG) #if !defined(__hpux__) && !defined(__hpux) int killpg(int pid, int sig) { return kill(-pid, sig); } #endif #endif #if !defined(HAVE_WARNX) static void vwarnx(const char *fmt, va_list args) { fprintf(stderr, "%s: ", progname); if ((fmt)) { vfprintf(stderr, fmt, args); fprintf(stderr, ": "); } } #endif #if !defined(HAVE_WARN) static void vwarn(const char *fmt, va_list args) { vwarnx(fmt, args); fprintf(stderr, "%s\n", strerror(errno)); } #endif #if !defined(HAVE_ERR) static void verr(int eval, const char *fmt, va_list args) { vwarn(fmt, args); exit(eval); } #endif #if !defined(HAVE_ERRX) static void verrx(int eval, const char *fmt, va_list args) { vwarnx(fmt, args); exit(eval); } #endif #if !defined(HAVE_ERR) void err(int eval, const char *fmt, ...) { va_list ap; va_start(ap, fmt); verr(eval, fmt, ap); va_end(ap); } #endif #if !defined(HAVE_ERRX) void errx(int eval, const char *fmt, ...) { va_list ap; va_start(ap, fmt); verrx(eval, fmt, ap); va_end(ap); } #endif #if !defined(HAVE_WARN) void warn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarn(fmt, ap); va_end(ap); } #endif #if !defined(HAVE_WARNX) void warnx(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vwarnx(fmt, ap); va_end(ap); } #endif Index: stable/12/contrib/bmake/var.c =================================================================== --- stable/12/contrib/bmake/var.c (revision 361673) +++ stable/12/contrib/bmake/var.c (revision 361674) @@ -1,4349 +1,4357 @@ -/* $NetBSD: var.c,v 1.218 2018/02/18 00:52:42 sjg Exp $ */ +/* $NetBSD: var.c,v 1.223 2020/04/25 18:20:57 christos Exp $ */ /* * Copyright (c) 1988, 1989, 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 1989 by Berkeley Softworks * All rights reserved. * * This code is derived from software contributed to Berkeley by * Adam de Boor. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef MAKE_NATIVE -static char rcsid[] = "$NetBSD: var.c,v 1.218 2018/02/18 00:52:42 sjg Exp $"; +static char rcsid[] = "$NetBSD: var.c,v 1.223 2020/04/25 18:20:57 christos Exp $"; #else #include #ifndef lint #if 0 static char sccsid[] = "@(#)var.c 8.3 (Berkeley) 3/19/94"; #else -__RCSID("$NetBSD: var.c,v 1.218 2018/02/18 00:52:42 sjg Exp $"); +__RCSID("$NetBSD: var.c,v 1.223 2020/04/25 18:20:57 christos Exp $"); #endif #endif /* not lint */ #endif /*- * var.c -- * Variable-handling functions * * Interface: * Var_Set Set the value of a variable in the given * context. The variable is created if it doesn't * yet exist. The value and variable name need not * be preserved. * * Var_Append Append more characters to an existing variable * in the given context. The variable needn't * exist already -- it will be created if it doesn't. * A space is placed between the old value and the * new one. * * Var_Exists See if a variable exists. * * Var_Value Return the value of a variable in a context or * NULL if the variable is undefined. * * Var_Subst Substitute named variable, or all variables if * NULL in a string using * the given context as the top-most one. If the * third argument is non-zero, Parse_Error is * called if any variables are undefined. * * Var_Parse Parse a variable expansion from a string and * return the result and the number of characters * consumed. * * Var_Delete Delete a variable in a context. * * Var_Init Initialize this module. * * Debugging: * Var_Dump Print out all variables defined in the given * context. * * XXX: There's a lot of duplication in these functions. */ #include #ifndef NO_REGEX #include #include #endif #include #include #include #include #include "make.h" #include "buf.h" #include "dir.h" #include "job.h" #include "metachar.h" extern int makelevel; /* * This lets us tell if we have replaced the original environ * (which we cannot free). */ char **savedEnv = NULL; /* * This is a harmless return value for Var_Parse that can be used by Var_Subst * to determine if there was an error in parsing -- easier than returning * a flag, as things outside this module don't give a hoot. */ char var_Error[] = ""; /* * Similar to var_Error, but returned when the 'VARF_UNDEFERR' flag for * Var_Parse is not set. Why not just use a constant? Well, gcc likes * to condense identical string instances... */ static char varNoError[] = ""; /* * Traditionally we consume $$ during := like any other expansion. * Other make's do not. * This knob allows controlling the behavior. * FALSE for old behavior. * TRUE for new compatible. */ #define SAVE_DOLLARS ".MAKE.SAVE_DOLLARS" static Boolean save_dollars = FALSE; /* * Internally, variables are contained in four different contexts. * 1) the environment. They may not be changed. If an environment * variable is appended-to, the result is placed in the global * context. * 2) the global context. Variables set in the Makefile are located in * the global context. It is the penultimate context searched when * substituting. * 3) the command-line context. All variables set on the command line * are placed in this context. They are UNALTERABLE once placed here. * 4) the local context. Each target has associated with it a context * list. On this list are located the structures describing such * local variables as $(@) and $(*) * The four contexts are searched in the reverse order from which they are * listed. */ GNode *VAR_INTERNAL; /* variables from make itself */ GNode *VAR_GLOBAL; /* variables from the makefile */ GNode *VAR_CMD; /* variables defined on the command-line */ #define FIND_CMD 0x1 /* look in VAR_CMD when searching */ #define FIND_GLOBAL 0x2 /* look in VAR_GLOBAL as well */ #define FIND_ENV 0x4 /* look in the environment also */ typedef struct Var { char *name; /* the variable's name */ Buffer val; /* its value */ int flags; /* miscellaneous status flags */ #define VAR_IN_USE 1 /* Variable's value currently being used. * Used to avoid recursion */ #define VAR_FROM_ENV 2 /* Variable comes from the environment */ #define VAR_JUNK 4 /* Variable is a junk variable that * should be destroyed when done with * it. Used by Var_Parse for undefined, * modified variables */ #define VAR_KEEP 8 /* Variable is VAR_JUNK, but we found * a use for it in some modifier and * the value is therefore valid */ #define VAR_EXPORTED 16 /* Variable is exported */ #define VAR_REEXPORT 32 /* Indicate if var needs re-export. * This would be true if it contains $'s */ #define VAR_FROM_CMD 64 /* Variable came from command line */ } Var; /* * Exporting vars is expensive so skip it if we can */ #define VAR_EXPORTED_NONE 0 #define VAR_EXPORTED_YES 1 #define VAR_EXPORTED_ALL 2 static int var_exportedVars = VAR_EXPORTED_NONE; /* * We pass this to Var_Export when doing the initial export * or after updating an exported var. */ #define VAR_EXPORT_PARENT 1 /* * We pass this to Var_Export1 to tell it to leave the value alone. */ #define VAR_EXPORT_LITERAL 2 /* Var*Pattern flags */ #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */ #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */ #define VAR_SUB_MATCHED 0x04 /* There was a match */ #define VAR_MATCH_START 0x08 /* Match at start of word */ #define VAR_MATCH_END 0x10 /* Match at end of word */ #define VAR_NOSUBST 0x20 /* don't expand vars in VarGetPattern */ /* Var_Set flags */ #define VAR_NO_EXPORT 0x01 /* do not export */ typedef struct { /* * The following fields are set by Var_Parse() when it * encounters modifiers that need to keep state for use by * subsequent modifiers within the same variable expansion. */ Byte varSpace; /* Word separator in expansions */ Boolean oneBigWord; /* TRUE if we will treat the variable as a * single big word, even if it contains * embedded spaces (as opposed to the * usual behaviour of treating it as * several space-separated words). */ } Var_Parse_State; /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/", * to VarSYSVMatch() for ":lhs=rhs". */ typedef struct { const char *lhs; /* String to match */ int leftLen; /* Length of string */ const char *rhs; /* Replacement string (w/ &'s removed) */ int rightLen; /* Length of replacement */ int flags; } VarPattern; /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */ typedef struct { GNode *ctxt; /* variable context */ char *tvar; /* name of temp var */ int tvarLen; char *str; /* string to expand */ int strLen; int errnum; /* errnum for not defined */ } VarLoop_t; #ifndef NO_REGEX /* struct passed as 'void *' to VarRESubstitute() for ":C///" */ typedef struct { regex_t re; int nsub; regmatch_t *matches; char *replace; int flags; } VarREPattern; #endif /* struct passed to VarSelectWords() for ":[start..end]" */ typedef struct { int start; /* first word to select */ int end; /* last word to select */ } VarSelectWords_t; static Var *VarFind(const char *, GNode *, int); static void VarAdd(const char *, const char *, GNode *); static Boolean VarHead(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); static Boolean VarTail(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); static Boolean VarSuffix(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); static Boolean VarRoot(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); static Boolean VarMatch(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); #ifdef SYSVVARSUB static Boolean VarSYSVMatch(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); #endif static Boolean VarNoMatch(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); #ifndef NO_REGEX static void VarREError(int, regex_t *, const char *); static Boolean VarRESubstitute(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); #endif static Boolean VarSubstitute(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); static Boolean VarLoopExpand(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *); static char *VarGetPattern(GNode *, Var_Parse_State *, int, const char **, int, int *, int *, VarPattern *); -static char *VarQuote(char *); +static char *VarQuote(char *, Boolean); static char *VarHash(char *); static char *VarModify(GNode *, Var_Parse_State *, const char *, Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *), void *); static char *VarOrder(const char *, const char); static char *VarUniq(const char *); static int VarWordCompare(const void *, const void *); static void VarPrintVar(void *); #define BROPEN '{' #define BRCLOSE '}' #define PROPEN '(' #define PRCLOSE ')' /*- *----------------------------------------------------------------------- * VarFind -- * Find the given variable in the given context and any other contexts * indicated. * * Input: * name name to find * ctxt context in which to find it * flags FIND_GLOBAL set means to look in the * VAR_GLOBAL context as well. FIND_CMD set means * to look in the VAR_CMD context also. FIND_ENV * set means to look in the environment * * Results: * A pointer to the structure describing the desired variable or * NULL if the variable does not exist. * * Side Effects: * None *----------------------------------------------------------------------- */ static Var * VarFind(const char *name, GNode *ctxt, int flags) { Hash_Entry *var; Var *v; /* * If the variable name begins with a '.', it could very well be one of * the local ones. We check the name against all the local variables * and substitute the short version in for 'name' if it matches one of * them. */ if (*name == '.' && isupper((unsigned char) name[1])) switch (name[1]) { case 'A': if (!strcmp(name, ".ALLSRC")) name = ALLSRC; if (!strcmp(name, ".ARCHIVE")) name = ARCHIVE; break; case 'I': if (!strcmp(name, ".IMPSRC")) name = IMPSRC; break; case 'M': if (!strcmp(name, ".MEMBER")) name = MEMBER; break; case 'O': if (!strcmp(name, ".OODATE")) name = OODATE; break; case 'P': if (!strcmp(name, ".PREFIX")) name = PREFIX; break; case 'T': if (!strcmp(name, ".TARGET")) name = TARGET; break; } #ifdef notyet /* for compatibility with gmake */ if (name[0] == '^' && name[1] == '\0') name = ALLSRC; #endif /* * First look for the variable in the given context. If it's not there, * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order, * depending on the FIND_* flags in 'flags' */ var = Hash_FindEntry(&ctxt->context, name); if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) { var = Hash_FindEntry(&VAR_CMD->context, name); } if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) { var = Hash_FindEntry(&VAR_GLOBAL->context, name); if ((var == NULL) && (ctxt != VAR_INTERNAL)) { /* VAR_INTERNAL is subordinate to VAR_GLOBAL */ var = Hash_FindEntry(&VAR_INTERNAL->context, name); } } if ((var == NULL) && (flags & FIND_ENV)) { char *env; if ((env = getenv(name)) != NULL) { int len; v = bmake_malloc(sizeof(Var)); v->name = bmake_strdup(name); len = strlen(env); Buf_Init(&v->val, len + 1); Buf_AddBytes(&v->val, len, env); v->flags = VAR_FROM_ENV; return (v); } else if (checkEnvFirst && (flags & FIND_GLOBAL) && (ctxt != VAR_GLOBAL)) { var = Hash_FindEntry(&VAR_GLOBAL->context, name); if ((var == NULL) && (ctxt != VAR_INTERNAL)) { var = Hash_FindEntry(&VAR_INTERNAL->context, name); } if (var == NULL) { return NULL; } else { return ((Var *)Hash_GetValue(var)); } } else { return NULL; } } else if (var == NULL) { return NULL; } else { return ((Var *)Hash_GetValue(var)); } } /*- *----------------------------------------------------------------------- * VarFreeEnv -- * If the variable is an environment variable, free it * * Input: * v the variable * destroy true if the value buffer should be destroyed. * * Results: * 1 if it is an environment variable 0 ow. * * Side Effects: * The variable is free'ed if it is an environent variable. *----------------------------------------------------------------------- */ static Boolean VarFreeEnv(Var *v, Boolean destroy) { if ((v->flags & VAR_FROM_ENV) == 0) return FALSE; free(v->name); Buf_Destroy(&v->val, destroy); free(v); return TRUE; } /*- *----------------------------------------------------------------------- * VarAdd -- * Add a new variable of name name and value val to the given context * * Input: * name name of variable to add * val value to set it to * ctxt context in which to set it * * Results: * None * * Side Effects: * The new variable is placed at the front of the given context * The name and val arguments are duplicated so they may * safely be freed. *----------------------------------------------------------------------- */ static void VarAdd(const char *name, const char *val, GNode *ctxt) { Var *v; int len; Hash_Entry *h; v = bmake_malloc(sizeof(Var)); len = val ? strlen(val) : 0; Buf_Init(&v->val, len+1); Buf_AddBytes(&v->val, len, val); v->flags = 0; h = Hash_CreateEntry(&ctxt->context, name, NULL); Hash_SetValue(h, v); v->name = h->name; if (DEBUG(VAR) && (ctxt->flags & INTERNAL) == 0) { fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); } } /*- *----------------------------------------------------------------------- * Var_Delete -- * Remove a variable from a context. * * Results: * None. * * Side Effects: * The Var structure is removed and freed. * *----------------------------------------------------------------------- */ void Var_Delete(const char *name, GNode *ctxt) { Hash_Entry *ln; char *cp; if (strchr(name, '$')) { cp = Var_Subst(NULL, name, VAR_GLOBAL, VARF_WANTRES); } else { cp = (char *)name; } ln = Hash_FindEntry(&ctxt->context, cp); if (DEBUG(VAR)) { fprintf(debug_file, "%s:delete %s%s\n", ctxt->name, cp, ln ? "" : " (not found)"); } if (cp != name) { free(cp); } if (ln != NULL) { Var *v; v = (Var *)Hash_GetValue(ln); if ((v->flags & VAR_EXPORTED)) { unsetenv(v->name); } if (strcmp(MAKE_EXPORTED, v->name) == 0) { var_exportedVars = VAR_EXPORTED_NONE; } if (v->name != ln->name) free(v->name); Hash_DeleteEntry(&ctxt->context, ln); Buf_Destroy(&v->val, TRUE); free(v); } } /* * Export a var. * We ignore make internal variables (those which start with '.') * Also we jump through some hoops to avoid calling setenv * more than necessary since it can leak. * We only manipulate flags of vars if 'parent' is set. */ static int Var_Export1(const char *name, int flags) { char tmp[BUFSIZ]; Var *v; char *val = NULL; int n; int parent = (flags & VAR_EXPORT_PARENT); if (*name == '.') return 0; /* skip internals */ if (!name[1]) { /* * A single char. * If it is one of the vars that should only appear in * local context, skip it, else we can get Var_Subst * into a loop. */ switch (name[0]) { case '@': case '%': case '*': case '!': return 0; } } v = VarFind(name, VAR_GLOBAL, 0); if (v == NULL) { return 0; } if (!parent && (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) { return 0; /* nothing to do */ } val = Buf_GetAll(&v->val, NULL); if ((flags & VAR_EXPORT_LITERAL) == 0 && strchr(val, '$')) { if (parent) { /* * Flag this as something we need to re-export. * No point actually exporting it now though, * the child can do it at the last minute. */ v->flags |= (VAR_EXPORTED|VAR_REEXPORT); return 1; } if (v->flags & VAR_IN_USE) { /* * We recursed while exporting in a child. * This isn't going to end well, just skip it. */ return 0; } n = snprintf(tmp, sizeof(tmp), "${%s}", name); if (n < (int)sizeof(tmp)) { val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES); setenv(name, val, 1); free(val); } } else { if (parent) { v->flags &= ~VAR_REEXPORT; /* once will do */ } if (parent || !(v->flags & VAR_EXPORTED)) { setenv(name, val, 1); } } /* * This is so Var_Set knows to call Var_Export again... */ if (parent) { v->flags |= VAR_EXPORTED; } return 1; } /* * This gets called from our children. */ void Var_ExportVars(void) { char tmp[BUFSIZ]; Hash_Entry *var; Hash_Search state; Var *v; char *val; int n; /* * Several make's support this sort of mechanism for tracking * recursion - but each uses a different name. * We allow the makefiles to update MAKELEVEL and ensure * children see a correctly incremented value. */ snprintf(tmp, sizeof(tmp), "%d", makelevel + 1); setenv(MAKE_LEVEL_ENV, tmp, 1); if (VAR_EXPORTED_NONE == var_exportedVars) return; if (VAR_EXPORTED_ALL == var_exportedVars) { /* * Ouch! This is crazy... */ for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state); var != NULL; var = Hash_EnumNext(&state)) { v = (Var *)Hash_GetValue(var); Var_Export1(v->name, 0); } return; } /* * We have a number of exported vars, */ n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}"); if (n < (int)sizeof(tmp)) { char **av; char *as; int ac; int i; val = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES); if (*val) { av = brk_string(val, &ac, FALSE, &as); for (i = 0; i < ac; i++) { Var_Export1(av[i], 0); } free(as); free(av); } free(val); } } /* * This is called when .export is seen or * .MAKE.EXPORTED is modified. * It is also called when any exported var is modified. */ void Var_Export(char *str, int isExport) { char *name; char *val; char **av; char *as; int flags; int ac; int i; if (isExport && (!str || !str[0])) { var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */ return; } flags = 0; if (strncmp(str, "-env", 4) == 0) { str += 4; } else if (strncmp(str, "-literal", 8) == 0) { str += 8; flags |= VAR_EXPORT_LITERAL; } else { flags |= VAR_EXPORT_PARENT; } val = Var_Subst(NULL, str, VAR_GLOBAL, VARF_WANTRES); if (*val) { av = brk_string(val, &ac, FALSE, &as); for (i = 0; i < ac; i++) { name = av[i]; if (!name[1]) { /* * A single char. * If it is one of the vars that should only appear in * local context, skip it, else we can get Var_Subst * into a loop. */ switch (name[0]) { case '@': case '%': case '*': case '!': continue; } } if (Var_Export1(name, flags)) { if (VAR_EXPORTED_ALL != var_exportedVars) var_exportedVars = VAR_EXPORTED_YES; if (isExport && (flags & VAR_EXPORT_PARENT)) { Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL); } } } free(as); free(av); } free(val); } /* * This is called when .unexport[-env] is seen. */ extern char **environ; void Var_UnExport(char *str) { char tmp[BUFSIZ]; char *vlist; char *cp; Boolean unexport_env; int n; if (!str || !str[0]) { return; /* assert? */ } vlist = NULL; str += 8; unexport_env = (strncmp(str, "-env", 4) == 0); if (unexport_env) { char **newenv; cp = getenv(MAKE_LEVEL_ENV); /* we should preserve this */ if (environ == savedEnv) { /* we have been here before! */ newenv = bmake_realloc(environ, 2 * sizeof(char *)); } else { if (savedEnv) { free(savedEnv); savedEnv = NULL; } newenv = bmake_malloc(2 * sizeof(char *)); } if (!newenv) return; /* Note: we cannot safely free() the original environ. */ environ = savedEnv = newenv; newenv[0] = NULL; newenv[1] = NULL; - setenv(MAKE_LEVEL_ENV, cp, 1); + if (cp && *cp) + setenv(MAKE_LEVEL_ENV, cp, 1); } else { for (; *str != '\n' && isspace((unsigned char) *str); str++) continue; if (str[0] && str[0] != '\n') { vlist = str; } } if (!vlist) { /* Using .MAKE.EXPORTED */ n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}"); if (n < (int)sizeof(tmp)) { vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES); } } if (vlist) { Var *v; char **av; char *as; int ac; int i; av = brk_string(vlist, &ac, FALSE, &as); for (i = 0; i < ac; i++) { v = VarFind(av[i], VAR_GLOBAL, 0); if (!v) continue; if (!unexport_env && (v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) { unsetenv(v->name); } v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT); /* * If we are unexporting a list, * remove each one from .MAKE.EXPORTED. * If we are removing them all, * just delete .MAKE.EXPORTED below. */ if (vlist == str) { n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":N%s}", v->name); if (n < (int)sizeof(tmp)) { cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES); Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0); free(cp); } } } free(as); free(av); if (vlist != str) { Var_Delete(MAKE_EXPORTED, VAR_GLOBAL); free(vlist); } } } /*- *----------------------------------------------------------------------- * Var_Set -- * Set the variable name to the value val in the given context. * * Input: * name name of variable to set * val value to give to the variable * ctxt context in which to set it * * Results: * None. * * Side Effects: * If the variable doesn't yet exist, a new record is created for it. * Else the old value is freed and the new one stuck in its place * * Notes: * The variable is searched for only in its context before being * created in that context. I.e. if the context is VAR_GLOBAL, * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only * VAR_CMD->context is searched. This is done to avoid the literally * thousands of unnecessary strcmp's that used to be done to * set, say, $(@) or $(<). * If the context is VAR_GLOBAL though, we check if the variable * was set in VAR_CMD from the command line and skip it if so. *----------------------------------------------------------------------- */ void Var_Set(const char *name, const char *val, GNode *ctxt, int flags) { Var *v; char *expanded_name = NULL; /* * We only look for a variable in the given context since anything set * here will override anything in a lower context, so there's not much * point in searching them all just to save a bit of memory... */ if (strchr(name, '$') != NULL) { expanded_name = Var_Subst(NULL, name, ctxt, VARF_WANTRES); if (expanded_name[0] == 0) { if (DEBUG(VAR)) { fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) " "name expands to empty string - ignored\n", name, val); } free(expanded_name); return; } name = expanded_name; } if (ctxt == VAR_GLOBAL) { v = VarFind(name, VAR_CMD, 0); if (v != NULL) { if ((v->flags & VAR_FROM_CMD)) { if (DEBUG(VAR)) { fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val); } goto out; } VarFreeEnv(v, TRUE); } } v = VarFind(name, ctxt, 0); if (v == NULL) { if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) { /* * This var would normally prevent the same name being added * to VAR_GLOBAL, so delete it from there if needed. * Otherwise -V name may show the wrong value. */ Var_Delete(name, VAR_GLOBAL); } VarAdd(name, val, ctxt); } else { Buf_Empty(&v->val); if (val) Buf_AddBytes(&v->val, strlen(val), val); if (DEBUG(VAR)) { fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val); } if ((v->flags & VAR_EXPORTED)) { Var_Export1(name, VAR_EXPORT_PARENT); } } /* * Any variables given on the command line are automatically exported * to the environment (as per POSIX standard) */ if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) { if (v == NULL) { /* we just added it */ v = VarFind(name, ctxt, 0); } if (v != NULL) v->flags |= VAR_FROM_CMD; /* * If requested, don't export these in the environment * individually. We still put them in MAKEOVERRIDES so * that the command-line settings continue to override * Makefile settings. */ if (varNoExportEnv != TRUE) setenv(name, val ? val : "", 1); Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL); } if (*name == '.') { if (strcmp(name, SAVE_DOLLARS) == 0) save_dollars = s2Boolean(val, save_dollars); } out: free(expanded_name); if (v != NULL) VarFreeEnv(v, TRUE); } /*- *----------------------------------------------------------------------- * Var_Append -- * The variable of the given name has the given value appended to it in * the given context. * * Input: * name name of variable to modify * val String to append to it * ctxt Context in which this should occur * * Results: * None * * Side Effects: * If the variable doesn't exist, it is created. Else the strings * are concatenated (with a space in between). * * Notes: * Only if the variable is being sought in the global context is the * environment searched. * XXX: Knows its calling circumstances in that if called with ctxt * an actual target, it will only search that context since only * a local variable could be being appended to. This is actually * a big win and must be tolerated. *----------------------------------------------------------------------- */ void Var_Append(const char *name, const char *val, GNode *ctxt) { Var *v; Hash_Entry *h; char *expanded_name = NULL; if (strchr(name, '$') != NULL) { expanded_name = Var_Subst(NULL, name, ctxt, VARF_WANTRES); if (expanded_name[0] == 0) { if (DEBUG(VAR)) { fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) " "name expands to empty string - ignored\n", name, val); } free(expanded_name); return; } name = expanded_name; } v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? (FIND_CMD|FIND_ENV) : 0); if (v == NULL) { Var_Set(name, val, ctxt, 0); } else if (ctxt == VAR_CMD || !(v->flags & VAR_FROM_CMD)) { Buf_AddByte(&v->val, ' '); Buf_AddBytes(&v->val, strlen(val), val); if (DEBUG(VAR)) { fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, Buf_GetAll(&v->val, NULL)); } if (v->flags & VAR_FROM_ENV) { /* * If the original variable came from the environment, we * have to install it in the global context (we could place * it in the environment, but then we should provide a way to * export other variables...) */ v->flags &= ~VAR_FROM_ENV; h = Hash_CreateEntry(&ctxt->context, name, NULL); Hash_SetValue(h, v); } } free(expanded_name); } /*- *----------------------------------------------------------------------- * Var_Exists -- * See if the given variable exists. * * Input: * name Variable to find * ctxt Context in which to start search * * Results: * TRUE if it does, FALSE if it doesn't * * Side Effects: * None. * *----------------------------------------------------------------------- */ Boolean Var_Exists(const char *name, GNode *ctxt) { Var *v; char *cp; if ((cp = strchr(name, '$')) != NULL) { cp = Var_Subst(NULL, name, ctxt, VARF_WANTRES); } v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV); free(cp); if (v == NULL) { return(FALSE); } else { (void)VarFreeEnv(v, TRUE); } return(TRUE); } /*- *----------------------------------------------------------------------- * Var_Value -- * Return the value of the named variable in the given context * * Input: * name name to find * ctxt context in which to search for it * * Results: * The value if the variable exists, NULL if it doesn't * * Side Effects: * None *----------------------------------------------------------------------- */ char * Var_Value(const char *name, GNode *ctxt, char **frp) { Var *v; v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); *frp = NULL; if (v != NULL) { char *p = (Buf_GetAll(&v->val, NULL)); if (VarFreeEnv(v, FALSE)) *frp = p; return p; } else { return NULL; } } /*- *----------------------------------------------------------------------- * VarHead -- * Remove the tail of the given word and place the result in the given * buffer. * * Input: * word Word to trim * addSpace True if need to add a space to the buffer * before sticking in the head * buf Buffer in which to store it * * Results: * TRUE if characters were added to the buffer (a space needs to be * added to the buffer before the next word). * * Side Effects: * The trimmed word is added to the buffer. * *----------------------------------------------------------------------- */ static Boolean VarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *dummy MAKE_ATTR_UNUSED) { char *slash; slash = strrchr(word, '/'); if (slash != NULL) { if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } *slash = '\0'; Buf_AddBytes(buf, strlen(word), word); *slash = '/'; return (TRUE); } else { /* * If no directory part, give . (q.v. the POSIX standard) */ if (addSpace && vpstate->varSpace) Buf_AddByte(buf, vpstate->varSpace); Buf_AddByte(buf, '.'); } return TRUE; } /*- *----------------------------------------------------------------------- * VarTail -- * Remove the head of the given word and place the result in the given * buffer. * * Input: * word Word to trim * addSpace True if need to add a space to the buffer * before adding the tail * buf Buffer in which to store it * * Results: * TRUE if characters were added to the buffer (a space needs to be * added to the buffer before the next word). * * Side Effects: * The trimmed word is added to the buffer. * *----------------------------------------------------------------------- */ static Boolean VarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *dummy MAKE_ATTR_UNUSED) { char *slash; if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } slash = strrchr(word, '/'); if (slash != NULL) { *slash++ = '\0'; Buf_AddBytes(buf, strlen(slash), slash); slash[-1] = '/'; } else { Buf_AddBytes(buf, strlen(word), word); } return TRUE; } /*- *----------------------------------------------------------------------- * VarSuffix -- * Place the suffix of the given word in the given buffer. * * Input: * word Word to trim * addSpace TRUE if need to add a space before placing the * suffix in the buffer * buf Buffer in which to store it * * Results: * TRUE if characters were added to the buffer (a space needs to be * added to the buffer before the next word). * * Side Effects: * The suffix from the word is placed in the buffer. * *----------------------------------------------------------------------- */ static Boolean VarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *dummy MAKE_ATTR_UNUSED) { char *dot; dot = strrchr(word, '.'); if (dot != NULL) { if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } *dot++ = '\0'; Buf_AddBytes(buf, strlen(dot), dot); dot[-1] = '.'; addSpace = TRUE; } return addSpace; } /*- *----------------------------------------------------------------------- * VarRoot -- * Remove the suffix of the given word and place the result in the * buffer. * * Input: * word Word to trim * addSpace TRUE if need to add a space to the buffer * before placing the root in it * buf Buffer in which to store it * * Results: * TRUE if characters were added to the buffer (a space needs to be * added to the buffer before the next word). * * Side Effects: * The trimmed word is added to the buffer. * *----------------------------------------------------------------------- */ static Boolean VarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *dummy MAKE_ATTR_UNUSED) { char *dot; if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } dot = strrchr(word, '.'); if (dot != NULL) { *dot = '\0'; Buf_AddBytes(buf, strlen(word), word); *dot = '.'; } else { Buf_AddBytes(buf, strlen(word), word); } return TRUE; } /*- *----------------------------------------------------------------------- * VarMatch -- * Place the word in the buffer if it matches the given pattern. * Callback function for VarModify to implement the :M modifier. * * Input: * word Word to examine * addSpace TRUE if need to add a space to the buffer * before adding the word, if it matches * buf Buffer in which to store it * pattern Pattern the word must match * * Results: * TRUE if a space should be placed in the buffer before the next * word. * * Side Effects: * The word may be copied to the buffer. * *----------------------------------------------------------------------- */ static Boolean VarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *pattern) { if (DEBUG(VAR)) fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern); if (Str_Match(word, (char *)pattern)) { if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } addSpace = TRUE; Buf_AddBytes(buf, strlen(word), word); } return(addSpace); } #ifdef SYSVVARSUB /*- *----------------------------------------------------------------------- * VarSYSVMatch -- * Place the word in the buffer if it matches the given pattern. * Callback function for VarModify to implement the System V % * modifiers. * * Input: * word Word to examine * addSpace TRUE if need to add a space to the buffer * before adding the word, if it matches * buf Buffer in which to store it * patp Pattern the word must match * * Results: * TRUE if a space should be placed in the buffer before the next * word. * * Side Effects: * The word may be copied to the buffer. * *----------------------------------------------------------------------- */ static Boolean VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *patp) { - int len; + size_t len; char *ptr; + Boolean hasPercent; VarPattern *pat = (VarPattern *)patp; char *varexp; if (addSpace && vpstate->varSpace) Buf_AddByte(buf, vpstate->varSpace); addSpace = TRUE; - if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) { + if ((ptr = Str_SYSVMatch(word, pat->lhs, &len, &hasPercent)) != NULL) { varexp = Var_Subst(NULL, pat->rhs, ctx, VARF_WANTRES); - Str_SYSVSubst(buf, varexp, ptr, len); + Str_SYSVSubst(buf, varexp, ptr, len, hasPercent); free(varexp); } else { Buf_AddBytes(buf, strlen(word), word); } return(addSpace); } #endif /*- *----------------------------------------------------------------------- * VarNoMatch -- * Place the word in the buffer if it doesn't match the given pattern. * Callback function for VarModify to implement the :N modifier. * * Input: * word Word to examine * addSpace TRUE if need to add a space to the buffer * before adding the word, if it matches * buf Buffer in which to store it * pattern Pattern the word must match * * Results: * TRUE if a space should be placed in the buffer before the next * word. * * Side Effects: * The word may be copied to the buffer. * *----------------------------------------------------------------------- */ static Boolean VarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *pattern) { if (!Str_Match(word, (char *)pattern)) { if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } addSpace = TRUE; Buf_AddBytes(buf, strlen(word), word); } return(addSpace); } /*- *----------------------------------------------------------------------- * VarSubstitute -- * Perform a string-substitution on the given word, placing the * result in the passed buffer. * * Input: * word Word to modify * addSpace True if space should be added before * other characters * buf Buffer for result * patternp Pattern for substitution * * Results: * TRUE if a space is needed before more characters are added. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static Boolean VarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *patternp) { int wordLen; /* Length of word */ char *cp; /* General pointer */ VarPattern *pattern = (VarPattern *)patternp; wordLen = strlen(word); if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) != (VAR_SUB_ONE|VAR_SUB_MATCHED)) { /* * Still substituting -- break it down into simple anchored cases * and if none of them fits, perform the general substitution case. */ if ((pattern->flags & VAR_MATCH_START) && (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) { /* * Anchored at start and beginning of word matches pattern */ if ((pattern->flags & VAR_MATCH_END) && (wordLen == pattern->leftLen)) { /* * Also anchored at end and matches to the end (word * is same length as pattern) add space and rhs only * if rhs is non-null. */ if (pattern->rightLen != 0) { if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } addSpace = TRUE; Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); } pattern->flags |= VAR_SUB_MATCHED; } else if (pattern->flags & VAR_MATCH_END) { /* * Doesn't match to end -- copy word wholesale */ goto nosub; } else { /* * Matches at start but need to copy in trailing characters */ if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){ if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } addSpace = TRUE; } Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); Buf_AddBytes(buf, wordLen - pattern->leftLen, (word + pattern->leftLen)); pattern->flags |= VAR_SUB_MATCHED; } } else if (pattern->flags & VAR_MATCH_START) { /* * Had to match at start of word and didn't -- copy whole word. */ goto nosub; } else if (pattern->flags & VAR_MATCH_END) { /* * Anchored at end, Find only place match could occur (leftLen * characters from the end of the word) and see if it does. Note * that because the $ will be left at the end of the lhs, we have * to use strncmp. */ cp = word + (wordLen - pattern->leftLen); if ((cp >= word) && (strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) { /* * Match found. If we will place characters in the buffer, * add a space before hand as indicated by addSpace, then * stuff in the initial, unmatched part of the word followed * by the right-hand-side. */ if (((cp - word) + pattern->rightLen) != 0) { if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } addSpace = TRUE; } Buf_AddBytes(buf, cp - word, word); Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); pattern->flags |= VAR_SUB_MATCHED; } else { /* * Had to match at end and didn't. Copy entire word. */ goto nosub; } } else { /* * Pattern is unanchored: search for the pattern in the word using * String_FindSubstring, copying unmatched portions and the * right-hand-side for each match found, handling non-global * substitutions correctly, etc. When the loop is done, any * remaining part of the word (word and wordLen are adjusted * accordingly through the loop) is copied straight into the * buffer. * addSpace is set FALSE as soon as a space is added to the * buffer. */ Boolean done; int origSize; done = FALSE; origSize = Buf_Size(buf); while (!done) { cp = Str_FindSubstring(word, pattern->lhs); if (cp != NULL) { if (addSpace && (((cp - word) + pattern->rightLen) != 0)){ Buf_AddByte(buf, vpstate->varSpace); addSpace = FALSE; } Buf_AddBytes(buf, cp-word, word); Buf_AddBytes(buf, pattern->rightLen, pattern->rhs); wordLen -= (cp - word) + pattern->leftLen; word = cp + pattern->leftLen; if (wordLen == 0) { done = TRUE; } if ((pattern->flags & VAR_SUB_GLOBAL) == 0) { done = TRUE; } pattern->flags |= VAR_SUB_MATCHED; } else { done = TRUE; } } if (wordLen != 0) { if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } Buf_AddBytes(buf, wordLen, word); } /* * If added characters to the buffer, need to add a space * before we add any more. If we didn't add any, just return * the previous value of addSpace. */ return ((Buf_Size(buf) != origSize) || addSpace); } return (addSpace); } nosub: if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } Buf_AddBytes(buf, wordLen, word); return(TRUE); } #ifndef NO_REGEX /*- *----------------------------------------------------------------------- * VarREError -- * Print the error caused by a regcomp or regexec call. * * Results: * None. * * Side Effects: * An error gets printed. * *----------------------------------------------------------------------- */ static void VarREError(int reerr, regex_t *pat, const char *str) { char *errbuf; int errlen; errlen = regerror(reerr, pat, 0, 0); errbuf = bmake_malloc(errlen); regerror(reerr, pat, errbuf, errlen); Error("%s: %s", str, errbuf); free(errbuf); } /*- *----------------------------------------------------------------------- * VarRESubstitute -- * Perform a regex substitution on the given word, placing the * result in the passed buffer. * * Results: * TRUE if a space is needed before more characters are added. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static Boolean VarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate MAKE_ATTR_UNUSED, char *word, Boolean addSpace, Buffer *buf, void *patternp) { VarREPattern *pat; int xrv; char *wp; char *rp; int added; int flags = 0; #define MAYBE_ADD_SPACE() \ if (addSpace && !added) \ Buf_AddByte(buf, ' '); \ added = 1 added = 0; wp = word; pat = patternp; if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) == (VAR_SUB_ONE|VAR_SUB_MATCHED)) xrv = REG_NOMATCH; else { tryagain: xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags); } switch (xrv) { case 0: pat->flags |= VAR_SUB_MATCHED; if (pat->matches[0].rm_so > 0) { MAYBE_ADD_SPACE(); Buf_AddBytes(buf, pat->matches[0].rm_so, wp); } for (rp = pat->replace; *rp; rp++) { if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) { MAYBE_ADD_SPACE(); Buf_AddByte(buf,rp[1]); rp++; } else if ((*rp == '&') || ((*rp == '\\') && isdigit((unsigned char)rp[1]))) { int n; const char *subbuf; int sublen; char errstr[3]; if (*rp == '&') { n = 0; errstr[0] = '&'; errstr[1] = '\0'; } else { n = rp[1] - '0'; errstr[0] = '\\'; errstr[1] = rp[1]; errstr[2] = '\0'; rp++; } if (n > pat->nsub) { Error("No subexpression %s", &errstr[0]); subbuf = ""; sublen = 0; } else if ((pat->matches[n].rm_so == -1) && (pat->matches[n].rm_eo == -1)) { Error("No match for subexpression %s", &errstr[0]); subbuf = ""; sublen = 0; } else { subbuf = wp + pat->matches[n].rm_so; sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so; } if (sublen > 0) { MAYBE_ADD_SPACE(); Buf_AddBytes(buf, sublen, subbuf); } } else { MAYBE_ADD_SPACE(); Buf_AddByte(buf, *rp); } } wp += pat->matches[0].rm_eo; if (pat->flags & VAR_SUB_GLOBAL) { flags |= REG_NOTBOL; if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) { MAYBE_ADD_SPACE(); Buf_AddByte(buf, *wp); wp++; } if (*wp) goto tryagain; } if (*wp) { MAYBE_ADD_SPACE(); Buf_AddBytes(buf, strlen(wp), wp); } break; default: VarREError(xrv, &pat->re, "Unexpected regex error"); /* fall through */ case REG_NOMATCH: if (*wp) { MAYBE_ADD_SPACE(); Buf_AddBytes(buf,strlen(wp),wp); } break; } return(addSpace||added); } #endif /*- *----------------------------------------------------------------------- * VarLoopExpand -- * Implements the :@@@ modifier of ODE make. * We set the temp variable named in pattern.lhs to word and expand * pattern.rhs storing the result in the passed buffer. * * Input: * word Word to modify * addSpace True if space should be added before * other characters * buf Buffer for result * pattern Datafor substitution * * Results: * TRUE if a space is needed before more characters are added. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static Boolean VarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate MAKE_ATTR_UNUSED, char *word, Boolean addSpace, Buffer *buf, void *loopp) { VarLoop_t *loop = (VarLoop_t *)loopp; char *s; int slen; if (word && *word) { Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT); s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum | VARF_WANTRES); if (s != NULL && *s != '\0') { if (addSpace && *s != '\n') Buf_AddByte(buf, ' '); Buf_AddBytes(buf, (slen = strlen(s)), s); addSpace = (slen > 0 && s[slen - 1] != '\n'); } free(s); } return addSpace; } /*- *----------------------------------------------------------------------- * VarSelectWords -- * Implements the :[start..end] modifier. * This is a special case of VarModify since we want to be able * to scan the list backwards if start > end. * * Input: * str String whose words should be trimmed * seldata words to select * * Results: * A string of all the words selected. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static char * VarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, const char *str, VarSelectWords_t *seldata) { Buffer buf; /* Buffer for the new string */ Boolean addSpace; /* TRUE if need to add a space to the * buffer before adding the trimmed * word */ char **av; /* word list */ char *as; /* word list memory */ int ac, i; int start, end, step; Buf_Init(&buf, 0); addSpace = FALSE; if (vpstate->oneBigWord) { /* fake what brk_string() would do if there were only one word */ ac = 1; av = bmake_malloc((ac + 1) * sizeof(char *)); as = bmake_strdup(str); av[0] = as; av[1] = NULL; } else { av = brk_string(str, &ac, FALSE, &as); } /* * Now sanitize seldata. * If seldata->start or seldata->end are negative, convert them to * the positive equivalents (-1 gets converted to argc, -2 gets * converted to (argc-1), etc.). */ if (seldata->start < 0) seldata->start = ac + seldata->start + 1; if (seldata->end < 0) seldata->end = ac + seldata->end + 1; /* * We avoid scanning more of the list than we need to. */ if (seldata->start > seldata->end) { start = MIN(ac, seldata->start) - 1; end = MAX(0, seldata->end - 1); step = -1; } else { start = MAX(0, seldata->start - 1); end = MIN(ac, seldata->end); step = 1; } for (i = start; (step < 0 && i >= end) || (step > 0 && i < end); i += step) { if (av[i] && *av[i]) { if (addSpace && vpstate->varSpace) { Buf_AddByte(&buf, vpstate->varSpace); } Buf_AddBytes(&buf, strlen(av[i]), av[i]); addSpace = TRUE; } } free(as); free(av); return Buf_Destroy(&buf, FALSE); } /*- * VarRealpath -- * Replace each word with the result of realpath() * if successful. */ static Boolean VarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate, char *word, Boolean addSpace, Buffer *buf, void *patternp MAKE_ATTR_UNUSED) { struct stat st; char rbuf[MAXPATHLEN]; char *rp; if (addSpace && vpstate->varSpace) { Buf_AddByte(buf, vpstate->varSpace); } addSpace = TRUE; rp = cached_realpath(word, rbuf); if (rp && *rp == '/' && stat(rp, &st) == 0) word = rp; Buf_AddBytes(buf, strlen(word), word); return(addSpace); } /*- *----------------------------------------------------------------------- * VarModify -- * Modify each of the words of the passed string using the given * function. Used to implement all modifiers. * * Input: * str String whose words should be trimmed * modProc Function to use to modify them * datum Datum to pass it * * Results: * A string of all the words modified appropriately. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static char * VarModify(GNode *ctx, Var_Parse_State *vpstate, const char *str, Boolean (*modProc)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *), void *datum) { Buffer buf; /* Buffer for the new string */ Boolean addSpace; /* TRUE if need to add a space to the * buffer before adding the trimmed * word */ char **av; /* word list */ char *as; /* word list memory */ int ac, i; Buf_Init(&buf, 0); addSpace = FALSE; if (vpstate->oneBigWord) { /* fake what brk_string() would do if there were only one word */ ac = 1; av = bmake_malloc((ac + 1) * sizeof(char *)); as = bmake_strdup(str); av[0] = as; av[1] = NULL; } else { av = brk_string(str, &ac, FALSE, &as); } for (i = 0; i < ac; i++) { addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum); } free(as); free(av); return Buf_Destroy(&buf, FALSE); } static int VarWordCompare(const void *a, const void *b) { int r = strcmp(*(const char * const *)a, *(const char * const *)b); return r; } /*- *----------------------------------------------------------------------- * VarOrder -- * Order the words in the string. * * Input: * str String whose words should be sorted. * otype How to order: s - sort, x - random. * * Results: * A string containing the words ordered. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static char * VarOrder(const char *str, const char otype) { Buffer buf; /* Buffer for the new string */ char **av; /* word list [first word does not count] */ char *as; /* word list memory */ int ac, i; Buf_Init(&buf, 0); av = brk_string(str, &ac, FALSE, &as); if (ac > 0) switch (otype) { case 's': /* sort alphabetically */ qsort(av, ac, sizeof(char *), VarWordCompare); break; case 'x': /* randomize */ { int rndidx; char *t; /* * We will use [ac..2] range for mod factors. This will produce * random numbers in [(ac-1)..0] interval, and minimal * reasonable value for mod factor is 2 (the mod 1 will produce * 0 with probability 1). */ for (i = ac-1; i > 0; i--) { rndidx = random() % (i + 1); if (i != rndidx) { t = av[i]; av[i] = av[rndidx]; av[rndidx] = t; } } } } /* end of switch */ for (i = 0; i < ac; i++) { Buf_AddBytes(&buf, strlen(av[i]), av[i]); if (i != ac - 1) Buf_AddByte(&buf, ' '); } free(as); free(av); return Buf_Destroy(&buf, FALSE); } /*- *----------------------------------------------------------------------- * VarUniq -- * Remove adjacent duplicate words. * * Input: * str String whose words should be sorted * * Results: * A string containing the resulting words. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static char * VarUniq(const char *str) { Buffer buf; /* Buffer for new string */ char **av; /* List of words to affect */ char *as; /* Word list memory */ int ac, i, j; Buf_Init(&buf, 0); av = brk_string(str, &ac, FALSE, &as); if (ac > 1) { for (j = 0, i = 1; i < ac; i++) if (strcmp(av[i], av[j]) != 0 && (++j != i)) av[j] = av[i]; ac = j + 1; } for (i = 0; i < ac; i++) { Buf_AddBytes(&buf, strlen(av[i]), av[i]); if (i != ac - 1) Buf_AddByte(&buf, ' '); } free(as); free(av); return Buf_Destroy(&buf, FALSE); } /*- *----------------------------------------------------------------------- * VarRange -- * Return an integer sequence * * Input: * str String whose words provide default range * ac range length, if 0 use str words * * Side Effects: * None. * *----------------------------------------------------------------------- */ static char * VarRange(const char *str, int ac) { Buffer buf; /* Buffer for new string */ char tmp[32]; /* each element */ char **av; /* List of words to affect */ char *as; /* Word list memory */ int i, n; Buf_Init(&buf, 0); if (ac > 0) { as = NULL; av = NULL; } else { av = brk_string(str, &ac, FALSE, &as); } for (i = 0; i < ac; i++) { n = snprintf(tmp, sizeof(tmp), "%d", 1 + i); if (n >= (int)sizeof(tmp)) break; Buf_AddBytes(&buf, n, tmp); if (i != ac - 1) Buf_AddByte(&buf, ' '); } free(as); free(av); return Buf_Destroy(&buf, FALSE); } /*- *----------------------------------------------------------------------- * VarGetPattern -- * Pass through the tstr looking for 1) escaped delimiters, * '$'s and backslashes (place the escaped character in * uninterpreted) and 2) unescaped $'s that aren't before * the delimiter (expand the variable substitution unless flags * has VAR_NOSUBST set). * Return the expanded string or NULL if the delimiter was missing * If pattern is specified, handle escaped ampersands, and replace * unescaped ampersands with the lhs of the pattern. * * Results: * A string of all the words modified appropriately. * If length is specified, return the string length of the buffer * If flags is specified and the last character of the pattern is a * $ set the VAR_MATCH_END bit of flags. * * Side Effects: * None. *----------------------------------------------------------------------- */ static char * VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED, int flags, const char **tstr, int delim, int *vflags, int *length, VarPattern *pattern) { const char *cp; char *rstr; Buffer buf; int junk; int errnum = flags & VARF_UNDEFERR; Buf_Init(&buf, 0); if (length == NULL) length = &junk; #define IS_A_MATCH(cp, delim) \ ((cp[0] == '\\') && ((cp[1] == delim) || \ (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&')))) /* * Skim through until the matching delimiter is found; * pick up variable substitutions on the way. Also allow * backslashes to quote the delimiter, $, and \, but don't * touch other backslashes. */ for (cp = *tstr; *cp && (*cp != delim); cp++) { if (IS_A_MATCH(cp, delim)) { Buf_AddByte(&buf, cp[1]); cp++; } else if (*cp == '$') { if (cp[1] == delim) { if (vflags == NULL) Buf_AddByte(&buf, *cp); else /* * Unescaped $ at end of pattern => anchor * pattern at end. */ *vflags |= VAR_MATCH_END; } else { if (vflags == NULL || (*vflags & VAR_NOSUBST) == 0) { char *cp2; int len; void *freeIt; /* * If unescaped dollar sign not before the * delimiter, assume it's a variable * substitution and recurse. */ cp2 = Var_Parse(cp, ctxt, errnum | VARF_WANTRES, &len, &freeIt); Buf_AddBytes(&buf, strlen(cp2), cp2); free(freeIt); cp += len - 1; } else { const char *cp2 = &cp[1]; if (*cp2 == PROPEN || *cp2 == BROPEN) { /* * Find the end of this variable reference * and suck it in without further ado. * It will be interperated later. */ int have = *cp2; int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE; int depth = 1; for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) { if (cp2[-1] != '\\') { if (*cp2 == have) ++depth; if (*cp2 == want) --depth; } } Buf_AddBytes(&buf, cp2 - cp, cp); cp = --cp2; } else Buf_AddByte(&buf, *cp); } } } else if (pattern && *cp == '&') Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs); else Buf_AddByte(&buf, *cp); } if (*cp != delim) { *tstr = cp; *length = 0; return NULL; } *tstr = ++cp; *length = Buf_Size(&buf); rstr = Buf_Destroy(&buf, FALSE); if (DEBUG(VAR)) fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr); return rstr; } /*- *----------------------------------------------------------------------- * VarQuote -- * Quote shell meta-characters and space characters in the string + * if quoteDollar is set, also quote and double any '$' characters. * * Results: * The quoted string * * Side Effects: * None. * *----------------------------------------------------------------------- */ static char * -VarQuote(char *str) +VarQuote(char *str, Boolean quoteDollar) { Buffer buf; const char *newline; size_t nlen; if ((newline = Shell_GetNewline()) == NULL) newline = "\\\n"; nlen = strlen(newline); Buf_Init(&buf, 0); for (; *str != '\0'; str++) { if (*str == '\n') { Buf_AddBytes(&buf, nlen, newline); continue; } if (isspace((unsigned char)*str) || ismeta((unsigned char)*str)) Buf_AddByte(&buf, '\\'); Buf_AddByte(&buf, *str); + if (quoteDollar && *str == '$') + Buf_AddBytes(&buf, 2, "\\$"); } str = Buf_Destroy(&buf, FALSE); if (DEBUG(VAR)) fprintf(debug_file, "QuoteMeta: [%s]\n", str); return str; } /*- *----------------------------------------------------------------------- * VarHash -- * Hash the string using the MurmurHash3 algorithm. * Output is computed using 32bit Little Endian arithmetic. * * Input: * str String to modify * * Results: * Hash value of str, encoded as 8 hex digits. * * Side Effects: * None. * *----------------------------------------------------------------------- */ static char * VarHash(char *str) { static const char hexdigits[16] = "0123456789abcdef"; Buffer buf; size_t len, len2; unsigned char *ustr = (unsigned char *)str; unsigned int h, k, c1, c2; h = 0x971e137bU; c1 = 0x95543787U; c2 = 0x2ad7eb25U; len2 = strlen(str); for (len = len2; len; ) { k = 0; switch (len) { default: k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0]; len -= 4; ustr += 4; break; case 3: k |= (ustr[2] << 16); + /* FALLTHROUGH */ case 2: k |= (ustr[1] << 8); + /* FALLTHROUGH */ case 1: k |= ustr[0]; len = 0; } c1 = c1 * 5 + 0x7b7d159cU; c2 = c2 * 5 + 0x6bce6396U; k *= c1; k = (k << 11) ^ (k >> 21); k *= c2; h = (h << 13) ^ (h >> 19); h = h * 5 + 0x52dce729U; h ^= k; } h ^= len2; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; Buf_Init(&buf, 0); for (len = 0; len < 8; ++len) { Buf_AddByte(&buf, hexdigits[h & 15]); h >>= 4; } return Buf_Destroy(&buf, FALSE); } static char * VarStrftime(const char *fmt, int zulu, time_t utc) { char buf[BUFSIZ]; if (!utc) time(&utc); if (!*fmt) fmt = "%c"; strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc)); buf[sizeof(buf) - 1] = '\0'; return bmake_strdup(buf); } /* * Now we need to apply any modifiers the user wants applied. * These are: * :M words which match the given . * is of the standard file * wildcarding form. * :N words which do not match the given . * :S[1gW] * Substitute for in the value * :C[1gW] * Substitute for regex in the value * :H Substitute the head of each word * :T Substitute the tail of each word * :E Substitute the extension (minus '.') of * each word * :R Substitute the root of each word * (pathname minus the suffix). * :O ("Order") Alphabeticaly sort words in variable. * :Ox ("intermiX") Randomize words in variable. * :u ("uniq") Remove adjacent duplicate words. * :tu Converts the variable contents to uppercase. * :tl Converts the variable contents to lowercase. * :ts[c] Sets varSpace - the char used to * separate words to 'c'. If 'c' is * omitted then no separation is used. * :tW Treat the variable contents as a single * word, even if it contains spaces. * (Mnemonic: one big 'W'ord.) * :tw Treat the variable contents as multiple * space-separated words. * (Mnemonic: many small 'w'ords.) * :[index] Select a single word from the value. * :[start..end] Select multiple words from the value. * :[*] or :[0] Select the entire value, as a single * word. Equivalent to :tW. * :[@] Select the entire value, as multiple * words. Undoes the effect of :[*]. * Equivalent to :tw. * :[#] Returns the number of words in the value. * * :?: * If the variable evaluates to true, return * true value, else return the second value. * :lhs=rhs Like :S, but the rhs goes to the end of * the invocation. * :sh Treat the current value as a command * to be run, new value is its output. * The following added so we can handle ODE makefiles. * :@@@ * Assign a temporary local variable * to the current value of each word in turn * and replace each word with the result of * evaluating * :D Use as value if variable defined * :U Use as value if variable undefined * :L Use the name of the variable as the value. * :P Use the path of the node that has the same * name as the variable as the value. This * basically includes an implied :L so that * the common method of refering to the path * of your dependent 'x' in a rule is to use * the form '${x:P}'. * :!! Run cmd much the same as :sh run's the * current value of the variable. * The ::= modifiers, actually assign a value to the variable. * Their main purpose is in supporting modifiers of .for loop * iterators and other obscure uses. They always expand to * nothing. In a target rule that would otherwise expand to an * empty line they can be preceded with @: to keep make happy. * Eg. * * foo: .USE * .for i in ${.TARGET} ${.TARGET:R}.gz * @: ${t::=$i} * @echo blah ${t:T} * .endfor * * ::= Assigns as the new value of variable. * ::?= Assigns as value of variable if * it was not already set. * ::+= Appends to variable. * ::!= Assigns output of as the new value of * variable. */ /* we now have some modifiers with long names */ #define STRMOD_MATCH(s, want, n) \ (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':')) #define STRMOD_MATCHX(s, want, n) \ (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':' || s[n] == '=')) #define CHARMOD_MATCH(c) (c == endc || c == ':') static char * ApplyModifiers(char *nstr, const char *tstr, int startc, int endc, Var *v, GNode *ctxt, int flags, int *lengthPtr, void **freePtr) { const char *start; const char *cp; /* Secondary pointer into str (place marker * for tstr) */ char *newStr; /* New value to return */ char *ep; char termc; /* Character which terminated scan */ int cnt; /* Used to count brace pairs when variable in * in parens or braces */ char delim; int modifier; /* that we are processing */ Var_Parse_State parsestate; /* Flags passed to helper functions */ time_t utc; /* for VarStrftime */ delim = '\0'; parsestate.oneBigWord = FALSE; parsestate.varSpace = ' '; /* word separator */ start = cp = tstr; while (*tstr && *tstr != endc) { if (*tstr == '$') { /* * We may have some complex modifiers in a variable. */ void *freeIt; char *rval; int rlen; int c; rval = Var_Parse(tstr, ctxt, flags, &rlen, &freeIt); /* * If we have not parsed up to endc or ':', * we are not interested. */ if (rval != NULL && *rval && (c = tstr[rlen]) != '\0' && c != ':' && c != endc) { free(freeIt); goto apply_mods; } if (DEBUG(VAR)) { fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n", rval, rlen, tstr, rlen, tstr + rlen); } tstr += rlen; if (rval != NULL && *rval) { int used; nstr = ApplyModifiers(nstr, rval, 0, 0, v, ctxt, flags, &used, freePtr); if (nstr == var_Error || (nstr == varNoError && (flags & VARF_UNDEFERR) == 0) || strlen(rval) != (size_t) used) { free(freeIt); goto out; /* error already reported */ } } free(freeIt); if (*tstr == ':') tstr++; else if (!*tstr && endc) { Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name); goto out; } continue; } apply_mods: if (DEBUG(VAR)) { fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name, *tstr, nstr); } newStr = var_Error; switch ((modifier = *tstr)) { case ':': { if (tstr[1] == '=' || (tstr[2] == '=' && (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) { /* * "::=", "::!=", "::+=", or "::?=" */ GNode *v_ctxt; /* context where v belongs */ const char *emsg; char *sv_name; VarPattern pattern; int how; int vflags; if (v->name[0] == 0) goto bad_modifier; v_ctxt = ctxt; sv_name = NULL; ++tstr; if (v->flags & VAR_JUNK) { /* * We need to bmake_strdup() it incase * VarGetPattern() recurses. */ sv_name = v->name; v->name = bmake_strdup(v->name); } else if (ctxt != VAR_GLOBAL) { Var *gv = VarFind(v->name, ctxt, 0); if (gv == NULL) v_ctxt = VAR_GLOBAL; else VarFreeEnv(gv, TRUE); } switch ((how = *tstr)) { case '+': case '?': case '!': cp = &tstr[2]; break; default: cp = ++tstr; break; } delim = startc == PROPEN ? PRCLOSE : BRCLOSE; pattern.flags = 0; vflags = (flags & VARF_WANTRES) ? 0 : VAR_NOSUBST; pattern.rhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, &vflags, &pattern.rightLen, NULL); if (v->flags & VAR_JUNK) { /* restore original name */ free(v->name); v->name = sv_name; } if (pattern.rhs == NULL) goto cleanup; termc = *--cp; delim = '\0'; if (flags & VARF_WANTRES) { switch (how) { case '+': Var_Append(v->name, pattern.rhs, v_ctxt); break; case '!': newStr = Cmd_Exec(pattern.rhs, &emsg); if (emsg) Error(emsg, nstr); else Var_Set(v->name, newStr, v_ctxt, 0); free(newStr); break; case '?': if ((v->flags & VAR_JUNK) == 0) break; /* FALLTHROUGH */ default: Var_Set(v->name, pattern.rhs, v_ctxt, 0); break; } } free(UNCONST(pattern.rhs)); newStr = varNoError; break; } goto default_case; /* "::" */ } case '@': { VarLoop_t loop; int vflags = VAR_NOSUBST; cp = ++tstr; delim = '@'; if ((loop.tvar = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, &vflags, &loop.tvarLen, NULL)) == NULL) goto cleanup; if ((loop.str = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, &vflags, &loop.strLen, NULL)) == NULL) goto cleanup; termc = *cp; delim = '\0'; loop.errnum = flags & VARF_UNDEFERR; loop.ctxt = ctxt; newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand, &loop); Var_Delete(loop.tvar, ctxt); free(loop.tvar); free(loop.str); break; } case '_': /* remember current value */ cp = tstr + 1; /* make sure it is set */ if (STRMOD_MATCHX(tstr, "_", 1)) { if (tstr[1] == '=') { char *np; int n; cp++; n = strcspn(cp, ":)}"); np = bmake_strndup(cp, n+1); np[n] = '\0'; cp = tstr + 2 + n; Var_Set(np, nstr, ctxt, 0); free(np); } else { Var_Set("_", nstr, ctxt, 0); } newStr = nstr; termc = *cp; break; } goto default_case; case 'D': case 'U': { Buffer buf; /* Buffer for patterns */ int nflags; if (flags & VARF_WANTRES) { int wantres; if (*tstr == 'U') wantres = ((v->flags & VAR_JUNK) != 0); else wantres = ((v->flags & VAR_JUNK) == 0); nflags = flags & ~VARF_WANTRES; if (wantres) nflags |= VARF_WANTRES; } else nflags = flags; /* * Pass through tstr looking for 1) escaped delimiters, * '$'s and backslashes (place the escaped character in * uninterpreted) and 2) unescaped $'s that aren't before * the delimiter (expand the variable substitution). * The result is left in the Buffer buf. */ Buf_Init(&buf, 0); for (cp = tstr + 1; *cp != endc && *cp != ':' && *cp != '\0'; cp++) { if ((*cp == '\\') && ((cp[1] == ':') || (cp[1] == '$') || (cp[1] == endc) || (cp[1] == '\\'))) { Buf_AddByte(&buf, cp[1]); cp++; } else if (*cp == '$') { /* * If unescaped dollar sign, assume it's a * variable substitution and recurse. */ char *cp2; int len; void *freeIt; cp2 = Var_Parse(cp, ctxt, nflags, &len, &freeIt); Buf_AddBytes(&buf, strlen(cp2), cp2); free(freeIt); cp += len - 1; } else { Buf_AddByte(&buf, *cp); } } termc = *cp; if ((v->flags & VAR_JUNK) != 0) v->flags |= VAR_KEEP; if (nflags & VARF_WANTRES) { newStr = Buf_Destroy(&buf, FALSE); } else { newStr = nstr; Buf_Destroy(&buf, TRUE); } break; } case 'L': { if ((v->flags & VAR_JUNK) != 0) v->flags |= VAR_KEEP; newStr = bmake_strdup(v->name); cp = ++tstr; termc = *tstr; break; } case 'P': { GNode *gn; if ((v->flags & VAR_JUNK) != 0) v->flags |= VAR_KEEP; gn = Targ_FindNode(v->name, TARG_NOCREATE); if (gn == NULL || gn->type & OP_NOPATH) { newStr = NULL; } else if (gn->path) { newStr = bmake_strdup(gn->path); } else { newStr = Dir_FindFile(v->name, Suff_FindPath(gn)); } if (!newStr) { newStr = bmake_strdup(v->name); } cp = ++tstr; termc = *tstr; break; } case '!': { const char *emsg; VarPattern pattern; pattern.flags = 0; delim = '!'; emsg = NULL; cp = ++tstr; if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, NULL, &pattern.rightLen, NULL)) == NULL) goto cleanup; if (flags & VARF_WANTRES) newStr = Cmd_Exec(pattern.rhs, &emsg); else newStr = varNoError; free(UNCONST(pattern.rhs)); if (emsg) Error(emsg, nstr); termc = *cp; delim = '\0'; if (v->flags & VAR_JUNK) { v->flags |= VAR_KEEP; } break; } case '[': { /* * Look for the closing ']', recursively * expanding any embedded variables. * * estr is a pointer to the expanded result, * which we must free(). */ char *estr; cp = tstr+1; /* point to char after '[' */ delim = ']'; /* look for closing ']' */ estr = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, NULL, NULL, NULL); if (estr == NULL) goto cleanup; /* report missing ']' */ /* now cp points just after the closing ']' */ delim = '\0'; if (cp[0] != ':' && cp[0] != endc) { /* Found junk after ']' */ free(estr); goto bad_modifier; } if (estr[0] == '\0') { /* Found empty square brackets in ":[]". */ free(estr); goto bad_modifier; } else if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */ /* * We will need enough space for the decimal * representation of an int. We calculate the * space needed for the octal representation, * and add enough slop to cope with a '-' sign * (which should never be needed) and a '\0' * string terminator. */ int newStrSize = (sizeof(int) * CHAR_BIT + 2) / 3 + 2; newStr = bmake_malloc(newStrSize); if (parsestate.oneBigWord) { strncpy(newStr, "1", newStrSize); } else { /* XXX: brk_string() is a rather expensive * way of counting words. */ char **av; char *as; int ac; av = brk_string(nstr, &ac, FALSE, &as); snprintf(newStr, newStrSize, "%d", ac); free(as); free(av); } termc = *cp; free(estr); break; } else if (estr[0] == '*' && estr[1] == '\0') { /* Found ":[*]" */ parsestate.oneBigWord = TRUE; newStr = nstr; termc = *cp; free(estr); break; } else if (estr[0] == '@' && estr[1] == '\0') { /* Found ":[@]" */ parsestate.oneBigWord = FALSE; newStr = nstr; termc = *cp; free(estr); break; } else { /* * We expect estr to contain a single * integer for :[N], or two integers * separated by ".." for :[start..end]. */ VarSelectWords_t seldata = { 0, 0 }; seldata.start = strtol(estr, &ep, 0); if (ep == estr) { /* Found junk instead of a number */ free(estr); goto bad_modifier; } else if (ep[0] == '\0') { /* Found only one integer in :[N] */ seldata.end = seldata.start; } else if (ep[0] == '.' && ep[1] == '.' && ep[2] != '\0') { /* Expecting another integer after ".." */ ep += 2; seldata.end = strtol(ep, &ep, 0); if (ep[0] != '\0') { /* Found junk after ".." */ free(estr); goto bad_modifier; } } else { /* Found junk instead of ".." */ free(estr); goto bad_modifier; } /* * Now seldata is properly filled in, * but we still have to check for 0 as * a special case. */ if (seldata.start == 0 && seldata.end == 0) { /* ":[0]" or perhaps ":[0..0]" */ parsestate.oneBigWord = TRUE; newStr = nstr; termc = *cp; free(estr); break; } else if (seldata.start == 0 || seldata.end == 0) { /* ":[0..N]" or ":[N..0]" */ free(estr); goto bad_modifier; } /* * Normal case: select the words * described by seldata. */ newStr = VarSelectWords(ctxt, &parsestate, nstr, &seldata); termc = *cp; free(estr); break; } } case 'g': cp = tstr + 1; /* make sure it is set */ if (STRMOD_MATCHX(tstr, "gmtime", 6)) { if (tstr[6] == '=') { utc = strtoul(&tstr[7], &ep, 10); cp = ep; } else { utc = 0; cp = tstr + 6; } newStr = VarStrftime(nstr, 1, utc); termc = *cp; } else { goto default_case; } break; case 'h': cp = tstr + 1; /* make sure it is set */ if (STRMOD_MATCH(tstr, "hash", 4)) { newStr = VarHash(nstr); cp = tstr + 4; termc = *cp; } else { goto default_case; } break; case 'l': cp = tstr + 1; /* make sure it is set */ if (STRMOD_MATCHX(tstr, "localtime", 9)) { if (tstr[9] == '=') { utc = strtoul(&tstr[10], &ep, 10); cp = ep; } else { utc = 0; cp = tstr + 9; } newStr = VarStrftime(nstr, 0, utc); termc = *cp; } else { goto default_case; } break; case 't': { cp = tstr + 1; /* make sure it is set */ if (tstr[1] != endc && tstr[1] != ':') { if (tstr[1] == 's') { /* * Use the char (if any) at tstr[2] * as the word separator. */ VarPattern pattern; if (tstr[2] != endc && (tstr[3] == endc || tstr[3] == ':')) { /* ":ts" or * ":ts:" */ parsestate.varSpace = tstr[2]; cp = tstr + 3; } else if (tstr[2] == endc || tstr[2] == ':') { /* ":ts" or ":ts:" */ parsestate.varSpace = 0; /* no separator */ cp = tstr + 2; } else if (tstr[2] == '\\') { const char *xp = &tstr[3]; int base = 8; /* assume octal */ switch (tstr[3]) { case 'n': parsestate.varSpace = '\n'; cp = tstr + 4; break; case 't': parsestate.varSpace = '\t'; cp = tstr + 4; break; case 'x': base = 16; xp++; goto get_numeric; case '0': base = 0; goto get_numeric; default: if (isdigit((unsigned char)tstr[3])) { get_numeric: parsestate.varSpace = strtoul(xp, &ep, base); if (*ep != ':' && *ep != endc) goto bad_modifier; cp = ep; } else { /* * ":ts". */ goto bad_modifier; } break; } } else { /* * Found ":ts". */ goto bad_modifier; } termc = *cp; /* * We cannot be certain that VarModify * will be used - even if there is a * subsequent modifier, so do a no-op * VarSubstitute now to for str to be * re-expanded without the spaces. */ pattern.flags = VAR_SUB_ONE; pattern.lhs = pattern.rhs = "\032"; pattern.leftLen = pattern.rightLen = 1; newStr = VarModify(ctxt, &parsestate, nstr, VarSubstitute, &pattern); } else if (tstr[2] == endc || tstr[2] == ':') { /* * Check for two-character options: * ":tu", ":tl" */ if (tstr[1] == 'A') { /* absolute path */ newStr = VarModify(ctxt, &parsestate, nstr, VarRealpath, NULL); cp = tstr + 2; termc = *cp; } else if (tstr[1] == 'u') { char *dp = bmake_strdup(nstr); for (newStr = dp; *dp; dp++) *dp = toupper((unsigned char)*dp); cp = tstr + 2; termc = *cp; } else if (tstr[1] == 'l') { char *dp = bmake_strdup(nstr); for (newStr = dp; *dp; dp++) *dp = tolower((unsigned char)*dp); cp = tstr + 2; termc = *cp; } else if (tstr[1] == 'W' || tstr[1] == 'w') { parsestate.oneBigWord = (tstr[1] == 'W'); newStr = nstr; cp = tstr + 2; termc = *cp; } else { /* Found ":t:" or * ":t". */ goto bad_modifier; } } else { /* * Found ":t". */ goto bad_modifier; } } else { /* * Found ":t" or ":t:". */ goto bad_modifier; } break; } case 'N': case 'M': { char *pattern; const char *endpat; /* points just after end of pattern */ char *cp2; Boolean copy; /* pattern should be, or has been, copied */ Boolean needSubst; int nest; copy = FALSE; needSubst = FALSE; nest = 1; /* * In the loop below, ignore ':' unless we are at * (or back to) the original brace level. * XXX This will likely not work right if $() and ${} * are intermixed. */ for (cp = tstr + 1; *cp != '\0' && !(*cp == ':' && nest == 1); cp++) { if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc || cp[1] == startc)) { if (!needSubst) { copy = TRUE; } cp++; continue; } if (*cp == '$') { needSubst = TRUE; } if (*cp == '(' || *cp == '{') ++nest; if (*cp == ')' || *cp == '}') { --nest; if (nest == 0) break; } } termc = *cp; endpat = cp; if (copy) { /* * Need to compress the \:'s out of the pattern, so * allocate enough room to hold the uncompressed * pattern (note that cp started at tstr+1, so * cp - tstr takes the null byte into account) and * compress the pattern into the space. */ pattern = bmake_malloc(cp - tstr); for (cp2 = pattern, cp = tstr + 1; cp < endpat; cp++, cp2++) { if ((*cp == '\\') && (cp+1 < endpat) && (cp[1] == ':' || cp[1] == endc)) { cp++; } *cp2 = *cp; } *cp2 = '\0'; endpat = cp2; } else { /* * Either Var_Subst or VarModify will need a * nul-terminated string soon, so construct one now. */ pattern = bmake_strndup(tstr+1, endpat - (tstr + 1)); } if (needSubst) { /* * pattern contains embedded '$', so use Var_Subst to * expand it. */ cp2 = pattern; pattern = Var_Subst(NULL, cp2, ctxt, flags | VARF_WANTRES); free(cp2); } if (DEBUG(VAR)) fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n", v->name, nstr, pattern); if (*tstr == 'M') { newStr = VarModify(ctxt, &parsestate, nstr, VarMatch, pattern); } else { newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch, pattern); } free(pattern); break; } case 'S': { VarPattern pattern; Var_Parse_State tmpparsestate; pattern.flags = 0; tmpparsestate = parsestate; delim = tstr[1]; tstr += 2; /* * If pattern begins with '^', it is anchored to the * start of the word -- skip over it and flag pattern. */ if (*tstr == '^') { pattern.flags |= VAR_MATCH_START; tstr += 1; } cp = tstr; if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, &pattern.flags, &pattern.leftLen, NULL)) == NULL) goto cleanup; if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, NULL, &pattern.rightLen, &pattern)) == NULL) goto cleanup; /* * Check for global substitution. If 'g' after the final * delimiter, substitution is global and is marked that * way. */ for (;; cp++) { switch (*cp) { case 'g': pattern.flags |= VAR_SUB_GLOBAL; continue; case '1': pattern.flags |= VAR_SUB_ONE; continue; case 'W': tmpparsestate.oneBigWord = TRUE; continue; } break; } termc = *cp; newStr = VarModify(ctxt, &tmpparsestate, nstr, VarSubstitute, &pattern); /* * Free the two strings. */ free(UNCONST(pattern.lhs)); free(UNCONST(pattern.rhs)); delim = '\0'; break; } case '?': { VarPattern pattern; Boolean value; int cond_rc; int lhs_flags, rhs_flags; /* find ':', and then substitute accordingly */ if (flags & VARF_WANTRES) { cond_rc = Cond_EvalExpression(NULL, v->name, &value, 0, FALSE); if (cond_rc == COND_INVALID) { lhs_flags = rhs_flags = VAR_NOSUBST; } else if (value) { lhs_flags = 0; rhs_flags = VAR_NOSUBST; } else { lhs_flags = VAR_NOSUBST; rhs_flags = 0; } } else { /* we are just consuming and discarding */ cond_rc = value = 0; lhs_flags = rhs_flags = VAR_NOSUBST; } pattern.flags = 0; cp = ++tstr; delim = ':'; if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, &lhs_flags, &pattern.leftLen, NULL)) == NULL) goto cleanup; /* BROPEN or PROPEN */ delim = endc; if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, &rhs_flags, &pattern.rightLen, NULL)) == NULL) goto cleanup; termc = *--cp; delim = '\0'; if (cond_rc == COND_INVALID) { Error("Bad conditional expression `%s' in %s?%s:%s", v->name, v->name, pattern.lhs, pattern.rhs); goto cleanup; } if (value) { newStr = UNCONST(pattern.lhs); free(UNCONST(pattern.rhs)); } else { newStr = UNCONST(pattern.rhs); free(UNCONST(pattern.lhs)); } if (v->flags & VAR_JUNK) { v->flags |= VAR_KEEP; } break; } #ifndef NO_REGEX case 'C': { VarREPattern pattern; char *re; int error; Var_Parse_State tmpparsestate; pattern.flags = 0; tmpparsestate = parsestate; delim = tstr[1]; tstr += 2; cp = tstr; if ((re = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, NULL, NULL, NULL)) == NULL) goto cleanup; if ((pattern.replace = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, NULL, NULL, NULL)) == NULL){ free(re); goto cleanup; } for (;; cp++) { switch (*cp) { case 'g': pattern.flags |= VAR_SUB_GLOBAL; continue; case '1': pattern.flags |= VAR_SUB_ONE; continue; case 'W': tmpparsestate.oneBigWord = TRUE; continue; } break; } termc = *cp; error = regcomp(&pattern.re, re, REG_EXTENDED); free(re); if (error) { *lengthPtr = cp - start + 1; VarREError(error, &pattern.re, "RE substitution error"); free(pattern.replace); goto cleanup; } pattern.nsub = pattern.re.re_nsub + 1; if (pattern.nsub < 1) pattern.nsub = 1; if (pattern.nsub > 10) pattern.nsub = 10; pattern.matches = bmake_malloc(pattern.nsub * sizeof(regmatch_t)); newStr = VarModify(ctxt, &tmpparsestate, nstr, VarRESubstitute, &pattern); regfree(&pattern.re); free(pattern.replace); free(pattern.matches); delim = '\0'; break; } #endif + case 'q': case 'Q': if (tstr[1] == endc || tstr[1] == ':') { - newStr = VarQuote(nstr); + newStr = VarQuote(nstr, modifier == 'q'); cp = tstr + 1; termc = *cp; break; } goto default_case; case 'T': if (tstr[1] == endc || tstr[1] == ':') { newStr = VarModify(ctxt, &parsestate, nstr, VarTail, NULL); cp = tstr + 1; termc = *cp; break; } goto default_case; case 'H': if (tstr[1] == endc || tstr[1] == ':') { newStr = VarModify(ctxt, &parsestate, nstr, VarHead, NULL); cp = tstr + 1; termc = *cp; break; } goto default_case; case 'E': if (tstr[1] == endc || tstr[1] == ':') { newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix, NULL); cp = tstr + 1; termc = *cp; break; } goto default_case; case 'R': if (tstr[1] == endc || tstr[1] == ':') { newStr = VarModify(ctxt, &parsestate, nstr, VarRoot, NULL); cp = tstr + 1; termc = *cp; break; } goto default_case; case 'r': cp = tstr + 1; /* make sure it is set */ if (STRMOD_MATCHX(tstr, "range", 5)) { int n; if (tstr[5] == '=') { n = strtoul(&tstr[6], &ep, 10); cp = ep; } else { n = 0; cp = tstr + 5; } newStr = VarRange(nstr, n); termc = *cp; break; } goto default_case; case 'O': { char otype; cp = tstr + 1; /* skip to the rest in any case */ if (tstr[1] == endc || tstr[1] == ':') { otype = 's'; termc = *cp; } else if ( (tstr[1] == 'x') && (tstr[2] == endc || tstr[2] == ':') ) { otype = tstr[1]; cp = tstr + 2; termc = *cp; } else { goto bad_modifier; } newStr = VarOrder(nstr, otype); break; } case 'u': if (tstr[1] == endc || tstr[1] == ':') { newStr = VarUniq(nstr); cp = tstr + 1; termc = *cp; break; } goto default_case; #ifdef SUNSHCMD case 's': if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) { const char *emsg; if (flags & VARF_WANTRES) { newStr = Cmd_Exec(nstr, &emsg); if (emsg) Error(emsg, nstr); } else newStr = varNoError; cp = tstr + 2; termc = *cp; break; } goto default_case; #endif default: default_case: { #ifdef SYSVVARSUB /* * This can either be a bogus modifier or a System-V * substitution command. */ VarPattern pattern; Boolean eqFound; pattern.flags = 0; eqFound = FALSE; /* * First we make a pass through the string trying * to verify it is a SYSV-make-style translation: * it must be: =) */ cp = tstr; cnt = 1; while (*cp != '\0' && cnt) { if (*cp == '=') { eqFound = TRUE; /* continue looking for endc */ } else if (*cp == endc) cnt--; else if (*cp == startc) cnt++; if (cnt) cp++; } if (*cp == endc && eqFound) { /* * Now we break this sucker into the lhs and * rhs. We must null terminate them of course. */ delim='='; cp = tstr; if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, &pattern.flags, &pattern.leftLen, NULL)) == NULL) goto cleanup; delim = endc; if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, flags, &cp, delim, NULL, &pattern.rightLen, &pattern)) == NULL) goto cleanup; /* * SYSV modifications happen through the whole * string. Note the pattern is anchored at the end. */ termc = *--cp; delim = '\0'; if (pattern.leftLen == 0 && *nstr == '\0') { newStr = nstr; /* special case */ } else { newStr = VarModify(ctxt, &parsestate, nstr, VarSYSVMatch, &pattern); } free(UNCONST(pattern.lhs)); free(UNCONST(pattern.rhs)); } else #endif { Error("Unknown modifier '%c'", *tstr); for (cp = tstr+1; *cp != ':' && *cp != endc && *cp != '\0'; cp++) continue; termc = *cp; newStr = var_Error; } } } if (DEBUG(VAR)) { fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n", v->name, modifier, newStr); } if (newStr != nstr) { if (*freePtr) { free(nstr); *freePtr = NULL; } nstr = newStr; if (nstr != var_Error && nstr != varNoError) { *freePtr = nstr; } } if (termc == '\0' && endc != '\0') { Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier); } else if (termc == ':') { cp++; } tstr = cp; } out: *lengthPtr = tstr - start; return (nstr); bad_modifier: /* "{(" */ Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr, v->name); cleanup: *lengthPtr = cp - start; if (delim != '\0') Error("Unclosed substitution for %s (%c missing)", v->name, delim); free(*freePtr); *freePtr = NULL; return (var_Error); } /*- *----------------------------------------------------------------------- * Var_Parse -- * Given the start of a variable invocation, extract the variable * name and find its value, then modify it according to the * specification. * * Input: * str The string to parse * ctxt The context for the variable * flags VARF_UNDEFERR if undefineds are an error * VARF_WANTRES if we actually want the result * VARF_ASSIGN if we are in a := assignment * lengthPtr OUT: The length of the specification * freePtr OUT: Non-NULL if caller should free *freePtr * * Results: * The (possibly-modified) value of the variable or var_Error if the * specification is invalid. The length of the specification is * placed in *lengthPtr (for invalid specifications, this is just * 2...?). * If *freePtr is non-NULL then it's a pointer that the caller * should pass to free() to free memory used by the result. * * Side Effects: * None. * *----------------------------------------------------------------------- */ /* coverity[+alloc : arg-*4] */ char * Var_Parse(const char *str, GNode *ctxt, int flags, int *lengthPtr, void **freePtr) { const char *tstr; /* Pointer into str */ Var *v; /* Variable in invocation */ Boolean haveModifier;/* TRUE if have modifiers for the variable */ char endc; /* Ending character when variable in parens * or braces */ char startc; /* Starting character when variable in parens * or braces */ int vlen; /* Length of variable name */ const char *start; /* Points to original start of str */ char *nstr; /* New string, used during expansion */ Boolean dynamic; /* TRUE if the variable is local and we're * expanding it in a non-local context. This * is done to support dynamic sources. The * result is just the invocation, unaltered */ const char *extramodifiers; /* extra modifiers to apply first */ char name[2]; *freePtr = NULL; extramodifiers = NULL; dynamic = FALSE; start = str; startc = str[1]; if (startc != PROPEN && startc != BROPEN) { /* * If it's not bounded by braces of some sort, life is much simpler. * We just need to check for the first character and return the * value if it exists. */ /* Error out some really stupid names */ if (startc == '\0' || strchr(")}:$", startc)) { *lengthPtr = 1; return var_Error; } name[0] = startc; name[1] = '\0'; v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); if (v == NULL) { *lengthPtr = 2; if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) { /* * If substituting a local variable in a non-local context, * assume it's for dynamic source stuff. We have to handle * this specially and return the longhand for the variable * with the dollar sign escaped so it makes it back to the * caller. Only four of the local variables are treated * specially as they are the only four that will be set * when dynamic sources are expanded. */ switch (str[1]) { case '@': return UNCONST("$(.TARGET)"); case '%': return UNCONST("$(.MEMBER)"); case '*': return UNCONST("$(.PREFIX)"); case '!': return UNCONST("$(.ARCHIVE)"); } } /* * Error */ return (flags & VARF_UNDEFERR) ? var_Error : varNoError; } else { haveModifier = FALSE; tstr = &str[1]; endc = str[1]; } } else { Buffer buf; /* Holds the variable name */ int depth = 1; endc = startc == PROPEN ? PRCLOSE : BRCLOSE; Buf_Init(&buf, 0); /* * Skip to the end character or a colon, whichever comes first. */ for (tstr = str + 2; *tstr != '\0'; tstr++) { /* * Track depth so we can spot parse errors. */ if (*tstr == startc) { depth++; } if (*tstr == endc) { if (--depth == 0) break; } if (depth == 1 && *tstr == ':') { break; } /* * A variable inside a variable, expand */ if (*tstr == '$') { int rlen; void *freeIt; char *rval = Var_Parse(tstr, ctxt, flags, &rlen, &freeIt); if (rval != NULL) { Buf_AddBytes(&buf, strlen(rval), rval); } free(freeIt); tstr += rlen - 1; } else Buf_AddByte(&buf, *tstr); } if (*tstr == ':') { haveModifier = TRUE; } else if (*tstr == endc) { haveModifier = FALSE; } else { /* * If we never did find the end character, return NULL * right now, setting the length to be the distance to * the end of the string, since that's what make does. */ *lengthPtr = tstr - str; Buf_Destroy(&buf, TRUE); return (var_Error); } str = Buf_GetAll(&buf, &vlen); /* * At this point, str points into newly allocated memory from * buf, containing only the name of the variable. * * start and tstr point into the const string that was pointed * to by the original value of the str parameter. start points * to the '$' at the beginning of the string, while tstr points * to the char just after the end of the variable name -- this * will be '\0', ':', PRCLOSE, or BRCLOSE. */ v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD); /* * Check also for bogus D and F forms of local variables since we're * in a local context and the name is the right length. */ if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) && (vlen == 2) && (str[1] == 'F' || str[1] == 'D') && strchr("@%?*!<>", str[0]) != NULL) { /* * Well, it's local -- go look for it. */ name[0] = *str; name[1] = '\0'; v = VarFind(name, ctxt, 0); if (v != NULL) { if (str[1] == 'D') { extramodifiers = "H:"; } else { /* F */ extramodifiers = "T:"; } } } if (v == NULL) { if (((vlen == 1) || (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) && ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL))) { /* * If substituting a local variable in a non-local context, * assume it's for dynamic source stuff. We have to handle * this specially and return the longhand for the variable * with the dollar sign escaped so it makes it back to the * caller. Only four of the local variables are treated * specially as they are the only four that will be set * when dynamic sources are expanded. */ switch (*str) { case '@': case '%': case '*': case '!': dynamic = TRUE; break; } } else if ((vlen > 2) && (*str == '.') && isupper((unsigned char) str[1]) && ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL))) { int len; len = vlen - 1; if ((strncmp(str, ".TARGET", len) == 0) || (strncmp(str, ".ARCHIVE", len) == 0) || (strncmp(str, ".PREFIX", len) == 0) || (strncmp(str, ".MEMBER", len) == 0)) { dynamic = TRUE; } } if (!haveModifier) { /* * No modifiers -- have specification length so we can return * now. */ *lengthPtr = tstr - start + 1; if (dynamic) { char *pstr = bmake_strndup(start, *lengthPtr); *freePtr = pstr; Buf_Destroy(&buf, TRUE); return(pstr); } else { Buf_Destroy(&buf, TRUE); return (flags & VARF_UNDEFERR) ? var_Error : varNoError; } } else { /* * Still need to get to the end of the variable specification, * so kludge up a Var structure for the modifications */ v = bmake_malloc(sizeof(Var)); v->name = UNCONST(str); Buf_Init(&v->val, 1); v->flags = VAR_JUNK; Buf_Destroy(&buf, FALSE); } } else Buf_Destroy(&buf, TRUE); } if (v->flags & VAR_IN_USE) { Fatal("Variable %s is recursive.", v->name); /*NOTREACHED*/ } else { v->flags |= VAR_IN_USE; } /* * Before doing any modification, we have to make sure the value * has been fully expanded. If it looks like recursion might be * necessary (there's a dollar sign somewhere in the variable's value) * we just call Var_Subst to do any other substitutions that are * necessary. Note that the value returned by Var_Subst will have * been dynamically-allocated, so it will need freeing when we * return. */ nstr = Buf_GetAll(&v->val, NULL); if (strchr(nstr, '$') != NULL) { nstr = Var_Subst(NULL, nstr, ctxt, flags); *freePtr = nstr; } v->flags &= ~VAR_IN_USE; if ((nstr != NULL) && (haveModifier || extramodifiers != NULL)) { void *extraFree; int used; extraFree = NULL; if (extramodifiers != NULL) { nstr = ApplyModifiers(nstr, extramodifiers, '(', ')', v, ctxt, flags, &used, &extraFree); } if (haveModifier) { /* Skip initial colon. */ tstr++; nstr = ApplyModifiers(nstr, tstr, startc, endc, v, ctxt, flags, &used, freePtr); tstr += used; free(extraFree); } else { *freePtr = extraFree; } } if (*tstr) { *lengthPtr = tstr - start + 1; } else { *lengthPtr = tstr - start; } if (v->flags & VAR_FROM_ENV) { Boolean destroy = FALSE; if (nstr != Buf_GetAll(&v->val, NULL)) { destroy = TRUE; } else { /* * Returning the value unmodified, so tell the caller to free * the thing. */ *freePtr = nstr; } VarFreeEnv(v, destroy); } else if (v->flags & VAR_JUNK) { /* * Perform any free'ing needed and set *freePtr to NULL so the caller * doesn't try to free a static pointer. * If VAR_KEEP is also set then we want to keep str as is. */ if (!(v->flags & VAR_KEEP)) { if (*freePtr) { free(nstr); *freePtr = NULL; } if (dynamic) { nstr = bmake_strndup(start, *lengthPtr); *freePtr = nstr; } else { nstr = (flags & VARF_UNDEFERR) ? var_Error : varNoError; } } if (nstr != Buf_GetAll(&v->val, NULL)) Buf_Destroy(&v->val, TRUE); free(v->name); free(v); } return (nstr); } /*- *----------------------------------------------------------------------- * Var_Subst -- * Substitute for all variables in the given string in the given context * If flags & VARF_UNDEFERR, Parse_Error will be called when an undefined * variable is encountered. * * Input: * var Named variable || NULL for all * str the string which to substitute * ctxt the context wherein to find variables * flags VARF_UNDEFERR if undefineds are an error * VARF_WANTRES if we actually want the result * VARF_ASSIGN if we are in a := assignment * * Results: * The resulting string. * * Side Effects: * None. The old string must be freed by the caller *----------------------------------------------------------------------- */ char * Var_Subst(const char *var, const char *str, GNode *ctxt, int flags) { Buffer buf; /* Buffer for forming things */ char *val; /* Value to substitute for a variable */ int length; /* Length of the variable invocation */ Boolean trailingBslash; /* variable ends in \ */ void *freeIt = NULL; /* Set if it should be freed */ static Boolean errorReported; /* Set true if an error has already * been reported to prevent a plethora * of messages when recursing */ Buf_Init(&buf, 0); errorReported = FALSE; trailingBslash = FALSE; while (*str) { if (*str == '\n' && trailingBslash) Buf_AddByte(&buf, ' '); if (var == NULL && (*str == '$') && (str[1] == '$')) { /* * A dollar sign may be escaped either with another dollar sign. * In such a case, we skip over the escape character and store the * dollar sign into the buffer directly. */ if (save_dollars && (flags & VARF_ASSIGN)) Buf_AddByte(&buf, *str); str++; Buf_AddByte(&buf, *str); str++; } else if (*str != '$') { /* * Skip as many characters as possible -- either to the end of * the string or to the next dollar sign (variable invocation). */ const char *cp; for (cp = str++; *str != '$' && *str != '\0'; str++) continue; Buf_AddBytes(&buf, str - cp, cp); } else { if (var != NULL) { int expand; for (;;) { if (str[1] == '\0') { /* A trailing $ is kind of a special case */ Buf_AddByte(&buf, str[0]); str++; expand = FALSE; } else if (str[1] != PROPEN && str[1] != BROPEN) { if (str[1] != *var || strlen(var) > 1) { Buf_AddBytes(&buf, 2, str); str += 2; expand = FALSE; } else expand = TRUE; break; } else { const char *p; /* * Scan up to the end of the variable name. */ for (p = &str[2]; *p && *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++) if (*p == '$') break; /* * A variable inside the variable. We cannot expand * the external variable yet, so we try again with * the nested one */ if (*p == '$') { Buf_AddBytes(&buf, p - str, str); str = p; continue; } if (strncmp(var, str + 2, p - str - 2) != 0 || var[p - str - 2] != '\0') { /* * Not the variable we want to expand, scan * until the next variable */ for (;*p != '$' && *p != '\0'; p++) continue; Buf_AddBytes(&buf, p - str, str); str = p; expand = FALSE; } else expand = TRUE; break; } } if (!expand) continue; } val = Var_Parse(str, ctxt, flags, &length, &freeIt); /* * When we come down here, val should either point to the * value of this variable, suitably modified, or be NULL. * Length should be the total length of the potential * variable invocation (from $ to end character...) */ if (val == var_Error || val == varNoError) { /* * If performing old-time variable substitution, skip over * the variable and continue with the substitution. Otherwise, * store the dollar sign and advance str so we continue with * the string... */ if (oldVars) { str += length; } else if ((flags & VARF_UNDEFERR) || val == var_Error) { /* * If variable is undefined, complain and skip the * variable. The complaint will stop us from doing anything * when the file is parsed. */ if (!errorReported) { Parse_Error(PARSE_FATAL, "Undefined variable \"%.*s\"",length,str); } str += length; errorReported = TRUE; } else { Buf_AddByte(&buf, *str); str += 1; } } else { /* * We've now got a variable structure to store in. But first, * advance the string pointer. */ str += length; /* * Copy all the characters from the variable value straight * into the new string. */ length = strlen(val); Buf_AddBytes(&buf, length, val); trailingBslash = length > 0 && val[length - 1] == '\\'; } free(freeIt); freeIt = NULL; } } return Buf_DestroyCompact(&buf); } /*- *----------------------------------------------------------------------- * Var_GetTail -- * Return the tail from each of a list of words. Used to set the * System V local variables. * * Input: * file Filename to modify * * Results: * The resulting string. * * Side Effects: * None. * *----------------------------------------------------------------------- */ #if 0 char * Var_GetTail(char *file) { return(VarModify(file, VarTail, NULL)); } /*- *----------------------------------------------------------------------- * Var_GetHead -- * Find the leading components of a (list of) filename(s). * XXX: VarHead does not replace foo by ., as (sun) System V make * does. * * Input: * file Filename to manipulate * * Results: * The leading components. * * Side Effects: * None. * *----------------------------------------------------------------------- */ char * Var_GetHead(char *file) { return(VarModify(file, VarHead, NULL)); } #endif /*- *----------------------------------------------------------------------- * Var_Init -- * Initialize the module * * Results: * None * * Side Effects: * The VAR_CMD and VAR_GLOBAL contexts are created *----------------------------------------------------------------------- */ void Var_Init(void) { VAR_INTERNAL = Targ_NewGN("Internal"); VAR_GLOBAL = Targ_NewGN("Global"); VAR_CMD = Targ_NewGN("Command"); } void Var_End(void) { } /****************** PRINT DEBUGGING INFO *****************/ static void VarPrintVar(void *vp) { Var *v = (Var *)vp; fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL)); } /*- *----------------------------------------------------------------------- * Var_Dump -- * print all variables in a context *----------------------------------------------------------------------- */ void Var_Dump(GNode *ctxt) { Hash_Search search; Hash_Entry *h; for (h = Hash_EnumFirst(&ctxt->context, &search); h != NULL; h = Hash_EnumNext(&search)) { VarPrintVar(Hash_GetValue(h)); } } Index: stable/12/usr.bin/bmake/Makefile =================================================================== --- stable/12/usr.bin/bmake/Makefile (revision 361673) +++ stable/12/usr.bin/bmake/Makefile (revision 361674) @@ -1,175 +1,186 @@ # This is a generated file, do NOT edit! # See contrib/bmake/bsd.after-import.mk # # $FreeBSD$ -.sinclude "Makefile.inc" - SRCTOP?= ${.CURDIR:H:H} # look here first for config.h CFLAGS+= -I${.CURDIR} # for after-import CLEANDIRS+= FreeBSD CLEANFILES+= bootstrap -# $Id: Makefile,v 1.99 2017/08/13 20:12:53 sjg Exp $ +# $Id: Makefile,v 1.104 2020/02/06 01:33:54 sjg Exp $ PROG?= ${.CURDIR:T} SRCS= \ arch.c \ buf.c \ compat.c \ cond.c \ dir.c \ for.c \ hash.c \ job.c \ main.c \ make.c \ make_malloc.c \ meta.c \ metachar.c \ parse.c \ str.c \ strlist.c \ suff.c \ targ.c \ trace.c \ util.c \ var.c # from lst.lib/ SRCS+= \ lstAppend.c \ lstAtEnd.c \ lstAtFront.c \ lstClose.c \ lstConcat.c \ lstDatum.c \ lstDeQueue.c \ lstDestroy.c \ lstDupl.c \ lstEnQueue.c \ lstFind.c \ lstFindFrom.c \ lstFirst.c \ lstForEach.c \ lstForEachFrom.c \ lstInit.c \ lstInsert.c \ lstIsAtEnd.c \ lstIsEmpty.c \ lstLast.c \ lstMember.c \ lstNext.c \ lstOpen.c \ lstPrev.c \ lstRemove.c \ lstReplace.c \ lstSucc.c +.sinclude "Makefile.inc" # this file gets generated by configure .sinclude "Makefile.config" .if !empty(LIBOBJS) SRCS+= ${LIBOBJS:T:.o=.c} .endif # just in case prefix?= /usr srcdir?= ${.CURDIR} DEFAULT_SYS_PATH?= ${prefix}/share/mk CPPFLAGS+= -DUSE_META CFLAGS+= ${CPPFLAGS} CFLAGS+= -D_PATH_DEFSYSPATH=\"${DEFAULT_SYS_PATH}\" CFLAGS+= -I. -I${srcdir} ${XDEFS} -DMAKE_NATIVE CFLAGS+= ${COPTS.${.ALLSRC:M*.c:T:u}} COPTS.main.c+= "-DMAKE_VERSION=\"${_MAKE_VERSION}\"" -# meta mode can be useful even without filemon +# meta mode can be useful even without filemon +# should be set by now +USE_FILEMON ?= no +.if ${USE_FILEMON:tl} != "no" +.PATH: ${srcdir}/filemon +SRCS+= filemon_${USE_FILEMON}.c +COPTS.meta.c+= -DUSE_FILEMON -DUSE_FILEMON_${USE_FILEMON:tu} +COPTS.job.c+= ${COPTS.meta.c} + +.if ${USE_FILEMON} == "dev" FILEMON_H ?= /usr/include/dev/filemon/filemon.h .if exists(${FILEMON_H}) && ${FILEMON_H:T} == "filemon.h" -COPTS.meta.c += -DHAVE_FILEMON_H -I${FILEMON_H:H} +COPTS.filemon_dev.c += -DHAVE_FILEMON_H -I${FILEMON_H:H} .endif +.endif # USE_FILEMON == dev + +.endif # USE_FILEMON .PATH: ${srcdir} .PATH: ${srcdir}/lst.lib .if make(obj) || make(clean) SUBDIR+= unit-tests .endif MAN= ${PROG}.1 MAN1= ${MAN} .if (${PROG} != "make") CLEANFILES+= my.history .if make(${MAN}) || !exists(${srcdir}/${MAN}) my.history: ${MAKEFILE} @(echo ".Nm"; \ echo "is derived from NetBSD"; \ echo ".Xr make 1 ."; \ echo "It uses autoconf to facilitate portability to other platforms."; \ echo ".Pp") > $@ .NOPATH: ${MAN} ${MAN}: make.1 my.history @echo making $@ @sed \ -e '/^.Dt/s/MAKE/${PROG:tu}/' \ -e 's/^.Nx/NetBSD/' \ -e '/^.Nm/s/make/${PROG}/' \ -e '/^.Sh HISTORY/rmy.history' \ -e '/^.Sh HISTORY/,$$s,^.Nm,make,' ${srcdir}/make.1 > $@ all beforeinstall: ${MAN} _mfromdir=. .endif .endif MANTARGET?= cat MANDEST?= ${MANDIR}/${MANTARGET}1 .if ${MANTARGET} == "cat" _mfromdir=${srcdir} .endif .include CPPFLAGS+= -DMAKE_NATIVE -DHAVE_CONFIG_H COPTS.var.c += -Wno-cast-qual COPTS.job.c += -Wno-format-nonliteral COPTS.parse.c += -Wno-format-nonliteral COPTS.var.c += -Wno-format-nonliteral # Force these SHAREDIR= ${SHAREDIR.bmake:U${prefix}/share} BINDIR= ${BINDIR.bmake:U${prefix}/bin} MANDIR= ${MANDIR.bmake:U${SHAREDIR}/man} .if !exists(.depend) ${OBJS}: config.h .endif # A simple unit-test driver to help catch regressions accept test: cd ${.CURDIR}/unit-tests && MAKEFLAGS= ${.MAKE} -r -m / TEST_MAKE=${TEST_MAKE:U${.OBJDIR}/${PROG:T}} ${.TARGET} # override some simple things BINDIR= /usr/bin MANDIR= /usr/share/man/man # make sure we get this CFLAGS+= ${COPTS.${.IMPSRC:T}} after-import: ${SRCTOP}/contrib/bmake/bsd.after-import.mk cd ${.CURDIR} && ${.MAKE} -f ${SRCTOP}/contrib/bmake/bsd.after-import.mk Index: stable/12/usr.bin/bmake/Makefile.config =================================================================== --- stable/12/usr.bin/bmake/Makefile.config (revision 361673) +++ stable/12/usr.bin/bmake/Makefile.config (revision 361674) @@ -1,26 +1,27 @@ # This is a generated file, do NOT edit! # See contrib/bmake/bsd.after-import.mk # # $FreeBSD$ SRCTOP?= ${.CURDIR:H:H} # things set by configure -_MAKE_VERSION=20180512 +_MAKE_VERSION?=20200517 prefix?= /usr srcdir= ${SRCTOP}/contrib/bmake CC?= cc DEFAULT_SYS_PATH?= .../share/mk:/usr/share/mk CPPFLAGS+= CFLAGS+= ${CPPFLAGS} -DHAVE_CONFIG_H LDFLAGS+= -LIBOBJS= ${LIBOBJDIR}stresep$U.o -LDADD= -USE_META= yes +LIBOBJS+= ${LIBOBJDIR}stresep$U.o +LDADD+= +USE_META?= yes +USE_FILEMON?= dev FILEMON_H?= /usr/include/dev/filemon/filemon.h BMAKE_PATH_MAX?= 1024 # used if MAXPATHLEN not defined CPPFLAGS+= -DBMAKE_PATH_MAX=${BMAKE_PATH_MAX} Index: stable/12/usr.bin/bmake/Makefile.depend =================================================================== --- stable/12/usr.bin/bmake/Makefile.depend (revision 361673) +++ stable/12/usr.bin/bmake/Makefile.depend (revision 361674) @@ -1,17 +1,16 @@ # $FreeBSD$ # Autogenerated - do NOT edit! DIRDEPS = \ - gnu/lib/csu \ include \ include/xlocale \ lib/${CSU_DIR} \ lib/libc \ lib/libcompiler_rt \ .include .if ${DEP_RELDIR} == ${_DEP_RELDIR} # local dependencies - needed for -jN in clean tree .endif Index: stable/12/usr.bin/bmake/config.h =================================================================== --- stable/12/usr.bin/bmake/config.h (revision 361673) +++ stable/12/usr.bin/bmake/config.h (revision 361674) @@ -1,346 +1,346 @@ /* $FreeBSD$ */ /* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.in by autoheader. */ /* Define if building universal (internal helper macro) */ /* #undef AC_APPLE_UNIVERSAL_BUILD */ /* Path of default shell */ /* #undef DEFSHELL_CUSTOM */ /* Shell spec to use by default */ /* #undef DEFSHELL_INDEX */ /* Define to 1 if you have the header file. */ #define HAVE_AR_H 1 /* Define to 1 if you have the declaration of `sys_siglist', and to 0 if you don't. */ #define HAVE_DECL_SYS_SIGLIST 1 /* Define to 1 if you have the header file, and it defines `DIR'. */ #define HAVE_DIRENT_H 1 /* Define to 1 if you have the `dirname' function. */ #define HAVE_DIRNAME 1 /* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ /* #undef HAVE_DOPRNT */ /* Define to 1 if you have the `err' function. */ #define HAVE_ERR 1 /* Define to 1 if you have the `errx' function. */ #define HAVE_ERRX 1 /* Define to 1 if you have the header file. */ #define HAVE_ERR_H 1 /* Define to 1 if you have the header file. */ #define HAVE_FCNTL_H 1 /* Define to 1 if you have the `fork' function. */ #define HAVE_FORK 1 /* Define to 1 if you have the `getcwd' function. */ #define HAVE_GETCWD 1 /* Define to 1 if you have the `getenv' function. */ #define HAVE_GETENV 1 /* Define to 1 if you have the `getopt' function. */ #define HAVE_GETOPT 1 /* Define to 1 if you have the `getwd' function. */ #define HAVE_GETWD 1 /* Define to 1 if you have the header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `killpg' function. */ #define HAVE_KILLPG 1 /* Define to 1 if you have the header file. */ #define HAVE_LIBGEN_H 1 /* Define to 1 if you have the header file. */ #define HAVE_LIMITS_H 1 /* Define to 1 if you have the header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the `mmap' function. */ #define HAVE_MMAP 1 /* Define to 1 if you have the header file, and it defines `DIR'. */ /* #undef HAVE_NDIR_H */ /* Define to 1 if you have the header file. */ #define HAVE_PATHS_H 1 /* Define to 1 if you have the header file. */ #define HAVE_POLL_H 1 /* Define to 1 if you have the `putenv' function. */ #define HAVE_PUTENV 1 /* Define to 1 if you have the header file. */ #define HAVE_RANLIB_H 1 /* Define to 1 if you have the `realpath' function. */ #define HAVE_REALPATH 1 /* Define to 1 if you have the `select' function. */ #define HAVE_SELECT 1 /* Define to 1 if you have the `setenv' function. */ #define HAVE_SETENV 1 /* Define to 1 if you have the `setpgid' function. */ #define HAVE_SETPGID 1 /* Define to 1 if you have the `setsid' function. */ #define HAVE_SETSID 1 /* Define to 1 if you have the `sigaction' function. */ #define HAVE_SIGACTION 1 /* Define to 1 if you have the `sigvec' function. */ #define HAVE_SIGVEC 1 /* Define to 1 if you have the `snprintf' function. */ #define HAVE_SNPRINTF 1 /* Define to 1 if you have the header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the `strerror' function. */ #define HAVE_STRERROR 1 /* Define to 1 if you have the `stresep' function. */ /* #undef HAVE_STRESEP */ /* Define to 1 if you have the `strftime' function. */ #define HAVE_STRFTIME 1 /* Define to 1 if you have the header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the `strlcpy' function. */ #define HAVE_STRLCPY 1 /* Define to 1 if you have the `strsep' function. */ #define HAVE_STRSEP 1 /* Define to 1 if you have the `strtod' function. */ #define HAVE_STRTOD 1 /* Define to 1 if you have the `strtol' function. */ #define HAVE_STRTOL 1 -/* Define to 1 if `struct stat' is a member of `st_rdev'. */ +/* Define to 1 if `st_rdev' is a member of `struct stat'. */ #define HAVE_STRUCT_STAT_ST_RDEV 1 /* Define to 1 if your `struct stat' has `st_rdev'. Deprecated, use `HAVE_STRUCT_STAT_ST_RDEV' instead. */ #define HAVE_ST_RDEV 1 /* Define to 1 if you have the `sysctl' function. */ #define HAVE_SYSCTL 1 /* Define to 1 if you have the header file, and it defines `DIR'. */ /* #undef HAVE_SYS_DIR_H */ /* Define to 1 if you have the header file. */ #define HAVE_SYS_MMAN_H 1 /* Define to 1 if you have the header file, and it defines `DIR'. */ /* #undef HAVE_SYS_NDIR_H */ /* Define to 1 if you have the header file. */ #define HAVE_SYS_PARAM_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_SELECT_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_SOCKET_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_SYSCTL_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_TIME_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_UIO_H 1 /* Define to 1 if you have that is POSIX.1 compatible. */ #define HAVE_SYS_WAIT_H 1 /* Define to 1 if you have the header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the `unsetenv' function. */ #define HAVE_UNSETENV 1 /* Define to 1 if you have the header file. */ #define HAVE_UTIME_H 1 /* Define to 1 if you have the `vfork' function. */ #define HAVE_VFORK 1 /* Define to 1 if you have the header file. */ /* #undef HAVE_VFORK_H */ /* Define to 1 if you have the `vprintf' function. */ #define HAVE_VPRINTF 1 /* Define to 1 if you have the `vsnprintf' function. */ #define HAVE_VSNPRINTF 1 /* Define to 1 if you have the `wait3' function. */ #define HAVE_WAIT3 1 /* Define to 1 if you have the `wait4' function. */ #define HAVE_WAIT4 1 /* Define to 1 if you have the `waitpid' function. */ #define HAVE_WAITPID 1 /* Define to 1 if you have the `warn' function. */ #define HAVE_WARN 1 /* Define to 1 if you have the `warnx' function. */ #define HAVE_WARNX 1 /* Define to 1 if `fork' works. */ #define HAVE_WORKING_FORK 1 /* Define to 1 if `vfork' works. */ #define HAVE_WORKING_VFORK 1 /* define if your compiler has __attribute__ */ #define HAVE___ATTRIBUTE__ 1 /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "sjg@NetBSD.org" /* Define to the full name of this package. */ #define PACKAGE_NAME "bmake" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "bmake 20171126" +#define PACKAGE_STRING "bmake 20200418" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "bmake" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "20171126" +#define PACKAGE_VERSION "20200418" /* Define as the return type of signal handlers (`int' or `void'). */ #define RETSIGTYPE void /* Define to 1 if the `S_IS*' macros in do not work properly. */ /* #undef STAT_MACROS_BROKEN */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define to 1 if you can safely include both and . */ #define TIME_WITH_SYS_TIME 1 /* Define to 1 if your declares `struct tm'. */ /* #undef TM_IN_SYS_TIME */ /* Enable extensions on AIX 3, Interix. */ #ifndef _ALL_SOURCE # define _ALL_SOURCE 1 #endif /* Enable GNU extensions on systems that have them. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif /* Enable threading extensions on Solaris. */ #ifndef _POSIX_PTHREAD_SEMANTICS # define _POSIX_PTHREAD_SEMANTICS 1 #endif /* Enable extensions on HP NonStop. */ #ifndef _TANDEM_SOURCE # define _TANDEM_SOURCE 1 #endif /* Enable general extensions on Solaris. */ #ifndef __EXTENSIONS__ # define __EXTENSIONS__ 1 #endif /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN /* # undef WORDS_BIGENDIAN */ # endif #endif /* Define to 1 if on MINIX. */ /* #undef _MINIX */ /* Define to 2 if the system does not provide POSIX.1 features except with this defined. */ /* #undef _POSIX_1_SOURCE */ /* Define to 1 if you need to in order for `stat' and other things to work. */ /* #undef _POSIX_SOURCE */ /* Define for Solaris 2.5.1 so the uint32_t typedef from , , or is not used. If the typedef were allowed, the #define below would cause a syntax error. */ /* #undef _UINT32_T */ /* C99 function name */ /* #undef __func__ */ /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ /* Define to `int' if does not define. */ /* #undef mode_t */ /* Define to `long int' if does not define. */ /* #undef off_t */ /* Define to `int' if does not define. */ /* #undef pid_t */ /* Define to `unsigned int' if does not define. */ /* #undef size_t */ /* Define to the type of an unsigned integer type of width exactly 32 bits if such a type exists and the standard includes do not define it. */ /* #undef uint32_t */ /* Define as `fork' if `vfork' does not work. */ /* #undef vfork */ Index: stable/12/usr.bin/bmake/unit-tests/Makefile =================================================================== --- stable/12/usr.bin/bmake/unit-tests/Makefile (revision 361673) +++ stable/12/usr.bin/bmake/unit-tests/Makefile (revision 361674) @@ -1,158 +1,159 @@ # This is a generated file, do NOT edit! # See contrib/bmake/bsd.after-import.mk # # $FreeBSD$ SRCTOP?= ${.CURDIR:H:H:H} -# $Id: Makefile.in,v 1.48 2015/12/07 04:06:29 sjg Exp $ +# $Id: Makefile.in,v 1.49 2018/09/21 21:39:05 sjg Exp $ # -# $NetBSD: Makefile,v 1.52 2015/05/05 21:51:09 sjg Exp $ +# $NetBSD: Makefile,v 1.53 2018/05/24 00:25:44 christos Exp $ # # Unit tests for make(1) # The main targets are: # # all: run all the tests # test: run 'all', and compare to expected results # accept: move generated output to expected results # # Adding a test case. # Each feature should get its own set of tests in its own suitably # named makefile (*.mk), with its own set of expected results (*.exp), # and it should be added to the TESTNAMES list. # srcdir= ${SRCTOP}/contrib/bmake/unit-tests .MAIN: all UNIT_TESTS:= ${srcdir} .PATH: ${UNIT_TESTS} # Each test is in a sub-makefile. # Keep the list sorted. TESTNAMES= \ comment \ cond1 \ cond2 \ error \ export \ export-all \ export-env \ doterror \ dotwait \ forloop \ forsubst \ hash \ misc \ moderrs \ modmatch \ modmisc \ modorder \ modts \ modword \ order \ posix \ qequals \ sunshcmd \ sysv \ ternary \ unexport \ unexport-env \ varcmd \ varmisc \ + varquote \ varshell # these tests were broken by referting POSIX chanegs STRICT_POSIX_TESTS = \ escape \ impsrc \ phony-end \ posix1 \ suffixes # Override make flags for certain tests flags.doterror= flags.order=-j1 OUTFILES= ${TESTNAMES:S/$/.out/} all: ${OUTFILES} CLEANFILES += *.rawout *.out *.status *.tmp *.core *.tmp CLEANFILES += obj*.[och] lib*.a # posix1.mk CLEANFILES += issue* .[ab]* # suffixes.mk CLEANRECURSIVE += dir dummy # posix1.mk clean: rm -f ${CLEANFILES} .if !empty(CLEANRECURSIVE) rm -rf ${CLEANRECURSIVE} .endif TEST_MAKE?= ${.MAKE} TOOL_SED?= sed TOOL_TR?= tr TOOL_DIFF?= diff DIFF_FLAGS?= -u .if defined(.PARSEDIR) # ensure consistent results from sort(1) LC_ALL= C LANG= C .export LANG LC_ALL .endif # some tests need extra post-processing SED_CMDS.varshell = -e 's,^[a-z]*sh: ,,' \ -e '/command/s,No such.*,not found,' # the tests are actually done with sub-makes. .SUFFIXES: .mk .rawout .out .mk.rawout: @echo ${TEST_MAKE} ${flags.${.TARGET:R}:U-k} -f ${.IMPSRC} -@cd ${.OBJDIR} && \ { ${TEST_MAKE} ${flags.${.TARGET:R}:U-k} -f ${.IMPSRC} \ 2>&1 ; echo $$? >${.TARGET:R}.status ; } > ${.TARGET}.tmp @mv ${.TARGET}.tmp ${.TARGET} # We always pretend .MAKE was called 'make' # and strip ${.CURDIR}/ from the output # and replace anything after 'stopped in' with unit-tests # so the results can be compared. .rawout.out: @echo postprocess ${.TARGET} @${TOOL_SED} -e 's,^${TEST_MAKE:T:C/\./\\\./g}[][0-9]*:,make:,' \ -e 's,${TEST_MAKE:C/\./\\\./g},make,' \ -e '/stopped/s, /.*, unit-tests,' \ -e 's,${.CURDIR:C/\./\\\./g}/,,g' \ -e 's,${UNIT_TESTS:C/\./\\\./g}/,,g' ${SED_CMDS.${.TARGET:T:R}} \ < ${.IMPSRC} > ${.TARGET}.tmp @echo "exit status `cat ${.TARGET:R}.status`" >> ${.TARGET}.tmp @mv ${.TARGET}.tmp ${.TARGET} # Compare all output files test: ${OUTFILES} .PHONY @failed= ; \ for test in ${TESTNAMES}; do \ ${TOOL_DIFF} ${DIFF_FLAGS} ${UNIT_TESTS}/$${test}.exp $${test}.out \ || failed="$${failed}$${failed:+ }$${test}" ; \ done ; \ if [ -n "$${failed}" ]; then \ echo "Failed tests: $${failed}" ; false ; \ else \ echo "All tests passed" ; \ fi accept: @for test in ${TESTNAMES}; do \ cmp -s ${UNIT_TESTS}/$${test}.exp $${test}.out \ || { echo "Replacing $${test}.exp" ; \ cp $${test}.out ${UNIT_TESTS}/$${test}.exp ; } \ done .if exists(${TEST_MAKE}) ${TESTNAMES:S/$/.rawout/}: ${TEST_MAKE} .endif .sinclude Index: stable/12 =================================================================== --- stable/12 (revision 361673) +++ stable/12 (revision 361674) Property changes on: stable/12 ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,1 ## Merged /head:r341652,342376,361307