How to use waitForSSH method of adb Package

Best Syzkaller code snippet using adb.waitForSSH

adb.go

Source:adb.go Github

copy

Full Screen

1// Copyright 2015 syzkaller project authors. All rights reserved.2// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.3// +build !ppc64le4package adb5import (6 "bytes"7 "fmt"8 "io"9 "io/ioutil"10 "os"11 "os/exec"12 "path/filepath"13 "regexp"14 "sync"15 "time"16 . "github.com/google/syzkaller/log"17 "github.com/google/syzkaller/vm"18)19func init() {20 vm.Register("adb", ctor)21}22type instance struct {23 cfg *vm.Config24 console string25 closed chan bool26}27func ctor(cfg *vm.Config) (vm.Instance, error) {28 inst := &instance{29 cfg: cfg,30 closed: make(chan bool),31 }32 closeInst := inst33 defer func() {34 if closeInst != nil {35 closeInst.Close()36 }37 }()38 if err := validateConfig(cfg); err != nil {39 return nil, err40 }41 if err := inst.repair(); err != nil {42 return nil, err43 }44 inst.console = findConsole(inst.cfg.Bin, inst.cfg.Device)45 if err := inst.checkBatteryLevel(); err != nil {46 return nil, err47 }48 // Remove temp files from previous runs.49 inst.adb("shell", "rm -Rf /data/syzkaller*")50 closeInst = nil51 return inst, nil52}53func validateConfig(cfg *vm.Config) error {54 if cfg.Bin == "" {55 cfg.Bin = "adb"56 }57 if !regexp.MustCompile("[0-9A-F]+").MatchString(cfg.Device) {58 return fmt.Errorf("invalid adb device id '%v'", cfg.Device)59 }60 return nil61}62var (63 consoleCacheMu sync.Mutex64 consoleToDev = make(map[string]string)65 devToConsole = make(map[string]string)66)67// findConsole returns console file associated with the dev device (e.g. /dev/ttyUSB0).68// This code was tested with Suzy-Q and Android Serial Cable (ASC). For Suzy-Q see:69// https://chromium.googlesource.com/chromiumos/platform/ec/+/master/docs/case_closed_debugging.md70// The difference between Suzy-Q and ASC is that ASC is a separate cable,71// so it is not possible to match USB bus/port used by adb with the serial console device;72// while Suzy-Q console uses the same USB calbe as adb.73// The overall idea is as follows. We use 'adb shell' to write a unique string onto console,74// then we read from all console devices and see on what console the unique string appears.75func findConsole(adb, dev string) string {76 consoleCacheMu.Lock()77 defer consoleCacheMu.Unlock()78 if con := devToConsole[dev]; con != "" {79 return con80 }81 con, err := findConsoleImpl(adb, dev)82 if err != nil {83 Logf(0, "failed to associate adb device %v with console: %v", dev, err)84 Logf(0, "falling back to 'adb shell dmesg -w'")85 Logf(0, "note: some bugs may be detected as 'lost connection to test machine' with no kernel output")86 con = "adb"87 devToConsole[dev] = con88 return con89 }90 devToConsole[dev] = con91 consoleToDev[con] = dev92 Logf(0, "associating adb device %v with console %v", dev, con)93 return con94}95func findConsoleImpl(adb, dev string) (string, error) {96 consoles, err := filepath.Glob("/dev/ttyUSB*")97 if err != nil {98 return "", fmt.Errorf("failed to list /dev/ttyUSB devices: %v", err)99 }100 output := make(map[string]*[]byte)101 errors := make(chan error, len(consoles))102 done := make(chan bool)103 for _, con := range consoles {104 if consoleToDev[con] != "" {105 continue106 }107 out := new([]byte)108 output[con] = out109 go func(con string) {110 tty, err := vm.OpenConsole(con)111 if err != nil {112 errors <- err113 return114 }115 defer tty.Close()116 go func() {117 <-done118 tty.Close()119 }()120 *out, _ = ioutil.ReadAll(tty)121 errors <- nil122 }(con)123 }124 if len(output) == 0 {125 return "", fmt.Errorf("no unassociated console devices left")126 }127 time.Sleep(500 * time.Millisecond)128 unique := fmt.Sprintf(">>>%v<<<", dev)129 cmd := exec.Command(adb, "-s", dev, "shell", "echo", "\"", unique, "\"", ">", "/dev/kmsg")130 if out, err := cmd.CombinedOutput(); err != nil {131 return "", fmt.Errorf("failed to run adb shell: %v\n%s", err, out)132 }133 time.Sleep(500 * time.Millisecond)134 close(done)135 var anyErr error136 for range output {137 err := <-errors138 if anyErr == nil && err != nil {139 anyErr = err140 }141 }142 con := ""143 for con1, out := range output {144 if bytes.Contains(*out, []byte(unique)) {145 if con == "" {146 con = con1147 } else {148 anyErr = fmt.Errorf("device is associated with several consoles: %v and %v", con, con1)149 }150 }151 }152 if con == "" {153 if anyErr != nil {154 return "", anyErr155 }156 return "", fmt.Errorf("no console is associated with this device")157 }158 return con, nil159}160func (inst *instance) Forward(port int) (string, error) {161 // If 35099 turns out to be busy, try to forward random ports several times.162 devicePort := 35099163 if _, err := inst.adb("reverse", fmt.Sprintf("tcp:%v", devicePort), fmt.Sprintf("tcp:%v", port)); err != nil {164 return "", err165 }166 return fmt.Sprintf("127.0.0.1:%v", devicePort), nil167}168func (inst *instance) adb(args ...string) ([]byte, error) {169 if inst.cfg.Debug {170 Logf(0, "executing adb %+v", args)171 }172 rpipe, wpipe, err := os.Pipe()173 if err != nil {174 return nil, fmt.Errorf("failed to create pipe: %v", err)175 }176 defer wpipe.Close()177 defer rpipe.Close()178 cmd := exec.Command(inst.cfg.Bin, append([]string{"-s", inst.cfg.Device}, args...)...)179 cmd.Stdout = wpipe180 cmd.Stderr = wpipe181 if err := cmd.Start(); err != nil {182 return nil, err183 }184 wpipe.Close()185 done := make(chan bool)186 go func() {187 select {188 case <-time.After(time.Minute):189 if inst.cfg.Debug {190 Logf(0, "adb hanged")191 }192 cmd.Process.Kill()193 case <-done:194 }195 }()196 if err := cmd.Wait(); err != nil {197 close(done)198 out, _ := ioutil.ReadAll(rpipe)199 if inst.cfg.Debug {200 Logf(0, "adb failed: %v\n%s", err, out)201 }202 return nil, fmt.Errorf("adb %+v failed: %v\n%s", args, err, out)203 }204 close(done)205 if inst.cfg.Debug {206 Logf(0, "adb returned")207 }208 out, _ := ioutil.ReadAll(rpipe)209 return out, nil210}211func (inst *instance) repair() error {212 // Assume that the device is in a bad state initially and reboot it.213 // Ignore errors, maybe we will manage to reboot it anyway.214 inst.waitForSsh()215 // History: adb reboot episodically hangs, so we used a more reliable way:216 // using syz-executor to issue reboot syscall. However, this has stopped217 // working, probably due to the introduction of seccomp. Therefore,218 // we revert this to `adb shell reboot` in the meantime, until a more219 // reliable solution can be sought out.220 if _, err := inst.adb("shell", "reboot"); err != nil {221 return err222 }223 // Now give it another 5 minutes to boot.224 if !vm.SleepInterruptible(10 * time.Second) {225 return fmt.Errorf("shutdown in progress")226 }227 if err := inst.waitForSsh(); err != nil {228 return err229 }230 // Switch to root for userdebug builds.231 inst.adb("root")232 if err := inst.waitForSsh(); err != nil {233 return err234 }235 return nil236}237func (inst *instance) waitForSsh() error {238 var err error239 for i := 0; i < 300; i++ {240 if !vm.SleepInterruptible(time.Second) {241 return fmt.Errorf("shutdown in progress")242 }243 if _, err = inst.adb("shell", "pwd"); err == nil {244 return nil245 }246 }247 return fmt.Errorf("instance is dead and unrepairable: %v", err)248}249func (inst *instance) checkBatteryLevel() error {250 const (251 minLevel = 20252 requiredLevel = 30253 )254 val, err := inst.getBatteryLevel(30)255 if err != nil {256 return err257 }258 if val >= minLevel {259 Logf(0, "device %v: battery level %v%%, OK", inst.cfg.Device, val)260 return nil261 }262 for {263 Logf(0, "device %v: battery level %v%%, waiting for %v%%", inst.cfg.Device, val, requiredLevel)264 if !vm.SleepInterruptible(time.Minute) {265 return nil266 }267 val, err = inst.getBatteryLevel(0)268 if err != nil {269 return err270 }271 if val >= requiredLevel {272 break273 }274 }275 return nil276}277func (inst *instance) getBatteryLevel(numRetry int) (int, error) {278 out, err := inst.adb("shell", "dumpsys battery | grep level:")279 // allow for retrying for devices that does not boot up so fast280 for ; numRetry >= 0 && err != nil; numRetry-- {281 if numRetry > 0 {282 // sleep for 5 seconds before retrying283 time.Sleep(5 * time.Second)284 out, err = inst.adb("shell", "dumpsys battery | grep level:")285 } else {286 if err != nil {287 return 0, err288 }289 }290 }291 val := 0292 for _, c := range out {293 if c >= '0' && c <= '9' {294 val = val*10 + int(c) - '0'295 continue296 }297 if val != 0 {298 break299 }300 }301 if val == 0 {302 return 0, fmt.Errorf("failed to parse 'dumpsys battery' output: %s", out)303 }304 return val, nil305}306func (inst *instance) Close() {307 close(inst.closed)308 os.RemoveAll(inst.cfg.Workdir)309}310func (inst *instance) Copy(hostSrc string) (string, error) {311 vmDst := filepath.Join("/data", filepath.Base(hostSrc))312 if _, err := inst.adb("push", hostSrc, vmDst); err != nil {313 return "", err314 }315 return vmDst, nil316}317func (inst *instance) Run(timeout time.Duration, stop <-chan bool, command string) (<-chan []byte, <-chan error, error) {318 var tty io.ReadCloser319 var err error320 if inst.console == "adb" {321 tty, err = vm.OpenAdbConsole(inst.cfg.Bin, inst.cfg.Device)322 } else {323 tty, err = vm.OpenConsole(inst.console)324 }325 if err != nil {326 return nil, nil, err327 }328 adbRpipe, adbWpipe, err := vm.LongPipe()329 if err != nil {330 tty.Close()331 return nil, nil, err332 }333 if inst.cfg.Debug {334 Logf(0, "starting: adb shell %v", command)335 }336 adb := exec.Command(inst.cfg.Bin, "-s", inst.cfg.Device, "shell", "cd /data; "+command)337 adb.Stdout = adbWpipe338 adb.Stderr = adbWpipe339 if err := adb.Start(); err != nil {340 tty.Close()341 adbRpipe.Close()342 adbWpipe.Close()343 return nil, nil, fmt.Errorf("failed to start adb: %v", err)344 }345 adbWpipe.Close()346 var tee io.Writer347 if inst.cfg.Debug {348 tee = os.Stdout349 }350 merger := vm.NewOutputMerger(tee)351 merger.Add("console", tty)352 merger.Add("adb", adbRpipe)353 errc := make(chan error, 1)354 signal := func(err error) {355 select {356 case errc <- err:357 default:358 }359 }360 go func() {361 select {362 case <-time.After(timeout):363 signal(vm.TimeoutErr)364 case <-stop:365 signal(vm.TimeoutErr)366 case <-inst.closed:367 if inst.cfg.Debug {368 Logf(0, "instance closed")369 }370 signal(fmt.Errorf("instance closed"))371 case err := <-merger.Err:372 adb.Process.Kill()373 tty.Close()374 merger.Wait()375 if cmdErr := adb.Wait(); cmdErr == nil {376 // If the command exited successfully, we got EOF error from merger.377 // But in this case no error has happened and the EOF is expected.378 err = nil379 }380 signal(err)381 return382 }383 adb.Process.Kill()384 tty.Close()385 merger.Wait()386 adb.Wait()387 }()388 return merger.Output, errc, nil389}...

