Exemplo n.º 1
0
    def _loadClass(self, name, subclasses):
        script_util.printVerbose("Loading " + name.encode('utf8')[:70])
        data = self._searchForFile(name)

        if data is None:
            raise ClassLoaderError('ClassNotFoundException', name)

        stream = binUnpacker.binUnpacker(data=data)
        new = ClassFile(stream)
        new.loadSupers(self, name, subclasses)
        self.classes[new.name] = new
        return new
Exemplo n.º 2
0
    def _loadClass(self, name, subclasses):
        script_util.printVerbose("Loading " + name.encode('utf8')[:70])
        data = self._searchForFile(name)

        if data is None:
            raise ClassLoaderError('ClassNotFoundException', name)

        stream = binUnpacker.binUnpacker(data=data)
        new = ClassFile(stream)
        new.loadSupers(self, name, subclasses)
        self.classes[new.name] = new
        return new
Exemplo n.º 3
0
def _getMethod(method, cb, forbidden_identifiers):
    try:
        graph = cb(method) if method.code is not None else None
        script_util.printVerbose('Decompiling method {} {}'.format(method.name.encode('utf8'), method.descriptor.encode('utf8')))
        code_ast = javamethod.generateAST(method, graph, forbidden_identifiers)
        return code_ast
    except Exception as e:
        if not IGNORE_EXCEPTIONS:
            raise
        if e.__class__.__name__ == 'DecompilationError':
            print 'Unable to decompile ' + method.class_.name
        else:
            print 'Decompiling {} failed!'.format(method.class_.name)
        code_ast = javamethod.generateAST(method, None, forbidden_identifiers)
        code_ast.comment = ' {0!r}: {0!s}'.format(e)
        return code_ast
Exemplo n.º 4
0
def _getMethod(method, cb, forbidden_identifiers):
    try:
        graph = cb(method) if method.code is not None else None
        script_util.printVerbose('Decompiling method {} {}'.format(
            method.name.encode('utf8'), method.descriptor.encode('utf8')))
        code_ast = javamethod.generateAST(method, graph, forbidden_identifiers)
        return code_ast
    except Exception as e:
        if not IGNORE_EXCEPTIONS:
            raise
        if e.__class__.__name__ == 'DecompilationError':
            print 'Unable to decompile ' + method.class_.name
        else:
            print 'Decompiling {} failed!'.format(method.class_.name)
        code_ast = javamethod.generateAST(method, None, forbidden_identifiers)
        code_ast.comment = ' {0!r}: {0!s}'.format(e)
        return code_ast
Exemplo n.º 5
0
def decompileClass(path=[], targets=None, outpath=None, skipMissing=False):
    writeout = script_util.fileDirOut(outpath, '.java')

    e = Environment()
    for part in path:
        e.addToPath(part)

    start_time = time.time()
    # random.shuffle(targets)
    with e: #keep jars open
        for i,target in enumerate(targets):
            script_util.printVerbose('processing target {}, {} remaining'.format(target, len(targets)-i))

            try:
                c = e.getClass(target)
                source = javaclass.generateAST(c, makeGraph).print_()
            except ClassLoaderError as err:
                if skipMissing:
                    print 'failed to decompile {} due to missing or invalid class {}'.format(target, err.data)
                    continue
                else:
                    raise

            #The single class decompiler doesn't add package declaration currently so we add it here
            if '/' in target:
                package = 'package {};\n\n'.format(target.replace('/','.').rpartition('.')[0])
                source = package + source

            filename = writeout(c.name, source)
            script_util.printVerbose('Class written to ' + filename)
            script_util.printVerbose('{} seconds elapsed'.format(time.time() - start_time))
            deleteUnusued(c)
Exemplo n.º 6
0
def disassembleClass(readTarget, targets=None, outpath=None):
    writeout = script_util.fileDirOut(outpath, '.j')

    # targets = targets[::-1]
    start_time = time.time()
    # __import__('random').shuffle(targets)
    for i,target in enumerate(targets):
        script_util.printVerbose('processing target {}, {}/{} remaining'.format(target, len(targets)-i, len(targets)))

        data = readTarget(target)
        stream = Krakatau.binUnpacker.binUnpacker(data=data)
        class_ = ClassFile(stream)
        class_.loadElements(keepRaw=True)

        source = Krakatau.assembler.disassembler.disassemble(class_)
        filename = writeout(class_.name, source)
        script_util.printVerbose('Class written to ' + filename)
        script_util.printVerbose('{} seconds elapsed'.format(time.time() - start_time))
Exemplo n.º 7
0
def disassembleClass(readTarget, targets=None, outpath=None):
    writeout = script_util.fileDirOut(outpath, '.j')

    # targets = targets[::-1]
    start_time = time.time()
    # __import__('random').shuffle(targets)
    for i, target in enumerate(targets):
        script_util.printVerbose(
            'processing target {}, {}/{} remaining'.format(
                target,
                len(targets) - i, len(targets)))

        data = readTarget(target)
        stream = Krakatau.binUnpacker.binUnpacker(data=data)
        class_ = ClassFile(stream)
        class_.loadElements(keepRaw=True)

        source = Krakatau.assembler.disassembler.disassemble(class_)
        filename = writeout(class_.name, source)
        script_util.printVerbose('Class written to ' + filename)
        script_util.printVerbose('{} seconds elapsed'.format(time.time() -
                                                             start_time))
Exemplo n.º 8
0
        filename = writeout(class_.name, source)
        script_util.printVerbose('Class written to ' + filename)
        script_util.printVerbose('{} seconds elapsed'.format(time.time() - start_time))

