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