python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
---|---|---|
# Caller-is functions.
# Copyright (C) 2008-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
import re
class CallerIs(gdb.Function):
"""Check the calling function's name.
Usage: $_caller_is (NAME [, NUMBER-OF-FRAMES])
Arguments:
NAME: The name of the function to search for.
NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
selected frame to compare with. If the value is greater than the depth of
the stack from that point then the result is False.
The default is 1.
Returns:
True if the function's name at the specified frame is equal to NAME."""
def __init__(self):
super(CallerIs, self).__init__("_caller_is")
def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
while nframes > 0:
frame = frame.older()
if frame is None:
return False
nframes = nframes - 1
return frame.name() == name.string()
class CallerMatches(gdb.Function):
"""Compare the calling function's name with a regexp.
Usage: $_caller_matches (REGEX [, NUMBER-OF-FRAMES])
Arguments:
REGEX: The regular expression to compare the function's name with.
NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
selected frame to compare with. If the value is greater than the depth of
the stack from that point then the result is False.
The default is 1.
Returns:
True if the function's name at the specified frame matches REGEX."""
def __init__(self):
super(CallerMatches, self).__init__("_caller_matches")
def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
while nframes > 0:
frame = frame.older()
if frame is None:
return False
nframes = nframes - 1
return re.match(name.string(), frame.name()) is not None
class AnyCallerIs(gdb.Function):
"""Check all calling function's names.
Usage: $_any_caller_is (NAME [, NUMBER-OF-FRAMES])
Arguments:
NAME: The name of the function to search for.
NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
selected frame to compare with. If the value is greater than the depth of
the stack from that point then the result is False.
The default is 1.
Returns:
True if any function's name is equal to NAME."""
def __init__(self):
super(AnyCallerIs, self).__init__("_any_caller_is")
def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
while nframes >= 0:
if frame.name() == name.string():
return True
frame = frame.older()
if frame is None:
return False
nframes = nframes - 1
return False
class AnyCallerMatches(gdb.Function):
"""Compare all calling function's names with a regexp.
Usage: $_any_caller_matches (REGEX [, NUMBER-OF-FRAMES])
Arguments:
REGEX: The regular expression to compare the function's name with.
NUMBER-OF-FRAMES: How many stack frames to traverse back from the currently
selected frame to compare with. If the value is greater than the depth of
the stack from that point then the result is False.
The default is 1.
Returns:
True if any function's name matches REGEX."""
def __init__(self):
super(AnyCallerMatches, self).__init__("_any_caller_matches")
def invoke(self, name, nframes=1):
if nframes < 0:
raise ValueError("nframes must be >= 0")
frame = gdb.selected_frame()
name_re = re.compile(name.string())
while nframes >= 0:
if name_re.match(frame.name()) is not None:
return True
frame = frame.older()
if frame is None:
return False
nframes = nframes - 1
return False
CallerIs()
CallerMatches()
AnyCallerIs()
AnyCallerMatches()
| cuda-gdb-master | gdb/python/lib/gdb/function/caller_is.py |
# Frame-filter commands.
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""GDB commands for working with frame-filters."""
import sys
import gdb
import gdb.frames
# GDB Commands.
class SetFilterPrefixCmd(gdb.Command):
"""Prefix command for 'set' frame-filter related operations."""
def __init__(self):
super(SetFilterPrefixCmd, self).__init__(
"set frame-filter", gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE, True
)
class ShowFilterPrefixCmd(gdb.Command):
"""Prefix command for 'show' frame-filter related operations."""
def __init__(self):
super(ShowFilterPrefixCmd, self).__init__(
"show frame-filter", gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE, True
)
class InfoFrameFilter(gdb.Command):
"""List all registered Python frame-filters.
Usage: info frame-filters"""
def __init__(self):
super(InfoFrameFilter, self).__init__("info frame-filter", gdb.COMMAND_DATA)
@staticmethod
def enabled_string(state):
"""Return "Yes" if filter is enabled, otherwise "No"."""
if state:
return "Yes"
else:
return "No"
def print_list(self, title, frame_filters, blank_line):
sorted_frame_filters = sorted(
frame_filters.items(),
key=lambda i: gdb.frames.get_priority(i[1]),
reverse=True,
)
if len(sorted_frame_filters) == 0:
return 0
print(title)
print(" Priority Enabled Name")
for frame_filter in sorted_frame_filters:
name = frame_filter[0]
try:
priority = "{:<8}".format(str(gdb.frames.get_priority(frame_filter[1])))
enabled = "{:<7}".format(
self.enabled_string(gdb.frames.get_enabled(frame_filter[1]))
)
print(" %s %s %s" % (priority, enabled, name))
except Exception:
e = sys.exc_info()[1]
print(" Error printing filter '" + name + "': " + str(e))
if blank_line:
print("")
return 1
def invoke(self, arg, from_tty):
any_printed = self.print_list("global frame-filters:", gdb.frame_filters, True)
cp = gdb.current_progspace()
any_printed += self.print_list(
"progspace %s frame-filters:" % cp.filename, cp.frame_filters, True
)
for objfile in gdb.objfiles():
any_printed += self.print_list(
"objfile %s frame-filters:" % objfile.filename,
objfile.frame_filters,
False,
)
if any_printed == 0:
print("No frame filters.")
# Internal enable/disable functions.
def _enable_parse_arg(cmd_name, arg):
"""Internal worker function to take an argument from
enable/disable and return a tuple of arguments.
Arguments:
cmd_name: Name of the command invoking this function.
args: The argument as a string.
Returns:
A tuple containing the dictionary, and the argument, or just
the dictionary in the case of "all".
"""
argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc == 0:
raise gdb.GdbError(cmd_name + " requires an argument")
if argv[0] == "all":
if argc > 1:
raise gdb.GdbError(
cmd_name + ": with 'all' " "you may not specify a filter."
)
elif argc != 2:
raise gdb.GdbError(cmd_name + " takes exactly two arguments.")
return argv
def _do_enable_frame_filter(command_tuple, flag):
"""Worker for enabling/disabling frame_filters.
Arguments:
command_type: A tuple with the first element being the
frame filter dictionary, and the second being
the frame filter name.
flag: True for Enable, False for Disable.
"""
list_op = command_tuple[0]
op_list = gdb.frames.return_list(list_op)
if list_op == "all":
for item in op_list:
gdb.frames.set_enabled(item, flag)
else:
frame_filter = command_tuple[1]
try:
ff = op_list[frame_filter]
except KeyError:
msg = "frame-filter '" + str(frame_filter) + "' not found."
raise gdb.GdbError(msg)
gdb.frames.set_enabled(ff, flag)
def _complete_frame_filter_list(text, word, all_flag):
"""Worker for frame filter dictionary name completion.
Arguments:
text: The full text of the command line.
word: The most recent word of the command line.
all_flag: Whether to include the word "all" in completion.
Returns:
A list of suggested frame filter dictionary name completions
from text/word analysis. This list can be empty when there
are no suggestions for completion.
"""
if all_flag:
filter_locations = ["all", "global", "progspace"]
else:
filter_locations = ["global", "progspace"]
for objfile in gdb.objfiles():
filter_locations.append(objfile.filename)
# If the user just asked for completions with no completion
# hints, just return all the frame filter dictionaries we know
# about.
if text == "":
return filter_locations
# Otherwise filter on what we know.
flist = filter(lambda x, y=text: x.startswith(y), filter_locations)
# If we only have one completion, complete it and return it.
if len(flist) == 1:
flist[0] = flist[0][len(text) - len(word) :]
# Otherwise, return an empty list, or a list of frame filter
# dictionaries that the previous filter operation returned.
return flist
def _complete_frame_filter_name(word, printer_dict):
"""Worker for frame filter name completion.
Arguments:
word: The most recent word of the command line.
printer_dict: The frame filter dictionary to search for frame
filter name completions.
Returns: A list of suggested frame filter name completions
from word analysis of the frame filter dictionary. This list
can be empty when there are no suggestions for completion.
"""
printer_keys = printer_dict.keys()
if word == "":
return printer_keys
flist = filter(lambda x, y=word: x.startswith(y), printer_keys)
return flist
class EnableFrameFilter(gdb.Command):
"""GDB command to enable the specified frame-filter.
Usage: enable frame-filter DICTIONARY [NAME]
DICTIONARY is the name of the frame filter dictionary on which to
operate. If dictionary is set to "all", perform operations on all
dictionaries. Named dictionaries are: "global" for the global
frame filter dictionary, "progspace" for the program space's frame
filter dictionary. If either all, or the two named dictionaries
are not specified, the dictionary name is assumed to be the name
of an "objfile" -- a shared library or an executable.
NAME matches the name of the frame-filter to operate on."""
def __init__(self):
super(EnableFrameFilter, self).__init__("enable frame-filter", gdb.COMMAND_DATA)
def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
frame filter name."""
if text.count(" ") == 0:
return _complete_frame_filter_list(text, word, True)
else:
printer_list = gdb.frames.return_list(text.split()[0].rstrip())
return _complete_frame_filter_name(word, printer_list)
def invoke(self, arg, from_tty):
command_tuple = _enable_parse_arg("enable frame-filter", arg)
_do_enable_frame_filter(command_tuple, True)
class DisableFrameFilter(gdb.Command):
"""GDB command to disable the specified frame-filter.
Usage: disable frame-filter DICTIONARY [NAME]
DICTIONARY is the name of the frame filter dictionary on which to
operate. If dictionary is set to "all", perform operations on all
dictionaries. Named dictionaries are: "global" for the global
frame filter dictionary, "progspace" for the program space's frame
filter dictionary. If either all, or the two named dictionaries
are not specified, the dictionary name is assumed to be the name
of an "objfile" -- a shared library or an executable.
NAME matches the name of the frame-filter to operate on."""
def __init__(self):
super(DisableFrameFilter, self).__init__(
"disable frame-filter", gdb.COMMAND_DATA
)
def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
frame filter name."""
if text.count(" ") == 0:
return _complete_frame_filter_list(text, word, True)
else:
printer_list = gdb.frames.return_list(text.split()[0].rstrip())
return _complete_frame_filter_name(word, printer_list)
def invoke(self, arg, from_tty):
command_tuple = _enable_parse_arg("disable frame-filter", arg)
_do_enable_frame_filter(command_tuple, False)
class SetFrameFilterPriority(gdb.Command):
"""GDB command to set the priority of the specified frame-filter.
Usage: set frame-filter priority DICTIONARY NAME PRIORITY
DICTIONARY is the name of the frame filter dictionary on which to
operate. Named dictionaries are: "global" for the global frame
filter dictionary, "progspace" for the program space's framefilter
dictionary. If either of these two are not specified, the
dictionary name is assumed to be the name of an "objfile" -- a
shared library or an executable.
NAME matches the name of the frame filter to operate on.
PRIORITY is the an integer to assign the new priority to the frame
filter."""
def __init__(self):
super(SetFrameFilterPriority, self).__init__(
"set frame-filter " "priority", gdb.COMMAND_DATA
)
def _parse_pri_arg(self, arg):
"""Internal worker to parse a priority from a tuple.
Arguments:
arg: Tuple which contains the arguments from the command.
Returns:
A tuple containing the dictionary, name and priority from
the arguments.
Raises:
gdb.GdbError: An error parsing the arguments.
"""
argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc != 3:
print("set frame-filter priority " "takes exactly three arguments.")
return None
return argv
def _set_filter_priority(self, command_tuple):
"""Internal worker for setting priority of frame-filters, by
parsing a tuple and calling _set_priority with the parsed
tuple.
Arguments:
command_tuple: Tuple which contains the arguments from the
command.
"""
list_op = command_tuple[0]
frame_filter = command_tuple[1]
# GDB returns arguments as a string, so convert priority to
# a number.
priority = int(command_tuple[2])
op_list = gdb.frames.return_list(list_op)
try:
ff = op_list[frame_filter]
except KeyError:
msg = "frame-filter '" + str(frame_filter) + "' not found."
raise gdb.GdbError(msg)
gdb.frames.set_priority(ff, priority)
def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
frame filter name."""
if text.count(" ") == 0:
return _complete_frame_filter_list(text, word, False)
else:
printer_list = gdb.frames.return_list(text.split()[0].rstrip())
return _complete_frame_filter_name(word, printer_list)
def invoke(self, arg, from_tty):
command_tuple = self._parse_pri_arg(arg)
if command_tuple is not None:
self._set_filter_priority(command_tuple)
class ShowFrameFilterPriority(gdb.Command):
"""GDB command to show the priority of the specified frame-filter.
Usage: show frame-filter priority DICTIONARY NAME
DICTIONARY is the name of the frame filter dictionary on which to
operate. Named dictionaries are: "global" for the global frame
filter dictionary, "progspace" for the program space's framefilter
dictionary. If either of these two are not specified, the
dictionary name is assumed to be the name of an "objfile" -- a
shared library or an executable.
NAME matches the name of the frame-filter to operate on."""
def __init__(self):
super(ShowFrameFilterPriority, self).__init__(
"show frame-filter " "priority", gdb.COMMAND_DATA
)
def _parse_pri_arg(self, arg):
"""Internal worker to parse a dictionary and name from a
tuple.
Arguments:
arg: Tuple which contains the arguments from the command.
Returns:
A tuple containing the dictionary, and frame filter name.
Raises:
gdb.GdbError: An error parsing the arguments.
"""
argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc != 2:
print("show frame-filter priority " "takes exactly two arguments.")
return None
return argv
def get_filter_priority(self, frame_filters, name):
"""Worker for retrieving the priority of frame_filters.
Arguments:
frame_filters: Name of frame filter dictionary.
name: object to select printers.
Returns:
The priority of the frame filter.
Raises:
gdb.GdbError: A frame filter cannot be found.
"""
op_list = gdb.frames.return_list(frame_filters)
try:
ff = op_list[name]
except KeyError:
msg = "frame-filter '" + str(name) + "' not found."
raise gdb.GdbError(msg)
return gdb.frames.get_priority(ff)
def complete(self, text, word):
"""Completion function for both frame filter dictionary, and
frame filter name."""
if text.count(" ") == 0:
return _complete_frame_filter_list(text, word, False)
else:
printer_list = frame._return_list(text.split()[0].rstrip())
return _complete_frame_filter_name(word, printer_list)
def invoke(self, arg, from_tty):
command_tuple = self._parse_pri_arg(arg)
if command_tuple is None:
return
filter_name = command_tuple[1]
list_name = command_tuple[0]
try:
priority = self.get_filter_priority(list_name, filter_name)
except Exception:
e = sys.exc_info()[1]
print("Error printing filter priority for '" + name + "':" + str(e))
else:
print(
"Priority of filter '"
+ filter_name
+ "' in list '"
+ list_name
+ "' is: "
+ str(priority)
)
# Register commands
SetFilterPrefixCmd()
ShowFilterPrefixCmd()
InfoFrameFilter()
EnableFrameFilter()
DisableFrameFilter()
SetFrameFilterPriority()
ShowFrameFilterPriority()
| cuda-gdb-master | gdb/python/lib/gdb/command/frame_filters.py |
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
| cuda-gdb-master | gdb/python/lib/gdb/command/__init__.py |
# Pretty-printer commands.
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""GDB commands for working with pretty-printers."""
import copy
import gdb
import re
def parse_printer_regexps(arg):
"""Internal utility to parse a pretty-printer command argv.
Arguments:
arg: The arguments to the command. The format is:
[object-regexp [name-regexp]].
Individual printers in a collection are named as
printer-name;subprinter-name.
Returns:
The result is a 3-tuple of compiled regular expressions, except that
the resulting compiled subprinter regexp is None if not provided.
Raises:
SyntaxError: an error processing ARG
"""
argv = gdb.string_to_argv(arg)
argc = len(argv)
object_regexp = "" # match everything
name_regexp = "" # match everything
subname_regexp = None
if argc > 3:
raise SyntaxError("too many arguments")
if argc >= 1:
object_regexp = argv[0]
if argc >= 2:
name_subname = argv[1].split(";", 1)
name_regexp = name_subname[0]
if len(name_subname) == 2:
subname_regexp = name_subname[1]
# That re.compile raises SyntaxError was determined empirically.
# We catch it and reraise it to provide a slightly more useful
# error message for the user.
try:
object_re = re.compile(object_regexp)
except SyntaxError:
raise SyntaxError("invalid object regexp: %s" % object_regexp)
try:
name_re = re.compile(name_regexp)
except SyntaxError:
raise SyntaxError("invalid name regexp: %s" % name_regexp)
if subname_regexp is not None:
try:
subname_re = re.compile(subname_regexp)
except SyntaxError:
raise SyntaxError("invalid subname regexp: %s" % subname_regexp)
else:
subname_re = None
return (object_re, name_re, subname_re)
def printer_enabled_p(printer):
"""Internal utility to see if printer (or subprinter) is enabled."""
if hasattr(printer, "enabled"):
return printer.enabled
else:
return True
class InfoPrettyPrinter(gdb.Command):
"""GDB command to list all registered pretty-printers.
Usage: info pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
OBJECT-REGEXP is a regular expression matching the objects to list.
Objects are "global", the program space's file, and the objfiles within
that program space.
NAME-REGEXP matches the name of the pretty-printer.
Individual printers in a collection are named as
printer-name;subprinter-name."""
def __init__(self):
super(InfoPrettyPrinter, self).__init__("info pretty-printer", gdb.COMMAND_DATA)
@staticmethod
def enabled_string(printer):
"""Return "" if PRINTER is enabled, otherwise " [disabled]"."""
if printer_enabled_p(printer):
return ""
else:
return " [disabled]"
@staticmethod
def printer_name(printer):
"""Return the printer's name."""
if hasattr(printer, "name"):
return printer.name
if hasattr(printer, "__name__"):
return printer.__name__
# This "shouldn't happen", but the public API allows for
# direct additions to the pretty-printer list, and we shouldn't
# crash because someone added a bogus printer.
# Plus we want to give the user a way to list unknown printers.
return "unknown"
def list_pretty_printers(self, pretty_printers, name_re, subname_re):
"""Print a list of pretty-printers."""
# A potential enhancement is to provide an option to list printers in
# "lookup order" (i.e. unsorted).
sorted_pretty_printers = sorted(
copy.copy(pretty_printers), key=self.printer_name
)
for printer in sorted_pretty_printers:
name = self.printer_name(printer)
enabled = self.enabled_string(printer)
if name_re.match(name):
print(" %s%s" % (name, enabled))
if hasattr(printer, "subprinters") and printer.subprinters is not None:
sorted_subprinters = sorted(
copy.copy(printer.subprinters), key=self.printer_name
)
for subprinter in sorted_subprinters:
if not subname_re or subname_re.match(subprinter.name):
print(
" %s%s"
% (subprinter.name, self.enabled_string(subprinter))
)
def invoke1(
self, title, printer_list, obj_name_to_match, object_re, name_re, subname_re
):
"""Subroutine of invoke to simplify it."""
if printer_list and object_re.match(obj_name_to_match):
print(title)
self.list_pretty_printers(printer_list, name_re, subname_re)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
(object_re, name_re, subname_re) = parse_printer_regexps(arg)
self.invoke1(
"global pretty-printers:",
gdb.pretty_printers,
"global",
object_re,
name_re,
subname_re,
)
cp = gdb.current_progspace()
self.invoke1(
"progspace %s pretty-printers:" % cp.filename,
cp.pretty_printers,
"progspace",
object_re,
name_re,
subname_re,
)
for objfile in gdb.objfiles():
self.invoke1(
"objfile %s pretty-printers:" % objfile.filename,
objfile.pretty_printers,
objfile.filename,
object_re,
name_re,
subname_re,
)
def count_enabled_printers(pretty_printers):
"""Return a 2-tuple of number of enabled and total printers."""
enabled = 0
total = 0
for printer in pretty_printers:
if hasattr(printer, "subprinters") and printer.subprinters is not None:
if printer_enabled_p(printer):
for subprinter in printer.subprinters:
if printer_enabled_p(subprinter):
enabled += 1
total += len(printer.subprinters)
else:
if printer_enabled_p(printer):
enabled += 1
total += 1
return (enabled, total)
def count_all_enabled_printers():
"""Return a 2-tuble of the enabled state and total number of all printers.
This includes subprinters.
"""
enabled_count = 0
total_count = 0
(t_enabled, t_total) = count_enabled_printers(gdb.pretty_printers)
enabled_count += t_enabled
total_count += t_total
(t_enabled, t_total) = count_enabled_printers(
gdb.current_progspace().pretty_printers
)
enabled_count += t_enabled
total_count += t_total
for objfile in gdb.objfiles():
(t_enabled, t_total) = count_enabled_printers(objfile.pretty_printers)
enabled_count += t_enabled
total_count += t_total
return (enabled_count, total_count)
def pluralize(text, n, suffix="s"):
"""Return TEXT pluralized if N != 1."""
if n != 1:
return "%s%s" % (text, suffix)
else:
return text
def show_pretty_printer_enabled_summary():
"""Print the number of printers enabled/disabled.
We count subprinters individually.
"""
(enabled_count, total_count) = count_all_enabled_printers()
print("%d of %d printers enabled" % (enabled_count, total_count))
def do_enable_pretty_printer_1(pretty_printers, name_re, subname_re, flag):
"""Worker for enabling/disabling pretty-printers.
Arguments:
pretty_printers: list of pretty-printers
name_re: regular-expression object to select printers
subname_re: regular expression object to select subprinters or None
if all are affected
flag: True for Enable, False for Disable
Returns:
The number of printers affected.
This is just for informational purposes for the user.
"""
total = 0
for printer in pretty_printers:
if (
hasattr(printer, "name")
and name_re.match(printer.name)
or hasattr(printer, "__name__")
and name_re.match(printer.__name__)
):
if hasattr(printer, "subprinters") and printer.subprinters is not None:
if not subname_re:
# Only record printers that change state.
if printer_enabled_p(printer) != flag:
for subprinter in printer.subprinters:
if printer_enabled_p(subprinter):
total += 1
# NOTE: We preserve individual subprinter settings.
printer.enabled = flag
else:
# NOTE: Whether this actually disables the subprinter
# depends on whether the printer's lookup function supports
# the "enable" API. We can only assume it does.
for subprinter in printer.subprinters:
if subname_re.match(subprinter.name):
# Only record printers that change state.
if (
printer_enabled_p(printer)
and printer_enabled_p(subprinter) != flag
):
total += 1
subprinter.enabled = flag
else:
# This printer has no subprinters.
# If the user does "disable pretty-printer .* .* foo"
# should we disable printers that don't have subprinters?
# How do we apply "foo" in this context? Since there is no
# "foo" subprinter it feels like we should skip this printer.
# There's still the issue of how to handle
# "disable pretty-printer .* .* .*", and every other variation
# that can match everything. For now punt and only support
# "disable pretty-printer .* .*" (i.e. subname is elided)
# to disable everything.
if not subname_re:
# Only record printers that change state.
if printer_enabled_p(printer) != flag:
total += 1
printer.enabled = flag
return total
def do_enable_pretty_printer(arg, flag):
"""Internal worker for enabling/disabling pretty-printers."""
(object_re, name_re, subname_re) = parse_printer_regexps(arg)
total = 0
if object_re.match("global"):
total += do_enable_pretty_printer_1(
gdb.pretty_printers, name_re, subname_re, flag
)
cp = gdb.current_progspace()
if object_re.match("progspace"):
total += do_enable_pretty_printer_1(
cp.pretty_printers, name_re, subname_re, flag
)
for objfile in gdb.objfiles():
if object_re.match(objfile.filename):
total += do_enable_pretty_printer_1(
objfile.pretty_printers, name_re, subname_re, flag
)
if flag:
state = "enabled"
else:
state = "disabled"
print("%d %s %s" % (total, pluralize("printer", total), state))
# Print the total list of printers currently enabled/disabled.
# This is to further assist the user in determining whether the result
# is expected. Since we use regexps to select it's useful.
show_pretty_printer_enabled_summary()
# Enable/Disable one or more pretty-printers.
#
# This is intended for use when a broken pretty-printer is shipped/installed
# and the user wants to disable that printer without disabling all the other
# printers.
#
# A useful addition would be -v (verbose) to show each printer affected.
class EnablePrettyPrinter(gdb.Command):
"""GDB command to enable the specified pretty-printer.
Usage: enable pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
OBJECT-REGEXP is a regular expression matching the objects to examine.
Objects are "global", the program space's file, and the objfiles within
that program space.
NAME-REGEXP matches the name of the pretty-printer.
Individual printers in a collection are named as
printer-name;subprinter-name."""
def __init__(self):
super(EnablePrettyPrinter, self).__init__(
"enable pretty-printer", gdb.COMMAND_DATA
)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
do_enable_pretty_printer(arg, True)
class DisablePrettyPrinter(gdb.Command):
"""GDB command to disable the specified pretty-printer.
Usage: disable pretty-printer [OBJECT-REGEXP [NAME-REGEXP]]
OBJECT-REGEXP is a regular expression matching the objects to examine.
Objects are "global", the program space's file, and the objfiles within
that program space.
NAME-REGEXP matches the name of the pretty-printer.
Individual printers in a collection are named as
printer-name;subprinter-name."""
def __init__(self):
super(DisablePrettyPrinter, self).__init__(
"disable pretty-printer", gdb.COMMAND_DATA
)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
do_enable_pretty_printer(arg, False)
def register_pretty_printer_commands():
"""Call from a top level script to install the pretty-printer commands."""
InfoPrettyPrinter()
EnablePrettyPrinter()
DisablePrettyPrinter()
register_pretty_printer_commands()
| cuda-gdb-master | gdb/python/lib/gdb/command/pretty_printers.py |
# Type printer commands.
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import copy
import gdb
"""GDB commands for working with type-printers."""
class InfoTypePrinter(gdb.Command):
"""GDB command to list all registered type-printers.
Usage: info type-printers"""
def __init__(self):
super(InfoTypePrinter, self).__init__("info type-printers", gdb.COMMAND_DATA)
def list_type_printers(self, type_printers):
"""Print a list of type printers."""
# A potential enhancement is to provide an option to list printers in
# "lookup order" (i.e. unsorted).
sorted_type_printers = sorted(copy.copy(type_printers), key=lambda x: x.name)
for printer in sorted_type_printers:
if printer.enabled:
enabled = ""
else:
enabled = " [disabled]"
print(" %s%s" % (printer.name, enabled))
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
sep = ""
for objfile in gdb.objfiles():
if objfile.type_printers:
print("%sType printers for %s:" % (sep, objfile.filename))
self.list_type_printers(objfile.type_printers)
sep = "\n"
if gdb.current_progspace().type_printers:
print("%sType printers for program space:" % sep)
self.list_type_printers(gdb.current_progspace().type_printers)
sep = "\n"
if gdb.type_printers:
print("%sGlobal type printers:" % sep)
self.list_type_printers(gdb.type_printers)
class _EnableOrDisableCommand(gdb.Command):
def __init__(self, setting, name):
super(_EnableOrDisableCommand, self).__init__(name, gdb.COMMAND_DATA)
self.setting = setting
def set_some(self, name, printers):
result = False
for p in printers:
if name == p.name:
p.enabled = self.setting
result = True
return result
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
for name in arg.split():
ok = False
for objfile in gdb.objfiles():
if self.set_some(name, objfile.type_printers):
ok = True
if self.set_some(name, gdb.current_progspace().type_printers):
ok = True
if self.set_some(name, gdb.type_printers):
ok = True
if not ok:
print("No type printer named '%s'" % name)
def add_some(self, result, word, printers):
for p in printers:
if p.name.startswith(word):
result.append(p.name)
def complete(self, text, word):
result = []
for objfile in gdb.objfiles():
self.add_some(result, word, objfile.type_printers)
self.add_some(result, word, gdb.current_progspace().type_printers)
self.add_some(result, word, gdb.type_printers)
return result
class EnableTypePrinter(_EnableOrDisableCommand):
"""GDB command to enable the specified type printer.
Usage: enable type-printer NAME
NAME is the name of the type-printer."""
def __init__(self):
super(EnableTypePrinter, self).__init__(True, "enable type-printer")
class DisableTypePrinter(_EnableOrDisableCommand):
"""GDB command to disable the specified type-printer.
Usage: disable type-printer NAME
NAME is the name of the type-printer."""
def __init__(self):
super(DisableTypePrinter, self).__init__(False, "disable type-printer")
InfoTypePrinter()
EnableTypePrinter()
DisableTypePrinter()
| cuda-gdb-master | gdb/python/lib/gdb/command/type_printers.py |
# Xmethod commands.
# Copyright 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
import re
"""GDB commands for working with xmethods."""
def validate_xm_regexp(part_name, regexp):
try:
return re.compile(regexp)
except SyntaxError:
raise SyntaxError("Invalid %s regexp: %s", part_name, regexp)
def parse_xm_command_args(arg):
"""Parses the arguments passed to a xmethod command.
Arguments:
arg: The argument string passed to a xmethod command.
Returns:
A 3-tuple: (<locus matching regular expression>,
<matcher matching regular expression>,
<name matching regular experession>)
"""
argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc > 2:
raise SyntaxError("Too many arguments to command.")
locus_regexp = ""
matcher_name_regexp = ""
xm_name_regexp = None
if argc >= 1:
locus_regexp = argv[0]
if argc == 2:
parts = argv[1].split(";", 1)
matcher_name_regexp = parts[0]
if len(parts) > 1:
xm_name_regexp = parts[1]
if xm_name_regexp:
name_re = validate_xm_regexp("xmethod name", xm_name_regexp)
else:
name_re = None
return (
validate_xm_regexp("locus", locus_regexp),
validate_xm_regexp("matcher name", matcher_name_regexp),
name_re,
)
def get_global_method_matchers(locus_re, matcher_re):
"""Returns a dict of matching globally registered xmethods.
Arguments:
locus_re: Even though only globally registered xmethods are
looked up, they will be looked up only if 'global' matches
LOCUS_RE.
matcher_re: The regular expression matching the names of xmethods.
Returns:
A dict of matching globally registered xmethod matchers. The only
key in the dict will be 'global'.
"""
locus_str = "global"
xm_dict = {locus_str: []}
if locus_re.match("global"):
xm_dict[locus_str].extend([m for m in gdb.xmethods if matcher_re.match(m.name)])
return xm_dict
def get_method_matchers_in_loci(loci, locus_re, matcher_re):
"""Returns a dict of matching registered xmethods in the LOCI.
Arguments:
loci: The list of loci to lookup matching xmethods in.
locus_re: If a locus is an objfile, then xmethod matchers will be
looked up in it only if its filename matches the regular
expression LOCUS_RE. If a locus is the current progspace,
then xmethod matchers will be looked up in it only if the
string "progspace" matches LOCUS_RE.
matcher_re: The regular expression to match the xmethod matcher
names.
Returns:
A dict of matching xmethod matchers. The keys of the dict are the
filenames of the loci the xmethod matchers belong to.
"""
xm_dict = {}
for locus in loci:
if isinstance(locus, gdb.Progspace):
if not locus_re.match("progspace"):
continue
locus_type = "progspace"
else:
if not locus_re.match(locus.filename):
continue
locus_type = "objfile"
locus_str = "%s %s" % (locus_type, locus.filename)
xm_dict[locus_str] = [m for m in locus.xmethods if matcher_re.match(m.name)]
return xm_dict
def print_xm_info(xm_dict, name_re):
"""Print a dictionary of xmethods."""
def get_status_string(m):
if not m.enabled:
return " [disabled]"
else:
return ""
if not xm_dict:
return
for locus_str in xm_dict:
if not xm_dict[locus_str]:
continue
print("Xmethods in %s:" % locus_str)
for matcher in xm_dict[locus_str]:
print(" %s%s" % (matcher.name, get_status_string(matcher)))
if not matcher.methods:
continue
for m in matcher.methods:
if name_re is None or name_re.match(m.name):
print(" %s%s" % (m.name, get_status_string(m)))
def set_xm_status1(xm_dict, name_re, status):
"""Set the status (enabled/disabled) of a dictionary of xmethods."""
for locus_str, matchers in xm_dict.items():
for matcher in matchers:
if not name_re:
# If the name regex is missing, then set the status of the
# matcher and move on.
matcher.enabled = status
continue
if not matcher.methods:
# The methods attribute could be None. Move on.
continue
for m in matcher.methods:
if name_re.match(m.name):
m.enabled = status
def set_xm_status(arg, status):
"""Set the status (enabled/disabled) of xmethods matching ARG.
This is a helper function for enable/disable commands. ARG is the
argument string passed to the commands.
"""
locus_re, matcher_re, name_re = parse_xm_command_args(arg)
set_xm_status1(get_global_method_matchers(locus_re, matcher_re), name_re, status)
set_xm_status1(
get_method_matchers_in_loci([gdb.current_progspace()], locus_re, matcher_re),
name_re,
status,
)
set_xm_status1(
get_method_matchers_in_loci(gdb.objfiles(), locus_re, matcher_re),
name_re,
status,
)
class InfoXMethod(gdb.Command):
"""GDB command to list registered xmethod matchers.
Usage: info xmethod [LOCUS-REGEXP [NAME-REGEXP]]
LOCUS-REGEXP is a regular expression matching the location of the
xmethod matchers. If it is omitted, all registered xmethod matchers
from all loci are listed. A locus could be 'global', a regular expression
matching the current program space's filename, or a regular expression
matching filenames of objfiles. Locus could be 'progspace' to specify that
only xmethods from the current progspace should be listed.
NAME-REGEXP is a regular expression matching the names of xmethod
matchers. If this omitted for a specified locus, then all registered
xmethods in the locus are listed. To list only a certain xmethods
managed by a single matcher, the name regexp can be specified as
matcher-name-regexp;xmethod-name-regexp."""
def __init__(self):
super(InfoXMethod, self).__init__("info xmethod", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
locus_re, matcher_re, name_re = parse_xm_command_args(arg)
print_xm_info(get_global_method_matchers(locus_re, matcher_re), name_re)
print_xm_info(
get_method_matchers_in_loci(
[gdb.current_progspace()], locus_re, matcher_re
),
name_re,
)
print_xm_info(
get_method_matchers_in_loci(gdb.objfiles(), locus_re, matcher_re), name_re
)
class EnableXMethod(gdb.Command):
"""GDB command to enable a specified (group of) xmethod(s).
Usage: enable xmethod [LOCUS-REGEXP [NAME-REGEXP]]
LOCUS-REGEXP is a regular expression matching the location of the
xmethod matchers. If it is omitted, all registered xmethods matchers
from all loci are enabled. A locus could be 'global', a regular expression
matching the current program space's filename, or a regular expression
matching filenames of objfiles. Locus could be 'progspace' to specify that
only xmethods from the current progspace should be enabled.
NAME-REGEXP is a regular expression matching the names of xmethods
within a given locus. If this omitted for a specified locus, then all
registered xmethod matchers in the locus are enabled. To enable only
a certain xmethods managed by a single matcher, the name regexp can be
specified as matcher-name-regexp;xmethod-name-regexp."""
def __init__(self):
super(EnableXMethod, self).__init__("enable xmethod", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
set_xm_status(arg, True)
class DisableXMethod(gdb.Command):
"""GDB command to disable a specified (group of) xmethod(s).
Usage: disable xmethod [LOCUS-REGEXP [NAME-REGEXP]]
LOCUS-REGEXP is a regular expression matching the location of the
xmethod matchers. If it is omitted, all registered xmethod matchers
from all loci are disabled. A locus could be 'global', a regular
expression matching the current program space's filename, or a regular
expression filenames of objfiles. Locus could be 'progspace' to specify
that only xmethods from the current progspace should be disabled.
NAME-REGEXP is a regular expression matching the names of xmethods
within a given locus. If this omitted for a specified locus, then all
registered xmethod matchers in the locus are disabled. To disable
only a certain xmethods managed by a single matcher, the name regexp
can be specified as matcher-name-regexp;xmethod-name-regexp."""
def __init__(self):
super(DisableXMethod, self).__init__("disable xmethod", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
set_xm_status(arg, False)
def register_xmethod_commands():
"""Installs the xmethod commands."""
InfoXMethod()
EnableXMethod()
DisableXMethod()
register_xmethod_commands()
| cuda-gdb-master | gdb/python/lib/gdb/command/xmethods.py |
# GDB 'explore' command.
# Copyright (C) 2012-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Implementation of the GDB 'explore' command using the GDB Python API."""
import gdb
import sys
class Explorer(object):
"""Internal class which invokes other explorers."""
# This map is filled by the Explorer.init_env() function
type_code_to_explorer_map = {}
_SCALAR_TYPE_LIST = (
gdb.TYPE_CODE_CHAR,
gdb.TYPE_CODE_INT,
gdb.TYPE_CODE_BOOL,
gdb.TYPE_CODE_FLT,
gdb.TYPE_CODE_VOID,
gdb.TYPE_CODE_ENUM,
)
@staticmethod
def guard_expr(expr):
length = len(expr)
guard = False
if expr[0] == "(" and expr[length - 1] == ")":
pass
else:
i = 0
while i < length:
c = expr[i]
if (
c == "_"
or ("a" <= c and c <= "z")
or ("A" <= c and c <= "Z")
or ("0" <= c and c <= "9")
):
pass
else:
guard = True
break
i += 1
if guard:
return "(" + expr + ")"
else:
return expr
@staticmethod
def explore_expr(expr, value, is_child):
"""Main function to explore an expression value.
Arguments:
expr: The expression string that is being explored.
value: The gdb.Value value of the expression.
is_child: Boolean value to indicate if the expression is a child.
An expression is a child if it is derived from the main
expression entered by the user. For example, if the user
entered an expression which evaluates to a struct, then
when exploring the fields of the struct, is_child is set
to True internally.
Returns:
No return value.
"""
type_code = value.type.code
if type_code in Explorer.type_code_to_explorer_map:
explorer_class = Explorer.type_code_to_explorer_map[type_code]
while explorer_class.explore_expr(expr, value, is_child):
pass
else:
print("Explorer for type '%s' not yet available.\n" % str(value.type))
@staticmethod
def explore_type(name, datatype, is_child):
"""Main function to explore a data type.
Arguments:
name: The string representing the path to the data type being
explored.
datatype: The gdb.Type value of the data type being explored.
is_child: Boolean value to indicate if the name is a child.
A name is a child if it is derived from the main name
entered by the user. For example, if the user entered
the name of struct type, then when exploring the fields
of the struct, is_child is set to True internally.
Returns:
No return value.
"""
type_code = datatype.code
if type_code in Explorer.type_code_to_explorer_map:
explorer_class = Explorer.type_code_to_explorer_map[type_code]
while explorer_class.explore_type(name, datatype, is_child):
pass
else:
print("Explorer for type '%s' not yet available.\n" % str(datatype))
@staticmethod
def init_env():
"""Initializes the Explorer environment.
This function should be invoked before starting any exploration. If
invoked before an exploration, it need not be invoked for subsequent
explorations.
"""
Explorer.type_code_to_explorer_map = {
gdb.TYPE_CODE_CHAR: ScalarExplorer,
gdb.TYPE_CODE_INT: ScalarExplorer,
gdb.TYPE_CODE_BOOL: ScalarExplorer,
gdb.TYPE_CODE_FLT: ScalarExplorer,
gdb.TYPE_CODE_VOID: ScalarExplorer,
gdb.TYPE_CODE_ENUM: ScalarExplorer,
gdb.TYPE_CODE_STRUCT: CompoundExplorer,
gdb.TYPE_CODE_UNION: CompoundExplorer,
gdb.TYPE_CODE_PTR: PointerExplorer,
gdb.TYPE_CODE_REF: ReferenceExplorer,
gdb.TYPE_CODE_RVALUE_REF: ReferenceExplorer,
gdb.TYPE_CODE_TYPEDEF: TypedefExplorer,
gdb.TYPE_CODE_ARRAY: ArrayExplorer,
}
@staticmethod
def is_scalar_type(type):
"""Checks whether a type is a scalar type.
A type is a scalar type of its type is
gdb.TYPE_CODE_CHAR or
gdb.TYPE_CODE_INT or
gdb.TYPE_CODE_BOOL or
gdb.TYPE_CODE_FLT or
gdb.TYPE_CODE_VOID or
gdb.TYPE_CODE_ENUM.
Arguments:
type: The type to be checked.
Returns:
'True' if 'type' is a scalar type. 'False' otherwise.
"""
return type.code in Explorer._SCALAR_TYPE_LIST
@staticmethod
def return_to_parent_value():
"""A utility function which prints that the current exploration session
is returning to the parent value. Useful when exploring values.
"""
print("\nReturning to parent value...\n")
@staticmethod
def return_to_parent_value_prompt():
"""A utility function which prompts the user to press the 'enter' key
so that the exploration session can shift back to the parent value.
Useful when exploring values.
"""
input("\nPress enter to return to parent value: ")
@staticmethod
def return_to_enclosing_type():
"""A utility function which prints that the current exploration session
is returning to the enclosing type. Useful when exploring types.
"""
print("\nReturning to enclosing type...\n")
@staticmethod
def return_to_enclosing_type_prompt():
"""A utility function which prompts the user to press the 'enter' key
so that the exploration session can shift back to the enclosing type.
Useful when exploring types.
"""
input("\nPress enter to return to enclosing type: ")
class ScalarExplorer(object):
"""Internal class used to explore scalar values."""
@staticmethod
def explore_expr(expr, value, is_child):
"""Function to explore scalar values.
See Explorer.explore_expr and Explorer.is_scalar_type for more
information.
"""
print("'%s' is a scalar value of type '%s'." % (expr, value.type))
print("%s = %s" % (expr, str(value)))
if is_child:
Explorer.return_to_parent_value_prompt()
Explorer.return_to_parent_value()
return False
@staticmethod
def explore_type(name, datatype, is_child):
"""Function to explore scalar types.
See Explorer.explore_type and Explorer.is_scalar_type for more
information.
"""
if datatype.code == gdb.TYPE_CODE_ENUM:
if is_child:
print("%s is of an enumerated type '%s'." % (name, str(datatype)))
else:
print("'%s' is an enumerated type." % name)
else:
if is_child:
print("%s is of a scalar type '%s'." % (name, str(datatype)))
else:
print("'%s' is a scalar type." % name)
if is_child:
Explorer.return_to_enclosing_type_prompt()
Explorer.return_to_enclosing_type()
return False
class PointerExplorer(object):
"""Internal class used to explore pointer values."""
@staticmethod
def explore_expr(expr, value, is_child):
"""Function to explore pointer values.
See Explorer.explore_expr for more information.
"""
print(
"'%s' is a pointer to a value of type '%s'"
% (expr, str(value.type.target()))
)
option = input(
"Continue exploring it as a pointer to a single " "value [y/n]: "
)
if option == "y":
deref_value = None
try:
deref_value = value.dereference()
str(deref_value)
except gdb.MemoryError:
print(
"'%s' a pointer pointing to an invalid memory " "location." % expr
)
if is_child:
Explorer.return_to_parent_value_prompt()
return False
Explorer.explore_expr(
"*%s" % Explorer.guard_expr(expr), deref_value, is_child
)
return False
option = input("Continue exploring it as a pointer to an " "array [y/n]: ")
if option == "y":
while True:
index = 0
try:
index = int(
input(
"Enter the index of the element you "
"want to explore in '%s': " % expr
)
)
except ValueError:
break
element_expr = "%s[%d]" % (Explorer.guard_expr(expr), index)
element = value[index]
try:
str(element)
except gdb.MemoryError:
print("Cannot read value at index %d." % index)
continue
Explorer.explore_expr(element_expr, element, True)
return False
if is_child:
Explorer.return_to_parent_value()
return False
@staticmethod
def explore_type(name, datatype, is_child):
"""Function to explore pointer types.
See Explorer.explore_type for more information.
"""
target_type = datatype.target()
print("\n%s is a pointer to a value of type '%s'." % (name, str(target_type)))
Explorer.explore_type("the pointee type of %s" % name, target_type, is_child)
return False
class ReferenceExplorer(object):
"""Internal class used to explore reference (TYPE_CODE_REF) values."""
@staticmethod
def explore_expr(expr, value, is_child):
"""Function to explore array values.
See Explorer.explore_expr for more information.
"""
referenced_value = value.referenced_value()
Explorer.explore_expr(expr, referenced_value, is_child)
return False
@staticmethod
def explore_type(name, datatype, is_child):
"""Function to explore pointer types.
See Explorer.explore_type for more information.
"""
target_type = datatype.target()
Explorer.explore_type(name, target_type, is_child)
return False
class ArrayExplorer(object):
"""Internal class used to explore arrays."""
@staticmethod
def explore_expr(expr, value, is_child):
"""Function to explore array values.
See Explorer.explore_expr for more information.
"""
target_type = value.type.target()
print("'%s' is an array of '%s'." % (expr, str(target_type)))
index = 0
try:
index = int(
input(
"Enter the index of the element you want to "
"explore in '%s': " % expr
)
)
except ValueError:
if is_child:
Explorer.return_to_parent_value()
return False
element = None
try:
element = value[index]
str(element)
except gdb.MemoryError:
print("Cannot read value at index %d." % index)
input("Press enter to continue... ")
return True
Explorer.explore_expr(
"%s[%d]" % (Explorer.guard_expr(expr), index), element, True
)
return True
@staticmethod
def explore_type(name, datatype, is_child):
"""Function to explore array types.
See Explorer.explore_type for more information.
"""
target_type = datatype.target()
print("%s is an array of '%s'." % (name, str(target_type)))
Explorer.explore_type("the array element of %s" % name, target_type, is_child)
return False
class CompoundExplorer(object):
"""Internal class used to explore struct, classes and unions."""
@staticmethod
def _print_fields(print_list):
"""Internal function which prints the fields of a struct/class/union."""
max_field_name_length = 0
for pair in print_list:
if max_field_name_length < len(pair[0]):
max_field_name_length = len(pair[0])
for pair in print_list:
print(" %*s = %s" % (max_field_name_length, pair[0], pair[1]))
@staticmethod
def _get_real_field_count(fields):
real_field_count = 0
for field in fields:
if not field.artificial:
real_field_count = real_field_count + 1
return real_field_count
@staticmethod
def explore_expr(expr, value, is_child):
"""Function to explore structs/classes and union values.
See Explorer.explore_expr for more information.
"""
datatype = value.type
type_code = datatype.code
fields = datatype.fields()
if type_code == gdb.TYPE_CODE_STRUCT:
type_desc = "struct/class"
else:
type_desc = "union"
if CompoundExplorer._get_real_field_count(fields) == 0:
print(
"The value of '%s' is a %s of type '%s' with no fields."
% (expr, type_desc, str(value.type))
)
if is_child:
Explorer.return_to_parent_value_prompt()
return False
print(
"The value of '%s' is a %s of type '%s' with the following "
"fields:\n" % (expr, type_desc, str(value.type))
)
has_explorable_fields = False
choice_to_compound_field_map = {}
current_choice = 0
print_list = []
for field in fields:
if field.artificial:
continue
field_full_name = Explorer.guard_expr(expr) + "." + field.name
if field.is_base_class:
field_value = value.cast(field.type)
else:
field_value = value[field.name]
literal_value = ""
if type_code == gdb.TYPE_CODE_UNION:
literal_value = "<Enter %d to explore this field of type " "'%s'>" % (
current_choice,
str(field.type),
)
has_explorable_fields = True
else:
if Explorer.is_scalar_type(field.type):
literal_value = "%s .. (Value of type '%s')" % (
str(field_value),
str(field.type),
)
else:
if field.is_base_class:
field_desc = "base class"
else:
field_desc = "field"
literal_value = "<Enter %d to explore this %s of type " "'%s'>" % (
current_choice,
field_desc,
str(field.type),
)
has_explorable_fields = True
choice_to_compound_field_map[str(current_choice)] = (
field_full_name,
field_value,
)
current_choice = current_choice + 1
print_list.append((field.name, literal_value))
CompoundExplorer._print_fields(print_list)
print("")
if has_explorable_fields:
choice = input("Enter the field number of choice: ")
if choice in choice_to_compound_field_map:
Explorer.explore_expr(
choice_to_compound_field_map[choice][0],
choice_to_compound_field_map[choice][1],
True,
)
return True
else:
if is_child:
Explorer.return_to_parent_value()
else:
if is_child:
Explorer.return_to_parent_value_prompt()
return False
@staticmethod
def explore_type(name, datatype, is_child):
"""Function to explore struct/class and union types.
See Explorer.explore_type for more information.
"""
type_code = datatype.code
type_desc = ""
if type_code == gdb.TYPE_CODE_STRUCT:
type_desc = "struct/class"
else:
type_desc = "union"
fields = datatype.fields()
if CompoundExplorer._get_real_field_count(fields) == 0:
if is_child:
print(
"%s is a %s of type '%s' with no fields."
% (name, type_desc, str(datatype))
)
Explorer.return_to_enclosing_type_prompt()
else:
print("'%s' is a %s with no fields." % (name, type_desc))
return False
if is_child:
print(
"%s is a %s of type '%s' "
"with the following fields:\n" % (name, type_desc, str(datatype))
)
else:
print("'%s' is a %s with the following " "fields:\n" % (name, type_desc))
current_choice = 0
choice_to_compound_field_map = {}
print_list = []
for field in fields:
if field.artificial:
continue
if field.is_base_class:
field_desc = "base class"
else:
field_desc = "field"
rhs = "<Enter %d to explore this %s of type '%s'>" % (
current_choice,
field_desc,
str(field.type),
)
print_list.append((field.name, rhs))
choice_to_compound_field_map[str(current_choice)] = (
field.name,
field.type,
field_desc,
)
current_choice = current_choice + 1
CompoundExplorer._print_fields(print_list)
print("")
if len(choice_to_compound_field_map) > 0:
choice = input("Enter the field number of choice: ")
if choice in choice_to_compound_field_map:
if is_child:
new_name = "%s '%s' of %s" % (
choice_to_compound_field_map[choice][2],
choice_to_compound_field_map[choice][0],
name,
)
else:
new_name = "%s '%s' of '%s'" % (
choice_to_compound_field_map[choice][2],
choice_to_compound_field_map[choice][0],
name,
)
Explorer.explore_type(
new_name, choice_to_compound_field_map[choice][1], True
)
return True
else:
if is_child:
Explorer.return_to_enclosing_type()
else:
if is_child:
Explorer.return_to_enclosing_type_prompt()
return False
class TypedefExplorer(object):
"""Internal class used to explore values whose type is a typedef."""
@staticmethod
def explore_expr(expr, value, is_child):
"""Function to explore typedef values.
See Explorer.explore_expr for more information.
"""
actual_type = value.type.strip_typedefs()
print(
"The value of '%s' is of type '%s' "
"which is a typedef of type '%s'"
% (expr, str(value.type), str(actual_type))
)
Explorer.explore_expr(expr, value.cast(actual_type), is_child)
return False
@staticmethod
def explore_type(name, datatype, is_child):
"""Function to explore typedef types.
See Explorer.explore_type for more information.
"""
actual_type = datatype.strip_typedefs()
if is_child:
print(
"The type of %s is a typedef of type '%s'." % (name, str(actual_type))
)
else:
print("The type '%s' is a typedef of type '%s'." % (name, str(actual_type)))
Explorer.explore_type(name, actual_type, is_child)
return False
class ExploreUtils(object):
"""Internal class which provides utilities for the main command classes."""
@staticmethod
def check_args(name, arg_str):
"""Utility to check if adequate number of arguments are passed to an
explore command.
Arguments:
name: The name of the explore command.
arg_str: The argument string passed to the explore command.
Returns:
True if adequate arguments are passed, false otherwise.
Raises:
gdb.GdbError if adequate arguments are not passed.
"""
if len(arg_str) < 1:
raise gdb.GdbError("ERROR: '%s' requires an argument." % name)
return False
else:
return True
@staticmethod
def get_type_from_str(type_str):
"""A utility function to deduce the gdb.Type value from a string
representing the type.
Arguments:
type_str: The type string from which the gdb.Type value should be
deduced.
Returns:
The deduced gdb.Type value if possible, None otherwise.
"""
try:
# Assume the current language to be C/C++ and make a try.
return gdb.parse_and_eval("(%s *)0" % type_str).type.target()
except RuntimeError:
# If assumption of current language to be C/C++ was wrong, then
# lookup the type using the API.
try:
return gdb.lookup_type(type_str)
except RuntimeError:
return None
@staticmethod
def get_value_from_str(value_str):
"""A utility function to deduce the gdb.Value value from a string
representing the value.
Arguments:
value_str: The value string from which the gdb.Value value should
be deduced.
Returns:
The deduced gdb.Value value if possible, None otherwise.
"""
try:
return gdb.parse_and_eval(value_str)
except RuntimeError:
return None
class ExploreCommand(gdb.Command):
"""Explore a value or a type valid in the current context.
Usage: explore ARG
- ARG is either a valid expression or a type name.
- At any stage of exploration, hit the return key (instead of a
choice, if any) to return to the enclosing type or value."""
def __init__(self):
super(ExploreCommand, self).__init__(
name="explore", command_class=gdb.COMMAND_DATA, prefix=True
)
def invoke(self, arg_str, from_tty):
if ExploreUtils.check_args("explore", arg_str) is False:
return
# Check if it is a value
value = ExploreUtils.get_value_from_str(arg_str)
if value is not None:
Explorer.explore_expr(arg_str, value, False)
return
# If it is not a value, check if it is a type
datatype = ExploreUtils.get_type_from_str(arg_str)
if datatype is not None:
Explorer.explore_type(arg_str, datatype, False)
return
# If it is neither a value nor a type, raise an error.
raise gdb.GdbError(
(
"'%s' neither evaluates to a value nor is a type "
"in the current context." % arg_str
)
)
class ExploreValueCommand(gdb.Command):
"""Explore value of an expression valid in the current context.
Usage: explore value ARG
- ARG is a valid expression.
- At any stage of exploration, hit the return key (instead of a
choice, if any) to return to the enclosing value."""
def __init__(self):
super(ExploreValueCommand, self).__init__(
name="explore value", command_class=gdb.COMMAND_DATA
)
def invoke(self, arg_str, from_tty):
if ExploreUtils.check_args("explore value", arg_str) is False:
return
value = ExploreUtils.get_value_from_str(arg_str)
if value is None:
raise gdb.GdbError(
(
" '%s' does not evaluate to a value in the current "
"context." % arg_str
)
)
return
Explorer.explore_expr(arg_str, value, False)
class ExploreTypeCommand(gdb.Command):
"""Explore a type or the type of an expression.
Usage: explore type ARG
- ARG is a valid expression or a type name.
- At any stage of exploration, hit the return key (instead of a
choice, if any) to return to the enclosing type."""
def __init__(self):
super(ExploreTypeCommand, self).__init__(
name="explore type", command_class=gdb.COMMAND_DATA
)
def invoke(self, arg_str, from_tty):
if ExploreUtils.check_args("explore type", arg_str) is False:
return
datatype = ExploreUtils.get_type_from_str(arg_str)
if datatype is not None:
Explorer.explore_type(arg_str, datatype, False)
return
value = ExploreUtils.get_value_from_str(arg_str)
if value is not None:
print("'%s' is of type '%s'." % (arg_str, str(value.type)))
Explorer.explore_type(str(value.type), value.type, False)
return
raise gdb.GdbError(
("'%s' is not a type or value in the current " "context." % arg_str)
)
Explorer.init_env()
ExploreCommand()
ExploreValueCommand()
ExploreTypeCommand()
| cuda-gdb-master | gdb/python/lib/gdb/command/explore.py |
# Extended prompt.
# Copyright (C) 2011-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""GDB command for working with extended prompts."""
import gdb
import gdb.prompt
class _ExtendedPrompt(gdb.Parameter):
"""Set the extended prompt.
Usage: set extended-prompt VALUE
Substitutions are applied to VALUE to compute the real prompt.
The currently defined substitutions are:"""
# Add the prompt library's dynamically generated help to the
# __doc__ string.
__doc__ = __doc__ + "\n" + gdb.prompt.prompt_help()
set_doc = "Set the extended prompt."
show_doc = "Show the extended prompt."
def __init__(self):
super(_ExtendedPrompt, self).__init__(
"extended-prompt", gdb.COMMAND_SUPPORT, gdb.PARAM_STRING_NOESCAPE
)
self.value = ""
self.hook_set = False
def get_show_string(self, pvalue):
if self.value:
return "The extended prompt is: " + self.value
else:
return "The extended prompt is not set."
def get_set_string(self):
if self.hook_set is False:
gdb.prompt_hook = self.before_prompt_hook
self.hook_set = True
return ""
def before_prompt_hook(self, current):
if self.value:
return gdb.prompt.substitute_prompt(self.value)
else:
return None
_ExtendedPrompt()
| cuda-gdb-master | gdb/python/lib/gdb/command/prompt.py |
# Unwinder commands.
# Copyright 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
import re
def validate_regexp(exp, idstring):
try:
return re.compile(exp)
except SyntaxError:
raise SyntaxError("Invalid %s regexp: %s." % (idstring, exp))
def parse_unwinder_command_args(arg):
"""Internal utility to parse unwinder command argv.
Arguments:
arg: The arguments to the command. The format is:
[locus-regexp [name-regexp]]
Returns:
A 2-tuple of compiled regular expressions.
Raises:
SyntaxError: an error processing ARG
"""
argv = gdb.string_to_argv(arg)
argc = len(argv)
if argc > 2:
raise SyntaxError("Too many arguments.")
locus_regexp = ""
name_regexp = ""
if argc >= 1:
locus_regexp = argv[0]
if argc >= 2:
name_regexp = argv[1]
return (
validate_regexp(locus_regexp, "locus"),
validate_regexp(name_regexp, "unwinder"),
)
class InfoUnwinder(gdb.Command):
"""GDB command to list unwinders.
Usage: info unwinder [LOCUS-REGEXP [NAME-REGEXP]]
LOCUS-REGEXP is a regular expression matching the location of the
unwinder. If it is omitted, all registered unwinders from all
loci are listed. A locus can be 'global', 'progspace' to list
the unwinders from the current progspace, or a regular expression
matching filenames of objfiles.
NAME-REGEXP is a regular expression to filter unwinder names. If
this omitted for a specified locus, then all registered unwinders
in the locus are listed."""
def __init__(self):
super(InfoUnwinder, self).__init__("info unwinder", gdb.COMMAND_STACK)
def list_unwinders(self, title, unwinders, name_re):
"""Lists the unwinders whose name matches regexp.
Arguments:
title: The line to print before the list.
unwinders: The list of the unwinders.
name_re: unwinder name filter.
"""
if not unwinders:
return
print(title)
for unwinder in unwinders:
if name_re.match(unwinder.name):
print(
" %s%s"
% (unwinder.name, "" if unwinder.enabled else " [disabled]")
)
def invoke(self, arg, from_tty):
locus_re, name_re = parse_unwinder_command_args(arg)
if locus_re.match("global"):
self.list_unwinders("Global:", gdb.frame_unwinders, name_re)
if locus_re.match("progspace"):
cp = gdb.current_progspace()
self.list_unwinders(
"Progspace %s:" % cp.filename, cp.frame_unwinders, name_re
)
for objfile in gdb.objfiles():
if locus_re.match(objfile.filename):
self.list_unwinders(
"Objfile %s:" % objfile.filename, objfile.frame_unwinders, name_re
)
def do_enable_unwinder1(unwinders, name_re, flag):
"""Enable/disable unwinders whose names match given regex.
Arguments:
unwinders: The list of unwinders.
name_re: Unwinder name filter.
flag: Enable/disable.
Returns:
The number of unwinders affected.
"""
total = 0
for unwinder in unwinders:
if name_re.match(unwinder.name):
unwinder.enabled = flag
total += 1
return total
def do_enable_unwinder(arg, flag):
"""Enable/disable unwinder(s)."""
(locus_re, name_re) = parse_unwinder_command_args(arg)
total = 0
if locus_re.match("global"):
total += do_enable_unwinder1(gdb.frame_unwinders, name_re, flag)
if locus_re.match("progspace"):
total += do_enable_unwinder1(
gdb.current_progspace().frame_unwinders, name_re, flag
)
for objfile in gdb.objfiles():
if locus_re.match(objfile.filename):
total += do_enable_unwinder1(objfile.frame_unwinders, name_re, flag)
if total > 0:
gdb.invalidate_cached_frames()
print(
"%d unwinder%s %s"
% (total, "" if total == 1 else "s", "enabled" if flag else "disabled")
)
class EnableUnwinder(gdb.Command):
"""GDB command to enable unwinders.
Usage: enable unwinder [LOCUS-REGEXP [NAME-REGEXP]]
LOCUS-REGEXP is a regular expression specifying the unwinders to
enable. It can 'global', 'progspace', or the name of an objfile
within that progspace.
NAME_REGEXP is a regular expression to filter unwinder names. If
this omitted for a specified locus, then all registered unwinders
in the locus are affected."""
def __init__(self):
super(EnableUnwinder, self).__init__("enable unwinder", gdb.COMMAND_STACK)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
do_enable_unwinder(arg, True)
class DisableUnwinder(gdb.Command):
"""GDB command to disable the specified unwinder.
Usage: disable unwinder [LOCUS-REGEXP [NAME-REGEXP]]
LOCUS-REGEXP is a regular expression specifying the unwinders to
disable. It can 'global', 'progspace', or the name of an objfile
within that progspace.
NAME_REGEXP is a regular expression to filter unwinder names. If
this omitted for a specified locus, then all registered unwinders
in the locus are affected."""
def __init__(self):
super(DisableUnwinder, self).__init__("disable unwinder", gdb.COMMAND_STACK)
def invoke(self, arg, from_tty):
"""GDB calls this to perform the command."""
do_enable_unwinder(arg, False)
def register_unwinder_commands():
"""Installs the unwinder commands."""
InfoUnwinder()
EnableUnwinder()
DisableUnwinder()
register_unwinder_commands()
| cuda-gdb-master | gdb/python/lib/gdb/command/unwinders.py |
#!/usr/bin/env python3
# Copyright (C) 2016-2022 Free Software Foundation, Inc.
#
# This file is part of GDB.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This program is used to analyze the test results (i.e., *.sum files)
# generated by GDB's testsuite, and print the testcases that are found
# to be racy.
#
# Racy testcases are considered as being testcases which can
# intermittently FAIL (or PASS) when run two or more times
# consecutively, i.e., tests whose results are not deterministic.
#
# This program is invoked when the user runs "make check" and
# specifies the RACY_ITER environment variable.
import sys
import os
import re
# The (global) dictionary that stores the associations between a *.sum
# file and its results. The data inside it will be stored as:
#
# files_and_tests = { 'file1.sum' : { 'PASS' : { 'test1', 'test2' ... },
# 'FAIL' : { 'test5', 'test6' ... },
# ...
# },
# { 'file2.sum' : { 'PASS' : { 'test1', 'test3' ... },
# ...
# }
# }
files_and_tests = dict()
# The relatioships between various states of the same tests that
# should be ignored. For example, if the same test PASSes on a
# testcase run but KFAILs on another, this test should be considered
# racy because a known-failure is... known.
ignore_relations = {"PASS": "KFAIL"}
# We are interested in lines that start with '.?(PASS|FAIL)'. In
# other words, we don't process errors (maybe we should).
sum_matcher = re.compile("^(.?(PASS|FAIL)): (.*)$")
def parse_sum_line(line, dic):
"""Parse a single LINE from a sumfile, and store the results in the
dictionary referenced by DIC."""
global sum_matcher
line = line.rstrip()
m = re.match(sum_matcher, line)
if m:
result = m.group(1)
test_name = m.group(3)
# Remove tail parentheses. These are likely to be '(timeout)'
# and other extra information that will only confuse us.
test_name = re.sub("(\s+)?\(.*$", "", test_name)
if result not in dic.keys():
dic[result] = set()
if test_name in dic[result]:
# If the line is already present in the dictionary, then
# we include a unique identifier in the end of it, in the
# form or '<<N>>' (where N is a number >= 2). This is
# useful because the GDB testsuite is full of non-unique
# test messages; however, if you process the racy summary
# file you will also need to perform this same operation
# in order to identify the racy test.
i = 2
while True:
nname = test_name + " <<" + str(i) + ">>"
if nname not in dic[result]:
break
i += 1
test_name = nname
dic[result].add(test_name)
def read_sum_files(files):
"""Read the sumfiles (passed as a list in the FILES variable), and
process each one, filling the FILES_AND_TESTS global dictionary with
information about them."""
global files_and_tests
for x in files:
with open(x, "r") as f:
files_and_tests[x] = dict()
for line in f.readlines():
parse_sum_line(line, files_and_tests[x])
def identify_racy_tests():
"""Identify and print the racy tests. This function basically works
on sets, and the idea behind it is simple. It takes all the sets that
refer to the same result (for example, all the sets that contain PASS
tests), and compare them. If a test is present in all PASS sets, then
it is not racy. Otherwise, it is.
This function does that for all sets (PASS, FAIL, KPASS, KFAIL, etc.),
and then print a sorted list (without duplicates) of all the tests
that were found to be racy."""
global files_and_tests
# First, construct two dictionaries that will hold one set of
# testcases for each state (PASS, FAIL, etc.).
#
# Each set in NONRACY_TESTS will contain only the non-racy
# testcases for that state. A non-racy testcase is a testcase
# that has the same state in all test runs.
#
# Each set in ALL_TESTS will contain all tests, racy or not, for
# that state.
nonracy_tests = dict()
all_tests = dict()
for f in files_and_tests:
for state in files_and_tests[f]:
try:
nonracy_tests[state] &= files_and_tests[f][state].copy()
except KeyError:
nonracy_tests[state] = files_and_tests[f][state].copy()
try:
all_tests[state] |= files_and_tests[f][state].copy()
except KeyError:
all_tests[state] = files_and_tests[f][state].copy()
# Now, we eliminate the tests that are present in states that need
# to be ignored. For example, tests both in the PASS and KFAIL
# states should not be considered racy.
ignored_tests = set()
for s1, s2 in ignore_relations.items():
try:
ignored_tests |= all_tests[s1] & all_tests[s2]
except:
continue
racy_tests = set()
for f in files_and_tests:
for state in files_and_tests[f]:
racy_tests |= files_and_tests[f][state] - nonracy_tests[state]
racy_tests = racy_tests - ignored_tests
# Print the header.
print("\t\t=== gdb racy tests ===\n")
# Print each test.
for line in sorted(racy_tests):
print(line)
# Print the summary.
print("\n")
print("\t\t=== gdb Summary ===\n")
print("# of racy tests:\t\t%d" % len(racy_tests))
if __name__ == "__main__":
if len(sys.argv) < 3:
# It only makes sense to invoke this program if you pass two
# or more files to be analyzed.
sys.exit("Usage: %s [FILE] [FILE] ..." % sys.argv[0])
read_sum_files(sys.argv[1:])
identify_racy_tests()
exit(0)
| cuda-gdb-master | gdb/testsuite/analyze-racy-logs.py |
#!/usr/bin/env python
# Copyright (C) 2018-2022 Free Software Foundation, Inc.
#
# This file is part of GDB.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This is a simple program that can be used to print timestamps on
# standard output. The inspiration for it was ts(1)
# (<https://joeyh.name/code/moreutils/>). We have our own version
# because unfortunately ts(1) is or may not be available on all
# systems that GDB supports.
#
# The usage is simple:
#
# #> some_command | print-ts.py [FORMAT]
#
# FORMAT must be a string compatible with "strftime". If nothing is
# provided, we choose a reasonable format.
import fileinput
import datetime
import sys
import os
if len(sys.argv) > 1:
fmt = sys.argv[1]
else:
fmt = "[%b %d %H:%M:%S]"
mypid = os.getpid()
for line in fileinput.input("-"):
sys.stdout.write(
"{} [{}] {}".format(datetime.datetime.now().strftime(fmt), mypid, line)
)
sys.stdout.flush()
| cuda-gdb-master | gdb/testsuite/print-ts.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
# Take a gdb.TargetConnection and return the connection number.
def conn_num(c):
return c.num
# Takes a gdb.TargetConnection and return a string that is either the
# type, or the type and details (if the details are not None).
def make_target_connection_string(c):
if c.details is None:
return c.type
else:
return "%s %s" % (c.type, c.details)
# A Python implementation of 'info connections'. Produce output that
# is identical to the output of 'info connections' so we can check
# that aspects of gdb.TargetConnection work correctly.
def info_connections():
all_connections = sorted(gdb.connections(), key=conn_num)
current_conn = gdb.selected_inferior().connection
what_width = 0
for c in all_connections:
s = make_target_connection_string(c)
if len(s) > what_width:
what_width = len(s)
fmt = " Num %%-%ds Description" % what_width
print(fmt % "What")
fmt = "%%s%%-3d %%-%ds %%s" % what_width
for c in all_connections:
if c == current_conn:
prefix = "* "
else:
prefix = " "
print(fmt % (prefix, c.num, make_target_connection_string(c), c.description))
def inf_num(i):
return i.num
# Print information about each inferior, and the connection it is
# using.
def info_inferiors():
all_inferiors = sorted(gdb.inferiors(), key=inf_num)
for i in gdb.inferiors():
print(
"Inferior %d, Connection #%d: %s"
% (i.num, i.connection_num, make_target_connection_string(i.connection))
)
| cuda-gdb-master | gdb/testsuite/gdb.multi/multi-target-info-inferiors.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python pretty
# printers.
import re
import gdb
# Printer for Inner.
class inner_print(object):
def __init__(self, val):
self.val = val
def to_string(self):
return "x(" + str(self.val["x"]) + ")"
def lookup_function(val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# Get the type name.
typename = type.tag
if typename is None:
return None
if typename == "pp::Inner":
return inner_print(val)
return None
gdb.pretty_printers.append(lookup_function)
| cuda-gdb-master | gdb/testsuite/gdb.rust/pp.py |
# Copyright (C) 2014-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from time import asctime, gmtime
import gdb # silence pyflakes
class TimeTPrinter:
def __init__(self, val):
self.val = val
def to_string(self):
secs = int(self.val["secs"])
return "%s (%d)" % (asctime(gmtime(secs)), secs)
def time_sniffer(val):
if val.type.tag == "pck__time_t":
return TimeTPrinter(val)
return None
gdb.pretty_printers.append(time_sniffer)
| cuda-gdb-master | gdb/testsuite/gdb.ada/pp-rec-component.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests that python pretty
# printers defined in a python script that is autoloaded have been
# registered when a custom event handler for the new_objfile event
# is called.
import gdb
import os
def new_objfile_handler(event):
assert isinstance(event, gdb.NewObjFileEvent)
objfile = event.new_objfile
# Only observe the custom test library.
libname = "libpy-autoloaded-pretty-printers-in-newobjfile-event"
if libname in os.path.basename(objfile.filename):
# If everything went well and the pretty-printer auto-load happened
# before notifying the Python listeners, we expect to see one pretty
# printer, and it must be ours.
all_good = (
len(objfile.pretty_printers) == 1
and objfile.pretty_printers[0].name == "my_library"
)
if all_good:
gdb.parse_and_eval("all_good = 1")
else:
print("Oops, not all good:")
print("pretty printer count: {}".format(len(objfile.pretty_printers)))
for pp in objfile.pretty_printers:
print(" - {}".format(pp.name))
gdb.events.new_objfile.connect(new_objfile_handler)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-autoloaded-pretty-printers-in-newobjfile-event.py |
# Copyright (C) 2014-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests Python-based
# frame-filters.
import gdb
import itertools
from gdb.FrameDecorator import FrameDecorator
class FrameObjFile:
def __init__(self):
self.name = "Filter1"
self.priority = 1
self.enabled = False
gdb.current_progspace().frame_filters["Progspace" + self.name] = self
gdb.current_objfile().frame_filters["ObjectFile" + self.name] = self
def filter(self, frame_iter):
return frame_iter
class FrameObjFile2:
def __init__(self):
self.name = "Filter2"
self.priority = 100
self.enabled = True
gdb.current_progspace().frame_filters["Progspace" + self.name] = self
gdb.current_objfile().frame_filters["ObjectFile" + self.name] = self
def filter(self, frame_iter):
return frame_iter
FrameObjFile()
FrameObjFile2()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-framefilter-invalidarg-gdb.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import tracemalloc
import gdb
import re
# A global variable in which we store a reference to the gdb.Inferior
# object sent to us in the new_inferior event.
inf = None
# Register the new_inferior event handler.
def new_inferior_handler(event):
global inf
inf = event.inferior
gdb.events.new_inferior.connect(new_inferior_handler)
# A global filters list, we only care about memory allocations
# originating from this script.
filters = [tracemalloc.Filter(True, "*py-inferior-leak.py")]
# Add a new inferior, and return the number of the new inferior.
def add_inferior():
output = gdb.execute("add-inferior", False, True)
m = re.search(r"Added inferior (\d+)", output)
if m:
num = int(m.group(1))
else:
raise RuntimeError("no match")
return num
# Run the test. When CLEAR is True we clear the global INF variable
# before comparing the before and after memory allocation traces.
# When CLEAR is False we leave INF set to reference the gdb.Inferior
# object, thus preventing the gdb.Inferior from being deallocated.
def test(clear):
global filters, inf
# Start tracing, and take a snapshot of the current allocations.
tracemalloc.start()
snapshot1 = tracemalloc.take_snapshot()
# Create an inferior, this triggers the new_inferior event, which
# in turn holds a reference to the new gdb.Inferior object in the
# global INF variable.
num = add_inferior()
gdb.execute("remove-inferiors %s" % num)
# Possibly clear the global INF variable.
if clear:
inf = None
# Now grab a second snapshot of memory allocations, and stop
# tracing memory allocations.
snapshot2 = tracemalloc.take_snapshot()
tracemalloc.stop()
# Filter the snapshots; we only care about allocations originating
# from this file.
snapshot1 = snapshot1.filter_traces(filters)
snapshot2 = snapshot2.filter_traces(filters)
# Compare the snapshots, this leaves only things that were
# allocated, but not deallocated since the first snapshot.
stats = snapshot2.compare_to(snapshot1, "traceback")
# Total up all the deallocated things.
total = 0
for stat in stats:
total += stat.size_diff
return total
# The first time we run this some global state will be allocated which
# shows up as memory that is allocated, but not released. So, run the
# test once and discard the result.
test(True)
# Now run the test twice, the first time we clear our global reference
# to the gdb.Inferior object, which should allow Python to deallocate
# the object. The second time we hold onto the global reference,
# preventing Python from performing the deallocation.
bytes_with_clear = test(True)
bytes_without_clear = test(False)
# The bug that used to exist in GDB was that even when we released the
# global reference the gdb.Inferior object would not be deallocated.
if bytes_with_clear > 0:
raise gdb.GdbError("memory leak when gdb.Inferior should be released")
if bytes_without_clear == 0:
raise gdb.GdbError("gdb.Inferior object is no longer allocated")
# Print a PASS message that the test script can see.
print("PASS")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-inferior-leak.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
import gdb.disassembler
import struct
import sys
from gdb.disassembler import Disassembler, DisassemblerResult
# A global, holds the program-counter address at which we should
# perform the extra disassembly that this script provides.
current_pc = None
# Remove all currently registered disassemblers.
def remove_all_python_disassemblers():
for a in gdb.architecture_names():
gdb.disassembler.register_disassembler(None, a)
gdb.disassembler.register_disassembler(None, None)
class TestDisassembler(Disassembler):
"""A base class for disassemblers within this script to inherit from.
Implements the __call__ method and ensures we only do any
disassembly wrapping for the global CURRENT_PC."""
def __init__(self):
global current_pc
super().__init__("TestDisassembler")
self.__info = None
if current_pc == None:
raise gdb.GdbError("no current_pc set")
def __call__(self, info):
global current_pc
if info.address != current_pc:
return None
self.__info = info
return self.disassemble(info)
def get_info(self):
return self.__info
def disassemble(self, info):
raise NotImplementedError("override the disassemble method")
class GlobalPreInfoDisassembler(TestDisassembler):
"""Check the attributes of DisassembleInfo before disassembly has occurred."""
def disassemble(self, info):
ad = info.address
ar = info.architecture
if ad != current_pc:
raise gdb.GdbError("invalid address")
if not isinstance(ar, gdb.Architecture):
raise gdb.GdbError("invalid architecture type")
result = gdb.disassembler.builtin_disassemble(info)
text = result.string + "\t## ad = 0x%x, ar = %s" % (ad, ar.name())
return DisassemblerResult(result.length, text)
class GlobalPostInfoDisassembler(TestDisassembler):
"""Check the attributes of DisassembleInfo after disassembly has occurred."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
ad = info.address
ar = info.architecture
if ad != current_pc:
raise gdb.GdbError("invalid address")
if not isinstance(ar, gdb.Architecture):
raise gdb.GdbError("invalid architecture type")
text = result.string + "\t## ad = 0x%x, ar = %s" % (ad, ar.name())
return DisassemblerResult(result.length, text)
class GlobalReadDisassembler(TestDisassembler):
"""Check the DisassembleInfo.read_memory method. Calls the builtin
disassembler, then reads all of the bytes of this instruction, and
adds them as a comment to the disassembler output."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
len = result.length
str = ""
for o in range(len):
if str != "":
str += " "
v = bytes(info.read_memory(1, o))[0]
if sys.version_info[0] < 3:
v = struct.unpack("<B", v)
str += "0x%02x" % v
text = result.string + "\t## bytes = %s" % str
return DisassemblerResult(result.length, text)
class GlobalAddrDisassembler(TestDisassembler):
"""Check the gdb.format_address method."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
arch = info.architecture
addr = info.address
program_space = info.progspace
str = gdb.format_address(addr, program_space, arch)
text = result.string + "\t## addr = %s" % str
return DisassemblerResult(result.length, text)
class GdbErrorEarlyDisassembler(TestDisassembler):
"""Raise a GdbError instead of performing any disassembly."""
def disassemble(self, info):
raise gdb.GdbError("GdbError instead of a result")
class RuntimeErrorEarlyDisassembler(TestDisassembler):
"""Raise a RuntimeError instead of performing any disassembly."""
def disassemble(self, info):
raise RuntimeError("RuntimeError instead of a result")
class GdbErrorLateDisassembler(TestDisassembler):
"""Raise a GdbError after calling the builtin disassembler."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
raise gdb.GdbError("GdbError after builtin disassembler")
class RuntimeErrorLateDisassembler(TestDisassembler):
"""Raise a RuntimeError after calling the builtin disassembler."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
raise RuntimeError("RuntimeError after builtin disassembler")
class MemoryErrorEarlyDisassembler(TestDisassembler):
"""Throw a memory error, ignore the error and disassemble."""
def disassemble(self, info):
tag = "## FAIL"
try:
info.read_memory(1, -info.address + 2)
except gdb.MemoryError:
tag = "## AFTER ERROR"
result = gdb.disassembler.builtin_disassemble(info)
text = result.string + "\t" + tag
return DisassemblerResult(result.length, text)
class MemoryErrorLateDisassembler(TestDisassembler):
"""Throw a memory error after calling the builtin disassembler, but
before we return a result."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
# The following read will throw an error.
info.read_memory(1, -info.address + 2)
return DisassemblerResult(1, "BAD")
class RethrowMemoryErrorDisassembler(TestDisassembler):
"""Catch and rethrow a memory error."""
def disassemble(self, info):
try:
info.read_memory(1, -info.address + 2)
except gdb.MemoryError as e:
raise gdb.MemoryError("cannot read code at address 0x2")
return DisassemblerResult(1, "BAD")
class ResultOfWrongType(TestDisassembler):
"""Return something that is not a DisassemblerResult from disassemble method"""
class Blah:
def __init__(self, length, string):
self.length = length
self.string = string
def disassemble(self, info):
return self.Blah(1, "ABC")
class ResultWrapper(gdb.disassembler.DisassemblerResult):
def __init__(self, length, string, length_x=None, string_x=None):
super().__init__(length, string)
if length_x is None:
self.__length = length
else:
self.__length = length_x
if string_x is None:
self.__string = string
else:
self.__string = string_x
@property
def length(self):
return self.__length
@property
def string(self):
return self.__string
class ResultWithInvalidLength(TestDisassembler):
"""Return a result object with an invalid length."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
return ResultWrapper(result.length, result.string, 0)
class ResultWithInvalidString(TestDisassembler):
"""Return a result object with an empty string."""
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
return ResultWrapper(result.length, result.string, None, "")
class TaggingDisassembler(TestDisassembler):
"""A simple disassembler that just tags the output."""
def __init__(self, tag):
super().__init__()
self._tag = tag
def disassemble(self, info):
result = gdb.disassembler.builtin_disassemble(info)
text = result.string + "\t## tag = %s" % self._tag
return DisassemblerResult(result.length, text)
class GlobalCachingDisassembler(TestDisassembler):
"""A disassembler that caches the DisassembleInfo that is passed in,
as well as a copy of the original DisassembleInfo.
Once the call into the disassembler is complete then the
DisassembleInfo objects become invalid, and any calls into them
should trigger an exception."""
# This is where we cache the DisassembleInfo objects.
cached_insn_disas = []
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def disassemble(self, info):
"""Disassemble the instruction, add a CACHED comment to the output,
and cache the DisassembleInfo so that it is not garbage collected."""
GlobalCachingDisassembler.cached_insn_disas.append(info)
GlobalCachingDisassembler.cached_insn_disas.append(self.MyInfo(info))
result = gdb.disassembler.builtin_disassemble(info)
text = result.string + "\t## CACHED"
return DisassemblerResult(result.length, text)
@staticmethod
def check():
"""Check that all of the methods on the cached DisassembleInfo trigger an
exception."""
for info in GlobalCachingDisassembler.cached_insn_disas:
assert isinstance(info, gdb.disassembler.DisassembleInfo)
assert not info.is_valid()
try:
val = info.address
raise gdb.GdbError("DisassembleInfo.address is still valid")
except RuntimeError as e:
assert str(e) == "DisassembleInfo is no longer valid."
except:
raise gdb.GdbError(
"DisassembleInfo.address raised an unexpected exception"
)
try:
val = info.architecture
raise gdb.GdbError("DisassembleInfo.architecture is still valid")
except RuntimeError as e:
assert str(e) == "DisassembleInfo is no longer valid."
except:
raise gdb.GdbError(
"DisassembleInfo.architecture raised an unexpected exception"
)
try:
val = info.read_memory(1, 0)
raise gdb.GdbError("DisassembleInfo.read is still valid")
except RuntimeError as e:
assert str(e) == "DisassembleInfo is no longer valid."
except:
raise gdb.GdbError(
"DisassembleInfo.read raised an unexpected exception"
)
print("PASS")
class GlobalNullDisassembler(TestDisassembler):
"""A disassembler that does not change the output at all."""
def disassemble(self, info):
pass
class ReadMemoryMemoryErrorDisassembler(TestDisassembler):
"""Raise a MemoryError exception from the DisassembleInfo.read_memory
method."""
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
# Throw a memory error with a specific address. We don't
# expect this address to show up in the output though.
raise gdb.MemoryError(0x1234)
def disassemble(self, info):
info = self.MyInfo(info)
return gdb.disassembler.builtin_disassemble(info)
class ReadMemoryGdbErrorDisassembler(TestDisassembler):
"""Raise a GdbError exception from the DisassembleInfo.read_memory
method."""
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
raise gdb.GdbError("read_memory raised GdbError")
def disassemble(self, info):
info = self.MyInfo(info)
return gdb.disassembler.builtin_disassemble(info)
class ReadMemoryRuntimeErrorDisassembler(TestDisassembler):
"""Raise a RuntimeError exception from the DisassembleInfo.read_memory
method."""
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
raise RuntimeError("read_memory raised RuntimeError")
def disassemble(self, info):
info = self.MyInfo(info)
return gdb.disassembler.builtin_disassemble(info)
class ReadMemoryCaughtMemoryErrorDisassembler(TestDisassembler):
"""Raise a MemoryError exception from the DisassembleInfo.read_memory
method, catch this in the outer disassembler."""
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
raise gdb.MemoryError(0x1234)
def disassemble(self, info):
info = self.MyInfo(info)
try:
return gdb.disassembler.builtin_disassemble(info)
except gdb.MemoryError:
return None
class ReadMemoryCaughtGdbErrorDisassembler(TestDisassembler):
"""Raise a GdbError exception from the DisassembleInfo.read_memory
method, catch this in the outer disassembler."""
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
raise gdb.GdbError("exception message")
def disassemble(self, info):
info = self.MyInfo(info)
try:
return gdb.disassembler.builtin_disassemble(info)
except gdb.GdbError as e:
if e.args[0] == "exception message":
return None
raise e
class ReadMemoryCaughtRuntimeErrorDisassembler(TestDisassembler):
"""Raise a RuntimeError exception from the DisassembleInfo.read_memory
method, catch this in the outer disassembler."""
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
raise RuntimeError("exception message")
def disassemble(self, info):
info = self.MyInfo(info)
try:
return gdb.disassembler.builtin_disassemble(info)
except RuntimeError as e:
if e.args[0] == "exception message":
return None
raise e
class MemorySourceNotABufferDisassembler(TestDisassembler):
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
return 1234
def disassemble(self, info):
info = self.MyInfo(info)
return gdb.disassembler.builtin_disassemble(info)
class MemorySourceBufferTooLongDisassembler(TestDisassembler):
"""The read memory returns too many bytes."""
class MyInfo(gdb.disassembler.DisassembleInfo):
def __init__(self, info):
super().__init__(info)
def read_memory(self, length, offset):
buffer = super().read_memory(length, offset)
# Create a new memory view made by duplicating BUFFER. This
# will trigger an error as GDB expects a buffer of exactly
# LENGTH to be returned, while this will return a buffer of
# 2*LENGTH.
return memoryview(
bytes([int.from_bytes(x, "little") for x in (list(buffer[0:]) * 2)])
)
def disassemble(self, info):
info = self.MyInfo(info)
return gdb.disassembler.builtin_disassemble(info)
class BuiltinDisassembler(Disassembler):
"""Just calls the builtin disassembler."""
def __init__(self):
super().__init__("BuiltinDisassembler")
def __call__(self, info):
return gdb.disassembler.builtin_disassemble(info)
class AnalyzingDisassembler(Disassembler):
class MyInfo(gdb.disassembler.DisassembleInfo):
"""Wrapper around builtin DisassembleInfo type that overrides the
read_memory method."""
def __init__(self, info, start, end, nop_bytes):
"""INFO is the DisassembleInfo we are wrapping. START and END are
addresses, and NOP_BYTES should be a memoryview object.
The length (END - START) should be the same as the length
of NOP_BYTES.
Any memory read requests outside the START->END range are
serviced normally, but any attempt to read within the
START->END range will return content from NOP_BYTES."""
super().__init__(info)
self._start = start
self._end = end
self._nop_bytes = nop_bytes
def _read_replacement(self, length, offset):
"""Return a slice of the buffer representing the replacement nop
instructions."""
assert self._nop_bytes is not None
rb = self._nop_bytes
# If this request is outside of a nop instruction then we don't know
# what to do, so just raise a memory error.
if offset >= len(rb) or (offset + length) > len(rb):
raise gdb.MemoryError("invalid length and offset combination")
# Return only the slice of the nop instruction as requested.
s = offset
e = offset + length
return rb[s:e]
def read_memory(self, length, offset=0):
"""Callback used by the builtin disassembler to read the contents of
memory."""
# If this request is within the region we are replacing with 'nop'
# instructions, then call the helper function to perform that
# replacement.
if self._start is not None:
assert self._end is not None
if self.address >= self._start and self.address < self._end:
return self._read_replacement(length, offset)
# Otherwise, we just forward this request to the default read memory
# implementation.
return super().read_memory(length, offset)
def __init__(self):
"""Constructor."""
super().__init__("AnalyzingDisassembler")
# Details about the instructions found during the first disassembler
# pass.
self._pass_1_length = []
self._pass_1_insn = []
self._pass_1_address = []
# The start and end address for the instruction we will replace with
# one or more 'nop' instructions during pass two.
self._start = None
self._end = None
# The index in the _pass_1_* lists for where the nop instruction can
# be found, also, the buffer of bytes that make up a nop instruction.
self._nop_index = None
self._nop_bytes = None
# A flag that indicates if we are in the first or second pass of
# this disassembler test.
self._first_pass = True
# The disassembled instructions collected during the second pass.
self._pass_2_insn = []
# A copy of _pass_1_insn that has been modified to include the extra
# 'nop' instructions we plan to insert during the second pass. This
# is then checked against _pass_2_insn after the second disassembler
# pass has completed.
self._check = []
def __call__(self, info):
"""Called to perform the disassembly."""
# Override the info object, this provides access to our
# read_memory function.
info = self.MyInfo(info, self._start, self._end, self._nop_bytes)
result = gdb.disassembler.builtin_disassemble(info)
# Record some informaiton about the first 'nop' instruction we find.
if self._nop_index is None and result.string == "nop":
self._nop_index = len(self._pass_1_length)
# The offset in the following read_memory call defaults to 0.
self._nop_bytes = info.read_memory(result.length)
# Record information about each instruction that is disassembled.
# This test is performed in two passes, and we need different
# information in each pass.
if self._first_pass:
self._pass_1_length.append(result.length)
self._pass_1_insn.append(result.string)
self._pass_1_address.append(info.address)
else:
self._pass_2_insn.append(result.string)
return result
def find_replacement_candidate(self):
"""Call this after the first disassembly pass. This identifies a suitable
instruction to replace with 'nop' instruction(s)."""
if self._nop_index is None:
raise gdb.GdbError("no nop was found")
nop_idx = self._nop_index
nop_length = self._pass_1_length[nop_idx]
# First we look for an instruction that is larger than a nop
# instruction, but whose length is an exact multiple of the nop
# instruction's length.
replace_idx = None
for idx in range(len(self._pass_1_length)):
if (
idx > 0
and idx != nop_idx
and self._pass_1_insn[idx] != "nop"
and self._pass_1_length[idx] > self._pass_1_length[nop_idx]
and self._pass_1_length[idx] % self._pass_1_length[nop_idx] == 0
):
replace_idx = idx
break
# If we still don't have a replacement candidate, then search again,
# this time looking for an instruciton that is the same length as a
# nop instruction.
if replace_idx is None:
for idx in range(len(self._pass_1_length)):
if (
idx > 0
and idx != nop_idx
and self._pass_1_insn[idx] != "nop"
and self._pass_1_length[idx] == self._pass_1_length[nop_idx]
):
replace_idx = idx
break
# Weird, the nop instruction must be larger than every other
# instruction, or all instructions are 'nop'?
if replace_idx is None:
raise gdb.GdbError("can't find an instruction to replace")
# Record the instruction range that will be replaced with 'nop'
# instructions, and mark that we are now on the second pass.
self._start = self._pass_1_address[replace_idx]
self._end = self._pass_1_address[replace_idx] + self._pass_1_length[replace_idx]
self._first_pass = False
print("Replace from 0x%x to 0x%x with NOP" % (self._start, self._end))
# Finally, build the expected result. Create the _check list, which
# is a copy of _pass_1_insn, but replace the instruction we
# identified above with a series of 'nop' instructions.
self._check = list(self._pass_1_insn)
nop_count = int(self._pass_1_length[replace_idx] / self._pass_1_length[nop_idx])
nops = ["nop"] * nop_count
self._check[replace_idx : (replace_idx + 1)] = nops
def check(self):
"""Call this after the second disassembler pass to validate the output."""
if self._check != self._pass_2_insn:
raise gdb.GdbError("mismatch")
print("PASS")
def add_global_disassembler(dis_class):
"""Create an instance of DIS_CLASS and register it as a global disassembler."""
dis = dis_class()
gdb.disassembler.register_disassembler(dis, None)
return dis
class InvalidDisassembleInfo(gdb.disassembler.DisassembleInfo):
"""An attempt to create a DisassembleInfo sub-class without calling
the parent class init method.
Attempts to use instances of this class should throw an error
saying that the DisassembleInfo is not valid, despite this class
having all of the required attributes.
The reason why this class will never be valid is that an internal
field (within the C++ code) can't be initialized without calling
the parent class init method."""
def __init__(self):
assert current_pc is not None
def is_valid(self):
return True
@property
def address(self):
global current_pc
return current_pc
@property
def architecture(self):
return gdb.selected_inferior().architecture()
@property
def progspace(self):
return gdb.selected_inferior().progspace
# Start with all disassemblers removed.
remove_all_python_disassemblers()
print("Python script imported")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-disasm.py |
# Copyright (C) 2018-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
import gdb.types
class cons_pp(object):
def __init__(self, val):
self._val = val
def to_string(self):
if int(self._val) == 0:
return "nil"
elif int(self._val["type"]) == 0:
return "( . )"
else:
return "%d" % self._val["atom"]["ival"]
def children(self):
if int(self._val) == 0:
return []
elif int(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
del gdb.pretty_printers[1:]
gdb.pretty_printers.append(cons_pp_lookup)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-mi-var-info-path-expression.py |
# Copyright (C) 2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Test Python free_objfile event.
import gdb
freed_objfile = None
def free_objfile_handler(event):
assert isinstance(event, gdb.FreeObjFileEvent)
global freed_objfile
freed_objfile = event.objfile.username
gdb.events.free_objfile.connect(free_objfile_handler)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-event-load.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite.
import gdb
# PR 18833
# We want to have two levels of redirection while MI is current_uiout.
# This will create one for to_string=True and then another for the
# parameter change notification.
gdb.execute("set width 101", to_string=True)
# And finally a command that will use the console stream without redirection
gdb.execute("list -q main")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-mi-objfile-gdb.py |
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python pretty
# printer registration.
import re
import gdb.types
import gdb.printing
def lookup_function_lookup_test(val):
class PrintFunctionLookup(object):
def __init__(self, val):
self.val = val
def to_string(self):
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.
if typename == "function_lookup_test":
return PrintFunctionLookup(val)
return None
class pp_s1(object):
def __init__(self, val):
self.val = val
def to_string(self):
a = self.val["a"]
b = self.val["b"]
return "s1 a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">"
class pp_s2(object):
def __init__(self, val):
self.val = val
def to_string(self):
a = self.val["a"]
b = self.val["b"]
return "s2 a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">"
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)
return pp
def build_pretty_printer2():
# This intentionally has the same name as build_pretty_printer1.
# It is used to test the "replace" functionality of
# 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)
return pp
# Note: Registering the printers is done in the .exp file.
| cuda-gdb-master | gdb/testsuite/gdb.python/py-pp-registration.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from time import asctime, gmtime
import gdb # silence pyflakes
class TimePrinter:
def __init__(self, val):
self.val = val
def to_string(self):
secs = int(self.val)
return "%s (%d)" % (asctime(gmtime(secs)), secs)
def build_pretty_printer():
pp = gdb.printing.RegexpCollectionPrettyPrinter("pp-notag")
pp.add_printer("time_t", "time_t", TimePrinter)
return pp
my_pretty_printer = build_pretty_printer()
gdb.printing.register_pretty_printer(gdb, my_pretty_printer)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-pp-re-notag.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import gdb
class pp_s(object):
def __init__(self, val):
self.val = val
def to_string(self):
m = self.val["m"]
return "m=<" + str(self.val["m"]) + ">"
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 lookup_function(val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
# Get the unqualified type, stripped of typedefs.
type = type.unqualified().strip_typedefs()
# Get the type name.
typename = type.tag
if typename is None:
return None
# Iterate over local dictionary of types to determine
# 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)
# 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
pretty_printers_dict = {}
register_pretty_printers()
gdb.pretty_printers.append(lookup_function)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-frame-args.py |
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python pretty
# 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))
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))
else:
print("all threads stopped")
def exit_handler(event):
assert isinstance(event, gdb.ExitedEvent)
print("event type: exit")
if hasattr(event, "exit_code"):
print("exit code: %d" % (event.exit_code))
else:
print("exit code: not-present")
print("exit inf: %d" % (event.inferior.num))
print("exit pid: %d" % (event.inferior.pid))
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))
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))
class test_events(gdb.Command):
"""Test events."""
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.")
test_events()
class test_newobj_events(gdb.Command):
"""NewObj events."""
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.")
test_newobj_events()
def gdb_exiting_handler(event, throw_error):
assert isinstance(event, gdb.GdbExitingEvent)
if throw_error:
raise gdb.GdbError("error from gdb_exiting_handler")
else:
print("event type: gdb-exiting")
print("exit code: %d" % (event.exit_code))
class test_exiting_event(gdb.Command):
"""GDB Exiting event."""
def __init__(self):
gdb.Command.__init__(self, "test-exiting-event", gdb.COMMAND_STACK)
def invoke(self, arg, from_tty):
if arg == "normal":
gdb.events.gdb_exiting.connect(lambda e: gdb_exiting_handler(e, False))
elif arg == "error":
gdb.events.gdb_exiting.connect(lambda e: gdb_exiting_handler(e, True))
else:
raise gdb.GdbError("invalid or missing argument")
print("GDB exiting event registered.")
test_exiting_event()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-events.py |
# Copyright (C) 2016-2022 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
class MyBP(gdb.Breakpoint):
def stop(self):
print("MyBP.stop was invoked!")
# Don't make this breakpoint stop
return False
try:
bp = MyBP("does_not_exist", gdb.BP_WATCHPOINT)
except RuntimeError:
pass
else:
assert False
| cuda-gdb-master | gdb/testsuite/gdb.python/py-breakpoint-create-fail.py |
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
class ClassName(gdb.Command):
"a"
def __init__(self):
gdb.Command.__init__(self, "ClassName", gdb.COMMAND_DATA, prefix=True)
def invoke(self, args, from_tty):
print
ClassName()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-error.py |
# Copyright (C) 2011-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# 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)
self.silent = True
print("init ExceptionFinishBreakpoint")
def stop(self):
print("stopped at ExceptionFinishBreakpoint")
return True
def out_of_scope(self):
print("exception did not finish ...")
print("Python script imported")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-finish-breakpoint2.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This script is auto-loaded when the py-auto-load-chaining-f1.o
# object is loaded.
import re
print("Entering f1.o auto-load script")
print("Current objfile is: %s" % gdb.current_objfile().filename)
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))
print("After loading f2.o...")
print("Current objfile is: %s" % gdb.current_objfile().filename)
print("Leaving f1.o auto-load script")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-auto-load-chaining-f1.o-gdb.py |
# Copyright (C) 2011-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# 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 TestBreakpoint(gdb.Breakpoint):
def __init__(self):
gdb.Breakpoint.__init__(self, spec="test_1", internal=1)
self.silent = True
self.count = 0
print("TestBreakpoint init")
def stop(self):
self.count += 1
try:
TestFinishBreakpoint(gdb.newest_frame(), self.count)
except ValueError as e:
print(e)
return False
class TestFinishBreakpoint(gdb.FinishBreakpoint):
def __init__(self, frame, count):
self.count = count
gdb.FinishBreakpoint.__init__(self, frame, internal=1)
def stop(self):
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
def out_of_scope(self):
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
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")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-finish-breakpoint.py |
# Copyright (C) 2020-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# A dummy stack unwinder used for testing the Python unwinders when we
# have inline frames. This unwinder will never claim any frames,
# instead, all it does it try to read all registers possible target
# registers as part of the frame sniffing process..
import gdb
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
the unwinding process."""
class frame_id(object):
"""Basic frame id."""
def __init__(self, sp, pc):
"""Create the frame id."""
self.sp = sp
self.pc = pc
def __init__(self):
"""Create the 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):
"""Return a list of register names that should be read. Only
gathers the list once, then caches the result."""
if self.regs is not None:
return self.regs
# Collect the names of all registers to read.
self.regs = list(pending_frame.architecture().register_names())
return self.regs
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)
except:
print("Dummy unwinder, exception")
raise
return None
# Register the ComRV stack unwinder.
gdb.unwinder.register_unwinder(None, dummy_unwinder(), True)
print("Python script imported")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-unwind-inline.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests Python-based
# frame-filters.
import gdb
import itertools
from gdb.FrameDecorator import FrameDecorator
import copy
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 not fname:
return None
if fname == "end_func":
extra = self.fobj.inferior_frame().read_var("str").string()
else:
extra = ""
fname = fname[::-1] + extra
return fname
class Dummy(FrameDecorator):
def __init__(self, fobj):
super(Dummy, self).__init__(fobj)
self.fobj = fobj
def function(self):
return "Dummy function"
def address(self):
return 0x123
def filename(self):
return "Dummy filename"
def frame_args(self):
return [("Foo", gdb.Value(12)), ("Bar", "Stuff"), ("FooBar", 42)]
def frame_locals(self):
return []
def line(self):
return 0
def elided(self):
return None
class FrameFilter:
def __init__(self):
self.name = "Reverse"
self.priority = 100
self.enabled = True
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"):
frame_iter = itertools.imap(Reverse_Function, frame_iter)
else:
frame_iter = map(Reverse_Function, frame_iter)
return frame_iter
class ElidingFrameDecorator(FrameDecorator):
def __init__(self, frame, elided_frames):
super(ElidingFrameDecorator, self).__init__(frame)
self.elided_frames = elided_frames
def elided(self):
return iter(self.elided_frames)
def address(self):
# Regression test for an overflow in the python layer.
bitsize = 8 * gdb.lookup_type("void").pointer().sizeof
mask = (1 << bitsize) - 1
return 0xFFFFFFFFFFFFFFFF & mask
class ElidingIterator:
def __init__(self, ii):
self.input_iterator = ii
def __iter__(self):
return self
def next(self):
frame = next(self.input_iterator)
if str(frame.function()) != "func1":
return frame
# Suppose we want to return the 'func1' frame but elide the
# next frame. E.g., if call in our interpreter language takes
# two C frames to implement, and the first one we see is the
# "sentinel".
elided = next(self.input_iterator)
return ElidingFrameDecorator(frame, [elided])
# Python 3.x requires __next__(self) while Python 2.x requires
# next(self). Define next(self), and for Python 3.x create this
# wrapper.
def __next__(self):
return self.next()
class FrameElider:
def __init__(self):
self.name = "Elider"
self.priority = 900
self.enabled = True
gdb.frame_filters[self.name] = self
def filter(self, frame_iter):
return ElidingIterator(frame_iter)
# This is here so the test can change the kind of error that is
# thrown.
name_error = RuntimeError
# A simple decorator that gives an error when computing the function.
class ErrorInName(FrameDecorator):
def __init__(self, frame):
FrameDecorator.__init__(self, frame)
def function(self):
raise name_error("whoops")
# A filter that supplies buggy frames. Disabled by default.
class ErrorFilter:
def __init__(self):
self.name = "Error"
self.priority = 1
self.enabled = False
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)
else:
return map(ErrorInName, frame_iter)
FrameFilter()
FrameElider()
ErrorFilter()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-framefilter.py |
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python pretty
# printers.
import re
import gdb.types
import gdb.printing
def lookup_function_lookup_test(val):
class PrintFunctionLookup(object):
def __init__(self, val):
self.val = val
def to_string(self):
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.
if typename == "function_lookup_test":
return PrintFunctionLookup(val)
return None
class pp_s(object):
def __init__(self, val):
self.val = val
def to_string(self):
a = self.val["a"]
b = self.val["b"]
if a.address != b:
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):
def __init__(self, val):
self.val = val
def to_string(self):
return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">"
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)
# 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"),
)
return pp
gdb.printing.register_pretty_printer(gdb, lookup_function_lookup_test)
my_pretty_printer = build_pretty_printer()
gdb.printing.register_pretty_printer(gdb, my_pretty_printer)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-pp-maint.py |
# Copyright (C) 2010-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite.
import re
class pp_ss:
def __init__(self, val):
self.val = val
def to_string(self):
return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">"
def lookup_function(val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
# Get the unqualified type, stripped of typedefs.
type = type.unqualified().strip_typedefs()
# Get the type name.
typename = type.tag
if typename is None:
return None
# Iterate over local dictionary of types to determine
# 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)
# Cannot find a pretty printer. Return None.
return None
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)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-section-script.py |
# Copyright (C) 2008-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests GDB's handling of
# bad python pretty printers.
# Test a printer with a bad children iterator.
import re
import gdb.printing
class BadChildrenContainerPrinter1(object):
"""Children iterator doesn't return a tuple of two elements."""
def __init__(self, val):
self.val = val
def to_string(self):
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"
pointer += 1
def children(self):
return self._bad_iterator(self.val["elements"], self.val["len"])
class BadChildrenContainerPrinter2(object):
"""Children iterator returns a tuple of two elements with bad values."""
def __init__(self, val):
self.val = val
def to_string(self):
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:
# The first argument is supposed to be a string.
yield (42, "intentional violation of children iterator protocol")
pointer += 1
def children(self):
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)
return pp
my_pretty_printer = build_pretty_printer()
gdb.printing.register_pretty_printer(gdb, my_pretty_printer)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-bad-printers.py |
# Copyright (C) 2019-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests GDB's printing of
# nested map like structures.
import re
import gdb
def _iterator1(pointer, len):
while len > 0:
map = pointer.dereference()
yield ("", map["name"])
yield ("", map.dereference())
pointer += 1
len -= 1
def _iterator2(pointer1, pointer2, len):
while len > 0:
yield ("", pointer1.dereference())
yield ("", pointer2.dereference())
pointer1 += 1
pointer2 += 1
len -= 1
class pp_map(object):
def __init__(self, val):
self.val = val
def to_string(self):
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"])
def display_hint(self):
return "map"
class pp_map_map(object):
def __init__(self, val):
self.val = val
def to_string(self):
if self.val["show_header"] == 0:
return None
else:
return "pp_map_map"
def children(self):
return _iterator1(self.val["values"], self.val["length"])
def display_hint(self):
return "map"
def lookup_function(val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
# Get the unqualified type, stripped of typedefs.
type = type.unqualified().strip_typedefs()
# Get the type name.
typename = type.tag
if typename is None:
return None
# Iterate over local dictionary of types to determine
# 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)
# Cannot find a pretty printer. Return None.
return None
# Lookup a printer for VAL in the typedefs dict.
def lookup_typedefs_function(val):
"Look-up and return a pretty-printer that can print val (typedefs)."
# Get the type.
type = val.type
if type is None or type.name is None or type.code != gdb.TYPE_CODE_TYPEDEF:
return None
# Iterate over local dictionary of typedef types to determine if a
# 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)
# 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
# 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)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-nested-maps.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python unwinders.
import re
import gdb.types
from gdb.unwinder import Unwinder, register_unwinder
class TestGlobalUnwinder(Unwinder):
def __init__(self):
super(TestGlobalUnwinder, self).__init__("global_unwinder")
def __call__(self, unwinder_info):
print("%s called" % self.name)
return None
class TestProgspaceUnwinder(Unwinder):
def __init__(self, name):
super(TestProgspaceUnwinder, self).__init__("%s_ps_unwinder" % name)
def __call__(self, unwinder_info):
print("%s called" % self.name)
return None
class TestObjfileUnwinder(Unwinder):
def __init__(self, name):
super(TestObjfileUnwinder, self).__init__("%s_obj_unwinder" % name)
def __call__(self, unwinder_info):
print("%s called" % self.name)
return None
gdb.unwinder.register_unwinder(None, TestGlobalUnwinder())
saw_runtime_error = False
try:
gdb.unwinder.register_unwinder(None, TestGlobalUnwinder(), replace=False)
except RuntimeError:
saw_runtime_error = True
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")
)
print("Python script imported")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-unwind-maint.py |
# Copyright (C) 2008-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python pretty
# printers.
import gdb
saved_options = {}
class PointPrinter(object):
def __init__(self, val):
self.val = val
def to_string(self):
global saved_options
saved_options = gdb.print_options()
if saved_options["summary"]:
return "No Data"
return "Pretty Point (%s, %s)" % (self.val["x"], self.val["y"])
def test_lookup_function(val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
# Get the unqualified type, stripped of typedefs.
type = type.unqualified().strip_typedefs()
# Get the type name.
typename = type.tag
if typename == "point":
return PointPrinter(val)
return None
gdb.pretty_printers.append(test_lookup_function)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-format-string.py |
# Copyright (C) 2011-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite.
import re
class pp_ss:
def __init__(self, val):
self.val = val
def to_string(self):
return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">"
def lookup_function(val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
# Get the unqualified type, stripped of typedefs.
type = type.unqualified().strip_typedefs()
# Get the type name.
typename = type.tag
if typename is None:
return None
# Iterate over local dictionary of types to determine
# 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)
# Cannot find a pretty printer. Return None.
return None
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)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-objfile-script-gdb.py |
# Copyright (C) 2016-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python printing
# to string from event handlers.
import gdb
stop_handler_str = ""
cont_handler_str = ""
def signal_stop_handler(event):
"""Stop event handler"""
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):
"""Continue event handler"""
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):
"""Test events."""
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.")
test_events()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-mi-events-gdb.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# A TUI window implemented in Python that responds to, and displays,
# stop and exit events.
import gdb
# When an event arrives we ask the window to redraw itself. We should
# only do this if the window is valid. When this flag is true we
# perform the is_valid check. When this flag is false
perform_valid_check = True
update_title = False
cleanup_properly = False
# A global place into which we can write the window title.
titles_at_the_close = {}
class EventWindow:
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._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...")
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
)
# 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...")
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)
self._stop_listener = None
self._exit_listener = None
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():
if update_title:
self._win.title = "This Is The Event Window (" + str(self._count) + ")"
else:
self.render()
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")
gdb.register_window_type("events", EventWindow)
| cuda-gdb-master | gdb/testsuite/gdb.python/tui-window-disabled.py |
# Copyright (C) 2014-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This testcase tests PR python/16699
import gdb
class CompleteFileInit(gdb.Command):
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")
class CompleteFileMethod(gdb.Command):
def __init__(self):
gdb.Command.__init__(self, "completefilemethod", gdb.COMMAND_USER)
def invoke(self, argument, from_tty):
raise gdb.GdbError("not implemented")
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
class CompleteLimit1(gdb.Command):
def __init__(self):
gdb.Command.__init__(self, "completelimit1", gdb.COMMAND_USER)
def invoke(self, argument, from_tty):
raise gdb.GdbError("not implemented")
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")
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 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 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 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 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 complete(self, text, word):
return [
"cl71",
"cl73",
"cl75",
"cl77",
"cl79",
"cl72",
"cl74",
"cl76",
"cl78",
"cl710",
]
CompleteFileInit()
CompleteFileMethod()
CompleteFileCommandCond()
CompleteLimit1()
CompleteLimit2()
CompleteLimit3()
CompleteLimit4()
CompleteLimit5()
CompleteLimit6()
CompleteLimit7()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-completion.py |
# Copyright 2014-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It test the xmethods support
# in the Python extension language.
import gdb
import re
from gdb.xmethod import XMethod
from gdb.xmethod import XMethodMatcher, XMethodWorker
from gdb.xmethod import SimpleXMethodMatcher
def A_plus_A(obj, opr):
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
def A_geta(obj):
print("From Python <A_geta>:")
return obj["a"]
def A_getarrayind(obj, index):
print("From Python <A_getarrayind>:")
return obj["array"][index]
def A_indexoper(obj, index):
return obj["array"][index].reference_value()
def B_indexoper(obj, index):
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()
# 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")
def get_result_type(self, obj, arg):
return gdb.lookup_type("void")
def __call__(self, obj, arg):
print("From Python <E_method_char>")
return None
class E_method_int_worker(XMethodWorker):
def __init__(self):
pass
def get_arg_types(self):
return gdb.lookup_type("int")
# Note: get_result_type method elided on purpose
def __call__(self, obj, arg):
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")]
def match(self, class_type, method_name):
class_tag = class_type.unqualified().tag
if not re.match("^dop::E$", class_tag):
return None
if not re.match("^method$", method_name):
return None
workers = []
if self.methods[0].enabled:
workers.append(E_method_int_worker())
if self.methods[1].enabled:
workers.append(E_method_char_worker())
return workers
# The G class method matcher and worker illustrate how to write
# 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
self._method_template_type = method_template_type
def get_arg_types(self):
pass
def __call__(self, obj):
print("From Python G<>::size_diff()")
return self._method_template_type.sizeof - self._class_template_type.sizeof
class G_size_mul_worker(XMethodWorker):
def __init__(self, class_template_type, method_template_val):
self._class_template_type = class_template_type
self._method_template_val = method_template_val
def get_arg_types(self):
pass
def __call__(self, obj):
print("From Python G<>::size_mul()")
return self._class_template_type.sizeof * self._method_template_val
class G_mul_worker(XMethodWorker):
def __init__(self, class_template_type, method_template_type):
self._class_template_type = class_template_type
self._method_template_type = method_template_type
def get_arg_types(self):
return self._method_template_type
def __call__(self, obj, 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")]
def _is_enabled(self, name):
for method in self.methods:
if method.name == name and method.enabled:
return True
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):
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"):
return None
t1_name = method_name[10:-1]
try:
t1_type = gdb.lookup_type(t1_name)
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"):
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"):
return None
t1_name = method_name[4:-1]
try:
t1_type = gdb.lookup_type(t1_name)
return G_mul_worker(t_type, t1_type)
except gdb.error:
return None
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
),
]
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())
| cuda-gdb-master | gdb/testsuite/gdb.python/py-xmethods.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from time import asctime, gmtime
import gdb # silence pyflakes
class TimePrinter:
def __init__(self, val):
self.val = val
def to_string(self):
secs = int(self.val)
return "%s (%d)" % (asctime(gmtime(secs)), secs)
def time_sniffer(val):
if hasattr(val.type, "name") and val.type.name == "time_t":
return TimePrinter(val)
return None
gdb.pretty_printers.append(time_sniffer)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-pp-integral.py |
# Copyright (C) 2012-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
class Recognizer(object):
def __init__(self):
self.enabled = True
def recognize(self, type_obj):
if type_obj.tag == "basic_string":
return "string"
return None
class StringTypePrinter(object):
def __init__(self):
self.name = "string"
self.enabled = True
def instantiate(self):
return Recognizer()
gdb.type_printers.append(StringTypePrinter())
| cuda-gdb-master | gdb/testsuite/gdb.python/py-typeprint.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import xml.etree.ElementTree as ET
import gdb
# Make use of gdb.RemoteTargetConnection.send_packet to fetch the
# thread list from the remote target.
#
# Sending existing serial protocol packets like this is not a good
# idea, there should be better ways to get this information using an
# official API, this is just being used as a test case.
#
# Really, the send_packet API would be used to send target
# specific packets to the target, but these are, by definition, target
# specific, so hard to test in a general testsuite.
def get_thread_list_str():
start_pos = 0
thread_desc = ""
conn = gdb.selected_inferior().connection
if not isinstance(conn, gdb.RemoteTargetConnection):
raise gdb.GdbError("connection is the wrong type")
while True:
str = conn.send_packet("qXfer:threads:read::%d,200" % start_pos).decode("ascii")
start_pos += 200
c = str[0]
str = str[1:]
thread_desc += str
if c == "l":
break
return thread_desc
# Use gdb.RemoteTargetConnection.send_packet to manually fetch the
# thread list, then extract the thread list using the gdb.Inferior and
# gdb.InferiorThread API. Compare the two results to ensure we
# managed to successfully read the thread list from the remote.
def run_send_packet_test():
# Find the IDs of all current threads.
all_threads = {}
for inf in gdb.inferiors():
for thr in inf.threads():
id = "p%x.%x" % (thr.ptid[0], thr.ptid[1])
all_threads[id] = False
# Now fetch the thread list from the remote, and parse the XML.
str = get_thread_list_str()
threads_xml = ET.fromstring(str)
# Look over all threads in the XML list and check we expected to
# find them, mark the ones we do find.
for thr in threads_xml:
id = thr.get("id")
if not id in all_threads:
raise "found unexpected thread in remote thread list"
else:
all_threads[id] = True
# Check that all the threads were found in the XML list.
for id in all_threads:
if not all_threads[id]:
raise "thread missingt from remote thread list"
# Test complete.
print("Send packet test passed")
# Convert a bytes object to a string. This follows the same rules as
# the 'maint packet' command so that the output from the two sources
# can be compared.
def bytes_to_string(byte_array):
res = ""
for b in byte_array:
b = int(b)
if b >= 32 and b <= 126:
res = res + ("%c" % b)
else:
res = res + ("\\x%02x" % b)
return res
# A very simple test for sending the packet that reads the auxv data.
# We convert the result to a string and expect to find some
# hex-encoded bytes in the output. This test will only work on
# targets that actually supply auxv data.
def run_auxv_send_packet_test(expected_result):
inf = gdb.selected_inferior()
conn = inf.connection
assert isinstance(conn, gdb.RemoteTargetConnection)
res = conn.send_packet("qXfer:auxv:read::0,1000")
assert isinstance(res, bytes)
string = bytes_to_string(res)
assert string.count("\\x") > 0
assert string == expected_result
print("auxv send packet test passed")
# Check that the value of 'global_var' is EXPECTED_VAL.
def check_global_var(expected_val):
val = int(gdb.parse_and_eval("global_var"))
val = val & 0xFFFFFFFF
if val != expected_val:
raise gdb.GdbError("global_var is 0x%x, expected 0x%x" % (val, expected_val))
# Return a bytes object representing an 'X' packet header with
# address ADDR.
def xpacket_header(addr):
return ("X%x,4:" % addr).encode("ascii")
# Set the 'X' packet to the remote target to set a global variable.
# Checks that we can send byte values.
def run_set_global_var_test():
inf = gdb.selected_inferior()
conn = inf.connection
assert isinstance(conn, gdb.RemoteTargetConnection)
addr = gdb.parse_and_eval("&global_var")
res = conn.send_packet("X%x,4:\x01\x01\x01\x01" % addr)
assert isinstance(res, bytes)
check_global_var(0x01010101)
res = conn.send_packet(xpacket_header(addr) + b"\x02\x02\x02\x02")
assert isinstance(res, bytes)
check_global_var(0x02020202)
# This first attempt will not work as we're passing a Unicode string
# containing non-ascii characters.
saw_error = False
try:
res = conn.send_packet("X%x,4:\xff\xff\xff\xff" % addr)
except UnicodeError:
saw_error = True
except:
assert False
assert saw_error
check_global_var(0x02020202)
# Now we pass a bytes object, which will work.
res = conn.send_packet(xpacket_header(addr) + b"\xff\xff\xff\xff")
check_global_var(0xFFFFFFFF)
print("set global_var test passed")
# Just to indicate the file was sourced correctly.
print("Sourcing complete.")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-send-packet.py |
# This testcase is part of GDB, the GNU debugger.
# Copyright 2008-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# 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")
| cuda-gdb-master | gdb/testsuite/gdb.python/source2.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
from gdb.unwinder import Unwinder
class FrameId(object):
def __init__(self, sp, pc):
self._sp = sp
self._pc = pc
@property
def sp(self):
return self._sp
@property
def pc(self):
return self._pc
class TestUnwinder(Unwinder):
def __init__(self, use_descriptors):
if use_descriptors:
tag = "using descriptors"
else:
tag = "using strings"
Unwinder.__init__(self, "break unwinding %s" % tag)
self._use_descriptors = use_descriptors
def __call__(self, pending_frame):
pc_desc = pending_frame.architecture().registers().find("pc")
pc = pending_frame.read_register(pc_desc)
sp_desc = pending_frame.architecture().registers().find("sp")
sp = pending_frame.read_register(sp_desc)
block = gdb.block_for_pc(int(pc))
if block is None:
return None
func = block.function
if func is None:
return None
if str(func) != "bar":
return None
fid = FrameId(pc, sp)
unwinder = pending_frame.create_unwind_info(fid)
if self._use_descriptors:
unwinder.add_saved_register(pc_desc, pc)
unwinder.add_saved_register(sp_desc, sp)
else:
unwinder.add_saved_register("pc", pc)
unwinder.add_saved_register("sp", sp)
return unwinder
gdb.unwinder.register_unwinder(None, TestUnwinder(True), True)
gdb.unwinder.register_unwinder(None, TestUnwinder(False), True)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-unwind-user-regs.py |
# Copyright (C) 2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class MyFinishBreakpoint(gdb.FinishBreakpoint):
def stop(self):
print("stopped at MyFinishBreakpoint")
return self.return_value == 4
class MyBreakpoint(gdb.Breakpoint):
def stop(self):
print("stopped at MyBreakpoint")
MyFinishBreakpoint()
return False
MyBreakpoint("subroutine", internal=True)
print("Python script imported")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-finish-breakpoint-deletion.py |
# Copyright (C) 2020-2022 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# A TUI window implemented in Python.
import gdb
the_window = None
class TestWindow:
def __init__(self, win):
global the_window
the_window = self
self.count = 0
self.win = win
win.title = "This Is The Title"
def render(self):
self.win.erase()
w = self.win.width
h = self.win.height
self.win.write("Test: " + str(self.count) + " " + str(w) + "x" + str(h))
self.count = self.count + 1
# Tries to delete the title attribute. GDB will throw an error.
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()
# A TUI window "constructor" that always fails.
def failwin(win):
raise RuntimeError("Whoops")
gdb.register_window_type("fail", failwin)
| cuda-gdb-master | gdb/testsuite/gdb.python/tui-window.py |
# Copyright (C) 2016-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# 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
# some frames, leading to the possibility of a recursive invocation of
# this unwinder. If that should happen, code contained herein detects
# that and prints a message which will cause some of the associated
# tests to FAIL.
import gdb
from gdb.unwinder import Unwinder
class TestUnwinder(Unwinder):
count = 0
@classmethod
def reset_count(cls):
cls.count = 0
@classmethod
def inc_count(cls):
cls.count += 1
test = "check_undefined_symbol"
@classmethod
def set_test(cls, test):
cls.test = test
def __init__(self):
Unwinder.__init__(self, "test unwinder")
self.recurse_level = 0
def __call__(self, pending_frame):
if self.recurse_level > 0:
gdb.write("TestUnwinder: Recursion detected - returning early.\n")
return None
self.recurse_level += 1
TestUnwinder.inc_count()
if TestUnwinder.test == "check_user_reg_pc":
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":
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":
try:
val = gdb.parse_and_eval("undefined_symbol")
except Exception as arg:
pass
self.recurse_level -= 1
return None
gdb.unwinder.register_unwinder(None, TestUnwinder(), True)
gdb.write("Python script imported\n")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-recurse-unwind.py |
# Copyright (C) 2008-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests python pretty
# printers.
import re
import gdb
def _iterator(pointer, len):
start = pointer
end = pointer + len
while pointer != end:
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):
start = pointer
end = pointer + len
while pointer != end:
if exception_flag:
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):
def __init__(self, val):
self.val = val
def to_string(self):
return self.val["whybother"]["contents"]
# 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"])
def children(self):
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")
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):
def __init__(self, val):
self.val = val
def to_string(self):
return "array %s with %d elements" % (self.val["name"], self.val["len"])
def children(self):
return _iterator(self.val["elements"], self.val["len"])
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):
def __init__(self, val):
self.val = val
def to_string(self):
return None
def children(self):
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"]))
# 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"]
class pp_s(object):
def __init__(self, val):
self.val = val
def to_string(self):
a = self.val["a"]
b = self.val["b"]
if a.address != b:
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):
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):
def __init__(self, val):
self.val = val
def to_string(self):
return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">"
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"])
class pp_vbase1(object):
def __init__(self, val):
self.val = val
def to_string(self):
return "pp class name: " + self.val.type.tag
class pp_nullstr(object):
def __init__(self, val):
self.val = val
def to_string(self):
return self.val["s"].string(gdb.target_charset())
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)
def display_hint(self):
return "string"
pp_ls_encoding = None
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"]
if pp_ls_encoding is not None:
if length >= 0:
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)
else:
if length >= 0:
return self.val["lazy_str"].lazy_string(length=length)
else:
return self.val["lazy_str"].lazy_string()
def display_hint(self):
return "string"
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"
def display_hint(self):
raise Exception("hint failed")
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"
def children(self):
return [("one", 1)]
class pp_outer(object):
"Print struct outer"
def __init__(self, val):
self.val = val
def to_string(self):
return "x = %s" % self.val["x"]
def children(self):
yield "s", self.val["s"]
yield "x", self.val["x"]
class MemoryErrorString(object):
"Raise an error"
def __init__(self, val):
self.val = val
def to_string(self):
raise gdb.MemoryError("Cannot access memory.")
def display_hint(self):
return "string"
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)"))
+ ">"
)
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):
"A printer without a to_string method"
def __init__(self, val):
self.val = val
def children(self):
yield "s", 27
def lookup_function(val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# If it points to a reference, get the reference.
if type.code == gdb.TYPE_CODE_REF:
type = type.target()
# Get the unqualified type, stripped of typedefs.
type = type.unqualified().strip_typedefs()
# Get the type name.
typename = type.tag
if typename is None:
return None
# Iterate over local dictionary of types to determine
# 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)
# Cannot find a pretty printer. Return None.
return None
def disable_lookup_function():
lookup_function.enabled = False
def enable_lookup_function():
lookup_function.enabled = True
# Lookup a printer for VAL in the typedefs dict.
def lookup_typedefs_function(val):
"Look-up and return a pretty-printer that can print val (typedefs)."
# Get the type.
type = val.type
if type is None or type.name is None or type.code != gdb.TYPE_CODE_TYPEDEF:
return None
# Iterate over local dictionary of typedef types to determine if a
# 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)
# 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
# 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 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 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 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("^memory_error$")] = MemoryErrorString
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
# 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)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-prettyprint.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
from gdb.unwinder import Unwinder
# These are set to test whether invalid register names cause an error.
add_saved_register_error = False
read_register_error = False
class FrameId(object):
def __init__(self, sp, pc):
self._sp = sp
self._pc = pc
@property
def sp(self):
return self._sp
@property
def pc(self):
return self._pc
class TestUnwinder(Unwinder):
AMD64_RBP = 6
AMD64_RSP = 7
AMD64_RIP = None
def __init__(self):
Unwinder.__init__(self, "test unwinder")
self.char_ptr_t = gdb.lookup_type("unsigned char").pointer()
self.char_ptr_ptr_t = self.char_ptr_t.pointer()
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")
self._last_arch = arch
def _read_word(self, address):
return address.cast(self.char_ptr_ptr_t).dereference()
def __call__(self, pending_frame):
"""Test unwinder written in Python.
This unwinder can unwind the frames that have been deliberately
corrupted in a specific way (functions in the accompanying
py-unwind.c file do that.)
This code is only on AMD64.
On AMD64 $RBP points to the innermost frame (unless the code
was compiled with -fomit-frame-pointer), which contains the
address of the previous frame at offset 0. The functions
deliberately corrupt their frames as follows:
Before After
Corruption: Corruption:
+--------------+ +--------------+
RBP-8 | | | Previous RBP |
+--------------+ +--------------+
RBP + Previous RBP | | RBP |
+--------------+ +--------------+
RBP+8 | Return RIP | | Return RIP |
+--------------+ +--------------+
Old SP | | | |
This unwinder recognizes the corrupt frames by checking that
*RBP == RBP, and restores previous RBP from the word above it.
"""
# 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")
self._update_register_descriptors(frame_arch)
try:
# NOTE: the registers in Unwinder API can be referenced
# either by name or by number. The code below uses both
# to achieve more coverage.
bp = pending_frame.read_register("rbp").cast(self.char_ptr_t)
if self._read_word(bp) != bp:
return None
# Found the frame that the test program has corrupted for us.
# The correct BP for the outer frame has been saved one word
# above, previous IP and SP are at the expected places.
previous_bp = self._read_word(bp - 8)
previous_ip = self._read_word(bp + 8)
previous_sp = bp + 16
try:
pending_frame.read_register("nosuchregister")
except ValueError:
global read_register_error
read_register_error = True
frame_id = FrameId(
pending_frame.read_register(TestUnwinder.AMD64_RSP),
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("rip", previous_ip)
unwind_info.add_saved_register("rsp", previous_sp)
try:
unwind_info.add_saved_register("nosuchregister", previous_sp)
except ValueError:
global add_saved_register_error
add_saved_register_error = True
return unwind_info
except (gdb.error, RuntimeError):
return None
gdb.unwinder.register_unwinder(None, TestUnwinder(), True)
print("Python script imported")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-unwind.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
from gdb.unwinder import Unwinder
class FrameId(object):
def __init__(self, sp, pc):
self._sp = sp
self._pc = pc
@property
def sp(self):
return self._sp
@property
def pc(self):
return self._pc
class TestUnwinder(Unwinder):
def __init__(self):
Unwinder.__init__(self, "show level")
def __call__(self, pending_frame):
pc_desc = pending_frame.architecture().registers().find("pc")
pc = pending_frame.read_register(pc_desc)
block = gdb.block_for_pc(int(pc))
if block is None:
return None
func = block.function
if func is None:
return None
print("Func %s, Level %d" % (str(func), pending_frame.level()))
# This unwinder never claims any frames.
return None
gdb.unwinder.register_unwinder(None, TestUnwinder(), True)
| cuda-gdb-master | gdb/testsuite/gdb.python/py-pending-frame-level.py |
# Copyright (C) 2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class MytypePrinter:
"""pretty print my type"""
def __init__(self, val):
self.val = val
def to_string(self):
calls = gdb.parse_and_eval("f()")
return "mytype is %s" % self.val["x"]
def ec_lookup_function(val):
typ = val.type
if typ.code == gdb.TYPE_CODE_REF:
typ = typ.target()
if str(typ) == "struct mytype":
return MytypePrinter(val)
return None
def disable_lookup_function():
ec_lookup_function.enabled = False
def enable_lookup_function():
ec_lookup_function.enabled = True
gdb.pretty_printers.append(ec_lookup_function)
| cuda-gdb-master | gdb/testsuite/gdb.python/pretty-print-call-by-hand.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This script is auto-loaded when the py-auto-load-chaining-f2.o
# object is loaded.
print("Entering f2.o auto-load script")
print("Current objfile is: %s" % gdb.current_objfile().filename)
print("Leaving f2.o auto-load script")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-auto-load-chaining-f2.o-gdb.py |
# Copyright (C) 2014-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests Python-based
# frame-filters.
import gdb
import itertools
from gdb.FrameDecorator import FrameDecorator
import copy
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 not fname:
return None
if fname == "end_func":
extra = self.fobj.inferior_frame().read_var("str").string()
else:
extra = ""
fname = fname[::-1] + extra
return fname
class FrameFilter:
def __init__(self):
self.name = "Reverse"
self.priority = 100
self.enabled = True
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"):
frame_iter = itertools.imap(Reverse_Function, frame_iter)
else:
frame_iter = map(Reverse_Function, frame_iter)
return frame_iter
FrameFilter()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-framefilter-invalidarg.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests Python-based
# frame-filters.
import gdb
import itertools
from gdb.FrameDecorator import FrameDecorator
class FrameObjFile:
def __init__(self):
self.name = "Filter1"
self.priority = 1
self.enabled = False
gdb.current_progspace().frame_filters["Progspace" + self.name] = self
gdb.current_objfile().frame_filters["ObjectFile" + self.name] = self
def filter(self, frame_iter):
return frame_iter
class FrameObjFile2:
def __init__(self):
self.name = "Filter2"
self.priority = 100
self.enabled = True
gdb.current_progspace().frame_filters["Progspace" + self.name] = self
gdb.current_objfile().frame_filters["ObjectFile" + self.name] = self
def filter(self, frame_iter):
return frame_iter
FrameObjFile()
FrameObjFile2()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-framefilter-gdb.py |
# Copyright (C) 2019-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
class BadKey:
def __repr__(self):
return "Bad Key"
class ReallyBadKey:
def __repr__(self):
return BadKey()
class pycmd1(gdb.MICommand):
def invoke(self, argv):
if argv[0] == "int":
return {"result": 42}
elif argv[0] == "str":
return {"result": "Hello world!"}
elif argv[0] == "ary":
return {"result": ["Hello", 42]}
elif argv[0] == "dct":
return {"result": {"hello": "world", "times": 42}}
elif argv[0] == "bk1":
return {"result": {BadKey(): "world"}}
elif argv[0] == "bk2":
return {"result": {1: "world"}}
elif argv[0] == "bk3":
return {"result": {ReallyBadKey(): "world"}}
elif argv[0] == "tpl":
return {"result": (42, "Hello")}
elif argv[0] == "itr":
return {"result": iter([1, 2, 3])}
elif argv[0] == "nn1":
return None
elif argv[0] == "nn2":
return {"result": [None]}
elif argv[0] == "red":
pycmd2("-pycmd")
return None
elif argv[0] == "nd1":
return [1, 2, 3]
elif argv[0] == "nd2":
return 123
elif argv[0] == "nd3":
return "abc"
elif argv[0] == "ik1":
return {"xxx yyy": 123}
elif argv[0] == "ik2":
return {"result": {"xxx yyy": 123}}
elif argv[0] == "ik3":
return {"xxx+yyy": 123}
elif argv[0] == "ik4":
return {"xxx.yyy": 123}
elif argv[0] == "ik5":
return {"123xxxyyy": 123}
elif argv[0] == "empty_key":
return {"": 123}
elif argv[0] == "dash-key":
return {"the-key": 123}
elif argv[0] == "exp":
raise gdb.GdbError()
else:
raise gdb.GdbError("Invalid parameter: %s" % argv[0])
class pycmd2(gdb.MICommand):
def invoke(self, argv):
if argv[0] == "str":
return {"result": "Ciao!"}
elif argv[0] == "red":
pycmd1("-pycmd")
raise gdb.GdbError("Command redefined but we failing anyway")
elif argv[0] == "new":
pycmd1("-pycmd-new")
return None
else:
raise gdb.GdbError("Invalid parameter: %s" % argv[0])
# This class creates a command that returns a string, which is passed
# when the command is created.
class pycmd3(gdb.MICommand):
def __init__(self, name, msg, top_level):
super(pycmd3, self).__init__(name)
self._msg = msg
self._top_level = top_level
def invoke(self, args):
return {self._top_level: {"msg": self._msg}}
# A command that is missing it's invoke method.
class no_invoke(gdb.MICommand):
def __init__(self, name):
super(no_invoke, self).__init__(name)
def free_invoke(obj, args):
return {"result": args}
# Run some test involving catching exceptions. It's easier to write
# these as a Python function which is then called from the exp script.
def run_exception_tests():
print("PASS")
| cuda-gdb-master | gdb/testsuite/gdb.python/py-mi-cmd.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
import itertools
from gdb.FrameDecorator import FrameDecorator
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):
def __init__(self, fobj):
super(Function_Returns_Address, self).__init__(fobj)
self._fobj = fobj
def function(self):
frame = self.inferior_frame()
return frame.pc()
class Frame_Filter:
def __init__(self):
self.name = "function_returns_address"
self.priority = 100
self.enabled = True
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"):
frame_iter = itertools.imap(Function_Returns_Address, frame_iter)
else:
frame_iter = map(Function_Returns_Address, frame_iter)
return frame_iter
Frame_Filter()
| cuda-gdb-master | gdb/testsuite/gdb.python/py-framefilter-addr.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This file is part of the GDB testsuite. It tests that python pretty
# printers defined in a python script that is autoloaded have been
# registered when a custom event handler for the new_objfile event
# is called.
import gdb.printing
class MyClassTestLibPrinter(object):
"Print a MyClassTestLib"
def __init__(self, val):
self.val = val
def to_string(self):
return "MyClassTestLib object, id: {}".format(self.val["id"])
def display_hint(self):
return "string"
def build_pretty_printer():
pp = gdb.printing.RegexpCollectionPrettyPrinter("my_library")
pp.add_printer("MyClassTestLib", "^MyClassTestLib$", MyClassTestLibPrinter)
return pp
gdb.printing.register_pretty_printer(gdb.current_objfile(), build_pretty_printer())
| cuda-gdb-master | gdb/testsuite/gdb.python/libpy-autoloaded-pretty-printers-in-newobjfile-event.so-gdb.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This dummy unwinder will break GDB's backtrce at the function called
# 'break_bt_here'.
import gdb
from gdb.unwinder import Unwinder
class FrameId(object):
def __init__(self, sp, pc):
self._sp = sp
self._pc = pc
@property
def sp(self):
return self._sp
@property
def pc(self):
return self._pc
class TestUnwinder(Unwinder):
def __init__(self):
Unwinder.__init__(self, "break unwinding")
def __call__(self, pending_frame):
pc_desc = pending_frame.architecture().registers().find("pc")
pc = pending_frame.read_register(pc_desc)
sp_desc = pending_frame.architecture().registers().find("sp")
sp = pending_frame.read_register(sp_desc)
block = gdb.block_for_pc(int(pc))
if block is None:
return None
func = block.function
if func is None:
return None
if str(func) != "break_bt_here":
return None
fid = FrameId(pc, sp)
return pending_frame.create_unwind_info(fid)
gdb.unwinder.register_unwinder(None, TestUnwinder(), True)
| cuda-gdb-master | gdb/testsuite/gdb.base/premature-dummy-frame-removal.py |
# Copyright (C) 2021-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
from gdb.unwinder import Unwinder
# Set this to the stack level the backtrace should be corrupted at.
# This will only work for frame 1, 3, or 5 in the test this unwinder
# was written for.
stop_at_level = None
# Set this to the stack frame size of frames 1, 3, and 5. These
# frames will all have the same stack frame size as they are the same
# function called recursively.
stack_adjust = None
class FrameId(object):
def __init__(self, sp, pc):
self._sp = sp
self._pc = pc
@property
def sp(self):
return self._sp
@property
def pc(self):
return self._pc
class TestUnwinder(Unwinder):
def __init__(self):
Unwinder.__init__(self, "stop at level")
def __call__(self, pending_frame):
global stop_at_level
global stack_adjust
if stop_at_level is None or pending_frame.level() != stop_at_level:
return None
if stack_adjust is None:
raise gdb.GdbError("invalid stack_adjust")
if not stop_at_level in [1, 3, 5]:
raise gdb.GdbError("invalid stop_at_level")
sp_desc = pending_frame.architecture().registers().find("sp")
sp = pending_frame.read_register(sp_desc) + stack_adjust
pc = (gdb.lookup_symbol("normal_func"))[0].value().address
unwinder = pending_frame.create_unwind_info(FrameId(sp, pc))
for reg in pending_frame.architecture().registers("general"):
val = pending_frame.read_register(reg)
unwinder.add_saved_register(reg, val)
return unwinder
gdb.unwinder.register_unwinder(None, TestUnwinder(), True)
# When loaded, it is expected that the stack looks like:
#
# main -> normal_func -> inline_func -> normal_func -> inline_func -> normal_func -> inline_func
#
# Compute the stack frame size of normal_func, which has inline_func
# inlined within it.
f0 = gdb.newest_frame()
f1 = f0.older()
f2 = f1.older()
f0_sp = f0.read_register("sp")
f2_sp = f2.read_register("sp")
stack_adjust = f2_sp - f0_sp
| cuda-gdb-master | gdb/testsuite/gdb.base/inline-frame-cycle-unwind.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Test printing of std::cerr.
# libstdc++ is typically near the end of the list of shared libraries,
# and thus searched last (or near last).
# Plus llvm had a bug where its pubnames output that gold uses to generate
# the index caused a massive perf regression (basically it emitted an entry
# for every CU that used it, whereas we only want the CU with the
# definition).
#
# Note: One difference between this test and gmonster-ptype-string.py
# is that here we do not pre-expand the symtab: we don't want include
# GDB's slowness in searching expanded symtabs first to color these results.
from perftest import perftest
from perftest import measure
from perftest import utils
class PrintCerr(perftest.TestCaseWithBasicMeasurements):
def __init__(self, name, run_names, binfile):
super(PrintCerr, self).__init__(name)
self.run_names = run_names
self.binfile = binfile
def warm_up(self):
pass
def execute_test(self):
for run in self.run_names:
this_run_binfile = "%s-%s" % (self.binfile, utils.convert_spaces(run))
utils.select_file(this_run_binfile)
utils.runto_main()
iteration = 5
while iteration > 0:
utils.safe_execute("mt flush symbol-cache")
func = lambda: utils.safe_execute("print gm_std::cerr")
self.measure.measure(func, run)
iteration -= 1
| cuda-gdb-master | gdb/testsuite/gdb.perf/gmonster-print-cerr.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This test case is to test the speed of GDB when it is analyzing the
# function prologue.
from perftest import perftest
class SkipPrologue(perftest.TestCaseWithBasicMeasurements):
def __init__(self, count):
super(SkipPrologue, self).__init__("skip-prologue")
self.count = count
def _test(self):
for _ in range(1, self.count):
# Insert breakpoints on function f1 and f2.
bp1 = gdb.Breakpoint("f1")
bp2 = gdb.Breakpoint("f2")
# Remove them.
bp1.delete()
bp2.delete()
def warm_up(self):
self._test()
def execute_test(self):
for i in range(1, 4):
gdb.execute("set code-cache off")
gdb.execute("set code-cache on")
self.measure.measure(self._test, i)
| cuda-gdb-master | gdb/testsuite/gdb.perf/skip-prologue.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Measure performance of running to main.
from perftest import perftest
from perftest import measure
from perftest import utils
class GmonsterRuntoMain(perftest.TestCaseWithBasicMeasurements):
def __init__(self, name, run_names, binfile):
super(GmonsterRuntoMain, self).__init__(name)
self.run_names = run_names
self.binfile = binfile
def warm_up(self):
pass
def execute_test(self):
for run in self.run_names:
this_run_binfile = "%s-%s" % (self.binfile, utils.convert_spaces(run))
utils.select_file(this_run_binfile)
iteration = 5
while iteration > 0:
func = lambda: utils.runto_main()
self.measure.measure(func, run)
iteration -= 1
| cuda-gdb-master | gdb/testsuite/gdb.perf/gmonster-runto-main.py |
# Copyright (C) 2016-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from perftest import perftest
class SkipCommand(perftest.TestCaseWithBasicMeasurements):
def __init__(self, name, step):
super(SkipCommand, self).__init__(name)
self.step = step
def warm_up(self):
for _ in range(0, 10):
gdb.execute("step", False, True)
def _run(self, r):
for _ in range(0, r):
gdb.execute("step", False, True)
def execute_test(self):
for i in range(1, 5):
func = lambda: self._run(i * self.step)
self.measure.measure(func, i * self.step)
| cuda-gdb-master | gdb/testsuite/gdb.perf/skip-command.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from perftest import perftest
class SingleStep(perftest.TestCaseWithBasicMeasurements):
def __init__(self, step):
super(SingleStep, self).__init__("single-step")
self.step = step
def warm_up(self):
for _ in range(0, self.step):
gdb.execute("stepi", False, True)
def _run(self, r):
for _ in range(0, r):
gdb.execute("stepi", False, True)
def execute_test(self):
for i in range(1, 5):
func = lambda: self._run(i * self.step)
self.measure.measure(func, i * self.step)
| cuda-gdb-master | gdb/testsuite/gdb.perf/single-step.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Measure speed of ptype of a std::string object.
# The difference between this test and gmonster-print-cerr.py is that
# here we are working with fully expanded symtabs. GDB searches
# these before it searches the index (there is work-in-progress to fix this),
# this test helps measure the issue.
from perftest import perftest
from perftest import measure
from perftest import utils
class GmonsterPtypeString(perftest.TestCaseWithBasicMeasurements):
def __init__(self, name, run_names, binfile):
super(GmonsterPtypeString, self).__init__(name)
self.run_names = run_names
self.binfile = binfile
def warm_up(self):
pass
def execute_test(self):
for run in self.run_names:
this_run_binfile = "%s-%s" % (self.binfile, utils.convert_spaces(run))
utils.select_file(this_run_binfile)
utils.runto_main()
utils.safe_execute("mt expand-symtabs")
iteration = 5
while iteration > 0:
utils.safe_execute("mt flush symbol-cache")
func1 = lambda: utils.safe_execute("ptype hello")
func = lambda: utils.run_n_times(2, func1)
self.measure.measure(func, run)
iteration -= 1
| cuda-gdb-master | gdb/testsuite/gdb.perf/gmonster-ptype-string.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Measure the speed of "ptype func" where a parameter of the function is a
# typedef used pervasively. This exercises the perf regression introduced by
# the original patch to pr 16253.
from perftest import perftest
from perftest import measure
from perftest import utils
class PervasiveTypedef(perftest.TestCaseWithBasicMeasurements):
def __init__(self, name, run_names, binfile):
# We want to measure time in this test.
super(PervasiveTypedef, self).__init__(name)
self.run_names = run_names
self.binfile = binfile
def warm_up(self):
pass
def func(self):
utils.select_file(self.this_run_binfile)
utils.safe_execute("ptype call_use_my_int_1")
def execute_test(self):
for run in self.run_names:
self.this_run_binfile = "%s-%s" % (self.binfile, utils.convert_spaces(run))
iteration = 5
while iteration > 0:
self.measure.measure(self.func, run)
iteration -= 1
| cuda-gdb-master | gdb/testsuite/gdb.perf/gmonster-pervasive-typedef.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Measure performance of selecting a file to debug.
from perftest import perftest
from perftest import measure
from perftest import utils
class GmonsterSelectFile(perftest.TestCaseWithBasicMeasurements):
def __init__(self, name, run_names, binfile):
super(GmonsterSelectFile, self).__init__(name)
self.run_names = run_names
self.binfile = binfile
def warm_up(self):
pass
def _doit(self, binfile):
utils.select_file(None)
utils.select_file(binfile)
def execute_test(self):
for run in self.run_names:
this_run_binfile = "%s-%s" % (self.binfile, utils.convert_spaces(run))
iteration = 5
while iteration > 0:
func = lambda: self._doit(this_run_binfile)
self.measure.measure(func, run)
iteration -= 1
| cuda-gdb-master | gdb/testsuite/gdb.perf/gmonster-select-file.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from perftest import perftest
class Disassemble(perftest.TestCaseWithBasicMeasurements):
def __init__(self):
super(Disassemble, self).__init__("disassemble")
def warm_up(self):
do_test_command = "disassemble evaluate_subexp_do_call"
gdb.execute(do_test_command, False, True)
def _do_test(self, c):
for func in [
"captured_main",
"handle_inferior_event",
"run_inferior_call",
"update_global_location_list",
]:
do_test_command = "disassemble %s" % func
for _ in range(c + 1):
gdb.execute(do_test_command, False, True)
def execute_test(self):
for i in range(3):
# Flush code cache.
gdb.execute("set code-cache off")
gdb.execute("set code-cache on")
self.measure.measure(lambda: self._do_test(i), i)
| cuda-gdb-master | gdb/testsuite/gdb.perf/disassemble.py |
# Copyright (C) 2018-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from perftest import perftest
class TemplateBreakpoints(perftest.TestCaseWithBasicMeasurements):
def __init__(self):
super(TemplateBreakpoints, self).__init__("template-breakpoints")
def warm_up(self):
for _ in range(0, 2):
gdb.Breakpoint("template-breakpoints.cc:38").delete()
def _do_test(self, bpcount):
for _ in range(1, bpcount):
gdb.Breakpoint("template-breakpoints.cc:38").delete()
def execute_test(self):
for bpcount in range(1, 10):
tfunc = lambda bound_bpcount=bpcount: self._do_test(bound_bpcount)
self.measure.measure(tfunc, bpcount)
| cuda-gdb-master | gdb/testsuite/gdb.perf/template-breakpoints.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Test handling of lookup of a symbol that doesn't exist.
# Efficient handling of this case is important, and not just for typos.
# Sometimes the debug info for the needed object isn't present.
from perftest import perftest
from perftest import measure
from perftest import utils
class NullLookup(perftest.TestCaseWithBasicMeasurements):
def __init__(self, name, run_names, binfile):
# We want to measure time in this test.
super(NullLookup, self).__init__(name)
self.run_names = run_names
self.binfile = binfile
def warm_up(self):
pass
def execute_test(self):
for run in self.run_names:
this_run_binfile = "%s-%s" % (self.binfile, utils.convert_spaces(run))
utils.select_file(this_run_binfile)
utils.runto_main()
utils.safe_execute("mt expand-symtabs")
iteration = 5
while iteration > 0:
utils.safe_execute("mt flush symbol-cache")
func = lambda: utils.safe_execute("p symbol_not_found")
self.measure.measure(func, run)
iteration -= 1
| cuda-gdb-master | gdb/testsuite/gdb.perf/gmonster-null-lookup.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from perftest import perftest
class BackTrace(perftest.TestCaseWithBasicMeasurements):
def __init__(self, depth):
super(BackTrace, self).__init__("backtrace")
self.depth = depth
def warm_up(self):
# Warm up.
gdb.execute("bt", False, True)
gdb.execute("bt", False, True)
def _do_test(self):
"""Do backtrace multiple times."""
do_test_command = "bt %d" % self.depth
for _ in range(1, 15):
gdb.execute(do_test_command, False, True)
def execute_test(self):
line_size = 2
for _ in range(1, 12):
# Keep the total size of dcache unchanged, and increase the
# line-size in the loop.
line_size_command = "set dcache line-size %d" % (line_size)
size_command = "set dcache size %d" % (4096 * 64 / line_size)
# Cache is cleared by changing line-size or size.
gdb.execute(line_size_command)
gdb.execute(size_command)
func = lambda: self._do_test()
self.measure.measure(func, line_size)
line_size *= 2
| cuda-gdb-master | gdb/testsuite/gdb.perf/backtrace.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This test case is to test the speed of GDB when it is handling the
# shared libraries of inferior are loaded and unloaded.
from perftest import perftest
from perftest import measure
class SolibLoadUnload1(perftest.TestCaseWithBasicMeasurements):
def __init__(self, solib_count, measure_load):
if measure_load:
name = "solib_load"
else:
name = "solib_unload"
# We want to measure time in this test.
super(SolibLoadUnload1, self).__init__(name)
self.solib_count = solib_count
self.measure_load = measure_load
def warm_up(self):
do_test_load = "call do_test_load (%d)" % self.solib_count
do_test_unload = "call do_test_unload (%d)" % self.solib_count
gdb.execute(do_test_load)
gdb.execute(do_test_unload)
def execute_test(self):
num = self.solib_count
iteration = 5
while num > 0 and iteration > 0:
# Do inferior calls to do_test_load and do_test_unload in pairs,
# but measure differently.
if self.measure_load:
do_test_load = "call do_test_load (%d)" % num
func = lambda: gdb.execute(do_test_load)
self.measure.measure(func, num)
do_test_unload = "call do_test_unload (%d)" % num
gdb.execute(do_test_unload)
else:
do_test_load = "call do_test_load (%d)" % num
gdb.execute(do_test_load)
do_test_unload = "call do_test_unload (%d)" % num
func = lambda: gdb.execute(do_test_unload)
self.measure.measure(func, num)
num = num / 2
iteration -= 1
class SolibLoadUnload(object):
def __init__(self, solib_count):
self.solib_count = solib_count
def run(self):
SolibLoadUnload1(self.solib_count, True).run()
SolibLoadUnload1(self.solib_count, False).run()
| cuda-gdb-master | gdb/testsuite/gdb.perf/solib.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
import os
import gc
import sys
# time.perf_counter() and time.process_time() were added in Python
# 3.3, time.clock() was removed in Python 3.8.
if sys.version_info < (3, 3, 0):
time.perf_counter = time.clock
time.process_time = time.clock
class Measure(object):
"""A class that measure and collect the interesting data for a given testcase.
An instance of Measure has a collection of measurements, and each
of them is to measure a given aspect, such as time and memory.
"""
def __init__(self, measurements):
"""Constructor of measure.
measurements is a collection of Measurement objects.
"""
self.measurements = measurements
def measure(self, func, id):
"""Measure the operations done by func with a collection of measurements."""
# Enable GC, force GC and disable GC before running test in order to reduce
# the interference from GC.
gc.enable()
gc.collect()
gc.disable()
for m in self.measurements:
m.start(id)
func()
for m in self.measurements:
m.stop(id)
gc.enable()
def report(self, reporter, name):
"""Report the measured results."""
for m in self.measurements:
m.report(reporter, name)
class Measurement(object):
"""A measurement for a certain aspect."""
def __init__(self, name, result):
"""Constructor of Measurement.
Attribute result is the TestResult associated with measurement.
"""
self.name = name
self.result = result
def start(self, id):
"""Abstract method to start the measurement."""
raise NotImplementedError("Abstract Method:start")
def stop(self, id):
"""Abstract method to stop the measurement.
When the measurement is stopped, we've got something, and
record them in result.
"""
raise NotImplementedError("Abstract Method:stop.")
def report(self, reporter, name):
"""Report the measured data by argument reporter."""
self.result.report(reporter, name + " " + self.name)
class MeasurementPerfCounter(Measurement):
"""Measurement on performance counter."""
# Measures time in fractional seconds, using a performance
# counter, i.e. a clock with the highest available resolution to
# measure a short duration. It includes time elapsed during sleep
# and is system-wide.
def __init__(self, result):
super(MeasurementPerfCounter, self).__init__("perf_counter", result)
self.start_time = 0
def start(self, id):
self.start_time = time.perf_counter()
def stop(self, id):
perf_counter = time.perf_counter() - self.start_time
self.result.record(id, perf_counter)
class MeasurementProcessTime(Measurement):
"""Measurement on process time."""
# Measures the sum of the system and user CPU time of the current
# process. Does not include time elapsed during sleep. It is
# process-wide by definition.
def __init__(self, result):
super(MeasurementProcessTime, self).__init__("process_time", result)
self.start_time = 0
def start(self, id):
self.start_time = time.process_time()
def stop(self, id):
process_time = time.process_time() - self.start_time
self.result.record(id, process_time)
class MeasurementWallTime(Measurement):
"""Measurement on Wall time."""
def __init__(self, result):
super(MeasurementWallTime, self).__init__("wall_time", result)
self.start_time = 0
def start(self, id):
self.start_time = time.time()
def stop(self, id):
wall_time = time.time() - self.start_time
self.result.record(id, wall_time)
class MeasurementVmSize(Measurement):
"""Measurement on memory usage represented by VmSize."""
def __init__(self, result):
super(MeasurementVmSize, self).__init__("vmsize", result)
def _compute_process_memory_usage(self, key):
file_path = "/proc/%d/status" % os.getpid()
try:
t = open(file_path)
v = t.read()
t.close()
except:
return 0
i = v.index(key)
v = v[i:].split(None, 3)
if len(v) < 3:
return 0
return int(v[1])
def start(self, id):
pass
def stop(self, id):
memory_used = self._compute_process_memory_usage("VmSize:")
self.result.record(id, memory_used)
| cuda-gdb-master | gdb/testsuite/gdb.perf/lib/perftest/measure.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
import perftest.testresult as testresult
import perftest.reporter as reporter
from perftest.measure import Measure
from perftest.measure import MeasurementPerfCounter
from perftest.measure import MeasurementProcessTime
from perftest.measure import MeasurementWallTime
from perftest.measure import MeasurementVmSize
class TestCase(object):
"""Base class of all performance testing cases.
Each sub-class should override methods execute_test, in which
several GDB operations are performed and measured by attribute
measure. Sub-class can also override method warm_up optionally
if the test case needs warm up.
"""
def __init__(self, name, measure):
"""Constructor of TestCase.
Construct an instance of TestCase with a name and a measure
which is to measure the test by several different measurements.
"""
self.name = name
self.measure = measure
def execute_test(self):
"""Abstract method to do the actual tests."""
raise NotImplementedError("Abstract Method.")
def warm_up(self):
"""Do some operations to warm up the environment."""
pass
def run(self, warm_up=True, append=True):
"""Run this test case.
It is a template method to invoke method warm_up,
execute_test, and finally report the measured results.
If parameter warm_up is True, run method warm_up. If parameter
append is True, the test result will be appended instead of
overwritten.
"""
if warm_up:
self.warm_up()
self.execute_test()
self.measure.report(reporter.TextReporter(append), self.name)
class TestCaseWithBasicMeasurements(TestCase):
"""Test case measuring CPU time, wall time and memory usage."""
def __init__(self, name):
result_factory = testresult.SingleStatisticResultFactory()
measurements = [
MeasurementPerfCounter(result_factory.create_result()),
MeasurementProcessTime(result_factory.create_result()),
MeasurementWallTime(result_factory.create_result()),
MeasurementVmSize(result_factory.create_result()),
]
super(TestCaseWithBasicMeasurements, self).__init__(name, Measure(measurements))
| cuda-gdb-master | gdb/testsuite/gdb.perf/lib/perftest/perftest.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Text reports are written here.
# This is the perftest counterpart to gdb.sum.
SUM_FILE_NAME = "perftest.sum"
# Raw data that went into the report is written here.
# This is the perftest counterpart to gdb.log.
LOG_FILE_NAME = "perftest.log"
class Reporter(object):
"""Base class of reporter to report test results in a certain format.
Subclass, which is specific to a report format, should overwrite
methods report, start and end.
"""
def __init__(self, append):
"""Constructor of Reporter.
attribute append is used to determine whether to append or
overwrite log file.
"""
self.append = append
def report(self, *args):
raise NotImplementedError("Abstract Method:report.")
def start(self):
"""Invoked when reporting is started."""
raise NotImplementedError("Abstract Method:start.")
def end(self):
"""Invoked when reporting is done.
It must be overridden to do some cleanups, such as closing file
descriptors.
"""
raise NotImplementedError("Abstract Method:end.")
class TextReporter(Reporter):
"""Report results in a plain text file 'perftest.log'."""
def __init__(self, append):
super(TextReporter, self).__init__(Reporter(append))
self.txt_sum = None
self.txt_log = None
def report(self, test_name, measurement_name, data_points):
if len(data_points) == 0:
self.txt_sum.write(
"%s %s *no data recorded*\n" % (test_name, measurement_name)
)
return
average = sum(data_points) / len(data_points)
data_min = min(data_points)
data_max = max(data_points)
self.txt_sum.write("%s %s %s\n" % (test_name, measurement_name, average))
self.txt_log.write(
"%s %s %s, min %s, max %s, data %s\n"
% (test_name, measurement_name, average, data_min, data_max, data_points)
)
def start(self):
mode = "a+" if self.append else "w"
self.txt_sum = open(SUM_FILE_NAME, mode)
self.txt_log = open(LOG_FILE_NAME, mode)
def end(self):
self.txt_sum.close()
self.txt_log.close()
| cuda-gdb-master | gdb/testsuite/gdb.perf/lib/perftest/reporter.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
GDB performance testing framework.
"""
| cuda-gdb-master | gdb/testsuite/gdb.perf/lib/perftest/__init__.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class TestResult(object):
"""Base class to record and report test results.
Method record is to record the results of test case, and report
method is to report the recorded results by a given reporter.
"""
def record(self, parameter, result):
raise NotImplementedError("Abstract Method:record.")
def report(self, reporter, name):
"""Report the test results by reporter."""
raise NotImplementedError("Abstract Method:report.")
class SingleStatisticTestResult(TestResult):
"""Test results for the test case with a single statistic."""
def __init__(self):
super(SingleStatisticTestResult, self).__init__()
self.results = dict()
def record(self, parameter, result):
if parameter in self.results:
self.results[parameter].append(result)
else:
self.results[parameter] = [result]
def report(self, reporter, name):
reporter.start()
for key in sorted(self.results.keys()):
reporter.report(name, key, self.results[key])
reporter.end()
class ResultFactory(object):
"""A factory to create an instance of TestResult."""
def create_result(self):
"""Create an instance of TestResult."""
raise NotImplementedError("Abstract Method:create_result.")
class SingleStatisticResultFactory(ResultFactory):
"""A factory to create an instance of SingleStatisticTestResult."""
def create_result(self):
return SingleStatisticTestResult()
| cuda-gdb-master | gdb/testsuite/gdb.perf/lib/perftest/testresult.py |
# Copyright (C) 2015-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gdb
def safe_execute(command):
"""Execute command, ignoring any gdb errors."""
result = None
try:
result = gdb.execute(command, to_string=True)
except gdb.error:
pass
return result
def convert_spaces(file_name):
"""Return file_name with all spaces replaced with "-"."""
return file_name.replace(" ", "-")
def select_file(file_name):
"""Select a file for debugging.
N.B. This turns confirmation off.
"""
safe_execute("set confirm off")
safe_execute("kill")
print("Selecting file %s" % (file_name))
if file_name is None:
gdb.execute("file")
else:
gdb.execute("file %s" % (file_name))
def runto(location):
"""Run the program to location.
N.B. This turns confirmation off.
"""
safe_execute("set confirm off")
gdb.execute("tbreak %s" % (location))
gdb.execute("run")
def runto_main():
"""Run the program to "main".
N.B. This turns confirmation off.
"""
runto("main")
def run_n_times(count, func):
"""Execute func count times."""
while count > 0:
func()
count -= 1
| cuda-gdb-master | gdb/testsuite/gdb.perf/lib/perftest/utils.py |
#! /usr/bin/env python3
# Copyright (C) 2011-2022 Free Software Foundation, Inc.
#
# This file is part of GDB.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This program requires readelf, gdb and objcopy. The default values are gdb
# from the build tree and objcopy and readelf from $PATH. They may be
# overridden by setting environment variables GDB, READELF and OBJCOPY
# respectively. We assume the current directory is either $obj/gdb or
# $obj/gdb/testsuite.
#
# Example usage:
#
# bash$ cd $objdir/gdb/testsuite
# bash$ python test_pubnames_and_indexes.py <binary_name>
"""test_pubnames_and_indexes.py
Test that the gdb_index produced by gold is identical to the gdb_index
produced by gdb itself.
Further check that the pubnames and pubtypes produced by gcc are identical
to those that gdb produces.
Finally, check that all strings are canonicalized identically.
"""
__author__ = "[email protected] (Sterling Augustine)"
import os
import subprocess
import sys
OBJCOPY = None
READELF = None
GDB = None
def get_pub_info(filename, readelf_option):
"""Parse and return all the pubnames or pubtypes produced by readelf with the
given option.
"""
readelf = subprocess.Popen(
[READELF, "--debug-dump=" + readelf_option, filename], stdout=subprocess.PIPE
)
pubnames = []
in_list = False
for line in readelf.stdout:
fields = line.split(None, 1)
if len(fields) == 2 and fields[0] == "Offset" and fields[1].strip() == "Name":
in_list = True
# Either a blank-line or a new Length field terminates the current section.
elif len(fields) == 0 or fields[0] == "Length:":
in_list = False
elif in_list:
pubnames.append(fields[1].strip())
readelf.wait()
return pubnames
def get_gdb_index(filename):
"""Use readelf to dump the gdb index and collect the types and names"""
readelf = subprocess.Popen(
[READELF, "--debug-dump=gdb_index", filename], stdout=subprocess.PIPE
)
index_symbols = []
symbol_table_started = False
for line in readelf.stdout:
if line == "Symbol table:\n":
symbol_table_started = True
elif symbol_table_started:
# Readelf prints gdb-index lines formatted like so:
# [ 4] two::c2<double>::c2: 0
# So take the string between the first close bracket and the last colon.
index_symbols.append(line[line.find("]") + 2 : line.rfind(":")])
readelf.wait()
return index_symbols
def CheckSets(list0, list1, name0, name1):
"""Report any setwise differences between the two lists"""
if len(list0) == 0 or len(list1) == 0:
return False
difference0 = set(list0) - set(list1)
if len(difference0) != 0:
print("Elements in " + name0 + " but not " + name1 + ": (", end=" ")
print(len(difference0), end=" ")
print(")")
for element in difference0:
print(" " + element)
difference1 = set(list1) - set(list0)
if len(difference1) != 0:
print("Elements in " + name1 + " but not " + name0 + ": (", end=" ")
print(len(difference1), end=" ")
print(")")
for element in difference1:
print(" " + element)
if len(difference0) != 0 or len(difference1) != 0:
return True
print(name0 + " and " + name1 + " are identical.")
return False
def find_executables():
"""Find the copies of readelf, objcopy and gdb to use."""
# Executable finding logic follows cc-with-index.sh
global READELF
READELF = os.getenv("READELF")
if READELF is None:
READELF = "readelf"
global OBJCOPY
OBJCOPY = os.getenv("OBJCOPY")
if OBJCOPY is None:
OBJCOPY = "objcopy"
global GDB
GDB = os.getenv("GDB")
if GDB is None:
if os.path.isfile("./gdb") and os.access("./gdb", os.X_OK):
GDB = "./gdb"
elif os.path.isfile("../gdb") and os.access("../gdb", os.X_OK):
GDB = "../gdb"
elif os.path.isfile("../../gdb") and os.access("../../gdb", os.X_OK):
GDB = "../../gdb"
else:
# Punt and use the gdb in the path.
GDB = "gdb"
def main(argv):
"""The main subprogram."""
if len(argv) != 2:
print("Usage: test_pubnames_and_indexes.py <filename>")
sys.exit(2)
find_executables()
# Get the index produced by Gold--It should have been built into the binary.
gold_index = get_gdb_index(argv[1])
# Collect the pubnames and types list
pubs_list = get_pub_info(argv[1], "pubnames")
pubs_list = pubs_list + get_pub_info(argv[1], "pubtypes")
# Generate a .gdb_index with gdb
gdb_index_file = argv[1] + ".gdb-generated-index"
subprocess.check_call(
[OBJCOPY, "--remove-section", ".gdb_index", argv[1], gdb_index_file]
)
subprocess.check_call(
[
GDB,
"-batch",
"-nx",
gdb_index_file,
"-ex",
"save gdb-index " + os.path.dirname(argv[1]),
"-ex",
"quit",
]
)
subprocess.check_call(
[
OBJCOPY,
"--add-section",
".gdb_index=" + gdb_index_file + ".gdb-index",
gdb_index_file,
]
)
gdb_index = get_gdb_index(gdb_index_file)
os.remove(gdb_index_file)
os.remove(gdb_index_file + ".gdb-index")
failed = False
gdb_index.sort()
gold_index.sort()
pubs_list.sort()
# Find the differences between the various indices.
if len(gold_index) == 0:
print("Gold index is empty")
failed |= True
if len(gdb_index) == 0:
print("Gdb index is empty")
failed |= True
if len(pubs_list) == 0:
print("Pubs list is empty")
failed |= True
failed |= CheckSets(gdb_index, gold_index, "gdb index", "gold index")
failed |= CheckSets(pubs_list, gold_index, "pubs list", "gold index")
failed |= CheckSets(pubs_list, gdb_index, "pubs list", "gdb index")
if failed:
print("Test failed")
sys.exit(1)
if __name__ == "__main__":
main(sys.argv)
| cuda-gdb-master | gdb/contrib/test_pubnames_and_indexes.py |
# Copyright (C) 2011-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Configure GDB using the ELinOS environment."""
import os
import glob
import gdb
def warn(msg):
print("warning: %s" % msg)
def get_elinos_environment():
"""Return the ELinOS environment.
If the ELinOS environment is properly set up, return a dictionary
which contains:
* The path to the ELinOS project at key 'project';
* The path to the ELinOS CDK at key 'cdk';
* The ELinOS target name at key 'target' (Eg. 'i486-linux');
* A list of Xenomai install prefixes (which could be empty, if
the ELinOS project does not include Xenomai) at key 'xenomai'.
If one of these cannot be found, print a warning; the corresponding
value in the returned dictionary will be None.
"""
result = {}
for key in ("project", "cdk", "target"):
var = "ELINOS_" + key.upper()
if var in os.environ:
result[key] = os.environ[var]
else:
warn("%s not set" % var)
result[key] = None
if result["project"] is not None:
result["xenomai"] = glob.glob(result["project"] + "/xenomai-[0-9.]*")
else:
result["xenomai"] = []
return result
def elinos_init():
"""Initialize debugger environment for ELinOS.
Let the debugger know where to find the ELinOS libraries on host. This
assumes that an ELinOS environment is properly set up. If some environment
variables are missing, warn about which library may be missing.
"""
elinos_env = get_elinos_environment()
solib_dirs = []
# System libraries
if None in (elinos_env[key] for key in ("cdk", "target")):
warn("ELinOS system libraries will not be loaded")
else:
solib_prefix = "%s/%s" % (elinos_env["cdk"], elinos_env["target"])
solib_dirs += ["%s/%s" % (solib_prefix, "lib")]
gdb.execute("set solib-absolute-prefix %s" % solib_prefix)
# Xenomai libraries. Those are optional, so have a lighter warning
# if they cannot be located.
if elinos_env["project"] is None:
warn("Xenomai libraries may not be loaded")
else:
for dir in elinos_env["xenomai"]:
solib_dirs += ["%s/%s" % (dir, "xenomai-build/usr/realtime/lib")]
if len(solib_dirs) != 0:
gdb.execute("set solib-search-path %s" % ":".join(solib_dirs))
if __name__ == "__main__":
elinos_init()
| cuda-gdb-master | gdb/system-gdbinit/elinos.py |
# Copyright (C) 2011-2022 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Configure GDB using the WRS/Linux environment."""
import os
if "ENV_PREFIX" in os.environ:
gdb.execute("set sysroot %s" % os.environ["ENV_PREFIX"])
else:
print("warning: ENV_PREFIX environment variable missing.")
print("The debugger will probably be unable to find the correct system libraries")
| cuda-gdb-master | gdb/system-gdbinit/wrs-linux.py |
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
import sys
import re
import time
infname = sys.argv[1]
inf = file(infname)
print(
"""\
<?xml version="1.0"?>
<!-- Copyright (C) 2009-%s Free Software Foundation, Inc.
Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved. This file is offered as-is,
without any warranty. -->
<!DOCTYPE feature SYSTEM "gdb-syscalls.dtd">
<!-- This file was generated using the following file:
%s
The file mentioned above belongs to the Linux Kernel.
Some small hand-edits were made. -->
<syscalls_info>"""
% (time.strftime("%Y"), infname)
)
def record(name, number, comment=None):
# nm = 'name="%s"' % name
# s = ' <syscall %-30s number="%d"/>' % (nm, number)
s = ' <syscall name="%s" number="%d"/>' % (name, number)
if comment:
s += " <!-- %s -->" % comment
print(s)
for line in inf:
m = re.match(r"^#define __NR_(\w+)\s+\(__NR_SYSCALL_BASE\+\s*(\d+)\)", line)
if m:
record(m.group(1), int(m.group(2)))
continue
m = re.match(r"^\s+/\* (\d+) was sys_(\w+) \*/$", line)
if m:
record(m.group(2), int(m.group(1)), "removed")
m = re.match(r"^#define __ARM_NR_(\w+)\s+\(__ARM_NR_BASE\+\s*(\d+)\)", line)
if m:
record("ARM_" + m.group(1), 0x0F0000 + int(m.group(2)))
continue
print("</syscalls_info>")
| cuda-gdb-master | gdb/syscalls/arm-linux.py |
#!/usr/bin/python
#
# Copyright (C) 2013-2022 Free Software Foundation, Inc.
#
# This script is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
# This script adjusts the copyright notices at the top of source files
# so that they have the form:
#
# Copyright XXXX-YYYY Free Software Foundation, Inc.
#
# It doesn't change code that is known to be maintained elsewhere or
# that carries a non-FSF copyright.
#
# Pass --this-year to the script if you want it to add the current year
# to all applicable notices. Pass --quilt if you are using quilt and
# want files to be added to the quilt before being changed.
#
# By default the script will update all directories for which the
# output has been vetted. You can instead pass the names of individual
# directories, including those that haven't been approved. So:
#
# update-copyright.pl --this-year
#
# is the command that would be used at the beginning of a year to update
# all copyright notices (and possibly at other times to check whether
# new files have been added with old years). On the other hand:
#
# update-copyright.pl --this-year libjava
#
# would run the script on just libjava/.
#
# This script was copied from gcc's contrib/ and modified to suit
# binutils. In contrast to the gcc script, this one will update
# the testsuite and --version output strings too.
import os
import re
import sys
import time
import subprocess
class Errors:
def __init__ (self):
self.num_errors = 0
def report (self, filename, string):
if filename:
string = filename + ': ' + string
sys.stderr.write (string + '\n')
self.num_errors += 1
def ok (self):
return self.num_errors == 0
class GenericFilter:
def __init__ (self):
self.skip_files = set()
self.skip_dirs = set()
self.skip_extensions = set()
self.fossilised_files = set()
self.own_files = set()
self.skip_files |= set ([
# Skip licence files.
'COPYING',
'COPYING.LIB',
'COPYING3',
'COPYING3.LIB',
'COPYING.LIBGLOSS',
'COPYING.NEWLIB',
'LICENSE',
'fdl.texi',
'gpl_v3.texi',
'fdl-1.3.xml',
'gpl-3.0.xml',
# Skip auto- and libtool-related files
'aclocal.m4',
'compile',
'config.guess',
'config.sub',
'depcomp',
'install-sh',
'libtool.m4',
'ltmain.sh',
'ltoptions.m4',
'ltsugar.m4',
'ltversion.m4',
'lt~obsolete.m4',
'missing',
'mkdep',
'mkinstalldirs',
'move-if-change',
'shlibpath.m4',
'symlink-tree',
'ylwrap',
# Skip FSF mission statement, etc.
'gnu.texi',
'funding.texi',
'appendix_free.xml',
# Skip imported texinfo files.
'texinfo.tex',
])
self.skip_extensions |= set ([
# Maintained by the translation project.
'.po',
# Automatically-generated.
'.pot',
])
self.skip_dirs |= set ([
'autom4te.cache',
])
def get_line_filter (self, dir, filename):
if filename.startswith ('ChangeLog'):
# Ignore references to copyright in changelog entries.
return re.compile ('\t')
return None
def skip_file (self, dir, filename):
if filename in self.skip_files:
return True
(base, extension) = os.path.splitext (os.path.join (dir, filename))
if extension in self.skip_extensions:
return True
if extension == '.in':
# Skip .in files produced by automake.
if os.path.exists (base + '.am'):
return True
# Skip files produced by autogen
if (os.path.exists (base + '.def')
and os.path.exists (base + '.tpl')):
return True
# Skip configure files produced by autoconf
if filename == 'configure':
if os.path.exists (base + '.ac'):
return True
if os.path.exists (base + '.in'):
return True
return False
def skip_dir (self, dir, subdir):
return subdir in self.skip_dirs
def is_fossilised_file (self, dir, filename):
if filename in self.fossilised_files:
return True
# Only touch current current ChangeLogs.
if filename != 'ChangeLog' and filename.find ('ChangeLog') >= 0:
return True
return False
def by_package_author (self, dir, filename):
return filename in self.own_files
class Copyright:
def __init__ (self, errors):
self.errors = errors
# Characters in a range of years. Include '.' for typos.
ranges = '[0-9](?:[-0-9.,\s]|\s+and\s+)*[0-9]'
# Non-whitespace characters in a copyright holder's name.
name = '[\w.,-]'
# Matches one year.
self.year_re = re.compile ('[0-9]+')
# Matches part of a year or copyright holder.
self.continuation_re = re.compile (ranges + '|' + name)
# Matches a full copyright notice:
self.copyright_re = re.compile (
# 1: 'Copyright (C)', etc.
'([Cc]opyright'
'|[Cc]opyright\s+\([Cc]\)'
'|[Cc]opyright\s+%s'
'|[Cc]opyright\s+©'
'|[Cc]opyright\s+@copyright{}'
'|@set\s+copyright[\w-]+)'
# 2: the years. Include the whitespace in the year, so that
# we can remove any excess.
'(\s*(?:' + ranges + ',?'
'|@value\{[^{}]*\})\s*)'
# 3: 'by ', if used
'(by\s+)?'
# 4: the copyright holder. Don't allow multiple consecutive
# spaces, so that right-margin gloss doesn't get caught
# (e.g. gnat_ugn.texi).
'(' + name + '(?:\s?' + name + ')*)?')
# A regexp for notices that might have slipped by. Just matching
# 'copyright' is too noisy, and 'copyright.*[0-9]' falls foul of
# HTML header markers, so check for 'copyright' and two digits.
self.other_copyright_re = re.compile ('(^|[^\._])copyright[^=]*[0-9][0-9]',
re.IGNORECASE)
self.comment_re = re.compile('#+|[*]+|;+|%+|//+|@c |dnl ')
self.holders = { '@copying': '@copying' }
self.holder_prefixes = set()
# True to 'quilt add' files before changing them.
self.use_quilt = False
# If set, force all notices to include this year.
self.max_year = None
# Goes after the year(s). Could be ', '.
self.separator = ' '
def add_package_author (self, holder, canon_form = None):
if not canon_form:
canon_form = holder
self.holders[holder] = canon_form
index = holder.find (' ')
while index >= 0:
self.holder_prefixes.add (holder[:index])
index = holder.find (' ', index + 1)
def add_external_author (self, holder):
self.holders[holder] = None
class BadYear():
def __init__ (self, year):
self.year = year
def __str__ (self):
return 'unrecognised year: ' + self.year
def parse_year (self, string):
year = int (string)
if len (string) == 2:
if year > 70:
return year + 1900
elif len (string) == 4:
return year
raise self.BadYear (string)
def year_range (self, years):
year_list = [self.parse_year (year)
for year in self.year_re.findall (years)]
assert len (year_list) > 0
return (min (year_list), max (year_list))
def set_use_quilt (self, use_quilt):
self.use_quilt = use_quilt
def include_year (self, year):
assert not self.max_year
self.max_year = year
def canonicalise_years (self, dir, filename, filter, years):
# Leave texinfo variables alone.
if years.startswith ('@value'):
return years
(min_year, max_year) = self.year_range (years)
# Update the upper bound, if enabled.
if self.max_year and not filter.is_fossilised_file (dir, filename):
max_year = max (max_year, self.max_year)
# Use a range.
if min_year == max_year:
return '%d' % min_year
else:
return '%d-%d' % (min_year, max_year)
def strip_continuation (self, line):
line = line.lstrip()
match = self.comment_re.match (line)
if match:
line = line[match.end():].lstrip()
return line
def is_complete (self, match):
holder = match.group (4)
return (holder
and (holder not in self.holder_prefixes
or holder in self.holders))
def update_copyright (self, dir, filename, filter, file, line, match):
orig_line = line
next_line = None
pathname = os.path.join (dir, filename)
intro = match.group (1)
if intro.startswith ('@set'):
# Texinfo year variables should always be on one line
after_years = line[match.end (2):].strip()
if after_years != '':
self.errors.report (pathname,
'trailing characters in @set: '
+ after_years)
return (False, orig_line, next_line)
else:
# If it looks like the copyright is incomplete, add the next line.
while not self.is_complete (match):
try:
next_line = file.next()
except StopIteration:
break
# If the next line doesn't look like a proper continuation,
# assume that what we've got is complete.
continuation = self.strip_continuation (next_line)
if not self.continuation_re.match (continuation):
break
# Merge the lines for matching purposes.
orig_line += next_line
line = line.rstrip() + ' ' + continuation
next_line = None
# Rematch with the longer line, at the original position.
match = self.copyright_re.match (line, match.start())
assert match
holder = match.group (4)
# Use the filter to test cases where markup is getting in the way.
if filter.by_package_author (dir, filename):
assert holder not in self.holders
elif not holder:
self.errors.report (pathname, 'missing copyright holder')
return (False, orig_line, next_line)
elif holder not in self.holders:
self.errors.report (pathname,
'unrecognised copyright holder: ' + holder)
return (False, orig_line, next_line)
else:
# See whether the copyright is associated with the package
# author.
canon_form = self.holders[holder]
if not canon_form:
return (False, orig_line, next_line)
# Make sure the author is given in a consistent way.
line = (line[:match.start (4)]
+ canon_form
+ line[match.end (4):])
# Remove any 'by'
line = line[:match.start (3)] + line[match.end (3):]
# Update the copyright years.
years = match.group (2).strip()
if (self.max_year
and match.start(0) > 0 and line[match.start(0)-1] == '"'
and not filter.is_fossilised_file (dir, filename)):
# A printed copyright date consists of the current year
canon_form = '%d' % self.max_year
else:
try:
canon_form = self.canonicalise_years (dir, filename, filter, years)
except self.BadYear as e:
self.errors.report (pathname, str (e))
return (False, orig_line, next_line)
line = (line[:match.start (2)]
+ ' ' + canon_form + self.separator
+ line[match.end (2):])
# Use the standard (C) form.
if intro.endswith ('right'):
intro += ' (C)'
elif intro.endswith ('(c)'):
intro = intro[:-3] + '(C)'
line = line[:match.start (1)] + intro + line[match.end (1):]
# Strip trailing whitespace
line = line.rstrip() + '\n'
return (line != orig_line, line, next_line)
def process_file (self, dir, filename, filter):
pathname = os.path.join (dir, filename)
if filename.endswith ('.tmp'):
# Looks like something we tried to create before.
try:
os.remove (pathname)
except OSError:
pass
return
lines = []
changed = False
line_filter = filter.get_line_filter (dir, filename)
with open (pathname, 'r') as file:
prev = None
for line in file:
while line:
next_line = None
# Leave filtered-out lines alone.
if not (line_filter and line_filter.match (line)):
match = self.copyright_re.search (line)
if match:
res = self.update_copyright (dir, filename, filter,
file, line, match)
(this_changed, line, next_line) = res
changed = changed or this_changed
# Check for copyright lines that might have slipped by.
elif self.other_copyright_re.search (line):
self.errors.report (pathname,
'unrecognised copyright: %s'
% line.strip())
lines.append (line)
line = next_line
# If something changed, write the new file out.
if changed and self.errors.ok():
tmp_pathname = pathname + '.tmp'
with open (tmp_pathname, 'w') as file:
for line in lines:
file.write (line)
if self.use_quilt:
subprocess.call (['quilt', 'add', pathname])
os.rename (tmp_pathname, pathname)
def process_tree (self, tree, filter):
for (dir, subdirs, filenames) in os.walk (tree):
# Don't recurse through directories that should be skipped.
for i in xrange (len (subdirs) - 1, -1, -1):
if filter.skip_dir (dir, subdirs[i]):
del subdirs[i]
# Handle the files in this directory.
for filename in filenames:
if filter.skip_file (dir, filename):
sys.stdout.write ('Skipping %s\n'
% os.path.join (dir, filename))
else:
self.process_file (dir, filename, filter)
class CmdLine:
def __init__ (self, copyright = Copyright):
self.errors = Errors()
self.copyright = copyright (self.errors)
self.dirs = []
self.default_dirs = []
self.chosen_dirs = []
self.option_handlers = dict()
self.option_help = []
self.add_option ('--help', 'Print this help', self.o_help)
self.add_option ('--quilt', '"quilt add" files before changing them',
self.o_quilt)
self.add_option ('--this-year', 'Add the current year to every notice',
self.o_this_year)
def add_option (self, name, help, handler):
self.option_help.append ((name, help))
self.option_handlers[name] = handler
def add_dir (self, dir, filter = GenericFilter()):
self.dirs.append ((dir, filter))
def o_help (self, option = None):
sys.stdout.write ('Usage: %s [options] dir1 dir2...\n\n'
'Options:\n' % sys.argv[0])
format = '%-15s %s\n'
for (what, help) in self.option_help:
sys.stdout.write (format % (what, help))
sys.stdout.write ('\nDirectories:\n')
format = '%-25s'
i = 0
for (dir, filter) in self.dirs:
i += 1
if i % 3 == 0 or i == len (self.dirs):
sys.stdout.write (dir + '\n')
else:
sys.stdout.write (format % dir)
sys.exit (0)
def o_quilt (self, option):
self.copyright.set_use_quilt (True)
def o_this_year (self, option):
self.copyright.include_year (time.localtime().tm_year)
def main (self):
for arg in sys.argv[1:]:
if arg[:1] != '-':
self.chosen_dirs.append (arg)
elif arg in self.option_handlers:
self.option_handlers[arg] (arg)
else:
self.errors.report (None, 'unrecognised option: ' + arg)
if self.errors.ok():
if len (self.chosen_dirs) == 0:
self.chosen_dirs = self.default_dirs
if len (self.chosen_dirs) == 0:
self.o_help()
else:
for chosen_dir in self.chosen_dirs:
canon_dir = os.path.join (chosen_dir, '')
count = 0
for (dir, filter) in self.dirs:
if (dir + os.sep).startswith (canon_dir):
count += 1
self.copyright.process_tree (dir, filter)
if count == 0:
self.errors.report (None, 'unrecognised directory: '
+ chosen_dir)
sys.exit (0 if self.errors.ok() else 1)
#----------------------------------------------------------------------------
class TopLevelFilter (GenericFilter):
def skip_dir (self, dir, subdir):
return True
class ConfigFilter (GenericFilter):
def __init__ (self):
GenericFilter.__init__ (self)
def skip_file (self, dir, filename):
if filename.endswith ('.m4'):
pathname = os.path.join (dir, filename)
with open (pathname) as file:
# Skip files imported from gettext.
if file.readline().find ('gettext-') >= 0:
return True
return GenericFilter.skip_file (self, dir, filename)
class LdFilter (GenericFilter):
def __init__ (self):
GenericFilter.__init__ (self)
self.skip_extensions |= set ([
# ld testsuite output match files.
'.ro',
])
class BinutilsCopyright (Copyright):
def __init__ (self, errors):
Copyright.__init__ (self, errors)
canon_fsf = 'Free Software Foundation, Inc.'
self.add_package_author ('Free Software Foundation', canon_fsf)
self.add_package_author ('Free Software Foundation.', canon_fsf)
self.add_package_author ('Free Software Foundation Inc.', canon_fsf)
self.add_package_author ('Free Software Foundation, Inc', canon_fsf)
self.add_package_author ('Free Software Foundation, Inc.', canon_fsf)
self.add_package_author ('The Free Software Foundation', canon_fsf)
self.add_package_author ('The Free Software Foundation, Inc.', canon_fsf)
self.add_package_author ('Software Foundation, Inc.', canon_fsf)
self.add_external_author ('Carnegie Mellon University')
self.add_external_author ('John D. Polstra.')
self.add_external_author ('Linaro Ltd.')
self.add_external_author ('MIPS Computer Systems, Inc.')
self.add_external_author ('Red Hat Inc.')
self.add_external_author ('Regents of the University of California.')
self.add_external_author ('The Regents of the University of California.')
self.add_external_author ('Third Eye Software, Inc.')
self.add_external_author ('Ulrich Drepper')
self.add_external_author ('Synopsys Inc.')
class BinutilsCmdLine (CmdLine):
def __init__ (self):
CmdLine.__init__ (self, BinutilsCopyright)
self.add_dir ('.', TopLevelFilter())
self.add_dir ('bfd')
self.add_dir ('binutils')
self.add_dir ('config', ConfigFilter())
self.add_dir ('cpu')
self.add_dir ('elfcpp')
self.add_dir ('etc')
self.add_dir ('gas')
self.add_dir ('gdb')
self.add_dir ('gold')
self.add_dir ('gprof')
self.add_dir ('include')
self.add_dir ('ld', LdFilter())
self.add_dir ('libctf')
self.add_dir ('libdecnumber')
self.add_dir ('libiberty')
self.add_dir ('opcodes')
self.add_dir ('readline')
self.add_dir ('sim')
self.default_dirs = [
'bfd',
'binutils',
'elfcpp',
'etc',
'gas',
'gold',
'gprof',
'include',
'ld',
'libctf',
'libiberty',
'opcodes',
]
BinutilsCmdLine().main()
| cuda-gdb-master | etc/update-copyright.py |
#!/usr/bin/python
#
# Copyright (C) 2014 Free Software Foundation, Inc.
#
# This script is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
import sys
import getopt
import re
import io
from datetime import datetime
from operator import attrgetter
# True if unrecognised lines should cause a fatal error. Might want to turn
# this on by default later.
strict = False
# True if the order of .log segments should match the .sum file, false if
# they should keep the original order.
sort_logs = True
# A version of open() that is safe against whatever binary output
# might be added to the log.
def safe_open (filename):
if sys.version_info >= (3, 0):
return open (filename, 'r', errors = 'surrogateescape')
return open (filename, 'r')
# Force stdout to handle escape sequences from a safe_open file.
if sys.version_info >= (3, 0):
sys.stdout = io.TextIOWrapper (sys.stdout.buffer,
errors = 'surrogateescape')
class Named:
def __init__ (self, name):
self.name = name
class ToolRun (Named):
def __init__ (self, name):
Named.__init__ (self, name)
# The variations run for this tool, mapped by --target_board name.
self.variations = dict()
# Return the VariationRun for variation NAME.
def get_variation (self, name):
if name not in self.variations:
self.variations[name] = VariationRun (name)
return self.variations[name]
class VariationRun (Named):
def __init__ (self, name):
Named.__init__ (self, name)
# A segment of text before the harness runs start, describing which
# baseboard files were loaded for the target.
self.header = None
# The harnesses run for this variation, mapped by filename.
self.harnesses = dict()
# A list giving the number of times each type of result has
# been seen.
self.counts = []
# Return the HarnessRun for harness NAME.
def get_harness (self, name):
if name not in self.harnesses:
self.harnesses[name] = HarnessRun (name)
return self.harnesses[name]
class HarnessRun (Named):
def __init__ (self, name):
Named.__init__ (self, name)
# Segments of text that make up the harness run, mapped by a test-based
# key that can be used to order them.
self.segments = dict()
# Segments of text that make up the harness run but which have
# no recognized test results. These are typically harnesses that
# are completely skipped for the target.
self.empty = []
# A list of results. Each entry is a pair in which the first element
# is a unique sorting key and in which the second is the full
# PASS/FAIL line.
self.results = []
# Add a segment of text to the harness run. If the segment includes
# test results, KEY is an example of one of them, and can be used to
# combine the individual segments in order. If the segment has no
# test results (e.g. because the harness doesn't do anything for the
# current configuration) then KEY is None instead. In that case
# just collect the segments in the order that we see them.
def add_segment (self, key, segment):
if key:
assert key not in self.segments
self.segments[key] = segment
else:
self.empty.append (segment)
class Segment:
def __init__ (self, filename, start):
self.filename = filename
self.start = start
self.lines = 0
class Prog:
def __init__ (self):
# The variations specified on the command line.
self.variations = []
# The variations seen in the input files.
self.known_variations = set()
# The tools specified on the command line.
self.tools = []
# Whether to create .sum rather than .log output.
self.do_sum = True
# Regexps used while parsing.
self.test_run_re = re.compile (r'^Test Run By (\S+) on (.*)$')
self.tool_re = re.compile (r'^\t\t=== (.*) tests ===$')
self.result_re = re.compile (r'^(PASS|XPASS|FAIL|XFAIL|UNRESOLVED'
r'|WARNING|ERROR|UNSUPPORTED|UNTESTED'
r'|KFAIL|KPASS|PATH|DUPLICATE):\s*(.+)')
self.completed_re = re.compile (r'.* completed at (.*)')
# Pieces of text to write at the head of the output.
# start_line is a pair in which the first element is a datetime
# and in which the second is the associated 'Test Run By' line.
self.start_line = None
self.native_line = ''
self.target_line = ''
self.host_line = ''
self.acats_premable = ''
# Pieces of text to write at the end of the output.
# end_line is like start_line but for the 'runtest completed' line.
self.acats_failures = []
self.version_output = ''
self.end_line = None
# Known summary types.
self.count_names = [
'# of DejaGnu errors\t\t',
'# of expected passes\t\t',
'# of unexpected failures\t',
'# of unexpected successes\t',
'# of expected failures\t\t',
'# of unknown successes\t\t',
'# of known failures\t\t',
'# of untested testcases\t\t',
'# of unresolved testcases\t',
'# of unsupported tests\t\t',
'# of paths in test names\t',
'# of duplicate test names\t'
]
self.runs = dict()
def usage (self):
name = sys.argv[0]
sys.stderr.write ('Usage: ' + name
+ ''' [-t tool] [-l variant-list] [-L] log-or-sum-file ...
tool The tool (e.g. g++, libffi) for which to create a
new test summary file. If not specified then output
is created for all tools.
variant-list One or more test variant names. If the list is
not specified then one is constructed from all
variants in the files for <tool>.
sum-file A test summary file with the format of those
created by runtest from DejaGnu.
If -L is used, merge *.log files instead of *.sum. In this
mode the exact order of lines may not be preserved, just different
Running *.exp chunks should be in correct order.
''')
sys.exit (1)
def fatal (self, what, string):
if not what:
what = sys.argv[0]
sys.stderr.write (what + ': ' + string + '\n')
sys.exit (1)
# Parse the command-line arguments.
def parse_cmdline (self):
try:
(options, self.files) = getopt.getopt (sys.argv[1:], 'l:t:L')
if len (self.files) == 0:
self.usage()
for (option, value) in options:
if option == '-l':
self.variations.append (value)
elif option == '-t':
self.tools.append (value)
else:
self.do_sum = False
except getopt.GetoptError as e:
self.fatal (None, e.msg)
# Try to parse time string TIME, returning an arbitrary time on failure.
# Getting this right is just a nice-to-have so failures should be silent.
def parse_time (self, time):
try:
return datetime.strptime (time, '%c')
except ValueError:
return datetime.now()
# Parse an integer and abort on failure.
def parse_int (self, filename, value):
try:
return int (value)
except ValueError:
self.fatal (filename, 'expected an integer, got: ' + value)
# Return a list that represents no test results.
def zero_counts (self):
return [0 for x in self.count_names]
# Return the ToolRun for tool NAME.
def get_tool (self, name):
if name not in self.runs:
self.runs[name] = ToolRun (name)
return self.runs[name]
# Add the result counts in list FROMC to TOC.
def accumulate_counts (self, toc, fromc):
for i in range (len (self.count_names)):
toc[i] += fromc[i]
# Parse the list of variations after 'Schedule of variations:'.
# Return the number seen.
def parse_variations (self, filename, file):
num_variations = 0
while True:
line = file.readline()
if line == '':
self.fatal (filename, 'could not parse variation list')
if line == '\n':
break
self.known_variations.add (line.strip())
num_variations += 1
return num_variations
# Parse from the first line after 'Running target ...' to the end
# of the run's summary.
def parse_run (self, filename, file, tool, variation, num_variations):
header = None
harness = None
segment = None
final_using = 0
has_warning = 0
# If this is the first run for this variation, add any text before
# the first harness to the header.
if not variation.header:
segment = Segment (filename, file.tell())
variation.header = segment
# Parse the rest of the summary (the '# of ' lines).
if len (variation.counts) == 0:
variation.counts = self.zero_counts()
# Parse up until the first line of the summary.
if num_variations == 1:
end = '\t\t=== ' + tool.name + ' Summary ===\n'
else:
end = ('\t\t=== ' + tool.name + ' Summary for '
+ variation.name + ' ===\n')
while True:
line = file.readline()
if line == '':
self.fatal (filename, 'no recognised summary line')
if line == end:
break
# Look for the start of a new harness.
if line.startswith ('Running ') and line.endswith (' ...\n'):
# Close off the current harness segment, if any.
if harness:
segment.lines -= final_using
harness.add_segment (first_key, segment)
name = line[len ('Running '):-len(' ...\n')]
harness = variation.get_harness (name)
segment = Segment (filename, file.tell())
first_key = None
final_using = 0
continue
# Record test results. Associate the first test result with
# the harness segment, so that if a run for a particular harness
# has been split up, we can reassemble the individual segments
# in a sensible order.
#
# dejagnu sometimes issues warnings about the testing environment
# before running any tests. Treat them as part of the header
# rather than as a test result.
match = self.result_re.match (line)
if match and (harness or not line.startswith ('WARNING:')):
if not harness:
self.fatal (filename, 'saw test result before harness name')
name = match.group (2)
# Ugly hack to get the right order for gfortran.
if name.startswith ('gfortran.dg/g77/'):
name = 'h' + name
# If we have a time out warning, make sure it appears
# before the following testcase diagnostic: we insert
# the testname before 'program' so that sort faces a
# list of testnames.
if line.startswith ('WARNING: program timed out'):
has_warning = 1
else:
if has_warning == 1:
key = (name, len (harness.results))
myline = 'WARNING: %s program timed out.\n' % name
harness.results.append ((key, myline))
has_warning = 0
key = (name, len (harness.results))
harness.results.append ((key, line))
if not first_key and sort_logs:
first_key = key
if line.startswith ('ERROR: (DejaGnu)'):
for i in range (len (self.count_names)):
if 'DejaGnu errors' in self.count_names[i]:
variation.counts[i] += 1
break
# 'Using ...' lines are only interesting in a header. Splitting
# the test up into parallel runs leads to more 'Using ...' lines
# than there would be in a single log.
if line.startswith ('Using '):
final_using += 1
else:
final_using = 0
# Add other text to the current segment, if any.
if segment:
segment.lines += 1
# Close off the final harness segment, if any.
if harness:
segment.lines -= final_using
harness.add_segment (first_key, segment)
while True:
before = file.tell()
line = file.readline()
if line == '':
break
if line == '\n':
continue
if not line.startswith ('# '):
file.seek (before)
break
found = False
for i in range (len (self.count_names)):
if line.startswith (self.count_names[i]):
count = line[len (self.count_names[i]):-1].strip()
variation.counts[i] += self.parse_int (filename, count)
found = True
break
if not found:
self.fatal (filename, 'unknown test result: ' + line[:-1])
# Parse an acats run, which uses a different format from dejagnu.
# We have just skipped over '=== acats configuration ==='.
def parse_acats_run (self, filename, file):
# Parse the preamble, which describes the configuration and logs
# the creation of support files.
record = (self.acats_premable == '')
if record:
self.acats_premable = '\t\t=== acats configuration ===\n'
while True:
line = file.readline()
if line == '':
self.fatal (filename, 'could not parse acats preamble')
if line == '\t\t=== acats tests ===\n':
break
if record:
self.acats_premable += line
# Parse the test results themselves, using a dummy variation name.
tool = self.get_tool ('acats')
variation = tool.get_variation ('none')
self.parse_run (filename, file, tool, variation, 1)
# Parse the failure list.
while True:
before = file.tell()
line = file.readline()
if line.startswith ('*** FAILURES: '):
self.acats_failures.append (line[len ('*** FAILURES: '):-1])
continue
file.seek (before)
break
# Parse the final summary at the end of a log in order to capture
# the version output that follows it.
def parse_final_summary (self, filename, file):
record = (self.version_output == '')
while True:
line = file.readline()
if line == '':
break
if line.startswith ('# of '):
continue
if record:
self.version_output += line
if line == '\n':
break
# Parse a .log or .sum file.
def parse_file (self, filename, file):
tool = None
target = None
num_variations = 1
while True:
line = file.readline()
if line == '':
return
# Parse the list of variations, which comes before the test
# runs themselves.
if line.startswith ('Schedule of variations:'):
num_variations = self.parse_variations (filename, file)
continue
# Parse a testsuite run for one tool/variation combination.
if line.startswith ('Running target '):
name = line[len ('Running target '):-1]
if not tool:
self.fatal (filename, 'could not parse tool name')
if name not in self.known_variations:
self.fatal (filename, 'unknown target: ' + name)
self.parse_run (filename, file, tool,
tool.get_variation (name),
num_variations)
# If there is only one variation then there is no separate
# summary for it. Record any following version output.
if num_variations == 1:
self.parse_final_summary (filename, file)
continue
# Parse the start line. In the case where several files are being
# parsed, pick the one with the earliest time.
match = self.test_run_re.match (line)
if match:
time = self.parse_time (match.group (2))
if not self.start_line or self.start_line[0] > time:
self.start_line = (time, line)
continue
# Parse the form used for native testing.
if line.startswith ('Native configuration is '):
self.native_line = line
continue
# Parse the target triplet.
if line.startswith ('Target is '):
self.target_line = line
continue
# Parse the host triplet.
if line.startswith ('Host is '):
self.host_line = line
continue
# Parse the acats premable.
if line == '\t\t=== acats configuration ===\n':
self.parse_acats_run (filename, file)
continue
# Parse the tool name.
match = self.tool_re.match (line)
if match:
tool = self.get_tool (match.group (1))
continue
# Skip over the final summary (which we instead create from
# individual runs) and parse the version output.
if tool and line == '\t\t=== ' + tool.name + ' Summary ===\n':
if file.readline() != '\n':
self.fatal (filename, 'expected blank line after summary')
self.parse_final_summary (filename, file)
continue
# Parse the completion line. In the case where several files
# are being parsed, pick the one with the latest time.
match = self.completed_re.match (line)
if match:
time = self.parse_time (match.group (1))
if not self.end_line or self.end_line[0] < time:
self.end_line = (time, line)
continue
# Sanity check to make sure that important text doesn't get
# dropped accidentally.
if strict and line.strip() != '':
self.fatal (filename, 'unrecognised line: ' + line[:-1])
# Output a segment of text.
def output_segment (self, segment):
with safe_open (segment.filename) as file:
file.seek (segment.start)
for i in range (segment.lines):
sys.stdout.write (file.readline())
# Output a summary giving the number of times each type of result has
# been seen.
def output_summary (self, tool, counts):
for i in range (len (self.count_names)):
name = self.count_names[i]
# dejagnu only prints result types that were seen at least once,
# but acats always prints a number of unexpected failures.
if (counts[i] > 0
or (tool.name == 'acats'
and name.startswith ('# of unexpected failures'))):
sys.stdout.write ('%s%d\n' % (name, counts[i]))
# Output unified .log or .sum information for a particular variation,
# with a summary at the end.
def output_variation (self, tool, variation):
self.output_segment (variation.header)
for harness in sorted (variation.harnesses.values(),
key = attrgetter ('name')):
sys.stdout.write ('Running ' + harness.name + ' ...\n')
if self.do_sum:
harness.results.sort()
for (key, line) in harness.results:
sys.stdout.write (line)
else:
# Rearrange the log segments into test order (but without
# rearranging text within those segments).
for key in sorted (harness.segments.keys()):
self.output_segment (harness.segments[key])
for segment in harness.empty:
self.output_segment (segment)
if len (self.variations) > 1:
sys.stdout.write ('\t\t=== ' + tool.name + ' Summary for '
+ variation.name + ' ===\n\n')
self.output_summary (tool, variation.counts)
# Output unified .log or .sum information for a particular tool,
# with a summary at the end.
def output_tool (self, tool):
counts = self.zero_counts()
if tool.name == 'acats':
# acats doesn't use variations, so just output everything.
# It also has a different approach to whitespace.
sys.stdout.write ('\t\t=== ' + tool.name + ' tests ===\n')
for variation in tool.variations.values():
self.output_variation (tool, variation)
self.accumulate_counts (counts, variation.counts)
sys.stdout.write ('\t\t=== ' + tool.name + ' Summary ===\n')
else:
# Output the results in the usual dejagnu runtest format.
sys.stdout.write ('\n\t\t=== ' + tool.name + ' tests ===\n\n'
'Schedule of variations:\n')
for name in self.variations:
if name in tool.variations:
sys.stdout.write (' ' + name + '\n')
sys.stdout.write ('\n')
for name in self.variations:
if name in tool.variations:
variation = tool.variations[name]
sys.stdout.write ('Running target '
+ variation.name + '\n')
self.output_variation (tool, variation)
self.accumulate_counts (counts, variation.counts)
sys.stdout.write ('\n\t\t=== ' + tool.name + ' Summary ===\n\n')
self.output_summary (tool, counts)
def main (self):
self.parse_cmdline()
try:
# Parse the input files.
for filename in self.files:
with safe_open (filename) as file:
self.parse_file (filename, file)
# Decide what to output.
if len (self.variations) == 0:
self.variations = sorted (self.known_variations)
else:
for name in self.variations:
if name not in self.known_variations:
self.fatal (None, 'no results for ' + name)
if len (self.tools) == 0:
self.tools = sorted (self.runs.keys())
# Output the header.
if self.start_line:
sys.stdout.write (self.start_line[1])
sys.stdout.write (self.native_line)
sys.stdout.write (self.target_line)
sys.stdout.write (self.host_line)
sys.stdout.write (self.acats_premable)
# Output the main body.
for name in self.tools:
if name not in self.runs:
self.fatal (None, 'no results for ' + name)
self.output_tool (self.runs[name])
# Output the footer.
if len (self.acats_failures) > 0:
sys.stdout.write ('*** FAILURES: '
+ ' '.join (self.acats_failures) + '\n')
sys.stdout.write (self.version_output)
if self.end_line:
sys.stdout.write (self.end_line[1])
except IOError as e:
self.fatal (e.filename, e.strerror)
Prog().main()
| cuda-gdb-master | contrib/dg-extract-results.py |
#!/usr/bin/env python3
# Copyright (C) 2020 Free Software Foundation, Inc.
#
# This file is part of GCC.
#
# GCC is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GCC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GCC; see the file COPYING. If not, write to
# the Free Software Foundation, 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
# This script parses a .diff file generated with 'diff -up' or 'diff -cp'
# and adds a skeleton ChangeLog file to the file. It does not try to be
# too smart when parsing function names, but it produces a reasonable
# approximation.
#
# Author: Martin Liska <[email protected]>
import argparse
import os
import re
import sys
from itertools import takewhile
import requests
from unidiff import PatchSet
pr_regex = re.compile(r'(\/(\/|\*)|[Cc*!])\s+(?P<pr>PR [a-z+-]+\/[0-9]+)')
dr_regex = re.compile(r'(\/(\/|\*)|[Cc*!])\s+(?P<dr>DR [0-9]+)')
identifier_regex = re.compile(r'^([a-zA-Z0-9_#].*)')
comment_regex = re.compile(r'^\/\*')
struct_regex = re.compile(r'^(class|struct|union|enum)\s+'
r'(GTY\(.*\)\s+)?([a-zA-Z0-9_]+)')
macro_regex = re.compile(r'#\s*(define|undef)\s+([a-zA-Z0-9_]+)')
super_macro_regex = re.compile(r'^DEF[A-Z0-9_]+\s*\(([a-zA-Z0-9_]+)')
fn_regex = re.compile(r'([a-zA-Z_][^()\s]*)\s*\([^*]')
template_and_param_regex = re.compile(r'<[^<>]*>')
bugzilla_url = 'https://gcc.gnu.org/bugzilla/rest.cgi/bug?id=%s&' \
'include_fields=summary'
function_extensions = set(['.c', '.cpp', '.C', '.cc', '.h', '.inc', '.def'])
help_message = """\
Generate ChangeLog template for PATCH.
PATCH must be generated using diff(1)'s -up or -cp options
(or their equivalent in git).
"""
script_folder = os.path.realpath(__file__)
gcc_root = os.path.dirname(os.path.dirname(script_folder))
def find_changelog(path):
folder = os.path.split(path)[0]
while True:
if os.path.exists(os.path.join(gcc_root, folder, 'ChangeLog')):
return folder
folder = os.path.dirname(folder)
if folder == '':
return folder
raise AssertionError()
def extract_function_name(line):
if comment_regex.match(line):
return None
m = struct_regex.search(line)
if m:
# Struct declaration
return m.group(1) + ' ' + m.group(3)
m = macro_regex.search(line)
if m:
# Macro definition
return m.group(2)
m = super_macro_regex.search(line)
if m:
# Supermacro
return m.group(1)
m = fn_regex.search(line)
if m:
# Discard template and function parameters.
fn = m.group(1)
fn = re.sub(template_and_param_regex, '', fn)
return fn.rstrip()
return None
def try_add_function(functions, line):
fn = extract_function_name(line)
if fn and fn not in functions:
functions.append(fn)
return bool(fn)
def sort_changelog_files(changed_file):
return (changed_file.is_added_file, changed_file.is_removed_file)
def get_pr_titles(prs):
output = ''
for pr in prs:
id = pr.split('/')[-1]
r = requests.get(bugzilla_url % id)
bugs = r.json()['bugs']
if len(bugs) == 1:
output += '%s - %s\n' % (pr, bugs[0]['summary'])
print(output)
if output:
output += '\n'
return output
def generate_changelog(data, no_functions=False, fill_pr_titles=False):
changelogs = {}
changelog_list = []
prs = []
out = ''
diff = PatchSet(data)
for file in diff:
changelog = find_changelog(file.path)
if changelog not in changelogs:
changelogs[changelog] = []
changelog_list.append(changelog)
changelogs[changelog].append(file)
# Extract PR entries from newly added tests
if 'testsuite' in file.path and file.is_added_file:
for line in list(file)[0]:
m = pr_regex.search(line.value)
if m:
pr = m.group('pr')
if pr not in prs:
prs.append(pr)
else:
m = dr_regex.search(line.value)
if m:
dr = m.group('dr')
if dr not in prs:
prs.append(dr)
else:
break
if fill_pr_titles:
out += get_pr_titles(prs)
# sort ChangeLog so that 'testsuite' is at the end
for changelog in sorted(changelog_list, key=lambda x: 'testsuite' in x):
files = changelogs[changelog]
out += '%s:\n' % os.path.join(changelog, 'ChangeLog')
out += '\n'
for pr in prs:
out += '\t%s\n' % pr
# new and deleted files should be at the end
for file in sorted(files, key=sort_changelog_files):
assert file.path.startswith(changelog)
in_tests = 'testsuite' in changelog or 'testsuite' in file.path
relative_path = file.path[len(changelog):].lstrip('/')
functions = []
if file.is_added_file:
msg = 'New test' if in_tests else 'New file'
out += '\t* %s: %s.\n' % (relative_path, msg)
elif file.is_removed_file:
out += '\t* %s: Removed.\n' % (relative_path)
elif hasattr(file, 'is_rename') and file.is_rename:
out += '\t* %s: Moved to...\n' % (relative_path)
new_path = file.target_file[2:]
# A file can be theoretically moved to a location that
# belongs to a different ChangeLog. Let user fix it.
if new_path.startswith(changelog):
new_path = new_path[len(changelog):].lstrip('/')
out += '\t* %s: ...here.\n' % (new_path)
else:
if not no_functions:
for hunk in file:
# Do not add function names for testsuite files
extension = os.path.splitext(relative_path)[1]
if not in_tests and extension in function_extensions:
last_fn = None
modified_visited = False
success = False
for line in hunk:
m = identifier_regex.match(line.value)
if line.is_added or line.is_removed:
if not line.value.strip():
continue
modified_visited = True
if m and try_add_function(functions,
m.group(1)):
last_fn = None
success = True
elif line.is_context:
if last_fn and modified_visited:
try_add_function(functions, last_fn)
last_fn = None
modified_visited = False
success = True
elif m:
last_fn = m.group(1)
modified_visited = False
if not success:
try_add_function(functions,
hunk.section_header)
if functions:
out += '\t* %s (%s):\n' % (relative_path, functions[0])
for fn in functions[1:]:
out += '\t(%s):\n' % fn
else:
out += '\t* %s:\n' % relative_path
out += '\n'
return out
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=help_message)
parser.add_argument('input', nargs='?',
help='Patch file (or missing, read standard input)')
parser.add_argument('-s', '--no-functions', action='store_true',
help='Do not generate function names in ChangeLogs')
parser.add_argument('-p', '--fill-up-bug-titles', action='store_true',
help='Download title of mentioned PRs')
parser.add_argument('-c', '--changelog',
help='Append the ChangeLog to a git commit message '
'file')
args = parser.parse_args()
if args.input == '-':
args.input = None
input = open(args.input) if args.input else sys.stdin
data = input.read()
output = generate_changelog(data, args.no_functions,
args.fill_up_bug_titles)
if args.changelog:
lines = open(args.changelog).read().split('\n')
start = list(takewhile(lambda l: not l.startswith('#'), lines))
end = lines[len(start):]
with open(args.changelog, 'w') as f:
if start:
# appent empty line
if start[-1] != '':
start.append('')
else:
# append 2 empty lines
start = 2 * ['']
f.write('\n'.join(start))
f.write('\n')
f.write(output)
f.write('\n'.join(end))
else:
print(output, end='')
| cuda-gdb-master | contrib/mklog.py |
#!/usr/bin/env python3
# Copyright (C) 1996-2022 Free Software Foundation, Inc.
#
# This file is part of the GNU simulators.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Helper to generate target-newlib-* files.
target-newlib-* are files that describe various newlib/libgloss values used
by the host/target interface. This needs to be rerun whenever the newlib source
changes. Developers manually run it.
If the path to newlib is not specified, it will be searched for in:
- the root of this source tree
- alongside this source tree
"""
import argparse
from pathlib import Path
import re
import subprocess
import sys
from typing import Iterable, List, TextIO
PROG = Path(__file__).name
# Unfortunately, many newlib/libgloss ports have seen fit to define their own
# syscall.h file. This means that system call numbers can vary for each port.
# Support for all this crud is kept here, rather than trying to get too fancy.
# If you want to try to improve this, please do, but don't break anything.
#
# If a target isn't listed here, it gets the standard syscall.h file (see
# libgloss/syscall.h) which hopefully new targets will use.
#
# NB: New ports should use libgloss, not newlib.
TARGET_DIRS = {
'cr16': 'libgloss/cr16/sys',
'd10v': 'newlib/libc/sys/d10v/sys',
# Port removed from the tree years ago.
#'i960': 'libgloss/i960',
'mcore': 'libgloss/mcore',
'riscv': 'libgloss/riscv/machine',
'sh': 'newlib/libc/sys/sh/sys',
'v850': 'libgloss/v850/sys',
}
# The header for the generated def file.
FILE_HEADER = f"""\
/* Newlib/libgloss macro values needed by remote target support. */
/* This file is machine generated by {PROG}. */\
"""
# Used to update sections of files.
START_MARKER = 'gennltvals: START'
END_MARKER = 'gennltvals: END'
def extract_syms(cpp: str, srcdir: Path,
headers: Iterable[str],
pattern: str,
filter: str = r'^$') -> dict:
"""Extract all the symbols from |headers| matching |pattern| using |cpp|."""
srcfile = ''.join(f'#include <{x}>\n' for x in headers)
syms = set()
define_pattern = re.compile(r'^#\s*define\s+(' + pattern + ')')
filter_pattern = re.compile(filter)
for header in headers:
with open(srcdir / header, 'r', encoding='utf-8') as fp:
data = fp.read()
for line in data.splitlines():
m = define_pattern.match(line)
if m and not filter_pattern.search(line):
syms.add(m.group(1))
for sym in syms:
srcfile += f'#ifdef {sym}\nDEFVAL "{sym}" {sym}\n#endif\n'
result = subprocess.run(
f'{cpp} -E -I"{srcdir}" -', shell=True, check=True, encoding='utf-8',
input=srcfile, capture_output=True)
ret = {}
for line in result.stdout.splitlines():
if line.startswith('DEFVAL '):
_, sym, val = line.split()
ret[sym.strip('"')] = val
return ret
def gentvals(output_dir: Path,
cpp: str, srctype: str, srcdir: Path,
headers: Iterable[str],
pattern: str,
filter: str = r'^$',
target: str = None):
"""Extract constants from the specified files using a regular expression.
We'll run things through the preprocessor.
"""
headers = tuple(headers)
# Require all files exist in order to regenerate properly.
for header in headers:
fullpath = srcdir / header
assert fullpath.exists(), f'{fullpath} does not exist'
syms = extract_syms(cpp, srcdir, headers, pattern, filter)
target_map = output_dir / f'target-newlib-{srctype}.c'
assert target_map.exists(), f'{target_map}: Missing skeleton'
old_lines = target_map.read_text().splitlines()
start_i = end_i = None
for i, line in enumerate(old_lines):
if START_MARKER in line:
start_i = i
if END_MARKER in line:
end_i = i
assert start_i and end_i
new_lines = old_lines[0:start_i + 1]
new_lines.extend(
f'#ifdef {sym}\n'
f' {{ "{sym}", {sym}, {val} }},\n'
f'#endif' for sym, val in sorted(syms.items()))
new_lines.extend(old_lines[end_i:])
target_map.write_text('\n'.join(new_lines) + '\n')
def gen_common(output_dir: Path, newlib: Path, cpp: str):
"""Generate the common C library constants.
No arch should override these.
"""
gentvals(output_dir, cpp, 'errno', newlib / 'newlib/libc/include',
('errno.h', 'sys/errno.h'), 'E[A-Z0-9]*')
gentvals(output_dir, cpp, 'signal', newlib / 'newlib/libc/include',
('signal.h', 'sys/signal.h'), r'SIG[A-Z0-9]*', filter=r'SIGSTKSZ')
gentvals(output_dir, cpp, 'open', newlib / 'newlib/libc/include',
('fcntl.h', 'sys/fcntl.h', 'sys/_default_fcntl.h'), r'O_[A-Z0-9]*')
def gen_target_syscall(output_dir: Path, newlib: Path, cpp: str):
"""Generate the target-specific syscall lists."""
target_map_c = output_dir / 'target-newlib-syscall.c'
old_lines_c = target_map_c.read_text().splitlines()
start_i = end_i = None
for i, line in enumerate(old_lines_c):
if START_MARKER in line:
start_i = i
if END_MARKER in line:
end_i = i
assert start_i and end_i, f'{target_map_c}: Unable to find markers'
new_lines_c = old_lines_c[0:start_i + 1]
new_lines_c_end = old_lines_c[end_i:]
target_map_h = output_dir / 'target-newlib-syscall.h'
old_lines_h = target_map_h.read_text().splitlines()
start_i = end_i = None
for i, line in enumerate(old_lines_h):
if START_MARKER in line:
start_i = i
if END_MARKER in line:
end_i = i
assert start_i and end_i, f'{target_map_h}: Unable to find markers'
new_lines_h = old_lines_h[0:start_i + 1]
new_lines_h_end = old_lines_h[end_i:]
headers = ('syscall.h',)
pattern = r'SYS_[_a-zA-Z0-9]*'
# Output the target-specific syscalls.
for target, subdir in sorted(TARGET_DIRS.items()):
syms = extract_syms(cpp, newlib / subdir, headers, pattern)
new_lines_c.append(f'CB_TARGET_DEFS_MAP cb_{target}_syscall_map[] = {{')
new_lines_c.extend(
f'#ifdef CB_{sym}\n'
' { '
f'"{sym[4:]}", CB_{sym}, TARGET_NEWLIB_{target.upper()}_{sym}'
' },\n'
'#endif' for sym in sorted(syms))
new_lines_c.append(' {NULL, -1, -1},')
new_lines_c.append('};\n')
new_lines_h.append(
f'extern CB_TARGET_DEFS_MAP cb_{target}_syscall_map[];')
new_lines_h.extend(
f'#define TARGET_NEWLIB_{target.upper()}_{sym} {val}'
for sym, val in sorted(syms.items()))
new_lines_h.append('')
# Then output the common syscall targets.
syms = extract_syms(cpp, newlib / 'libgloss', headers, pattern)
new_lines_c.append(f'CB_TARGET_DEFS_MAP cb_init_syscall_map[] = {{')
new_lines_c.extend(
f'#ifdef CB_{sym}\n'
f' {{ "{sym[4:]}", CB_{sym}, TARGET_NEWLIB_{sym} }},\n'
f'#endif' for sym in sorted(syms))
new_lines_c.append(' {NULL, -1, -1},')
new_lines_c.append('};')
new_lines_h.append('extern CB_TARGET_DEFS_MAP cb_init_syscall_map[];')
new_lines_h.extend(
f'#define TARGET_NEWLIB_{sym} {val}'
for sym, val in sorted(syms.items()))
new_lines_c.extend(new_lines_c_end)
target_map_c.write_text('\n'.join(new_lines_c) + '\n')
new_lines_h.extend(new_lines_h_end)
target_map_h.write_text('\n'.join(new_lines_h) + '\n')
def gen_targets(output_dir: Path, newlib: Path, cpp: str):
"""Generate the target-specific lists."""
gen_target_syscall(output_dir, newlib, cpp)
def gen(output_dir: Path, newlib: Path, cpp: str):
"""Generate all the things!"""
gen_common(output_dir, newlib, cpp)
gen_targets(output_dir, newlib, cpp)
def get_parser() -> argparse.ArgumentParser:
"""Get CLI parser."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
'-o', '--output', type=Path,
help='write to the specified directory')
parser.add_argument(
'--cpp', type=str, default='cpp',
help='the preprocessor to use')
parser.add_argument(
'--srcroot', type=Path,
help='the root of this source tree')
parser.add_argument(
'newlib', nargs='?', type=Path,
help='path to the newlib+libgloss source tree')
return parser
def parse_args(argv: List[str]) -> argparse.Namespace:
"""Process the command line & default options."""
parser = get_parser()
opts = parser.parse_args(argv)
if opts.output is None:
# Default to where the script lives.
opts.output = Path(__file__).resolve().parent
if opts.srcroot is None:
opts.srcroot = Path(__file__).resolve().parent.parent.parent
else:
opts.srcroot = opts.srcroot.resolve()
if opts.newlib is None:
# Try to find newlib relative to our source tree.
if (opts.srcroot / 'newlib').is_dir():
# If newlib is manually in the same source tree, use it.
if (opts.srcroot / 'libgloss').is_dir():
opts.newlib = opts.srcroot
else:
opts.newlib = opts.srcroot / 'newlib'
elif (opts.srcroot.parent / 'newlib').is_dir():
# Or see if it's alongside the gdb/binutils repo.
opts.newlib = opts.srcroot.parent / 'newlib'
if opts.newlib is None or not opts.newlib.is_dir():
parser.error('unable to find newlib')
return opts
def main(argv: List[str]) -> int:
"""The main entry point for scripts."""
opts = parse_args(argv)
gen(opts.output, opts.newlib, opts.cpp)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| cuda-gdb-master | sim/common/gennltvals.py |
#!/usr/bin/env python
# This will create golden files in a directory passed to it.
# A Test calls this internally to create the golden files
# So it can process them (so we don't have to checkin the files).
# Ensure msgpack-python and cbor are installed first, using:
# sudo apt-get install python-dev
# sudo apt-get install python-pip
# pip install --user msgpack-python msgpack-rpc-python cbor
# Ensure all "string" keys are utf strings (else encoded as bytes)
import cbor, msgpack, msgpackrpc, sys, os, threading
def get_test_data_list():
# get list with all primitive types, and a combo type
l0 = [
-8,
-1616,
-32323232,
-6464646464646464,
192,
1616,
32323232,
6464646464646464,
192,
-3232.0,
-6464646464.0,
3232.0,
6464.0,
6464646464.0,
False,
True,
u"null",
None,
u"someday",
1328176922000002000,
u"",
-2206187877999998000,
u"bytestring",
270,
u"none",
-2013855847999995777,
#-6795364578871345152,
]
l1 = [
{ "true": True,
"false": False },
{ "true": u"True",
"false": False,
"uint16(1616)": 1616 },
{ "list": [1616, 32323232, True, -3232.0, {"TRUE":True, "FALSE":False}, [True, False] ],
"int32":32323232, "bool": True,
"LONG STRING": u"123456789012345678901234567890123456789012345678901234567890",
"SHORT STRING": u"1234567890" },
{ True: "true", 138: False, "false": 200 }
]
l = []
l.extend(l0)
l.append(l0)
l.append(1)
l.extend(l1)
return l
def build_test_data(destdir):
l = get_test_data_list()
for i in range(len(l)):
# packer = msgpack.Packer()
serialized = msgpack.dumps(l[i])
f = open(os.path.join(destdir, str(i) + '.msgpack.golden'), 'wb')
f.write(serialized)
f.close()
serialized = cbor.dumps(l[i])
f = open(os.path.join(destdir, str(i) + '.cbor.golden'), 'wb')
f.write(serialized)
f.close()
def doRpcServer(port, stopTimeSec):
class EchoHandler(object):
def Echo123(self, msg1, msg2, msg3):
return ("1:%s 2:%s 3:%s" % (msg1, msg2, msg3))
def EchoStruct(self, msg):
return ("%s" % msg)
addr = msgpackrpc.Address('localhost', port)
server = msgpackrpc.Server(EchoHandler())
server.listen(addr)
# run thread to stop it after stopTimeSec seconds if > 0
if stopTimeSec > 0:
def myStopRpcServer():
server.stop()
t = threading.Timer(stopTimeSec, myStopRpcServer)
t.start()
server.start()
def doRpcClientToPythonSvc(port):
address = msgpackrpc.Address('localhost', port)
client = msgpackrpc.Client(address, unpack_encoding='utf-8')
print client.call("Echo123", "A1", "B2", "C3")
print client.call("EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"})
def doRpcClientToGoSvc(port):
# print ">>>> port: ", port, " <<<<<"
address = msgpackrpc.Address('localhost', port)
client = msgpackrpc.Client(address, unpack_encoding='utf-8')
print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"])
print client.call("TestRpcInt.EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"})
def doMain(args):
if len(args) == 2 and args[0] == "testdata":
build_test_data(args[1])
elif len(args) == 3 and args[0] == "rpc-server":
doRpcServer(int(args[1]), int(args[2]))
elif len(args) == 2 and args[0] == "rpc-client-python-service":
doRpcClientToPythonSvc(int(args[1]))
elif len(args) == 2 and args[0] == "rpc-client-go-service":
doRpcClientToGoSvc(int(args[1]))
else:
print("Usage: test.py " +
"[testdata|rpc-server|rpc-client-python-service|rpc-client-go-service] ...")
if __name__ == "__main__":
doMain(sys.argv[1:])
| packer-builder-xenserver-master | vendor/github.com/ugorji/go/codec/test.py |
import yaml
from pathlib import Path
import json
import humanize
def load_hosts(hosts_file):
with open(hosts_file, "r", encoding="utf-8") as file:
data = yaml.safe_load(file)
dgx_nodes = data.get("aisloader_hosts").get("hosts")
return dgx_nodes.keys()
def read_results(host_list, bench_type, bench_size):
directory = f"output/{bench_type}/{bench_size}"
base_name = f"bench-{bench_size}-{bench_type}-"
host_results = {}
# load all the output files
for host in host_list:
filename = f"{base_name}aistore{host}.json"
outfile = Path(directory).joinpath(filename)
with open(str(outfile), "r", encoding="utf-8") as file:
content = file.read()
host_results[host] = {"results": json.loads(content)}
return host_results
# min, avg, max
def get_latencies(bench_res, bench_type):
final_stats = bench_res[-1].get(bench_type)
return (
final_stats.get("min_latency"),
final_stats.get("latency"),
final_stats.get("max_latency"),
)
def get_final_throughput(bench_res, bench_type):
final_stats = bench_res[-1].get(bench_type)
return final_stats.get("throughput")
def combine_results(result_dict, bench_type):
total_lat_min = 10000000000000000
total_lat_max = 0
lats = []
tputs = []
for host_values in result_dict.values():
host_res = host_values.get("results")
min_lat, avg_lat, max_lat = get_latencies(host_res, bench_type)
if min_lat < total_lat_min:
total_lat_min = min_lat
if max_lat > total_lat_max:
total_lat_max = max_lat
lats.append(int(avg_lat))
tputs.append(int(get_final_throughput(host_res, bench_type)))
avg_lat = sum(lats) / len(lats)
total_tput = sum(tputs)
return total_lat_min, avg_lat, total_lat_max, total_tput
def get_natural_time(raw_time):
units = ["ns", "µs", "ms", "s"]
unit_index = 0
while raw_time >= 1000 and unit_index < len(units) - 1:
raw_time /= 1000
unit_index += 1
return f"{raw_time:.2f} {units[unit_index]}"
def pretty_print_res(bench_type, bench_size, res, total_drives):
lat_min, avg_lat, lat_max, total_tput = res
print(f"Benchmark results for type {bench_type} with size {bench_size}")
print("Latencies: ")
print(
f"min: {get_natural_time(lat_min)}, avg: {get_natural_time(avg_lat)}, max: {get_natural_time(lat_max)}"
)
print(
f"Cluster average throughput: {humanize.naturalsize(total_tput, binary=True)}/s ({humanize.naturalsize(total_tput/total_drives, binary=True)}/s per drive)"
)
print()
def main(configs, args):
for config in configs:
bench_type, bench_size = config
# load hosts from ansible yaml file
host_list = load_hosts(args.host_file)
results = read_results(host_list, bench_type, bench_size)
combined_results = combine_results(results, bench_type)
pretty_print_res(
bench_type, bench_size, combined_results, total_drives=args.total_drives
)
if __name__ == "__main__":
bench_runs = [
("get", "100MB"),
("put", "100MB"),
("put", "10MB"),
("get", "10MB"),
("put", "1MB"),
("get", "1MB"),
]
import argparse
parser = argparse.ArgumentParser(
description="Parses and combines results from multiple aisloader outputs"
)
parser.add_argument(
"--host_file",
default="inventory.yaml",
help="Filename containing ansible hosts",
)
parser.add_argument(
"--total_drives",
type=int,
default=30,
help="Number of drives on the AIS cluster being tested",
)
parser.add_argument(
"--aisloader_hosts",
default="dgx_nodes",
help="Name of hosts running the aisloader benchmark",
)
run_args = parser.parse_args()
main(bench_runs, run_args)
| aistore-master | bench/tools/aisloader-composer/parse_results.py |
__version__ = "1.4.13"
| aistore-master | python/aistore/version.py |
"""
This module is a temporary patch to support the torchdata integration for AIStore SDK versions > 1.04.
Torchdata expects the sdk structure to have aistore.client.Client, but Client now exists in aistore.sdk.client
"""
# pylint: disable=unused-variable,unused-import
from aistore.sdk.client import Client
| aistore-master | python/aistore/client.py |
import logging
from aistore.sdk.client import Client
from aistore.version import __version__
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
| aistore-master | python/aistore/__init__.py |
#
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
"""
Allow use of Amazon's boto3 and botocore libraries with AIStore.
If you would like to interact with AIStore using the popular
boto3 (or botocore) libraries, you can do so by importing this
module (you'll also need to install wrapt):
```
import wrapt
from aistore.botocore_patch import botocore
```
By way of explanation: by default, botocore (used by boto3)
does not respect HTTP redirects that make use of the
`location` header. Since AIStore uses them for load
balancing, trying to use boto without patching it first
results in various ClientErrors.
Importing this module patches the botocore library to respect
the location header under the same conditions used by AIStore:
the response code is 301, 302 or 307, and the "location" header
is set.
"""
import inspect
import wrapt
# pylint: disable=unused-argument
def _ais_redirect_wrapper(wrapped, instance, args, kwargs):
"""
Intercept S3 redirections from AIStore and patch them to:
- Respect HTTP 301, 302 or 307 redirects using the 'Location' header
- Fail after 3 redirects for a given operation (rather than just one)
We make no attempt to differentiate semantically between different 3XX
codes; we just reuse the same method and request context, and hit the
url specified by the "location" response header.
We also don't try to handle caching via 'Cache-Control' or 'Expires'
(though we might, later).
"""
response = kwargs.get("response")
request_dict = kwargs.get("request_dict")
intercept_criteria = [
lambda: response is not None,
lambda: isinstance(response, tuple) and isinstance(request_dict, dict),
lambda: response[0].status_code in [301, 302, 307],
lambda: request_dict["context"]["s3_redirect"].get("ais_redirect_count", 0)
<= 3,
lambda: {k.lower(): v for k, v in response[0].headers.items()}.get("location"),
]
try:
if not all(i() for i in intercept_criteria):
return wrapped(*args, **kwargs)
except Exception: # pylint: disable=broad-except
return wrapped(*args, **kwargs)
if request_dict["context"]["s3_redirect"].get("ais_redirect_count") is None:
request_dict["context"]["s3_redirect"]["ais_redirect_count"] = 0
request_dict["context"]["s3_redirect"]["ais_redirect_count"] += 1
request_dict["url"] = response[0].headers["location"]
return 0
@wrapt.when_imported("botocore.utils")
def _apply_patches(module): # pylint: disable=unused-variable
"""
When botocore.utils is imported, patch it to handle redirects.
We can't future proof against everything, but we make a reasonable
effort to find all likely "S3RegionRedirector" type classes below
(at time of writing there are two, "S3RegionRedirector" and "S3RegionRedirectorv2".
If the S3RegionRedirector.redirect_on_error method bound to each
fails to match our signature, we'll bail.
"""
redirectors = [
c[1]
for c in inspect.getmembers(module, inspect.isclass)
if "S3RegionRedirector" in c[0]
]
def _expected_sig(self, request_dict, response, operation, **kwargs):
pass
for redirector in redirectors:
assert inspect.signature(redirector.redirect_from_error) == inspect.signature(
_expected_sig
)
wrapt.wrap_function_wrapper(
module, redirector.__name__ + ".redirect_from_error", _ais_redirect_wrapper
)
| aistore-master | python/aistore/botocore_patch/botocore.py |
aistore-master | python/aistore/botocore_patch/__init__.py |
|
#
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
import sys
import base64
from typing import Callable, List
import cloudpickle
from aistore.sdk.const import (
HTTP_METHOD_DELETE,
HTTP_METHOD_GET,
HTTP_METHOD_POST,
HTTP_METHOD_PUT,
URL_PATH_ETL,
UTF_ENCODING,
)
from aistore.sdk.etl_const import (
ETL_SUPPORTED_PYTHON_VERSIONS,
DEFAULT_ETL_RUNTIME,
DEFAULT_ETL_COMM,
DEFAULT_ETL_TIMEOUT,
ETL_COMM_SPEC,
ETL_COMM_CODE,
CODE_TEMPLATE,
)
from aistore.sdk.types import ETLDetails, InitCodeETLArgs, InitSpecETLArgs
def _get_default_runtime():
"""
Determines etl runtime to use if not specified
Returns:
String of runtime
"""
version = f"{sys.version_info.major}.{sys.version_info.minor}"
if version in ETL_SUPPORTED_PYTHON_VERSIONS:
return f"python{version}v2"
return DEFAULT_ETL_RUNTIME
# pylint: disable=unused-variable
def _validate_comm_type(given: str, valid: List[str]):
if given not in valid:
valid_str = ", ".join(valid)
raise ValueError(f"communication_type should be one of: {valid_str}")
class Etl:
"""
A class containing ETL-related functions.
"""
def __init__(self, client: "Client", name: str):
self._client = client
self._name = name
@property
def name(self) -> str:
"""Name of the ETL"""
return self._name
def init_spec(
self,
template: str,
communication_type: str = DEFAULT_ETL_COMM,
timeout: str = DEFAULT_ETL_TIMEOUT,
arg_type: str = "",
) -> str:
"""
Initializes ETL based on Kubernetes pod spec template.
Args:
template (str): Kubernetes pod spec template
Existing templates can be found at `sdk.etl_templates`
For more information visit: https://github.com/NVIDIA/ais-etl/tree/master/transformers
communication_type (str): Communication type of the ETL (options: hpull, hrev, hpush)
timeout (str): Timeout of the ETL job (e.g. 5m for 5 minutes)
Returns:
Job ID string associated with this ETL
"""
_validate_comm_type(communication_type, ETL_COMM_SPEC)
# spec
spec_encoded = base64.b64encode(template.encode(UTF_ENCODING)).decode(
UTF_ENCODING
)
value = InitSpecETLArgs(
spec=spec_encoded,
etl_name=self._name,
communication_type=communication_type,
timeout=timeout,
arg_type=arg_type,
).as_dict()
return self._client.request(HTTP_METHOD_PUT, path=URL_PATH_ETL, json=value).text
# pylint: disable=too-many-arguments
def init_code(
self,
transform: Callable,
dependencies: List[str] = None,
preimported_modules: List[str] = None,
runtime: str = _get_default_runtime(),
communication_type: str = DEFAULT_ETL_COMM,
timeout: str = DEFAULT_ETL_TIMEOUT,
chunk_size: int = None,
arg_type: str = "",
) -> str:
"""
Initializes ETL based on the provided source code.
Args:
transform (Callable): Transform function of the ETL
dependencies (list[str]): Python dependencies to install
preimported_modules (list[str]): Modules to import before running the transform function. This can
be necessary in cases where the modules used both attempt to import each other circularly
runtime (str): [optional, default= V2 implementation of the current python version if supported, else
python3.8v2] Runtime environment of the ETL [choose from: python3.8v2, python3.10v2, python3.11v2]
(see ext/etl/runtime/all.go)
communication_type (str): [optional, default="hpush"] Communication type of the ETL (options: hpull, hrev,
hpush, io)
timeout (str): [optional, default="5m"] Timeout of the ETL job (e.g. 5m for 5 minutes)
chunk_size (int): Chunk size in bytes if transform function in streaming data.
(whole object is read by default)
arg_type (optional, str): The type of argument the runtime will provide the transform function.
The default value of "" will provide the raw bytes read from the object.
When used with hpull communication_type, setting this to "url" will provide the URL of the object.
Returns:
Job ID string associated with this ETL
"""
_validate_comm_type(communication_type, ETL_COMM_CODE)
# code functions to call
functions = {
"transform": "transform",
}
value = InitCodeETLArgs(
etl_name=self._name,
runtime=runtime,
communication_type=communication_type,
timeout=timeout,
dependencies=self._encode_dependencies(dependencies),
functions=functions,
code=self._encode_transform(
transform, preimported_modules, communication_type
),
chunk_size=chunk_size,
arg_type=arg_type,
).as_dict()
return self._client.request(
HTTP_METHOD_PUT,
path=URL_PATH_ETL,
json=value,
).text
def view(self) -> ETLDetails:
"""
View ETL details
Returns:
ETLDetails: details of the ETL
"""
resp = self._client.request_deserialize(
HTTP_METHOD_GET, path=f"{URL_PATH_ETL}/{self._name}", res_model=ETLDetails
)
return resp
def start(self):
"""
Resumes a stopped ETL with given ETL name.
Note: Deleted ETLs cannot be started.
"""
self._client.request(
HTTP_METHOD_POST, path=f"{URL_PATH_ETL}/{self._name}/start"
)
def stop(self):
"""
Stops ETL. Stops (but does not delete) all the pods created by Kubernetes for this ETL and
terminates any transforms.
"""
self._client.request(HTTP_METHOD_POST, path=f"{URL_PATH_ETL}/{self._name}/stop")
def delete(self):
"""
Delete ETL. Deletes pods created by Kubernetes for this ETL and specifications for this ETL
in Kubernetes.
Note: Running ETLs cannot be deleted.
"""
self._client.request(HTTP_METHOD_DELETE, path=f"{URL_PATH_ETL}/{self._name}")
@staticmethod
def _encode_transform(
transform: Callable,
preimported_modules: List[str] = None,
comm_type: str = None,
):
transform = base64.b64encode(cloudpickle.dumps(transform)).decode(UTF_ENCODING)
io_comm_context = "transform()" if comm_type == "io" else ""
modules = preimported_modules if preimported_modules else []
template = CODE_TEMPLATE.format(modules, transform, io_comm_context).encode(
UTF_ENCODING
)
return base64.b64encode(template).decode(UTF_ENCODING)
@staticmethod
def _encode_dependencies(dependencies: List[str]):
if dependencies is None:
dependencies = []
dependencies.append("cloudpickle==2.2.0")
deps = "\n".join(dependencies).encode(UTF_ENCODING)
return base64.b64encode(deps).decode(UTF_ENCODING)
| aistore-master | python/aistore/sdk/etl.py |
#
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
from urllib.parse import urljoin, urlencode
from typing import TypeVar, Type, Any, Dict
import requests
from aistore.sdk.const import (
JSON_CONTENT_TYPE,
HEADER_USER_AGENT,
USER_AGENT_BASE,
HEADER_CONTENT_TYPE,
HEADERS_KW,
)
from aistore.sdk.utils import handle_errors, decode_response
from aistore.version import __version__ as sdk_version
T = TypeVar("T")
# pylint: disable=unused-variable
class RequestClient:
"""
Internal client for buckets, objects, jobs, etc. to use for making requests to an AIS cluster
Args:
endpoint (str): AIStore endpoint
"""
def __init__(self, endpoint: str):
self._endpoint = endpoint
self._base_url = urljoin(endpoint, "v1")
self._session = requests.session()
@property
def base_url(self):
"""
Returns: AIS cluster base url
"""
return self._base_url
@property
def endpoint(self):
"""
Returns: AIS cluster endpoint
"""
return self._endpoint
@property
def session(self):
"""
Returns: Active request session
"""
return self._session
def request_deserialize(
self, method: str, path: str, res_model: Type[T], **kwargs
) -> T:
"""
Make a request to the AIS cluster and deserialize the response to a defined type
Args:
method (str): HTTP method, e.g. POST, GET, PUT, DELETE
path (str): URL path to call
res_model (Type[T]): Resulting type to which the response should be deserialized
**kwargs (optional): Optional keyword arguments to pass with the call to request
Returns:
Parsed result of the call to the API, as res_model
"""
resp = self.request(method, path, **kwargs)
return decode_response(res_model, resp)
def request(self, method: str, path: str, **kwargs) -> requests.Response:
"""
Make a request to the AIS cluster
Args:
method (str): HTTP method, e.g. POST, GET, PUT, DELETE
path (str): URL path to call
**kwargs (optional): Optional keyword arguments to pass with the call to request
Returns:
Raw response from the API
"""
url = f"{self._base_url}/{path.lstrip('/')}"
if HEADERS_KW not in kwargs:
kwargs[HEADERS_KW] = {}
headers = kwargs.get(HEADERS_KW, {})
headers[HEADER_CONTENT_TYPE] = JSON_CONTENT_TYPE
headers[HEADER_USER_AGENT] = f"{USER_AGENT_BASE}/{sdk_version}"
resp = self._session.request(
method,
url,
**kwargs,
)
if resp.status_code < 200 or resp.status_code >= 300:
handle_errors(resp)
return resp
def get_full_url(self, path: str, params: Dict[str, Any]):
"""
Get the full URL to the path on the cluster with the parameters given
Args:
path: Path on the cluster
params: Query parameters to include
Returns:
URL including cluster base url and parameters
"""
return f"{self._base_url}/{path.lstrip('/')}?{urlencode(params)}"
| aistore-master | python/aistore/sdk/request_client.py |
# Returns the MD5 sum of the original data as the response.
# pylint: disable=unused-variable
MD5 = """
apiVersion: v1
kind: Pod
metadata:
name: transformer-md5
annotations:
# Values it can take ["hpull://","hrev://","hpush://"]
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_md5:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 80
command: ['/code/server.py', '--listen', '0.0.0.0', '--port', '80']
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns "Hello World!" on any request.
# pylint: disable=unused-variable
HELLO_WORLD = """
apiVersion: v1
kind: Pod
metadata:
name: transformer-hello-world
annotations:
# Values it can take ["hpull://","hrev://","hpush://"]
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_hello_world:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 8000
command: ["gunicorn", "main:app", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"]
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns "Hello World!" on any request.
# pylint: disable=unused-variable
GO_HELLO_WORLD = """
apiVersion: v1
kind: Pod
metadata:
name: hello-world-go-transformer
annotations:
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_hello_world_go:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 80
command: ['./echo', '-l', '0.0.0.0', '-p', '80']
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns the original data, with an MD5 sum in the response headers.
# pylint: disable=unused-variable
GO_ECHO = """
apiVersion: v1
kind: Pod
metadata:
name: echo-go
annotations:
# Values it can take ["hpull://","hrev://","hpush://"]
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_echo_go:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 80
command: ['./echo', '-l', '0.0.0.0', '-p', '80']
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns the original data, with an MD5 sum in the response headers.
# pylint: disable=unused-variable
ECHO = """
apiVersion: v1
kind: Pod
metadata:
name: transformer-echo
annotations:
# Values it can take ["hpull://","hrev://","hpush://"]
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_echo:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 8000
command: ["gunicorn", "main:app", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"]
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns the transformed TensorFlow compatible data for the input TAR files. For
# more information on command options, visit
# https://github.com/NVIDIA/ais-etl/blob/master/transformers/tar2tf/README.md.
# pylint: disable=unused-variable
TAR2TF = """
apiVersion: v1
kind: Pod
metadata:
name: tar2tf
annotations:
# Values it can take ["hpull://","hrev://","hpush://"]
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_tar2tf:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 80
# To enable conversion e.g.
command: ['./tar2tf', '-l', '0.0.0.0', '-p', '80', '{arg}', '{val}']
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns the compressed/decompressed file. For more information on command options, visit
# https://github.com/NVIDIA/ais-etl/blob/master/transformers/compress/README.md.
# pylint: disable=unused-variable
COMPRESS = """
apiVersion: v1
kind: Pod
metadata:
name: transformer-compress
annotations:
# Values `communication_type` can take are ["hpull://", "hrev://", "hpush://", "io://"].
# Visit https://github.com/NVIDIA/aistore/blob/master/docs/etl.md#communication-mechanisms
# for more details.
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_compress:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 80
command: ['/code/server.py', '--listen', '0.0.0.0', '--port', '80']
env:
# COMPRESS_OPTIONS is a dictionary (JSON string) of additional parameters
# `mode` and `compression`. For more information on additional parameters, refer to
# https://github.com/NVIDIA/ais-etl/blob/master/transformers/compress/README.md.
- name: COMPRESS_OPTIONS
value: '{compress_options}'
readinessProbe:
httpGet:
path: /health
port: default
"""
# pylint: disable=unused-variable
KERAS_TRANSFORMER = """
apiVersion: v1
kind: Pod
metadata:
name: transformer-keras
annotations:
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_keras:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 8000
command: ["gunicorn", "main:app", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"]
env:
- name: FORMAT
value: "{format}"
- name: TRANSFORM
value: '{transform}'
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns the FFMPEG decoded content. For more information on command options, visit
# https://github.com/NVIDIA/ais-etl/blob/master/transformers/ffmpeg/README.md.
# pylint: disable=unused-variable
FFMPEG = """
apiVersion: v1
kind: Pod
metadata:
name: transformer-ffmpeg
annotations:
communication_type: "{communication_type}://"
wait_timeout: 5m
spec:
containers:
- name: server
image: aistorage/transformer_ffmpeg:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 80
command: ['/code/server.py', '--listen', '0.0.0.0', '--port', '80']
env:
# FFMPEG_OPTIONS is a dictionary (JSON string) of FFMPEG decode parameters. For more information on
# FFMPEG decode parameters, refer to https://ffmpeg.org/ffmpeg.html#Synopsis.
- name: FFMPEG_OPTIONS
value: '{ffmpeg_options}'
readinessProbe:
httpGet:
path: /health
port: default
"""
# Returns the transformed images using `Torchvision` pre-processing. For more
# information on command options, visit
# https://github.com/NVIDIA/ais-etl/blob/master/transformers/torchvision_preprocess/README.md.
# pylint: disable=unused-variable
TORCHVISION_TRANSFORMER = """
apiVersion: v1
kind: Pod
metadata:
name: transformer-torchvision
annotations:
# Values `communication_type` can take are ["hpull://", "hrev://", "hpush://", "io://"].
# Visit https://github.com/NVIDIA/aistore/blob/master/docs/etl.md#communication-mechanisms
communication_type: "{communication_type}://"
wait_timeout: 10m
spec:
containers:
- name: server
image: aistorage/transformer_torchvision:latest
imagePullPolicy: Always
ports:
- name: default
containerPort: 8000
command: ["gunicorn", "main:app", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000"]
env:
- name: FORMAT
# expected values - PNG, JPEG, etc
value: "{format}"
- name: TRANSFORM
value: '{transform}'
readinessProbe:
httpGet:
path: /health
port: default
"""
| aistore-master | python/aistore/sdk/etl_templates.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.