xref: /llvm-project/compiler-rt/test/sanitizer_common/android_commands/android_common.py (revision f98ee40f4b5d7474fc67e82824bf6abbaedb7b1c)
1import os, sys, subprocess, tempfile
2import time
3
4ANDROID_TMPDIR = "/data/local/tmp/Output"
5ADB = os.environ.get("ADB", "adb")
6
7verbose = False
8if os.environ.get("ANDROID_RUN_VERBOSE") == "1":
9    verbose = True
10
11
12def host_to_device_path(path):
13    rel = os.path.relpath(path, "/")
14    dev = os.path.join(ANDROID_TMPDIR, rel)
15    return dev
16
17
18def adb(args, attempts=1, timeout_sec=600):
19    if verbose:
20        print(args)
21    tmpname = tempfile.mktemp()
22    out = open(tmpname, "w")
23    ret = 255
24    while attempts > 0 and ret != 0:
25        attempts -= 1
26        ret = subprocess.call(
27            ["timeout", str(timeout_sec), ADB] + args,
28            stdout=out,
29            stderr=subprocess.STDOUT,
30        )
31    if ret != 0:
32        print("adb command failed", args)
33        print(tmpname)
34        out.close()
35        out = open(tmpname, "r")
36        print(out.read())
37    out.close()
38    os.unlink(tmpname)
39    return ret
40
41
42def pull_from_device(path):
43    tmp = tempfile.mktemp()
44    adb(["pull", path, tmp], 5, 60)
45    text = open(tmp, "r").read()
46    os.unlink(tmp)
47    return text
48
49
50def push_to_device(path):
51    dst_path = host_to_device_path(path)
52    adb(["push", path, dst_path], 5, 60)
53