Home | History | Annotate | Line # | Download | only in src
build.sh revision 1.376
      1 #! /usr/bin/env sh
      2 #	$NetBSD: build.sh,v 1.376 2024/04/20 12:25:46 rillig 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_iso_image=false
    561 	do_iso_image_source=false
    562 	do_live_image=false
    563 	do_install_image=false
    564 	do_disk_image=false
    565 	do_params=false
    566 	do_show_params=false
    567 	do_rump=false
    568 	do_dtb=false
    569 
    570 	# done_{operation}=true if given operation has been done.
    571 	#
    572 	done_rebuildmake=false
    573 
    574 	# Create scratch directory
    575 	#
    576 	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
    577 	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
    578 	trap "cd /; rm -r -f \"${tmpdir}\"" 0
    579 	results="${tmpdir}/build.sh.results"
    580 
    581 	# Set source directories
    582 	#
    583 	setmakeenv NETBSDSRCDIR "${TOP}"
    584 
    585 	# Make sure KERNOBJDIR is an absolute path if defined
    586 	#
    587 	case "${KERNOBJDIR}" in
    588 	''|/*)	;;
    589 	*)	KERNOBJDIR="${TOP}/${KERNOBJDIR}"
    590 		setmakeenv KERNOBJDIR "${KERNOBJDIR}"
    591 		;;
    592 	esac
    593 
    594 	# Find the version of NetBSD
    595 	#
    596 	DISTRIBVER="$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh)"
    597 
    598 	# Set the BUILDSEED to NetBSD-"N"
    599 	#
    600 	setmakeenv BUILDSEED "NetBSD-$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh -m)"
    601 
    602 	# Set MKARZERO to "yes"
    603 	#
    604 	setmakeenv MKARZERO "yes"
    605 
    606 }
    607 
    608 # valid_MACHINE_ARCH -- A multi-line string, listing all valid
    609 # MACHINE/MACHINE_ARCH pairs.
    610 #
    611 # Each line contains a MACHINE and MACHINE_ARCH value, an optional ALIAS
    612 # which may be used to refer to the MACHINE/MACHINE_ARCH pair, and an
    613 # optional DEFAULT or NO_DEFAULT keyword.
    614 #
    615 # When a MACHINE corresponds to multiple possible values of
    616 # MACHINE_ARCH, then this table should list all allowed combinations.
    617 # If the MACHINE is associated with a default MACHINE_ARCH (to be
    618 # used when the user specifies the MACHINE but fails to specify the
    619 # MACHINE_ARCH), then one of the lines should have the "DEFAULT"
    620 # keyword.  If there is no default MACHINE_ARCH for a particular
    621 # MACHINE, then there should be a line with the "NO_DEFAULT" keyword,
    622 # and with a blank MACHINE_ARCH.
    623 #
    624 valid_MACHINE_ARCH='
    625 MACHINE=acorn32		MACHINE_ARCH=earmv4	ALIAS=eacorn32 DEFAULT
    626 MACHINE=algor		MACHINE_ARCH=mips64el	ALIAS=algor64
    627 MACHINE=algor		MACHINE_ARCH=mipsel	DEFAULT
    628 MACHINE=alpha		MACHINE_ARCH=alpha
    629 MACHINE=amd64		MACHINE_ARCH=x86_64
    630 MACHINE=amiga		MACHINE_ARCH=m68k
    631 MACHINE=amigappc	MACHINE_ARCH=powerpc
    632 MACHINE=arc		MACHINE_ARCH=mips64el	ALIAS=arc64
    633 MACHINE=arc		MACHINE_ARCH=mipsel	DEFAULT
    634 MACHINE=atari		MACHINE_ARCH=m68k
    635 MACHINE=bebox		MACHINE_ARCH=powerpc
    636 MACHINE=cats		MACHINE_ARCH=earmv4	ALIAS=ecats DEFAULT
    637 MACHINE=cesfic		MACHINE_ARCH=m68k
    638 MACHINE=cobalt		MACHINE_ARCH=mips64el	ALIAS=cobalt64
    639 MACHINE=cobalt		MACHINE_ARCH=mipsel	DEFAULT
    640 MACHINE=dreamcast	MACHINE_ARCH=sh3el
    641 MACHINE=emips		MACHINE_ARCH=mipseb
    642 MACHINE=epoc32		MACHINE_ARCH=earmv4	ALIAS=eepoc32 DEFAULT
    643 MACHINE=evbarm		MACHINE_ARCH=		NO_DEFAULT
    644 MACHINE=evbarm		MACHINE_ARCH=earmv4	ALIAS=evbearmv4-el	ALIAS=evbarmv4-el
    645 MACHINE=evbarm		MACHINE_ARCH=earmv4eb	ALIAS=evbearmv4-eb	ALIAS=evbarmv4-eb
    646 MACHINE=evbarm		MACHINE_ARCH=earmv5	ALIAS=evbearmv5-el	ALIAS=evbarmv5-el
    647 MACHINE=evbarm		MACHINE_ARCH=earmv5hf	ALIAS=evbearmv5hf-el	ALIAS=evbarmv5hf-el
    648 MACHINE=evbarm		MACHINE_ARCH=earmv5eb	ALIAS=evbearmv5-eb	ALIAS=evbarmv5-eb
    649 MACHINE=evbarm		MACHINE_ARCH=earmv5hfeb	ALIAS=evbearmv5hf-eb	ALIAS=evbarmv5hf-eb
    650 MACHINE=evbarm		MACHINE_ARCH=earmv6	ALIAS=evbearmv6-el	ALIAS=evbarmv6-el
    651 MACHINE=evbarm		MACHINE_ARCH=earmv6hf	ALIAS=evbearmv6hf-el	ALIAS=evbarmv6hf-el
    652 MACHINE=evbarm		MACHINE_ARCH=earmv6eb	ALIAS=evbearmv6-eb	ALIAS=evbarmv6-eb
    653 MACHINE=evbarm		MACHINE_ARCH=earmv6hfeb	ALIAS=evbearmv6hf-eb	ALIAS=evbarmv6hf-eb
    654 MACHINE=evbarm		MACHINE_ARCH=earmv7	ALIAS=evbearmv7-el	ALIAS=evbarmv7-el
    655 MACHINE=evbarm		MACHINE_ARCH=earmv7eb	ALIAS=evbearmv7-eb	ALIAS=evbarmv7-eb
    656 MACHINE=evbarm		MACHINE_ARCH=earmv7hf	ALIAS=evbearmv7hf-el	ALIAS=evbarmv7hf-el
    657 MACHINE=evbarm		MACHINE_ARCH=earmv7hfeb	ALIAS=evbearmv7hf-eb	ALIAS=evbarmv7hf-eb
    658 MACHINE=evbarm		MACHINE_ARCH=aarch64	ALIAS=evbarm64-el	ALIAS=evbarm64
    659 MACHINE=evbarm		MACHINE_ARCH=aarch64eb	ALIAS=evbarm64-eb
    660 MACHINE=evbcf		MACHINE_ARCH=coldfire
    661 MACHINE=evbmips		MACHINE_ARCH=		NO_DEFAULT
    662 MACHINE=evbmips		MACHINE_ARCH=mips64eb	ALIAS=evbmips64-eb
    663 MACHINE=evbmips		MACHINE_ARCH=mips64el	ALIAS=evbmips64-el
    664 MACHINE=evbmips		MACHINE_ARCH=mipseb	ALIAS=evbmips-eb
    665 MACHINE=evbmips		MACHINE_ARCH=mipsel	ALIAS=evbmips-el
    666 MACHINE=evbmips		MACHINE_ARCH=mipsn64eb	ALIAS=evbmipsn64-eb
    667 MACHINE=evbmips		MACHINE_ARCH=mipsn64el	ALIAS=evbmipsn64-el
    668 MACHINE=evbppc		MACHINE_ARCH=powerpc	DEFAULT
    669 MACHINE=evbppc		MACHINE_ARCH=powerpc64	ALIAS=evbppc64
    670 MACHINE=evbsh3		MACHINE_ARCH=		NO_DEFAULT
    671 MACHINE=evbsh3		MACHINE_ARCH=sh3eb	ALIAS=evbsh3-eb
    672 MACHINE=evbsh3		MACHINE_ARCH=sh3el	ALIAS=evbsh3-el
    673 MACHINE=ews4800mips	MACHINE_ARCH=mipseb
    674 MACHINE=hp300		MACHINE_ARCH=m68k
    675 MACHINE=hppa		MACHINE_ARCH=hppa
    676 MACHINE=hpcarm		MACHINE_ARCH=earmv4	ALIAS=hpcearm DEFAULT
    677 MACHINE=hpcmips		MACHINE_ARCH=mipsel
    678 MACHINE=hpcsh		MACHINE_ARCH=sh3el
    679 MACHINE=i386		MACHINE_ARCH=i386
    680 MACHINE=ia64		MACHINE_ARCH=ia64
    681 MACHINE=ibmnws		MACHINE_ARCH=powerpc
    682 MACHINE=iyonix		MACHINE_ARCH=earm	ALIAS=eiyonix DEFAULT
    683 MACHINE=landisk		MACHINE_ARCH=sh3el
    684 MACHINE=luna68k		MACHINE_ARCH=m68k
    685 MACHINE=mac68k		MACHINE_ARCH=m68k
    686 MACHINE=macppc		MACHINE_ARCH=powerpc	DEFAULT
    687 MACHINE=macppc		MACHINE_ARCH=powerpc64	ALIAS=macppc64
    688 MACHINE=mipsco		MACHINE_ARCH=mipseb
    689 MACHINE=mmeye		MACHINE_ARCH=sh3eb
    690 MACHINE=mvme68k		MACHINE_ARCH=m68k
    691 MACHINE=mvmeppc		MACHINE_ARCH=powerpc
    692 MACHINE=netwinder	MACHINE_ARCH=earmv4	ALIAS=enetwinder DEFAULT
    693 MACHINE=news68k		MACHINE_ARCH=m68k
    694 MACHINE=newsmips	MACHINE_ARCH=mipseb
    695 MACHINE=next68k		MACHINE_ARCH=m68k
    696 MACHINE=ofppc		MACHINE_ARCH=powerpc	DEFAULT
    697 MACHINE=ofppc		MACHINE_ARCH=powerpc64	ALIAS=ofppc64
    698 MACHINE=or1k		MACHINE_ARCH=or1k
    699 MACHINE=playstation2	MACHINE_ARCH=mipsel
    700 MACHINE=pmax		MACHINE_ARCH=mips64el	ALIAS=pmax64
    701 MACHINE=pmax		MACHINE_ARCH=mipsel	DEFAULT
    702 MACHINE=prep		MACHINE_ARCH=powerpc
    703 MACHINE=riscv		MACHINE_ARCH=riscv64	ALIAS=riscv64 DEFAULT
    704 MACHINE=riscv		MACHINE_ARCH=riscv32	ALIAS=riscv32
    705 MACHINE=rs6000		MACHINE_ARCH=powerpc
    706 MACHINE=sandpoint	MACHINE_ARCH=powerpc
    707 MACHINE=sbmips		MACHINE_ARCH=		NO_DEFAULT
    708 MACHINE=sbmips		MACHINE_ARCH=mips64eb	ALIAS=sbmips64-eb
    709 MACHINE=sbmips		MACHINE_ARCH=mips64el	ALIAS=sbmips64-el
    710 MACHINE=sbmips		MACHINE_ARCH=mipseb	ALIAS=sbmips-eb
    711 MACHINE=sbmips		MACHINE_ARCH=mipsel	ALIAS=sbmips-el
    712 MACHINE=sgimips		MACHINE_ARCH=mips64eb	ALIAS=sgimips64
    713 MACHINE=sgimips		MACHINE_ARCH=mipseb	DEFAULT
    714 MACHINE=shark		MACHINE_ARCH=earmv4	ALIAS=eshark DEFAULT
    715 MACHINE=sparc		MACHINE_ARCH=sparc
    716 MACHINE=sparc64		MACHINE_ARCH=sparc64
    717 MACHINE=sun2		MACHINE_ARCH=m68000
    718 MACHINE=sun3		MACHINE_ARCH=m68k
    719 MACHINE=vax		MACHINE_ARCH=vax
    720 MACHINE=virt68k		MACHINE_ARCH=m68k
    721 MACHINE=x68k		MACHINE_ARCH=m68k
    722 MACHINE=zaurus		MACHINE_ARCH=earm	ALIAS=ezaurus DEFAULT
    723 '
    724 
    725 # getarch -- find the default MACHINE_ARCH for a MACHINE,
    726 # or convert an alias to a MACHINE/MACHINE_ARCH pair.
    727 #
    728 # Saves the original value of MACHINE in makewrappermachine before
    729 # alias processing.
    730 #
    731 # Sets MACHINE and MACHINE_ARCH if the input MACHINE value is
    732 # recognised as an alias, or recognised as a machine that has a default
    733 # MACHINE_ARCH (or that has only one possible MACHINE_ARCH).
    734 #
    735 # Leaves MACHINE and MACHINE_ARCH unchanged if MACHINE is recognised
    736 # as being associated with multiple MACHINE_ARCH values with no default.
    737 #
    738 # Bombs if MACHINE is not recognised.
    739 #
    740 getarch()
    741 {
    742 	local IFS
    743 	local found=""
    744 	local line
    745 
    746 	IFS="${nl}"
    747 	makewrappermachine="${MACHINE}"
    748 	for line in ${valid_MACHINE_ARCH}; do
    749 		line="${line%%#*}" # ignore comments
    750 		line="$( IFS=" ${tab}" ; echo $line )" # normalise white space
    751 		case "${line} " in
    752 		" ")
    753 			# skip blank lines or comment lines
    754 			continue
    755 			;;
    756 		*" ALIAS=${MACHINE} "*)
    757 			# Found a line with a matching ALIAS=<alias>.
    758 			found="$line"
    759 			break
    760 			;;
    761 		"MACHINE=${MACHINE} "*" NO_DEFAULT"*)
    762 			# Found an explicit "NO_DEFAULT" for this MACHINE.
    763 			found="$line"
    764 			break
    765 			;;
    766 		"MACHINE=${MACHINE} "*" DEFAULT"*)
    767 			# Found an explicit "DEFAULT" for this MACHINE.
    768 			found="$line"
    769 			break
    770 			;;
    771 		"MACHINE=${MACHINE} "*)
    772 			# Found a line for this MACHINE.  If it's the
    773 			# first such line, then tentatively accept it.
    774 			# If it's not the first matching line, then
    775 			# remember that there was more than one match.
    776 			case "$found" in
    777 			'')	found="$line" ;;
    778 			*)	found="MULTIPLE_MATCHES" ;;
    779 			esac
    780 			;;
    781 		esac
    782 	done
    783 
    784 	case "$found" in
    785 	*NO_DEFAULT*|*MULTIPLE_MATCHES*)
    786 		# MACHINE is OK, but MACHINE_ARCH is still unknown
    787 		return
    788 		;;
    789 	"MACHINE="*" MACHINE_ARCH="*)
    790 		# Obey the MACHINE= and MACHINE_ARCH= parts of the line.
    791 		IFS=" "
    792 		for frag in ${found}; do
    793 			case "$frag" in
    794 			MACHINE=*|MACHINE_ARCH=*)
    795 				eval "$frag"
    796 				;;
    797 			esac
    798 		done
    799 		;;
    800 	*)
    801 		bomb "Unknown target MACHINE: ${MACHINE}"
    802 		;;
    803 	esac
    804 }
    805 
    806 # validatearch -- check that the MACHINE/MACHINE_ARCH pair is supported.
    807 #
    808 # Bombs if the pair is not supported.
    809 #
    810 validatearch()
    811 {
    812 	local IFS
    813 	local line
    814 	local foundpair=false foundmachine=false foundarch=false
    815 
    816 	case "${MACHINE_ARCH}" in
    817 	"")
    818 		bomb "No MACHINE_ARCH provided. Use 'build.sh -m ${MACHINE} list-arch' to show options"
    819 		;;
    820 	esac
    821 
    822 	IFS="${nl}"
    823 	for line in ${valid_MACHINE_ARCH}; do
    824 		line="${line%%#*}" # ignore comments
    825 		line="$( IFS=" ${tab}" ; echo $line )" # normalise white space
    826 		case "${line} " in
    827 		" ")
    828 			# skip blank lines or comment lines
    829 			continue
    830 			;;
    831 		"MACHINE=${MACHINE} MACHINE_ARCH=${MACHINE_ARCH} "*)
    832 			foundpair=true
    833 			;;
    834 		"MACHINE=${MACHINE} "*)
    835 			foundmachine=true
    836 			;;
    837 		*"MACHINE_ARCH=${MACHINE_ARCH} "*)
    838 			foundarch=true
    839 			;;
    840 		esac
    841 	done
    842 
    843 	case "${foundpair}:${foundmachine}:${foundarch}" in
    844 	true:*)
    845 		: OK
    846 		;;
    847 	*:false:*)
    848 		bomb "Unknown target MACHINE: ${MACHINE}"
    849 		;;
    850 	*:*:false)
    851 		bomb "Unknown target MACHINE_ARCH: ${MACHINE_ARCH}"
    852 		;;
    853 	*)
    854 		bomb "MACHINE_ARCH '${MACHINE_ARCH}' does not support MACHINE '${MACHINE}'"
    855 		;;
    856 	esac
    857 }
    858 
    859 # listarch -- list valid MACHINE/MACHINE_ARCH/ALIAS values,
    860 # optionally restricted to those where the MACHINE and/or MACHINE_ARCH
    861 # match specified glob patterns.
    862 #
    863 listarch()
    864 {
    865 	local machglob="$1" archglob="$2"
    866 	local IFS
    867 	local wildcard="*"
    868 	local line xline frag
    869 	local line_matches_machine line_matches_arch
    870 	local found=false
    871 
    872 	# Empty machglob or archglob should match anything
    873 	: "${machglob:=${wildcard}}"
    874 	: "${archglob:=${wildcard}}"
    875 
    876 	IFS="${nl}"
    877 	for line in ${valid_MACHINE_ARCH}; do
    878 		line="${line%%#*}" # ignore comments
    879 		xline="$( IFS=" ${tab}" ; echo $line )" # normalise white space
    880 		[ -z "${xline}" ] && continue # skip blank or comment lines
    881 
    882 		line_matches_machine=false
    883 		line_matches_arch=false
    884 
    885 		IFS=" "
    886 		for frag in ${xline}; do
    887 			case "${frag}" in
    888 			MACHINE=${machglob})
    889 				line_matches_machine=true ;;
    890 			ALIAS=${machglob})
    891 				line_matches_machine=true ;;
    892 			MACHINE_ARCH=${archglob})
    893 				line_matches_arch=true ;;
    894 			esac
    895 		done
    896 
    897 		if $line_matches_machine && $line_matches_arch; then
    898 			found=true
    899 			echo "$line"
    900 		fi
    901 	done
    902 	if ! $found; then
    903 		echo >&2 "No match for" \
    904 		    "MACHINE=${machglob} MACHINE_ARCH=${archglob}"
    905 		return 1
    906 	fi
    907 	return 0
    908 }
    909 
    910 # nobomb_getmakevar --
    911 # Given the name of a make variable in $1, show make's idea of the
    912 # value of that variable, or return 1 if there's an error.
    913 #
    914 nobomb_getmakevar()
    915 {
    916 	[ -x "${make}" ] || return 1
    917 	"${make}" -m ${TOP}/share/mk -s -B -f- _x_ <<EOF || return 1
    918 _x_:
    919 	echo \${$1}
    920 .include <bsd.prog.mk>
    921 .include <bsd.kernobj.mk>
    922 EOF
    923 }
    924 
    925 # bomb_getmakevar --
    926 # Given the name of a make variable in $1, show make's idea of the
    927 # value of that variable, or bomb if there's an error.
    928 #
    929 bomb_getmakevar()
    930 {
    931 	[ -x "${make}" ] || bomb "bomb_getmakevar $1: ${make} is not executable"
    932 	nobomb_getmakevar "$1" || bomb "bomb_getmakevar $1: ${make} failed"
    933 }
    934 
    935 # getmakevar --
    936 # Given the name of a make variable in $1, show make's idea of the
    937 # value of that variable, or show a literal '$' followed by the
    938 # variable name if ${make} is not executable.  This is intended for use in
    939 # messages that need to be readable even if $make hasn't been built,
    940 # such as when build.sh is run with the "-n" option.
    941 #
    942 getmakevar()
    943 {
    944 	if [ -x "${make}" ]; then
    945 		bomb_getmakevar "$1"
    946 	else
    947 		echo "\$$1"
    948 	fi
    949 }
    950 
    951 setmakeenv()
    952 {
    953 	eval "$1='$2'; export $1"
    954 	makeenv="${makeenv} $1"
    955 }
    956 
    957 safe_setmakeenv()
    958 {
    959 	case "$1" in
    960 
    961 	#	Look for any vars we want to prohibit here, like:
    962 	# Bad | Dangerous)	usage "Cannot override $1 with -V";;
    963 
    964 	# That first char is OK has already been verified.
    965 	*[!A-Za-z0-9_]*)	usage "Bad variable name (-V): '$1'";;
    966 	esac
    967 	setmakeenv "$@"
    968 }
    969 
    970 unsetmakeenv()
    971 {
    972 	eval "unset $1"
    973 	makeenv="${makeenv} $1"
    974 }
    975 
    976 safe_unsetmakeenv()
    977 {
    978 	case "$1" in
    979 
    980 	#	Look for any vars user should not be able to unset
    981 	# Needed | Must_Have)	usage "Variable $1 cannot be unset";;
    982 
    983 	[!A-Za-z_]* | *[!A-Za-z0-9_]*)	usage "Bad variable name (-Z): '$1'";;
    984 	esac
    985 	unsetmakeenv "$1"
    986 }
    987 
    988 # Given a variable name in $1, modify the variable in place as follows:
    989 # For each space-separated word in the variable, call resolvepath.
    990 #
    991 resolvepaths()
    992 {
    993 	local var="$1"
    994 	local val
    995 	eval val=\"\${${var}}\"
    996 	local newval=''
    997 	local word
    998 	for word in ${val}; do
    999 		resolvepath word
   1000 		newval="${newval}${newval:+ }${word}"
   1001 	done
   1002 	eval ${var}=\"\${newval}\"
   1003 }
   1004 
   1005 # Given a variable name in $1, modify the variable in place as follows:
   1006 # Convert possibly-relative path to absolute path by prepending
   1007 # ${TOP} if necessary.  Also delete trailing "/", if any.
   1008 #
   1009 resolvepath()
   1010 {
   1011 	local var="$1"
   1012 	local val
   1013 	eval val=\"\${${var}}\"
   1014 	case "${val}" in
   1015 	/)
   1016 		;;
   1017 	/*)
   1018 		val="${val%/}"
   1019 		;;
   1020 	*)
   1021 		val="${TOP}/${val%/}"
   1022 		;;
   1023 	esac
   1024 	eval ${var}=\"\${val}\"
   1025 }
   1026 
   1027 # Show synopsis to stdout.
   1028 #
   1029 synopsis()
   1030 {
   1031 	cat <<_usage_
   1032 
   1033 Usage: ${progname} [-EnoPRrUux] [-a ARCH] [-B BID] [-C EXTRAS]
   1034                 [-c COMPILER] [-D DEST] [-j NJOB] [-M MOBJ] [-m MACH]
   1035                 [-N NOISY] [-O OOBJ] [-R RELEASE] [-S SEED] [-T TOOLS]
   1036                 [-V VAR=[VALUE]] [-w WRAPPER] [-X X11SRC]
   1037                 [-Z VAR]
   1038                 OPERATION ...
   1039        ${progname} ( -h | -? )
   1040 
   1041 _usage_
   1042 }
   1043 
   1044 # Show help to stdout.
   1045 #
   1046 help()
   1047 {
   1048 	synopsis
   1049 	cat <<_usage_
   1050  Build OPERATIONs (all imply "obj" and "tools"):
   1051     build               Run "make build".
   1052     distribution        Run "make distribution" (includes DESTDIR/etc/ files).
   1053     release             Run "make release" (includes kernels & distrib media).
   1054 
   1055  Other OPERATIONs:
   1056     help                Show this help message, and exit.
   1057     makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
   1058                         Always performed.
   1059     cleandir            Run "make cleandir".  [Default unless -u is used]
   1060     dtb                 Build devicetree blobs.
   1061     obj                 Run "make obj".  [Default unless -o is used]
   1062     tools               Build and install tools.
   1063     install=IDIR        Run "make installworld" to IDIR to install all sets
   1064                         except 'etc'.  Useful after "distribution" or "release".
   1065     kernel=CONF         Build kernel with config file CONF.
   1066     kernel.gdb=CONF     Build kernel (including netbsd.gdb) with config
   1067                         file CONF.
   1068     releasekernel=CONF  Install kernel built by kernel=CONF to RELEASEDIR.
   1069     kernels             Build all kernels.
   1070     installmodules=IDIR Run "make installmodules" to IDIR to install all
   1071                         kernel modules.
   1072     modules             Build kernel modules.
   1073     rumptest            Do a linktest for rump (for developers).
   1074     sets                Create binary sets in
   1075                         RELEASEDIR/RELEASEMACHINEDIR/binary/sets.
   1076                         DESTDIR should be populated beforehand.
   1077     distsets            Same as "distribution sets".
   1078     sourcesets          Create source sets in RELEASEDIR/source/sets.
   1079     syspkgs             Create syspkgs in
   1080                         RELEASEDIR/RELEASEMACHINEDIR/binary/syspkgs.
   1081     iso-image           Create CD-ROM image in RELEASEDIR/images.
   1082     iso-image-source    Create CD-ROM image with source in RELEASEDIR/images.
   1083     live-image          Create bootable live image in
   1084                         RELEASEDIR/RELEASEMACHINEDIR/installation/liveimage.
   1085     install-image       Create bootable installation image in
   1086                         RELEASEDIR/RELEASEMACHINEDIR/installation/installimage.
   1087     disk-image=TARGET   Create bootable disk image in
   1088                         RELEASEDIR/RELEASEMACHINEDIR/binary/gzimg/TARGET.img.gz.
   1089     params              Create params file with various make(1) parameters.
   1090     show-params         Show various make(1) parameters.
   1091     list-arch           Show a list of valid MACHINE/MACHINE_ARCH values,
   1092                         and exit.  The list may be narrowed by passing glob
   1093                         patterns or exact values in MACHINE or MACHINE_ARCH.
   1094     mkrepro-timestamp   Show the latest source timestamp used for reproducible
   1095                         builds and exit.  Requires -P or -V MKREPRO=yes.
   1096 
   1097  Options:
   1098     -a ARCH        Set MACHINE_ARCH=ARCH.  [Default: deduced from MACHINE]
   1099     -B BID         Set BUILDID=BID.
   1100     -C EXTRAS      Append EXTRAS to CDEXTRA for inclusion on CD-ROM.
   1101     -c COMPILER    Select compiler from COMPILER:
   1102                        clang
   1103                        gcc
   1104                    [Default: gcc]
   1105     -D DEST        Set DESTDIR=DEST.  [Default: destdir.\${MACHINE}]
   1106     -E             Set "expert" mode; disables various safety checks.
   1107                    Should not be used without expert knowledge of the build
   1108                    system.
   1109     -h             Show this help message, and exit.
   1110     -j NJOB        Run up to NJOB jobs in parallel; see make(1) -j.
   1111     -M MOBJ        Set obj root directory to MOBJ; sets MAKEOBJDIRPREFIX=MOBJ,
   1112                    unsets MAKEOBJDIR.
   1113     -m MACH        Set MACHINE=MACH.  Some MACH values are actually
   1114                    aliases that set MACHINE/MACHINE_ARCH pairs.
   1115                    [Default: deduced from the host system if the host
   1116                    OS is NetBSD]
   1117     -N NOISY       Set the noisiness (MAKEVERBOSE) level of the build to NOISY:
   1118                        0   Minimal output ("quiet").
   1119                        1   Describe what is occurring.
   1120                        2   Describe what is occurring and echo the actual
   1121                            command.
   1122                        3   Ignore the effect of the "@" prefix in make
   1123                            commands.
   1124                        4   Trace shell commands using the shell's -x flag.
   1125                    [Default: 2]
   1126     -n             Show commands that would be executed, but do not execute
   1127                    them.
   1128     -O OOBJ        Set obj root directory to OOBJ; sets a MAKEOBJDIR pattern
   1129                    using OOBJ, unsets MAKEOBJDIRPREFIX.
   1130     -o             Set MKOBJDIRS=no; do not create objdirs at start of build.
   1131     -P             Set MKREPRO and MKREPRO_TIMESTAMP to the latest source
   1132                    CVS timestamp for reproducible builds.
   1133     -R RELEASE     Set RELEASEDIR=RELEASE.  [Default: releasedir]
   1134     -r             Remove contents of TOOLDIR and DESTDIR before building.
   1135     -S SEED        Set BUILDSEED=SEED.  [Default: NetBSD-majorversion]
   1136     -T TOOLS       Set TOOLDIR=TOOLS.  If unset, and TOOLDIR is not set
   1137                    in the environment, ${toolprefix}make will be (re)built
   1138                    unconditionally.
   1139     -U             Set MKUNPRIVED=yes; build without requiring root privileges,
   1140                    install from an unprivileged build with proper file
   1141                    permissions.
   1142     -u             Set MKUPDATE=yes; do not run "make cleandir" first.
   1143                    Without this, everything is rebuilt, including the tools.
   1144     -V VAR=[VALUE] Set variable VAR=VALUE.
   1145     -w WRAPPER     Create ${toolprefix}make script as WRAPPER.
   1146                    [Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE}]
   1147     -X X11SRC      Set X11SRCDIR=X11SRC.  [Default: /usr/xsrc]
   1148     -x             Set MKX11=yes; build X11 from X11SRCDIR.
   1149     -Z VAR         Unset ("zap") variable VAR.
   1150     -?             Show this help message, and exit.
   1151 
   1152 _usage_
   1153 }
   1154 
   1155 # Show optional error message, help to stderr, and exit 1.
   1156 #
   1157 usage()
   1158 {
   1159 	if [ -n "$*" ]; then
   1160 		echo 1>&2 ""
   1161 		echo 1>&2 "${progname}: $*"
   1162 	fi
   1163 	synopsis 1>&2
   1164 	exit 1
   1165 }
   1166 
   1167 parseoptions()
   1168 {
   1169 	opts='a:B:C:c:D:Ehj:M:m:N:nO:oPR:rS:T:UuV:w:X:xZ:'
   1170 	opt_a=false
   1171 	opt_m=false
   1172 
   1173 	if type getopts >/dev/null 2>&1; then
   1174 		# Use POSIX getopts.
   1175 		#
   1176 		getoptcmd='getopts :${opts} opt && opt=-${opt}'
   1177 		optargcmd=':'
   1178 		optremcmd='shift $((${OPTIND} -1))'
   1179 	else
   1180 		type getopt >/dev/null 2>&1 ||
   1181 		    bomb "Shell does not support getopts or getopt"
   1182 
   1183 		# Use old-style getopt(1) (doesn't handle whitespace in args).
   1184 		#
   1185 		args="$(getopt ${opts} $*)"
   1186 		[ $? = 0 ] || usage
   1187 		set -- ${args}
   1188 
   1189 		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
   1190 		optargcmd='OPTARG="$1"; shift'
   1191 		optremcmd=':'
   1192 	fi
   1193 
   1194 	# Parse command line options.
   1195 	#
   1196 	while eval ${getoptcmd}; do
   1197 		case ${opt} in
   1198 
   1199 		-a)
   1200 			eval ${optargcmd}
   1201 			MACHINE_ARCH=${OPTARG}
   1202 			opt_a=true
   1203 			;;
   1204 
   1205 		-B)
   1206 			eval ${optargcmd}
   1207 			BUILDID=${OPTARG}
   1208 			;;
   1209 
   1210 		-C)
   1211 			eval ${optargcmd}; resolvepaths OPTARG
   1212 			CDEXTRA="${CDEXTRA}${CDEXTRA:+ }${OPTARG}"
   1213 			;;
   1214 
   1215 		-c)
   1216 			eval ${optargcmd}
   1217 			case "${OPTARG}" in
   1218 			gcc)	# default, no variables needed
   1219 				;;
   1220 			clang)	setmakeenv HAVE_LLVM yes
   1221 				setmakeenv MKLLVM yes
   1222 				setmakeenv MKGCC no
   1223 				;;
   1224 			#pcc)	...
   1225 			#	;;
   1226 			*)	bomb "Unknown compiler: ${OPTARG}"
   1227 			esac
   1228 			;;
   1229 
   1230 		-D)
   1231 			eval ${optargcmd}; resolvepath OPTARG
   1232 			setmakeenv DESTDIR "${OPTARG}"
   1233 			;;
   1234 
   1235 		-E)
   1236 			do_expertmode=true
   1237 			;;
   1238 
   1239 		-j)
   1240 			eval ${optargcmd}
   1241 			parallel="-j ${OPTARG}"
   1242 			;;
   1243 
   1244 		-M)
   1245 			eval ${optargcmd}; resolvepath OPTARG
   1246 			case "${OPTARG}" in
   1247 			\$*)	usage "-M argument must not begin with '\$'"
   1248 				;;
   1249 			*\$*)	# can use resolvepath, but can't set TOP_objdir
   1250 				resolvepath OPTARG
   1251 				;;
   1252 			*)	resolvepath OPTARG
   1253 				TOP_objdir="${OPTARG}${TOP}"
   1254 				;;
   1255 			esac
   1256 			unsetmakeenv MAKEOBJDIR
   1257 			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
   1258 			;;
   1259 
   1260 			# -m overrides MACHINE_ARCH unless "-a" is specified
   1261 		-m)
   1262 			eval ${optargcmd}
   1263 			MACHINE="${OPTARG}"
   1264 			opt_m=true
   1265 			;;
   1266 
   1267 		-N)
   1268 			eval ${optargcmd}
   1269 			case "${OPTARG}" in
   1270 			0|1|2|3|4)
   1271 				setmakeenv MAKEVERBOSE "${OPTARG}"
   1272 				;;
   1273 			*)
   1274 				usage "'${OPTARG}' is not a valid value for -N"
   1275 				;;
   1276 			esac
   1277 			;;
   1278 
   1279 		-n)
   1280 			runcmd=echo
   1281 			;;
   1282 
   1283 		-O)
   1284 			eval ${optargcmd}
   1285 			case "${OPTARG}" in
   1286 			*\$*)	usage "-O argument must not contain '\$'"
   1287 				;;
   1288 			*)	resolvepath OPTARG
   1289 				TOP_objdir="${OPTARG}"
   1290 				;;
   1291 			esac
   1292 			unsetmakeenv MAKEOBJDIRPREFIX
   1293 			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
   1294 			;;
   1295 
   1296 		-o)
   1297 			MKOBJDIRS=no
   1298 			;;
   1299 
   1300 		-P)
   1301 			MKREPRO=yes
   1302 			;;
   1303 
   1304 		-R)
   1305 			eval ${optargcmd}; resolvepath OPTARG
   1306 			setmakeenv RELEASEDIR "${OPTARG}"
   1307 			;;
   1308 
   1309 		-r)
   1310 			do_removedirs=true
   1311 			do_rebuildmake=true
   1312 			;;
   1313 
   1314 		-S)
   1315 			eval ${optargcmd}
   1316 			setmakeenv BUILDSEED "${OPTARG}"
   1317 			;;
   1318 
   1319 		-T)
   1320 			eval ${optargcmd}; resolvepath OPTARG
   1321 			TOOLDIR="${OPTARG}"
   1322 			export TOOLDIR
   1323 			;;
   1324 
   1325 		-U)
   1326 			setmakeenv MKUNPRIVED yes
   1327 			;;
   1328 
   1329 		-u)
   1330 			setmakeenv MKUPDATE yes
   1331 			;;
   1332 
   1333 		-V)
   1334 			eval ${optargcmd}
   1335 			case "${OPTARG}" in
   1336 		    # XXX: consider restricting which variables can be changed?
   1337 			[a-zA-Z_]*=*)
   1338 				safe_setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
   1339 				;;
   1340 			[a-zA-Z_]*)
   1341 				safe_setmakeenv "${OPTARG}" ""
   1342 				;;
   1343 			*)
   1344 				usage "-V argument must be of the form 'VAR[=VALUE]'"
   1345 				;;
   1346 			esac
   1347 			;;
   1348 
   1349 		-w)
   1350 			eval ${optargcmd}; resolvepath OPTARG
   1351 			makewrapper="${OPTARG}"
   1352 			;;
   1353 
   1354 		-X)
   1355 			eval ${optargcmd}; resolvepath OPTARG
   1356 			setmakeenv X11SRCDIR "${OPTARG}"
   1357 			;;
   1358 
   1359 		-x)
   1360 			setmakeenv MKX11 yes
   1361 			;;
   1362 
   1363 		-Z)
   1364 			eval ${optargcmd}
   1365 		    # XXX: consider restricting which variables can be unset?
   1366 			safe_unsetmakeenv "${OPTARG}"
   1367 			;;
   1368 
   1369 		--)
   1370 			break
   1371 			;;
   1372 
   1373 		-h)
   1374 			help
   1375 			exit 0
   1376 			;;
   1377 
   1378 		'-?')
   1379 			if [ "${OPTARG}" = '?' ]; then
   1380 				help
   1381 				exit 0
   1382 			fi
   1383 			usage "Unknown option -${OPTARG}"
   1384 			;;
   1385 
   1386 		-:)
   1387 			usage "Missing argument for option -${OPTARG}"
   1388 			;;
   1389 
   1390 		*)
   1391 			usage "Unimplemented option ${opt}"
   1392 			;;
   1393 
   1394 		esac
   1395 	done
   1396 
   1397 	# Validate operations.
   1398 	#
   1399 	eval ${optremcmd}
   1400 	while [ $# -gt 0 ]; do
   1401 		op=$1; shift
   1402 		operations="${operations} ${op}"
   1403 
   1404 		case "${op}" in
   1405 
   1406 		help)
   1407 			help
   1408 			exit 0
   1409 			;;
   1410 
   1411 		list-arch)
   1412 			listarch "${MACHINE}" "${MACHINE_ARCH}"
   1413 			exit
   1414 			;;
   1415 		mkrepro-timestamp)
   1416 			setup_mkrepro quiet
   1417 			echo ${MKREPRO_TIMESTAMP:-0}
   1418 			[ ${MKREPRO_TIMESTAMP:-0} -ne 0 ]; exit
   1419 			;;
   1420 
   1421 		kernel=*|releasekernel=*|kernel.gdb=*)
   1422 			arg=${op#*=}
   1423 			op=${op%%=*}
   1424 			[ -n "${arg}" ] ||
   1425 			    bomb "Must supply a kernel name with '${op}=...'"
   1426 			;;
   1427 
   1428 		disk-image=*)
   1429 			arg=${op#*=}
   1430 			op=disk_image
   1431 			[ -n "${arg}" ] ||
   1432 			    bomb "Must supply a target name with '${op}=...'"
   1433 
   1434 			;;
   1435 
   1436 		install=*|installmodules=*)
   1437 			arg=${op#*=}
   1438 			op=${op%%=*}
   1439 			[ -n "${arg}" ] ||
   1440 			    bomb "Must supply a directory with 'install=...'"
   1441 			;;
   1442 
   1443 		distsets)
   1444 			operations="$(echo "$operations" | sed 's/distsets/distribution sets/')"
   1445 			do_sets=true
   1446 			op=distribution
   1447 			;;
   1448 
   1449 		build|\
   1450 		cleandir|\
   1451 		distribution|\
   1452 		dtb|\
   1453 		install-image|\
   1454 		iso-image-source|\
   1455 		iso-image|\
   1456 		kernels|\
   1457 		libs|\
   1458 		live-image|\
   1459 		makewrapper|\
   1460 		modules|\
   1461 		obj|\
   1462 		params|\
   1463 		release|\
   1464 		rump|\
   1465 		rumptest|\
   1466 		sets|\
   1467 		show-params|\
   1468 		sourcesets|\
   1469 		syspkgs|\
   1470 		tools)
   1471 			;;
   1472 
   1473 		*)
   1474 			usage "Unknown OPERATION '${op}'"
   1475 			;;
   1476 
   1477 		esac
   1478 		# ${op} may contain chars that are not allowed in variable
   1479 		# names.  Replace them with '_' before setting do_${op}.
   1480 		op="$( echo "$op" | tr -s '.-' '__')"
   1481 		eval do_${op}=true
   1482 	done
   1483 	[ -n "${operations}" ] || usage "Missing OPERATION to perform"
   1484 
   1485 	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
   1486 	#
   1487 	if [ -z "${MACHINE}" ]; then
   1488 		[ "${uname_s}" = "NetBSD" ] ||
   1489 		    bomb "MACHINE must be set, or -m must be used, for cross builds"
   1490 		MACHINE=${uname_m}
   1491 		MACHINE_ARCH=${uname_p}
   1492 	fi
   1493 	if $opt_m && ! $opt_a; then
   1494 		# Settings implied by the command line -m option
   1495 		# override MACHINE_ARCH from the environment (if any).
   1496 		getarch
   1497 	fi
   1498 	[ -n "${MACHINE_ARCH}" ] || getarch
   1499 	validatearch
   1500 
   1501 	# Set up default make(1) environment.
   1502 	#
   1503 	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
   1504 	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
   1505 	[ -z "${BUILDINFO}" ] || makeenv="${makeenv} BUILDINFO"
   1506 	MAKEFLAGS="-de -m ${TOP}/share/mk ${MAKEFLAGS}"
   1507 	MAKEFLAGS="${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
   1508 	export MAKEFLAGS MACHINE MACHINE_ARCH
   1509 	setmakeenv USETOOLS "yes"
   1510 	setmakeenv MAKEWRAPPERMACHINE "${makewrappermachine:-${MACHINE}}"
   1511 	setmakeenv MAKE_OBJDIR_CHECK_WRITABLE no
   1512 }
   1513 
   1514 # sanitycheck --
   1515 # Sanity check after parsing command line options, before rebuildmake.
   1516 #
   1517 sanitycheck()
   1518 {
   1519 	# Install as non-root is a bad idea.
   1520 	#
   1521 	if ${do_install} && [ "$id_u" -ne 0 ] ; then
   1522 		if ${do_expertmode}; then
   1523 			warning "Will install as an unprivileged user"
   1524 		else
   1525 			bomb "-E must be set for install as an unprivileged user"
   1526 		fi
   1527 	fi
   1528 
   1529 	# If the PATH contains any non-absolute components (including,
   1530 	# but not limited to, "." or ""), then complain.  As an exception,
   1531 	# allow "" or "." as the last component of the PATH.  This is fatal
   1532 	# if expert mode is not in effect.
   1533 	#
   1534 	local path="${PATH}"
   1535 	path="${path%:}"	# delete trailing ":"
   1536 	path="${path%:.}"	# delete trailing ":."
   1537 	case ":${path}:/" in
   1538 	*:[!/~]*)
   1539 		if ${do_expertmode}; then
   1540 			warning "PATH contains non-absolute components"
   1541 		else
   1542 			bomb "PATH environment variable must not" \
   1543 			     "contain non-absolute components"
   1544 		fi
   1545 		;;
   1546 	esac
   1547 
   1548 	while [ ${MKX11-no} = "yes" ]; do		# not really a loop
   1549 		test -n "${X11SRCDIR}" && {
   1550 		    test -d "${X11SRCDIR}" ||
   1551 		    	bomb "X11SRCDIR (${X11SRCDIR}) does not exist (with -x)"
   1552 		    break
   1553 		}
   1554 		for _xd in \
   1555 		    "${NETBSDSRCDIR%/*}/xsrc" \
   1556 		    "${NETBSDSRCDIR}/xsrc" \
   1557 		    /usr/xsrc
   1558 		do
   1559 		    test -d "${_xd}" &&
   1560 			setmakeenv X11SRCDIR "${_xd}" &&
   1561 			break 2
   1562 		done
   1563 		bomb "Asked to build X11 but no xsrc"
   1564 	done
   1565 }
   1566 
   1567 # print_tooldir_program --
   1568 # Try to find and show a path to an existing
   1569 # ${TOOLDIR}/bin/${toolprefix}program
   1570 #
   1571 print_tooldir_program()
   1572 {
   1573 	local possible_TOP_OBJ
   1574 	local possible_TOOLDIR
   1575 	local possible_program
   1576 	local tooldir_program
   1577 	local program=${1}
   1578 
   1579 	if [ -n "${TOOLDIR}" ]; then
   1580 		echo "${TOOLDIR}/bin/${toolprefix}${program}"
   1581 		return
   1582 	fi
   1583 
   1584 	# Set host_ostype to something like "NetBSD-4.5.6-i386".  This
   1585 	# is intended to match the HOST_OSTYPE variable in <bsd.own.mk>.
   1586 	#
   1587 	local host_ostype="${uname_s}-$(
   1588 		echo "${uname_r}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
   1589 		)-$(
   1590 		echo "${uname_p}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
   1591 		)"
   1592 
   1593 	# Look in a few potential locations for
   1594 	# ${possible_TOOLDIR}/bin/${toolprefix}${program}.
   1595 	# If we find it, then set possible_program.
   1596 	#
   1597 	# In the usual case (without interference from environment
   1598 	# variables or /etc/mk.conf), <bsd.own.mk> should set TOOLDIR to
   1599 	# "${_SRC_TOP_OBJ_}/tooldir.${host_ostype}".
   1600 	#
   1601 	# In practice it's difficult to figure out the correct value
   1602 	# for _SRC_TOP_OBJ_.  In the easiest case, when the -M or -O
   1603 	# options were passed to build.sh, then ${TOP_objdir} will be
   1604 	# the correct value.  We also try a few other possibilities, but
   1605 	# we do not replicate all the logic of <bsd.obj.mk>.
   1606 	#
   1607 	for possible_TOP_OBJ in \
   1608 		"${TOP_objdir}" \
   1609 		"${MAKEOBJDIRPREFIX:+${MAKEOBJDIRPREFIX}${TOP}}" \
   1610 		"${TOP}" \
   1611 		"${TOP}/obj" \
   1612 		"${TOP}/obj.${MACHINE}"
   1613 	do
   1614 		[ -n "${possible_TOP_OBJ}" ] || continue
   1615 		possible_TOOLDIR="${possible_TOP_OBJ}/tooldir.${host_ostype}"
   1616 		possible_program="${possible_TOOLDIR}/bin/${toolprefix}${program}"
   1617 		if [ -x "${possible_program}" ]; then
   1618 			echo ${possible_program}
   1619 			return;
   1620 		fi
   1621 	done
   1622 	echo ""
   1623 }
   1624 
   1625 # print_tooldir_make --
   1626 # Try to find and show a path to an existing
   1627 # ${TOOLDIR}/bin/${toolprefix}make, for use by rebuildmake() before a
   1628 # new version of ${toolprefix}make has been built.
   1629 #
   1630 # * If TOOLDIR was set in the environment or on the command line, use
   1631 #   that value.
   1632 # * Otherwise try to guess what TOOLDIR would be if not overridden by
   1633 #   /etc/mk.conf, and check whether the resulting directory contains
   1634 #   a copy of ${toolprefix}make (this should work for everybody who
   1635 #   doesn't override TOOLDIR via /etc/mk.conf);
   1636 # * Failing that, search for ${toolprefix}make, nbmake, bmake, or make,
   1637 #   in the PATH (this might accidentally find a version of make that
   1638 #   does not understand the syntax used by NetBSD make, and that will
   1639 #   lead to failure in the next step);
   1640 # * If a copy of make was found above, try to use it with
   1641 #   nobomb_getmakevar to find the correct value for TOOLDIR, and believe the
   1642 #   result only if it's a directory that already exists;
   1643 # * If a value of TOOLDIR was found above, and if
   1644 #   ${TOOLDIR}/bin/${toolprefix}make exists, show that value.
   1645 #
   1646 print_tooldir_make()
   1647 {
   1648 	local possible_make
   1649 	local possible_TOOLDIR
   1650 	local tooldir_make
   1651 
   1652 	possible_make=$(print_tooldir_program make)
   1653 	# If the above didn't work, search the PATH for a suitable
   1654 	# ${toolprefix}make, nbmake, bmake, or make.
   1655 	#
   1656 	: ${possible_make:=$(find_in_PATH ${toolprefix}make '')}
   1657 	: ${possible_make:=$(find_in_PATH nbmake '')}
   1658 	: ${possible_make:=$(find_in_PATH bmake '')}
   1659 	: ${possible_make:=$(find_in_PATH make '')}
   1660 
   1661 	# At this point, we don't care whether possible_make is in the
   1662 	# correct TOOLDIR or not; we simply want it to be usable by
   1663 	# getmakevar to help us find the correct TOOLDIR.
   1664 	#
   1665 	# Use ${possible_make} with nobomb_getmakevar to try to find
   1666 	# the value of TOOLDIR.  Believe the result only if it's
   1667 	# a directory that already exists and contains bin/${toolprefix}make.
   1668 	#
   1669 	if [ -x "${possible_make}" ]; then
   1670 		possible_TOOLDIR="$(
   1671 			make="${possible_make}" \
   1672 			nobomb_getmakevar TOOLDIR 2>/dev/null
   1673 			)"
   1674 		if [ $? = 0 ] && [ -n "${possible_TOOLDIR}" ] \
   1675 		    && [ -d "${possible_TOOLDIR}" ];
   1676 		then
   1677 			tooldir_make="${possible_TOOLDIR}/bin/${toolprefix}make"
   1678 			if [ -x "${tooldir_make}" ]; then
   1679 				echo "${tooldir_make}"
   1680 				return 0
   1681 			fi
   1682 		fi
   1683 	fi
   1684 	return 1
   1685 }
   1686 
   1687 # rebuildmake --
   1688 # Rebuild nbmake in a temporary directory if necessary.  Sets $make
   1689 # to a path to the nbmake executable.  Sets done_rebuildmake=true
   1690 # if nbmake was rebuilt.
   1691 #
   1692 # There is a cyclic dependency between building nbmake and choosing
   1693 # TOOLDIR: TOOLDIR may be affected by settings in /etc/mk.conf, so we
   1694 # would like to use getmakevar to get the value of TOOLDIR; but we can't
   1695 # use getmakevar before we have an up to date version of nbmake; we
   1696 # might already have an up to date version of nbmake in TOOLDIR, but we
   1697 # don't yet know where TOOLDIR is.
   1698 #
   1699 # The default value of TOOLDIR also depends on the location of the top
   1700 # level object directory, so $(getmakevar TOOLDIR) invoked before or
   1701 # after making the top level object directory may produce different
   1702 # results.
   1703 #
   1704 # Strictly speaking, we should do the following:
   1705 #
   1706 #    1. build a new version of nbmake in a temporary directory;
   1707 #    2. use the temporary nbmake to create the top level obj directory;
   1708 #    3. use $(getmakevar TOOLDIR) with the temporary nbmake to
   1709 #       get the correct value of TOOLDIR;
   1710 #    4. move the temporary nbmake to ${TOOLDIR}/bin/nbmake.
   1711 #
   1712 # However, people don't like building nbmake unnecessarily if their
   1713 # TOOLDIR has not changed since an earlier build.  We try to avoid
   1714 # rebuilding a temporary version of nbmake by taking some shortcuts to
   1715 # guess a value for TOOLDIR, looking for an existing version of nbmake
   1716 # in that TOOLDIR, and checking whether that nbmake is newer than the
   1717 # sources used to build it.
   1718 #
   1719 rebuildmake()
   1720 {
   1721 	make="$(print_tooldir_make)"
   1722 	if [ -n "${make}" ] && [ -x "${make}" ]; then
   1723 		for f in usr.bin/make/*.[ch]; do
   1724 			if [ "${f}" -nt "${make}" ]; then
   1725 				statusmsg "${make} outdated" \
   1726 					"(older than ${f}), needs building."
   1727 				do_rebuildmake=true
   1728 				break
   1729 			fi
   1730 		done
   1731 	else
   1732 		statusmsg "No \$TOOLDIR/bin/${toolprefix}make, needs building."
   1733 		do_rebuildmake=true
   1734 	fi
   1735 
   1736 	# Build bootstrap ${toolprefix}make if needed.
   1737 	if ! ${do_rebuildmake}; then
   1738 		return
   1739 	fi
   1740 
   1741 	# Silent configure with MAKEVERBOSE==0
   1742 	if [ ${MAKEVERBOSE:-2} -eq 0 ]; then
   1743 		configure_args=--silent
   1744 	fi
   1745 
   1746 	statusmsg "Bootstrapping ${toolprefix}make"
   1747 	${runcmd} cd "${tmpdir}"
   1748 	${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
   1749 		CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
   1750 	    ${HOST_SH} "${TOP}/tools/make/configure" ${configure_args} ||
   1751 	( cp ${tmpdir}/config.log ${tmpdir}-config.log
   1752 	      bomb "Configure of ${toolprefix}make failed, see ${tmpdir}-config.log for details" )
   1753 	${runcmd} ${HOST_SH} buildmake.sh ||
   1754 	    bomb "Build of ${toolprefix}make failed"
   1755 	make="${tmpdir}/${toolprefix}make"
   1756 	${runcmd} cd "${TOP}"
   1757 	${runcmd} rm -f usr.bin/make/*.o
   1758 	done_rebuildmake=true
   1759 }
   1760 
   1761 # validatemakeparams --
   1762 # Perform some late sanity checks, after rebuildmake,
   1763 # but before createmakewrapper or any real work.
   1764 #
   1765 # Creates the top-level obj directory, because that
   1766 # is needed by some of the sanity checks.
   1767 #
   1768 # Shows status messages reporting the values of several variables.
   1769 #
   1770 validatemakeparams()
   1771 {
   1772 	# Determine MAKECONF first, and set in the makewrapper.
   1773 	# If set in the environment, then use that.
   1774 	# else if ./mk.conf exists, then set MAKECONF to that,
   1775 	# else use the default from share/mk/bsd.own.mk (/etc/mk.conf).
   1776 	#
   1777 	if [ -n "${MAKECONF+1}" ]; then
   1778 		setmakeenv MAKECONF "${MAKECONF}"
   1779 		statusmsg2 "getenv MAKECONF:" "${MAKECONF}"
   1780 	elif [ -f "${TOP}/mk.conf" ]; then
   1781 		setmakeenv MAKECONF "${TOP}/mk.conf"
   1782 		statusmsg2 "mk.conf MAKECONF:" "${MAKECONF}"
   1783 	else
   1784 		MAKECONF=$(getmakevar MAKECONF)
   1785 		setmakeenv MAKECONF "${MAKECONF}"
   1786 		statusmsg2 "share/mk MAKECONF:" "${MAKECONF}"
   1787 	fi
   1788 	if [ -z "${MAKECONF}" ]; then
   1789 		bomb "MAKECONF must not be empty"
   1790 	elif [ -e "${MAKECONF}" ]; then
   1791 		statusmsg2 "MAKECONF file:" "${MAKECONF}"
   1792 	else
   1793 		statusmsg2 "MAKECONF file:" "${MAKECONF} (File not found)"
   1794 	fi
   1795 
   1796 	# Normalise MKOBJDIRS, MKUNPRIVED, and MKUPDATE.
   1797 	# These may be set as build.sh options or in "mk.conf".
   1798 	# Don't export them as they're only used for tests in build.sh.
   1799 	#
   1800 	MKOBJDIRS=$(getmakevar MKOBJDIRS)
   1801 	MKUNPRIVED=$(getmakevar MKUNPRIVED)
   1802 	MKUPDATE=$(getmakevar MKUPDATE)
   1803 
   1804 	# Non-root should always use either the -U or -E flag.
   1805 	#
   1806 	if ! ${do_expertmode} && \
   1807 	    [ "$id_u" -ne 0 ] && \
   1808 	    [ "${MKUNPRIVED}" = "no" ] ; then
   1809 		bomb "-U or -E must be set for build as an unprivileged user"
   1810 	fi
   1811 
   1812 	if [ "${runcmd}" = "echo" ]; then
   1813 		TOOLCHAIN_MISSING=no
   1814 		EXTERNAL_TOOLCHAIN=""
   1815 	else
   1816 		TOOLCHAIN_MISSING=$(bomb_getmakevar TOOLCHAIN_MISSING)
   1817 		EXTERNAL_TOOLCHAIN=$(bomb_getmakevar EXTERNAL_TOOLCHAIN)
   1818 	fi
   1819 	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
   1820 	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
   1821 		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
   1822 		${runcmd} echo "	MACHINE:      ${MACHINE}"
   1823 		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
   1824 		${runcmd} echo ""
   1825 		${runcmd} echo "All builds for this platform should be done via a traditional make"
   1826 		${runcmd} echo "If you wish to use an external cross-toolchain, set"
   1827 		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
   1828 		${runcmd} echo "in either the environment or mk.conf and rerun"
   1829 		${runcmd} echo "	${progname} $*"
   1830 		exit 1
   1831 	fi
   1832 
   1833 	if [ "${MKOBJDIRS}" != "no" ]; then
   1834 		# Create the top-level object directory.
   1835 		#
   1836 		# "make obj NOSUBDIR=" can handle most cases, but it
   1837 		# can't handle the case where MAKEOBJDIRPREFIX is set
   1838 		# while the corresponding directory does not exist
   1839 		# (rules in <bsd.obj.mk> would abort the build).  We
   1840 		# therefore have to handle the MAKEOBJDIRPREFIX case
   1841 		# without invoking "make obj".  The MAKEOBJDIR case
   1842 		# could be handled either way, but we choose to handle
   1843 		# it similarly to MAKEOBJDIRPREFIX.
   1844 		#
   1845 		if [ -n "${TOP_obj}" ]; then
   1846 			# It must have been set by the "-M" or "-O"
   1847 			# command line options, so there's no need to
   1848 			# use getmakevar
   1849 			:
   1850 		elif [ -n "$MAKEOBJDIRPREFIX" ]; then
   1851 			TOP_obj="$(getmakevar MAKEOBJDIRPREFIX)${TOP}"
   1852 		elif [ -n "$MAKEOBJDIR" ]; then
   1853 			TOP_obj="$(getmakevar MAKEOBJDIR)"
   1854 		fi
   1855 		if [ -n "$TOP_obj" ]; then
   1856 			${runcmd} mkdir -p "${TOP_obj}" ||
   1857 			    bomb "Can't create top level object directory" \
   1858 					"${TOP_obj}"
   1859 		else
   1860 			${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1861 			    bomb "Can't create top level object directory" \
   1862 					"using make obj"
   1863 		fi
   1864 
   1865 		# make obj in tools to ensure that the objdir for "tools"
   1866 		# is available.
   1867 		#
   1868 		${runcmd} cd tools
   1869 		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1870 		    bomb "Failed to make obj in tools"
   1871 		${runcmd} cd "${TOP}"
   1872 	fi
   1873 
   1874 	# Find TOOLDIR, DESTDIR, and RELEASEDIR, according to getmakevar,
   1875 	# and bomb if they have changed from the values we had from the
   1876 	# command line or environment.
   1877 	#
   1878 	# This must be done after creating the top-level object directory.
   1879 	#
   1880 	for var in TOOLDIR DESTDIR RELEASEDIR
   1881 	do
   1882 		eval oldval=\"\$${var}\"
   1883 		newval="$(getmakevar $var)"
   1884 		if ! $do_expertmode; then
   1885 			: ${_SRC_TOP_OBJ_:=$(getmakevar _SRC_TOP_OBJ_)}
   1886 			case "$var" in
   1887 			DESTDIR)
   1888 				: ${newval:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
   1889 				makeenv="${makeenv} DESTDIR"
   1890 				;;
   1891 			RELEASEDIR)
   1892 				: ${newval:=${_SRC_TOP_OBJ_}/releasedir}
   1893 				makeenv="${makeenv} RELEASEDIR"
   1894 				;;
   1895 			esac
   1896 		fi
   1897 		if [ -n "$oldval" ] && [ "$oldval" != "$newval" ]; then
   1898 			bomb "Value of ${var} has changed" \
   1899 				"(was \"${oldval}\", now \"${newval}\")"
   1900 		fi
   1901 		eval ${var}=\"\${newval}\"
   1902 		eval export ${var}
   1903 		statusmsg2 "${var} path:" "${newval}"
   1904 	done
   1905 
   1906 	# RELEASEMACHINEDIR is just a subdir name, e.g. "i386".
   1907 	RELEASEMACHINEDIR=$(getmakevar RELEASEMACHINEDIR)
   1908 
   1909 	# Check validity of TOOLDIR and DESTDIR.
   1910 	#
   1911 	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
   1912 		bomb "TOOLDIR '${TOOLDIR}' invalid"
   1913 	fi
   1914 	removedirs="${TOOLDIR}"
   1915 
   1916 	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
   1917 		if ${do_distribution} || ${do_release} || \
   1918 		   [ "${uname_s}" != "NetBSD" ] || \
   1919 		   [ "${uname_m}" != "${MACHINE}" ]; then
   1920 			bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'"
   1921 		fi
   1922 		if ! ${do_expertmode}; then
   1923 			bomb "DESTDIR must != / for non -E (expert) builds"
   1924 		fi
   1925 		statusmsg "WARNING: Building to /, in expert mode."
   1926 		statusmsg "         This may cause your system to break!  Reasons include:"
   1927 		statusmsg "            - your kernel is not up to date"
   1928 		statusmsg "            - the libraries or toolchain have changed"
   1929 		statusmsg "         YOU HAVE BEEN WARNED!"
   1930 	else
   1931 		removedirs="${removedirs} ${DESTDIR}"
   1932 	fi
   1933 	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
   1934 		bomb "Must set RELEASEDIR with 'releasekernel=...'"
   1935 	fi
   1936 
   1937 	# If a previous build.sh run used -U (and therefore created a
   1938 	# METALOG file), then most subsequent build.sh runs must also
   1939 	# use -U.  If DESTDIR is about to be removed, then don't perform
   1940 	# this check.
   1941 	#
   1942 	case "${do_removedirs} ${removedirs} " in
   1943 	true*" ${DESTDIR} "*)
   1944 		# DESTDIR is about to be removed
   1945 		;;
   1946 	*)
   1947 		if [ -e "${DESTDIR}/METALOG" ] && \
   1948 		    [ "${MKUNPRIVED}" = "no" ] ; then
   1949 			if $do_expertmode; then
   1950 				warning "A previous build.sh run specified -U"
   1951 			else
   1952 				bomb "A previous build.sh run specified -U; you must specify it again now"
   1953 			fi
   1954 		fi
   1955 		;;
   1956 	esac
   1957 
   1958 	# live-image and install-image targets require binary sets
   1959 	# (actually DESTDIR/etc/mtree/set.* files) built with MKUNPRIVED.
   1960 	# If release operation is specified with live-image or install-image,
   1961 	# the release op should be performed with -U for later image ops.
   1962 	#
   1963 	if ${do_release} && ( ${do_live_image} || ${do_install_image} ) && \
   1964 	    [ "${MKUNPRIVED}" = "no" ] ; then
   1965 		bomb "-U must be specified on building release to create images later"
   1966 	fi
   1967 }
   1968 
   1969 
   1970 createmakewrapper()
   1971 {
   1972 	# Remove the target directories.
   1973 	#
   1974 	if ${do_removedirs}; then
   1975 		for f in ${removedirs}; do
   1976 			statusmsg "Removing ${f}"
   1977 			${runcmd} rm -r -f "${f}"
   1978 		done
   1979 	fi
   1980 
   1981 	# Recreate $TOOLDIR.
   1982 	#
   1983 	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
   1984 	    bomb "mkdir of '${TOOLDIR}/bin' failed"
   1985 
   1986 	# If we did not previously rebuild ${toolprefix}make, then
   1987 	# check whether $make is still valid and the same as the output
   1988 	# from print_tooldir_make.  If not, then rebuild make now.  A
   1989 	# possible reason for this being necessary is that the actual
   1990 	# value of TOOLDIR might be different from the value guessed
   1991 	# before the top level obj dir was created.
   1992 	#
   1993 	if ! ${done_rebuildmake} && \
   1994 	    ( [ ! -x "$make" ] || [ "$make" != "$(print_tooldir_make)" ] )
   1995 	then
   1996 		rebuildmake
   1997 	fi
   1998 
   1999 	# Install ${toolprefix}make if it was built.
   2000 	#
   2001 	if ${done_rebuildmake}; then
   2002 		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
   2003 		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
   2004 		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
   2005 		make="${TOOLDIR}/bin/${toolprefix}make"
   2006 		statusmsg "Created ${make}"
   2007 	fi
   2008 
   2009 	# Build a ${toolprefix}make wrapper script, usable by hand as
   2010 	# well as by build.sh.
   2011 	#
   2012 	if [ -z "${makewrapper}" ]; then
   2013 		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
   2014 		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
   2015 	fi
   2016 
   2017 	${runcmd} rm -f "${makewrapper}"
   2018 	if [ "${runcmd}" = "echo" ]; then
   2019 		echo 'cat <<EOF >'${makewrapper}
   2020 		makewrapout=
   2021 	else
   2022 		makewrapout=">>\${makewrapper}"
   2023 	fi
   2024 
   2025 	case "${KSH_VERSION:-${SH_VERSION}}" in
   2026 	*PD\ KSH*|*MIRBSD\ KSH*)
   2027 		set +o braceexpand
   2028 		;;
   2029 	esac
   2030 
   2031 	eval cat <<EOF ${makewrapout}
   2032 #! ${HOST_SH}
   2033 # Set proper variables to allow easy "make" building of a NetBSD subtree.
   2034 # Generated from:  \$NetBSD: build.sh,v 1.376 2024/04/20 12:25:46 rillig Exp $
   2035 # with these arguments: ${_args}
   2036 #
   2037 
   2038 EOF
   2039 	{
   2040 		sorted_vars="$(for var in ${makeenv}; do echo "${var}" ; done \
   2041 			| sort -u )"
   2042 		for var in ${sorted_vars}; do
   2043 			eval val=\"\${${var}}\"
   2044 			eval is_set=\"\${${var}+set}\"
   2045 			if [ -z "${is_set}" ]; then
   2046 				echo "unset ${var}"
   2047 			else
   2048 				qval="$(shell_quote "${val}")"
   2049 				echo "${var}=${qval}; export ${var}"
   2050 			fi
   2051 		done
   2052 
   2053 		cat <<EOF
   2054 
   2055 exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
   2056 EOF
   2057 	} | eval cat "${makewrapout}"
   2058 	[ "${runcmd}" = "echo" ] && echo EOF
   2059 	${runcmd} chmod +x "${makewrapper}"
   2060 	statusmsg2 "Updated makewrapper:" "${makewrapper}"
   2061 }
   2062 
   2063 make_in_dir()
   2064 {
   2065 	local dir="$1"
   2066 	local op="$2"
   2067 	${runcmd} cd "${dir}" ||
   2068 	    bomb "Failed to cd to \"${dir}\""
   2069 	${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2070 	    bomb "Failed to make ${op} in \"${dir}\""
   2071 	${runcmd} cd "${TOP}" ||
   2072 	    bomb "Failed to cd back to \"${TOP}\""
   2073 }
   2074 
   2075 buildtools()
   2076 {
   2077 	if [ "${MKOBJDIRS}" != "no" ]; then
   2078 		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
   2079 		    bomb "Failed to make obj-tools"
   2080 	fi
   2081 	if [ "${MKUPDATE}" = "no" ]; then
   2082 		make_in_dir tools cleandir
   2083 	fi
   2084 	make_in_dir tools build_install
   2085 	statusmsg "Tools built to ${TOOLDIR}"
   2086 }
   2087 
   2088 buildlibs()
   2089 {
   2090 	if [ "${MKOBJDIRS}" != "no" ]; then
   2091 		${runcmd} "${makewrapper}" ${parallel} obj ||
   2092 		    bomb "Failed to make obj"
   2093 	fi
   2094 	if [ "${MKUPDATE}" = "no" ]; then
   2095 		make_in_dir lib cleandir
   2096 	fi
   2097 	make_in_dir . do-distrib-dirs
   2098 	make_in_dir . includes
   2099 	make_in_dir . do-lib
   2100 	statusmsg "libs built"
   2101 }
   2102 
   2103 getkernelconf()
   2104 {
   2105 	kernelconf="$1"
   2106 	if [ "${MKOBJDIRS}" != "no" ]; then
   2107 		# The correct value of KERNOBJDIR might
   2108 		# depend on a prior "make obj" in
   2109 		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
   2110 		#
   2111 		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
   2112 		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
   2113 		make_in_dir "${KERNSRCDIR}/${KERNARCHDIR}/compile" obj
   2114 	fi
   2115 	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
   2116 	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
   2117 	case "${kernelconf}" in
   2118 	*/*)
   2119 		kernelconfpath="${kernelconf}"
   2120 		kernelconfname="${kernelconf##*/}"
   2121 		;;
   2122 	*)
   2123 		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
   2124 		kernelconfname="${kernelconf}"
   2125 		;;
   2126 	esac
   2127 	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
   2128 }
   2129 
   2130 diskimage()
   2131 {
   2132 	ARG="$(echo $1 | tr '[:lower:]' '[:upper:]')"
   2133 	[ -f "${DESTDIR}/etc/mtree/set.base" ] ||
   2134 	    bomb "The release binaries must be built first"
   2135 	kerneldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
   2136 	kernel="${kerneldir}/netbsd-${ARG}.gz"
   2137 	[ -f "${kernel}" ] ||
   2138 	    bomb "The kernel ${kernel} must be built first"
   2139 	make_in_dir "${NETBSDSRCDIR}/etc" "smp_${1}"
   2140 }
   2141 
   2142 buildkernel()
   2143 {
   2144 	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
   2145 		# Building tools every time we build a kernel is clearly
   2146 		# unnecessary.  We could try to figure out whether rebuilding
   2147 		# the tools is necessary this time, but it doesn't seem worth
   2148 		# the trouble.  Instead, we say it's the user's responsibility
   2149 		# to rebuild the tools if necessary.
   2150 		#
   2151 		statusmsg "Building kernel without building new tools"
   2152 		buildkernelwarned=true
   2153 	fi
   2154 	getkernelconf $1
   2155 	statusmsg2 "Building kernel:" "${kernelconf}"
   2156 	statusmsg2 "Build directory:" "${kernelbuildpath}"
   2157 	${runcmd} mkdir -p "${kernelbuildpath}" ||
   2158 	    bomb "Cannot mkdir: ${kernelbuildpath}"
   2159 	if [ "${MKUPDATE}" = "no" ]; then
   2160 		make_in_dir "${kernelbuildpath}" cleandir
   2161 	fi
   2162 	[ -x "${TOOLDIR}/bin/${toolprefix}config" ] \
   2163 	|| bomb "${TOOLDIR}/bin/${toolprefix}config does not exist. You need to \"$0 tools\" first"
   2164 	CONFIGOPTS=$(getmakevar CONFIGOPTS)
   2165 	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" ${CONFIGOPTS} \
   2166 		-b "${kernelbuildpath}" -s "${TOP}/sys" ${configopts} \
   2167 		"${kernelconfpath}" ||
   2168 	    bomb "${toolprefix}config failed for ${kernelconf}"
   2169 	make_in_dir "${kernelbuildpath}" depend
   2170 	make_in_dir "${kernelbuildpath}" all
   2171 
   2172 	if [ "${runcmd}" != "echo" ]; then
   2173 		statusmsg "Kernels built from ${kernelconf}:"
   2174 		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   2175 		for kern in ${kernlist:-netbsd}; do
   2176 			[ -f "${kernelbuildpath}/${kern}" ] && \
   2177 			    echo "  ${kernelbuildpath}/${kern}"
   2178 		done | tee -a "${results}"
   2179 	fi
   2180 }
   2181 
   2182 releasekernel()
   2183 {
   2184 	getkernelconf $1
   2185 	kernelreldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
   2186 	${runcmd} mkdir -p "${kernelreldir}"
   2187 	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   2188 	for kern in ${kernlist:-netbsd}; do
   2189 		builtkern="${kernelbuildpath}/${kern}"
   2190 		[ -f "${builtkern}" ] || continue
   2191 		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
   2192 		statusmsg2 "Kernel copy:" "${releasekern}"
   2193 		if [ "${runcmd}" = "echo" ]; then
   2194 			echo "gzip -c -9 < ${builtkern} > ${releasekern}"
   2195 		else
   2196 			gzip -c -9 < "${builtkern}" > "${releasekern}"
   2197 		fi
   2198 	done
   2199 }
   2200 
   2201 buildkernels()
   2202 {
   2203 	allkernels=$( runcmd= make_in_dir etc '-V ${ALL_KERNELS}' )
   2204 	for k in $allkernels; do
   2205 		buildkernel "${k}"
   2206 	done
   2207 }
   2208 
   2209 buildmodules()
   2210 {
   2211 	setmakeenv MKBINUTILS no
   2212 	if ! ${do_tools} && ! ${buildmoduleswarned:-false}; then
   2213 		# Building tools every time we build modules is clearly
   2214 		# unnecessary as well as a kernel.
   2215 		#
   2216 		statusmsg "Building modules without building new tools"
   2217 		buildmoduleswarned=true
   2218 	fi
   2219 
   2220 	statusmsg "Building kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   2221 	if [ "${MKOBJDIRS}" != "no" ]; then
   2222 		make_in_dir sys/modules obj
   2223 	fi
   2224 	if [ "${MKUPDATE}" = "no" ]; then
   2225 		make_in_dir sys/modules cleandir
   2226 	fi
   2227 	make_in_dir sys/modules dependall
   2228 	make_in_dir sys/modules install
   2229 
   2230 	statusmsg "Successful build of kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   2231 }
   2232 
   2233 builddtb()
   2234 {
   2235 	statusmsg "Building devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
   2236 	if [ "${MKOBJDIRS}" != "no" ]; then
   2237 		make_in_dir sys/dtb obj
   2238 	fi
   2239 	if [ "${MKUPDATE}" = "no" ]; then
   2240 		make_in_dir sys/dtb cleandir
   2241 	fi
   2242 	make_in_dir sys/dtb dependall
   2243 	make_in_dir sys/dtb install
   2244 
   2245 	statusmsg "Successful build of devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
   2246 }
   2247 
   2248 installmodules()
   2249 {
   2250 	dir="$1"
   2251 	${runcmd} "${makewrapper}" INSTALLMODULESDIR="${dir}" installmodules ||
   2252 	    bomb "Failed to make installmodules to ${dir}"
   2253 	statusmsg "Successful installmodules to ${dir}"
   2254 }
   2255 
   2256 installworld()
   2257 {
   2258 	dir="$1"
   2259 	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
   2260 	    bomb "Failed to make installworld to ${dir}"
   2261 	statusmsg "Successful installworld to ${dir}"
   2262 }
   2263 
   2264 # Run rump build&link tests.
   2265 #
   2266 # To make this feasible for running without having to install includes and
   2267 # libraries into destdir (i.e. quick), we only run ld.  This is possible
   2268 # since the rump kernel is a closed namespace apart from calls to rumpuser.
   2269 # Therefore, if ld complains only about rumpuser symbols, rump kernel
   2270 # linking was successful.
   2271 #
   2272 # We test that rump links with a number of component configurations.
   2273 # These attempt to mimic what is encountered in the full build.
   2274 # See list below.  The list should probably be either autogenerated
   2275 # or managed elsewhere; keep it here until a better idea arises.
   2276 #
   2277 # Above all, note that THIS IS NOT A SUBSTITUTE FOR A FULL BUILD.
   2278 #
   2279 
   2280 # XXX: uwe: kern/56599 - while riastradh addressed librump problems,
   2281 # there are still unwanted dependencies:
   2282 #    net -> net_net
   2283 #    vfs -> fifo
   2284 
   2285 # -lrumpvfs -> $LRUMPVFS for now
   2286 LRUMPVFS="-lrumpvfs -lrumpvfs_nofifofs"
   2287 
   2288 RUMP_LIBSETS="
   2289 	-lrump,
   2290         -lrumpvfs
   2291             --no-whole-archive -lrumpvfs_nofifofs -lrump,
   2292 	-lrumpkern_tty
   2293             --no-whole-archive $LRUMPVFS -lrump,
   2294 	-lrumpfs_tmpfs
   2295             --no-whole-archive $LRUMPVFS -lrump,
   2296 	-lrumpfs_ffs -lrumpfs_msdos
   2297             --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrump,
   2298 	-lrumpnet_virtif -lrumpnet_netinet -lrumpnet_net -lrumpnet
   2299 	    --no-whole-archive -lrump,
   2300 	-lrumpfs_nfs
   2301 	    --no-whole-archive $LRUMPVFS
   2302 	    -lrumpnet_sockin -lrumpnet_virtif -lrumpnet_netinet
   2303             --start-group -lrumpnet_net -lrumpnet --end-group -lrump,
   2304 	-lrumpdev_cgd -lrumpdev_raidframe -lrumpdev_rnd -lrumpdev_dm
   2305             --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrumpkern_crypto -lrump
   2306 "
   2307 
   2308 dorump()
   2309 {
   2310 	local doclean=""
   2311 	local doobjs=""
   2312 
   2313 	export RUMPKERN_ONLY=1
   2314 	# create obj and distrib dirs
   2315 	if [ "${MKOBJDIRS}" != "no" ]; then
   2316 		make_in_dir "${NETBSDSRCDIR}/etc/mtree" obj
   2317 		make_in_dir "${NETBSDSRCDIR}/sys/rump" obj
   2318 	fi
   2319 	${runcmd} "${makewrapper}" ${parallel} do-distrib-dirs \
   2320 	    || bomb "Could not create distrib-dirs"
   2321 
   2322 	[ "${MKUPDATE}" = "no" ] && doclean="cleandir"
   2323 	targlist="${doclean} ${doobjs} dependall install"
   2324 	# optimize: for test we build only static libs (3x test speedup)
   2325 	if [ "${1}" = "rumptest" ] ; then
   2326 		setmakeenv NOPIC 1
   2327 		setmakeenv NOPROFILE 1
   2328 	fi
   2329 	for cmd in ${targlist} ; do
   2330 		make_in_dir "${NETBSDSRCDIR}/sys/rump" ${cmd}
   2331 	done
   2332 
   2333 	# if we just wanted to build & install rump, we're done
   2334 	[ "${1}" != "rumptest" ] && return
   2335 
   2336 	${runcmd} cd "${NETBSDSRCDIR}/sys/rump/librump/rumpkern" \
   2337 	    || bomb "cd to rumpkern failed"
   2338 	md_quirks=`${runcmd} "${makewrapper}" -V '${_SYMQUIRK}'`
   2339 	# one little, two little, three little backslashes ...
   2340 	md_quirks="$(echo ${md_quirks} | sed 's,\\,\\\\,g'";s/'//g" )"
   2341 	${runcmd} cd "${TOP}" || bomb "cd to ${TOP} failed"
   2342 	tool_ld=`${runcmd} "${makewrapper}" -V '${LD}'`
   2343 
   2344 	local oIFS="${IFS}"
   2345 	IFS=","
   2346 	for set in ${RUMP_LIBSETS} ; do
   2347 		IFS="${oIFS}"
   2348 		${runcmd} ${tool_ld} -nostdlib -L${DESTDIR}/usr/lib	\
   2349 		    -static --whole-archive ${set} --no-whole-archive -lpthread -lc 2>&1 -o /tmp/rumptest.$$ | \
   2350 		      awk -v quirks="${md_quirks}" '
   2351 			/undefined reference/ &&
   2352 			    !/more undefined references.*follow/{
   2353 				if (match($NF,
   2354 				    "`(rumpuser_|rumpcomp_|__" quirks ")") == 0)
   2355 					fails[NR] = $0
   2356 			}
   2357 			/cannot find -l/{fails[NR] = $0}
   2358 			/cannot open output file/{fails[NR] = $0}
   2359 			END{
   2360 				for (x in fails)
   2361 					print fails[x]
   2362 				exit x!=0
   2363 			}'
   2364 		[ $? -ne 0 ] && bomb "Testlink of rump failed: ${set}"
   2365 	done
   2366 	statusmsg "Rump build&link tests successful"
   2367 }
   2368 
   2369 repro_date() {
   2370 	# try the bsd date fail back the linux one
   2371 	date -u -r "$1" 2> /dev/null || date -u -d "@$1"
   2372 }
   2373 
   2374 setup_mkrepro()
   2375 {
   2376 	local quiet="$1"
   2377 
   2378 	if [ ${MKREPRO-no} != "yes" ]; then
   2379 		return
   2380 	fi
   2381 	if [ ${MKREPRO_TIMESTAMP-0} -ne 0 ]; then
   2382 		return;
   2383 	fi
   2384 
   2385 	local dirs=${NETBSDSRCDIR-/usr/src}/
   2386 	if [ ${MKX11-no} = "yes" ]; then
   2387 		dirs="$dirs ${X11SRCDIR-/usr/xsrc}/"
   2388 	fi
   2389 
   2390 	MKREPRO_TIMESTAMP=0
   2391 	local d
   2392 	local t
   2393 	local vcs
   2394 	for d in ${dirs}; do
   2395 		if [ -d "${d}CVS" ]; then
   2396 			local cvslatest=$(print_tooldir_program cvslatest)
   2397 			if [ ! -x "${cvslatest}" ]; then
   2398 				buildtools
   2399 			fi
   2400 
   2401 			local cvslatestflags=
   2402 			if ${do_expertmode}; then
   2403 				cvslatestflags=-i
   2404 			fi
   2405 
   2406 			t=$("${cvslatest}" ${cvslatestflags} "${d}")
   2407 			vcs=cvs
   2408 		elif [ -d "${d}.git" -o -f "${d}.git" ]; then
   2409 			t=$(cd "${d}" && git log -1 --format=%ct)
   2410 			vcs=git
   2411 		elif [ -d "${d}.hg" ]; then
   2412 			t=$(hg --repo "$d" log -r . --template '{date.unixtime}\n')
   2413 			vcs=hg
   2414 		elif [ -f "${d}.hg_archival.txt" ]; then
   2415 			local stat=$(print_tooldir_program stat)
   2416 			if [ ! -x "${stat}" ]; then
   2417 				buildtools
   2418 			fi
   2419 
   2420 			t=$("${stat}" -t '%s' -f '%m' "${d}.hg_archival.txt")
   2421 			vcs=hg
   2422 		else
   2423 			bomb "Cannot determine VCS for '$d'"
   2424 		fi
   2425 
   2426 		if [ -z "$t" ]; then
   2427 			bomb "Failed to get timestamp for vcs=$vcs in '$d'"
   2428 		fi
   2429 
   2430 		#echo "latest $d $vcs $t"
   2431 		if [ "$t" -gt "$MKREPRO_TIMESTAMP" ]; then
   2432 			MKREPRO_TIMESTAMP="$t"
   2433 		fi
   2434 	done
   2435 
   2436 	[ "${MKREPRO_TIMESTAMP}" != "0" ] || bomb "Failed to compute timestamp"
   2437 	if [ -z "${quiet}" ]; then
   2438 		statusmsg2 "MKREPRO_TIMESTAMP" \
   2439 			"$(repro_date "${MKREPRO_TIMESTAMP}")"
   2440 	fi
   2441 	export MKREPRO MKREPRO_TIMESTAMP
   2442 }
   2443 
   2444 main()
   2445 {
   2446 	initdefaults
   2447 	_args=$@
   2448 	parseoptions "$@"
   2449 
   2450 	sanitycheck
   2451 
   2452 	build_start=$(date)
   2453 	statusmsg2 "${progname} command:" "$0 $*"
   2454 	statusmsg2 "${progname} started:" "${build_start}"
   2455 	statusmsg2 "NetBSD version:"   "${DISTRIBVER}"
   2456 	statusmsg2 "MACHINE:"          "${MACHINE}"
   2457 	statusmsg2 "MACHINE_ARCH:"     "${MACHINE_ARCH}"
   2458 	statusmsg2 "Build platform:"   "${uname_s} ${uname_r} ${uname_m}"
   2459 	statusmsg2 "HOST_SH:"          "${HOST_SH}"
   2460 	if [ -n "${BUILDID}" ]; then
   2461 		statusmsg2 "BUILDID:"  "${BUILDID}"
   2462 	fi
   2463 	if [ -n "${BUILDINFO}" ]; then
   2464 		printf "%b\n" "${BUILDINFO}" | \
   2465 		while read -r line ; do
   2466 			[ -s "${line}" ] && continue
   2467 			statusmsg2 "BUILDINFO:"  "${line}"
   2468 		done
   2469 	fi
   2470 
   2471 	if [ -n "${MAKECONF+1}" ] && [ -z "${MAKECONF}" ]; then
   2472 		bomb "MAKECONF must not be empty"
   2473 	fi
   2474 
   2475 	rebuildmake
   2476 	validatemakeparams
   2477 	createmakewrapper
   2478 	setup_mkrepro
   2479 
   2480 	# Perform the operations.
   2481 	#
   2482 	for op in ${operations}; do
   2483 		case "${op}" in
   2484 
   2485 		makewrapper)
   2486 			# no-op
   2487 			;;
   2488 
   2489 		tools)
   2490 			buildtools
   2491 			;;
   2492 		libs)
   2493 			buildlibs
   2494 			;;
   2495 
   2496 		sets)
   2497 			statusmsg "Building sets from pre-populated ${DESTDIR}"
   2498 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2499 			    bomb "Failed to make ${op}"
   2500 			setdir=${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
   2501 			statusmsg "Built sets to ${setdir}"
   2502 			;;
   2503 
   2504 		build|distribution|release)
   2505 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2506 			    bomb "Failed to make ${op}"
   2507 			statusmsg "Successful make ${op}"
   2508 			;;
   2509 
   2510 		cleandir|obj|sourcesets|syspkgs|params|show-params)
   2511 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2512 			    bomb "Failed to make ${op}"
   2513 			statusmsg "Successful make ${op}"
   2514 			;;
   2515 
   2516 		iso-image|iso-image-source)
   2517 			${runcmd} "${makewrapper}" ${parallel} \
   2518 			    CDEXTRA="$CDEXTRA" ${op} ||
   2519 			    bomb "Failed to make ${op}"
   2520 			statusmsg "Successful make ${op}"
   2521 			;;
   2522 
   2523 		live-image|install-image)
   2524 			# install-image and live-image require mtree spec files
   2525 			# built with MKUNPRIVED.  Assume MKUNPRIVED build has been
   2526 			# performed if METALOG file is created in DESTDIR.
   2527 			if [ ! -e "${DESTDIR}/METALOG" ] ; then
   2528 				bomb "The release binaries must have been built with -U to create images"
   2529 			fi
   2530 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   2531 			    bomb "Failed to make ${op}"
   2532 			statusmsg "Successful make ${op}"
   2533 			;;
   2534 		kernel=*)
   2535 			arg=${op#*=}
   2536 			buildkernel "${arg}"
   2537 			;;
   2538 		kernel.gdb=*)
   2539 			arg=${op#*=}
   2540 			configopts="-D DEBUG=-g"
   2541 			buildkernel "${arg}"
   2542 			;;
   2543 		releasekernel=*)
   2544 			arg=${op#*=}
   2545 			releasekernel "${arg}"
   2546 			;;
   2547 
   2548 		kernels)
   2549 			buildkernels
   2550 			;;
   2551 
   2552 		disk-image=*)
   2553 			arg=${op#*=}
   2554 			diskimage "${arg}"
   2555 			;;
   2556 
   2557 		dtb)
   2558 			builddtb
   2559 			;;
   2560 
   2561 		modules)
   2562 			buildmodules
   2563 			;;
   2564 
   2565 		installmodules=*)
   2566 			arg=${op#*=}
   2567 			if [ "${arg}" = "/" ] && \
   2568 			    (	[ "${uname_s}" != "NetBSD" ] || \
   2569 				[ "${uname_m}" != "${MACHINE}" ] ); then
   2570 				bomb "'${op}' must != / for cross builds"
   2571 			fi
   2572 			installmodules "${arg}"
   2573 			;;
   2574 
   2575 		install=*)
   2576 			arg=${op#*=}
   2577 			if [ "${arg}" = "/" ] && \
   2578 			    (	[ "${uname_s}" != "NetBSD" ] || \
   2579 				[ "${uname_m}" != "${MACHINE}" ] ); then
   2580 				bomb "'${op}' must != / for cross builds"
   2581 			fi
   2582 			installworld "${arg}"
   2583 			;;
   2584 
   2585 		rump)
   2586 			make_in_dir . do-distrib-dirs
   2587 			make_in_dir . includes
   2588 			make_in_dir lib/csu dependall
   2589 			make_in_dir lib/csu install
   2590 			make_in_dir external/gpl3/gcc/lib/libgcc dependall
   2591 			make_in_dir external/gpl3/gcc/lib/libgcc install
   2592 			dorump "${op}"
   2593 			;;
   2594 
   2595 		rumptest)
   2596 			dorump "${op}"
   2597 			;;
   2598 
   2599 		*)
   2600 			bomb "Unknown OPERATION '${op}'"
   2601 			;;
   2602 
   2603 		esac
   2604 	done
   2605 
   2606 	statusmsg2 "${progname} ended:" "$(date)"
   2607 	if [ -s "${results}" ]; then
   2608 		echo "===> Summary of results:"
   2609 		sed -e 's/^===>//;s/^/	/' "${results}"
   2610 		echo "===> ."
   2611 	fi
   2612 }
   2613 
   2614 main "$@"
   2615