diff options
author | Simon Marchi <simon.marchi@polymtl.ca> | 2021-05-07 10:56:20 -0400 |
---|---|---|
committer | Simon Marchi <simon.marchi@polymtl.ca> | 2021-05-07 10:56:20 -0400 |
commit | 13123da89a2c7e06a5312ca6b4b24c68ba1c6c2d (patch) | |
tree | ec33a85ccb58f44445608d0cab68020fa588cb74 /gdb/testsuite/gdb.python | |
parent | a9b49cbcd5935a713da5715799ea3b24e0a52851 (diff) | |
download | gdb-13123da89a2c7e06a5312ca6b4b24c68ba1c6c2d.zip gdb-13123da89a2c7e06a5312ca6b4b24c68ba1c6c2d.tar.gz gdb-13123da89a2c7e06a5312ca6b4b24c68ba1c6c2d.tar.bz2 |
gdb: re-format Python files using black 21.4b0
Re-format all Python files using black [1] version 21.4b0. The goal is
that from now on, we keep all Python files formatted using black. And
that we never have to discuss formatting during review (for these files
at least) ever again.
One change is needed in gdb.python/py-prettyprint.exp, because it
matches the string representation of an exception, which shows source
code. So the change in formatting must be replicated in the expected
regexp.
To document our usage of black I plan on adding this to the "GDB Python
Coding Standards" wiki page [2]:
--8<--
All Python source files under the `gdb/` directory must be formatted
using black version 21.4b0.
This specific version can be installed using:
$ pip3 install 'black == 21.4b0'
All you need to do to re-format files is run `black <file/directory>`,
and black will re-format any Python file it finds in there. It runs
quite fast, so the simplest is to do:
$ black gdb/
from the top-level.
If you notice that black produces changes unrelated to your patch, it's
probably because someone forgot to run it before you. In this case,
don't include unrelated hunks in your patch. Push an obvious patch
fixing the formatting and rebase your work on top of that.
-->8--
Once this is merged, I plan on setting a up an `ignoreRevsFile`
config so that git-blame ignores this commit, as described here:
https://github.com/psf/black#migrating-your-code-style-without-ruining-git-blame
I also plan on working on a git commit hook (checked in the repo) to
automatically check the formatting of the Python files on commit.
[1] https://pypi.org/project/black/
[2] https://sourceware.org/gdb/wiki/Internals%20GDB-Python-Coding-Standards
gdb/ChangeLog:
* Re-format all Python files using black.
gdb/testsuite/ChangeLog:
* Re-format all Python files using black.
* gdb.python/py-prettyprint.exp (run_lang_tests): Adjust.
Change-Id: I28588a22c2406afd6bc2703774ddfff47cd61919
Diffstat (limited to 'gdb/testsuite/gdb.python')
34 files changed, 902 insertions, 750 deletions
diff --git a/gdb/testsuite/gdb.python/py-auto-load-chaining-f1.o-gdb.py b/gdb/testsuite/gdb.python/py-auto-load-chaining-f1.o-gdb.py index 4f5a4e7..e15e196 100644 --- a/gdb/testsuite/gdb.python/py-auto-load-chaining-f1.o-gdb.py +++ b/gdb/testsuite/gdb.python/py-auto-load-chaining-f1.o-gdb.py @@ -18,20 +18,18 @@ import re -print ("Entering f1.o auto-load script") +print("Entering f1.o auto-load script") -print ("Current objfile is: %s" - % gdb.current_objfile ().filename) +print("Current objfile is: %s" % gdb.current_objfile().filename) -print ("Chain loading f2.o...") +print("Chain loading f2.o...") -filename = gdb.current_objfile ().filename -filename = re.sub (r"-f1.o$", "-f2.o", filename) -r2 = gdb.lookup_global_symbol ('region_2').value () -gdb.execute ("add-symbol-file %s 0x%x" % (filename, r2)) +filename = gdb.current_objfile().filename +filename = re.sub(r"-f1.o$", "-f2.o", filename) +r2 = gdb.lookup_global_symbol("region_2").value() +gdb.execute("add-symbol-file %s 0x%x" % (filename, r2)) -print ("After loading f2.o...") -print ("Current objfile is: %s" - % gdb.current_objfile ().filename) +print("After loading f2.o...") +print("Current objfile is: %s" % gdb.current_objfile().filename) -print ("Leaving f1.o auto-load script") +print("Leaving f1.o auto-load script") diff --git a/gdb/testsuite/gdb.python/py-auto-load-chaining-f2.o-gdb.py b/gdb/testsuite/gdb.python/py-auto-load-chaining-f2.o-gdb.py index f5c29cd..b94a9da 100644 --- a/gdb/testsuite/gdb.python/py-auto-load-chaining-f2.o-gdb.py +++ b/gdb/testsuite/gdb.python/py-auto-load-chaining-f2.o-gdb.py @@ -16,9 +16,8 @@ # This script is auto-loaded when the py-auto-load-chaining-f2.o # object is loaded. -print ("Entering f2.o auto-load script") +print("Entering f2.o auto-load script") -print ("Current objfile is: %s" - % gdb.current_objfile ().filename) +print("Current objfile is: %s" % gdb.current_objfile().filename) -print ("Leaving f2.o auto-load script") +print("Leaving f2.o auto-load script") diff --git a/gdb/testsuite/gdb.python/py-bad-printers.py b/gdb/testsuite/gdb.python/py-bad-printers.py index 412b889..8e13f3d 100644 --- a/gdb/testsuite/gdb.python/py-bad-printers.py +++ b/gdb/testsuite/gdb.python/py-bad-printers.py @@ -29,18 +29,18 @@ class BadChildrenContainerPrinter1(object): self.val = val def to_string(self): - return 'container %s with %d elements' % (self.val['name'], self.val['len']) + return "container %s with %d elements" % (self.val["name"], self.val["len"]) @staticmethod def _bad_iterator(pointer, len): start = pointer end = pointer + len while pointer != end: - yield 'intentional violation of children iterator protocol' + yield "intentional violation of children iterator protocol" pointer += 1 def children(self): - return self._bad_iterator(self.val['elements'], self.val['len']) + return self._bad_iterator(self.val["elements"], self.val["len"]) class BadChildrenContainerPrinter2(object): @@ -50,7 +50,7 @@ class BadChildrenContainerPrinter2(object): self.val = val def to_string(self): - return 'container %s with %d elements' % (self.val['name'], self.val['len']) + return "container %s with %d elements" % (self.val["name"], self.val["len"]) @staticmethod def _bad_iterator(pointer, len): @@ -58,20 +58,18 @@ class BadChildrenContainerPrinter2(object): end = pointer + len while pointer != end: # The first argument is supposed to be a string. - yield (42, 'intentional violation of children iterator protocol') + yield (42, "intentional violation of children iterator protocol") pointer += 1 def children(self): - return self._bad_iterator(self.val['elements'], self.val['len']) + return self._bad_iterator(self.val["elements"], self.val["len"]) def build_pretty_printer(): pp = gdb.printing.RegexpCollectionPrettyPrinter("bad-printers") - pp.add_printer('container1', '^container$', - BadChildrenContainerPrinter1) - pp.add_printer('container2', '^container$', - BadChildrenContainerPrinter2) + pp.add_printer("container1", "^container$", BadChildrenContainerPrinter1) + pp.add_printer("container2", "^container$", BadChildrenContainerPrinter2) return pp diff --git a/gdb/testsuite/gdb.python/py-breakpoint-create-fail.py b/gdb/testsuite/gdb.python/py-breakpoint-create-fail.py index bb2f0da..f44126b 100644 --- a/gdb/testsuite/gdb.python/py-breakpoint-create-fail.py +++ b/gdb/testsuite/gdb.python/py-breakpoint-create-fail.py @@ -18,13 +18,13 @@ import gdb class MyBP(gdb.Breakpoint): def stop(self): - print('MyBP.stop was invoked!') + print("MyBP.stop was invoked!") # Don't make this breakpoint stop return False try: - bp = MyBP('does_not_exist', gdb.BP_WATCHPOINT) + bp = MyBP("does_not_exist", gdb.BP_WATCHPOINT) except RuntimeError: pass else: diff --git a/gdb/testsuite/gdb.python/py-completion.py b/gdb/testsuite/gdb.python/py-completion.py index 8d3ba3a..a34c3a7 100644 --- a/gdb/testsuite/gdb.python/py-completion.py +++ b/gdb/testsuite/gdb.python/py-completion.py @@ -17,123 +17,190 @@ import gdb + class CompleteFileInit(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completefileinit',gdb.COMMAND_USER,gdb.COMPLETE_FILENAME) + def __init__(self): + gdb.Command.__init__( + self, "completefileinit", gdb.COMMAND_USER, gdb.COMPLETE_FILENAME + ) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') class CompleteFileMethod(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completefilemethod',gdb.COMMAND_USER) + def __init__(self): + gdb.Command.__init__(self, "completefilemethod", gdb.COMMAND_USER) - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + return gdb.COMPLETE_FILENAME - def complete(self,text,word): - return gdb.COMPLETE_FILENAME class CompleteFileCommandCond(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completefilecommandcond',gdb.COMMAND_USER) - - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') - - def complete(self,text,word): - # This is a test made to know if the command - # completion still works fine. When the user asks to - # complete something like "completefilecommandcond - # /path/to/py-completion-t", it should not complete to - # "/path/to/py-completion-test/", but instead just - # wait for input. - if "py-completion-t" in text: - return gdb.COMPLETE_COMMAND - else: - return gdb.COMPLETE_FILENAME + def __init__(self): + gdb.Command.__init__(self, "completefilecommandcond", gdb.COMMAND_USER) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + # This is a test made to know if the command + # completion still works fine. When the user asks to + # complete something like "completefilecommandcond + # /path/to/py-completion-t", it should not complete to + # "/path/to/py-completion-test/", but instead just + # wait for input. + if "py-completion-t" in text: + return gdb.COMPLETE_COMMAND + else: + return gdb.COMPLETE_FILENAME + class CompleteLimit1(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completelimit1',gdb.COMMAND_USER) + def __init__(self): + gdb.Command.__init__(self, "completelimit1", gdb.COMMAND_USER) - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") - def complete(self,text,word): - return ["cl11", "cl12", "cl13"] + def complete(self, text, word): + return ["cl11", "cl12", "cl13"] -class CompleteLimit2(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completelimit2', - gdb.COMMAND_USER) - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') +class CompleteLimit2(gdb.Command): + def __init__(self): + gdb.Command.__init__(self, "completelimit2", gdb.COMMAND_USER) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + return [ + "cl21", + "cl23", + "cl25", + "cl27", + "cl29", + "cl22", + "cl24", + "cl26", + "cl28", + "cl210", + ] - def complete(self,text,word): - return ["cl21", "cl23", "cl25", "cl27", "cl29", - "cl22", "cl24", "cl26", "cl28", "cl210"] class CompleteLimit3(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completelimit3', - gdb.COMMAND_USER) - - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') + def __init__(self): + gdb.Command.__init__(self, "completelimit3", gdb.COMMAND_USER) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + return [ + "cl31", + "cl33", + "cl35", + "cl37", + "cl39", + "cl32", + "cl34", + "cl36", + "cl38", + "cl310", + ] - def complete(self,text,word): - return ["cl31", "cl33", "cl35", "cl37", "cl39", - "cl32", "cl34", "cl36", "cl38", "cl310"] class CompleteLimit4(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completelimit4', - gdb.COMMAND_USER) - - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') + def __init__(self): + gdb.Command.__init__(self, "completelimit4", gdb.COMMAND_USER) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + return [ + "cl41", + "cl43", + "cl45", + "cl47", + "cl49", + "cl42", + "cl44", + "cl46", + "cl48", + "cl410", + ] - def complete(self,text,word): - return ["cl41", "cl43", "cl45", "cl47", "cl49", - "cl42", "cl44", "cl46", "cl48", "cl410"] class CompleteLimit5(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completelimit5', - gdb.COMMAND_USER) + def __init__(self): + gdb.Command.__init__(self, "completelimit5", gdb.COMMAND_USER) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + return [ + "cl51", + "cl53", + "cl55", + "cl57", + "cl59", + "cl52", + "cl54", + "cl56", + "cl58", + "cl510", + ] - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') - - def complete(self,text,word): - return ["cl51", "cl53", "cl55", "cl57", "cl59", - "cl52", "cl54", "cl56", "cl58", "cl510"] class CompleteLimit6(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completelimit6', - gdb.COMMAND_USER) - - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') + def __init__(self): + gdb.Command.__init__(self, "completelimit6", gdb.COMMAND_USER) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + return [ + "cl61", + "cl63", + "cl65", + "cl67", + "cl69", + "cl62", + "cl64", + "cl66", + "cl68", + "cl610", + ] - def complete(self,text,word): - return ["cl61", "cl63", "cl65", "cl67", "cl69", - "cl62", "cl64", "cl66", "cl68", "cl610"] class CompleteLimit7(gdb.Command): - def __init__(self): - gdb.Command.__init__(self,'completelimit7', - gdb.COMMAND_USER) - - def invoke(self,argument,from_tty): - raise gdb.GdbError('not implemented') + def __init__(self): + gdb.Command.__init__(self, "completelimit7", gdb.COMMAND_USER) + + def invoke(self, argument, from_tty): + raise gdb.GdbError("not implemented") + + def complete(self, text, word): + return [ + "cl71", + "cl73", + "cl75", + "cl77", + "cl79", + "cl72", + "cl74", + "cl76", + "cl78", + "cl710", + ] - def complete(self,text,word): - return ["cl71", "cl73", "cl75", "cl77", "cl79", - "cl72", "cl74", "cl76", "cl78", "cl710"] CompleteFileInit() CompleteFileMethod() diff --git a/gdb/testsuite/gdb.python/py-error.py b/gdb/testsuite/gdb.python/py-error.py index 14934d4..9ef3af9 100644 --- a/gdb/testsuite/gdb.python/py-error.py +++ b/gdb/testsuite/gdb.python/py-error.py @@ -15,11 +15,15 @@ import gdb + class ClassName(gdb.Command): - 'a' + "a" + def __init__(self): - gdb.Command.__init__ (self, "ClassName", gdb.COMMAND_DATA, prefix=True) + gdb.Command.__init__(self, "ClassName", gdb.COMMAND_DATA, prefix=True) + def invoke(self, args, from_tty): print + ClassName() diff --git a/gdb/testsuite/gdb.python/py-events.py b/gdb/testsuite/gdb.python/py-events.py index bd1dd74..6a67627 100644 --- a/gdb/testsuite/gdb.python/py-events.py +++ b/gdb/testsuite/gdb.python/py-events.py @@ -17,102 +17,114 @@ # printers. import gdb -def signal_stop_handler (event): - if (isinstance (event, gdb.StopEvent)): - print ("event type: stop") - if (isinstance (event, gdb.SignalEvent)): - print ("stop reason: signal") - print ("stop signal: %s" % (event.stop_signal)) - if ( event.inferior_thread is not None) : - print ("thread num: %s" % (event.inferior_thread.num)) - -def breakpoint_stop_handler (event): - if (isinstance (event, gdb.StopEvent)): - print ("event type: stop") - if (isinstance (event, gdb.BreakpointEvent)): - print ("stop reason: breakpoint") - print ("first breakpoint number: %s" % (event.breakpoint.number)) + +def signal_stop_handler(event): + if isinstance(event, gdb.StopEvent): + print("event type: stop") + if isinstance(event, gdb.SignalEvent): + print("stop reason: signal") + print("stop signal: %s" % (event.stop_signal)) + if event.inferior_thread is not None: + print("thread num: %s" % (event.inferior_thread.num)) + + +def breakpoint_stop_handler(event): + if isinstance(event, gdb.StopEvent): + print("event type: stop") + if isinstance(event, gdb.BreakpointEvent): + print("stop reason: breakpoint") + print("first breakpoint number: %s" % (event.breakpoint.number)) for bp in event.breakpoints: - print ("breakpoint number: %s" % (bp.number)) - if ( event.inferior_thread is not None) : - print ("thread num: %s" % (event.inferior_thread.num)) + print("breakpoint number: %s" % (bp.number)) + if event.inferior_thread is not None: + print("thread num: %s" % (event.inferior_thread.num)) else: - print ("all threads stopped") - -def exit_handler (event): - assert (isinstance (event, gdb.ExitedEvent)) - print ("event type: exit") - print ("exit code: %d" % (event.exit_code)) - print ("exit inf: %d" % (event.inferior.num)) - print ("dir ok: %s" % str('exit_code' in dir(event))) - -def continue_handler (event): - assert (isinstance (event, gdb.ContinueEvent)) - print ("event type: continue") - if ( event.inferior_thread is not None) : - print ("thread num: %s" % (event.inferior_thread.num)) - -def new_objfile_handler (event): - assert (isinstance (event, gdb.NewObjFileEvent)) - print ("event type: new_objfile") - print ("new objfile name: %s" % (event.new_objfile.filename)) - -def clear_objfiles_handler (event): - assert (isinstance (event, gdb.ClearObjFilesEvent)) - print ("event type: clear_objfiles") - print ("progspace: %s" % (event.progspace.filename)) - -def inferior_call_handler (event): - if (isinstance (event, gdb.InferiorCallPreEvent)): - print ("event type: pre-call") - elif (isinstance (event, gdb.InferiorCallPostEvent)): - print ("event type: post-call") + print("all threads stopped") + + +def exit_handler(event): + assert isinstance(event, gdb.ExitedEvent) + print("event type: exit") + print("exit code: %d" % (event.exit_code)) + print("exit inf: %d" % (event.inferior.num)) + print("dir ok: %s" % str("exit_code" in dir(event))) + + +def continue_handler(event): + assert isinstance(event, gdb.ContinueEvent) + print("event type: continue") + if event.inferior_thread is not None: + print("thread num: %s" % (event.inferior_thread.num)) + + +def new_objfile_handler(event): + assert isinstance(event, gdb.NewObjFileEvent) + print("event type: new_objfile") + print("new objfile name: %s" % (event.new_objfile.filename)) + + +def clear_objfiles_handler(event): + assert isinstance(event, gdb.ClearObjFilesEvent) + print("event type: clear_objfiles") + print("progspace: %s" % (event.progspace.filename)) + + +def inferior_call_handler(event): + if isinstance(event, gdb.InferiorCallPreEvent): + print("event type: pre-call") + elif isinstance(event, gdb.InferiorCallPostEvent): + print("event type: post-call") else: assert False - print ("ptid: %s" % (event.ptid,)) - print ("address: 0x%x" % (event.address)) + print("ptid: %s" % (event.ptid,)) + print("address: 0x%x" % (event.address)) + -def register_changed_handler (event): - assert (isinstance (event, gdb.RegisterChangedEvent)) - print ("event type: register-changed") - assert (isinstance (event.frame, gdb.Frame)) - print ("frame: %s" % (event.frame)) - print ("num: %s" % (event.regnum)) +def register_changed_handler(event): + assert isinstance(event, gdb.RegisterChangedEvent) + print("event type: register-changed") + assert isinstance(event.frame, gdb.Frame) + print("frame: %s" % (event.frame)) + print("num: %s" % (event.regnum)) -def memory_changed_handler (event): - assert (isinstance (event, gdb.MemoryChangedEvent)) - print ("event type: memory-changed") - print ("address: %s" % (event.address)) - print ("length: %s" % (event.length)) +def memory_changed_handler(event): + assert isinstance(event, gdb.MemoryChangedEvent) + print("event type: memory-changed") + print("address: %s" % (event.address)) + print("length: %s" % (event.length)) -class test_events (gdb.Command): + +class test_events(gdb.Command): """Test events.""" - def __init__ (self): - gdb.Command.__init__ (self, "test-events", gdb.COMMAND_STACK) + def __init__(self): + gdb.Command.__init__(self, "test-events", gdb.COMMAND_STACK) + + def invoke(self, arg, from_tty): + gdb.events.stop.connect(signal_stop_handler) + gdb.events.stop.connect(breakpoint_stop_handler) + gdb.events.exited.connect(exit_handler) + gdb.events.cont.connect(continue_handler) + gdb.events.inferior_call.connect(inferior_call_handler) + gdb.events.memory_changed.connect(memory_changed_handler) + gdb.events.register_changed.connect(register_changed_handler) + print("Event testers registered.") - def invoke (self, arg, from_tty): - gdb.events.stop.connect (signal_stop_handler) - gdb.events.stop.connect (breakpoint_stop_handler) - gdb.events.exited.connect (exit_handler) - gdb.events.cont.connect (continue_handler) - gdb.events.inferior_call.connect (inferior_call_handler) - gdb.events.memory_changed.connect (memory_changed_handler) - gdb.events.register_changed.connect (register_changed_handler) - print ("Event testers registered.") -test_events () +test_events() -class test_newobj_events (gdb.Command): + +class test_newobj_events(gdb.Command): """NewObj events.""" - def __init__ (self): - gdb.Command.__init__ (self, "test-objfile-events", gdb.COMMAND_STACK) + def __init__(self): + gdb.Command.__init__(self, "test-objfile-events", gdb.COMMAND_STACK) + + def invoke(self, arg, from_tty): + gdb.events.new_objfile.connect(new_objfile_handler) + gdb.events.clear_objfiles.connect(clear_objfiles_handler) + print("Object file events registered.") - def invoke (self, arg, from_tty): - gdb.events.new_objfile.connect (new_objfile_handler) - gdb.events.clear_objfiles.connect (clear_objfiles_handler) - print ("Object file events registered.") -test_newobj_events () +test_newobj_events() diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint.py b/gdb/testsuite/gdb.python/py-finish-breakpoint.py index 392a074..7791079 100644 --- a/gdb/testsuite/gdb.python/py-finish-breakpoint.py +++ b/gdb/testsuite/gdb.python/py-finish-breakpoint.py @@ -15,75 +15,79 @@ # This file is part of the GDB testsuite. It tests python Finish # Breakpoints. - -class MyFinishBreakpoint (gdb.FinishBreakpoint): - def __init__(self, val, frame): - gdb.FinishBreakpoint.__init__ (self, frame) - print ("MyFinishBreakpoint init") - self.val = val - - def stop(self): - print ("MyFinishBreakpoint stop with %d" % int (self.val.dereference ())) - print ("return_value is: %d" % int (self.return_value)) - gdb.execute ("where 1") - return True - - def out_of_scope(self): - print ("MyFinishBreakpoint out of scope") + + +class MyFinishBreakpoint(gdb.FinishBreakpoint): + def __init__(self, val, frame): + gdb.FinishBreakpoint.__init__(self, frame) + print("MyFinishBreakpoint init") + self.val = val + + def stop(self): + print("MyFinishBreakpoint stop with %d" % int(self.val.dereference())) + print("return_value is: %d" % int(self.return_value)) + gdb.execute("where 1") + return True + + def out_of_scope(self): + print("MyFinishBreakpoint out of scope") + class TestBreakpoint(gdb.Breakpoint): def __init__(self): - gdb.Breakpoint.__init__ (self, spec="test_1", internal=1) + gdb.Breakpoint.__init__(self, spec="test_1", internal=1) self.silent = True self.count = 0 - print ("TestBreakpoint init") - + print("TestBreakpoint init") + def stop(self): self.count += 1 try: - TestFinishBreakpoint (gdb.newest_frame (), self.count) + TestFinishBreakpoint(gdb.newest_frame(), self.count) except ValueError as e: - print (e) + print(e) return False -class TestFinishBreakpoint (gdb.FinishBreakpoint): - def __init__ (self, frame, count): + +class TestFinishBreakpoint(gdb.FinishBreakpoint): + def __init__(self, frame, count): self.count = count - gdb.FinishBreakpoint.__init__ (self, frame, internal=1) - - + gdb.FinishBreakpoint.__init__(self, frame, internal=1) + def stop(self): - print ("-->", self.number) - if (self.count == 3): - print ("test stop: %d" % self.count) + print("-->", self.number) + if self.count == 3: + print("test stop: %d" % self.count) return True else: - print ("test don't stop: %d" % self.count) - return False - - + print("test don't stop: %d" % self.count) + return False + def out_of_scope(self): - print ("test didn't finish: %d" % self.count) + print("test didn't finish: %d" % self.count) + class TestExplicitBreakpoint(gdb.Breakpoint): - def stop(self): - try: - SimpleFinishBreakpoint (gdb.newest_frame ()) - except ValueError as e: - print (e) - return False + def stop(self): + try: + SimpleFinishBreakpoint(gdb.newest_frame()) + except ValueError as e: + print(e) + return False + class SimpleFinishBreakpoint(gdb.FinishBreakpoint): - def __init__(self, frame): - gdb.FinishBreakpoint.__init__ (self, frame) - - print ("SimpleFinishBreakpoint init") - - def stop(self): - print ("SimpleFinishBreakpoint stop" ) - return True - - def out_of_scope(self): - print ("SimpleFinishBreakpoint out of scope") - -print ("Python script imported") + def __init__(self, frame): + gdb.FinishBreakpoint.__init__(self, frame) + + print("SimpleFinishBreakpoint init") + + def stop(self): + print("SimpleFinishBreakpoint stop") + return True + + def out_of_scope(self): + print("SimpleFinishBreakpoint out of scope") + + +print("Python script imported") diff --git a/gdb/testsuite/gdb.python/py-finish-breakpoint2.py b/gdb/testsuite/gdb.python/py-finish-breakpoint2.py index 85406b9..9cf3c4d 100644 --- a/gdb/testsuite/gdb.python/py-finish-breakpoint2.py +++ b/gdb/testsuite/gdb.python/py-finish-breakpoint2.py @@ -16,18 +16,19 @@ # This file is part of the GDB testsuite. It tests python Finish # Breakpoints. + class ExceptionFinishBreakpoint(gdb.FinishBreakpoint): def __init__(self, frame): - gdb.FinishBreakpoint.__init__ (self, frame, internal=1) + gdb.FinishBreakpoint.__init__(self, frame, internal=1) self.silent = True - print ("init ExceptionFinishBreakpoint") - + print("init ExceptionFinishBreakpoint") + def stop(self): - print ("stopped at ExceptionFinishBreakpoint") - return True - + print("stopped at ExceptionFinishBreakpoint") + return True + def out_of_scope(self): - print ("exception did not finish ...") + print("exception did not finish ...") -print ("Python script imported") +print("Python script imported") diff --git a/gdb/testsuite/gdb.python/py-format-string.py b/gdb/testsuite/gdb.python/py-format-string.py index f86b888..f346c2e 100644 --- a/gdb/testsuite/gdb.python/py-format-string.py +++ b/gdb/testsuite/gdb.python/py-format-string.py @@ -18,14 +18,16 @@ import gdb -class PointPrinter (object): - def __init__ (self, val): + +class PointPrinter(object): + def __init__(self, val): self.val = val - def to_string (self): - return 'Pretty Point (%s, %s)' % (self.val['x'], self.val['y']) + def to_string(self): + return "Pretty Point (%s, %s)" % (self.val["x"], self.val["y"]) + -def test_lookup_function (val): +def test_lookup_function(val): "Look-up and return a pretty-printer that can print val." # Get the type. @@ -33,17 +35,18 @@ def test_lookup_function (val): # If it points to a reference, get the reference. if type.code == gdb.TYPE_CODE_REF: - type = type.target () + type = type.target() # Get the unqualified type, stripped of typedefs. - type = type.unqualified ().strip_typedefs () + type = type.unqualified().strip_typedefs() # Get the type name. typename = type.tag - if typename == 'point': - return PointPrinter (val) + if typename == "point": + return PointPrinter(val) return None -gdb.pretty_printers.append (test_lookup_function) + +gdb.pretty_printers.append(test_lookup_function) diff --git a/gdb/testsuite/gdb.python/py-frame-args.py b/gdb/testsuite/gdb.python/py-frame-args.py index d80d761..32d7204 100644 --- a/gdb/testsuite/gdb.python/py-frame-args.py +++ b/gdb/testsuite/gdb.python/py-frame-args.py @@ -16,7 +16,8 @@ import re import gdb -class pp_s (object): + +class pp_s(object): def __init__(self, val): self.val = val @@ -24,19 +25,20 @@ class pp_s (object): m = self.val["m"] return "m=<" + str(self.val["m"]) + ">" -class pp_ss (object): + +class pp_ss(object): def __init__(self, val): self.val = val def to_string(self): return "super struct" - def children (self): - yield 'a', self.val['a'] - yield 'b', self.val['b'] + def children(self): + yield "a", self.val["a"] + yield "b", self.val["b"] -def lookup_function (val): +def lookup_function(val): "Look-up and return a pretty-printer that can print val." # Get the type. @@ -44,12 +46,12 @@ def lookup_function (val): # If it points to a reference, get the reference. if type.code == gdb.TYPE_CODE_REF: - type = type.target () + type = type.target() # Get the unqualified type, stripped of typedefs. - type = type.unqualified ().strip_typedefs () + type = type.unqualified().strip_typedefs() - # Get the type name. + # Get the type name. typename = type.tag if typename == None: return None @@ -58,18 +60,19 @@ def lookup_function (val): # if a printer is registered for that type. Return an # instantiation of the printer if found. for function in pretty_printers_dict: - if function.match (typename): - return pretty_printers_dict[function] (val) - + if function.match(typename): + return pretty_printers_dict[function](val) + # Cannot find a pretty printer. Return None. return None -def register_pretty_printers (): - pretty_printers_dict[re.compile ('^s$')] = pp_s - pretty_printers_dict[re.compile ('^ss$')] = pp_ss +def register_pretty_printers(): + pretty_printers_dict[re.compile("^s$")] = pp_s + pretty_printers_dict[re.compile("^ss$")] = pp_ss + pretty_printers_dict = {} -register_pretty_printers () -gdb.pretty_printers.append (lookup_function) +register_pretty_printers() +gdb.pretty_printers.append(lookup_function) diff --git a/gdb/testsuite/gdb.python/py-framefilter-addr.py b/gdb/testsuite/gdb.python/py-framefilter-addr.py index a27879a..f994f01 100644 --- a/gdb/testsuite/gdb.python/py-framefilter-addr.py +++ b/gdb/testsuite/gdb.python/py-framefilter-addr.py @@ -20,33 +20,32 @@ import copy # A FrameDecorator that just returns gdb.Frame.pc () from 'function'. # We want to ensure that GDB correctly handles this case. -class Function_Returns_Address (FrameDecorator): - +class Function_Returns_Address(FrameDecorator): def __init__(self, fobj): - super (Function_Returns_Address, self).__init__ (fobj) + super(Function_Returns_Address, self).__init__(fobj) self._fobj = fobj - def function (self): - frame = self.inferior_frame () - return frame.pc () + def function(self): + frame = self.inferior_frame() + return frame.pc() -class Frame_Filter (): - def __init__ (self): +class Frame_Filter: + def __init__(self): self.name = "function_returns_address" self.priority = 100 self.enabled = True - gdb.frame_filters [self.name] = self + gdb.frame_filters[self.name] = self - def filter (self, frame_iter): + def filter(self, frame_iter): # Python 3.x moved the itertools.imap functionality to map(), # so check if it is available. if hasattr(itertools, "imap"): - frame_iter = itertools.imap (Function_Returns_Address, - frame_iter) + frame_iter = itertools.imap(Function_Returns_Address, frame_iter) else: frame_iter = map(Function_Returns_Address, frame_iter) return frame_iter + Frame_Filter() diff --git a/gdb/testsuite/gdb.python/py-framefilter-invalidarg.py b/gdb/testsuite/gdb.python/py-framefilter-invalidarg.py index 9a8fb3e..609ff80 100644 --- a/gdb/testsuite/gdb.python/py-framefilter-invalidarg.py +++ b/gdb/testsuite/gdb.python/py-framefilter-invalidarg.py @@ -20,40 +20,40 @@ import itertools from gdb.FrameDecorator import FrameDecorator import copy -class Reverse_Function (FrameDecorator): +class Reverse_Function(FrameDecorator): def __init__(self, fobj): super(Reverse_Function, self).__init__(fobj) self.fobj = fobj - def function (self): - fname = str (self.fobj.function()) - if (fname == None or fname == ""): + def function(self): + fname = str(self.fobj.function()) + if fname == None or fname == "": return None - if fname == 'end_func': - extra = self.fobj.inferior_frame().read_var('str').string() + if fname == "end_func": + extra = self.fobj.inferior_frame().read_var("str").string() else: - extra = '' + extra = "" fname = fname[::-1] + extra return fname -class FrameFilter (): - def __init__ (self): +class FrameFilter: + def __init__(self): self.name = "Reverse" self.priority = 100 self.enabled = True - gdb.frame_filters [self.name] = self + gdb.frame_filters[self.name] = self - def filter (self, frame_iter): + def filter(self, frame_iter): # Python 3.x moved the itertools.imap functionality to map(), # so check if it is available. if hasattr(itertools, "imap"): - frame_iter = itertools.imap (Reverse_Function, - frame_iter) + frame_iter = itertools.imap(Reverse_Function, frame_iter) else: frame_iter = map(Reverse_Function, frame_iter) return frame_iter + FrameFilter() diff --git a/gdb/testsuite/gdb.python/py-framefilter.py b/gdb/testsuite/gdb.python/py-framefilter.py index ee640ea..ce5a35d 100644 --- a/gdb/testsuite/gdb.python/py-framefilter.py +++ b/gdb/testsuite/gdb.python/py-framefilter.py @@ -20,71 +20,70 @@ import itertools from gdb.FrameDecorator import FrameDecorator import copy -class Reverse_Function (FrameDecorator): +class Reverse_Function(FrameDecorator): def __init__(self, fobj): super(Reverse_Function, self).__init__(fobj) self.fobj = fobj - def function (self): - fname = str (self.fobj.function()) - if (fname == None or fname == ""): + def function(self): + fname = str(self.fobj.function()) + if fname == None or fname == "": return None - if fname == 'end_func': - extra = self.fobj.inferior_frame().read_var('str').string() + if fname == "end_func": + extra = self.fobj.inferior_frame().read_var("str").string() else: - extra = '' + extra = "" fname = fname[::-1] + extra return fname -class Dummy (FrameDecorator): +class Dummy(FrameDecorator): def __init__(self, fobj): super(Dummy, self).__init__(fobj) self.fobj = fobj - def function (self): + def function(self): return "Dummy function" - def address (self): + def address(self): return 0x123 - def filename (self): + def filename(self): return "Dummy filename" - def frame_args (self): - return [("Foo",gdb.Value(12)),("Bar","Stuff"), ("FooBar",42)] + def frame_args(self): + return [("Foo", gdb.Value(12)), ("Bar", "Stuff"), ("FooBar", 42)] - def frame_locals (self): + def frame_locals(self): return [] - def line (self): + def line(self): return 0 - def elided (self): + def elided(self): return None -class FrameFilter (): - def __init__ (self): +class FrameFilter: + def __init__(self): self.name = "Reverse" self.priority = 100 self.enabled = True - gdb.frame_filters [self.name] = self + gdb.frame_filters[self.name] = self - def filter (self, frame_iter): + def filter(self, frame_iter): # Python 3.x moved the itertools.imap functionality to map(), # so check if it is available. if hasattr(itertools, "imap"): - frame_iter = itertools.imap (Reverse_Function, - frame_iter) + frame_iter = itertools.imap(Reverse_Function, frame_iter) else: frame_iter = map(Reverse_Function, frame_iter) return frame_iter -class ElidingFrameDecorator(FrameDecorator): +class ElidingFrameDecorator(FrameDecorator): def __init__(self, frame, elided_frames): super(ElidingFrameDecorator, self).__init__(frame) self.elided_frames = elided_frames @@ -92,11 +91,12 @@ class ElidingFrameDecorator(FrameDecorator): def elided(self): return iter(self.elided_frames) - def address (self): + def address(self): # Regression test for an overflow in the python layer. - bitsize = 8 * gdb.lookup_type('void').pointer().sizeof + bitsize = 8 * gdb.lookup_type("void").pointer().sizeof mask = (1 << bitsize) - 1 - return 0xffffffffffffffff & mask + return 0xFFFFFFFFFFFFFFFF & mask + class ElidingIterator: def __init__(self, ii): @@ -107,7 +107,7 @@ class ElidingIterator: def next(self): frame = next(self.input_iterator) - if str(frame.function()) != 'func1': + if str(frame.function()) != "func1": return frame # Suppose we want to return the 'func1' frame but elide the @@ -123,16 +123,17 @@ class ElidingIterator: def __next__(self): return self.next() -class FrameElider (): - def __init__ (self): +class FrameElider: + def __init__(self): self.name = "Elider" self.priority = 900 self.enabled = True - gdb.frame_filters [self.name] = self + gdb.frame_filters[self.name] = self + + def filter(self, frame_iter): + return ElidingIterator(frame_iter) - def filter (self, frame_iter): - return ElidingIterator (frame_iter) # This is here so the test can change the kind of error that is # thrown. @@ -144,24 +145,26 @@ class ErrorInName(FrameDecorator): FrameDecorator.__init__(self, frame) def function(self): - raise name_error('whoops') + raise name_error("whoops") + # A filter that supplies buggy frames. Disabled by default. -class ErrorFilter(): - def __init__ (self): +class ErrorFilter: + def __init__(self): self.name = "Error" self.priority = 1 self.enabled = False - gdb.frame_filters [self.name] = self + gdb.frame_filters[self.name] = self def filter(self, frame_iter): # Python 3.x moved the itertools.imap functionality to map(), # so check if it is available. if hasattr(itertools, "imap"): - return itertools.imap (ErrorInName, frame_iter) + return itertools.imap(ErrorInName, frame_iter) else: return map(ErrorInName, frame_iter) + FrameFilter() FrameElider() ErrorFilter() diff --git a/gdb/testsuite/gdb.python/py-mi-events-gdb.py b/gdb/testsuite/gdb.python/py-mi-events-gdb.py index f1726fc..c60bab2 100644 --- a/gdb/testsuite/gdb.python/py-mi-events-gdb.py +++ b/gdb/testsuite/gdb.python/py-mi-events-gdb.py @@ -22,31 +22,33 @@ import gdb stop_handler_str = "" cont_handler_str = "" -def signal_stop_handler (event): + +def signal_stop_handler(event): """Stop event handler""" - assert (isinstance (event, gdb.StopEvent)) + assert isinstance(event, gdb.StopEvent) global stop_handler_str stop_handler_str = "stop_handler\n" stop_handler_str += gdb.execute("info break", False, True) -def continue_handler (event): +def continue_handler(event): """Continue event handler""" - assert (isinstance (event, gdb.ContinueEvent)) + assert isinstance(event, gdb.ContinueEvent) global cont_handler_str cont_handler_str = "continue_handler\n" cont_handler_str += gdb.execute("info break", False, True) -class test_events (gdb.Command): +class test_events(gdb.Command): """Test events.""" - def __init__ (self): - gdb.Command.__init__ (self, "test-events", gdb.COMMAND_STACK) + def __init__(self): + gdb.Command.__init__(self, "test-events", gdb.COMMAND_STACK) + + def invoke(self, arg, from_tty): + gdb.events.stop.connect(signal_stop_handler) + gdb.events.cont.connect(continue_handler) + print("Event testers registered.") - def invoke (self, arg, from_tty): - gdb.events.stop.connect (signal_stop_handler) - gdb.events.cont.connect (continue_handler) - print ("Event testers registered.") -test_events () +test_events() diff --git a/gdb/testsuite/gdb.python/py-mi-var-info-path-expression.py b/gdb/testsuite/gdb.python/py-mi-var-info-path-expression.py index 09060df..d9ba2e2 100644 --- a/gdb/testsuite/gdb.python/py-mi-var-info-path-expression.py +++ b/gdb/testsuite/gdb.python/py-mi-var-info-path-expression.py @@ -23,35 +23,35 @@ if sys.version_info[0] > 2: class cons_pp(object): - def __init__(self, val): - self._val = val - - def to_string(self): - if long(self._val) == 0: - return "nil" - elif long(self._val['type']) == 0: - return "( . )" - else: - return "%d" % self._val['atom']['ival'] - - def children(self): - if long(self._val) == 0: - return [] - elif long(self._val['type']) == 0: - return [ - ('atom', self._val['atom']) - ] - else: - return [ - ('car' , self._val["slots"][0]), - ('cdr' , self._val["slots"][1]), - ] + def __init__(self, val): + self._val = val + + def to_string(self): + if long(self._val) == 0: + return "nil" + elif long(self._val["type"]) == 0: + return "( . )" + else: + return "%d" % self._val["atom"]["ival"] + + def children(self): + if long(self._val) == 0: + return [] + elif long(self._val["type"]) == 0: + return [("atom", self._val["atom"])] + else: + return [ + ("car", self._val["slots"][0]), + ("cdr", self._val["slots"][1]), + ] + def cons_pp_lookup(val): - if str(val.type) == 'struct cons *': - return cons_pp(val) - else: - return None + if str(val.type) == "struct cons *": + return cons_pp(val) + else: + return None + del gdb.pretty_printers[1:] gdb.pretty_printers.append(cons_pp_lookup) diff --git a/gdb/testsuite/gdb.python/py-nested-maps.py b/gdb/testsuite/gdb.python/py-nested-maps.py index 9352bdd..163fc86 100644 --- a/gdb/testsuite/gdb.python/py-nested-maps.py +++ b/gdb/testsuite/gdb.python/py-nested-maps.py @@ -19,15 +19,17 @@ import re import gdb -def _iterator1 (pointer, len): + +def _iterator1(pointer, len): while len > 0: map = pointer.dereference() - yield ('', map['name']) - yield ('', map.dereference()) + yield ("", map["name"]) + yield ("", map.dereference()) pointer += 1 len -= 1 -def _iterator2 (pointer1, pointer2, len): + +def _iterator2(pointer1, pointer2, len): while len > 0: yield ("", pointer1.dereference()) yield ("", pointer2.dereference()) @@ -35,42 +37,42 @@ def _iterator2 (pointer1, pointer2, len): pointer2 += 1 len -= 1 -class pp_map (object): + +class pp_map(object): def __init__(self, val): self.val = val def to_string(self): - if (self.val['show_header'] == 0): + if self.val["show_header"] == 0: return None else: return "pp_map" def children(self): - return _iterator2(self.val['keys'], - self.val['values'], - self.val['length']) + return _iterator2(self.val["keys"], self.val["values"], self.val["length"]) + + def display_hint(self): + return "map" - def display_hint (self): - return 'map' -class pp_map_map (object): +class pp_map_map(object): def __init__(self, val): self.val = val def to_string(self): - if (self.val['show_header'] == 0): + if self.val["show_header"] == 0: return None else: return "pp_map_map" def children(self): - return _iterator1(self.val['values'], - self.val['length']) + return _iterator1(self.val["values"], self.val["length"]) - def display_hint (self): - return 'map' + def display_hint(self): + return "map" -def lookup_function (val): + +def lookup_function(val): "Look-up and return a pretty-printer that can print val." # Get the type. @@ -78,10 +80,10 @@ def lookup_function (val): # If it points to a reference, get the reference. if type.code == gdb.TYPE_CODE_REF: - type = type.target () + type = type.target() # Get the unqualified type, stripped of typedefs. - type = type.unqualified ().strip_typedefs () + type = type.unqualified().strip_typedefs() # Get the type name. typename = type.tag @@ -93,14 +95,15 @@ def lookup_function (val): # if a printer is registered for that type. Return an # instantiation of the printer if found. for function in pretty_printers_dict: - if function.match (typename): - return pretty_printers_dict[function] (val) + if function.match(typename): + return pretty_printers_dict[function](val) # Cannot find a pretty printer. Return None. return None + # Lookup a printer for VAL in the typedefs dict. -def lookup_typedefs_function (val): +def lookup_typedefs_function(val): "Look-up and return a pretty-printer that can print val (typedefs)." # Get the type. @@ -113,23 +116,25 @@ def lookup_typedefs_function (val): # printer is registered for that type. Return an instantiation of # the printer if found. for function in typedefs_pretty_printers_dict: - if function.match (type.name): - return typedefs_pretty_printers_dict[function] (val) + if function.match(type.name): + return typedefs_pretty_printers_dict[function](val) # Cannot find a pretty printer. return None -def register_pretty_printers (): - pretty_printers_dict[re.compile ('^struct map_t$')] = pp_map - pretty_printers_dict[re.compile ('^map_t$')] = pp_map - pretty_printers_dict[re.compile ('^struct map_map_t$')] = pp_map_map - pretty_printers_dict[re.compile ('^map_map_t$')] = pp_map_map + +def register_pretty_printers(): + pretty_printers_dict[re.compile("^struct map_t$")] = pp_map + pretty_printers_dict[re.compile("^map_t$")] = pp_map + pretty_printers_dict[re.compile("^struct map_map_t$")] = pp_map_map + pretty_printers_dict[re.compile("^map_map_t$")] = pp_map_map + # Dict for struct types with typedefs fully stripped. pretty_printers_dict = {} # Dict for typedef types. typedefs_pretty_printers_dict = {} -register_pretty_printers () -gdb.pretty_printers.append (lookup_function) -gdb.pretty_printers.append (lookup_typedefs_function) +register_pretty_printers() +gdb.pretty_printers.append(lookup_function) +gdb.pretty_printers.append(lookup_typedefs_function) diff --git a/gdb/testsuite/gdb.python/py-objfile-script-gdb.py b/gdb/testsuite/gdb.python/py-objfile-script-gdb.py index e323da9..88372e4 100644 --- a/gdb/testsuite/gdb.python/py-objfile-script-gdb.py +++ b/gdb/testsuite/gdb.python/py-objfile-script-gdb.py @@ -17,6 +17,7 @@ import re + class pp_ss: def __init__(self, val): self.val = val @@ -24,7 +25,8 @@ class pp_ss: def to_string(self): return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">" -def lookup_function (val): + +def lookup_function(val): "Look-up and return a pretty-printer that can print val." # Get the type. @@ -32,12 +34,12 @@ def lookup_function (val): # If it points to a reference, get the reference. if type.code == gdb.TYPE_CODE_REF: - type = type.target () + type = type.target() # Get the unqualified type, stripped of typedefs. - type = type.unqualified ().strip_typedefs () + type = type.unqualified().strip_typedefs() - # Get the type name. + # Get the type name. typename = type.tag if typename == None: @@ -47,17 +49,19 @@ def lookup_function (val): # if a printer is registered for that type. Return an # instantiation of the printer if found. for function in pretty_printers_dict: - if function.match (typename): - return pretty_printers_dict[function] (val) - + if function.match(typename): + return pretty_printers_dict[function](val) + # Cannot find a pretty printer. Return None. return None -def register_pretty_printers (): - pretty_printers_dict[re.compile ('^ss$')] = pp_ss + +def register_pretty_printers(): + pretty_printers_dict[re.compile("^ss$")] = pp_ss + pretty_printers_dict = {} -register_pretty_printers () -gdb.current_progspace().pretty_printers.append (lookup_function) +register_pretty_printers() +gdb.current_progspace().pretty_printers.append(lookup_function) diff --git a/gdb/testsuite/gdb.python/py-pp-integral.py b/gdb/testsuite/gdb.python/py-pp-integral.py index dd6ea8e..fddef70 100644 --- a/gdb/testsuite/gdb.python/py-pp-integral.py +++ b/gdb/testsuite/gdb.python/py-pp-integral.py @@ -27,7 +27,7 @@ class TimePrinter: def time_sniffer(val): - if hasattr(val.type, 'name') and val.type.name == "time_t": + if hasattr(val.type, "name") and val.type.name == "time_t": return TimePrinter(val) return None diff --git a/gdb/testsuite/gdb.python/py-pp-maint.py b/gdb/testsuite/gdb.python/py-pp-maint.py index 79c029c..4375430 100644 --- a/gdb/testsuite/gdb.python/py-pp-maint.py +++ b/gdb/testsuite/gdb.python/py-pp-maint.py @@ -27,8 +27,7 @@ def lookup_function_lookup_test(val): self.val = val def to_string(self): - return ("x=<" + str(self.val["x"]) + - "> y=<" + str(self.val["y"]) + ">") + return "x=<" + str(self.val["x"]) + "> y=<" + str(self.val["y"]) + ">" typename = gdb.types.get_basic_type(val.type).tag # Note: typename could be None. @@ -37,7 +36,7 @@ def lookup_function_lookup_test(val): return None -class pp_s (object): +class pp_s(object): def __init__(self, val): self.val = val @@ -49,7 +48,7 @@ class pp_s (object): return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">" -class pp_ss (object): +class pp_ss(object): def __init__(self, val): self.val = val @@ -60,15 +59,18 @@ class pp_ss (object): def build_pretty_printer(): pp = gdb.printing.RegexpCollectionPrettyPrinter("pp-test") - pp.add_printer('struct s', '^struct s$', pp_s) - pp.add_printer('s', '^s$', pp_s) + pp.add_printer("struct s", "^struct s$", pp_s) + pp.add_printer("s", "^s$", pp_s) # Use a lambda this time to exercise doing things this way. - pp.add_printer('struct ss', '^struct ss$', lambda val: pp_ss(val)) - pp.add_printer('ss', '^ss$', lambda val: pp_ss(val)) - - pp.add_printer('enum flag_enum', '^flag_enum$', - gdb.printing.FlagEnumerationPrinter('enum flag_enum')) + pp.add_printer("struct ss", "^struct ss$", lambda val: pp_ss(val)) + pp.add_printer("ss", "^ss$", lambda val: pp_ss(val)) + + pp.add_printer( + "enum flag_enum", + "^flag_enum$", + gdb.printing.FlagEnumerationPrinter("enum flag_enum"), + ) return pp diff --git a/gdb/testsuite/gdb.python/py-pp-re-notag.py b/gdb/testsuite/gdb.python/py-pp-re-notag.py index 0bd2b43..cd873bd 100644 --- a/gdb/testsuite/gdb.python/py-pp-re-notag.py +++ b/gdb/testsuite/gdb.python/py-pp-re-notag.py @@ -28,7 +28,7 @@ class TimePrinter: def build_pretty_printer(): pp = gdb.printing.RegexpCollectionPrettyPrinter("pp-notag") - pp.add_printer('time_t', 'time_t', TimePrinter) + pp.add_printer("time_t", "time_t", TimePrinter) return pp diff --git a/gdb/testsuite/gdb.python/py-pp-registration.py b/gdb/testsuite/gdb.python/py-pp-registration.py index edf58ca..f34936e 100644 --- a/gdb/testsuite/gdb.python/py-pp-registration.py +++ b/gdb/testsuite/gdb.python/py-pp-registration.py @@ -27,8 +27,7 @@ def lookup_function_lookup_test(val): self.val = val def to_string(self): - return ("x=<" + str(self.val["x"]) + - "> y=<" + str(self.val["y"]) + ">") + return "x=<" + str(self.val["x"]) + "> y=<" + str(self.val["y"]) + ">" typename = gdb.types.get_basic_type(val.type).tag # Note: typename could be None. @@ -37,7 +36,7 @@ def lookup_function_lookup_test(val): return None -class pp_s1 (object): +class pp_s1(object): def __init__(self, val): self.val = val @@ -47,7 +46,7 @@ class pp_s1 (object): return "s1 a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">" -class pp_s2 (object): +class pp_s2(object): def __init__(self, val): self.val = val @@ -60,8 +59,8 @@ class pp_s2 (object): def build_pretty_printer1(): pp = gdb.printing.RegexpCollectionPrettyPrinter("pp-test") - pp.add_printer('struct s', '^struct s$', pp_s1) - pp.add_printer('s', '^s$', pp_s1) + pp.add_printer("struct s", "^struct s$", pp_s1) + pp.add_printer("s", "^s$", pp_s1) return pp @@ -72,9 +71,10 @@ def build_pretty_printer2(): # register_pretty_printer. pp = gdb.printing.RegexpCollectionPrettyPrinter("pp-test") - pp.add_printer('struct s', '^struct s$', pp_s2) - pp.add_printer('s', '^s$', pp_s2) + pp.add_printer("struct s", "^struct s$", pp_s2) + pp.add_printer("s", "^s$", pp_s2) return pp + # Note: Registering the printers is done in the .exp file. diff --git a/gdb/testsuite/gdb.python/py-prettyprint.exp b/gdb/testsuite/gdb.python/py-prettyprint.exp index 6a3968f..1a5b43f 100644 --- a/gdb/testsuite/gdb.python/py-prettyprint.exp +++ b/gdb/testsuite/gdb.python/py-prettyprint.exp @@ -127,7 +127,7 @@ proc run_lang_tests {exefile lang} { [multi_line \ "Traceback\[^\r\n\]+" \ "\\s+File \"\[^\r\n\]+/py-prettyprint.py\", line \[0-9\]+, in display_hint" \ - "\\s+raise Exception \[^\r\n\]+" \ + "\\s+raise Exception\[^\r\n\]+" \ "Exception: invalid object state found in display_hint"] gdb_test "print c" \ [multi_line \ diff --git a/gdb/testsuite/gdb.python/py-prettyprint.py b/gdb/testsuite/gdb.python/py-prettyprint.py index fab03a6..84dbc3b 100644 --- a/gdb/testsuite/gdb.python/py-prettyprint.py +++ b/gdb/testsuite/gdb.python/py-prettyprint.py @@ -19,73 +19,78 @@ import re import gdb -def _iterator (pointer, len): + +def _iterator(pointer, len): start = pointer end = pointer + len while pointer != end: - yield ('[%d]' % int (pointer - start), pointer.dereference()) + yield ("[%d]" % int(pointer - start), pointer.dereference()) pointer += 1 + # Same as _iterator but can be told to raise an exception. -def _iterator_except (pointer, len): +def _iterator_except(pointer, len): start = pointer end = pointer + len while pointer != end: if exception_flag: - raise gdb.MemoryError ('hi bob') - yield ('[%d]' % int (pointer - start), pointer.dereference()) + raise gdb.MemoryError("hi bob") + yield ("[%d]" % int(pointer - start), pointer.dereference()) pointer += 1 + # Test returning a Value from a printer. -class string_print (object): +class string_print(object): def __init__(self, val): self.val = val def to_string(self): - return self.val['whybother']['contents'] + return self.val["whybother"]["contents"] -# Test a class-based printer. -class ContainerPrinter (object): +# Test a class-based printer. +class ContainerPrinter(object): def __init__(self, val): self.val = val def to_string(self): - return 'container %s with %d elements' % (self.val['name'], self.val['len']) + return "container %s with %d elements" % (self.val["name"], self.val["len"]) def children(self): - return _iterator(self.val['elements'], self.val['len']) + return _iterator(self.val["elements"], self.val["len"]) - def display_hint (self): - if (self.val['is_map_p'] and self.val['is_array_p']): - raise Exception ("invalid object state found in display_hint") + def display_hint(self): + if self.val["is_map_p"] and self.val["is_array_p"]: + raise Exception("invalid object state found in display_hint") - if (self.val['is_map_p']): - return 'map' - elif (self.val['is_array_p']): - return 'array' + if self.val["is_map_p"]: + return "map" + elif self.val["is_array_p"]: + return "array" else: return None + # Treats a container as array. -class ArrayPrinter (object): +class ArrayPrinter(object): def __init__(self, val): self.val = val def to_string(self): - return 'array %s with %d elements' % (self.val['name'], self.val['len']) + return "array %s with %d elements" % (self.val["name"], self.val["len"]) def children(self): - return _iterator(self.val['elements'], self.val['len']) + return _iterator(self.val["elements"], self.val["len"]) + + def display_hint(self): + return "array" - def display_hint (self): - return 'array' # Flag to make NoStringContainerPrinter throw an exception. exception_flag = False # Test a printer where to_string is None -class NoStringContainerPrinter (object): +class NoStringContainerPrinter(object): def __init__(self, val): self.val = val @@ -93,28 +98,29 @@ class NoStringContainerPrinter (object): return None def children(self): - return _iterator_except (self.val['elements'], self.val['len']) + return _iterator_except(self.val["elements"], self.val["len"]) + # See ToStringReturnsValueWrapper. class ToStringReturnsValueInner: - def __init__(self, val): self.val = val def to_string(self): - return 'Inner to_string {}'.format(int(self.val['val'])) + return "Inner to_string {}".format(int(self.val["val"])) + # Test a printer that returns a gdb.Value in its to_string. That gdb.Value # also has its own pretty-printer. class ToStringReturnsValueWrapper: - def __init__(self, val): self.val = val def to_string(self): - return self.val['inner'] + return self.val["inner"] + -class pp_s (object): +class pp_s(object): def __init__(self, val): self.val = val @@ -125,155 +131,174 @@ class pp_s (object): raise Exception("&a(%s) != b(%s)" % (str(a.address), str(b))) return " a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">" -class pp_ss (object): + +class pp_ss(object): def __init__(self, val): self.val = val def to_string(self): return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">" -class pp_sss (object): + +class pp_sss(object): def __init__(self, val): self.val = val def to_string(self): - return "a=<" + str(self.val['a']) + "> b=<" + str(self.val["b"]) + ">" + return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">" -class pp_multiple_virtual (object): - def __init__ (self, val): + +class pp_multiple_virtual(object): + def __init__(self, val): self.val = val - def to_string (self): - return "pp value variable is: " + str (self.val['value']) + def to_string(self): + return "pp value variable is: " + str(self.val["value"]) + -class pp_vbase1 (object): - def __init__ (self, val): +class pp_vbase1(object): + def __init__(self, val): self.val = val - def to_string (self): + def to_string(self): return "pp class name: " + self.val.type.tag -class pp_nullstr (object): + +class pp_nullstr(object): def __init__(self, val): self.val = val def to_string(self): - return self.val['s'].string(gdb.target_charset()) + return self.val["s"].string(gdb.target_charset()) + -class pp_ns (object): +class pp_ns(object): "Print a std::basic_string of some kind" def __init__(self, val): self.val = val def to_string(self): - len = self.val['length'] - return self.val['null_str'].string (gdb.target_charset(), length = len) + len = self.val["length"] + return self.val["null_str"].string(gdb.target_charset(), length=len) + + def display_hint(self): + return "string" - def display_hint (self): - return 'string' pp_ls_encoding = None -class pp_ls (object): + +class pp_ls(object): "Print a std::basic_string of some kind" def __init__(self, val): self.val = val def to_string(self): - length = self.val['len'] + length = self.val["len"] if pp_ls_encoding is not None: if length >= 0: - return self.val['lazy_str'].lazy_string( - encoding = pp_ls_encoding, - length = length) + return self.val["lazy_str"].lazy_string( + encoding=pp_ls_encoding, length=length + ) else: - return self.val['lazy_str'].lazy_string( - encoding = pp_ls_encoding) + return self.val["lazy_str"].lazy_string(encoding=pp_ls_encoding) else: if length >= 0: - return self.val['lazy_str'].lazy_string(length = length) + return self.val["lazy_str"].lazy_string(length=length) else: - return self.val['lazy_str'].lazy_string() + return self.val["lazy_str"].lazy_string() + + def display_hint(self): + return "string" - def display_hint (self): - return 'string' -class pp_hint_error (object): +class pp_hint_error(object): "Throw error from display_hint" def __init__(self, val): self.val = val def to_string(self): - return 'hint_error_val' + return "hint_error_val" - def display_hint (self): + def display_hint(self): raise Exception("hint failed") -class pp_children_as_list (object): + +class pp_children_as_list(object): "Throw error from display_hint" def __init__(self, val): self.val = val def to_string(self): - return 'children_as_list_val' + return "children_as_list_val" + + def children(self): + return [("one", 1)] - def children (self): - return [('one', 1)] -class pp_outer (object): +class pp_outer(object): "Print struct outer" - def __init__ (self, val): + def __init__(self, val): self.val = val - def to_string (self): - return "x = %s" % self.val['x'] + def to_string(self): + return "x = %s" % self.val["x"] + + def children(self): + yield "s", self.val["s"] + yield "x", self.val["x"] - def children (self): - yield 's', self.val['s'] - yield 'x', self.val['x'] -class MemoryErrorString (object): +class MemoryErrorString(object): "Raise an error" def __init__(self, val): self.val = val def to_string(self): - raise gdb.MemoryError ("Cannot access memory.") + raise gdb.MemoryError("Cannot access memory.") - def display_hint (self): - return 'string' + def display_hint(self): + return "string" -class pp_eval_type (object): + +class pp_eval_type(object): def __init__(self, val): self.val = val def to_string(self): gdb.execute("bt", to_string=True) - return "eval=<" + str(gdb.parse_and_eval("eval_func (123456789, 2, 3, 4, 5, 6, 7, 8)")) + ">" + return ( + "eval=<" + + str(gdb.parse_and_eval("eval_func (123456789, 2, 3, 4, 5, 6, 7, 8)")) + + ">" + ) + -class pp_int_typedef (object): +class pp_int_typedef(object): def __init__(self, val): self.val = val def to_string(self): return "type=%s, val=%s" % (self.val.type, int(self.val)) -class pp_int_typedef3 (object): + +class pp_int_typedef3(object): "A printer without a to_string method" def __init__(self, val): self.val = val def children(self): - yield 's', 27 + yield "s", 27 -def lookup_function (val): + +def lookup_function(val): "Look-up and return a pretty-printer that can print val." # Get the type. @@ -281,12 +306,12 @@ def lookup_function (val): # If it points to a reference, get the reference. if type.code == gdb.TYPE_CODE_REF: - type = type.target () + type = type.target() # Get the unqualified type, stripped of typedefs. - type = type.unqualified ().strip_typedefs () + type = type.unqualified().strip_typedefs() - # Get the type name. + # Get the type name. typename = type.tag if typename == None: @@ -296,21 +321,24 @@ def lookup_function (val): # if a printer is registered for that type. Return an # instantiation of the printer if found. for function in pretty_printers_dict: - if function.match (typename): - return pretty_printers_dict[function] (val) - + if function.match(typename): + return pretty_printers_dict[function](val) + # Cannot find a pretty printer. Return None. return None -def disable_lookup_function (): + +def disable_lookup_function(): lookup_function.enabled = False -def enable_lookup_function (): + +def enable_lookup_function(): lookup_function.enabled = True + # Lookup a printer for VAL in the typedefs dict. -def lookup_typedefs_function (val): +def lookup_typedefs_function(val): "Look-up and return a pretty-printer that can print val (typedefs)." # Get the type. @@ -323,72 +351,82 @@ def lookup_typedefs_function (val): # printer is registered for that type. Return an instantiation of # the printer if found. for function in typedefs_pretty_printers_dict: - if function.match (type.name): - return typedefs_pretty_printers_dict[function] (val) + if function.match(type.name): + return typedefs_pretty_printers_dict[function](val) # Cannot find a pretty printer. return None -def register_pretty_printers (): - pretty_printers_dict[re.compile ('^struct s$')] = pp_s - pretty_printers_dict[re.compile ('^s$')] = pp_s - pretty_printers_dict[re.compile ('^S$')] = pp_s - - pretty_printers_dict[re.compile ('^struct ss$')] = pp_ss - pretty_printers_dict[re.compile ('^ss$')] = pp_ss - pretty_printers_dict[re.compile ('^const S &$')] = pp_s - pretty_printers_dict[re.compile ('^SSS$')] = pp_sss - - pretty_printers_dict[re.compile ('^VirtualTest$')] = pp_multiple_virtual - pretty_printers_dict[re.compile ('^Vbase1$')] = pp_vbase1 - - pretty_printers_dict[re.compile ('^struct nullstr$')] = pp_nullstr - pretty_printers_dict[re.compile ('^nullstr$')] = pp_nullstr - + +def register_pretty_printers(): + pretty_printers_dict[re.compile("^struct s$")] = pp_s + pretty_printers_dict[re.compile("^s$")] = pp_s + pretty_printers_dict[re.compile("^S$")] = pp_s + + pretty_printers_dict[re.compile("^struct ss$")] = pp_ss + pretty_printers_dict[re.compile("^ss$")] = pp_ss + pretty_printers_dict[re.compile("^const S &$")] = pp_s + pretty_printers_dict[re.compile("^SSS$")] = pp_sss + + pretty_printers_dict[re.compile("^VirtualTest$")] = pp_multiple_virtual + pretty_printers_dict[re.compile("^Vbase1$")] = pp_vbase1 + + pretty_printers_dict[re.compile("^struct nullstr$")] = pp_nullstr + pretty_printers_dict[re.compile("^nullstr$")] = pp_nullstr + # Note that we purposely omit the typedef names here. # Printer lookup is based on canonical name. # However, we do need both tagged and untagged variants, to handle # both the C and C++ cases. - pretty_printers_dict[re.compile ('^struct string_repr$')] = string_print - pretty_printers_dict[re.compile ('^struct container$')] = ContainerPrinter - pretty_printers_dict[re.compile ('^struct justchildren$')] = NoStringContainerPrinter - pretty_printers_dict[re.compile ('^string_repr$')] = string_print - pretty_printers_dict[re.compile ('^container$')] = ContainerPrinter - pretty_printers_dict[re.compile ('^justchildren$')] = NoStringContainerPrinter + pretty_printers_dict[re.compile("^struct string_repr$")] = string_print + pretty_printers_dict[re.compile("^struct container$")] = ContainerPrinter + pretty_printers_dict[re.compile("^struct justchildren$")] = NoStringContainerPrinter + pretty_printers_dict[re.compile("^string_repr$")] = string_print + pretty_printers_dict[re.compile("^container$")] = ContainerPrinter + pretty_printers_dict[re.compile("^justchildren$")] = NoStringContainerPrinter + + pretty_printers_dict[ + re.compile("^struct to_string_returns_value_inner$") + ] = ToStringReturnsValueInner + pretty_printers_dict[ + re.compile("^to_string_returns_value_inner$") + ] = ToStringReturnsValueInner + pretty_printers_dict[ + re.compile("^struct to_string_returns_value_wrapper$") + ] = ToStringReturnsValueWrapper + pretty_printers_dict[ + re.compile("^to_string_returns_value_wrapper$") + ] = ToStringReturnsValueWrapper - pretty_printers_dict[re.compile ('^struct to_string_returns_value_inner$')] = ToStringReturnsValueInner - pretty_printers_dict[re.compile ('^to_string_returns_value_inner$')] = ToStringReturnsValueInner - pretty_printers_dict[re.compile ('^struct to_string_returns_value_wrapper$')] = ToStringReturnsValueWrapper - pretty_printers_dict[re.compile ('^to_string_returns_value_wrapper$')] = ToStringReturnsValueWrapper + pretty_printers_dict[re.compile("^struct ns$")] = pp_ns + pretty_printers_dict[re.compile("^ns$")] = pp_ns - pretty_printers_dict[re.compile ('^struct ns$')] = pp_ns - pretty_printers_dict[re.compile ('^ns$')] = pp_ns + pretty_printers_dict[re.compile("^struct lazystring$")] = pp_ls + pretty_printers_dict[re.compile("^lazystring$")] = pp_ls - pretty_printers_dict[re.compile ('^struct lazystring$')] = pp_ls - pretty_printers_dict[re.compile ('^lazystring$')] = pp_ls + pretty_printers_dict[re.compile("^struct outerstruct$")] = pp_outer + pretty_printers_dict[re.compile("^outerstruct$")] = pp_outer - pretty_printers_dict[re.compile ('^struct outerstruct$')] = pp_outer - pretty_printers_dict[re.compile ('^outerstruct$')] = pp_outer + pretty_printers_dict[re.compile("^struct hint_error$")] = pp_hint_error + pretty_printers_dict[re.compile("^hint_error$")] = pp_hint_error - pretty_printers_dict[re.compile ('^struct hint_error$')] = pp_hint_error - pretty_printers_dict[re.compile ('^hint_error$')] = pp_hint_error + pretty_printers_dict[re.compile("^struct children_as_list$")] = pp_children_as_list + pretty_printers_dict[re.compile("^children_as_list$")] = pp_children_as_list - pretty_printers_dict[re.compile ('^struct children_as_list$')] = pp_children_as_list - pretty_printers_dict[re.compile ('^children_as_list$')] = pp_children_as_list + pretty_printers_dict[re.compile("^memory_error$")] = MemoryErrorString - pretty_printers_dict[re.compile ('^memory_error$')] = MemoryErrorString + pretty_printers_dict[re.compile("^eval_type_s$")] = pp_eval_type - pretty_printers_dict[re.compile ('^eval_type_s$')] = pp_eval_type + typedefs_pretty_printers_dict[re.compile("^int_type$")] = pp_int_typedef + typedefs_pretty_printers_dict[re.compile("^int_type2$")] = pp_int_typedef + typedefs_pretty_printers_dict[re.compile("^int_type3$")] = pp_int_typedef3 - typedefs_pretty_printers_dict[re.compile ('^int_type$')] = pp_int_typedef - typedefs_pretty_printers_dict[re.compile ('^int_type2$')] = pp_int_typedef - typedefs_pretty_printers_dict[re.compile ('^int_type3$')] = pp_int_typedef3 # Dict for struct types with typedefs fully stripped. pretty_printers_dict = {} # Dict for typedef types. typedefs_pretty_printers_dict = {} -register_pretty_printers () -gdb.pretty_printers.append (lookup_function) -gdb.pretty_printers.append (lookup_typedefs_function) +register_pretty_printers() +gdb.pretty_printers.append(lookup_function) +gdb.pretty_printers.append(lookup_typedefs_function) diff --git a/gdb/testsuite/gdb.python/py-recurse-unwind.py b/gdb/testsuite/gdb.python/py-recurse-unwind.py index 8c7b134..1545614 100644 --- a/gdb/testsuite/gdb.python/py-recurse-unwind.py +++ b/gdb/testsuite/gdb.python/py-recurse-unwind.py @@ -16,7 +16,7 @@ # This unwinder never does any unwinding. It'll (pretend to) "sniff" # the frame and ultimately return None, indicating that actual unwinding # should be performed by some other unwinder. -# +# # But, prior to returning None, it will attempt to obtain the value # associated with a symbol via a call to gdb.parse_and_eval(). In # the course of doing this evaluation, GDB will potentially access @@ -28,23 +28,24 @@ import gdb from gdb.unwinder import Unwinder + class TestUnwinder(Unwinder): count = 0 @classmethod - def reset_count (cls): + def reset_count(cls): cls.count = 0 @classmethod - def inc_count (cls): + def inc_count(cls): cls.count += 1 - test = 'check_undefined_symbol' + test = "check_undefined_symbol" @classmethod - def set_test (cls, test) : - cls.test = test + def set_test(cls, test): + cls.test = test def __init__(self): Unwinder.__init__(self, "test unwinder") @@ -59,19 +60,19 @@ class TestUnwinder(Unwinder): self.recurse_level += 1 TestUnwinder.inc_count() - if TestUnwinder.test == 'check_user_reg_pc' : + if TestUnwinder.test == "check_user_reg_pc": - pc = pending_frame.read_register('pc') - pc_as_int = int(pc.cast(gdb.lookup_type('int'))) + pc = pending_frame.read_register("pc") + pc_as_int = int(pc.cast(gdb.lookup_type("int"))) # gdb.write("In unwinder: pc=%x\n" % pc_as_int) - elif TestUnwinder.test == 'check_pae_pc' : + elif TestUnwinder.test == "check_pae_pc": - pc = gdb.parse_and_eval('$pc') - pc_as_int = int(pc.cast(gdb.lookup_type('int'))) + pc = gdb.parse_and_eval("$pc") + pc_as_int = int(pc.cast(gdb.lookup_type("int"))) # gdb.write("In unwinder: pc=%x\n" % pc_as_int) - elif TestUnwinder.test == 'check_undefined_symbol' : + elif TestUnwinder.test == "check_undefined_symbol": try: val = gdb.parse_and_eval("undefined_symbol") @@ -83,5 +84,6 @@ class TestUnwinder(Unwinder): return None + gdb.unwinder.register_unwinder(None, TestUnwinder(), True) gdb.write("Python script imported\n") diff --git a/gdb/testsuite/gdb.python/py-section-script.py b/gdb/testsuite/gdb.python/py-section-script.py index 079244c..aac70a0 100644 --- a/gdb/testsuite/gdb.python/py-section-script.py +++ b/gdb/testsuite/gdb.python/py-section-script.py @@ -17,6 +17,7 @@ import re + class pp_ss: def __init__(self, val): self.val = val @@ -24,7 +25,8 @@ class pp_ss: def to_string(self): return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">" -def lookup_function (val): + +def lookup_function(val): "Look-up and return a pretty-printer that can print val." # Get the type. @@ -32,12 +34,12 @@ def lookup_function (val): # If it points to a reference, get the reference. if type.code == gdb.TYPE_CODE_REF: - type = type.target () + type = type.target() # Get the unqualified type, stripped of typedefs. - type = type.unqualified ().strip_typedefs () + type = type.unqualified().strip_typedefs() - # Get the type name. + # Get the type name. typename = type.tag if typename == None: @@ -47,17 +49,19 @@ def lookup_function (val): # if a printer is registered for that type. Return an # instantiation of the printer if found. for function in pretty_printers_dict: - if function.match (typename): - return pretty_printers_dict[function] (val) - + if function.match(typename): + return pretty_printers_dict[function](val) + # Cannot find a pretty printer. Return None. return None -def register_pretty_printers (): - pretty_printers_dict[re.compile ('^ss$')] = pp_ss + +def register_pretty_printers(): + pretty_printers_dict[re.compile("^ss$")] = pp_ss + pretty_printers_dict = {} -register_pretty_printers () -gdb.current_progspace().pretty_printers.append (lookup_function) +register_pretty_printers() +gdb.current_progspace().pretty_printers.append(lookup_function) diff --git a/gdb/testsuite/gdb.python/py-typeprint.py b/gdb/testsuite/gdb.python/py-typeprint.py index 9746087..557707f 100644 --- a/gdb/testsuite/gdb.python/py-typeprint.py +++ b/gdb/testsuite/gdb.python/py-typeprint.py @@ -15,21 +15,24 @@ import gdb + class Recognizer(object): def __init__(self): self.enabled = True def recognize(self, type_obj): - if type_obj.tag == 'basic_string': - return 'string' + if type_obj.tag == "basic_string": + return "string" return None + class StringTypePrinter(object): def __init__(self): - self.name = 'string' + self.name = "string" self.enabled = True def instantiate(self): return Recognizer() + gdb.type_printers.append(StringTypePrinter()) diff --git a/gdb/testsuite/gdb.python/py-unwind-inline.py b/gdb/testsuite/gdb.python/py-unwind-inline.py index 4ee52c5..3042472 100644 --- a/gdb/testsuite/gdb.python/py-unwind-inline.py +++ b/gdb/testsuite/gdb.python/py-unwind-inline.py @@ -23,49 +23,50 @@ from gdb.unwinder import Unwinder apb_global = None -class dummy_unwinder (Unwinder): - """ A dummy unwinder that looks at a bunch of registers as part of + +class dummy_unwinder(Unwinder): + """A dummy unwinder that looks at a bunch of registers as part of the unwinding process.""" - class frame_id (object): - """ Basic frame id.""" + class frame_id(object): + """Basic frame id.""" - def __init__ (self, sp, pc): - """ Create the frame id.""" + def __init__(self, sp, pc): + """Create the frame id.""" self.sp = sp self.pc = pc - def __init__ (self): + def __init__(self): """Create the unwinder.""" - Unwinder.__init__ (self, "dummy stack unwinder") + Unwinder.__init__(self, "dummy stack unwinder") self.void_ptr_t = gdb.lookup_type("void").pointer() self.regs = None - def get_regs (self, pending_frame): + def get_regs(self, pending_frame): """Return a list of register names that should be read. Only gathers the list once, then caches the result.""" - if (self.regs != None): + if self.regs != None: return self.regs # Collect the names of all registers to read. - self.regs = list (pending_frame.architecture () - .register_names ()) + self.regs = list(pending_frame.architecture().register_names()) return self.regs - def __call__ (self, pending_frame): + def __call__(self, pending_frame): """Actually performs the unwind, or at least sniffs this frame to see if the unwinder should claim it, which is never does.""" try: - for r in (self.get_regs (pending_frame)): - v = pending_frame.read_register (r).cast (self.void_ptr_t) + for r in self.get_regs(pending_frame): + v = pending_frame.read_register(r).cast(self.void_ptr_t) except: - print ("Dummy unwinder, exception") + print("Dummy unwinder, exception") raise return None + # Register the ComRV stack unwinder. -gdb.unwinder.register_unwinder (None, dummy_unwinder (), True) +gdb.unwinder.register_unwinder(None, dummy_unwinder(), True) -print ("Python script imported") +print("Python script imported") diff --git a/gdb/testsuite/gdb.python/py-unwind-maint.py b/gdb/testsuite/gdb.python/py-unwind-maint.py index 51d9c9e..426fe76 100644 --- a/gdb/testsuite/gdb.python/py-unwind-maint.py +++ b/gdb/testsuite/gdb.python/py-unwind-maint.py @@ -19,6 +19,7 @@ import re import gdb.types from gdb.unwinder import Unwinder, register_unwinder + class TestGlobalUnwinder(Unwinder): def __init__(self): super(TestGlobalUnwinder, self).__init__("global_unwinder") @@ -27,6 +28,7 @@ class TestGlobalUnwinder(Unwinder): print("%s called" % self.name) return None + class TestProgspaceUnwinder(Unwinder): def __init__(self, name): super(TestProgspaceUnwinder, self).__init__("%s_ps_unwinder" % name) @@ -35,6 +37,7 @@ class TestProgspaceUnwinder(Unwinder): print("%s called" % self.name) return None + class TestObjfileUnwinder(Unwinder): def __init__(self, name): super(TestObjfileUnwinder, self).__init__("%s_obj_unwinder" % name) @@ -44,7 +47,6 @@ class TestObjfileUnwinder(Unwinder): return None - gdb.unwinder.register_unwinder(None, TestGlobalUnwinder()) saw_runtime_error = False try: @@ -54,6 +56,7 @@ except RuntimeError: if not saw_runtime_error: raise RuntimeError("Missing runtime error from register_unwinder.") gdb.unwinder.register_unwinder(None, TestGlobalUnwinder(), replace=True) -gdb.unwinder.register_unwinder(gdb.current_progspace(), - TestProgspaceUnwinder("py_unwind_maint")) +gdb.unwinder.register_unwinder( + gdb.current_progspace(), TestProgspaceUnwinder("py_unwind_maint") +) print("Python script imported") diff --git a/gdb/testsuite/gdb.python/py-unwind.py b/gdb/testsuite/gdb.python/py-unwind.py index 2230d5d..931e979 100644 --- a/gdb/testsuite/gdb.python/py-unwind.py +++ b/gdb/testsuite/gdb.python/py-unwind.py @@ -16,8 +16,8 @@ import gdb from gdb.unwinder import Unwinder -class FrameId(object): +class FrameId(object): def __init__(self, sp, pc): self._sp = sp self._pc = pc @@ -30,6 +30,7 @@ class FrameId(object): def pc(self): return self._pc + class TestUnwinder(Unwinder): AMD64_RBP = 6 AMD64_RSP = 7 @@ -42,9 +43,9 @@ class TestUnwinder(Unwinder): self._last_arch = None # Update the register descriptor AMD64_RIP based on ARCH. - def _update_register_descriptors (self, arch): - if (self._last_arch != arch): - TestUnwinder.AMD64_RIP = arch.registers ().find ("rip") + def _update_register_descriptors(self, arch): + if self._last_arch != arch: + TestUnwinder.AMD64_RIP = arch.registers().find("rip") self._last_arch = arch def _read_word(self, address): @@ -79,12 +80,12 @@ class TestUnwinder(Unwinder): # Check that we can access the architecture of the pending # frame, and that this is the same architecture as for the # currently selected inferior. - inf_arch = gdb.selected_inferior ().architecture () - frame_arch = pending_frame.architecture () - if (inf_arch != frame_arch): - raise gdb.GdbError ("architecture mismatch") + inf_arch = gdb.selected_inferior().architecture() + frame_arch = pending_frame.architecture() + if inf_arch != frame_arch: + raise gdb.GdbError("architecture mismatch") - self._update_register_descriptors (frame_arch) + self._update_register_descriptors(frame_arch) try: # NOTE: the registers in Unwinder API can be referenced @@ -102,15 +103,16 @@ class TestUnwinder(Unwinder): frame_id = FrameId( pending_frame.read_register(TestUnwinder.AMD64_RSP), - pending_frame.read_register(TestUnwinder.AMD64_RIP)) + pending_frame.read_register(TestUnwinder.AMD64_RIP), + ) unwind_info = pending_frame.create_unwind_info(frame_id) - unwind_info.add_saved_register(TestUnwinder.AMD64_RBP, - previous_bp) + unwind_info.add_saved_register(TestUnwinder.AMD64_RBP, previous_bp) unwind_info.add_saved_register("rip", previous_ip) unwind_info.add_saved_register("rsp", previous_sp) return unwind_info except (gdb.error, RuntimeError): return None + gdb.unwinder.register_unwinder(None, TestUnwinder(), True) print("Python script imported") diff --git a/gdb/testsuite/gdb.python/py-xmethods.py b/gdb/testsuite/gdb.python/py-xmethods.py index 7bfd190..1df3bd0 100644 --- a/gdb/testsuite/gdb.python/py-xmethods.py +++ b/gdb/testsuite/gdb.python/py-xmethods.py @@ -25,52 +25,55 @@ from gdb.xmethod import SimpleXMethodMatcher def A_plus_A(obj, opr): - print('From Python <A_plus_A>:') - return obj['a'] + opr['a'] + print("From Python <A_plus_A>:") + return obj["a"] + opr["a"] def plus_plus_A(obj): - print('From Python <plus_plus_A>:') - return obj['a'] + 1 + print("From Python <plus_plus_A>:") + return obj["a"] + 1 def A_geta(obj): - print('From Python <A_geta>:') - return obj['a'] + print("From Python <A_geta>:") + return obj["a"] def A_getarrayind(obj, index): - print('From Python <A_getarrayind>:') - return obj['array'][index] + print("From Python <A_getarrayind>:") + return obj["array"][index] + def A_indexoper(obj, index): - return obj['array'][index].reference_value() + return obj["array"][index].reference_value() + def B_indexoper(obj, index): - return obj['array'][index].const_value().reference_value() + return obj["array"][index].const_value().reference_value() -type_A = gdb.parse_and_eval('(dop::A *) 0').type.target() -type_B = gdb.parse_and_eval('(dop::B *) 0').type.target() -type_int = gdb.parse_and_eval('(int *) 0').type.target() +type_A = gdb.parse_and_eval("(dop::A *) 0").type.target() +type_B = gdb.parse_and_eval("(dop::B *) 0").type.target() +type_int = gdb.parse_and_eval("(int *) 0").type.target() # The E class matcher and worker test two things: # 1. xmethod returning None. # 2. Matcher returning a list of workers. + class E_method_char_worker(XMethodWorker): def __init__(self): pass def get_arg_types(self): - return gdb.lookup_type('char') + return gdb.lookup_type("char") def get_result_type(self, obj, arg): - return gdb.lookup_type('void') + return gdb.lookup_type("void") def __call__(self, obj, arg): - print('From Python <E_method_char>') + print("From Python <E_method_char>") return None @@ -79,25 +82,25 @@ class E_method_int_worker(XMethodWorker): pass def get_arg_types(self): - return gdb.lookup_type('int') + return gdb.lookup_type("int") # Note: get_result_type method elided on purpose def __call__(self, obj, arg): - print('From Python <E_method_int>') + print("From Python <E_method_int>") return None class E_method_matcher(XMethodMatcher): def __init__(self): - XMethodMatcher.__init__(self, 'E_methods') - self.methods = [XMethod('method_int'), XMethod('method_char')] + XMethodMatcher.__init__(self, "E_methods") + self.methods = [XMethod("method_int"), XMethod("method_char")] def match(self, class_type, method_name): class_tag = class_type.unqualified().tag - if not re.match('^dop::E$', class_tag): + if not re.match("^dop::E$", class_tag): return None - if not re.match('^method$', method_name): + if not re.match("^method$", method_name): return None workers = [] if self.methods[0].enabled: @@ -111,6 +114,7 @@ class E_method_matcher(XMethodMatcher): # xmethod matchers and workers for template classes and template # methods. + class G_size_diff_worker(XMethodWorker): def __init__(self, class_template_type, method_template_type): self._class_template_type = class_template_type @@ -120,9 +124,8 @@ class G_size_diff_worker(XMethodWorker): pass def __call__(self, obj): - print('From Python G<>::size_diff()') - return (self._method_template_type.sizeof - - self._class_template_type.sizeof) + print("From Python G<>::size_diff()") + return self._method_template_type.sizeof - self._class_template_type.sizeof class G_size_mul_worker(XMethodWorker): @@ -134,7 +137,7 @@ class G_size_mul_worker(XMethodWorker): pass def __call__(self, obj): - print('From Python G<>::size_mul()') + print("From Python G<>::size_mul()") return self._class_template_type.sizeof * self._method_template_val @@ -147,16 +150,14 @@ class G_mul_worker(XMethodWorker): return self._method_template_type def __call__(self, obj, arg): - print('From Python G<>::mul()') - return obj['t'] * arg + print("From Python G<>::mul()") + return obj["t"] * arg class G_methods_matcher(XMethodMatcher): def __init__(self): - XMethodMatcher.__init__(self, 'G_methods') - self.methods = [XMethod('size_diff'), - XMethod('size_mul'), - XMethod('mul')] + XMethodMatcher.__init__(self, "G_methods") + self.methods = [XMethod("size_diff"), XMethod("size_mul"), XMethod("mul")] def _is_enabled(self, name): for method in self.methods: @@ -165,16 +166,15 @@ class G_methods_matcher(XMethodMatcher): def match(self, class_type, method_name): class_tag = class_type.unqualified().tag - if not re.match('^dop::G<[ ]*[_a-zA-Z][ _a-zA-Z0-9]*>$', - class_tag): + if not re.match("^dop::G<[ ]*[_a-zA-Z][ _a-zA-Z0-9]*>$", class_tag): return None t_name = class_tag[7:-1] try: t_type = gdb.lookup_type(t_name) except gdb.error: return None - if re.match('^size_diff<[ ]*[_a-zA-Z][ _a-zA-Z0-9]*>$', method_name): - if not self._is_enabled('size_diff'): + if re.match("^size_diff<[ ]*[_a-zA-Z][ _a-zA-Z0-9]*>$", method_name): + if not self._is_enabled("size_diff"): return None t1_name = method_name[10:-1] try: @@ -182,13 +182,13 @@ class G_methods_matcher(XMethodMatcher): return G_size_diff_worker(t_type, t1_type) except gdb.error: return None - if re.match('^size_mul<[ ]*[0-9]+[ ]*>$', method_name): - if not self._is_enabled('size_mul'): + if re.match("^size_mul<[ ]*[0-9]+[ ]*>$", method_name): + if not self._is_enabled("size_mul"): return None m_val = int(method_name[9:-1]) return G_size_mul_worker(t_type, m_val) - if re.match('^mul<[ ]*[_a-zA-Z][ _a-zA-Z0-9]*>$', method_name): - if not self._is_enabled('mul'): + if re.match("^mul<[ ]*[_a-zA-Z][ _a-zA-Z0-9]*>$", method_name): + if not self._is_enabled("mul"): return None t1_name = method_name[4:-1] try: @@ -199,41 +199,29 @@ class G_methods_matcher(XMethodMatcher): global_dm_list = [ - SimpleXMethodMatcher(r'A_plus_A', - r'^dop::A$', - r'operator\+', - A_plus_A, - # This is a replacement, hence match the arg type - # exactly! - type_A.const().reference()), - SimpleXMethodMatcher(r'plus_plus_A', - r'^dop::A$', - r'operator\+\+', - plus_plus_A), - SimpleXMethodMatcher(r'A_geta', - r'^dop::A$', - r'^geta$', - A_geta), - SimpleXMethodMatcher(r'A_getarrayind', - r'^dop::A$', - r'^getarrayind$', - A_getarrayind, - type_int), - SimpleXMethodMatcher(r'A_indexoper', - r'^dop::A$', - r'operator\[\]', - A_indexoper, - type_int), - SimpleXMethodMatcher(r'B_indexoper', - r'^dop::B$', - r'operator\[\]', - B_indexoper, - type_int) + SimpleXMethodMatcher( + r"A_plus_A", + r"^dop::A$", + r"operator\+", + A_plus_A, + # This is a replacement, hence match the arg type + # exactly! + type_A.const().reference(), + ), + SimpleXMethodMatcher(r"plus_plus_A", r"^dop::A$", r"operator\+\+", plus_plus_A), + SimpleXMethodMatcher(r"A_geta", r"^dop::A$", r"^geta$", A_geta), + SimpleXMethodMatcher( + r"A_getarrayind", r"^dop::A$", r"^getarrayind$", A_getarrayind, type_int + ), + SimpleXMethodMatcher( + r"A_indexoper", r"^dop::A$", r"operator\[\]", A_indexoper, type_int + ), + SimpleXMethodMatcher( + r"B_indexoper", r"^dop::B$", r"operator\[\]", B_indexoper, type_int + ), ] for matcher in global_dm_list: gdb.xmethod.register_xmethod_matcher(gdb, matcher) -gdb.xmethod.register_xmethod_matcher(gdb.current_progspace(), - G_methods_matcher()) -gdb.xmethod.register_xmethod_matcher(gdb.current_progspace(), - E_method_matcher()) +gdb.xmethod.register_xmethod_matcher(gdb.current_progspace(), G_methods_matcher()) +gdb.xmethod.register_xmethod_matcher(gdb.current_progspace(), E_method_matcher()) diff --git a/gdb/testsuite/gdb.python/source2.py b/gdb/testsuite/gdb.python/source2.py index 1a332f6..a2cff76 100644 --- a/gdb/testsuite/gdb.python/source2.py +++ b/gdb/testsuite/gdb.python/source2.py @@ -15,4 +15,4 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -print ('y%ss' % 'e') +print("y%ss" % "e") diff --git a/gdb/testsuite/gdb.python/tui-window-disabled.py b/gdb/testsuite/gdb.python/tui-window-disabled.py index 0b3c076..2510f13 100644 --- a/gdb/testsuite/gdb.python/tui-window-disabled.py +++ b/gdb/testsuite/gdb.python/tui-window-disabled.py @@ -28,62 +28,65 @@ cleanup_properly = False # A global place into which we can write the window title. titles_at_the_close = {} + class EventWindow: - def __init__ (self, win): + def __init__(self, win): self._win = win self._count = 0 win.title = "This Is The Event Window" - self._stop_listener = lambda e : self._event ('stop', e) - gdb.events.stop.connect (self._stop_listener) - self._exit_listener = lambda e : self._event ('exit', e) - gdb.events.exited.connect (self._exit_listener) + self._stop_listener = lambda e: self._event("stop", e) + gdb.events.stop.connect(self._stop_listener) + self._exit_listener = lambda e: self._event("exit", e) + gdb.events.exited.connect(self._exit_listener) self._events = [] # Ensure we can erase and write to the window from the # constructor, the window should be valid by this point. - self._win.erase () - self._win.write ("Hello world...") + self._win.erase() + self._win.write("Hello world...") - def close (self): + def close(self): global cleanup_properly global titles_at_the_close # Ensure that window properties can be read within the close method. - titles_at_the_close[self._win.title] = dict (width=self._win.width, - height=self._win.height) + titles_at_the_close[self._win.title] = dict( + width=self._win.width, height=self._win.height + ) # The following calls are pretty pointless, but this ensures # that we can erase and write to a window from the close # method, the last moment a window should be valid. - self._win.erase () - self._win.write ("Goodbye cruel world...") + self._win.erase() + self._win.write("Goodbye cruel world...") if cleanup_properly: # Disconnect the listeners and delete the lambda functions. # This removes cyclic references to SELF, and so alows SELF to # be deleted. - gdb.events.stop.disconnect (self._stop_listener) - gdb.events.exited.disconnect (self._exit_listener) + gdb.events.stop.disconnect(self._stop_listener) + gdb.events.exited.disconnect(self._exit_listener) self._stop_listener = None self._exit_listener = None - def _event (self, type, event): + def _event(self, type, event): global perform_valid_check global update_title self._count += 1 - self._events.insert (0, type) - if not perform_valid_check or self._win.is_valid (): + self._events.insert(0, type) + if not perform_valid_check or self._win.is_valid(): if update_title: - self._win.title = "This Is The Event Window (" + str (self._count) + ")" + self._win.title = "This Is The Event Window (" + str(self._count) + ")" else: - self.render () + self.render() - def render (self): - self._win.erase () + def render(self): + self._win.erase() w = self._win.width h = self._win.height - for i in range (min (h, len (self._events))): - self._win.write (self._events[i] + "\n") + for i in range(min(h, len(self._events))): + self._win.write(self._events[i] + "\n") + gdb.register_window_type("events", EventWindow) diff --git a/gdb/testsuite/gdb.python/tui-window.py b/gdb/testsuite/gdb.python/tui-window.py index 3bea788..db824e9 100644 --- a/gdb/testsuite/gdb.python/tui-window.py +++ b/gdb/testsuite/gdb.python/tui-window.py @@ -19,6 +19,7 @@ import gdb the_window = None + class TestWindow: def __init__(self, win): global the_window @@ -38,14 +39,17 @@ class TestWindow: def remove_title(self): del self.win.title + gdb.register_window_type("test", TestWindow) # Call REMOVE_TITLE on the global window object. -def delete_window_title (): - the_window.remove_title () +def delete_window_title(): + the_window.remove_title() + # A TUI window "constructor" that always fails. def failwin(win): raise RuntimeError("Whoops") + gdb.register_window_type("fail", failwin) |