if __name__== "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Krakatau decompiler and bytecode analysis tool')
    parser.add_argument('-out',help='Path to generate files in')
    parser.add_argument('-r', action='store_true', help="Process all files in the directory target and subdirectories")
    parser.add_argument('-q', action='store_true', help="Quiet output; only show warnings or errors")
    parser.add_argument('-path',help='Jar to look for class in')
    parser.add_argument('target',help='Name of class or jar file to decompile')
    args = parser.parse_args()

    script_util.setVerbose(args.q == False)
    script_util.printVerbose(script_util.copyright)

    targets = script_util.findFiles(args.target, args.r, '.class')

    jar = args.path
    if jar is None and args.target.endswith('.jar'):
        jar = args.target

    #allow reading files from a jar if target is specified as a jar
    if jar:
        def readArchive(name):
            with zipfile.ZipFile(jar, 'r') as archive:
                return archive.open(name).read()
        readTarget = readArchive
    else:
        readTarget = readFile
Exemplo n.º 9
0
        description='Krakatau decompiler and bytecode analysis tool')
    parser.add_argument('-out', help='Path to generate files in')
    parser.add_argument(
        '-r',
        action='store_true',
        help="Process all files in the directory target and subdirectories")
    parser.add_argument('-q',
                        action='store_true',
                        help="Quiet output; only show warnings or errors")
    parser.add_argument('-path', help='Jar to look for class in')
    parser.add_argument('target',
                        help='Name of class or jar file to decompile')
    args = parser.parse_args()

    script_util.setVerbose(args.q == False)
    script_util.printVerbose(script_util.copyright)

    targets = script_util.findFiles(args.target, args.r, '.class')

    jar = args.path
    if jar is None and args.target.endswith('.jar'):
        jar = args.target

    #allow reading files from a jar if target is specified as a jar
    if jar:

        def readArchive(name):
            with zipfile.ZipFile(jar, 'r') as archive:
                return archive.open(name).read()

        readTarget = readArchive
Exemplo n.º 10
0
    parse_trees = parser.parse(assembly, lexer=lexer)
    return parse_trees and [assembler.assemble(tree, makeLineNumbers, jasmode, basename) for tree in parse_trees]

if __name__== "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Krakatau bytecode assembler')
    parser.add_argument('-out',help='Path to generate files in')
    parser.add_argument('-g', action='store_true', help="Add line number information to the generated class")
    parser.add_argument('-jas', action='store_true', help="Enable Jasmin compatibility mode")
    parser.add_argument('-r', action='store_true', help="Process all files in the directory target and subdirectories")
    parser.add_argument('-q', action='store_true', help="Quiet output; only show warnings or errors")
    parser.add_argument('target',help='Name of file to assemble')
    args = parser.parse_args()

    script_util.setVerbose(args.q == False)
    script_util.printVerbose(script_util.copyright)

    targets = script_util.findFiles(args.target, args.r, '.j')
    writeout = script_util.fileDirOut(args.out, '.class')

    for i, target in enumerate(targets):
        script_util.printVerbose('Processing file {}, {}/{} remaining'.format(target, len(targets)-i, len(targets)))
        pairs = assembleClass(target, args.g, args.jas)

        # if pairs is None:
        #     print 'Assembly of ', target, 'failed!'
        #     continue

        for name, data in pairs:
            filename = writeout(name, data)
            script_util.printVerbose('Class written to ' + filename)
Exemplo n.º 11
0
            deleteUnusued(c)

if __name__== "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Krakatau decompiler and bytecode analysis tool')
    parser.add_argument('-path',action='append',help='Semicolon seperated paths or jars to search when loading classes')
    parser.add_argument('-out',help='Path to generate source files in')
    parser.add_argument('-nauto', action='store_true', help="Don't attempt to automatically locate the Java standard library. If enabled, you must specify the path explicitly.")
    parser.add_argument('-r', action='store_true', help="Process all files in the directory target and subdirectories")
    parser.add_argument('-q', action='store_true', help="Quiet output; only show warnings or errors")
    parser.add_argument('-skip', action='store_true', help="Skip classes when an error occurs due to missing dependencies")
    parser.add_argument('target',help='Name of class or jar file to decompile')
    args = parser.parse_args()

    script_util.setVerbose(args.q == False)
    script_util.printVerbose(script_util.copyright)

    path = []
    if not args.nauto:
        script_util.printVerbose('Attempting to automatically locate the standard library...')
        found = findJRE()
        if found:
            script_util.printVerbose('Found at ' + found)
            path.append(found)
        else:
            print 'Unable to find the standard library'

    if args.path:
        for part in args.path:
            path.extend(part.split(';'))
Exemplo n.º 12
0
        help="Add line number information to the generated class")
    parser.add_argument('-jas',
                        action='store_true',
                        help="Enable Jasmin compatibility mode")
    parser.add_argument(
        '-r',
        action='store_true',
        help="Process all files in the directory target and subdirectories")
    parser.add_argument('-q',
                        action='store_true',
                        help="Quiet output; only show warnings or errors")
    parser.add_argument('target', help='Name of file to assemble')
    args = parser.parse_args()

    script_util.setVerbose(args.q == False)
    script_util.printVerbose(script_util.copyright)

    targets = script_util.findFiles(args.target, args.r, '.j')
    writeout = script_util.fileDirOut(args.out, '.class')

    for i, target in enumerate(targets):
        script_util.printVerbose('Processing file {}, {}/{} remaining'.format(
            target,
            len(targets) - i, len(targets)))
        pairs = assembleClass(target, args.g, args.jas)

        # if pairs is None:
        #     print 'Assembly of ', target, 'failed!'
        #     continue

        for name, data in pairs: