Debian Codegraph @

rpython/rlib/debug.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import sys
4 import time
5 from collections import Counter
6
7 from rpython.rlib.objectmodel import enforceargs
8 from rpython.rtyper.extregistry import ExtRegistryEntry
9 from rpython.rlib.objectmodel import we_are_translated, always_inline
10 from rpython.rlib.rarithmetic import is_valid_int, r_longlong
11 from rpython.rlib.rtimer import read_timestamp
12 from rpython.rtyper.extfunc import register_external
13 from rpython.rtyper.lltypesystem import lltype
14 from rpython.rtyper.lltypesystem import rffi
15 from rpython.translator.tool.cbuild import ExternalCompilationInfo
16
17 # Expose these here (public interface)
18 from rpython.rtyper.debug import (
19 ll_assert, FatalError, fatalerror, fatalerror_notb, debug_print_traceback,
20 ll_assert_not_none)
21
22
23 class DebugLog(list):
24 def debug_print(self, *args):
25 self.append(('debug_print',) + args)
26
27 def debug_start(self, category, time=None):
28 self.append(('debug_start', category, time))
29
30 def debug_stop(self, category, time=None):
31 for i in xrange(len(self) - 1, -1, -1):
32 if self[i][0] == 'debug_start':
33 assert self[i][1] == category, (
34 "nesting error: starts with %r but stops with %r" %
35 (self[i][1], category))
36 starttime = self[i][2]
37 if starttime is not None or time is not None:
38 self[i:] = [(category, starttime, time, self[i + 1:])]
39 else:
40 self[i:] = [(category, self[i + 1:])]
41 return
42 assert False, ("nesting error: no start corresponding to stop %r" %
43 (category,))
44
45 def reset(self):
46 # only for tests: empty the log
47 self[:] = []
48
49 def summary(self, flatten=False):
50 res = Counter()
51 def visit(lst):
52 for section, sublist in lst:
53 if section == 'debug_print':
54 continue
55 res[section] += 1
56 if flatten:
57 visit(sublist)
58 #
59 visit(self)
60 return res
61
62 def __repr__(self):
63 import pprint
64 return pprint.pformat(list(self))
65
66 _log = None # patched from tests to be an object of class DebugLog
67 # or compatible
68
69 def debug_print(*args):
70 for arg in args:
71 print(arg, end=" ", file=sys.stderr)
72 print(file=sys.stderr)
73 if _log is not None:
74 _log.debug_print(*args)
75
76 class Entry(ExtRegistryEntry):
77 _about_ = debug_print
78
79 def compute_result_annotation(self, *args_s):
80 return None
81
82 def specialize_call(self, hop):
83 vlist = hop.inputargs(*hop.args_r)
84 hop.exception_cannot_occur()
85 t = hop.rtyper.annotator.translator
86 if t.config.translation.log:
87 hop.genop('debug_print', vlist)
88
89
90 if sys.stderr.isatty():
91 _start_colors_1 = "\033[1m\033[31m"
92 _start_colors_2 = "\033[31m"
93 _stop_colors = "\033[0m"
94 else:
95 _start_colors_1 = ""
96 _start_colors_2 = ""
97 _stop_colors = ""
98
99 @always_inline
100 @enforceargs(str, bool)
101 def debug_start(category, timestamp=False):
102 """
103 Start a PYPYLOG section.
104
105 By default, the return value is undefined. If timestamp is True, always
106 return the current timestamp, even if PYPYLOG is not set.
107 """
108 return _debug_start(category, timestamp)
109
110 @always_inline
111 @enforceargs(str, bool)
112 def debug_stop(category, timestamp=False):
113 """
114 Stop a PYPYLOG section. See debug_start for docs about timestamp
115 """
116 return _debug_stop(category, timestamp)
117
118
119 def _debug_start(category, timestamp):
120 ts = read_timestamp()
121 print('%s[%x] {%s%s' % (_start_colors_1, ts, category, _stop_colors),
122 file=sys.stderr)
123 if _log is not None:
124 _log.debug_start(category)
125
126 if timestamp:
127 return r_longlong(ts)
128 return r_longlong(-42) # random undefined value
129
130 def _debug_stop(category, timestamp):
131 ts = read_timestamp()
132 print('%s[%x] %s}%s' % (_start_colors_2, ts, category, _stop_colors),
133 file=sys.stderr)
134 if _log is not None:
135 _log.debug_stop(category)
136
137 if timestamp:
138 return r_longlong(ts)
139 return r_longlong(-42) # random undefined value
140
141 class Entry(ExtRegistryEntry):
142 _about_ = _debug_start, _debug_stop
143
144 def compute_result_annotation(self, s_category, s_timestamp):
145 from rpython.rlib.rtimer import s_TIMESTAMP
146 return s_TIMESTAMP
147
148 def specialize_call(self, hop):
149 from rpython.rtyper.lltypesystem.rstr import string_repr
150 from rpython.rlib.rtimer import TIMESTAMP_type
151 fn = self.instance
152 _, r_timestamp = hop.args_r
153 vlist = hop.inputargs(string_repr, r_timestamp)
154 hop.exception_cannot_occur()
155 t = hop.rtyper.annotator.translator
156 if t.config.translation.log:
157 opname = fn.__name__[1:] # remove the '_'
158 return hop.genop(opname, vlist, resulttype=TIMESTAMP_type)
159 else:
160 return hop.inputconst(TIMESTAMP_type, r_longlong(0))
161
162
163 def have_debug_prints():
164 # returns True if the next calls to debug_print show up,
165 # and False if they would not have any effect.
166 return True
167
168 def have_debug_prints_for(category_prefix):
169 # returns True if debug prints are enabled for at least some
170 # category strings starting with "prefix" (must be a constant).
171 assert len(category_prefix) > 0
172 return True
173
174 class Entry(ExtRegistryEntry):
175 _about_ = have_debug_prints, have_debug_prints_for
176
177 def compute_result_annotation(self, s_prefix=None):
178 from rpython.annotator import model as annmodel
179 t = self.bookkeeper.annotator.translator
180 if t.config.translation.log:
181 return annmodel.s_Bool
182 else:
183 return self.bookkeeper.immutablevalue(False)
184
185 def specialize_call(self, hop):
186 t = hop.rtyper.annotator.translator
187 hop.exception_cannot_occur()
188 if t.config.translation.log:
189 if hop.args_v:
190 [c_prefix] = hop.args_v
191 assert len(c_prefix.value) > 0
192 args = [hop.inputconst(lltype.Void, c_prefix.value)]
193 return hop.genop('have_debug_prints_for', args,
194 resulttype=lltype.Bool)
195 return hop.genop('have_debug_prints', [], resulttype=lltype.Bool)
196 else:
197 return hop.inputconst(lltype.Bool, False)
198
199
200 def debug_offset():
201 """ Return an offset in log file
202 """
203 return -1
204
205 class Entry(ExtRegistryEntry):
206 _about_ = debug_offset
207
208 def compute_result_annotation(self):
209 from rpython.annotator import model as annmodel
210 return annmodel.SomeInteger()
211
212 def specialize_call(self, hop):
213 hop.exception_cannot_occur()
214 return hop.genop('debug_offset', [], resulttype=lltype.Signed)
215
216
217 def debug_flush():
218 """ Flushes the debug file.
219
220 With the reverse-debugger, it also closes the output log.
221 """
222 pass
223
224 class Entry(ExtRegistryEntry):
225 _about_ = debug_flush
226
227 def compute_result_annotation(self):
228 return None
229
230 def specialize_call(self, hop):
231 hop.exception_cannot_occur()
232 return hop.genop('debug_flush', [])
233
234
235 def debug_forked(original_offset):
236 """ Call after a fork(), passing as argument the result of
237 debug_offset() called before the fork.
238 """
239 pass
240
241 class Entry(ExtRegistryEntry):
242 _about_ = debug_forked
243
244 def compute_result_annotation(self, s_original_offset):
245 return None
246
247 def specialize_call(self, hop):
248 vlist = hop.inputargs(lltype.Signed)
249 hop.exception_cannot_occur()
250 return hop.genop('debug_forked', vlist)
251
252
253 def llinterpcall(RESTYPE, pythonfunction, *args):
254 """When running on the llinterp, this causes the llinterp to call to
255 the provided Python function with the run-time value of the given args.
256 The Python function should return a low-level object of type RESTYPE.
257 This should never be called after translation: use this only if
258 running_on_llinterp is true.
259 """
260 raise NotImplementedError
261
262 class Entry(ExtRegistryEntry):
263 _about_ = llinterpcall
264
265 def compute_result_annotation(self, s_RESTYPE, s_pythonfunction, *args_s):
266 from rpython.annotator import model as annmodel
267 from rpython.rtyper.llannotation import lltype_to_annotation
268 assert s_RESTYPE.is_constant()
269 assert s_pythonfunction.is_constant()
270 s_result = s_RESTYPE.const
271 if isinstance(s_result, lltype.LowLevelType):
272 s_result = lltype_to_annotation(s_result)
273 assert isinstance(s_result, annmodel.SomeObject)
274 return s_result
275
276 def specialize_call(self, hop):
277 from rpython.annotator import model as annmodel
278 RESTYPE = hop.args_s[0].const
279 if not isinstance(RESTYPE, lltype.LowLevelType):
280 assert isinstance(RESTYPE, annmodel.SomeObject)
281 r_result = hop.rtyper.getrepr(RESTYPE)
282 RESTYPE = r_result.lowleveltype
283 pythonfunction = hop.args_s[1].const
284 c_pythonfunction = hop.inputconst(lltype.Void, pythonfunction)
285 args_v = [hop.inputarg(hop.args_r[i], arg=i)
286 for i in range(2, hop.nb_args)]
287 hop.exception_is_here()
288 return hop.genop('debug_llinterpcall', [c_pythonfunction] + args_v,
289 resulttype=RESTYPE)
290
291
292 def check_annotation(arg, checker):
293 """ Function checking if annotation is as expected when translating,
294 does nothing when just run. Checker is supposed to be a constant
295 callable which checks if annotation is as expected,
296 arguments passed are (current annotation, bookkeeper)
297 """
298 return arg
299
300 class Entry(ExtRegistryEntry):
301 _about_ = check_annotation
302
303 def compute_result_annotation(self, s_arg, s_checker):
304 if not s_checker.is_constant():
305 raise ValueError(
306 "Second argument of check_annotation must be constant")
307 checker = s_checker.const
308 checker(s_arg, self.bookkeeper)
309 return s_arg
310
311 def specialize_call(self, hop):
312 hop.exception_cannot_occur()
313 return hop.inputarg(hop.args_r[0], arg=0)
314
315 def check_not_access_directly(arg):
316 """ check that arg does not have the access_directly=True hint set """
317 return arg
318
319 class Entry(ExtRegistryEntry):
320 _about_ = check_not_access_directly
321
322 def compute_result_annotation(self, s_arg):
323 assert not s_arg.flags.get('access_directly', False)
324 return s_arg
325
326 def specialize_call(self, hop):
327 hop.exception_cannot_occur()
328 return hop.inputarg(hop.args_r[0], arg=0)
329
330
331 def make_sure_not_resized(arg):
332 """ Function checking whether annotation of SomeList is never resized,
333 useful for debugging. Does nothing when run directly
334 """
335 return arg
336
337 class Entry(ExtRegistryEntry):
338 _about_ = make_sure_not_resized
339
340 def compute_result_annotation(self, s_arg):
341 from rpython.annotator.model import SomeList, s_None
342 if s_None.contains(s_arg):
343 return s_arg # only None: just return
344 assert isinstance(s_arg, SomeList)
345 # the logic behind it is that we try not to propagate
346 # make_sure_not_resized, when list comprehension is not on
347 config = self.bookkeeper.annotator.translator.config
348 if config.translation.list_comprehension_operations:
349 s_arg.listdef.never_resize()
350 else:
351 from rpython.annotator.annrpython import log
352 log.WARNING(
353 "make_sure_not_resized called, but has no effect since "
354 "list_comprehension is off")
355 return s_arg
356
357 def specialize_call(self, hop):
358 hop.exception_cannot_occur()
359 return hop.inputarg(hop.args_r[0], arg=0)
360
361
362 def mark_dict_non_null(d):
363 """ Mark dictionary as having non-null keys and values. A warning would
364 be emitted (not an error!) in case annotation disagrees.
365
366 This doesn't work for r_dicts. For them, pass
367 r_dict(..., force_non_null=True) to the constructor.
368 """
369 assert isinstance(d, dict)
370 return d
371
372
373 class DictMarkEntry(ExtRegistryEntry):
374 _about_ = mark_dict_non_null
375
376 def compute_result_annotation(self, s_dict):
377 from rpython.annotator.model import SomeDict
378
379 assert isinstance(s_dict, SomeDict)
380 s_dict.dictdef.force_non_null = True
381 return s_dict
382
383 def specialize_call(self, hop):
384 hop.exception_cannot_occur()
385 return hop.inputarg(hop.args_r[0], arg=0)
386
387 class IntegerCanBeNegative(Exception):
388 pass
389
390 class UnexpectedRUInt(Exception):
391 pass
392
393 class ExpectedRegularInt(Exception):
394 pass
395
396 class NegativeArgumentNotAllowed(Exception):
397 pass
398
399 def check_nonneg(x):
400 """Give a translation-time error if 'x' is not known to be non-negative.
401 To help debugging, this also gives a translation-time error if 'x' is
402 actually typed as an r_uint (in which case the call to check_nonneg()
403 is a bit strange and probably unexpected).
404 """
405 try:
406 assert type(x)(-1) < 0 # otherwise, 'x' is a r_uint or similar
407 except NegativeArgumentNotAllowed:
408 pass
409 else:
410 assert x >= 0
411 return x
412
413 class Entry(ExtRegistryEntry):
414 _about_ = check_nonneg
415
416 def compute_result_annotation(self, s_arg):
417 from rpython.annotator.model import SomeInteger
418 if isinstance(s_arg, SomeInteger) and s_arg.unsigned:
419 raise UnexpectedRUInt("check_nonneg() arg is a %s" % (
420 s_arg.knowntype,))
421 s_nonneg = SomeInteger(nonneg=True)
422 if not s_nonneg.contains(s_arg):
423 raise IntegerCanBeNegative
424 return s_arg
425
426 def specialize_call(self, hop):
427 hop.exception_cannot_occur()
428 return hop.inputarg(hop.args_r[0], arg=0)
429
430 def check_regular_int(x):
431 """Give a translation-time error if 'x' is not a plain int
432 (e.g. if it's a r_longlong or an r_uint).
433 """
434 assert is_valid_int(x)
435 return x
436
437 class Entry(ExtRegistryEntry):
438 _about_ = check_regular_int
439
440 def compute_result_annotation(self, s_arg):
441 from rpython.annotator.model import SomeInteger
442 if not SomeInteger().contains(s_arg):
443 raise ExpectedRegularInt(s_arg)
444 return s_arg
445
446 def specialize_call(self, hop):
447 hop.exception_cannot_occur()
448 return hop.inputarg(hop.args_r[0], arg=0)
449
450 def check_list_of_chars(l):
451 if not we_are_translated():
452 assert isinstance(l, list)
453 for x in l:
454 assert isinstance(x, (unicode, str)) and len(x) == 1
455 return l
456
457 class NotAListOfChars(Exception):
458 pass
459
460 class Entry(ExtRegistryEntry):
461 _about_ = check_list_of_chars
462
463 def compute_result_annotation(self, s_arg):
464 from rpython.annotator.model import SomeList, s_None
465 from rpython.annotator.model import SomeChar, SomeUnicodeCodePoint
466 from rpython.annotator.model import SomeImpossibleValue
467 if s_None.contains(s_arg):
468 return s_arg # only None: just return
469 assert isinstance(s_arg, SomeList)
470 if not isinstance(
471 s_arg.listdef.listitem.s_value,
472 (SomeChar, SomeUnicodeCodePoint, SomeImpossibleValue)):
473 raise NotAListOfChars
474 return s_arg
475
476 def specialize_call(self, hop):
477 hop.exception_cannot_occur()
478 return hop.inputarg(hop.args_r[0], arg=0)
479
480
481 def attach_gdb():
482 import pdb; pdb.set_trace()
483
484 if not sys.platform.startswith('win'):
485 if sys.platform.startswith('linux'):
486 # Only necessary on Linux
487 eci = ExternalCompilationInfo(includes=['string.h', 'assert.h',
488 'sys/prctl.h'],
489 post_include_bits=["""
490 /* If we have an old Linux kernel (or compile with old system headers),
491 the following two macros are not defined. But we would still like
492 a pypy translated on such a system to run on a more modern system. */
493 #ifndef PR_SET_PTRACER
494 # define PR_SET_PTRACER 0x59616d61
495 #endif
496 #ifndef PR_SET_PTRACER_ANY
497 # define PR_SET_PTRACER_ANY ((unsigned long)-1)
498 #endif
499 static void pypy__allow_attach(void) {
500 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
501 }
502 """])
503 allow_attach = rffi.llexternal(
504 "pypy__allow_attach", [], lltype.Void,
505 compilation_info=eci, _nowrapper=True)
506 else:
507 # Do nothing, there's no prctl
508 def allow_attach():
509 pass
510
511 def impl_attach_gdb():
512 import os
513 allow_attach()
514 pid = os.getpid()
515 gdbpid = os.fork()
516 if gdbpid == 0:
517 shell = os.environ.get("SHELL") or "/bin/sh"
518 sepidx = shell.rfind(os.sep) + 1
519 if sepidx > 0:
520 argv0 = shell[sepidx:]
521 else:
522 argv0 = shell
523 try:
524 os.execv(shell, [argv0, "-c", "gdb -p %d" % pid])
525 except OSError as e:
526 os.write(2, "Could not start GDB: %s" % (
527 os.strerror(e.errno)))
528 os._exit(1)
529 else:
530 time.sleep(1) # give the GDB time to attach
531
532 else:
533 def make_vs_attach_eci():
534 # The COM interface to the Debugger has to be compiled as a .cpp file by
535 # Visual C. So we generate the source and then add a commandline switch
536 # to treat this source file as C++
537 import os
538 eci = ExternalCompilationInfo(post_include_bits=["""
539 #ifdef __cplusplus
540 extern "C" {
541 #endif
542 RPY_EXPORTED void AttachToVS();
543 #ifdef __cplusplus
544 }
545 #endif
546 """],
547 separate_module_sources=["""
548 #import "libid:80cc9f66-e7d8-4ddd-85b6-d9e6cd0e93e2" version("8.0") lcid("0") raw_interfaces_only named_guids
549 extern "C" RPY_EXPORTED void AttachToVS() {
550 CoInitialize(0);
551 HRESULT hr;
552 CLSID Clsid;
553
554 CLSIDFromProgID(L"VisualStudio.DTE", &Clsid);
555 IUnknown *Unknown;
556 if (FAILED(GetActiveObject(Clsid, 0, &Unknown))) {
557 puts("Could not attach to Visual Studio (is it not running?");
558 return;
559 }
560
561 EnvDTE::_DTE *Interface;
562 hr = Unknown->QueryInterface(&Interface);
563 if (FAILED(GetActiveObject(Clsid, 0, &Unknown))) {
564 puts("Could not open COM interface to Visual Studio (no permissions?)");
565 return;
566 }
567
568 EnvDTE::Debugger *Debugger;
569 puts("Waiting for Visual Studio Debugger to become idle");
570 while (FAILED(Interface->get_Debugger(&Debugger)));
571
572 EnvDTE::Processes *Processes;
573 while (FAILED(Debugger->get_LocalProcesses(&Processes)));
574
575 long Count = 0;
576 if (FAILED(Processes->get_Count(&Count))) {
577 puts("Cannot query Process count");
578 }
579
580 for (int i = 0; i <= Count; i++) {
581 EnvDTE::Process *Process;
582 if (FAILED(Processes->Item(variant_t(i), &Process))) {
583 continue;
584 }
585
586 long ProcessID;
587 while (FAILED(Process->get_ProcessID(&ProcessID)));
588
589 if (ProcessID == GetProcessId(GetCurrentProcess())) {
590 printf("Found process ID %d\\n", ProcessID);
591 Process->Attach();
592 Debugger->Break(false);
593 CoUninitialize();
594 return;
595 }
596 }
597 }
598 """]
599 )
600 eci = eci.convert_sources_to_files()
601 d = eci._copy_attributes()
602 cfile = d['separate_module_files'][0]
603 cppfile = cfile.replace(".c", "_vsdebug.cpp")
604 os.rename(cfile, cppfile)
605 d['separate_module_files'] = [cppfile]
606 return ExternalCompilationInfo(**d)
607
608 ll_attach = rffi.llexternal("AttachToVS", [], lltype.Void,
609 compilation_info=make_vs_attach_eci())
610 def impl_attach_gdb():
611 #ll_attach()
612 print("AttachToVS is disabled at the moment (compilation failure)")
613
614 register_external(attach_gdb, [], result=None,
615 export_name="impl_attach_gdb", llimpl=impl_attach_gdb)