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