1#! /bin/bash
2#
3# Copyright 2019 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17usage() {
18  cat >&2 <<EOF
19Determine and print the 32- or 64-bit architecture of a device.
20
21Usage:
22  $0 --32    Select the 32-bit architecture
23  $0 --64    Select the 64-bit architecture
24EOF
25  exit 1
26}
27
28if [[ $# -ne 1 ]]; then
29  usage
30fi
31
32ARCHITECTURES_32="(arm|x86|none)"
33ARCHITECTURES_64="(arm64|x86_64|none)"
34
35case "$1" in
36  (--32)
37    ARCHITECTURES_PATTERN="${ARCHITECTURES_32}"
38    ;;
39  (--64)
40    ARCHITECTURES_PATTERN="${ARCHITECTURES_64}"
41    ;;
42  (*) usage;;
43esac
44
45# Need to be root to query /data/dalvik-cache
46adb root > /dev/null
47adb wait-for-device
48ISA=
49ISA_adb_invocation=
50ISA_outcome=
51# We iterate a few times to workaround an adb issue. b/32655576
52for i in {1..10}; do
53  ISA_adb_invocation=$(adb shell ls /data/dalvik-cache)
54  ISA_outcome=$?
55  ISA=$(echo $ISA_adb_invocation | grep -Ewo "${ARCHITECTURES_PATTERN}")
56  if [[ -n "$ISA" ]]; then
57    break;
58  fi
59done
60if [[ -z "$ISA" ]]; then
61  echo >&2 "Unable to determine architecture"
62  # Print a few things for helping diagnosing the problem.
63  echo >&2 "adb invocation output: $ISA_adb_invocation"
64  echo >&2 "adb invocation outcome: $ISA_outcome"
65  echo >&2 $(adb shell ls -F /data/dalvik-cache)
66  echo >&2 $(adb shell ls /data/dalvik-cache)
67  echo >&2 ${ARCHITECTURES_PATTERN}
68  echo >&2 $(adb shell ls -F /data/dalvik-cache | grep -Ewo "${ARCHITECTURES_PATTERN}")
69  exit 1
70fi
71
72echo "$ISA"
73