blob: efc083ccb62b6a9d0218e30fde18bc0dd74765e4 [file] [log] [blame]
#!/bin/sh
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# TODO(b/131121671): Update this when script with a method that works for
# user images.
logged_in_file='/run/state/logged-in'
is_connected() {
[ -n "$(adb devices 2>/dev/null | grep "${target}")" ]
}
# The user might still be logging in.
# The loop below will wait for ~15 seconds at most.
attempts=0
while [ "${attempts}" -le 30 ] && [ ! -f "${logged_in_file}" ]; do
sleep 0.5
: $(( attempts += 1 ))
done
if [ ! -f "${logged_in_file}" ]; then
echo "$0: Could not connect, user is not logged in." >&2
exit 1
fi
# 'adb shell' always passes the command line to /bin/sh, so we need to
# escape arguments.
command="$(/usr/bin/printf "%q " "$@")"
# adb tries to create .android in the home directory, pass it
# a temporary directory instead.
tmpdir=$(mktemp -d)
export HOME="${tmpdir}"
# Concierge dynamically assigns a VSOCK CID for each VM. Ask the service which
# CID is currently assigned to ARCVM.
ID="$(cryptohome --action=status | jq -r '.mounts[0].owner')"
if [ "$?" != "0" ]; then
echo "$0: Failed to get cryptohome ID, exiting."
exit 1
fi
CID="$(/usr/bin/concierge_client --get_vm_cid --name=arcvm \
--cryptohome_id="${ID}")"
if [ "$?" != "0" ]; then
echo "$0: Failed to get CID from concierge, exiting."
exit 1
elif [ -z "${CID}" ]; then
echo "$0: Empty CID value returned from concierge, exiting."
exit 1
fi
target="vsock:${CID}:5555"
# Try to start the server first if it's not started.
adb start-server 2>/dev/null
# It is necessary to wait a little bit after a successful 'adb connect'
# before running 'adb shell', else a 'device offline' error occurs and
# the command fails.
# The loop below will wait for ~5 seconds at most incase the VM is
# booting, and will wait for 500ms even after a successful connection
# instead of immediately breaking.
attempts=0
while [ "${attempts}" -le 10 ] && ! is_connected; do
adb connect ${target} >/dev/null
sleep 0.5
: $(( attempts += 1 ))
done
if ! is_connected; then
echo "$0: Could not connect, is the VM running?" >&2
rm -rf "${tmpdir}"
exit 1
fi
if [ $# -eq 0 ]; then
adb shell
else
# Run /system/bin/sh to be consistent with 'android-sh'.
adb exec-out "exec /system/bin/sh ${command}"
fi
ret=$?
rm -rf "${tmpdir}"
exit $ret