How to use parseAdbOutToInt method of adb Package

Best Syzkaller code snippet using adb.parseAdbOutToInt

adb.go

Source:adb.go Github

copy

Full Screen

...158 consoleCacheMu sync.Mutex159 consoleToDev = make(map[string]string)160 devToConsole = make(map[string]string)161)162func parseAdbOutToInt(out []byte) int {163 val := 0164 for _, c := range out {165 if c >= '0' && c <= '9' {166 val = val*10 + int(c) - '0'167 continue168 }169 if val != 0 {170 break171 }172 }173 return val174}175// findConsole returns console file associated with the dev device (e.g. /dev/ttyUSB0).176// This code was tested with Suzy-Q and Android Serial Cable (ASC). For Suzy-Q see:177// https://chromium.googlesource.com/chromiumos/platform/ec/+/master/docs/case_closed_debugging.md178// The difference between Suzy-Q and ASC is that ASC is a separate cable,179// so it is not possible to match USB bus/port used by adb with the serial console device;180// while Suzy-Q console uses the same USB calbe as adb.181// The overall idea is as follows. We use 'adb shell' to write a unique string onto console,182// then we read from all console devices and see on what console the unique string appears.183func findConsole(adb, dev string) string {184 consoleCacheMu.Lock()185 defer consoleCacheMu.Unlock()186 if con := devToConsole[dev]; con != "" {187 return con188 }189 con, err := findConsoleImpl(adb, dev)190 if err != nil {191 log.Logf(0, "failed to associate adb device %v with console: %v", dev, err)192 log.Logf(0, "falling back to 'adb shell dmesg -w'")193 log.Logf(0, "note: some bugs may be detected as 'lost connection to test machine' with no kernel output")194 con = "adb"195 devToConsole[dev] = con196 return con197 }198 devToConsole[dev] = con199 consoleToDev[con] = dev200 return con201}202func findConsoleImpl(adb, dev string) (string, error) {203 // Attempt to find an exact match, at /dev/ttyUSB.{SERIAL}204 // This is something that can be set up on Linux via 'udev' rules205 exactCon := "/dev/ttyUSB." + dev206 if osutil.IsExist(exactCon) {207 return exactCon, nil208 }209 // Search all consoles, as described in 'findConsole'210 consoles, err := filepath.Glob("/dev/ttyUSB*")211 if err != nil {212 return "", fmt.Errorf("failed to list /dev/ttyUSB devices: %v", err)213 }214 output := make(map[string]*[]byte)215 errors := make(chan error, len(consoles))216 done := make(chan bool)217 for _, con := range consoles {218 if consoleToDev[con] != "" {219 continue220 }221 out := new([]byte)222 output[con] = out223 go func(con string) {224 tty, err := vmimpl.OpenConsole(con)225 if err != nil {226 errors <- err227 return228 }229 defer tty.Close()230 go func() {231 <-done232 tty.Close()233 }()234 *out, _ = ioutil.ReadAll(tty)235 errors <- nil236 }(con)237 }238 if len(output) == 0 {239 return "", fmt.Errorf("no unassociated console devices left")240 }241 time.Sleep(500 * time.Millisecond)242 unique := fmt.Sprintf(">>>%v<<<", dev)243 cmd := osutil.Command(adb, "-s", dev, "shell", "echo", "\"<1>", unique, "\"", ">", "/dev/kmsg")244 if out, err := cmd.CombinedOutput(); err != nil {245 return "", fmt.Errorf("failed to run adb shell: %v\n%s", err, out)246 }247 time.Sleep(500 * time.Millisecond)248 close(done)249 var anyErr error250 for range output {251 err := <-errors252 if anyErr == nil && err != nil {253 anyErr = err254 }255 }256 con := ""257 for con1, out := range output {258 if bytes.Contains(*out, []byte(unique)) {259 if con == "" {260 con = con1261 } else {262 anyErr = fmt.Errorf("device is associated with several consoles: %v and %v", con, con1)263 }264 }265 }266 if con == "" {267 if anyErr != nil {268 return "", anyErr269 }270 return "", fmt.Errorf("no console is associated with this device")271 }272 return con, nil273}274func (inst *instance) Forward(port int) (string, error) {275 var err error276 for i := 0; i < 1000; i++ {277 devicePort := vmimpl.RandomPort()278 _, err = inst.adb("reverse", fmt.Sprintf("tcp:%v", devicePort), fmt.Sprintf("tcp:%v", port))279 if err == nil {280 return fmt.Sprintf("127.0.0.1:%v", devicePort), nil281 }282 }283 return "", err284}285func (inst *instance) adb(args ...string) ([]byte, error) {286 return inst.adbWithTimeout(time.Minute, args...)287}288func (inst *instance) adbWithTimeout(timeout time.Duration, args ...string) ([]byte, error) {289 if inst.debug {290 log.Logf(0, "executing adb %+v", args)291 }292 args = append([]string{"-s", inst.device}, args...)293 out, err := osutil.RunCmd(timeout, "", inst.adbBin, args...)294 if inst.debug {295 log.Logf(0, "adb returned")296 }297 return out, err298}299func (inst *instance) waitForBootCompletion() {300 // ADB connects to a phone and starts syz-fuzzer while the phone is still booting.301 // This enables syzkaller to create a race condition which in certain cases doesn't302 // allow the phone to finalize initialization.303 // To determine whether a system has booted and started all system processes and304 // services we wait for a process named 'com.android.systemui' to start. It's possible305 // that in the future a new devices which doesn't have 'systemui' process will be fuzzed306 // with adb, in this case this code should be modified with a new process name to search for.307 log.Logf(2, "waiting for boot completion")308 sleepTime := 5309 sleepDuration := time.Duration(sleepTime) * time.Second310 maxWaitTime := 60 * 3 // 3 minutes to wait until boot completion311 maxRetries := maxWaitTime / sleepTime312 i := 0313 for ; i < maxRetries; i++ {314 time.Sleep(sleepDuration)315 if out, err := inst.adb("shell", "pgrep systemui | wc -l"); err == nil {316 count := parseAdbOutToInt(out)317 if count != 0 {318 log.Logf(0, "boot completed")319 break320 }321 } else {322 log.Logf(0, "failed to execute command 'pgrep systemui | wc -l', %v", err)323 break324 }325 }326 if i == maxRetries {327 log.Logf(0, "failed to determine boot completion, can't find 'com.android.systemui' process")328 }329}330func (inst *instance) repair() error {331 // Assume that the device is in a bad state initially and reboot it.332 // Ignore errors, maybe we will manage to reboot it anyway.333 if inst.cfg.RepairScript != "" {334 if err := inst.runScript(inst.cfg.RepairScript); err != nil {335 return err336 }337 }338 inst.waitForSSH()339 // History: adb reboot episodically hangs, so we used a more reliable way:340 // using syz-executor to issue reboot syscall. However, this has stopped341 // working, probably due to the introduction of seccomp. Therefore,342 // we revert this to `adb shell reboot` in the meantime, until a more343 // reliable solution can be sought out.344 if inst.cfg.TargetReboot {345 if _, err := inst.adb("shell", "reboot"); err != nil {346 return err347 }348 // Now give it another 5 minutes to boot.349 if !vmimpl.SleepInterruptible(10 * time.Second) {350 return fmt.Errorf("shutdown in progress")351 }352 if err := inst.waitForSSH(); err != nil {353 return err354 }355 }356 // Switch to root for userdebug builds.357 inst.adb("root")358 inst.waitForSSH()359 inst.waitForBootCompletion()360 // Mount debugfs.361 if _, err := inst.adb("shell", "ls /sys/kernel/debug/kcov"); err != nil {362 log.Logf(2, "debugfs was unmounted mounting")363 // This prop only exist on Android 12+364 inst.adb("shell", "setprop persist.dbg.keep_debugfs_mounted 1")365 if _, err := inst.adb("shell", "mount -t debugfs debugfs /sys/kernel/debug "+366 "&& chmod 0755 /sys/kernel/debug"); err != nil {367 return err368 }369 }370 if inst.cfg.StartupScript != "" {371 if err := inst.runScript(inst.cfg.StartupScript); err != nil {372 return err373 }374 }375 return nil376}377func (inst *instance) runScript(script string) error {378 log.Logf(2, "adb: executing %s", script)379 // Execute the contents of the script.380 contents, err := ioutil.ReadFile(script)381 if err != nil {382 return fmt.Errorf("unable to read %s: %v", script, err)383 }384 c := string(contents)385 output, err := osutil.RunCmd(5*time.Minute, "", "sh", "-c", c)386 if err != nil {387 return fmt.Errorf("failed to execute %s: %v", script, err)388 }389 log.Logf(2, "adb: execute %s output\n%s", script, output)390 log.Logf(2, "adb: done executing %s", script)391 return nil392}393func (inst *instance) waitForSSH() error {394 if !vmimpl.SleepInterruptible(time.Second) {395 return fmt.Errorf("shutdown in progress")396 }397 if _, err := inst.adbWithTimeout(10*time.Minute, "wait-for-device"); err != nil {398 return fmt.Errorf("instance is dead and unrepairable: %v", err)399 }400 return nil401}402func (inst *instance) checkBatteryLevel() error {403 const (404 minLevel = 20405 requiredLevel = 30406 )407 val, err := inst.getBatteryLevel(30)408 if err != nil {409 return err410 }411 if val >= minLevel {412 log.Logf(0, "device %v: battery level %v%%, OK", inst.device, val)413 return nil414 }415 for {416 log.Logf(0, "device %v: battery level %v%%, waiting for %v%%", inst.device, val, requiredLevel)417 if !vmimpl.SleepInterruptible(time.Minute) {418 return nil419 }420 val, err = inst.getBatteryLevel(0)421 if err != nil {422 return err423 }424 if val >= requiredLevel {425 break426 }427 }428 return nil429}430func (inst *instance) getBatteryLevel(numRetry int) (int, error) {431 out, err := inst.adb("shell", "dumpsys battery | grep level:")432 // Allow for retrying for devices that does not boot up so fast.433 for ; numRetry >= 0 && err != nil; numRetry-- {434 if numRetry > 0 {435 // Sleep for 5 seconds before retrying.436 time.Sleep(5 * time.Second)437 out, err = inst.adb("shell", "dumpsys battery | grep level:")438 }439 }440 if err != nil {441 return 0, err442 }443 val := parseAdbOutToInt(out)444 if val == 0 {445 return 0, fmt.Errorf("failed to parse 'dumpsys battery' output: %s", out)446 }447 return val, nil448}449func (inst *instance) Close() {450 close(inst.closed)451}452func (inst *instance) Copy(hostSrc string) (string, error) {453 vmDst := filepath.Join("/data", filepath.Base(hostSrc))454 if _, err := inst.adb("push", hostSrc, vmDst); err != nil {455 return "", err456 }457 return vmDst, nil...

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2var (3func main() {4 winmanifest.SetAppID("adb")5 err := ui.Main(func() {6 button := ui.NewButton("Click me")7 button.OnClicked(func(*ui.Button) {8 ui.MsgBox(mainwin, "Confirmation", "Are you sure?")9 ui.Quit()10 })11 box := ui.NewVerticalBox()12 box.Append(button, false)13 mainwin = ui.NewWindow("adb", 200, 100, false)14 mainwin.SetMargined(true)15 mainwin.SetChild(box)16 mainwin.OnClosing(func(*ui.Window) bool {17 ui.Quit()18 })19 mainwin.Show()20 })21 if err != nil {22 log.Println(err)23 }24}25func parseAdbOutToInt(out []byte) int {26 output := string(out)27 output = strings.Replace(output, "28 output = strings.Replace(output, "\r", "", -1)29 output = strings.Replace(output, "\t", "", -1)30 output = strings.Replace(output, " ", "", -1)31 output = strings.Replace(output, ":", "", -1)32 output = strings.Replace(output, "%", "", -1)33 output = strings.Replace(output, "Battery", "", -1)34 output = strings.Replace(output, "level", "", -1)35 output = strings.Replace(output, "temperature", "", -1)36 output = strings.Replace(output, "health", "", -1)37 output = strings.Replace(output, "status", "", -1)38 output = strings.Replace(output, "voltage", "", -1)39 output = strings.Replace(output, "present", "", -1)40 output = strings.Replace(output, "charging", "", -1)41 output = strings.Replace(output, "technology", "", -1)42 output = strings.Replace(output, "scale", "", -

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adb := adb.NewAdb()4 adb.RunAdbCommand("devices")5 adb.RunAdbCommand("shell", "am", "start", "-n", "com.android.calculator2/.Calculator")6 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_3")7 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_2")8 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_1")9 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_2")10 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_3")11 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_4")12 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_5")13 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_6")14 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_7")15 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_8")16 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_9")17 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_0")18 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_EQUALS")19 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_2")20 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_1")21 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_2")22 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_3")23 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_4")24 adb.RunAdbCommand("shell", "input", "keyevent", "KEYCODE_5")25 adb.RunAdbCommand("shell", "input", "

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adbObj := adb.Adb{Path: "adb"}4 adbObj.ParseAdbOutToInt("adb", "shell", "getprop", "ro.build.version.sdk")5 fmt.Println(adbObj.SdkVer)6}

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, world.")4 adb := adb.Adb{}5 adb.Connect()6 adb.GetDeviceList()7 fmt.Println(adb.ParseAdbOutToInt(adb.AdbOut))8}9import (10type Adb struct {11}12func (adb *Adb) Connect() {13 cmd := exec.Command("adb", "connect", "

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adbInstance := adb.NewAdb()4 batteryLevel, err := adbInstance.GetBatteryLevel()5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(batteryLevel)9}10import (11type Adb struct {12}13func NewAdb() *Adb {14 return &Adb{}15}16func (a *Adb) GetBatteryLevel() (int, error) {17 out, err := exec.Command("adb", "shell", "dumpsys", "battery").Output()18 if err != nil {19 }20 return a.parseAdbOutToInt(string(out), "level: ")21}22func (a *Adb) parseAdbOutToInt(out string, key string) (int, error) {23 scanner := bufio.NewScanner(strings.NewReader(out))24 for scanner.Scan() {25 line := scanner.Text()26 if strings.Contains(line, key) {27 levelString := strings.Replace(line, key, "", 1)28 level, err := strconv.Atoi(levelString)29 if err != nil {30 }31 }32 }33 return 0, errors.New(fmt.Sprintf("key %s not found in adb output", key))34}

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adb := adb.NewAdb()4 devices := adb.Devices()5 x := adb.ParseAdbOutToInt(device.Shell("wm size"))6 y := adb.ParseAdbOutToInt(device.Shell("wm size"))7 fmt.Println("X:", x, "Y:", y)8}9import (10func main() {11 adb := adb.NewAdb()12 devices := adb.Devices()13 x := adb.ParseAdbOutToInt(device.Shell("wm size"))14 y := adb.ParseAdbOutToInt(device.Shell("wm size"))15 fmt.Println("X:", x, "Y:", y)16}17import (18func main() {19 adb := adb.NewAdb()20 devices := adb.Devices()21 x := adb.ParseAdbOutToInt(device.Shell("wm size"))22 y := adb.ParseAdbOutToInt(device.Shell("wm size"))23 fmt.Println("X:", x, "Y:", y)24}25import (26func main() {27 adb := adb.NewAdb()28 devices := adb.Devices()

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 a := adb.Adb{}4 a.Initialize()5 a.StartAdbServer()6 a.ConnectToAdb()7 a.StartApp("com.android.settings")8 a.WaitForActivity("com.android.settings.Settings")9 a.StopApp("com.android.settings")10 a.WaitForActivity("com.android.settings.Settings")11 a.PressHome()12 a.PressBack()13 a.PressMenu()14 a.PressSearch()15 a.PressVolumeUp()16 a.PressVolumeDown()17 a.PressVolumeMute()18 a.PressPower()19 a.PressCamera()

Full Screen

Full Screen

parseAdbOutToInt

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 adbObj := adb.NewAdb()4 adbObj.Connect()5 adbObj.GetDevices()6 adbObj.GetProperties()7 adbObj.GetProp("ro.build.version.sdk")8 fmt.Println("ro.build.version.sdk value is : ", adbObj.ParseAdbOutToInt())9}10import (11func main() {12 adbObj := adb.NewAdb()13 adbObj.Connect()14 adbObj.GetDevices()15 adbObj.GetProperties()16 adbObj.GetProp("ro.build.version.sdk")17 fmt.Println("ro.build.version.sdk value is : ", adbObj.ParseAdbOutToBool())18}19import (20func main() {21 adbObj := adb.NewAdb()22 adbObj.Connect()23 adbObj.GetDevices()24 adbObj.GetProperties()25 adbObj.GetProp("ro.build.version.sdk")26 fmt.Println("ro.build.version.sdk value is : ", adbObj.ParseAdbOutToString())27}28import (29func main() {30 adbObj := adb.NewAdb()31 adbObj.Connect()32 adbObj.GetDevices()33 adbObj.GetProperties()34 adbObj.GetProp("ro.build.version.sdk")35 fmt.Println("ro.build.version.sdk value is : ", adbObj.ParseAdbOutToFloat())36}

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