build.sh revision 1.368
1#! /usr/bin/env sh
2#	$NetBSD: build.sh,v 1.368 2023/04/23 09:54:15 uwe Exp $
3#
4# Copyright (c) 2001-2022 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 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 print the result.  If not found,
362# print 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, prints "unknown", or prints 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, print 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, print 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, print make's idea of the
935# value of that variable, or print 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# Display synopsis to stdout.
1026synopsis()
1027{
1028	cat <<_usage_
1029
1030Usage: ${progname} [-EnoPRrUux] [-a ARCH] [-B BID] [-C EXTRAS]
1031                [-c COMPILER] [-D DEST] [-j NJOB] [-M MOBJ] [-m MACH]
1032                [-N NOISY] [-O OOBJ] [-R RELEASE] [-S SEED] [-T TOOLS]
1033                [-V VAR=[VALUE]] [-w WRAPPER] [-X X11SRC]
1034                [-Z VAR]
1035                OPERATION ...
1036       ${progname} ( -h | -? )
1037
1038_usage_
1039}
1040
1041# Display help to stdout.
1042#
1043help()
1044{
1045	synopsis
1046	cat <<_usage_
1047 Build OPERATIONs (all imply "obj" and "tools"):
1048    build               Run "make build".
1049    distribution        Run "make distribution" (includes DESTDIR/etc/ files).
1050    release             Run "make release" (includes kernels & distrib media).
1051
1052 Other OPERATIONs:
1053    help                Show this message and exit.
1054    makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
1055                        Always performed.
1056    cleandir            Run "make cleandir".  [Default unless -u is used]
1057    dtb                 Build devicetree blobs.
1058    obj                 Run "make obj".  [Default unless -o is used]
1059    tools               Build and install tools.
1060    install=IDIR        Run "make installworld" to IDIR to install all sets
1061                        except 'etc'.  Useful after "distribution" or "release".
1062    kernel=CONF         Build kernel with config file CONF.
1063    kernel.gdb=CONF     Build kernel (including netbsd.gdb) with config
1064                        file CONF.
1065    releasekernel=CONF  Install kernel built by kernel=CONF to RELEASEDIR.
1066    kernels             Build all kernels.
1067    installmodules=IDIR Run "make installmodules" to IDIR to install all
1068                        kernel modules.
1069    modules             Build kernel modules.
1070    rumptest            Do a linktest for rump (for developers).
1071    sets                Create binary sets in
1072                        RELEASEDIR/RELEASEMACHINEDIR/binary/sets.
1073                        DESTDIR should be populated beforehand.
1074    distsets            Same as "distribution sets".
1075    sourcesets          Create source sets in RELEASEDIR/source/sets.
1076    syspkgs             Create syspkgs in
1077                        RELEASEDIR/RELEASEMACHINEDIR/binary/syspkgs.
1078    iso-image           Create CD-ROM image in RELEASEDIR/images.
1079    iso-image-source    Create CD-ROM image with source in RELEASEDIR/images.
1080    live-image          Create bootable live image in
1081                        RELEASEDIR/RELEASEMACHINEDIR/installation/liveimage.
1082    install-image       Create bootable installation image in
1083                        RELEASEDIR/RELEASEMACHINEDIR/installation/installimage.
1084    disk-image=TARGET   Create bootable disk image in
1085                        RELEASEDIR/RELEASEMACHINEDIR/binary/gzimg/TARGET.img.gz.
1086    params              Display various make(1) parameters.
1087    list-arch           Display a list of valid MACHINE/MACHINE_ARCH values,
1088                        and exit.  The list may be narrowed by passing glob
1089                        patterns or exact values in MACHINE or MACHINE_ARCH.
1090    mkrepro-timestamp   Show the latest source timestamp used for reproducable
1091                        builds and exit.  Requires -P or -V MKREPRO=yes.
1092
1093 Options:
1094    -a ARCH        Set MACHINE_ARCH=ARCH.  [Default: deduced from MACHINE]
1095    -B BID         Set BUILDID=BID.
1096    -C EXTRAS      Append EXTRAS to CDEXTRA for inclusion on CD-ROM.
1097    -c COMPILER    Select compiler from COMPILER:
1098                       clang
1099                       gcc
1100                   [Default: gcc]
1101    -D DEST        Set DESTDIR=DEST.  [Default: destdir.\${MACHINE}]
1102    -E             Set "expert" mode; disables various safety checks.
1103                   Should not be used without expert knowledge of the build
1104                   system.
1105    -h             Print this help message, and exit.
1106    -j NJOB        Run up to NJOB jobs in parallel; see make(1) -j.
1107    -M MOBJ        Set obj root directory to MOBJ; sets MAKEOBJDIRPREFIX=MOBJ,
1108                   unsets MAKEOBJDIR.
1109    -m MACH        Set MACHINE=MACH.  Some MACH values are actually
1110                   aliases that set MACHINE/MACHINE_ARCH pairs.
1111                   [Default: deduced from the host system if the host
1112                   OS is NetBSD]
1113    -N NOISY       Set the noisyness (MAKEVERBOSE) level of the build to NOISY:
1114                       0   Minimal output ("quiet").
1115                       1   Describe what is occurring.
1116                       2   Describe what is occurring and echo the actual
1117                           command.
1118                       3   Ignore the effect of the "@" prefix in make
1119                           commands.
1120                       4   Trace shell commands using the shell's -x flag.
1121                   [Default: 2]
1122    -n             Show commands that would be executed, but do not execute
1123                   them.
1124    -O OOBJ        Set obj root directory to OOBJ; sets a MAKEOBJDIR pattern
1125                   using OOBJ, unsets MAKEOBJDIRPREFIX.
1126    -o             Set MKOBJDIRS=no; do not create objdirs at start of build.
1127    -P             Set MKREPRO and MKREPRO_TIMESTAMP to the latest source
1128                   CVS timestamp for reproducible builds.
1129    -R RELEASE     Set RELEASEDIR=RELEASE.  [Default: releasedir]
1130    -r             Remove contents of TOOLDIR and DESTDIR before building.
1131    -S SEED        Set BUILDSEED=SEED.  [Default: NetBSD-majorversion]
1132    -T TOOLS       Set TOOLDIR=TOOLS.  If unset, and TOOLDIR is not set
1133                   in the environment, ${toolprefix}make will be (re)built
1134                   unconditionally.
1135    -U             Set MKUNPRIVED=yes; build without requiring root privileges,
1136                   install from an unprivileged build with proper file
1137                   permissions.
1138    -u             Set MKUPDATE=yes; do not run "make cleandir" first.
1139                   Without this, everything is rebuilt, including the tools.
1140    -V VAR=[VALUE] Set variable VAR=VALUE.
1141    -w WRAPPER     Create ${toolprefix}make script as WRAPPER.
1142                   [Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE}]
1143    -X X11SRC      Set X11SRCDIR=X11SRC.  [Default: /usr/xsrc]
1144    -x             Set MKX11=yes; build X11 from X11SRCDIR.
1145    -Z VAR         Unset ("zap") variable VAR.
1146    -?             Print this help message, and exit.
1147
1148_usage_
1149}
1150
1151# Display optional error message, help to stderr, and exit 1.
1152#
1153usage()
1154{
1155	if [ -n "$*" ]; then
1156		echo 1>&2 ""
1157		echo 1>&2 "${progname}: $*"
1158	fi
1159	synopsis 1>&2
1160	exit 1
1161}
1162
1163parseoptions()
1164{
1165	opts='a:B:C:c:D:Ehj:M:m:N:nO:oPR:rS:T:UuV:w:X:xZ:'
1166	opt_a=false
1167	opt_m=false
1168
1169	if type getopts >/dev/null 2>&1; then
1170		# Use POSIX getopts.
1171		#
1172		getoptcmd='getopts :${opts} opt && opt=-${opt}'
1173		optargcmd=':'
1174		optremcmd='shift $((${OPTIND} -1))'
1175	else
1176		type getopt >/dev/null 2>&1 ||
1177		    bomb "Shell does not support getopts or getopt"
1178
1179		# Use old-style getopt(1) (doesn't handle whitespace in args).
1180		#
1181		args="$(getopt ${opts} $*)"
1182		[ $? = 0 ] || usage
1183		set -- ${args}
1184
1185		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
1186		optargcmd='OPTARG="$1"; shift'
1187		optremcmd=':'
1188	fi
1189
1190	# Parse command line options.
1191	#
1192	while eval ${getoptcmd}; do
1193		case ${opt} in
1194
1195		-a)
1196			eval ${optargcmd}
1197			MACHINE_ARCH=${OPTARG}
1198			opt_a=true
1199			;;
1200
1201		-B)
1202			eval ${optargcmd}
1203			BUILDID=${OPTARG}
1204			;;
1205
1206		-C)
1207			eval ${optargcmd}; resolvepaths OPTARG
1208			CDEXTRA="${CDEXTRA}${CDEXTRA:+ }${OPTARG}"
1209			;;
1210
1211		-c)
1212			eval ${optargcmd}
1213			case "${OPTARG}" in
1214			gcc)	# default, no variables needed
1215				;;
1216			clang)	setmakeenv HAVE_LLVM yes
1217				setmakeenv MKLLVM yes
1218				setmakeenv MKGCC no
1219				;;
1220			#pcc)	...
1221			#	;;
1222			*)	bomb "Unknown compiler: ${OPTARG}"
1223			esac
1224			;;
1225
1226		-D)
1227			eval ${optargcmd}; resolvepath OPTARG
1228			setmakeenv DESTDIR "${OPTARG}"
1229			;;
1230
1231		-E)
1232			do_expertmode=true
1233			;;
1234
1235		-j)
1236			eval ${optargcmd}
1237			parallel="-j ${OPTARG}"
1238			;;
1239
1240		-M)
1241			eval ${optargcmd}; resolvepath OPTARG
1242			case "${OPTARG}" in
1243			\$*)	usage "-M argument must not begin with '\$'"
1244				;;
1245			*\$*)	# can use resolvepath, but can't set TOP_objdir
1246				resolvepath OPTARG
1247				;;
1248			*)	resolvepath OPTARG
1249				TOP_objdir="${OPTARG}${TOP}"
1250				;;
1251			esac
1252			unsetmakeenv MAKEOBJDIR
1253			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
1254			;;
1255
1256			# -m overrides MACHINE_ARCH unless "-a" is specified
1257		-m)
1258			eval ${optargcmd}
1259			MACHINE="${OPTARG}"
1260			opt_m=true
1261			;;
1262
1263		-N)
1264			eval ${optargcmd}
1265			case "${OPTARG}" in
1266			0|1|2|3|4)
1267				setmakeenv MAKEVERBOSE "${OPTARG}"
1268				;;
1269			*)
1270				usage "'${OPTARG}' is not a valid value for -N"
1271				;;
1272			esac
1273			;;
1274
1275		-n)
1276			runcmd=echo
1277			;;
1278
1279		-O)
1280			eval ${optargcmd}
1281			case "${OPTARG}" in
1282			*\$*)	usage "-O argument must not contain '\$'"
1283				;;
1284			*)	resolvepath OPTARG
1285				TOP_objdir="${OPTARG}"
1286				;;
1287			esac
1288			unsetmakeenv MAKEOBJDIRPREFIX
1289			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
1290			;;
1291
1292		-o)
1293			MKOBJDIRS=no
1294			;;
1295
1296		-P)
1297			MKREPRO=yes
1298			;;
1299
1300		-R)
1301			eval ${optargcmd}; resolvepath OPTARG
1302			setmakeenv RELEASEDIR "${OPTARG}"
1303			;;
1304
1305		-r)
1306			do_removedirs=true
1307			do_rebuildmake=true
1308			;;
1309
1310		-S)
1311			eval ${optargcmd}
1312			setmakeenv BUILDSEED "${OPTARG}"
1313			;;
1314
1315		-T)
1316			eval ${optargcmd}; resolvepath OPTARG
1317			TOOLDIR="${OPTARG}"
1318			export TOOLDIR
1319			;;
1320
1321		-U)
1322			setmakeenv MKUNPRIVED yes
1323			;;
1324
1325		-u)
1326			setmakeenv MKUPDATE yes
1327			;;
1328
1329		-V)
1330			eval ${optargcmd}
1331			case "${OPTARG}" in
1332		    # XXX: consider restricting which variables can be changed?
1333			[a-zA-Z_]*=*)
1334				safe_setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
1335				;;
1336			[a-zA-Z_]*)
1337				safe_setmakeenv "${OPTARG}" ""
1338				;;
1339			*)
1340				usage "-V argument must be of the form 'VAR[=VALUE]'"
1341				;;
1342			esac
1343			;;
1344
1345		-w)
1346			eval ${optargcmd}; resolvepath OPTARG
1347			makewrapper="${OPTARG}"
1348			;;
1349
1350		-X)
1351			eval ${optargcmd}; resolvepath OPTARG
1352			setmakeenv X11SRCDIR "${OPTARG}"
1353			;;
1354
1355		-x)
1356			setmakeenv MKX11 yes
1357			;;
1358
1359		-Z)
1360			eval ${optargcmd}
1361		    # XXX: consider restricting which variables can be unset?
1362			safe_unsetmakeenv "${OPTARG}"
1363			;;
1364
1365		--)
1366			break
1367			;;
1368
1369		-h)
1370			help
1371			exit 0
1372			;;
1373
1374		'-?')
1375			if [ "${OPTARG}" = '?' ]; then
1376				help
1377				exit 0
1378			fi
1379			usage "Unknown option -${OPTARG}"
1380			;;
1381
1382		-:)
1383			usage "Missing argument for option -${OPTARG}"
1384			;;
1385
1386		*)
1387			usage "Unimplemented option ${opt}"
1388			;;
1389
1390		esac
1391	done
1392
1393	# Validate operations.
1394	#
1395	eval ${optremcmd}
1396	while [ $# -gt 0 ]; do
1397		op=$1; shift
1398		operations="${operations} ${op}"
1399
1400		case "${op}" in
1401
1402		help)
1403			help
1404			exit 0
1405			;;
1406
1407		list-arch)
1408			listarch "${MACHINE}" "${MACHINE_ARCH}"
1409			exit
1410			;;
1411		mkrepro-timestamp)
1412			setup_mkrepro quiet
1413			echo ${MKREPRO_TIMESTAMP:-0}
1414			[ ${MKREPRO_TIMESTAMP:-0} -ne 0 ]; exit
1415			;;
1416
1417		kernel=*|releasekernel=*|kernel.gdb=*)
1418			arg=${op#*=}
1419			op=${op%%=*}
1420			[ -n "${arg}" ] ||
1421			    bomb "Must supply a kernel name with '${op}=...'"
1422			;;
1423
1424		disk-image=*)
1425			arg=${op#*=}
1426			op=disk_image
1427			[ -n "${arg}" ] ||
1428			    bomb "Must supply a target name with '${op}=...'"
1429
1430			;;
1431
1432		install=*|installmodules=*)
1433			arg=${op#*=}
1434			op=${op%%=*}
1435			[ -n "${arg}" ] ||
1436			    bomb "Must supply a directory with 'install=...'"
1437			;;
1438
1439		distsets)
1440			operations="$(echo "$operations" | sed 's/distsets/distribution sets/')"
1441			do_sets=true
1442			op=distribution
1443			;;
1444
1445		build|\
1446		cleandir|\
1447		distribution|\
1448		dtb|\
1449		install-image|\
1450		iso-image-source|\
1451		iso-image|\
1452		kernels|\
1453		libs|\
1454		live-image|\
1455		makewrapper|\
1456		modules|\
1457		obj|\
1458		params|\
1459		release|\
1460		rump|\
1461		rumptest|\
1462		sets|\
1463		sourcesets|\
1464		syspkgs|\
1465		tools)
1466			;;
1467
1468		*)
1469			usage "Unknown OPERATION '${op}'"
1470			;;
1471
1472		esac
1473		# ${op} may contain chars that are not allowed in variable
1474		# names.  Replace them with '_' before setting do_${op}.
1475		op="$( echo "$op" | tr -s '.-' '__')"
1476		eval do_${op}=true
1477	done
1478	[ -n "${operations}" ] || usage "Missing OPERATION to perform"
1479
1480	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
1481	#
1482	if [ -z "${MACHINE}" ]; then
1483		[ "${uname_s}" = "NetBSD" ] ||
1484		    bomb "MACHINE must be set, or -m must be used, for cross builds"
1485		MACHINE=${uname_m}
1486		MACHINE_ARCH=${uname_p}
1487	fi
1488	if $opt_m && ! $opt_a; then
1489		# Settings implied by the command line -m option
1490		# override MACHINE_ARCH from the environment (if any).
1491		getarch
1492	fi
1493	[ -n "${MACHINE_ARCH}" ] || getarch
1494	validatearch
1495
1496	# Set up default make(1) environment.
1497	#
1498	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
1499	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
1500	[ -z "${BUILDINFO}" ] || makeenv="${makeenv} BUILDINFO"
1501	MAKEFLAGS="-de -m ${TOP}/share/mk ${MAKEFLAGS}"
1502	MAKEFLAGS="${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
1503	export MAKEFLAGS MACHINE MACHINE_ARCH
1504	setmakeenv USETOOLS "yes"
1505	setmakeenv MAKEWRAPPERMACHINE "${makewrappermachine:-${MACHINE}}"
1506	setmakeenv MAKE_OBJDIR_CHECK_WRITABLE no
1507}
1508
1509# sanitycheck --
1510# Sanity check after parsing command line options, before rebuildmake.
1511#
1512sanitycheck()
1513{
1514	# Install as non-root is a bad idea.
1515	#
1516	if ${do_install} && [ "$id_u" -ne 0 ] ; then
1517		if ${do_expertmode}; then
1518			warning "Will install as an unprivileged user"
1519		else
1520			bomb "-E must be set for install as an unprivileged user"
1521		fi
1522	fi
1523
1524	# If the PATH contains any non-absolute components (including,
1525	# but not limited to, "." or ""), then complain.  As an exception,
1526	# allow "" or "." as the last component of the PATH.  This is fatal
1527	# if expert mode is not in effect.
1528	#
1529	local path="${PATH}"
1530	path="${path%:}"	# delete trailing ":"
1531	path="${path%:.}"	# delete trailing ":."
1532	case ":${path}:/" in
1533	*:[!/~]*)
1534		if ${do_expertmode}; then
1535			warning "PATH contains non-absolute components"
1536		else
1537			bomb "PATH environment variable must not" \
1538			     "contain non-absolute components"
1539		fi
1540		;;
1541	esac
1542
1543	while [ ${MKX11-no} = "yes" ]; do		# not really a loop
1544		test -n "${X11SRCDIR}" && {
1545		    test -d "${X11SRCDIR}" ||
1546		    	bomb "X11SRCDIR (${X11SRCDIR}) does not exist (with -x)"
1547		    break
1548		}
1549		for _xd in \
1550		    "${NETBSDSRCDIR%/*}/xsrc" \
1551		    "${NETBSDSRCDIR}/xsrc" \
1552		    /usr/xsrc
1553		do
1554		    test -d "${_xd}" &&
1555			setmakeenv X11SRCDIR "${_xd}" &&
1556			break 2
1557		done
1558		bomb "Asked to build X11 but no xsrc"
1559	done
1560}
1561
1562# print_tooldir_make --
1563# Try to find and print a path to an existing
1564# ${TOOLDIR}/bin/${toolprefix}program
1565print_tooldir_program()
1566{
1567	local possible_TOP_OBJ
1568	local possible_TOOLDIR
1569	local possible_program
1570	local tooldir_program
1571	local program=${1}
1572
1573	if [ -n "${TOOLDIR}" ]; then
1574		echo "${TOOLDIR}/bin/${toolprefix}${program}"
1575		return
1576	fi
1577
1578	# Set host_ostype to something like "NetBSD-4.5.6-i386".  This
1579	# is intended to match the HOST_OSTYPE variable in <bsd.own.mk>.
1580	#
1581	local host_ostype="${uname_s}-$(
1582		echo "${uname_r}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
1583		)-$(
1584		echo "${uname_p}" | sed -e 's/([^)]*)//g' -e 's/ /_/g'
1585		)"
1586
1587	# Look in a few potential locations for
1588	# ${possible_TOOLDIR}/bin/${toolprefix}${program}.
1589	# If we find it, then set possible_program.
1590	#
1591	# In the usual case (without interference from environment
1592	# variables or /etc/mk.conf), <bsd.own.mk> should set TOOLDIR to
1593	# "${_SRC_TOP_OBJ_}/tooldir.${host_ostype}".
1594	#
1595	# In practice it's difficult to figure out the correct value
1596	# for _SRC_TOP_OBJ_.  In the easiest case, when the -M or -O
1597	# options were passed to build.sh, then ${TOP_objdir} will be
1598	# the correct value.  We also try a few other possibilities, but
1599	# we do not replicate all the logic of <bsd.obj.mk>.
1600	#
1601	for possible_TOP_OBJ in \
1602		"${TOP_objdir}" \
1603		"${MAKEOBJDIRPREFIX:+${MAKEOBJDIRPREFIX}${TOP}}" \
1604		"${TOP}" \
1605		"${TOP}/obj" \
1606		"${TOP}/obj.${MACHINE}"
1607	do
1608		[ -n "${possible_TOP_OBJ}" ] || continue
1609		possible_TOOLDIR="${possible_TOP_OBJ}/tooldir.${host_ostype}"
1610		possible_program="${possible_TOOLDIR}/bin/${toolprefix}${program}"
1611		if [ -x "${possible_make}" ]; then
1612			echo ${possible_program}
1613			return;
1614		fi
1615	done
1616	echo ""
1617}
1618# print_tooldir_make --
1619# Try to find and print a path to an existing
1620# ${TOOLDIR}/bin/${toolprefix}make, for use by rebuildmake() before a
1621# new version of ${toolprefix}make has been built.
1622#
1623# * If TOOLDIR was set in the environment or on the command line, use
1624#   that value.
1625# * Otherwise try to guess what TOOLDIR would be if not overridden by
1626#   /etc/mk.conf, and check whether the resulting directory contains
1627#   a copy of ${toolprefix}make (this should work for everybody who
1628#   doesn't override TOOLDIR via /etc/mk.conf);
1629# * Failing that, search for ${toolprefix}make, nbmake, bmake, or make,
1630#   in the PATH (this might accidentally find a version of make that
1631#   does not understand the syntax used by NetBSD make, and that will
1632#   lead to failure in the next step);
1633# * If a copy of make was found above, try to use it with
1634#   nobomb_getmakevar to find the correct value for TOOLDIR, and believe the
1635#   result only if it's a directory that already exists;
1636# * If a value of TOOLDIR was found above, and if
1637#   ${TOOLDIR}/bin/${toolprefix}make exists, print that value.
1638#
1639print_tooldir_make()
1640{
1641	local possible_make
1642	local possible_TOOLDIR
1643	local tooldir_make
1644
1645	possible_make=$(print_tooldir_program make)
1646	# If the above didn't work, search the PATH for a suitable
1647	# ${toolprefix}make, nbmake, bmake, or make.
1648	#
1649	: ${possible_make:=$(find_in_PATH ${toolprefix}make '')}
1650	: ${possible_make:=$(find_in_PATH nbmake '')}
1651	: ${possible_make:=$(find_in_PATH bmake '')}
1652	: ${possible_make:=$(find_in_PATH make '')}
1653
1654	# At this point, we don't care whether possible_make is in the
1655	# correct TOOLDIR or not; we simply want it to be usable by
1656	# getmakevar to help us find the correct TOOLDIR.
1657	#
1658	# Use ${possible_make} with nobomb_getmakevar to try to find
1659	# the value of TOOLDIR.  Believe the result only if it's
1660	# a directory that already exists and contains bin/${toolprefix}make.
1661	#
1662	if [ -x "${possible_make}" ]; then
1663		possible_TOOLDIR="$(
1664			make="${possible_make}" \
1665			nobomb_getmakevar TOOLDIR 2>/dev/null
1666			)"
1667		if [ $? = 0 ] && [ -n "${possible_TOOLDIR}" ] \
1668		    && [ -d "${possible_TOOLDIR}" ];
1669		then
1670			tooldir_make="${possible_TOOLDIR}/bin/${toolprefix}make"
1671			if [ -x "${tooldir_make}" ]; then
1672				echo "${tooldir_make}"
1673				return 0
1674			fi
1675		fi
1676	fi
1677	return 1
1678}
1679
1680# rebuildmake --
1681# Rebuild nbmake in a temporary directory if necessary.  Sets $make
1682# to a path to the nbmake executable.  Sets done_rebuildmake=true
1683# if nbmake was rebuilt.
1684#
1685# There is a cyclic dependency between building nbmake and choosing
1686# TOOLDIR: TOOLDIR may be affected by settings in /etc/mk.conf, so we
1687# would like to use getmakevar to get the value of TOOLDIR; but we can't
1688# use getmakevar before we have an up to date version of nbmake; we
1689# might already have an up to date version of nbmake in TOOLDIR, but we
1690# don't yet know where TOOLDIR is.
1691#
1692# The default value of TOOLDIR also depends on the location of the top
1693# level object directory, so $(getmakevar TOOLDIR) invoked before or
1694# after making the top level object directory may produce different
1695# results.
1696#
1697# Strictly speaking, we should do the following:
1698#
1699#    1. build a new version of nbmake in a temporary directory;
1700#    2. use the temporary nbmake to create the top level obj directory;
1701#    3. use $(getmakevar TOOLDIR) with the temporary nbmake to
1702#       get the correct value of TOOLDIR;
1703#    4. move the temporary nbmake to ${TOOLDIR}/bin/nbmake.
1704#
1705# However, people don't like building nbmake unnecessarily if their
1706# TOOLDIR has not changed since an earlier build.  We try to avoid
1707# rebuilding a temporary version of nbmake by taking some shortcuts to
1708# guess a value for TOOLDIR, looking for an existing version of nbmake
1709# in that TOOLDIR, and checking whether that nbmake is newer than the
1710# sources used to build it.
1711#
1712rebuildmake()
1713{
1714	make="$(print_tooldir_make)"
1715	if [ -n "${make}" ] && [ -x "${make}" ]; then
1716		for f in usr.bin/make/*.[ch]; do
1717			if [ "${f}" -nt "${make}" ]; then
1718				statusmsg "${make} outdated" \
1719					"(older than ${f}), needs building."
1720				do_rebuildmake=true
1721				break
1722			fi
1723		done
1724	else
1725		statusmsg "No \$TOOLDIR/bin/${toolprefix}make, needs building."
1726		do_rebuildmake=true
1727	fi
1728
1729	# Build bootstrap ${toolprefix}make if needed.
1730	if ! ${do_rebuildmake}; then
1731		return
1732	fi
1733
1734	# Silent configure with MAKEVERBOSE==0
1735	if [ ${MAKEVERBOSE:-2} -eq 0 ]; then
1736		configure_args=--silent
1737	fi
1738
1739	statusmsg "Bootstrapping ${toolprefix}make"
1740	${runcmd} cd "${tmpdir}"
1741	${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
1742		CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
1743	    ${HOST_SH} "${TOP}/tools/make/configure" ${configure_args} ||
1744	( cp ${tmpdir}/config.log ${tmpdir}-config.log
1745	      bomb "Configure of ${toolprefix}make failed, see ${tmpdir}-config.log for details" )
1746	${runcmd} ${HOST_SH} buildmake.sh ||
1747	    bomb "Build of ${toolprefix}make failed"
1748	make="${tmpdir}/${toolprefix}make"
1749	${runcmd} cd "${TOP}"
1750	${runcmd} rm -f usr.bin/make/*.o
1751	done_rebuildmake=true
1752}
1753
1754# validatemakeparams --
1755# Perform some late sanity checks, after rebuildmake,
1756# but before createmakewrapper or any real work.
1757#
1758# Creates the top-level obj directory, because that
1759# is needed by some of the sanity checks.
1760#
1761# Prints status messages reporting the values of several variables.
1762#
1763validatemakeparams()
1764{
1765	# MAKECONF (which defaults to /etc/mk.conf in share/mk/bsd.own.mk)
1766	# can affect many things, so mention it in an early status message.
1767	#
1768	MAKECONF=$(getmakevar MAKECONF)
1769	if [ -e "${MAKECONF}" ]; then
1770		statusmsg2 "MAKECONF file:" "${MAKECONF}"
1771	else
1772		statusmsg2 "MAKECONF file:" "${MAKECONF} (File not found)"
1773	fi
1774
1775	# Normalise MKOBJDIRS, MKUNPRIVED, and MKUPDATE.
1776	# These may be set as build.sh options or in "mk.conf".
1777	# Don't export them as they're only used for tests in build.sh.
1778	#
1779	MKOBJDIRS=$(getmakevar MKOBJDIRS)
1780	MKUNPRIVED=$(getmakevar MKUNPRIVED)
1781	MKUPDATE=$(getmakevar MKUPDATE)
1782
1783	# Non-root should always use either the -U or -E flag.
1784	#
1785	if ! ${do_expertmode} && \
1786	    [ "$id_u" -ne 0 ] && \
1787	    [ "${MKUNPRIVED}" = "no" ] ; then
1788		bomb "-U or -E must be set for build as an unprivileged user"
1789	fi
1790
1791	if [ "${runcmd}" = "echo" ]; then
1792		TOOLCHAIN_MISSING=no
1793		EXTERNAL_TOOLCHAIN=""
1794	else
1795		TOOLCHAIN_MISSING=$(bomb_getmakevar TOOLCHAIN_MISSING)
1796		EXTERNAL_TOOLCHAIN=$(bomb_getmakevar EXTERNAL_TOOLCHAIN)
1797	fi
1798	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
1799	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
1800		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
1801		${runcmd} echo "	MACHINE:      ${MACHINE}"
1802		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
1803		${runcmd} echo ""
1804		${runcmd} echo "All builds for this platform should be done via a traditional make"
1805		${runcmd} echo "If you wish to use an external cross-toolchain, set"
1806		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
1807		${runcmd} echo "in either the environment or mk.conf and rerun"
1808		${runcmd} echo "	${progname} $*"
1809		exit 1
1810	fi
1811
1812	if [ "${MKOBJDIRS}" != "no" ]; then
1813		# Create the top-level object directory.
1814		#
1815		# "make obj NOSUBDIR=" can handle most cases, but it
1816		# can't handle the case where MAKEOBJDIRPREFIX is set
1817		# while the corresponding directory does not exist
1818		# (rules in <bsd.obj.mk> would abort the build).  We
1819		# therefore have to handle the MAKEOBJDIRPREFIX case
1820		# without invoking "make obj".  The MAKEOBJDIR case
1821		# could be handled either way, but we choose to handle
1822		# it similarly to MAKEOBJDIRPREFIX.
1823		#
1824		if [ -n "${TOP_obj}" ]; then
1825			# It must have been set by the "-M" or "-O"
1826			# command line options, so there's no need to
1827			# use getmakevar
1828			:
1829		elif [ -n "$MAKEOBJDIRPREFIX" ]; then
1830			TOP_obj="$(getmakevar MAKEOBJDIRPREFIX)${TOP}"
1831		elif [ -n "$MAKEOBJDIR" ]; then
1832			TOP_obj="$(getmakevar MAKEOBJDIR)"
1833		fi
1834		if [ -n "$TOP_obj" ]; then
1835			${runcmd} mkdir -p "${TOP_obj}" ||
1836			    bomb "Can't create top level object directory" \
1837					"${TOP_obj}"
1838		else
1839			${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
1840			    bomb "Can't create top level object directory" \
1841					"using make obj"
1842		fi
1843
1844		# make obj in tools to ensure that the objdir for "tools"
1845		# is available.
1846		#
1847		${runcmd} cd tools
1848		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
1849		    bomb "Failed to make obj in tools"
1850		${runcmd} cd "${TOP}"
1851	fi
1852
1853	# Find TOOLDIR, DESTDIR, and RELEASEDIR, according to getmakevar,
1854	# and bomb if they have changed from the values we had from the
1855	# command line or environment.
1856	#
1857	# This must be done after creating the top-level object directory.
1858	#
1859	for var in TOOLDIR DESTDIR RELEASEDIR
1860	do
1861		eval oldval=\"\$${var}\"
1862		newval="$(getmakevar $var)"
1863		if ! $do_expertmode; then
1864			: ${_SRC_TOP_OBJ_:=$(getmakevar _SRC_TOP_OBJ_)}
1865			case "$var" in
1866			DESTDIR)
1867				: ${newval:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
1868				makeenv="${makeenv} DESTDIR"
1869				;;
1870			RELEASEDIR)
1871				: ${newval:=${_SRC_TOP_OBJ_}/releasedir}
1872				makeenv="${makeenv} RELEASEDIR"
1873				;;
1874			esac
1875		fi
1876		if [ -n "$oldval" ] && [ "$oldval" != "$newval" ]; then
1877			bomb "Value of ${var} has changed" \
1878				"(was \"${oldval}\", now \"${newval}\")"
1879		fi
1880		eval ${var}=\"\${newval}\"
1881		eval export ${var}
1882		statusmsg2 "${var} path:" "${newval}"
1883	done
1884
1885	# RELEASEMACHINEDIR is just a subdir name, e.g. "i386".
1886	RELEASEMACHINEDIR=$(getmakevar RELEASEMACHINEDIR)
1887
1888	# Check validity of TOOLDIR and DESTDIR.
1889	#
1890	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
1891		bomb "TOOLDIR '${TOOLDIR}' invalid"
1892	fi
1893	removedirs="${TOOLDIR}"
1894
1895	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
1896		if ${do_distribution} || ${do_release} || \
1897		   [ "${uname_s}" != "NetBSD" ] || \
1898		   [ "${uname_m}" != "${MACHINE}" ]; then
1899			bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'"
1900		fi
1901		if ! ${do_expertmode}; then
1902			bomb "DESTDIR must != / for non -E (expert) builds"
1903		fi
1904		statusmsg "WARNING: Building to /, in expert mode."
1905		statusmsg "         This may cause your system to break!  Reasons include:"
1906		statusmsg "            - your kernel is not up to date"
1907		statusmsg "            - the libraries or toolchain have changed"
1908		statusmsg "         YOU HAVE BEEN WARNED!"
1909	else
1910		removedirs="${removedirs} ${DESTDIR}"
1911	fi
1912	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
1913		bomb "Must set RELEASEDIR with 'releasekernel=...'"
1914	fi
1915
1916	# If a previous build.sh run used -U (and therefore created a
1917	# METALOG file), then most subsequent build.sh runs must also
1918	# use -U.  If DESTDIR is about to be removed, then don't perform
1919	# this check.
1920	#
1921	case "${do_removedirs} ${removedirs} " in
1922	true*" ${DESTDIR} "*)
1923		# DESTDIR is about to be removed
1924		;;
1925	*)
1926		if [ -e "${DESTDIR}/METALOG" ] && \
1927		    [ "${MKUNPRIVED}" = "no" ] ; then
1928			if $do_expertmode; then
1929				warning "A previous build.sh run specified -U"
1930			else
1931				bomb "A previous build.sh run specified -U; you must specify it again now"
1932			fi
1933		fi
1934		;;
1935	esac
1936
1937	# live-image and install-image targets require binary sets
1938	# (actually DESTDIR/etc/mtree/set.* files) built with MKUNPRIVED.
1939	# If release operation is specified with live-image or install-image,
1940	# the release op should be performed with -U for later image ops.
1941	#
1942	if ${do_release} && ( ${do_live_image} || ${do_install_image} ) && \
1943	    [ "${MKUNPRIVED}" = "no" ] ; then
1944		bomb "-U must be specified on building release to create images later"
1945	fi
1946}
1947
1948
1949createmakewrapper()
1950{
1951	# Remove the target directories.
1952	#
1953	if ${do_removedirs}; then
1954		for f in ${removedirs}; do
1955			statusmsg "Removing ${f}"
1956			${runcmd} rm -r -f "${f}"
1957		done
1958	fi
1959
1960	# Recreate $TOOLDIR.
1961	#
1962	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
1963	    bomb "mkdir of '${TOOLDIR}/bin' failed"
1964
1965	# If we did not previously rebuild ${toolprefix}make, then
1966	# check whether $make is still valid and the same as the output
1967	# from print_tooldir_make.  If not, then rebuild make now.  A
1968	# possible reason for this being necessary is that the actual
1969	# value of TOOLDIR might be different from the value guessed
1970	# before the top level obj dir was created.
1971	#
1972	if ! ${done_rebuildmake} && \
1973	    ( [ ! -x "$make" ] || [ "$make" != "$(print_tooldir_make)" ] )
1974	then
1975		rebuildmake
1976	fi
1977
1978	# Install ${toolprefix}make if it was built.
1979	#
1980	if ${done_rebuildmake}; then
1981		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
1982		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
1983		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
1984		make="${TOOLDIR}/bin/${toolprefix}make"
1985		statusmsg "Created ${make}"
1986	fi
1987
1988	# Build a ${toolprefix}make wrapper script, usable by hand as
1989	# well as by build.sh.
1990	#
1991	if [ -z "${makewrapper}" ]; then
1992		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
1993		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
1994	fi
1995
1996	${runcmd} rm -f "${makewrapper}"
1997	if [ "${runcmd}" = "echo" ]; then
1998		echo 'cat <<EOF >'${makewrapper}
1999		makewrapout=
2000	else
2001		makewrapout=">>\${makewrapper}"
2002	fi
2003
2004	case "${KSH_VERSION:-${SH_VERSION}}" in
2005	*PD\ KSH*|*MIRBSD\ KSH*)
2006		set +o braceexpand
2007		;;
2008	esac
2009
2010	eval cat <<EOF ${makewrapout}
2011#! ${HOST_SH}
2012# Set proper variables to allow easy "make" building of a NetBSD subtree.
2013# Generated from:  \$NetBSD: build.sh,v 1.368 2023/04/23 09:54:15 uwe Exp $
2014# with these arguments: ${_args}
2015#
2016
2017EOF
2018	{
2019		sorted_vars="$(for var in ${makeenv}; do echo "${var}" ; done \
2020			| sort -u )"
2021		for var in ${sorted_vars}; do
2022			eval val=\"\${${var}}\"
2023			eval is_set=\"\${${var}+set}\"
2024			if [ -z "${is_set}" ]; then
2025				echo "unset ${var}"
2026			else
2027				qval="$(shell_quote "${val}")"
2028				echo "${var}=${qval}; export ${var}"
2029			fi
2030		done
2031
2032		cat <<EOF
2033
2034exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
2035EOF
2036	} | eval cat "${makewrapout}"
2037	[ "${runcmd}" = "echo" ] && echo EOF
2038	${runcmd} chmod +x "${makewrapper}"
2039	statusmsg2 "Updated makewrapper:" "${makewrapper}"
2040}
2041
2042make_in_dir()
2043{
2044	local dir="$1"
2045	local op="$2"
2046	${runcmd} cd "${dir}" ||
2047	    bomb "Failed to cd to \"${dir}\""
2048	${runcmd} "${makewrapper}" ${parallel} ${op} ||
2049	    bomb "Failed to make ${op} in \"${dir}\""
2050	${runcmd} cd "${TOP}" ||
2051	    bomb "Failed to cd back to \"${TOP}\""
2052}
2053
2054buildtools()
2055{
2056	if [ "${MKOBJDIRS}" != "no" ]; then
2057		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
2058		    bomb "Failed to make obj-tools"
2059	fi
2060	if [ "${MKUPDATE}" = "no" ]; then
2061		make_in_dir tools cleandir
2062	fi
2063	make_in_dir tools build_install
2064	statusmsg "Tools built to ${TOOLDIR}"
2065}
2066
2067buildlibs()
2068{
2069	if [ "${MKOBJDIRS}" != "no" ]; then
2070		${runcmd} "${makewrapper}" ${parallel} obj ||
2071		    bomb "Failed to make obj"
2072	fi
2073	if [ "${MKUPDATE}" = "no" ]; then
2074		make_in_dir lib cleandir
2075	fi
2076	make_in_dir . do-distrib-dirs
2077	make_in_dir . includes
2078	make_in_dir . do-lib
2079	statusmsg "libs built"
2080}
2081
2082getkernelconf()
2083{
2084	kernelconf="$1"
2085	if [ "${MKOBJDIRS}" != "no" ]; then
2086		# The correct value of KERNOBJDIR might
2087		# depend on a prior "make obj" in
2088		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
2089		#
2090		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
2091		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
2092		make_in_dir "${KERNSRCDIR}/${KERNARCHDIR}/compile" obj
2093	fi
2094	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
2095	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
2096	case "${kernelconf}" in
2097	*/*)
2098		kernelconfpath="${kernelconf}"
2099		kernelconfname="${kernelconf##*/}"
2100		;;
2101	*)
2102		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
2103		kernelconfname="${kernelconf}"
2104		;;
2105	esac
2106	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
2107}
2108
2109diskimage()
2110{
2111	ARG="$(echo $1 | tr '[:lower:]' '[:upper:]')"
2112	[ -f "${DESTDIR}/etc/mtree/set.base" ] ||
2113	    bomb "The release binaries must be built first"
2114	kerneldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
2115	kernel="${kerneldir}/netbsd-${ARG}.gz"
2116	[ -f "${kernel}" ] ||
2117	    bomb "The kernel ${kernel} must be built first"
2118	make_in_dir "${NETBSDSRCDIR}/etc" "smp_${1}"
2119}
2120
2121buildkernel()
2122{
2123	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
2124		# Building tools every time we build a kernel is clearly
2125		# unnecessary.  We could try to figure out whether rebuilding
2126		# the tools is necessary this time, but it doesn't seem worth
2127		# the trouble.  Instead, we say it's the user's responsibility
2128		# to rebuild the tools if necessary.
2129		#
2130		statusmsg "Building kernel without building new tools"
2131		buildkernelwarned=true
2132	fi
2133	getkernelconf $1
2134	statusmsg2 "Building kernel:" "${kernelconf}"
2135	statusmsg2 "Build directory:" "${kernelbuildpath}"
2136	${runcmd} mkdir -p "${kernelbuildpath}" ||
2137	    bomb "Cannot mkdir: ${kernelbuildpath}"
2138	if [ "${MKUPDATE}" = "no" ]; then
2139		make_in_dir "${kernelbuildpath}" cleandir
2140	fi
2141	[ -x "${TOOLDIR}/bin/${toolprefix}config" ] \
2142	|| bomb "${TOOLDIR}/bin/${toolprefix}config does not exist. You need to \"$0 tools\" first"
2143	CONFIGOPTS=$(getmakevar CONFIGOPTS)
2144	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" ${CONFIGOPTS} \
2145		-b "${kernelbuildpath}" -s "${TOP}/sys" ${configopts} \
2146		"${kernelconfpath}" ||
2147	    bomb "${toolprefix}config failed for ${kernelconf}"
2148	make_in_dir "${kernelbuildpath}" depend
2149	make_in_dir "${kernelbuildpath}" all
2150
2151	if [ "${runcmd}" != "echo" ]; then
2152		statusmsg "Kernels built from ${kernelconf}:"
2153		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
2154		for kern in ${kernlist:-netbsd}; do
2155			[ -f "${kernelbuildpath}/${kern}" ] && \
2156			    echo "  ${kernelbuildpath}/${kern}"
2157		done | tee -a "${results}"
2158	fi
2159}
2160
2161releasekernel()
2162{
2163	getkernelconf $1
2164	kernelreldir="${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/kernel"
2165	${runcmd} mkdir -p "${kernelreldir}"
2166	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
2167	for kern in ${kernlist:-netbsd}; do
2168		builtkern="${kernelbuildpath}/${kern}"
2169		[ -f "${builtkern}" ] || continue
2170		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
2171		statusmsg2 "Kernel copy:" "${releasekern}"
2172		if [ "${runcmd}" = "echo" ]; then
2173			echo "gzip -c -9 < ${builtkern} > ${releasekern}"
2174		else
2175			gzip -c -9 < "${builtkern}" > "${releasekern}"
2176		fi
2177	done
2178}
2179
2180buildkernels()
2181{
2182	allkernels=$( runcmd= make_in_dir etc '-V ${ALL_KERNELS}' )
2183	for k in $allkernels; do
2184		buildkernel "${k}"
2185	done
2186}
2187
2188buildmodules()
2189{
2190	setmakeenv MKBINUTILS no
2191	if ! ${do_tools} && ! ${buildmoduleswarned:-false}; then
2192		# Building tools every time we build modules is clearly
2193		# unnecessary as well as a kernel.
2194		#
2195		statusmsg "Building modules without building new tools"
2196		buildmoduleswarned=true
2197	fi
2198
2199	statusmsg "Building kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
2200	if [ "${MKOBJDIRS}" != "no" ]; then
2201		make_in_dir sys/modules obj
2202	fi
2203	if [ "${MKUPDATE}" = "no" ]; then
2204		make_in_dir sys/modules cleandir
2205	fi
2206	make_in_dir sys/modules dependall
2207	make_in_dir sys/modules install
2208
2209	statusmsg "Successful build of kernel modules for NetBSD/${MACHINE} ${DISTRIBVER}"
2210}
2211
2212builddtb()
2213{
2214	statusmsg "Building devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
2215	if [ "${MKOBJDIRS}" != "no" ]; then
2216		make_in_dir sys/dtb obj
2217	fi
2218	if [ "${MKUPDATE}" = "no" ]; then
2219		make_in_dir sys/dtb cleandir
2220	fi
2221	make_in_dir sys/dtb dependall
2222	make_in_dir sys/dtb install
2223
2224	statusmsg "Successful build of devicetree blobs for NetBSD/${MACHINE} ${DISTRIBVER}"
2225}
2226
2227installmodules()
2228{
2229	dir="$1"
2230	${runcmd} "${makewrapper}" INSTALLMODULESDIR="${dir}" installmodules ||
2231	    bomb "Failed to make installmodules to ${dir}"
2232	statusmsg "Successful installmodules to ${dir}"
2233}
2234
2235installworld()
2236{
2237	dir="$1"
2238	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
2239	    bomb "Failed to make installworld to ${dir}"
2240	statusmsg "Successful installworld to ${dir}"
2241}
2242
2243# Run rump build&link tests.
2244#
2245# To make this feasible for running without having to install includes and
2246# libraries into destdir (i.e. quick), we only run ld.  This is possible
2247# since the rump kernel is a closed namespace apart from calls to rumpuser.
2248# Therefore, if ld complains only about rumpuser symbols, rump kernel
2249# linking was successful.
2250#
2251# We test that rump links with a number of component configurations.
2252# These attempt to mimic what is encountered in the full build.
2253# See list below.  The list should probably be either autogenerated
2254# or managed elsewhere; keep it here until a better idea arises.
2255#
2256# Above all, note that THIS IS NOT A SUBSTITUTE FOR A FULL BUILD.
2257#
2258
2259# XXX: uwe: kern/56599 - while riastradh addressed librump problems,
2260# there are still unwanted dependencies:
2261#    net -> net_net
2262#    vfs -> fifo
2263
2264# -lrumpvfs -> $LRUMPVFS for now
2265LRUMPVFS="-lrumpvfs -lrumpvfs_nofifofs"
2266
2267RUMP_LIBSETS="
2268	-lrump,
2269        -lrumpvfs
2270            --no-whole-archive -lrumpvfs_nofifofs -lrump,
2271	-lrumpkern_tty
2272            --no-whole-archive $LRUMPVFS -lrump,
2273	-lrumpfs_tmpfs
2274            --no-whole-archive $LRUMPVFS -lrump,
2275	-lrumpfs_ffs -lrumpfs_msdos
2276            --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrump,
2277	-lrumpnet_virtif -lrumpnet_netinet -lrumpnet_net -lrumpnet
2278	    --no-whole-archive -lrump,
2279	-lrumpfs_nfs
2280	    --no-whole-archive $LRUMPVFS
2281	    -lrumpnet_sockin -lrumpnet_virtif -lrumpnet_netinet
2282            --start-group -lrumpnet_net -lrumpnet --end-group -lrump,
2283	-lrumpdev_cgd -lrumpdev_raidframe -lrumpdev_rnd -lrumpdev_dm
2284            --no-whole-archive $LRUMPVFS -lrumpdev_disk -lrumpdev -lrumpkern_crypto -lrump
2285"
2286
2287dorump()
2288{
2289	local doclean=""
2290	local doobjs=""
2291
2292	export RUMPKERN_ONLY=1
2293	# create obj and distrib dirs
2294	if [ "${MKOBJDIRS}" != "no" ]; then
2295		make_in_dir "${NETBSDSRCDIR}/etc/mtree" obj
2296		make_in_dir "${NETBSDSRCDIR}/sys/rump" obj
2297	fi
2298	${runcmd} "${makewrapper}" ${parallel} do-distrib-dirs \
2299	    || bomb "Could not create distrib-dirs"
2300
2301	[ "${MKUPDATE}" = "no" ] && doclean="cleandir"
2302	targlist="${doclean} ${doobjs} dependall install"
2303	# optimize: for test we build only static libs (3x test speedup)
2304	if [ "${1}" = "rumptest" ] ; then
2305		setmakeenv NOPIC 1
2306		setmakeenv NOPROFILE 1
2307	fi
2308	for cmd in ${targlist} ; do
2309		make_in_dir "${NETBSDSRCDIR}/sys/rump" ${cmd}
2310	done
2311
2312	# if we just wanted to build & install rump, we're done
2313	[ "${1}" != "rumptest" ] && return
2314
2315	${runcmd} cd "${NETBSDSRCDIR}/sys/rump/librump/rumpkern" \
2316	    || bomb "cd to rumpkern failed"
2317	md_quirks=`${runcmd} "${makewrapper}" -V '${_SYMQUIRK}'`
2318	# one little, two little, three little backslashes ...
2319	md_quirks="$(echo ${md_quirks} | sed 's,\\,\\\\,g'";s/'//g" )"
2320	${runcmd} cd "${TOP}" || bomb "cd to ${TOP} failed"
2321	tool_ld=`${runcmd} "${makewrapper}" -V '${LD}'`
2322
2323	local oIFS="${IFS}"
2324	IFS=","
2325	for set in ${RUMP_LIBSETS} ; do
2326		IFS="${oIFS}"
2327		${runcmd} ${tool_ld} -nostdlib -L${DESTDIR}/usr/lib	\
2328		    -static --whole-archive ${set} --no-whole-archive -lpthread -lc 2>&1 -o /tmp/rumptest.$$ | \
2329		      awk -v quirks="${md_quirks}" '
2330			/undefined reference/ &&
2331			    !/more undefined references.*follow/{
2332				if (match($NF,
2333				    "`(rumpuser_|rumpcomp_|__" quirks ")") == 0)
2334					fails[NR] = $0
2335			}
2336			/cannot find -l/{fails[NR] = $0}
2337			/cannot open output file/{fails[NR] = $0}
2338			END{
2339				for (x in fails)
2340					print fails[x]
2341				exit x!=0
2342			}'
2343		[ $? -ne 0 ] && bomb "Testlink of rump failed: ${set}"
2344	done
2345	statusmsg "Rump build&link tests successful"
2346}
2347
2348repro_date() {
2349	# try the bsd date fail back the linux one
2350	date -u -r "$1" 2> /dev/null || date -u -d "@$1"
2351}
2352
2353setup_mkrepro()
2354{
2355	local quiet="$1"
2356
2357	if [ ${MKREPRO-no} != "yes" ]; then
2358		return
2359	fi
2360	if [ ${MKREPRO_TIMESTAMP-0} -ne 0 ]; then
2361		return;
2362	fi
2363
2364	local dirs=${NETBSDSRCDIR-/usr/src}/
2365	if [ ${MKX11-no} = "yes" ]; then
2366		dirs="$dirs ${X11SRCDIR-/usr/xsrc}/"
2367	fi
2368
2369	MKREPRO_TIMESTAMP=0
2370	local d
2371	local t
2372	local vcs
2373	for d in ${dirs}; do
2374		if [ -d "${d}CVS" ]; then
2375			local cvslatest=$(print_tooldir_program cvslatest)
2376			if [ ! -x "${cvslatest}" ]; then
2377				buildtools
2378			fi
2379
2380			local cvslatestflags=
2381			if ${do_expertmode}; then
2382				cvslatestflags=-i
2383			fi
2384
2385			t=$("${cvslatest}" ${cvslatestflags} "${d}")
2386			vcs=cvs
2387		elif [ -d "${d}.git" ]; then
2388			t=$(cd "${d}" && git log -1 --format=%ct)
2389			vcs=git
2390		elif [ -d "${d}.hg" ]; then
2391			t=$(hg --repo "$d" log -r . --template '{date.unixtime}\n')
2392			vcs=hg
2393		elif [ -f "${d}.hg_archival.txt" ]; then
2394			local stat=$(print_tooldir_program stat)
2395			if [ ! -x "${stat}" ]; then
2396				buildtools
2397			fi
2398
2399			t=$("${stat}" -t '%s' -f '%m' "${d}.hg_archival.txt")
2400			vcs=hg
2401		else
2402			bomb "Cannot determine VCS for '$d'"
2403		fi
2404
2405		if [ -z "$t" ]; then
2406			bomb "Failed to get timestamp for vcs=$vcs in '$d'"
2407		fi
2408
2409		#echo "latest $d $vcs $t"
2410		if [ "$t" -gt "$MKREPRO_TIMESTAMP" ]; then
2411			MKREPRO_TIMESTAMP="$t"
2412		fi
2413	done
2414
2415	[ "${MKREPRO_TIMESTAMP}" != "0" ] || bomb "Failed to compute timestamp"
2416	if [ -z "${quiet}" ]; then
2417		statusmsg2 "MKREPRO_TIMESTAMP" \
2418			"$(repro_date "${MKREPRO_TIMESTAMP}")"
2419	fi
2420	export MKREPRO MKREPRO_TIMESTAMP
2421}
2422
2423main()
2424{
2425	initdefaults
2426	_args=$@
2427	parseoptions "$@"
2428
2429	sanitycheck
2430
2431	build_start=$(date)
2432	statusmsg2 "${progname} command:" "$0 $*"
2433	statusmsg2 "${progname} started:" "${build_start}"
2434	statusmsg2 "NetBSD version:"   "${DISTRIBVER}"
2435	statusmsg2 "MACHINE:"          "${MACHINE}"
2436	statusmsg2 "MACHINE_ARCH:"     "${MACHINE_ARCH}"
2437	statusmsg2 "Build platform:"   "${uname_s} ${uname_r} ${uname_m}"
2438	statusmsg2 "HOST_SH:"          "${HOST_SH}"
2439	if [ -n "${BUILDID}" ]; then
2440		statusmsg2 "BUILDID:"  "${BUILDID}"
2441	fi
2442	if [ -n "${BUILDINFO}" ]; then
2443		printf "%b\n" "${BUILDINFO}" | \
2444		while read -r line ; do
2445			[ -s "${line}" ] && continue
2446			statusmsg2 "BUILDINFO:"  "${line}"
2447		done
2448	fi
2449
2450	rebuildmake
2451	validatemakeparams
2452	createmakewrapper
2453	setup_mkrepro
2454
2455	# Perform the operations.
2456	#
2457	for op in ${operations}; do
2458		case "${op}" in
2459
2460		makewrapper)
2461			# no-op
2462			;;
2463
2464		tools)
2465			buildtools
2466			;;
2467		libs)
2468			buildlibs
2469			;;
2470
2471		sets)
2472			statusmsg "Building sets from pre-populated ${DESTDIR}"
2473			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2474			    bomb "Failed to make ${op}"
2475			setdir=${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
2476			statusmsg "Built sets to ${setdir}"
2477			;;
2478
2479		build|distribution|release)
2480			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2481			    bomb "Failed to make ${op}"
2482			statusmsg "Successful make ${op}"
2483			;;
2484
2485		cleandir|obj|sourcesets|syspkgs|params)
2486			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2487			    bomb "Failed to make ${op}"
2488			statusmsg "Successful make ${op}"
2489			;;
2490
2491		iso-image|iso-image-source)
2492			${runcmd} "${makewrapper}" ${parallel} \
2493			    CDEXTRA="$CDEXTRA" ${op} ||
2494			    bomb "Failed to make ${op}"
2495			statusmsg "Successful make ${op}"
2496			;;
2497
2498		live-image|install-image)
2499			# install-image and live-image require mtree spec files
2500			# built with UNPRIVED.  Assume UNPRIVED build has been
2501			# performed if METALOG file is created in DESTDIR.
2502			if [ ! -e "${DESTDIR}/METALOG" ] ; then
2503				bomb "The release binaries must have been built with -U to create images"
2504			fi
2505			${runcmd} "${makewrapper}" ${parallel} ${op} ||
2506			    bomb "Failed to make ${op}"
2507			statusmsg "Successful make ${op}"
2508			;;
2509		kernel=*)
2510			arg=${op#*=}
2511			buildkernel "${arg}"
2512			;;
2513		kernel.gdb=*)
2514			arg=${op#*=}
2515			configopts="-D DEBUG=-g"
2516			buildkernel "${arg}"
2517			;;
2518		releasekernel=*)
2519			arg=${op#*=}
2520			releasekernel "${arg}"
2521			;;
2522
2523		kernels)
2524			buildkernels
2525			;;
2526
2527		disk-image=*)
2528			arg=${op#*=}
2529			diskimage "${arg}"
2530			;;
2531
2532		dtb)
2533			builddtb
2534			;;
2535
2536		modules)
2537			buildmodules
2538			;;
2539
2540		installmodules=*)
2541			arg=${op#*=}
2542			if [ "${arg}" = "/" ] && \
2543			    (	[ "${uname_s}" != "NetBSD" ] || \
2544				[ "${uname_m}" != "${MACHINE}" ] ); then
2545				bomb "'${op}' must != / for cross builds"
2546			fi
2547			installmodules "${arg}"
2548			;;
2549
2550		install=*)
2551			arg=${op#*=}
2552			if [ "${arg}" = "/" ] && \
2553			    (	[ "${uname_s}" != "NetBSD" ] || \
2554				[ "${uname_m}" != "${MACHINE}" ] ); then
2555				bomb "'${op}' must != / for cross builds"
2556			fi
2557			installworld "${arg}"
2558			;;
2559
2560		rump)
2561			make_in_dir . do-distrib-dirs
2562			make_in_dir . includes
2563			make_in_dir lib/csu dependall
2564			make_in_dir lib/csu install
2565			make_in_dir external/gpl3/gcc/lib/libgcc dependall
2566			make_in_dir external/gpl3/gcc/lib/libgcc install
2567			dorump "${op}"
2568			;;
2569
2570		rumptest)
2571			dorump "${op}"
2572			;;
2573
2574		*)
2575			bomb "Unknown OPERATION '${op}'"
2576			;;
2577
2578		esac
2579	done
2580
2581	statusmsg2 "${progname} ended:" "$(date)"
2582	if [ -s "${results}" ]; then
2583		echo "===> Summary of results:"
2584		sed -e 's/^===>//;s/^/	/' "${results}"
2585		echo "===> ."
2586	fi
2587}
2588
2589main "$@"
2590