blob: 83c0c8909ef853e96c8430fc23aa37193d1236af [file] [log] [blame]
Chris Sosa2b736002012-02-12 16:16:08 -08001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
rspangler@google.comd74220d2009-10-09 20:56:14 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5# Common constants for build scripts
6# This must evaluate properly for both /bin/bash and /bin/sh
7
8# All scripts should die on error unless commands are specifically excepted
9# by prefixing with '!' or surrounded by 'set +e' / 'set -e'.
rspangler@google.comd74220d2009-10-09 20:56:14 +000010
11# The number of jobs to pass to tools that can run in parallel (such as make
12# and dpkg-buildpackage
Brian Harring28bb01f2012-05-09 15:26:09 -070013if [ -z "${NUM_JOBS}" ]; then
14 NUM_JOBS=$(grep -c "^processor" /proc/cpuinfo)
15fi
16# Ensure that any sub scripts we invoke get the max proc count.
17export NUM_JOBS="${NUM_JOBS}"
rspangler@google.comd74220d2009-10-09 20:56:14 +000018
Simon Glass142ca062011-02-09 13:39:43 -080019# True if we have the 'pv' utility - also set up COMMON_PV_CAT for convenience
20COMMON_PV_OK=1
21COMMON_PV_CAT=pv
22pv -V >/dev/null 2>&1 || COMMON_PV_OK=0
23if [ $COMMON_PV_OK -eq 0 ]; then
24 COMMON_PV_CAT=cat
25fi
26
Greg Spencer798d75f2011-02-01 22:04:49 -080027# Make sure we have the location and name of the calling script, using
28# the current value if it is already set.
29SCRIPT_LOCATION=${SCRIPT_LOCATION:-$(dirname "$(readlink -f "$0")")}
30SCRIPT_NAME=${SCRIPT_NAME:-$(basename "$0")}
rspangler@google.comd74220d2009-10-09 20:56:14 +000031
Anton Staaf30acb0b2011-01-26 16:00:20 -080032# Detect whether we're inside a chroot or not
33if [ -e /etc/debian_chroot ]
rspangler@google.comd74220d2009-10-09 20:56:14 +000034then
Anton Staaf30acb0b2011-01-26 16:00:20 -080035 INSIDE_CHROOT=1
rspangler@google.comd74220d2009-10-09 20:56:14 +000036else
Anton Staaf30acb0b2011-01-26 16:00:20 -080037 INSIDE_CHROOT=0
rspangler@google.comd74220d2009-10-09 20:56:14 +000038fi
39
Mike Frysinger669b28b2012-02-07 18:01:00 -050040# Determine and set up variables needed for fancy color output (if supported).
41V_BOLD_RED=
42V_BOLD_GREEN=
43V_BOLD_YELLOW=
44V_REVERSE=
45V_VIDOFF=
46
47if tput colors >/dev/null 2>&1; then
48 # order matters: we want VIDOFF last so that when we trace with `set -x`,
49 # our terminal doesn't bleed colors as bash dumps the values of vars.
50 V_BOLD_RED="$(tput bold; tput setaf 1)"
51 V_BOLD_GREEN="$(tput bold; tput setaf 2)"
52 V_BOLD_YELLOW="$(tput bold; tput setaf 3)"
53 V_REVERSE="$(tput rev)"
54 V_VIDOFF="$(tput sgr0)"
55fi
56
Brian Harring7f175a52012-03-02 05:37:00 -080057# Stubs for sh compatibility.
Mike Frysinger6b1abb22012-05-11 13:44:06 -040058_dump_trace() { :; }
59_escaped_echo() {
Brian Harring7f175a52012-03-02 05:37:00 -080060 printf '%b\n' "$*"
61}
62
63# Bash awareness, including stacktraces if possible.
64if [ -n "${BASH_VERSION-}" ]; then
65 function _escaped_echo() {
66 echo -e "$@"
67 }
68 # Turn on bash debug support if available.
69 if shopt -s extdebug 2> /dev/null; then
70 # Pull the path relative to this lib; SCRIPT_ROOT should always be set,
71 # but has never been formally required.
72 if [ -n "${SOURCE_ROOT-}" ]; then
73 . "${SOURCE_ROOT}"/common_bash_backtraces.sh
74 else
75 x=$(readlink -f "${BASH_SOURCE[0]}")
76 . "${x%/*}"/common_bash_backtraces.sh
77 unset x
78 fi
79 fi
80fi
81
Mike Frysinger669b28b2012-02-07 18:01:00 -050082# Declare these asap so that code below can safely assume they exist.
Mike Frysinger6b1abb22012-05-11 13:44:06 -040083_message() {
Brian Harring7f175a52012-03-02 05:37:00 -080084 local prefix="${1}"
85 shift
86 if [ $# -eq 0 ]; then
87 _escaped_echo >&2 "${prefix}${CROS_LOG_PREFIX:-""}:${V_VIDOFF}"
88 return
89 fi
90 (
91 # Handle newlines in the message, prefixing each chunk correctly.
92 # Do this in a subshell to avoid having to track IFS/set -f state.
93 IFS="
94"
95 set +f
96 set -- $*
97 IFS=' '
98 if [ $# -eq 0 ]; then
99 # Empty line was requested.
100 set -- ''
101 fi
102 for line in "$@"; do
103 _escaped_echo >&2 "${prefix}${CROS_LOG_PREFIX:-}: ${line}${V_VIDOFF}"
104 done
105 )
106}
107
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400108info() {
Brian Harring7f175a52012-03-02 05:37:00 -0800109 _message "${V_BOLD_GREEN}INFO " "$*"
Mike Frysinger669b28b2012-02-07 18:01:00 -0500110}
111
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400112warn() {
Brian Harring7f175a52012-03-02 05:37:00 -0800113 _message "${V_BOLD_YELLOW}WARNING " "$*"
Mike Frysinger669b28b2012-02-07 18:01:00 -0500114}
115
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400116error() {
Brian Harring7f175a52012-03-02 05:37:00 -0800117 _message "${V_BOLD_RED}ERROR " "$*"
Mike Frysinger669b28b2012-02-07 18:01:00 -0500118}
119
Brian Harring7f175a52012-03-02 05:37:00 -0800120
121# For all die functions, they must explicitly force set +eu;
122# no reason to have them cause their own crash if we're inthe middle
123# of reporting an error condition then exiting.
124
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400125die_err_trap() {
Brian Harring7f175a52012-03-02 05:37:00 -0800126 local command="$1" result="$2"
127 set +e +u
128
129 # Per the message, bash misreports 127 as 1 during err trap sometimes.
130 # Note this fact to ensure users don't place too much faith in the
131 # exit code in that case.
132 set -- "Command '${command}' exited with nonzero code: ${result}"
133 if [ -n "${BASH_VERSION-}" ]; then
134 if [ "$result" = 1 ] && [ -z "$(type -t $command)" ]; then
135 set -- "$@" \
136 '(Note bash sometimes misreports "command not found" as exit code 1 '\
137'instead of 127)'
138 fi
139 fi
140 _dump_trace
141 error
142 error "Command failed:"
143 DIE_PREFIX=' '
144 die_notrace "$@"
145}
146
147# Exit this script due to a failure, outputting a backtrace in the process.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400148die() {
Brian Harring7f175a52012-03-02 05:37:00 -0800149 set +e +u
150 _dump_trace
151 error
152 error "Error was:"
153 DIE_PREFIX=' '
154 die_notrace "$@"
155}
156
157# Exit this script w/out a backtrace.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400158die_notrace() {
Brian Harring7f175a52012-03-02 05:37:00 -0800159 set +e +u
160 if [ $# -eq 0 ]; then
161 set -- '(no error message given)'
162 fi
163 for line in "$@"; do
164 error "${DIE_PREFIX}$line"
165 done
Mike Frysinger669b28b2012-02-07 18:01:00 -0500166 exit 1
167}
168
Anton Staaf30acb0b2011-01-26 16:00:20 -0800169# Construct a list of possible locations for the source tree. This list is
170# based on various environment variables and globals that may have been set
171# by the calling script.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400172get_gclient_root_list() {
Anton Staaf30acb0b2011-01-26 16:00:20 -0800173 if [ $INSIDE_CHROOT -eq 1 ]; then
174 echo "/home/${USER}/trunk"
175
176 if [ -n "${SUDO_USER}" ]; then echo "/home/${SUDO_USER}/trunk"; fi
177 fi
178
179 if [ -n "${COMMON_SH}" ]; then echo "$(dirname "$COMMON_SH")/../.."; fi
180 if [ -n "${BASH_SOURCE}" ]; then echo "$(dirname "$BASH_SOURCE")/../.."; fi
181}
182
183# Based on the list of possible source locations we set GCLIENT_ROOT if it is
184# not already defined by looking for a src directory in each seach path
185# location. If we do not find a valid looking root we error out.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400186get_gclient_root() {
Anton Staaf30acb0b2011-01-26 16:00:20 -0800187 if [ -n "${GCLIENT_ROOT}" ]; then
188 return
189 fi
190
191 for path in $(get_gclient_root_list); do
192 if [ -d "${path}/src" ]; then
193 GCLIENT_ROOT=${path}
194 break
195 fi
196 done
197
198 if [ -z "${GCLIENT_ROOT}" ]; then
199 # Using dash or sh, we don't know where we are. $0 refers to the calling
200 # script, not ourselves, so that doesn't help us.
201 echo "Unable to determine location for common.sh. If you are sourcing"
202 echo "common.sh from a script run via dash or sh, you must do it in the"
203 echo "following way:"
204 echo ' COMMON_SH="$(dirname "$0")/../../scripts/common.sh"'
205 echo ' . "$COMMON_SH"'
206 echo "where the first line is the relative path from your script to"
207 echo "common.sh."
208 exit 1
209 fi
210}
211
212# Find root of source tree
213get_gclient_root
214
rspangler@google.comd74220d2009-10-09 20:56:14 +0000215# Canonicalize the directories for the root dir and the calling script.
216# readlink is part of coreutils and should be present even in a bare chroot.
tedbo4f44d9e2010-01-08 17:26:11 -0800217# This is better than just using
rspangler@google.comd74220d2009-10-09 20:56:14 +0000218# FOO = "$(cd $FOO ; pwd)"
tedbo4f44d9e2010-01-08 17:26:11 -0800219# since that leaves symbolic links intact.
rspangler@google.comd74220d2009-10-09 20:56:14 +0000220# Note that 'realpath' is equivalent to 'readlink -f'.
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400221SCRIPT_LOCATION=$(readlink -f "$SCRIPT_LOCATION")
222GCLIENT_ROOT=$(readlink -f "$GCLIENT_ROOT")
rspangler@google.comd74220d2009-10-09 20:56:14 +0000223
224# Other directories should always be pathed down from GCLIENT_ROOT.
225SRC_ROOT="$GCLIENT_ROOT/src"
226SRC_INTERNAL="$GCLIENT_ROOT/src-internal"
227SCRIPTS_DIR="$SRC_ROOT/scripts"
228
229# Load developer's custom settings. Default location is in scripts dir,
230# since that's available both inside and outside the chroot. By convention,
231# settings from this file are variables starting with 'CHROMEOS_'
232CHROMEOS_DEV_SETTINGS="${CHROMEOS_DEV_SETTINGS:-$SCRIPTS_DIR/.chromeos_dev}"
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400233if [ -f "$CHROMEOS_DEV_SETTINGS" ]; then
rspangler@google.comd74220d2009-10-09 20:56:14 +0000234 # Turn on exit-on-error during custom settings processing
Greg Spencer798d75f2011-02-01 22:04:49 -0800235 SAVE_OPTS=$(set +o)
Brian Harring7f175a52012-03-02 05:37:00 -0800236 switch_to_strict_mode
rspangler@google.comd74220d2009-10-09 20:56:14 +0000237
238 # Read settings
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400239 . "$CHROMEOS_DEV_SETTINGS"
rspangler@google.comd74220d2009-10-09 20:56:14 +0000240
241 # Restore previous state of exit-on-error
242 eval "$SAVE_OPTS"
243fi
244
245# Load shflags
Zdenek Behan07d24222011-11-02 00:46:25 +0000246# NOTE: This code snippet is in particular used by the au-generator (which
247# stores shflags in ./lib/shflags/) and should not be touched.
248if [ -f "${SCRIPTS_DIR}/lib/shflags/shflags" ]; then
Mike Frysinger77c674b2012-02-07 18:05:07 -0500249 . "${SCRIPTS_DIR}/lib/shflags/shflags" || die "Couldn't find shflags"
Zdenek Behan07d24222011-11-02 00:46:25 +0000250else
251 . ./lib/shflags/shflags || die "Couldn't find shflags"
252fi
rspangler@google.comd74220d2009-10-09 20:56:14 +0000253
Bill Richardson10d27c22010-01-20 13:38:50 -0800254# Our local mirror
255DEFAULT_CHROMEOS_SERVER=${CHROMEOS_SERVER:-"http://build.chromium.org/mirror"}
rspangler@google.comd74220d2009-10-09 20:56:14 +0000256
Bill Richardson10d27c22010-01-20 13:38:50 -0800257# Upstream mirrors and build suites come in 2 flavors
258# DEV - development chroot, used to build the chromeos image
259# IMG - bootable image, to run on actual hardware
rspangler@google.comd74220d2009-10-09 20:56:14 +0000260
Bill Richardson10d27c22010-01-20 13:38:50 -0800261DEFAULT_DEV_MIRROR=${CHROMEOS_DEV_MIRROR:-"${DEFAULT_CHROMEOS_SERVER}/ubuntu"}
262DEFAULT_DEV_SUITE=${CHROMEOS_DEV_SUITE:-"karmic"}
263
264DEFAULT_IMG_MIRROR=${CHROMEOS_IMG_MIRROR:-"${DEFAULT_CHROMEOS_SERVER}/ubuntu"}
265DEFAULT_IMG_SUITE=${CHROMEOS_IMG_SUITE:-"karmic"}
rspangler@google.comd74220d2009-10-09 20:56:14 +0000266
267# Default location for chroot
268DEFAULT_CHROOT_DIR=${CHROMEOS_CHROOT_DIR:-"$GCLIENT_ROOT/chroot"}
269
270# All output files from build should go under $DEFAULT_BUILD_ROOT, so that
271# they don't pollute the source directory.
272DEFAULT_BUILD_ROOT=${CHROMEOS_BUILD_ROOT:-"$SRC_ROOT/build"}
273
David McMahon49302942010-02-18 16:55:35 -0800274# Set up a global ALL_BOARDS value
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400275if [ -d "$SRC_ROOT/overlays" ]; then
276 ALL_BOARDS=$(cd "$SRC_ROOT/overlays"; \
277 ls -1d overlay-* 2>&- | sed 's,overlay-,,g')
David Rochberg3b910702010-12-02 10:45:21 -0500278fi
David McMahon49302942010-02-18 16:55:35 -0800279# Strip CR
280ALL_BOARDS=$(echo $ALL_BOARDS)
Mike Frysingerc17a4932012-03-12 17:07:40 -0400281
282# Sets the default board variable for calling script.
283if [ -f "$GCLIENT_ROOT/src/scripts/.default_board" ] ; then
284 DEFAULT_BOARD=$(cat "$GCLIENT_ROOT/src/scripts/.default_board")
285 # Check for user typos like whitespace.
286 if [[ -n ${DEFAULT_BOARD//[a-zA-Z0-9-_]} ]] ; then
287 die ".default_board: invalid name detected; please fix:" \
288 "'${DEFAULT_BOARD}'"
289 fi
290fi
291# Stub to get people to upgrade.
292get_default_board() {
293 warn "please upgrade your script, and make sure to run build_packages"
294}
David McMahon49302942010-02-18 16:55:35 -0800295
David Jamesff072012010-11-30 13:22:05 -0800296# Enable --fast by default.
Greg Spencer798d75f2011-02-01 22:04:49 -0800297DEFAULT_FAST=${FLAGS_TRUE}
David James03668642010-07-28 17:08:29 -0700298
Chris Sosab0f57322011-10-25 03:07:23 +0000299# Directory to store built images. Should be set by sourcing script when used.
300BUILD_DIR=
Simon Glass142ca062011-02-09 13:39:43 -0800301
302# Standard filenames
Chris Sosab0f57322011-10-25 03:07:23 +0000303CHROMEOS_BASE_IMAGE_NAME="chromiumos_base_image.bin"
Simon Glass142ca062011-02-09 13:39:43 -0800304CHROMEOS_IMAGE_NAME="chromiumos_image.bin"
Chris Sosab0f57322011-10-25 03:07:23 +0000305CHROMEOS_DEVELOPER_IMAGE_NAME="chromiumos_image.bin"
Gilad Arnold08366272012-02-08 10:46:26 -0800306CHROMEOS_RECOVERY_IMAGE_NAME="recovery_image.bin"
Simon Glass142ca062011-02-09 13:39:43 -0800307CHROMEOS_TEST_IMAGE_NAME="chromiumos_test_image.bin"
Chris Sosab885b802011-02-16 15:33:11 -0800308CHROMEOS_FACTORY_TEST_IMAGE_NAME="chromiumos_factory_image.bin"
Chris Sosab0f57322011-10-25 03:07:23 +0000309CHROMEOS_FACTORY_INSTALL_SHIM_NAME="factory_install_shim.bin"
Simon Glass142ca062011-02-09 13:39:43 -0800310
rspangler@google.comd74220d2009-10-09 20:56:14 +0000311# Directory locations inside the dev chroot
312CHROOT_TRUNK_DIR="/home/$USER/trunk"
313
Chris Sosaaa1a7fd2010-04-02 14:06:29 -0700314# Install make for portage ebuilds. Used by build_image and gmergefs.
Chris Masoned11ce172010-11-09 14:22:08 -0800315# TODO: Is /usr/local/autotest-chrome still used by anyone?
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800316COMMON_INSTALL_MASK="
Daniel Erate82f07c2010-12-21 13:39:22 -0800317 *.a
318 *.la
319 /etc/init.d
320 /etc/runlevels
Hung-Te Lin76272be2012-08-07 19:10:09 +0800321 /firmware
Daniel Erate82f07c2010-12-21 13:39:22 -0800322 /lib/rc
323 /usr/bin/Xnest
324 /usr/bin/Xvfb
325 /usr/include
326 /usr/lib/debug
327 /usr/lib/gcc
328 /usr/lib/gtk-2.0/include
Mike Frysinger27b5edb2012-08-08 18:52:06 -0400329 /usr/lib*/pkgconfig
Daniel Erate82f07c2010-12-21 13:39:22 -0800330 /usr/local/autotest-chrome
331 /usr/man
332 /usr/share/aclocal
333 /usr/share/doc
334 /usr/share/gettext
335 /usr/share/gtk-2.0
336 /usr/share/gtk-doc
337 /usr/share/info
338 /usr/share/man
339 /usr/share/openrc
340 /usr/share/pkgconfig
341 /usr/share/readline
Chris Wolfed13775f2011-07-26 16:34:38 -0400342 /usr/src
Daniel Erate82f07c2010-12-21 13:39:22 -0800343 "
Chris Sosaaa1a7fd2010-04-02 14:06:29 -0700344
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800345# Mask for base, dev, and test images (build_image, build_image --test)
346DEFAULT_INSTALL_MASK="
347 $COMMON_INSTALL_MASK
348 /usr/local/autotest
Joseph Hwangca63e042012-03-24 20:38:21 +0800349 /lib/modules/*/kernel/drivers/input/misc/uinput.ko
Olof Johansson1222b2e2012-08-08 15:27:35 -0700350 /lib/modules/*/build
351 /lib/modules/*/source
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800352 "
353
354# Mask for factory test image (build_image --factory)
355FACTORY_TEST_INSTALL_MASK="
356 $COMMON_INSTALL_MASK
357 */.svn
358 */CVS
359 /usr/local/autotest/[^c]*
360 /usr/local/autotest/conmux
361 /usr/local/autotest/client/deps/chrome_test
362 /usr/local/autotest/client/deps/piglit
363 /usr/local/autotest/client/deps/pyauto_dep
364 /usr/local/autotest/client/deps/realtimecomm_*
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800365 /usr/local/autotest/client/site_tests/graphics_WebGLConformance
366 /usr/local/autotest/client/site_tests/platform_ToolchainOptions
367 /usr/local/autotest/client/site_tests/realtimecomm_GTalk*
Jon Salzd712ae92012-07-11 14:12:16 +0800368 /usr/local/autotest/client/tests
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800369 "
370
Chris Sosac9422fa2012-03-05 15:58:07 -0800371# Mask for factory install shim (build_image factory_install)
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800372FACTORY_SHIM_INSTALL_MASK="
373 $DEFAULT_INSTALL_MASK
374 /opt/[^g]*
Daniel Erate82f07c2010-12-21 13:39:22 -0800375 /opt/google/chrome
376 /opt/google/o3d
377 /opt/google/talkplugin
Daniel Erate82f07c2010-12-21 13:39:22 -0800378 /usr/lib/dri
379 /usr/lib/python2.6/test
Daniel Erate82f07c2010-12-21 13:39:22 -0800380 /usr/local/autotest-pkgs
381 /usr/share/X11
382 /usr/share/chewing
383 /usr/share/fonts
384 /usr/share/ibus-pinyin
385 /usr/share/libhangul
386 /usr/share/locale
387 /usr/share/m17n
388 /usr/share/mime
389 /usr/share/sounds
390 /usr/share/tts
391 /usr/share/zoneinfo
392 "
Tom Wai-Hong Tamf87a3672010-05-17 16:06:33 +0800393
rspangler@google.comd74220d2009-10-09 20:56:14 +0000394# -----------------------------------------------------------------------------
395# Functions
396
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400397setup_board_warning() {
tedbo373c3902010-04-12 10:52:40 -0700398 echo
399 echo "$V_REVERSE================= WARNING ======================$V_VIDOFF"
Chris Sosaacada732010-02-23 15:20:03 -0800400 echo
401 echo "*** No default board detected in " \
402 "$GCLIENT_ROOT/src/scripts/.default_board"
403 echo "*** Either run setup_board with default flag set"
404 echo "*** or echo |board_name| > $GCLIENT_ROOT/src/scripts/.default_board"
405 echo
406}
407
Don Garrett640a0582010-05-04 16:54:28 -0700408# Enter a chroot and restart the current script if needed
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400409restart_in_chroot_if_needed() {
David Rochberg3b910702010-12-02 10:45:21 -0500410 # NB: Pass in ARGV: restart_in_chroot_if_needed "$@"
Greg Spencer798d75f2011-02-01 22:04:49 -0800411 if [ $INSIDE_CHROOT -ne 1 ]; then
Chris Sosafd2cdec2011-03-24 16:06:59 -0700412 # Get inside_chroot path for script.
413 local chroot_path="$(reinterpret_path_for_chroot "$0")"
Zdenek Behan2811c162011-08-13 00:47:38 +0200414 exec $GCLIENT_ROOT/chromite/bin/cros_sdk -- "$chroot_path" "$@"
Don Garrett640a0582010-05-04 16:54:28 -0700415 fi
416}
417
rspangler@google.comd74220d2009-10-09 20:56:14 +0000418# Fail unless we're inside the chroot. This guards against messing up your
419# workstation.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400420assert_inside_chroot() {
Greg Spencer798d75f2011-02-01 22:04:49 -0800421 if [ $INSIDE_CHROOT -ne 1 ]; then
rspangler@google.comd74220d2009-10-09 20:56:14 +0000422 echo "This script must be run inside the chroot. Run this first:"
Zdenek Behan2811c162011-08-13 00:47:38 +0200423 echo " cros_sdk"
rspangler@google.comd74220d2009-10-09 20:56:14 +0000424 exit 1
425 fi
426}
427
428# Fail if we're inside the chroot. This guards against creating or entering
429# nested chroots, among other potential problems.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400430assert_outside_chroot() {
Greg Spencer798d75f2011-02-01 22:04:49 -0800431 if [ $INSIDE_CHROOT -ne 0 ]; then
rspangler@google.comd74220d2009-10-09 20:56:14 +0000432 echo "This script must be run outside the chroot."
433 exit 1
434 fi
435}
436
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400437assert_not_root_user() {
Greg Spencer798d75f2011-02-01 22:04:49 -0800438 if [ $(id -u) = 0 ]; then
derat@google.com86dcc8e2009-11-21 19:49:49 +0000439 echo "This script must be run as a non-root user."
440 exit 1
441 fi
442}
443
Luigi Semenzato1f82e122010-03-23 12:43:08 -0700444# Check that all arguments are flags; that is, there are no remaining arguments
445# after parsing from shflags. Allow (with a warning) a single empty-string
446# argument.
447#
448# TODO: fix buildbot so that it doesn't pass the empty-string parameter,
449# then change this function.
450#
451# Usage: check_flags_only_and_allow_null_arg "$@" && set --
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400452check_flags_only_and_allow_null_arg() {
Luigi Semenzato1f82e122010-03-23 12:43:08 -0700453 do_shift=1
454 if [[ $# == 1 && -z "$@" ]]; then
455 echo "$0: warning: ignoring null argument" >&2
456 shift
457 do_shift=0
458 fi
459 if [[ $# -gt 0 ]]; then
460 echo "error: invalid arguments: \"$@\"" >&2
461 flags_help
462 exit 1
463 fi
464 return $do_shift
465}
466
Chris Sosaaa1a7fd2010-04-02 14:06:29 -0700467# Removes single quotes around parameter
468# Arguments:
469# $1 - string which optionally has surrounding quotes
470# Returns:
471# None, but prints the string without quotes.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400472remove_quotes() {
Chris Sosaaa1a7fd2010-04-02 14:06:29 -0700473 echo "$1" | sed -e "s/^'//; s/'$//"
474}
tedbo373c3902010-04-12 10:52:40 -0700475
476# Writes stdin to the given file name as root using sudo in overwrite mode.
477#
478# $1 - The output file name.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400479sudo_clobber() {
tedbo373c3902010-04-12 10:52:40 -0700480 sudo tee "$1" > /dev/null
481}
482
483# Writes stdin to the given file name as root using sudo in append mode.
484#
485# $1 - The output file name.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400486sudo_append() {
tedbo373c3902010-04-12 10:52:40 -0700487 sudo tee -a "$1" > /dev/null
488}
robotboy98912212010-04-12 14:08:14 -0700489
Mike Frysinger286b5922011-09-28 11:59:53 -0400490# Execute multiple commands in a single sudo. Generally will speed things
491# up by avoiding multiple calls to `sudo`. If any commands fail, we will
492# call die with the failing command. We can handle a max of ~100 commands,
493# but hopefully no one will ever try that many at once.
494#
495# $@ - The commands to execute, one per arg.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400496sudo_multi() {
Mike Frysinger286b5922011-09-28 11:59:53 -0400497 local i cmds
498
499 # Construct the shell code to execute. It'll be of the form:
500 # ... && ( ( command ) || exit <command index> ) && ...
501 # This way we know which command exited. The exit status of
502 # the underlying command is lost, but we never cared about it
503 # in the first place (other than it is non zero), so oh well.
504 for (( i = 1; i <= $#; ++i )); do
505 cmds+=" && ( ( ${!i} ) || exit $(( i + 10 )) )"
506 done
507
508 # Execute our constructed shell code.
509 sudo -- sh -c ":${cmds[*]}" && i=0 || i=$?
510
511 # See if this failed, and if so, print out the failing command.
512 if [[ $i -gt 10 ]]; then
513 : $(( i -= 10 ))
514 die "sudo_multi failed: ${!i}"
515 elif [[ $i -ne 0 ]]; then
516 die "sudo_multi failed for unknown reason $i"
517 fi
518}
519
Mike Frysinger1aa61242011-09-15 17:46:44 -0400520# Locate all mounts below a specified directory.
521#
522# $1 - The root tree.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400523sub_mounts() {
Mike Frysinger1aa61242011-09-15 17:46:44 -0400524 # Assume that `mount` outputs a list of mount points in the order
525 # that things were mounted (since it always has and hopefully always
526 # will). As such, we have to unmount in reverse order to cleanly
527 # unmount submounts (think /dev/pts and /dev).
Zdenek Behan1d5d3b52012-05-01 01:58:48 +0200528 awk -v path="$1" -v len="${#1}" \
529 '(substr($2, 1, len) == path) { print $2 }' /proc/mounts | \
Mike Frysinger1aa61242011-09-15 17:46:44 -0400530 tac
531}
532
robotboy98912212010-04-12 14:08:14 -0700533# Unmounts a directory, if the unmount fails, warn, and then lazily unmount.
534#
535# $1 - The path to unmount.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400536safe_umount_tree() {
Mike Frysinger1aa61242011-09-15 17:46:44 -0400537 local mounts=$(sub_mounts "$1")
robotboy98912212010-04-12 14:08:14 -0700538
Mike Frysingere8aec372011-09-21 00:03:22 -0400539 # Hmm, this shouldn't normally happen, but anything is possible.
540 if [ -z "${mounts}" ] ; then
541 return 0
542 fi
543
Mike Frysinger1aa61242011-09-15 17:46:44 -0400544 # First try to unmount in one shot to speed things up.
545 if sudo umount -d ${mounts}; then
546 return 0
547 fi
robotboy98912212010-04-12 14:08:14 -0700548
Mike Frysinger1aa61242011-09-15 17:46:44 -0400549 # Well that didn't work, so lazy unmount remaining ones.
550 mounts=$(sub_mounts "$1")
551 warn "Failed to unmount ${mounts}"
552 warn "Doing a lazy unmount"
553 if ! sudo umount -d -l ${mounts}; then
554 mounts=$(sub_mounts "$1")
555 die "Failed to lazily unmount ${mounts}"
robotboy98912212010-04-12 14:08:14 -0700556 fi
557}
Chris Sosa702618f2010-05-14 12:52:32 -0700558
Matt Tennant298f61a2012-06-25 21:54:33 -0700559get_git_id() {
560 git var GIT_COMMITTER_IDENT | sed -e 's/^.*<\(\S\+\)>.*$/\1/'
561}
562
Chris Sosad4455022010-05-20 10:14:06 -0700563# Fixes symlinks that are incorrectly prefixed with the build root ${1}
564# rather than the real running root '/'.
565# TODO(sosa) - Merge setup - cleanup below with this method.
566fix_broken_symlinks() {
567 local build_root="${1}"
568 local symlinks=$(find "${build_root}/usr/local" -lname "${build_root}/*")
Greg Spencer798d75f2011-02-01 22:04:49 -0800569 local symlink
Chris Sosad4455022010-05-20 10:14:06 -0700570 for symlink in ${symlinks}; do
571 echo "Fixing ${symlink}"
572 local target=$(ls -l "${symlink}" | cut -f 2 -d '>')
573 # Trim spaces from target (bashism).
574 target=${target/ /}
575 # Make new target (removes rootfs prefix).
576 new_target=$(echo ${target} | sed "s#${build_root}##")
577
578 echo "Fixing symlink ${symlink}"
579 sudo unlink "${symlink}"
580 sudo ln -sf "${new_target}" "${symlink}"
581 done
582}
583
Chris Sosa702618f2010-05-14 12:52:32 -0700584# Sets up symlinks for the developer root. It is necessary to symlink
585# usr and local since the developer root is mounted at /usr/local and
586# applications expect to be installed under /usr/local/bin, etc.
587# This avoids packages installing into /usr/local/usr/local/bin.
588# ${1} specifies the symlink target for the developer root.
589# ${2} specifies the symlink target for the var directory.
590# ${3} specifies the location of the stateful partition.
591setup_symlinks_on_root() {
592 # Give args better names.
593 local dev_image_target=${1}
594 local var_target=${2}
595 local dev_image_root="${3}/dev_image"
596
597 # If our var target is actually the standard var, we are cleaning up the
598 # symlinks (could also check for /usr/local for the dev_image_target).
599 if [ ${var_target} = "/var" ]; then
600 echo "Cleaning up /usr/local symlinks for ${dev_image_root}"
601 else
602 echo "Setting up symlinks for /usr/local for ${dev_image_root}"
603 fi
604
605 # Set up symlinks that should point to ${dev_image_target}.
Greg Spencer798d75f2011-02-01 22:04:49 -0800606 local path
Chris Sosa702618f2010-05-14 12:52:32 -0700607 for path in usr local; do
608 if [ -h "${dev_image_root}/${path}" ]; then
609 sudo unlink "${dev_image_root}/${path}"
610 elif [ -e "${dev_image_root}/${path}" ]; then
611 die "${dev_image_root}/${path} should be a symlink if exists"
612 fi
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400613 sudo ln -s "${dev_image_target}" "${dev_image_root}/${path}"
Chris Sosa702618f2010-05-14 12:52:32 -0700614 done
615
616 # Setup var symlink.
617 if [ -h "${dev_image_root}/var" ]; then
618 sudo unlink "${dev_image_root}/var"
619 elif [ -e "${dev_image_root}/var" ]; then
620 die "${dev_image_root}/var should be a symlink if it exists"
621 fi
622
623 sudo ln -s "${var_target}" "${dev_image_root}/var"
624}
Nick Sandersd2509272010-06-16 03:50:04 -0700625
Will Drewry55b42c92010-10-20 15:44:11 -0500626# These two helpers clobber the ro compat value in our root filesystem.
627#
628# When the system is built with --enable_rootfs_verification, bit-precise
629# integrity checking is performed. That precision poses a usability issue on
630# systems that automount partitions with recognizable filesystems, such as
631# ext2/3/4. When the filesystem is mounted 'rw', ext2 metadata will be
632# automatically updated even if no other writes are performed to the
633# filesystem. In addition, ext2+ does not support a "read-only" flag for a
634# given filesystem. That said, forward and backward compatibility of
635# filesystem features are supported by tracking if a new feature breaks r/w or
636# just write compatibility. We abuse the read-only compatibility flag[1] in
637# the filesystem header by setting the high order byte (le) to FF. This tells
638# the kernel that features R24-R31 are all enabled. Since those features are
639# undefined on all ext-based filesystem, all standard kernels will refuse to
640# mount the filesystem as read-write -- only read-only[2].
641#
642# [1] 32-bit flag we are modifying:
643# http://git.chromium.org/cgi-bin/gitweb.cgi?p=kernel.git;a=blob;f=include/linux/ext2_fs.h#l417
644# [2] Mount behavior is enforced here:
645# http://git.chromium.org/cgi-bin/gitweb.cgi?p=kernel.git;a=blob;f=fs/ext2/super.c#l857
646#
647# N.B., if the high order feature bits are used in the future, we will need to
648# revisit this technique.
649disable_rw_mount() {
650 local rootfs="$1"
651 local offset="${2-0}" # in bytes
Will Drewry9b7cb512010-10-20 18:11:24 -0500652 local ro_compat_offset=$((0x464 + 3)) # Set 'highest' byte
653 printf '\377' |
Will Drewry55b42c92010-10-20 15:44:11 -0500654 sudo dd of="$rootfs" seek=$((offset + ro_compat_offset)) \
655 conv=notrunc count=1 bs=1
656}
657
658enable_rw_mount() {
659 local rootfs="$1"
660 local offset="${2-0}"
Will Drewry9b7cb512010-10-20 18:11:24 -0500661 local ro_compat_offset=$((0x464 + 3)) # Set 'highest' byte
662 printf '\000' |
Will Drewry55b42c92010-10-20 15:44:11 -0500663 sudo dd of="$rootfs" seek=$((offset + ro_compat_offset)) \
664 conv=notrunc count=1 bs=1
665}
666
Nick Sandersd2509272010-06-16 03:50:04 -0700667# Get current timestamp. Assumes common.sh runs at startup.
668start_time=$(date +%s)
669
Matt Tennant298f61a2012-06-25 21:54:33 -0700670# Get time elapsed since start_time in seconds.
671get_elapsed_seconds() {
Greg Spencer798d75f2011-02-01 22:04:49 -0800672 local end_time=$(date +%s)
673 local elapsed_seconds=$(($end_time - $start_time))
Matt Tennant298f61a2012-06-25 21:54:33 -0700674 echo ${elapsed_seconds}
675}
676
677# Print time elapsed since start_time.
678print_time_elapsed() {
679 # Optional first arg to specify elapsed_seconds. If not given, will
680 # recalculate elapsed time to now. Optional second arg to specify
681 # command name associated with elapsed time.
682 local elapsed_seconds=${1:-$(get_elapsed_seconds)}
683 local cmd_base=${2:-}
684
Greg Spencer798d75f2011-02-01 22:04:49 -0800685 local minutes=$(($elapsed_seconds / 60))
686 local seconds=$(($elapsed_seconds % 60))
Matt Tennant298f61a2012-06-25 21:54:33 -0700687
688 if [ -n "${cmd_base}" ]; then
689 info "Elapsed time (${cmd_base}): ${minutes}m${seconds}s"
690 else
691 info "Elapsed time: ${minutes}m${seconds}s"
692 fi
693}
694
695# Associative array for filling in extra command-specific stats before
696# calling command_completed.
697declare -A EXTRA_COMMAND_STATS
698
699# Save original command line.
700command_line_arr=( "$0" "$@" )
701
702command_completed() {
703 # Call print_elapsed_time regardless.
704 local run_time=$(get_elapsed_seconds)
705 local cmd_base=$(basename "${command_line_arr[0]}")
706 print_time_elapsed ${run_time} ${cmd_base}
707
708 # Prepare command stats in an associative array. Additonal command-specific
709 # stats can be added through EXTRA_COMMAND_STATS associative array.
710 declare -A stats
711 stats=(
712 [cmd_line]=${command_line_arr[*]}
713 [cmd_base]=${cmd_base}
714 [cmd_args]=${command_line_arr[*]:1}
715 [run_time]=${run_time}
716 [username]=$(get_git_id)
717 [board]=${FLAGS_board}
718 [host]=$(hostname -f)
719 [cpu_count]=$(grep -c processor /proc/cpuinfo)
720 [cpu_type]=$(uname -p)
721 )
722
723 local attr
724 for attr in "${!EXTRA_COMMAND_STATS[@]}"; do
725 stats[${attr}]=${EXTRA_COMMAND_STATS[${attr}]}
726 done
727
728 # Prepare temporary file for stats.
729 local tmpfile=$(mktemp -t tmp.stats.XXXXXX)
730 trap "rm -f '${tmpfile}'" EXIT
731
732 # Write stats out to temporary file.
733 echo "Chromium OS Build Command Stats - Version 1" > "${tmpfile}"
734 for attr in "${!stats[@]}"; do
735 echo "${attr} ${stats[${attr}]}"
736 done >> "${tmpfile}"
737
738 # Call upload_command_stats on the stats file. If it fails do not stop.
739 "${GCLIENT_ROOT}"/chromite/bin/upload_command_stats "${tmpfile}" || true
740
741 rm "${tmpfile}"
742 trap - EXIT
Nick Sandersd2509272010-06-16 03:50:04 -0700743}
Doug Anderson0c9e88d2010-10-19 14:49:39 -0700744
Anton Staaf9bcd8412011-01-24 15:27:14 -0800745# The board and variant command line options can be used in a number of ways
746# to specify the board and variant. The board can encode both pieces of
747# information separated by underscores. Or the variant can be passed using
748# the separate variant option. This function extracts the canonical board and
749# variant information and provides it in the BOARD, VARIANT and BOARD_VARIANT
750# variables.
751get_board_and_variant() {
752 local flags_board="${1}"
753 local flags_variant="${2}"
754
755 BOARD=$(echo "$flags_board" | cut -d '_' -f 1)
756 VARIANT=${flags_variant:-$(echo "$flags_board" | cut -s -d '_' -f 2)}
757
758 if [ -n "$VARIANT" ]; then
759 BOARD_VARIANT="${BOARD}_${VARIANT}"
760 else
761 BOARD_VARIANT="${BOARD}"
762 fi
763}
Simon Glass142ca062011-02-09 13:39:43 -0800764
765# This function converts a chromiumos image into a test image, either
766# in place or by copying to a new test image filename first. It honors
767# the following flags (see mod_image_for_test.sh)
768#
769# --factory
770# --factory_install
771# --force_copy
772#
773# On entry, pass the directory containing the image, and the image filename
774# On exit, it puts the pathname of the resulting test image into
775# CHROMEOS_RETURN_VAL
776# (yes this is ugly, but perhaps less ugly than the alternatives)
777#
778# Usage:
779# SRC_IMAGE=$(prepare_test_image "directory" "imagefile")
780prepare_test_image() {
781 # If we're asked to modify the image for test, then let's make a copy and
782 # modify that instead.
783 # Check for manufacturing image.
784 local args
785
786 if [ ${FLAGS_factory} -eq ${FLAGS_TRUE} ]; then
787 args="--factory"
788 fi
789
790 # Check for install shim.
791 if [ ${FLAGS_factory_install} -eq ${FLAGS_TRUE} ]; then
792 args="--factory_install"
793 fi
794
795 # Check for forcing copy of image
796 if [ ${FLAGS_force_copy} -eq ${FLAGS_TRUE} ]; then
797 args="${args} --force_copy"
798 fi
799
800 # Modify the image for test, creating a new test image
801 "${SCRIPTS_DIR}/mod_image_for_test.sh" --board=${FLAGS_board} \
802 --image="$1/$2" --noinplace ${args}
803
804 # From now on we use the just-created test image
Simon Glass6e448ae2011-03-03 11:20:54 -0800805 if [ ${FLAGS_factory} -eq ${FLAGS_TRUE} ]; then
806 CHROMEOS_RETURN_VAL="$1/${CHROMEOS_FACTORY_TEST_IMAGE_NAME}"
807 else
808 CHROMEOS_RETURN_VAL="$1/${CHROMEOS_TEST_IMAGE_NAME}"
809 fi
Simon Glass142ca062011-02-09 13:39:43 -0800810}
Anton Staaf6f5262d2011-03-02 09:35:54 -0800811
812# Check that the specified file exists. If the file path is empty or the file
813# doesn't exist on the filesystem generate useful error messages. Otherwise
814# show the user the name and path of the file that will be used. The padding
815# parameter can be used to tabulate multiple name:path pairs. For example:
816#
817# check_for_file "really long name" "...:" "file.foo"
818# check_for_file "short name" ".........:" "another.bar"
819#
820# Results in the following output:
821#
822# Using really long name...: file.foo
823# Using short name.........: another.bar
824#
825# If tabulation is not required then passing "" for padding generates the
826# output "Using <name> <path>"
827check_for_file() {
828 local name=$1
829 local padding=$2
830 local path=$3
831
832 if [ -z "${path}" ]; then
833 die "No ${name} file specified."
834 fi
835
836 if [ ! -e "${path}" ]; then
837 die "No ${name} file found at: ${path}"
838 else
839 info "Using ${name}${padding} ${path}"
840 fi
841}
842
843# Check that the specified tool exists. If it does not exist in the PATH
844# generate a useful error message indicating how to install the ebuild
845# that contains the required tool.
846check_for_tool() {
847 local tool=$1
848 local ebuild=$2
849
850 if ! which "${tool}" >/dev/null ; then
851 error "The ${tool} utility was not found in your path. Run the following"
852 error "command in your chroot to install it: sudo -E emerge ${ebuild}"
853 exit 1
854 fi
855}
Chris Sosafd2cdec2011-03-24 16:06:59 -0700856
857# Reinterprets path from outside the chroot for use inside.
858# Returns "" if "" given.
859# $1 - The path to reinterpret.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400860reinterpret_path_for_chroot() {
Chris Sosafd2cdec2011-03-24 16:06:59 -0700861 if [ $INSIDE_CHROOT -ne 1 ]; then
862 if [ -z "${1}" ]; then
863 echo ""
864 else
865 local path_abs_path=$(readlink -f "${1}")
866 local gclient_root_abs_path=$(readlink -f "${GCLIENT_ROOT}")
867
868 # Strip the repository root from the path.
869 local relative_path=$(echo ${path_abs_path} \
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400870 | sed "s:${gclient_root_abs_path}/::")
Chris Sosafd2cdec2011-03-24 16:06:59 -0700871
872 if [ "${relative_path}" = "${path_abs_path}" ]; then
873 die "Error reinterpreting path. Path ${1} is not within source tree."
874 fi
875
876 # Prepend the chroot repository path.
877 echo "/home/${USER}/trunk/${relative_path}"
878 fi
879 else
880 # Path is already inside the chroot :).
881 echo "${1}"
882 fi
883}
Gabe Black83d8b822011-08-01 17:50:09 -0700884
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400885emerge_custom_kernel() {
David James0ea96e42011-08-03 11:53:50 -0700886 local install_root="$1"
David Jamesdee866c2012-03-15 14:53:19 -0700887 local root=/build/${FLAGS_board}
David James0ea96e42011-08-03 11:53:50 -0700888 local tmp_pkgdir=${root}/custom-packages
889
890 # Clean up any leftover state in custom directories.
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400891 sudo rm -rf "${tmp_pkgdir}"
David James0ea96e42011-08-03 11:53:50 -0700892
893 # Update chromeos-initramfs to contain the latest binaries from the build
894 # tree. This is basically just packaging up already-built binaries from
895 # $root. We are careful not to muck with the existing prebuilts so that
896 # prebuilts can be uploaded in parallel.
897 # TODO(davidjames): Implement ABI deps so that chromeos-initramfs will be
898 # rebuilt automatically when its dependencies change.
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400899 sudo -E PKGDIR="${tmp_pkgdir}" $EMERGE_BOARD_CMD -1 \
David James0ea96e42011-08-03 11:53:50 -0700900 chromeos-base/chromeos-initramfs || die "Cannot emerge chromeos-initramfs"
901
902 # Verify all dependencies of the kernel are installed. This should be a
903 # no-op, but it's good to check in case a developer didn't run
Mike Frysinger0957a182012-03-21 23:17:14 -0400904 # build_packages. We need the expand_virtual call to workaround a bug
905 # in portage where it only installs the virtual pkg.
906 local kernel=$(portageq-${FLAGS_board} expand_virtual ${root} \
907 virtual/linux-sources)
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400908 sudo -E PKGDIR="${tmp_pkgdir}" $EMERGE_BOARD_CMD --onlydeps \
David James0ea96e42011-08-03 11:53:50 -0700909 ${kernel} || die "Cannot emerge kernel dependencies"
910
911 # Build the kernel. This uses the standard root so that we can pick up the
912 # initramfs from there. But we don't actually install the kernel to the
913 # standard root, because that'll muck up the kernel debug symbols there,
914 # which we want to upload in parallel.
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400915 sudo -E PKGDIR="${tmp_pkgdir}" $EMERGE_BOARD_CMD --buildpkgonly \
David James0ea96e42011-08-03 11:53:50 -0700916 ${kernel} || die "Cannot emerge kernel"
917
918 # Install the custom kernel to the provided install root.
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400919 sudo -E PKGDIR="${tmp_pkgdir}" $EMERGE_BOARD_CMD --usepkgonly \
David James0ea96e42011-08-03 11:53:50 -0700920 --root=${install_root} ${kernel} || die "Cannot emerge kernel to root"
921}
Brian Harringfeb04f72012-02-03 21:22:50 -0800922
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400923enable_strict_sudo() {
Brian Harringfeb04f72012-02-03 21:22:50 -0800924 if [ -z "$CROS_SUDO_KEEP_ALIVE" ]; then
925 echo "$0 was somehow invoked in a way that the sudo keep alive could"
926 echo "not be found. Failing due to this. See crosbug.com/18393."
927 exit 126
928 fi
929 function sudo {
930 `type -P sudo` -n "$@"
931 }
932}
Gilad Arnold207a7c72012-02-09 10:19:16 -0800933
Chris Wolfe21a27b72012-02-27 13:00:51 -0500934# Checks that stdin and stderr are both terminals.
935# If so, we assume that there is a live user we can interact with.
936# This check can be overridden by setting the CROS_NO_PROMPT environment
937# variable to a non-empty value.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400938is_interactive() {
Chris Wolfe21a27b72012-02-27 13:00:51 -0500939 [ -z "${CROS_NO_PROMPT}" -a -t 0 -a -t 2 ]
940}
941
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400942assert_interactive() {
Chris Wolfe21a27b72012-02-27 13:00:51 -0500943 if ! is_interactive; then
944 die "Script ${0##*/} tried to get user input on a non-interactive terminal."
945 fi
946}
947
Gilad Arnold207a7c72012-02-09 10:19:16 -0800948# Selection menu with a default option: this is similar to bash's select
949# built-in, only that in case of an empty selection it'll return the default
950# choice. Like select, it uses PS3 as the prompt.
951#
952# $1: name of variable to be assigned the selected value; it better not be of
953# the form choose_foo to avoid conflict with local variables.
954# $2: default value to return in case of an empty user entry.
955# $3: value to return in case of an invalid choice.
956# $...: options for selection.
957#
958# Usage example:
959#
960# PS3="Select one [1]: "
961# choose reply "foo" "ERROR" "foo" "bar" "foobar"
962#
963# This will present the following menu and prompt:
964#
965# 1) foo
966# 2) bar
967# 3) foobar
968# Select one [1]:
969#
970# The return value will be stored in a variable named 'reply'. If the input is
971# 1, 2 or 3, the return value will be "foo", "bar" or "foobar", respectively.
972# If it is empty (i.e. the user clicked Enter) it will be "foo". Anything else
973# will return "ERROR".
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400974choose() {
Gilad Arnold207a7c72012-02-09 10:19:16 -0800975 typeset -i choose_i=1
976
977 # Retrieve output variable name and default return value.
978 local choose_reply=$1
979 local choose_default="$2"
980 local choose_invalid="$3"
981 shift 3
982
983 # Select a return value
984 unset REPLY
985 if [ $# -gt 0 ]; then
Chris Wolfe21a27b72012-02-27 13:00:51 -0500986 assert_interactive
987
Gilad Arnold207a7c72012-02-09 10:19:16 -0800988 # Actual options provided, present a menu and prompt for a choice.
989 local choose_opt
990 for choose_opt in "$@"; do
Chris Wolfe21a27b72012-02-27 13:00:51 -0500991 echo "$choose_i) $choose_opt" >&2
Gilad Arnold207a7c72012-02-09 10:19:16 -0800992 choose_i=choose_i+1
993 done
994 read -p "$PS3"
995 fi
996 # Filter out strings containing non-digits.
997 if [ "${REPLY}" != "${REPLY%%[!0-9]*}" ]; then
998 REPLY=0
999 fi
1000 choose_i="${REPLY}"
1001
1002 if [ $choose_i -ge 1 -a $choose_i -le $# ]; then
1003 # Valid choice, return the corresponding value.
1004 eval ${choose_reply}="${!choose_i}"
1005 elif [ -z "${REPLY}" ]; then
1006 # Empty choice, return default value.
1007 eval ${choose_reply}="${choose_default}"
1008 else
1009 # Invalid choice, return corresponding value.
1010 eval ${choose_reply}="${choose_invalid}"
1011 fi
1012}
David James855afb72012-03-14 20:04:59 -07001013
1014# Display --help if requested. This is used to hide options from help
1015# that are not intended for developer use.
1016#
1017# How to use:
1018# 1) Declare the options that you want to appear in help.
1019# 2) Call this function.
1020# 3) Declare the options that you don't want to appear in help.
1021#
1022# See build_packages for example usage.
Mike Frysinger6b1abb22012-05-11 13:44:06 -04001023show_help_if_requested() {
David James855afb72012-03-14 20:04:59 -07001024 for opt in "$@"; do
1025 if [ "$opt" = "-h" ] || [ "$opt" = "--help" ]; then
1026 flags_help
1027 exit 0
1028 fi
1029 done
1030}
Brian Harring7f175a52012-03-02 05:37:00 -08001031
Mike Frysinger6b1abb22012-05-11 13:44:06 -04001032switch_to_strict_mode() {
Brian Harring7f175a52012-03-02 05:37:00 -08001033 # Set up strict execution mode; note that the trap
1034 # must follow switch_to_strict_mode, else it will have no effect.
1035 set -e
1036 trap 'die_err_trap "${BASH_COMMAND:-command unknown}" "$?"' ERR
1037 if [ $# -ne 0 ]; then
1038 set "$@"
1039 fi
1040}
1041
1042# TODO: Re-enable this once shflags is set -e safe.
1043#switch_to_strict_mode