1#! /usr/bin/env sh
2#	$NetBSD: build.sh,v 1.253.2.1 2012/03/02 16:48:10 riz Exp $
3#
4# Copyright (c) 2001-2011 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, to build or cross-build NetBSD.
33#
34
35#
36# {{{ Begin shell feature tests.
37#
38# We try to determine whether or not this script is being run under
39# a shell that supports the features that we use.  If not, we try to
40# re-exec the script under another shell.  If we can't find another
41# suitable shell, then we print a message and exit.
42#
43
44errmsg=''		# error message, if not empty
45shelltest=false		# if true, exit after testing the shell
46re_exec_allowed=true	# if true, we may exec under another shell
47
48# Parse special command line options in $1.  These special options are
49# for internal use only, are not documented, and are not valid anywhere
50# other than $1.
51case "$1" in
52"--shelltest")
53    shelltest=true
54    re_exec_allowed=false
55    shift
56    ;;
57"--no-re-exec")
58    re_exec_allowed=false
59    shift
60    ;;
61esac
62
63# Solaris /bin/sh, and other SVR4 shells, do not support "!".
64# This is the first feature that we test, because subsequent
65# tests use "!".
66#
67if test -z "$errmsg"; then
68    if ( eval '! false' ) >/dev/null 2>&1 ; then
69	:
70    else
71	errmsg='Shell does not support "!".'
72    fi
73fi
74
75# Does the shell support functions?
76#
77if test -z "$errmsg"; then
78    if ! (
79	eval 'somefunction() { : ; }'
80	) >/dev/null 2>&1
81    then
82	errmsg='Shell does not support functions.'
83    fi
84fi
85
86# Does the shell support the "local" keyword for variables in functions?
87#
88# Local variables are not required by SUSv3, but some scripts run during
89# the NetBSD build use them.
90#
91# ksh93 fails this test; it uses an incompatible syntax involving the
92# keywords 'function' and 'typeset'.
93#
94if test -z "$errmsg"; then
95    if ! (
96	eval 'f() { local v=2; }; v=1; f && test x"$v" = x"1"'
97	) >/dev/null 2>&1
98    then
99	errmsg='Shell does not support the "local" keyword in functions.'
100    fi
101fi
102
103# Does the shell support ${var%suffix}, ${var#prefix}, and their variants?
104#
105# We don't bother testing for ${var+value}, ${var-value}, or their variants,
106# since shells without those are sure to fail other tests too.
107#
108if test -z "$errmsg"; then
109    if ! (
110	eval 'var=a/b/c ;
111	      test x"${var#*/};${var##*/};${var%/*};${var%%/*}" = \
112		   x"b/c;c;a/b;a" ;'
113	) >/dev/null 2>&1
114    then
115	errmsg='Shell does not support "${var%suffix}" or "${var#prefix}".'
116    fi
117fi
118
119# Does the shell support IFS?
120#
121# zsh in normal mode (as opposed to "emulate sh" mode) fails this test.
122#
123if test -z "$errmsg"; then
124    if ! (
125	eval 'IFS=: ; v=":a b::c" ; set -- $v ; IFS=+ ;
126		test x"$#;$1,$2,$3,$4;$*" = x"4;,a b,,c;+a b++c"'
127	) >/dev/null 2>&1
128    then
129	errmsg='Shell does not support IFS word splitting.'
130    fi
131fi
132
133# Does the shell support ${1+"$@"}?
134#
135# Some versions of zsh fail this test, even in "emulate sh" mode.
136#
137if test -z "$errmsg"; then
138    if ! (
139	eval 'set -- "a a a" "b b b"; set -- ${1+"$@"};
140	      test x"$#;$1;$2" = x"2;a a a;b b b";'
141	) >/dev/null 2>&1
142    then
143	errmsg='Shell does not support ${1+"$@"}.'
144    fi
145fi
146
147# Does the shell support $(...) command substitution?
148#
149if test -z "$errmsg"; then
150    if ! (
151	eval 'var=$(echo abc); test x"$var" = x"abc"'
152	) >/dev/null 2>&1
153    then
154	errmsg='Shell does not support "$(...)" command substitution.'
155    fi
156fi
157
158# Does the shell support $(...) command substitution with
159# unbalanced parentheses?
160#
161# Some shells known to fail this test are:  NetBSD /bin/ksh (as of 2009-12),
162# bash-3.1, pdksh-5.2.14, zsh-4.2.7 in "emulate sh" mode.
163#
164if test -z "$errmsg"; then
165    if ! (
166	eval 'var=$(case x in x) echo abc;; esac); test x"$var" = x"abc"'
167	) >/dev/null 2>&1
168    then
169	# XXX: This test is ignored because so many shells fail it; instead,
170	#      the NetBSD build avoids using the problematic construct.
171	: ignore 'Shell does not support "$(...)" with unbalanced ")".'
172    fi
173fi
174
175# Does the shell support getopts or getopt?
176#
177if test -z "$errmsg"; then
178    if ! (
179	eval 'type getopts || type getopt'
180	) >/dev/null 2>&1
181    then
182	errmsg='Shell does not support getopts or getopt.'
183    fi
184fi
185
186#
187# If shelltest is true, exit now, reporting whether or not the shell is good.
188#
189if $shelltest; then
190    if test -n "$errmsg"; then
191	echo >&2 "$0: $errmsg"
192	exit 1
193    else
194	exit 0
195    fi
196fi
197
198#
199# If the shell was bad, try to exec a better shell, or report an error.
200#
201# Loops are broken by passing an extra "--no-re-exec" flag to the new
202# instance of this script.
203#
204if test -n "$errmsg"; then
205    if $re_exec_allowed; then
206	for othershell in \
207	    "${HOST_SH}" /usr/xpg4/bin/sh ksh ksh88 mksh pdksh bash dash
208	    # NOTE: some shells known not to work are:
209	    # any shell using csh syntax;
210	    # Solaris /bin/sh (missing many modern features);
211	    # ksh93 (incompatible syntax for local variables);
212	    # zsh (many differences, unless run in compatibility mode).
213	do
214	    test -n "$othershell" || continue
215	    if eval 'type "$othershell"' >/dev/null 2>&1 \
216		&& "$othershell" "$0" --shelltest >/dev/null 2>&1
217	    then
218		cat <<EOF
219$0: $errmsg
220$0: Retrying under $othershell
221EOF
222		HOST_SH="$othershell"
223		export HOST_SH
224		exec $othershell "$0" --no-re-exec "$@" # avoid ${1+"$@"}
225	    fi
226	    # If HOST_SH was set, but failed the test above,
227	    # then give up without trying any other shells.
228	    test x"${othershell}" = x"${HOST_SH}" && break
229	done
230    fi
231
232    #
233    # If we get here, then the shell is bad, and we either could not
234    # find a replacement, or were not allowed to try a replacement.
235    #
236    cat <<EOF
237$0: $errmsg
238
239The NetBSD build system requires a shell that supports modern POSIX
240features, as well as the "local" keyword in functions (which is a
241widely-implemented but non-standardised feature).
242
243Please re-run this script under a suitable shell.  For example:
244
245	/path/to/suitable/shell $0 ...
246
247The above command will usually enable build.sh to automatically set
248HOST_SH=/path/to/suitable/shell, but if that fails, then you may also
249need to explicitly set the HOST_SH environment variable, as follows:
250
251	HOST_SH=/path/to/suitable/shell
252	export HOST_SH
253	\${HOST_SH} $0 ...
254EOF
255    exit 1
256fi
257
258#
259# }}} End shell feature tests.
260#
261
262progname=${0##*/}
263toppid=$$
264results=/dev/null
265tab='	'
266trap "exit 1" 1 2 3 15
267
268bomb()
269{
270	cat >&2 <<ERRORMESSAGE
271
272ERROR: $@
273*** BUILD ABORTED ***
274ERRORMESSAGE
275	kill ${toppid}		# in case we were invoked from a subshell
276	exit 1
277}
278
279
280statusmsg()
281{
282	${runcmd} echo "===> $@" | tee -a "${results}"
283}
284
285statusmsg2()
286{
287	local msg
288
289	msg="${1}"
290	shift
291	case "${msg}" in
292	????????????????*)	;;
293	??????????*)		msg="${msg}      ";;
294	?????*)			msg="${msg}           ";;
295	*)			msg="${msg}                ";;
296	esac
297	case "${msg}" in
298	?????????????????????*)	;;
299	????????????????????)	msg="${msg} ";;
300	???????????????????)	msg="${msg}  ";;
301	??????????????????)	msg="${msg}   ";;
302	?????????????????)	msg="${msg}    ";;
303	????????????????)	msg="${msg}     ";;
304	esac
305	statusmsg "${msg}$*"
306}
307
308warning()
309{
310	statusmsg "Warning: $@"
311}
312
313# Find a program in the PATH, and print the result.  If not found,
314# print a default.  If $2 is defined (even if it is an empty string),
315# then that is the default; otherwise, $1 is used as the default.
316find_in_PATH()
317{
318	local prog="$1"
319	local result="${2-"$1"}"
320	local oldIFS="${IFS}"
321	local dir
322	IFS=":"
323	for dir in ${PATH}; do
324		if [ -x "${dir}/${prog}" ]; then
325			result="${dir}/${prog}"
326			break
327		fi
328	done
329	IFS="${oldIFS}"
330	echo "${result}"
331}
332
333# Try to find a working POSIX shell, and set HOST_SH to refer to it.
334# Assumes that uname_s, uname_m, and PWD have been set.
335set_HOST_SH()
336{
337	# Even if ${HOST_SH} is already defined, we still do the
338	# sanity checks at the end.
339
340	# Solaris has /usr/xpg4/bin/sh.
341	#
342	[ -z "${HOST_SH}" ] && [ x"${uname_s}" = x"SunOS" ] && \
343		[ -x /usr/xpg4/bin/sh ] && HOST_SH="/usr/xpg4/bin/sh"
344
345	# Try to get the name of the shell that's running this script,
346	# by parsing the output from "ps".  We assume that, if the host
347	# system's ps command supports -o comm at all, it will do so
348	# in the usual way: a one-line header followed by a one-line
349	# result, possibly including trailing white space.  And if the
350	# host system's ps command doesn't support -o comm, we assume
351	# that we'll get an error message on stderr and nothing on
352	# stdout.  (We don't try to use ps -o 'comm=' to suppress the
353	# header line, because that is less widely supported.)
354	#
355	# If we get the wrong result here, the user can override it by
356	# specifying HOST_SH in the environment.
357	#
358	[ -z "${HOST_SH}" ] && HOST_SH="$(
359		(ps -p $$ -o comm | sed -ne "2s/[ ${tab}]*\$//p") 2>/dev/null )"
360
361	# If nothing above worked, use "sh".  We will later find the
362	# first directory in the PATH that has a "sh" program.
363	#
364	[ -z "${HOST_SH}" ] && HOST_SH="sh"
365
366	# If the result so far is not an absolute path, try to prepend
367	# PWD or search the PATH.
368	#
369	case "${HOST_SH}" in
370	/*)	:
371		;;
372	*/*)	HOST_SH="${PWD}/${HOST_SH}"
373		;;
374	*)	HOST_SH="$(find_in_PATH "${HOST_SH}")"
375		;;
376	esac
377
378	# If we don't have an absolute path by now, bomb.
379	#
380	case "${HOST_SH}" in
381	/*)	:
382		;;
383	*)	bomb "HOST_SH=\"${HOST_SH}\" is not an absolute path."
384		;;
385	esac
386
387	# If HOST_SH is not executable, bomb.
388	#
389	[ -x "${HOST_SH}" ] ||
390	    bomb "HOST_SH=\"${HOST_SH}\" is not executable."
391
392	# If HOST_SH fails tests, bomb.
393	# ("$0" may be a path that is no longer valid, because we have
394	# performed "cd $(dirname $0)", so don't use $0 here.)
395	#
396	"${HOST_SH}" build.sh --shelltest ||
397	    bomb "HOST_SH=\"${HOST_SH}\" failed functionality tests."
398}
399
400# initdefaults --
401# Set defaults before parsing command line options.
402#
403initdefaults()
404{
405	makeenv=
406	makewrapper=
407	makewrappermachine=
408	runcmd=
409	operations=
410	removedirs=
411
412	[ -d usr.bin/make ] || cd "$(dirname $0)"
413	[ -d usr.bin/make ] ||
414	    bomb "build.sh must be run from the top source level"
415	[ -f share/mk/bsd.own.mk ] ||
416	    bomb "src/share/mk is missing; please re-fetch the source tree"
417
418	# Set various environment variables to known defaults,
419	# to minimize (cross-)build problems observed "in the field".
420	#
421	# LC_ALL=C must be set before we try to parse the output from
422	# any command.  Other variables are set (or unset) here, before
423	# we parse command line arguments.
424	#
425	# These variables can be overridden via "-V var=value" if
426	# you know what you are doing.
427	#
428	unsetmakeenv INFODIR
429	unsetmakeenv LESSCHARSET
430	unsetmakeenv MAKEFLAGS
431	setmakeenv LC_ALL C
432
433	# Find information about the build platform.  This should be
434	# kept in sync with _HOST_OSNAME, _HOST_OSREL, and _HOST_ARCH
435	# variables in share/mk/bsd.sys.mk.
436	#
437	# Note that "uname -p" is not part of POSIX, but we want uname_p
438	# to be set to the host MACHINE_ARCH, if possible.  On systems
439	# where "uname -p" fails, prints "unknown", or prints a string
440	# that does not look like an identifier, fall back to using the
441	# output from "uname -m" instead.
442	#
443	uname_s=$(uname -s 2>/dev/null)
444	uname_r=$(uname -r 2>/dev/null)
445	uname_m=$(uname -m 2>/dev/null)
446	uname_p=$(uname -p 2>/dev/null || echo "unknown")
447	case "${uname_p}" in
448	''|unknown|*[^-_A-Za-z0-9]*) uname_p="${uname_m}" ;;
449	esac
450
451	id_u=$(id -u 2>/dev/null || /usr/xpg4/bin/id -u 2>/dev/null)
452
453	# If $PWD is a valid name of the current directory, POSIX mandates
454	# that pwd return it by default which causes problems in the
455	# presence of symlinks.  Unsetting PWD is simpler than changing
456	# every occurrence of pwd to use -P.
457	#
458	# XXX Except that doesn't work on Solaris. Or many Linuces.
459	#
460	unset PWD
461	TOP=$(/bin/pwd -P 2>/dev/null || /bin/pwd 2>/dev/null)
462
463	# The user can set HOST_SH in the environment, or we try to
464	# guess an appropriate value.  Then we set several other
465	# variables from HOST_SH.
466	#
467	set_HOST_SH
468	setmakeenv HOST_SH "${HOST_SH}"
469	setmakeenv BSHELL "${HOST_SH}"
470	setmakeenv CONFIG_SHELL "${HOST_SH}"
471
472	# Set defaults.
473	#
474	toolprefix=nb
475
476	# Some systems have a small ARG_MAX.  -X prevents make(1) from
477	# exporting variables in the environment redundantly.
478	#
479	case "${uname_s}" in
480	Darwin | FreeBSD | CYGWIN*)
481		MAKEFLAGS="-X ${MAKEFLAGS}"
482		;;
483	esac
484
485	# do_{operation}=true if given operation is requested.
486	#
487	do_expertmode=false
488	do_rebuildmake=false
489	do_removedirs=false
490	do_tools=false
491	do_cleandir=false
492	do_obj=false
493	do_build=false
494	do_distribution=false
495	do_release=false
496	do_kernel=false
497	do_releasekernel=false
498	do_modules=false
499	do_installmodules=false
500	do_install=false
501	do_sets=false
502	do_sourcesets=false
503	do_syspkgs=false
504	do_iso_image=false
505	do_iso_image_source=false
506	do_live_image=false
507	do_install_image=false
508	do_params=false
509	do_rump=false
510
511	# done_{operation}=true if given operation has been done.
512	#
513	done_rebuildmake=false
514
515	# Create scratch directory
516	#
517	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
518	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
519	trap "cd /; rm -r -f \"${tmpdir}\"" 0
520	results="${tmpdir}/build.sh.results"
521
522	# Set source directories
523	#
524	setmakeenv NETBSDSRCDIR "${TOP}"
525
526	# Make sure KERNOBJDIR is an absolute path if defined
527	#
528	case "${KERNOBJDIR}" in
529	''|/*)	;;
530	*)	KERNOBJDIR="${TOP}/${KERNOBJDIR}"
531		setmakeenv KERNOBJDIR "${KERNOBJDIR}"
532		;;
533	esac
534
535	# Find the version of NetBSD
536	#
537	DISTRIBVER="$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh)"
538
539	# Set the BUILDSEED to NetBSD-"N"
540	#
541	setmakeenv BUILDSEED "NetBSD-$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh -m)"
542
543	# Set MKARZERO to "yes"
544	#
545	setmakeenv MKARZERO "yes"
546
547}
548
549getarch()
550{
551	# Translate some MACHINE name aliases (known only to build.sh)
552	# into proper MACHINE and MACHINE_ARCH names.  Save the alias
553	# name in makewrappermachine.
554	#
555	case "${MACHINE}" in
556
557	evbarm-e[bl])
558		makewrappermachine=${MACHINE}
559		# MACHINE_ARCH is "arm" or "armeb", not "armel"
560		MACHINE_ARCH=arm${MACHINE##*-}
561		MACHINE_ARCH=${MACHINE_ARCH%el}
562		MACHINE=${MACHINE%-e[bl]}
563		;;
564
565	evbmips-e[bl]|sbmips-e[bl])
566		makewrappermachine=${MACHINE}
567		MACHINE_ARCH=mips${MACHINE##*-}
568		MACHINE=${MACHINE%-e[bl]}
569		;;
570
571	evbmips64-e[bl]|sbmips64-e[bl])
572		makewrappermachine=${MACHINE}
573		MACHINE_ARCH=mips64${MACHINE##*-}
574		MACHINE=${MACHINE%64-e[bl]}
575		;;
576
577	evbsh3-e[bl])
578		makewrappermachine=${MACHINE}
579		MACHINE_ARCH=sh3${MACHINE##*-}
580		MACHINE=${MACHINE%-e[bl]}
581		;;
582
583	esac
584
585	# Translate a MACHINE into a default MACHINE_ARCH.
586	#
587	case "${MACHINE}" in
588
589	acorn26|acorn32|cats|hpcarm|iyonix|netwinder|shark|zaurus)
590		MACHINE_ARCH=arm
591		;;
592
593	evbarm)		# unspecified MACHINE_ARCH gets LE
594		MACHINE_ARCH=${MACHINE_ARCH:=arm}
595		;;
596
597	hp700)
598		MACHINE_ARCH=hppa
599		;;
600
601	sun2)
602		MACHINE_ARCH=m68000
603		;;
604
605	amiga|atari|cesfic|hp300|luna68k|mac68k|mvme68k|news68k|next68k|sun3|x68k)
606		MACHINE_ARCH=m68k
607		;;
608
609	evbmips|sbmips)		# no default MACHINE_ARCH
610		;;
611
612	sgimips64)
613		makewrappermachine=${MACHINE}
614		MACHINE=${MACHINE%64}
615		MACHINE_ARCH=mips64eb
616		;;
617
618	ews4800mips|mipsco|newsmips|sgimips|emips)
619		MACHINE_ARCH=mipseb
620		;;
621
622	algor64|arc64|cobalt64|pmax64)
623		makewrappermachine=${MACHINE}
624		MACHINE=${MACHINE%64}
625		MACHINE_ARCH=mips64el
626		;;
627
628	algor|arc|cobalt|hpcmips|pmax)
629		MACHINE_ARCH=mipsel
630		;;
631
632	evbppc64|macppc64|ofppc64)
633		makewrappermachine=${MACHINE}
634		MACHINE=${MACHINE%64}
635		MACHINE_ARCH=powerpc64
636		;;
637
638	amigappc|bebox|evbppc|ibmnws|macppc|mvmeppc|ofppc|prep|rs6000|sandpoint)
639		MACHINE_ARCH=powerpc
640		;;
641
642	evbsh3)			# no default MACHINE_ARCH
643		;;
644
645	mmeye)
646		MACHINE_ARCH=sh3eb
647		;;
648
649	dreamcast|hpcsh|landisk)
650		MACHINE_ARCH=sh3el
651		;;
652
653	amd64)
654		MACHINE_ARCH=x86_64
655		;;
656
657	alpha|i386|sparc|sparc64|vax|ia64)
658		MACHINE_ARCH=${MACHINE}
659		;;
660
661	*)
662		bomb "Unknown target MACHINE: ${MACHINE}"
663		;;
664
665	esac
666}
667
668validatearch()
669{
670	# Ensure that the MACHINE_ARCH exists (and is supported by build.sh).
671	#
672	case "${MACHINE_ARCH}" in
673
674	alpha|arm|armeb|hppa|i386|m68000|m68k|mipse[bl]|mips64e[bl]|powerpc|powerpc64|sh3e[bl]|sparc|sparc64|vax|x86_64|ia64)
675		;;
676
677	"")
678		bomb "No MACHINE_ARCH provided"
679		;;
680
681	*)
682		bomb "Unknown target MACHINE_ARCH: ${MACHINE_ARCH}"
683		;;
684
685	esac
686
687	# Determine valid MACHINE_ARCHs for MACHINE
688	#
689	case "${MACHINE}" in
690
691	evbarm)
692		arches="arm armeb"
693		;;
694
695	algor|arc|cobalt|pmax)
696		arches="mipsel mips64el"
697		;;
698
699	evbmips|sbmips)
700		arches="mipseb mipsel mips64eb mips64el"
701		;;
702
703	sgimips)
704		arches="mipseb mips64eb"
705		;;
706
707	evbsh3)
708		arches="sh3eb sh3el"
709		;;
710
711	macppc|evbppc|ofppc)
712		arches="powerpc powerpc64"
713		;;
714	*)
715		oma="${MACHINE_ARCH}"
716		getarch
717		arches="${MACHINE_ARCH}"
718		MACHINE_ARCH="${oma}"
719		;;
720
721	esac
722
723	# Ensure that MACHINE_ARCH supports MACHINE
724	#
725	archok=false
726	for a in ${arches}; do
727		if [ "${a}" = "${MACHINE_ARCH}" ]; then
728			archok=true
729			break
730		fi
731	done
732	${archok} ||
733	    bomb "MACHINE_ARCH '${MACHINE_ARCH}' does not support MACHINE '${MACHINE}'"
734}
735
736# nobomb_getmakevar --
737# Given the name of a make variable in $1, print make's idea of the
738# value of that variable, or return 1 if there's an error.
739#
740nobomb_getmakevar()
741{
742	[ -x "${make}" ] || return 1
743	"${make}" -m ${TOP}/share/mk -s -B -f- _x_ <<EOF || return 1
744_x_:
745	echo \${$1}
746.include <bsd.prog.mk>
747.include <bsd.kernobj.mk>
748EOF
749}
750
751# bomb_getmakevar --
752# Given the name of a make variable in $1, print make's idea of the
753# value of that variable, or bomb if there's an error.
754#
755bomb_getmakevar()
756{
757	[ -x "${make}" ] || bomb "bomb_getmakevar $1: ${make} is not executable"
758	nobomb_getmakevar "$1" || bomb "bomb_getmakevar $1: ${make} failed"
759}
760
761# getmakevar --
762# Given the name of a make variable in $1, print make's idea of the
763# value of that variable, or print a literal '$' followed by the
764# variable name if ${make} is not executable.  This is intended for use in
765# messages that need to be readable even if $make hasn't been built,
766# such as when build.sh is run with the "-n" option.
767#
768getmakevar()
769{
770	if [ -x "${make}" ]; then
771		bomb_getmakevar "$1"
772	else
773		echo "\$$1"
774	fi
775}
776
777setmakeenv()
778{
779	eval "$1='$2'; export $1"
780	makeenv="${makeenv} $1"
781}
782
783unsetmakeenv()
784{
785	eval "unset $1"
786	makeenv="${makeenv} $1"
787}
788
789# Given a variable name in $1, modify the variable in place as follows:
790# For each space-separated word in the variable, call resolvepath.
791resolvepaths()
792{
793	local var="$1"
794	local val
795	eval val=\"\${${var}}\"
796	local newval=''
797	local word
798	for word in ${val}; do
799		resolvepath word
800		newval="${newval}${newval:+ }${word}"
801	done
802	eval ${var}=\"\${newval}\"
803}
804
805# Given a variable name in $1, modify the variable in place as follows:
806# Convert possibly-relative path to absolute path by prepending
807# ${TOP} if necessary.  Also delete trailing "/", if any.
808resolvepath()
809{
810	local var="$1"
811	local val
812	eval val=\"\${${var}}\"
813	case "${val}" in
814	/)
815		;;
816	/*)
817		val="${val%/}"
818		;;
819	*)
820		val="${TOP}/${val%/}"
821		;;
822	esac
823	eval ${var}=\"\${val}\"
824}
825
826usage()
827{
828	if [ -n "$*" ]; then
829		echo ""
830		echo "${progname}: $*"
831	fi
832	cat <<_usage_
833
834Usage: ${progname} [-EhnorUuxy] [-a arch] [-B buildid] [-C cdextras]
835                [-D dest] [-j njob] [-M obj] [-m mach] [-N noisy]
836                [-O obj] [-R release] [-S seed] [-T tools]
837                [-V var=[value]] [-w wrapper] [-X x11src] [-Y extsrcsrc]
838                [-Z var]
839                operation [...]
840
841 Build operations (all imply "obj" and "tools"):
842    build               Run "make build".
843    distribution        Run "make distribution" (includes DESTDIR/etc/ files).
844    release             Run "make release" (includes kernels & distrib media).
845
846 Other operations:
847    help                Show this message and exit.
848    makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
849                        Always performed.
850    cleandir            Run "make cleandir".  [Default unless -u is used]
851    obj                 Run "make obj".  [Default unless -o is used]
852    tools               Build and install tools.
853    install=idir        Run "make installworld" to \`idir' to install all sets
854                        except \`etc'.  Useful after "distribution" or "release"
855    kernel=conf         Build kernel with config file \`conf'
856    releasekernel=conf  Install kernel built by kernel=conf to RELEASEDIR.
857    installmodules=idir Run "make installmodules" to \`idir' to install all
858                        kernel modules.
859    modules             Build kernel modules.
860    rumptest            Do a linktest for rump (for developers).
861    sets                Create binary sets in
862                        RELEASEDIR/RELEASEMACHINEDIR/binary/sets.
863                        DESTDIR should be populated beforehand.
864    sourcesets          Create source sets in RELEASEDIR/source/sets.
865    syspkgs             Create syspkgs in
866                        RELEASEDIR/RELEASEMACHINEDIR/binary/syspkgs.
867    iso-image           Create CD-ROM image in RELEASEDIR/iso.
868    iso-image-source    Create CD-ROM image with source in RELEASEDIR/iso.
869    live-image          Create bootable live image in
870                        RELEASEDIR/RELEASEMACHINEDIR/installation/liveimage.
871    install-image       Create bootable installation image in
872                        RELEASEDIR/RELEASEMACHINEDIR/installation/installimage.
873    params              Display various make(1) parameters.
874
875 Options:
876    -a arch        Set MACHINE_ARCH to arch.  [Default: deduced from MACHINE]
877    -B buildid     Set BUILDID to buildid.
878    -C cdextras    Append cdextras to CDEXTRA variable for inclusion on CD-ROM.
879    -D dest        Set DESTDIR to dest.  [Default: destdir.MACHINE]
880    -E             Set "expert" mode; disables various safety checks.
881                   Should not be used without expert knowledge of the build system.
882    -h             Print this help message.
883    -j njob        Run up to njob jobs in parallel; see make(1) -j.
884    -M obj         Set obj root directory to obj; sets MAKEOBJDIRPREFIX.
885                   Unsets MAKEOBJDIR.
886    -m mach        Set MACHINE to mach; not required if NetBSD native.
887    -N noisy       Set the noisyness (MAKEVERBOSE) level of the build:
888                       0   Minimal output ("quiet")
889                       1   Describe what is occurring
890                       2   Describe what is occurring and echo the actual command
891                       3   Ignore the effect of the "@" prefix in make commands
892                       4   Trace shell commands using the shell's -x flag
893                   [Default: 2]
894    -n             Show commands that would be executed, but do not execute them.
895    -O obj         Set obj root directory to obj; sets a MAKEOBJDIR pattern.
896                   Unsets MAKEOBJDIRPREFIX.
897    -o             Set MKOBJDIRS=no; do not create objdirs at start of build.
898    -R release     Set RELEASEDIR to release.  [Default: releasedir]
899    -r             Remove contents of TOOLDIR and DESTDIR before building.
900    -S seed        Set BUILDSEED to seed.  [Default: NetBSD-majorversion]
901    -T tools       Set TOOLDIR to tools.  If unset, and TOOLDIR is not set in
902                   the environment, ${toolprefix}make will be (re)built
903                   unconditionally.
904    -U             Set MKUNPRIVED=yes; build without requiring root privileges,
905                   install from an UNPRIVED build with proper file permissions.
906    -u             Set MKUPDATE=yes; do not run "make cleandir" first.
907                   Without this, everything is rebuilt, including the tools.
908    -V var=[value] Set variable \`var' to \`value'.
909    -w wrapper     Create ${toolprefix}make script as wrapper.
910                   [Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE}]
911    -X x11src      Set X11SRCDIR to x11src.  [Default: /usr/xsrc]
912    -x             Set MKX11=yes; build X11 from X11SRCDIR
913    -Y extsrcsrc   Set EXTSRCSRCDIR to extsrcsrc.  [Default: /usr/extsrc]
914    -y             Set MKEXTSRC=yes; build extsrc from EXTSRCSRCDIR
915    -Z var         Unset ("zap") variable \`var'.
916
917_usage_
918	exit 1
919}
920
921parseoptions()
922{
923	opts='a:B:C:D:Ehj:M:m:N:nO:oR:rS:T:UuV:w:X:xY:yZ:'
924	opt_a=no
925
926	if type getopts >/dev/null 2>&1; then
927		# Use POSIX getopts.
928		#
929		getoptcmd='getopts ${opts} opt && opt=-${opt}'
930		optargcmd=':'
931		optremcmd='shift $((${OPTIND} -1))'
932	else
933		type getopt >/dev/null 2>&1 ||
934		    bomb "Shell does not support getopts or getopt"
935
936		# Use old-style getopt(1) (doesn't handle whitespace in args).
937		#
938		args="$(getopt ${opts} $*)"
939		[ $? = 0 ] || usage
940		set -- ${args}
941
942		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
943		optargcmd='OPTARG="$1"; shift'
944		optremcmd=':'
945	fi
946
947	# Parse command line options.
948	#
949	while eval ${getoptcmd}; do
950		case ${opt} in
951
952		-a)
953			eval ${optargcmd}
954			MACHINE_ARCH=${OPTARG}
955			opt_a=yes
956			;;
957
958		-B)
959			eval ${optargcmd}
960			BUILDID=${OPTARG}
961			;;
962
963		-C)
964			eval ${optargcmd}; resolvepaths OPTARG
965			CDEXTRA="${CDEXTRA}${CDEXTRA:+ }${OPTARG}"
966			;;
967
968		-D)
969			eval ${optargcmd}; resolvepath OPTARG
970			setmakeenv DESTDIR "${OPTARG}"
971			;;
972
973		-E)
974			do_expertmode=true
975			;;
976
977		-j)
978			eval ${optargcmd}
979			parallel="-j ${OPTARG}"
980			;;
981
982		-M)
983			eval ${optargcmd}; resolvepath OPTARG
984			case "${OPTARG}" in
985			\$*)	usage "-M argument must not begin with '\$'"
986				;;
987			*\$*)	# can use resolvepath, but can't set TOP_objdir
988				resolvepath OPTARG
989				;;
990			*)	resolvepath OPTARG
991				TOP_objdir="${OPTARG}${TOP}"
992				;;
993			esac
994			unsetmakeenv MAKEOBJDIR
995			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
996			;;
997
998			# -m overrides MACHINE_ARCH unless "-a" is specified
999		-m)
1000			eval ${optargcmd}
1001			MACHINE="${OPTARG}"
1002			[ "${opt_a}" != "yes" ] && getarch
1003			;;
1004
1005		-N)
1006			eval ${optargcmd}
1007			case "${OPTARG}" in
1008			0|1|2|3|4)
1009				setmakeenv MAKEVERBOSE "${OPTARG}"
1010				;;
1011			*)
1012				usage "'${OPTARG}' is not a valid value for -N"
1013				;;
1014			esac
1015			;;
1016
1017		-n)
1018			runcmd=echo
1019			;;
1020
1021		-O)
1022			eval ${optargcmd}
1023			case "${OPTARG}" in
1024			*\$*)	usage "-O argument must not contain '\$'"
1025				;;
1026			*)	resolvepath OPTARG
1027				TOP_objdir="${OPTARG}"
1028				;;
1029			esac
1030			unsetmakeenv MAKEOBJDIRPREFIX
1031			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
1032			;;
1033
1034		-o)
1035			MKOBJDIRS=no
1036			;;
1037
1038		-R)
1039			eval ${optargcmd}; resolvepath OPTARG
1040			setmakeenv RELEASEDIR "${OPTARG}"
1041			;;
1042
1043		-r)
1044			do_removedirs=true
1045			do_rebuildmake=true
1046			;;
1047
1048		-S)
1049			eval ${optargcmd}
1050			setmakeenv BUILDSEED "${OPTARG}"
1051			;;
1052
1053		-T)
1054			eval ${optargcmd}; resolvepath OPTARG
1055			TOOLDIR="${OPTARG}"
1056			export TOOLDIR
1057			;;
1058
1059		-U)
1060			setmakeenv MKUNPRIVED yes
1061			;;
1062
1063		-u)
1064			setmakeenv MKUPDATE yes
1065			;;
1066
1067		-V)
1068			eval ${optargcmd}
1069			case "${OPTARG}" in
1070		    # XXX: consider restricting which variables can be changed?
1071			[a-zA-Z_][a-zA-Z_0-9]*=*)
1072				setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
1073				;;
1074			*)
1075				usage "-V argument must be of the form 'var=[value]'"
1076				;;
1077			esac
1078			;;
1079
1080		-w)
1081			eval ${optargcmd}; resolvepath OPTARG
1082			makewrapper="${OPTARG}"
1083			;;
1084
1085		-X)
1086			eval ${optargcmd}; resolvepath OPTARG
1087			setmakeenv X11SRCDIR "${OPTARG}"
1088			;;
1089
1090		-x)
1091			setmakeenv MKX11 yes
1092			;;
1093
1094		-Y)
1095			eval ${optargcmd}; resolvepath OPTARG
1096			setmakeenv EXTSRCSRCDIR "${OPTARG}"
1097			;;
1098
1099		-y)
1100			setmakeenv MKEXTSRC yes
1101			;;
1102
1103		-Z)
1104			eval ${optargcmd}
1105		    # XXX: consider restricting which variables can be unset?
1106			unsetmakeenv "${OPTARG}"
1107			;;
1108
1109		--)
1110			break
1111			;;
1112
1113		-'?'|-h)
1114			usage
1115			;;
1116
1117		esac
1118	done
1119
1120	# Validate operations.
1121	#
1122	eval ${optremcmd}
1123	while [ $# -gt 0 ]; do
1124		op=$1; shift
1125		operations="${operations} ${op}"
1126
1127		case "${op}" in
1128
1129		help)
1130			usage
1131			;;
1132
1133		makewrapper|cleandir|obj|tools|build|distribution|release|sets|sourcesets|syspkgs|params)
1134			;;
1135
1136		iso-image)
1137			op=iso_image	# used as part of a variable name
1138			;;
1139
1140		iso-image-source)
1141			op=iso_image_source   # used as part of a variable name
1142			;;
1143
1144		live-image)
1145			op=live_image	# used as part of a variable name
1146			;;
1147
1148		install-image)
1149			op=install_image # used as part of a variable name
1150			;;
1151
1152		kernel=*|releasekernel=*)
1153			arg=${op#*=}
1154			op=${op%%=*}
1155			[ -n "${arg}" ] ||
1156			    bomb "Must supply a kernel name with \`${op}=...'"
1157			;;
1158
1159		modules)
1160			op=modules
1161			;;
1162
1163		install=*|installmodules=*)
1164			arg=${op#*=}
1165			op=${op%%=*}
1166			[ -n "${arg}" ] ||
1167			    bomb "Must supply a directory with \`install=...'"
1168			;;
1169
1170		rump|rumptest)
1171			op=${op}
1172			;;
1173
1174		*)
1175			usage "Unknown operation \`${op}'"
1176			;;
1177
1178		esac
1179		eval do_${op}=true
1180	done
1181	[ -n "${operations}" ] || usage "Missing operation to perform."
1182
1183	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
1184	#
1185	if [ -z "${MACHINE}" ]; then
1186		[ "${uname_s}" = "NetBSD" ] ||
1187		    bomb "MACHINE must be set, or -m must be used, for cross builds."
1188		MACHINE=${uname_m}
1189	fi
1190	[ -n "${MACHINE_ARCH}" ] || getarch
1191	validatearch
1192
1193	# Set up default make(1) environment.
1194	#
1195	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
1196	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
1197	MAKEFLAGS="-de -m ${TOP}/share/mk ${MAKEFLAGS}"
1198	MAKEFLAGS="${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
1199	export MAKEFLAGS MACHINE MACHINE_ARCH
1200}
1201
1202# sanitycheck --
1203# Sanity check after parsing command line options, before rebuildmake.
1204#
1205sanitycheck()
1206{
1207	# If the PATH contains any non-absolute components (including,
1208	# but not limited to, "." or ""), then complain.  As an exception,
1209	# allow "" or "." as the last component of the PATH.  This is fatal
1210	# if expert mode is not in effect.
1211	#
1212	local path="${PATH}"
1213	path="${path%:}"	# delete trailing ":"
1214	path="${path%:.}"	# delete trailing ":."
1215	case ":${path}:/" in
1216	*:[!/]*)
1217		if ${do_expertmode}; then
1218			warning "PATH contains non-absolute components"
1219		else
1220			bomb "PATH environment variable must not" \
1221			     "contain non-absolute components"
1222		fi
1223		;;
1224	esac
1225}
1226
1227# print_tooldir_make --
1228# Try to find and print a path to an existing
1229# ${TOOLDIR}/bin/${toolprefix}make, for use by rebuildmake() before a
1230# new version of ${toolprefix}make has been built.
1231#
1232# * If TOOLDIR was set in the environment or on the command line, use
1233#   that value.
1234# * Otherwise try to guess what TOOLDIR would be if not overridden by
1235#   /etc/mk.conf, and check whether the resulting directory contains
1236#   a copy of ${toolprefix}make (this should work for everybody who
1237#   doesn't override TOOLDIR via /etc/mk.conf);
1238# * Failing that, search for ${toolprefix}make, nbmake, bmake, or make,
1239#   in the PATH (this might accidentally find a version of make that
1240#   does not understand the syntax used by NetBSD make, and that will
1241#   lead to failure in the next step);
1242# * If a copy of make was found above, try to use it with
1243#   nobomb_getmakevar to find the correct value for TOOLDIR, and believe the
1244#   result only if it's a directory that already exists;
1245# * If a value of TOOLDIR was found above, and if
1246#   ${TOOLDIR}/bin/${toolprefix}make exists, print that value.
1247#
1248print_tooldir_make()
1249{
1250	local possible_TOP_OBJ
1251	local possible_TOOLDIR
1252	local possible_make
1253	local tooldir_make
1254
1255	if [ -n "${TOOLDIR}" ]; then
1256		echo "${TOOLDIR}/bin/${toolprefix}make"
1257		return 0
1258	fi
1259
1260	# Set host_ostype to something like "NetBSD-4.5.6-i386".  This
1261	# is intended to match the HOST_OSTYPE variable in <bsd.own.mk>.
1262	#
1263	local host_ostype="${uname_s}-$(
1264		echo "${uname_r}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
1265		)-$(
1266		echo "${uname_p}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
1267		)"
1268
1269	# Look in a few potential locations for
1270	# ${possible_TOOLDIR}/bin/${toolprefix}make.
1271	# If we find it, then set possible_make.
1272	#
1273	# In the usual case (without interference from environment
1274	# variables or /etc/mk.conf), <bsd.own.mk> should set TOOLDIR to
1275	# "${_SRC_TOP_OBJ_}/tooldir.${host_ostype}".
1276	#
1277	# In practice it's difficult to figure out the correct value
1278	# for _SRC_TOP_OBJ_.  In the easiest case, when the -M or -O
1279	# options were passed to build.sh, then ${TOP_objdir} will be
1280	# the correct value.  We also try a few other possibilities, but
1281	# we do not replicate all the logic of <bsd.obj.mk>.
1282	#
1283	for possible_TOP_OBJ in \
1284		"${TOP_objdir}" \
1285		"${MAKEOBJDIRPREFIX:+${MAKEOBJDIRPREFIX}${TOP}}" \
1286		"${TOP}" \
1287		"${TOP}/obj" \
1288		"${TOP}/obj.${MACHINE}"
1289	do
1290		[ -n "${possible_TOP_OBJ}" ] || continue
1291		possible_TOOLDIR="${possible_TOP_OBJ}/tooldir.${host_ostype}"
1292		possible_make="${possible_TOOLDIR}/bin/${toolprefix}make"
1293		if [ -x "${possible_make}" ]; then
1294			break
1295		else
1296			unset possible_make
1297		fi
1298	done
1299
1300	# If the above didn't work, search the PATH for a suitable
1301	# ${toolprefix}make, nbmake, bmake, or make.
1302	#
1303	: ${possible_make:=$(find_in_PATH ${toolprefix}make '')}
1304	: ${possible_make:=$(find_in_PATH nbmake '')}
1305	: ${possible_make:=$(find_in_PATH bmake '')}
1306	: ${possible_make:=$(find_in_PATH make '')}
1307
1308	# At this point, we don't care whether possible_make is in the
1309	# correct TOOLDIR or not; we simply want it to be usable by
1310	# getmakevar to help us find the correct TOOLDIR.
1311	#
1312	# Use ${possible_make} with nobomb_getmakevar to try to find
1313	# the value of TOOLDIR.  Believe the result only if it's
1314	# a directory that already exists and contains bin/${toolprefix}make.
1315	#
1316	if [ -x "${possible_make}" ]; then
1317		possible_TOOLDIR="$(
1318			make="${possible_make}" \
1319			nobomb_getmakevar TOOLDIR 2>/dev/null
1320			)"
1321		if [ $? = 0 ] && [ -n "${possible_TOOLDIR}" ] \
1322		    && [ -d "${possible_TOOLDIR}" ];
1323		then
1324			tooldir_make="${possible_TOOLDIR}/bin/${toolprefix}make"
1325			if [ -x "${tooldir_make}" ]; then
1326				echo "${tooldir_make}"
1327				return 0
1328			fi
1329		fi
1330	fi
1331	return 1
1332}
1333
1334# rebuildmake --
1335# Rebuild nbmake in a temporary directory if necessary.  Sets $make
1336# to a path to the nbmake executable.  Sets done_rebuildmake=true
1337# if nbmake was rebuilt.
1338#
1339# There is a cyclic dependency between building nbmake and choosing
1340# TOOLDIR: TOOLDIR may be affected by settings in /etc/mk.conf, so we
1341# would like to use getmakevar to get the value of TOOLDIR; but we can't
1342# use getmakevar before we have an up to date version of nbmake; we
1343# might already have an up to date version of nbmake in TOOLDIR, but we
1344# don't yet know where TOOLDIR is.
1345#
1346# The default value of TOOLDIR also depends on the location of the top
1347# level object directory, so $(getmakevar TOOLDIR) invoked before or
1348# after making the top level object directory may produce different
1349# results.
1350#
1351# Strictly speaking, we should do the following:
1352#
1353#    1. build a new version of nbmake in a temporary directory;
1354#    2. use the temporary nbmake to create the top level obj directory;
1355#    3. use $(getmakevar TOOLDIR) with the temporary nbmake to
1356#       get the corect value of TOOLDIR;
1357#    4. move the temporary nbmake to ${TOOLDIR}/bin/nbmake.
1358#
1359# However, people don't like building nbmake unnecessarily if their
1360# TOOLDIR has not changed since an earlier build.  We try to avoid
1361# rebuilding a temporary version of nbmake by taking some shortcuts to
1362# guess a value for TOOLDIR, looking for an existing version of nbmake
1363# in that TOOLDIR, and checking whether that nbmake is newer than the
1364# sources used to build it.
1365#
1366rebuildmake()
1367{
1368	make="$(print_tooldir_make)"
1369	if [ -n "${make}" ] && [ -x "${make}" ]; then
1370		for f in usr.bin/make/*.[ch] usr.bin/make/lst.lib/*.[ch]; do
1371			if [ "${f}" -nt "${make}" ]; then
1372				statusmsg "${make} outdated" \
1373					"(older than ${f}), needs building."
1374				do_rebuildmake=true
1375				break
1376			fi
1377		done
1378	else
1379		statusmsg "No \$TOOLDIR/bin/${toolprefix}make, needs building."
1380		do_rebuildmake=true
1381	fi
1382
1383	# Build bootstrap ${toolprefix}make if needed.
1384	if ${do_rebuildmake}; then
1385		statusmsg "Bootstrapping ${toolprefix}make"
1386		${runcmd} cd "${tmpdir}"
1387		${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
1388			CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
1389			${HOST_SH} "${TOP}/tools/make/configure" ||
1390		    bomb "Configure of ${toolprefix}make failed"
1391		${runcmd} ${HOST_SH} buildmake.sh ||
1392		    bomb "Build of ${toolprefix}make failed"
1393		make="${tmpdir}/${toolprefix}make"
1394		${runcmd} cd "${TOP}"
1395		${runcmd} rm -f usr.bin/make/*.o usr.bin/make/lst.lib/*.o
1396		done_rebuildmake=true
1397	fi
1398}
1399
1400# validatemakeparams --
1401# Perform some late sanity checks, after rebuildmake,
1402# but before createmakewrapper or any real work.
1403#
1404# Also create the top-level obj directory.
1405#
1406validatemakeparams()
1407{
1408	if [ "${runcmd}" = "echo" ]; then
1409		TOOLCHAIN_MISSING=no
1410		EXTERNAL_TOOLCHAIN=""
1411	else
1412		TOOLCHAIN_MISSING=$(bomb_getmakevar TOOLCHAIN_MISSING)
1413		EXTERNAL_TOOLCHAIN=$(bomb_getmakevar EXTERNAL_TOOLCHAIN)
1414	fi
1415	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
1416	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
1417		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
1418		${runcmd} echo "	MACHINE:      ${MACHINE}"
1419		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
1420		${runcmd} echo ""
1421		${runcmd} echo "All builds for this platform should be done via a traditional make"
1422		${runcmd} echo "If you wish to use an external cross-toolchain, set"
1423		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
1424		${runcmd} echo "in either the environment or mk.conf and rerun"
1425		${runcmd} echo "	${progname} $*"
1426		exit 1
1427	fi
1428
1429	# Normalise MKOBJDIRS, MKUNPRIVED, and MKUPDATE
1430	# These may be set as build.sh options or in "mk.conf".
1431	# Don't export them as they're only used for tests in build.sh.
1432	#
1433	MKOBJDIRS=$(getmakevar MKOBJDIRS)
1434	MKUNPRIVED=$(getmakevar MKUNPRIVED)
1435	MKUPDATE=$(getmakevar MKUPDATE)
1436
1437	if [ "${MKOBJDIRS}" != "no" ]; then
1438		# Create the top-level object directory.
1439		#
1440		# "make obj NOSUBDIR=" can handle most cases, but it
1441		# can't handle the case where MAKEOBJDIRPREFIX is set
1442		# while the corresponding directory does not exist
1443		# (rules in <bsd.obj.mk> would abort the build).  We
1444		# therefore have to handle the MAKEOBJDIRPREFIX case
1445		# without invoking "make obj".  The MAKEOBJDIR case
1446		# could be handled either way, but we choose to handle
1447		# it similarly to MAKEOBJDIRPREFIX.
1448		#
1449		if [ -n "${TOP_obj}" ]; then
1450			# It must have been set by the "-M" or "-O"
1451			# command line options, so there's no need to
1452			# use getmakevar
1453			:
1454		elif [ -n "$MAKEOBJDIRPREFIX" ]; then
1455			TOP_obj="$(getmakevar MAKEOBJDIRPREFIX)${TOP}"
1456		elif [ -n "$MAKEOBJDIR" ]; then
1457			TOP_obj="$(getmakevar MAKEOBJDIR)"
1458		fi
1459		if [ -n "$TOP_obj" ]; then
1460			${runcmd} mkdir -p "${TOP_obj}" ||
1461			    bomb "Can't create top level object directory" \
1462					"${TOP_obj}"
1463		else
1464			${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
1465			    bomb "Can't create top level object directory" \
1466					"using make obj"
1467		fi
1468
1469		# make obj in tools to ensure that the objdir for "tools"
1470		# is available.
1471		#
1472		${runcmd} cd tools
1473		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
1474		    bomb "Failed to make obj in tools"
1475		${runcmd} cd "${TOP}"
1476	fi
1477
1478	# Find TOOLDIR, DESTDIR, and RELEASEDIR, according to getmakevar,
1479	# and bomb if they have changed from the values we had from the
1480	# command line or environment.
1481	#
1482	# This must be done after creating the top-level object directory.
1483	#
1484	for var in TOOLDIR DESTDIR RELEASEDIR
1485	do
1486		eval oldval=\"\$${var}\"
1487		newval="$(getmakevar $var)"
1488		if ! $do_expertmode; then
1489			: ${_SRC_TOP_OBJ_:=$(getmakevar _SRC_TOP_OBJ_)}
1490			case "$var" in
1491			DESTDIR)
1492				: ${newval:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
1493				makeenv="${makeenv} DESTDIR"
1494				;;
1495			RELEASEDIR)
1496				: ${newval:=${_SRC_TOP_OBJ_}/releasedir}
1497				makeenv="${makeenv} RELEASEDIR"
1498				;;
1499			esac
1500		fi
1501		if [ -n "$oldval" ] && [ "$oldval" != "$newval" ]; then
1502			bomb "Value of ${var} has changed" \
1503				"(was \"${oldval}\", now \"${newval}\")"
1504		fi
1505		eval ${var}=\"\${newval}\"
1506		eval export ${var}
1507		statusmsg2 "${var} path:" "${newval}"
1508	done
1509
1510	# RELEASEMACHINEDIR is just a subdir name, e.g. "i386".
1511	RELEASEMACHINEDIR=$(getmakevar RELEASEMACHINEDIR)
1512
1513	# Check validity of TOOLDIR and DESTDIR.
1514	#
1515	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
1516		bomb "TOOLDIR '${TOOLDIR}' invalid"
1517	fi
1518	removedirs="${TOOLDIR}"
1519
1520	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
1521		if ${do_build} || ${do_distribution} || ${do_release}; then
1522			if ! ${do_build} || \
1523			   [ "${uname_s}" != "NetBSD" ] || \
1524			   [ "${uname_m}" != "${MACHINE}" ]; then
1525				bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'."
1526			fi
1527			if ! ${do_expertmode}; then
1528				bomb "DESTDIR must != / for non -E (expert) builds"
1529			fi
1530			statusmsg "WARNING: Building to /, in expert mode."
1531			statusmsg "         This may cause your system to break!  Reasons include:"
1532			statusmsg "            - your kernel is not up to date"
1533			statusmsg "            - the libraries or toolchain have changed"
1534			statusmsg "         YOU HAVE BEEN WARNED!"
1535		fi
1536	else
1537		removedirs="${removedirs} ${DESTDIR}"
1538	fi
1539	if ${do_build} || ${do_distribution} || ${do_release}; then
1540		if ! ${do_expertmode} && \
1541		    [ "$id_u" -ne 0 ] && \
1542		    [ "${MKUNPRIVED}" = "no" ] ; then
1543			bomb "-U or -E must be set for build as an unprivileged user."
1544		fi
1545	fi
1546	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
1547		bomb "Must set RELEASEDIR with \`releasekernel=...'"
1548	fi
1549
1550	# Install as non-root is a bad idea.
1551	#
1552	if ${do_install} && [ "$id_u" -ne 0 ] ; then
1553		if ${do_expertmode}; then
1554			warning "Will install as an unprivileged user."
1555		else
1556			bomb "-E must be set for install as an unprivileged user."
1557		fi
1558	fi
1559
1560	# If a previous build.sh run used -U (and therefore created a
1561	# METALOG file), then most subsequent build.sh runs must also
1562	# use -U.  If DESTDIR is about to be removed, then don't perform
1563	# this check.
1564	#
1565	case "${do_removedirs} ${removedirs} " in
1566	true*" ${DESTDIR} "*)
1567		# DESTDIR is about to be removed
1568		;;
1569	*)
1570		if ( ${do_build} || ${do_distribution} || ${do_release} || \
1571		    ${do_install} ) && \
1572		    [ -e "${DESTDIR}/METALOG" ] && \
1573		    [ "${MKUNPRIVED}" = "no" ] ; then
1574			if $do_expertmode; then
1575				warning "A previous build.sh run specified -U."
1576			else
1577				bomb "A previous build.sh run specified -U; you must specify it again now."
1578			fi
1579		fi
1580		;;
1581	esac
1582
1583	# live-image and install-image targets require binary sets
1584	# (actually DESTDIR/etc/mtree/set.* files) built with MKUNPRIVED.
1585	# If release operation is specified with live-image or install-image,
1586	# the release op should be performed with -U for later image ops.
1587	#
1588	if ${do_release} && ( ${do_live_image} || ${do_install_image} ) && \
1589	    [ "${MKUNPRIVED}" = "no" ] ; then
1590		bomb "-U must be specified on building release to create images later."
1591	fi
1592}
1593
1594
1595createmakewrapper()
1596{
1597	# Remove the target directories.
1598	#
1599	if ${do_removedirs}; then
1600		for f in ${removedirs}; do
1601			statusmsg "Removing ${f}"
1602			${runcmd} rm -r -f "${f}"
1603		done
1604	fi
1605
1606	# Recreate $TOOLDIR.
1607	#
1608	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
1609	    bomb "mkdir of '${TOOLDIR}/bin' failed"
1610
1611	# If we did not previously rebuild ${toolprefix}make, then
1612	# check whether $make is still valid and the same as the output
1613	# from print_tooldir_make.  If not, then rebuild make now.  A
1614	# possible reason for this being necessary is that the actual
1615	# value of TOOLDIR might be different from the value guessed
1616	# before the top level obj dir was created.
1617	#
1618	if ! ${done_rebuildmake} && \
1619	    ( [ ! -x "$make" ] || [ "$make" != "$(print_tooldir_make)" ] )
1620	then
1621		rebuildmake
1622	fi
1623
1624	# Install ${toolprefix}make if it was built.
1625	#
1626	if ${done_rebuildmake}; then
1627		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
1628		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
1629		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
1630		make="${TOOLDIR}/bin/${toolprefix}make"
1631		statusmsg "Created ${make}"
1632	fi
1633
1634	# Build a ${toolprefix}make wrapper script, usable by hand as
1635	# well as by build.sh.
1636	#
1637	if [ -z "${makewrapper}" ]; then
1638		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
1639		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
1640	fi
1641
1642	${runcmd} rm -f "${makewrapper}"
1643	if [ "${runcmd}" = "echo" ]; then
1644		echo 'cat <<EOF >'${makewrapper}
1645		makewrapout=
1646	else
1647		makewrapout=">>\${makewrapper}"
1648	fi
1649
1650	case "${KSH_VERSION:-${SH_VERSION}}" in
1651	*PD\ KSH*|*MIRBSD\ KSH*)
1652		set +o braceexpand
1653		;;
1654	esac
1655
1656	eval cat <<EOF ${makewrapout}
1657#! ${HOST_SH}
1658# Set proper variables to allow easy "make" building of a NetBSD subtree.
1659# Generated from:  \$NetBSD: build.sh,v 1.253.2.1 2012/03/02 16:48:10 riz Exp $
1660# with these arguments: ${_args}
1661#
1662
1663EOF
1664	{
1665		for f in ${makeenv}; do
1666			if eval "[ -z \"\${$f}\" -a \"\${${f}-X}\" = \"X\" ]"; then
1667				eval echo "unset ${f}"
1668			else
1669				eval echo "${f}=\'\$$(echo ${f})\'\;\ export\ ${f}"
1670			fi
1671		done
1672
1673		eval cat <<EOF
1674MAKEWRAPPERMACHINE=${makewrappermachine:-${MACHINE}}; export MAKEWRAPPERMACHINE
1675USETOOLS=yes; export USETOOLS
1676EOF
1677	} | eval sort -u "${makewrapout}"
1678	eval cat <<EOF "${makewrapout}"
1679
1680exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
1681EOF
1682	[ "${runcmd}" = "echo" ] && echo EOF
1683	${runcmd} chmod +x "${makewrapper}"
1684	statusmsg2 "Updated makewrapper:" "${makewrapper}"
1685}
1686
1687make_in_dir()
1688{
1689	dir="$1"
1690	op="$2"
1691	${runcmd} cd "${dir}" ||
1692	    bomb "Failed to cd to \"${dir}\""
1693	${runcmd} "${makewrapper}" ${parallel} ${op} ||
1694	    bomb "Failed to make ${op} in \"${dir}\""
1695	${runcmd} cd "${TOP}" ||
1696	    bomb "Failed to cd back to \"${TOP}\""
1697}
1698
1699buildtools()
1700{
1701	if [ "${MKOBJDIRS}" != "no" ]; then
1702		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
1703		    bomb "Failed to make obj-tools"
1704	fi
1705	if [ "${MKUPDATE}" = "no" ]; then
1706		make_in_dir tools cleandir
1707	fi
1708	make_in_dir tools dependall
1709	make_in_dir tools install
1710	statusmsg "Tools built to ${TOOLDIR}"
1711}
1712
1713getkernelconf()
1714{
1715	kernelconf="$1"
1716	if [ "${MKOBJDIRS}" != "no" ]; then
1717		# The correct value of KERNOBJDIR might
1718		# depend on a prior "make obj" in
1719		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
1720		#
1721		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
1722		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
1723		make_in_dir "${KERNSRCDIR}/${KERNARCHDIR}/compile" obj
1724	fi
1725	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
1726	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
1727	case "${kernelconf}" in
1728	*/*)
1729		kernelconfpath="${kernelconf}"
1730		kernelconfname="${kernelconf##*/}"
1731		;;
1732	*)
1733		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
1734		kernelconfname="${kernelconf}"
1735		;;
1736	esac
1737	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
1738}
1739
1740buildkernel()
1741{
1742	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
1743		# Building tools every time we build a kernel is clearly
1744		# unnecessary.  We could try to figure out whether rebuilding
1745		# the tools is necessary this time, but it doesn't seem worth
1746		# the trouble.  Instead, we say it's the user's responsibility
1747		# to rebuild the tools if necessary.
1748		#
1749		statusmsg "Building kernel without building new tools"
1750		buildkernelwarned=true
1751	fi
1752	getkernelconf $1
1753	statusmsg2 "Building kernel:" "${kernelconf}"
1754	statusmsg2 "Build directory:" "${kernelbuildpath}"
1755	${runcmd} mkdir -p "${kernelbuildpath}" ||
1756	    bomb "Cannot mkdir: ${kernelbuildpath}"
1757	if [ "${MKUPDATE}" = "no" ]; then
1758		make_in_dir "${kernelbuildpath}" cleandir
1759	fi
1760	[ -x "${TOOLDIR}/bin/${toolprefix}config" ] \
1761	|| bomb "${TOOLDIR}/bin/${toolprefix}config does not exist. You need to \"$0 tools\" first."
1762	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" -b "${kernelbuildpath}" \
1763		-s "${TOP}/sys" "${kernelconfpath}" ||
1764	    bomb "${toolprefix}config failed for ${kernelconf}"
1765	make_in_dir "${kernelbuildpath}" depend
1766	make_in_dir "${kernelbuildpath}" all
1767
1768	if [ "${runcmd}" != "echo" ]; then
1769		statusmsg "Kernels built from ${kernelconf}:"
1770		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
1771		for kern in ${kernlist:-netbsd}; do
1772			[ -f "${kernelbuildpath}/${kern}" ] && \
1773			    echo "  ${kernelbuildpath}/${kern}"
1774		done | tee -a "${results}"
1775	fi
1776}
1777
1778releasekernel()
1779{
1780	getkernelconf $1
1781	kernelreldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
1782	${runcmd} mkdir -p "${kernelreldir}"
1783	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
1784	for kern in ${kernlist:-netbsd}; do
1785		builtkern="${kernelbuildpath}/${kern}"
1786		[ -f "${builtkern}" ] || continue
1787		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
1788		statusmsg2 "Kernel copy:" "${releasekern}"
1789		if [ "${runcmd}" = "echo" ]; then
1790			echo "gzip -c -9 < ${builtkern} > ${releasekern}"
1791		else
1792			gzip -c -9 < "${builtkern}" > "${releasekern}"
1793		fi
1794	done
1795}
1796
1797buildmodules()
1798{
1799	setmakeenv MKBINUTILS no
1800	if ! ${do_tools} && ! ${buildmoduleswarned:-false}; then
1801		# Building tools every time we build modules is clearly
1802		# unnecessary as well as a kernel.
1803		#
1804		statusmsg "Building modules without building new tools"
1805		buildmoduleswarned=true
1806	fi
1807
1808	statusmsg "Building kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
1809	if [ "${MKOBJDIRS}" != "no" ]; then
1810		make_in_dir sys/modules obj ||
1811		    bomb "Failed to make obj in sys/modules"
1812	fi
1813	if [ "${MKUPDATE}" = "no" ]; then
1814		make_in_dir sys/modules cleandir
1815	fi
1816	${runcmd} "${makewrapper}" ${parallel} do-sys-modules ||
1817	    bomb "Failed to make do-sys-modules"
1818
1819	statusmsg "Successful build of kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
1820}
1821
1822installmodules()
1823{
1824	dir="$1"
1825	${runcmd} "${makewrapper}" INSTALLMODULESDIR="${dir}" installmodules ||
1826	    bomb "Failed to make installmodules to ${dir}"
1827	statusmsg "Successful installmodules to ${dir}"
1828}
1829
1830installworld()
1831{
1832	dir="$1"
1833	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
1834	    bomb "Failed to make installworld to ${dir}"
1835	statusmsg "Successful installworld to ${dir}"
1836}
1837
1838# Run rump build&link tests.
1839#
1840# To make this feasible for running without having to install includes and
1841# libraries into destdir (i.e. quick), we only run ld.  This is possible
1842# since the rump kernel is a closed namespace apart from calls to rumpuser.
1843# Therefore, if ld complains only about rumpuser symbols, rump kernel
1844# linking was successful.
1845#
1846# We test that rump links with a number of component configurations.
1847# These attempt to mimic what is encountered in the full build.
1848# See list below.  The list should probably be either autogenerated
1849# or managed elsewhere; keep it here until a better idea arises.
1850#
1851# Above all, note that THIS IS NOT A SUBSTITUTE FOR A FULL BUILD.
1852#
1853
1854RUMP_LIBSETS='
1855	-lrump,
1856	-lrumpvfs -lrump,
1857	-lrumpvfs -lrumpdev -lrump,
1858	-lrumpnet -lrump,
1859	-lrumpkern_tty -lrumpvfs -lrump,
1860	-lrumpfs_tmpfs -lrumpvfs -lrump,
1861	-lrumpfs_ffs -lrumpfs_msdos -lrumpvfs -lrumpdev_disk -lrumpdev -lrump,
1862	-lrumpnet_virtif -lrumpnet_netinet -lrumpnet_net -lrumpnet -lrump,
1863	-lrumpnet_sockin -lrumpfs_smbfs -lrumpdev_netsmb
1864	    -lrumpkern_crypto -lrumpdev -lrumpnet -lrumpvfs -lrump,
1865	-lrumpnet_sockin -lrumpfs_nfs -lrumpnet -lrumpvfs -lrump,
1866	-lrumpdev_cgd -lrumpdev_raidframe -lrumpdev_disk -lrumpdev_rnd
1867	    -lrumpdev_dm -lrumpdev -lrumpvfs -lrumpkern_crypto -lrump'
1868dorump()
1869{
1870	local doclean=""
1871	local doobjs=""
1872
1873	# we cannot link libs without building csu, and that leads to lossage
1874	[ "${1}" != "rumptest" ] && bomb 'build.sh rump not yet functional. ' \
1875	    'did you mean "rumptest"?'
1876
1877	# create obj and distrib dirs
1878	if [ "${MKOBJDIRS}" != "no" ]; then
1879		make_in_dir "${NETBSDSRCDIR}/etc/mtree" obj
1880		make_in_dir "${NETBSDSRCDIR}/sys/rump" obj
1881	fi
1882	${runcmd} "${makewrapper}" ${parallel} do-distrib-dirs \
1883	    || bomb 'could not create distrib-dirs'
1884
1885	[ "${MKUPDATE}" = "no" ] && doclean="cleandir"
1886	targlist="${doclean} ${doobjs} dependall install"
1887	# optimize: for test we build only static libs (3x test speedup)
1888	if [ "${1}" = "rumptest" ] ; then
1889		setmakeenv NOPIC 1
1890		setmakeenv NOPROFILE 1
1891	fi
1892	for cmd in ${targlist} ; do
1893		make_in_dir "${NETBSDSRCDIR}/sys/rump" ${cmd}
1894	done
1895
1896	# if we just wanted to build & install rump, we're done
1897	[ "${1}" != "rumptest" ] && return
1898
1899	${runcmd} cd "${NETBSDSRCDIR}/sys/rump/librump/rumpkern" \
1900	    || bomb "cd to rumpkern failed"
1901	md_quirks=`${runcmd} "${makewrapper}" -V '${_SYMQUIRK}'`
1902	# one little, two little, three little backslashes ...
1903	md_quirks="$(echo ${md_quirks} | sed 's,\\,\\\\,g'";s/'//g" )"
1904	${runcmd} cd "${TOP}" || bomb "cd to ${TOP} failed"
1905	tool_ld=`${runcmd} "${makewrapper}" -V '${LD}'`
1906
1907	local oIFS="${IFS}"
1908	IFS=","
1909	for set in ${RUMP_LIBSETS} ; do
1910		IFS="${oIFS}"
1911		${runcmd} ${tool_ld} -nostdlib -L${DESTDIR}/usr/lib	\
1912		    -static --whole-archive ${set} 2>&1 -o /tmp/rumptest.$$ | \
1913		      awk -v quirks="${md_quirks}" '
1914			/undefined reference/ &&
1915			    !/more undefined references.*follow/{
1916				if (match($NF,
1917				    "`(rumpuser_|__" quirks ")") == 0)
1918					fails[NR] = $0
1919			}
1920			/cannot find -l/{fails[NR] = $0}
1921			/cannot open output file/{fails[NR] = $0}
1922			END{
1923				for (x in fails)
1924					print fails[x]
1925				exit x!=0
1926			}'
1927		[ $? -ne 0 ] && bomb "Testlink of rump failed: ${set}"
1928	done
1929	statusmsg "Rump build&link tests successful"
1930}
1931
1932main()
1933{
1934	initdefaults
1935	_args=$@
1936	parseoptions "$@"
1937
1938	sanitycheck
1939
1940	build_start=$(date)
1941	statusmsg2 "${progname} command:" "$0 $*"
1942	statusmsg2 "${progname} started:" "${build_start}"
1943	statusmsg2 "NetBSD version:"   "${DISTRIBVER}"
1944	statusmsg2 "MACHINE:"          "${MACHINE}"
1945	statusmsg2 "MACHINE_ARCH:"     "${MACHINE_ARCH}"
1946	statusmsg2 "Build platform:"   "${uname_s} ${uname_r} ${uname_m}"
1947	statusmsg2 "HOST_SH:"          "${HOST_SH}"
1948
1949	rebuildmake
1950	validatemakeparams
1951	createmakewrapper
1952
1953	# Perform the operations.
1954	#
1955	for op in ${operations}; do
1956		case "${op}" in
1957
1958		makewrapper)
1959			# no-op
1960			;;
1961
1962		tools)
1963			buildtools
1964			;;
1965
1966		sets)
1967			statusmsg "Building sets from pre-populated ${DESTDIR}"
1968			${runcmd} "${makewrapper}" ${parallel} ${op} ||
1969			    bomb "Failed to make ${op}"
1970			setdir=${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
1971			statusmsg "Built sets to ${setdir}"
1972			;;
1973
1974		cleandir|obj|build|distribution|release|sourcesets|syspkgs|params)
1975			${runcmd} "${makewrapper}" ${parallel} ${op} ||
1976			    bomb "Failed to make ${op}"
1977			statusmsg "Successful make ${op}"
1978			;;
1979
1980		iso-image|iso-image-source)
1981			${runcmd} "${makewrapper}" ${parallel} \
1982			    CDEXTRA="$CDEXTRA" ${op} ||
1983			    bomb "Failed to make ${op}"
1984			statusmsg "Successful make ${op}"
1985			;;
1986
1987		live-image|install-image)
1988			# install-image and live-image require mtree spec files
1989			# built with UNPRIVED.  Assume UNPRIVED build has been
1990			# performed if METALOG file is created in DESTDIR.
1991			if [ ! -e "${DESTDIR}/METALOG" ] ; then
1992				bomb "The release binaries must have been built with -U to create images."
1993			fi
1994			${runcmd} "${makewrapper}" ${parallel} ${op} ||
1995			    bomb "Failed to make ${op}"
1996			statusmsg "Successful make ${op}"
1997			;;
1998		kernel=*)
1999			arg=${op#*=}
2000			buildkernel "${arg}"
2001			;;
2002
2003		releasekernel=*)
2004			arg=${op#*=}
2005			releasekernel "${arg}"
2006			;;
2007
2008		modules)
2009			buildmodules
2010			;;
2011
2012		installmodules=*)
2013			arg=${op#*=}
2014			if [ "${arg}" = "/" ] && \
2015			    (	[ "${uname_s}" != "NetBSD" ] || \
2016				[ "${uname_m}" != "${MACHINE}" ] ); then
2017				bomb "'${op}' must != / for cross builds."
2018			fi
2019			installmodules "${arg}"
2020			;;
2021
2022		install=*)
2023			arg=${op#*=}
2024			if [ "${arg}" = "/" ] && \
2025			    (	[ "${uname_s}" != "NetBSD" ] || \
2026				[ "${uname_m}" != "${MACHINE}" ] ); then
2027				bomb "'${op}' must != / for cross builds."
2028			fi
2029			installworld "${arg}"
2030			;;
2031
2032		rump|rumptest)
2033			dorump "${op}"
2034			;;
2035
2036		*)
2037			bomb "Unknown operation \`${op}'"
2038			;;
2039
2040		esac
2041	done
2042
2043	statusmsg2 "${progname} ended:" "$(date)"
2044	if [ -s "${results}" ]; then
2045		echo "===> Summary of results:"
2046		sed -e 's/^===>//;s/^/	/' "${results}"
2047		echo "===> ."
2048	fi
2049}
2050
2051main "$@"
2052