GDB (xrefs)
Loading...
Searching...
No Matches
__init__.py
Go to the documentation of this file.
1# Copyright (C) 2010-2023 Free Software Foundation, Inc.
2
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.
7#
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.
12#
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/>.
15
16import signal
17import threading
18import traceback
19import os
20import sys
21import _gdb
22from contextlib import contextmanager
23
24# Python 3 moved "reload"
25if sys.version_info >= (3, 4):
26 from importlib import reload
27else:
28 from imp import reload
29
30from _gdb import *
31
32# Historically, gdb.events was always available, so ensure it's
33# still available without an explicit import.
34import _gdbevents as events
35
36sys.modules["gdb.events"] = events
37
38
39class _GdbFile(object):
40 # These two are needed in Python 3
41 encoding = "UTF-8"
42 errors = "strict"
43
44 def __init__(self, stream):
45 self.stream = stream
46
47 def close(self):
48 # Do nothing.
49 return None
50
51 def isatty(self):
52 return False
53
54 def writelines(self, iterable):
55 for line in iterable:
56 self.writewrite(line)
57
58 def flush(self):
59 flush(stream=self.stream)
60
61 def write(self, s):
62 write(s, stream=self.stream)
63
64
65sys.stdout = _GdbFile(STDOUT)
66
67sys.stderr = _GdbFile(STDERR)
68
69# Default prompt hook does nothing.
70prompt_hook = None
71
72# Ensure that sys.argv is set to something.
73# We do not use PySys_SetArgvEx because it did not appear until 2.6.6.
74sys.argv = [""]
75
76# Initial pretty printers.
77pretty_printers = []
78
79# Initial type printers.
80type_printers = []
81# Initial xmethod matchers.
82xmethods = []
83# Initial frame filters.
84frame_filters = {}
85# Initial frame unwinders.
86frame_unwinders = []
87
88
89def _execute_unwinders(pending_frame):
90 """Internal function called from GDB to execute all unwinders.
91
92 Runs each currently enabled unwinder until it finds the one that
93 can unwind given frame.
94
95 Arguments:
96 pending_frame: gdb.PendingFrame instance.
97
98 Returns:
99 Tuple with:
100
101 [0] gdb.UnwindInfo instance
102 [1] Name of unwinder that claimed the frame (type `str`)
103
104 or None, if no unwinder has claimed the frame.
105 """
106 for objfile in objfiles():
107 for unwinder in objfile.frame_unwinders:
108 if unwinder.enabled:
109 unwind_info = unwinder(pending_frame)
110 if unwind_info is not None:
111 return (unwind_info, unwinder.name)
112
113 for unwinder in current_progspace().frame_unwinders:
114 if unwinder.enabled:
115 unwind_info = unwinder(pending_frame)
116 if unwind_info is not None:
117 return (unwind_info, unwinder.name)
118
119 for unwinder in frame_unwinders:
120 if unwinder.enabled:
121 unwind_info = unwinder(pending_frame)
122 if unwind_info is not None:
123 return (unwind_info, unwinder.name)
124
125 return None
126
127
128def _execute_file(filepath):
129 """This function is used to replace Python 2's PyRun_SimpleFile.
130
131 Loads and executes the given file.
132
133 We could use the runpy module, but its documentation says:
134 "Furthermore, any functions and classes defined by the executed code are
135 not guaranteed to work correctly after a runpy function has returned."
136 """
137 globals = sys.modules["__main__"].__dict__
138 set_file = False
139 # Set file (if not set) so that the imported file can use it (e.g. to
140 # access file-relative paths). This matches what PyRun_SimpleFile does.
141 if not hasattr(globals, "__file__"):
142 globals["__file__"] = filepath
143 set_file = True
144 try:
145 with open(filepath, "rb") as file:
146 # We pass globals also as locals to match what Python does
147 # in PyRun_SimpleFile.
148 compiled = compile(file.read(), filepath, "exec")
149 exec(compiled, globals, globals)
150 finally:
151 if set_file:
152 del globals["__file__"]
153
154
155# Convenience variable to GDB's python directory
156PYTHONDIR = os.path.dirname(os.path.dirname(__file__))
157
158# Auto-load all functions/commands.
159
160# Packages to auto-load.
161
162packages = ["function", "command", "printer"]
163
164# pkgutil.iter_modules is not available prior to Python 2.6. Instead,
165# manually iterate the list, collating the Python files in each module
166# path. Construct the module name, and import.
167
168
170 for package in packages:
171 location = os.path.join(os.path.dirname(__file__), package)
172 if os.path.exists(location):
173 py_files = filter(
174 lambda x: x.endswith(".py") and x != "__init__.py", os.listdir(location)
175 )
176
177 for py_file in py_files:
178 # Construct from foo.py, gdb.module.foo
179 modname = "%s.%s.%s" % (__name__, package, py_file[:-3])
180 try:
181 if modname in sys.modules:
182 # reload modules with duplicate names
183 reload(__import__(modname))
184 else:
185 __import__(modname)
186 except:
187 sys.stderr.write(traceback.format_exc() + "\n")
188
189
191
192
193def GdbSetPythonDirectory(dir):
194 """Update sys.path, reload gdb and auto-load packages."""
195 global PYTHONDIR
196
197 try:
198 sys.path.remove(PYTHONDIR)
199 except ValueError:
200 pass
201 sys.path.insert(0, dir)
202
203 PYTHONDIR = dir
204
205 # note that reload overwrites the gdb module without deleting existing
206 # attributes
207 reload(__import__(__name__))
209
210
212 "Return the current Progspace."
213 return selected_inferior().progspace
214
215
216def objfiles():
217 "Return a sequence of the current program space's objfiles."
218 return current_progspace().objfiles()
219
220
221def solib_name(addr):
222 """solib_name (Long) -> String.\n\
223Return the name of the shared library holding a given address, or None."""
224 return current_progspace().solib_name(addr)
225
226
227def block_for_pc(pc):
228 "Return the block containing the given pc value, or None."
230
231
232def find_pc_line(pc):
233 """find_pc_line (pc) -> Symtab_and_line.
234 Return the gdb.Symtab_and_line object corresponding to the pc value."""
236
237
238def set_parameter(name, value):
239 """Set the GDB parameter NAME to VALUE."""
240 # Handle the specific cases of None and booleans here, because
241 # gdb.parameter can return them, but they can't be passed to 'set'
242 # this way.
243 if value is None:
244 value = "unlimited"
245 elif isinstance(value, bool):
246 if value:
247 value = "on"
248 else:
249 value = "off"
250 execute("set " + name + " " + str(value), to_string=True)
251
252
253@contextmanager
254def 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)
259 try:
260 # Nothing that useful to return.
261 yield None
262 finally:
263 set_parameter(name, old_value)
264
265
266@contextmanager
267def blocked_signals():
268 """A helper function that blocks and unblocks signals."""
269 if not hasattr(signal, "pthread_sigmask"):
270 yield
271 return
272
273 to_block = {signal.SIGCHLD, signal.SIGINT, signal.SIGALRM, signal.SIGWINCH}
274 old_mask = signal.pthread_sigmask(signal.SIG_BLOCK, to_block)
275 try:
276 yield None
277 finally:
278 signal.pthread_sigmask(signal.SIG_SETMASK, old_mask)
279
280
281class Thread(threading.Thread):
282 """A GDB-specific wrapper around threading.Thread
283
284 This wrapper ensures that the new thread blocks any signals that
285 must be delivered on GDB's main thread."""
286
287 def start(self):
288 # GDB requires that these be delivered to the main thread. We
289 # do this here to avoid any possible race with the creation of
290 # the new thread. The thread mask is inherited by new
291 # threads.
292 with blocked_signals():
293 super().start()
start(self)
Definition __init__.py:287
flush(self)
Definition __init__.py:58
writelines(self, iterable)
Definition __init__.py:54
close(self)
Definition __init__.py:47
isatty(self)
Definition __init__.py:51
write(self, s)
Definition __init__.py:61
__init__(self, stream)
Definition __init__.py:44
_auto_load_packages()
Definition __init__.py:169
current_progspace()
Definition __init__.py:211
find_pc_line(pc)
Definition __init__.py:232
block_for_pc(pc)
Definition __init__.py:227
GdbSetPythonDirectory(dir)
Definition __init__.py:193
_execute_file(filepath)
Definition __init__.py:128
_execute_unwinders(pending_frame)
Definition __init__.py:89
with_parameter(name, value)
Definition __init__.py:254
objfiles()
Definition __init__.py:216
blocked_signals()
Definition __init__.py:267
solib_name(addr)
Definition __init__.py:221
set_parameter(name, value)
Definition __init__.py:238