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