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