Debian Codegraph @

lib_pypy/_pypy_remote_debug.py

raw symbols SCIP
1 """
2 EXPERIMENTAL and subject to change
3
4 Support for injecting Python code into another PyPy process. Can be used for
5 remote debugging, dumping the heap, interrupting a crashing process, etc.
6
7 Usage:
8
9 pypy -m _pypy_remote_debug <pid> <scriptfile>
10 """
11 from __future__ import print_function
12 import os
13 import sys
14 import time
15
16 # __________________________________________________________
17 # Linux support only for now
18 #
19 # in case we want to add windows support we could look at pymem: https://pypi.org/project/Pymem/
20 # for Mac https://developer.apple.com/documentation/kernel/1402070-mach_vm_write
21
22 # __________________________________________________________
23 # first, some elf support
24 #
25 # Note that this implementation is inspired by the ELF object file reader
26 # here:
27 #
28 # http://www.tinyos.net/tinyos-1.x/tools/src/mspgcc-pybsl/elf.py
29 #
30 # which includes this copyright:
31 #
32 # (C) 2003 [email protected]
33 # Python license
34 #
35 # Author : Christopher Batten
36 # Date : May 20, 2014
37 #
38 # BSD License
39 #
40 # adapted for pydrofoil and later PyPy by cfbolz
41
42 import struct
43
44 class ElfBase(object):
45 def _unpack(self, data, is_64bit):
46 from struct import unpack
47 self.is_64bit = is_64bit
48 if self.is_64bit:
49 format = self.FORMAT64
50 else:
51 format = self.FORMAT
52 return unpack(format, data)
53
54 @classmethod
55 def from_file(cls, file_obj, is_64bit, offset=0):
56 file_obj.seek(offset)
57 ehdr_data = file_obj.read(cls.NBYTES64 if is_64bit else cls.NBYTES)
58 return cls(ehdr_data, is_64bit=is_64bit)
59
60
61 class ElfHeader(ElfBase):
62 FORMAT64 = "<16sHHIQQQIHHHHHH"
63 FORMAT = "<16sHHIIIIIHHHHHH"
64 NBYTES = struct.calcsize(FORMAT)
65 NBYTES64 = struct.calcsize(FORMAT64)
66
67 def __init__(self, data, is_64bit=False):
68 self.ident, self.type, self.machine, self.version, self.entry, self.phoff, self.shoff, self.flags, self.ehsize, self.phentsize, self.phnum, self.shentsize, self.shnum, self.shstrndx = self._unpack(data, is_64bit)
69
70
71 class ElfProgramHeader(ElfBase):
72 FORMAT = "<IIIIIIII"
73 FORMAT64 = "<IIQQQQQQ"
74 NBYTES = struct.calcsize(FORMAT)
75 NBYTES64 = struct.calcsize(FORMAT64)
76
77 PT_LOAD = 1 # loadable segment
78
79 def __init__(self, data, is_64bit=False):
80 fields = self._unpack(data, is_64bit)
81 if is_64bit:
82 self.type, self.flags, self.offset, self.vaddr, self.paddr, self.filesz, self.memsz, self.align = fields
83 else:
84 self.type, self.offset, self.vaddr, self.paddr, self.filesz, self.memsz, self.flags, self.align = fields
85
86
87 class ElfSectionHeader(ElfBase):
88 FORMAT = "<IIIIIIIIII"
89 FORMAT64 = "<IIQQQQIIQQ"
90 NBYTES = struct.calcsize(FORMAT)
91 NBYTES64 = struct.calcsize(FORMAT64)
92
93 TYPE_SYMTAB = 2
94 TYPE_STRTAB = 3
95 TYPE_DYNSYM = 11
96
97 name_as_bytes = None
98 section_data = None
99 section_index = None
100
101 def __init__(self, data, is_64bit=False):
102 self.name, self.type, self.flags, self.addr, self.offset, self.size, self.link, self.info, self.addralign, self.entsize = self._unpack(data, is_64bit)
103
104 def __repr__(self):
105 return "<ElfSectionHeader name_as_bytes=%r section_index=%s type=%s>" % (self.name_as_bytes, self.section_index, self.type)
106
107
108
109
110 class ElfSymTabEntry(ElfBase):
111 FORMAT = "<IIIBBH"
112 FORMAT64 = "<IBBHQQ"
113 NBYTES = struct.calcsize(FORMAT)
114 NBYTES64 = struct.calcsize(FORMAT64)
115
116 name_as_bytes = None
117
118 def __init__(self, data="", is_64bit=False):
119 fields = self._unpack(data, is_64bit)
120 if is_64bit:
121 self.name, self.info, self.other, self.shndx, self.value, self.size = fields
122 else:
123 self.name, self.value, self.size, self.info, self.other, self.shndx = fields
124
125 def __repr__(self):
126 if self.name_as_bytes:
127 return "<ElfSymTabEntry name_as_bytes=%r value=%x size=%x info=%s>" % (self.name_as_bytes, self.value, self.size, self.info)
128 return "<ElfSymTabEntry value=%x size=%x info=%s>" % (self.value, self.size, self.info)
129
130
131 def read_header(file_obj):
132 file_obj.seek(0)
133 first_bytes = file_obj.read(5)
134 if not first_bytes.startswith(b"\x7fELF"):
135 raise ValueError("Not a valid ELF file")
136 if first_bytes[4:5] == b'\x02':
137 is_64bit = True
138 elif first_bytes[4:5] == b'\x01':
139 is_64bit = False
140 else:
141 raise ValueError("unknown kind of elf file")
142 return ElfHeader.from_file(file_obj, is_64bit)
143
144 def _elf_section_headers(file_obj):
145 ehdr = read_header(file_obj)
146
147 symtab_data = None
148 strtab_data = None
149 shstr_data = None
150 sections = []
151 for section_idx in range(ehdr.shnum):
152 section_header = ElfSectionHeader.from_file(file_obj, ehdr.is_64bit,
153 ehdr.shoff + section_idx * ehdr.shentsize)
154 section_header.section_index = section_idx
155 file_obj.seek(section_header.offset)
156 data = file_obj.read(section_header.size)
157 section_header.section_data = data
158 sections.append(section_header)
159 if section_header.type not in (ElfSectionHeader.TYPE_STRTAB, ElfSectionHeader.TYPE_SYMTAB):
160 continue
161
162 if section_header.type == ElfSectionHeader.TYPE_STRTAB:
163 if section_idx == ehdr.shstrndx:
164 shstr_data = data
165 for section_header in sections:
166 start = section_header.name
167 end = shstr_data.find(b'\0', start)
168 assert end >= 0
169 section_header.name_as_bytes = shstr_data[start: end]
170 return sections, ehdr #, symtab_data, strtab_data
171
172 def _find_section(sections, what):
173 res = []
174 for section in sections:
175 if section.type == what or section.name_as_bytes == what:
176 res.append(section)
177 return res
178
179 def _iter_symbol_and_dynsym(file_obj):
180 sections, ehdr = _elf_section_headers(file_obj)
181 symtabs = _find_section(sections, ElfSectionHeader.TYPE_SYMTAB) + _find_section(sections, ElfSectionHeader.TYPE_DYNSYM)
182 for symtab in symtabs:
183 strtab_index = symtab.link
184 if not 0 <= strtab_index < len(sections):
185 continue
186 strtab = sections[strtab_index]
187 if strtab.type != ElfSectionHeader.TYPE_STRTAB:
188 continue
189 for sym in _elf_iter_symbols(ehdr, symtab.section_data, strtab.section_data):
190 sym.source = symtab
191 yield sym
192 return
193
194
195 def elf_find_symbol(file_obj, symbol):
196 for sym in _iter_symbol_and_dynsym(file_obj):
197 if sym.name_as_bytes == symbol:
198 if sym.value:
199 return sym.value
200 if sym.info:
201 return sym.info
202 raise ValueError('not found')
203
204
205 def _elf_iter_symbols(ehdr, symtab_data, strtab_data):
206 symtabentry_nbytes = ElfSymTabEntry.NBYTES64 if ehdr.is_64bit else ElfSymTabEntry.NBYTES
207 num_symbols = len(symtab_data) // symtabentry_nbytes
208 for sym_idx in range(num_symbols):
209 start = sym_idx * symtabentry_nbytes
210 sym_data = symtab_data[start: start + symtabentry_nbytes]
211 if sym_idx == 0:
212 continue
213
214 sym = ElfSymTabEntry(sym_data, ehdr.is_64bit)
215 start = sym.name
216 assert start >= 0
217 end = strtab_data.find(b'\0', start)
218 if end < 0:
219 continue
220 name = strtab_data[start: end]
221 sym.name_as_bytes = name
222 yield sym
223
224
225 def elf_read_first_load_section(file_obj):
226 ehdr = read_header(file_obj)
227
228 for program_index in range(ehdr.phnum):
229 phdr = ElfProgramHeader.from_file(file_obj, ehdr.is_64bit,
230 ehdr.phoff + program_index * ehdr.phentsize)
231 if phdr.type != ElfProgramHeader.PT_LOAD:
232 continue
233 return phdr
234
235 # __________________________________________________________
236 # reading and writing the memory of another process
237
238 import cffi
239
240 ffi = cffi.FFI()
241
242
243 ffi.cdef("""
244 struct iovec {
245 void* iov_base;
246 size_t iov_len;
247 };
248
249 typedef int pid_t;
250 long process_vm_readv(pid_t pid,
251 const struct iovec *local_iov,
252 unsigned long liovcnt,
253 const struct iovec *remote_iov,
254 unsigned long riovcnt,
255 unsigned long flags);
256 long process_vm_writev(pid_t pid,
257 const struct iovec *local_iov,
258 unsigned long liovcnt,
259 const struct iovec *remote_iov,
260 unsigned long riovcnt,
261 unsigned long flags);
262 """)
263 lib = ffi.dlopen(None)
264
265 def read_memory(pid, address, size):
266 iovec = ffi.new('struct iovec[2]')
267 target = ffi.new('char[]', size)
268 # transfers data to the local process, from the remote process
269 iovec[0].iov_base = target
270 iovec[0].iov_len = size
271 iovec[1].iov_base = ffi.cast('void*', address)
272 iovec[1].iov_len = size
273 result = lib.process_vm_readv(pid, iovec, 1, iovec + 1, 1, 0)
274 if result != size:
275 raise OSError(os.strerror(ffi.errno))
276 return ffi.buffer(target, size)[:]
277
278 def write_memory(pid, address, content):
279 iovec = ffi.new('struct iovec[2]')
280 # transfers data from the local, to the remote process
281 source = ffi.from_buffer(content)
282 iovec[0].iov_base = source
283 iovec[0].iov_len = len(content)
284 iovec[1].iov_base = ffi.cast('void*', address)
285 iovec[1].iov_len = len(content)
286 result = lib.process_vm_writev(pid, iovec, 1, iovec + 1, 1, 0)
287 if result != len(content):
288 raise OSError(os.strerror(ffi.errno))
289
290 # __________________________________________________________
291 # parsing proc maps
292
293
294 def _read_and_parse_maps(pid='self', filter=None):
295 if filter is not None and os.path.isabs(filter):
296 # follow symlinks
297 filter = os.path.realpath(filter)
298 with open('/proc/%s/maps' % pid) as f:
299 return _parse_maps(f, filter)
300
301 def _parse_maps(lineiter, filter=None):
302 parsed_maps = []
303 libpypy = None
304 for entry in lineiter:
305 mapping = entry.split()
306 mapping_range = mapping[0]
307 from_, to_ = mapping_range.split('-', 1)
308 from_ = int(from_, 16)
309 to_ = int(to_, 16)
310 file_offset = int(mapping[2], 16)
311 mapping_file = mapping[-1]
312 if filter is not None and filter not in mapping_file:
313 continue
314 parsed_maps.append(dict(
315 file=mapping[-1], from_=from_, to_=to_,
316 permissions=mapping[1], file_offset=file_offset,
317 full_line=entry))
318 return parsed_maps
319
320 def _find_file_and_base_addr(pid='self'):
321 maps = _read_and_parse_maps(pid, 'libpypy')
322 if not maps:
323 executable = os.path.realpath('/proc/%s/exe' % pid)
324 maps = _read_and_parse_maps(pid, executable)
325 if not maps:
326 raise ValueError('could not find executable nor libpypy.so in /proc/%s/maps' % pid)
327 for map in maps:
328 if map['file_offset'] == 0:
329 return map['file'], map['from_']
330 assert 0, "no map with file offset 0 found"
331
332 def _check_elf_debuglink(file):
333 with open(file, 'rb') as f:
334 sections, ehdr = _elf_section_headers(f)
335 debuglinks = [section for section in sections if section.name_as_bytes == b'.gnu_debuglink']
336 if debuglinks:
337 debuglink = debuglinks[0]
338 end = debuglink.section_data.find(b'\x00')
339 fn = debuglink.section_data[:end].decode('utf-8')
340 res = os.path.join(os.path.dirname(os.path.realpath(file)), fn)
341 try:
342 os.stat(res)
343 except OSError:
344 pass
345 else:
346 return res
347 return file
348
349 # __________________________________________________________
350 # symbolication support, used by _vmprof.resolve_address and
351 # _vmprof.resolve_many_addr
352
353 def _proc_map_find_base_map(value, maps=None):
354 if maps is None:
355 maps = _read_and_parse_maps()
356 base_map = None
357 for map_entry in maps:
358 if not map_entry['file'].startswith('/'):
359 continue
360 if base_map is None or base_map['file'] != map_entry['file']:
361 base_map = map_entry
362 if map_entry['from_'] <= value < map_entry['to_']:
363 # find the base map, ie the first entry with the same file name
364 for base_map in maps:
365 if base_map['file'] == map_entry['file'] and base_map['file_offset'] == 0:
366 return base_map
367 assert 0, 'unreachable'
368 else:
369 return None
370
371
372 def _symbolify(value):
373 map_entry = _proc_map_find_base_map(value)
374 if map_entry is None:
375 return None
376 filename = map_entry['file']
377 base_addr = map_entry['from_']
378 with open(filename, 'rb') as f:
379 phdr = elf_read_first_load_section(f)
380 assert phdr.vaddr % phdr.align == 0
381 filename = _check_elf_debuglink(filename)
382 with open(filename, 'rb') as f:
383 symbol_value = value - base_addr + phdr.vaddr
384 f.seek(0)
385 for sym in _iter_symbol_and_dynsym(f):
386 if sym.value <= symbol_value < sym.value + sym.size:
387 return sym.name_as_bytes, filename
388 return None
389
390 def _symbolify_all(values):
391 # this is quite efficient, because it sorts the values, then sorts the
392 # symbols within a shared library, and proceeds in a sorted order, merging
393 # values and symbols
394 values = sorted(values)
395 res = {}
396 map_entry = None
397 for value in values:
398 if map_entry is None or map_entry['to_'] < value:
399 map_entry = _proc_map_find_base_map(value)
400 if map_entry is None:
401 continue
402 filename = map_entry['file']
403 base_addr = map_entry['from_']
404 with open(filename, 'rb') as f:
405 phdr = elf_read_first_load_section(f)
406 assert phdr.vaddr % phdr.align == 0
407 filename = _check_elf_debuglink(filename)
408 with open(filename, 'rb') as f:
409 syms = [sym for sym in _iter_symbol_and_dynsym(f) if sym.name_as_bytes]
410 syms.sort(key=lambda sym: sym.value)
411 symindex = 0
412 symbol_value = value - base_addr + phdr.vaddr
413 for symindex in range(symindex, len(syms)):
414 sym = syms[symindex]
415 if sym.value <= symbol_value < sym.value + sym.size:
416 res[value] = (sym.name_as_bytes, filename)
417 if sym.value > symbol_value:
418 break
419 else:
420 continue
421 return res
422
423 # __________________________________________________________
424 # actually starting the debugger
425
426
427 COOKIE_OFFSET = struct.calcsize('l')
428 PENDING_CALL_OFFSET = COOKIE_OFFSET + struct.calcsize('cccccccc')
429 PATH_OFFSET = PENDING_CALL_OFFSET + struct.calcsize('l')
430 PATH_MAX = 1024
431
432
433 def compute_remote_addr(pid='self', symbolname=b'pypysig_counter'):
434 file, base_addr = _find_file_and_base_addr(pid)
435 origfile = file
436 with open(file, 'rb') as f:
437 phdr = elf_read_first_load_section(f)
438 assert phdr.offset == 0
439
440 try:
441 with open(file, 'rb') as f:
442 symbol_value = elf_find_symbol(f, symbolname)
443 except ValueError:
444 file = _check_elf_debuglink(file)
445 if file == origfile:
446 raise ValueError('symbol not found')
447 with open(file, 'rb') as f:
448 symbol_value = elf_find_symbol(f, symbolname)
449 # compute address in target process
450 # XXX I don't understand how alignment works, assert that it is aligned
451 assert phdr.vaddr % phdr.align == 0
452 return base_addr + symbol_value - phdr.vaddr
453
454
455 def start_debugger(pid, filename, wait=True):
456 if not sys.platform.startswith('linux'):
457 raise ValueError('This works on Linux only so far')
458 addr = compute_remote_addr(pid)
459 cookie = read_memory(pid, addr + COOKIE_OFFSET, 8)
460 assert cookie == b'pypysigs'
461 if not isinstance(filename, bytes):
462 raise TypeError('filename must be bytes, not %r' % (type(filename).__name__, ))
463 if not len(filename) + 1 < PATH_MAX:
464 raise ValueError('path can be at most %s bytes long, not %s' % (PATH_MAX - 1, len(filename)))
465 if b'\x00' in filename:
466 raise ValueError('filename must not contain null byte')
467 # write the path plus null byte
468 write_memory(pid, addr + PATH_OFFSET, filename + b'\x00')
469 # write a 1 into pypysig_counter.debugger_pending_call
470 write_memory(pid, addr + PENDING_CALL_OFFSET, struct.pack('l', 1))
471 # write a -1 into pypysig_counter.value
472 write_memory(pid, addr, struct.pack('l', -1))
473 if wait:
474 while 1:
475 time.sleep(0.1)
476 value, = struct.unpack('l', read_memory(pid, addr + PENDING_CALL_OFFSET, struct.calcsize('l')))
477 if value == 0:
478 return
479
480 def main():
481 import argparse
482 parser = argparse.ArgumentParser(description="Execute Python code in another PyPy process.")
483 parser.add_argument("pid", help="process id of the target process", type=int)
484 parser.add_argument("script", nargs='?', help="script file to execute in the remote process")
485 parser.add_argument("-c", help="python code passed as string to execute in the remote process", metavar='code')
486 parser.add_argument("--dont-wait", help="dont wait for the other process to run the debug code", action='store_true')
487 args = parser.parse_args()
488
489 if not sys.platform.startswith('linux'):
490 parser.error('This works on Linux only so far')
491 if args.script:
492 start_debugger(args.pid, os.path.realpath(args.script), wait=not args.dont_wait)
493 elif args.c:
494 if args.dont_wait:
495 parser.error("can't pass -c and --dont-wait together")
496 import tempfile
497 with tempfile.NamedTemporaryFile(mode='wb') as f:
498 f.write(args.c.encode('utf-8'))
499 f.flush()
500 # make it world-readable, in case we have to use sudo
501 os.chmod(f.name, 0o644)
502 start_debugger(args.pid, f.name, wait=True)
503 else:
504 parser.error('need to pass either a script or -c')
505
506
507 if __name__ == '__main__':
508 main()