Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
|
ppi
2015/07/09 13:12:40
please add a top-level pydoc explaining what this
etiennej
2015/07/15 07:13:21
I gave a high-level description, and put the detai
| |
| 5 import logging | |
| 6 import gdb | |
| 7 import glob | |
| 8 import itertools | |
| 9 import os | |
| 10 import os.path | |
| 11 import shutil | |
| 12 import subprocess | |
| 13 import sys | |
| 14 import tempfile | |
| 15 import time | |
| 16 | |
| 17 FILE = __file__ | |
|
ppi
2015/07/09 13:12:39
Why? __file__ is a known thing, should we stick wi
etiennej
2015/07/15 07:13:20
There was an issue with __file__ not being defined
| |
| 18 | |
| 19 sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(FILE)))) | |
| 20 import android_gdb.config as config | |
| 21 from android_gdb.remote_file_connection import RemoteFileConnection | |
| 22 | |
| 23 | |
| 24 def _GetDirAbove(dirname): | |
|
ppi
2015/07/09 13:12:39
Let's make this return None if the dir is not foun
ppi
2015/07/09 13:12:39
_get_dir_above
ppi
2015/07/09 13:12:40
Can you infer all paths in `debugger` and always p
etiennej
2015/07/15 07:13:20
Done.
| |
| 25 """Returns the directory "above" this file containing |dirname|.""" | |
| 26 path = os.path.abspath(FILE) | |
| 27 while True: | |
| 28 path, _ = os.path.split(path) | |
| 29 assert path | |
| 30 if dirname in os.listdir(path): | |
| 31 return path | |
| 32 | |
| 33 | |
| 34 def gdb_execute(command): | |
|
ppi
2015/07/09 13:12:40
_gdb_execute?
etiennej
2015/07/15 07:13:20
Done.
| |
| 35 """Executes a GDB command.""" | |
| 36 return gdb.execute(command, to_string=True) | |
| 37 | |
| 38 | |
| 39 class Mapping(object): | |
|
ppi
2015/07/09 13:12:39
Please add a pydoc - what does a "Mapping" represe
etiennej
2015/07/15 07:13:20
Done.
| |
| 40 def __init__(self, line): | |
| 41 self.start = int(line[0], 16) | |
| 42 self.end = int(line[1], 16) | |
| 43 self.size = int(line[2], 16) | |
| 44 self.offset = int(line[3], 16) | |
| 45 self.filename = line[4] | |
| 46 | |
| 47 | |
| 48 def get_mapped_files(): | |
|
ppi
2015/07/09 13:12:39
Please describe the output format / value.
ppi
2015/07/09 13:12:40
_get_mapped_files?
etiennej
2015/07/15 07:13:20
Done.
etiennej
2015/07/15 07:13:20
Done.
| |
| 49 mappings = [Mapping(x) for x in | |
| 50 [x.split() for x in | |
| 51 gdb_execute("info proc map").split('\n')] | |
| 52 if len(x) == 5 and x[4][0] == '/'] | |
|
ppi
2015/07/09 13:12:39
Please explain what's happening here - example ret
etiennej
2015/07/15 07:13:20
Done.
| |
| 53 res = {} | |
| 54 for m in mappings: | |
| 55 libname = m.filename[m.filename.rfind('/') + 1:] | |
| 56 res[libname] = res.get(libname, []) + [m] | |
| 57 return res.values() | |
| 58 | |
| 59 | |
| 60 class DebugSession(object): | |
| 61 def __init__(self, | |
| 62 build_directory=None, | |
| 63 package_name='org.chromium.mojo.shell', | |
|
ppi
2015/07/09 13:12:39
Let's push this default up to `debugger`? It's lik
etiennej
2015/07/15 07:13:20
Done.
| |
| 64 adb='adb', | |
| 65 pyelftools_dir=None): | |
| 66 if build_directory == None: | |
| 67 self.build_directory = os.path.join( | |
| 68 _GetDirAbove('out'), 'out', 'android_Debug') | |
| 69 else: | |
| 70 self.build_directory = build_directory | |
| 71 if not os.path.exists(self.build_directory): | |
| 72 logging.fatal("Please pass a valid build directory") | |
| 73 sys.exit(1) | |
| 74 self.package_name = package_name | |
| 75 self.adb = adb | |
| 76 self.remote_file_cache = os.path.join(os.getenv('HOME'), '.mojosymbols') | |
| 77 | |
| 78 | |
| 79 if pyelftools_dir == None: | |
| 80 # No directory for pyelftools is specified. Try first to load it from the | |
| 81 # system installation. If that fails, then try to guess. | |
| 82 try: | |
| 83 import elftools.elf.elffile as elffile | |
| 84 except ImportError: | |
| 85 pyelftools_dir = os.path.join(_GetDirAbove('third_party'), | |
| 86 'third_party', 'pyelftools') | |
| 87 sys.path.append(pyelftools_dir) | |
| 88 try: | |
| 89 import elftools.elf.elffile as elffile | |
| 90 except ImportError: | |
| 91 logging.fatal("Unable to find elftools module; please install it " | |
| 92 "(for exmple, using 'pip install elftools')") | |
| 93 sys.exit(1) | |
| 94 else: | |
| 95 sys.path.append(pyelftools_dir) | |
| 96 import elftools.elf.elffile as elffile | |
| 97 | |
| 98 self._elffile = elffile | |
|
ppi
2015/07/09 13:12:40
_elffile_module?
etiennej
2015/07/15 07:13:21
Done.
| |
| 99 | |
| 100 self.libraries = self._find_libraries(build_directory) | |
|
ppi
2015/07/09 13:12:39
unify the naming convention, should all of these b
etiennej
2015/07/15 07:13:21
Done.
| |
| 101 self.rfc = RemoteFileConnection('localhost', 10000) | |
| 102 if not os.path.exists(self.remote_file_cache): | |
| 103 os.makedirs(self.remote_file_cache) | |
| 104 self.done_mapping = set() | |
| 105 self._downloaded_files = [] | |
| 106 | |
| 107 def __del__(self): | |
| 108 gdbserver_pid = self._get_pid('gdbserver') | |
| 109 if gdbserver_pid is not None: | |
| 110 subprocess.check_call([self.adb, 'shell', 'kill', gdbserver_pid]) | |
| 111 remote_file_reader_pid = self._get_pid('remote_file_reader') | |
| 112 if remote_file_reader_pid is not None: | |
| 113 subprocess.check_call([self.adb, 'shell', 'kill', remote_file_reader_pid]) | |
| 114 | |
| 115 def _find_libraries(self, lib_dir): | |
|
ppi
2015/07/09 13:12:40
Please add a pydoc explaining the return value.
etiennej
2015/07/15 07:13:21
Done.
| |
| 116 res = {} | |
| 117 for fn in glob.glob('%s/*.so' % lib_dir): | |
| 118 with open(fn, 'r') as f: | |
| 119 s = self._get_signature(f) | |
| 120 if s is not None: | |
| 121 res[s] = fn | |
| 122 return res | |
| 123 | |
| 124 def _get_signature(self, file_object): | |
|
ppi
2015/07/09 13:12:39
file_object -> file?
etiennej
2015/07/15 07:13:20
I would prefer not redefining python internals.
| |
| 125 """Compute a unique signature of a library file.""" | |
|
ppi
2015/07/09 13:12:40
Computes
etiennej
2015/07/15 07:13:21
Done.
| |
| 126 elf = self._elffile.ELFFile(file_object) | |
| 127 text_section = elf.get_section_by_name('.text') | |
| 128 file_object.seek(text_section['sh_offset']) | |
| 129 data = file_object.read(min(4096, text_section['sh_size'])) | |
|
ppi
2015/07/09 13:12:39
Are we hashing only the first 4096 bytes of the te
qsr
2015/07/09 13:54:18
You cannot hash the entire file, because on the ho
ppi
2015/07/09 14:16:11
Makes sense. Etienne, could you please import thes
etiennej
2015/07/15 07:13:20
Done.
| |
| 130 def combine((i, c)): | |
| 131 return i ^ ord(c) | |
| 132 result = 16 * [0] | |
| 133 for i in xrange(0, len(data), len(result)): | |
| 134 result = map(combine, | |
| 135 itertools.izip_longest(result, | |
| 136 data[i:i + len(result)], | |
| 137 fillvalue='\0')) | |
| 138 return ''.join(["%02x" % x for x in result]) | |
| 139 | |
| 140 def _associate_symbols(self, mapping, local_file): | |
| 141 with open(local_file, "r") as f: | |
| 142 elf = self._elffile.ELFFile(f) | |
| 143 s = elf.get_section_by_name(".text") | |
| 144 text_address = mapping[0].start + s['sh_offset'] | |
| 145 gdb_execute("add-symbol-file %s 0x%x" % (local_file, text_address)) | |
| 146 | |
| 147 def _download_file(self, remote): | |
| 148 """Downloads a remote file through GDB connection. | |
| 149 | |
| 150 Returns: | |
| 151 The filename of the downloaded file | |
| 152 """ | |
| 153 temp_file = tempfile.NamedTemporaryFile() | |
| 154 gdb_execute("remote get %s %s" % (remote, temp_file.name)) | |
| 155 # This allows the deletion of temporary files on disk when the debugging | |
| 156 # session terminates. | |
| 157 self._downloaded_files.append(temp_file) | |
| 158 return temp_file.name | |
| 159 | |
| 160 def _download_and_associate_symbol(self, mapping): | |
| 161 self._associate_symbols(mapping, self._download_file(mapping[0].filename)) | |
| 162 | |
| 163 def _find_mapping_for_address(self, mappings, address): | |
| 164 for m in mappings: | |
| 165 for s in m: | |
|
ppi
2015/07/09 13:12:39
what is 's'?
etiennej
2015/07/15 07:13:21
Done.
| |
| 166 if address >= s.start and address <= s.end: | |
| 167 return m | |
| 168 return None | |
| 169 | |
| 170 def _try_to_map(self, mapping): | |
| 171 remote_file = mapping[0].filename | |
| 172 if remote_file in self.done_mapping: | |
| 173 return False | |
| 174 self.done_mapping.add(remote_file) | |
| 175 self.rfc.open(remote_file) | |
| 176 s = self._get_signature(self.rfc) | |
| 177 if s is not None: | |
| 178 if s in self.libraries: | |
| 179 self._associate_symbols(mapping, self.libraries[s]) | |
| 180 else: | |
|
ppi
2015/07/09 13:12:40
Can you comment on when we hit this case and what
etiennej
2015/07/15 07:13:20
Done.
| |
| 181 local_file = os.path.join(self.remote_file_cache, s) | |
| 182 if not os.path.exists(local_file): | |
| 183 tmp_output = self._download_file(remote_file) | |
| 184 shutil.move(tmp_output, local_file) | |
| 185 self._associate_symbols(mapping, local_file) | |
| 186 return True | |
| 187 return False | |
| 188 | |
| 189 def _update_symbols(self): | |
| 190 """Updates the mapping between symbols as seen from GDB and local library | |
| 191 files.""" | |
| 192 mapped_files = get_mapped_files() | |
| 193 gdb_execute("info threads") | |
| 194 nb_threads = len(gdb_execute("info threads").split("\n")) - 2 | |
| 195 # Map all symbols in /data/ | |
|
ppi
2015/07/09 13:12:39
Which are the symbols in "/data"? Are these the na
qsr
2015/07/09 13:54:18
Yes.
ppi
2015/07/09 14:16:10
Thanks! I guess I meant that this could be said in
etiennej
2015/07/15 07:13:20
Done.
| |
| 196 for m in mapped_files: | |
| 197 filename = m[0].filename | |
| 198 if ((filename.startswith('/data/data/') or | |
| 199 filename.startswith('/data/app')) and | |
| 200 not filename.endswith('.apk') and | |
| 201 not filename.endswith('.dex')): | |
| 202 print 'Pre-mapping: %s' % m[0].filename | |
| 203 self._try_to_map(m) | |
| 204 for i in xrange(nb_threads): | |
| 205 try: | |
| 206 gdb_execute("thread %d" % (i + 1)) | |
| 207 frame = gdb.newest_frame() | |
| 208 while frame and frame.is_valid(): | |
| 209 if frame.name() is None: | |
| 210 m = self._find_mapping_for_address(mapped_files, frame.pc()) | |
| 211 if m is not None and self._try_to_map(m): | |
| 212 # Force gdb to recompute its frames. | |
| 213 gdb_execute("info threads") | |
| 214 frame = gdb.newest_frame() | |
| 215 assert frame.is_valid() | |
| 216 if (frame.older() is not None and | |
| 217 frame.older().is_valid() and | |
| 218 frame.older().pc() != frame.pc()): | |
| 219 frame = frame.older() | |
| 220 else: | |
| 221 frame = None | |
| 222 except gdb.error as _: | |
| 223 import traceback | |
| 224 traceback.print_exc() | |
| 225 | |
| 226 def _get_pid(self, application): | |
|
ppi
2015/07/09 13:12:39
_get_device_app_pid?
etiennej
2015/07/15 07:13:21
Done.
| |
| 227 """Gets the PID of an application running on a device.""" | |
| 228 output = subprocess.check_output([self.adb, 'shell', 'ps']) | |
| 229 for line in output.split('\n'): | |
| 230 elements = line.split() | |
| 231 if len(elements) > 0 and elements[-1] == application: | |
| 232 return elements[1] | |
| 233 return None | |
| 234 | |
| 235 def start_debug(self): | |
|
ppi
2015/07/09 13:12:39
The class is already called DebugSession, maybe ju
etiennej
2015/07/15 07:13:21
Done.
| |
| 236 """Starts a debugging session.""" | |
| 237 gdbserver_pid = self._get_pid('gdbserver') | |
| 238 if gdbserver_pid is not None: | |
| 239 subprocess.check_call([self.adb, 'shell', 'kill', gdbserver_pid]) | |
| 240 shell_pid = self._get_pid(self.package_name) | |
| 241 if shell_pid is None: | |
| 242 raise Exception('Unable to find a running mojo shell.') | |
| 243 subprocess.check_call([self.adb, 'forward', 'tcp:9999', 'tcp:9999']) | |
| 244 subprocess.Popen( | |
| 245 [self.adb, 'shell', 'gdbserver', '--attach', ':9999', shell_pid]) | |
| 246 time.sleep(0.1) | |
|
ppi
2015/07/09 13:12:40
Why? Please explain the sleep in a comment.
etiennej
2015/07/15 07:13:20
Done.
| |
| 247 | |
| 248 read_process = subprocess.Popen( | |
|
ppi
2015/07/09 13:12:40
reader_process?
etiennej
2015/07/15 07:13:20
Done.
| |
| 249 [self.adb, 'shell', config.REMOTE_FILE_READER_DEVICE_PATH], | |
| 250 stdout=subprocess.PIPE) | |
| 251 port = int(read_process.stdout.readline()) | |
| 252 subprocess.check_call([self.adb, 'forward', 'tcp:10000', 'tcp:%d' % port]) | |
| 253 self.rfc.connect() | |
| 254 | |
| 255 gdb_execute('target remote localhost:9999') | |
| 256 | |
| 257 self._update_symbols() | |
| 258 def on_stop(_): | |
| 259 self._update_symbols() | |
| 260 gdb.events.stop.connect(on_stop) | |
| OLD | NEW |