2 GDB extension that adds Cython support.
5 from __future__ import with_statement
19 from lxml import etree
25 from xml.etree import cElementTree as etree
29 from xml.etree import ElementTree as etree
32 # normal cElementTree install
33 import cElementTree as etree
35 # normal ElementTree install
36 import elementtree.ElementTree as etree
39 import pygments.lexers
40 import pygments.formatters
43 sys.stderr.write("Install pygments for colorized source code.\n")
45 if hasattr(gdb, 'string_to_argv'):
46 from gdb import string_to_argv
48 from shlex import split as string_to_argv
50 from Cython.Debugger import libpython
54 PythonObject = 'PythonObject'
56 _data_types = dict(CObject=CObject, PythonObject=PythonObject)
57 _filesystemencoding = sys.getfilesystemencoding() or 'UTF-8'
61 def dont_suppress_errors(function):
63 @functools.wraps(function)
64 def wrapper(*args, **kwargs):
66 return function(*args, **kwargs)
73 def default_selected_gdb_frame(err=True):
74 def decorator(function):
75 @functools.wraps(function)
76 def wrapper(self, frame=None, *args, **kwargs):
78 frame = frame or gdb.selected_frame()
80 raise gdb.GdbError("No frame is currently selected.")
82 if err and frame.name() is None:
83 raise NoFunctionNameInFrameError()
85 return function(self, frame, *args, **kwargs)
89 def require_cython_frame(function):
90 @functools.wraps(function)
91 @require_running_program
92 def wrapper(self, *args, **kwargs):
93 frame = kwargs.get('frame') or gdb.selected_frame()
94 if not self.is_cython_function(frame):
95 raise gdb.GdbError('Selected frame does not correspond with a '
96 'Cython function we know about.')
97 return function(self, *args, **kwargs)
100 def dispatch_on_frame(c_command, python_command=None):
101 def decorator(function):
102 @functools.wraps(function)
103 def wrapper(self, *args, **kwargs):
104 is_cy = self.is_cython_function()
105 is_py = self.is_python_function()
107 if is_cy or (is_py and not python_command):
108 function(self, *args, **kwargs)
110 gdb.execute(python_command)
111 elif self.is_relevant_function():
112 gdb.execute(c_command)
114 raise gdb.GdbError("Not a function cygdb knows about. "
115 "Use the normal GDB commands instead.")
120 def require_running_program(function):
121 @functools.wraps(function)
122 def wrapper(*args, **kwargs):
126 raise gdb.GdbError("No frame is currently selected.")
128 return function(*args, **kwargs)
132 def gdb_function_value_to_unicode(function):
133 @functools.wraps(function)
134 def wrapper(self, string, *args, **kwargs):
135 if isinstance(string, gdb.Value):
136 string = string.string()
138 return function(self, string, *args, **kwargs)
142 # Classes that represent the debug information
143 # Don't rename the parameters of these classes, they come directly from the XML
145 class CythonModule(object):
146 def __init__(self, module_name, filename, c_filename):
147 self.name = module_name
148 self.filename = filename
149 self.c_filename = c_filename
151 # {cython_lineno: min(c_linenos)}
152 self.lineno_cy2c = {}
153 # {c_lineno: cython_lineno}
154 self.lineno_c2cy = {}
157 def qualified_name(self, varname):
158 return '.'.join(self.name, varname)
160 class CythonVariable(object):
162 def __init__(self, name, cname, qualified_name, type):
165 self.qualified_name = qualified_name
168 class CythonFunction(CythonVariable):
177 super(CythonFunction, self).__init__(name,
182 self.pf_cname = pf_cname
183 self.lineno = int(lineno)
186 self.step_into_functions = set()
189 # General purpose classes
191 class CythonBase(object):
193 @default_selected_gdb_frame(err=False)
194 def is_cython_function(self, frame):
195 return frame.name() in self.cy.functions_by_cname
197 @default_selected_gdb_frame(err=False)
198 def is_python_function(self, frame):
200 Tells if a frame is associated with a Python function.
201 If we can't read the Python frame information, don't regard it as such.
203 if frame.name() == 'PyEval_EvalFrameEx':
204 pyframe = libpython.Frame(frame).get_pyop()
205 return pyframe and not pyframe.is_optimized_out()
208 @default_selected_gdb_frame()
209 def get_c_function_name(self, frame):
212 @default_selected_gdb_frame()
213 def get_c_lineno(self, frame):
214 return frame.find_sal().line
216 @default_selected_gdb_frame()
217 def get_cython_function(self, frame):
218 result = self.cy.functions_by_cname.get(frame.name())
220 raise NoCythonFunctionInFrameError()
224 @default_selected_gdb_frame()
225 def get_cython_lineno(self, frame):
227 Get the current Cython line number. Returns 0 if there is no
228 correspondence between the C and Cython code.
230 cyfunc = self.get_cython_function(frame)
231 return cyfunc.module.lineno_c2cy.get(self.get_c_lineno(frame), 0)
233 @default_selected_gdb_frame()
234 def get_source_desc(self, frame):
235 filename = lineno = lexer = None
236 if self.is_cython_function(frame):
237 filename = self.get_cython_function(frame).module.filename
238 lineno = self.get_cython_lineno(frame)
240 lexer = pygments.lexers.CythonLexer(stripall=False)
241 elif self.is_python_function(frame):
242 pyframeobject = libpython.Frame(frame).get_pyop()
244 if not pyframeobject:
245 raise gdb.GdbError('Unable to read information on python frame')
247 filename = pyframeobject.filename()
248 lineno = pyframeobject.current_line_num()
251 lexer = pygments.lexers.PythonLexer(stripall=False)
253 symbol_and_line_obj = frame.find_sal()
254 if not symbol_and_line_obj or not symbol_and_line_obj.symtab:
258 filename = symbol_and_line_obj.symtab.filename
259 lineno = symbol_and_line_obj.line
261 lexer = pygments.lexers.CLexer(stripall=False)
263 return SourceFileDescriptor(filename, lexer), lineno
265 @default_selected_gdb_frame()
266 def get_source_line(self, frame):
267 source_desc, lineno = self.get_source_desc()
268 return source_desc.get_source(lineno)
270 @default_selected_gdb_frame()
271 def is_relevant_function(self, frame):
273 returns whether we care about a frame on the user-level when debugging
277 older_frame = frame.older()
278 if self.is_cython_function(frame) or self.is_python_function(frame):
280 elif (parameters.step_into_c_code and
281 older_frame and self.is_cython_function(older_frame)):
282 # direct C function call from a Cython function
283 cython_func = self.get_cython_function(older_frame)
284 return name in cython_func.step_into_functions
288 @default_selected_gdb_frame(err=False)
289 def print_stackframe(self, frame, index, is_c=False):
291 Print a C, Cython or Python stack frame and the line of source code
294 # do this to prevent the require_cython_frame decorator from
295 # raising GdbError when calling self.cy.cy_cvalue.invoke()
296 selected_frame = gdb.selected_frame()
300 source_desc, lineno = self.get_source_desc(frame)
301 except NoFunctionNameInFrameError:
302 print '#%-2d Unknown Frame (compile with -g)' % index
305 if not is_c and self.is_python_function(frame):
306 pyframe = libpython.Frame(frame).get_pyop()
307 if pyframe is None or pyframe.is_optimized_out():
308 # print this python function as a C function
309 return self.print_stackframe(frame, index, is_c=True)
311 func_name = pyframe.co_name
312 func_cname = 'PyEval_EvalFrameEx'
314 elif self.is_cython_function(frame):
315 cyfunc = self.get_cython_function(frame)
316 f = lambda arg: self.cy.cy_cvalue.invoke(arg, frame=frame)
318 func_name = cyfunc.name
319 func_cname = cyfunc.cname
320 func_args = [] # [(arg, f(arg)) for arg in cyfunc.arguments]
322 source_desc, lineno = self.get_source_desc(frame)
323 func_name = frame.name()
324 func_cname = func_name
328 gdb_value = gdb.parse_and_eval(func_cname)
332 # Seriously? Why is the address not an int?
333 func_address = int(str(gdb_value.address).split()[0], 0)
335 a = ', '.join('%s=%s' % (name, val) for name, val in func_args)
336 print '#%-2d 0x%016x in %s(%s)' % (index, func_address, func_name, a),
338 if source_desc.filename is not None:
339 print 'at %s:%s' % (source_desc.filename, lineno),
344 print ' ' + source_desc.get_source(lineno)
348 selected_frame.select()
350 def get_cython_globals_dict(self):
352 Get the Cython globals dict where the remote names are turned into
355 m = gdb.parse_and_eval('__pyx_m')
358 PyModuleObject = gdb.lookup_type('PyModuleObject')
360 raise gdb.GdbError(textwrap.dedent("""\
361 Unable to lookup type PyModuleObject, did you compile python
362 with debugging support (-g)?"""))
364 m = m.cast(PyModuleObject.pointer())
365 pyobject_dict = libpython.PyObjectPtr.from_pyobject_ptr(m['md_dict'])
369 for k, v in pyobject_dict.iteritems():
370 result[k.proxyval(seen)] = v
374 def print_gdb_value(self, name, value, max_name_length=None, prefix=''):
375 if libpython.pretty_printer_lookup(value):
378 typename = '(%s) ' % (value.type,)
380 if max_name_length is None:
381 print '%s%s = %s%s' % (prefix, name, typename, value)
383 print '%s%-*s = %s%s' % (prefix, max_name_length, name, typename,
387 class SourceFileDescriptor(object):
388 def __init__(self, filename, lexer, formatter=None):
389 self.filename = filename
391 self.formatter = formatter
394 return self.filename is not None
397 if pygments and self.lexer and parameters.colorize_code:
398 bg = parameters.terminal_background.value
399 if self.formatter is None:
400 formatter = pygments.formatters.TerminalFormatter(bg=bg)
402 formatter = self.formatter
404 return pygments.highlight(code, self.lexer, formatter)
408 def _get_source(self, start, stop, lex_source, mark_line, lex_entire):
409 with open(self.filename) as f:
410 # to provide "correct" colouring, the entire code needs to be
411 # lexed. However, this makes a lot of things terribly slow, so
412 # we decide not to. Besides, it's unlikely to matter.
414 if lex_source and lex_entire:
415 f = self.lex(f.read()).splitlines()
417 slice = itertools.islice(f, start - 1, stop - 1)
419 for idx, line in enumerate(slice):
420 if start + idx == mark_line:
425 if lex_source and not lex_entire:
426 line = self.lex(line)
428 yield '%s %4d %s' % (prefix, start + idx, line.rstrip())
430 def get_source(self, start, stop=None, lex_source=True, mark_line=0,
432 exc = gdb.GdbError('Unable to retrieve source code')
434 if not self.filename:
437 start = max(start, 1)
443 self._get_source(start, stop, lex_source, mark_line, lex_entire))
450 class CyGDBError(gdb.GdbError):
452 Base class for Cython-command related erorrs
455 def __init__(self, *args):
456 args = args or (self.msg,)
457 super(CyGDBError, self).__init__(*args)
459 class NoCythonFunctionInFrameError(CyGDBError):
461 raised when the user requests the current cython function, which is
464 msg = "Current function is a function cygdb doesn't know about"
466 class NoFunctionNameInFrameError(NoCythonFunctionInFrameError):
468 raised when the name of the C function could not be determined
469 in the current C stack frame
471 msg = ('C function name could not be determined in the current C stack '
477 class CythonParameter(gdb.Parameter):
479 Base class for cython parameters
482 def __init__(self, name, command_class, parameter_class, default=None):
483 self.show_doc = self.set_doc = self.__class__.__doc__
484 super(CythonParameter, self).__init__(name, command_class,
486 if default is not None:
489 def __nonzero__(self):
490 return bool(self.value)
492 __bool__ = __nonzero__ # python 3
494 class CompleteUnqualifiedFunctionNames(CythonParameter):
496 Have 'cy break' complete unqualified function or method names.
499 class ColorizeSourceCode(CythonParameter):
501 Tell cygdb whether to colorize source code.
504 class TerminalBackground(CythonParameter):
506 Tell cygdb about the user's terminal background (light or dark).
509 class StepIntoCCode(CythonParameter):
511 Tells cygdb whether to step into C functions called directly from Cython
515 class CythonParameters(object):
517 Simple container class that might get more functionality in the distant
518 future (mostly to remind us that we're dealing with parameters).
522 self.complete_unqualified = CompleteUnqualifiedFunctionNames(
523 'cy_complete_unqualified',
524 gdb.COMMAND_BREAKPOINTS,
527 self.colorize_code = ColorizeSourceCode(
532 self.terminal_background = TerminalBackground(
533 'cy_terminal_background_color',
537 self.step_into_c_code = StepIntoCCode(
538 'cy_step_into_c_code',
543 parameters = CythonParameters()
548 class CythonCommand(gdb.Command, CythonBase):
550 Base class for Cython commands
553 command_class = gdb.COMMAND_NONE
556 def _register(cls, clsname, args, kwargs):
557 if not hasattr(cls, 'completer_class'):
558 return cls(clsname, cls.command_class, *args, **kwargs)
560 return cls(clsname, cls.command_class, cls.completer_class,
564 def register(cls, *args, **kwargs):
565 alias = getattr(cls, 'alias', None)
567 cls._register(cls.alias, args, kwargs)
569 return cls._register(cls.name, args, kwargs)
572 class CyCy(CythonCommand):
574 Invoke a Cython command. Available commands are:
592 command_class = gdb.COMMAND_NONE
593 completer_class = gdb.COMPLETE_COMMAND
595 def __init__(self, *args):
596 super(CythonCommand, self).__init__(*args, prefix=True)
599 import_ = CyImport.register(),
600 break_ = CyBreak.register(),
601 step = CyStep.register(),
602 next = CyNext.register(),
603 run = CyRun.register(),
604 cont = CyCont.register(),
605 up = CyUp.register(),
606 down = CyDown.register(),
607 bt = CyBacktrace.register(),
608 list = CyList.register(),
609 print_ = CyPrint.register(),
610 locals = CyLocals.register(),
611 globals = CyGlobals.register(),
612 cy_cname = CyCName('cy_cname'),
613 cy_cvalue = CyCValue('cy_cvalue'),
614 cy_lineno = CyLine('cy_lineno'),
617 for command_name, command in commands.iteritems():
619 setattr(self, command_name, command)
623 # Cython module namespace
624 self.cython_namespace = {}
626 # maps (unique) qualified function names (e.g.
627 # cythonmodule.ClassName.method_name) to the CythonFunction object
628 self.functions_by_qualified_name = {}
630 # unique cnames of Cython functions
631 self.functions_by_cname = {}
633 # map function names like method_name to a list of all such
634 # CythonFunction objects
635 self.functions_by_name = collections.defaultdict(list)
638 class CyImport(CythonCommand):
640 Import debug information outputted by the Cython compiler
641 Example: cy import FILE...
645 command_class = gdb.COMMAND_STATUS
646 completer_class = gdb.COMPLETE_FILENAME
648 def invoke(self, args, from_tty):
649 args = args.encode(_filesystemencoding)
650 for arg in string_to_argv(args):
654 raise gdb.GdbError('Unable to open file %r: %s' %
659 for module in t.getroot():
660 cython_module = CythonModule(**module.attrib)
661 self.cy.cython_namespace[cython_module.name] = cython_module
663 for variable in module.find('Globals'):
665 cython_module.globals[d['name']] = CythonVariable(**d)
667 for function in module.find('Functions'):
668 cython_function = CythonFunction(module=cython_module,
671 # update the global function mappings
672 name = cython_function.name
673 qname = cython_function.qualified_name
675 self.cy.functions_by_name[name].append(cython_function)
676 self.cy.functions_by_qualified_name[
677 cython_function.qualified_name] = cython_function
678 self.cy.functions_by_cname[
679 cython_function.cname] = cython_function
681 d = cython_module.functions[qname] = cython_function
683 for local in function.find('Locals'):
685 cython_function.locals[d['name']] = CythonVariable(**d)
687 for step_into_func in function.find('StepIntoFunctions'):
688 d = step_into_func.attrib
689 cython_function.step_into_functions.add(d['name'])
691 cython_function.arguments.extend(
692 funcarg.tag for funcarg in function.find('Arguments'))
694 for marker in module.find('LineNumberMapping'):
695 cython_lineno = int(marker.attrib['cython_lineno'])
696 c_linenos = map(int, marker.attrib['c_linenos'].split())
697 cython_module.lineno_cy2c[cython_lineno] = min(c_linenos)
698 for c_lineno in c_linenos:
699 cython_module.lineno_c2cy[c_lineno] = cython_lineno
701 self.cy.step.init_breakpoints()
704 class CyBreak(CythonCommand):
706 Set a breakpoint for Cython code using Cython qualified name notation, e.g.:
708 cy break cython_modulename.ClassName.method_name...
712 cy break function_or_method_name...
714 or for a line number:
716 cy break cython_module:lineno...
718 Set a Python breakpoint:
719 Break on any function or method named 'func' in module 'modname'
721 cy break -p modname.func...
723 Break on any function or method named 'func'
729 command_class = gdb.COMMAND_BREAKPOINTS
731 def _break_pyx(self, name):
732 modulename, _, lineno = name.partition(':')
735 cython_module = self.cy.cython_namespace[modulename]
737 cython_module = self.get_cython_function().module
739 if lineno in cython_module.lineno_cy2c:
740 c_lineno = cython_module.lineno_cy2c[lineno]
741 breakpoint = '%s:%s' % (cython_module.c_filename, c_lineno)
742 gdb.execute('break ' + breakpoint)
744 raise GdbError("Not a valid line number. "
745 "Does it contain actual code?")
747 def _break_funcname(self, funcname):
748 func = self.cy.functions_by_qualified_name.get(funcname)
752 funcs = self.cy.functions_by_name.get(funcname)
754 gdb.execute('break ' + funcname)
758 # multiple functions, let the user pick one
759 print 'There are multiple such functions:'
760 for idx, func in enumerate(funcs):
761 print '%3d) %s' % (idx, func.qualified_name)
766 "Select a function, press 'a' for all "
767 "functions or press 'q' or '^D' to quit: ")
771 if result.lower() == 'q':
773 elif result.lower() == 'a':
776 elif (result.isdigit() and
777 0 <= int(result) < len(funcs)):
778 break_funcs = [funcs[int(result)]]
781 print 'Not understood...'
783 break_funcs = [funcs[0]]
785 for func in break_funcs:
786 gdb.execute('break %s' % func.cname)
788 gdb.execute('break %s' % func.pf_cname)
790 def invoke(self, function_names, from_tty):
791 argv = string_to_argv(function_names.encode('UTF-8'))
792 if function_names.startswith('-p'):
794 python_breakpoints = True
796 python_breakpoints = False
798 for funcname in argv:
799 if python_breakpoints:
800 gdb.execute('py-break %s' % funcname)
801 elif ':' in funcname:
802 self._break_pyx(funcname)
804 self._break_funcname(funcname)
806 @dont_suppress_errors
807 def complete(self, text, word):
808 names = self.cy.functions_by_qualified_name
809 if parameters.complete_unqualified:
810 names = itertools.chain(names, self.cy.functions_by_name)
812 words = text.strip().split()
813 if words and '.' in words[-1]:
815 compl = [n for n in self.cy.functions_by_qualified_name
816 if n.startswith(lastword)]
818 seen = set(text[:-len(word)].split())
819 return [n for n in names if n.startswith(word) and n not in seen]
821 if len(lastword) > len(word):
822 # readline sees something (e.g. a '.') as a word boundary, so don't
823 # "recomplete" this prefix
824 strip_prefix_length = len(lastword) - len(word)
825 compl = [n[strip_prefix_length:] for n in compl]
830 class CythonCodeStepper(CythonCommand, libpython.GenericCodeStepper):
832 Base class for CyStep and CyNext. It implements the interface dictated by
833 libpython.GenericCodeStepper.
836 def lineno(self, frame):
837 # Take care of the Python and Cython levels. We need to care for both
838 # as we can't simply dispath to 'py-step', since that would work for
839 # stepping through Python code, but it would not step back into Cython-
840 # related code. The C level should be dispatched to the 'step' command.
841 if self.is_cython_function(frame):
842 return self.get_cython_lineno(frame)
844 return libpython.py_step.lineno(frame)
846 def get_source_line(self, frame):
848 line = super(CythonCodeStepper, self).get_source_line(frame)
852 return line.strip() or None
856 return cls(cls.name, stepinto=getattr(cls, 'stepinto', False))
858 def runtime_break_functions(self):
859 if self.is_cython_function():
860 return self.get_cython_function().step_into_functions
862 def static_break_functions(self):
863 result = ['PyEval_EvalFrameEx']
864 result.extend(self.cy.functions_by_cname)
867 def invoke(self, args, from_tty):
868 if not self.is_cython_function() and not self.is_python_function():
874 self.finish_executing(gdb.execute(command, to_string=True))
876 super(CythonCodeStepper, self).invoke(args, from_tty)
879 class CyStep(CythonCodeStepper):
880 "Step through Cython, Python or C code."
886 class CyNext(CythonCodeStepper):
887 "Step-over Python code."
893 class CyRun(CythonCodeStepper):
895 Run a Cython program. This is like the 'run' command, except that it
896 displays Cython or Python source lines as well
902 def invoke(self, *args):
903 self.finish_executing(gdb.execute(self._command, to_string=True))
908 Continue a Cython program. This is like the 'run' command, except that it
909 displays Cython or Python source lines as well.
916 class CyUp(CythonCommand):
918 Go up a Cython, Python or relevant C frame.
923 def invoke(self, *args):
925 gdb.execute(self._command, to_string=True)
926 while not self.is_relevant_function(gdb.selected_frame()):
927 gdb.execute(self._command, to_string=True)
928 except RuntimeError, e:
929 raise gdb.GdbError(*e.args)
931 frame = gdb.selected_frame()
934 frame = frame.older()
937 self.print_stackframe(index=index - 1)
942 Go down a Cython, Python or relevant C frame.
949 class CyBacktrace(CythonCommand):
950 'Print the Cython stack'
953 alias = 'cy backtrace'
954 command_class = gdb.COMMAND_STACK
955 completer_class = gdb.COMPLETE_NONE
957 @require_running_program
958 def invoke(self, args, from_tty):
959 # get the first frame
960 selected_frame = frame = gdb.selected_frame()
962 frame = frame.older()
964 print_all = args == '-a'
972 is_relevant = self.is_relevant_function(frame)
976 if print_all or is_relevant:
977 self.print_stackframe(frame, index)
980 frame = frame.newer()
982 selected_frame.select()
985 class CyList(CythonCommand):
987 List Cython source code. To disable to customize colouring see the cy_*
992 command_class = gdb.COMMAND_FILES
993 completer_class = gdb.COMPLETE_NONE
995 @dispatch_on_frame(c_command='list')
996 def invoke(self, _, from_tty):
997 sd, lineno = self.get_source_desc()
998 source = sd.get_source(lineno - 5, lineno + 5, mark_line=lineno,
1003 class CyPrint(CythonCommand):
1005 Print a Cython variable using 'cy-print x' or 'cy-print module.function.x'
1009 command_class = gdb.COMMAND_DATA
1011 def invoke(self, name, from_tty, max_name_length=None):
1012 if self.is_python_function():
1013 return gdb.execute('py-print ' + name)
1014 elif self.is_cython_function():
1015 value = self.cy.cy_cvalue.invoke(name.lstrip('*'))
1018 value = value.dereference()
1022 self.print_gdb_value(name, value, max_name_length)
1024 gdb.execute('print ' + name)
1027 if self.is_cython_function():
1028 f = self.get_cython_function()
1029 return list(itertools.chain(f.locals, f.globals))
1034 sortkey = lambda (name, value): name.lower()
1036 class CyLocals(CythonCommand):
1038 List the locals from the current Cython frame.
1042 command_class = gdb.COMMAND_STACK
1043 completer_class = gdb.COMPLETE_NONE
1045 def _print_if_initialized(self, cyvar, max_name_length, prefix=''):
1047 value = gdb.parse_and_eval(cyvar.cname)
1048 except RuntimeError:
1049 # variable not initialized yet
1052 self.print_gdb_value(cyvar.name, value, max_name_length, prefix)
1054 @dispatch_on_frame(c_command='info locals', python_command='py-locals')
1055 def invoke(self, args, from_tty):
1056 local_cython_vars = self.get_cython_function().locals
1057 max_name_length = len(max(local_cython_vars, key=len))
1058 for name, cyvar in sorted(local_cython_vars.iteritems(), key=sortkey):
1059 self._print_if_initialized(cyvar, max_name_length)
1062 class CyGlobals(CyLocals):
1064 List the globals from the current Cython module.
1068 command_class = gdb.COMMAND_STACK
1069 completer_class = gdb.COMPLETE_NONE
1071 @dispatch_on_frame(c_command='info variables', python_command='py-globals')
1072 def invoke(self, args, from_tty):
1073 global_python_dict = self.get_cython_globals_dict()
1074 module_globals = self.get_cython_function().module.globals
1077 max_globals_dict_len = 0
1079 max_globals_len = len(max(module_globals, key=len))
1080 if global_python_dict:
1081 max_globals_dict_len = len(max(global_python_dict))
1083 max_name_length = max(max_globals_len, max_globals_dict_len)
1086 print 'Python globals:'
1087 for k, v in sorted(global_python_dict.iteritems(), key=sortkey):
1088 v = v.get_truncated_repr(libpython.MAX_OUTPUT_LEN)
1090 print ' %-*s = %s' % (max_name_length, k, v)
1093 for name, cyvar in sorted(module_globals.iteritems(), key=sortkey):
1094 if name not in seen:
1095 self._print_if_initialized(cyvar, max_name_length,
1101 class CyCName(gdb.Function, CythonBase):
1103 Get the C name of a Cython variable in the current context.
1106 print $cy_cname("function")
1107 print $cy_cname("Class.method")
1108 print $cy_cname("module.function")
1111 @require_cython_frame
1112 @gdb_function_value_to_unicode
1113 def invoke(self, cyname, frame=None):
1114 frame = frame or gdb.selected_frame()
1117 if self.is_cython_function(frame):
1118 cython_function = self.get_cython_function(frame)
1119 if cyname in cython_function.locals:
1120 cname = cython_function.locals[cyname].cname
1121 elif cyname in cython_function.module.globals:
1122 cname = cython_function.module.globals[cyname].cname
1124 qname = '%s.%s' % (cython_function.module.name, cyname)
1125 if qname in cython_function.module.functions:
1126 cname = cython_function.module.functions[qname].cname
1129 cname = self.cy.functions_by_qualified_name.get(cyname)
1132 raise gdb.GdbError('No such Cython variable: %s' % cyname)
1137 class CyCValue(CyCName):
1139 Get the value of a Cython variable.
1142 @require_cython_frame
1143 @gdb_function_value_to_unicode
1144 def invoke(self, cyname, frame=None):
1146 cname = super(CyCValue, self).invoke(cyname, frame=frame)
1147 return gdb.parse_and_eval(cname)
1148 except (gdb.GdbError, RuntimeError):
1149 # variable exists but may not have been initialized yet, or may be
1150 # in the globals dict of the Cython module
1151 d = self.get_cython_globals_dict()
1153 return d[cyname]._gdbval
1155 raise gdb.GdbError("Variable %s not initialized yet." % cyname)
1158 class CyLine(gdb.Function, CythonBase):
1160 Get the current Cython line.
1163 @require_cython_frame
1165 return self.get_cython_lineno()
1168 cy = CyCy.register()