build.sh revision 1.106
1#! /usr/bin/env sh
2#	$NetBSD: build.sh,v 1.106 2003/05/26 06:35:17 lukem Exp $
3#
4# Copyright (c) 2001-2003 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# 3. All advertising materials mentioning features or use of this software
19#    must display the following acknowledgement:
20#        This product includes software developed by the NetBSD
21#        Foundation, Inc. and its contributors.
22# 4. Neither the name of The NetBSD Foundation nor the names of its
23#    contributors may be used to endorse or promote products derived
24#    from this software without specific prior written permission.
25#
26# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36# POSSIBILITY OF SUCH DAMAGE.
37#
38#
39# Top level build wrapper, for a system containing no tools.
40#
41# This script should run on any POSIX-compliant shell.  For systems
42# with a strange /bin/sh, "ksh" or "bash" may be an ample alternative.
43#
44# Note, however, that due to the way the interpreter is invoked above,
45# if a POSIX-compliant shell is the first in the PATH, you won't have
46# to take any further action.
47#
48
49progname=${0##*/}
50toppid=$$
51results=/dev/null
52trap "exit 1" 1 2 3 15
53
54bomb()
55{
56	cat >&2 <<ERRORMESSAGE
57
58ERROR: $@
59*** BUILD ABORTED ***
60ERRORMESSAGE
61	kill ${toppid}		# in case we were invoked from a subshell
62	exit 1
63}
64
65
66statusmsg()
67{
68	${runcmd} echo "===> $@" | tee -a "${results}"
69}
70
71initdefaults()
72{
73	cd "$(dirname $0)"
74	[ -d usr.bin/make ] ||
75	    bomb "build.sh must be run from the top source level"
76	[ -f share/mk/bsd.own.mk ] ||
77	    bomb "src/share/mk is missing; please re-fetch the source tree"
78
79	uname_s=$(uname -s 2>/dev/null)
80	uname_m=$(uname -m 2>/dev/null)
81
82	# If $PWD is a valid name of the current directory, POSIX mandates
83	# that pwd return it by default which causes problems in the
84	# presence of symlinks.  Unsetting PWD is simpler than changing
85	# every occurrence of pwd to use -P.
86	#
87	# XXX Except that doesn't work on Solaris.
88	#
89	unset PWD
90	if [ "${uname_s}" = "SunOS" ]; then
91		TOP=$(pwd -P)
92	else
93		TOP=$(pwd)
94	fi
95
96	# Set defaults.
97	#
98	toolprefix=nb
99
100	# Some systems have a small ARG_MAX.  -X prevents make(1) from
101	# exporting variables in the environment redundantly.
102	#
103	case "${uname_s}" in
104	Darwin | FreeBSD | CYGWIN*)
105		MAKEFLAGS=-X
106		;;
107	*)
108		MAKEFLAGS=
109		;;
110	esac
111
112	makeenv=
113	makewrapper=
114	makewrappermachine=
115	runcmd=
116	operations=
117	removedirs=
118	do_expertmode=false
119	do_rebuildmake=false
120	do_removedirs=false
121
122	# do_{operation}=true if given operation is requested.
123	#
124	do_tools=false
125	do_obj=false
126	do_build=false
127	do_distribution=false
128	do_release=false
129	do_kernel=false
130	do_releasekernel=false
131	do_install=false
132	do_sets=false
133	do_sourcesets=false
134
135	# Create scratch directory
136	#
137	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
138	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
139	trap "cd /; rm -r -f \"${tmpdir}\"" 0
140	results="${tmpdir}/build.sh.results"
141}
142
143getarch()
144{
145	# Translate a MACHINE into a default MACHINE_ARCH.
146	#
147	case "${MACHINE}" in
148
149	acorn26|acorn32|cats|evbarm|hpcarm|netwinder|shark)
150		MACHINE_ARCH=arm
151		;;
152
153	hp700)
154		MACHINE_ARCH=hppa
155		;;
156
157	sun2)
158		MACHINE_ARCH=m68000
159		;;
160
161	amiga|atari|cesfic|hp300|luna68k|mac68k|mvme68k|news68k|next68k|sun3|x68k)
162		MACHINE_ARCH=m68k
163		;;
164
165	evbmips-e[bl]|sbmips-e[bl])
166		MACHINE_ARCH=mips${MACHINE##*-}
167		makewrappermachine=${MACHINE}
168		MACHINE=${MACHINE%-e[bl]}
169		;;
170
171	evbmips|sbmips)		# no default MACHINE_ARCH
172		;;
173
174	mipsco|newsmips|sgimips)
175		MACHINE_ARCH=mipseb
176		;;
177
178	algor|arc|cobalt|hpcmips|playstation2|pmax)
179		MACHINE_ARCH=mipsel
180		;;
181
182	pc532)
183		MACHINE_ARCH=ns32k
184		;;
185
186	amigappc|bebox|evbppc|macppc|mvmeppc|ofppc|pmppc|prep|sandpoint)
187		MACHINE_ARCH=powerpc
188		;;
189
190	evbsh3-e[bl])
191		MACHINE_ARCH=sh3${MACHINE##*-}
192		makewrappermachine=${MACHINE}
193		MACHINE=${MACHINE%-e[bl]}
194		;;
195
196	evbsh3)			# no default MACHINE_ARCH
197		;;
198
199	mmeye)
200		MACHINE_ARCH=sh3eb
201		;;
202
203	dreamcast|hpcsh)
204		MACHINE_ARCH=sh3el
205		;;
206
207	evbsh5)
208		MACHINE_ARCH=sh5el
209		;;
210	amd64)
211		MACHINE_ARCH=x86_64
212		;;
213
214	alpha|i386|sparc|sparc64|vax)
215		MACHINE_ARCH=${MACHINE}
216		;;
217
218	*)
219		bomb "Unknown target MACHINE: ${MACHINE}"
220		;;
221
222	esac
223}
224
225validatearch()
226{
227	# Ensure that the MACHINE_ARCH exists (and is supported by build.sh).
228	#
229	case "${MACHINE_ARCH}" in
230
231	alpha|arm|armeb|hppa|i386|m68000|m68k|mipse[bl]|ns32k|powerpc|sh[35]e[bl]|sparc|sparc64|vax|x86_64)
232		;;
233
234	"")
235		bomb "No MACHINE_ARCH provided"
236		;;
237
238	*)
239		bomb "Unknown target MACHINE_ARCH: ${MACHINE_ARCH}"
240		;;
241
242	esac
243
244	# Determine valid MACHINE_ARCHs for MACHINE
245	#
246	case "${MACHINE}" in
247
248	evbarm)
249		arches="arm armeb"
250		;;
251
252	evbmips|sbmips)
253		arches="mipseb mipsel"
254		;;
255
256	evbsh3)
257		arches="sh3eb sh3el"
258		;;
259
260	evbsh5)
261		arches="sh5eb sh5el"
262		;;
263
264	*)
265		oma="${MACHINE_ARCH}"
266		getarch
267		arches="${MACHINE_ARCH}"
268		MACHINE_ARCH="${oma}"
269		;;
270
271	esac
272
273	# Ensure that MACHINE_ARCH supports MACHINE
274	#
275	archok=false
276	for a in ${arches}; do
277		if [ "${a}" = "${MACHINE_ARCH}" ]; then
278			archok=true
279			break
280		fi
281	done
282	${archok} ||
283	    bomb "MACHINE_ARCH '${MACHINE_ARCH}' does not support MACHINE '${MACHINE}'"
284}
285
286raw_getmakevar()
287{
288	[ -x "${make}" ] || bomb "raw_getmakevar $1: ${make} is not executable"
289	"${make}" -m ${TOP}/share/mk -s -f- _x_ <<EOF
290_x_:
291	echo \${$1}
292.include <bsd.prog.mk>
293.include <bsd.kernobj.mk>
294EOF
295}
296
297getmakevar()
298{
299	# raw_getmakevar() doesn't work properly if $make hasn't yet been
300	# built, which can happen when running with the "-n" option.
301	# getmakevar() deals with this by emitting a literal '$'
302	# followed by the variable name, instead of trying to find the
303	# variable's value.
304	#
305	if [ -x "${make}" ]; then
306		raw_getmakevar "$1"
307	else
308		echo "\$$1"
309	fi
310}
311
312resolvepath()
313{
314	case "${OPTARG}" in
315	/*)
316		;;
317	*)
318		OPTARG="${TOP}/${OPTARG}"
319		;;
320	esac
321}
322
323usage()
324{
325	if [ -n "$*" ]; then
326		echo ""
327		echo "${progname}: $*"
328	fi
329	cat <<_usage_
330
331Usage: ${progname} [-EnorUu] [-a arch] [-B buildid] [-D dest] [-j njob] [-M obj]
332                [-m mach] [-O obj] [-R release] [-T tools] [-V var=[value]]
333                [-w wrapper]   operation [...]
334
335 Build operations (all imply "obj" and "tools"):
336    build               Run "make build"
337    distribution        Run "make distribution" (includes DESTDIR/etc/ files)
338    release             Run "make release" (includes kernels & distrib media)
339
340 Other operations:
341    help                Show this message (and exit)
342    makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
343                        (Always done)
344    obj                 Run "make obj" (default unless -o is used)
345    tools               Build and install tools
346    install=idir        Run "make installworld" to \`idir'
347                        (useful after 'distribution' or 'release')
348    kernel=conf         Build kernel with config file \`conf'
349    releasekernel=conf  Install kernel built by kernel=conf to RELEASEDIR
350    sets                Create binary sets in RELEASEDIR/MACHINE/binary/sets
351    sourcesets          Create source sets in RELEASEDIR/source/sets
352
353 Options:
354    -a arch     Set MACHINE_ARCH to arch (otherwise deduced from MACHINE)
355    -B buildId  Set BUILDID to buildId
356    -D dest     Set DESTDIR to dest.  (Default: destdir.MACHINE)
357    -E          Set "expert" mode; disables various safety checks.
358                Should not be used without expert knowledge of the build system
359    -j njob     Run up to njob jobs in parallel; see make(1)
360    -M obj      Set obj root directory to obj (sets MAKEOBJDIRPREFIX)
361    -m mach     Set MACHINE to mach (not required if NetBSD native)
362    -n          Show commands that would be executed, but do not execute them
363    -O obj      Set obj root directory to obj (sets a MAKEOBJDIR pattern)
364    -o          Set MKOBJDIRS=no (do not create objdirs at start of build)
365    -R release  Set RELEASEDIR to release.  (Default: releasedir)
366    -r          Remove contents of TOOLDIR and DESTDIR before building
367    -T tools    Set TOOLDIR to tools.  If unset, and TOOLDIR is not set in
368                the environment, ${toolprefix}make will be (re)built unconditionally
369    -U          Set UNPRIVED (build without requiring root privileges)
370    -u          Set UPDATE (do not run "make clean" first).
371		Without this, everything is rebuilt, including the tools.
372    -V v=[val]  Set variable \`v' to \`val'
373    -w wrapper  Create ${toolprefix}make script as wrapper
374                (Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE})
375
376_usage_
377	exit 1
378}
379
380parseoptions()
381{
382	opts='a:B:bD:dEhi:j:k:M:m:nO:oR:rT:tUuV:w:'
383	opt_a=no
384
385	if type getopts >/dev/null 2>&1; then
386		# Use POSIX getopts.
387		#
388		getoptcmd='getopts ${opts} opt && opt=-${opt}'
389		optargcmd=':'
390		optremcmd='shift $((${OPTIND} -1))'
391	else
392		type getopt >/dev/null 2>&1 ||
393		    bomb "/bin/sh shell is too old; try ksh or bash"
394
395		# Use old-style getopt(1) (doesn't handle whitespace in args).
396		#
397		args="$(getopt ${opts} $*)"
398		[ $? = 0 ] || usage
399		set -- ${args}
400
401		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
402		optargcmd='OPTARG="$1"; shift'
403		optremcmd=':'
404	fi
405
406	# Parse command line options.
407	#
408	while eval ${getoptcmd}; do
409		case ${opt} in
410
411		-a)
412			eval ${optargcmd}
413			MACHINE_ARCH=${OPTARG}
414			opt_a=yes
415			;;
416
417		-B)
418			eval ${optargcmd}
419			BUILDID=${OPTARG}
420			;;
421
422		-b)
423			usage "'-b' has been replaced by 'makewrapper'"
424			;;
425
426		-D)
427			eval ${optargcmd}; resolvepath
428			DESTDIR="${OPTARG}"
429			export DESTDIR
430			makeenv="${makeenv} DESTDIR"
431			;;
432
433		-d)
434			usage "'-d' has been replaced by 'distribution'"
435			;;
436
437		-E)
438			do_expertmode=true
439			;;
440
441		-i)
442			usage "'-i idir' has been replaced by 'install=idir'"
443			;;
444
445		-j)
446			eval ${optargcmd}
447			parallel="-j ${OPTARG}"
448			;;
449
450		-k)
451			usage "'-k conf' has been replaced by 'kernel=conf'"
452			;;
453
454		-M)
455			eval ${optargcmd}; resolvepath
456			MAKEOBJDIRPREFIX="${OPTARG}"
457			export MAKEOBJDIRPREFIX
458			makeobjdir="${OPTARG}"
459			makeenv="${makeenv} MAKEOBJDIRPREFIX"
460			;;
461
462			# -m overrides MACHINE_ARCH unless "-a" is specified
463		-m)
464			eval ${optargcmd}
465			MACHINE="${OPTARG}"
466			[ "${opt_a}" != "yes" ] && getarch
467			;;
468
469		-n)
470			runcmd=echo
471			;;
472
473		-O)
474			eval ${optargcmd}; resolvepath
475			MAKEOBJDIR="\${.CURDIR:C,^$TOP,$OPTARG,}"
476			export MAKEOBJDIR
477			makeobjdir="${OPTARG}"
478			makeenv="${makeenv} MAKEOBJDIR"
479			;;
480
481		-o)
482			MKOBJDIRS=no
483			;;
484
485		-R)
486			eval ${optargcmd}; resolvepath
487			RELEASEDIR="${OPTARG}"
488			export RELEASEDIR
489			makeenv="${makeenv} RELEASEDIR"
490			;;
491
492		-r)
493			do_removedirs=true
494			do_rebuildmake=true
495			;;
496
497		-T)
498			eval ${optargcmd}; resolvepath
499			TOOLDIR="${OPTARG}"
500			export TOOLDIR
501			;;
502
503		-t)
504			usage "'-t' has been replaced by 'tools'"
505			;;
506
507		-U)
508			UNPRIVED=yes
509			export UNPRIVED
510			makeenv="${makeenv} UNPRIVED"
511			;;
512
513		-u)
514			UPDATE=yes
515			export UPDATE
516			makeenv="${makeenv} UPDATE"
517			;;
518
519		-V)
520			eval ${optargcmd}
521			case "${OPTARG}" in
522		    # XXX: consider restricting which variables can be changed?
523			[a-zA-Z_][a-zA-Z_0-9]*=*)
524				var=${OPTARG%%=*}
525				value=${OPTARG#*=}
526				eval "${var}=\"${value}\"; export ${var}"
527				makeenv="${makeenv} ${var}"
528				;;
529			*)
530				usage "-V argument must be of the form 'var=[value]'"
531				;;
532			esac
533			;;
534
535		-w)
536			eval ${optargcmd}; resolvepath
537			makewrapper="${OPTARG}"
538			;;
539
540		--)
541			break
542			;;
543
544		-'?'|-h)
545			usage
546			;;
547
548		esac
549	done
550
551	# Validate operations.
552	#
553	eval ${optremcmd}
554	while [ $# -gt 0 ]; do
555		op=$1; shift
556		operations="${operations} ${op}"
557
558		case "${op}" in
559
560		help)
561			usage
562			;;
563
564		makewrapper|obj|tools|build|distribution|release|sets|sourcesets)
565			;;
566
567		kernel=*|releasekernel=*)
568			arg=${op#*=}
569			op=${op%%=*}
570			[ -n "${arg}" ] ||
571			    bomb "Must supply a kernel name with \`${op}=...'"
572			;;
573
574		install=*)
575			arg=${op#*=}
576			op=${op%%=*}
577			[ -n "${arg}" ] ||
578			    bomb "Must supply a directory with \`install=...'"
579			;;
580
581		*)
582			usage "Unknown operation \`${op}'"
583			;;
584
585		esac
586		eval do_${op}=true
587	done
588	[ -n "${operations}" ] || usage "Missing operation to perform."
589
590	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
591	#
592	if [ -z "${MACHINE}" ]; then
593		[ "${uname_s}" = "NetBSD" ] ||
594		    bomb "MACHINE must be set, or -m must be used, for cross builds."
595		MACHINE=${uname_m}
596	fi
597	[ -n "${MACHINE_ARCH}" ] || getarch
598	validatearch
599
600	# Set up default make(1) environment.
601	#
602	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
603	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
604	MAKEFLAGS="-m ${TOP}/share/mk ${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
605	export MAKEFLAGS MACHINE MACHINE_ARCH
606}
607
608rebuildmake()
609{
610	# Test make source file timestamps against installed ${toolprefix}make
611	# binary, if TOOLDIR is pre-set.
612	#
613	# Note that we do NOT try to grovel "mk.conf" here to find out if
614	# TOOLDIR is set there, because it can contain make variable
615	# expansions and other stuff only parseable *after* we have a working
616	# ${toolprefix}make.  So this logic can only work if the user has
617	# pre-set TOOLDIR in the environment or used the -T option to build.sh.
618	#
619	make="${TOOLDIR-nonexistent}/bin/${toolprefix}make"
620	if [ -x "${make}" ]; then
621		for f in usr.bin/make/*.[ch] usr.bin/make/lst.lib/*.[ch]; do
622			if [ "${f}" -nt "${make}" ]; then
623				do_rebuildmake=true
624				break
625			fi
626		done
627	else
628		do_rebuildmake=true
629	fi
630
631	# Build bootstrap ${toolprefix}make if needed.
632	if ${do_rebuildmake}; then
633		statusmsg "Bootstrapping ${toolprefix}make"
634		${runcmd} cd "${tmpdir}"
635		${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
636			CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
637			"${TOP}/tools/make/configure" ||
638		    bomb "Configure of ${toolprefix}make failed"
639		${runcmd} sh buildmake.sh ||
640		    bomb "Build of ${toolprefix}make failed"
641		make="${tmpdir}/${toolprefix}make"
642		${runcmd} cd "${TOP}"
643		${runcmd} rm -f usr.bin/make/*.o usr.bin/make/lst.lib/*.o
644	fi
645}
646
647validatemakeparams()
648{
649	if [ "${runcmd}" = "echo" ]; then
650		TOOLCHAIN_MISSING=no
651		EXTERNAL_TOOLCHAIN=""
652	else
653		TOOLCHAIN_MISSING=$(raw_getmakevar TOOLCHAIN_MISSING)
654		EXTERNAL_TOOLCHAIN=$(raw_getmakevar EXTERNAL_TOOLCHAIN)
655	fi
656	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
657	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
658		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
659		${runcmd} echo "	MACHINE:      ${MACHINE}"
660		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
661		${runcmd} echo ""
662		${runcmd} echo "All builds for this platform should be done via a traditional make"
663		${runcmd} echo "If you wish to use an external cross-toolchain, set"
664		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
665		${runcmd} echo "in either the environment or mk.conf and rerun"
666		${runcmd} echo "	${progname} $*"
667		exit 1
668	fi
669
670	if [ "${MKOBJDIRS}" != "no" ]; then
671		# If setting -M or -O to the root of an obj dir, make sure
672		# the base directory is made before continuing as <bsd.own.mk>
673		# will need this to pick up _SRC_TOP_OBJ_
674		#
675		if [ ! -z "${makeobjdir}" ]; then
676			${runcmd} mkdir -p "${makeobjdir}"
677		fi
678
679		# make obj in tools to ensure that the objdir for the top-level
680		# of the source tree and for "tools" is available, in case the
681		# default TOOLDIR setting from <bsd.own.mk> is used, or the
682		# build.sh default DESTDIR and RELEASEDIR is to be used.
683		#
684		${runcmd} cd tools
685		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
686		    bomb "Failed to make obj in tools"
687		${runcmd} cd "${TOP}"
688	fi
689
690	statusmsg "MACHINE:          ${MACHINE}"
691	statusmsg "MACHINE_ARCH:     ${MACHINE_ARCH}"
692
693	# Find TOOLDIR, DESTDIR, and RELEASEDIR.
694	#
695	TOOLDIR=$(getmakevar TOOLDIR)
696	statusmsg "TOOLDIR path:     ${TOOLDIR}"
697	DESTDIR=$(getmakevar DESTDIR)
698	RELEASEDIR=$(getmakevar RELEASEDIR)
699	if ! $do_expertmode; then
700		_SRC_TOP_OBJ_=$(getmakevar _SRC_TOP_OBJ_)
701		: ${DESTDIR:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
702		: ${RELEASEDIR:=${_SRC_TOP_OBJ_}/releasedir}
703		makeenv="${makeenv} DESTDIR RELEASEDIR"
704	fi
705	export TOOLDIR DESTDIR RELEASEDIR
706	statusmsg "DESTDIR path:     ${DESTDIR}"
707	statusmsg "RELEASEDIR path:  ${RELEASEDIR}"
708
709	# Check validity of TOOLDIR and DESTDIR.
710	#
711	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
712		bomb "TOOLDIR '${TOOLDIR}' invalid"
713	fi
714	removedirs="${TOOLDIR}"
715
716	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
717		if ${do_build} || ${do_distribution} || ${do_release}; then
718			if ! ${do_build} || \
719			   [ "${uname_s}" != "NetBSD" ] || \
720			   [ "${uname_m}" != "${MACHINE}" ]; then
721				bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'."
722			fi
723			if ! ${do_expertmode}; then
724				bomb "DESTDIR must != / for non -E (expert) builds"
725			fi
726			statusmsg "WARNING: Building to /, in expert mode."
727			statusmsg "         This may cause your system to break!  Reasons include:"
728			statusmsg "            - your kernel is not up to date"
729			statusmsg "            - the libraries or toolchain have changed"
730			statusmsg "         YOU HAVE BEEN WARNED!"
731		fi
732	else
733		removedirs="${removedirs} ${DESTDIR}"
734	fi
735	if ${do_build} || ${do_distribution} || ${do_release}; then
736		if ! ${do_expertmode} && \
737		    [ $(id -u 2>/dev/null) -ne 0 ] &&\
738		    [ -z "${UNPRIVED}" ] ; then
739			bomb "-U or -E must be set for build as an unprivileged user."
740		fi
741        fi
742	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
743		bomb "Must set RELEASEDIR with \`releasekernel=...'"
744	fi
745}
746
747
748createmakewrapper()
749{
750	# Remove the target directories.
751	#
752	if ${do_removedirs}; then
753		for f in ${removedirs}; do
754			statusmsg "Removing ${f}"
755			${runcmd} rm -r -f "${f}"
756		done
757	fi
758
759	# Recreate $TOOLDIR.
760	#
761	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
762	    bomb "mkdir of '${TOOLDIR}/bin' failed"
763
764	# Install ${toolprefix}make if it was built.
765	#
766	if ${do_rebuildmake}; then
767		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
768		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
769		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
770		make="${TOOLDIR}/bin/${toolprefix}make"
771		statusmsg "Created ${make}"
772	fi
773
774	# Build a ${toolprefix}make wrapper script, usable by hand as
775	# well as by build.sh.
776	#
777	if [ -z "${makewrapper}" ]; then
778		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
779		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
780	fi
781
782	${runcmd} rm -f "${makewrapper}"
783	if [ "${runcmd}" = "echo" ]; then
784		echo 'cat <<EOF >'${makewrapper}
785		makewrapout=
786	else
787		makewrapout=">>\${makewrapper}"
788	fi
789
790	eval cat <<EOF ${makewrapout}
791#! /bin/sh
792# Set proper variables to allow easy "make" building of a NetBSD subtree.
793# Generated from:  \$NetBSD: build.sh,v 1.106 2003/05/26 06:35:17 lukem Exp $
794#
795
796EOF
797	for f in ${makeenv}; do
798		eval echo "${f}=\'\$$(echo ${f})\'\;\ export\ ${f}" ${makewrapout}
799	done
800	eval echo "USETOOLS=yes\; export USETOOLS" ${makewrapout}
801
802	eval cat <<EOF ${makewrapout}
803
804exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
805EOF
806	[ "${runcmd}" = "echo" ] && echo EOF
807	${runcmd} chmod +x "${makewrapper}"
808	statusmsg "makewrapper:      ${makewrapper}"
809	statusmsg "Updated ${makewrapper}"
810}
811
812buildtools()
813{
814	if [ "${MKOBJDIRS}" != "no" ]; then
815		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
816		    bomb "Failed to make obj-tools"
817	fi
818	${runcmd} cd tools
819	if [ -z "${UPDATE}" ]; then
820		cleandir=cleandir
821	else
822		cleandir=
823	fi
824	${runcmd} "${makewrapper}" ${cleandir} dependall install ||
825	    bomb "Failed to make tools"
826	statusmsg "Tools built to ${TOOLDIR}"
827}
828
829getkernelconf()
830{
831	kernelconf="$1"
832	if [ "${MKOBJDIRS}" != "no" ] && [ ! -z "${makeobjdir}" ]; then
833		# The correct value of KERNOBJDIR might
834		# depend on a prior "make obj" in
835		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
836		#
837		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
838		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
839		${runcmd} cd "${KERNSRCDIR}/${KERNARCHDIR}/compile"
840		${runcmd} "${makewrapper}" obj ||
841		    bomb "Failed to make obj in ${KERNSRCDIR}/${KERNARCHDIR}/compile"
842		${runcmd} cd "${TOP}"
843	fi
844	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
845	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
846	case "${kernelconf}" in
847	*/*)
848		kernelconfpath="${kernelconf}"
849		kernelconfname="${kernelconf##*/}"
850		;;
851	*)
852		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
853		kernelconfname="${kernelconf}"
854		;;
855	esac
856	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
857}
858
859buildkernel()
860{
861	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
862		# Building tools every time we build a kernel is clearly
863		# unnecessary.  We could try to figure out whether rebuilding
864		# the tools is necessary this time, but it doesn't seem worth
865		# the trouble.  Instead, we say it's the user's responsibility
866		# to rebuild the tools if necessary.
867		#
868		statusmsg "Building kernel without building new tools"
869		buildkernelwarned=true
870	fi
871	getkernelconf $1
872	statusmsg "Building kernel:  ${kernelconf}"
873	statusmsg "Build directory:  ${kernelbuildpath}"
874	${runcmd} mkdir -p "${kernelbuildpath}" ||
875	    bomb "Cannot mkdir: ${kernelbuildpath}"
876	if [ -z "${UPDATE}" ]; then
877		${runcmd} cd "${kernelbuildpath}"
878		${runcmd} "${makewrapper}" cleandir ||
879		    bomb "Failed to make cleandir in ${kernelbuildpath}"
880		${runcmd} cd "${TOP}"
881	fi
882	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" -b "${kernelbuildpath}" \
883		-s "${TOP}/sys" "${kernelconfpath}" ||
884	    bomb "${toolprefix}config failed for ${kernelconf}"
885	${runcmd} cd "${kernelbuildpath}"
886	${runcmd} "${makewrapper}" depend ||
887	    bomb "Failed to make depend in ${kernelbuildpath}"
888	${runcmd} "${makewrapper}" ${parallel} all ||
889	    bomb "Failed to make all in ${kernelbuildpath}"
890	${runcmd} cd "${TOP}"
891
892	if [ "${runcmd}" != "echo" ]; then
893		statusmsg "Kernels built from ${kernelconf}:"
894		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
895		for kern in ${kernlist:-netbsd}; do
896			[ -f "${kernelbuildpath}/${kern}" ] && \
897			    echo "  ${kernelbuildpath}/${kern}"
898		done | tee -a "${results}"
899	fi
900}
901
902releasekernel()
903{
904	getkernelconf $1
905	kernelreldir="${RELEASEDIR}/${MACHINE}/binary/kernel"
906	${runcmd} mkdir -p "${kernelreldir}"
907	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
908echo "releasekernel: conf ${kernelconf}, name ${kernelconfname}, build ${kernelbuildpath}"
909	for kern in ${kernlist:-netbsd}; do
910echo "  checking ${kern} in ${kernelbuildpath}"
911		builtkern="${kernelbuildpath}/${kern}"
912		[ -f "${builtkern}" ] || continue
913		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
914		statusmsg "Kernel copy:      ${releasekern}"
915		${runcmd} gzip -c -9 < "${builtkern}" > "${releasekern}"
916	done
917}
918
919installworld()
920{
921	dir="$1"
922	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
923	    bomb "Failed to make installworld to ${dir}"
924	statusmsg "Successful installworld to ${dir}"
925}
926
927
928main()
929{
930	initdefaults
931	parseoptions "$@"
932
933	build_start=$(date)
934	statusmsg "${progname} command: $0 $@"
935	statusmsg "${progname} started: ${build_start}"
936
937	rebuildmake
938	validatemakeparams
939	createmakewrapper
940
941	# Perform the operations.
942	#
943	for op in ${operations}; do
944		case "${op}" in
945
946		makewrapper)
947			# no-op
948			;;
949
950		tools)
951			buildtools
952			;;
953
954		obj|build|distribution|release|sets|sourcesets)
955			${runcmd} "${makewrapper}" ${parallel} ${op} ||
956			    bomb "Failed to make ${op}"
957			statusmsg "Successful make ${op}"
958			;;
959
960		kernel=*)
961			arg=${op#*=}
962			buildkernel "${arg}"
963			;;
964
965		releasekernel=*)
966			arg=${op#*=}
967			releasekernel "${arg}"
968			;;
969
970		install=*)
971			arg=${op#*=}
972			if [ "${arg}" = "/" ] && \
973			    (	[ "${uname_s}" != "NetBSD" ] || \
974				[ "${uname_m}" != "${MACHINE}" ] ); then
975				bomb "'${op}' must != / for cross builds."
976			fi
977			installworld "${arg}"
978			;;
979
980		*)
981			bomb "Unknown operation \`${op}'"
982			;;
983
984		esac
985	done
986
987	statusmsg "${progname} started: ${build_start}"
988	statusmsg "${progname} ended:   $(date)"
989	if [ -s "${results}" ]; then
990		echo "===> Summary of results:"
991		sed -e 's/^===>//;s/^/	/' "${results}"
992		echo "===> ."
993	fi
994}
995
996main "$@"
997