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