Пример #1
0
def deparse_code_with_fragments_and_map(*args, **kwargs):
    """
    Like deparse_code_with_map but saves fragments.
    Deprecated. Use code_deparse_with_fragments_and_map
    """
    kwargs['walker'] = LineMapFragmentWalker
    return fragments.deparse_code(*args, **kwargs)
Пример #2
0
    def run(self, args):
        co = self.proc.curframe.f_code
        name = co.co_name
        last_i = self.proc.curframe.f_lasti
        if last_i == -1: last_i = 0

        sys_version = version_info[0] + (version_info[1] / 10.0)
        try:
            deparsed = deparse_code(sys_version, co, is_pypy=IS_PYPY)
            nodeInfo = deparsed_find((name, last_i), deparsed, co)
            if not nodeInfo:
                self.errmsg("Can't find exact offset %d" % last_i)
                return
        except:
            self.errmsg("error in deparsing code")
            return
        if '?' == args[0][-1]:
            extractInfo = deparsed.extract_node_info(nodeInfo.node)
        else:
            extractInfo, _ = deparsed.extract_parent_info(nodeInfo.node)
        text = extractInfo.selectedText
        text = text.strip()
        self.msg("Evaluating: %s" % text)
        try:
            self.proc.exec_line(text)
        except:
            pass
Пример #3
0
    def run(self, args):
        co = self.proc.curframe.f_code
        name = co.co_name
        last_i = self.proc.curframe.f_lasti
        if last_i == -1: last_i = 0

        sys_version = version_info[0] + (version_info[1] / 10.0)
        try:
            deparsed = deparse_code(sys_version, co, is_pypy=IS_PYPY)
            nodeInfo = deparsed_find((name, last_i), deparsed, co)
            if not nodeInfo:
                self.errmsg("Can't find exact offset %d" % last_i)
                return
        except:
            self.errmsg("error in deparsing code")
            return
        if '?' == args[0][-1]:
            extractInfo = deparsed.extract_node_info(nodeInfo.node)
        else:
            extractInfo, _ = deparsed.extract_parent_info(nodeInfo.node)
        text = extractInfo.selectedText
        text = text.strip()
        self.msg("Evaluating: %s" % text)
        try:
            self.proc.exec_line(text)
        except:
            pass
Пример #4
0
def deparse_fn(code):
    try:
        from uncompyle6.semantics.fragments import deparse_code
    except ImportError:
        return None
    sys_version = sys.version_info[0] + (sys.version_info[1] / 10.0)
    try:
        deparsed = deparse_code(sys_version, code, is_pypy=IS_PYPY)
        return deparsed.text.strip()
    except:
        raise
    return None
Пример #5
0
def print_tb(tb, limit=None, file=None, verbosity=0):
    """Print up to 'limit' stack trace entries from the traceback 'tb'.

    If 'limit' is omitted or None, all entries are printed.  If 'file'
    is omitted or None, the output goes to sys.stderr; otherwise
    'file' should be an open file or file-like object with a write()
    method.
    """
    if file is None:
        file = sys.stderr
    if limit is None:
        if hasattr(sys, 'tracebacklimit'):
            limit = sys.tracebacklimit
    n = 0
    nodeInfo = None
    while tb is not None and (limit is None or n < limit):
        f = tb.tb_frame
        lineno = tb.tb_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name

        linecache.checkcache(filename)
        _print(file,
               '  File "%s", line %d, in %s' % (filename, lineno, name))

        if verbosity > 0:
            try:
               deparsed = deparse_code(SYS_VERSION, co)
               from trepan.api import debug; debug()
               nodeInfo = deparsed_find((name, f.f_lasti), deparsed, co)
            except:
                pass

            if nodeInfo:
                extractInfo = deparsed.extract_node_info(nodeInfo)
                _print(file, extractInfo.selectedLine)
                _print(file, extractInfo.markerLine)

            if verbosity > 1:
                _print(file, "instruction: %s" % (nodeInfo.node))

        line = linecache.getline(filename, lineno, f.f_globals)
        if line: _print(file, '    ' + line.strip())
        tb = tb.tb_next
        n = n+1
