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