Home | History | Annotate | Line # | Download | only in src
build.sh revision 1.380
      1 #! /usr/bin/env sh
      2 #	$NetBSD: build.sh,v 1.380 2024/11/29 16:55:24 riastradh Exp $
      3 #
      4 # Copyright (c) 2001-2023 The NetBSD Foundation, Inc.
      5 # All rights reserved.
      6 #
      7 # This code is derived from software contributed to The NetBSD Foundation
      8 # by Todd Vierling and Luke Mewburn.
      9 #
     10 # Redistribution and use in source and binary forms, with or without
     11 # modification, are permitted provided that the following conditions
     12 # are met:
     13 # 1. Redistributions of source code must retain the above copyright
     14 #    notice, this list of conditions and the following disclaimer.
     15 # 2. Redistributions in binary form must reproduce the above copyright
     16 #    notice, this list of conditions and the following disclaimer in the
     17 #    documentation and/or other materials provided with the distribution.
     18 #
     19 # THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20 # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22 # PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29 # POSSIBILITY OF SUCH DAMAGE.
     30 #
     31 #
     32 # Top level build wrapper, to build or cross-build NetBSD.
     33 #
     34 
     35 #
     36 # {{{ Begin shell feature tests.
     37 #
     38 # We try to determine whether or not this script is being run under
     39 # a shell that supports the features that we use.  If not, we try to
     40 # re-exec the script under another shell.  If we can't find another
     41 # suitable shell, then we show a message and exit.
     42 #
     43 
     44 errmsg=''		# error message, if not empty
     45 shelltest=false		# if true, exit after testing the shell
     46 re_exec_allowed=true	# if true, we may exec under another shell
     47 
     48 # Parse special command line options in $1.  These special options are
     49 # for internal use only, are not documented, and are not valid anywhere
     50 # other than $1.
     51 case "$1" in
     52 "--shelltest")
     53     shelltest=true
     54     re_exec_allowed=false
     55     shift
     56     ;;
     57 "--no-re-exec")
     58     re_exec_allowed=false
     59     shift
     60     ;;
     61 esac
     62 
     63 # Solaris /bin/sh, and other SVR4 shells, do not support "!".
     64 # This is the first feature that we test, because subsequent
     65 # tests use "!".
     66 #
     67 if test -z "$errmsg"; then
     68     if ( eval '! false' ) >/dev/null 2>&1 ; then
     69 	:
     70     else
     71 	errmsg='Shell does not support "!".'
     72     fi
     73 fi
     74 
     75 # Does the shell support functions?
     76 #
     77 if test -z "$errmsg"; then
     78     if ! (
     79 	eval 'somefunction() { : ; }'
     80 	) >/dev/null 2>&1
     81     then
     82 	errmsg='Shell does not support functions.'
     83     fi
     84 fi
     85 
     86 # Does the shell support the "local" keyword for variables in functions?
     87 #
     88 # Local variables are not required by SUSv3, but some scripts run during
     89 # the NetBSD build use them.
     90 #
     91 # ksh93 fails this test; it uses an incompatible syntax involving the
     92 # keywords 'function' and 'typeset'.
     93 #
     94 if test -z "$errmsg"; then
     95     if ! (
     96 	eval 'f() { local v=2; }; v=1; f && test x"$v" = x"1"'
     97 	) >/dev/null 2>&1
     98     then
     99 	errmsg='Shell does not support the "local" keyword in functions.'
    100     fi
    101 fi
    102 
    103 # Does the shell support ${var%suffix}, ${var#prefix}, and their variants?
    104 #
    105 # We don't bother testing for ${var+value}, ${var-value}, or their variants,
    106 # since shells without those are sure to fail other tests too.
    107 #
    108 if test -z "$errmsg"; then
    109     if ! (
    110 	eval 'var=a/b/c ;
    111 	      test x"${var#*/};${var##*/};${var%/*};${var%%/*}" = \
    112 		   x"b/c;c;a/b;a" ;'
    113 	) >/dev/null 2>&1
    114     then
    115 	errmsg='Shell does not support "${var%suffix}" or "${var#prefix}".'
    116     fi
    117 fi
    118 
    119 # Does the shell support IFS?
    120 #
    121 # zsh in normal mode (as opposed to "emulate sh" mode) fails this test.
    122 #
    123 if test -z "$errmsg"; then
    124     if ! (
    125 	eval 'IFS=: ; v=":a b::c" ; set -- $v ; IFS=+ ;
    126 		test x"$#;$1,$2,$3,$4;$*" = x"4;,a b,,c;+a b++c"'
    127 	) >/dev/null 2>&1
    128     then
    129 	errmsg='Shell does not support IFS word splitting.'
    130     fi
    131 fi
    132 
    133 # Does the shell support ${1+"$@"}?
    134 #
    135 # Some versions of zsh fail this test, even in "emulate sh" mode.
    136 #
    137 if test -z "$errmsg"; then
    138     if ! (
    139 	eval 'set -- "a a a" "b b b"; set -- ${1+"$@"};
    140 	      test x"$#;$1;$2" = x"2;a a a;b b b";'
    141 	) >/dev/null 2>&1
    142     then
    143 	errmsg='Shell does not support ${1+"$@"}.'
    144     fi
    145 fi
    146 
    147 # Does the shell support $(...) command substitution?
    148 #
    149 if test -z "$errmsg"; then
    150     if ! (
    151 	eval 'var=$(echo abc); test x"$var" = x"abc"'
    152 	) >/dev/null 2>&1
    153     then
    154 	errmsg='Shell does not support "$(...)" command substitution.'
    155     fi
    156 fi
    157 
    158 # Does the shell support $(...) command substitution with
    159 # unbalanced parentheses?
    160 #
    161 # Some shells known to fail this test are:  NetBSD /bin/ksh (as of 2009-12),
    162 # bash-3.1, pdksh-5.2.14, zsh-4.2.7 in "emulate sh" mode.
    163 #
    164 if test -z "$errmsg"; then
    165     if ! (
    166 	eval 'var=$(case x in x) echo abc;; esac); test x"$var" = x"abc"'
    167 	) >/dev/null 2>&1
    168     then
    169 	# XXX: This test is ignored because so many shells fail it; instead,
    170 	#      the NetBSD build avoids using the problematic construct.
    171 	: ignore 'Shell does not support "$(...)" with unbalanced ")".'
    172     fi
    173 fi
    174 
    175 # Does the shell support getopts or getopt?
    176 #
    177 if test -z "$errmsg"; then
    178     if ! (
    179 	eval 'type getopts || type getopt'
    180 	) >/dev/null 2>&1
    181     then
    182 	errmsg='Shell does not support getopts or getopt.'
    183     fi
    184 fi
    185 
    186 #
    187 # If shelltest is true, exit now, reporting whether or not the shell is good.
    188 #
    189 if $shelltest; then
    190     if test -n "$errmsg"; then
    191 	echo >&2 "$0: $errmsg"
    192 	exit 1
    193     else
    194 	exit 0
    195     fi
    196 fi
    197 
    198 #
    199 # If the shell was bad, try to exec a better shell, or report an error.
    200 #
    201 # Loops are broken by passing an extra "--no-re-exec" flag to the new
    202 # instance of this script.
    203 #
    204 if test -n "$errmsg"; then
    205     if $re_exec_allowed; then
    206 	for othershell in \
    207 	    "${HOST_SH}" /usr/xpg4/bin/sh ksh ksh88 mksh pdksh dash bash
    208 	    # NOTE: some shells known not to work are:
    209 	    # any shell using csh syntax;
    210 	    # Solaris /bin/sh (missing many modern features);
    211 	    # ksh93 (incompatible syntax for local variables);
    212 	    # zsh (many differences, unless run in compatibility mode).
    213 	do
    214 	    test -n "$othershell" || continue
    215 	    if eval 'type "$othershell"' >/dev/null 2>&1 \
    216 		&& "$othershell" "$0" --shelltest >/dev/null 2>&1
    217 	    then
    218 		cat <<EOF
    219 $0: $errmsg
    220 $0: Retrying under $othershell
    221 EOF
    222 		HOST_SH="$othershell"
    223 		export HOST_SH
    224 		exec $othershell "$0" --no-re-exec "$@" # avoid ${1+"$@"}
    225 	    fi
    226 	    # If HOST_SH was set, but failed the test above,
    227 	    # then give up without trying any other shells.
    228 	    test x"${othershell}" = x"${HOST_SH}" && break
    229 	done
    230     fi
    231 
    232     #
    233     # If we get here, then the shell is bad, and we either could not
    234     # find a replacement, or were not allowed to try a replacement.
    235     #
    236     cat <<EOF
    237 $0: $errmsg
    238 
    239 The NetBSD build system requires a shell that supports modern POSIX
    240 features, as well as the "local" keyword in functions (which is a
    241 widely-implemented but non-standardised feature).
    242 
    243 Please re-run this script under a suitable shell.  For example:
    244 
    245 	/path/to/suitable/shell $0 ...
    246 
    247 The above command will usually enable build.sh to automatically set
    248 HOST_SH=/path/to/suitable/shell, but if that fails, then you may also
    249 need to explicitly set the HOST_SH environment variable, as follows:
    250 
    251 	HOST_SH=/path/to/suitable/shell
    252 	export HOST_SH
    253 	\${HOST_SH} $0 ...
    254 EOF
    255     exit 1
    256 fi
    257 
    258 #
    259 # }}} End shell feature tests.
    260 #
    261 
    262 progname=${0##*/}
    263 toppid=$$
    264 results=/dev/null
    265 tab='	'
    266 nl='
    267 '
    268 trap "exit 1" 1 2 3 15
    269 
    270 bomb()
    271 {
    272 	cat >&2 <<ERRORMESSAGE
    273 
    274 ERROR: $@
    275 
    276 *** BUILD ABORTED ***
    277 ERRORMESSAGE
    278 	kill ${toppid}		# in case we were invoked from a subshell
    279 	exit 1
    280 }
    281 
    282 # Quote args to make them safe in the shell.
    283 # Usage: quotedlist="$(shell_quote args...)"
    284 #
    285 # After building up a quoted list, use it by evaling it inside
    286 # double quotes, like this:
    287 #    eval "set -- $quotedlist"
    288 # or like this:
    289 #    eval "\$command $quotedlist \$filename"
    290 #
    291 shell_quote()
    292 {(
    293 	local result=''
    294 	local arg qarg
    295 	LC_COLLATE=C ; export LC_COLLATE # so [a-zA-Z0-9] works in ASCII
    296 	for arg in "$@" ; do
    297 		case "${arg}" in
    298 		'')
    299 			qarg="''"
    300 			;;
    301 		*[!-./a-zA-Z0-9]*)
    302 			# Convert each embedded ' to '\'',
    303 			# then insert ' at the beginning of the first line,
    304 			# and append ' at the end of the last line.
    305 			# Finally, elide unnecessary '' pairs at the
    306 			# beginning and end of the result and as part of
    307 			# '\'''\'' sequences that result from multiple
    308 			# adjacent quotes in he input.
    309 			qarg="$(printf "%s\n" "$arg" | \
    310 			    ${SED:-sed} -e "s/'/'\\\\''/g" \
    311 				-e "1s/^/'/" -e "\$s/\$/'/" \
    312 				-e "1s/^''//" -e "\$s/''\$//" \
    313 				-e "s/'''/'/g"
    314 				)"
    315 			;;
    316 		*)
    317 			# Arg is not the empty string, and does not contain
    318 			# any unsafe characters.  Leave it unchanged for
    319 			# readability.
    320 			qarg="${arg}"
    321 			;;
    322 		esac
    323 		result="${result}${result:+ }${qarg}"
    324 	done
    325 	printf "%s\n" "$result"
    326 )}
    327 
    328 statusmsg()
    329 {
    330 	${runcmd} echo "===> $@" | tee -a "${results}"
    331 }
    332 
    333 statusmsg2()
    334 {
    335 	local msg
    336 
    337 	msg="${1}"
    338 	shift
    339 	case "${msg}" in
    340 	????????????????*)	;;
    341 	??????????*)		msg="${msg}      ";;
    342 	?????*)			msg="${msg}           ";;
    343 	*)			msg="${msg}                ";;
    344 	esac
    345 	case "${msg}" in
    346 	?????????????????????*)	;;
    347 	????????????????????)	msg="${msg} ";;
    348 	???????????????????)	msg="${msg}  ";;
    349 	??????????????????)	msg="${msg}   ";;
    350 	?????????????????)	msg="${msg}    ";;
    351 	????????????????)	msg="${msg}     ";;
    352 	esac
    353 	statusmsg "${msg}$*"
    354 }
    355 
    356 warning()
    357 {
    358 	statusmsg "Warning: $@"
    359 }
    360 
    361 # Find a program in the PATH, and show the result.  If not found,
    362 # show a default.  If $2 is defined (even if it is an empty string),
    363 # then that is the default; otherwise, $1 is used as the default.
    364 #
    365 find_in_PATH()
    366 {
    367 	local prog="$1"
    368 	local result="${2-"$1"}"
    369 	local oldIFS="${IFS}"
    370 	local dir
    371 	IFS=":"
    372 	for dir in ${PATH}; do
    373 		if [ -x "${dir}/${prog}" ]; then
    374 			result="${dir}/${prog}"
    375 			break
    376 		fi
    377 	done
    378 	IFS="${oldIFS}"
    379 	echo "${result}"
    380 }
    381 
    382 # Try to find a working POSIX shell, and set HOST_SH to refer to it.
    383 # Assumes that uname_s, uname_m, and PWD have been set.
    384 #
    385 set_HOST_SH()
    386 {
    387 	# Even if ${HOST_SH} is already defined, we still do the
    388 	# sanity checks at the end.
    389 
    390 	# Solaris has /usr/xpg4/bin/sh.
    391 	#
    392 	[ -z "${HOST_SH}" ] && [ x"${uname_s}" = x"SunOS" ] && \
    393 		[ -x /usr/xpg4/bin/sh ] && HOST_SH="/usr/xpg4/bin/sh"
    394 
    395 	# Try to get the name of the shell that's running this script,
    396 	# by parsing the output from "ps".  We assume that, if the host
    397 	# system's ps command supports -o comm at all, it will do so
    398 	# in the usual way: a one-line header followed by a one-line
    399 	# result, possibly including trailing white space.  And if the
    400 	# host system's ps command doesn't support -o comm, we assume
    401 	# that we'll get an error message on stderr and nothing on
    402 	# stdout.  (We don't try to use ps -o 'comm=' to suppress the
    403 	# header line, because that is less widely supported.)
    404 	#
    405 	# If we get the wrong result here, the user can override it by
    406 	# specifying HOST_SH in the environment.
    407 	#
    408 	[ -z "${HOST_SH}" ] && HOST_SH="$(
    409 		(ps -p $$ -o comm | sed -ne "2s/[ ${tab}]*\$//p") 2>/dev/null )"
    410 
    411 	# If nothing above worked, use "sh".  We will later find the
    412 	# first directory in the PATH that has a "sh" program.
    413 	#
    414 	[ -z "${HOST_SH}" ] && HOST_SH="sh"
    415 
    416 	# If the result so far is not an absolute path, try to prepend
    417 	# PWD or search the PATH.
    418 	#
    419 	case "${HOST_SH}" in
    420 	/*)	:
    421 		;;
    422 	*/*)	HOST_SH="${PWD}/${HOST_SH}"
    423 		;;
    424 	*)	HOST_SH="$(find_in_PATH "${HOST_SH}")"
    425 		;;
    426 	esac
    427 
    428 	# If we don't have an absolute path by now, bomb.
    429 	#
    430 	case "${HOST_SH}" in
    431 	/*)	:
    432 		;;
    433 	*)	bomb "HOST_SH=\"${HOST_SH}\" is not an absolute path"
    434 		;;
    435 	esac
    436 
    437 	# If HOST_SH is not executable, bomb.
    438 	#
    439 	[ -x "${HOST_SH}" ] ||
    440 	    bomb "HOST_SH=\"${HOST_SH}\" is not executable"
    441 
    442 	# If HOST_SH fails tests, bomb.
    443 	# ("$0" may be a path that is no longer valid, because we have
    444 	# performed "cd $(dirname $0)", so don't use $0 here.)
    445 	#
    446 	"${HOST_SH}" build.sh --shelltest ||
    447 	    bomb "HOST_SH=\"${HOST_SH}\" failed functionality tests"
    448 }
    449 
    450 # initdefaults --
    451 # Set defaults before parsing command line options.
    452 #
    453 initdefaults()
    454 {
    455 	makeenv=
    456 	makewrapper=
    457 	makewrappermachine=
    458 	runcmd=
    459 	operations=
    460 	removedirs=
    461 
    462 	[ -d usr.bin/make ] || cd "$(dirname $0)"
    463 	[ -d usr.bin/make ] ||
    464 	    bomb "usr.bin/make not found; build.sh must be run from the top \
    465 level of source directory"
    466 	[ -f share/mk/bsd.own.mk ] ||
    467 	    bomb "src/share/mk is missing; please re-fetch the source tree"
    468 
    469 	# Set various environment variables to known defaults,
    470 	# to minimize (cross-)build problems observed "in the field".
    471 	#
    472 	# LC_ALL=C must be set before we try to parse the output from
    473 	# any command.  Other variables are set (or unset) here, before
    474 	# we parse command line arguments.
    475 	#
    476 	# These variables can be overridden via "-V var=value" if
    477 	# you know what you are doing.
    478 	#
    479 	unsetmakeenv C_INCLUDE_PATH
    480 	unsetmakeenv CPLUS_INCLUDE_PATH
    481 	unsetmakeenv INFODIR
    482 	unsetmakeenv LESSCHARSET
    483 	unsetmakeenv MAKEFLAGS
    484 	unsetmakeenv TERMINFO
    485 	setmakeenv LC_ALL C
    486 
    487 	# Find information about the build platform.  This should be
    488 	# kept in sync with _HOST_OSNAME, _HOST_OSREL, and _HOST_ARCH
    489 	# variables in share/mk/bsd.sys.mk.
    490 	#
    491 	# Note that "uname -p" is not part of POSIX, but we want uname_p
    492 	# to be set to the host MACHINE_ARCH, if possible.  On systems
    493 	# where "uname -p" fails, shows "unknown", or shows a string
    494 	# that does not look like an identifier, fall back to using the
    495 	# output from "uname -m" instead.
    496 	#
    497 	uname_s=$(uname -s 2>/dev/null)
    498 	uname_r=$(uname -r 2>/dev/null)
    499 	uname_m=$(uname -m 2>/dev/null)
    500 	uname_p=$(uname -p 2>/dev/null || echo "unknown")
    501 	case "${uname_p}" in
    502 	''|unknown|*[!-_A-Za-z0-9]*) uname_p="${uname_m}" ;;
    503 	esac
    504 
    505 	id_u=$(id -u 2>/dev/null || /usr/xpg4/bin/id -u 2>/dev/null)
    506 
    507 	# If $PWD is a valid name of the current directory, POSIX mandates
    508 	# that pwd return it by default which causes problems in the
    509 	# presence of symlinks.  Unsetting PWD is simpler than changing
    510 	# every occurrence of pwd to use -P.
    511 	#
    512 	# XXX Except that doesn't work on Solaris. Or many Linuces.
    513 	#
    514 	unset PWD
    515 	TOP=$( (exec pwd -P 2>/dev/null) || (exec pwd 2>/dev/null) )
    516 
    517 	# The user can set HOST_SH in the environment, or we try to
    518 	# guess an appropriate value.  Then we set several other
    519 	# variables from HOST_SH.
    520 	#
    521 	set_HOST_SH
    522 	setmakeenv HOST_SH "${HOST_SH}"
    523 	setmakeenv BSHELL "${HOST_SH}"
    524 	setmakeenv CONFIG_SHELL "${HOST_SH}"
    525 
    526 	# Set defaults.
    527 	#
    528 	toolprefix=nb
    529 
    530 	# Some systems have a small ARG_MAX.  -X prevents make(1) from
    531 	# exporting variables in the environment redundantly.
    532 	#
    533 	case "${uname_s}" in
    534 	Darwin | FreeBSD | CYGWIN*)
    535 		MAKEFLAGS="-X ${MAKEFLAGS}"
    536 		;;
    537 	esac
    538 
    539 	# do_{operation}=true if given operation is requested.
    540 	#
    541 	do_expertmode=false
    542 	do_rebuildmake=false
    543 	do_removedirs=false
    544 	do_tools=false
    545 	do_libs=false
    546 	do_cleandir=false
    547 	do_obj=false
    548 	do_build=false
    549 	do_distribution=false
    550 	do_release=false
    551 	do_kernel=false
    552 	do_releasekernel=false
    553 	do_kernels=false
    554 	do_modules=false
    555 	do_installmodules=false
    556 	do_install=false
    557 	do_sets=false
    558 	do_sourcesets=false
    559 	do_syspkgs=false
    560 	do_pkg=false
    561 	do_iso_image=false
    562 	do_iso_image_source=false
    563 	do_live_image=false
    564 	do_install_image=false
    565 	do_disk_image=false
    566 	do_params=false
    567 	do_show_params=false
    568 	do_rump=false
    569 	do_dtb=false
    570 
    571 	# done_{operation}=true if given operation has been done.
    572 	#
    573 	done_rebuildmake=false
    574 
    575 	# Create scratch directory
    576 	#
    577 	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
    578 	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
    579 	trap "cd /; rm -r -f \"${tmpdir}\"" 0
    580 	results="${tmpdir}/build.sh.results"
    581 
    582 	# Set source directories
    583 	#
    584 	setmakeenv NETBSDSRCDIR "${TOP}"
    585 
    586 	# Make sure KERNOBJDIR is an absolute path if defined
    587 	#
    588 	case "${KERNOBJDIR}" in
    589 	''|/*)	;;
    590 	*)	KERNOBJDIR="${TOP}/${KERNOBJDIR}"
    591 		setmakeenv KERNOBJDIR "${KERNOBJDIR}"
    592 		;;
    593 	esac
    594 
    595 	# Find the version of NetBSD
    596 	#
    597 	DISTRIBVER="$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh)"
    598 
    599 	# Set the BUILDSEED to NetBSD-"N"
    600 	#
    601 	setmakeenv BUILDSEED "NetBSD-$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh -m)"
    602 
    603 	# Set MKARZERO to "yes"
    604 	#
    605 	setmakeenv MKARZERO "yes"
    606 
    607 }
    608 
    609 # valid_MACHINE_ARCH -- A multi-line string, listing all valid
    610 # MACHINE/MACHINE_ARCH pairs.
    611 #
    612 # Each line contains a MACHINE and MACHINE_ARCH value, an optional ALIAS
    613 # which may be used to refer to the MACHINE/MACHINE_ARCH pair, and an
    614 # optional DEFAULT or NO_DEFAULT keyword.
    615 #
    616 # When a MACHINE corresponds to multiple possible values of
    617 # MACHINE_ARCH, then this table should list all allowed combinations.
    618 # If the MACHINE is associated with a default MACHINE_ARCH (to be
    619 # used when the user specifies the MACHINE but fails to specify the
    620 # MACHINE_ARCH), then one of the lines should have the "DEFAULT"
    621 # keyword.  If there is no default MACHINE_ARCH for a particular
    622 # MACHINE, then there should be a line with the "NO_DEFAULT" keyword,
    623 # and with a blank MACHINE_ARCH.
    624 #
    625 valid_MACHINE_ARCH='
    626 MACHINE=acorn32		MACHINE_ARCH=earmv4	ALIAS=eacorn32 DEFAULT
    627 MACHINE=algor		MACHINE_ARCH=mips64el	ALIAS=algor64
    628 MACHINE=algor		MACHINE_ARCH=mipsel	DEFAULT
    629 MACHINE=alpha		MACHINE_ARCH=alpha
    630 MACHINE=amd64		MACHINE_ARCH=x86_64
    631 MACHINE=amiga		MACHINE_ARCH=m68k
    632 MACHINE=amigappc	MACHINE_ARCH=powerpc
    633 MACHINE=arc		MACHINE_ARCH=mips64el	ALIAS=arc64
    634 MACHINE=arc		MACHINE_ARCH=mipsel	DEFAULT
    635 MACHINE=atari		MACHINE_ARCH=m68k
    636 MACHINE=bebox		MACHINE_ARCH=powerpc
    637 MACHINE=cats		MACHINE_ARCH=earmv4	ALIAS=ecats DEFAULT
    638 MACHINE=cesfic		MACHINE_ARCH=m68k
    639 MACHINE=cobalt		MACHINE_ARCH=mips64el	ALIAS=cobalt64
    640 MACHINE=cobalt		MACHINE_ARCH=mipsel	DEFAULT
    641 MACHINE=dreamcast	MACHINE_ARCH=sh3el
    642 MACHINE=emips		MACHINE_ARCH=mipseb
    643 MACHINE=epoc32		MACHINE_ARCH=earmv4	ALIAS=eepoc32 DEFAULT
    644 MACHINE=evbarm		MACHINE_ARCH=		NO_DEFAULT
    645 MACHINE=evbarm		MACHINE_ARCH=earmv4	ALIAS=evbearmv4-el	ALIAS=evbarmv4-el
    646 MACHINE=evbarm		MACHINE_ARCH=earmv4eb	ALIAS=evbearmv4-eb	ALIAS=evbarmv4-eb
    647 MACHINE=evbarm		MACHINE_ARCH=earmv5	ALIAS=evbearmv5-el	ALIAS=evbarmv5-el
    648 MACHINE=evbarm		MACHINE_ARCH=earmv5hf	ALIAS=evbearmv5hf-el	ALIAS=evbarmv5hf-el
    649 MACHINE=evbarm		MACHINE_ARCH=earmv5eb	ALIAS=evbearmv5-eb	ALIAS=evbarmv5-eb
    650 MACHINE=evbarm		MACHINE_ARCH=earmv5hfeb	ALIAS=evbearmv5hf-eb	ALIAS=evbarmv5hf-eb
    651 MACHINE=evbarm		MACHINE_ARCH=earmv6	ALIAS=evbearmv6-el	ALIAS=evbarmv6-el
    652 MACHINE=evbarm		MACHINE_ARCH=earmv6hf	ALIAS=evbearmv6hf-el	ALIAS=evbarmv6hf-el
    653 MACHINE=evbarm		MACHINE_ARCH=earmv6eb	ALIAS=evbearmv6-eb	ALIAS=evbarmv6-eb
    654 MACHINE=evbarm		MACHINE_ARCH=earmv6hfeb	ALIAS=evbearmv6hf-eb	ALIAS=evbarmv6hf-eb
    655 MACHINE=evbarm		MACHINE_ARCH=earmv7	ALIAS=evbearmv7-el	ALIAS=evbarmv7-el
    656 MACHINE=evbarm		MACHINE_ARCH=earmv7eb	ALIAS=evbearmv7-eb	ALIAS=evbarmv7-eb
    657 MACHINE=evbarm		MACHINE_ARCH=earmv7hf	ALIAS=evbearmv7hf-el	ALIAS=evbarmv7hf-el
    658 MACHINE=evbarm		MACHINE_ARCH=earmv7hfeb	ALIAS=evbearmv7hf-eb	ALIAS=evbarmv7hf-eb
    659 MACHINE=evbarm		MACHINE_ARCH=aarch64	ALIAS=evbarm64-el	ALIAS=evbarm64
    660 MACHINE=evbarm		MACHINE_ARCH=aarch64eb	ALIAS=evbarm64-eb
    661 MACHINE=evbcf		MACHINE_ARCH=coldfire
    662 MACHINE=evbmips		MACHINE_ARCH=		NO_DEFAULT
    663 MACHINE=evbmips		MACHINE_ARCH=mips64eb	ALIAS=evbmips64-eb
    664 MACHINE=evbmips		MACHINE_ARCH=mips64el	ALIAS=evbmips64-el
    665 MACHINE=evbmips		MACHINE_ARCH=mipseb	ALIAS=evbmips-eb
    666 MACHINE=evbmips		MACHINE_ARCH=mipsel	ALIAS=evbmips-el
    667 MACHINE=evbmips		MACHINE_ARCH=mipsn64eb	ALIAS=evbmipsn64-eb
    668 MACHINE=evbmips		MACHINE_ARCH=mipsn64el	ALIAS=evbmipsn64-el
    669 MACHINE=evbppc		MACHINE_ARCH=powerpc	DEFAULT
    670 MACHINE=evbppc		MACHINE_ARCH=powerpc64	ALIAS=evbppc64
    671 MACHINE=evbsh3		MACHINE_ARCH=		NO_DEFAULT
    672 MACHINE=evbsh3		MACHINE_ARCH=sh3eb	ALIAS=evbsh3-eb
    673 MACHINE=evbsh3		MACHINE_ARCH=sh3el	ALIAS=evbsh3-el
    674 MACHINE=ews4800mips	MACHINE_ARCH=mipseb
    675 MACHINE=hp300		MACHINE_ARCH=m68k
    676 MACHINE=hppa		MACHINE_ARCH=hppa
    677 MACHINE=hpcarm		MACHINE_ARCH=earmv4	ALIAS=hpcearm DEFAULT
    678 MACHINE=hpcmips		MACHINE_ARCH=mipsel
    679 MACHINE=hpcsh		MACHINE_ARCH=sh3el
    680 MACHINE=i386		MACHINE_ARCH=i386
    681 MACHINE=ia64		MACHINE_ARCH=ia64
    682 MACHINE=ibmnws		MACHINE_ARCH=powerpc
    683 MACHINE=iyonix		MACHINE_ARCH=earm	ALIAS=eiyonix DEFAULT
    684 MACHINE=landisk		MACHINE_ARCH=sh3el
    685 MACHINE=luna68k		MACHINE_ARCH=m68k
    686 MACHINE=mac68k		MACHINE_ARCH=m68k
    687 MACHINE=macppc		MACHINE_ARCH=powerpc	DEFAULT
    688 MACHINE=macppc		MACHINE_ARCH=powerpc64	ALIAS=macppc64
    689 MACHINE=mipsco		MACHINE_ARCH=mipseb
    690 MACHINE=mmeye		MACHINE_ARCH=sh3eb
    691 MACHINE=mvme68k		MACHINE_ARCH=m68k
    692 MACHINE=mvmeppc		MACHINE_ARCH=powerpc
    693 MACHINE=netwinder	MACHINE_ARCH=earmv4	ALIAS=enetwinder DEFAULT
    694 MACHINE=news68k		MACHINE_ARCH=m68k
    695 MACHINE=newsmips	MACHINE_ARCH=mipseb
    696 MACHINE=next68k		MACHINE_ARCH=m68k
    697 MACHINE=ofppc		MACHINE_ARCH=powerpc	DEFAULT
    698 MACHINE=ofppc		MACHINE_ARCH=powerpc64	ALIAS=ofppc64
    699 MACHINE=or1k		MACHINE_ARCH=or1k
    700 MACHINE=playstation2	MACHINE_ARCH=mipsel
    701 MACHINE=pmax		MACHINE_ARCH=mips64el	ALIAS=pmax64
    702 MACHINE=pmax		MACHINE_ARCH=mipsel	DEFAULT
    703 MACHINE=prep		MACHINE_ARCH=powerpc
    704 MACHINE=riscv		MACHINE_ARCH=riscv64	ALIAS=riscv64 DEFAULT
    705 MACHINE=riscv		MACHINE_ARCH=riscv32	ALIAS=riscv32
    706 MACHINE=rs6000		MACHINE_ARCH=powerpc
    707 MACHINE=sandpoint	MACHINE_ARCH=powerpc
    708 MACHINE=sbmips		MACHINE_ARCH=		NO_DEFAULT
    709 MACHINE=sbmips		MACHINE_ARCH=mips64eb	ALIAS=sbmips64-eb
    710 MACHINE=sbmips		MACHINE_ARCH=mips64el	ALIAS=sbmips64-el
    711 MACHINE=sbmips		MACHINE_ARCH=mipseb	ALIAS=sbmips-eb
    712 MACHINE=sbmips		MACHINE_ARCH=mipsel	ALIAS=sbmips-el
    713 MACHINE=sgimips		MACHINE_ARCH=mips64eb	ALIAS=sgimips64
    714 MACHINE=sgimips		MACHINE_ARCH=mipseb	DEFAULT
    715 MACHINE=shark		MACHINE_ARCH=earmv4	ALIAS=eshark DEFAULT
    716 MACHINE=sparc		MACHINE_ARCH=sparc
    717 MACHINE=sparc64		MACHINE_ARCH=sparc64
    718 MACHINE=sun2		MACHINE_ARCH=m68000
    719 MACHINE=sun3		MACHINE_ARCH=m68k
    720 MACHINE=vax		MACHINE_ARCH=vax
    721 MACHINE=virt68k		MACHINE_ARCH=m68k
    722 MACHINE=x68k		MACHINE_ARCH=m68k
    723 MACHINE=zaurus		MACHINE_ARCH=earm	ALIAS=ezaurus DEFAULT
    724 '
    725 
    726 # getarch -- find the default MACHINE_ARCH for a MACHINE,
    727 # or convert an alias to a MACHINE/MACHINE_ARCH pair.
    728 #
    729 # Saves the original value of MACHINE in makewrappermachine before
    730 # alias processing.
    731 #
    732 # Sets MACHINE and MACHINE_ARCH if the input MACHINE value is
    733 # recognised as an alias, or recognised as a machine that has a default
    734 # MACHINE_ARCH (or that has only one possible MACHINE_ARCH).
    735 #
    736 # Leaves MACHINE and MACHINE_ARCH unchanged if MACHINE is recognised
    737 # as being associated with multiple MACHINE_ARCH values with no default.
    738 #
    739 # Bombs if MACHINE is not recognised.
    740 #
    741 getarch()
    742 {
    743 	local IFS
    744 	local found=""
    745 	local line
    746 
    747 	IFS="${nl}"
    748 	makewrappermachine="${MACHINE}"
    749 	for line in ${valid_MACHINE_ARCH}; do
    750 		line="${line%%#*}" # ignore comments
    751 		line="$( IFS=" ${tab}" ; echo $line )" # normalise white space
    752 		case "${line} " in
    753 		" ")
    754 			# skip blank lines or comment lines
    755 			continue
    756 			;;
    757 		*" ALIAS=${MACHINE} "*)
    758 			# Found a line with a matching ALIAS=<alias>.
    759 			found="$line"
    760 			break
    761 			;;
    762 		"MACHINE=${MACHINE} "*" NO_DEFAULT"*)
    763 			# Found an explicit "NO_DEFAULT" for this MACHINE.
    764 			found="$line"
    765 			break
    766 			;;
    767 		"MACHINE=${MACHINE} "*" DEFAULT"*)
    768 			# Found an explicit "DEFAULT" for this MACHINE.
    769 			found="$line"
    770 			break
    771 			;;
    772 		"MACHINE=${MACHINE} "*)
    773 			# Found a line for this MACHINE.  If it's the
    774 			# first such line, then tentatively accept it.
    775 			# If it's not the first matching line, then
    776 			# remember that there was more than one match.
    777 			case "$found" in
    778 			'')	found="$line" ;;
    779 			*)	found="MULTIPLE_MATCHES" ;;
    780 			esac
    781 			;;
    782 		esac
    783 	done
    784 
    785 	case "$found" in
    786 	*NO_DEFAULT*|*MULTIPLE_MATCHES*)
    787 		# MACHINE is OK, but MACHINE_ARCH is still unknown
    788 		return
    789 		;;
    790 	"MACHINE="*" MACHINE_ARCH="*)
    791 		# Obey the MACHINE= and MACHINE_ARCH= parts of the line.
    792 		IFS=" "
    793 		for frag in ${found}; do
    794 			case "$frag" in
    795 			MACHINE=*|MACHINE_ARCH=*)
    796 				eval "$frag"
    797 				;;
    798 			esac
    799 		done
    800 		;;
    801 	*)
    802 		bomb "Unknown target MACHINE: ${MACHINE}"
    803 		;;
    804 	esac
    805 }
    806 
    807 # validatearch -- check that the MACHINE/MACHINE_ARCH pair is supported.
    808 #
    809 # Bombs if the pair is not supported.
    810 #
    811 validatearch()
    812 {
    813 	local IFS
    814 	local line
    815 	local foundpair=false foundmachine=false foundarch=false
    816 
    817 	case "${MACHINE_ARCH}" in
    818 	"")
    819 		bomb "No MACHINE_ARCH provided. Use 'build.sh -m ${MACHINE} list-arch' to show options"
    820 		;;
    821 	esac
    822 
    823 	IFS="${nl}"
    824 	for line in ${valid_MACHINE_ARCH}; do
    825 		line="${line%%#*}" # ignore comments
    826 		line="$( IFS=" ${tab}" ; echo $line )" # normalise white space
    827 		case "${line} " in
    828 		" ")
    829 			# skip blank lines or comment lines
    830 			continue
    831 			;;
    832 		"MACHINE=${MACHINE} MACHINE_ARCH=${MACHINE_ARCH} "*)
    833 			foundpair=true
    834 			;;
    835 		"MACHINE=${MACHINE} "*)
    836 			foundmachine=true
    837 			;;
    838 		*"MACHINE_ARCH=${MACHINE_ARCH} "*)
    839 			foundarch=true
    840 			;;
    841 		esac
    842 	done
    843 
    844 	case "${foundpair}:${foundmachine}:${foundarch}" in
    845 	true:*)
    846 		: OK
    847 		;;
    848 	*:false:*)
    849 		bomb "Unknown target MACHINE: ${MACHINE}"
    850 		;;
    851 	*:*:false)
    852 		bomb "Unknown target MACHINE_ARCH: ${MACHINE_ARCH}"
    853 		;;
    854 	*)
    855 		bomb "MACHINE_ARCH '${MACHINE_ARCH}' does not support MACHINE '${MACHINE}'"
    856 		;;
    857 	esac
    858 }
    859 
    860 # listarch -- list valid MACHINE/MACHINE_ARCH/ALIAS values,
    861 # optionally restricted to those where the MACHINE and/or MACHINE_ARCH
    862 # match specified glob patterns.
    863 #
    864 listarch()
    865 {
    866 	local machglob="$1" archglob="$2"
    867 	local IFS
    868 	local wildcard="*"
    869 	local line xline frag
    870 	local line_matches_machine line_matches_arch
    871 	local found=false
    872 
    873 	# Empty machglob or archglob should match anything
    874 	: "${machglob:=${wildcard}}"
    875 	: "${archglob:=${wildcard}}"
    876 
    877 	IFS="${nl}"
    878 	for line in ${valid_MACHINE_ARCH}; do
    879 		line="${line%%#*}" # ignore comments
    880 		xline="$( IFS=" ${tab}" ; echo $line )" # normalise white space
    881 		[ -z "${xline}" ] && continue # skip blank or comment lines
    882 
    883 		line_matches_machine=false
    884 		line_matches_arch=false
    885 
    886 		IFS=" "
    887 		for frag in ${xline}; do
    888 			case "${frag}" in
    889 			MACHINE=${machglob})
    890 				line_matches_machine=true ;;
    891 			ALIAS=${machglob})
    892 				line_matches_machine=true ;;
    893 			MACHINE_ARCH=${archglob})
    894 				line_matches_arch=true ;;
    895 			esac
    896 		done
    897 
    898 		if $line_matches_machine && $line_matches_arch; then
    899 			found=true
    900 			echo "$line"
    901 		fi
    902 	done
    903 	if ! $found; then
    904 		echo >&2 "No match for" \
    905 		    "MACHINE=${machglob} MACHINE_ARCH=${archglob}"
    906 		return 1
    907 	fi
    908 	return 0
    909 }
    910 
    911 # nobomb_getmakevar --
    912 # Given the name of a make variable in $1, show make's idea of the
    913 # value of that variable, or return 1 if there's an error.
    914 #
    915 nobomb_getmakevar()
    916 {
    917 	[ -x "${make}" ] || return 1
    918 	"${make}" -m ${TOP}/share/mk -s -B -f- _x_ <<EOF || return 1
    919 _x_:
    920 	echo \${$1}
    921 .include <bsd.prog.mk>
    922 .include <bsd.kernobj.mk>
    923 EOF
    924 }
    925 
    926 # bomb_getmakevar --
    927 # Given the name of a make variable in $1, show make's idea of the
    928 # value of that variable, or bomb if there's an error.
    929 #
    930 bomb_getmakevar()
    931 {
    932 	[ -x "${make}" ] || bomb "bomb_getmakevar $1: ${make} is not executable"
    933 	nobomb_getmakevar "$1" || bomb "bomb_getmakevar $1: ${make} failed"
    934 }
    935 
    936 # getmakevar --
    937 # Given the name of a make variable in $1, show make's idea of the
    938 # value of that variable, or show a literal '$' followed by the
    939 # variable name if ${make} is not executable.  This is intended for use in
    940 # messages that need to be readable even if $make hasn't been built,
    941 # such as when build.sh is run with the "-n" option.
    942 #
    943 getmakevar()
    944 {
    945 	if [ -x "${make}" ]; then
    946 		bomb_getmakevar "$1"
    947 	else
    948 		echo "\$$1"
    949 	fi
    950 }
    951 
    952 setmakeenv()
    953 {
    954 	eval "$1='$2'; export $1"
    955 	makeenv="${makeenv} $1"
    956 }
    957 
    958 safe_setmakeenv()
    959 {
    960 	case "$1" in
    961 
    962 	#	Look for any vars we want to prohibit here, like:
    963 	# Bad | Dangerous)	usage "Cannot override $1 with -V";;
    964 
    965 	# That first char is OK has already been verified.
    966 	*[!A-Za-z0-9_]*)	usage "Bad variable name (-V): '$1'";;
    967 	esac
    968 	setmakeenv "$@"
    969 }
    970 
    971 unsetmakeenv()
    972 {
    973 	eval "unset $1"
    974 	makeenv="${makeenv} $1"
    975 }
    976 
    977 safe_unsetmakeenv()
    978 {
    979 	case "$1" in
    980 
    981 	#	Look for any vars user should not be able to unset
    982 	# Needed | Must_Have)	usage "Variable $1 cannot be unset";;
    983 
    984 	[!A-Za-z_]* | *[!A-Za-z0-9_]*)	usage "Bad variable name (-Z): '$1'";;
    985 	esac
    986 	unsetmakeenv "$1"
    987 }
    988 
    989 # Clear all variables defined in makeenv.  Used to run a subprocess
    990 # outside the usual NetBSD build's make environment.
    991 #
    992 clearmakeenv()
    993 {
    994 	local var
    995 
    996 	for var in ${makeenv}; do
    997 		unset ${var}
    998 	done
    999 }
   1000 
   1001 # Given a variable name in $1, modify the variable in place as follows:
   1002 # For each space-separated word in the variable, call resolvepath.
   1003 #
   1004 resolvepaths()
   1005 {
   1006 	local var="$1"
   1007 	local val
   1008 	eval val=\"\${${var}}\"
   1009 	local newval=''
   1010 	local word
   1011 	for word in ${val}; do
   1012 		resolvepath word
   1013 		newval="${newval}${newval:+ }${word}"
   1014 	done
   1015 	eval ${var}=\"\${newval}\"
   1016 }
   1017 
   1018 # Given a variable name in $1, modify the variable in place as follows:
   1019 # Convert possibly-relative path to absolute path by prepending
   1020 # ${TOP} if necessary.  Also delete trailing "/", if any.
   1021 #
   1022 resolvepath()
   1023 {
   1024 	local var="$1"
   1025 	local val
   1026 	eval val=\"\${${var}}\"
   1027 	case "${val}" in
   1028 	/)
   1029 		;;
   1030 	/*)
   1031 		val="${val%/}"
   1032 		;;
   1033 	*)
   1034 		val="${TOP}/${val%/}"
   1035 		;;
   1036 	esac
   1037 	eval ${var}=\"\${val}\"
   1038 }
   1039 
   1040 # Show synopsis to stdout.
   1041 #
   1042 synopsis()
   1043 {
   1044 	cat <<_usage_
   1045 
   1046 Usage: ${progname} [-EnoPRrUux] [-a ARCH] [-B BID] [-C EXTRAS]
   1047                 [-c COMPILER] [-D DEST] [-j NJOB] [-M MOBJ] [-m MACH]
   1048                 [-N NOISY] [-O OOBJ] [-R RELEASE] [-S SEED] [-T TOOLS]
   1049                 [-V VAR=[VALUE]] [-w WRAPPER] [-X X11SRC]
   1050                 [-Z VAR]
   1051                 OPERATION ...
   1052        ${progname} ( -h | -? )
   1053 
   1054 _usage_
   1055 }
   1056 
   1057 # Show help to stdout.
   1058 #
   1059 help()
   1060 {
   1061 	synopsis
   1062 	cat <<_usage_
   1063  Build OPERATIONs (all imply "obj" and "tools"):
   1064     build               Run "make build".
   1065     distribution        Run "make distribution" (includes DESTDIR/etc/ files).
   1066     release             Run "make release" (includes kernels & distrib media).
   1067 
   1068  Other OPERATIONs:
   1069     help                Show this help message, and exit.
   1070     makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
   1071                         Always performed.
   1072     cleandir            Run "make cleandir".  [Default unless -u is used]
   1073     dtb                 Build devicetree blobs.
   1074     obj                 Run "make obj".  [Default unless -o is used]
   1075     tools               Build and install tools.
   1076     install=IDIR        Run "make installworld" to IDIR to install all sets
   1077                         except 'etc'.  Useful after "distribution" or "release".
   1078     kernel=CONF         Build kernel with config file CONF.
   1079     kernel.gdb=CONF     Build kernel (including netbsd.gdb) with config
   1080                         file CONF.
   1081     releasekernel=CONF  Install kernel built by kernel=CONF to RELEASEDIR.
   1082     kernels             Build all kernels.
   1083     installmodules=IDIR Run "make installmodules" to IDIR to install all
   1084                         kernel modules.
   1085     modules             Build kernel modules.
   1086     rumptest            Do a linktest for rump (for developers).
   1087     sets                Create binary sets in
   1088                         RELEASEDIR/RELEASEMACHINEDIR/binary/sets.
   1089                         DESTDIR should be populated beforehand.
   1090     distsets            Same as "distribution sets".
   1091     sourcesets          Create source sets in RELEASEDIR/source/sets.
   1092     syspkgs             Create syspkgs in
   1093                         RELEASEDIR/RELEASEMACHINEDIR/binary/syspkgs.
   1094     pkg=CATEGORY/PKG    (EXPERIMENT) Build a package CATEGORY/PKG from pkgsrc.
   1095     iso-image           Create CD-ROM image in RELEASEDIR/images.
   1096     iso-image-source    Create CD-ROM image with source in RELEASEDIR/images.
   1097     live-image          Create bootable live image in
   1098                         RELEASEDIR/RELEASEMACHINEDIR/installation/liveimage.
   1099     install-image       Create bootable installation image in
   1100                         RELEASEDIR/RELEASEMACHINEDIR/installation/installimage.
   1101     disk-image=TARGET   Create bootable disk image in
   1102                         RELEASEDIR/RELEASEMACHINEDIR/binary/gzimg/TARGET.img.gz.
   1103     params              Create params file with various make(1) parameters.
   1104     show-params         Show various make(1) parameters.
   1105     list-arch           Show a list of valid MACHINE/MACHINE_ARCH values,
   1106                         and exit.  The list may be narrowed by passing glob
   1107                         patterns or exact values in MACHINE or MACHINE_ARCH.
   1108     mkrepro-timestamp   Show the latest source timestamp used for reproducible
   1109                         builds and exit.  Requires -P or -V MKREPRO=yes.
   1110 
   1111  Options:
   1112     -a ARCH        Set MACHINE_ARCH=ARCH.  [Default: deduced from MACHINE]
   1113     -B BID         Set BUILDID=BID.
   1114     -C EXTRAS      Append EXTRAS to CDEXTRA for inclusion on CD-ROM.
   1115     -c COMPILER    Select compiler from COMPILER:
   1116                        clang
   1117                        gcc
   1118                    [Default: gcc]
   1119     -D DEST        Set DESTDIR=DEST.  [Default: destdir.\${MACHINE}]
   1120     -E             Set "expert" mode; disables various safety checks.
   1121                    Should not be used without expert knowledge of the build
   1122                    system.
   1123     -h             Show this help message, and exit.
   1124     -j NJOB        Run up to NJOB jobs in parallel; see make(1) -j.
   1125     -M MOBJ        Set obj root directory to MOBJ; sets MAKEOBJDIRPREFIX=MOBJ,
   1126                    unsets MAKEOBJDIR.
   1127     -m MACH        Set MACHINE=MACH.  Some MACH values are actually
   1128                    aliases that set MACHINE/MACHINE_ARCH pairs.
   1129                    [Default: deduced from the host system if the host
   1130                    OS is NetBSD]
   1131     -N NOISY       Set the noisiness (MAKEVERBOSE) level of the build to NOISY:
   1132                        0   Minimal output ("quiet").
   1133                        1   Describe what is occurring.
   1134                        2   Describe what is occurring and echo the actual
   1135                            command.
   1136                        3   Ignore the effect of the "@" prefix in make
   1137                            commands.
   1138                        4   Trace shell commands using the shell's -x flag.
   1139                    [Default: 2]
   1140     -n             Show commands that would be executed, but do not execute
   1141                    them.
   1142     -O OOBJ        Set obj root directory to OOBJ; sets a MAKEOBJDIR pattern
   1143                    using OOBJ, unsets MAKEOBJDIRPREFIX.
   1144     -o             Set MKOBJDIRS=no; do not create objdirs at start of build.
   1145     -P             Set MKREPRO and MKREPRO_TIMESTAMP to the latest source
   1146                    CVS timestamp for reproducible builds.
   1147     -R RELEASE     Set RELEASEDIR=RELEASE.  [Default: releasedir]
   1148     -r             Remove contents of TOOLDIR and DESTDIR before building.
   1149     -S SEED        Set BUILDSEED=SEED.  [Default: NetBSD-majorversion]
   1150     -T TOOLS       Set TOOLDIR=TOOLS.  If unset, and TOOLDIR is not set
   1151                    in the environment, ${toolprefix}make will be (re)built
   1152                    unconditionally.
   1153     -U             Set MKUNPRIVED=yes; build without requiring root privileges,
   1154                    install from an unprivileged build with proper file
   1155                    permissions.
   1156     -u             Set MKUPDATE=yes; do not run "make cleandir" first.
   1157                    Without this, everything is rebuilt, including the tools.
   1158     -V VAR=[VALUE] Set variable VAR=VALUE.
   1159     -w WRAPPER     Create ${toolprefix}make script as WRAPPER.
   1160                    [Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE}]
   1161     -X X11SRC      Set X11SRCDIR=X11SRC.  [Default: /usr/xsrc]
   1162     -x             Set MKX11=yes; build X11 from X11SRCDIR.
   1163     -Z VAR         Unset ("zap") variable VAR.
   1164     -?             Show this help message, and exit.
   1165 
   1166 _usage_
   1167 }
   1168 
   1169 # Show optional error message, help to stderr, and exit 1.
   1170 #
   1171 usage()
   1172 {
   1173 	if [ -n "$*" ]; then
   1174 		echo 1>&2 ""
   1175 		echo 1>&2 "${progname}: $*"
   1176 	fi
   1177 	synopsis 1>&2
   1178 	exit 1
   1179 }
   1180 
   1181 parseoptions()
   1182 {
   1183 	opts='a:B:C:c:D:Ehj:M:m:N:nO:oPR:rS:T:UuV:w:X:xZ:'
   1184 	opt_a=false
   1185 	opt_m=false
   1186 
   1187 	if type getopts >/dev/null 2>&1; then
   1188 		# Use POSIX getopts.
   1189 		#
   1190 		getoptcmd='getopts :${opts} opt && opt=-${opt}'
   1191 		optargcmd=':'
   1192 		optremcmd='shift $((${OPTIND} -1))'
   1193 	else
   1194 		type getopt >/dev/null 2>&1 ||
   1195 		    bomb "Shell does not support getopts or getopt"
   1196 
   1197 		# Use old-style getopt(1) (doesn't handle whitespace in args).
   1198 		#
   1199 		args="$(getopt ${opts} $*)"
   1200 		[ $? = 0 ] || usage
   1201 		set -- ${args}
   1202 
   1203 		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
   1204 		optargcmd='OPTARG="$1"; shift'
   1205 		optremcmd=':'
   1206 	fi
   1207 
   1208 	# Parse command line options.
   1209 	#
   1210 	while eval ${getoptcmd}; do
   1211 		case ${opt} in
   1212 
   1213 		-a)
   1214 			eval ${optargcmd}
   1215 			MACHINE_ARCH=${OPTARG}
   1216 			opt_a=true
   1217 			;;
   1218 
   1219 		-B)
   1220 			eval ${optargcmd}
   1221 			BUILDID=${OPTARG}
   1222 			;;
   1223 
   1224 		-C)
   1225 			eval ${optargcmd}; resolvepaths OPTARG
   1226 			CDEXTRA="${CDEXTRA}${CDEXTRA:+ }${OPTARG}"
   1227 			;;
   1228 
   1229 		-c)
   1230 			eval ${optargcmd}
   1231 			case "${OPTARG}" in
   1232 			gcc)	# default, no variables needed
   1233 				;;
   1234 			clang)	setmakeenv HAVE_LLVM yes
   1235 				setmakeenv MKLLVM yes
   1236 				setmakeenv MKGCC no
   1237 				;;
   1238 			#pcc)	...
   1239 			#	;;
   1240 			*)	bomb "Unknown compiler: ${OPTARG}"
   1241 			esac
   1242 			;;
   1243 
   1244 		-D)
   1245 			eval ${optargcmd}; resolvepath OPTARG
   1246 			setmakeenv DESTDIR "${OPTARG}"
   1247 			;;
   1248 
   1249 		-E)
   1250 			do_expertmode=true
   1251 			;;
   1252 
   1253 		-j)
   1254 			eval ${optargcmd}
   1255 			parallel="-j ${OPTARG}"
   1256 			;;
   1257 
   1258 		-M)
   1259 			eval ${optargcmd}; resolvepath OPTARG
   1260 			case "${OPTARG}" in
   1261 			\$*)	usage "-M argument must not begin with '\$'"
   1262 				;;
   1263 			*\$*)	# can use resolvepath, but can't set TOP_objdir
   1264 				resolvepath OPTARG
   1265 				;;
   1266 			*)	resolvepath OPTARG
   1267 				TOP_objdir="${OPTARG}${TOP}"
   1268 				;;
   1269 			esac
   1270 			unsetmakeenv MAKEOBJDIR
   1271 			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
   1272 			;;
   1273 
   1274 			# -m overrides MACHINE_ARCH unless "-a" is specified
   1275 		-m)
   1276 			eval ${optargcmd}
   1277 			MACHINE="${OPTARG}"
   1278 			opt_m=true
   1279 			;;
   1280 
   1281 		-N)
   1282 			eval ${optargcmd}
   1283 			case "${OPTARG}" in
   1284 			0|1|2|3|4)
   1285 				setmakeenv MAKEVERBOSE "${OPTARG}"
   1286 				;;
   1287 			*)
   1288 				usage "'${OPTARG}' is not a valid value for -N"
   1289 				;;
   1290 			esac
   1291 			;;
   1292 
   1293 		-n)
   1294 			runcmd=echo
   1295 			;;
   1296 
   1297 		-O)
   1298 			eval ${optargcmd}
   1299 			case "${OPTARG}" in
   1300 			*\$*)	usage "-O argument must not contain '\$'"
   1301 				;;
   1302 			*)	resolvepath OPTARG
   1303 				TOP_objdir="${OPTARG}"
   1304 				;;
   1305 			esac
   1306 			unsetmakeenv MAKEOBJDIRPREFIX
   1307 			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
   1308 			;;
   1309 
   1310 		-o)
   1311 			MKOBJDIRS=no
   1312 			;;
   1313 
   1314 		-P)
   1315 			MKREPRO=yes
   1316 			;;
   1317 
   1318 		-R)
   1319 			eval ${optargcmd}; resolvepath OPTARG
   1320 			setmakeenv RELEASEDIR "${OPTARG}"
   1321 			;;
   1322 
   1323 		-r)
   1324 			do_removedirs=true
   1325 			do_rebuildmake=true
   1326 			;;
   1327 
   1328 		-S)
   1329 			eval ${optargcmd}
   1330 			setmakeenv BUILDSEED "${OPTARG}"
   1331 			;;
   1332 
   1333 		-T)
   1334 			eval ${optargcmd}; resolvepath OPTARG
   1335 			TOOLDIR="${OPTARG}"
   1336 			export TOOLDIR
   1337 			;;
   1338 
   1339 		-U)
   1340 			setmakeenv MKUNPRIVED yes
   1341 			;;
   1342 
   1343 		-u)
   1344 			setmakeenv MKUPDATE yes
   1345 			;;
   1346 
   1347 		-V)
   1348 			eval ${optargcmd}
   1349 			case "${OPTARG}" in
   1350 		    # XXX: consider restricting which variables can be changed?
   1351 			[a-zA-Z_]*=*)
   1352 				safe_setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
   1353 				;;
   1354 			[a-zA-Z_]*)
   1355 				safe_setmakeenv "${OPTARG}" ""
   1356 				;;
   1357 			*)
   1358 				usage "-V argument must be of the form 'VAR[=VALUE]'"
   1359 				;;
   1360 			esac
   1361 			;;
   1362 
   1363 		-w)
   1364 			eval ${optargcmd}; resolvepath OPTARG
   1365 			makewrapper="${OPTARG}"
   1366 			;;
   1367 
   1368 		-X)
   1369 			eval ${optargcmd}; resolvepath OPTARG
   1370 			setmakeenv X11SRCDIR "${OPTARG}"
   1371 			;;
   1372 
   1373 		-x)
   1374 			setmakeenv MKX11 yes
   1375 			;;
   1376 
   1377 		-Z)
   1378 			eval ${optargcmd}
   1379 		    # XXX: consider restricting which variables can be unset?
   1380 			safe_unsetmakeenv "${OPTARG}"
   1381 			;;
   1382 
   1383 		--)
   1384 			break
   1385 			;;
   1386 
   1387 		-h)
   1388 			help
   1389 			exit 0
   1390 			;;
   1391 
   1392 		'-?')
   1393 			if [ "${OPTARG}" = '?' ]; then
   1394 				help
   1395 				exit 0
   1396 			fi
   1397 			usage "Unknown option -${OPTARG}"
   1398 			;;
   1399 
   1400 		-:)
   1401 			usage "Missing argument for option -${OPTARG}"
   1402 			;;
   1403 
   1404 		*)
   1405 			usage "Unimplemented option ${opt}"
   1406 			;;
   1407 
   1408 		esac
   1409 	done
   1410 
   1411 	# Validate operations.
   1412 	#
   1413 	eval ${optremcmd}
   1414 	while [ $# -gt 0 ]; do
   1415 		op=$1; shift
   1416 		operations="${operations} ${op}"
   1417 
   1418 		case "${op}" in
   1419 
   1420 		help)
   1421 			help
   1422 			exit 0
   1423 			;;
   1424 
   1425 		list-arch)
   1426 			listarch "${MACHINE}" "${MACHINE_ARCH}"
   1427 			exit
   1428 			;;
   1429 		mkrepro-timestamp)
   1430 			setup_mkrepro quiet
   1431 			echo ${MKREPRO_TIMESTAMP:-0}
   1432 			[ ${MKREPRO_TIMESTAMP:-0} -ne 0 ]; exit
   1433 			;;
   1434 
   1435 		kernel=*|releasekernel=*|kernel.gdb=*)
   1436 			arg=${op#*=}
   1437 			op=${op%%=*}
   1438 			[ -n "${arg}" ] ||
   1439 			    bomb "Must supply a kernel name with '${op}=...'"
   1440 			;;
   1441 
   1442 		disk-image=*)
   1443 			arg=${op#*=}
   1444 			op=disk_image
   1445 			[ -n "${arg}" ] ||
   1446 			    bomb "Must supply a target name with '${op}=...'"
   1447 
   1448 			;;
   1449 
   1450 		pkg=*)
   1451 			arg=${op#*=}
   1452 			op=${op%%=*}
   1453 			[ -n "${arg}" ] ||
   1454 			    bomb "Must supply category/package with 'pkg=...'"
   1455 			;;
   1456 
   1457 		install=*|installmodules=*)
   1458 			arg=${op#*=}
   1459 			op=${op%%=*}
   1460 			[ -n "${arg}" ] ||
   1461 			    bomb "Must supply a directory with 'install=...'"
   1462 			;;
   1463 
   1464 		distsets)
   1465 			operations="$(echo "$operations" | sed 's/distsets/distribution sets/')"
   1466 			do_sets=true
   1467 			op=distribution
   1468 			;;
   1469 
   1470 		build|\
   1471 		cleandir|\
   1472 		distribution|\
   1473 		dtb|\
   1474 		install-image|\
   1475 		iso-image-source|\
   1476 		iso-image|\
   1477 		kernels|\
   1478 		libs|\
   1479 		live-image|\
   1480 		makewrapper|\
   1481 		modules|\
   1482 		obj|\
   1483 		params|\
   1484 		release|\
   1485 		rump|\
   1486 		rumptest|\
   1487 		sets|\
   1488 		show-params|\
   1489 		sourcesets|\
   1490 		syspkgs|\
   1491 		tools)
   1492 			;;
   1493 
   1494 		*)
   1495 			usage "Unknown OPERATION '${op}'"
   1496 			;;
   1497 
   1498 		esac
   1499 		# ${op} may contain chars that are not allowed in variable
   1500 		# names.  Replace them with '_' before setting do_${op}.
   1501 		op="$( echo "$op" | tr -s '.-' '__')"
   1502 		eval do_${op}=true
   1503 	done
   1504 	[ -n "${operations}" ] || usage "Missing OPERATION to perform"
   1505 
   1506 	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
   1507 	#
   1508 	if [ -z "${MACHINE}" ]; then
   1509 		[ "${uname_s}" = "NetBSD" ] ||
   1510 		    bomb "MACHINE must be set, or -m must be used, for cross builds"
   1511 		MACHINE=${uname_m}
   1512 		MACHINE_ARCH=${uname_p}
   1513 	fi
   1514 	if $opt_m && ! $opt_a; then
   1515 		# Settings implied by the command line -m option
   1516 		# override MACHINE_ARCH from the environment (if any).
   1517 		getarch
   1518 	fi
   1519 	[ -n "${MACHINE_ARCH}" ] || getarch
   1520 	validatearch
   1521 
   1522 	# Set up default make(1) environment.
   1523 	#
   1524 	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
   1525 	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
   1526 	[ -z "${BUILDINFO}" ] || makeenv="${makeenv} BUILDINFO"
   1527 	MAKEFLAGS="-de -m ${TOP}/share/mk ${MAKEFLAGS}"
   1528 	MAKEFLAGS="${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
   1529 	export MAKEFLAGS MACHINE MACHINE_ARCH
   1530 	setmakeenv USETOOLS "yes"
   1531 	setmakeenv MAKEWRAPPERMACHINE "${makewrappermachine:-${MACHINE}}"
   1532 	setmakeenv MAKE_OBJDIR_CHECK_WRITABLE no
   1533 }
   1534 
   1535 # sanitycheck --
   1536 # Sanity check after parsing command line options, before rebuildmake.
   1537 #
   1538 sanitycheck()
   1539 {
   1540 	# Install as non-root is a bad idea.
   1541 	#
   1542 	if ${do_install} && [ "$id_u" -ne 0 ] ; then
   1543 		if ${do_expertmode}; then
   1544 			warning "Will install as an unprivileged user"
   1545 		else
   1546 			bomb "-E must be set for install as an unprivileged user"
   1547 		fi
   1548 	fi
   1549 
   1550 	# If the PATH contains any non-absolute components (including,
   1551 	# but not limited to, "." or ""), then complain.  As an exception,
   1552 	# allow "" or "." as the last component of the PATH.  This is fatal
   1553 	# if expert mode is not in effect.
   1554 	#
   1555 	local path="${PATH}"
   1556 	path="${path%:}"	# delete trailing ":"
   1557 	path="${path%:.}"	# delete trailing ":."
   1558 	case ":${path}:/" in
   1559 	*:[!/~]*)
   1560 		if ${do_expertmode}; then
   1561 			warning "PATH contains non-absolute components"
   1562 		else
   1563 			bomb "PATH environment variable must not" \
   1564 			     "contain non-absolute components"
   1565 		fi
   1566 		;;
   1567 	esac
   1568 
   1569 	while [ ${MKX11-no} = "yes" ]; do		# not really a loop
   1570 		test -n "${X11SRCDIR}" && {
   1571 		    test -d "${X11SRCDIR}/external" ||
   1572 		    	bomb "X11SRCDIR (${X11SRCDIR}) does not exist (with -x)"
   1573 		    break
   1574 		}
   1575 		for _xd in \
   1576 		    "${NETBSDSRCDIR%/*}/xsrc" \
   1577 		    "${NETBSDSRCDIR}/xsrc" \
   1578 		    /usr/xsrc
   1579 		do
   1580 		    test -f "${_xd}/Makefile" &&
   1581 			setmakeenv X11SRCDIR "${_xd}" &&
   1582 			break 2
   1583 		done
   1584 		bomb "Asked to build X11 but no xsrc"
   1585 	done
   1586 
   1587 	while $do_pkg; do				# not really a loop
   1588 		test -n "${PKGSRCDIR}" && {
   1589 		    test -f "${PKGSRCDIR}/mk/bsd.pkg.mk" ||
   1590 		    	bomb "PKGSRCDIR (${PKGSRCDIR}) does not exist"
   1591 		    break
   1592 		}
   1593 		for _pd in \
   1594 		    "${NETBSDSRCDIR%/*}/pkgsrc" \
   1595 		    "${NETBSDSRCDIR}/pkgsrc" \
   1596 		    /usr/pkgsrc
   1597 		do
   1598 		    test -f "${_pd}/mk/bsd.pkg.mk" &&
   1599 			setmakeenv PKGSRCDIR "${_pd}" &&
   1600 			break 2
   1601 		done
   1602 		bomb "Asked to build package but no pkgsrc"
   1603 	done
   1604 }
   1605 
   1606 # print_tooldir_program --
   1607 # Try to find and show a path to an existing
   1608 # ${TOOLDIR}/bin/${toolprefix}program
   1609 #
   1610 print_tooldir_program()
   1611 {
   1612 	local possible_TOP_OBJ
   1613 	local possible_TOOLDIR
   1614 	local possible_program
   1615 	local tooldir_program
   1616 	local program=${1}
   1617 
   1618 	if [ -n "${TOOLDIR}" ]; then
   1619 		echo "${TOOLDIR}/bin/${toolprefix}${program}"
   1620 		return
   1621 	fi
   1622 
   1623 	# Set host_ostype to something like "NetBSD-4.5.6-i386".  This
   1624 	# is intended to match the HOST_OSTYPE variable in <bsd.own.mk>.
   1625 	#
   1626 	local host_ostype="${uname_s}-$(
   1627 		echo "${uname_r}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
   1628 		)-$(
   1629 		echo "${uname_p}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
   1630 		)"
   1631 
   1632 	# Look in a few potential locations for
   1633 	# ${possible_TOOLDIR}/bin/${toolprefix}${program}.
   1634 	# If we find it, then set possible_program.
   1635 	#
   1636 	# In the usual case (without interference from environment
   1637 	# variables or /etc/mk.conf), <bsd.own.mk> should set TOOLDIR to
   1638 	# "${_SRC_TOP_OBJ_}/tooldir.${host_ostype}".
   1639 	#
   1640 	# In practice it's difficult to figure out the correct value
   1641 	# for _SRC_TOP_OBJ_.  In the easiest case, when the -M or -O
   1642 	# options were passed to build.sh, then ${TOP_objdir} will be
   1643 	# the correct value.  We also try a few other possibilities, but
   1644 	# we do not replicate all the logic of <bsd.obj.mk>.
   1645 	#
   1646 	for possible_TOP_OBJ in \
   1647 		"${TOP_objdir}" \
   1648 		"${MAKEOBJDIRPREFIX:+${MAKEOBJDIRPREFIX}${TOP}}" \
   1649 		"${TOP}" \
   1650 		"${TOP}/obj" \
   1651 		"${TOP}/obj.${MACHINE}"
   1652 	do
   1653 		[ -n "${possible_TOP_OBJ}" ] || continue
   1654 		possible_TOOLDIR="${possible_TOP_OBJ}/tooldir.${host_ostype}"
   1655 		possible_program="${possible_TOOLDIR}/bin/${toolprefix}${program}"
   1656 		if [ -x "${possible_program}" ]; then
   1657 			echo ${possible_program}
   1658 			return;
   1659 		fi
   1660 	done
   1661 	echo ""
   1662 }
   1663 
   1664 # print_tooldir_make --
   1665 # Try to find and show a path to an existing
   1666 # ${TOOLDIR}/bin/${toolprefix}make, for use by rebuildmake() before a
   1667 # new version of ${toolprefix}make has been built.
   1668 #
   1669 # * If TOOLDIR was set in the environment or on the command line, use
   1670 #   that value.
   1671 # * Otherwise try to guess what TOOLDIR would be if not overridden by
   1672 #   /etc/mk.conf, and check whether the resulting directory contains
   1673 #   a copy of ${toolprefix}make (this should work for everybody who
   1674 #   doesn't override TOOLDIR via /etc/mk.conf);
   1675 # * Failing that, search for ${toolprefix}make, nbmake, bmake, or make,
   1676 #   in the PATH (this might accidentally find a version of make that
   1677 #   does not understand the syntax used by NetBSD make, and that will
   1678 #   lead to failure in the next step);
   1679 # * If a copy of make was found above, try to use it with
   1680 #   nobomb_getmakevar to find the correct value for TOOLDIR, and believe the
   1681 #   result only if it's a directory that already exists;
   1682 # * If a value of TOOLDIR was found above, and if
   1683 #   ${TOOLDIR}/bin/${toolprefix}make exists, show that value.
   1684 #
   1685 print_tooldir_make()
   1686 {
   1687 	local possible_make
   1688 	local possible_TOOLDIR
   1689 	local tooldir_make
   1690 
   1691 	possible_make=$(print_tooldir_program make)
   1692 	# If the above didn't work, search the PATH for a suitable
   1693 	# ${toolprefix}make, nbmake, bmake, or make.
   1694 	#
   1695 	: ${possible_make:=$(find_in_PATH ${toolprefix}make '')}
   1696 	: ${possible_make:=$(find_in_PATH nbmake '')}
   1697 	: ${possible_make:=$(find_in_PATH bmake '')}
   1698 	: ${possible_make:=$(find_in_PATH make '')}
   1699 
   1700 	# At this point, we don't care whether possible_make is in the
   1701 	# correct TOOLDIR or not; we simply want it to be usable by
   1702 	# getmakevar to help us find the correct TOOLDIR.
   1703 	#
   1704 	# Use ${possible_make} with nobomb_getmakevar to try to find
   1705 	# the value of TOOLDIR.  Believe the result only if it's
   1706 	# a directory that already exists and contains bin/${toolprefix}make.
   1707 	#
   1708 	if [ -x "${possible_make}" ]; then
   1709 		possible_TOOLDIR="$(
   1710 			make="${possible_make}" \
   1711 			nobomb_getmakevar TOOLDIR 2>/dev/null
   1712 			)"
   1713 		if [ $? = 0 ] && [ -n "${possible_TOOLDIR}" ] \
   1714 		    && [ -d "${possible_TOOLDIR}" ];
   1715 		then
   1716 			tooldir_make="${possible_TOOLDIR}/bin/${toolprefix}make"
   1717 			if [ -x "${tooldir_make}" ]; then
   1718 				echo "${tooldir_make}"
   1719 				return 0
   1720 			fi
   1721 		fi
   1722 	fi
   1723 	return 1
   1724 }
   1725 
   1726 # rebuildmake --
   1727 # Rebuild nbmake in a temporary directory if necessary.  Sets $make
   1728 # to a path to the nbmake executable.  Sets done_rebuildmake=true
   1729 # if nbmake was rebuilt.
   1730 #
   1731 # There is a cyclic dependency between building nbmake and choosing
   1732 # TOOLDIR: TOOLDIR may be affected by settings in /etc/mk.conf, so we
   1733 # would like to use getmakevar to get the value of TOOLDIR; but we can't
   1734 # use getmakevar before we have an up to date version of nbmake; we
   1735 # might already have an up to date version of nbmake in TOOLDIR, but we
   1736 # don't yet know where TOOLDIR is.
   1737 #
   1738 # The default value of TOOLDIR also depends on the location of the top
   1739 # level object directory, so $(getmakevar TOOLDIR) invoked before or
   1740 # after making the top level object directory may produce different
   1741 # results.
   1742 #
   1743 # Strictly speaking, we should do the following:
   1744 #
   1745 #    1. build a new version of nbmake in a temporary directory;
   1746 #    2. use the temporary nbmake to create the top level obj directory;
   1747 #    3. use $(getmakevar TOOLDIR) with the temporary nbmake to
   1748 #       get the correct value of TOOLDIR;
   1749 #    4. move the temporary nbmake to ${TOOLDIR}/bin/nbmake.
   1750 #
   1751 # However, people don't like building nbmake unnecessarily if their
   1752 # TOOLDIR has not changed since an earlier build.  We try to avoid
   1753 # rebuilding a temporary version of nbmake by taking some shortcuts to
   1754 # guess a value for TOOLDIR, looking for an existing version of nbmake
   1755 # in that TOOLDIR, and checking whether that nbmake is newer than the
   1756 # sources used to build it.
   1757 #
   1758 rebuildmake()
   1759 {
   1760 	make="$(print_tooldir_make)"
   1761 	if [ -n "${make}" ] && [ -x "${make}" ]; then
   1762 		for f in usr.bin/make/*.[ch]; do
   1763 			if [ "${f}" -nt "${make}" ]; then
   1764 				statusmsg "${make} outdated" \
   1765 					"(older than ${f}), needs building."
   1766 				do_rebuildmake=true
   1767 				break
   1768 			fi
   1769 		done
   1770 	else
   1771 		statusmsg "No \$TOOLDIR/bin/${toolprefix}make, needs building."
   1772 		do_rebuildmake=true
   1773 	fi
   1774 
   1775 	# Build bootstrap ${toolprefix}make if needed.
   1776 	if ! ${do_rebuildmake}; then
   1777 		return
   1778 	fi
   1779 
   1780 	# Silent configure with MAKEVERBOSE==0
   1781 	if [ ${MAKEVERBOSE:-2} -eq 0 ]; then
   1782 		configure_args=--silent
   1783 	fi
   1784 
   1785 	statusmsg "Bootstrapping ${toolprefix}make"
   1786 	${runcmd} cd "${tmpdir}"
   1787 	${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
   1788 		CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
   1789 	    ${HOST_SH} "${TOP}/tools/make/configure" ${configure_args} ||
   1790 	( cp ${tmpdir}/config.log ${tmpdir}-config.log
   1791 	      bomb "Configure of ${toolprefix}make failed, see ${tmpdir}-config.log for details" )
   1792 	${runcmd} ${HOST_SH} buildmake.sh ||
   1793 	    bomb "Build of ${toolprefix}make failed"
   1794 	make="${tmpdir}/${toolprefix}make"
   1795 	${runcmd} cd "${TOP}"
   1796 	${runcmd} rm -f usr.bin/make/*.o
   1797 	done_rebuildmake=true
   1798 }
   1799 
   1800 # validatemakeparams --
   1801 # Perform some late sanity checks, after rebuildmake,
   1802 # but before createmakewrapper or any real work.
   1803 #
   1804 # Creates the top-level obj directory, because that
   1805 # is needed by some of the sanity checks.
   1806 #
   1807 # Shows status messages reporting the values of several variables.
   1808 #
   1809 validatemakeparams()
   1810 {
   1811 	# Determine MAKECONF first, and set in the makewrapper.
   1812 	# If set in the environment, then use that.
   1813 	# else if ./mk.conf exists, then set MAKECONF to that,
   1814 	# else use the default from share/mk/bsd.own.mk (/etc/mk.conf).
   1815 	#
   1816 	if [ -n "${MAKECONF+1}" ]; then
   1817 		setmakeenv MAKECONF "${MAKECONF}"
   1818 		statusmsg2 "getenv MAKECONF:" "${MAKECONF}"
   1819 	elif [ -f "${TOP}/mk.conf" ]; then
   1820 		setmakeenv MAKECONF "${TOP}/mk.conf"
   1821 		statusmsg2 "mk.conf MAKECONF:" "${MAKECONF}"
   1822 	else
   1823 		MAKECONF=$(getmakevar MAKECONF)
   1824 		setmakeenv MAKECONF "${MAKECONF}"
   1825 		statusmsg2 "share/mk MAKECONF:" "${MAKECONF}"
   1826 	fi
   1827 	if [ -z "${MAKECONF}" ]; then
   1828 		bomb "MAKECONF must not be empty"
   1829 	elif [ -e "${MAKECONF}" ]; then
   1830 		statusmsg2 "MAKECONF file:" "${MAKECONF}"
   1831 	else
   1832 		statusmsg2 "MAKECONF file:" "${MAKECONF} (File not found)"
   1833 	fi
   1834 
   1835 	# Normalise MKOBJDIRS, MKUNPRIVED, and MKUPDATE.
   1836 	# These may be set as build.sh options or in "mk.conf".
   1837 	# Don't export them as they're only used for tests in build.sh.
   1838 	#
   1839 	MKOBJDIRS=$(getmakevar MKOBJDIRS)
   1840 	MKUNPRIVED=$(getmakevar MKUNPRIVED)
   1841 	MKUPDATE=$(getmakevar MKUPDATE)
   1842 
   1843 	# Non-root should always use either the -U or -E flag.
   1844 	#
   1845 	if ! ${do_expertmode} && \
   1846 	    [ "$id_u" -ne 0 ] && \
   1847 	    [ "${MKUNPRIVED}" = "no" ] ; then
   1848 		bomb "-U or -E must be set for build as an unprivileged user"
   1849 	fi
   1850 
   1851 	if [ "${runcmd}" = "echo" ]; then
   1852 		TOOLCHAIN_MISSING=no
   1853 		EXTERNAL_TOOLCHAIN=""
   1854 	else
   1855 		TOOLCHAIN_MISSING=$(bomb_getmakevar TOOLCHAIN_MISSING)
   1856 		EXTERNAL_TOOLCHAIN=$(bomb_getmakevar EXTERNAL_TOOLCHAIN)
   1857 	fi
   1858 	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
   1859 	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
   1860 		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
   1861 		${runcmd} echo "	MACHINE:      ${MACHINE}"
   1862 		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
   1863 		${runcmd} echo ""
   1864 		${runcmd} echo "All builds for this platform should be done via a traditional make"
   1865 		${runcmd} echo "If you wish to use an external cross-toolchain, set"
   1866 		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
   1867 		${runcmd} echo "in either the environment or mk.conf and rerun"
   1868 		${runcmd} echo "	${progname} $*"
   1869 		exit 1
   1870 	fi
   1871 
   1872 	if [ "${MKOBJDIRS}" != "no" ]; then
   1873 		# Create the top-level object directory.
   1874 		#
   1875 		# "make obj NOSUBDIR=" can handle most cases, but it
   1876 		# can't handle the case where MAKEOBJDIRPREFIX is set
   1877 		# while the corresponding directory does not exist
   1878 		# (rules in <bsd.obj.mk> would abort the build).  We
   1879 		# therefore have to handle the MAKEOBJDIRPREFIX case
   1880 		# without invoking "make obj".  The MAKEOBJDIR case
   1881 		# could be handled either way, but we choose to handle
   1882 		# it similarly to MAKEOBJDIRPREFIX.
   1883 		#
   1884 		if [ -n "${TOP_obj}" ]; then
   1885 			# It must have been set by the "-M" or "-O"
   1886 			# command line options, so there's no need to
   1887 			# use getmakevar
   1888 			:
   1889 		elif [ -n "$MAKEOBJDIRPREFIX" ]; then
   1890 			TOP_obj="$(getmakevar MAKEOBJDIRPREFIX)${TOP}"
   1891 		elif [ -n "$MAKEOBJDIR" ]; then
   1892 			TOP_obj="$(getmakevar MAKEOBJDIR)"
   1893 		fi
   1894 		if [ -n "$TOP_obj" ]; then
   1895 			${runcmd} mkdir -p "${TOP_obj}" ||
   1896 			    bomb "Can't create top level object directory" \
   1897 					"${TOP_obj}"
   1898 		else
   1899 			${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1900 			    bomb "Can't create top level object directory" \
   1901 					"using make obj"
   1902 		fi
   1903 
   1904 		# make obj in tools to ensure that the objdir for "tools"
   1905 		# is available.
   1906 		#
   1907 		${runcmd} cd tools
   1908 		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1909 		    bomb "Failed to make obj in tools"
   1910 		${runcmd} cd "${TOP}"
   1911 	fi
   1912 
   1913 	# Find TOOLDIR, DESTDIR, and RELEASEDIR, according to getmakevar,
   1914 	# and bomb if they have changed from the values we had from the
   1915 	# command line or environment.
   1916 	#
   1917 	# This must be done after creating the top-level object directory.
   1918 	#
   1919 	for var in TOOLDIR DESTDIR RELEASEDIR
   1920 	do
   1921 		eval oldval=\"\$${var}\"
   1922 		newval="$(getmakevar $var)"
   1923 		if ! $do_expertmode; then
   1924 			: ${_SRC_TOP_OBJ_:=$(getmakevar _SRC_TOP_OBJ_)}
   1925 			case "$var" in
   1926 			DESTDIR)
   1927 				: ${newval:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
   1928 				makeenv="${makeenv} DESTDIR"
   1929 				;;
   1930 			RELEASEDIR)
   1931 				: ${newval:=${_SRC_TOP_OBJ_}/releasedir}
   1932 				makeenv="${makeenv} RELEASEDIR"
   1933 				;;
   1934 			esac
   1935 		fi
   1936 		if [ -n "$oldval" ] && [ "$oldval" != "$newval" ]; then
   1937 			bomb "Value of ${var} has changed" \
   1938 				"(was \"${oldval}\", now \"${newval}\")"
   1939 		fi
   1940 		eval ${var}=\"\${newval}\"
   1941 		eval export ${var}
   1942 		statusmsg2 "${var} path:" "${newval}"
   1943 	done
   1944 
   1945 	# RELEASEMACHINEDIR is just a subdir name, e.g. "i386".
   1946 	RELEASEMACHINEDIR=$(getmakevar RELEASEMACHINEDIR)
   1947 
   1948 	# Check validity of TOOLDIR and DESTDIR.
   1949 	#
   1950 	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
   1951 		bomb "TOOLDIR '${TOOLDIR}' invalid"
   1952 	fi
   1953 	removedirs="${TOOLDIR}"
   1954 
   1955 	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
   1956 		if ${do_distribution} || ${do_release} || \
   1957 		   [ "${uname_s}" != "NetBSD" ] || \
   1958 		   [ "${uname_m}" != "${MACHINE}" ]; then
   1959 			bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'"
   1960 		fi
   1961 		if ! ${do_expertmode}; then
   1962 			bomb "DESTDIR must != / for non -E (expert) builds"
   1963 		fi
   1964 		statusmsg "WARNING: Building to /, in expert mode."
   1965 		statusmsg "         This may cause your system to break!  Reasons include:"
   1966 		statusmsg "            - your kernel is not up to date"
   1967 		statusmsg "            - the libraries or toolchain have changed"
   1968 		statusmsg "         YOU HAVE BEEN WARNED!"
   1969 	else
   1970 		removedirs="${removedirs} ${DESTDIR}"
   1971 	fi
   1972 	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
   1973 		bomb "Must set RELEASEDIR with 'releasekernel=...'"
   1974 	fi
   1975 
   1976 	# If a previous build.sh run used -U (and therefore created a
   1977 	# METALOG file), then most subsequent build.sh runs must also
   1978 	# use -U.  If DESTDIR is about to be removed, then don't perform
   1979 	# this check.
   1980 	#
   1981 	case "${do_removedirs} ${removedirs} " in
   1982 	true*" ${DESTDIR} "*)
   1983 		# DESTDIR is about to be removed
   1984 		;;
   1985 	*)
   1986 		if [ -e "${DESTDIR}/METALOG" ] && \
   1987 		    [ "${MKUNPRIVED}" = "no" ] ; then
   1988 			if $do_expertmode; then
   1989 				warning "A previous build.sh run specified -U"
   1990 			else
   1991 				bomb "A previous build.sh run specified -U; you must specify it again now"
   1992 			fi
   1993 		fi
   1994 		;;
   1995 	esac
   1996 
   1997 	# live-image and install-image targets require binary sets
   1998 	# (actually DESTDIR/etc/mtree/set.* files) built with MKUNPRIVED.
   1999 	# If release operation is specified with live-image or install-image,
   2000 	# the release op should be performed with -U for later image ops.
   2001 	#
   2002 	if ${do_release} && ( ${do_live_image} || ${do_install_image} ) && \
   2003 	    [ "${MKUNPRIVED}" = "no" ] ; then
   2004 		bomb "-U must be specified on building release to create images later"
   2005 	fi
   2006 }
   2007 
   2008 
   2009 createmakewrapper()
   2010 {
   2011 	# Remove the target directories.
   2012 	#
   2013 	if ${do_removedirs}; then
   2014 		for f in ${removedirs}; do
   2015 			statusmsg "Removing ${f}"
   2016 			${runcmd} rm -r -f "${f}"
   2017 		done
   2018 	fi
   2019 
   2020 	# Recreate $TOOLDIR.
   2021 	#
   2022 	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
   2023 	    bomb "mkdir of '${TOOLDIR}/bin' failed"
   2024 
   2025 	# If we did not previously rebuild ${toolprefix}make, then
   2026 	# check whether $make is still valid and the same as the output
   2027 	# from print_tooldir_make.  If not, then rebuild make now.  A
   2028 	# possible reason for this being necessary is that the actual
   2029 	# value of TOOLDIR might be different from the value guessed
   2030 	# before the top level obj dir was created.
   2031 	#
   2032 	if ! ${done_rebuildmake} && \
   2033 	    ( [ ! -x "$make" ] || [ "$make" != "$(print_tooldir_make)" ] )
   2034 	then
   2035 		rebuildmake
   2036 	fi
   2037 
   2038 	# Install ${toolprefix}make if it was built.
   2039 	#
   2040 	if ${done_rebuildmake}; then
   2041 		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
   2042 		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
   2043 		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
   2044 		make="${TOOLDIR}/bin/${toolprefix}make"
   2045 		statusmsg "Created ${make}"
   2046 	fi
   2047 
   2048 	# Build a ${toolprefix}make wrapper script, usable by hand as
   2049 	# well as by build.sh.
   2050 	#
   2051 	if [ -z "${makewrapper}" ]; then
   2052 		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
   2053 		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
   2054 	fi
   2055 
   2056 	${runcmd} rm -f "${makewrapper}"
   2057 	if [ "${runcmd}" = "echo" ]; then
   2058 		echo 'cat <<EOF >'${makewrapper}
   2059 		makewrapout=
   2060 	else
   2061 		makewrapout=">>\${makewrapper}"
   2062 	fi
   2063 
   2064 	case "${KSH_VERSION:-${SH_VERSION}}" in
   2065 	*PD\ KSH*|*MIRBSD\ KSH*)
   2066 		set +o braceexpand
   2067 		;;
   2068 	esac
   2069 
   2070 	eval cat <<EOF ${makewrapout}
   2071 #! ${HOST_SH}
   2072 # Set proper variables to allow easy "make" building of a NetBSD subtree.
   2073 # Generated from:  \$NetBSD: build.sh,v 1.380 2024/11/29 16:55:24 riastradh Exp $
   2074 # with these arguments: ${_args}
   2075 #
   2076 
   2077 EOF
   2078 	{
   2079 		sorted_vars="$(for var in ${makeenv}; do echo "${var}" ; done \
   2080 			| sort -u )"
   2081 		for var in ${sorted_vars}; do
   2082 			eval val=\"\${${var}}\"
   2083 			eval is_set=\"\${${var}+set}\"
   2084 			if [ -z "${is_set}" ]; then
   2085 				echo "unset ${var}"
   2086 			else
   2087 				qval="$(shell_quote "${val}")"
   2088 				echo "${var}=${qval}; export ${var}"
   2089 			fi
   2090 		done
   2091 
   2092 		cat <<EOF
   2093 
   2094 exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
   2095 EOF
   2096 	} | eval cat "${makewrapout}"
   2097 	[ "${runcmd}" = "echo" ] && echo EOF
   2098 	${runcmd} chmod +x "${makewrapper}"
   2099 	statusmsg2 "Updated makewrapper:" "${makewrapper}"
   2100 }
   2101 
   2102 make_in_dir()
   2103 {
   2104 	local dir="$1"
   2105 	local op="$2"
   2106 	${runcmd} cd "${dir}" ||
   2107 	    bomb "Failed to cd to \"${dir}\""
   2108 	${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2109 	    bomb "Failed to make ${op} in \"${dir}\""
   2110 	${runcmd} cd "${TOP}" ||
   2111 	    bomb "Failed to cd back to \"${TOP}\""
   2112 }
   2113 
   2114 buildtools()
   2115 {
   2116 	if [ "${MKOBJDIRS}" != "no" ]; then
   2117 		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
   2118 		    bomb "Failed to make obj-tools"
   2119 	fi
   2120 	if [ "${MKUPDATE}" = "no" ]; then
   2121 		make_in_dir tools cleandir
   2122 	fi
   2123 	make_in_dir tools build_install
   2124 	statusmsg "Tools built to ${TOOLDIR}"
   2125 }
   2126 
   2127 buildlibs()
   2128 {
   2129 	if [ "${MKOBJDIRS}" != "no" ]; then
   2130 		${runcmd} "${makewrapper}" ${parallel} obj ||
   2131 		    bomb "Failed to make obj"
   2132 	fi
   2133 	if [ "${MKUPDATE}" = "no" ]; then
   2134 		make_in_dir lib cleandir
   2135 	fi
   2136 	make_in_dir . do-distrib-dirs
   2137 	make_in_dir . includes
   2138 	make_in_dir . do-lib
   2139 	statusmsg "libs built"
   2140 }
   2141 
   2142 getkernelconf()
   2143 {
   2144 	kernelconf="$1"
   2145 	if [ "${MKOBJDIRS}" != "no" ]; then
   2146 		# The correct value of KERNOBJDIR might
   2147 		# depend on a prior "make obj" in
   2148 		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
   2149 		#
   2150 		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
   2151 		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
   2152 		make_in_dir "${KERNSRCDIR}/${KERNARCHDIR}/compile" obj
   2153 	fi
   2154 	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
   2155 	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
   2156 	case "${kernelconf}" in
   2157 	*/*)
   2158 		kernelconfpath="${kernelconf}"
   2159 		kernelconfname="${kernelconf##*/}"
   2160 		;;
   2161 	*)
   2162 		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
   2163 		kernelconfname="${kernelconf}"
   2164 		;;
   2165 	esac
   2166 	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
   2167 }
   2168 
   2169 diskimage()
   2170 {
   2171 	ARG="$(echo $1 | tr '[:lower:]' '[:upper:]')"
   2172 	[ -f "${DESTDIR}/etc/mtree/set.base" ] ||
   2173 	    bomb "The release binaries must be built first"
   2174 	kerneldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
   2175 	kernel="${kerneldir}/netbsd-${ARG}.gz"
   2176 	[ -f "${kernel}" ] ||
   2177 	    bomb "The kernel ${kernel} must be built first"
   2178 	make_in_dir "${NETBSDSRCDIR}/etc" "smp_${1}"
   2179 }
   2180 
   2181 buildkernel()
   2182 {
   2183 	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
   2184 		# Building tools every time we build a kernel is clearly
   2185 		# unnecessary.  We could try to figure out whether rebuilding
   2186 		# the tools is necessary this time, but it doesn't seem worth
   2187 		# the trouble.  Instead, we say it's the user's responsibility
   2188 		# to rebuild the tools if necessary.
   2189 		#
   2190 		statusmsg "Building kernel without building new tools"
   2191 		buildkernelwarned=true
   2192 	fi
   2193 	getkernelconf $1
   2194 	statusmsg2 "Building kernel:" "${kernelconf}"
   2195 	statusmsg2 "Build directory:" "${kernelbuildpath}"
   2196 	${runcmd} mkdir -p "${kernelbuildpath}" ||
   2197 	    bomb "Cannot mkdir: ${kernelbuildpath}"
   2198 	if [ "${MKUPDATE}" = "no" ]; then
   2199 		make_in_dir "${kernelbuildpath}" cleandir
   2200 	fi
   2201 	[ -x "${TOOLDIR}/bin/${toolprefix}config" ] \
   2202 	|| bomb "${TOOLDIR}/bin/${toolprefix}config does not exist. You need to \"$0 tools\" first"
   2203 	CONFIGOPTS=$(getmakevar CONFIGOPTS)
   2204 	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" ${CONFIGOPTS} \
   2205 		-b "${kernelbuildpath}" -s "${TOP}/sys" ${configopts} \
   2206 		"${kernelconfpath}" ||
   2207 	    bomb "${toolprefix}config failed for ${kernelconf}"
   2208 	make_in_dir "${kernelbuildpath}" depend
   2209 	make_in_dir "${kernelbuildpath}" all
   2210 
   2211 	if [ "${runcmd}" != "echo" ]; then
   2212 		statusmsg "Kernels built from ${kernelconf}:"
   2213 		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   2214 		for kern in ${kernlist:-netbsd}; do
   2215 			[ -f "${kernelbuildpath}/${kern}" ] && \
   2216 			    echo "  ${kernelbuildpath}/${kern}"
   2217 		done | tee -a "${results}"
   2218 	fi
   2219 }
   2220 
   2221 releasekernel()
   2222 {
   2223 	getkernelconf $1
   2224 	kernelreldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
   2225 	${runcmd} mkdir -p "${kernelreldir}"
   2226 	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   2227 	for kern in ${kernlist:-netbsd}; do
   2228 		builtkern="${kernelbuildpath}/${kern}"
   2229 		[ -f "${builtkern}" ] || continue
   2230 		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
   2231 		statusmsg2 "Kernel copy:" "${releasekern}"
   2232 		if [ "${runcmd}" = "echo" ]; then
   2233 			echo "gzip -c -9 < ${builtkern} > ${releasekern}"
   2234 		else
   2235 			gzip -c -9 < "${builtkern}" > "${releasekern}"
   2236 		fi
   2237 	done
   2238 }
   2239 
   2240 buildkernels()
   2241 {
   2242 	allkernels=$( runcmd= make_in_dir etc '-V ${ALL_KERNELS}' )
   2243 	for k in $allkernels; do
   2244 		buildkernel "${k}"
   2245 	done
   2246 }
   2247 
   2248 buildmodules()
   2249 {
   2250 	setmakeenv MKBINUTILS no
   2251 	if ! ${do_tools} && ! ${buildmoduleswarned:-false}; then
   2252 		# Building tools every time we build modules is clearly
   2253 		# unnecessary as well as a kernel.
   2254 		#
   2255 		statusmsg "Building modules without building new tools"
   2256 		buildmoduleswarned=true
   2257 	fi
   2258 
   2259 	statusmsg "Building kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   2260 	if [ "${MKOBJDIRS}" != "no" ]; then
   2261 		make_in_dir sys/modules obj
   2262 	fi
   2263 	if [ "${MKUPDATE}" = "no" ]; then
   2264 		make_in_dir sys/modules cleandir
   2265 	fi
   2266 	make_in_dir sys/modules dependall
   2267 	make_in_dir sys/modules install
   2268 
   2269 	statusmsg "Successful build of kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   2270 }
   2271 
   2272 builddtb()
   2273 {
   2274 	statusmsg "Building devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
   2275 	if [ "${MKOBJDIRS}" != "no" ]; then
   2276 		make_in_dir sys/dtb obj
   2277 	fi
   2278 	if [ "${MKUPDATE}" = "no" ]; then
   2279 		make_in_dir sys/dtb cleandir
   2280 	fi
   2281 	make_in_dir sys/dtb dependall
   2282 	make_in_dir sys/dtb install
   2283 
   2284 	statusmsg "Successful build of devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
   2285 }
   2286 
   2287 buildpkg()
   2288 {
   2289 	local catpkg
   2290 	local pkgroot
   2291 	local makejobsarg
   2292 	local makejobsvar
   2293 	local quiet
   2294 	local opsys_version
   2295 
   2296 	catpkg="$1"
   2297 
   2298 	pkgroot="${TOP_objdir:-${TOP}}/pkgroot"
   2299 	${runcmd} mkdir -p "${pkgroot}" ||
   2300 	    bomb "Can't create package root" "${pkgroot}"
   2301 
   2302 	# Get a symlink-free absolute path to pkg -- pkgsrc wants this.
   2303 	#
   2304 	# XXX See TOP= above regarding pwd -P.
   2305 	pkgroot=$(unset PWD; cd "${pkgroot}" &&
   2306 		((exec pwd -P 2>/dev/null) || (exec pwd 2>/dev/null)))
   2307 
   2308 	case $parallel in
   2309 	"-j "*)
   2310 		makejobsarg="--make-jobs ${parallel#-j }"
   2311 		makejobsvar="MAKE_JOBS=${parallel#-j }"
   2312 		;;
   2313 	*)	makejobsarg=""
   2314 		makejobsvar=""
   2315 		;;
   2316 	esac
   2317 
   2318 	if [ "${MAKEVERBOSE}" -eq 0 ]; then
   2319 		quiet="--quiet"
   2320 	else
   2321 		quiet=""
   2322 	fi
   2323 
   2324 	# Derived from pkgsrc/mk/bsd.prefs.mk rev. 1.451.
   2325 	opsys_version=$(echo "${DISTRIBVER}" |
   2326 		awk -F. '{major=int($1); minor=int($2); if (minor>=100) minor=99; patch=int($3); if (patch>=100) patch=99; printf "%02d%02d%02d", major, minor, patch}')
   2327 
   2328 	# Bootstrap pkgsrc if needed.
   2329 	#
   2330 	# XXX Redo this if it's out-of-date, not just if it's missing.
   2331 	if ! [ -x "${pkgroot}/pkg/bin/bmake" ]; then
   2332 		statusmsg "Bootstrapping pkgsrc"
   2333 
   2334 		cat >"${pkgroot}/mk.conf-fragment" <<EOF
   2335 USE_CROSS_COMPILE?=	no
   2336 TOOLDIR=		${TOOLDIR}
   2337 CROSS_DESTDIR=		${DESTDIR}
   2338 CROSS_MACHINE_ARCH=	${MACHINE_ARCH}
   2339 CROSS_OPSYS=		NetBSD
   2340 CROSS_OS_VERSION=	${DISTRIBVER}
   2341 CROSS_OPSYS_VERSION=	${opsys_version}
   2342 CROSS_LOWER_OPSYS=	netbsd
   2343 CROSS_LOWER_OPSYS_VERSUFFIX=	# empty
   2344 CROSS_LOWER_OS_VARIANT=		# empty
   2345 CROSS_LOWER_VARIANT_VERSION=	# empty
   2346 CROSS_LOWER_VENDOR=		# empty
   2347 CROSS_OBJECT_FMT=	ELF
   2348 
   2349 ALLOW_VULNERABLE_PACKAGES=	yes
   2350 BINPKG_SITES=			# empty
   2351 FAILOVER_FETCH=			yes
   2352 FETCH_TIMEOUT=			1800
   2353 PASSIVE_FETCH=			yes
   2354 
   2355 DISTDIR=		${pkgroot}/distfiles
   2356 PACKAGES=		${pkgroot}/packages
   2357 WRKOBJDIR=		${pkgroot}/work
   2358 
   2359 .-include "${MAKECONF}"
   2360 
   2361 MKDEBUG=		no	# interferes with pkgsrc builds
   2362 EOF
   2363 
   2364 		# XXX Set --abi for mips and whatever else needs it?
   2365 		# XXX Unprivileged native tools, privileged cross.
   2366 		(cd "${PKGSRCDIR}" && clearmakeenv && ./bootstrap/bootstrap \
   2367 			${makejobsarg} \
   2368 			--mk-fragment "${pkgroot}/mk.conf-fragment" \
   2369 			--prefix "${pkgroot}/pkg" \
   2370 			${quiet} \
   2371 			--unprivileged \
   2372 			--workdir "${pkgroot}/bootwork") \
   2373 		|| bomb "Failed to bootstrap pkgsrc"
   2374 	fi
   2375 
   2376 	# Build the package.
   2377 	(cd "${PKGSRCDIR}/${catpkg}" && clearmakeenv && \
   2378 		"${pkgroot}/pkg/bin/bmake" package \
   2379 			USE_CROSS_COMPILE=yes \
   2380 			${makejobsvar}) \
   2381 	|| bomb "Failed to build ${catpkg}"
   2382 }
   2383 
   2384 installmodules()
   2385 {
   2386 	dir="$1"
   2387 	${runcmd} "${makewrapper}" INSTALLMODULESDIR="${dir}" installmodules ||
   2388 	    bomb "Failed to make installmodules to ${dir}"
   2389 	statusmsg "Successful installmodules to ${dir}"
   2390 }
   2391 
   2392 installworld()
   2393 {
   2394 	dir="$1"
   2395 	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
   2396 	    bomb "Failed to make installworld to ${dir}"
   2397 	statusmsg "Successful installworld to ${dir}"
   2398 }
   2399 
   2400 # Run rump build&link tests.
   2401 #
   2402 # To make this feasible for running without having to install includes and
   2403 # libraries into destdir (i.e. quick), we only run ld.  This is possible
   2404 # since the rump kernel is a closed namespace apart from calls to rumpuser.
   2405 # Therefore, if ld complains only about rumpuser symbols, rump kernel
   2406 # linking was successful.
   2407 #
   2408 # We test that rump links with a number of component configurations.
   2409 # These attempt to mimic what is encountered in the full build.
   2410 # See list below.  The list should probably be either autogenerated
   2411 # or managed elsewhere; keep it here until a better idea arises.
   2412 #
   2413 # Above all, note that THIS IS NOT A SUBSTITUTE FOR A FULL BUILD.
   2414 #
   2415 
   2416 # XXX: uwe: kern/56599 - while riastradh addressed librump problems,
   2417 # there are still unwanted dependencies:
   2418 #    net -> net_net
   2419 #    vfs -> fifo
   2420 
   2421 # -lrumpvfs -> $LRUMPVFS for now
   2422 LRUMPVFS="-lrumpvfs -lrumpvfs_nofifofs"
   2423 
   2424 RUMP_LIBSETS="
   2425 	-lrump,
   2426         -lrumpvfs
   2427             --no-whole-archive -lrumpvfs_nofifofs -lrump,
   2428 	-lrumpkern_tty
   2429             --no-whole-archive $LRUMPVFS -lrump,
   2430 	-lrumpfs_tmpfs
   2431             --no-whole-archive $LRUMPVFS -lrump,
   2432 	-lrumpfs_ffs -lrumpfs_msdos
   2433             --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrump,
   2434 	-lrumpnet_virtif -lrumpnet_netinet -lrumpnet_net -lrumpnet
   2435 	    --no-whole-archive -lrump,
   2436 	-lrumpfs_nfs
   2437 	    --no-whole-archive $LRUMPVFS
   2438 	    -lrumpnet_sockin -lrumpnet_virtif -lrumpnet_netinet
   2439             --start-group -lrumpnet_net -lrumpnet --end-group -lrump,
   2440 	-lrumpdev_cgd -lrumpdev_raidframe -lrumpdev_rnd -lrumpdev_dm
   2441             --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrumpkern_crypto -lrump
   2442 "
   2443 
   2444 dorump()
   2445 {
   2446 	local doclean=""
   2447 	local doobjs=""
   2448 
   2449 	export RUMPKERN_ONLY=1
   2450 	# create obj and distrib dirs
   2451 	if [ "${MKOBJDIRS}" != "no" ]; then
   2452 		make_in_dir "${NETBSDSRCDIR}/etc/mtree" obj
   2453 		make_in_dir "${NETBSDSRCDIR}/sys/rump" obj
   2454 	fi
   2455 	${runcmd} "${makewrapper}" ${parallel} do-distrib-dirs \
   2456 	    || bomb "Could not create distrib-dirs"
   2457 
   2458 	[ "${MKUPDATE}" = "no" ] && doclean="cleandir"
   2459 	targlist="${doclean} ${doobjs} dependall install"
   2460 	# optimize: for test we build only static libs (3x test speedup)
   2461 	if [ "${1}" = "rumptest" ] ; then
   2462 		setmakeenv NOPIC 1
   2463 		setmakeenv NOPROFILE 1
   2464 	fi
   2465 	for cmd in ${targlist} ; do
   2466 		make_in_dir "${NETBSDSRCDIR}/sys/rump" ${cmd}
   2467 	done
   2468 
   2469 	# if we just wanted to build & install rump, we're done
   2470 	[ "${1}" != "rumptest" ] && return
   2471 
   2472 	${runcmd} cd "${NETBSDSRCDIR}/sys/rump/librump/rumpkern" \
   2473 	    || bomb "cd to rumpkern failed"
   2474 	md_quirks=`${runcmd} "${makewrapper}" -V '${_SYMQUIRK}'`
   2475 	# one little, two little, three little backslashes ...
   2476 	md_quirks="$(echo ${md_quirks} | sed 's,\\,\\\\,g'";s/'//g" )"
   2477 	${runcmd} cd "${TOP}" || bomb "cd to ${TOP} failed"
   2478 	tool_ld=`${runcmd} "${makewrapper}" -V '${LD}'`
   2479 
   2480 	local oIFS="${IFS}"
   2481 	IFS=","
   2482 	for set in ${RUMP_LIBSETS} ; do
   2483 		IFS="${oIFS}"
   2484 		${runcmd} ${tool_ld} -nostdlib -L${DESTDIR}/usr/lib	\
   2485 		    -static --whole-archive ${set} --no-whole-archive -lpthread -lc 2>&1 -o /tmp/rumptest.$$ | \
   2486 		      awk -v quirks="${md_quirks}" '
   2487 			/undefined reference/ &&
   2488 			    !/more undefined references.*follow/{
   2489 				if (match($NF,
   2490 				    "`(rumpuser_|rumpcomp_|__" quirks ")") == 0)
   2491 					fails[NR] = $0
   2492 			}
   2493 			/cannot find -l/{fails[NR] = $0}
   2494 			/cannot open output file/{fails[NR] = $0}
   2495 			END{
   2496 				for (x in fails)
   2497 					print fails[x]
   2498 				exit x!=0
   2499 			}'
   2500 		[ $? -ne 0 ] && bomb "Testlink of rump failed: ${set}"
   2501 	done
   2502 	statusmsg "Rump build&link tests successful"
   2503 }
   2504 
   2505 repro_date() {
   2506 	# try the bsd date fail back the linux one
   2507 	date -u -r "$1" 2> /dev/null || date -u -d "@$1"
   2508 }
   2509 
   2510 setup_mkrepro()
   2511 {
   2512 	local quiet="$1"
   2513 
   2514 	if [ ${MKREPRO-no} != "yes" ]; then
   2515 		return
   2516 	fi
   2517 	if [ ${MKREPRO_TIMESTAMP-0} -ne 0 ]; then
   2518 		return;
   2519 	fi
   2520 
   2521 	local dirs=${NETBSDSRCDIR-/usr/src}/
   2522 	if [ ${MKX11-no} = "yes" ]; then
   2523 		dirs="$dirs ${X11SRCDIR-/usr/xsrc}/"
   2524 	fi
   2525 
   2526 	MKREPRO_TIMESTAMP=0
   2527 	local d
   2528 	local t
   2529 	local vcs
   2530 	for d in ${dirs}; do
   2531 		if [ -d "${d}CVS" ]; then
   2532 			local cvslatest=$(print_tooldir_program cvslatest)
   2533 			if [ ! -x "${cvslatest}" ]; then
   2534 				buildtools
   2535 			fi
   2536 
   2537 			local cvslatestflags=
   2538 			if ${do_expertmode}; then
   2539 				cvslatestflags=-i
   2540 			fi
   2541 
   2542 			t=$("${cvslatest}" ${cvslatestflags} "${d}")
   2543 			vcs=cvs
   2544 		elif [ -d "${d}.git" -o -f "${d}.git" ]; then
   2545 			t=$(cd "${d}" && git log -1 --format=%ct)
   2546 			vcs=git
   2547 		elif [ -d "${d}.hg" ]; then
   2548 			t=$(hg --repo "$d" log -r . --template '{date.unixtime}\n')
   2549 			vcs=hg
   2550 		elif [ -f "${d}.hg_archival.txt" ]; then
   2551 			local stat=$(print_tooldir_program stat)
   2552 			if [ ! -x "${stat}" ]; then
   2553 				buildtools
   2554 			fi
   2555 
   2556 			t=$("${stat}" -t '%s' -f '%m' "${d}.hg_archival.txt")
   2557 			vcs=hg
   2558 		else
   2559 			bomb "Cannot determine VCS for '$d'"
   2560 		fi
   2561 
   2562 		if [ -z "$t" ]; then
   2563 			bomb "Failed to get timestamp for vcs=$vcs in '$d'"
   2564 		fi
   2565 
   2566 		#echo "latest $d $vcs $t"
   2567 		if [ "$t" -gt "$MKREPRO_TIMESTAMP" ]; then
   2568 			MKREPRO_TIMESTAMP="$t"
   2569 		fi
   2570 	done
   2571 
   2572 	[ "${MKREPRO_TIMESTAMP}" -ne 0 ] || bomb "Failed to compute timestamp"
   2573 	if [ -z "${quiet}" ]; then
   2574 		statusmsg2 "MKREPRO_TIMESTAMP" \
   2575 			"$(repro_date "${MKREPRO_TIMESTAMP}")"
   2576 	fi
   2577 	export MKREPRO MKREPRO_TIMESTAMP
   2578 }
   2579 
   2580 main()
   2581 {
   2582 	initdefaults
   2583 	_args=$@
   2584 	parseoptions "$@"
   2585 
   2586 	sanitycheck
   2587 
   2588 	build_start=$(date)
   2589 	statusmsg2 "${progname} command:" "$0 $*"
   2590 	statusmsg2 "${progname} started:" "${build_start}"
   2591 	statusmsg2 "NetBSD version:"   "${DISTRIBVER}"
   2592 	statusmsg2 "MACHINE:"          "${MACHINE}"
   2593 	statusmsg2 "MACHINE_ARCH:"     "${MACHINE_ARCH}"
   2594 	statusmsg2 "Build platform:"   "${uname_s} ${uname_r} ${uname_m}"
   2595 	statusmsg2 "HOST_SH:"          "${HOST_SH}"
   2596 	if [ -n "${BUILDID}" ]; then
   2597 		statusmsg2 "BUILDID:"  "${BUILDID}"
   2598 	fi
   2599 	if [ -n "${BUILDINFO}" ]; then
   2600 		printf "%b\n" "${BUILDINFO}" | \
   2601 		while read -r line ; do
   2602 			[ -s "${line}" ] && continue
   2603 			statusmsg2 "BUILDINFO:"  "${line}"
   2604 		done
   2605 	fi
   2606 
   2607 	if [ -n "${MAKECONF+1}" ] && [ -z "${MAKECONF}" ]; then
   2608 		bomb "MAKECONF must not be empty"
   2609 	fi
   2610 
   2611 	rebuildmake
   2612 	validatemakeparams
   2613 	createmakewrapper
   2614 	setup_mkrepro
   2615 
   2616 	# Perform the operations.
   2617 	#
   2618 	for op in ${operations}; do
   2619 		case "${op}" in
   2620 
   2621 		makewrapper)
   2622 			# no-op
   2623 			;;
   2624 
   2625 		tools)
   2626 			buildtools
   2627 			;;
   2628 		libs)
   2629 			buildlibs
   2630 			;;
   2631 
   2632 		sets)
   2633 			statusmsg "Building sets from pre-populated ${DESTDIR}"
   2634 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2635 			    bomb "Failed to make ${op}"
   2636 			setdir=${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
   2637 			statusmsg "Built sets to ${setdir}"
   2638 			;;
   2639 
   2640 		build|distribution|release)
   2641 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2642 			    bomb "Failed to make ${op}"
   2643 			statusmsg "Successful make ${op}"
   2644 			;;
   2645 
   2646 		cleandir|obj|sourcesets|syspkgs|params|show-params)
   2647 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2648 			    bomb "Failed to make ${op}"
   2649 			statusmsg "Successful make ${op}"
   2650 			;;
   2651 
   2652 		iso-image|iso-image-source)
   2653 			${runcmd} "${makewrapper}" ${parallel} \
   2654 			    CDEXTRA="$CDEXTRA" ${op} ||
   2655 			    bomb "Failed to make ${op}"
   2656 			statusmsg "Successful make ${op}"
   2657 			;;
   2658 
   2659 		live-image|install-image)
   2660 			# install-image and live-image require mtree spec files
   2661 			# built with MKUNPRIVED.  Assume MKUNPRIVED build has been
   2662 			# performed if METALOG file is created in DESTDIR.
   2663 			if [ ! -e "${DESTDIR}/METALOG" ] ; then
   2664 				bomb "The release binaries must have been built with -U to create images"
   2665 			fi
   2666 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2667 			    bomb "Failed to make ${op}"
   2668 			statusmsg "Successful make ${op}"
   2669 			;;
   2670 		kernel=*)
   2671 			arg=${op#*=}
   2672 			buildkernel "${arg}"
   2673 			;;
   2674 		kernel.gdb=*)
   2675 			arg=${op#*=}
   2676 			configopts="-D DEBUG=-g"
   2677 			buildkernel "${arg}"
   2678 			;;
   2679 		releasekernel=*)
   2680 			arg=${op#*=}
   2681 			releasekernel "${arg}"
   2682 			;;
   2683 
   2684 		kernels)
   2685 			buildkernels
   2686 			;;
   2687 
   2688 		disk-image=*)
   2689 			arg=${op#*=}
   2690 			diskimage "${arg}"
   2691 			;;
   2692 
   2693 		dtb)
   2694 			builddtb
   2695 			;;
   2696 
   2697 		modules)
   2698 			buildmodules
   2699 			;;
   2700 
   2701 		pkg=*)
   2702 			arg=${op#*=}
   2703 			if ! [ -d "$PKGSRCDIR"/"$arg" ]; then
   2704 				bomb "no such package ${arg}"
   2705 			fi
   2706 			buildpkg "${arg}"
   2707 			;;
   2708 
   2709 		installmodules=*)
   2710 			arg=${op#*=}
   2711 			if [ "${arg}" = "/" ] && \
   2712 			    (	[ "${uname_s}" != "NetBSD" ] || \
   2713 				[ "${uname_m}" != "${MACHINE}" ] ); then
   2714 				bomb "'${op}' must != / for cross builds"
   2715 			fi
   2716 			installmodules "${arg}"
   2717 			;;
   2718 
   2719 		install=*)
   2720 			arg=${op#*=}
   2721 			if [ "${arg}" = "/" ] && \
   2722 			    (	[ "${uname_s}" != "NetBSD" ] || \
   2723 				[ "${uname_m}" != "${MACHINE}" ] ); then
   2724 				bomb "'${op}' must != / for cross builds"
   2725 			fi
   2726 			installworld "${arg}"
   2727 			;;
   2728 
   2729 		rump)
   2730 			make_in_dir . do-distrib-dirs
   2731 			make_in_dir . includes
   2732 			make_in_dir lib/csu dependall
   2733 			make_in_dir lib/csu install
   2734 			make_in_dir external/gpl3/gcc/lib/libgcc dependall
   2735 			make_in_dir external/gpl3/gcc/lib/libgcc install
   2736 			dorump "${op}"
   2737 			;;
   2738 
   2739 		rumptest)
   2740 			dorump "${op}"
   2741 			;;
   2742 
   2743 		*)
   2744 			bomb "Unknown OPERATION '${op}'"
   2745 			;;
   2746 
   2747 		esac
   2748 	done
   2749 
   2750 	statusmsg2 "${progname} ended:" "$(date)"
   2751 	if [ -s "${results}" ]; then
   2752 		echo "===> Summary of results:"
   2753 		sed -e 's/^===>//;s/^/	/' "${results}"
   2754 		echo "===> ."
   2755 	fi
   2756 }
   2757 
   2758 main "$@"
   2759