Пример #6
0
    def run(self, args):
        co = self.proc.curframe.f_code
        name = co.co_name

        try:
            opts, args = getopt(args[1:], "hpPAto:O", [
                "help", "parent", "pretty", "AST", 'tree', "offset=", "offsets"
            ])
        except GetoptError as err:
            # print help information and exit:
            print(str(
                err))  # will print something like "option -a not recognized"
            return

        show_parent = False
        show_ast = False
        offset = None
        show_offsets = False
        for o, a in opts:
            if o in ("-h", "--help"):
                self.proc.commands['help'].run(['help', 'deparse'])
                return
            elif o in ("-O", "--offsets"):
                show_offsets = True
            elif o in ("-p", "--parent"):
                show_parent = True
            elif o in ("-A", "--tree", '--AST'):
                show_ast = True
            elif o in ("-o", '--offset'):
                offset = a
            else:
                self.errmsg("unhandled option '%s'" % o)
            pass
        pass
        nodeInfo = None

        try:
            float_version = sysinfo2float()
        except:
            self.errmsg(sys.exc_info()[1])
            return
        if len(args) >= 1 and args[0] == '.':
            temp_filename, name_for_code = deparse_and_cache(co, self.errmsg)
            if not temp_filename:
                return
            self.print_text(''.join(getlines(temp_filename)))
            return
        elif show_offsets:
            deparsed = deparse_code(float_version, co, is_pypy=IS_PYPY)
            self.section("Offsets known:")
            m = self.columnize_commands(
                list(sorted(deparsed.offsets.keys(), key=lambda x: str(x[0]))))
            self.msg_nocr(m)
            return
        elif offset is not None:
            mess = ("The 'deparse' command when given an argument requires an"
                    " instruction offset. Got: '%s'" % offset)
            last_i = self.proc.get_an_int(offset, mess)
            if last_i is None:
                return
        else:
            last_i = self.proc.curframe.f_lasti
            if last_i == -1: last_i = 0

        try:
            deparsed = deparse_code(float_version, co, is_pypy=IS_PYPY)
            nodeInfo = deparsed_find((name, last_i), deparsed, co)
            if not nodeInfo:
                self.errmsg(
                    "Can't find exact offset %d; giving inexact results" %
                    last_i)
                deparsed = deparse_code_around_offset(co.co_name,
                                                      last_i,
                                                      float_version,
                                                      co,
                                                      is_pypy=IS_PYPY)
        except:
            self.errmsg(sys.exc_info()[1])
            self.errmsg("error in deparsing code at offset %d" % last_i)
            return
        if not nodeInfo:
            nodeInfo = deparsed_find((name, last_i), deparsed, co)
        if nodeInfo:
            extractInfo = deparsed.extract_node_info(nodeInfo)
            parentInfo = None
            # print extractInfo
            if show_ast:
                p = deparsed.ast
                if show_parent:
                    parentInfo, p = deparsed.extract_parent_info(nodeInfo.node)
                self.msg(p)
            if extractInfo:
                self.rst_msg("*instruction:* %s" % (nodeInfo.node))
                self.print_text(extractInfo.selectedLine)
                self.msg(extractInfo.markerLine)
                if show_parent:
                    if not parentInfo:
                        parentInfo, p = deparsed.extract_parent_info(
                            nodeInfo.node)
                    if parentInfo:
                        self.section("Contained in...")
                        self.rst_msg("\t*Grammar Symbol:* %s" % p.kind)
                        self.print_text(parentInfo.selectedLine)
                        self.msg(parentInfo.markerLine)
                    pass
                pass
            pass
        elif last_i == -1:
            if name:
                self.msg("At beginning of %s " % name)
            elif self.core.filename(None):
                self.msg("At beginning of program %s" %
                         self.core.filename(None))
            else:
                self.msg("At beginning")
        else:
            self.errmsg(
                "haven't recorded info for offset %d. Offsets I know are:" %
                last_i)
            m = self.columnize_commands(
                list(sorted(deparsed.offsets.keys(), key=lambda x: str(x[0]))))
            self.msg_nocr(m)
        return
Пример #7
0
f1 = define_func(2, 2, b'|\x00|\x01k\x02S\x00', (None, ), ())
f2 = define_func(1, 1, b't\x00|\x00\x83\x01S\x00', (None, ), ('ord', ))
f3 = define_func(0, 0, b't\x00d\x01\x83\x01S\x00', (None, 'Give me flag: '),
                 ('input', ))
