Debian Codegraph @

pypy/interpreter/reverse_debugging.py

raw symbols SCIP
1 import sys
2 from rpython.rlib import revdb
3 from rpython.rlib.debug import make_sure_not_resized
4 from rpython.rlib.objectmodel import specialize, we_are_translated
5 from rpython.rtyper.annlowlevel import cast_gcref_to_instance
6 from pypy.interpreter.error import OperationError, oefmt
7 from pypy.interpreter.baseobjspace import W_Root
8 from pypy.interpreter import gateway, typedef, pycode, pytraceback, pyframe
9 from pypy.module.marshal import interp_marshal
10 from pypy.interpreter.executioncontext import AbstractActionFlag, ActionFlag
11
12
13 class DBState:
14 standard_code = True
15 breakpoint_stack_id = 0
16 breakpoint_funcnames = None
17 breakpoint_filelines = None
18 breakpoint_by_file = None
19 breakpoint_version = 0
20 printed_objects = {}
21 metavars = []
22 watch_progs = []
23 watch_futures = {}
24
25 dbstate = DBState()
26
27
28 pycode.PyCode.co_revdb_linestarts = None # or a string: see below
29 pycode.PyCode.co_revdb_bkpt_version = 0 # see check_and_trigger_bkpt()
30 pycode.PyCode.co_revdb_bkpt_cache = None # see check_and_trigger_bkpt()
31
32 # invariant: "f_revdb_nextline_instr" is the bytecode offset of
33 # the start of the line that follows "last_instr".
34 pyframe.PyFrame.f_revdb_nextline_instr = -1
35
36
37 # ____________________________________________________________
38
39
40 def setup_revdb(space):
41 """Called at run-time, before the space is set up.
42
43 The various register_debug_command() lines attach functions
44 to some commands that 'revdb.py' can call, if we are running
45 in replay mode.
46 """
47 assert space.config.translation.reverse_debugger
48 dbstate.space = space
49
50 make_sure_not_resized(dbstate.watch_progs)
51 make_sure_not_resized(dbstate.metavars)
52
53 revdb.register_debug_command(revdb.CMD_PRINT, lambda_print)
54 revdb.register_debug_command(revdb.CMD_BACKTRACE, lambda_backtrace)
55 revdb.register_debug_command(revdb.CMD_LOCALS, lambda_locals)
56 revdb.register_debug_command(revdb.CMD_BREAKPOINTS, lambda_breakpoints)
57 revdb.register_debug_command(revdb.CMD_STACKID, lambda_stackid)
58 revdb.register_debug_command("ALLOCATING", lambda_allocating)
59 revdb.register_debug_command(revdb.CMD_ATTACHID, lambda_attachid)
60 revdb.register_debug_command(revdb.CMD_COMPILEWATCH, lambda_compilewatch)
61 revdb.register_debug_command(revdb.CMD_CHECKWATCH, lambda_checkwatch)
62 revdb.register_debug_command(revdb.CMD_WATCHVALUES, lambda_watchvalues)
63
64
65 # ____________________________________________________________
66
67
68 def enter_call(caller_frame, callee_frame):
69 if dbstate.breakpoint_funcnames is not None:
70 name = callee_frame.getcode().co_name
71 if name in dbstate.breakpoint_funcnames:
72 revdb.breakpoint(dbstate.breakpoint_funcnames[name])
73 if dbstate.breakpoint_stack_id != 0 and caller_frame is not None:
74 if dbstate.breakpoint_stack_id == revdb.get_unique_id(caller_frame):
75 revdb.breakpoint(-1)
76 #
77 code = callee_frame.pycode
78 if code.co_revdb_linestarts is None:
79 build_co_revdb_linestarts(code)
80
81 def leave_call(caller_frame, got_exception):
82 if dbstate.breakpoint_stack_id != 0 and caller_frame is not None:
83 if dbstate.breakpoint_stack_id == revdb.get_unique_id(caller_frame):
84 revdb.breakpoint(-2)
85 if we_are_translated():
86 stop_point_activate(-2 + got_exception)
87
88 def stop_point():
89 if we_are_translated():
90 revdb.breakpoint(-3)
91
92
93 def jump_backward(frame, jumpto):
94 # When we see a jump backward, we set 'f_revdb_nextline_instr' in
95 # such a way that the next instruction, at 'jumpto', will trigger
96 # stop_point_activate(). We have to trigger it even if
97 # 'jumpto' is not actually a start of line. For example, after a
98 # 'while foo:', the body ends with a JUMP_ABSOLUTE which
99 # jumps back to the *second* opcode of the while.
100 frame.f_revdb_nextline_instr = jumpto
101
102
103 def potential_stop_point(frame):
104 if not we_are_translated():
105 return
106 #
107 # We only record a stop_point at every line, not every bytecode.
108 # Uses roughly the same algo as ExecutionContext.run_trace_func()
109 # to know where the line starts are, but tweaked for speed,
110 # avoiding the quadratic complexity when run N times with a large
111 # code object.
112 #
113 cur = frame.last_instr
114 if cur < frame.f_revdb_nextline_instr:
115 return # fast path: we're still inside the same line as before
116 #
117 call_stop_point_at_line = True
118 co_revdb_linestarts = frame.pycode.co_revdb_linestarts
119 if cur > frame.f_revdb_nextline_instr:
120 #
121 # We jumped forward over the start of the next line. We're
122 # inside a different line, but we will only trigger a stop
123 # point if we're at the starting bytecode of that line. Fetch
124 # from co_revdb_linestarts the start of the line that is at or
125 # follows 'cur'.
126 ch = ord(co_revdb_linestarts[cur])
127 if ch == 0:
128 pass # we are at the start of a line now
129 else:
130 # We are not, so don't call stop_point_activate().
131 # We still have to fill f_revdb_nextline_instr.
132 call_stop_point_at_line = False
133 #
134 if call_stop_point_at_line:
135 stop_point_activate(pycode=frame.pycode, opindex=cur)
136 cur += 1
137 ch = ord(co_revdb_linestarts[cur])
138 #
139 # Update f_revdb_nextline_instr. Check if 'ch' was greater than
140 # 255, in which case it was rounded down to 255 and we have to
141 # continue looking
142 nextline_instr = cur + ch
143 while ch == 255:
144 ch = ord(co_revdb_linestarts[nextline_instr])
145 nextline_instr += ch
146 frame.f_revdb_nextline_instr = nextline_instr
147
148
149 def build_co_revdb_linestarts(code):
150 # Inspired by findlinestarts() in the 'dis' standard module.
151 # Set up 'bits' so that it contains \x00 at line starts and \xff
152 # in-between.
153 bits = ['\xff'] * (len(code.co_code) + 1)
154 if not code.hidden_applevel:
155 lnotab = code.get_co_lnotab()
156 addr = 0
157 p = 0
158 newline = 1
159 while p + 1 < len(lnotab):
160 byte_incr = ord(lnotab[p])
161 line_incr = ord(lnotab[p+1]) # signed (maybe negative) from py3.6
162 if byte_incr:
163 if newline != 0:
164 bits[addr] = '\x00'
165 newline = 0
166 addr += byte_incr
167 newline |= line_incr
168 p += 2
169 if newline:
170 bits[addr] = '\x00'
171 bits[len(code.co_code)] = '\x00'
172 #
173 # Change 'bits' so that the character at 'i', if not \x00, measures
174 # how far the next \x00 is
175 next_null = len(code.co_code)
176 p = next_null - 1
177 while p >= 0:
178 if bits[p] == '\x00':
179 next_null = p
180 else:
181 ch = next_null - p
182 if ch > 255: ch = 255
183 bits[p] = chr(ch)
184 p -= 1
185 lstart = ''.join(bits)
186 code.co_revdb_linestarts = lstart
187 return lstart
188
189 def get_final_lineno(code):
190 lineno = code.co_firstlineno
191 largest_line_no = lineno
192 lnotab = code.get_co_lnotab()
193 p = 1
194 while p < len(lnotab):
195 line_incr = ord(lnotab[p])
196 if line_incr > 0x7f:
197 line_incr -= 0x100
198 lineno += line_incr
199 if lineno > largest_line_no:
200 largest_line_no = lineno
201 p += 2
202 return largest_line_no
203
204 def find_line_starts(code):
205 # RPython version of dis.findlinestarts()
206 lnotab = code.get_co_lnotab()
207 lastlineno = -1
208 lineno = code.co_firstlineno
209 addr = 0
210 p = 0
211 result = []
212 while p < len(lnotab) - 1:
213 byte_incr = ord(lnotab[p + 0])
214 line_incr = ord(lnotab[p + 1])
215 if byte_incr:
216 if lineno != lastlineno:
217 result.append((addr, lineno))
218 lastlineno = lineno
219 addr += byte_incr
220 if line_incr > 0x7f:
221 line_incr -= 0x100
222 lineno += line_incr
223 p += 2
224 if lineno != lastlineno:
225 result.append((addr, lineno))
226 return result
227
228 class NonStandardCode(object):
229 def __enter__(self):
230 dbstate.standard_code = False
231 self.t = dbstate.space.actionflag._ticker
232 self.c = dbstate.space.actionflag._ticker_revdb_count
233 def __exit__(self, *args):
234 dbstate.space.actionflag._ticker = self.t
235 dbstate.space.actionflag._ticker_revdb_count = self.c
236 dbstate.standard_code = True
237 non_standard_code = NonStandardCode()
238
239
240 def stop_point_activate(place=0, pycode=None, opindex=-1):
241 if revdb.watch_save_state():
242 any_watch_point = False
243 # ^^ this flag is set to True if we must continue to enter this
244 # block of code. If it is still False for watch_restore_state()
245 # below, then future watch_save_state() will return False too---
246 # until the next time revdb.c:set_revdb_breakpoints() is called.
247 space = dbstate.space
248 with non_standard_code:
249 watch_id = -1
250 if dbstate.breakpoint_by_file is not None:
251 any_watch_point = True
252 if pycode is not None:
253 watch_id = check_and_trigger_bkpt(pycode, opindex)
254 if watch_id == -1:
255 for prog, watch_id, expected in dbstate.watch_progs:
256 any_watch_point = True
257 try:
258 got = _run_watch(space, prog)
259 except OperationError as e:
260 got = e.errorstr(space)
261 except Exception:
262 break
263 if got != expected:
264 break
265 else:
266 watch_id = -1
267 revdb.watch_restore_state(any_watch_point)
268 if watch_id != -1:
269 revdb.breakpoint(watch_id)
270 revdb.stop_point(place)
271
272
273 def future_object(space):
274 return space.w_Ellipsis # a random prebuilt object
275
276 def load_metavar(index):
277 assert index >= 0
278 space = dbstate.space
279 metavars = dbstate.metavars
280 w_var = metavars[index] if index < len(metavars) else None
281 if w_var is None:
282 raise oefmt(space.w_NameError, "no constant object '$%d'",
283 index)
284 if w_var is future_object(space):
285 raise oefmt(space.w_RuntimeError,
286 "'$%d' refers to an object created later in time",
287 index)
288 return w_var
289
290 def set_metavar(index, w_obj):
291 assert index >= 0
292 if index >= len(dbstate.metavars):
293 missing = index + 1 - len(dbstate.metavars)
294 dbstate.metavars = dbstate.metavars + [None] * missing
295 dbstate.metavars[index] = w_obj
296
297
298 # ____________________________________________________________
299
300
301 def fetch_cur_frame(silent=False):
302 ec = dbstate.space.threadlocals.get_ec()
303 if ec is None:
304 frame = None
305 else:
306 frame = ec.topframeref()
307 if frame is None and not silent:
308 revdb.send_print("No stack.")
309 return frame
310
311 def compile(source, mode):
312 assert not dbstate.standard_code
313 space = dbstate.space
314 compiler = space.createcompiler()
315 code = compiler.compile(source, '<revdb>', mode, 0,
316 hidden_applevel=True)
317 return code
318
319
320 class W_RevDBOutput(W_Root):
321 softspace = 0
322
323 def __init__(self, space):
324 self.space = space
325
326 def descr_write(self, w_buffer):
327 assert not dbstate.standard_code
328 space = self.space
329 if space.isinstance_w(w_buffer, space.w_unicode):
330 w_buffer = space.call_method(w_buffer, 'encode',
331 space.newtext('utf-8')) # safe?
332 revdb.send_output(space.bytes_w(w_buffer))
333
334 def descr_get_softspace(space, revdb):
335 return space.newint(revdb.softspace)
336 def descr_set_softspace(space, revdb, w_newvalue):
337 revdb.softspace = space.int_w(w_newvalue)
338
339 W_RevDBOutput.typedef = typedef.TypeDef(
340 "revdb_output",
341 write = gateway.interp2app(W_RevDBOutput.descr_write),
342 # XXX is 'softspace' still necessary in Python 3?
343 softspace = typedef.GetSetProperty(descr_get_softspace,
344 descr_set_softspace,
345 cls=W_RevDBOutput),
346 )
347
348 def revdb_displayhook(space, w_obj):
349 """Modified sys.displayhook() that also outputs '$NUM = ',
350 for non-prebuilt objects. Such objects are then recorded in
351 'printed_objects'.
352 """
353 assert not dbstate.standard_code
354 if space.is_w(w_obj, space.w_None):
355 return
356 uid = revdb.get_unique_id(w_obj)
357 if uid > 0:
358 dbstate.printed_objects[uid] = w_obj
359 revdb.send_nextnid(uid) # outputs '$NUM = '
360 space.setitem(space.builtin.w_dict, space.newtext('_'), w_obj)
361 # do repr() after setitem: if w_obj was produced successfully,
362 # but its repr crashes because it tries to do I/O, then we already
363 # have it recorded in '_' and in '$NUM ='.
364 w_repr = space.repr(w_obj)
365 if space.isinstance_w(w_repr, space.w_unicode):
366 w_repr = space.call_method(w_repr, 'encode',
367 space.newtext('utf-8')) # safe?
368 revdb.send_print(space.bytes_w(w_repr))
369
370 @gateway.unwrap_spec(name='text0', level=int)
371 def revdb_importhook(space, name, w_globals=None,
372 w_locals=None, w_fromlist=None, level=-1):
373 # Incredibly simplified version of __import__, which only returns
374 # already-imported modules and doesn't call any custom import
375 # hooks. Recognizes only absolute imports. With a 'fromlist'
376 # argument that is a non-empty list, returns the module 'name3' if
377 # the 'name' argument is 'name1.name2.name3'. With an empty or
378 # None 'fromlist' argument, returns the module 'name1' instead.
379 return space.appexec([space.newtext(name), w_fromlist or space.w_None,
380 space.newint(level), space.sys],
381 """(name, fromlist, level, sys):
382 if level > 0:
383 raise ImportError("only absolute imports are "
384 "supported in the debugger")
385 basename = name.split('.')[0]
386 try:
387 basemod = sys.modules[basename]
388 mod = sys.modules[name]
389 except KeyError:
390 raise ImportError("'%s' not found or not imported yet "
391 "(the debugger can't import new modules, "
392 "and only supports absolute imports)" % (name,))
393 if fromlist:
394 return mod
395 return basemod
396 """)
397
398 @specialize.memo()
399 def get_revdb_displayhook(space):
400 return gateway.interp2app(revdb_displayhook).spacebind(space)
401
402 @specialize.memo()
403 def get_revdb_importhook(space):
404 return gateway.interp2app(revdb_importhook).spacebind(space)
405
406
407 def prepare_print_environment(space):
408 assert not dbstate.standard_code
409 w_revdb_output = W_RevDBOutput(space)
410 w_displayhook = get_revdb_displayhook(space)
411 w_import = get_revdb_importhook(space)
412 space.sys.setdictvalue(space, 'stdout', w_revdb_output)
413 space.sys.setdictvalue(space, 'stderr', w_revdb_output)
414 space.sys.setdictvalue(space, 'displayhook', w_displayhook)
415 space.builtin.setdictvalue(space, '__import__', w_import)
416
417 def command_print(cmd, expression):
418 frame = fetch_cur_frame()
419 if frame is None:
420 return
421 space = dbstate.space
422 with non_standard_code:
423 try:
424 prepare_print_environment(space)
425 code = compile(expression, 'single')
426 try:
427 code.exec_code(space,
428 frame.get_w_globals(),
429 frame.getdictscope())
430
431 except OperationError as operationerr:
432 # can't use sys.excepthook: it will likely try to do 'import
433 # traceback', which might not be doable without using I/O
434 tb = operationerr.get_traceback()
435 if tb is not None:
436 revdb.send_print("Traceback (most recent call last):")
437 while tb is not None:
438 if not isinstance(tb, pytraceback.PyTraceback):
439 revdb.send_print(" ??? %s" % tb)
440 break
441 show_frame(tb.frame, tb.get_lineno(), indent=' ')
442 tb = tb.next
443 revdb.send_print(operationerr.errorstr(space))
444
445 # set the sys.last_xxx attributes
446 w_type = operationerr.w_type
447 w_value = operationerr.get_w_value(space)
448 w_tb = operationerr.get_traceback()
449 w_dict = space.sys.w_dict
450 space.setitem(w_dict, space.newtext('last_type'), w_type)
451 space.setitem(w_dict, space.newtext('last_value'), w_value)
452 space.setitem(w_dict, space.newtext('last_traceback'), w_tb)
453
454 except OperationError as e:
455 revdb.send_print(e.errorstr(space, use_repr=True))
456 lambda_print = lambda: command_print
457
458
459 def file_and_lineno(frame, lineno):
460 code = frame.getcode()
461 return 'File "%s", line %d in %s' % (
462 code.co_filename, lineno, code.co_name)
463
464 def show_frame(frame, lineno=0, indent=''):
465 if lineno == 0:
466 lineno = frame.get_last_lineno()
467 revdb.send_output("%s%s\n%s " % (
468 indent,
469 file_and_lineno(frame, lineno),
470 indent))
471 revdb.send_linecache(frame.getcode().co_filename, lineno)
472
473 def display_function_part(frame, max_lines_before, max_lines_after):
474 if frame is None:
475 return
476 code = frame.getcode()
477 if code.co_filename.startswith('<builtin>'):
478 return
479 first_lineno = code.co_firstlineno
480 current_lineno = frame.get_last_lineno()
481 final_lineno = get_final_lineno(code)
482 #
483 ellipsis_after = False
484 if first_lineno < current_lineno - max_lines_before - 1:
485 first_lineno = current_lineno - max_lines_before
486 revdb.send_print("...")
487 if final_lineno > current_lineno + max_lines_after + 1:
488 final_lineno = current_lineno + max_lines_after
489 ellipsis_after = True
490 #
491 for i in range(first_lineno, final_lineno + 1):
492 if i == current_lineno:
493 if revdb.current_place() == -2: # <= this is the arg to stop_point()
494 prompt = "<< " # return
495 elif revdb.current_place() == -1:
496 prompt = "!! " # exceptional return
497 else:
498 prompt = " > " # plain line
499 revdb.send_output(prompt)
500 else:
501 revdb.send_output(" ")
502 revdb.send_linecache(code.co_filename, i, strip=False)
503 #
504 if ellipsis_after:
505 revdb.send_print("...")
506
507 def command_backtrace(cmd, extra):
508 frame = fetch_cur_frame(silent=True)
509 if cmd.c_arg1 == 0:
510 if frame is not None:
511 revdb.send_print("%s:" % (
512 file_and_lineno(frame, frame.get_last_lineno()),))
513 display_function_part(frame, max_lines_before=8, max_lines_after=5)
514 elif cmd.c_arg1 == 2:
515 display_function_part(frame, max_lines_before=1000,max_lines_after=1000)
516 else:
517 revdb.send_print("Current call stack (most recent call last):")
518 if frame is None:
519 revdb.send_print(" (empty)")
520 frames = []
521 while frame is not None:
522 frames.append(frame)
523 if len(frames) == 200:
524 revdb.send_print(" ...")
525 break
526 frame = frame.get_f_back()
527 while len(frames) > 0:
528 show_frame(frames.pop(), indent=' ')
529 lambda_backtrace = lambda: command_backtrace
530
531
532 def command_locals(cmd, extra):
533 frame = fetch_cur_frame()
534 if frame is None:
535 return
536 space = dbstate.space
537 with non_standard_code:
538 try:
539 prepare_print_environment(space)
540 space.appexec([space.sys,
541 frame.getdictscope()], """(sys, locals):
542 lst = sorted(locals.keys())
543 print('Locals:')
544 for key in lst:
545 try:
546 print(' %s =' % key, end=' ', flush=True)
547 s = '%r' % locals[key]
548 if len(s) > 140:
549 s = s[:100] + '...' + s[-30:]
550 print(s)
551 except:
552 exc, val, tb = sys.exc_info()
553 print('!<%s: %r>' % (exc, val))
554 """)
555 except OperationError as e:
556 revdb.send_print(e.errorstr(space, use_repr=True))
557 lambda_locals = lambda: command_locals
558
559 # ____________________________________________________________
560
561
562 def check_and_trigger_bkpt(pycode, opindex):
563 # We cache on 'pycode.co_revdb_bkpt_cache' either None or a dict
564 # mapping {opindex: bkpt_num}. This cache is updated when the
565 # version in 'pycode.co_revdb_bkpt_version' does not match
566 # 'dbstate.breakpoint_version' any more.
567 if pycode.co_revdb_bkpt_version != dbstate.breakpoint_version:
568 update_bkpt_cache(pycode)
569 cache = pycode.co_revdb_bkpt_cache
570 if cache is not None and opindex in cache:
571 return cache[opindex]
572 else:
573 return -1
574
575 def update_bkpt_cache(pycode):
576 # initialized by command_breakpoints():
577 # dbstate.breakpoint_filelines == [('FILENAME', lineno, bkpt_num)]
578 # computed lazily (here, first half of the logic):
579 # dbstate.breakpoint_by_file == {'co_filename': {lineno: bkpt_num}}
580 # the goal is to set:
581 # pycode.co_revdb_bkpt_cache == {opindex: bkpt_num}
582
583 co_filename = pycode.co_filename
584 try:
585 linenos = dbstate.breakpoint_by_file[co_filename]
586 except KeyError:
587 linenos = None
588 match = co_filename.upper() # ignore cAsE in filename matching
589 for filename, lineno, bkpt_num in dbstate.breakpoint_filelines:
590 if match.endswith(filename) and (
591 len(match) == len(filename) or
592 match[-len(filename)-1] in '/\\'): # a valid prefix
593 if linenos is None:
594 linenos = {}
595 linenos[lineno] = bkpt_num
596 dbstate.breakpoint_by_file[co_filename] = linenos
597
598 newcache = None
599 if linenos is not None:
600 # parse co_lnotab to figure out the opindexes that correspond
601 # to the marked line numbers. here, linenos == {lineno: bkpt_num}
602 for addr, lineno in find_line_starts(pycode):
603 if lineno in linenos:
604 if newcache is None:
605 newcache = {}
606 newcache[addr] = linenos[lineno]
607
608 pycode.co_revdb_bkpt_cache = newcache
609 pycode.co_revdb_bkpt_version = dbstate.breakpoint_version
610
611
612 def valid_identifier(s):
613 if not s:
614 return False
615 if s[0].isdigit():
616 return False
617 for c in s:
618 if not (c.isalnum() or c == '_'):
619 return False
620 return True
621
622 def add_breakpoint_funcname(name, i):
623 if dbstate.breakpoint_funcnames is None:
624 dbstate.breakpoint_funcnames = {}
625 dbstate.breakpoint_funcnames[name] = i
626
627 def add_breakpoint_fileline(filename, lineno, i):
628 # dbstate.breakpoint_filelines is just a list of (FILENAME, lineno, i).
629 # dbstate.breakpoint_by_file is {co_filename: {lineno: i}}, but
630 # computed lazily when we encounter a code object with the given
631 # co_filename. Any suffix 'filename' matches 'co_filename'.
632 if dbstate.breakpoint_filelines is None:
633 dbstate.breakpoint_filelines = []
634 dbstate.breakpoint_by_file = {}
635 dbstate.breakpoint_filelines.append((filename.upper(), lineno, i))
636
637 def add_breakpoint(name, i):
638 # if it is empty, complain
639 if not name:
640 revdb.send_print("Empty breakpoint name")
641 revdb.send_change_breakpoint(i)
642 return
643 # if it is surrounded by < >, it is the name of a code object
644 if name.startswith('<') and name.endswith('>'):
645 add_breakpoint_funcname(name, i)
646 return
647 # if it has no ':', it can be a valid identifier (which we
648 # register as a function name), or a lineno
649 original_name = name
650 j = name.rfind(':')
651 if j < 0:
652 try:
653 lineno = int(name)
654 except ValueError:
655 if name.endswith('()'):
656 n = len(name) - 2
657 assert n >= 0
658 name = name[:n]
659 if not valid_identifier(name):
660 revdb.send_print(
661 'Note: "%s()" doesn''t look like a function name. '
662 'Setting breakpoint anyway' % name)
663 add_breakpoint_funcname(name, i)
664 name += '()'
665 if name != original_name:
666 revdb.send_change_breakpoint(i, name)
667 return
668 # "number" does the same as ":number"
669 filename = ''
670 else:
671 # if it has a ':', it must end in ':lineno'
672 try:
673 lineno = int(name[j+1:])
674 except ValueError:
675 revdb.send_print('expected a line number after colon')
676 revdb.send_change_breakpoint(i)
677 return
678 filename = name[:j]
679
680 # the text before must be a pathname, possibly a relative one,
681 # or be escaped by < >. if it isn't, make it absolute and normalized
682 # and warn if it doesn't end in '.py'.
683 if filename == '':
684 frame = fetch_cur_frame()
685 if frame is None:
686 revdb.send_change_breakpoint(i)
687 return
688 filename = frame.getcode().co_filename
689 elif filename.startswith('<') and filename.endswith('>'):
690 pass # use unmodified
691 elif not filename.lower().endswith('.py'):
692 # use unmodified, but warn
693 revdb.send_print(
694 'Note: "%s" doesn''t look like a Python filename. '
695 'Setting breakpoint anyway' % (filename,))
696
697 add_breakpoint_fileline(filename, lineno, i)
698 name = '%s:%d' % (filename, lineno)
699 if name != original_name:
700 revdb.send_change_breakpoint(i, name)
701
702 def command_breakpoints(cmd, extra):
703 space = dbstate.space
704 dbstate.breakpoint_stack_id = cmd.c_arg1
705 revdb.set_thread_breakpoint(cmd.c_arg2)
706 dbstate.breakpoint_funcnames = None
707 dbstate.breakpoint_filelines = None
708 dbstate.breakpoint_by_file = None
709 dbstate.breakpoint_version += 1
710 watch_progs = []
711 with non_standard_code:
712 for i, kind, name in revdb.split_breakpoints_arg(extra):
713 if kind == 'B':
714 add_breakpoint(name, i)
715 elif kind == 'W':
716 code = interp_marshal.loads(space, space.newbytes(name))
717 watch_progs.append((code, i, ''))
718 dbstate.watch_progs = watch_progs[:]
719 lambda_breakpoints = lambda: command_breakpoints
720
721
722 def command_watchvalues(cmd, extra):
723 expected = extra.split('\x00')
724 for j in range(len(dbstate.watch_progs)):
725 prog, i, _ = dbstate.watch_progs[j]
726 if i >= len(expected):
727 raise IndexError
728 dbstate.watch_progs[j] = prog, i, expected[i]
729 lambda_watchvalues = lambda: command_watchvalues
730
731
732 def command_stackid(cmd, extra):
733 frame = fetch_cur_frame(silent=True)
734 if frame is not None and cmd.c_arg1 != 0: # parent_flag
735 frame = dbstate.space.getexecutioncontext().getnextframe_nohidden(frame)
736 if frame is None:
737 uid = 0
738 else:
739 uid = revdb.get_unique_id(frame)
740 if revdb.current_place() == -2:
741 hidden_level = 1 # hide the "<<" events from next/bnext commands
742 else:
743 hidden_level = 0
744 revdb.send_answer(revdb.ANSWER_STACKID, uid, hidden_level)
745 lambda_stackid = lambda: command_stackid
746
747
748 def command_allocating(uid, gcref):
749 w_obj = cast_gcref_to_instance(W_Root, gcref)
750 dbstate.printed_objects[uid] = w_obj
751 try:
752 index_metavar = dbstate.watch_futures.pop(uid)
753 except KeyError:
754 pass
755 else:
756 set_metavar(index_metavar, w_obj)
757 lambda_allocating = lambda: command_allocating
758
759
760 def command_attachid(cmd, extra):
761 space = dbstate.space
762 index_metavar = cmd.c_arg1
763 uid = cmd.c_arg2
764 try:
765 w_obj = dbstate.printed_objects[uid]
766 except KeyError:
767 # uid not found, probably a future object
768 dbstate.watch_futures[uid] = index_metavar
769 w_obj = future_object(space)
770 set_metavar(index_metavar, w_obj)
771 lambda_attachid = lambda: command_attachid
772
773
774 def command_compilewatch(cmd, expression):
775 space = dbstate.space
776 with non_standard_code:
777 try:
778 code = compile(expression, 'eval')
779 marshalled_code = space.bytes_w(interp_marshal.dumps(
780 space, code))
781 except OperationError as e:
782 revdb.send_watch(e.errorstr(space), ok_flag=0)
783 else:
784 revdb.send_watch(marshalled_code, ok_flag=1)
785 lambda_compilewatch = lambda: command_compilewatch
786
787 def command_checkwatch(cmd, marshalled_code):
788 space = dbstate.space
789 with non_standard_code:
790 try:
791 code = interp_marshal.loads(space, space.newbytes(marshalled_code))
792 text = _run_watch(space, code)
793 except OperationError as e:
794 revdb.send_watch(e.errorstr(space), ok_flag=0)
795 else:
796 revdb.send_watch(text, ok_flag=1)
797 lambda_checkwatch = lambda: command_checkwatch
798
799
800 def _run_watch(space, prog):
801 # must be called from non_standard_code!
802 w_dict = space.builtin.w_dict
803 w_res = prog.exec_code(space, w_dict, w_dict)
804 return space.text_w(space.repr(w_res))
805
806
807 # ____________________________________________________________
808
809
810 ActionFlag._ticker_revdb_count = -1
811
812 class RDBSignalActionFlag(AbstractActionFlag):
813 # Used instead of pypy.module.signal.interp_signal.SignalActionFlag
814 # when we have reverse-debugging. That other class would work too,
815 # but inefficiently: it would generate two words of data per bytecode.
816 # This class is tweaked to generate one byte per _SIG_TICKER_COUNT
817 # bytecodes, at the expense of not reacting to signals instantly.
818
819 # Threads: after 10'000 calls to decrement_ticker(), it should
820 # return -1. It should also return -1 if there was a signal.
821 # This is done by calling _update_ticker_from_signals() every 100
822 # calls, and invoking rsignal.pypysig_check_and_reset(); this in
823 # turn returns -1 if there was a signal or if it was called 100
824 # times.
825
826 _SIG_TICKER_COUNT = 100
827 _ticker = 0
828 _ticker_revdb_count = _SIG_TICKER_COUNT * 10
829
830 def get_ticker(self):
831 return self._ticker
832
833 def reset_ticker(self, value):
834 self._ticker = value
835
836 def rearm_ticker(self):
837 self._ticker = -1
838
839 def decrement_ticker(self, by):
840 if we_are_translated():
841 c = self._ticker_revdb_count - 1
842 if c < 0:
843 c = self._update_ticker_from_signals()
844 self._ticker_revdb_count = c
845 #if self.has_bytecode_counter: # this 'if' is constant-folded
846 # print ("RDBSignalActionFlag: has_bytecode_counter: "
847 # "not supported for now")
848 # raise NotImplementedError
849 return self._ticker
850
851 def _update_ticker_from_signals(self):
852 from rpython.rlib import rsignal
853 if dbstate.standard_code:
854 if rsignal.pypysig_check_and_reset():
855 self.rearm_ticker()
856 return self._SIG_TICKER_COUNT
857 _update_ticker_from_signals._dont_inline_ = True