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