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