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