]>
git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/python/lib/gdb/__init__.py
1 # Copyright (C) 2010-2022 Free Software Foundation, Inc.
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 3 of the License, or
6 # (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from contextlib
import contextmanager
22 # Python 3 moved "reload"
23 if sys
.version_info
>= (3, 4):
24 from importlib
import reload
26 from imp
import reload
30 # Historically, gdb.events was always available, so ensure it's
31 # still available without an explicit import.
32 import _gdbevents
as events
34 sys
.modules
["gdb.events"] = events
37 class _GdbFile(object):
38 # These two are needed in Python 3
49 def writelines(self
, iterable
):
57 class _GdbOutputFile(_GdbFile
):
59 write(s
, stream
=STDOUT
)
62 sys
.stdout
= _GdbOutputFile()
65 class _GdbOutputErrorFile(_GdbFile
):
67 write(s
, stream
=STDERR
)
70 sys
.stderr
= _GdbOutputErrorFile()
72 # Default prompt hook does nothing.
75 # Ensure that sys.argv is set to something.
76 # We do not use PySys_SetArgvEx because it did not appear until 2.6.6.
79 # Initial pretty printers.
82 # Initial type printers.
84 # Initial xmethod matchers.
86 # Initial frame filters.
88 # Initial frame unwinders.
92 def _execute_unwinders(pending_frame
):
93 """Internal function called from GDB to execute all unwinders.
95 Runs each currently enabled unwinder until it finds the one that
96 can unwind given frame.
99 pending_frame: gdb.PendingFrame instance.
104 [0] gdb.UnwindInfo instance
105 [1] Name of unwinder that claimed the frame (type `str`)
107 or None, if no unwinder has claimed the frame.
109 for objfile
in objfiles():
110 for unwinder
in objfile
.frame_unwinders
:
112 unwind_info
= unwinder(pending_frame
)
113 if unwind_info
is not None:
114 return (unwind_info
, unwinder
.name
)
116 for unwinder
in current_progspace().frame_unwinders
:
118 unwind_info
= unwinder(pending_frame
)
119 if unwind_info
is not None:
120 return (unwind_info
, unwinder
.name
)
122 for unwinder
in frame_unwinders
:
124 unwind_info
= unwinder(pending_frame
)
125 if unwind_info
is not None:
126 return (unwind_info
, unwinder
.name
)
131 def _execute_file(filepath
):
132 """This function is used to replace Python 2's PyRun_SimpleFile.
134 Loads and executes the given file.
136 We could use the runpy module, but its documentation says:
137 "Furthermore, any functions and classes defined by the executed code are
138 not guaranteed to work correctly after a runpy function has returned."
140 globals = sys
.modules
["__main__"].__dict
__
142 # Set file (if not set) so that the imported file can use it (e.g. to
143 # access file-relative paths). This matches what PyRun_SimpleFile does.
144 if not hasattr(globals, "__file__"):
145 globals["__file__"] = filepath
148 with
open(filepath
, "rb") as file:
149 # We pass globals also as locals to match what Python does
150 # in PyRun_SimpleFile.
151 compiled
= compile(file.read(), filepath
, "exec")
152 exec(compiled
, globals, globals)
155 del globals["__file__"]
158 # Convenience variable to GDB's python directory
159 PYTHONDIR
= os
.path
.dirname(os
.path
.dirname(__file__
))
161 # Auto-load all functions/commands.
163 # Packages to auto-load.
165 packages
= ["function", "command", "printer"]
167 # pkgutil.iter_modules is not available prior to Python 2.6. Instead,
168 # manually iterate the list, collating the Python files in each module
169 # path. Construct the module name, and import.
172 def _auto_load_packages():
173 for package
in packages
:
174 location
= os
.path
.join(os
.path
.dirname(__file__
), package
)
175 if os
.path
.exists(location
):
177 lambda x
: x
.endswith(".py") and x
!= "__init__.py", os
.listdir(location
)
180 for py_file
in py_files
:
181 # Construct from foo.py, gdb.module.foo
182 modname
= "%s.%s.%s" % (__name__
, package
, py_file
[:-3])
184 if modname
in sys
.modules
:
185 # reload modules with duplicate names
186 reload(__import__(modname
))
190 sys
.stderr
.write(traceback
.format_exc() + "\n")
193 _auto_load_packages()
196 def GdbSetPythonDirectory(dir):
197 """Update sys.path, reload gdb and auto-load packages."""
201 sys
.path
.remove(PYTHONDIR
)
204 sys
.path
.insert(0, dir)
208 # note that reload overwrites the gdb module without deleting existing
210 reload(__import__(__name__
))
211 _auto_load_packages()
214 def current_progspace():
215 "Return the current Progspace."
216 return selected_inferior().progspace
220 "Return a sequence of the current program space's objfiles."
221 return current_progspace().objfiles()
224 def solib_name(addr
):
225 """solib_name (Long) -> String.\n\
226 Return the name of the shared library holding a given address, or None."""
227 return current_progspace().solib_name(addr
)
230 def block_for_pc(pc
):
231 "Return the block containing the given pc value, or None."
232 return current_progspace().block_for_pc(pc
)
235 def find_pc_line(pc
):
236 """find_pc_line (pc) -> Symtab_and_line.
237 Return the gdb.Symtab_and_line object corresponding to the pc value."""
238 return current_progspace().find_pc_line(pc
)
241 def set_parameter(name
, value
):
242 """Set the GDB parameter NAME to VALUE."""
243 # Handle the specific case of booleans here, because gdb.parameter
244 # can return them, but they can't be passed to 'set' this way.
245 if isinstance(value
, bool):
250 execute("set " + name
+ " " + str(value
), to_string
=True)
254 def with_parameter(name
, value
):
255 """Temporarily set the GDB parameter NAME to VALUE.
256 Note that this is a context manager."""
257 old_value
= parameter(name
)
258 set_parameter(name
, value
)
260 # Nothing that useful to return.
263 set_parameter(name
, old_value
)