1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
8 // This program can be used as go_android_GOARCH_exec by the Go tool.
9 // It executes binaries on an android device using adb.
28 func run(args ...string) (string, error) {
29 cmd := adbCmd(args...)
30 buf := new(strings.Builder)
31 cmd.Stdout = io.MultiWriter(os.Stdout, buf)
32 // If the adb subprocess somehow hangs, go test will kill this wrapper
33 // and wait for our os.Stderr (and os.Stdout) to close as a result.
34 // However, if the os.Stderr (or os.Stdout) file descriptors are
35 // passed on, the hanging adb subprocess will hold them open and
36 // go test will hang forever.
38 // Avoid that by wrapping stderr, breaking the short circuit and
39 // forcing cmd.Run to use another pipe and goroutine to pass
40 // along stderr from adb.
41 cmd.Stderr = struct{ io.Writer }{os.Stderr}
44 return "", fmt.Errorf("adb %s: %v", strings.Join(args, " "), err)
46 return buf.String(), nil
49 func adb(args ...string) error {
50 if out, err := adbCmd(args...).CombinedOutput(); err != nil {
51 fmt.Fprintf(os.Stderr, "adb %s\n%s", strings.Join(args, " "), out)
57 func adbCmd(args ...string) *exec.Cmd {
58 if flags := os.Getenv("GOANDROID_ADB_FLAGS"); flags != "" {
59 args = append(strings.Split(flags, " "), args...)
61 return exec.Command("adb", args...)
65 deviceRoot = "/data/local/tmp/go_android_exec"
66 deviceGoroot = deviceRoot + "/goroot"
71 log.SetPrefix("go_android_exec: ")
72 exitCode, err := runMain()
79 func runMain() (int, error) {
80 // Concurrent use of adb is flaky, so serialize adb commands.
81 // See https://github.com/golang/go/issues/23795 or
82 // https://issuetracker.google.com/issues/73230216.
83 lockPath := filepath.Join(os.TempDir(), "go_android_exec-adb-lock")
84 lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0666)
89 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
93 // In case we're booting a device or emulator alongside all.bash, wait for
94 // it to be ready. adb wait-for-device is not enough, we have to
95 // wait for sys.boot_completed.
96 if err := adb("wait-for-device", "exec-out", "while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;"); err != nil {
100 // Done once per make.bash.
101 if err := adbCopyGoroot(); err != nil {
105 // Prepare a temporary directory that will be cleaned up at the end.
106 // Binary names can conflict.
107 // E.g. template.test from the {html,text}/template packages.
108 binName := filepath.Base(os.Args[1])
109 deviceGotmp := fmt.Sprintf(deviceRoot+"/%s-%d", binName, os.Getpid())
110 deviceGopath := deviceGotmp + "/gopath"
111 defer adb("exec-out", "rm", "-rf", deviceGotmp) // Clean up.
113 // Determine the package by examining the current working
114 // directory, which will look something like
115 // "$GOROOT/src/mime/multipart" or "$GOPATH/src/golang.org/x/mobile".
116 // We extract everything after the $GOROOT or $GOPATH to run on the
117 // same relative directory on the target device.
118 subdir, inGoRoot, err := subdir()
122 deviceCwd := filepath.Join(deviceGopath, subdir)
124 deviceCwd = filepath.Join(deviceGoroot, subdir)
126 if err := adb("exec-out", "mkdir", "-p", deviceCwd); err != nil {
129 if err := adbCopyTree(deviceCwd, subdir); err != nil {
133 // Copy .go files from the package.
134 goFiles, err := filepath.Glob("*.go")
138 if len(goFiles) > 0 {
139 args := append(append([]string{"push"}, goFiles...), deviceCwd)
140 if err := adb(args...); err != nil {
146 deviceBin := fmt.Sprintf("%s/%s", deviceGotmp, binName)
147 if err := adb("push", os.Args[1], deviceBin); err != nil {
151 // Forward SIGQUIT from the go command to show backtraces from
152 // the binary instead of from this wrapper.
153 quit := make(chan os.Signal, 1)
154 signal.Notify(quit, syscall.SIGQUIT)
157 // We don't have the PID of the running process; use the
158 // binary name instead.
159 adb("exec-out", "killall -QUIT "+binName)
163 // https://code.google.com/p/android/issues/detail?id=3254
164 // dont trust the exitcode of adb. Instead, append the exitcode to
165 // the output and parse it from there.
166 const exitstr = "exitcode="
167 cmd := `export TMPDIR="` + deviceGotmp + `"` +
168 `; export GOROOT="` + deviceGoroot + `"` +
169 `; export GOPATH="` + deviceGopath + `"` +
170 `; export CGO_ENABLED=0` +
171 `; export GOPROXY=` + os.Getenv("GOPROXY") +
172 `; export GOCACHE="` + deviceRoot + `/gocache"` +
173 `; export PATH=$PATH:"` + deviceGoroot + `/bin"` +
174 `; cd "` + deviceCwd + `"` +
175 "; '" + deviceBin + "' " + strings.Join(os.Args[2:], " ") +
176 "; echo -n " + exitstr + "$?"
177 output, err := run("exec-out", cmd)
178 signal.Reset(syscall.SIGQUIT)
184 exitIdx := strings.LastIndex(output, exitstr)
186 return 0, fmt.Errorf("no exit code: %q", output)
188 code, err := strconv.Atoi(output[exitIdx+len(exitstr):])
190 return 0, fmt.Errorf("bad exit code: %v", err)
195 // subdir determines the package based on the current working directory,
196 // and returns the path to the package source relative to $GOROOT (or $GOPATH).
197 func subdir() (pkgpath string, underGoRoot bool, err error) {
198 cwd, err := os.Getwd()
200 return "", false, err
202 cwd, err = filepath.EvalSymlinks(cwd)
204 return "", false, err
206 goroot, err := filepath.EvalSymlinks(runtime.GOROOT())
208 return "", false, err
210 if subdir, err := filepath.Rel(goroot, cwd); err == nil {
211 if !strings.Contains(subdir, "..") {
212 return subdir, true, nil
216 for _, p := range filepath.SplitList(build.Default.GOPATH) {
217 pabs, err := filepath.EvalSymlinks(p)
219 return "", false, err
221 if subdir, err := filepath.Rel(pabs, cwd); err == nil {
222 if !strings.Contains(subdir, "..") {
223 return subdir, false, nil
227 return "", false, fmt.Errorf("the current path %q is not in either GOROOT(%q) or GOPATH(%q)",
228 cwd, runtime.GOROOT(), build.Default.GOPATH)
231 // adbCopyTree copies testdata, go.mod, go.sum files from subdir
232 // and from parent directories all the way up to the root of subdir.
233 // go.mod and go.sum files are needed for the go tool modules queries,
234 // and the testdata directories for tests. It is common for tests to
235 // reach out into testdata from parent packages.
236 func adbCopyTree(deviceCwd, subdir string) error {
239 for _, path := range []string{"testdata", "go.mod", "go.sum"} {
240 path := filepath.Join(dir, path)
241 if _, err := os.Stat(path); err != nil {
244 devicePath := filepath.Join(deviceCwd, dir)
245 if err := adb("exec-out", "mkdir", "-p", devicePath); err != nil {
248 if err := adb("push", path, devicePath); err != nil {
255 subdir = filepath.Dir(subdir)
256 dir = filepath.Join(dir, "..")
261 // adbCopyGoroot clears deviceRoot for previous versions of GOROOT, GOPATH
262 // and temporary data. Then, it copies relevant parts of GOROOT to the device,
263 // including the go tool built for android.
264 // A lock file ensures this only happens once, even with concurrent exec
266 func adbCopyGoroot() error {
267 // Also known by cmd/dist. The bootstrap command deletes the file.
268 statPath := filepath.Join(os.TempDir(), "go_android_exec-adb-sync-status")
269 stat, err := os.OpenFile(statPath, os.O_CREATE|os.O_RDWR, 0666)
274 // Serialize check and copying.
275 if err := syscall.Flock(int(stat.Fd()), syscall.LOCK_EX); err != nil {
278 s, err := io.ReadAll(stat)
282 if string(s) == "done" {
285 // Delete GOROOT, GOPATH and any leftover test data.
286 if err := adb("exec-out", "rm", "-rf", deviceRoot); err != nil {
289 deviceBin := filepath.Join(deviceGoroot, "bin")
290 if err := adb("exec-out", "mkdir", "-p", deviceBin); err != nil {
293 goroot := runtime.GOROOT()
294 // Build go for android.
295 goCmd := filepath.Join(goroot, "bin", "go")
296 tmpGo, err := os.CreateTemp("", "go_android_exec-cmd-go-*")
301 defer os.Remove(tmpGo.Name())
303 if out, err := exec.Command(goCmd, "build", "-o", tmpGo.Name(), "cmd/go").CombinedOutput(); err != nil {
304 return fmt.Errorf("failed to build go tool for device: %s\n%v", out, err)
306 deviceGo := filepath.Join(deviceBin, "go")
307 if err := adb("push", tmpGo.Name(), deviceGo); err != nil {
310 for _, dir := range []string{"src", "test", "lib", "api"} {
311 if err := adb("push", filepath.Join(goroot, dir), filepath.Join(deviceGoroot)); err != nil {
316 // Copy only the relevant from pkg.
317 if err := adb("exec-out", "mkdir", "-p", filepath.Join(deviceGoroot, "pkg", "tool")); err != nil {
320 if err := adb("push", filepath.Join(goroot, "pkg", "include"), filepath.Join(deviceGoroot, "pkg")); err != nil {
323 runtimea, err := exec.Command(goCmd, "list", "-f", "{{.Target}}", "runtime").Output()
324 pkgdir := filepath.Dir(string(runtimea))
326 return errors.New("could not find android pkg dir")
328 if err := adb("push", pkgdir, filepath.Join(deviceGoroot, "pkg")); err != nil {
331 tooldir := filepath.Join(goroot, "pkg", "tool", filepath.Base(pkgdir))
332 if err := adb("push", tooldir, filepath.Join(deviceGoroot, "pkg", "tool")); err != nil {
336 if _, err := stat.Write([]byte("done")); err != nil {