Home | History | Annotate | Line # | Download | only in src
build.sh revision 1.218
      1 #! /usr/bin/env sh
      2 #	$NetBSD: build.sh,v 1.218 2009/11/17 20:49:34 apb Exp $
      3 #
      4 # Copyright (c) 2001-2009 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, for a system containing no tools.
     33 #
     34 # This script should run on any POSIX-compliant shell.  If the
     35 # first "sh" found in the PATH is a POSIX-compliant shell, then
     36 # you should not need to take any special action.  Otherwise, you
     37 # should set the environment variable HOST_SH to a POSIX-compliant
     38 # shell, and invoke build.sh with that shell.  (Depending on your
     39 # system, one of /bin/ksh, /usr/local/bin/bash, or /usr/xpg4/bin/sh
     40 # might be a suitable shell.)
     41 #
     42 
     43 progname=${0##*/}
     44 toppid=$$
     45 results=/dev/null
     46 tab='	'
     47 trap "exit 1" 1 2 3 15
     48 
     49 bomb()
     50 {
     51 	cat >&2 <<ERRORMESSAGE
     52 
     53 ERROR: $@
     54 *** BUILD ABORTED ***
     55 ERRORMESSAGE
     56 	kill ${toppid}		# in case we were invoked from a subshell
     57 	exit 1
     58 }
     59 
     60 
     61 statusmsg()
     62 {
     63 	${runcmd} echo "===> $@" | tee -a "${results}"
     64 }
     65 
     66 warning()
     67 {
     68 	statusmsg "Warning: $@"
     69 }
     70 
     71 # Find a program in the PATH, and print the result.  If not found,
     72 # print a default.  If $2 is defined (even if it is an empty string),
     73 # then that is the default; otherwise, $1 is used as the default.
     74 find_in_PATH()
     75 {
     76 	local prog="$1"
     77 	local result="${2-"$1"}"
     78 	local oldIFS="${IFS}"
     79 	local dir
     80 	IFS=":"
     81 	for dir in ${PATH}; do
     82 		if [ -x "${dir}/${prog}" ]; then
     83 			result="${dir}/${prog}"
     84 			break
     85 		fi
     86 	done
     87 	IFS="${oldIFS}"
     88 	echo "${result}"
     89 }
     90 
     91 # Try to find a working POSIX shell, and set HOST_SH to refer to it.
     92 # Assumes that uname_s, uname_m, and PWD have been set.
     93 set_HOST_SH()
     94 {
     95 	# Even if ${HOST_SH} is already defined, we still do the
     96 	# sanity checks at the end.
     97 
     98 	# Solaris has /usr/xpg4/bin/sh.
     99 	#
    100 	[ -z "${HOST_SH}" ] && [ x"${uname_s}" = x"SunOS" ] && \
    101 		[ -x /usr/xpg4/bin/sh ] && HOST_SH="/usr/xpg4/bin/sh"
    102 
    103 	# Try to get the name of the shell that's running this script,
    104 	# by parsing the output from "ps".  We assume that, if the host
    105 	# system's ps command supports -o comm at all, it will do so
    106 	# in the usual way: a one-line header followed by a one-line
    107 	# result, possibly including trailing white space.  And if the
    108 	# host system's ps command doesn't support -o comm, we assume
    109 	# that we'll get an error message on stderr and nothing on
    110 	# stdout.  (We don't try to use ps -o 'comm=' to suppress the
    111 	# header line, because that is less widely supported.)
    112 	#
    113 	# If we get the wrong result here, the user can override it by
    114 	# specifying HOST_SH in the environment.
    115 	#
    116 	[ -z "${HOST_SH}" ] && HOST_SH="$(
    117 		(ps -p $$ -o comm | sed -ne "2s/[ ${tab}]*\$//p") 2>/dev/null )"
    118 
    119 	# If nothing above worked, use "sh".  We will later find the
    120 	# first directory in the PATH that has a "sh" program.
    121 	#
    122 	[ -z "${HOST_SH}" ] && HOST_SH="sh"
    123 
    124 	# If the result so far is not an absolute path, try to prepend
    125 	# PWD or search the PATH.
    126 	#
    127 	case "${HOST_SH}" in
    128 	/*)	:
    129 		;;
    130 	*/*)	HOST_SH="${PWD}/${HOST_SH}"
    131 		;;
    132 	*)	HOST_SH="$(find_in_PATH "${HOST_SH}")"
    133 		;;
    134 	esac
    135 
    136 	# If we don't have an absolute path by now, bomb.
    137 	#
    138 	case "${HOST_SH}" in
    139 	/*)	:
    140 		;;
    141 	*)	bomb "HOST_SH=\"${HOST_SH}\" is not an absolute path."
    142 		;;
    143 	esac
    144 
    145 	# If HOST_SH is not executable, bomb.
    146 	#
    147 	[ -x "${HOST_SH}" ] ||
    148 	    bomb "HOST_SH=\"${HOST_SH}\" is not executable."
    149 }
    150 
    151 initdefaults()
    152 {
    153 	makeenv=
    154 	makewrapper=
    155 	makewrappermachine=
    156 	runcmd=
    157 	operations=
    158 	removedirs=
    159 
    160 	[ -d usr.bin/make ] || cd "$(dirname $0)"
    161 	[ -d usr.bin/make ] ||
    162 	    bomb "build.sh must be run from the top source level"
    163 	[ -f share/mk/bsd.own.mk ] ||
    164 	    bomb "src/share/mk is missing; please re-fetch the source tree"
    165 
    166 	# Set LC_ALL=C before we try to parse the output from any command
    167 	setmakeenv LC_ALL C
    168 
    169 	# Find information about the build platform.  This should be
    170 	# kept in sync with _HOST_OSNAME, _HOST_OSREL, and _HOST_ARCH
    171 	# variables in share/mk/bsd.sys.mk.
    172 	#
    173 	# Note that "uname -p" is not part of POSIX, but we want uname_p
    174 	# to be set to the host MACHINE_ARCH, if possible.  On systems
    175 	# where "uname -p" fails, prints "unknown", or prints a string
    176 	# that does not look like an identifier, fall back to using the
    177 	# output from "uname -m" instead.
    178 	#
    179 	uname_s=$(uname -s 2>/dev/null)
    180 	uname_r=$(uname -r 2>/dev/null)
    181 	uname_m=$(uname -m 2>/dev/null)
    182 	uname_p=$(uname -p 2>/dev/null || echo "unknown")
    183 	case "${uname_p}" in
    184 	''|unknown|*[^-_A-Za-z0-9]*) uname_p="${uname_m}" ;;
    185 	esac
    186 
    187 	id_u=$(id -u 2>/dev/null || /usr/xpg4/bin/id -u 2>/dev/null)
    188 
    189 	# If $PWD is a valid name of the current directory, POSIX mandates
    190 	# that pwd return it by default which causes problems in the
    191 	# presence of symlinks.  Unsetting PWD is simpler than changing
    192 	# every occurrence of pwd to use -P.
    193 	#
    194 	# XXX Except that doesn't work on Solaris. Or many Linuces.
    195 	#
    196 	unset PWD
    197 	TOP=$(/bin/pwd -P 2>/dev/null || /bin/pwd 2>/dev/null)
    198 
    199 	# The user can set HOST_SH in the environment, or we try to
    200 	# guess an appropriate value.  Then we set several other
    201 	# variables from HOST_SH.
    202 	#
    203 	set_HOST_SH
    204 	setmakeenv HOST_SH "${HOST_SH}"
    205 	setmakeenv BSHELL "${HOST_SH}"
    206 	setmakeenv CONFIG_SHELL "${HOST_SH}"
    207 
    208 	# Set defaults.
    209 	#
    210 	toolprefix=nb
    211 
    212 	# Some systems have a small ARG_MAX.  -X prevents make(1) from
    213 	# exporting variables in the environment redundantly.
    214 	#
    215 	case "${uname_s}" in
    216 	Darwin | FreeBSD | CYGWIN*)
    217 		MAKEFLAGS=-X
    218 		;;
    219 	*)
    220 		MAKEFLAGS=
    221 		;;
    222 	esac
    223 
    224 	# do_{operation}=true if given operation is requested.
    225 	#
    226 	do_expertmode=false
    227 	do_rebuildmake=false
    228 	do_removedirs=false
    229 	do_tools=false
    230 	do_cleandir=false
    231 	do_obj=false
    232 	do_build=false
    233 	do_distribution=false
    234 	do_release=false
    235 	do_kernel=false
    236 	do_releasekernel=false
    237 	do_modules=false
    238 	do_install=false
    239 	do_sets=false
    240 	do_sourcesets=false
    241 	do_syspkgs=false
    242 	do_iso_image=false
    243 	do_iso_image_source=false
    244 	do_params=false
    245 
    246 	# done_{operation}=true if given operation has been done.
    247 	#
    248 	done_rebuildmake=false
    249 
    250 	# Create scratch directory
    251 	#
    252 	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
    253 	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
    254 	trap "cd /; rm -r -f \"${tmpdir}\"" 0
    255 	results="${tmpdir}/build.sh.results"
    256 
    257 	# Set source directories
    258 	#
    259 	setmakeenv NETBSDSRCDIR "${TOP}"
    260 
    261 	# Find the version of NetBSD
    262 	#
    263 	DISTRIBVER="$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh)"
    264 
    265 	# Set the BUILDSEED to NetBSD-"N"
    266 	#
    267 	setmakeenv BUILDSEED "NetBSD-$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh -m)"
    268 
    269 	# Set MKARZERO to "yes"
    270 	#
    271 	setmakeenv MKARZERO "yes"
    272 
    273 	# Set various environment variables to known defaults,
    274 	# to minimize (cross-)build problems observed "in the field".
    275 	#
    276 	unsetmakeenv INFODIR
    277 	unsetmakeenv LESSCHARSET
    278 }
    279 
    280 getarch()
    281 {
    282 	# Translate some MACHINE name aliases (known only to build.sh)
    283 	# into proper MACHINE and MACHINE_ARCH names.  Save the alias
    284 	# name in makewrappermachine.
    285 	#
    286 	case "${MACHINE}" in
    287 
    288 	evbarm-e[bl])
    289 		makewrappermachine=${MACHINE}
    290 		# MACHINE_ARCH is "arm" or "armeb", not "armel"
    291 		MACHINE_ARCH=arm${MACHINE##*-}
    292 		MACHINE_ARCH=${MACHINE_ARCH%el}
    293 		MACHINE=${MACHINE%-e[bl]}
    294 		;;
    295 
    296 	evbmips-e[bl]|sbmips-e[bl])
    297 		makewrappermachine=${MACHINE}
    298 		MACHINE_ARCH=mips${MACHINE##*-}
    299 		MACHINE=${MACHINE%-e[bl]}
    300 		;;
    301 
    302 	evbmips64-e[bl]|sbmips64-e[bl])
    303 		makewrappermachine=${MACHINE}
    304 		MACHINE_ARCH=mips64${MACHINE##*-}
    305 		MACHINE=${MACHINE%64-e[bl]}
    306 		;;
    307 
    308 	evbsh3-e[bl])
    309 		makewrappermachine=${MACHINE}
    310 		MACHINE_ARCH=sh3${MACHINE##*-}
    311 		MACHINE=${MACHINE%-e[bl]}
    312 		;;
    313 
    314 	esac
    315 
    316 	# Translate a MACHINE into a default MACHINE_ARCH.
    317 	#
    318 	case "${MACHINE}" in
    319 
    320 	acorn26|acorn32|cats|hpcarm|iyonix|netwinder|shark|zaurus)
    321 		MACHINE_ARCH=arm
    322 		;;
    323 
    324 	evbarm)		# unspecified MACHINE_ARCH gets LE
    325 		MACHINE_ARCH=${MACHINE_ARCH:=arm}
    326 		;;
    327 
    328 	hp700)
    329 		MACHINE_ARCH=hppa
    330 		;;
    331 
    332 	sun2)
    333 		MACHINE_ARCH=m68000
    334 		;;
    335 
    336 	amiga|atari|cesfic|hp300|luna68k|mac68k|mvme68k|news68k|next68k|sun3|x68k)
    337 		MACHINE_ARCH=m68k
    338 		;;
    339 
    340 	evbmips|sbmips)		# no default MACHINE_ARCH
    341 		;;
    342 
    343 	ews4800mips|mipsco|newsmips|sgimips)
    344 		MACHINE_ARCH=mipseb
    345 		;;
    346 
    347 	algor|arc|cobalt|hpcmips|playstation2|pmax)
    348 		MACHINE_ARCH=mipsel
    349 		;;
    350 
    351 	evbppc64|macppc64|ofppc64)
    352 		makewrappermachine=${MACHINE}
    353 		MACHINE=${MACHINE%64}
    354 		MACHINE_ARCH=powerpc64
    355 		;;
    356 
    357 	amigappc|bebox|evbppc|ibmnws|macppc|mvmeppc|ofppc|prep|rs6000|sandpoint)
    358 		MACHINE_ARCH=powerpc
    359 		;;
    360 
    361 	evbsh3)			# no default MACHINE_ARCH
    362 		;;
    363 
    364 	mmeye)
    365 		MACHINE_ARCH=sh3eb
    366 		;;
    367 
    368 	dreamcast|hpcsh|landisk)
    369 		MACHINE_ARCH=sh3el
    370 		;;
    371 
    372 	amd64)
    373 		MACHINE_ARCH=x86_64
    374 		;;
    375 
    376 	alpha|i386|sparc|sparc64|vax|ia64)
    377 		MACHINE_ARCH=${MACHINE}
    378 		;;
    379 
    380 	*)
    381 		bomb "Unknown target MACHINE: ${MACHINE}"
    382 		;;
    383 
    384 	esac
    385 }
    386 
    387 validatearch()
    388 {
    389 	# Ensure that the MACHINE_ARCH exists (and is supported by build.sh).
    390 	#
    391 	case "${MACHINE_ARCH}" in
    392 
    393 	alpha|arm|armeb|hppa|i386|m68000|m68k|mipse[bl]|mips64e[bl]|powerpc|powerpc64|sh3e[bl]|sparc|sparc64|vax|x86_64|ia64)
    394 		;;
    395 
    396 	"")
    397 		bomb "No MACHINE_ARCH provided"
    398 		;;
    399 
    400 	*)
    401 		bomb "Unknown target MACHINE_ARCH: ${MACHINE_ARCH}"
    402 		;;
    403 
    404 	esac
    405 
    406 	# Determine valid MACHINE_ARCHs for MACHINE
    407 	#
    408 	case "${MACHINE}" in
    409 
    410 	evbarm)
    411 		arches="arm armeb"
    412 		;;
    413 
    414 	evbmips|sbmips)
    415 		arches="mipseb mipsel mips64eb mips64el"
    416 		;;
    417 
    418 	sgimips)
    419 		arches="mipseb mips64eb"
    420 		;;
    421 
    422 	evbsh3)
    423 		arches="sh3eb sh3el"
    424 		;;
    425 
    426 	macppc|evbppc|ofppc)
    427 		arches="powerpc powerpc64"
    428 		;;
    429 	*)
    430 		oma="${MACHINE_ARCH}"
    431 		getarch
    432 		arches="${MACHINE_ARCH}"
    433 		MACHINE_ARCH="${oma}"
    434 		;;
    435 
    436 	esac
    437 
    438 	# Ensure that MACHINE_ARCH supports MACHINE
    439 	#
    440 	archok=false
    441 	for a in ${arches}; do
    442 		if [ "${a}" = "${MACHINE_ARCH}" ]; then
    443 			archok=true
    444 			break
    445 		fi
    446 	done
    447 	${archok} ||
    448 	    bomb "MACHINE_ARCH '${MACHINE_ARCH}' does not support MACHINE '${MACHINE}'"
    449 }
    450 
    451 # nobomb_getmakevar --
    452 # Given the name of a make variable in $1, print make's idea of the
    453 # value of that variable, or return 1 if there's an error.
    454 #
    455 nobomb_getmakevar()
    456 {
    457 	[ -x "${make}" ] || return 1
    458 	"${make}" -m ${TOP}/share/mk -s -B -f- _x_ <<EOF || return 1
    459 _x_:
    460 	echo \${$1}
    461 .include <bsd.prog.mk>
    462 .include <bsd.kernobj.mk>
    463 EOF
    464 }
    465 
    466 # nobomb_getmakevar --
    467 # Given the name of a make variable in $1, print make's idea of the
    468 # value of that variable, or bomb if there's an error.
    469 #
    470 bomb_getmakevar()
    471 {
    472 	[ -x "${make}" ] || bomb "bomb_getmakevar $1: ${make} is not executable"
    473 	nobomb_getmakevar "$1" || bomb "bomb_getmakevar $1: ${make} failed"
    474 }
    475 
    476 # nobomb_getmakevar --
    477 # Given the name of a make variable in $1, print make's idea of the
    478 # value of that variable, or print a literal '$' followed by the
    479 # variable name if ${make} is not executable.  This is intended for use in
    480 # messages that need to be readable even if $make hasn't been built,
    481 # such as when build.sh is run with the "-n" option.
    482 #
    483 getmakevar()
    484 {
    485 	if [ -x "${make}" ]; then
    486 		bomb_getmakevar "$1"
    487 	else
    488 		echo "\$$1"
    489 	fi
    490 }
    491 
    492 setmakeenv()
    493 {
    494 	eval "$1='$2'; export $1"
    495 	makeenv="${makeenv} $1"
    496 }
    497 
    498 unsetmakeenv()
    499 {
    500 	eval "unset $1"
    501 	makeenv="${makeenv} $1"
    502 }
    503 
    504 # Given a variable name in $1, modify the variable in place as follows:
    505 # For each space-separated word in the variable, call resolvepath.
    506 resolvepaths()
    507 {
    508 	local var="$1"
    509 	local val
    510 	eval val=\"\${${var}}\"
    511 	local newval=''
    512 	local word
    513 	for word in ${val}; do
    514 		resolvepath word
    515 		newval="${newval}${newval:+ }${word}"
    516 	done
    517 	eval ${var}=\"\${newval}\"
    518 }
    519 
    520 # Given a variable name in $1, modify the variable in place as follows:
    521 # Convert possibly-relative path to absolute path by prepending
    522 # ${TOP} if necessary.  Also delete trailing "/", if any.
    523 resolvepath()
    524 {
    525 	local var="$1"
    526 	local val
    527 	eval val=\"\${${var}}\"
    528 	case "${val}" in
    529 	/)
    530 		;;
    531 	/*)
    532 		val="${val%/}"
    533 		;;
    534 	*)
    535 		val="${TOP}/${val%/}"
    536 		;;
    537 	esac
    538 	eval ${var}=\"\${val}\"
    539 }
    540 
    541 usage()
    542 {
    543 	if [ -n "$*" ]; then
    544 		echo ""
    545 		echo "${progname}: $*"
    546 	fi
    547 	cat <<_usage_
    548 
    549 Usage: ${progname} [-EnorUux] [-a arch] [-B buildid] [-C cdextras]
    550                 [-D dest] [-j njob] [-M obj] [-m mach] [-N noisy]
    551                 [-O obj] [-R release] [-S seed] [-T tools]
    552                 [-V var=[value]] [-w wrapper] [-X x11src] [-Z var]
    553                 operation [...]
    554 
    555  Build operations (all imply "obj" and "tools"):
    556     build               Run "make build".
    557     distribution        Run "make distribution" (includes DESTDIR/etc/ files).
    558     release             Run "make release" (includes kernels & distrib media).
    559 
    560  Other operations:
    561     help                Show this message and exit.
    562     makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
    563                         Always performed.
    564     cleandir            Run "make cleandir".  [Default unless -u is used]
    565     obj                 Run "make obj".  [Default unless -o is used]
    566     tools               Build and install tools.
    567     install=idir        Run "make installworld" to \`idir' to install all sets
    568                         except \`etc'.  Useful after "distribution" or "release"
    569     kernel=conf         Build kernel with config file \`conf'
    570     releasekernel=conf  Install kernel built by kernel=conf to RELEASEDIR.
    571     modules             Build and install kernel modules.
    572     sets                Create binary sets in
    573                         RELEASEDIR/RELEASEMACHINEDIR/binary/sets.
    574                         DESTDIR should be populated beforehand.
    575     sourcesets          Create source sets in RELEASEDIR/source/sets.
    576     syspkgs             Create syspkgs in
    577                         RELEASEDIR/RELEASEMACHINEDIR/binary/syspkgs.
    578     iso-image           Create CD-ROM image in RELEASEDIR/iso.
    579     iso-image-source    Create CD-ROM image with source in RELEASEDIR/iso.
    580     params              Display various make(1) parameters.
    581 
    582  Options:
    583     -a arch     Set MACHINE_ARCH to arch.  [Default: deduced from MACHINE]
    584     -B buildId  Set BUILDID to buildId.
    585     -C cdextras Append cdextras to CDEXTRA variable for inclusion on CD-ROM.
    586     -D dest     Set DESTDIR to dest.  [Default: destdir.MACHINE]
    587     -E          Set "expert" mode; disables various safety checks.
    588                 Should not be used without expert knowledge of the build system.
    589     -h          Print this help message.
    590     -j njob     Run up to njob jobs in parallel; see make(1) -j.
    591     -M obj      Set obj root directory to obj; sets MAKEOBJDIRPREFIX.
    592                 Unsets MAKEOBJDIR.
    593     -m mach     Set MACHINE to mach; not required if NetBSD native.
    594     -N noisy    Set the noisyness (MAKEVERBOSE) level of the build:
    595                     0   Minimal output ("quiet")
    596                     1   Describe what is occurring
    597                     2   Describe what is occurring and echo the actual command
    598                     3   Ignore the effect of the "@" prefix in make commands
    599                     4   Trace shell commands using the shell's -x flag
    600                 [Default: 2]
    601     -n          Show commands that would be executed, but do not execute them.
    602     -O obj      Set obj root directory to obj; sets a MAKEOBJDIR pattern.
    603                 Unsets MAKEOBJDIRPREFIX.
    604     -o          Set MKOBJDIRS=no; do not create objdirs at start of build.
    605     -R release  Set RELEASEDIR to release.  [Default: releasedir]
    606     -r          Remove contents of TOOLDIR and DESTDIR before building.
    607     -S seed     Set BUILDSEED to seed.  [Default: NetBSD-majorversion]
    608     -T tools    Set TOOLDIR to tools.  If unset, and TOOLDIR is not set in
    609                 the environment, ${toolprefix}make will be (re)built unconditionally.
    610     -U          Set MKUNPRIVED=yes; build without requiring root privileges,
    611                 install from an UNPRIVED build with proper file permissions.
    612     -u          Set MKUPDATE=yes; do not run "make cleandir" first.
    613                 Without this, everything is rebuilt, including the tools.
    614     -V v=[val]  Set variable \`v' to \`val'.
    615     -w wrapper  Create ${toolprefix}make script as wrapper.
    616                 [Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE}]
    617     -X x11src   Set X11SRCDIR to x11src.  [Default: /usr/xsrc]
    618     -x          Set MKX11=yes; build X11 from X11SRCDIR
    619     -Z v        Unset ("zap") variable \`v'.
    620 
    621 _usage_
    622 	exit 1
    623 }
    624 
    625 parseoptions()
    626 {
    627 	opts='a:B:C:D:Ehj:M:m:N:nO:oR:rS:T:UuV:w:xX:Z:'
    628 	opt_a=no
    629 
    630 	if type getopts >/dev/null 2>&1; then
    631 		# Use POSIX getopts.
    632 		#
    633 		getoptcmd='getopts ${opts} opt && opt=-${opt}'
    634 		optargcmd=':'
    635 		optremcmd='shift $((${OPTIND} -1))'
    636 	else
    637 		type getopt >/dev/null 2>&1 ||
    638 		    bomb "/bin/sh shell is too old; try ksh or bash"
    639 
    640 		# Use old-style getopt(1) (doesn't handle whitespace in args).
    641 		#
    642 		args="$(getopt ${opts} $*)"
    643 		[ $? = 0 ] || usage
    644 		set -- ${args}
    645 
    646 		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
    647 		optargcmd='OPTARG="$1"; shift'
    648 		optremcmd=':'
    649 	fi
    650 
    651 	# Parse command line options.
    652 	#
    653 	while eval ${getoptcmd}; do
    654 		case ${opt} in
    655 
    656 		-a)
    657 			eval ${optargcmd}
    658 			MACHINE_ARCH=${OPTARG}
    659 			opt_a=yes
    660 			;;
    661 
    662 		-B)
    663 			eval ${optargcmd}
    664 			BUILDID=${OPTARG}
    665 			;;
    666 
    667 		-C)
    668 			eval ${optargcmd}; resolvepaths OPTARG
    669 			CDEXTRA="${CDEXTRA}${CDEXTRA:+ }${OPTARG}"
    670 			;;
    671 
    672 		-D)
    673 			eval ${optargcmd}; resolvepath OPTARG
    674 			setmakeenv DESTDIR "${OPTARG}"
    675 			;;
    676 
    677 		-E)
    678 			do_expertmode=true
    679 			;;
    680 
    681 		-j)
    682 			eval ${optargcmd}
    683 			parallel="-j ${OPTARG}"
    684 			;;
    685 
    686 		-M)
    687 			eval ${optargcmd}; resolvepath OPTARG
    688 			case "${OPTARG}" in
    689 			\$*)	usage "-M argument must not begin with '$'"
    690 				;;
    691 			*\$*)	# can use resolvepath, but can't set TOP_objdir
    692 				resolvepath OPTARG
    693 				;;
    694 			*)	resolvepath OPTARG
    695 				TOP_objdir="${OPTARG}${TOP}"
    696 				;;
    697 			esac
    698 			unsetmakeenv MAKEOBJDIR
    699 			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
    700 			;;
    701 
    702 			# -m overrides MACHINE_ARCH unless "-a" is specified
    703 		-m)
    704 			eval ${optargcmd}
    705 			MACHINE="${OPTARG}"
    706 			[ "${opt_a}" != "yes" ] && getarch
    707 			;;
    708 
    709 		-N)
    710 			eval ${optargcmd}
    711 			case "${OPTARG}" in
    712 			0|1|2|3|4)
    713 				setmakeenv MAKEVERBOSE "${OPTARG}"
    714 				;;
    715 			*)
    716 				usage "'${OPTARG}' is not a valid value for -N"
    717 				;;
    718 			esac
    719 			;;
    720 
    721 		-n)
    722 			runcmd=echo
    723 			;;
    724 
    725 		-O)
    726 			eval ${optargcmd}
    727 			case "${OPTARG}" in
    728 			*\$*)	usage "-O argument must not contain '$'"
    729 				;;
    730 			*)	resolvepath OPTARG
    731 				TOP_objdir="${OPTARG}"
    732 				;;
    733 			esac
    734 			unsetmakeenv MAKEOBJDIRPREFIX
    735 			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
    736 			;;
    737 
    738 		-o)
    739 			MKOBJDIRS=no
    740 			;;
    741 
    742 		-R)
    743 			eval ${optargcmd}; resolvepath OPTARG
    744 			setmakeenv RELEASEDIR "${OPTARG}"
    745 			;;
    746 
    747 		-r)
    748 			do_removedirs=true
    749 			do_rebuildmake=true
    750 			;;
    751 
    752 		-S)
    753 			eval ${optargcmd}
    754 			setmakeenv BUILDSEED "${OPTARG}"
    755 			;;
    756 
    757 		-T)
    758 			eval ${optargcmd}; resolvepath OPTARG
    759 			TOOLDIR="${OPTARG}"
    760 			export TOOLDIR
    761 			;;
    762 
    763 		-U)
    764 			setmakeenv MKUNPRIVED yes
    765 			;;
    766 
    767 		-u)
    768 			setmakeenv MKUPDATE yes
    769 			;;
    770 
    771 		-V)
    772 			eval ${optargcmd}
    773 			case "${OPTARG}" in
    774 		    # XXX: consider restricting which variables can be changed?
    775 			[a-zA-Z_][a-zA-Z_0-9]*=*)
    776 				setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
    777 				;;
    778 			*)
    779 				usage "-V argument must be of the form 'var=[value]'"
    780 				;;
    781 			esac
    782 			;;
    783 
    784 		-w)
    785 			eval ${optargcmd}; resolvepath OPTARG
    786 			makewrapper="${OPTARG}"
    787 			;;
    788 
    789 		-X)
    790 			eval ${optargcmd}; resolvepath OPTARG
    791 			setmakeenv X11SRCDIR "${OPTARG}"
    792 			;;
    793 
    794 		-x)
    795 			setmakeenv MKX11 yes
    796 			;;
    797 
    798 		-Z)
    799 			eval ${optargcmd}
    800 		    # XXX: consider restricting which variables can be unset?
    801 			unsetmakeenv "${OPTARG}"
    802 			;;
    803 
    804 		--)
    805 			break
    806 			;;
    807 
    808 		-'?'|-h)
    809 			usage
    810 			;;
    811 
    812 		esac
    813 	done
    814 
    815 	# Validate operations.
    816 	#
    817 	eval ${optremcmd}
    818 	while [ $# -gt 0 ]; do
    819 		op=$1; shift
    820 		operations="${operations} ${op}"
    821 
    822 		case "${op}" in
    823 
    824 		help)
    825 			usage
    826 			;;
    827 
    828 		makewrapper|cleandir|obj|tools|build|distribution|release|sets|sourcesets|syspkgs|params)
    829 			;;
    830 
    831 		iso-image)
    832 			op=iso_image	# used as part of a variable name
    833 			;;
    834 
    835 		iso-image-source)
    836 			op=iso_image_source   # used as part of a variable name
    837 			;;
    838 
    839 		kernel=*|releasekernel=*)
    840 			arg=${op#*=}
    841 			op=${op%%=*}
    842 			[ -n "${arg}" ] ||
    843 			    bomb "Must supply a kernel name with \`${op}=...'"
    844 			;;
    845 
    846 		modules)
    847 			op=modules
    848 			;;
    849 
    850 		install=*)
    851 			arg=${op#*=}
    852 			op=${op%%=*}
    853 			[ -n "${arg}" ] ||
    854 			    bomb "Must supply a directory with \`install=...'"
    855 			;;
    856 
    857 		*)
    858 			usage "Unknown operation \`${op}'"
    859 			;;
    860 
    861 		esac
    862 		eval do_${op}=true
    863 	done
    864 	[ -n "${operations}" ] || usage "Missing operation to perform."
    865 
    866 	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
    867 	#
    868 	if [ -z "${MACHINE}" ]; then
    869 		[ "${uname_s}" = "NetBSD" ] ||
    870 		    bomb "MACHINE must be set, or -m must be used, for cross builds."
    871 		MACHINE=${uname_m}
    872 	fi
    873 	[ -n "${MACHINE_ARCH}" ] || getarch
    874 	validatearch
    875 
    876 	# Set up default make(1) environment.
    877 	#
    878 	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
    879 	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
    880 	MAKEFLAGS="-de -m ${TOP}/share/mk ${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
    881 	export MAKEFLAGS MACHINE MACHINE_ARCH
    882 }
    883 
    884 sanitycheck()
    885 {
    886 	# If the PATH contains any non-absolute components (including,
    887 	# but not limited to, "." or ""), then complain.  As an exception,
    888 	# allow "" or "." as the last component of the PATH.  This is fatal
    889 	# if expert mode is not in effect.
    890 	#
    891 	local path="${PATH}"
    892 	path="${path%:}"	# delete trailing ":"
    893 	path="${path%:.}"	# delete trailing ":."
    894 	case ":${path}:/" in
    895 	*:[!/]*)
    896 		if ${do_expertmode}; then
    897 			warning "PATH contains non-absolute components"
    898 		else
    899 			bomb "PATH environment variable must not" \
    900 			     "contain non-absolute components"
    901 		fi
    902 		;;
    903 	esac
    904 }
    905 
    906 # print_tooldir_make --
    907 # Try to find and print a path to an existing
    908 # ${TOOLDIR}/bin/${toolprefix}make, for use by rebuildmake() before a
    909 # new version of ${toolprefix}make has been built.
    910 #
    911 # * If TOOLDIR was set in the environment or on the command line, use
    912 #   that value.
    913 # * Otherwise try to guess what TOOLDIR would be if not overridden by
    914 #   /etc/mk.conf, and check whether the resulting directory contains
    915 #   a copy of ${toolprefix}make (this should work for everybody who
    916 #   doesn't override TOOLDIR via /etc/mk.conf);
    917 # * Failing that, search for ${toolprefix}make, nbmake, bmake, or make,
    918 #   in the PATH (this might accidentally find a non-NetBSD version of
    919 #   make, which will lead to failure in the next step);
    920 # * If a copy of make was found above, try to use it with
    921 #   nobomb_getmakevar to find the correct value for TOOLDIR, and believe the
    922 #   result only if it's a directory that already exists;
    923 # * If a value of TOOLDIR was found above, and if
    924 #   ${TOOLDIR}/bin/${toolprefix}make exists, print that value.
    925 #
    926 print_tooldir_make()
    927 {
    928 	local possible_TOP_OBJ
    929 	local possible_TOOLDIR
    930 	local possible_make
    931 	local tooldir_make
    932 
    933 	if [ -n "${TOOLDIR}" ]; then
    934 		echo "${TOOLDIR}/bin/${toolprefix}make"
    935 		return 0
    936 	fi
    937 
    938 	# Set host_ostype to something like "NetBSD-4.5.6-i386".  This
    939 	# is intended to match the HOST_OSTYPE variable in <bsd.own.mk>.
    940 	#
    941 	local host_ostype="${uname_s}-$(
    942 		echo "${uname_r}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
    943 		)-$(
    944 		echo "${uname_p}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
    945 		)"
    946 
    947 	# Look in a few potential locations for
    948 	# ${possible_TOOLDIR}/bin/${toolprefix}make.
    949 	# If we find it, then set possible_make.
    950 	#
    951 	# In the usual case (without interference from environment
    952 	# variables or /etc/mk.conf), <bsd.own.mk> should set TOOLDIR to
    953 	# "${_SRC_TOP_OBJ_}/tooldir.${host_ostype}".
    954 	#
    955 	# In practice it's difficult to figure out the correct value
    956 	# for _SRC_TOP_OBJ_.  In the easiest case, when the -M or -O
    957 	# options were passed to build.sh, then ${TOP_objdir} will be
    958 	# the correct value.  We also try a few other possibilities, but
    959 	# we do not replicate all the logic of <bsd.obj.mk>.
    960 	#
    961 	for possible_TOP_OBJ in \
    962 		"${TOP_objdir}" \
    963 		"${MAKEOBJDIRPREFIX:+${MAKEOBJDIRPREFIX}${TOP}}" \
    964 		"${TOP}" \
    965 		"${TOP}/obj" \
    966 		"${TOP}/obj.${MACHINE}"
    967 	do
    968 		[ -n "${possible_TOP_OBJ}" ] || continue
    969 		possible_TOOLDIR="${possible_TOP_OBJ}/tooldir.${host_ostype}"
    970 		possible_make="${possible_TOOLDIR}/bin/${toolprefix}make"
    971 		if [ -x "${possible_make}" ]; then
    972 			break
    973 		else
    974 			unset possible_make
    975 		fi
    976 	done
    977 
    978 	# If the above didn't work, search the PATH for a suitable
    979 	# ${toolprefix}make, nbmake, bmake, or make.
    980 	#
    981 	: ${possible_make:=$(find_in_PATH ${toolprefix}make '')}
    982 	: ${possible_make:=$(find_in_PATH nbmake '')}
    983 	: ${possible_make:=$(find_in_PATH bmake '')}
    984 	: ${possible_make:=$(find_in_PATH make '')}
    985 
    986 	# At this point, we don't care whether possible_make is in the
    987 	# correct TOOLDIR or not; we simply want it to be usable by
    988 	# getmakevar to help us find the correct TOOLDIR.
    989 	#
    990 	# Use ${possible_make} with nobomb_getmakevar to try to find
    991 	# the value of TOOLDIR.  Believe the result only if it's
    992 	# a directory that already exists and contains bin/${toolprefix}make.
    993 	#
    994 	if [ -x "${possible_make}" ]; then
    995 		possible_TOOLDIR="$(
    996 			make="${possible_make}" nobomb_getmakevar TOOLDIR
    997 			)"
    998 		if [ $? = 0 ] && [ -n "${possible_TOOLDIR}" ] \
    999 		    && [ -d "${possible_TOOLDIR}" ];
   1000 		then
   1001 			tooldir_make="${possible_TOOLDIR}/bin/${toolprefix}make"
   1002 			if [ -x "${tooldir_make}" ]; then
   1003 				echo "${tooldir_make}"
   1004 				return 0
   1005 			fi
   1006 		fi
   1007 	fi
   1008 	return 1
   1009 }
   1010 
   1011 # rebuildmake --
   1012 # Rebuild nbmake in a temporary directory if necessary.  Sets $make
   1013 # to a path to the nbmake executable.  Sets done_rebuildmake=true
   1014 # if nbmake was rebuilt.
   1015 #
   1016 # There is a cyclic dependency between building nbmake and choosing
   1017 # TOOLDIR: TOOLDIR may be affected by settings in /etc/mk.conf, so we
   1018 # would like to use getmakevar to get the value of TOOLDIR; but we can't
   1019 # use getmakevar before we have an up to date version of nbmake; we
   1020 # might already have an up to date version of nbmake in TOOLDIR, but we
   1021 # don't yet know where TOOLDIR is.
   1022 #
   1023 # The default value of TOOLDIR also depends on the location of the top
   1024 # level object directory, so $(getmakevar TOOLDIR) invoked before or
   1025 # after making the top level object directory may produce different
   1026 # results.
   1027 #
   1028 # Strictly speaking, we should do the following:
   1029 #
   1030 #    1. build a new version of nbmake in a temporary directory;
   1031 #    2. use the temporary nbmake to create the top level obj directory;
   1032 #    3. use $(getmakevar TOOLDIR) with the temporary nbmake to
   1033 #       get the corect value of TOOLDIR;
   1034 #    4. move the temporary nbmake to ${TOOLDIR}/bin/nbmake.
   1035 #
   1036 # However, people don't like building nbmake unnecessarily if their
   1037 # TOOLDIR has not changed since an earlier build.  We try to avoid
   1038 # rebuilding a temporary version of nbmake by taking some shortcuts to
   1039 # guess a value for TOOLDIR, looking for an existing version of nbmake
   1040 # in that TOOLDIR, and checking whether that nbmake is newer than the
   1041 # sources used to build it.
   1042 #
   1043 rebuildmake()
   1044 {
   1045 	make="$(print_tooldir_make)"
   1046 	if [ -n "${make}" ] && [ -x "${make}" ]; then
   1047 		for f in usr.bin/make/*.[ch] usr.bin/make/lst.lib/*.[ch]; do
   1048 			if [ "${f}" -nt "${make}" ]; then
   1049 				statusmsg "${make} outdated" \
   1050 					"(older than ${f}), needs building."
   1051 				do_rebuildmake=true
   1052 				break
   1053 			fi
   1054 		done
   1055 	else
   1056 		statusmsg "No \$TOOLDIR/bin/${toolprefix}make, needs building."
   1057 		do_rebuildmake=true
   1058 	fi
   1059 
   1060 	# Build bootstrap ${toolprefix}make if needed.
   1061 	if ${do_rebuildmake}; then
   1062 		statusmsg "Bootstrapping ${toolprefix}make"
   1063 		${runcmd} cd "${tmpdir}"
   1064 		${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
   1065 			CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
   1066 			${HOST_SH} "${TOP}/tools/make/configure" ||
   1067 		    bomb "Configure of ${toolprefix}make failed"
   1068 		${runcmd} ${HOST_SH} buildmake.sh ||
   1069 		    bomb "Build of ${toolprefix}make failed"
   1070 		make="${tmpdir}/${toolprefix}make"
   1071 		${runcmd} cd "${TOP}"
   1072 		${runcmd} rm -f usr.bin/make/*.o usr.bin/make/lst.lib/*.o
   1073 		done_rebuildmake=true
   1074 	fi
   1075 }
   1076 
   1077 validatemakeparams()
   1078 {
   1079 	if [ "${runcmd}" = "echo" ]; then
   1080 		TOOLCHAIN_MISSING=no
   1081 		EXTERNAL_TOOLCHAIN=""
   1082 	else
   1083 		TOOLCHAIN_MISSING=$(bomb_getmakevar TOOLCHAIN_MISSING)
   1084 		EXTERNAL_TOOLCHAIN=$(bomb_getmakevar EXTERNAL_TOOLCHAIN)
   1085 	fi
   1086 	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
   1087 	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
   1088 		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
   1089 		${runcmd} echo "	MACHINE:      ${MACHINE}"
   1090 		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
   1091 		${runcmd} echo ""
   1092 		${runcmd} echo "All builds for this platform should be done via a traditional make"
   1093 		${runcmd} echo "If you wish to use an external cross-toolchain, set"
   1094 		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
   1095 		${runcmd} echo "in either the environment or mk.conf and rerun"
   1096 		${runcmd} echo "	${progname} $*"
   1097 		exit 1
   1098 	fi
   1099 
   1100 	# Normalise MKOBJDIRS, MKUNPRIVED, and MKUPDATE
   1101 	# These may be set as build.sh options or in "mk.conf".
   1102 	# Don't export them as they're only used for tests in build.sh.
   1103 	#
   1104 	MKOBJDIRS=$(getmakevar MKOBJDIRS)
   1105 	MKUNPRIVED=$(getmakevar MKUNPRIVED)
   1106 	MKUPDATE=$(getmakevar MKUPDATE)
   1107 
   1108 	if [ "${MKOBJDIRS}" != "no" ]; then
   1109 		# Create the top-level object directory.
   1110 		#
   1111 		# "make obj NOSUBDIR=" can handle most cases, but it
   1112 		# can't handle the case where MAKEOBJDIRPREFIX is set
   1113 		# while the corresponding directory does not exist
   1114 		# (rules in <bsd.obj.mk> would abort the build).  We
   1115 		# therefore have to handle the MAKEOBJDIRPREFIX case
   1116 		# without invoking "make obj".  The MAKEOBJDIR case
   1117 		# could be handled either way, but we choose to handle
   1118 		# it similarly to MAKEOBJDIRPREFIX.
   1119 		#
   1120 		if [ -n "${TOP_obj}" ]; then
   1121 			# It must have been set by the "-M" or "-O"
   1122 			# command line options, so there's no need to
   1123 			# use getmakevar
   1124 			:
   1125 		elif [ -n "$MAKEOBJDIRPREFIX" ]; then
   1126 			TOP_obj="$(getmakevar MAKEOBJDIRPREFIX)${TOP}"
   1127 		elif [ -n "$MAKEOBJDIR" ]; then
   1128 			TOP_obj="$(getmakevar MAKEOBJDIR)"
   1129 		fi
   1130 		if [ -n "$TOP_obj" ]; then
   1131 			${runcmd} mkdir -p "${TOP_obj}" ||
   1132 			    bomb "Can't create top level object directory" \
   1133 					"${TOP_obj}"
   1134 		else
   1135 			${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1136 			    bomb "Can't create top level object directory" \
   1137 					"using make obj"
   1138 		fi
   1139 
   1140 		# make obj in tools to ensure that the objdir for "tools"
   1141 		# is available.
   1142 		#
   1143 		${runcmd} cd tools
   1144 		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
   1145 		    bomb "Failed to make obj in tools"
   1146 		${runcmd} cd "${TOP}"
   1147 	fi
   1148 
   1149 	# Find TOOLDIR, DESTDIR, and RELEASEDIR, according to getmakevar,
   1150 	# and bomb if they have changed from the values we had from the
   1151 	# command line or environment.
   1152 	#
   1153 	# This must be done after creating the top-level object directory.
   1154 	#
   1155 	for var in TOOLDIR DESTDIR RELEASEDIR
   1156 	do
   1157 		eval oldval=\"\$${var}\"
   1158 		newval="$(getmakevar $var)"
   1159 		if ! $do_expertmode; then
   1160 			: ${_SRC_TOP_OBJ_:=$(getmakevar _SRC_TOP_OBJ_)}
   1161 			case "$var" in
   1162 			DESTDIR)
   1163 				: ${newval:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
   1164 				makeenv="${makeenv} DESTDIR"
   1165 				;;
   1166 			RELEASEDIR)
   1167 				: ${newval:=${_SRC_TOP_OBJ_}/releasedir}
   1168 				makeenv="${makeenv} RELEASEDIR"
   1169 				;;
   1170 			esac
   1171 		fi
   1172 		if [ -n "$oldval" ] && [ "$oldval" != "$newval" ]; then
   1173 			bomb "Value of ${var} has changed" \
   1174 				"(was \"${oldval}\", now \"${newval}\")"
   1175 		fi
   1176 		eval ${var}=\"\${newval}\"
   1177 		eval export ${var}
   1178 		statusmsg "${var} path:     ${newval}"
   1179 	done
   1180 
   1181 	# RELEASEMACHINEDIR is just a subdir name, e.g. "i386".
   1182 	RELEASEMACHINEDIR=$(getmakevar RELEASEMACHINEDIR)
   1183 
   1184 	# Check validity of TOOLDIR and DESTDIR.
   1185 	#
   1186 	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
   1187 		bomb "TOOLDIR '${TOOLDIR}' invalid"
   1188 	fi
   1189 	removedirs="${TOOLDIR}"
   1190 
   1191 	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
   1192 		if ${do_build} || ${do_distribution} || ${do_release}; then
   1193 			if ! ${do_build} || \
   1194 			   [ "${uname_s}" != "NetBSD" ] || \
   1195 			   [ "${uname_m}" != "${MACHINE}" ]; then
   1196 				bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'."
   1197 			fi
   1198 			if ! ${do_expertmode}; then
   1199 				bomb "DESTDIR must != / for non -E (expert) builds"
   1200 			fi
   1201 			statusmsg "WARNING: Building to /, in expert mode."
   1202 			statusmsg "         This may cause your system to break!  Reasons include:"
   1203 			statusmsg "            - your kernel is not up to date"
   1204 			statusmsg "            - the libraries or toolchain have changed"
   1205 			statusmsg "         YOU HAVE BEEN WARNED!"
   1206 		fi
   1207 	else
   1208 		removedirs="${removedirs} ${DESTDIR}"
   1209 	fi
   1210 	if ${do_build} || ${do_distribution} || ${do_release}; then
   1211 		if ! ${do_expertmode} && \
   1212 		    [ "$id_u" -ne 0 ] && \
   1213 		    [ "${MKUNPRIVED}" = "no" ] ; then
   1214 			bomb "-U or -E must be set for build as an unprivileged user."
   1215 		fi
   1216 	fi
   1217 	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
   1218 		bomb "Must set RELEASEDIR with \`releasekernel=...'"
   1219 	fi
   1220 
   1221 	# Install as non-root is a bad idea.
   1222 	#
   1223 	if ${do_install} && [ "$id_u" -ne 0 ] ; then
   1224 		if ${do_expertmode}; then
   1225 			warning "Will install as an unprivileged user."
   1226 		else
   1227 			bomb "-E must be set for install as an unprivileged user."
   1228 		fi
   1229 	fi
   1230 
   1231 	# If a previous build.sh run used -U (and therefore created a
   1232 	# METALOG file), then most subsequent build.sh runs must also
   1233 	# use -U.  If DESTDIR is about to be removed, then don't perform
   1234 	# this check.
   1235 	#
   1236 	case "${do_removedirs} ${removedirs} " in
   1237 	true*" ${DESTDIR} "*)
   1238 		# DESTDIR is about to be removed
   1239 		;;
   1240 	*)
   1241 		if ( ${do_build} || ${do_distribution} || ${do_release} || \
   1242 		    ${do_install} ) && \
   1243 		    [ -e "${DESTDIR}/METALOG" ] && \
   1244 		    [ "${MKUNPRIVED}" = "no" ] ; then
   1245 			if $do_expertmode; then
   1246 				warning "A previous build.sh run specified -U."
   1247 			else
   1248 				bomb "A previous build.sh run specified -U; you must specify it again now."
   1249 			fi
   1250 		fi
   1251 		;;
   1252 	esac
   1253 }
   1254 
   1255 
   1256 createmakewrapper()
   1257 {
   1258 	# Remove the target directories.
   1259 	#
   1260 	if ${do_removedirs}; then
   1261 		for f in ${removedirs}; do
   1262 			statusmsg "Removing ${f}"
   1263 			${runcmd} rm -r -f "${f}"
   1264 		done
   1265 	fi
   1266 
   1267 	# Recreate $TOOLDIR.
   1268 	#
   1269 	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
   1270 	    bomb "mkdir of '${TOOLDIR}/bin' failed"
   1271 
   1272 	# If we did not previously rebuild ${toolprefix}make, then
   1273 	# check whether $make is still valid and the same as the output
   1274 	# from print_tooldir_make.  If not, then rebuild make now.  A
   1275 	# possible reason for this being necessary is that the actual
   1276 	# value of TOOLDIR might be different from the value guessed
   1277 	# before the top level obj dir was created.
   1278 	#
   1279 	if ! ${done_rebuildmake} && \
   1280 	    ( [ ! -x "$make" ] || [ "$make" != "$(print_tooldir_make)" ] )
   1281 	then
   1282 		rebuildmake
   1283 	fi
   1284 
   1285 	# Install ${toolprefix}make if it was built.
   1286 	#
   1287 	if ${done_rebuildmake}; then
   1288 		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
   1289 		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
   1290 		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
   1291 		make="${TOOLDIR}/bin/${toolprefix}make"
   1292 		statusmsg "Created ${make}"
   1293 	fi
   1294 
   1295 	# Build a ${toolprefix}make wrapper script, usable by hand as
   1296 	# well as by build.sh.
   1297 	#
   1298 	if [ -z "${makewrapper}" ]; then
   1299 		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
   1300 		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
   1301 	fi
   1302 
   1303 	${runcmd} rm -f "${makewrapper}"
   1304 	if [ "${runcmd}" = "echo" ]; then
   1305 		echo 'cat <<EOF >'${makewrapper}
   1306 		makewrapout=
   1307 	else
   1308 		makewrapout=">>\${makewrapper}"
   1309 	fi
   1310 
   1311 	case "${KSH_VERSION:-${SH_VERSION}}" in
   1312 	*PD\ KSH*|*MIRBSD\ KSH*)
   1313 		set +o braceexpand
   1314 		;;
   1315 	esac
   1316 
   1317 	eval cat <<EOF ${makewrapout}
   1318 #! ${HOST_SH}
   1319 # Set proper variables to allow easy "make" building of a NetBSD subtree.
   1320 # Generated from:  \$NetBSD: build.sh,v 1.218 2009/11/17 20:49:34 apb Exp $
   1321 # with these arguments: ${_args}
   1322 #
   1323 
   1324 EOF
   1325 	{
   1326 		for f in ${makeenv}; do
   1327 			if eval "[ -z \"\${$f}\" -a \"\${${f}-X}\" = \"X\" ]"; then
   1328 				eval echo "unset ${f}"
   1329 			else
   1330 				eval echo "${f}=\'\$$(echo ${f})\'\;\ export\ ${f}"
   1331 			fi
   1332 		done
   1333 
   1334 		eval cat <<EOF
   1335 MAKEWRAPPERMACHINE=${makewrappermachine:-${MACHINE}}; export MAKEWRAPPERMACHINE
   1336 USETOOLS=yes; export USETOOLS
   1337 EOF
   1338 	} | eval sort -u "${makewrapout}"
   1339 	eval cat <<EOF "${makewrapout}"
   1340 
   1341 exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
   1342 EOF
   1343 	[ "${runcmd}" = "echo" ] && echo EOF
   1344 	${runcmd} chmod +x "${makewrapper}"
   1345 	statusmsg "makewrapper:      ${makewrapper}"
   1346 	statusmsg "Updated ${makewrapper}"
   1347 }
   1348 
   1349 make_in_dir()
   1350 {
   1351 	dir="$1"
   1352 	op="$2"
   1353 	${runcmd} cd "${dir}" ||
   1354 	    bomb "Failed to cd to \"${dir}\""
   1355 	${runcmd} "${makewrapper}" ${parallel} ${op} ||
   1356 	    bomb "Failed to make ${op} in \"${dir}\""
   1357 	${runcmd} cd "${TOP}" ||
   1358 	    bomb "Failed to cd back to \"${TOP}\""
   1359 }
   1360 
   1361 buildtools()
   1362 {
   1363 	if [ "${MKOBJDIRS}" != "no" ]; then
   1364 		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
   1365 		    bomb "Failed to make obj-tools"
   1366 	fi
   1367 	if [ "${MKUPDATE}" = "no" ]; then
   1368 		make_in_dir tools cleandir
   1369 	fi
   1370 	make_in_dir tools dependall
   1371 	make_in_dir tools install
   1372 	statusmsg "Tools built to ${TOOLDIR}"
   1373 }
   1374 
   1375 getkernelconf()
   1376 {
   1377 	kernelconf="$1"
   1378 	if [ "${MKOBJDIRS}" != "no" ]; then
   1379 		# The correct value of KERNOBJDIR might
   1380 		# depend on a prior "make obj" in
   1381 		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
   1382 		#
   1383 		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
   1384 		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
   1385 		make_in_dir "${KERNSRCDIR}/${KERNARCHDIR}/compile" obj
   1386 	fi
   1387 	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
   1388 	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
   1389 	case "${kernelconf}" in
   1390 	*/*)
   1391 		kernelconfpath="${kernelconf}"
   1392 		kernelconfname="${kernelconf##*/}"
   1393 		;;
   1394 	*)
   1395 		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
   1396 		kernelconfname="${kernelconf}"
   1397 		;;
   1398 	esac
   1399 	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
   1400 }
   1401 
   1402 buildkernel()
   1403 {
   1404 	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
   1405 		# Building tools every time we build a kernel is clearly
   1406 		# unnecessary.  We could try to figure out whether rebuilding
   1407 		# the tools is necessary this time, but it doesn't seem worth
   1408 		# the trouble.  Instead, we say it's the user's responsibility
   1409 		# to rebuild the tools if necessary.
   1410 		#
   1411 		statusmsg "Building kernel without building new tools"
   1412 		buildkernelwarned=true
   1413 	fi
   1414 	getkernelconf $1
   1415 	statusmsg "Building kernel:  ${kernelconf}"
   1416 	statusmsg "Build directory:  ${kernelbuildpath}"
   1417 	${runcmd} mkdir -p "${kernelbuildpath}" ||
   1418 	    bomb "Cannot mkdir: ${kernelbuildpath}"
   1419 	if [ "${MKUPDATE}" = "no" ]; then
   1420 		make_in_dir "${kernelbuildpath}" cleandir
   1421 	fi
   1422 	[ -x "${TOOLDIR}/bin/${toolprefix}config" ] \
   1423 	|| bomb "${TOOLDIR}/bin/${toolprefix}config does not exist. You need to \"$0 tools\" first."
   1424 	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" -b "${kernelbuildpath}" \
   1425 		-s "${TOP}/sys" "${kernelconfpath}" ||
   1426 	    bomb "${toolprefix}config failed for ${kernelconf}"
   1427 	make_in_dir "${kernelbuildpath}" depend
   1428 	make_in_dir "${kernelbuildpath}" all
   1429 
   1430 	if [ "${runcmd}" != "echo" ]; then
   1431 		statusmsg "Kernels built from ${kernelconf}:"
   1432 		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   1433 		for kern in ${kernlist:-netbsd}; do
   1434 			[ -f "${kernelbuildpath}/${kern}" ] && \
   1435 			    echo "  ${kernelbuildpath}/${kern}"
   1436 		done | tee -a "${results}"
   1437 	fi
   1438 }
   1439 
   1440 releasekernel()
   1441 {
   1442 	getkernelconf $1
   1443 	kernelreldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
   1444 	${runcmd} mkdir -p "${kernelreldir}"
   1445 	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
   1446 	for kern in ${kernlist:-netbsd}; do
   1447 		builtkern="${kernelbuildpath}/${kern}"
   1448 		[ -f "${builtkern}" ] || continue
   1449 		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
   1450 		statusmsg "Kernel copy:      ${releasekern}"
   1451 		if [ "${runcmd}" = "echo" ]; then
   1452 			echo "gzip -c -9 < ${builtkern} > ${releasekern}"
   1453 		else
   1454 			gzip -c -9 < "${builtkern}" > "${releasekern}"
   1455 		fi
   1456 	done
   1457 }
   1458 
   1459 buildmodules()
   1460 {
   1461 	if ! ${do_tools} && ! ${buildmoduleswarned:-false}; then
   1462 		# Building tools every time we build modules is clearly
   1463 		# unnecessary as well as a kernel.
   1464 		#
   1465 		statusmsg "Building modules without building new tools"
   1466 		buildmoduleswarned=true
   1467 	fi
   1468 
   1469 	statusmsg "Building kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   1470 	if [ "${MKOBJDIRS}" != "no" ]; then
   1471 		make_in_dir sys/modules obj ||
   1472 		    bomb "Failed to make obj in sys/modules"
   1473 	fi
   1474 	if [ "${MKUPDATE}" = "no" ]; then
   1475 		make_in_dir sys/modules cleandir
   1476 	fi
   1477 	${runcmd} "${makewrapper}" ${parallel} do-sys-modules ||
   1478 	    bomb "Failed to make do-sys-modules"
   1479 
   1480 	statusmsg "Successful build kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
   1481 }
   1482 
   1483 installworld()
   1484 {
   1485 	dir="$1"
   1486 	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
   1487 	    bomb "Failed to make installworld to ${dir}"
   1488 	statusmsg "Successful installworld to ${dir}"
   1489 }
   1490 
   1491 
   1492 main()
   1493 {
   1494 	initdefaults
   1495 	_args=$@
   1496 	parseoptions "$@"
   1497 
   1498 	sanitycheck
   1499 
   1500 	build_start=$(date)
   1501 	statusmsg "${progname} command: $0 $@"
   1502 	statusmsg "${progname} started: ${build_start}"
   1503 	statusmsg "NetBSD version:   ${DISTRIBVER}"
   1504 	statusmsg "MACHINE:          ${MACHINE}"
   1505 	statusmsg "MACHINE_ARCH:     ${MACHINE_ARCH}"
   1506 	statusmsg "Build platform:   ${uname_s} ${uname_r} ${uname_m}"
   1507 	statusmsg "HOST_SH:          ${HOST_SH}"
   1508 
   1509 	rebuildmake
   1510 	validatemakeparams
   1511 	createmakewrapper
   1512 
   1513 	# Perform the operations.
   1514 	#
   1515 	for op in ${operations}; do
   1516 		case "${op}" in
   1517 
   1518 		makewrapper)
   1519 			# no-op
   1520 			;;
   1521 
   1522 		tools)
   1523 			buildtools
   1524 			;;
   1525 
   1526 		sets)
   1527 			statusmsg "Building sets from pre-populated ${DESTDIR}"
   1528 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   1529 			    bomb "Failed to make ${op}"
   1530 			setdir=${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
   1531 			statusmsg "Built sets to ${setdir}"
   1532 			;;
   1533 
   1534 		cleandir|obj|build|distribution|release|sourcesets|syspkgs|params)
   1535 			${runcmd} "${makewrapper}" ${parallel} ${op} ||
   1536 			    bomb "Failed to make ${op}"
   1537 			statusmsg "Successful make ${op}"
   1538 			;;
   1539 
   1540 		iso-image|iso-image-source)
   1541 			${runcmd} "${makewrapper}" ${parallel} \
   1542 			    CDEXTRA="$CDEXTRA" ${op} ||
   1543 			    bomb "Failed to make ${op}"
   1544 			statusmsg "Successful make ${op}"
   1545 			;;
   1546 
   1547 		kernel=*)
   1548 			arg=${op#*=}
   1549 			buildkernel "${arg}"
   1550 			;;
   1551 
   1552 		releasekernel=*)
   1553 			arg=${op#*=}
   1554 			releasekernel "${arg}"
   1555 			;;
   1556 
   1557 		modules)
   1558 			buildmodules
   1559 			;;
   1560 
   1561 		install=*)
   1562 			arg=${op#*=}
   1563 			if [ "${arg}" = "/" ] && \
   1564 			    (	[ "${uname_s}" != "NetBSD" ] || \
   1565 				[ "${uname_m}" != "${MACHINE}" ] ); then
   1566 				bomb "'${op}' must != / for cross builds."
   1567 			fi
   1568 			installworld "${arg}"
   1569 			;;
   1570 
   1571 		*)
   1572 			bomb "Unknown operation \`${op}'"
   1573 			;;
   1574 
   1575 		esac
   1576 	done
   1577 
   1578 	statusmsg "${progname} ended:   $(date)"
   1579 	if [ -s "${results}" ]; then
   1580 		echo "===> Summary of results:"
   1581 		sed -e 's/^===>//;s/^/	/' "${results}"
   1582 		echo "===> ."
   1583 	fi
   1584 }
   1585 
   1586 main "$@"
   1587