f4 = define_func(
    1, 3,
    b'd\x01d\x02d\x03d\x04d\x05d\x01d\x06d\x07d\x08d\td\x03d\nd\x0bd\x0cd\rd\x08d\x0cd\x0ed\x0cd\x0fd\x0ed\x10d\x11d\td\x12d\x03d\x10d\x03d\x0ed\x13d\x0bd\nd\x14d\x08d\x13d\x01d\x01d\nd\td\x01d\x12d\x0bd\x10d\x0fd\x14d\x03d\x0bd\x15d\x16g1}\x01t\x00|\x00\x83\x01t\x00|\x01\x83\x01k\x03r\x82t\x01d\x17\x83\x01\x01\x00d\x18S\x00t\x02|\x00|\x01\x83\x02D\x00]$}\x02t\x03|\x02d\x19\x19\x00t\x04|\x02d\x1a\x19\x00\x83\x01\x83\x02d\x18k\x02r\x8c\x01\x00d\x18S\x00q\x8cd\x1bS\x00',
    (None, 99, 121, 98, 114, 105, 115, 123, 52, 97, 100, 51, 101, 55, 57, 53,
     54, 48, 49, 50, 56, 102, 125, 'Length mismatch!', False, 1, 0, True),
    ('len', 'print', 'zip', 'f1', 'f2'))
f5 = define_func(
    0, 1,
    b't\x00\x83\x00}\x00t\x01|\x00\x83\x01d\x01k\x08r\x1ct\x02d\x02\x83\x01\x01\x00n\x08t\x02d\x03\x83\x01\x01\x00d\x00S\x00',
    (None, False, 'Nope!', 'Yep!'), ('f3', 'f4', 'print'))

from uncompyle6.semantics.fragments import deparse_code
funcs = [f1, f2, f3, f4, f5]
for i, fun in enumerate(funcs):
    print('-' * 10, "Function", i + 1, '-' * 10)
    print(deparse_code(3.8, fun.__code__).text)
print(''.join([
    chr(x) for x in [
        99, 121, 98, 114, 105, 99, 115, 123, 52, 97, 98, 100, 51, 101, 55, 52,
        101, 57, 101, 53, 57, 54, 48, 97, 49, 98, 54, 98, 57, 50, 51, 100, 56,
        52, 50, 99, 99, 100, 97, 99, 49, 51, 54, 53, 56, 98, 51, 102, 125
    ]
]))

# f5()
Пример #8
0
    def run(self, args):
        co = self.proc.curframe.f_code
        name = co.co_name

        try:
            opts, args = getopt(args[1:], "hpAPo:",
                                ["help", "parent", "pretty", "tree", "AST",
                                 "offset"])
        except GetoptError as err:
            # print help information and exit:
            print(str(err))  # will print something like "option -a not recognized"
            return

        pretty = False
        show_parent = False
        show_ast = False
        offset = None
        for o, a in opts:
            if o in ("-h", "--help"):
                self.proc.commands['help'].run(['help', 'deparse'])
                return
            elif o in ("-p", "--parent"):
                show_parent = True
            elif o in ("-P", "--pretty"):
                pretty = True
            elif o in ("-A", "--tree", '--AST'):
                show_ast = True
            elif o in ("-o", '--offset'):
                offset = a
            else:
                self.errmsg("unhandled option %s" % o)
            pass
        pass

        sys_version = version_info.major + (version_info.minor / 10.0)
        if len(args) >= 1 and args[0] == '.':
            try:
                if pretty:
                    deparsed = deparse_code(sys_version, co)
                    text = deparsed.text
                else:
                    out = StringIO()
                    deparsed = deparse_code_pretty(sys_version, co, out)
                    text = out.getvalue()
                    pass
            except:
                self.errmsg("error in deparsing code")

                return
            self.print_text(text)
            return

        elif offset:
            mess = ("The 'deparse' command when given an argument requires an"
                    " instruction offset. Got: %s" % offset)
            last_i = self.proc.get_an_int(offset, mess)
            if last_i is None:
                return
        else:
            last_i = self.proc.curframe.f_lasti
            if last_i == -1: last_i = 0

        try:
            deparsed = deparse_code(sys_version, co)
        except:
            self.errmsg("error in deparsing code at %d" % last_i)
            return
        if (name, last_i) in deparsed.offsets.keys():
            nodeInfo =  deparsed.offsets[name, last_i]
            extractInfo = deparsed.extract_node_info(nodeInfo)
            parentInfo = None
            # print extractInfo
            if show_ast:
                p = deparsed.ast
                if show_parent:
                    parentInfo, p = deparsed.extract_parent_info(nodeInfo.node)
                self.msg(p)
            if extractInfo:
                self.msg("opcode: %s" % nodeInfo.node.type)
                self.print_text(extractInfo.selectedLine)
                self.msg(extractInfo.markerLine)
                if show_parent:
                    if not parentInfo:
                        parentInfo, p = deparsed.extract_parent_info(nodeInfo.node)
                    if parentInfo:
                        self.msg("Contained in...")
                        self.print_text(parentInfo.selectedLine)
                        self.msg(parentInfo.markerLine)
                        self.msg("parsed type: %s" % p.type)
                    pass
                pass
            pass
        elif last_i == -1:
            if name:
                self.msg("At beginning of %s " % name)
            elif self.core.filename(None):
                self.msg("At beginning of program %s" % self.core.filename(None))
            else:
                self.msg("At beginning")
        else:
            self.errmsg("haven't recorded info for offset %d. Offsets I know are:"
                        % last_i)
            offsets = sorted([(str(x[0]), str(x[1])) for x in tuple(deparsed.offsets)])
            m = self.columnize_commands(offsets)
            self.msg_nocr(m)
        return
