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