Home | History | Annotate | Line # | Download | only in src
build.sh revision 1.250
      1 #! /usr/bin/env sh
      2 #	$NetBSD: build.sh,v 1.250 2011/09/14 17:35:44 apb Exp $
      3 #
      4 # Copyright (c) 2001-2011 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 print 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 wheher 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 bash dash
    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 trap "exit 1" 1 2 3 15
    267 
    268 bomb()
    269 {
    270 	cat >&2 <<ERRORMESSAGE
    271 
    272 ERROR: $@
    273 *** BUILD ABORTED ***
    274 ERRORMESSAGE
    275 	kill ${toppid}		# in case we were invoked from a subshell
    276 	exit 1
    277 }
    278 
    279 
    280 statusmsg()
    281 {
    282 	${runcmd} echo "===> $@" | tee -a "${results}"
    283 }
    284 
    285 statusmsg2()
    286 {
    287 	local msg
    288 
    289 	msg="${1}"
    290 	shift
    291 	case "${msg}" in
    292 	????????????????*)	;;
    293 	??????????*)		msg="${msg}      ";;
    294 	?????*)			msg="${msg}           ";;
    295 	*)			msg="${msg}                ";;
    296 	esac
    297 	case "${msg}" in
    298 	?????????????????????*)	;;
    299 	????????????????????)	msg="${msg} ";;
    300 	???????????????????)	msg="${msg}  ";;
    301 	??????????????????)	msg="${msg}   ";;
    302 	?????????????????)	msg="${msg}    ";;
    303 	????????????????)	msg="${msg}     ";;
    304 	esac
    305 	statusmsg "${msg}$*"
    306 }
    307 
    308 warning()
    309 {
    310 	statusmsg "Warning: $@"
    311 }
    312 
    313 # Find a program in the PATH, and print the result.  If not found,
    314 # print a default.  If $2 is defined (even if it is an empty string),
    315 # then that is the default; otherwise, $1 is used as the default.
    316 find_in_PATH()
    317 {
    318 	local prog="$1"
    319 	local result="${2-"$1"}"
    320 	local oldIFS="${IFS}"
    321 	local dir
    322 	IFS=":"
    323 	for dir in ${PATH}; do
    324 		if [ -x "${dir}/${prog}" ]; then
    325 			result="${dir}/${prog}"
    326 			break
    327 		fi
    328 	done
    329 	IFS="${oldIFS}"
    330 	echo "${result}"
    331 }
    332 
    333 # Try to find a working POSIX shell, and set HOST_SH to refer to it.
    334 # Assumes that uname_s, uname_m, and PWD have been set.
    335 set_HOST_SH()
    336 {
    337 	# Even if ${HOST_SH} is already defined, we still do the
    338 	# sanity checks at the end.
    339 
    340 	# Solaris has /usr/xpg4/bin/sh.
    341 	#
    342 	[ -z "${HOST_SH}" ] && [ x"${uname_s}" = x"SunOS" ] && \
    343 		[ -x /usr/xpg4/bin/sh ] && HOST_SH="/usr/xpg4/bin/sh"
    344 
    345 	# Try to get the name of the shell that's running this script,
    346 	# by parsing the output from "ps".  We assume that, if the host
    347 	# system's ps command supports -o comm at all, it will do so
    348 	# in the usual way: a one-line header followed by a one-line
    349 	# result, possibly including trailing white space.  And if the
    350 	# host system's ps command doesn't support -o comm, we assume
    351 	# that we'll get an error message on stderr and nothing on
    352 	# stdout.  (We don't try to use ps -o 'comm=' to suppress the
    353 	# header line, because that is less widely supported.)
    354 	#
    355 	# If we get the wrong result here, the user can override it by
    356 	# specifying HOST_SH in the environment.
    357 	#
    358 	[ -z "${HOST_SH}" ] && HOST_SH="$(
    359 		(ps -p $$ -o comm | sed -ne "2s/[ ${tab}]*\$//p") 2>/dev/null )"
    360 
    361 	# If nothing above worked, use "sh".  We will later find the
    362 	# first directory in the PATH that has a "sh" program.
    363 	#
    364 	[ -z "${HOST_SH}" ] && HOST_SH="sh"
    365 
    366 	# If the result so far is not an absolute path, try to prepend
    367 	# PWD or search the PATH.
    368 	#
    369 	case "${HOST_SH}" in
    370 	/*)	:
    371 		;;
    372 	*/*)	HOST_SH="${PWD}/${HOST_SH}"
    373 		;;
    374 	*)	HOST_SH="$(find_in_PATH "${HOST_SH}")"
    375 		;;
    376 	esac
    377 
    378 	# If we don't have an absolute path by now, bomb.
    379 	#
    380 	case "${HOST_SH}" in
    381 	/*)	:
    382 		;;
    383 	*)	bomb "HOST_SH=\"${HOST_SH}\" is not an absolute path."
    384 		;;
    385 	esac
    386 
    387 	# If HOST_SH is not executable, bomb.
    388 	#
    389 	[ -x "${HOST_SH}" ] ||
    390 	    bomb "HOST_SH=\"${HOST_SH}\" is not executable."
    391 
    392 	# If HOST_SH fails tests, bomb.
    393 	# ("$0" may be a path that is no longer valid, because we have
    394 	# performed "cd $(dirname $0)", so don't use $0 here.)
    395 	#
    396 	"${HOST_SH}" build.sh --shelltest ||
    397 	    bomb "HOST_SH=\"${HOST_SH}\" failed functionality tests."
    398 }
    399 
    400 # initdefaults --
    401 # Set defaults before parsing command line options.
    402 #
    403 initdefaults()
    404 {
    405 	makeenv=
    406 	makewrapper=
    407 	makewrappermachine=
    408 	runcmd=
    409 	operations=
    410 	removedirs=
    411 
    412 	[ -d usr.bin/make ] || cd "$(dirname $0)"
    413 	[ -d usr.bin/make ] ||
    414 	    bomb "build.sh must be run from the top source level"
    415 	[ -f share/mk/bsd.own.mk ] ||
    416 	    bomb "src/share/mk is missing; please re-fetch the source tree"
    417 
    418 	# Set various environment variables to known defaults,
    419 	# to minimize (cross-)build problems observed "in the field".
    420 	#
    421 	# LC_ALL=C must be set before we try to parse the output from
    422 	# any command.  Other variables are set (or unset) here, before
    423 	# we parse command line arguments.
    424 	#
    425 	# These variables can be overridden via "-V var=value" if
    426 	# you know what you are doing.
    427 	#
    428 	unsetmakeenv INFODIR
    429 	unsetmakeenv LESSCHARSET
    430 	unsetmakeenv MAKEFLAGS
    431 	setmakeenv LC_ALL C
    432 
    433 	# Find information about the build platform.  This should be
    434 	# kept in sync with _HOST_OSNAME, _HOST_OSREL, and _HOST_ARCH
    435 	# variables in share/mk/bsd.sys.mk.
    436 	#
    437 	# Note that "uname -p" is not part of POSIX, but we want uname_p
    438 	# to be set to the host MACHINE_ARCH, if possible.  On systems
    439 	# where "uname -p" fails, prints "unknown", or prints a string
    440 	# that does not look like an identifier, fall back to using the
    441 	# output from "uname -m" instead.
    442 	#
    443 	uname_s=$(uname -s 2>/dev/null)
    444 	uname_r=$(uname -r 2>/dev/null)
    445 	uname_m=$(uname -m 2>/dev/null)
    446 	uname_p=$(uname -p 2>/dev/null || echo "unknown")
    447 	case "${uname_p}" in
    448 	''|unknown|*[^-_A-Za-z0-9]*) uname_p="${uname_m}" ;;
    449 	esac
    450 
    451 	id_u=$(id -u 2>/dev/null || /usr/xpg4/bin/id -u 2>/dev/null)
    452 
    453 	# If $PWD is a valid name of the current directory, POSIX mandates
    454 	# that pwd return it by default which causes problems in the
    455 	# presence of symlinks.  Unsetting PWD is simpler than changing
    456 	# every occurrence of pwd to use -P.
    457 	#
    458 	# XXX Except that doesn't work on Solaris. Or many Linuces.
    459 	#
    460 	unset PWD
    461 	TOP=$(/bin/pwd -P 2>/dev/null || /bin/pwd 2>/dev/null)
    462 
    463 	# The user can set HOST_SH in the environment, or we try to
    464 	# guess an appropriate value.  Then we set several other
    465 	# variables from HOST_SH.
    466 	#
    467 	set_HOST_SH
    468 	setmakeenv HOST_SH "${HOST_SH}"
    469 	setmakeenv BSHELL "${HOST_SH}"
    470 	setmakeenv CONFIG_SHELL "${HOST_SH}"
    471 
    472 	# Set defaults.
    473 	#
    474 	toolprefix=nb
    475 
    476 	# Some systems have a small ARG_MAX.  -X prevents make(1) from
    477 	# exporting variables in the environment redundantly.
    478 	#
    479 	case "${uname_s}" in
    480 	Darwin | FreeBSD | CYGWIN*)
    481 		MAKEFLAGS="-X ${MAKEFLAGS}"
    482 		;;
    483 	esac
    484 
    485 	# do_{operation}=true if given operation is requested.
    486 	#
    487 	do_expertmode=false
    488 	do_rebuildmake=false
    489 	do_removedirs=false
    490 	do_tools=false
    491 	do_cleandir=false
    492 	do_obj=false
    493 	do_build=false
    494 	do_distribution=false
    495 	do_release=false
    496 	do_kernel=false
    497 	do_releasekernel=false
    498 	do_modules=false
    499 	do_installmodules=false
    500 	do_install=false
    501 	do_sets=false
    502 	do_sourcesets=false
    503 	do_syspkgs=false
    504 	do_iso_image=false
    505 	do_iso_image_source=false
    506 	do_params=false
    507 	do_rump=false
    508 
    509 	# done_{operation}=true if given operation has been done.
    510 	#
    511 	done_rebuildmake=false
    512 
    513 	# Create scratch directory
    514 	#
    515 	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
    516 	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
    517 	trap "cd /; rm -r -f \"${tmpdir}\"" 0
    518 	results="${tmpdir}/build.sh.results"
    519 
    520 	# Set source directories
    521 	#
    522 	setmakeenv NETBSDSRCDIR "${TOP}"
    523 
    524 	# Make sure KERNOBJDIR is an absolute path if defined
    525 	#
    526 	case "${KERNOBJDIR}" in
    527 	''|/*)	;;
    528 	*)	KERNOBJDIR="${TOP}/${KERNOBJDIR}"
    529 		setmakeenv KERNOBJDIR "${KERNOBJDIR}"
    530 		;;
    531 	esac
    532 
    533 	# Find the version of NetBSD
    534 	#
    535 	DISTRIBVER="$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh)"
    536 
    537 	# Set the BUILDSEED to NetBSD-"N"
    538 	#
    539 	setmakeenv BUILDSEED "NetBSD-$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh -m)"
    540 
    541 	# Set MKARZERO to "yes"
    542 	#
    543 	setmakeenv MKARZERO "yes"
    544 
    545 }
    546 
    547 getarch()
    548 {
    549 	# Translate some MACHINE name aliases (known only to build.sh)
    550 	# into proper MACHINE and MACHINE_ARCH names.  Save the alias
    551 	# name in makewrappermachine.
    552 	#
    553 	case "${MACHINE}" in
    554 
    555 	evbarm-e[bl])
    556 		makewrappermachine=${MACHINE}
    557 		# MACHINE_ARCH is "arm" or "armeb", not "armel"
    558 		MACHINE_ARCH=arm${MACHINE##*-}
    559 		MACHINE_ARCH=${MACHINE_ARCH%el}
    560 		MACHINE=${MACHINE%-e[bl]}
    561 		;;
    562 
    563 	evbmips-e[bl]|sbmips-e[bl])
    564 		makewrappermachine=${MACHINE}
    565 		MACHINE_ARCH=mips${MACHINE##*-}
    566 		MACHINE=${MACHINE%-e[bl]}
    567 		;;
    568 
    569 	evbmips64-e[bl]|sbmips64-e[bl])
    570 		makewrappermachine=${MACHINE}
    571 		MACHINE_ARCH=mips64${MACHINE##*-}
    572 		MACHINE=${MACHINE%64-e[bl]}
    573 		;;
    574 
    575 	evbsh3-e[bl])
    576 		makewrappermachine=${MACHINE}
    577 		MACHINE_ARCH=sh3${MACHINE##*-}
    578 		MACHINE=${MACHINE%-e[bl]}
    579 		;;
    580 
    581 	esac
    582 
    583 	# Translate a MACHINE into a default MACHINE_ARCH.
    584 	#
    585 	case "${MACHINE}" in
    586 
    587 	acorn26|acorn32|cats|hpcarm|iyonix|netwinder|shark|zaurus)
    588 		MACHINE_ARCH=arm
    589 		;;
    590 
    591 	evbarm)		# unspecified MACHINE_ARCH gets LE
    592 		MACHINE_ARCH=${MACHINE_ARCH:=arm}
    593 		;;
    594 
    595 	hp700)
    596 		MACHINE_ARCH=hppa
    597 		;;
    598 
    599 	sun2)
    600 		MACHINE_ARCH=m68000
    601 		;;
    602 
    603 	amiga|atari|cesfic|hp300|luna68k|mac68k|mvme68k|news68k|next68k|sun3|x68k)
    604 		MACHINE_ARCH=m68k
    605 		;;
    606 
    607 	evbmips|sbmips)		# no default MACHINE_ARCH
    608 		;;
    609 
    610 	sgimips64)
    611 		makewrappermachine=${MACHINE}
    612 		MACHINE=${MACHINE%64}
    613 		MACHINE_ARCH=mips64eb
    614 		;;
    615 
    616 	ews4800mips|mipsco|newsmips|sgimips|emips)
    617 		MACHINE_ARCH=mipseb
    618 		;;
    619 
    620 	algor64|arc64|cobalt64|pmax64)
    621 		makewrappermachine=${MACHINE}
    622 		MACHINE=${MACHINE%64}
    623 		MACHINE_ARCH=mips64el
    624 		;;
    625 
    626 	algor|arc|cobalt|hpcmips|pmax)
    627 		MACHINE_ARCH=mipsel
    628 		;;
    629 
    630 	evbppc64|macppc64|ofppc64)
    631 		makewrappermachine=${MACHINE}
    632 		MACHINE=${MACHINE%64}
    633 		MACHINE_ARCH=powerpc64
    634 		;;
    635 
    636 	amigappc|bebox|evbppc|ibmnws|macppc|mvmeppc|ofppc|prep|rs6000|sandpoint)
    637 		MACHINE_ARCH=powerpc
    638 		;;
    639 
    640 	evbsh3)			# no default MACHINE_ARCH
    641 		;;
    642 
    643 	mmeye)
    644 		MACHINE_ARCH=sh3eb
    645 		;;
    646 
    647 	dreamcast|hpcsh|landisk)
    648 		MACHINE_ARCH=sh3el
    649 		;;
    650 
    651 	amd64)
    652 		MACHINE_ARCH=x86_64
    653 		;;
    654 
    655 	alpha|i386|sparc|sparc64|vax|ia64)
    656 		MACHINE_ARCH=${MACHINE}
    657 		;;
    658 
    659 	*)
    660 		bomb "Unknown target MACHINE: ${MACHINE}"
    661 		;;
    662 
    663 	esac
    664 }
    665 
    666 validatearch()
    667 {
    668 	# Ensure that the MACHINE_ARCH exists (and is supported by build.sh).
    669 	#
    670 	case "${MACHINE_ARCH}" in
    671 
    672 	alpha|arm|armeb|hppa|i386|m68000|m68k|mipse[bl]|mips64e[bl]|powerpc|powerpc64|sh3e[bl]|sparc|sparc64|vax|x86_64|ia64)
    673 		;;
    674 
    675 	"")
    676 		bomb "No MACHINE_ARCH provided"
    677 		;;
    678 
    679 	*)
    680 		bomb "Unknown target MACHINE_ARCH: ${MACHINE_ARCH}"
    681 		;;
    682 
    683 	esac
    684 
    685 	# Determine valid MACHINE_ARCHs for MACHINE
    686 	#
    687 	case "${MACHINE}" in
    688 
    689 	evbarm)
    690 		arches="arm armeb"
    691 		;;
    692 
    693 	algor|arc|cobalt|pmax)
    694 		arches="mipsel mips64el"
    695 		;;
    696 
    697 	evbmips|sbmips)
    698 		arches="mipseb mipsel mips64eb mips64el"
    699 		;;
    700 
    701 	sgimips)
    702 		arches="mipseb mips64eb"
    703 		;;
    704 
    705 	evbsh3)
    706 		arches="sh3eb sh3el"
    707 		;;
    708 
    709 	macppc|evbppc|ofppc)
    710 		arches="powerpc powerpc64"
    711 		;;
    712 	*)
    713 		oma="${MACHINE_ARCH}"
    714 		getarch
    715 		arches="${MACHINE_ARCH}"
    716 		MACHINE_ARCH="${oma}"
    717 		;;
    718 
    719 	esac
    720 
    721 	# Ensure that MACHINE_ARCH supports MACHINE
    722 	#
    723 	archok=false
    724 	for a in ${arches}; do
    725 		if [ "${a}" = "${MACHINE_ARCH}" ]; then
    726 			archok=true
    727 			break
    728 		fi
    729 	done
    730 	${archok} ||
    731 	    bomb "MACHINE_ARCH '${MACHINE_ARCH}' does not support MACHINE '${MACHINE}'"
    732 }
    733 
    734 # nobomb_getmakevar --
    735 # Given the name of a make variable in $1, print make's idea of the
    736 # value of that variable, or return 1 if there's an error.
    737 #
    738 nobomb_getmakevar()
    739 {
    740 	[ -x "${make}" ] || return 1
    741 	"${make}" -m ${TOP}/share/mk -s -B -f- _x_ <<EOF || return 1
    742 _x_:
    743 	echo \${$1}
    744 .include <bsd.prog.mk>
    745 .include <bsd.kernobj.mk>
    746 EOF
    747 }
    748 
    749 # bomb_getmakevar --
    750 # Given the name of a make variable in $1, print make's idea of the
    751 # value of that variable, or bomb if there's an error.
    752 #
    753 bomb_getmakevar()
    754 {
    755 	[ -x "${make}" ] || bomb "bomb_getmakevar $1: ${make} is not executable"
    756 	nobomb_getmakevar "$1" || bomb "bomb_getmakevar $1: ${make} failed"
    757 }
    758 
    759 # getmakevar --
    760 # Given the name of a make variable in $1, print make's idea of the
    761 # value of that variable, or print a literal '$' followed by the
    762 # variable name if ${make} is not executable.  This is intended for use in
    763 # messages that need to be readable even if $make hasn't been built,
    764 # such as when build.sh is run with the "-n" option.
    765 #
    766 getmakevar()
    767 {
    768 	if [ -x "${make}" ]; then
    769 		bomb_getmakevar "$1"
    770 	else
    771 		echo "\$$1"
    772 	fi
    773 }
    774 
    775 setmakeenv()
    776 {
    777 	eval "$1='$2'; export $1"
    778 	makeenv="${makeenv} $1"
    779 }
    780 
    781 unsetmakeenv()
    782 {
    783 	eval "unset $1"
    784 	makeenv="${makeenv} $1"
    785 }
    786 
    787 # Given a variable name in $1, modify the variable in place as follows:
    788 # For each space-separated word in the variable, call resolvepath.
    789 resolvepaths()
    790 {
    791 	local var="$1"
    792 	local val
    793 	eval val=\"\${${var}}\"
    794 	local newval=''
    795 	local word
    796 	for word in ${val}; do
    797 		resolvepath word
    798 		newval="${newval}${newval:+ }${word}"
    799 	done
    800 	eval ${var}=\"\${newval}\"
    801 }
    802 
    803 # Given a variable name in $1, modify the variable in place as follows:
    804 # Convert possibly-relative path to absolute path by prepending
    805 # ${TOP} if necessary.  Also delete trailing "/", if any.
    806 resolvepath()
    807 {
    808 	local var="$1"
    809 	local val
    810 	eval val=\"\${${var}}\"
    811 	case "${val}" in
    812 	/)
    813 		;;
    814 	/*)
    815 		val="${val%/}"
    816 		;;
    817 	*)
    818 		val="${TOP}/${val%/}"
    819 		;;
    820 	esac
    821 	eval ${var}=\"\${val}\"
    822 }
    823 
    824 usage()
    825 {
    826 	if [ -n "$*" ]; then
    827 		echo ""
    828 		echo "${progname}: $*"
    829 	fi
    830 	cat <<_usage_
    831 
    832 Usage: ${progname} [-EhnorUuxy] [-a arch] [-B buildid] [-C cdextras]
    833                 [-D dest] [-j njob] [-M obj] [-m mach] [-N noisy]
    834                 [-O obj] [-R release] [-S seed] [-T tools]
    835                 [-V var=[value]] [-w wrapper] [-X x11src] [-Y extsrcsrc]
    836                 [-Z var]
    837                 operation [...]
    838 
    839  Build operations (all imply "obj" and "tools"):
    840     build               Run "make build".
    841     distribution        Run "make distribution" (includes DESTDIR/etc/ files).
    842     release             Run "make release" (includes kernels & distrib media).
    843 
    844  Other operations:
    845     help                Show this message and exit.
    846     makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
    847                         Always performed.
    848     cleandir            Run "make cleandir".  [Default unless -u is used]
    849     obj                 Run "make obj".  [Default unless -o is used]
    850     tools               Build and install tools.
    851     install=idir        Run "make installworld" to \`idir' to install all sets
    852                         except \`etc'.  Useful after "distribution" or "release"
    853     kernel=conf         Build kernel with config file \`conf'
    854     releasekernel=conf  Install kernel built by kernel=conf to RELEASEDIR.
    855     installmodules=idir Run "make installmodules" to \`idir' to install all
    856                         kernel modules.
    857     modules             Build kernel modules.
    858     rumptest            Do a linktest for rump (for developers).
    859     sets                Create binary sets in
    860                         RELEASEDIR/RELEASEMACHINEDIR/binary/sets.
    861                         DESTDIR should be populated beforehand.
    862     sourcesets          Create source sets in RELEASEDIR/source/sets.
    863     syspkgs             Create syspkgs in
    864                         RELEASEDIR/RELEASEMACHINEDIR/binary/syspkgs.
    865     iso-image           Create CD-ROM image in RELEASEDIR/iso.
    866     iso-image-source    Create CD-ROM image with source in RELEASEDIR/iso.
    867     params              Display various make(1) parameters.
    868 
    869  Options:
    870     -a arch        Set MACHINE_ARCH to arch.  [Default: deduced from MACHINE]
    871     -B buildid     Set BUILDID to buildid.
    872     -C cdextras    Append cdextras to CDEXTRA variable for inclusion on CD-ROM.
    873     -D dest        Set DESTDIR to dest.  [Default: destdir.MACHINE]
    874     -E             Set "expert" mode; disables various safety checks.
    875                    Should not be used without expert knowledge of the build system.
    876     -h             Print this help message.
    877     -j njob        Run up to njob jobs in parallel; see make(1) -j.
    878     -M obj         Set obj root directory to obj; sets MAKEOBJDIRPREFIX.
    879                    Unsets MAKEOBJDIR.
    880     -m mach        Set MACHINE to mach; not required if NetBSD native.
    881     -N noisy       Set the noisyness (MAKEVERBOSE) level of the build:
    882                        0   Minimal output ("quiet")
    883                        1   Describe what is occurring
    884                        2   Describe what is occurring and echo the actual command
    885                        3   Ignore the effect of the "@" prefix in make commands
    886                        4   Trace shell commands using the shell's -x flag
    887                    [Default: 2]
    888     -n             Show commands that would be executed, but do not execute them.
    889     -O obj         Set obj root directory to obj; sets a MAKEOBJDIR pattern.
    890                    Unsets MAKEOBJDIRPREFIX.
    891     -o             Set MKOBJDIRS=no; do not create objdirs at start of build.
    892     -R release     Set RELEASEDIR to release.  [Default: releasedir]
    893     -r             Remove contents of TOOLDIR and DESTDIR before building.
    894     -S seed        Set BUILDSEED to seed.  [Default: NetBSD-majorversion]
    895     -T tools       Set TOOLDIR to tools.  If unset, and TOOLDIR is not set in
    896                    the environment, ${toolprefix}make will be (re)built
    897                    unconditionally.
    898     -U             Set MKUNPRIVED=yes; build without requiring root privileges,
    899                    install from an UNPRIVED build with proper file permissions.
    900     -u             Set MKUPDATE=yes; do not run "make cleandir" first.
    901                    Without this, everything is rebuilt, including the tools.
    902     -V var=[value] Set variable \`var' to \`value'.
    903     -w wrapper     Create ${toolprefix}make script as wrapper.
    904                    [Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE}]
    905     -X x11src      Set X11SRCDIR to x11src.  [Default: /usr/xsrc]
    906     -x             Set MKX11=yes; build X11 from X11SRCDIR
    907     -Y extsrcsrc   Set EXTSRCSRCDIR to extsrcsrc.  [Default: /usr/extsrc]
    908     -y             Set MKEXTSRC=yes; build extsrc from EXTSRCSRCDIR
    909     -Z var         Unset ("zap") variable \`var'.
    910 
    911 _usage_
    912 	exit 1
    913 }
    914 
    915 parseoptions()
    916 {
    917 	opts='a:B:C:D:Ehj:M:m:N:nO:oR:rS:T:UuV:w:X:xY:yZ:'
    918 	opt_a=no
    919 
    920 	if type getopts >/dev/null 2>&1; then
    921 		# Use POSIX getopts.
    922 		#
    923 		getoptcmd='getopts ${opts} opt && opt=-${opt}'
    924 		optargcmd=':'
    925 		optremcmd='shift $((${OPTIND} -1))'
    926 	else
    927 		type getopt >/dev/null 2>&1 ||
    928 		    bomb "Shell does not support getopts or getopt"
    929 
    930 		# Use old-style getopt(1) (doesn't handle whitespace in args).
    931 		#
    932 		args="$(getopt ${opts} $*)"
    933 		[ $? = 0 ] || usage
    934 		set -- ${args}
    935 
    936 		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
    937 		optargcmd='OPTARG="$1"; shift'
    938 		optremcmd=':'
    939 	fi
    940 
    941 	# Parse command line options.
    942 	#
    943 	while eval ${getoptcmd}; do
    944 		case ${opt} in
    945 
    946 		-a)
    947 			eval ${optargcmd}
    948 			MACHINE_ARCH=${OPTARG}
    949 			opt_a=yes
    950 			;;
    951 
    952 		-B)
    953 			eval ${optargcmd}
    954 			BUILDID=${OPTARG}
    955 			;;
    956 
    957 		-C)
    958 			eval ${optargcmd}; resolvepaths OPTARG
    959 			CDEXTRA="${CDEXTRA}${CDEXTRA:+ }${OPTARG}"
    960 			;;
    961 
    962 		-D)
    963 			eval ${optargcmd}; resolvepath OPTARG
    964 			setmakeenv DESTDIR "${OPTARG}"
    965 			;;
    966 
    967 		-E)
    968 			do_expertmode=true
    969 			;;
    970 
    971 		-j)
    972 			eval ${optargcmd}
    973 			parallel="-j ${OPTARG}"
    974 			;;
    975 
    976 		-M)
    977 			eval ${optargcmd}; resolvepath OPTARG
    978 			case "${OPTARG}" in
    979 			\$*)	usage "-M argument must not begin with '\$'"
    980 				;;
    981 			*\$*)	# can use resolvepath, but can't set TOP_objdir
    982 				resolvepath OPTARG
    983 				;;
    984 			*)	resolvepath OPTARG
    985 				TOP_objdir="${OPTARG}${TOP}"
    986 				;;
    987 			esac
    988 			unsetmakeenv MAKEOBJDIR
    989 			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
    990 			;;
    991 
    992 			# -m overrides MACHINE_ARCH unless "-a" is specified
    993 		-m)
    994 			eval ${optargcmd}
    995 			MACHINE="${OPTARG}"
    996 			[ "${opt_a}" != "yes" ] && getarch
    997 			;;
    998 
    999 		-N)
   1000 			eval ${optargcmd}
   1001 			case "${OPTARG}" in
   1002 			0|1|2|3|4)
   1003 				setmakeenv MAKEVERBOSE "${OPTARG}"
   1004 				;;
   1005 			*)
   1006 				usage "'${OPTARG}' is not a valid value for -N"
   1007 				;;
   1008 			esac
   1009 			;;
   1010 
   1011 		-n)
   1012 			runcmd=echo
   1013 			;;
   1014 
   1015 		-O)
   1016 			eval ${optargcmd}
   1017 			case "${OPTARG}" in
   1018 			*\$*)	usage "-O argument must not contain '\$'"
   1019 				;;
   1020 			*)	resolvepath OPTARG
   1021 				TOP_objdir="${OPTARG}"
   1022 				;;
   1023 			esac
   1024 			unsetmakeenv MAKEOBJDIRPREFIX
   1025 			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
   1026 			;;
   1027 
   1028 		-o)
   1029 			MKOBJDIRS=no
   1030 			;;
   1031 
   1032 		-R)
   1033 			eval ${optargcmd}; resolvepath OPTARG
   1034 			setmakeenv RELEASEDIR "${OPTARG}"
   1035 			;;
   1036 
   1037 		-r)
   1038 			do_removedirs=true
   1039 			do_rebuildmake=true
   1040 			;;
   1041 
   1042 		-S)
   1043 			eval ${optargcmd}
   1044 			setmakeenv BUILDSEED "${OPTARG}"
   1045 			;;
   1046 
   1047 		-T)
   1048 			eval ${optargcmd}; resolvepath OPTARG
   1049 			TOOLDIR="${OPTARG}"
   1050 			export TOOLDIR
   1051 			;;
   1052 
   1053 		-U)
   1054 			setmakeenv MKUNPRIVED yes
   1055 			;;
   1056 
   1057 		-u)
   1058 			setmakeenv MKUPDATE yes
   1059 			;;
   1060 
   1061 		-V)
   1062 			eval ${optargcmd}
   1063 			case "${OPTARG}" in
   1064 		    # XXX: consider restricting which variables can be changed?
   1065 			[a-zA-Z_][a-zA-Z_0-9]*=*)
   1066 				setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
   1067 				;;
   1068 			*)
   1069 				usage "-V argument must be of the form 'var=[value]'"
   1070 				;;
   1071 			esac
   1072 			;;
   1073 
   1074 		-w)
   1075 			eval ${optargcmd}; resolvepath OPTARG
   1076 			makewrapper="${OPTARG}"
   1077 			;;
   1078 
   1079 		-X)
   1080 			eval ${optargcmd}; resolvepath OPTARG
   1081 			setmakeenv X11SRCDIR "${OPTARG}"
   1082 			;;
   1083 
   1084 		-x)
   1085 			setmakeenv MKX11 yes
   1086 			;;
   1087 
   1088 		-Y)
   1089 			eval ${optargcmd}; resolvepath OPTARG
   1090 			setmakeenv EXTSRCSRCDIR "${OPTARG}"
   1091 			;;
   1092 
   1093 		-y)
   1094 			setmakeenv MKEXTSRC yes
   1095 			;;
   1096 
   1097 		-Z)
   1098 			eval ${optargcmd}
   1099 		    # XXX: consider restricting which variables can be unset?
   1100 			unsetmakeenv "${OPTARG}"
   1101 			;;
   1102 
   1103 		--)
   1104 			break
   1105 			;;
   1106 
   1107 		-'?'|-h)
   1108 			usage
   1109 			;;
   1110 
   1111 		esac
   1112 	done
   1113 
   1114 	# Validate operations.
   1115 	#
   1116 	eval ${optremcmd}
   1117 	while [ $# -gt 0 ]; do
   1118 		op=$1; shift
   1119 		operations="${operations} ${op}"
   1120 
   1121 		case "${op}" in
   1122 
   1123 		help)
   1124 			usage
   1125 			;;
   1126 
   1127 		makewrapper|cleandir|obj|tools|build|distribution|release|sets|sourcesets|syspkgs|params)
   1128 			;;
   1129 
   1130 		iso-image)
   1131 			op=iso_image	# used as part of a variable name
   1132 			;;
   1133 
   1134 		iso-image-source)
   1135 			op=iso_image_source   # used as part of a variable name
   1136 			;;
   1137 
   1138 		kernel=*|releasekernel=*)
   1139 			arg=${op#*=}
   1140 			op=${op%%=*}
   1141 			[ -n "${arg}" ] ||
   1142 			    bomb "Must supply a kernel name with \`${op}=...'"
   1143 			;;
   1144 
   1145 		modules)
   1146 			op=modules
   1147 			;;
   1148 
   1149 		install=*|installmodules=*)
   1150 			arg=${op#*=}
   1151 			op=${op%%=*}
   1152 			[ -n "${arg}" ] ||
   1153 			    bomb "Must supply a directory with \`install=...'"
   1154 			;;
   1155 
   1156 		rump|rumptest)
   1157 			op=${op}
   1158 			;;
   1159 
   1160 		*)
   1161 			usage "Unknown operation \`${op}'"
   1162 			;;
   1163 
   1164 		esac
   1165 		eval do_${op}=true
   1166 	done
   1167 	[ -n "${operations}" ] || usage "Missing operation to perform."
   1168 
   1169 	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
   1170 	#
   1171 	if [ -z "${MACHINE}" ]; then
   1172 		[ "${uname_s}" = "NetBSD" ] ||
   1173 		    bomb "MACHINE must be set, or -m must be used, for cross builds."
   1174 		MACHINE=${uname_m}
   1175 	fi
   1176 	[ -n "${MACHINE_ARCH}" ] || getarch
   1177 	validatearch
   1178 
   1179 	# Set up default make(1) environment.
   1180 	#
   1181 	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
   1182 	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
   1183 	MAKEFLAGS="-de -m ${TOP}/share/mk ${MAKEFLAGS}"
   1184 	MAKEFLAGS="${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
   1185 	export MAKEFLAGS MACHINE MACHINE_ARCH
   1186 }
   1187 
   1188 # sanitycheck --
   1189 # Sanity check after parsing command line options, before rebuildmake.
   1190 #
   1191 sanitycheck()
   1192 {
   1193 	# If the PATH contains any non-absolute components (including,
   1194 	# but not limited to, "." or ""), then complain.  As an exception,
   1195 	# allow "" or "." as the last component of the PATH.  This is fatal
   1196 	# if expert mode is not in effect.
   1197 	#
   1198 	local path="${PATH}"
   1199 	path="${path%:}"	# delete trailing ":"
   1200 	path="${path%:.}"	# delete trailing ":."
   1201 	case ":${path}:/" in
   1202 	*:[!/]*)
   1203 		if ${do_expertmode}; then
   1204 			warning "PATH contains non-absolute components"
   1205 		else
   1206 			bomb "PATH environment variable must not" \
   1207 			     "contain non-absolute components"
   1208 		fi
   1209 		;;
   1210 	esac
   1211 }
   1212 
   1213 # print_tooldir_make --
   1214 # Try to find and print a path to an existing
   1215 # ${TOOLDIR}/bin/${toolprefix}make, for use by rebuildmake() before a
   1216 # new version of ${toolprefix}make has been built.
   1217 #
   1218 # * If TOOLDIR was set in the environment or on the command line, use
   1219 #   that value.
   1220 # * Otherwise try to guess what TOOLDIR would be if not overridden by
   1221 #   /etc/mk.conf, and check whether the resulting directory contains
   1222 #   a copy of ${toolprefix}make (this should work for everybody who
   1223 #   doesn't override TOOLDIR via /etc/mk.conf);
   1224 # * Failing that, search for ${toolprefix}make, nbmake, bmake, or make,
   1225 #   in the PATH (this might accidentally find a version of make that
   1226 #   does not understand the syntax used by NetBSD make, and that will
   1227 #   lead to failure in the next step);
   1228 # * If a copy of make was found above, try to use it with
   1229 #   nobomb_getmakevar to find the correct value for TOOLDIR, and believe the
   1230 #   result only if it's a directory that already exists;
   1231 # * If a value of TOOLDIR was found above, and if
   1232 #   ${TOOLDIR}/bin/${toolprefix}make exists, print that value.
   1233 #
   1234 print_tooldir_make()
   1235 {
   1236 	local possible_TOP_OBJ
   1237 	local possible_TOOLDIR
   1238 	local possible_make
   1239 	local tooldir_make
   1240 
   1241 	if [ -n "${TOOLDIR}" ]; then
   1242 		echo "${TOOLDIR}/bin/${toolprefix}make"
   1243 		return 0
   1244 	fi
   1245 
   1246 	# Set host_ostype to something like "NetBSD-4.5.6-i386".  This
   1247 	# is intended to match the HOST_OSTYPE variable in <bsd.own.mk>.
   1248 	#
   1249 	local host_ostype="${uname_s}-$(
   1250 		echo "${uname_r}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
   1251 		)-$(
   1252 		echo "${uname_p}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
   1253 		)"
   1254 
   1255 	# Look in a few potential locations for
   1256 	# ${possible_TOOLDIR}/bin/${toolprefix}make.
   1257 	# If we find it, then set possible_make.
   1258 	#
   1259 	# In the usual case (without interference from environment
   1260 	# variables or /etc/mk.conf), <bsd.own.mk> should set TOOLDIR to
   1261 	# "${_SRC_TOP_OBJ_}/tooldir.${host_ostype}".
   1262 	#
   1263 	# In practice it's difficult to figure out the correct value
   1264 	# for _SRC_TOP_OBJ_.  In the easiest case, when the -M or -O
   1265 	# options were passed to build.sh, then ${TOP_objdir} will be
   1266 	# the correct value.  We also try a few other possibilities, but
   1267 	# we do not replicate all the logic of <bsd.obj.mk>.
   1268 	#
   1269 	for possible_TOP_OBJ in \
   1270 		"${TOP_objdir}" \
   1271 		"${MAKEOBJDIRPREFIX:+${MAKEOBJDIRPREFIX}${TOP}}" \
   1272 		"${TOP}" \
   1273 		"${TOP}/obj" \
   1274 		"${TOP}/obj.${MACHINE}"
   1275 	do
   1276 		[ -n "${possible_TOP_OBJ}" ] || continue
   1277 		possible_TOOLDIR="${possible_TOP_OBJ}/tooldir.${host_ostype}"
   1278 		possible_make="${possible_TOOLDIR}/bin/${toolprefix}make"
   1279 		if [ -x "${possible_make}" ]; then
   1280 			break
   1281 		else
   1282 			unset possible_make
   1283 		fi
   1284 	done
   1285 
   1286 	# If the above didn't work, search the PATH for a suitable
   1287 	# ${toolprefix}make, nbmake, bmake, or make.
   1288 	#
   1289 	: ${possible_make:=$(find_in_PATH ${toolprefix}make '')}
   1290 	: ${possible_make:=$(find_in_PATH nbmake '')}
   1291 	: ${possible_make:=$(find_in_PATH bmake '')}
   1292 	: ${possible_make:=$(find_in_PATH make '')}
   1293 
   1294 	# At this point, we don't care whether possible_make is in the
   1295 	# correct TOOLDIR or not; we simply want it to be usable by
   1296 	# getmakevar to help us find the correct TOOLDIR.
   1297 	#
   1298 	# Use ${possible_make} with nobomb_getmakevar to try to find
   1299 	# the value of TOOLDIR.  Believe the result only if it's
   1300 	# a directory that already exists and contains bin/${toolprefix}make.
   1301 	#
   1302 	if [ -x "${possible_make}" ]; then
   1303 		possible_TOOLDIR="$(
   1304 			make="${possible_make}" \
   1305 			nobomb_getmakevar TOOLDIR 2>/dev/null
   1306 			)"
   1307 		if [ $? = 0 ] && [ -n "${possible_TOOLDIR}" ] \
   1308 		    && [ -d "${possible_TOOLDIR}" ];
   1309 		then
   1310 			tooldir_make="${possible_TOOLDIR}/bin/${toolprefix}make"
   1311 			if [ -x "${tooldir_make}" ]; then
   1312 				echo "${tooldir_make}"
   1313 				return 0
   1314 			fi
   1315 		fi
   1316 	fi
   1317 	return 1
   1318 }
   1319 
   1320 # rebuildmake --
   1321 # Rebuild nbmake in a temporary directory if necessary.  Sets $make
   1322 # to a path to the nbmake executable.  Sets done_rebuildmake=true
   1323 # if nbmake was rebuilt.
   1324 #
   1325 # There is a cyclic dependency between building nbmake and choosing
   1326 # TOOLDIR: TOOLDIR may be affected by settings in /etc/mk.conf, so we
   1327 # would like to use getmakevar to get the value of TOOLDIR; but we can't
   1328 # use getmakevar before we have an up to date version of nbmake; we
   1329 # might already have an up to date version of nbmake in TOOLDIR, but we
   1330 # don't yet know where TOOLDIR is.
   1331 #
   1332 # The default value of TOOLDIR also depends on the location of the top
   1333 # level object directory, so $(getmakevar TOOLDIR) invoked before or
   1334 # after making the top level object directory may produce different
   1335 # results.
   1336 #
   1337 # Strictly speaking, we should do the following:
   1338 #
   1339 #    1. build a new version of nbmake in a temporary directory;
   1340 #    2. use the temporary nbmake to create the top level obj directory;
   1341 #    3. use $(getmakevar TOOLDIR) with the temporary nbmake to
   1342 #       get the corect value of TOOLDIR;
   1343 #    4. move the temporary nbmake to ${TOOLDIR}/bin/nbmake.
   1344 #
   1345 # However, people don't like building nbmake unnecessarily if their
   1346 # TOOLDIR has not changed since an earlier build.  We try to avoid
   1347 # rebuilding a temporary version of nbmake by taking some shortcuts to
   1348 # guess a value for TOOLDIR, looking for an existing version of nbmake
   1349 # in that TOOLDIR, and checking whether that nbmake is newer than the
   1350 # sources used to build it.
   1351 #
   1352 rebuildmake()
   1353 {
   1354 	make="$(print_tooldir_make)"
   1355 	if [ -n "${make}" ] && [ -x "${make}" ]; then
   1356 		for f in usr.bin/make/*.[ch] usr.bin/make/lst.lib/*.[ch]; do
   1357 			if [ "${f}" -nt "${make}" ]; then
   1358 				statusmsg "${make} outdated" \
   1359 					"(older than ${f}), needs building."
   1360 				do_rebuildmake=true
   1361 				break
   1362 			fi
   1363 		done
   1364 	else
   1365 		statusmsg "No \$TOOLDIR/bin/${toolprefix}make, needs building."
   1366 		do_rebuildmake=true
   1367 	fi
   1368 
   1369 	# Build bootstrap ${toolprefix}make if needed.
   1370 	if ${do_rebuildmake}; then
   1371 		statusmsg "Bootstrapping ${toolprefix}make"
   1372 		${runcmd} cd "${tmpdir}"
   1373 		${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
   1374 			CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
   1375 			${HOST_SH} "${TOP}/tools/make/configure" ||
   1376 		    bomb "Configure of ${toolprefix}make failed"
   1377 		${runcmd} ${HOST_SH} buildmake.sh ||
   1378 		    bomb "Build of ${toolprefix}make failed"
   1379 		make="${tmpdir}/${toolprefix}make"
   1380 		${runcmd} cd "${TOP}"
   1381 		${runcmd} rm -f usr.bin/make/*.o usr.bin/make/lst.lib/*.o
   1382 		done_rebuildmake=true
   1383 	fi
   1384 }
   1385 
   1386 # validatemakeparams --
   1387 # Perform some late sanity checks, after rebuildmake,
   1388 # but before createmakewrapper or any real work.
   1389 #
   1390 # Also create the top-level obj directory.
   1391 #
   1392 validatemakeparams()
   1393 {
   1394 	if [ "${runcmd}" = "echo" ]; then
   1395 		TOOLCHAIN_MISSING=no
   1396 		EXTERNAL_TOOLCHAIN=""
   1397 	else
   1398 		TOOLCHAIN_MISSING=$(bomb_getmakevar TOOLCHAIN_MISSING)
   1399 		EXTERNAL_TOOLCHAIN=$(bomb_getmakevar EXTERNAL_TOOLCHAIN)
   1400 	fi
   1401 	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
   1402 	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
   1403 		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
   1404 		${runcmd} echo "	MACHINE:      ${MACHINE}"
   1405 		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
   1406 		${runcmd} echo ""
   1407 		${runcmd} echo "All builds for this platform should be done via a traditional make"
   1408 		${runcmd} echo "If you wish to use an external cross-toolchain, set"
   1409 		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
   1410 		${runcmd} echo "in either the environment or mk.conf and rerun"
   1411 		${runcmd} echo "	${progname} $*"
   1412 		exit 1
   1413 	fi
   1414 
   1415 	# Normalise MKOBJDIRS, MKUNPRIVED, and MKUPDATE
   1416 	# These may be set as build.sh options or in "mk.conf".
   1417 	# Don't export them as they're only used for tests in build.sh.
   1418 	#
   1419 	MKOBJDIRS=$(getmakevar MKOBJDIRS)
   1420 	MKUNPRIVED=$(getmakevar MKUNPRIVED)
   1421 	MKUPDATE=$(getmakevar MKUPDATE)
   1422 
   1423 	if [ "${MKOBJDIRS}" != "no" ]; then
   1424 		# Create the top-level object directory.
   1425 		#
   1426 		# "make obj NOSUBDIR=" can handle most cases, but it
   1427 		# can't handle the case where MAKEOBJDIRPREFIX is set
   1428 		# while the corresponding directory does not exist
   1429 		# (rules in <bsd.obj.mk> would abort the build).  We
   1430 		# therefore have to handle the MAKEOBJDIRPREFIX case
   1431 		# without invoking "make obj".  The MAKEOBJDIR case
   1432 		# could be handled either way, but we choose to handle
   1433 		# it similarly to MAKEOBJDIRPREFIX.
   1434 		#
   1435 		if [ -n "${TOP_obj}" ]; then
   1436 			# It must have been set by the "-M" or "-O"
   1437 			# command line options, so there's no need to
   1438 			# use getmakevar
   1439 			:
   1440 		elif [ -n "$MAKEOBJDIRPREFIX" ]; then
   1441 			TOP_obj="$(getmakevar MAKEOBJDIRPREFIX)${TOP}"
   1442 		elif [ -n "$MAKEOBJDIR" ]; then
   1443 			TOP_obj="$(getmakevar MAKEOBJDIR)"
   1444 		fi
   1445 		if [ -n "$TOP_obj" ]; then
   1446 			${runcmd} mkdir -p "${TOP_obj}" ||
   1447 			    bomb "Can't create top level object directory" \
   1448 					"${TOP_obj}"
   1449 		else
   1450 			${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1451 			    bomb "Can't create top level object directory" \
   1452 					"using make obj"
   1453 		fi
   1454 
   1455 		# make obj in tools to ensure that the objdir for "tools"
   1456 		# is available.
   1457 		#
   1458 		${runcmd} cd tools
   1459 		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1460 		    bomb "Failed to make obj in tools"
   1461 		${runcmd} cd "${TOP}"
   1462 	fi
   1463 
   1464 	# Find TOOLDIR, DESTDIR, and RELEASEDIR, according to getmakevar,
   1465 	# and bomb if they have changed from the values we had from the
   1466 	# command line or environment.
   1467 	#
   1468 	# This must be done after creating the top-level object directory.
   1469 	#
   1470 	for var in TOOLDIR DESTDIR RELEASEDIR
   1471 	do
   1472 		eval oldval=\"\$${var}\"
   1473 		newval="$(getmakevar $var)"
   1474 		if ! $do_expertmode; then
   1475 			: ${_SRC_TOP_OBJ_:=$(getmakevar _SRC_TOP_OBJ_)}
   1476 			case "$var" in
   1477 			DESTDIR)
   1478 				: ${newval:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
   1479 				makeenv="${makeenv} DESTDIR"
   1480 				;;
   1481 			RELEASEDIR)
   1482 				: ${newval:=${_SRC_TOP_OBJ_}/releasedir}
   1483 				makeenv="${makeenv} RELEASEDIR"
   1484 				;;
   1485 			esac
   1486 		fi
   1487 		if [ -n "$oldval" ] && [ "$oldval" != "$newval" ]; then
   1488 			bomb "Value of ${var} has changed" \
   1489 				"(was \"${oldval}\", now \"${newval}\")"
   1490 		fi
   1491 		eval ${var}=\"\${newval}\"
   1492 		eval export ${var}
   1493 		statusmsg2 "${var} path:" "${newval}"
   1494 	done
   1495 
   1496 	# RELEASEMACHINEDIR is just a subdir name, e.g. "i386".
   1497 	RELEASEMACHINEDIR=$(getmakevar RELEASEMACHINEDIR)
   1498 
   1499 	# Check validity of TOOLDIR and DESTDIR.
   1500 	#
   1501 	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
   1502 		bomb "TOOLDIR '${TOOLDIR}' invalid"
   1503 	fi
   1504 	removedirs="${TOOLDIR}"
   1505 
   1506 	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
   1507 		if ${do_build} || ${do_distribution} || ${do_release}; then
   1508 			if ! ${do_build} || \
   1509 			   [ "${uname_s}" != "NetBSD" ] || \
   1510 			   [ "${uname_m}" != "${MACHINE}" ]; then
   1511 				bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'."
   1512 			fi
   1513 			if ! ${do_expertmode}; then
   1514 				bomb "DESTDIR must != / for non -E (expert) builds"
   1515 			fi
   1516 			statusmsg "WARNING: Building to /, in expert mode."
   1517 			statusmsg "         This may cause your system to break!  Reasons include:"
   1518 			statusmsg "            - your kernel is not up to date"
   1519 			statusmsg "            - the libraries or toolchain have changed"
   1520 			statusmsg "         YOU HAVE BEEN WARNED!"
   1521 		fi
   1522 	else
   1523 		removedirs="${removedirs} ${DESTDIR}"
   1524 	fi
   1525 	if ${do_build} || ${do_distribution} || ${do_release}; then
   1526 		if ! ${do_expertmode} && \
   1527 		    [ "$id_u" -ne 0 ] && \
   1528 		    [ "${MKUNPRIVED}" = "no" ] ; then
   1529 			bomb "-U or -E must be set for build as an unprivileged user."
   1530 		fi
   1531 	fi
   1532 	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
   1533 		bomb "Must set RELEASEDIR with \`releasekernel=...'"
   1534 	fi
   1535 
   1536 	# Install as non-root is a bad idea.
   1537 	#
   1538 	if ${do_install} && [ "$id_u" -ne 0 ] ; then
   1539 		if ${do_expertmode}; then
   1540 			warning "Will install as an unprivileged user."
   1541 		else
   1542 			bomb "-E must be set for install as an unprivileged user."
   1543 		fi
   1544 	fi
   1545 
   1546 	# If a previous build.sh run used -U (and therefore created a
   1547 	# METALOG file), then most subsequent build.sh runs must also
   1548 	# use -U.  If DESTDIR is about to be removed, then don't perform
   1549 	# this check.
   1550 	#
   1551 	case "${do_removedirs} ${removedirs} " in
   1552 	true*" ${DESTDIR} "*)
   1553 		# DESTDIR is about to be removed
   1554 		;;
   1555 	*)
   1556 		if ( ${do_build} || ${do_distribution} || ${do_release} || \
   1557 		    ${do_install} ) && \
   1558 		    [ -e "${DESTDIR}/METALOG" ] && \
   1559 		    [ "${MKUNPRIVED}" = "no" ] ; then
   1560 			if $do_expertmode; then
   1561 				warning "A previous build.sh run specified -U."
   1562 			else
   1563 				bomb "A previous build.sh run specified -U; you must specify it again now."
   1564 			fi
   1565 		fi
   1566 		;;
   1567 	esac
   1568 }
   1569 
   1570 
   1571 createmakewrapper()
   1572 {
   1573 	# Remove the target directories.
   1574 	#
   1575 	if ${do_removedirs}; then
   1576 		for f in ${removedirs}; do
   1577 			statusmsg "Removing ${f}"
   1578 			${runcmd} rm -r -f "${f}"
   1579 		done
   1580 	fi
   1581 
   1582 	# Recreate $TOOLDIR.
   1583 	#
   1584 	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
   1585 	    bomb "mkdir of '${TOOLDIR}/bin' failed"
   1586 
   1587 	# If we did not previously rebuild ${toolprefix}make, then
   1588 	# check whether $make is still valid and the same as the output
   1589 	# from print_tooldir_make.  If not, then rebuild make now.  A
   1590 	# possible reason for this being necessary is that the actual
   1591 	# value of TOOLDIR might be different from the value guessed
   1592 	# before the top level obj dir was created.
   1593 	#
   1594 	if ! ${done_rebuildmake} && \
   1595 	    ( [ ! -x "$make" ] || [ "$make" != "$(print_tooldir_make)" ] )
   1596 	then
   1597 		rebuildmake
   1598 	fi
   1599 
   1600 	# Install ${toolprefix}make if it was built.
   1601 	#
   1602 	if ${done_rebuildmake}; then
   1603 		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
   1604 		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
   1605 		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
   1606 		make="${TOOLDIR}/bin/${toolprefix}make"
   1607 		statusmsg "Created ${make}"
   1608 	fi
   1609 
   1610 	# Build a ${toolprefix}make wrapper script, usable by hand as
   1611 	# well as by build.sh.
   1612 	#
   1613 	if [ -z "${makewrapper}" ]; then
   1614 		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
   1615 		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
   1616 	fi
   1617 
   1618 	${runcmd} rm -f "${makewrapper}"
   1619 	if [ "${runcmd}" = "echo" ]; then
   1620 		echo 'cat <<EOF >'${makewrapper}
   1621 		makewrapout=
   1622 	else
   1623 		makewrapout=">>\${makewrapper}"
   1624 	fi
   1625 
   1626 	case "${KSH_VERSION:-${SH_VERSION}}" in
   1627 	*PD\ KSH*|*MIRBSD\ KSH*)
   1628 		set +o braceexpand
   1629 		;;
   1630 	esac
   1631 
   1632 	eval cat <<EOF ${makewrapout}
   1633 #! ${HOST_SH}
   1634 # Set proper variables to allow easy "make" building of a NetBSD subtree.
   1635 # Generated from:  \$NetBSD: build.sh,v 1.250 2011/09/14 17:35:44 apb Exp $
   1636 # with these arguments: ${_args}
   1637 #
   1638 
   1639 EOF
   1640 	{
   1641 		for f in ${makeenv}; do
   1642 			if eval "[ -z \"\${$f}\" -a \"\${${f}-X}\" = \"X\" ]"; then
   1643 				eval echo "unset ${f}"
   1644 			else
   1645 				eval echo "${f}=\'\$$(echo ${f})\'\;\ export\ ${f}"
   1646 			fi
   1647 		done
   1648 
   1649 		eval cat <<EOF
   1650 MAKEWRAPPERMACHINE=${makewrappermachine:-${MACHINE}}; export MAKEWRAPPERMACHINE
   1651 USETOOLS=yes; export USETOOLS
   1652 EOF
   1653 	} | eval sort -u "${makewrapout}"
   1654 	eval cat <<EOF "${makewrapout}"
   1655 
   1656 exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
   1657 EOF
   1658 	[ "${runcmd}" = "echo" ] && echo EOF
   1659 	${runcmd} chmod +x "${makewrapper}"
   1660 	statusmsg2 "Updated makewrapper:" "${makewrapper}"
   1661 }
   1662 
   1663 make_in_dir()
   1664 {
   1665 	dir="$1"
   1666 	op="$2"
   1667 	${runcmd} cd "${dir}" ||
   1668 	    bomb "Failed to cd to \"${dir}\""
   1669 	${runcmd} "${makewrapper}" ${parallel} ${op} ||
   1670 	    bomb "Failed to make ${op} in \"${dir}\""
   1671 	${runcmd} cd "${TOP}" ||
   1672 	    bomb "Failed to cd back to \"${TOP}\""
   1673 }
   1674 
   1675 buildtools()
   1676 {
   1677 	if [ "${MKOBJDIRS}" != "no" ]; then
   1678 		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
   1679 		    bomb "Failed to make obj-tools"
   1680 	fi
   1681 	if [ "${MKUPDATE}" = "no" ]; then
   1682 		make_in_dir tools cleandir
   1683 	fi
   1684 	make_in_dir tools dependall
   1685 	make_in_dir tools install
   1686 	statusmsg "Tools built to ${TOOLDIR}"
   1687 }
   1688 
   1689 getkernelconf()
   1690 {
   1691 	kernelconf="$1"
   1692 	if [ "${MKOBJDIRS}" != "no" ]; then
   1693 		# The correct value of KERNOBJDIR might
   1694 		# depend on a prior "make obj" in
   1695 		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
   1696 		#
   1697 		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
   1698 		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
   1699 		make_in_dir "${KERNSRCDIR}/${KERNARCHDIR}/compile" obj
   1700 	fi
   1701 	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
   1702 	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
   1703 	case "${kernelconf}" in
   1704 	*/*)
   1705 		kernelconfpath="${kernelconf}"
   1706 		kernelconfname="${kernelconf##*/}"
   1707 		;;
   1708 	*)
   1709 		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
   1710 		kernelconfname="${kernelconf}"
   1711 		;;
   1712 	esac
   1713 	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
   1714 }
   1715 
   1716 buildkernel()
   1717 {
   1718 	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
   1719 		# Building tools every time we build a kernel is clearly
   1720 		# unnecessary.  We could try to figure out whether rebuilding
   1721 		# the tools is necessary this time, but it doesn't seem worth
   1722 		# the trouble.  Instead, we say it's the user's responsibility
   1723 		# to rebuild the tools if necessary.
   1724 		#
   1725 		statusmsg "Building kernel without building new tools"
   1726 		buildkernelwarned=true
   1727 	fi
   1728 	getkernelconf $1
   1729 	statusmsg2 "Building kernel:" "${kernelconf}"
   1730 	statusmsg2 "Build directory:" "${kernelbuildpath}"
   1731 	${runcmd} mkdir -p "${kernelbuildpath}" ||
   1732 	    bomb "Cannot mkdir: ${kernelbuildpath}"
   1733 	if [ "${MKUPDATE}" = "no" ]; then
   1734 		make_in_dir "${kernelbuildpath}" cleandir
   1735 	fi
   1736 	[ -x "${TOOLDIR}/bin/${toolprefix}config" ] \
   1737 	|| bomb "${TOOLDIR}/bin/${toolprefix}config does not exist. You need to \"$0 tools\" first."
   1738 	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" -b "${kernelbuildpath}" \
   1739 		-s "${TOP}/sys" "${kernelconfpath}" ||
   1740 	    bomb "${toolprefix}config failed for ${kernelconf}"
   1741 	make_in_dir "${kernelbuildpath}" depend
   1742 	make_in_dir "${kernelbuildpath}" all
   1743 
   1744 	if [ "${runcmd}" != "echo" ]; then
   1745 		statusmsg "Kernels built from ${kernelconf}:"
   1746 		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   1747 		for kern in ${kernlist:-netbsd}; do
   1748 			[ -f "${kernelbuildpath}/${kern}" ] && \
   1749 			    echo "  ${kernelbuildpath}/${kern}"
   1750 		done | tee -a "${results}"
   1751 	fi
   1752 }
   1753 
   1754 releasekernel()
   1755 {
   1756 	getkernelconf $1
   1757 	kernelreldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
   1758 	${runcmd} mkdir -p "${kernelreldir}"
   1759 	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   1760 	for kern in ${kernlist:-netbsd}; do
   1761 		builtkern="${kernelbuildpath}/${kern}"
   1762 		[ -f "${builtkern}" ] || continue
   1763 		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
   1764 		statusmsg2 "Kernel copy:" "${releasekern}"
   1765 		if [ "${runcmd}" = "echo" ]; then
   1766 			echo "gzip -c -9 < ${builtkern} > ${releasekern}"
   1767 		else
   1768 			gzip -c -9 < "${builtkern}" > "${releasekern}"
   1769 		fi
   1770 	done
   1771 }
   1772 
   1773 buildmodules()
   1774 {
   1775 	setmakeenv MKBINUTILS no
   1776 	if ! ${do_tools} && ! ${buildmoduleswarned:-false}; then
   1777 		# Building tools every time we build modules is clearly
   1778 		# unnecessary as well as a kernel.
   1779 		#
   1780 		statusmsg "Building modules without building new tools"
   1781 		buildmoduleswarned=true
   1782 	fi
   1783 
   1784 	statusmsg "Building kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   1785 	if [ "${MKOBJDIRS}" != "no" ]; then
   1786 		make_in_dir sys/modules obj ||
   1787 		    bomb "Failed to make obj in sys/modules"
   1788 	fi
   1789 	if [ "${MKUPDATE}" = "no" ]; then
   1790 		make_in_dir sys/modules cleandir
   1791 	fi
   1792 	${runcmd} "${makewrapper}" ${parallel} do-sys-modules ||
   1793 	    bomb "Failed to make do-sys-modules"
   1794 
   1795 	statusmsg "Successful build of kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   1796 }
   1797 
   1798 installmodules()
   1799 {
   1800 	dir="$1"
   1801 	${runcmd} "${makewrapper}" INSTALLMODULESDIR="${dir}" installmodules ||
   1802 	    bomb "Failed to make installmodules to ${dir}"
   1803 	statusmsg "Successful installmodules to ${dir}"
   1804 }
   1805 
   1806 installworld()
   1807 {
   1808 	dir="$1"
   1809 	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
   1810 	    bomb "Failed to make installworld to ${dir}"
   1811 	statusmsg "Successful installworld to ${dir}"
   1812 }
   1813 
   1814 # Run rump build&link tests.
   1815 #
   1816 # To make this feasible for running without having to install includes and
   1817 # libraries into destdir (i.e. quick), we only run ld.  This is possible
   1818 # since the rump kernel is a closed namespace apart from calls to rumpuser.
   1819 # Therefore, if ld complains only about rumpuser symbols, rump kernel
   1820 # linking was successful.
   1821 #
   1822 # We test that rump links with a number of component configurations.
   1823 # These attempt to mimic what is encountered in the full build.
   1824 # See list below.  The list should probably be either autogenerated
   1825 # or managed elsewhere; keep it here until a better idea arises.
   1826 #
   1827 # Above all, note that THIS IS NOT A SUBSTITUTE FOR A FULL BUILD.
   1828 #
   1829 
   1830 RUMP_LIBSETS='
   1831 	-lrump,
   1832 	-lrumpvfs -lrump,
   1833 	-lrumpdev -lrump,
   1834 	-lrumpnet -lrump,
   1835 	-lrumpkern_tty -lrumpvfs -lrump,
   1836 	-lrumpfs_tmpfs -lrumpvfs -lrump,
   1837 	-lrumpfs_ffs -lrumpfs_msdos -lrumpvfs -lrumpdev_disk -lrumpdev -lrump,
   1838 	-lrumpnet_virtif -lrumpnet_netinet -lrumpnet_net -lrumpnet -lrump,
   1839 	-lrumpnet_sockin -lrumpfs_smbfs -lrumpdev_netsmb
   1840 	    -lrumpkern_crypto -lrumpdev -lrumpnet -lrumpvfs -lrump,
   1841 	-lrumpnet_sockin -lrumpfs_nfs -lrumpnet -lrumpvfs -lrump,
   1842 	-lrumpdev_cgd -lrumpdev_raidframe -lrumpdev_disk -lrumpdev_rnd
   1843 	    -lrumpdev_dm -lrumpdev -lrumpvfs -lrumpkern_crypto -lrump'
   1844 dorump()
   1845 {
   1846 	local doclean=""
   1847 	local doobjs=""
   1848 
   1849 	# we cannot link libs without building csu, and that leads to lossage
   1850 	[ "${1}" != "rumptest" ] && bomb 'build.sh rump not yet functional. ' \
   1851 	    'did you mean "rumptest"?'
   1852 
   1853 	# create obj and distrib dirs
   1854 	if [ "${MKOBJDIRS}" != "no" ]; then
   1855 		make_in_dir "${NETBSDSRCDIR}/etc/mtree" obj
   1856 		make_in_dir "${NETBSDSRCDIR}/sys/rump" obj
   1857 	fi
   1858 	${runcmd} "${makewrapper}" ${parallel} do-distrib-dirs \
   1859 	    || bomb 'could not create distrib-dirs'
   1860 
   1861 	[ "${MKUPDATE}" = "no" ] && doclean="cleandir"
   1862 	targlist="${doclean} ${doobjs} dependall install"
   1863 	# optimize: for test we build only static libs (3x test speedup)
   1864 	if [ "${1}" = "rumptest" ] ; then
   1865 		setmakeenv NOPIC 1
   1866 		setmakeenv NOPROFILE 1
   1867 	fi
   1868 	for cmd in ${targlist} ; do
   1869 		make_in_dir "${NETBSDSRCDIR}/sys/rump" ${cmd}
   1870 	done
   1871 
   1872 	# if we just wanted to build & install rump, we're done
   1873 	[ "${1}" != "rumptest" ] && return
   1874 
   1875 	${runcmd} cd "${NETBSDSRCDIR}/sys/rump/librump/rumpkern" \
   1876 	    || bomb "cd to rumpkern failed"
   1877 	md_quirks=`${runcmd} "${makewrapper}" -V '${_SYMQUIRK}'`
   1878 	# one little, two little, three little backslashes ...
   1879 	md_quirks="$(echo ${md_quirks} | sed 's,\\,\\\\,g'";s/'//g" )"
   1880 	${runcmd} cd "${TOP}" || bomb "cd to ${TOP} failed"
   1881 	tool_ld=`${runcmd} "${makewrapper}" -V '${LD}'`
   1882 
   1883 	local oIFS="${IFS}"
   1884 	IFS=","
   1885 	for set in ${RUMP_LIBSETS} ; do
   1886 		IFS="${oIFS}"
   1887 		${runcmd} ${tool_ld} -nostdlib -L${DESTDIR}/usr/lib	\
   1888 		    -static --whole-archive ${set} 2>&1 -o /tmp/rumptest.$$ | \
   1889 		      awk -v quirks="${md_quirks}" '
   1890 			/undefined reference/ &&
   1891 			    !/more undefined references.*follow/{
   1892 				if (match($NF,
   1893 				    "`(rumpuser_|__" quirks ")") == 0)
   1894 					fails[NR] = $0
   1895 			}
   1896 			/cannot find -l/{fails[NR] = $0}
   1897 			/cannot open output file/{fails[NR] = $0}
   1898 			END{
   1899 				for (x in fails)
   1900 					print fails[x]
   1901 				exit x!=0
   1902 			}'
   1903 		[ $? -ne 0 ] && bomb "Testlink of rump failed: ${set}"
   1904 	done
   1905 	statusmsg "Rump build&link tests successful"
   1906 }
   1907 
   1908 main()
   1909 {
   1910 	initdefaults
   1911 	_args=$@
   1912 	parseoptions "$@"
   1913 
   1914 	sanitycheck
   1915 
   1916 	build_start=$(date)
   1917 	statusmsg2 "${progname} command:" "$0 $*"
   1918 	statusmsg2 "${progname} started:" "${build_start}"
   1919 	statusmsg2 "NetBSD version:"   "${DISTRIBVER}"
   1920 	statusmsg2 "MACHINE:"          "${MACHINE}"
   1921 	statusmsg2 "MACHINE_ARCH:"     "${MACHINE_ARCH}"
   1922 	statusmsg2 "Build platform:"   "${uname_s} ${uname_r} ${uname_m}"
   1923 	statusmsg2 "HOST_SH:"          "${HOST_SH}"
   1924 
   1925 	rebuildmake
   1926 	validatemakeparams
   1927 	createmakewrapper
   1928 
   1929 	# Perform the operations.
   1930 	#
   1931 	for op in ${operations}; do
   1932 		case "${op}" in
   1933 
   1934 		makewrapper)
   1935 			# no-op
   1936 			;;
   1937 
   1938 		tools)
   1939 			buildtools
   1940 			;;
   1941 
   1942 		sets)
   1943 			statusmsg "Building sets from pre-populated ${DESTDIR}"
   1944 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   1945 			    bomb "Failed to make ${op}"
   1946 			setdir=${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
   1947 			statusmsg "Built sets to ${setdir}"
   1948 			;;
   1949 
   1950 		cleandir|obj|build|distribution|release|sourcesets|syspkgs|params)
   1951 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   1952 			    bomb "Failed to make ${op}"
   1953 			statusmsg "Successful make ${op}"
   1954 			;;
   1955 
   1956 		iso-image|iso-image-source)
   1957 			${runcmd} "${makewrapper}" ${parallel} \
   1958 			    CDEXTRA="$CDEXTRA" ${op} ||
   1959 			    bomb "Failed to make ${op}"
   1960 			statusmsg "Successful make ${op}"
   1961 			;;
   1962 
   1963 		kernel=*)
   1964 			arg=${op#*=}
   1965 			buildkernel "${arg}"
   1966 			;;
   1967 
   1968 		releasekernel=*)
   1969 			arg=${op#*=}
   1970 			releasekernel "${arg}"
   1971 			;;
   1972 
   1973 		modules)
   1974 			buildmodules
   1975 			;;
   1976 
   1977 		installmodules=*)
   1978 			arg=${op#*=}
   1979 			if [ "${arg}" = "/" ] && \
   1980 			    (	[ "${uname_s}" != "NetBSD" ] || \
   1981 				[ "${uname_m}" != "${MACHINE}" ] ); then
   1982 				bomb "'${op}' must != / for cross builds."
   1983 			fi
   1984 			installmodules "${arg}"
   1985 			;;
   1986 
   1987 		install=*)
   1988 			arg=${op#*=}
   1989 			if [ "${arg}" = "/" ] && \
   1990 			    (	[ "${uname_s}" != "NetBSD" ] || \
   1991 				[ "${uname_m}" != "${MACHINE}" ] ); then
   1992 				bomb "'${op}' must != / for cross builds."
   1993 			fi
   1994 			installworld "${arg}"
   1995 			;;
   1996 
   1997 		rump|rumptest)
   1998 			dorump "${op}"
   1999 			;;
   2000 
   2001 		*)
   2002 			bomb "Unknown operation \`${op}'"
   2003 			;;
   2004 
   2005 		esac
   2006 	done
   2007 
   2008 	statusmsg2 "${progname} ended:" "$(date)"
   2009 	if [ -s "${results}" ]; then
   2010 		echo "===> Summary of results:"
   2011 		sed -e 's/^===>//;s/^/	/' "${results}"
   2012 		echo "===> ."
   2013 	fi
   2014 }
   2015 
   2016 main "$@"
   2017