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