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.
29 func run(args ...string) (string, error) {
30 cmd := adbCmd(args...)
31 buf := new(bytes.Buffer)
32 cmd.Stdout = io.MultiWriter(os.Stdout, buf)
33 // If the adb subprocess somehow hangs, go test will kill this wrapper
34 // and wait for our os.Stderr (and os.Stdout) to close as a result.
35 // However, if the os.Stderr (or os.Stdout) file descriptors are
36 // passed on, the hanging adb subprocess will hold them open and
37 // go test will hang forever.
39 // Avoid that by wrapping stderr, breaking the short circuit and
40 // forcing cmd.Run to use another pipe and goroutine to pass
41 // along stderr from adb.
42 cmd.Stderr = struct{ io.Writer }{os.Stderr}
45 return "", fmt.Errorf("adb %s: %v", strings.Join(args, " "), err)
47 return buf.String(), nil
50 func adb(args ...string) error {
51 if out, err := adbCmd(args...).CombinedOutput(); err != nil {
52 fmt.Fprintf(os.Stderr, "adb %s\n%s", strings.Join(args, " "), out)
58 func adbCmd(args ...string) *exec.Cmd {
59 if flags := os.Getenv("GOANDROID_ADB_FLAGS"); flags != "" {
60 args = append(strings.Split(flags, " "), args...)
62 return exec.Command("adb", args...)
66 deviceRoot = "/data/local/tmp/go_android_exec"
67 deviceGoroot = deviceRoot + "/goroot"
72 log.SetPrefix("go_android_exec: ")
73 exitCode, err := runMain()
80 func runMain() (int, error) {
81 // Concurrent use of adb is flaky, so serialize adb commands.
82 // See https://github.com/golang/go/issues/23795 or
83 // https://issuetracker.google.com/issues/73230216.
84 lockPath := filepath.Join(os.TempDir(), "go_android_exec-adb-lock")
85 lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0666)
90 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
94 // In case we're booting a device or emulator alongside all.bash, wait for
95 // it to be ready. adb wait-for-device is not enough, we have to
96 // wait for sys.boot_completed.
97 if err := adb("wait-for-device", "exec-out", "while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;"); err != nil {
101 // Done once per make.bash.
102 if err := adbCopyGoroot(); err != nil {
106 // Prepare a temporary directory that will be cleaned up at the end.
107 // Binary names can conflict.
108 // E.g. template.test from the {html,text}/template packages.
109 binName := filepath.Base(os.Args[1])
110 deviceGotmp := fmt.Sprintf(deviceRoot+"/%s-%d", binName, os.Getpid())
111 deviceGopath := deviceGotmp + "/gopath"
112 defer adb("exec-out", "rm", "-rf", deviceGotmp) // Clean up.
114 // Determine the package by examining the current working
115 // directory, which will look something like
116 // "$GOROOT/src/mime/multipart" or "$GOPATH/src/golang.org/x/mobile".
117 // We extract everything after the $GOROOT or $GOPATH to run on the
118 // same relative directory on the target device.
119 subdir, inGoRoot, err := subdir()
123 deviceCwd := filepath.Join(deviceGopath, subdir)
125 deviceCwd = filepath.Join(deviceGoroot, subdir)
127 if err := adb("exec-out", "mkdir", "-p", deviceCwd); err != nil {
130 if err := adbCopyTree(deviceCwd, subdir); err != nil {
134 // Copy .go files from the package.
135 goFiles, err := filepath.Glob("*.go")
139 if len(goFiles) > 0 {
140 args := append(append([]string{"push"}, goFiles...), deviceCwd)
141 if err := adb(args...); err != nil {
147 deviceBin := fmt.Sprintf("%s/%s", deviceGotmp, binName)
148 if err := adb("push", os.Args[1], deviceBin); err != nil {
152 // Forward SIGQUIT from the go command to show backtraces from
153 // the binary instead of from this wrapper.
154 quit := make(chan os.Signal, 1)
155 signal.Notify(quit, syscall.SIGQUIT)
158 // We don't have the PID of the running process; use the
159 // binary name instead.
160 adb("exec-out", "killall -QUIT "+binName)
164 // https://code.google.com/p/android/issues/detail?id=3254
165 // dont trust the exitcode of adb. Instead, append the exitcode to
166 // the output and parse it from there.
167 const exitstr = "exitcode="
168 cmd := `export TMPDIR="` + deviceGotmp + `"` +
169 `; export GOROOT="` + deviceGoroot + `"` +
170 `; export GOPATH="` + deviceGopath + `"` +
171 `; export CGO_ENABLED=0` +
172 `; export GOPROXY=` + os.Getenv("GOPROXY") +
173 `; export GOCACHE="` + deviceRoot + `/gocache"` +
174 `; export PATH=$PATH:"` + deviceGoroot + `/bin"` +
175 `; cd "` + deviceCwd + `"` +
176 "; '" + deviceBin + "' " + strings.Join(os.Args[2:], " ") +
177 "; echo -n " + exitstr + "$?"
178 output, err := run("exec-out", cmd)
179 signal.Reset(syscall.SIGQUIT)
185 exitIdx := strings.LastIndex(output, exitstr)
187 return 0, fmt.Errorf("no exit code: %q", output)
189 code, err := strconv.Atoi(output[exitIdx+len(exitstr):])
191 return 0, fmt.Errorf("bad exit code: %v", err)
196 // subdir determines the package based on the current working directory,
197 // and returns the path to the package source relative to $GOROOT (or $GOPATH).
198 func subdir() (pkgpath string, underGoRoot bool, err error) {
199 cwd, err := os.Getwd()
201 return "", false, err
203 cwd, err = filepath.EvalSymlinks(cwd)
205 return "", false, err
207 goroot, err := filepath.EvalSymlinks(runtime.GOROOT())
209 return "", false, err
211 if subdir, err := filepath.Rel(goroot, cwd); err == nil {
212 if !strings.Contains(subdir, "..") {
213 return subdir, true, nil
217 for _, p := range filepath.SplitList(build.Default.GOPATH) {
218 pabs, err := filepath.EvalSymlinks(p)
220 return "", false, err
222 if subdir, err := filepath.Rel(pabs, cwd); err == nil {
223 if !strings.Contains(subdir, "..") {
224 return subdir, false, nil
228 return "", false, fmt.Errorf("the current path %q is not in either GOROOT(%q) or GOPATH(%q)",
229 cwd, runtime.GOROOT(), build.Default.GOPATH)
232 // adbCopyTree copies testdata, go.mod, go.sum files from subdir
233 // and from parent directories all the way up to the root of subdir.
234 // go.mod and go.sum files are needed for the go tool modules queries,
235 // and the testdata directories for tests. It is common for tests to
236 // reach out into testdata from parent packages.
237 func adbCopyTree(deviceCwd, subdir string) error {
240 for _, path := range []string{"testdata", "go.mod", "go.sum"} {
241 path := filepath.Join(dir, path)
242 if _, err := os.Stat(path); err != nil {
245 devicePath := filepath.Join(deviceCwd, dir)
246 if err := adb("exec-out", "mkdir", "-p", devicePath); err != nil {
249 if err := adb("push", path, devicePath); err != nil {
256 subdir = filepath.Dir(subdir)
257 dir = filepath.Join(dir, "..")
262 // adbCopyGoroot clears deviceRoot for previous versions of GOROOT, GOPATH
263 // and temporary data. Then, it copies relevant parts of GOROOT to the device,
264 // including the go tool built for android.
265 // A lock file ensures this only happens once, even with concurrent exec
267 func adbCopyGoroot() error {
268 // Also known by cmd/dist. The bootstrap command deletes the file.
269 statPath := filepath.Join(os.TempDir(), "go_android_exec-adb-sync-status")
270 stat, err := os.OpenFile(statPath, os.O_CREATE|os.O_RDWR, 0666)
275 // Serialize check and copying.
276 if err := syscall.Flock(int(stat.Fd()), syscall.LOCK_EX); err != nil {
279 s, err := io.ReadAll(stat)
283 if string(s) == "done" {
286 // Delete GOROOT, GOPATH and any leftover test data.
287 if err := adb("exec-out", "rm", "-rf", deviceRoot); err != nil {
290 deviceBin := filepath.Join(deviceGoroot, "bin")
291 if err := adb("exec-out", "mkdir", "-p", deviceBin); err != nil {
294 goroot := runtime.GOROOT()
295 // Build go for android.
296 goCmd := filepath.Join(goroot, "bin", "go")
297 tmpGo, err := os.CreateTemp("", "go_android_exec-cmd-go-*")
302 defer os.Remove(tmpGo.Name())
304 if out, err := exec.Command(goCmd, "build", "-o", tmpGo.Name(), "cmd/go").CombinedOutput(); err != nil {
305 return fmt.Errorf("failed to build go tool for device: %s\n%v", out, err)
307 deviceGo := filepath.Join(deviceBin, "go")
308 if err := adb("push", tmpGo.Name(), deviceGo); err != nil {
311 for _, dir := range []string{"src", "test", "lib", "api"} {
312 if err := adb("push", filepath.Join(goroot, dir), filepath.Join(deviceGoroot)); err != nil {
317 // Copy only the relevant from pkg.
318 if err := adb("exec-out", "mkdir", "-p", filepath.Join(deviceGoroot, "pkg", "tool")); err != nil {
321 if err := adb("push", filepath.Join(goroot, "pkg", "include"), filepath.Join(deviceGoroot, "pkg")); err != nil {
324 runtimea, err := exec.Command(goCmd, "list", "-f", "{{.Target}}", "runtime").Output()
325 pkgdir := filepath.Dir(string(runtimea))
327 return errors.New("could not find android pkg dir")
329 if err := adb("push", pkgdir, filepath.Join(deviceGoroot, "pkg")); err != nil {
332 tooldir := filepath.Join(goroot, "pkg", "tool", filepath.Base(pkgdir))
333 if err := adb("push", tooldir, filepath.Join(deviceGoroot, "pkg", "tool")); err != nil {
337 if _, err := stat.Write([]byte("done")); err != nil {