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