blob: 2d670c6a267306b0a54a85313026d4c7602229f4 [file] [log] [blame]
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001#!/bin/bash
Chris Sosa2b736002012-02-12 16:16:08 -08002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
rspangler@google.comd74220d2009-10-09 20:56:14 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
rspangler@google.comd74220d2009-10-09 20:56:14 +00006# All scripts should die on error unless commands are specifically excepted
7# by prefixing with '!' or surrounded by 'set +e' / 'set -e'.
rspangler@google.comd74220d2009-10-09 20:56:14 +00008
9# The number of jobs to pass to tools that can run in parallel (such as make
10# and dpkg-buildpackage
Alex Deymo135faa12015-01-21 11:20:13 -080011if [[ -z ${NUM_JOBS:-} ]]; then
Brian Harring28bb01f2012-05-09 15:26:09 -070012 NUM_JOBS=$(grep -c "^processor" /proc/cpuinfo)
13fi
14# Ensure that any sub scripts we invoke get the max proc count.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050015export NUM_JOBS
rspangler@google.comd74220d2009-10-09 20:56:14 +000016
Greg Spencer798d75f2011-02-01 22:04:49 -080017# Make sure we have the location and name of the calling script, using
18# the current value if it is already set.
Alex Deymo7ba56be2015-02-12 14:28:06 -080019: ${SCRIPT_LOCATION:=$(dirname "$(readlink -f -- "$0")")}
20: ${SCRIPT_NAME:=$(basename -- "$0")}
rspangler@google.comd74220d2009-10-09 20:56:14 +000021
Anton Staaf30acb0b2011-01-26 16:00:20 -080022# Detect whether we're inside a chroot or not
David James47e0e8a2015-03-11 15:24:10 -070023CHROOT_VERSION_FILE=/etc/cros_chroot_version
24if [[ -e ${CHROOT_VERSION_FILE} ]]; then
Anton Staaf30acb0b2011-01-26 16:00:20 -080025 INSIDE_CHROOT=1
rspangler@google.comd74220d2009-10-09 20:56:14 +000026else
Anton Staaf30acb0b2011-01-26 16:00:20 -080027 INSIDE_CHROOT=0
rspangler@google.comd74220d2009-10-09 20:56:14 +000028fi
29
Mike Frysinger669b28b2012-02-07 18:01:00 -050030# Determine and set up variables needed for fancy color output (if supported).
31V_BOLD_RED=
32V_BOLD_GREEN=
33V_BOLD_YELLOW=
Mike Frysinger669b28b2012-02-07 18:01:00 -050034V_VIDOFF=
35
Mike Frysinger8e477cd2019-08-21 23:59:12 -040036if [[ -t 1 ]]; then
Mike Frysinger669b28b2012-02-07 18:01:00 -050037 # order matters: we want VIDOFF last so that when we trace with `set -x`,
38 # our terminal doesn't bleed colors as bash dumps the values of vars.
Mike Frysinger8e477cd2019-08-21 23:59:12 -040039 V_BOLD_RED=$'\e[1;31m'
40 V_BOLD_GREEN=$'\e[1;32m'
41 V_BOLD_YELLOW=$'\e[1;33m'
42 V_VIDOFF=$'\e[m'
Mike Frysinger669b28b2012-02-07 18:01:00 -050043fi
44
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050045# Turn on bash debug support if available for backtraces.
46shopt -s extdebug 2>/dev/null
Brian Harring7f175a52012-03-02 05:37:00 -080047
Marc Herbertff9fa312015-01-16 17:18:53 -080048# Output a backtrace. Optional parameter allows hiding the last
49# frame(s) so functions like "die()" can hide their additional
50# frame(s) if they wish.
Mike Frysingerbbec7112019-08-22 00:44:29 -040051_dump_trace() {
Marc Herbertff9fa312015-01-16 17:18:53 -080052 # Default = 0 hidden frames: show everything except dump_trace
53 # frame itself.
54 local hidden_frames=${1:-0}
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050055 local j n p func src line args
56 p=${#BASH_ARGV[@]}
Marc Herbertff9fa312015-01-16 17:18:53 -080057
Marc Herbertf51cf8f2015-01-20 13:56:00 -080058 error "$(date)"
Marc Herbertee1fcbb2015-05-28 10:37:46 -070059 error "$(ps f -o pgid,ppid,pid,etime,cputime,%cpu,command)"
Marc Herbertf51cf8f2015-01-20 13:56:00 -080060
Marc Herbertff9fa312015-01-16 17:18:53 -080061 # Frame 0 is ourselves so it's always suppressed / does not count.
62 for (( n = ${#FUNCNAME[@]}; n > hidden_frames; --n )); do
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050063 func=${FUNCNAME[${n} - 1]}
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050064 line=${BASH_LINENO[${n} - 1]}
65 args=
66 if [[ -z ${BASH_ARGC[${n} -1]} ]]; then
67 args='(args unknown, no debug available)'
Brian Harring7f175a52012-03-02 05:37:00 -080068 else
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050069 for (( j = 0; j < ${BASH_ARGC[${n} -1]}; ++j )); do
70 args="${args:+${args} }'${BASH_ARGV[$(( p - j - 1 ))]}'"
71 done
72 ! (( p -= ${BASH_ARGC[${n} - 1]} ))
Brian Harring7f175a52012-03-02 05:37:00 -080073 fi
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050074 if [[ ${n} == ${#FUNCNAME[@]} ]]; then
Marc Herbertee1fcbb2015-05-28 10:37:46 -070075 error "Arguments of $$: ${0##/*} ${args}"
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050076 error "Backtrace: (most recent call is last)"
77 else
Marc Herbert2e8c5902015-01-15 20:17:31 -080078 src=${BASH_SOURCE[${n}]##*/}
Marc Herbertfa6cbe72015-01-20 14:09:09 -080079 curr_func=${FUNCNAME[${n}]}
80 error "$(printf ' %s:%s:%s(), called: %s %s ' \
81 "${src}" "${line}" "${curr_func}" "${func}" "${args}")"
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050082 fi
83 done
84}
Brian Harring7f175a52012-03-02 05:37:00 -080085
Mike Frysinger669b28b2012-02-07 18:01:00 -050086# Declare these asap so that code below can safely assume they exist.
Mike Frysinger6b1abb22012-05-11 13:44:06 -040087_message() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050088 local prefix=$1
Brian Harring7f175a52012-03-02 05:37:00 -080089 shift
Mike Frysingerbaae8eb2013-01-15 01:34:26 -050090 if [[ $# -eq 0 ]]; then
91 echo -e "${prefix}${CROS_LOG_PREFIX:-""}:${V_VIDOFF}" >&2
Brian Harring7f175a52012-03-02 05:37:00 -080092 return
93 fi
94 (
95 # Handle newlines in the message, prefixing each chunk correctly.
96 # Do this in a subshell to avoid having to track IFS/set -f state.
97 IFS="
98"
99 set +f
100 set -- $*
101 IFS=' '
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500102 if [[ $# -eq 0 ]]; then
Brian Harring7f175a52012-03-02 05:37:00 -0800103 # Empty line was requested.
104 set -- ''
105 fi
106 for line in "$@"; do
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500107 echo -e "${prefix}${CROS_LOG_PREFIX:-}: ${line}${V_VIDOFF}" >&2
Brian Harring7f175a52012-03-02 05:37:00 -0800108 done
109 )
110}
111
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400112info() {
Brian Harring7f175a52012-03-02 05:37:00 -0800113 _message "${V_BOLD_GREEN}INFO " "$*"
Mike Frysinger669b28b2012-02-07 18:01:00 -0500114}
115
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400116warn() {
Brian Harring7f175a52012-03-02 05:37:00 -0800117 _message "${V_BOLD_YELLOW}WARNING " "$*"
Mike Frysinger669b28b2012-02-07 18:01:00 -0500118}
119
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400120error() {
Brian Harring7f175a52012-03-02 05:37:00 -0800121 _message "${V_BOLD_RED}ERROR " "$*"
Mike Frysinger669b28b2012-02-07 18:01:00 -0500122}
123
Brian Harring7f175a52012-03-02 05:37:00 -0800124
125# For all die functions, they must explicitly force set +eu;
Alex Deymof9235952015-01-15 11:15:09 -0800126# no reason to have them cause their own crash if we're in the middle
Brian Harring7f175a52012-03-02 05:37:00 -0800127# of reporting an error condition then exiting.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400128die_err_trap() {
Mike Frysinger9ebc8ce2015-04-06 13:15:01 -0400129 local result=${1:-$?}
130 local command=${2:-${BASH_COMMAND:-command unknown}}
Brian Harring7f175a52012-03-02 05:37:00 -0800131 set +e +u
132
Mike Frysinger9ebc8ce2015-04-06 13:15:01 -0400133 if [[ ${result} == "0" ]]; then
134 # Let callers simplify by setting us as an EXIT trap handler.
135 return 0
136 fi
137
Brian Harring7f175a52012-03-02 05:37:00 -0800138 # Per the message, bash misreports 127 as 1 during err trap sometimes.
139 # Note this fact to ensure users don't place too much faith in the
140 # exit code in that case.
141 set -- "Command '${command}' exited with nonzero code: ${result}"
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500142 if [[ ${result} -eq 1 ]] && [[ -z $(type -t ${command}) ]]; then
143 set -- "$@" \
144 '(Note bash sometimes misreports "command not found" as exit code 1 '\
Brian Harring7f175a52012-03-02 05:37:00 -0800145'instead of 127)'
Brian Harring7f175a52012-03-02 05:37:00 -0800146 fi
Mike Frysingerbbec7112019-08-22 00:44:29 -0400147 _dump_trace 1
Brian Harring7f175a52012-03-02 05:37:00 -0800148 error
149 error "Command failed:"
150 DIE_PREFIX=' '
151 die_notrace "$@"
152}
153
154# Exit this script due to a failure, outputting a backtrace in the process.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400155die() {
Brian Harring7f175a52012-03-02 05:37:00 -0800156 set +e +u
Mike Frysingerbbec7112019-08-22 00:44:29 -0400157 _dump_trace 1
Brian Harring7f175a52012-03-02 05:37:00 -0800158 error
159 error "Error was:"
160 DIE_PREFIX=' '
161 die_notrace "$@"
162}
163
164# Exit this script w/out a backtrace.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400165die_notrace() {
Brian Harring7f175a52012-03-02 05:37:00 -0800166 set +e +u
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500167 if [[ $# -eq 0 ]]; then
Brian Harring7f175a52012-03-02 05:37:00 -0800168 set -- '(no error message given)'
169 fi
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500170 local line
Brian Harring7f175a52012-03-02 05:37:00 -0800171 for line in "$@"; do
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500172 error "${DIE_PREFIX}${line}"
Brian Harring7f175a52012-03-02 05:37:00 -0800173 done
Mike Frysinger669b28b2012-02-07 18:01:00 -0500174 exit 1
175}
176
David Jamesbf13ea82013-05-08 14:17:25 -0700177# Check for a single string in a list of space-separated strings.
178# e.g. has "foo" "foo bar baz" is true, but has "f" "foo bar baz" is not.
179has() { [[ " ${*:2} " == *" $1 "* ]]; }
180
Brian Harring9086a3f2013-01-14 01:43:16 -0800181# Directory locations inside the dev chroot; try the new default,
182# falling back to user specific paths if the upgrade has yet to
183# happen.
184_user="${USER}"
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500185[[ ${USER} == "root" ]] && _user="${SUDO_USER}"
Brian Harring9086a3f2013-01-14 01:43:16 -0800186_CHROOT_TRUNK_DIRS=( "/home/${_user}/trunk" /mnt/host/source )
187_DEPOT_TOOLS_DIRS=( "/home/${_user}/depot_tools" /mnt/host/depot_tools )
188unset _user
189
190_process_mount_pt() {
191 # Given 4 arguments; the root path, the variable to set,
192 # the old location, and the new; finally, forcing the upgrade is doable
193 # via if a 5th arg is provided.
194 # This will then try to migrate the old to new if we can do so right now
195 # (else leaving symlinks in place w/in the new), and will set $1 to the
196 # new location.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500197 local base=${1:-/} var=$2 old=$3 new=$4 force=${5:-false}
198 local _sudo=$([[ ${USER} != "root" ]] && echo sudo)
199 local val=${new}
Mike Frysinger2d9a97d2015-02-25 01:38:56 -0500200 if ${force} || [[ -L ${base}/${new} ]] || [[ ! -e ${base}/${new} ]]; then
Brian Harring9086a3f2013-01-14 01:43:16 -0800201 # Ok, it's either a symlink or this is the first run. Upgrade if we can-
202 # specifically, if we're outside the chroot and we can rmdir the old.
203 # If we cannot rmdir the old, that's due to a mount being bound to that
204 # point (even if we can't see it, it's there)- thus fallback to adding
205 # compat links.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500206 if ${force} || ( [[ ${INSIDE_CHROOT} -eq 0 ]] && \
207 ${_sudo} rmdir "${base}/${old}" 2>/dev/null ); then
Brian Harring9086a3f2013-01-14 01:43:16 -0800208 ${_sudo} rm -f "${base}/${new}" || :
209 ${_sudo} mkdir -p "${base}/${new}" "$(dirname "${base}/${old}" )"
210 ${_sudo} ln -s "${new}" "${base}/${old}"
211 else
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500212 if [[ ! -L ${base}/${new} ]]; then
Brian Harring9086a3f2013-01-14 01:43:16 -0800213 # We can't do the upgrade right now; install compatibility links.
214 ${_sudo} mkdir -p "$(dirname "${base}/${new}")" "${base}/${old}"
215 ${_sudo} ln -s "${old}" "${base}/${new}"
216 fi
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500217 val=${old}
Brian Harring9086a3f2013-01-14 01:43:16 -0800218 fi
219 fi
220 eval "${var}=\"${val}\""
221}
222
223set_chroot_trunk_dir() {
224 # This takes two optional arguments; the first being the path to the chroot
225 # base; this is only used by enter_chroot. The second argument is whether
226 # or not to force the new pathways; this is only used by make_chroot. Passing
227 # a non-null value for $2 forces the new paths.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500228 if [[ ${INSIDE_CHROOT} -eq 0 ]] && [[ -z ${1-} ]]; then
Brian Harring9086a3f2013-01-14 01:43:16 -0800229 # Can't do the upgrade, thus skip trying to do so.
230 CHROOT_TRUNK_DIR="${_CHROOT_TRUNK_DIRS[1]}"
231 DEPOT_TOOLS_DIR="${_DEPOT_TOOLS_DIRS[1]}"
232 return
233 fi
Alex Deymo76277de2015-01-22 11:02:13 -0800234 _process_mount_pt "${1:-}" CHROOT_TRUNK_DIR "${_CHROOT_TRUNK_DIRS[@]}" \
235 ${2:+true}
236 _process_mount_pt "${1:-}" DEPOT_TOOLS_DIR "${_DEPOT_TOOLS_DIRS[@]}" \
237 ${2:+true}
Brian Harring9086a3f2013-01-14 01:43:16 -0800238}
239
240set_chroot_trunk_dir
241
Anton Staaf30acb0b2011-01-26 16:00:20 -0800242# Construct a list of possible locations for the source tree. This list is
243# based on various environment variables and globals that may have been set
244# by the calling script.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400245get_gclient_root_list() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500246 if [[ ${INSIDE_CHROOT} -eq 1 ]]; then
Brian Harring2499bfb2012-12-18 16:23:31 -0800247 echo "${CHROOT_TRUNK_DIR}"
Anton Staaf30acb0b2011-01-26 16:00:20 -0800248 fi
249
Alex Deymo135faa12015-01-21 11:20:13 -0800250 if [[ -n ${COMMON_SH:-} ]]; then echo "$(dirname "${COMMON_SH}")/../.."; fi
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500251 if [[ -n ${BASH_SOURCE} ]]; then echo "$(dirname "${BASH_SOURCE}")/../.."; fi
Anton Staaf30acb0b2011-01-26 16:00:20 -0800252}
253
254# Based on the list of possible source locations we set GCLIENT_ROOT if it is
255# not already defined by looking for a src directory in each seach path
256# location. If we do not find a valid looking root we error out.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400257get_gclient_root() {
Alex Deymo135faa12015-01-21 11:20:13 -0800258 if [[ -n ${GCLIENT_ROOT:-} ]]; then
Anton Staaf30acb0b2011-01-26 16:00:20 -0800259 return
260 fi
261
262 for path in $(get_gclient_root_list); do
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500263 if [[ -d ${path}/src ]]; then
Anton Staaf30acb0b2011-01-26 16:00:20 -0800264 GCLIENT_ROOT=${path}
265 break
266 fi
267 done
268
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500269 if [[ -z ${GCLIENT_ROOT} ]]; then
Anton Staaf30acb0b2011-01-26 16:00:20 -0800270 # Using dash or sh, we don't know where we are. $0 refers to the calling
271 # script, not ourselves, so that doesn't help us.
272 echo "Unable to determine location for common.sh. If you are sourcing"
273 echo "common.sh from a script run via dash or sh, you must do it in the"
274 echo "following way:"
275 echo ' COMMON_SH="$(dirname "$0")/../../scripts/common.sh"'
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500276 echo ' . "${COMMON_SH}"'
Anton Staaf30acb0b2011-01-26 16:00:20 -0800277 echo "where the first line is the relative path from your script to"
278 echo "common.sh."
279 exit 1
280 fi
281}
282
David James76764882012-10-24 19:46:29 -0700283# Populate the ENVIRONMENT_WHITELIST array.
284load_environment_whitelist() {
285 set -f
286 ENVIRONMENT_WHITELIST=(
287 $("${GCLIENT_ROOT}/chromite/scripts/cros_env_whitelist")
288 )
289 set +f
290}
291
Anton Staaf30acb0b2011-01-26 16:00:20 -0800292# Find root of source tree
293get_gclient_root
294
rspangler@google.comd74220d2009-10-09 20:56:14 +0000295# Canonicalize the directories for the root dir and the calling script.
296# readlink is part of coreutils and should be present even in a bare chroot.
tedbo4f44d9e2010-01-08 17:26:11 -0800297# This is better than just using
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500298# FOO="$(cd ${FOO} ; pwd)"
tedbo4f44d9e2010-01-08 17:26:11 -0800299# since that leaves symbolic links intact.
rspangler@google.comd74220d2009-10-09 20:56:14 +0000300# Note that 'realpath' is equivalent to 'readlink -f'.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500301SCRIPT_LOCATION=$(readlink -f "${SCRIPT_LOCATION}")
302GCLIENT_ROOT=$(readlink -f "${GCLIENT_ROOT}")
rspangler@google.comd74220d2009-10-09 20:56:14 +0000303
304# Other directories should always be pathed down from GCLIENT_ROOT.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500305SRC_ROOT="${GCLIENT_ROOT}/src"
306SRC_INTERNAL="${GCLIENT_ROOT}/src-internal"
307SCRIPTS_DIR="${SRC_ROOT}/scripts"
308BUILD_LIBRARY_DIR="${SCRIPTS_DIR}/build_library"
Mike Frysinger66accd22017-09-13 03:50:30 -0400309CHROMITE_BIN="${GCLIENT_ROOT}/chromite/bin"
Alex Klein999443c2018-10-17 12:02:05 -0600310IMAGES_DIR="${GCLIENT_ROOT}/src/build/images"
rspangler@google.comd74220d2009-10-09 20:56:14 +0000311
312# Load developer's custom settings. Default location is in scripts dir,
313# since that's available both inside and outside the chroot. By convention,
314# settings from this file are variables starting with 'CHROMEOS_'
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500315: ${CHROMEOS_DEV_SETTINGS:=${SCRIPTS_DIR}/.chromeos_dev}
316if [[ -f ${CHROMEOS_DEV_SETTINGS} ]]; then
rspangler@google.comd74220d2009-10-09 20:56:14 +0000317 # Turn on exit-on-error during custom settings processing
Greg Spencer798d75f2011-02-01 22:04:49 -0800318 SAVE_OPTS=$(set +o)
Brian Harring7f175a52012-03-02 05:37:00 -0800319 switch_to_strict_mode
rspangler@google.comd74220d2009-10-09 20:56:14 +0000320
321 # Read settings
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500322 . "${CHROMEOS_DEV_SETTINGS}"
rspangler@google.comd74220d2009-10-09 20:56:14 +0000323
324 # Restore previous state of exit-on-error
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500325 eval "${SAVE_OPTS}"
rspangler@google.comd74220d2009-10-09 20:56:14 +0000326fi
327
328# Load shflags
Zdenek Behan07d24222011-11-02 00:46:25 +0000329# NOTE: This code snippet is in particular used by the au-generator (which
330# stores shflags in ./lib/shflags/) and should not be touched.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500331if [[ -f ${SCRIPTS_DIR}/lib/shflags/shflags ]]; then
Mike Frysinger77c674b2012-02-07 18:05:07 -0500332 . "${SCRIPTS_DIR}/lib/shflags/shflags" || die "Couldn't find shflags"
Zdenek Behan07d24222011-11-02 00:46:25 +0000333else
334 . ./lib/shflags/shflags || die "Couldn't find shflags"
335fi
rspangler@google.comd74220d2009-10-09 20:56:14 +0000336
Bill Richardson10d27c22010-01-20 13:38:50 -0800337# Our local mirror
338DEFAULT_CHROMEOS_SERVER=${CHROMEOS_SERVER:-"http://build.chromium.org/mirror"}
rspangler@google.comd74220d2009-10-09 20:56:14 +0000339
Bill Richardson10d27c22010-01-20 13:38:50 -0800340# Upstream mirrors and build suites come in 2 flavors
341# DEV - development chroot, used to build the chromeos image
342# IMG - bootable image, to run on actual hardware
rspangler@google.comd74220d2009-10-09 20:56:14 +0000343
Bill Richardson10d27c22010-01-20 13:38:50 -0800344DEFAULT_DEV_MIRROR=${CHROMEOS_DEV_MIRROR:-"${DEFAULT_CHROMEOS_SERVER}/ubuntu"}
345DEFAULT_DEV_SUITE=${CHROMEOS_DEV_SUITE:-"karmic"}
346
347DEFAULT_IMG_MIRROR=${CHROMEOS_IMG_MIRROR:-"${DEFAULT_CHROMEOS_SERVER}/ubuntu"}
348DEFAULT_IMG_SUITE=${CHROMEOS_IMG_SUITE:-"karmic"}
rspangler@google.comd74220d2009-10-09 20:56:14 +0000349
350# Default location for chroot
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500351DEFAULT_CHROOT_DIR=${CHROMEOS_CHROOT_DIR:-"${GCLIENT_ROOT}/chroot"}
rspangler@google.comd74220d2009-10-09 20:56:14 +0000352
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500353# All output files from build should go under ${DEFAULT_BUILD_ROOT}, so that
rspangler@google.comd74220d2009-10-09 20:56:14 +0000354# they don't pollute the source directory.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500355DEFAULT_BUILD_ROOT=${CHROMEOS_BUILD_ROOT:-"${SRC_ROOT}/build"}
rspangler@google.comd74220d2009-10-09 20:56:14 +0000356
Chris Ching4bc95a12016-11-22 13:44:13 -0700357# Default location for event files
358DEFAULT_EVENT_DIR=${DEFAULT_EVENT_DIR:-"${DEFAULT_BUILD_ROOT}/events"}
359
360# Default event file. Format is YYYYDD.HHMM.json
361DEFAULT_EVENT_FILE=${DEFAULT_EVENT_FILE:-"${DEFAULT_EVENT_DIR}/$(date +%Y%m%d.%H%M.).json"}
362
Mike Frysingerc17a4932012-03-12 17:07:40 -0400363# Sets the default board variable for calling script.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500364if [[ -f ${GCLIENT_ROOT}/src/scripts/.default_board ]]; then
365 DEFAULT_BOARD=$(<"${GCLIENT_ROOT}/src/scripts/.default_board")
Mike Frysingerc17a4932012-03-12 17:07:40 -0400366 # Check for user typos like whitespace.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500367 if [[ -n ${DEFAULT_BOARD//[a-zA-Z0-9-_]} ]]; then
Mike Frysingerc17a4932012-03-12 17:07:40 -0400368 die ".default_board: invalid name detected; please fix:" \
369 "'${DEFAULT_BOARD}'"
370 fi
371fi
372# Stub to get people to upgrade.
373get_default_board() {
374 warn "please upgrade your script, and make sure to run build_packages"
375}
David McMahon49302942010-02-18 16:55:35 -0800376
David Jamesff072012010-11-30 13:22:05 -0800377# Enable --fast by default.
Greg Spencer798d75f2011-02-01 22:04:49 -0800378DEFAULT_FAST=${FLAGS_TRUE}
David James03668642010-07-28 17:08:29 -0700379
Chris Sosab0f57322011-10-25 03:07:23 +0000380# Directory to store built images. Should be set by sourcing script when used.
381BUILD_DIR=
Simon Glass142ca062011-02-09 13:39:43 -0800382
Mike Frysinger34808e52017-01-11 21:14:08 -0500383# Path to the verified boot directory where we get signing related keys/scripts.
384VBOOT_DIR="${CHROOT_TRUNK_DIR}/src/platform/vboot_reference"
385VBOOT_TESTKEYS_DIR="${VBOOT_DIR}/tests/testkeys"
Mike Frysinger40cea032017-03-12 19:48:20 -0400386# We load these from the chroot rather than directly from the vboot source repo
387# so we work correctly even in a minilayout.
388VBOOT_DEVKEYS_DIR="/usr/share/vboot/devkeys"
389VBOOT_SIGNING_DIR="/usr/share/vboot/bin"
Mike Frysinger34808e52017-01-11 21:14:08 -0500390
Simon Glass142ca062011-02-09 13:39:43 -0800391# Standard filenames
Chris Sosab0f57322011-10-25 03:07:23 +0000392CHROMEOS_BASE_IMAGE_NAME="chromiumos_base_image.bin"
Simon Glass142ca062011-02-09 13:39:43 -0800393CHROMEOS_IMAGE_NAME="chromiumos_image.bin"
Chris Sosab0f57322011-10-25 03:07:23 +0000394CHROMEOS_DEVELOPER_IMAGE_NAME="chromiumos_image.bin"
Gilad Arnold08366272012-02-08 10:46:26 -0800395CHROMEOS_RECOVERY_IMAGE_NAME="recovery_image.bin"
Simon Glass142ca062011-02-09 13:39:43 -0800396CHROMEOS_TEST_IMAGE_NAME="chromiumos_test_image.bin"
Chris Sosab0f57322011-10-25 03:07:23 +0000397CHROMEOS_FACTORY_INSTALL_SHIM_NAME="factory_install_shim.bin"
Bertrand SIMONNETb17cd572015-04-01 10:27:37 -0700398SYSROOT_SETTINGS_FILE="/var/cache/edb/chromeos"
Simon Glass142ca062011-02-09 13:39:43 -0800399
Rahul Chaudhry306f6882015-05-13 15:14:13 -0700400# Install mask for portage ebuilds. Used by build_image and gmergefs.
Chris Masoned11ce172010-11-09 14:22:08 -0800401# TODO: Is /usr/local/autotest-chrome still used by anyone?
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800402COMMON_INSTALL_MASK="
Daniel Erate82f07c2010-12-21 13:39:22 -0800403 *.a
Alex Deymo1856c4f2014-09-24 08:15:34 -0700404 *.c
405 *.cc
Rahul Chaudhry306f6882015-05-13 15:14:13 -0700406 *.go
Daniel Erate82f07c2010-12-21 13:39:22 -0800407 *.la
Rene Bolldorf32228222012-07-21 14:18:22 -0400408 *.h
Brian Norrisef0880d2016-05-19 12:39:56 -0700409 *.hh
Rene Bolldorf32228222012-07-21 14:18:22 -0400410 *.hpp
Kevin Cernekee6ab57a92015-06-25 15:43:06 -0700411 *.h++
Nam T. Nguyenaa15f142015-05-15 14:27:50 -0700412 *.hxx
Mike Frysinger97c6ac92014-06-16 00:06:37 -0400413 */.keep*
Shuhei Takahashic62d3072019-01-29 18:04:35 +0900414 /build/libexec/tast
415 /build/share/tast
Daniel Erate82f07c2010-12-21 13:39:22 -0800416 /etc/init.d
417 /etc/runlevels
Qijiang Fan6834cba2018-04-04 16:41:56 +0900418 /etc/selinux/intermediates
Hung-Te Lin76272be2012-08-07 19:10:09 +0800419 /firmware
Mike Frysinger785f09d2013-09-25 22:11:21 -0400420 /lib/modules/*/vdso
Daniel Erate82f07c2010-12-21 13:39:22 -0800421 /lib/rc
Tomasz Figa435f0e52017-01-06 14:28:06 +0900422 /opt/google/containers/android/vendor/lib*/pkgconfig
Benjamin Gordonffcb2b12017-10-24 13:02:46 -0600423 /opt/google/containers/android/build
Nam T. Nguyenf1de1a72015-05-27 08:37:46 -0700424 /usr/bin/*-config
Daniel Erate82f07c2010-12-21 13:39:22 -0800425 /usr/bin/Xnest
426 /usr/bin/Xvfb
Manoj Gupta019843b2017-08-17 13:28:18 -0700427 /usr/include/c++
Mike Frysinger10c56472013-03-01 00:58:10 -0500428 /usr/include/nspr/*
Yunlian Jianged7cd2d2018-10-27 13:07:02 -0700429 /usr/include/rpcsvc/*.x
Bing Xue18e37582019-01-17 17:04:54 -0800430 /usr/include/tensorflow
Yufeng Wang6dea68d2019-05-13 11:52:51 -0700431 /usr/include/boost
Mike Frysinger10c56472013-03-01 00:58:10 -0500432 /usr/include/X11/*
Daniel Erate82f07c2010-12-21 13:39:22 -0800433 /usr/lib/debug
Rahul Chaudhry306f6882015-05-13 15:14:13 -0700434 /usr/lib/gopath
Mike Frysinger27b5edb2012-08-08 18:52:06 -0400435 /usr/lib*/pkgconfig
Daniel Erate82f07c2010-12-21 13:39:22 -0800436 /usr/local/autotest-chrome
437 /usr/man
438 /usr/share/aclocal
Brian Norris0f3c4e22016-06-21 12:23:18 -0700439 /usr/share/cups/drv
Daniel Erate82f07c2010-12-21 13:39:22 -0800440 /usr/share/doc
441 /usr/share/gettext
442 /usr/share/gtk-2.0
443 /usr/share/gtk-doc
444 /usr/share/info
445 /usr/share/man
Brian Norris0f3c4e22016-06-21 12:23:18 -0700446 /usr/share/ppd
Daniel Erate82f07c2010-12-21 13:39:22 -0800447 /usr/share/openrc
448 /usr/share/pkgconfig
Ryan Harrisonb8bd5942013-02-02 13:39:43 -0500449 /usr/share/profiling
Daniel Erate82f07c2010-12-21 13:39:22 -0800450 /usr/share/readline
Chris Wolfed13775f2011-07-26 16:34:38 -0400451 /usr/src
Daniel Erate82f07c2010-12-21 13:39:22 -0800452 "
Chris Sosaaa1a7fd2010-04-02 14:06:29 -0700453
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800454# Mask for base, dev, and test images (build_image, build_image --test)
455DEFAULT_INSTALL_MASK="
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500456 ${COMMON_INSTALL_MASK}
Don Garrettac1cd0d2013-07-18 18:04:06 -0700457 /boot/config-*
458 /boot/System.map-*
Aviv Kesheta1838ba2013-07-23 10:58:23 -0700459 /usr/local/build/autotest
Olof Johansson1222b2e2012-08-08 15:27:35 -0700460 /lib/modules/*/build
461 /lib/modules/*/source
Kees Cook74f163b2012-12-18 15:46:51 -0800462 test_*.ko
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800463 "
464
Chris Sosac9422fa2012-03-05 15:58:07 -0800465# Mask for factory install shim (build_image factory_install)
Hung-Te Lind32c59f2012-01-19 19:54:01 +0800466FACTORY_SHIM_INSTALL_MASK="
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500467 ${DEFAULT_INSTALL_MASK}
Cheng-Han Yangc924c2c2018-11-02 17:02:29 +0800468 /opt/google/chrome
469 /opt/google/containers
Vic Yang982556a2012-12-11 11:41:54 +0800470 /usr/lib64/dri
Hung-Te Lin7f721ec2017-07-18 15:14:48 +0800471 /usr/lib/dri
Daniel Erate82f07c2010-12-21 13:39:22 -0800472 /usr/share/X11
Hung-Te Lin7f721ec2017-07-18 15:14:48 +0800473 /usr/share/chromeos-assets/[^i]*
474 /usr/share/chromeos-assets/i[^m]*
Daniel Erate82f07c2010-12-21 13:39:22 -0800475 /usr/share/fonts
Daniel Erate82f07c2010-12-21 13:39:22 -0800476 /usr/share/locale
Daniel Erate82f07c2010-12-21 13:39:22 -0800477 /usr/share/mime
Vic Yang982556a2012-12-11 11:41:54 +0800478 /usr/share/oem
Daniel Erate82f07c2010-12-21 13:39:22 -0800479 /usr/share/sounds
480 /usr/share/tts
481 /usr/share/zoneinfo
482 "
Tom Wai-Hong Tamf87a3672010-05-17 16:06:33 +0800483
Sabin Floarese790ea72016-11-21 14:56:41 +0200484# Mask for images without systemd.
485SYSTEMD_INSTALL_MASK="
Chris Morin83226ab2018-12-07 19:53:48 -0800486 /lib/systemd/network
487 /usr/lib/systemd/system
Sabin Floarese790ea72016-11-21 14:56:41 +0200488"
489
rspangler@google.comd74220d2009-10-09 20:56:14 +0000490# -----------------------------------------------------------------------------
491# Functions
492
Don Garrett640a0582010-05-04 16:54:28 -0700493# Enter a chroot and restart the current script if needed
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400494restart_in_chroot_if_needed() {
David Rochberg3b910702010-12-02 10:45:21 -0500495 # NB: Pass in ARGV: restart_in_chroot_if_needed "$@"
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500496 if [[ ${INSIDE_CHROOT} -ne 1 ]]; then
Chris Sosafd2cdec2011-03-24 16:06:59 -0700497 # Get inside_chroot path for script.
498 local chroot_path="$(reinterpret_path_for_chroot "$0")"
Mike Frysinger66accd22017-09-13 03:50:30 -0400499 exec "${CHROMITE_BIN}/cros_sdk" -- "${chroot_path}" "$@"
Don Garrett640a0582010-05-04 16:54:28 -0700500 fi
501}
502
rspangler@google.comd74220d2009-10-09 20:56:14 +0000503# Fail unless we're inside the chroot. This guards against messing up your
504# workstation.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400505assert_inside_chroot() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500506 if [[ ${INSIDE_CHROOT} -ne 1 ]]; then
rspangler@google.comd74220d2009-10-09 20:56:14 +0000507 echo "This script must be run inside the chroot. Run this first:"
Zdenek Behan2811c162011-08-13 00:47:38 +0200508 echo " cros_sdk"
rspangler@google.comd74220d2009-10-09 20:56:14 +0000509 exit 1
510 fi
511}
512
513# Fail if we're inside the chroot. This guards against creating or entering
514# nested chroots, among other potential problems.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400515assert_outside_chroot() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500516 if [[ ${INSIDE_CHROOT} -ne 0 ]]; then
rspangler@google.comd74220d2009-10-09 20:56:14 +0000517 echo "This script must be run outside the chroot."
518 exit 1
519 fi
520}
521
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400522assert_not_root_user() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500523 if [[ ${UID:-$(id -u)} == 0 ]]; then
derat@google.com86dcc8e2009-11-21 19:49:49 +0000524 echo "This script must be run as a non-root user."
525 exit 1
526 fi
527}
528
David James76764882012-10-24 19:46:29 -0700529assert_root_user() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500530 if [[ ${UID:-$(id -u)} != 0 ]] || [[ ${SUDO_USER:-root} == "root" ]]; then
David James76764882012-10-24 19:46:29 -0700531 die_notrace "This script must be run using sudo from a non-root user."
532 fi
533}
534
tedbo373c3902010-04-12 10:52:40 -0700535# Writes stdin to the given file name as root using sudo in overwrite mode.
536#
537# $1 - The output file name.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400538sudo_clobber() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500539 sudo tee "$1" >/dev/null
tedbo373c3902010-04-12 10:52:40 -0700540}
541
542# Writes stdin to the given file name as root using sudo in append mode.
543#
544# $1 - The output file name.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400545sudo_append() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500546 sudo tee -a "$1" >/dev/null
tedbo373c3902010-04-12 10:52:40 -0700547}
robotboy98912212010-04-12 14:08:14 -0700548
Mike Frysinger286b5922011-09-28 11:59:53 -0400549# Execute multiple commands in a single sudo. Generally will speed things
550# up by avoiding multiple calls to `sudo`. If any commands fail, we will
551# call die with the failing command. We can handle a max of ~100 commands,
552# but hopefully no one will ever try that many at once.
553#
554# $@ - The commands to execute, one per arg.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400555sudo_multi() {
Mike Frysinger286b5922011-09-28 11:59:53 -0400556 local i cmds
557
558 # Construct the shell code to execute. It'll be of the form:
559 # ... && ( ( command ) || exit <command index> ) && ...
560 # This way we know which command exited. The exit status of
561 # the underlying command is lost, but we never cared about it
562 # in the first place (other than it is non zero), so oh well.
563 for (( i = 1; i <= $#; ++i )); do
564 cmds+=" && ( ( ${!i} ) || exit $(( i + 10 )) )"
565 done
566
567 # Execute our constructed shell code.
568 sudo -- sh -c ":${cmds[*]}" && i=0 || i=$?
569
570 # See if this failed, and if so, print out the failing command.
571 if [[ $i -gt 10 ]]; then
572 : $(( i -= 10 ))
573 die "sudo_multi failed: ${!i}"
574 elif [[ $i -ne 0 ]]; then
575 die "sudo_multi failed for unknown reason $i"
576 fi
577}
578
Chris Masonebbccc242014-02-08 16:23:53 -0800579# Clears out stale shadow-utils locks in the given target root.
580sudo_clear_shadow_locks() {
581 info "Clearing shadow utils lockfiles under $1"
582 sudo rm -f "$1/etc/"{passwd,group,shadow,gshadow}.lock*
583}
584
David James76764882012-10-24 19:46:29 -0700585# Writes stdin to the given file name as the sudo user in overwrite mode.
586#
587# $@ - The output file names.
588user_clobber() {
589 install -m644 -o ${SUDO_UID} -g ${SUDO_GID} /dev/stdin "$@"
590}
591
David James22dc2ba2012-11-29 15:46:58 -0800592# Copies the specified file owned by the user to the specified location.
593# If the copy fails as root (e.g. due to root_squash and NFS), retry the copy
594# with the user's account before failing.
595user_cp() {
596 cp -p "$@" 2>/dev/null || sudo -u ${SUDO_USER} -- cp -p "$@"
597}
598
David James76764882012-10-24 19:46:29 -0700599# Appends stdin to the given file name as the sudo user.
600#
601# $1 - The output file name.
602user_append() {
603 cat >> "$1"
604 chown ${SUDO_UID}:${SUDO_GID} "$1"
605}
606
607# Create the specified directory, along with parents, as the sudo user.
608#
609# $@ - The directories to create.
610user_mkdir() {
611 install -o ${SUDO_UID} -g ${SUDO_GID} -d "$@"
612}
613
614# Create the specified symlink as the sudo user.
615#
616# $1 - Link target
617# $2 - Link name
618user_symlink() {
619 ln -sfT "$1" "$2"
620 chown -h ${SUDO_UID}:${SUDO_GID} "$2"
621}
622
Mike Frysinger1aa61242011-09-15 17:46:44 -0400623# Locate all mounts below a specified directory.
624#
625# $1 - The root tree.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400626sub_mounts() {
Mike Frysinger1aa61242011-09-15 17:46:44 -0400627 # Assume that `mount` outputs a list of mount points in the order
628 # that things were mounted (since it always has and hopefully always
629 # will). As such, we have to unmount in reverse order to cleanly
630 # unmount submounts (think /dev/pts and /dev).
Alex Deymo7ba56be2015-02-12 14:28:06 -0800631 awk -v path="$1" -v len="${#1}" \
Benjamin Gordon1d5afed2017-06-14 16:35:32 -0600632 '(substr($2, 1, len+1) == path ||
633 substr($2, 1, len+1) == (path "/")) { print $2 }' /proc/mounts | \
Zdenek Behan52970f42012-08-30 22:36:40 +0200634 tac | \
635 sed -e 's/\\040(deleted)$//'
636 # Hack(zbehan): If a bind mount's source is mysteriously removed,
637 # we'd end up with an orphaned mount with the above string in its name.
638 # It can only be seen through /proc/mounts and will stick around even
639 # when it should be gone already. crosbug.com/31250
Mike Frysinger1aa61242011-09-15 17:46:44 -0400640}
641
robotboy98912212010-04-12 14:08:14 -0700642# Unmounts a directory, if the unmount fails, warn, and then lazily unmount.
643#
644# $1 - The path to unmount.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400645safe_umount_tree() {
Alex Deymo7ba56be2015-02-12 14:28:06 -0800646 local mount_point="$1"
robotboy98912212010-04-12 14:08:14 -0700647
Alex Deymo7ba56be2015-02-12 14:28:06 -0800648 local mounts=( $(sub_mounts "${mount_point}") )
649
650 # Silently return if the mount_point was already unmounted.
651 if [[ ${#mounts[@]} -eq 0 ]]; then
Mike Frysingere8aec372011-09-21 00:03:22 -0400652 return 0
653 fi
654
Mike Frysinger1aa61242011-09-15 17:46:44 -0400655 # First try to unmount in one shot to speed things up.
Chirantan Ekbote30823e92016-06-29 11:39:03 -0700656 if LC_ALL=C safe_umount -d "${mounts[@]}"; then
657 return 0
David Jamesd9b67982012-10-26 09:46:50 -0700658 fi
659
660 # Well that didn't work, so lazy unmount remaining ones.
Alex Deymo7ba56be2015-02-12 14:28:06 -0800661 warn "Failed to unmount ${mounts[@]}, these are the processes using the" \
662 "mount points."
663 sudo fuser -vm "${mount_point}" || true
664
Mike Frysinger1aa61242011-09-15 17:46:44 -0400665 warn "Doing a lazy unmount"
Alex Deymo7ba56be2015-02-12 14:28:06 -0800666 if ! safe_umount -d -l "${mounts[@]}"; then
667 mounts=( $(sub_mounts "${mount_point}") )
668 die "Failed to lazily unmount ${mounts[@]}"
robotboy98912212010-04-12 14:08:14 -0700669 fi
670}
Chris Sosa702618f2010-05-14 12:52:32 -0700671
Brian Harringece65e02012-08-30 13:42:21 -0700672
David James76764882012-10-24 19:46:29 -0700673# Run umount as root.
Brian Harringece65e02012-08-30 13:42:21 -0700674safe_umount() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500675 $([[ ${UID:-$(id -u)} != 0 ]] && echo sudo) umount "$@"
Brian Harringece65e02012-08-30 13:42:21 -0700676}
677
Gabe Black0a68b202014-10-08 22:09:10 -0700678# Run a command with sudo in a way that still preferentially uses files
679# from au-generator.zip, but still finds things in /sbin and /usr/sbin when
680# not using au-generator.zip.
681au_generator_sudo() {
682 # When searching for env, the unmodified path is used and env is potentially
683 # found somewhere out in the system. env itself sees the modified PATH
684 # and will find the command where we're telling it to. Running the command
685 # directly without env will escape our constructed PATH.
686 sudo -E PATH="${PATH}:/sbin:/usr/sbin" env "$@"
687}
688
Gabe Blackfbdb1d52014-09-22 23:43:35 -0700689# Setup a loopback device for a file and scan for partitions, with retries.
690#
691# $1 - The file to back the new loopback device.
692# $2-$N - Additional arguments to pass to losetup.
693loopback_partscan() {
694 local lb_dev image="$1"
695 shift
Gabe Black01ba4de2015-03-11 16:34:56 -0700696 lb_dev=$(au_generator_sudo losetup --show -f "$@" "${image}")
697 # Ignore problems deleting existing partitions. There shouldn't be any
698 # which will upset partx, but that's actually ok.
699 au_generator_sudo partx -d "${lb_dev}" 2>/dev/null || true
700 au_generator_sudo partx -a "${lb_dev}"
Gabe Blackfbdb1d52014-09-22 23:43:35 -0700701
Gabe Black7bb6c5a2015-03-16 20:23:06 -0700702 echo "${lb_dev}"
Gabe Blackfbdb1d52014-09-22 23:43:35 -0700703}
704
705# Detach a loopback device set up earlier.
706#
Gabe Black01ba4de2015-03-11 16:34:56 -0700707# $1 - The loop device to detach.
708# $2-$N - Additional arguments to pass to losetup.
Gabe Blackfbdb1d52014-09-22 23:43:35 -0700709loopback_detach() {
Mike Frysingeraf64ed52015-04-06 13:20:39 -0400710 # Retry the deletes before we detach. crbug.com/469259
711 local i
712 for (( i = 0; i < 10; i++ )); do
713 if au_generator_sudo partx -d "$1"; then
714 break
715 fi
716 warn "Sleeping & retrying ..."
717 sync
718 sleep 1
719 done
Gabe Black0a68b202014-10-08 22:09:10 -0700720 au_generator_sudo losetup --detach "$@"
Gabe Blackfbdb1d52014-09-22 23:43:35 -0700721}
722
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500723# Fixes symlinks that are incorrectly prefixed with the build root $1
Chris Sosad4455022010-05-20 10:14:06 -0700724# rather than the real running root '/'.
725# TODO(sosa) - Merge setup - cleanup below with this method.
726fix_broken_symlinks() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500727 local build_root=$1
Chris Sosad4455022010-05-20 10:14:06 -0700728 local symlinks=$(find "${build_root}/usr/local" -lname "${build_root}/*")
Greg Spencer798d75f2011-02-01 22:04:49 -0800729 local symlink
Chris Sosad4455022010-05-20 10:14:06 -0700730 for symlink in ${symlinks}; do
731 echo "Fixing ${symlink}"
732 local target=$(ls -l "${symlink}" | cut -f 2 -d '>')
733 # Trim spaces from target (bashism).
734 target=${target/ /}
735 # Make new target (removes rootfs prefix).
736 new_target=$(echo ${target} | sed "s#${build_root}##")
737
738 echo "Fixing symlink ${symlink}"
739 sudo unlink "${symlink}"
740 sudo ln -sf "${new_target}" "${symlink}"
741 done
742}
743
Chris Sosa702618f2010-05-14 12:52:32 -0700744# Sets up symlinks for the developer root. It is necessary to symlink
745# usr and local since the developer root is mounted at /usr/local and
746# applications expect to be installed under /usr/local/bin, etc.
747# This avoids packages installing into /usr/local/usr/local/bin.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500748# $1 specifies the symlink target for the developer root.
749# $2 specifies the symlink target for the var directory.
750# $3 specifies the location of the stateful partition.
Chris Sosa702618f2010-05-14 12:52:32 -0700751setup_symlinks_on_root() {
752 # Give args better names.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500753 local dev_image_target=$1
754 local var_target=$2
755 local dev_image_root="$3/dev_image"
Chris Sosa702618f2010-05-14 12:52:32 -0700756
Mike Frysinger9e155382019-07-12 21:11:00 -0400757 # Make sure the dev_image dir itself exists.
758 if [[ ! -d "${dev_image_root}" ]]; then
759 sudo mkdir "${dev_image_root}"
760 fi
761
Chris Sosa702618f2010-05-14 12:52:32 -0700762 # If our var target is actually the standard var, we are cleaning up the
763 # symlinks (could also check for /usr/local for the dev_image_target).
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500764 if [[ ${var_target} == "/var" ]]; then
Chris Sosa702618f2010-05-14 12:52:32 -0700765 echo "Cleaning up /usr/local symlinks for ${dev_image_root}"
766 else
767 echo "Setting up symlinks for /usr/local for ${dev_image_root}"
768 fi
769
770 # Set up symlinks that should point to ${dev_image_target}.
Greg Spencer798d75f2011-02-01 22:04:49 -0800771 local path
Chris Sosa702618f2010-05-14 12:52:32 -0700772 for path in usr local; do
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500773 if [[ -h ${dev_image_root}/${path} ]]; then
Chris Sosa702618f2010-05-14 12:52:32 -0700774 sudo unlink "${dev_image_root}/${path}"
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500775 elif [[ -e ${dev_image_root}/${path} ]]; then
Chris Sosa702618f2010-05-14 12:52:32 -0700776 die "${dev_image_root}/${path} should be a symlink if exists"
777 fi
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400778 sudo ln -s "${dev_image_target}" "${dev_image_root}/${path}"
Chris Sosa702618f2010-05-14 12:52:32 -0700779 done
780
781 # Setup var symlink.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500782 if [[ -h ${dev_image_root}/var ]]; then
Chris Sosa702618f2010-05-14 12:52:32 -0700783 sudo unlink "${dev_image_root}/var"
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500784 elif [[ -e ${dev_image_root}/var ]]; then
Chris Sosa702618f2010-05-14 12:52:32 -0700785 die "${dev_image_root}/var should be a symlink if it exists"
786 fi
787
788 sudo ln -s "${var_target}" "${dev_image_root}/var"
789}
Nick Sandersd2509272010-06-16 03:50:04 -0700790
Will Drewry55b42c92010-10-20 15:44:11 -0500791# These two helpers clobber the ro compat value in our root filesystem.
792#
793# When the system is built with --enable_rootfs_verification, bit-precise
794# integrity checking is performed. That precision poses a usability issue on
795# systems that automount partitions with recognizable filesystems, such as
796# ext2/3/4. When the filesystem is mounted 'rw', ext2 metadata will be
797# automatically updated even if no other writes are performed to the
798# filesystem. In addition, ext2+ does not support a "read-only" flag for a
799# given filesystem. That said, forward and backward compatibility of
800# filesystem features are supported by tracking if a new feature breaks r/w or
801# just write compatibility. We abuse the read-only compatibility flag[1] in
802# the filesystem header by setting the high order byte (le) to FF. This tells
803# the kernel that features R24-R31 are all enabled. Since those features are
804# undefined on all ext-based filesystem, all standard kernels will refuse to
805# mount the filesystem as read-write -- only read-only[2].
806#
807# [1] 32-bit flag we are modifying:
Aaron Gable5dde8482013-09-27 18:35:57 -0700808# https://chromium.googlesource.com/chromiumos/third_party/kernel.git/+/master/include/linux/ext2_fs.h#l417
Will Drewry55b42c92010-10-20 15:44:11 -0500809# [2] Mount behavior is enforced here:
Aaron Gable5dde8482013-09-27 18:35:57 -0700810# https://chromium.googlesource.com/chromiumos/third_party/kernel.git/+/master/ext2/super.c#l857
Will Drewry55b42c92010-10-20 15:44:11 -0500811#
812# N.B., if the high order feature bits are used in the future, we will need to
813# revisit this technique.
814disable_rw_mount() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500815 local rootfs=$1
Will Drewry55b42c92010-10-20 15:44:11 -0500816 local offset="${2-0}" # in bytes
Will Drewry9b7cb512010-10-20 18:11:24 -0500817 local ro_compat_offset=$((0x464 + 3)) # Set 'highest' byte
Alex Deymof6a527d2015-01-12 18:30:58 -0800818 is_ext_filesystem "${rootfs}" "${offset}" || return 0
Alex Deymo41226312015-03-09 15:35:24 -0700819 is_ext2_rw_mount_enabled "${rootfs}" "${offset}" || return 0
820
821 make_block_device_rw "${rootfs}"
Will Drewry9b7cb512010-10-20 18:11:24 -0500822 printf '\377' |
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500823 sudo dd of="${rootfs}" seek=$((offset + ro_compat_offset)) \
Alex Deymo41226312015-03-09 15:35:24 -0700824 conv=notrunc count=1 bs=1 status=none
LaMont Jones70743742019-04-26 10:14:33 -0600825 # Force all of the file writes to complete, in case it's necessary for
826 # crbug.com/954188
827 sync
Will Drewry55b42c92010-10-20 15:44:11 -0500828}
829
830enable_rw_mount() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500831 local rootfs=$1
Will Drewry55b42c92010-10-20 15:44:11 -0500832 local offset="${2-0}"
Will Drewry9b7cb512010-10-20 18:11:24 -0500833 local ro_compat_offset=$((0x464 + 3)) # Set 'highest' byte
Alex Deymof6a527d2015-01-12 18:30:58 -0800834 is_ext_filesystem "${rootfs}" "${offset}" || return 0
Alex Deymo41226312015-03-09 15:35:24 -0700835 is_ext2_rw_mount_enabled "${rootfs}" "${offset}" && return 0
836
837 make_block_device_rw "${rootfs}"
Will Drewry9b7cb512010-10-20 18:11:24 -0500838 printf '\000' |
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500839 sudo dd of="${rootfs}" seek=$((offset + ro_compat_offset)) \
Alex Deymo41226312015-03-09 15:35:24 -0700840 conv=notrunc count=1 bs=1 status=none
LaMont Jones70743742019-04-26 10:14:33 -0600841 # Force all of the file writes to complete, in case it's necessary for
842 # crbug.com/954188
843 sync
Alex Deymo41226312015-03-09 15:35:24 -0700844}
845
846is_ext2_rw_mount_enabled() {
847 local rootfs=$1
848 local offset="${2-0}"
849 local ro_compat_offset=$((0x464 + 3)) # Get 'highest' byte
850 local ro_compat_flag=$(sudo dd if="${rootfs}" \
851 skip=$((offset + ro_compat_offset)) bs=1 count=1 status=none \
852 2>/dev/null | hexdump -e '1 "%.2x"')
853 test "${ro_compat_flag}" = "00"
Will Drewry55b42c92010-10-20 15:44:11 -0500854}
855
Alex Deymof9235952015-01-15 11:15:09 -0800856# Returns whether the passed rootfs is an extended filesystem by checking the
Alex Deymof6a527d2015-01-12 18:30:58 -0800857# ext2 s_magic field in the superblock.
858is_ext_filesystem() {
859 local rootfs=$1
860 local offset="${2-0}"
861 local ext_magic_offset=$((0x400 + 56))
Alex Deymo41226312015-03-09 15:35:24 -0700862 local ext_magic=$(sudo dd if="${rootfs}" \
863 skip=$((offset + ext_magic_offset)) bs=1 count=2 2>/dev/null |
864 hexdump -e '1/2 "%.4x"')
Alex Deymof6a527d2015-01-12 18:30:58 -0800865 test "${ext_magic}" = "ef53"
866}
867
Alex Deymo41226312015-03-09 15:35:24 -0700868# If the passed argument is a block device, ensure it is writtable and make it
869# writtable if not.
870make_block_device_rw() {
871 local block_dev="$1"
872 [[ -b "${block_dev}" ]] || return 0
873 if [[ $(sudo blockdev --getro "${block_dev}") == "1" ]]; then
874 sudo blockdev --setrw "${block_dev}"
875 fi
876}
877
Nick Sandersd2509272010-06-16 03:50:04 -0700878# Get current timestamp. Assumes common.sh runs at startup.
879start_time=$(date +%s)
880
Matt Tennant298f61a2012-06-25 21:54:33 -0700881# Get time elapsed since start_time in seconds.
Mike Frysingerbbec7112019-08-22 00:44:29 -0400882_get_elapsed_seconds() {
Greg Spencer798d75f2011-02-01 22:04:49 -0800883 local end_time=$(date +%s)
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500884 local elapsed_seconds=$(( end_time - start_time ))
Matt Tennant298f61a2012-06-25 21:54:33 -0700885 echo ${elapsed_seconds}
886}
887
888# Print time elapsed since start_time.
889print_time_elapsed() {
890 # Optional first arg to specify elapsed_seconds. If not given, will
891 # recalculate elapsed time to now. Optional second arg to specify
892 # command name associated with elapsed time.
Mike Frysingerbbec7112019-08-22 00:44:29 -0400893 local elapsed_seconds=${1:-$(_get_elapsed_seconds)}
Matt Tennant298f61a2012-06-25 21:54:33 -0700894 local cmd_base=${2:-}
895
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500896 local minutes=$(( elapsed_seconds / 60 ))
897 local seconds=$(( elapsed_seconds % 60 ))
Matt Tennant298f61a2012-06-25 21:54:33 -0700898
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500899 if [[ -n ${cmd_base} ]]; then
Matt Tennant298f61a2012-06-25 21:54:33 -0700900 info "Elapsed time (${cmd_base}): ${minutes}m${seconds}s"
901 else
902 info "Elapsed time: ${minutes}m${seconds}s"
903 fi
904}
905
Matt Tennant298f61a2012-06-25 21:54:33 -0700906command_completed() {
907 # Call print_elapsed_time regardless.
Mike Frysingerbbec7112019-08-22 00:44:29 -0400908 local run_time=$(_get_elapsed_seconds)
Mike Frysinger3131d412019-03-02 14:09:37 -0500909 local cmd_base=$(basename "$0")
Matt Tennant298f61a2012-06-25 21:54:33 -0700910 print_time_elapsed ${run_time} ${cmd_base}
Nick Sandersd2509272010-06-16 03:50:04 -0700911}
Doug Anderson0c9e88d2010-10-19 14:49:39 -0700912
Bertrand SIMONNETb17cd572015-04-01 10:27:37 -0700913# Load a single variable from a bash file.
914# $1 - Path to the file.
915# $2 - Variable to get.
916get_variable() {
917 local filepath=$1
918 local variable=$2
919 local lockfile="${filepath}.lock"
920
921 if [[ -e "${filepath}" ]]; then
922 userowned_file "${lockfile}"
Bertrand SIMONNET48b6e782015-03-26 16:04:07 -0700923 (
Bertrand SIMONNETb17cd572015-04-01 10:27:37 -0700924 flock 201
925 . "${filepath}"
Bertrand SIMONNET48b6e782015-03-26 16:04:07 -0700926 if [[ "${!variable+set}" == "set" ]]; then
927 echo "${!variable}"
Bertrand SIMONNET48b6e782015-03-26 16:04:07 -0700928 fi
Bertrand SIMONNETb17cd572015-04-01 10:27:37 -0700929 ) 201>"${lockfile}"
930 fi
931}
932
Bertrand SIMONNETb17cd572015-04-01 10:27:37 -0700933# Creates a user owned file.
934# $1 - Path to the file.
935userowned_file() {
936 local filepath=$1
937
938 if [[ ! -w "${filepath}" ]]; then
939 cmds=(
940 "mkdir -p '$(dirname "${filepath}")'"
941 "touch '${filepath}'"
942 "chown ${USER} '${filepath}'"
Bertrand SIMONNET48b6e782015-03-26 16:04:07 -0700943 )
Bertrand SIMONNETb17cd572015-04-01 10:27:37 -0700944 sudo_multi "${cmds[@]}"
Bertrand SIMONNET48b6e782015-03-26 16:04:07 -0700945 fi
946}
947
Albert Chaulk5d190f72013-07-12 11:42:18 -0700948# Load configuration files that allow board-specific overrides of default
949# functionality to be specified in overlays.
Steve Fungd3b1f5f2015-03-29 21:47:24 -0700950# $1 - File to load.
Albert Chaulk5d190f72013-07-12 11:42:18 -0700951load_board_specific_script() {
Steve Fung88897cc2015-03-25 13:38:38 -0700952 local file=$1 overlay
953 [[ $# -ne 1 ]] && die "load_board_specific_script requires exactly 1 param"
954 for overlay in ${BOARD_OVERLAY}; do
Albert Chaulk5d190f72013-07-12 11:42:18 -0700955 local setup_sh="${overlay}/scripts/${file}"
956 if [[ -e ${setup_sh} ]]; then
957 source "${setup_sh}"
958 fi
959 done
960}
961
Chris Sosafd2cdec2011-03-24 16:06:59 -0700962# Reinterprets path from outside the chroot for use inside.
963# Returns "" if "" given.
964# $1 - The path to reinterpret.
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400965reinterpret_path_for_chroot() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500966 if [[ ${INSIDE_CHROOT} -ne 1 ]]; then
967 if [[ -z $1 ]]; then
Chris Sosafd2cdec2011-03-24 16:06:59 -0700968 echo ""
969 else
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500970 local path_abs_path=$(readlink -f "$1")
Chris Sosafd2cdec2011-03-24 16:06:59 -0700971 local gclient_root_abs_path=$(readlink -f "${GCLIENT_ROOT}")
972
973 # Strip the repository root from the path.
974 local relative_path=$(echo ${path_abs_path} \
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400975 | sed "s:${gclient_root_abs_path}/::")
Chris Sosafd2cdec2011-03-24 16:06:59 -0700976
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500977 if [[ ${relative_path} == "${path_abs_path}" ]]; then
978 die "Error reinterpreting path. Path $1 is not within source tree."
Chris Sosafd2cdec2011-03-24 16:06:59 -0700979 fi
980
981 # Prepend the chroot repository path.
Chris Sosaed2ff4b2013-08-30 12:58:41 -0700982 echo "/mnt/host/source/${relative_path}"
Chris Sosafd2cdec2011-03-24 16:06:59 -0700983 fi
984 else
985 # Path is already inside the chroot :).
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500986 echo "$1"
Chris Sosafd2cdec2011-03-24 16:06:59 -0700987 fi
988}
Gabe Black83d8b822011-08-01 17:50:09 -0700989
Mike Frysinger6b1abb22012-05-11 13:44:06 -0400990emerge_custom_kernel() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -0500991 local install_root=$1
David Jamesdee866c2012-03-15 14:53:19 -0700992 local root=/build/${FLAGS_board}
David James0ea96e42011-08-03 11:53:50 -0700993 local tmp_pkgdir=${root}/custom-packages
994
995 # Clean up any leftover state in custom directories.
Mike Frysingera1a06ab2011-08-10 11:40:30 -0400996 sudo rm -rf "${tmp_pkgdir}"
David James0ea96e42011-08-03 11:53:50 -0700997
Aviv Keshet14373912014-06-27 14:34:06 +0000998 # Update chromeos-initramfs to contain the latest binaries from the build
999 # tree. This is basically just packaging up already-built binaries from
1000 # ${root}. We are careful not to muck with the existing prebuilts so that
1001 # prebuilts can be uploaded in parallel.
1002 # TODO(davidjames): Implement ABI deps so that chromeos-initramfs will be
1003 # rebuilt automatically when its dependencies change.
1004 sudo -E PKGDIR="${tmp_pkgdir}" ${EMERGE_BOARD_CMD} -1 \
1005 chromeos-base/chromeos-initramfs || die "Cannot emerge chromeos-initramfs"
1006
David James0ea96e42011-08-03 11:53:50 -07001007 # Verify all dependencies of the kernel are installed. This should be a
1008 # no-op, but it's good to check in case a developer didn't run
Mike Frysinger0957a182012-03-21 23:17:14 -04001009 # build_packages. We need the expand_virtual call to workaround a bug
1010 # in portage where it only installs the virtual pkg.
1011 local kernel=$(portageq-${FLAGS_board} expand_virtual ${root} \
1012 virtual/linux-sources)
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001013 sudo -E PKGDIR="${tmp_pkgdir}" ${EMERGE_BOARD_CMD} --onlydeps \
David James0ea96e42011-08-03 11:53:50 -07001014 ${kernel} || die "Cannot emerge kernel dependencies"
1015
1016 # Build the kernel. This uses the standard root so that we can pick up the
1017 # initramfs from there. But we don't actually install the kernel to the
1018 # standard root, because that'll muck up the kernel debug symbols there,
1019 # which we want to upload in parallel.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001020 sudo -E PKGDIR="${tmp_pkgdir}" ${EMERGE_BOARD_CMD} --buildpkgonly \
David James0ea96e42011-08-03 11:53:50 -07001021 ${kernel} || die "Cannot emerge kernel"
1022
1023 # Install the custom kernel to the provided install root.
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001024 sudo -E PKGDIR="${tmp_pkgdir}" ${EMERGE_BOARD_CMD} --usepkgonly \
David James0ea96e42011-08-03 11:53:50 -07001025 --root=${install_root} ${kernel} || die "Cannot emerge kernel to root"
1026}
Brian Harringfeb04f72012-02-03 21:22:50 -08001027
Mike Frysinger6b1abb22012-05-11 13:44:06 -04001028enable_strict_sudo() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001029 if [[ -z ${CROS_SUDO_KEEP_ALIVE} ]]; then
Brian Harringfeb04f72012-02-03 21:22:50 -08001030 echo "$0 was somehow invoked in a way that the sudo keep alive could"
1031 echo "not be found. Failing due to this. See crosbug.com/18393."
1032 exit 126
1033 fi
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001034 sudo() {
1035 $(type -P sudo) -n "$@"
Brian Harringfeb04f72012-02-03 21:22:50 -08001036 }
1037}
Gilad Arnold207a7c72012-02-09 10:19:16 -08001038
David James855afb72012-03-14 20:04:59 -07001039# Display --help if requested. This is used to hide options from help
1040# that are not intended for developer use.
1041#
1042# How to use:
1043# 1) Declare the options that you want to appear in help.
1044# 2) Call this function.
1045# 3) Declare the options that you don't want to appear in help.
1046#
1047# See build_packages for example usage.
Mike Frysinger6b1abb22012-05-11 13:44:06 -04001048show_help_if_requested() {
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001049 local opt
David James855afb72012-03-14 20:04:59 -07001050 for opt in "$@"; do
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001051 if [[ ${opt} == "-h" || ${opt} == "--help" ]]; then
David James855afb72012-03-14 20:04:59 -07001052 flags_help
1053 exit 0
1054 fi
1055 done
1056}
Brian Harring7f175a52012-03-02 05:37:00 -08001057
Mike Frysinger6b1abb22012-05-11 13:44:06 -04001058switch_to_strict_mode() {
Brian Harring7f175a52012-03-02 05:37:00 -08001059 # Set up strict execution mode; note that the trap
1060 # must follow switch_to_strict_mode, else it will have no effect.
1061 set -e
Mike Frysinger9ebc8ce2015-04-06 13:15:01 -04001062 trap 'die_err_trap' ERR
Mike Frysingerbaae8eb2013-01-15 01:34:26 -05001063 if [[ $# -ne 0 ]]; then
Brian Harring7f175a52012-03-02 05:37:00 -08001064 set "$@"
1065 fi
1066}
1067
1068# TODO: Re-enable this once shflags is set -e safe.
1069#switch_to_strict_mode