build.sh revision 1.370
1#! /usr/bin/env sh
2#	$NetBSD: build.sh,v 1.370 2023/06/02 14:29:11 lukem Exp $
3#
4# Copyright (c) 2001-2023 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 show 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 dash bash
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='	'
266nl='
267'
268trap "exit 1" 1 2 3 15
269
270bomb()
271{
272	cat >&2 <<ERRORMESSAGE
273
274ERROR: $@
275
276*** BUILD ABORTED ***
277ERRORMESSAGE
278	kill ${toppid}		# in case we were invoked from a subshell
279	exit 1
280}
281
282# Quote args to make them safe in the shell.
283# Usage: quotedlist="$(shell_quote args...)"
284#
285# After building up a quoted list, use it by evaling it inside
286# double quotes, like this:
287#    eval "set -- $quotedlist"
288# or like this:
289#    eval "\$command $quotedlist \$filename"
290#
291shell_quote()
292{(
293	local result=''
294	local arg qarg
295	LC_COLLATE=C ; export LC_COLLATE # so [a-zA-Z0-9] works in ASCII
296	for arg in "$@" ; do
297		case "${arg}" in
298		'')
299			qarg="''"
300			;;
301		*[!-./a-zA-Z0-9]*)
302			# Convert each embedded ' to '\'',
303			# then insert ' at the beginning of the first line,
304			# and append ' at the end of the last line.
305			# Finally, elide unnecessary '' pairs at the
306			# beginning and end of the result and as part of
307			# '\'''\'' sequences that result from multiple
308			# adjacent quotes in he input.
309			qarg="$(printf "%s\n" "$arg" | \
310			    ${SED:-sed} -e "s/'/'\\\\''/g" \
311				-e "1s/^/'/" -e "\$s/\$/'/" \
312				-e "1s/^''//" -e "\$s/''\$//" \
313				-e "s/'''/'/g"
314				)"
315			;;
316		*)
317			# Arg is not the empty string, and does not contain
318			# any unsafe characters.  Leave it unchanged for
319			# readability.
320			qarg="${arg}"
321			;;
322		esac
323		result="${result}${result:+ }${qarg}"
324	done
325	printf "%s\n" "$result"
326)}
327
328statusmsg()
329{
330	${runcmd} echo "===> $@" | tee -a "${results}"
331}
332
333statusmsg2()
334{
335	local msg
336
337	msg="${1}"
338	shift
339	case "${msg}" in
340	????????????????*)	;;
341	??????????*)		msg="${msg}      ";;
342	?????*)			msg="${msg}           ";;
343	*)			msg="${msg}                ";;
344	esac
345	case "${msg}" in
346	?????????????????????*)	;;
347	????????????????????)	msg="${msg} ";;
348	???????????????????)	msg="${msg}  ";;
349	??????????????????)	msg="${msg}   ";;
350	?????????????????)	msg="${msg}    ";;
351	????????????????)	msg="${msg}     ";;
352	esac
353	statusmsg "${msg}$*"
354}
355
356warning()
357{
358	statusmsg "Warning: $@"
359}
360
361# Find a program in the PATH, and show the result.  If not found,
362# show a default.  If $2 is defined (even if it is an empty string),
363# then that is the default; otherwise, $1 is used as the default.
364#
365find_in_PATH()
366{
367	local prog="$1"
368	local result="${2-"$1"}"
369	local oldIFS="${IFS}"
370	local dir
371	IFS=":"
372	for dir in ${PATH}; do
373		if [ -x "${dir}/${prog}" ]; then
374			result="${dir}/${prog}"
375			break
376		fi
377	done
378	IFS="${oldIFS}"
379	echo "${result}"
380}
381
382# Try to find a working POSIX shell, and set HOST_SH to refer to it.
383# Assumes that uname_s, uname_m, and PWD have been set.
384#
385set_HOST_SH()
386{
387	# Even if ${HOST_SH} is already defined, we still do the
388	# sanity checks at the end.
389
390	# Solaris has /usr/xpg4/bin/sh.
391	#
392	[ -z "${HOST_SH}" ] && [ x"${uname_s}" = x"SunOS" ] && \
393		[ -x /usr/xpg4/bin/sh ] && HOST_SH="/usr/xpg4/bin/sh"
394
395	# Try to get the name of the shell that's running this script,
396	# by parsing the output from "ps".  We assume that, if the host
397	# system's ps command supports -o comm at all, it will do so
398	# in the usual way: a one-line header followed by a one-line
399	# result, possibly including trailing white space.  And if the
400	# host system's ps command doesn't support -o comm, we assume
401	# that we'll get an error message on stderr and nothing on
402	# stdout.  (We don't try to use ps -o 'comm=' to suppress the
403	# header line, because that is less widely supported.)
404	#
405	# If we get the wrong result here, the user can override it by
406	# specifying HOST_SH in the environment.
407	#
408	[ -z "${HOST_SH}" ] && HOST_SH="$(
409		(ps -p $$ -o comm | sed -ne "2s/[ ${tab}]*\$//p") 2>/dev/null )"
410
411	# If nothing above worked, use "sh".  We will later find the
412	# first directory in the PATH that has a "sh" program.
413	#
414	[ -z "${HOST_SH}" ] && HOST_SH="sh"
415
416	# If the result so far is not an absolute path, try to prepend
417	# PWD or search the PATH.
418	#
419	case "${HOST_SH}" in
420	/*)	:
421		;;
422	*/*)	HOST_SH="${PWD}/${HOST_SH}"
423		;;
424	*)	HOST_SH="$(find_in_PATH "${HOST_SH}")"
425		;;
426	esac
427
428	# If we don't have an absolute path by now, bomb.
429	#
430	case "${HOST_SH}" in
431	/*)	:
432		;;
433	*)	bomb "HOST_SH=\"${HOST_SH}\" is not an absolute path"
434		;;
435	esac
436
437	# If HOST_SH is not executable, bomb.
438	#
439	[ -x "${HOST_SH}" ] ||
440	    bomb "HOST_SH=\"${HOST_SH}\" is not executable"
441
442	# If HOST_SH fails tests, bomb.
443	# ("$0" may be a path that is no longer valid, because we have
444	# performed "cd $(dirname $0)", so don't use $0 here.)
445	#
446	"${HOST_SH}" build.sh --shelltest ||
447	    bomb "HOST_SH=\"${HOST_SH}\" failed functionality tests"
448}
449
450# initdefaults --
451# Set defaults before parsing command line options.
452#
453initdefaults()
454{
455	makeenv=
456	makewrapper=
457	makewrappermachine=
458	runcmd=
459	operations=
460	removedirs=
461
462	[ -d usr.bin/make ] || cd "$(dirname $0)"
463	[ -d usr.bin/make ] ||
464	    bomb "usr.bin/make not found; build.sh must be run from the top \
465level of source directory"
466	[ -f share/mk/bsd.own.mk ] ||
467	    bomb "src/share/mk is missing; please re-fetch the source tree"
468
469	# Set various environment variables to known defaults,
470	# to minimize (cross-)build problems observed "in the field".
471	#
472	# LC_ALL=C must be set before we try to parse the output from
473	# any command.  Other variables are set (or unset) here, before
474	# we parse command line arguments.
475	#
476	# These variables can be overridden via "-V var=value" if
477	# you know what you are doing.
478	#
479	unsetmakeenv C_INCLUDE_PATH
480	unsetmakeenv CPLUS_INCLUDE_PATH
481	unsetmakeenv INFODIR
482	unsetmakeenv LESSCHARSET
483	unsetmakeenv MAKEFLAGS
484	unsetmakeenv TERMINFO
485	setmakeenv LC_ALL C
486
487	# Find information about the build platform.  This should be
488	# kept in sync with _HOST_OSNAME, _HOST_OSREL, and _HOST_ARCH
489	# variables in share/mk/bsd.sys.mk.
490	#
491	# Note that "uname -p" is not part of POSIX, but we want uname_p
492	# to be set to the host MACHINE_ARCH, if possible.  On systems
493	# where "uname -p" fails, shows "unknown", or shows a string
494	# that does not look like an identifier, fall back to using the
495	# output from "uname -m" instead.
496	#
497	uname_s=$(uname -s 2>/dev/null)
498	uname_r=$(uname -r 2>/dev/null)
499	uname_m=$(uname -m 2>/dev/null)
500	uname_p=$(uname -p 2>/dev/null || echo "unknown")
501	case "${uname_p}" in
502	''|unknown|*[!-_A-Za-z0-9]*) uname_p="${uname_m}" ;;
503	esac
504
505	id_u=$(id -u 2>/dev/null || /usr/xpg4/bin/id -u 2>/dev/null)
506
507	# If $PWD is a valid name of the current directory, POSIX mandates
508	# that pwd return it by default which causes problems in the
509	# presence of symlinks.  Unsetting PWD is simpler than changing
510	# every occurrence of pwd to use -P.
511	#
512	# XXX Except that doesn't work on Solaris. Or many Linuces.
513	#
514	unset PWD
515	TOP=$( (exec pwd -P 2>/dev/null) || (exec pwd 2>/dev/null) )
516
517	# The user can set HOST_SH in the environment, or we try to
518	# guess an appropriate value.  Then we set several other
519	# variables from HOST_SH.
520	#
521	set_HOST_SH
522	setmakeenv HOST_SH "${HOST_SH}"
523	setmakeenv BSHELL "${HOST_SH}"
524	setmakeenv CONFIG_SHELL "${HOST_SH}"
525
526	# Set defaults.
527	#
528	toolprefix=nb
529
530	# Some systems have a small ARG_MAX.  -X prevents make(1) from
531	# exporting variables in the environment redundantly.
532	#
533	case "${uname_s}" in
534	Darwin | FreeBSD | CYGWIN*)
535		MAKEFLAGS="-X ${MAKEFLAGS}"
536		;;
537	esac
538
539	# do_{operation}=true if given operation is requested.
540	#
541	do_expertmode=false
542	do_rebuildmake=false
543	do_removedirs=false
544	do_tools=false
545	do_libs=false
546	do_cleandir=false
547	do_obj=false
548	do_build=false
549	do_distribution=false
550	do_release=false
551	do_kernel=false
552	do_releasekernel=false
553	do_kernels=false
554	do_modules=false
555	do_installmodules=false
556	do_install=false
557	do_sets=false
558	do_sourcesets=false
559	do_syspkgs=false
560	do_iso_image=false
561	do_iso_image_source=false
562	do_live_image=false
563	do_install_image=false
564	do_disk_image=false
565	do_params=false
566	do_rump=false
567	do_dtb=false
568
569	# done_{operation}=true if given operation has been done.
570	#
571	done_rebuildmake=false
572
573	# Create scratch directory
574	#
575	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
576	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
577	trap "cd /; rm -r -f \"${tmpdir}\"" 0
578	results="${tmpdir}/build.sh.results"
579
580	# Set source directories
581	#
582	setmakeenv NETBSDSRCDIR "${TOP}"
583
584	# Make sure KERNOBJDIR is an absolute path if defined
585	#
586	case "${KERNOBJDIR}" in
587	''|/*)	;;
588	*)	KERNOBJDIR="${TOP}/${KERNOBJDIR}"
589		setmakeenv KERNOBJDIR "${KERNOBJDIR}"
590		;;
591	esac
592
593	# Find the version of NetBSD
594	#
595	DISTRIBVER="$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh)"
596
597	# Set the BUILDSEED to NetBSD-"N"
598	#
599	setmakeenv BUILDSEED "NetBSD-$(${HOST_SH} ${TOP}/sys/conf/osrelease.sh -m)"
600
601	# Set MKARZERO to "yes"
602	#
603	setmakeenv MKARZERO "yes"
604
605}
606
607# valid_MACHINE_ARCH -- A multi-line string, listing all valid
608# MACHINE/MACHINE_ARCH pairs.
609#
610# Each line contains a MACHINE and MACHINE_ARCH value, an optional ALIAS
611# which may be used to refer to the MACHINE/MACHINE_ARCH pair, and an
612# optional DEFAULT or NO_DEFAULT keyword.
613#
614# When a MACHINE corresponds to multiple possible values of
615# MACHINE_ARCH, then this table should list all allowed combinations.
616# If the MACHINE is associated with a default MACHINE_ARCH (to be
617# used when the user specifies the MACHINE but fails to specify the
618# MACHINE_ARCH), then one of the lines should have the "DEFAULT"
619# keyword.  If there is no default MACHINE_ARCH for a particular
620# MACHINE, then there should be a line with the "NO_DEFAULT" keyword,
621# and with a blank MACHINE_ARCH.
622#
623valid_MACHINE_ARCH='
624MACHINE=acorn32		MACHINE_ARCH=earmv4	ALIAS=eacorn32 DEFAULT
625MACHINE=algor		MACHINE_ARCH=mips64el	ALIAS=algor64
626MACHINE=algor		MACHINE_ARCH=mipsel	DEFAULT
627MACHINE=alpha		MACHINE_ARCH=alpha
628MACHINE=amd64		MACHINE_ARCH=x86_64
629MACHINE=amiga		MACHINE_ARCH=m68k
630MACHINE=amigappc	MACHINE_ARCH=powerpc
631MACHINE=arc		MACHINE_ARCH=mips64el	ALIAS=arc64
632MACHINE=arc		MACHINE_ARCH=mipsel	DEFAULT
633MACHINE=atari		MACHINE_ARCH=m68k
634MACHINE=bebox		MACHINE_ARCH=powerpc
635MACHINE=cats		MACHINE_ARCH=earmv4	ALIAS=ecats DEFAULT
636MACHINE=cesfic		MACHINE_ARCH=m68k
637MACHINE=cobalt		MACHINE_ARCH=mips64el	ALIAS=cobalt64
638MACHINE=cobalt		MACHINE_ARCH=mipsel	DEFAULT
639MACHINE=dreamcast	MACHINE_ARCH=sh3el
640MACHINE=emips		MACHINE_ARCH=mipseb
641MACHINE=epoc32		MACHINE_ARCH=earmv4	ALIAS=eepoc32 DEFAULT
642MACHINE=evbarm		MACHINE_ARCH=		NO_DEFAULT
643MACHINE=evbarm		MACHINE_ARCH=earmv4	ALIAS=evbearmv4-el	ALIAS=evbarmv4-el
644MACHINE=evbarm		MACHINE_ARCH=earmv4eb	ALIAS=evbearmv4-eb	ALIAS=evbarmv4-eb
645MACHINE=evbarm		MACHINE_ARCH=earmv5	ALIAS=evbearmv5-el	ALIAS=evbarmv5-el
646MACHINE=evbarm		MACHINE_ARCH=earmv5hf	ALIAS=evbearmv5hf-el	ALIAS=evbarmv5hf-el
647MACHINE=evbarm		MACHINE_ARCH=earmv5eb	ALIAS=evbearmv5-eb	ALIAS=evbarmv5-eb
648MACHINE=evbarm		MACHINE_ARCH=earmv5hfeb	ALIAS=evbearmv5hf-eb	ALIAS=evbarmv5hf-eb
649MACHINE=evbarm		MACHINE_ARCH=earmv6	ALIAS=evbearmv6-el	ALIAS=evbarmv6-el
650MACHINE=evbarm		MACHINE_ARCH=earmv6hf	ALIAS=evbearmv6hf-el	ALIAS=evbarmv6hf-el
651MACHINE=evbarm		MACHINE_ARCH=earmv6eb	ALIAS=evbearmv6-eb	ALIAS=evbarmv6-eb
652MACHINE=evbarm		MACHINE_ARCH=earmv6hfeb	ALIAS=evbearmv6hf-eb	ALIAS=evbarmv6hf-eb
653MACHINE=evbarm		MACHINE_ARCH=earmv7	ALIAS=evbearmv7-el	ALIAS=evbarmv7-el
654MACHINE=evbarm		MACHINE_ARCH=earmv7eb	ALIAS=evbearmv7-eb	ALIAS=evbarmv7-eb
655MACHINE=evbarm		MACHINE_ARCH=earmv7hf	ALIAS=evbearmv7hf-el	ALIAS=evbarmv7hf-el
656MACHINE=evbarm		MACHINE_ARCH=earmv7hfeb	ALIAS=evbearmv7hf-eb	ALIAS=evbarmv7hf-eb
657MACHINE=evbarm		MACHINE_ARCH=aarch64	ALIAS=evbarm64-el	ALIAS=evbarm64
658MACHINE=evbarm		MACHINE_ARCH=aarch64eb	ALIAS=evbarm64-eb
659MACHINE=evbcf		MACHINE_ARCH=coldfire
660MACHINE=evbmips		MACHINE_ARCH=		NO_DEFAULT
661MACHINE=evbmips		MACHINE_ARCH=mips64eb	ALIAS=evbmips64-eb
662MACHINE=evbmips		MACHINE_ARCH=mips64el	ALIAS=evbmips64-el
663MACHINE=evbmips		MACHINE_ARCH=mipseb	ALIAS=evbmips-eb
664MACHINE=evbmips		MACHINE_ARCH=mipsel	ALIAS=evbmips-el
665MACHINE=evbmips		MACHINE_ARCH=mipsn64eb	ALIAS=evbmipsn64-eb
666MACHINE=evbmips		MACHINE_ARCH=mipsn64el	ALIAS=evbmipsn64-el
667MACHINE=evbppc		MACHINE_ARCH=powerpc	DEFAULT
668MACHINE=evbppc		MACHINE_ARCH=powerpc64	ALIAS=evbppc64
669MACHINE=evbsh3		MACHINE_ARCH=		NO_DEFAULT
670MACHINE=evbsh3		MACHINE_ARCH=sh3eb	ALIAS=evbsh3-eb
671MACHINE=evbsh3		MACHINE_ARCH=sh3el	ALIAS=evbsh3-el
672MACHINE=ews4800mips	MACHINE_ARCH=mipseb
673MACHINE=hp300		MACHINE_ARCH=m68k
674MACHINE=hppa		MACHINE_ARCH=hppa
675MACHINE=hpcarm		MACHINE_ARCH=earmv4	ALIAS=hpcearm DEFAULT
676MACHINE=hpcmips		MACHINE_ARCH=mipsel
677MACHINE=hpcsh		MACHINE_ARCH=sh3el
678MACHINE=i386		MACHINE_ARCH=i386
679MACHINE=ia64		MACHINE_ARCH=ia64
680MACHINE=ibmnws		MACHINE_ARCH=powerpc
681MACHINE=iyonix		MACHINE_ARCH=earm	ALIAS=eiyonix DEFAULT
682MACHINE=landisk		MACHINE_ARCH=sh3el
683MACHINE=luna68k		MACHINE_ARCH=m68k
684MACHINE=mac68k		MACHINE_ARCH=m68k
685MACHINE=macppc		MACHINE_ARCH=powerpc	DEFAULT
686MACHINE=macppc		MACHINE_ARCH=powerpc64	ALIAS=macppc64
687MACHINE=mipsco		MACHINE_ARCH=mipseb
688MACHINE=mmeye		MACHINE_ARCH=sh3eb
689MACHINE=mvme68k		MACHINE_ARCH=m68k
690MACHINE=mvmeppc		MACHINE_ARCH=powerpc
691MACHINE=netwinder	MACHINE_ARCH=earmv4	ALIAS=enetwinder DEFAULT
692MACHINE=news68k		MACHINE_ARCH=m68k
693MACHINE=newsmips	MACHINE_ARCH=mipseb
694MACHINE=next68k		MACHINE_ARCH=m68k
695MACHINE=ofppc		MACHINE_ARCH=powerpc	DEFAULT
696MACHINE=ofppc		MACHINE_ARCH=powerpc64	ALIAS=ofppc64
697MACHINE=or1k		MACHINE_ARCH=or1k
698MACHINE=playstation2	MACHINE_ARCH=mipsel
699MACHINE=pmax		MACHINE_ARCH=mips64el	ALIAS=pmax64
700MACHINE=pmax		MACHINE_ARCH=mipsel	DEFAULT
701MACHINE=prep		MACHINE_ARCH=powerpc
702MACHINE=riscv		MACHINE_ARCH=riscv64	ALIAS=riscv64 DEFAULT
703MACHINE=riscv		MACHINE_ARCH=riscv32	ALIAS=riscv32
704MACHINE=rs6000		MACHINE_ARCH=powerpc
705MACHINE=sandpoint	MACHINE_ARCH=powerpc
706MACHINE=sbmips		MACHINE_ARCH=		NO_DEFAULT
707MACHINE=sbmips		MACHINE_ARCH=mips64eb	ALIAS=sbmips64-eb
708MACHINE=sbmips		MACHINE_ARCH=mips64el	ALIAS=sbmips64-el
709MACHINE=sbmips		MACHINE_ARCH=mipseb	ALIAS=sbmips-eb
710MACHINE=sbmips		MACHINE_ARCH=mipsel	ALIAS=sbmips-el
711MACHINE=sgimips		MACHINE_ARCH=mips64eb	ALIAS=sgimips64
712MACHINE=sgimips		MACHINE_ARCH=mipseb	DEFAULT
713MACHINE=shark		MACHINE_ARCH=earmv4	ALIAS=eshark DEFAULT
714MACHINE=sparc		MACHINE_ARCH=sparc
715MACHINE=sparc64		MACHINE_ARCH=sparc64
716MACHINE=sun2		MACHINE_ARCH=m68000
717MACHINE=sun3		MACHINE_ARCH=m68k
718MACHINE=vax		MACHINE_ARCH=vax
719MACHINE=x68k		MACHINE_ARCH=m68k
720MACHINE=zaurus		MACHINE_ARCH=earm	ALIAS=ezaurus DEFAULT
721'
722
723# getarch -- find the default MACHINE_ARCH for a MACHINE,
724# or convert an alias to a MACHINE/MACHINE_ARCH pair.
725#
726# Saves the original value of MACHINE in makewrappermachine before
727# alias processing.
728#
729# Sets MACHINE and MACHINE_ARCH if the input MACHINE value is
730# recognised as an alias, or recognised as a machine that has a default
731# MACHINE_ARCH (or that has only one possible MACHINE_ARCH).
732#
733# Leaves MACHINE and MACHINE_ARCH unchanged if MACHINE is recognised
734# as being associated with multiple MACHINE_ARCH values with no default.
735#
736# Bombs if MACHINE is not recognised.
737#
738getarch()
739{
740	local IFS
741	local found=""
742	local line
743
744	IFS="${nl}"
745	makewrappermachine="${MACHINE}"
746	for line in ${valid_MACHINE_ARCH}; do
747		line="${line%%#*}" # ignore comments
748		line="$( IFS=" ${tab}" ; echo $line )" # normalise white space
749		case "${line} " in
750		" ")
751			# skip blank lines or comment lines
752			continue
753			;;
754		*" ALIAS=${MACHINE} "*)
755			# Found a line with a matching ALIAS=<alias>.
756			found="$line"
757			break
758			;;
759		"MACHINE=${MACHINE} "*" NO_DEFAULT"*)
760			# Found an explicit "NO_DEFAULT" for this MACHINE.
761			found="$line"
762			break
763			;;
764		"MACHINE=${MACHINE} "*" DEFAULT"*)
765			# Found an explicit "DEFAULT" for this MACHINE.
766			found="$line"
767			break
768			;;
769		"MACHINE=${MACHINE} "*)
770			# Found a line for this MACHINE.  If it's the
771			# first such line, then tentatively accept it.
772			# If it's not the first matching line, then
773			# remember that there was more than one match.
774			case "$found" in
775			'')	found="$line" ;;
776			*)	found="MULTIPLE_MATCHES" ;;
777			esac
778			;;
779		esac
780	done
781
782	case "$found" in
783	*NO_DEFAULT*|*MULTIPLE_MATCHES*)
784		# MACHINE is OK, but MACHINE_ARCH is still unknown
785		return
786		;;
787	"MACHINE="*" MACHINE_ARCH="*)
788		# Obey the MACHINE= and MACHINE_ARCH= parts of the line.
789		IFS=" "
790		for frag in ${found}; do
791			case "$frag" in
792			MACHINE=*|MACHINE_ARCH=*)
793				eval "$frag"
794				;;
795			esac
796		done
797		;;
798	*)
799		bomb "Unknown target MACHINE: ${MACHINE}"
800		;;
801	esac
802}
803
804# validatearch -- check that the MACHINE/MACHINE_ARCH pair is supported.
805#
806# Bombs if the pair is not supported.
807#
808validatearch()
809{
810	local IFS
811	local line
812	local foundpair=false foundmachine=false foundarch=false
813
814	case "${MACHINE_ARCH}" in
815	"")
816		bomb "No MACHINE_ARCH provided. Use 'build.sh -m ${MACHINE} list-arch' to show options"
817		;;
818	esac
819
820	IFS="${nl}"
821	for line in ${valid_MACHINE_ARCH}; do
822		line="${line%%#*}" # ignore comments
823		line="$( IFS=" ${tab}" ; echo $line )" # normalise white space
824		case "${line} " in
825		" ")
826			# skip blank lines or comment lines
827			continue
828			;;
829		"MACHINE=${MACHINE} MACHINE_ARCH=${MACHINE_ARCH} "*)
830			foundpair=true
831			;;
832		"MACHINE=${MACHINE} "*)
833			foundmachine=true
834			;;
835		*"MACHINE_ARCH=${MACHINE_ARCH} "*)
836			foundarch=true
837			;;
838		esac
839	done
840
841	case "${foundpair}:${foundmachine}:${foundarch}" in
842	true:*)
843		: OK
844		;;
845	*:false:*)
846		bomb "Unknown target MACHINE: ${MACHINE}"
847		;;
848	*:*:false)
849		bomb "Unknown target MACHINE_ARCH: ${MACHINE_ARCH}"
850		;;
851	*)
852		bomb "MACHINE_ARCH '${MACHINE_ARCH}' does not support MACHINE '${MACHINE}'"
853		;;
854	esac
855}
856
857# listarch -- list valid MACHINE/MACHINE_ARCH/ALIAS values,
858# optionally restricted to those where the MACHINE and/or MACHINE_ARCH
859# match specified glob patterns.
860#
861listarch()
862{
863	local machglob="$1" archglob="$2"
864	local IFS
865	local wildcard="*"
866	local line xline frag
867	local line_matches_machine line_matches_arch
868	local found=false
869
870	# Empty machglob or archglob should match anything
871	: "${machglob:=${wildcard}}"
872	: "${archglob:=${wildcard}}"
873
874	IFS="${nl}"
875	for line in ${valid_MACHINE_ARCH}; do
876		line="${line%%#*}" # ignore comments
877		xline="$( IFS=" ${tab}" ; echo $line )" # normalise white space
878		[ -z "${xline}" ] && continue # skip blank or comment lines
879
880		line_matches_machine=false
881		line_matches_arch=false
882
883		IFS=" "
884		for frag in ${xline}; do
885			case "${frag}" in
886			MACHINE=${machglob})
887				line_matches_machine=true ;;
888			ALIAS=${machglob})
889				line_matches_machine=true ;;
890			MACHINE_ARCH=${archglob})
891				line_matches_arch=true ;;
892			esac
893		done
894
895		if $line_matches_machine && $line_matches_arch; then
896			found=true
897			echo "$line"
898		fi
899	done
900	if ! $found; then
901		echo >&2 "No match for" \
902		    "MACHINE=${machglob} MACHINE_ARCH=${archglob}"
903		return 1
904	fi
905	return 0
906}
907
908# nobomb_getmakevar --
909# Given the name of a make variable in $1, show make's idea of the
910# value of that variable, or return 1 if there's an error.
911#
912nobomb_getmakevar()
913{
914	[ -x "${make}" ] || return 1
915	"${make}" -m ${TOP}/share/mk -s -B -f- _x_ <<EOF || return 1
916_x_:
917	echo \${$1}
918.include <bsd.prog.mk>
919.include <bsd.kernobj.mk>
920EOF
921}
922
923# bomb_getmakevar --
924# Given the name of a make variable in $1, show make's idea of the
925# value of that variable, or bomb if there's an error.
926#
927bomb_getmakevar()
928{
929	[ -x "${make}" ] || bomb "bomb_getmakevar $1: ${make} is not executable"
930	nobomb_getmakevar "$1" || bomb "bomb_getmakevar $1: ${make} failed"
931}
932
933# getmakevar --
934# Given the name of a make variable in $1, show make's idea of the
935# value of that variable, or show a literal '$' followed by the
936# variable name if ${make} is not executable.  This is intended for use in
937# messages that need to be readable even if $make hasn't been built,
938# such as when build.sh is run with the "-n" option.
939#
940getmakevar()
941{
942	if [ -x "${make}" ]; then
943		bomb_getmakevar "$1"
944	else
945		echo "\$$1"
946	fi
947}
948
949setmakeenv()
950{
951	eval "$1='$2'; export $1"
952	makeenv="${makeenv} $1"
953}
954
955safe_setmakeenv()
956{
957	case "$1" in
958
959	#	Look for any vars we want to prohibit here, like:
960	# Bad | Dangerous)	usage "Cannot override $1 with -V";;
961
962	# That first char is OK has already been verified.
963	*[!A-Za-z0-9_]*)	usage "Bad variable name (-V): '$1'";;
964	esac
965	setmakeenv "$@"
966}
967
968unsetmakeenv()
969{
970	eval "unset $1"
971	makeenv="${makeenv} $1"
972}
973
974safe_unsetmakeenv()
975{
976	case "$1" in
977
978	#	Look for any vars user should not be able to unset
979	# Needed | Must_Have)	usage "Variable $1 cannot be unset";;
980
981	[!A-Za-z_]* | *[!A-Za-z0-9_]*)	usage "Bad variable name (-Z): '$1'";;
982	esac
983	unsetmakeenv "$1"
984}
985
986# Given a variable name in $1, modify the variable in place as follows:
987# For each space-separated word in the variable, call resolvepath.
988#
989resolvepaths()
990{
991	local var="$1"
992	local val
993	eval val=\"\${${var}}\"
994	local newval=''
995	local word
996	for word in ${val}; do
997		resolvepath word
998		newval="${newval}${newval:+ }${word}"
999	done
1000	eval ${var}=\"\${newval}\"
1001}
1002
1003# Given a variable name in $1, modify the variable in place as follows:
1004# Convert possibly-relative path to absolute path by prepending
1005# ${TOP} if necessary.  Also delete trailing "/", if any.
1006#
1007resolvepath()
1008{
1009	local var="$1"
1010	local val
1011	eval val=\"\${${var}}\"
1012	case "${val}" in
1013	/)
1014		;;
1015	/*)
1016		val="${val%/}"
1017		;;
1018	*)
1019		val="${TOP}/${val%/}"
1020		;;
1021	esac
1022	eval ${var}=\"\${val}\"
1023}
1024
1025# Show synopsis to stdout.
1026#
1027synopsis()
1028{
1029	cat <<_usage_
1030
1031Usage: ${progname} [-EnoPRrUux] [-a ARCH] [-B BID] [-C EXTRAS]
1032                [-c COMPILER] [-D DEST] [-j NJOB] [-M MOBJ] [-m MACH]
1033                [-N NOISY] [-O OOBJ] [-R RELEASE] [-S SEED] [-T TOOLS]
1034                [-V VAR=[VALUE]] [-w WRAPPER] [-X X11SRC]
1035                [-Z VAR]
1036                OPERATION ...
1037       ${progname} ( -h | -? )
1038
1039_usage_
1040}
1041
1042# Show help to stdout.
1043#
1044help()
1045{
1046	synopsis
1047	cat <<_usage_
1048 Build OPERATIONs (all imply "obj" and "tools"):
1049    build               Run "make build".
1050    distribution        Run "make distribution" (includes DESTDIR/etc/ files).
1051    release             Run "make release" (includes kernels & distrib media).
1052
1053 Other OPERATIONs:
1054    help                Show this help message, and exit.
1055    makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
1056                        Always performed.
1057    cleandir            Run "make cleandir".  [Default unless -u is used]
1058    dtb                 Build devicetree blobs.
1059    obj                 Run "make obj".  [Default unless -o is used]
1060    tools               Build and install tools.
1061    install=IDIR        Run "make installworld" to IDIR to install all sets
1062                        except 'etc'.  Useful after "distribution" or "release".
1063    kernel=CONF         Build kernel with config file CONF.
1064    kernel.gdb=CONF     Build kernel (including netbsd.gdb) with config
1065                        file CONF.
1066    releasekernel=CONF  Install kernel built by kernel=CONF to RELEASEDIR.
1067    kernels             Build all kernels.
1068    installmodules=IDIR Run "make installmodules" to IDIR to install all
1069                        kernel modules.
1070    modules             Build kernel modules.
1071    rumptest            Do a linktest for rump (for developers).
1072    sets                Create binary sets in
1073                        RELEASEDIR/RELEASEMACHINEDIR/binary/sets.
1074                        DESTDIR should be populated beforehand.
1075    distsets            Same as "distribution sets".
1076    sourcesets          Create source sets in RELEASEDIR/source/sets.
1077    syspkgs             Create syspkgs in
1078                        RELEASEDIR/RELEASEMACHINEDIR/binary/syspkgs.
1079    iso-image           Create CD-ROM image in RELEASEDIR/images.
1080    iso-image-source    Create CD-ROM image with source in RELEASEDIR/images.
1081    live-image          Create bootable live image in
1082                        RELEASEDIR/RELEASEMACHINEDIR/installation/liveimage.
1083    install-image       Create bootable installation image in
1084                        RELEASEDIR/RELEASEMACHINEDIR/installation/installimage.
1085    disk-image=TARGET   Create bootable disk image in
1086                        RELEASEDIR/RELEASEMACHINEDIR/binary/gzimg/TARGET.img.gz.
1087    params              Show various make(1) parameters.
1088    list-arch           Show a list of valid MACHINE/MACHINE_ARCH values,
1089                        and exit.  The list may be narrowed by passing glob
1090                        patterns or exact values in MACHINE or MACHINE_ARCH.
1091    mkrepro-timestamp   Show the latest source timestamp used for reproducable
1092                        builds and exit.  Requires -P or -V MKREPRO=yes.
1093
1094 Options:
1095    -a ARCH        Set MACHINE_ARCH=ARCH.  [Default: deduced from MACHINE]
1096    -B BID         Set BUILDID=BID.
1097    -C EXTRAS      Append EXTRAS to CDEXTRA for inclusion on CD-ROM.
1098    -c COMPILER    Select compiler from COMPILER:
1099                       clang
1100                       gcc
1101                   [Default: gcc]
1102    -D DEST        Set DESTDIR=DEST.  [Default: destdir.\${MACHINE}]
1103    -E             Set "expert" mode; disables various safety checks.
1104                   Should not be used without expert knowledge of the build
1105                   system.
1106    -h             Show this help message, and exit.
1107    -j NJOB        Run up to NJOB jobs in parallel; see make(1) -j.
1108    -M MOBJ        Set obj root directory to MOBJ; sets MAKEOBJDIRPREFIX=MOBJ,
1109                   unsets MAKEOBJDIR.
1110    -m MACH        Set MACHINE=MACH.  Some MACH values are actually
1111                   aliases that set MACHINE/MACHINE_ARCH pairs.
1112                   [Default: deduced from the host system if the host
1113                   OS is NetBSD]
1114    -N NOISY       Set the noisyness (MAKEVERBOSE) level of the build to NOISY:
1115                       0   Minimal output ("quiet").
1116                       1   Describe what is occurring.
1117                       2   Describe what is occurring and echo the actual
1118                           command.
1119                       3   Ignore the effect of the "@" prefix in make
1120                           commands.
1121                       4   Trace shell commands using the shell's -x flag.
1122                   [Default: 2]
1123    -n             Show commands that would be executed, but do not execute
1124                   them.
1125    -O OOBJ        Set obj root directory to OOBJ; sets a MAKEOBJDIR pattern
1126                   using OOBJ, unsets MAKEOBJDIRPREFIX.
1127    -o             Set MKOBJDIRS=no; do not create objdirs at start of build.
1128    -P             Set MKREPRO and MKREPRO_TIMESTAMP to the latest source
1129                   CVS timestamp for reproducible builds.
1130    -R RELEASE     Set RELEASEDIR=RELEASE.  [Default: releasedir]
1131    -r             Remove contents of TOOLDIR and DESTDIR before building.
1132    -S SEED        Set BUILDSEED=SEED.  [Default: NetBSD-majorversion]
1133    -T TOOLS       Set TOOLDIR=TOOLS.  If unset, and TOOLDIR is not set
1134                   in the environment, ${toolprefix}make will be (re)built
1135                   unconditionally.
1136    -U             Set MKUNPRIVED=yes; build without requiring root privileges,
1137                   install from an unprivileged build with proper file
1138                   permissions.
1139    -u             Set MKUPDATE=yes; do not run "make cleandir" first.
1140                   Without this, everything is rebuilt, including the tools.
1141    -V VAR=[VALUE] Set variable VAR=VALUE.
1142    -w WRAPPER     Create ${toolprefix}make script as WRAPPER.
1143                   [Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE}]
1144    -X X11SRC      Set X11SRCDIR=X11SRC.  [Default: /usr/xsrc]
1145    -x             Set MKX11=yes; build X11 from X11SRCDIR.
1146    -Z VAR         Unset ("zap") variable VAR.
1147    -?             Show this help message, and exit.
1148
1149_usage_
1150}
1151
1152# Show optional error message, help to stderr, and exit 1.
1153#
1154usage()
1155{
1156	if [ -n "$*" ]; then
1157		echo 1>&2 ""
1158		echo 1>&2 "${progname}: $*"
1159	fi
1160	synopsis 1>&2
1161	exit 1
1162}
1163
1164parseoptions()
1165{
1166	opts='a:B:C:c:D:Ehj:M:m:N:nO:oPR:rS:T:UuV:w:X:xZ:'
1167	opt_a=false
1168	opt_m=false
1169
1170	if type getopts >/dev/null 2>&1; then
1171		# Use POSIX getopts.
1172		#
1173		getoptcmd='getopts :${opts} opt && opt=-${opt}'
1174		optargcmd=':'
1175		optremcmd='shift $((${OPTIND} -1))'
1176	else
1177		type getopt >/dev/null 2>&1 ||
1178		    bomb "Shell does not support getopts or getopt"
1179
1180		# Use old-style getopt(1) (doesn't handle whitespace in args).
1181		#
1182		args="$(getopt ${opts} $*)"
1183		[ $? = 0 ] || usage
1184		set -- ${args}
1185
1186		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
1187		optargcmd='OPTARG="$1"; shift'
1188		optremcmd=':'
1189	fi
1190
1191	# Parse command line options.
1192	#
1193	while eval ${getoptcmd}; do
1194		case ${opt} in
1195
1196		-a)
1197			eval ${optargcmd}
1198			MACHINE_ARCH=${OPTARG}
1199			opt_a=true
1200			;;
1201
1202		-B)
1203			eval ${optargcmd}
1204			BUILDID=${OPTARG}
1205			;;
1206
1207		-C)
1208			eval ${optargcmd}; resolvepaths OPTARG
1209			CDEXTRA="${CDEXTRA}${CDEXTRA:+ }${OPTARG}"
1210			;;
1211
1212		-c)
1213			eval ${optargcmd}
1214			case "${OPTARG}" in
1215			gcc)	# default, no variables needed
1216				;;
1217			clang)	setmakeenv HAVE_LLVM yes
1218				setmakeenv MKLLVM yes
1219				setmakeenv MKGCC no
1220				;;
1221			#pcc)	...
1222			#	;;
1223			*)	bomb "Unknown compiler: ${OPTARG}"
1224			esac
1225			;;
1226
1227		-D)
1228			eval ${optargcmd}; resolvepath OPTARG
1229			setmakeenv DESTDIR "${OPTARG}"
1230			;;
1231
1232		-E)
1233			do_expertmode=true
1234			;;
1235
1236		-j)
1237			eval ${optargcmd}
1238			parallel="-j ${OPTARG}"
1239			;;
1240
1241		-M)
1242			eval ${optargcmd}; resolvepath OPTARG
1243			case "${OPTARG}" in
1244			\$*)	usage "-M argument must not begin with '\$'"
1245				;;
1246			*\$*)	# can use resolvepath, but can't set TOP_objdir
1247				resolvepath OPTARG
1248				;;
1249			*)	resolvepath OPTARG
1250				TOP_objdir="${OPTARG}${TOP}"
1251				;;
1252			esac
1253			unsetmakeenv MAKEOBJDIR
1254			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
1255			;;
1256
1257			# -m overrides MACHINE_ARCH unless "-a" is specified
1258		-m)
1259			eval ${optargcmd}
1260			MACHINE="${OPTARG}"
1261			opt_m=true
1262			;;
1263
1264		-N)
1265			eval ${optargcmd}
1266			case "${OPTARG}" in
1267			0|1|2|3|4)
1268				setmakeenv MAKEVERBOSE "${OPTARG}"
1269				;;
1270			*)
1271				usage "'${OPTARG}' is not a valid value for -N"
1272				;;
1273			esac
1274			;;
1275
1276		-n)
1277			runcmd=echo
1278			;;
1279
1280		-O)
1281			eval ${optargcmd}
1282			case "${OPTARG}" in
1283			*\$*)	usage "-O argument must not contain '\$'"
1284				;;
1285			*)	resolvepath OPTARG
1286				TOP_objdir="${OPTARG}"
1287				;;
1288			esac
1289			unsetmakeenv MAKEOBJDIRPREFIX
1290			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
1291			;;
1292
1293		-o)
1294			MKOBJDIRS=no
1295			;;
1296
1297		-P)
1298			MKREPRO=yes
1299			;;
1300
1301		-R)
1302			eval ${optargcmd}; resolvepath OPTARG
1303			setmakeenv RELEASEDIR "${OPTARG}"
1304			;;
1305
1306		-r)
1307			do_removedirs=true
1308			do_rebuildmake=true
1309			;;
1310
1311		-S)
1312			eval ${optargcmd}
1313			setmakeenv BUILDSEED "${OPTARG}"
1314			;;
1315
1316		-T)
1317			eval ${optargcmd}; resolvepath OPTARG
1318			TOOLDIR="${OPTARG}"
1319			export TOOLDIR
1320			;;
1321
1322		-U)
1323			setmakeenv MKUNPRIVED yes
1324			;;
1325
1326		-u)
1327			setmakeenv MKUPDATE yes
1328			;;
1329
1330		-V)
1331			eval ${optargcmd}
1332			case "${OPTARG}" in
1333		    # XXX: consider restricting which variables can be changed?
1334			[a-zA-Z_]*=*)
1335				safe_setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
1336				;;
1337			[a-zA-Z_]*)
1338				safe_setmakeenv "${OPTARG}" ""
1339				;;
1340			*)
1341				usage "-V argument must be of the form 'VAR[=VALUE]'"
1342				;;
1343			esac
1344			;;
1345
1346		-w)
1347			eval ${optargcmd}; resolvepath OPTARG
1348			makewrapper="${OPTARG}"
1349			;;
1350
1351		-X)
1352			eval ${optargcmd}; resolvepath OPTARG
1353			setmakeenv X11SRCDIR "${OPTARG}"
1354			;;
1355
1356		-x)
1357			setmakeenv MKX11 yes
1358			;;
1359
1360		-Z)
1361			eval ${optargcmd}
1362		    # XXX: consider restricting which variables can be unset?
1363			safe_unsetmakeenv "${OPTARG}"
1364			;;
1365
1366		--)
1367			break
1368			;;
1369
1370		-h)
1371			help
1372			exit 0
1373			;;
1374
1375		'-?')
1376			if [ "${OPTARG}" = '?' ]; then
1377				help
1378				exit 0
1379			fi
1380			usage "Unknown option -${OPTARG}"
1381			;;
1382
1383		-:)
1384			usage "Missing argument for option -${OPTARG}"
1385			;;
1386
1387		*)
1388			usage "Unimplemented option ${opt}"
1389			;;
1390
1391		esac
1392	done
1393
1394	# Validate operations.
1395	#
1396	eval ${optremcmd}
1397	while [ $# -gt 0 ]; do
1398		op=$1; shift
1399		operations="${operations} ${op}"
1400
1401		case "${op}" in
1402
1403		help)
1404			help
1405			exit 0
1406			;;
1407
1408		list-arch)
1409			listarch "${MACHINE}" "${MACHINE_ARCH}"
1410			exit
1411			;;
1412		mkrepro-timestamp)
1413			setup_mkrepro quiet
1414			echo ${MKREPRO_TIMESTAMP:-0}
1415			[ ${MKREPRO_TIMESTAMP:-0} -ne 0 ]; exit
1416			;;
1417
1418		kernel=*|releasekernel=*|kernel.gdb=*)
1419			arg=${op#*=}
1420			op=${op%%=*}
1421			[ -n "${arg}" ] ||
1422			    bomb "Must supply a kernel name with '${op}=...'"
1423			;;
1424
1425		disk-image=*)
1426			arg=${op#*=}
1427			op=disk_image
1428			[ -n "${arg}" ] ||
1429			    bomb "Must supply a target name with '${op}=...'"
1430
1431			;;
1432
1433		install=*|installmodules=*)
1434			arg=${op#*=}
1435			op=${op%%=*}
1436			[ -n "${arg}" ] ||
1437			    bomb "Must supply a directory with 'install=...'"
1438			;;
1439
1440		distsets)
1441			operations="$(echo "$operations" | sed 's/distsets/distribution sets/')"
1442			do_sets=true
1443			op=distribution
1444			;;
1445
1446		build|\
1447		cleandir|\
1448		distribution|\
1449		dtb|\
1450		install-image|\
1451		iso-image-source|\
1452		iso-image|\
1453		kernels|\
1454		libs|\
1455		live-image|\
1456		makewrapper|\
1457		modules|\
1458		obj|\
1459		params|\
1460		release|\
1461		rump|\
1462		rumptest|\
1463		sets|\
1464		sourcesets|\
1465		syspkgs|\
1466		tools)
1467			;;
1468
1469		*)
1470			usage "Unknown OPERATION '${op}'"
1471			;;
1472
1473		esac
1474		# ${op} may contain chars that are not allowed in variable
1475		# names.  Replace them with '_' before setting do_${op}.
1476		op="$( echo "$op" | tr -s '.-' '__')"
1477		eval do_${op}=true
1478	done
1479	[ -n "${operations}" ] || usage "Missing OPERATION to perform"
1480
1481	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
1482	#
1483	if [ -z "${MACHINE}" ]; then
1484		[ "${uname_s}" = "NetBSD" ] ||
1485		    bomb "MACHINE must be set, or -m must be used, for cross builds"
1486		MACHINE=${uname_m}
1487		MACHINE_ARCH=${uname_p}
1488	fi
1489	if $opt_m && ! $opt_a; then
1490		# Settings implied by the command line -m option
1491		# override MACHINE_ARCH from the environment (if any).
1492		getarch
1493	fi
1494	[ -n "${MACHINE_ARCH}" ] || getarch
1495	validatearch
1496
1497	# Set up default make(1) environment.
1498	#
1499	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
1500	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
1501	[ -z "${BUILDINFO}" ] || makeenv="${makeenv} BUILDINFO"
1502	MAKEFLAGS="-de -m ${TOP}/share/mk ${MAKEFLAGS}"
1503	MAKEFLAGS="${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
1504	export MAKEFLAGS MACHINE MACHINE_ARCH
1505	setmakeenv USETOOLS "yes"
1506	setmakeenv MAKEWRAPPERMACHINE "${makewrappermachine:-${MACHINE}}"
1507	setmakeenv MAKE_OBJDIR_CHECK_WRITABLE no
1508}
1509
1510# sanitycheck --
1511# Sanity check after parsing command line options, before rebuildmake.
1512#
1513sanitycheck()
1514{
1515	# Install as non-root is a bad idea.
1516	#
1517	if ${do_install} && [ "$id_u" -ne 0 ] ; then
1518		if ${do_expertmode}; then
1519			warning "Will install as an unprivileged user"
1520		else
1521			bomb "-E must be set for install as an unprivileged user"
1522		fi
1523	fi
1524
1525	# If the PATH contains any non-absolute components (including,
1526	# but not limited to, "." or ""), then complain.  As an exception,
1527	# allow "" or "." as the last component of the PATH.  This is fatal
1528	# if expert mode is not in effect.
1529	#
1530	local path="${PATH}"
1531	path="${path%:}"	# delete trailing ":"
1532	path="${path%:.}"	# delete trailing ":."
1533	case ":${path}:/" in
1534	*:[!/~]*)
1535		if ${do_expertmode}; then
1536			warning "PATH contains non-absolute components"
1537		else
1538			bomb "PATH environment variable must not" \
1539			     "contain non-absolute components"
1540		fi
1541		;;
1542	esac
1543
1544	while [ ${MKX11-no} = "yes" ]; do		# not really a loop
1545		test -n "${X11SRCDIR}" && {
1546		    test -d "${X11SRCDIR}" ||
1547		    	bomb "X11SRCDIR (${X11SRCDIR}) does not exist (with -x)"
1548		    break
1549		}
1550		for _xd in \
1551		    "${NETBSDSRCDIR%/*}/xsrc" \
1552		    "${NETBSDSRCDIR}/xsrc" \
1553		    /usr/xsrc
1554		do
1555		    test -d "${_xd}" &&
1556			setmakeenv X11SRCDIR "${_xd}" &&
1557			break 2
1558		done
1559		bomb "Asked to build X11 but no xsrc"
1560	done
1561}
1562
1563# print_tooldir_program --
1564# Try to find and show a path to an existing
1565# ${TOOLDIR}/bin/${toolprefix}program
1566#
1567print_tooldir_program()
1568{
1569	local possible_TOP_OBJ
1570	local possible_TOOLDIR
1571	local possible_program
1572	local tooldir_program
1573	local program=${1}
1574
1575	if [ -n "${TOOLDIR}" ]; then
1576		echo "${TOOLDIR}/bin/${toolprefix}${program}"
1577		return
1578	fi
1579
1580	# Set host_ostype to something like "NetBSD-4.5.6-i386".  This
1581	# is intended to match the HOST_OSTYPE variable in <bsd.own.mk>.
1582	#
1583	local host_ostype="${uname_s}-$(
1584		echo "${uname_r}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
1585		)-$(
1586		echo "${uname_p}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
1587		)"
1588
1589	# Look in a few potential locations for
1590	# ${possible_TOOLDIR}/bin/${toolprefix}${program}.
1591	# If we find it, then set possible_program.
1592	#
1593	# In the usual case (without interference from environment
1594	# variables or /etc/mk.conf), <bsd.own.mk> should set TOOLDIR to
1595	# "${_SRC_TOP_OBJ_}/tooldir.${host_ostype}".
1596	#
1597	# In practice it's difficult to figure out the correct value
1598	# for _SRC_TOP_OBJ_.  In the easiest case, when the -M or -O
1599	# options were passed to build.sh, then ${TOP_objdir} will be
1600	# the correct value.  We also try a few other possibilities, but
1601	# we do not replicate all the logic of <bsd.obj.mk>.
1602	#
1603	for possible_TOP_OBJ in \
1604		"${TOP_objdir}" \
1605		"${MAKEOBJDIRPREFIX:+${MAKEOBJDIRPREFIX}${TOP}}" \
1606		"${TOP}" \
1607		"${TOP}/obj" \
1608		"${TOP}/obj.${MACHINE}"
1609	do
1610		[ -n "${possible_TOP_OBJ}" ] || continue
1611		possible_TOOLDIR="${possible_TOP_OBJ}/tooldir.${host_ostype}"
1612		possible_program="${possible_TOOLDIR}/bin/${toolprefix}${program}"
1613		if [ -x "${possible_make}" ]; then
1614			echo ${possible_program}
1615			return;
1616		fi
1617	done
1618	echo ""
1619}
1620
1621# print_tooldir_make --
1622# Try to find and show a path to an existing
1623# ${TOOLDIR}/bin/${toolprefix}make, for use by rebuildmake() before a
1624# new version of ${toolprefix}make has been built.
1625#
1626# * If TOOLDIR was set in the environment or on the command line, use
1627#   that value.
1628# * Otherwise try to guess what TOOLDIR would be if not overridden by
1629#   /etc/mk.conf, and check whether the resulting directory contains
1630#   a copy of ${toolprefix}make (this should work for everybody who
1631#   doesn't override TOOLDIR via /etc/mk.conf);
1632# * Failing that, search for ${toolprefix}make, nbmake, bmake, or make,
1633#   in the PATH (this might accidentally find a version of make that
1634#   does not understand the syntax used by NetBSD make, and that will
1635#   lead to failure in the next step);
1636# * If a copy of make was found above, try to use it with
1637#   nobomb_getmakevar to find the correct value for TOOLDIR, and believe the
1638#   result only if it's a directory that already exists;
1639# * If a value of TOOLDIR was found above, and if
1640#   ${TOOLDIR}/bin/${toolprefix}make exists, show that value.
1641#
1642print_tooldir_make()
1643{
1644	local possible_make
1645	local possible_TOOLDIR
1646	local tooldir_make
1647
1648	possible_make=$(print_tooldir_program make)
1649	# If the above didn't work, search the PATH for a suitable
1650	# ${toolprefix}make, nbmake, bmake, or make.
1651	#
1652	: ${possible_make:=$(find_in_PATH ${toolprefix}make '')}
1653	: ${possible_make:=$(find_in_PATH nbmake '')}
1654	: ${possible_make:=$(find_in_PATH bmake '')}
1655	: ${possible_make:=$(find_in_PATH make '')}
1656
1657	# At this point, we don't care whether possible_make is in the
1658	# correct TOOLDIR or not; we simply want it to be usable by
1659	# getmakevar to help us find the correct TOOLDIR.
1660	#
1661	# Use ${possible_make} with nobomb_getmakevar to try to find
1662	# the value of TOOLDIR.  Believe the result only if it's
1663	# a directory that already exists and contains bin/${toolprefix}make.
1664	#
1665	if [ -x "${possible_make}" ]; then
1666		possible_TOOLDIR="$(
1667			make="${possible_make}" \
1668			nobomb_getmakevar TOOLDIR 2>/dev/null
1669			)"
1670		if [ $? = 0 ] && [ -n "${possible_TOOLDIR}" ] \
1671		    && [ -d "${possible_TOOLDIR}" ];
1672		then
1673			tooldir_make="${possible_TOOLDIR}/bin/${toolprefix}make"
1674			if [ -x "${tooldir_make}" ]; then
1675				echo "${tooldir_make}"
1676				return 0
1677			fi
1678		fi
1679	fi
1680	return 1
1681}
1682
1683# rebuildmake --
1684# Rebuild nbmake in a temporary directory if necessary.  Sets $make
1685# to a path to the nbmake executable.  Sets done_rebuildmake=true
1686# if nbmake was rebuilt.
1687#
1688# There is a cyclic dependency between building nbmake and choosing
1689# TOOLDIR: TOOLDIR may be affected by settings in /etc/mk.conf, so we
1690# would like to use getmakevar to get the value of TOOLDIR; but we can't
1691# use getmakevar before we have an up to date version of nbmake; we
1692# might already have an up to date version of nbmake in TOOLDIR, but we
1693# don't yet know where TOOLDIR is.
1694#
1695# The default value of TOOLDIR also depends on the location of the top
1696# level object directory, so $(getmakevar TOOLDIR) invoked before or
1697# after making the top level object directory may produce different
1698# results.
1699#
1700# Strictly speaking, we should do the following:
1701#
1702#    1. build a new version of nbmake in a temporary directory;
1703#    2. use the temporary nbmake to create the top level obj directory;
1704#    3. use $(getmakevar TOOLDIR) with the temporary nbmake to
1705#       get the correct value of TOOLDIR;
1706#    4. move the temporary nbmake to ${TOOLDIR}/bin/nbmake.
1707#
1708# However, people don't like building nbmake unnecessarily if their
1709# TOOLDIR has not changed since an earlier build.  We try to avoid
1710# rebuilding a temporary version of nbmake by taking some shortcuts to
1711# guess a value for TOOLDIR, looking for an existing version of nbmake
1712# in that TOOLDIR, and checking whether that nbmake is newer than the
1713# sources used to build it.
1714#
1715rebuildmake()
1716{
1717	make="$(print_tooldir_make)"
1718	if [ -n "${make}" ] && [ -x "${make}" ]; then
1719		for f in usr.bin/make/*.[ch]; do
1720			if [ "${f}" -nt "${make}" ]; then
1721				statusmsg "${make} outdated" \
1722					"(older than ${f}), needs building."
1723				do_rebuildmake=true
1724				break
1725			fi
1726		done
1727	else
1728		statusmsg "No \$TOOLDIR/bin/${toolprefix}make, needs building."
1729		do_rebuildmake=true
1730	fi
1731
1732	# Build bootstrap ${toolprefix}make if needed.
1733	if ! ${do_rebuildmake}; then
1734		return
1735	fi
1736
1737	# Silent configure with MAKEVERBOSE==0
1738	if [ ${MAKEVERBOSE:-2} -eq 0 ]; then
1739		configure_args=--silent
1740	fi
1741
1742	statusmsg "Bootstrapping ${toolprefix}make"
1743	${runcmd} cd "${tmpdir}"
1744	${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
1745		CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
1746	    ${HOST_SH} "${TOP}/tools/make/configure" ${configure_args} ||
1747	( cp ${tmpdir}/config.log ${tmpdir}-config.log
1748	      bomb "Configure of ${toolprefix}make failed, see ${tmpdir}-config.log for details" )
1749	${runcmd} ${HOST_SH} buildmake.sh ||
1750	    bomb "Build of ${toolprefix}make failed"
1751	make="${tmpdir}/${toolprefix}make"
1752	${runcmd} cd "${TOP}"
1753	${runcmd} rm -f usr.bin/make/*.o
1754	done_rebuildmake=true
1755}
1756
1757# validatemakeparams --
1758# Perform some late sanity checks, after rebuildmake,
1759# but before createmakewrapper or any real work.
1760#
1761# Creates the top-level obj directory, because that
1762# is needed by some of the sanity checks.
1763#
1764# Shows status messages reporting the values of several variables.
1765#
1766validatemakeparams()
1767{
1768	# MAKECONF (which defaults to /etc/mk.conf in share/mk/bsd.own.mk)
1769	# can affect many things, so mention it in an early status message.
1770	#
1771	MAKECONF=$(getmakevar MAKECONF)
1772	if [ -e "${MAKECONF}" ]; then
1773		statusmsg2 "MAKECONF file:" "${MAKECONF}"
1774	else
1775		statusmsg2 "MAKECONF file:" "${MAKECONF} (File not found)"
1776	fi
1777
1778	# Normalise MKOBJDIRS, MKUNPRIVED, and MKUPDATE.
1779	# These may be set as build.sh options or in "mk.conf".
1780	# Don't export them as they're only used for tests in build.sh.
1781	#
1782	MKOBJDIRS=$(getmakevar MKOBJDIRS)
1783	MKUNPRIVED=$(getmakevar MKUNPRIVED)
1784	MKUPDATE=$(getmakevar MKUPDATE)
1785
1786	# Non-root should always use either the -U or -E flag.
1787	#
1788	if ! ${do_expertmode} && \
1789	    [ "$id_u" -ne 0 ] && \
1790	    [ "${MKUNPRIVED}" = "no" ] ; then
1791		bomb "-U or -E must be set for build as an unprivileged user"
1792	fi
1793
1794	if [ "${runcmd}" = "echo" ]; then
1795		TOOLCHAIN_MISSING=no
1796		EXTERNAL_TOOLCHAIN=""
1797	else
1798		TOOLCHAIN_MISSING=$(bomb_getmakevar TOOLCHAIN_MISSING)
1799		EXTERNAL_TOOLCHAIN=$(bomb_getmakevar EXTERNAL_TOOLCHAIN)
1800	fi
1801	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
1802	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
1803		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
1804		${runcmd} echo "	MACHINE:      ${MACHINE}"
1805		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
1806		${runcmd} echo ""
1807		${runcmd} echo "All builds for this platform should be done via a traditional make"
1808		${runcmd} echo "If you wish to use an external cross-toolchain, set"
1809		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
1810		${runcmd} echo "in either the environment or mk.conf and rerun"
1811		${runcmd} echo "	${progname} $*"
1812		exit 1
1813	fi
1814
1815	if [ "${MKOBJDIRS}" != "no" ]; then
1816		# Create the top-level object directory.
1817		#
1818		# "make obj NOSUBDIR=" can handle most cases, but it
1819		# can't handle the case where MAKEOBJDIRPREFIX is set
1820		# while the corresponding directory does not exist
1821		# (rules in <bsd.obj.mk> would abort the build).  We
1822		# therefore have to handle the MAKEOBJDIRPREFIX case
1823		# without invoking "make obj".  The MAKEOBJDIR case
1824		# could be handled either way, but we choose to handle
1825		# it similarly to MAKEOBJDIRPREFIX.
1826		#
1827		if [ -n "${TOP_obj}" ]; then
1828			# It must have been set by the "-M" or "-O"
1829			# command line options, so there's no need to
1830			# use getmakevar
1831			:
1832		elif [ -n "$MAKEOBJDIRPREFIX" ]; then
1833			TOP_obj="$(getmakevar MAKEOBJDIRPREFIX)${TOP}"
1834		elif [ -n "$MAKEOBJDIR" ]; then
1835			TOP_obj="$(getmakevar MAKEOBJDIR)"
1836		fi
1837		if [ -n "$TOP_obj" ]; then
1838			${runcmd} mkdir -p "${TOP_obj}" ||
1839			    bomb "Can't create top level object directory" \
1840					"${TOP_obj}"
1841		else
1842			${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
1843			    bomb "Can't create top level object directory" \
1844					"using make obj"
1845		fi
1846
1847		# make obj in tools to ensure that the objdir for "tools"
1848		# is available.
1849		#
1850		${runcmd} cd tools
1851		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
1852		    bomb "Failed to make obj in tools"
1853		${runcmd} cd "${TOP}"
1854	fi
1855
1856	# Find TOOLDIR, DESTDIR, and RELEASEDIR, according to getmakevar,
1857	# and bomb if they have changed from the values we had from the
1858	# command line or environment.
1859	#
1860	# This must be done after creating the top-level object directory.
1861	#
1862	for var in TOOLDIR DESTDIR RELEASEDIR
1863	do
1864		eval oldval=\"\$${var}\"
1865		newval="$(getmakevar $var)"
1866		if ! $do_expertmode; then
1867			: ${_SRC_TOP_OBJ_:=$(getmakevar _SRC_TOP_OBJ_)}
1868			case "$var" in
1869			DESTDIR)
1870				: ${newval:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
1871				makeenv="${makeenv} DESTDIR"
1872				;;
1873			RELEASEDIR)
1874				: ${newval:=${_SRC_TOP_OBJ_}/releasedir}
1875				makeenv="${makeenv} RELEASEDIR"
1876				;;
1877			esac
1878		fi
1879		if [ -n "$oldval" ] && [ "$oldval" != "$newval" ]; then
1880			bomb "Value of ${var} has changed" \
1881				"(was \"${oldval}\", now \"${newval}\")"
1882		fi
1883		eval ${var}=\"\${newval}\"
1884		eval export ${var}
1885		statusmsg2 "${var} path:" "${newval}"
1886	done
1887
1888	# RELEASEMACHINEDIR is just a subdir name, e.g. "i386".
1889	RELEASEMACHINEDIR=$(getmakevar RELEASEMACHINEDIR)
1890
1891	# Check validity of TOOLDIR and DESTDIR.
1892	#
1893	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
1894		bomb "TOOLDIR '${TOOLDIR}' invalid"
1895	fi
1896	removedirs="${TOOLDIR}"
1897
1898	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
1899		if ${do_distribution} || ${do_release} || \
1900		   [ "${uname_s}" != "NetBSD" ] || \
1901		   [ "${uname_m}" != "${MACHINE}" ]; then
1902			bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'"
1903		fi
1904		if ! ${do_expertmode}; then
1905			bomb "DESTDIR must != / for non -E (expert) builds"
1906		fi
1907		statusmsg "WARNING: Building to /, in expert mode."
1908		statusmsg "         This may cause your system to break!  Reasons include:"
1909		statusmsg "            - your kernel is not up to date"
1910		statusmsg "            - the libraries or toolchain have changed"
1911		statusmsg "         YOU HAVE BEEN WARNED!"
1912	else
1913		removedirs="${removedirs} ${DESTDIR}"
1914	fi
1915	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
1916		bomb "Must set RELEASEDIR with 'releasekernel=...'"
1917	fi
1918
1919	# If a previous build.sh run used -U (and therefore created a
1920	# METALOG file), then most subsequent build.sh runs must also
1921	# use -U.  If DESTDIR is about to be removed, then don't perform
1922	# this check.
1923	#
1924	case "${do_removedirs} ${removedirs} " in
1925	true*" ${DESTDIR} "*)
1926		# DESTDIR is about to be removed
1927		;;
1928	*)
1929		if [ -e "${DESTDIR}/METALOG" ] && \
1930		    [ "${MKUNPRIVED}" = "no" ] ; then
1931			if $do_expertmode; then
1932				warning "A previous build.sh run specified -U"
1933			else
1934				bomb "A previous build.sh run specified -U; you must specify it again now"
1935			fi
1936		fi
1937		;;
1938	esac
1939
1940	# live-image and install-image targets require binary sets
1941	# (actually DESTDIR/etc/mtree/set.* files) built with MKUNPRIVED.
1942	# If release operation is specified with live-image or install-image,
1943	# the release op should be performed with -U for later image ops.
1944	#
1945	if ${do_release} && ( ${do_live_image} || ${do_install_image} ) && \
1946	    [ "${MKUNPRIVED}" = "no" ] ; then
1947		bomb "-U must be specified on building release to create images later"
1948	fi
1949}
1950
1951
1952createmakewrapper()
1953{
1954	# Remove the target directories.
1955	#
1956	if ${do_removedirs}; then
1957		for f in ${removedirs}; do
1958			statusmsg "Removing ${f}"
1959			${runcmd} rm -r -f "${f}"
1960		done
1961	fi
1962
1963	# Recreate $TOOLDIR.
1964	#
1965	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
1966	    bomb "mkdir of '${TOOLDIR}/bin' failed"
1967
1968	# If we did not previously rebuild ${toolprefix}make, then
1969	# check whether $make is still valid and the same as the output
1970	# from print_tooldir_make.  If not, then rebuild make now.  A
1971	# possible reason for this being necessary is that the actual
1972	# value of TOOLDIR might be different from the value guessed
1973	# before the top level obj dir was created.
1974	#
1975	if ! ${done_rebuildmake} && \
1976	    ( [ ! -x "$make" ] || [ "$make" != "$(print_tooldir_make)" ] )
1977	then
1978		rebuildmake
1979	fi
1980
1981	# Install ${toolprefix}make if it was built.
1982	#
1983	if ${done_rebuildmake}; then
1984		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
1985		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
1986		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
1987		make="${TOOLDIR}/bin/${toolprefix}make"
1988		statusmsg "Created ${make}"
1989	fi
1990
1991	# Build a ${toolprefix}make wrapper script, usable by hand as
1992	# well as by build.sh.
1993	#
1994	if [ -z "${makewrapper}" ]; then
1995		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
1996		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
1997	fi
1998
1999	${runcmd} rm -f "${makewrapper}"
2000	if [ "${runcmd}" = "echo" ]; then
2001		echo 'cat <<EOF >'${makewrapper}
2002		makewrapout=
2003	else
2004		makewrapout=">>\${makewrapper}"
2005	fi
2006
2007	case "${KSH_VERSION:-${SH_VERSION}}" in
2008	*PD\ KSH*|*MIRBSD\ KSH*)
2009		set +o braceexpand
2010		;;
2011	esac
2012
2013	eval cat <<EOF ${makewrapout}
2014#! ${HOST_SH}
2015# Set proper variables to allow easy "make" building of a NetBSD subtree.
2016# Generated from:  \$NetBSD: build.sh,v 1.370 2023/06/02 14:29:11 lukem Exp $
2017# with these arguments: ${_args}
2018#
2019
2020EOF
2021	{
2022		sorted_vars="$(for var in ${makeenv}; do echo "${var}" ; done \
2023			| sort -u )"
2024		for var in ${sorted_vars}; do
2025			eval val=\"\${${var}}\"
2026			eval is_set=\"\${${var}+set}\"
2027			if [ -z "${is_set}" ]; then
2028				echo "unset ${var}"
2029			else
2030				qval="$(shell_quote "${val}")"
2031				echo "${var}=${qval}; export ${var}"
2032			fi
2033		done
2034
2035		cat <<EOF
2036
2037exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
2038EOF
2039	} | eval cat "${makewrapout}"
2040	[ "${runcmd}" = "echo" ] && echo EOF
2041	${runcmd} chmod +x "${makewrapper}"
2042	statusmsg2 "Updated makewrapper:" "${makewrapper}"
2043}
2044
2045make_in_dir()
2046{
2047	local dir="$1"
2048	local op="$2"
2049	${runcmd} cd "${dir}" ||
2050	    bomb "Failed to cd to \"${dir}\""
2051	${runcmd} "${makewrapper}" ${parallel} ${op} ||
2052	    bomb "Failed to make ${op} in \"${dir}\""
2053	${runcmd} cd "${TOP}" ||
2054	    bomb "Failed to cd back to \"${TOP}\""
2055}
2056
2057buildtools()
2058{
2059	if [ "${MKOBJDIRS}" != "no" ]; then
2060		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
2061		    bomb "Failed to make obj-tools"
2062	fi
2063	if [ "${MKUPDATE}" = "no" ]; then
2064		make_in_dir tools cleandir
2065	fi
2066	make_in_dir tools build_install
2067	statusmsg "Tools built to ${TOOLDIR}"
2068}
2069
2070buildlibs()
2071{
2072	if [ "${MKOBJDIRS}" != "no" ]; then
2073		${runcmd} "${makewrapper}" ${parallel} obj ||
2074		    bomb "Failed to make obj"
2075	fi
2076	if [ "${MKUPDATE}" = "no" ]; then
2077		make_in_dir lib cleandir
2078	fi
2079	make_in_dir . do-distrib-dirs
2080	make_in_dir . includes
2081	make_in_dir . do-lib
2082	statusmsg "libs built"
2083}
2084
2085getkernelconf()
2086{
2087	kernelconf="$1"
2088	if [ "${MKOBJDIRS}" != "no" ]; then
2089		# The correct value of KERNOBJDIR might
2090		# depend on a prior "make obj" in
2091		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
2092		#
2093		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
2094		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
2095		make_in_dir "${KERNSRCDIR}/${KERNARCHDIR}/compile" obj
2096	fi
2097	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
2098	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
2099	case "${kernelconf}" in
2100	*/*)
2101		kernelconfpath="${kernelconf}"
2102		kernelconfname="${kernelconf##*/}"
2103		;;
2104	*)
2105		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
2106		kernelconfname="${kernelconf}"
2107		;;
2108	esac
2109	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
2110}
2111
2112diskimage()
2113{
2114	ARG="$(echo $1 | tr '[:lower:]' '[:upper:]')"
2115	[ -f "${DESTDIR}/etc/mtree/set.base" ] ||
2116	    bomb "The release binaries must be built first"
2117	kerneldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
2118	kernel="${kerneldir}/netbsd-${ARG}.gz"
2119	[ -f "${kernel}" ] ||
2120	    bomb "The kernel ${kernel} must be built first"
2121	make_in_dir "${NETBSDSRCDIR}/etc" "smp_${1}"
2122}
2123
2124buildkernel()
2125{
2126	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
2127		# Building tools every time we build a kernel is clearly
2128		# unnecessary.  We could try to figure out whether rebuilding
2129		# the tools is necessary this time, but it doesn't seem worth
2130		# the trouble.  Instead, we say it's the user's responsibility
2131		# to rebuild the tools if necessary.
2132		#
2133		statusmsg "Building kernel without building new tools"
2134		buildkernelwarned=true
2135	fi
2136	getkernelconf $1
2137	statusmsg2 "Building kernel:" "${kernelconf}"
2138	statusmsg2 "Build directory:" "${kernelbuildpath}"
2139	${runcmd} mkdir -p "${kernelbuildpath}" ||
2140	    bomb "Cannot mkdir: ${kernelbuildpath}"
2141	if [ "${MKUPDATE}" = "no" ]; then
2142		make_in_dir "${kernelbuildpath}" cleandir
2143	fi
2144	[ -x "${TOOLDIR}/bin/${toolprefix}config" ] \
2145	|| bomb "${TOOLDIR}/bin/${toolprefix}config does not exist. You need to \"$0 tools\" first"
2146	CONFIGOPTS=$(getmakevar CONFIGOPTS)
2147	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" ${CONFIGOPTS} \
2148		-b "${kernelbuildpath}" -s "${TOP}/sys" ${configopts} \
2149		"${kernelconfpath}" ||
2150	    bomb "${toolprefix}config failed for ${kernelconf}"
2151	make_in_dir "${kernelbuildpath}" depend
2152	make_in_dir "${kernelbuildpath}" all
2153
2154	if [ "${runcmd}" != "echo" ]; then
2155		statusmsg "Kernels built from ${kernelconf}:"
2156		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
2157		for kern in ${kernlist:-netbsd}; do
2158			[ -f "${kernelbuildpath}/${kern}" ] && \
2159			    echo "  ${kernelbuildpath}/${kern}"
2160		done | tee -a "${results}"
2161	fi
2162}
2163
2164releasekernel()
2165{
2166	getkernelconf $1
2167	kernelreldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
2168	${runcmd} mkdir -p "${kernelreldir}"
2169	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
2170	for kern in ${kernlist:-netbsd}; do
2171		builtkern="${kernelbuildpath}/${kern}"
2172		[ -f "${builtkern}" ] || continue
2173		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
2174		statusmsg2 "Kernel copy:" "${releasekern}"
2175		if [ "${runcmd}" = "echo" ]; then
2176			echo "gzip -c -9 < ${builtkern} > ${releasekern}"
2177		else
2178			gzip -c -9 < "${builtkern}" > "${releasekern}"
2179		fi
2180	done
2181}
2182
2183buildkernels()
2184{
2185	allkernels=$( runcmd= make_in_dir etc '-V ${ALL_KERNELS}' )
2186	for k in $allkernels; do
2187		buildkernel "${k}"
2188	done
2189}
2190
2191buildmodules()
2192{
2193	setmakeenv MKBINUTILS no
2194	if ! ${do_tools} && ! ${buildmoduleswarned:-false}; then
2195		# Building tools every time we build modules is clearly
2196		# unnecessary as well as a kernel.
2197		#
2198		statusmsg "Building modules without building new tools"
2199		buildmoduleswarned=true
2200	fi
2201
2202	statusmsg "Building kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
2203	if [ "${MKOBJDIRS}" != "no" ]; then
2204		make_in_dir sys/modules obj
2205	fi
2206	if [ "${MKUPDATE}" = "no" ]; then
2207		make_in_dir sys/modules cleandir
2208	fi
2209	make_in_dir sys/modules dependall
2210	make_in_dir sys/modules install
2211
2212	statusmsg "Successful build of kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
2213}
2214
2215builddtb()
2216{
2217	statusmsg "Building devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
2218	if [ "${MKOBJDIRS}" != "no" ]; then
2219		make_in_dir sys/dtb obj
2220	fi
2221	if [ "${MKUPDATE}" = "no" ]; then
2222		make_in_dir sys/dtb cleandir
2223	fi
2224	make_in_dir sys/dtb dependall
2225	make_in_dir sys/dtb install
2226
2227	statusmsg "Successful build of devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
2228}
2229
2230installmodules()
2231{
2232	dir="$1"
2233	${runcmd} "${makewrapper}" INSTALLMODULESDIR="${dir}" installmodules ||
2234	    bomb "Failed to make installmodules to ${dir}"
2235	statusmsg "Successful installmodules to ${dir}"
2236}
2237
2238installworld()
2239{
2240	dir="$1"
2241	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
2242	    bomb "Failed to make installworld to ${dir}"
2243	statusmsg "Successful installworld to ${dir}"
2244}
2245
2246# Run rump build&link tests.
2247#
2248# To make this feasible for running without having to install includes and
2249# libraries into destdir (i.e. quick), we only run ld.  This is possible
2250# since the rump kernel is a closed namespace apart from calls to rumpuser.
2251# Therefore, if ld complains only about rumpuser symbols, rump kernel
2252# linking was successful.
2253#
2254# We test that rump links with a number of component configurations.
2255# These attempt to mimic what is encountered in the full build.
2256# See list below.  The list should probably be either autogenerated
2257# or managed elsewhere; keep it here until a better idea arises.
2258#
2259# Above all, note that THIS IS NOT A SUBSTITUTE FOR A FULL BUILD.
2260#
2261
2262# XXX: uwe: kern/56599 - while riastradh addressed librump problems,
2263# there are still unwanted dependencies:
2264#    net -> net_net
2265#    vfs -> fifo
2266
2267# -lrumpvfs -> $LRUMPVFS for now
2268LRUMPVFS="-lrumpvfs -lrumpvfs_nofifofs"
2269
2270RUMP_LIBSETS="
2271	-lrump,
2272        -lrumpvfs
2273            --no-whole-archive -lrumpvfs_nofifofs -lrump,
2274	-lrumpkern_tty
2275            --no-whole-archive $LRUMPVFS -lrump,
2276	-lrumpfs_tmpfs
2277            --no-whole-archive $LRUMPVFS -lrump,
2278	-lrumpfs_ffs -lrumpfs_msdos
2279            --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrump,
2280	-lrumpnet_virtif -lrumpnet_netinet -lrumpnet_net -lrumpnet
2281	    --no-whole-archive -lrump,
2282	-lrumpfs_nfs
2283	    --no-whole-archive $LRUMPVFS
2284	    -lrumpnet_sockin -lrumpnet_virtif -lrumpnet_netinet
2285            --start-group -lrumpnet_net -lrumpnet --end-group -lrump,
2286	-lrumpdev_cgd -lrumpdev_raidframe -lrumpdev_rnd -lrumpdev_dm
2287            --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrumpkern_crypto -lrump
2288"
2289
2290dorump()
2291{
2292	local doclean=""
2293	local doobjs=""
2294
2295	export RUMPKERN_ONLY=1
2296	# create obj and distrib dirs
2297	if [ "${MKOBJDIRS}" != "no" ]; then
2298		make_in_dir "${NETBSDSRCDIR}/etc/mtree" obj
2299		make_in_dir "${NETBSDSRCDIR}/sys/rump" obj
2300	fi
2301	${runcmd} "${makewrapper}" ${parallel} do-distrib-dirs \
2302	    || bomb "Could not create distrib-dirs"
2303
2304	[ "${MKUPDATE}" = "no" ] && doclean="cleandir"
2305	targlist="${doclean} ${doobjs} dependall install"
2306	# optimize: for test we build only static libs (3x test speedup)
2307	if [ "${1}" = "rumptest" ] ; then
2308		setmakeenv NOPIC 1
2309		setmakeenv NOPROFILE 1
2310	fi
2311	for cmd in ${targlist} ; do
2312		make_in_dir "${NETBSDSRCDIR}/sys/rump" ${cmd}
2313	done
2314
2315	# if we just wanted to build & install rump, we're done
2316	[ "${1}" != "rumptest" ] && return
2317
2318	${runcmd} cd "${NETBSDSRCDIR}/sys/rump/librump/rumpkern" \
2319	    || bomb "cd to rumpkern failed"
2320	md_quirks=`${runcmd} "${makewrapper}" -V '${_SYMQUIRK}'`
2321	# one little, two little, three little backslashes ...
2322	md_quirks="$(echo ${md_quirks} | sed 's,\\,\\\\,g'";s/'//g" )"
2323	${runcmd} cd "${TOP}" || bomb "cd to ${TOP} failed"
2324	tool_ld=`${runcmd} "${makewrapper}" -V '${LD}'`
2325
2326	local oIFS="${IFS}"
2327	IFS=","
2328	for set in ${RUMP_LIBSETS} ; do
2329		IFS="${oIFS}"
2330		${runcmd} ${tool_ld} -nostdlib -L${DESTDIR}/usr/lib	\
2331		    -static --whole-archive ${set} --no-whole-archive -lpthread -lc 2>&1 -o /tmp/rumptest.$$ | \
2332		      awk -v quirks="${md_quirks}" '
2333			/undefined reference/ &&
2334			    !/more undefined references.*follow/{
2335				if (match($NF,
2336				    "`(rumpuser_|rumpcomp_|__" quirks ")") == 0)
2337					fails[NR] = $0
2338			}
2339			/cannot find -l/{fails[NR] = $0}
2340			/cannot open output file/{fails[NR] = $0}
2341			END{
2342				for (x in fails)
2343					print fails[x]
2344				exit x!=0
2345			}'
2346		[ $? -ne 0 ] && bomb "Testlink of rump failed: ${set}"
2347	done
2348	statusmsg "Rump build&link tests successful"
2349}
2350
2351repro_date() {
2352	# try the bsd date fail back the linux one
2353	date -u -r "$1" 2> /dev/null || date -u -d "@$1"
2354}
2355
2356setup_mkrepro()
2357{
2358	local quiet="$1"
2359
2360	if [ ${MKREPRO-no} != "yes" ]; then
2361		return
2362	fi
2363	if [ ${MKREPRO_TIMESTAMP-0} -ne 0 ]; then
2364		return;
2365	fi
2366
2367	local dirs=${NETBSDSRCDIR-/usr/src}/
2368	if [ ${MKX11-no} = "yes" ]; then
2369		dirs="$dirs ${X11SRCDIR-/usr/xsrc}/"
2370	fi
2371
2372	MKREPRO_TIMESTAMP=0
2373	local d
2374	local t
2375	local vcs
2376	for d in ${dirs}; do
2377		if [ -d "${d}CVS" ]; then
2378			local cvslatest=$(print_tooldir_program cvslatest)
2379			if [ ! -x "${cvslatest}" ]; then
2380				buildtools
2381			fi
2382
2383			local cvslatestflags=
2384			if ${do_expertmode}; then
2385				cvslatestflags=-i
2386			fi
2387
2388			t=$("${cvslatest}" ${cvslatestflags} "${d}")
2389			vcs=cvs
2390		elif [ -d "${d}.git" ]; then
2391			t=$(cd "${d}" && git log -1 --format=%ct)
2392			vcs=git
2393		elif [ -d "${d}.hg" ]; then
2394			t=$(hg --repo "$d" log -r . --template '{date.unixtime}\n')
2395			vcs=hg
2396		elif [ -f "${d}.hg_archival.txt" ]; then
2397			local stat=$(print_tooldir_program stat)
2398			if [ ! -x "${stat}" ]; then
2399				buildtools
2400			fi
2401
2402			t=$("${stat}" -t '%s' -f '%m' "${d}.hg_archival.txt")
2403			vcs=hg
2404		else
2405			bomb "Cannot determine VCS for '$d'"
2406		fi
2407
2408		if [ -z "$t" ]; then
2409			bomb "Failed to get timestamp for vcs=$vcs in '$d'"
2410		fi
2411
2412		#echo "latest $d $vcs $t"
2413		if [ "$t" -gt "$MKREPRO_TIMESTAMP" ]; then
2414			MKREPRO_TIMESTAMP="$t"
2415		fi
2416	done
2417
2418	[ "${MKREPRO_TIMESTAMP}" != "0" ] || bomb "Failed to compute timestamp"
2419	if [ -z "${quiet}" ]; then
2420		statusmsg2 "MKREPRO_TIMESTAMP" \
2421			"$(repro_date "${MKREPRO_TIMESTAMP}")"
2422	fi
2423	export MKREPRO MKREPRO_TIMESTAMP
2424}
2425
2426main()
2427{
2428	initdefaults
2429	_args=$@
2430	parseoptions "$@"
2431
2432	sanitycheck
2433
2434	build_start=$(date)
2435	statusmsg2 "${progname} command:" "$0 $*"
2436	statusmsg2 "${progname} started:" "${build_start}"
2437	statusmsg2 "NetBSD version:"   "${DISTRIBVER}"
2438	statusmsg2 "MACHINE:"          "${MACHINE}"
2439	statusmsg2 "MACHINE_ARCH:"     "${MACHINE_ARCH}"
2440	statusmsg2 "Build platform:"   "${uname_s} ${uname_r} ${uname_m}"
2441	statusmsg2 "HOST_SH:"          "${HOST_SH}"
2442	if [ -n "${BUILDID}" ]; then
2443		statusmsg2 "BUILDID:"  "${BUILDID}"
2444	fi
2445	if [ -n "${BUILDINFO}" ]; then
2446		printf "%b\n" "${BUILDINFO}" | \
2447		while read -r line ; do
2448			[ -s "${line}" ] && continue
2449			statusmsg2 "BUILDINFO:"  "${line}"
2450		done
2451	fi
2452
2453	rebuildmake
2454	validatemakeparams
2455	createmakewrapper
2456	setup_mkrepro
2457
2458	# Perform the operations.
2459	#
2460	for op in ${operations}; do
2461		case "${op}" in
2462
2463		makewrapper)
2464			# no-op
2465			;;
2466
2467		tools)
2468			buildtools
2469			;;
2470		libs)
2471			buildlibs
2472			;;
2473
2474		sets)
2475			statusmsg "Building sets from pre-populated ${DESTDIR}"
2476			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2477			    bomb "Failed to make ${op}"
2478			setdir=${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
2479			statusmsg "Built sets to ${setdir}"
2480			;;
2481
2482		build|distribution|release)
2483			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2484			    bomb "Failed to make ${op}"
2485			statusmsg "Successful make ${op}"
2486			;;
2487
2488		cleandir|obj|sourcesets|syspkgs|params)
2489			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2490			    bomb "Failed to make ${op}"
2491			statusmsg "Successful make ${op}"
2492			;;
2493
2494		iso-image|iso-image-source)
2495			${runcmd} "${makewrapper}" ${parallel} \
2496			    CDEXTRA="$CDEXTRA" ${op} ||
2497			    bomb "Failed to make ${op}"
2498			statusmsg "Successful make ${op}"
2499			;;
2500
2501		live-image|install-image)
2502			# install-image and live-image require mtree spec files
2503			# built with MKUNPRIVED.  Assume MKUNPRIVED build has been
2504			# performed if METALOG file is created in DESTDIR.
2505			if [ ! -e "${DESTDIR}/METALOG" ] ; then
2506				bomb "The release binaries must have been built with -U to create images"
2507			fi
2508			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2509			    bomb "Failed to make ${op}"
2510			statusmsg "Successful make ${op}"
2511			;;
2512		kernel=*)
2513			arg=${op#*=}
2514			buildkernel "${arg}"
2515			;;
2516		kernel.gdb=*)
2517			arg=${op#*=}
2518			configopts="-D DEBUG=-g"
2519			buildkernel "${arg}"
2520			;;
2521		releasekernel=*)
2522			arg=${op#*=}
2523			releasekernel "${arg}"
2524			;;
2525
2526		kernels)
2527			buildkernels
2528			;;
2529
2530		disk-image=*)
2531			arg=${op#*=}
2532			diskimage "${arg}"
2533			;;
2534
2535		dtb)
2536			builddtb
2537			;;
2538
2539		modules)
2540			buildmodules
2541			;;
2542
2543		installmodules=*)
2544			arg=${op#*=}
2545			if [ "${arg}" = "/" ] && \
2546			    (	[ "${uname_s}" != "NetBSD" ] || \
2547				[ "${uname_m}" != "${MACHINE}" ] ); then
2548				bomb "'${op}' must != / for cross builds"
2549			fi
2550			installmodules "${arg}"
2551			;;
2552
2553		install=*)
2554			arg=${op#*=}
2555			if [ "${arg}" = "/" ] && \
2556			    (	[ "${uname_s}" != "NetBSD" ] || \
2557				[ "${uname_m}" != "${MACHINE}" ] ); then
2558				bomb "'${op}' must != / for cross builds"
2559			fi
2560			installworld "${arg}"
2561			;;
2562
2563		rump)
2564			make_in_dir . do-distrib-dirs
2565			make_in_dir . includes
2566			make_in_dir lib/csu dependall
2567			make_in_dir lib/csu install
2568			make_in_dir external/gpl3/gcc/lib/libgcc dependall
2569			make_in_dir external/gpl3/gcc/lib/libgcc install
2570			dorump "${op}"
2571			;;
2572
2573		rumptest)
2574			dorump "${op}"
2575			;;
2576
2577		*)
2578			bomb "Unknown OPERATION '${op}'"
2579			;;
2580
2581		esac
2582	done
2583
2584	statusmsg2 "${progname} ended:" "$(date)"
2585	if [ -s "${results}" ]; then
2586		echo "===> Summary of results:"
2587		sed -e 's/^===>//;s/^/	/' "${results}"
2588		echo "===> ."
2589	fi
2590}
2591
2592main "$@"
2593