xref: /netbsd-src/build.sh (revision 326b2259b73e878289ebd80cd9d20bc5aee35e99)
1#! /usr/bin/env sh
2#	$NetBSD: build.sh,v 1.111 2003/07/29 10:07:15 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	do_params=false
135
136	# Create scratch directory
137	#
138	tmpdir="${TMPDIR-/tmp}/nbbuild$$"
139	mkdir "${tmpdir}" || bomb "Cannot mkdir: ${tmpdir}"
140	trap "cd /; rm -r -f \"${tmpdir}\"" 0
141	results="${tmpdir}/build.sh.results"
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|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
325resolvepath()
326{
327	case "${OPTARG}" in
328	/*)
329		;;
330	*)
331		OPTARG="${TOP}/${OPTARG}"
332		;;
333	esac
334}
335
336usage()
337{
338	if [ -n "$*" ]; then
339		echo ""
340		echo "${progname}: $*"
341	fi
342	cat <<_usage_
343
344Usage: ${progname} [-EnorUu] [-a arch] [-B buildid] [-D dest] [-j njob] [-M obj]
345                [-m mach] [-O obj] [-R release] [-T tools] [-V var=[value]]
346                [-w wrapper] [-Z var]   operation [...]
347
348 Build operations (all imply "obj" and "tools"):
349    build               Run "make build"
350    distribution        Run "make distribution" (includes DESTDIR/etc/ files)
351    release             Run "make release" (includes kernels & distrib media)
352
353 Other operations:
354    help                Show this message (and exit)
355    makewrapper         Create ${toolprefix}make-\${MACHINE} wrapper and ${toolprefix}make.
356                        (Always done)
357    obj                 Run "make obj" (default unless -o is used)
358    tools               Build and install tools
359    install=idir        Run "make installworld" to \`idir'
360                        (useful after 'distribution' or 'release')
361    kernel=conf         Build kernel with config file \`conf'
362    releasekernel=conf  Install kernel built by kernel=conf to RELEASEDIR
363    sets                Create binary sets in RELEASEDIR/MACHINE/binary/sets
364    sourcesets          Create source sets in RELEASEDIR/source/sets
365    params              Display various make(1) parameters
366
367 Options:
368    -a arch     Set MACHINE_ARCH to arch (otherwise deduced from MACHINE)
369    -B buildId  Set BUILDID to buildId
370    -D dest     Set DESTDIR to dest.  (Default: destdir.MACHINE)
371    -E          Set "expert" mode; disables various safety checks.
372                Should not be used without expert knowledge of the build system
373    -j njob     Run up to njob jobs in parallel; see make(1)
374    -M obj      Set obj root directory to obj (sets MAKEOBJDIRPREFIX)
375                Unsets MAKEOBJDIR.
376    -m mach     Set MACHINE to mach (not required if NetBSD native)
377    -n          Show commands that would be executed, but do not execute them
378    -O obj      Set obj root directory to obj (sets a MAKEOBJDIR pattern).
379                Unsets MAKEOBJDIRPREFIX.
380    -o          Set MKOBJDIRS=no (do not create objdirs at start of build)
381    -R release  Set RELEASEDIR to release.  (Default: releasedir)
382    -r          Remove contents of TOOLDIR and DESTDIR before building
383    -T tools    Set TOOLDIR to tools.  If unset, and TOOLDIR is not set in
384                the environment, ${toolprefix}make will be (re)built unconditionally
385    -U          Set MKUNPRIVED=yes (build without requiring root privileges)
386    -u          Set MKUPDATE=yes (do not run "make clean" first).
387		Without this, everything is rebuilt, including the tools.
388    -V v=[val]  Set variable \`v' to \`val'
389    -w wrapper  Create ${toolprefix}make script as wrapper
390                (Default: \${TOOLDIR}/bin/${toolprefix}make-\${MACHINE})
391    -Z v        Unset ("zap") variable \`v'
392
393_usage_
394	exit 1
395}
396
397parseoptions()
398{
399	opts='a:B:bD:dEhi:j:k:M:m:nO:oR:rT:tUuV:w:Z:'
400	opt_a=no
401
402	if type getopts >/dev/null 2>&1; then
403		# Use POSIX getopts.
404		#
405		getoptcmd='getopts ${opts} opt && opt=-${opt}'
406		optargcmd=':'
407		optremcmd='shift $((${OPTIND} -1))'
408	else
409		type getopt >/dev/null 2>&1 ||
410		    bomb "/bin/sh shell is too old; try ksh or bash"
411
412		# Use old-style getopt(1) (doesn't handle whitespace in args).
413		#
414		args="$(getopt ${opts} $*)"
415		[ $? = 0 ] || usage
416		set -- ${args}
417
418		getoptcmd='[ $# -gt 0 ] && opt="$1" && shift'
419		optargcmd='OPTARG="$1"; shift'
420		optremcmd=':'
421	fi
422
423	# Parse command line options.
424	#
425	while eval ${getoptcmd}; do
426		case ${opt} in
427
428		-a)
429			eval ${optargcmd}
430			MACHINE_ARCH=${OPTARG}
431			opt_a=yes
432			;;
433
434		-B)
435			eval ${optargcmd}
436			BUILDID=${OPTARG}
437			;;
438
439		-b)
440			usage "'-b' has been replaced by 'makewrapper'"
441			;;
442
443		-D)
444			eval ${optargcmd}; resolvepath
445			setmakeenv DESTDIR "${OPTARG}"
446			;;
447
448		-d)
449			usage "'-d' has been replaced by 'distribution'"
450			;;
451
452		-E)
453			do_expertmode=true
454			;;
455
456		-i)
457			usage "'-i idir' has been replaced by 'install=idir'"
458			;;
459
460		-j)
461			eval ${optargcmd}
462			parallel="-j ${OPTARG}"
463			;;
464
465		-k)
466			usage "'-k conf' has been replaced by 'kernel=conf'"
467			;;
468
469		-M)
470			eval ${optargcmd}; resolvepath
471			makeobjdir="${OPTARG}"
472			unsetmakeenv MAKEOBJDIR
473			setmakeenv MAKEOBJDIRPREFIX "${OPTARG}"
474			;;
475
476			# -m overrides MACHINE_ARCH unless "-a" is specified
477		-m)
478			eval ${optargcmd}
479			MACHINE="${OPTARG}"
480			[ "${opt_a}" != "yes" ] && getarch
481			;;
482
483		-n)
484			runcmd=echo
485			;;
486
487		-O)
488			eval ${optargcmd}; resolvepath
489			makeobjdir="${OPTARG}"
490			unsetmakeenv MAKEOBJDIRPREFIX
491			setmakeenv MAKEOBJDIR "\${.CURDIR:C,^$TOP,$OPTARG,}"
492			;;
493
494		-o)
495			MKOBJDIRS=no
496			;;
497
498		-R)
499			eval ${optargcmd}; resolvepath
500			setmakeenv RELEASEDIR "${OPTARG}"
501			;;
502
503		-r)
504			do_removedirs=true
505			do_rebuildmake=true
506			;;
507
508		-T)
509			eval ${optargcmd}; resolvepath
510			TOOLDIR="${OPTARG}"
511			export TOOLDIR
512			;;
513
514		-t)
515			usage "'-t' has been replaced by 'tools'"
516			;;
517
518		-U)
519			setmakeenv MKUNPRIVED yes
520			;;
521
522		-u)
523			setmakeenv MKUPDATE yes
524			;;
525
526		-V)
527			eval ${optargcmd}
528			case "${OPTARG}" in
529		    # XXX: consider restricting which variables can be changed?
530			[a-zA-Z_][a-zA-Z_0-9]*=*)
531				setmakeenv "${OPTARG%%=*}" "${OPTARG#*=}"
532				;;
533			*)
534				usage "-V argument must be of the form 'var=[value]'"
535				;;
536			esac
537			;;
538
539		-w)
540			eval ${optargcmd}; resolvepath
541			makewrapper="${OPTARG}"
542			;;
543
544		-Z)
545			eval ${optargcmd}
546		    # XXX: consider restricting which variables can be unset?
547			unsetmakeenv "${OPTARG}"
548			;;
549
550		--)
551			break
552			;;
553
554		-'?'|-h)
555			usage
556			;;
557
558		esac
559	done
560
561	# Validate operations.
562	#
563	eval ${optremcmd}
564	while [ $# -gt 0 ]; do
565		op=$1; shift
566		operations="${operations} ${op}"
567
568		case "${op}" in
569
570		help)
571			usage
572			;;
573
574		makewrapper|obj|tools|build|distribution|release|sets|sourcesets|params)
575			;;
576
577		kernel=*|releasekernel=*)
578			arg=${op#*=}
579			op=${op%%=*}
580			[ -n "${arg}" ] ||
581			    bomb "Must supply a kernel name with \`${op}=...'"
582			;;
583
584		install=*)
585			arg=${op#*=}
586			op=${op%%=*}
587			[ -n "${arg}" ] ||
588			    bomb "Must supply a directory with \`install=...'"
589			;;
590
591		*)
592			usage "Unknown operation \`${op}'"
593			;;
594
595		esac
596		eval do_${op}=true
597	done
598	[ -n "${operations}" ] || usage "Missing operation to perform."
599
600	# Set up MACHINE*.  On a NetBSD host, these are allowed to be unset.
601	#
602	if [ -z "${MACHINE}" ]; then
603		[ "${uname_s}" = "NetBSD" ] ||
604		    bomb "MACHINE must be set, or -m must be used, for cross builds."
605		MACHINE=${uname_m}
606	fi
607	[ -n "${MACHINE_ARCH}" ] || getarch
608	validatearch
609
610	# Set up default make(1) environment.
611	#
612	setmakeenv LC_ALL C
613	makeenv="${makeenv} TOOLDIR MACHINE MACHINE_ARCH MAKEFLAGS"
614	[ -z "${BUILDID}" ] || makeenv="${makeenv} BUILDID"
615	MAKEFLAGS="-m ${TOP}/share/mk ${MAKEFLAGS} MKOBJDIRS=${MKOBJDIRS-yes}"
616	export MAKEFLAGS MACHINE MACHINE_ARCH
617}
618
619rebuildmake()
620{
621	# Test make source file timestamps against installed ${toolprefix}make
622	# binary, if TOOLDIR is pre-set.
623	#
624	# Note that we do NOT try to grovel "mk.conf" here to find out if
625	# TOOLDIR is set there, because it can contain make variable
626	# expansions and other stuff only parseable *after* we have a working
627	# ${toolprefix}make.  So this logic can only work if the user has
628	# pre-set TOOLDIR in the environment or used the -T option to build.sh.
629	#
630	make="${TOOLDIR-nonexistent}/bin/${toolprefix}make"
631	if [ -x "${make}" ]; then
632		for f in usr.bin/make/*.[ch] usr.bin/make/lst.lib/*.[ch]; do
633			if [ "${f}" -nt "${make}" ]; then
634				do_rebuildmake=true
635				break
636			fi
637		done
638	else
639		do_rebuildmake=true
640	fi
641
642	# Build bootstrap ${toolprefix}make if needed.
643	if ${do_rebuildmake}; then
644		statusmsg "Bootstrapping ${toolprefix}make"
645		${runcmd} cd "${tmpdir}"
646		${runcmd} env CC="${HOST_CC-cc}" CPPFLAGS="${HOST_CPPFLAGS}" \
647			CFLAGS="${HOST_CFLAGS--O}" LDFLAGS="${HOST_LDFLAGS}" \
648			"${TOP}/tools/make/configure" ||
649		    bomb "Configure of ${toolprefix}make failed"
650		${runcmd} sh buildmake.sh ||
651		    bomb "Build of ${toolprefix}make failed"
652		make="${tmpdir}/${toolprefix}make"
653		${runcmd} cd "${TOP}"
654		${runcmd} rm -f usr.bin/make/*.o usr.bin/make/lst.lib/*.o
655	fi
656}
657
658validatemakeparams()
659{
660	if [ "${runcmd}" = "echo" ]; then
661		TOOLCHAIN_MISSING=no
662		EXTERNAL_TOOLCHAIN=""
663	else
664		TOOLCHAIN_MISSING=$(raw_getmakevar TOOLCHAIN_MISSING)
665		EXTERNAL_TOOLCHAIN=$(raw_getmakevar EXTERNAL_TOOLCHAIN)
666	fi
667	if [ "${TOOLCHAIN_MISSING}" = "yes" ] && \
668	   [ -z "${EXTERNAL_TOOLCHAIN}" ]; then
669		${runcmd} echo "ERROR: build.sh (in-tree cross-toolchain) is not yet available for"
670		${runcmd} echo "	MACHINE:      ${MACHINE}"
671		${runcmd} echo "	MACHINE_ARCH: ${MACHINE_ARCH}"
672		${runcmd} echo ""
673		${runcmd} echo "All builds for this platform should be done via a traditional make"
674		${runcmd} echo "If you wish to use an external cross-toolchain, set"
675		${runcmd} echo "	EXTERNAL_TOOLCHAIN=<path to toolchain root>"
676		${runcmd} echo "in either the environment or mk.conf and rerun"
677		${runcmd} echo "	${progname} $*"
678		exit 1
679	fi
680
681	if [ "${MKOBJDIRS}" != "no" ]; then
682		# If setting -M or -O to the root of an obj dir, make sure
683		# the base directory is made before continuing as <bsd.own.mk>
684		# will need this to pick up _SRC_TOP_OBJ_
685		#
686		if [ ! -z "${makeobjdir}" ]; then
687			${runcmd} mkdir -p "${makeobjdir}"
688		fi
689
690		# make obj in tools to ensure that the objdir for the top-level
691		# of the source tree and for "tools" is available, in case the
692		# default TOOLDIR setting from <bsd.own.mk> is used, or the
693		# build.sh default DESTDIR and RELEASEDIR is to be used.
694		#
695		${runcmd} cd tools
696		${runcmd} "${make}" -m ${TOP}/share/mk obj NOSUBDIR= ||
697		    bomb "Failed to make obj in tools"
698		${runcmd} cd "${TOP}"
699	fi
700
701	statusmsg "MACHINE:          ${MACHINE}"
702	statusmsg "MACHINE_ARCH:     ${MACHINE_ARCH}"
703
704	# Find TOOLDIR, DESTDIR, and RELEASEDIR.
705	#
706	TOOLDIR=$(getmakevar TOOLDIR)
707	statusmsg "TOOLDIR path:     ${TOOLDIR}"
708	DESTDIR=$(getmakevar DESTDIR)
709	RELEASEDIR=$(getmakevar RELEASEDIR)
710	if ! $do_expertmode; then
711		_SRC_TOP_OBJ_=$(getmakevar _SRC_TOP_OBJ_)
712		: ${DESTDIR:=${_SRC_TOP_OBJ_}/destdir.${MACHINE}}
713		: ${RELEASEDIR:=${_SRC_TOP_OBJ_}/releasedir}
714		makeenv="${makeenv} DESTDIR RELEASEDIR"
715	fi
716	export TOOLDIR DESTDIR RELEASEDIR
717	statusmsg "DESTDIR path:     ${DESTDIR}"
718	statusmsg "RELEASEDIR path:  ${RELEASEDIR}"
719
720	# Check validity of TOOLDIR and DESTDIR.
721	#
722	if [ -z "${TOOLDIR}" ] || [ "${TOOLDIR}" = "/" ]; then
723		bomb "TOOLDIR '${TOOLDIR}' invalid"
724	fi
725	removedirs="${TOOLDIR}"
726
727	if [ -z "${DESTDIR}" ] || [ "${DESTDIR}" = "/" ]; then
728		if ${do_build} || ${do_distribution} || ${do_release}; then
729			if ! ${do_build} || \
730			   [ "${uname_s}" != "NetBSD" ] || \
731			   [ "${uname_m}" != "${MACHINE}" ]; then
732				bomb "DESTDIR must != / for cross builds, or ${progname} 'distribution' or 'release'."
733			fi
734			if ! ${do_expertmode}; then
735				bomb "DESTDIR must != / for non -E (expert) builds"
736			fi
737			statusmsg "WARNING: Building to /, in expert mode."
738			statusmsg "         This may cause your system to break!  Reasons include:"
739			statusmsg "            - your kernel is not up to date"
740			statusmsg "            - the libraries or toolchain have changed"
741			statusmsg "         YOU HAVE BEEN WARNED!"
742		fi
743	else
744		removedirs="${removedirs} ${DESTDIR}"
745	fi
746	if ${do_build} || ${do_distribution} || ${do_release}; then
747		if ! ${do_expertmode} && \
748		    [ $(id -u 2>/dev/null) -ne 0 ] && \
749		    [ -z "${MKUNPRIVED}" ] ; then
750			bomb "-U or -E must be set for build as an unprivileged user."
751		fi
752        fi
753	if ${do_releasekernel} && [ -z "${RELEASEDIR}" ]; then
754		bomb "Must set RELEASEDIR with \`releasekernel=...'"
755	fi
756}
757
758
759createmakewrapper()
760{
761	# Remove the target directories.
762	#
763	if ${do_removedirs}; then
764		for f in ${removedirs}; do
765			statusmsg "Removing ${f}"
766			${runcmd} rm -r -f "${f}"
767		done
768	fi
769
770	# Recreate $TOOLDIR.
771	#
772	${runcmd} mkdir -p "${TOOLDIR}/bin" ||
773	    bomb "mkdir of '${TOOLDIR}/bin' failed"
774
775	# Install ${toolprefix}make if it was built.
776	#
777	if ${do_rebuildmake}; then
778		${runcmd} rm -f "${TOOLDIR}/bin/${toolprefix}make"
779		${runcmd} cp "${make}" "${TOOLDIR}/bin/${toolprefix}make" ||
780		    bomb "Failed to install \$TOOLDIR/bin/${toolprefix}make"
781		make="${TOOLDIR}/bin/${toolprefix}make"
782		statusmsg "Created ${make}"
783	fi
784
785	# Build a ${toolprefix}make wrapper script, usable by hand as
786	# well as by build.sh.
787	#
788	if [ -z "${makewrapper}" ]; then
789		makewrapper="${TOOLDIR}/bin/${toolprefix}make-${makewrappermachine:-${MACHINE}}"
790		[ -z "${BUILDID}" ] || makewrapper="${makewrapper}-${BUILDID}"
791	fi
792
793	${runcmd} rm -f "${makewrapper}"
794	if [ "${runcmd}" = "echo" ]; then
795		echo 'cat <<EOF >'${makewrapper}
796		makewrapout=
797	else
798		makewrapout=">>\${makewrapper}"
799	fi
800
801	eval cat <<EOF ${makewrapout}
802#! /bin/sh
803# Set proper variables to allow easy "make" building of a NetBSD subtree.
804# Generated from:  \$NetBSD: build.sh,v 1.111 2003/07/29 10:07:15 lukem Exp $
805#
806
807EOF
808	for f in ${makeenv}; do
809		if eval "[ -z \"\${$f}\" -a \"\${${f}-X}\" = \"X\" ]"; then
810			eval echo "unset ${f}" ${makewrapout}
811		else
812			eval echo "${f}=\'\$$(echo ${f})\'\;\ export\ ${f}" ${makewrapout}
813		fi
814	done
815	eval echo "USETOOLS=yes\; export USETOOLS" ${makewrapout}
816
817	eval cat <<EOF ${makewrapout}
818
819exec "\${TOOLDIR}/bin/${toolprefix}make" \${1+"\$@"}
820EOF
821	[ "${runcmd}" = "echo" ] && echo EOF
822	${runcmd} chmod +x "${makewrapper}"
823	statusmsg "makewrapper:      ${makewrapper}"
824	statusmsg "Updated ${makewrapper}"
825}
826
827buildtools()
828{
829	if [ "${MKOBJDIRS}" != "no" ]; then
830		${runcmd} "${makewrapper}" ${parallel} obj-tools ||
831		    bomb "Failed to make obj-tools"
832	fi
833	${runcmd} cd tools
834	if [ -z "${MKUPDATE}" ]; then
835		cleandir=cleandir
836	else
837		cleandir=
838	fi
839	${runcmd} "${makewrapper}" ${cleandir} dependall install ||
840	    bomb "Failed to make tools"
841	statusmsg "Tools built to ${TOOLDIR}"
842	${runcmd} cd "${TOP}"
843}
844
845getkernelconf()
846{
847	kernelconf="$1"
848	if [ "${MKOBJDIRS}" != "no" ] && [ ! -z "${makeobjdir}" ]; then
849		# The correct value of KERNOBJDIR might
850		# depend on a prior "make obj" in
851		# ${KERNSRCDIR}/${KERNARCHDIR}/compile.
852		#
853		KERNSRCDIR="$(getmakevar KERNSRCDIR)"
854		KERNARCHDIR="$(getmakevar KERNARCHDIR)"
855		${runcmd} cd "${KERNSRCDIR}/${KERNARCHDIR}/compile"
856		${runcmd} "${makewrapper}" obj ||
857		    bomb "Failed to make obj in ${KERNSRCDIR}/${KERNARCHDIR}/compile"
858		${runcmd} cd "${TOP}"
859	fi
860	KERNCONFDIR="$(getmakevar KERNCONFDIR)"
861	KERNOBJDIR="$(getmakevar KERNOBJDIR)"
862	case "${kernelconf}" in
863	*/*)
864		kernelconfpath="${kernelconf}"
865		kernelconfname="${kernelconf##*/}"
866		;;
867	*)
868		kernelconfpath="${KERNCONFDIR}/${kernelconf}"
869		kernelconfname="${kernelconf}"
870		;;
871	esac
872	kernelbuildpath="${KERNOBJDIR}/${kernelconfname}"
873}
874
875buildkernel()
876{
877	if ! ${do_tools} && ! ${buildkernelwarned:-false}; then
878		# Building tools every time we build a kernel is clearly
879		# unnecessary.  We could try to figure out whether rebuilding
880		# the tools is necessary this time, but it doesn't seem worth
881		# the trouble.  Instead, we say it's the user's responsibility
882		# to rebuild the tools if necessary.
883		#
884		statusmsg "Building kernel without building new tools"
885		buildkernelwarned=true
886	fi
887	getkernelconf $1
888	statusmsg "Building kernel:  ${kernelconf}"
889	statusmsg "Build directory:  ${kernelbuildpath}"
890	${runcmd} mkdir -p "${kernelbuildpath}" ||
891	    bomb "Cannot mkdir: ${kernelbuildpath}"
892	if [ -z "${MKUPDATE}" ]; then
893		${runcmd} cd "${kernelbuildpath}"
894		${runcmd} "${makewrapper}" cleandir ||
895		    bomb "Failed to make cleandir in ${kernelbuildpath}"
896		${runcmd} cd "${TOP}"
897	fi
898	${runcmd} "${TOOLDIR}/bin/${toolprefix}config" -b "${kernelbuildpath}" \
899		-s "${TOP}/sys" "${kernelconfpath}" ||
900	    bomb "${toolprefix}config failed for ${kernelconf}"
901	${runcmd} cd "${kernelbuildpath}"
902	${runcmd} "${makewrapper}" depend ||
903	    bomb "Failed to make depend in ${kernelbuildpath}"
904	${runcmd} "${makewrapper}" ${parallel} all ||
905	    bomb "Failed to make all in ${kernelbuildpath}"
906	${runcmd} cd "${TOP}"
907
908	if [ "${runcmd}" != "echo" ]; then
909		statusmsg "Kernels built from ${kernelconf}:"
910		kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
911		for kern in ${kernlist:-netbsd}; do
912			[ -f "${kernelbuildpath}/${kern}" ] && \
913			    echo "  ${kernelbuildpath}/${kern}"
914		done | tee -a "${results}"
915	fi
916}
917
918releasekernel()
919{
920	getkernelconf $1
921	kernelreldir="${RELEASEDIR}/${MACHINE}/binary/kernel"
922	${runcmd} mkdir -p "${kernelreldir}"
923	kernlist=$(awk '$1 == "config" { print $2 }' ${kernelconfpath})
924	for kern in ${kernlist:-netbsd}; do
925		builtkern="${kernelbuildpath}/${kern}"
926		[ -f "${builtkern}" ] || continue
927		releasekern="${kernelreldir}/${kern}-${kernelconfname}.gz"
928		statusmsg "Kernel copy:      ${releasekern}"
929		${runcmd} gzip -c -9 < "${builtkern}" > "${releasekern}"
930	done
931}
932
933installworld()
934{
935	dir="$1"
936	${runcmd} "${makewrapper}" INSTALLWORLDDIR="${dir}" installworld ||
937	    bomb "Failed to make installworld to ${dir}"
938	statusmsg "Successful installworld to ${dir}"
939}
940
941
942main()
943{
944	initdefaults
945	parseoptions "$@"
946
947	build_start=$(date)
948	statusmsg "${progname} command: $0 $@"
949	statusmsg "${progname} started: ${build_start}"
950
951	rebuildmake
952	validatemakeparams
953	createmakewrapper
954
955	# Perform the operations.
956	#
957	for op in ${operations}; do
958		case "${op}" in
959
960		makewrapper)
961			# no-op
962			;;
963
964		tools)
965			buildtools
966			;;
967
968		obj|build|distribution|release|sets|sourcesets|params)
969			${runcmd} "${makewrapper}" ${parallel} ${op} ||
970			    bomb "Failed to make ${op}"
971			statusmsg "Successful make ${op}"
972			;;
973
974		kernel=*)
975			arg=${op#*=}
976			buildkernel "${arg}"
977			;;
978
979		releasekernel=*)
980			arg=${op#*=}
981			releasekernel "${arg}"
982			;;
983
984		install=*)
985			arg=${op#*=}
986			if [ "${arg}" = "/" ] && \
987			    (	[ "${uname_s}" != "NetBSD" ] || \
988				[ "${uname_m}" != "${MACHINE}" ] ); then
989				bomb "'${op}' must != / for cross builds."
990			fi
991			installworld "${arg}"
992			;;
993
994		*)
995			bomb "Unknown operation \`${op}'"
996			;;
997
998		esac
999	done
1000
1001	statusmsg "${progname} started: ${build_start}"
1002	statusmsg "${progname} ended:   $(date)"
1003	if [ -s "${results}" ]; then
1004		echo "===> Summary of results:"
1005		sed -e 's/^===>//;s/^/	/' "${results}"
1006		echo "===> ."
1007	fi
1008}
1009
1010main "$@"
1011