Full Screen

Full Screen

waitForSSH

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adb := adb.New()4 adb.WaitForSSH()5 fmt.Println("waitForSSH method is working fine")6 adb.WaitForDevice()7 fmt.Println("waitForDevice method is working fine")8 adb.WaitForRecovery()9 fmt.Println("waitForRecovery method is working fine")10 adb.WaitForBootloader()11 fmt.Println("waitForBootloader method is working fine")12 adb.WaitForDeviceNotPresent()13 fmt.Println("waitForDeviceNotPresent method is working fine")14 adb.WaitForDeviceAbsent()15 fmt.Println("waitForDeviceAbsent method is working fine")16}

Full Screen

Full Screen

waitForSSH

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 winmanifest.SetAppUserModelID("org.example.yourappname")4 err := ui.Main(func() {5 button := ui.NewButton("Click Me")6 button.OnClicked(func(*ui.Button) {

Full Screen

Full Screen

waitForSSH

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adb := Adb{4 }5 err := adb.waitForSSH()6 if err != nil {7 log.Fatal(err)8 }9 fmt.Println("SSH is now available")10}11import (12func main() {13 adb := Adb{14 }15 err := adb.waitForDevice()16 if err != nil {17 log.Fatal(err)18 }19 fmt.Println("Device is now available")20}21import (22func main() {23 adb := Adb{24 }25 err := adb.waitForEmulator()26 if err != nil {27 log.Fatal(err)28 }29 fmt.Println("Emulator is now available")30}31import (32func main() {33 adb := Adb{34 }35 err := adb.waitForDeviceOffline()36 if err != nil {37 log.Fatal(err)38 }39 fmt.Println("Device is now offline")40}41import (42func main() {43 adb := Adb{44 }45 err := adb.waitForEmulatorToStop()46 if err != nil {47 log.Fatal(err)48 }49 fmt.Println("Emulator is now stopped")50}

Full Screen

Full Screen

waitForSSH

Using AI Code Generation

copy

Full Screen

1public class Adb {2 public static void main(String[] args) throws InterruptedException {3 waitForSSH(5);4 }5 public static void waitForSSH(int timeout) throws InterruptedException {6 String cmd = "adb shell exit";7 Process proc = null;8 boolean isReady = false;9 int counter = 0;10 while (!isReady && counter < timeout) {11 try {12 proc = Runtime.getRuntime().exec(cmd);13 proc.waitFor();14 isReady = true;15 } catch (IOException e) {16 System.out.println("Device not ready yet");17 Thread.sleep(1000);18 counter++;19 }20 }21 if (isReady) {22 System.out.println("Device is ready");23 } else {24 System.out.println("Device is not ready");25 }26 }27}

Full Screen

Full Screen

waitForSSH

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adbInstance := adb.New()4 deviceList, err := adbInstance.GetDevices()5 if err != nil {6 fmt.Println("Error in getting devices", err)7 }8 for _, device := range deviceList {9 serialNumber := device.GetSerialNumber()10 if device.IsConnected() {11 if device.IsRecovery() {12 if device.IsFastboot() {13 if device.IsBootloader() {14 if device.IsSideload() {15 if device.IsSideload() {16 if device.IsSideload() {17 if device.IsSideload() {18 if device.IsSideload() {19 if device.IsSideload() {20 if device.IsSideload() {21 if device.IsSideload() {22 if device.IsSideload() {23 if device.IsSideload() {24 if device.IsSideload() {25 if device.IsSideload() {26 if device.IsSideload() {

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