How to use Copy method of adb Package

Best Syzkaller code snippet using adb.Copy

go_android_exec.go

Source:go_android_exec.go Github

copy

Full Screen

1// Copyright 2014 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4// +build ignore5// This program can be used as go_android_GOARCH_exec by the Go tool.6// It executes binaries on an android device using adb.7package main8import (9 "bytes"10 "errors"11 "fmt"12 "go/build"13 "io"14 "io/ioutil"15 "log"16 "os"17 "os/exec"18 "os/signal"19 "path/filepath"20 "runtime"21 "strconv"22 "strings"23 "syscall"24)25func run(args ...string) (string, error) {26 cmd := adbCmd(args...)27 buf := new(bytes.Buffer)28 cmd.Stdout = io.MultiWriter(os.Stdout, buf)29 // If the adb subprocess somehow hangs, go test will kill this wrapper30 // and wait for our os.Stderr (and os.Stdout) to close as a result.31 // However, if the os.Stderr (or os.Stdout) file descriptors are32 // passed on, the hanging adb subprocess will hold them open and33 // go test will hang forever.34 //35 // Avoid that by wrapping stderr, breaking the short circuit and36 // forcing cmd.Run to use another pipe and goroutine to pass37 // along stderr from adb.38 cmd.Stderr = struct{ io.Writer }{os.Stderr}39 err := cmd.Run()40 if err != nil {41 return "", fmt.Errorf("adb %s: %v", strings.Join(args, " "), err)42 }43 return buf.String(), nil44}45func adb(args ...string) error {46 if out, err := adbCmd(args...).CombinedOutput(); err != nil {47 fmt.Fprintf(os.Stderr, "adb %s\n%s", strings.Join(args, " "), out)48 return err49 }50 return nil51}52func adbCmd(args ...string) *exec.Cmd {53 if flags := os.Getenv("GOANDROID_ADB_FLAGS"); flags != "" {54 args = append(strings.Split(flags, " "), args...)55 }56 return exec.Command("adb", args...)57}58const (59 deviceRoot = "/data/local/tmp/go_android_exec"60 deviceGoroot = deviceRoot + "/goroot"61)62func main() {63 log.SetFlags(0)64 log.SetPrefix("go_android_exec: ")65 exitCode, err := runMain()66 if err != nil {67 log.Fatal(err)68 }69 os.Exit(exitCode)70}71func runMain() (int, error) {72 // Concurrent use of adb is flaky, so serialize adb commands.73 // See https://github.com/golang/go/issues/23795 or74 // https://issuetracker.google.com/issues/73230216.75 lockPath := filepath.Join(os.TempDir(), "go_android_exec-adb-lock")76 lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0666)77 if err != nil {78 return 0, err79 }80 defer lock.Close()81 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {82 return 0, err83 }84 // In case we're booting a device or emulator alongside all.bash, wait for85 // it to be ready. adb wait-for-device is not enough, we have to86 // wait for sys.boot_completed.87 if err := adb("wait-for-device", "exec-out", "while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;"); err != nil {88 return 0, err89 }90 // Done once per make.bash.91 if err := adbCopyGoroot(); err != nil {92 return 0, err93 }94 // Prepare a temporary directory that will be cleaned up at the end.95 // Binary names can conflict.96 // E.g. template.test from the {html,text}/template packages.97 binName := filepath.Base(os.Args[1])98 deviceGotmp := fmt.Sprintf(deviceRoot+"/%s-%d", binName, os.Getpid())99 deviceGopath := deviceGotmp + "/gopath"100 defer adb("exec-out", "rm", "-rf", deviceGotmp) // Clean up.101 // Determine the package by examining the current working102 // directory, which will look something like103 // "$GOROOT/src/mime/multipart" or "$GOPATH/src/golang.org/x/mobile".104 // We extract everything after the $GOROOT or $GOPATH to run on the105 // same relative directory on the target device.106 subdir, inGoRoot, err := subdir()107 if err != nil {108 return 0, err109 }110 deviceCwd := filepath.Join(deviceGopath, subdir)111 if inGoRoot {112 deviceCwd = filepath.Join(deviceGoroot, subdir)113 } else {114 if err := adb("exec-out", "mkdir", "-p", deviceCwd); err != nil {115 return 0, err116 }117 if err := adbCopyTree(deviceCwd, subdir); err != nil {118 return 0, err119 }120 // Copy .go files from the package.121 goFiles, err := filepath.Glob("*.go")122 if err != nil {123 return 0, err124 }125 if len(goFiles) > 0 {126 args := append(append([]string{"push"}, goFiles...), deviceCwd)127 if err := adb(args...); err != nil {128 return 0, err129 }130 }131 }132 deviceBin := fmt.Sprintf("%s/%s", deviceGotmp, binName)133 if err := adb("push", os.Args[1], deviceBin); err != nil {134 return 0, err135 }136 // Forward SIGQUIT from the go command to show backtraces from137 // the binary instead of from this wrapper.138 quit := make(chan os.Signal, 1)139 signal.Notify(quit, syscall.SIGQUIT)140 go func() {141 for range quit {142 // We don't have the PID of the running process; use the143 // binary name instead.144 adb("exec-out", "killall -QUIT "+binName)145 }146 }()147 // In light of148 // https://code.google.com/p/android/issues/detail?id=3254149 // dont trust the exitcode of adb. Instead, append the exitcode to150 // the output and parse it from there.151 const exitstr = "exitcode="152 cmd := `export TMPDIR="` + deviceGotmp + `"` +153 `; export GOROOT="` + deviceGoroot + `"` +154 `; export GOPATH="` + deviceGopath + `"` +155 `; export CGO_ENABLED=0` +156 `; export GOPROXY=` + os.Getenv("GOPROXY") +157 `; export GOCACHE="` + deviceRoot + `/gocache"` +158 `; export PATH=$PATH:"` + deviceGoroot + `/bin"` +159 `; cd "` + deviceCwd + `"` +160 "; '" + deviceBin + "' " + strings.Join(os.Args[2:], " ") +161 "; echo -n " + exitstr + "$?"162 output, err := run("exec-out", cmd)163 signal.Reset(syscall.SIGQUIT)164 close(quit)165 if err != nil {166 return 0, err167 }168 exitIdx := strings.LastIndex(output, exitstr)169 if exitIdx == -1 {170 return 0, fmt.Errorf("no exit code: %q", output)171 }172 code, err := strconv.Atoi(output[exitIdx+len(exitstr):])173 if err != nil {174 return 0, fmt.Errorf("bad exit code: %v", err)175 }176 return code, nil177}178// subdir determines the package based on the current working directory,179// and returns the path to the package source relative to $GOROOT (or $GOPATH).180func subdir() (pkgpath string, underGoRoot bool, err error) {181 cwd, err := os.Getwd()182 if err != nil {183 return "", false, err184 }185 cwd, err = filepath.EvalSymlinks(cwd)186 if err != nil {187 return "", false, err188 }189 goroot, err := filepath.EvalSymlinks(runtime.GOROOT())190 if err != nil {191 return "", false, err192 }193 if subdir, err := filepath.Rel(goroot, cwd); err == nil {194 if !strings.Contains(subdir, "..") {195 return subdir, true, nil196 }197 }198 for _, p := range filepath.SplitList(build.Default.GOPATH) {199 pabs, err := filepath.EvalSymlinks(p)200 if err != nil {201 return "", false, err202 }203 if subdir, err := filepath.Rel(pabs, cwd); err == nil {204 if !strings.Contains(subdir, "..") {205 return subdir, false, nil206 }207 }208 }209 return "", false, fmt.Errorf("the current path %q is not in either GOROOT(%q) or GOPATH(%q)",210 cwd, runtime.GOROOT(), build.Default.GOPATH)211}212// adbCopyTree copies testdata, go.mod, go.sum files from subdir213// and from parent directories all the way up to the root of subdir.214// go.mod and go.sum files are needed for the go tool modules queries,215// and the testdata directories for tests. It is common for tests to216// reach out into testdata from parent packages.217func adbCopyTree(deviceCwd, subdir string) error {218 dir := ""219 for {220 for _, path := range []string{"testdata", "go.mod", "go.sum"} {221 path := filepath.Join(dir, path)222 if _, err := os.Stat(path); err != nil {223 continue224 }225 devicePath := filepath.Join(deviceCwd, dir)226 if err := adb("exec-out", "mkdir", "-p", devicePath); err != nil {227 return err228 }229 if err := adb("push", path, devicePath); err != nil {230 return err231 }232 }233 if subdir == "." {234 break235 }236 subdir = filepath.Dir(subdir)237 dir = filepath.Join(dir, "..")238 }239 return nil240}241// adbCopyGoroot clears deviceRoot for previous versions of GOROOT, GOPATH242// and temporary data. Then, it copies relevant parts of GOROOT to the device,243// including the go tool built for android.244// A lock file ensures this only happens once, even with concurrent exec245// wrappers.246func adbCopyGoroot() error {247 // Also known by cmd/dist. The bootstrap command deletes the file.248 statPath := filepath.Join(os.TempDir(), "go_android_exec-adb-sync-status")249 stat, err := os.OpenFile(statPath, os.O_CREATE|os.O_RDWR, 0666)250 if err != nil {251 return err252 }253 defer stat.Close()254 // Serialize check and copying.255 if err := syscall.Flock(int(stat.Fd()), syscall.LOCK_EX); err != nil {256 return err257 }258 s, err := ioutil.ReadAll(stat)259 if err != nil {260 return err261 }262 if string(s) == "done" {263 return nil264 }265 // Delete GOROOT, GOPATH and any leftover test data.266 if err := adb("exec-out", "rm", "-rf", deviceRoot); err != nil {267 return err268 }269 deviceBin := filepath.Join(deviceGoroot, "bin")270 if err := adb("exec-out", "mkdir", "-p", deviceBin); err != nil {271 return err272 }273 goroot := runtime.GOROOT()274 // Build go for android.275 goCmd := filepath.Join(goroot, "bin", "go")276 tmpGo, err := ioutil.TempFile("", "go_android_exec-cmd-go-*")277 if err != nil {278 return err279 }280 tmpGo.Close()281 defer os.Remove(tmpGo.Name())282 if out, err := exec.Command(goCmd, "build", "-o", tmpGo.Name(), "cmd/go").CombinedOutput(); err != nil {283 return fmt.Errorf("failed to build go tool for device: %s\n%v", out, err)284 }285 deviceGo := filepath.Join(deviceBin, "go")286 if err := adb("push", tmpGo.Name(), deviceGo); err != nil {287 return err288 }289 for _, dir := range []string{"src", "test", "lib", "api"} {290 if err := adb("push", filepath.Join(goroot, dir), filepath.Join(deviceGoroot)); err != nil {291 return err292 }293 }294 // Copy only the relevant from pkg.295 if err := adb("exec-out", "mkdir", "-p", filepath.Join(deviceGoroot, "pkg", "tool")); err != nil {296 return err297 }298 if err := adb("push", filepath.Join(goroot, "pkg", "include"), filepath.Join(deviceGoroot, "pkg")); err != nil {299 return err300 }301 runtimea, err := exec.Command(goCmd, "list", "-f", "{{.Target}}", "runtime").Output()302 pkgdir := filepath.Dir(string(runtimea))303 if pkgdir == "" {304 return errors.New("could not find android pkg dir")305 }306 if err := adb("push", pkgdir, filepath.Join(deviceGoroot, "pkg")); err != nil {307 return err308 }...

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s := stack.New()4 s.Push(1)5 s.Push(2)6 s.Push(3)7 s.Push(4)8 s.Push(5)9 s.Push(6)10 fmt.Println(s)11 s2 := stack.New()12 s2.Push(10)13 s2.Push(11)14 s2.Push(12)15 s2.Push(13)16 s2.Push(14)17 s2.Push(15)18 fmt.Println(s2)19 s.Copy(s2)20 fmt.Println(s)21}22&{[1 2 3 4 5 6] 6}23&{[10 11 12 13 14 15] 6}24&{[10 11 12 13 14 15] 6}25golang | stack | Pop() method26golang | stack | Push() method27golang | stack | Peek() method28golang | stack | Len() method29golang | stack | New() method30golang | stack | Clear() method31golang | stack | Empty() method32golang | stack | Contains() method33golang | stack | Values() method34golang | stack | String() method

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import ( 2func main() {3 f, err := os.Open("1.txt")4 if err != nil {5 fmt.Println(err)6 }7 defer f.Close()8 f2, err := os.Create("2.txt")9 if err != nil {10 fmt.Println(err)11 }12 defer f2.Close()13 _, err = io.Copy(f2, f)14 if err != nil {15 fmt.Println(err)16 }17}18func CopyN(dst Writer, src Reader, n int64) (written int64, err error)19import ( 20func main() {21 f, err := os.Open("1.txt")22 if err != nil {23 fmt.Println(err)24 }25 defer f.Close()26 f2, err := os.Create("3.txt")27 if err != nil {28 fmt.Println(err)29 }30 defer f2.Close()31 _, err = io.CopyN(f2, f, 5)32 if err != nil {33 fmt.Println(err)34 }35}36func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)37import (

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 r := mux.NewRouter()4 r.HandleFunc("/copy", CopyHandler)5 http.Handle("/", r)6 http.ListenAndServe(":8080", nil)7}8func CopyHandler(w http.ResponseWriter, r *http.Request) {9 fmt.Fprint(w, "Copy")10}11import (12func main() {13 r := mux.NewRouter()14 r.HandleFunc("/delete", DeleteHandler)15 http.Handle("/", r)16 http.ListenAndServe(":8080", nil)17}18func DeleteHandler(w http.ResponseWriter, r *http.Request) {19 fmt.Fprint(w, "Delete")20}21import (22func main() {23 r := mux.NewRouter()24 r.HandleFunc("/move", MoveHandler)25 http.Handle("/", r)26 http.ListenAndServe(":8080", nil)27}28func MoveHandler(w http.ResponseWriter, r *http.Request) {29 fmt.Fprint(w, "Move")30}31import (32func main() {33 r := mux.NewRouter()34 r.HandleFunc("/rename", RenameHandler)35 http.Handle("/", r)36 http.ListenAndServe(":8080", nil)37}38func RenameHandler(w http.ResponseWriter, r *http.Request) {39 fmt.Fprint(w, "Rename")40}41import (42func main() {43 r := mux.NewRouter()44 r.HandleFunc("/stat", StatHandler)45 http.Handle("/", r)46 http.ListenAndServe(":8080", nil)47}48func StatHandler(w http.ResponseWriter, r *http.Request) {49 fmt.Fprint(w, "Stat")50}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adb := NewAdb()4 device := NewDevice(adb)5 devices, err := device.Devices()6 if err != nil {7 log.Fatal(err)8 }9 for _, device := range devices {10 fmt.Println("Device Name:", device.Name)11 fmt.Println("Device Serial:", device.Serial)12 fmt.Println("Device State:", device.State)13 fmt.Println()14 }15 file := NewFile(adb)16 files, err := file.List("/sdcard")17 if err != nil {18 log.Fatal(err)19 }20 for _, file := range files {21 fmt.Println("File Name:", file.Name)22 fmt.Println("File Size:", file.Size)23 fmt.Println("File Mod Time:", file.ModTime)24 fmt.Println()25 }26 pkg := NewPackage(adb)27 packages, err := pkg.List()28 if err != nil {29 log.Fatal(err)30 }31 for _, pkg := range packages {32 fmt.Println("Package Name:", pkg.Name)33 fmt.Println("Package Version:", pkg.Version)34 fmt.Println("Package Path:", pkg.Path)35 fmt.Println()36 }37 process := NewProcess(adb)38 processes, err := process.List()39 if err != nil {40 log.Fatal(err)41 }

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adbInst, err := adb.New()4 if err != nil {5 log.Fatal(err)6 }7 devices, err := adbInst.Devices()8 if err != nil {9 log.Fatal(err)10 }11 err = device.Copy("/sdcard/test.txt", "test.txt")12 if err != nil {13 log.Fatal(err)14 }15 fmt.Println("File copied")16}17import (18func main() {19 adbInst, err := adb.New()20 if err != nil {21 log.Fatal(err)22 }23 devices, err := adbInst.Devices()24 if err != nil {25 log.Fatal(err)26 }27 err = device.Push("test.txt", "/sdcard/test.txt")28 if err != nil {29 log.Fatal(err)30 }31 fmt.Println("File copied")32}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 dir, err := os.Getwd()4 if err != nil {5 logrus.Fatal(err)6 }7 fmt.Println(dir)8 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {9 if info.IsDir() {10 }11 if strings.HasSuffix(info.Name(), ".go") {12 file, err := os.Open(path)13 if err != nil {14 logrus.Fatal(err)15 }16 defer file.Close()17 utf8Reader := transform.NewReader(file, simplifiedchinese.GBK.NewDecoder())18 content, err := ioutil.ReadAll(utf8Reader)19 if err != nil {20 logrus.Fatal(err)21 }22 ioutil.WriteFile(path, content, os.ModePerm)23 }24 })25}26import (27func main() {28 dir, err := os.Getwd()29 if err != nil {30 logrus.Fatal(err)31 }32 fmt.Println(dir)33 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {34 if info.IsDir() {35 }

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 js, err := joystick.Open(0)4 if err != nil {5 panic(err)6 }7 defer js.Close()8 state, err := js.Read()9 if err != nil {10 panic(err)11 }12 pretty.Println(state)13 for {14 state, err = js.Read()15 if err != nil {16 panic(err)17 }18 if state.Buttons[0] {19 fmt.Println("Button 0 pressed")20 }21 if state.Buttons[1] {22 fmt.Println("Button 1 pressed")23 }24 }25}26import (27func main() {28 js, err := joystick.Open(0)29 if err != nil {30 panic(err)31 }32 defer js.Close()33 state, err := js.Read()34 if err != nil {35 panic(err)36 }37 pretty.Println(state)38 for {39 state, err = js.Read()40 if err != nil {41 panic(err)42 }43 if state.Buttons[0] {44 fmt.Println("Button 0 pressed")45 }46 if state.Buttons[1] {47 fmt.Println("Button 1 pressed")48 }49 }50}51import (52func main() {53 js, err := joystick.Open(0)54 if err != nil {55 panic(err)56 }57 defer js.Close()58 state, err := js.Read()59 if err != nil {60 panic(err)61 }62 pretty.Println(state)63 for {64 state, err = js.Read()65 if err != nil {66 panic(err)67 }

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful