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