Automatic Copyright Year update after running gdb/copyright.py
[deliverable/binutils-gdb.git] / gdb / python / lib / gdb / __init__.py
1 # Copyright (C) 2010-2022 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
16 import traceback
17 import os
18 import sys
19 import _gdb
20
21 # Python 3 moved "reload"
22 if sys.version_info >= (3, 4):
23 from importlib import reload
24 elif sys.version_info[0] > 2:
25 from imp import reload
26
27 from _gdb import *
28
29
30 class _GdbFile(object):
31 # These two are needed in Python 3
32 encoding = "UTF-8"
33 errors = "strict"
34
35 def close(self):
36 # Do nothing.
37 return None
38
39 def isatty(self):
40 return False
41
42 def writelines(self, iterable):
43 for line in iterable:
44 self.write(line)
45
46 def flush(self):
47 flush()
48
49
50 class _GdbOutputFile(_GdbFile):
51 def write(self, s):
52 write(s, stream=STDOUT)
53
54
55 sys.stdout = _GdbOutputFile()
56
57
58 class _GdbOutputErrorFile(_GdbFile):
59 def write(self, s):
60 write(s, stream=STDERR)
61
62
63 sys.stderr = _GdbOutputErrorFile()
64
65 # Default prompt hook does nothing.
66 prompt_hook = None
67
68 # Ensure that sys.argv is set to something.
69 # We do not use PySys_SetArgvEx because it did not appear until 2.6.6.
70 sys.argv = [""]
71
72 # Initial pretty printers.
73 pretty_printers = []
74
75 # Initial type printers.
76 type_printers = []
77 # Initial xmethod matchers.
78 xmethods = []
79 # Initial frame filters.
80 frame_filters = {}
81 # Initial frame unwinders.
82 frame_unwinders = []
83
84
85 def _execute_unwinders(pending_frame):
86 """Internal function called from GDB to execute all unwinders.
87
88 Runs each currently enabled unwinder until it finds the one that
89 can unwind given frame.
90
91 Arguments:
92 pending_frame: gdb.PendingFrame instance.
93
94 Returns:
95 Tuple with:
96
97 [0] gdb.UnwindInfo instance
98 [1] Name of unwinder that claimed the frame (type `str`)
99
100 or None, if no unwinder has claimed the frame.
101 """
102 for objfile in objfiles():
103 for unwinder in objfile.frame_unwinders:
104 if unwinder.enabled:
105 unwind_info = unwinder(pending_frame)
106 if unwind_info is not None:
107 return (unwind_info, unwinder.name)
108
109 for unwinder in current_progspace().frame_unwinders:
110 if unwinder.enabled:
111 unwind_info = unwinder(pending_frame)
112 if unwind_info is not None:
113 return (unwind_info, unwinder.name)
114
115 for unwinder in frame_unwinders:
116 if unwinder.enabled:
117 unwind_info = unwinder(pending_frame)
118 if unwind_info is not None:
119 return (unwind_info, unwinder.name)
120
121 return None
122
123
124 def _execute_file(filepath):
125 """This function is used to replace Python 2's PyRun_SimpleFile.
126
127 Loads and executes the given file.
128
129 We could use the runpy module, but its documentation says:
130 "Furthermore, any functions and classes defined by the executed code are
131 not guaranteed to work correctly after a runpy function has returned."
132 """
133 globals = sys.modules["__main__"].__dict__
134 set_file = False
135 # Set file (if not set) so that the imported file can use it (e.g. to
136 # access file-relative paths). This matches what PyRun_SimpleFile does.
137 if not hasattr(globals, "__file__"):
138 globals["__file__"] = filepath
139 set_file = True
140 try:
141 with open(filepath, "rb") as file:
142 # We pass globals also as locals to match what Python does
143 # in PyRun_SimpleFile.
144 compiled = compile(file.read(), filepath, "exec")
145 exec(compiled, globals, globals)
146 finally:
147 if set_file:
148 del globals["__file__"]
149
150
151 # Convenience variable to GDB's python directory
152 PYTHONDIR = os.path.dirname(os.path.dirname(__file__))
153
154 # Auto-load all functions/commands.
155
156 # Packages to auto-load.
157
158 packages = ["function", "command", "printer"]
159
160 # pkgutil.iter_modules is not available prior to Python 2.6. Instead,
161 # manually iterate the list, collating the Python files in each module
162 # path. Construct the module name, and import.
163
164
165 def _auto_load_packages():
166 for package in packages:
167 location = os.path.join(os.path.dirname(__file__), package)
168 if os.path.exists(location):
169 py_files = filter(
170 lambda x: x.endswith(".py") and x != "__init__.py", os.listdir(location)
171 )
172
173 for py_file in py_files:
174 # Construct from foo.py, gdb.module.foo
175 modname = "%s.%s.%s" % (__name__, package, py_file[:-3])
176 try:
177 if modname in sys.modules:
178 # reload modules with duplicate names
179 reload(__import__(modname))
180 else:
181 __import__(modname)
182 except:
183 sys.stderr.write(traceback.format_exc() + "\n")
184
185
186 _auto_load_packages()
187
188
189 def GdbSetPythonDirectory(dir):
190 """Update sys.path, reload gdb and auto-load packages."""
191 global PYTHONDIR
192
193 try:
194 sys.path.remove(PYTHONDIR)
195 except ValueError:
196 pass
197 sys.path.insert(0, dir)
198
199 PYTHONDIR = dir
200
201 # note that reload overwrites the gdb module without deleting existing
202 # attributes
203 reload(__import__(__name__))
204 _auto_load_packages()
205
206
207 def current_progspace():
208 "Return the current Progspace."
209 return selected_inferior().progspace
210
211
212 def objfiles():
213 "Return a sequence of the current program space's objfiles."
214 return current_progspace().objfiles()
215
216
217 def solib_name(addr):
218 """solib_name (Long) -> String.\n\
219 Return the name of the shared library holding a given address, or None."""
220 return current_progspace().solib_name(addr)
221
222
223 def block_for_pc(pc):
224 "Return the block containing the given pc value, or None."
225 return current_progspace().block_for_pc(pc)
226
227
228 def find_pc_line(pc):
229 """find_pc_line (pc) -> Symtab_and_line.
230 Return the gdb.Symtab_and_line object corresponding to the pc value."""
231 return current_progspace().find_pc_line(pc)
232
233
234 try:
235 from pygments import formatters, lexers, highlight
236
237 def colorize(filename, contents):
238 # Don't want any errors.
239 try:
240 lexer = lexers.get_lexer_for_filename(filename, stripnl=False)
241 formatter = formatters.TerminalFormatter()
242 return highlight(contents, lexer, formatter)
243 except:
244 return None
245
246
247 except:
248
249 def colorize(filename, contents):
250 return None
This page took 0.03484 seconds and 4 git commands to generate.