-
Notifications
You must be signed in to change notification settings - Fork 55
/
device.py
370 lines (296 loc) · 11.1 KB
/
device.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""
Author: Roee Hay / Aleph Research / HCL Technologies
"""
import os
import re
from serializable import Serializable
from adb import fastboot,common,usb_exceptions,adb_commands, sign_m2crypto
from log import *
from config import Config
from enum import Enum
import time
import usb1
import subprocess
class Device:
def __init__(self, serial=None):
self.connected = False
self.fb = None
self.data = DeviceData()
self.usbdev = None
self.last_output = None
self.set_state(State.DISCONNECTED)
self.serial = serial
self.fb_error = None
self.fb_error_timeout = False
@staticmethod
def get_fastboot_devices():
return common.UsbHandle.FindDevices(fastboot.DeviceIsAvailable, timeout_ms=Config.timeout)
@staticmethod
def get_adb_devices():
return common.UsbHandle.FindDevices(adb_commands.DeviceIsAvailable, timeout_ms=Config.timeout)
def find_fastboot_device(self):
return self.find_device(Device.get_fastboot_devices())
def find_adb_device(self):
return self.find_device(Device.get_adb_devices())
def find_device(self, devices):
i = 0
for d in devices:
i += 1
if not self.serial or d.serial_number == self.serial:
return d
return
"""
Reboots to bootloaders. First it tries to use python-adb, falling back to the adb binary.
"""
def adb_reboot_bootloader(self):
I("adb: rebooting to bootloader")
try:
self.adb().RebootBootloader()
return
except UnicodeDecodeError:
# https://github.com/google/python-adb/issues/52
D("python-adb bug, falling-back to adb bin")
except usb_exceptions.WriteFailedError:
# Happens when adb server is running
D("adb server is running, cannot use python-adb, falling-back to adb bin")
# fall-backs to adb binary
if self.serial and re.match(r"\w+", self.serial()):
adb_cmd = Config.adb_path + " -s %s reboot bootloader 2>/dev/null" % self.serial
else:
adb_cmd = Config.adb_path + " reboot bootloader 2>/dev/null"
os.system(adb_cmd)
time.sleep(5)
self.set_state(State.DISCONNECTED)
"""
Wait for the device to be connected in either fastboot or adb.
"""
def wait_for_device(self):
while State.DISCONNECTED == self.state:
usbdev = self.find_fastboot_device()
if None != usbdev:
try:
usbdev.Open()
I("fastboot connected to %s", usbdev.serial_number)
except usb1.USBError as e:
usbdev.Close()
time.sleep(5)
continue
self.usbdev = usbdev
self.set_state(State.CONNECTED_FB)
continue
usbdev = self.find_adb_device()
if None != usbdev:
try:
usbdev.Open()
I("adb: connected")
self.set_state(State.CONNECTED_ADB_DEVICE)
except usb1.USBErrorBusy as e:
self.set_state(self.adb_get_state())
if State.CONNECTED_ADB_DEVICE == self.state:
I("adb: connected")
except usb1.USBError:
usbdev.Close()
time.sleep(5)
continue
self.usbdev = usbdev
continue
I("Waiting for device...")
time.sleep(5)
"""
Waits for the device to be in fastboot mode. If it's in adb, it will reboot it to bootloader
"""
def wait_for_fastboot(self):
while State.CONNECTED_FB != self.state:
if State.CONNECTED_ADB_DEVICE == self.state:
self.adb_reboot_bootloader()
self.wait_for_device()
if State.DISCONNECTED == self.state:
self.wait_for_device()
def adb(self):
signer = sign_m2crypto.M2CryptoSigner(os.path.expanduser(Config.adb_key_path))
return adb_commands.AdbCommands.Connect(self.usbdev, rsa_keys=[signer])
def fastboot(self):
return fastboot.FastbootCommands(self.usbdev)
def serial_number(self):
self.wait_for_device()
return self.usbdev.serial_number
def get_last_fb_output(self):
return self.last_output.get()
"""
Conduct a single fastboot command
"""
def do_fb_command(self, func, allow_timeout=False, *args, **kargs):
self.wait_for_fastboot()
self.last_output = CmdLogger()
try:
getattr(self.fastboot(), func)(info_cb=self.last_output, *args, **kargs)
return self.last_output.get()
except fastboot.FastbootRemoteFailure as e:
r = self.get_last_fb_output()
msg = e.args[1]
raise FastbootRemoteFailure(msg)
except fastboot.FastbootStateMismatch as e:
W("fastboot state mistmatch")
self.disconnect()
raise FastbootUSBException("")
except usb_exceptions.LibusbWrappingError as e:
if "LIBUSB_ERROR_TIMEOUT" in str(e.usb_error):
if allow_timeout:
D("Allowed timeout during FB command: %s, args = %s, kargs = %s", func, str(*args), str(**kargs))
raise FastbootTimeoutException()
D("timeout during FB command: %s, args = %s, kargs = %s", func, str(*args), str(**kargs))
self.disconnect()
raise FastbootUSBException(e.usb_error)
"""
Conduct a fastboot command until success (handles USB disconnections etc).
It first resolves (if needed) the command not found error, by issuing a bogus command.
"""
def wait_for_fb_command(self, func, allow_timeout = False, allow_usb_error = False, *args, **kargs):
while True:
try:
self.resolve_fb_error()
return self.do_fb_command(func, allow_timeout, *args, **kargs)
except FastbootUSBException as e:
if allow_usb_error:
raise e
W("USB Error (%s) detected during command: %s, args = %s, kargs = %s", e.msg, func, str(*args),
str(**kargs))
def set_state(self, state):
self.state = state
"""
Disconnect the device and clean-up everything.
"""
def disconnect(self):
self.clear_fb_error()
self.set_state(State.DISCONNECTED)
if None != self.usbdev:
self.usbdev.Close()
self.usbdev = None
"""
Issue a fastboot oem command.
"""
def oem(self, cmd, allow_timeout=False, allow_usb_error = False):
try:
r = self.wait_for_fb_command("Oem", allow_timeout, allow_usb_error, cmd)
if self.is_fb_error(r, cmd):
raise FastbootCommandNotFound()
return r
except FastbootTimeoutException:
if self.fb_error_timeout:
raise FastbootCommandNotFound()
raise FastbootTimeoutException
except FastbootRemoteFailure, e:
r = self.get_last_fb_output()
error = e.msg
if self.is_fb_error(error+r, cmd):
raise FastbootCommandNotFound()
raise FastbootRemoteFailure(error)
"""
Get a remote variable through fastboot
"""
def getvar(self, k):
try:
return self.data[k]
except KeyError:
try:
self.data[k] = self.wait_for_fb_command("Getvar", False, False, k)
except fastboot.FastbootRemoteFailure:
return ""
return self.data[k]
def product(self):
return self.getvar("product")
def unlocked(self):
return self.getvar("unlocked")
def oemprojectname(self):
return self.getvar("oem_project_name")
"""
Try to resolve the bootloader name according to hints from fastboot info
"""
def bootloader_name(self):
p = self.product()
# OnePlus devices
if p.startswith("msm") and self.oemprojectname():
return self.oemprojectname()
return p
"""
Resolve the real device name
"""
def device(self):
try:
return Config.bootloader_names[self.bootloader_name()]
except KeyError:
return self.bootloader_name()
"""
Query the ADB state
"""
def adb_get_state(self):
try:
output = subprocess.check_output([Config.adb_path, "get-state"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return State.DISCONNECTED
if "device" in output:
return State.CONNECTED_ADB_DEVICE
return State.DISCONNECTED
def clear_fb_error(self):
self.fb_error_timeout = False
self.fb_error = None
"""
Resolve the fastboot command not found error by issuing a bogus command.
Some devices do not return when issuing a non-existing command, we handle those too.
"""
def resolve_fb_error(self):
if None != self.fb_error:
return
try:
self.fb_error = self.do_fb_command("Oem", True, Config.oem_error_cmd)
except FastbootRemoteFailure as e:
self.fb_error = e.msg + self.get_last_fb_output()
except FastbootTimeoutException as e:
D("Error is indicated by USB timeout")
self.fb_error_timeout = True
return
self.fb_error = self.normalize_fb_error(self.fb_error)
D("Error str: " + self.fb_error)
"""
Classifies whether a given response for a command indicates it's a non-existing one.
"""
def is_fb_error(self, msg, cmd):
cmd = self.normalize_fb_error(cmd)
msg = self.normalize_fb_error(msg)
if msg == self.fb_error:
return True
if self.normalize_fb_error(self.fb_error.replace(Config.oem_error_cmd, cmd)) == msg:
return True
if self.normalize_fb_error(self.fb_error.replace(Config.oem_error_cmd, re.split("\s", cmd)[0])) == msg:
return True
return False
@staticmethod
def normalize_fb_error(error):
try:
return error.replace("\n", "").lower()
except UnicodeDecodeError:
return error
class FastbootException(Exception): pass
class FastbootNotConnectedException(FastbootException): pass
class FastbootTimeoutException(FastbootException): pass
class FastbootCommandNotFound(FastbootException): pass
class FastbootFatalError(FastbootException): pass
class FastbootRemoteFailure(FastbootException):
def __init__(self, msg):
self.msg = msg
class FastbootUSBException(FastbootException):
def __init__(self, msg):
self.msg = msg
class DeviceData(Serializable):
pass
class CmdLogger:
def __init__(self):
self.output = []
def __call__(self, fbmsg):
self.output.append(fbmsg.message)
def get(self):
return "\n".join(self.output)
class State(Enum):
DISCONNECTED = 0,
CONNECTED_FB = 1,
CONNECTED_ADB_DEVICE = 2