Пример #9
0
    def run(self, args):
        # Can't do anything if we don't have uncompyle6 deparse
        try:
            from uncompyle6.semantics.fragments import deparse_code
            from uncompyle6.semantics.pysource import deparse_code as deparse_code_pretty
        except ImportError:
            self.errmsg("deparse needs to be installed to run this command")
            return

        co = self.proc.curframe.f_code
        name = co.co_name

        sys_version = version_info.major + (version_info.minor / 10.0)
        if len(args) >= 2 and args[1] == '.':
            try:
                if args[-1] == '-u':
                    deparsed = deparse_code(sys_version, co)
                    text = deparsed.text
                else:
                    out = StringIO()
                    deparsed = deparse_code_pretty(sys_version, co, out)
                    text = out.getvalue()
                    pass
            except:
                self.errmsg("error in deparsing code")

                return
            self.print_text(text)
            return

        elif ( (len(args) == 2 and args[1] != '-p')
             or len(args) == 3 and args[2] == '-p'):
            last_i = self.proc.get_an_int(args[1],
                                          ("The 'deparse' command when given an argument requires an"
                                           " instruction offset. Got: %s") %
                                          args[1])
            if last_i is None:
                return
        else:
            last_i = self.proc.curframe.f_lasti
            if last_i == -1: last_i = 0

        try:
            deparsed = deparse_code(sys_version, co)
        except:
            self.errmsg("error in deparsing code at %d" % last_i)
            return
        if (name, last_i) in deparsed.offsets.keys():
            nodeInfo =  deparsed.offsets[name, last_i]
            extractInfo = deparsed.extract_node_info(nodeInfo)
            # print extractInfo
            if extractInfo:
                self.msg("opcode: %s" % nodeInfo.node.type)
                self.print_text(extractInfo.selectedLine)
                self.msg(extractInfo.markerLine)
                if args[-1] == '-p':
                    extractInfo, p = deparsed.extract_parent_info(nodeInfo.node)
                    if extractInfo:
                        self.msg("Contained in...")
                        self.print_text(extractInfo.selectedLine)
                        self.msg(extractInfo.markerLine)
                        self.msg("parsed type: %s" % p.type)
                    pass
                pass
            pass
        elif last_i == -1:
            if name:
                self.msg("At beginning of %s " % name)
            elif self.core.filename(None):
                self.msg("At beginning of program %s" % self.core.filename(None))
            else:
                self.msg("At beginning")
        else:
            self.errmsg("haven't recorded info for offset %d. Offsets I know are:"
                        % last_i)
            m = self.columnize_commands(list(sorted(deparsed.offsets.keys(),
                                                    key=lambda x: str(x[0]))))
            self.msg_nocr(m)
        return