Java Code Examples for org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair#getSecond()

The following examples show how to use org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair#getSecond() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cfr   File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
    GetOptParser getOptParser = new GetOptParser();

    Options options = null;
    List<String> files = null;
    try {
        Pair<List<String>, Options> processedArgs = getOptParser.parse(args, OptionsImpl.getFactory());
        files = processedArgs.getFirst();
        options = processedArgs.getSecond();
        if (files.size() == 0) {
            throw new IllegalArgumentException("Insufficient unqualified parameters - provide at least one filename.");
        }
    } catch (Exception e) {
        getOptParser.showHelp(e);
        System.exit(1);
    }

    if (options.optionIsSet(OptionsImpl.HELP) || files.isEmpty()) {
        getOptParser.showOptionHelp(OptionsImpl.getFactory(), options, OptionsImpl.HELP);
        return;
    }

    CfrDriver cfrDriver = new CfrDriver.Builder().withBuiltOptions(options).build();
    cfrDriver.analyse(files);
}
 
Example 2
Source Project: cfr   File: ClassFile.java    License: MIT License 6 votes vote down vote up
public void dumpReceiverClassIdentity(List<AnnotationTableTypeEntry> recieverAnnotations, Dumper d) {
    Pair<List<AnnotationTableTypeEntry>, List<AnnotationTableTypeEntry>> split = Functional.partition(recieverAnnotations, new Predicate<AnnotationTableTypeEntry>() {
        @Override
        public boolean test(AnnotationTableTypeEntry in) {
            return in.getTypePath().segments.isEmpty();
        }
    });
    List<AnnotationTableTypeEntry> pre = split.getFirst();
    List<AnnotationTableTypeEntry> type = split.getSecond();
    if (!pre.isEmpty()) {
        pre.get(0).dump(d);
        d.print(" ");
    }
    JavaTypeInstance t = classSignature.getThisGeneralTypeClass(this.getClassType(), constantPool);
    JavaAnnotatedTypeInstance jat = t.getAnnotatedInstance();
    DecompilerComments comments = new DecompilerComments();
    TypeAnnotationHelper.apply(jat, type, comments);
    d.dump(comments);
    d.dump(jat);
}
 
Example 3
Source Project: cfr   File: ClassFileDumperEnum.java    License: MIT License 6 votes vote down vote up
private static void dumpEntry(Dumper d, Pair<StaticVariable, AbstractConstructorInvokation> entry, boolean last, JavaTypeInstance classType) {
    StaticVariable staticVariable = entry.getFirst();
    AbstractConstructorInvokation constructorInvokation = entry.getSecond();
    d.fieldName(staticVariable.getFieldName(), classType, false, true, true);

    if (constructorInvokation instanceof ConstructorInvokationSimple) {
        List<Expression> args = constructorInvokation.getArgs();
        if (args.size() > 2) {
            d.separator("(");
            for (int x = 2, len = args.size(); x < len; ++x) {
                if (x > 2) d.print(", ");
                d.dump(args.get(x));
            }
            d.separator(")");
        }
    } else if (constructorInvokation instanceof ConstructorInvokationAnonymousInner) {
        ((ConstructorInvokationAnonymousInner) constructorInvokation).dumpForEnum(d);
    } else {
        MiscUtils.handyBreakPoint();
    }
    if (last) {
        d.endCodeln();
    } else {
        d.print(",").newln();
    }
}
 
Example 4
@Override
public String decompileClassNode(FileContainer container, ClassNode cn) {
    try {
        byte[] bytes = JDA.getClassBytes(container, cn);
        GetOptParser getOptParser = new GetOptParser();
        Pair processedArgs = getOptParser.parse(generateMainMethod(), OptionsImpl.getFactory());
        List files = (List)processedArgs.getFirst();
        Options options = (Options)processedArgs.getSecond();
        ClassFileSourceImpl classFileSource = new ClassFileSourceImpl(options);
        DCCommonState dcCommonState = new DCCommonState(options, classFileSource);
        return doClass(dcCommonState, bytes);
    } catch (Exception e) {
        return parseException(e);
    }
}
 
Example 5
Source Project: cfr   File: SinkDumperFactory.java    License: MIT License 5 votes vote down vote up
private Dumper SinkSourceClassDumper(final OutputSinkFactory.Sink<SinkReturns.Decompiled> sink, final int version, JavaTypeInstance classType, MethodErrorCollector methodErrorCollector, TypeUsageInformation typeUsageInformation, IllegalIdentifierDump illegalIdentifierDump) {
    final StringBuilder sb = new StringBuilder();
    final Pair<String, String> names = ClassNameUtils.getPackageAndClassNames(classType);

    return new StringStreamDumper(methodErrorCollector, sb, typeUsageInformation, options, illegalIdentifierDump, new MovableDumperContext()) {

        @Override
        public void close() {
            final String java = sb.toString();
            SinkReturns.DecompiledMultiVer res = new SinkReturns.DecompiledMultiVer() {
                @Override
                public String getPackageName() {
                    return names.getFirst();
                }

                @Override
                public String getClassName() {
                    return names.getSecond();
                }

                @Override
                public String getJava() {
                    return java;
                }

                @Override
                public int getRuntimeFrom() {
                    return version;
                }
            };

            sink.write(res);
        }
    };
}
 
Example 6
Source Project: cfr   File: DCCommonState.java    License: MIT License 5 votes vote down vote up
public ClassFile loadClassFileAtPath(final String path) {
    try {
        Pair<byte[], String> content = classFileSource.getClassFileContent(path);
        ByteData data = new BaseByteData(content.getFirst());
        return new ClassFile(data, content.getSecond(), this);
    } catch (Exception e) {
        couldNotLoadClasses.add(path);
        throw new CannotLoadClassException(path, e);
    }
}
 
Example 7
Source Project: cfr   File: ClassFile.java    License: MIT License 5 votes vote down vote up
private void analyseInnerClassesPass1(DCCommonState state) {
    if (innerClassesByTypeInfo == null) return;
    for (Pair<InnerClassAttributeInfo, ClassFile> innerClassInfoClassFilePair : innerClassesByTypeInfo.values()) {
        ClassFile classFile = innerClassInfoClassFilePair.getSecond();
        classFile.analyseMid(state);
    }
}
 
Example 8
Source Project: cfr   File: ClassFile.java    License: MIT License 5 votes vote down vote up
private void analysePassOuterFirst(UnaryProcedure<ClassFile> fn) {
    try {
        fn.call(this);
    } catch (RuntimeException e) {
        addComment("Exception performing whole class analysis ignored.", e);
    }

    if (innerClassesByTypeInfo == null) return;
    for (Pair<InnerClassAttributeInfo, ClassFile> innerClassInfoClassFilePair : innerClassesByTypeInfo.values()) {
        ClassFile classFile = innerClassInfoClassFilePair.getSecond();
        classFile.analysePassOuterFirst(fn);
    }
}
 
Example 9
Source Project: cfr   File: InferredJavaType.java    License: MIT License 5 votes vote down vote up
private void collapseTypeClash(boolean force) {
    if (resolved) return;

    List<JavaTypeInstance> clashTypes = ListFactory.newList();
    int arraySize = clashes.get(0).getJavaTypeInstance().getNumArrayDimensions();
    for (IJTInternal clash : clashes) {
        JavaTypeInstance clashType = clash.getJavaTypeInstance();
        if (clashType.getNumArrayDimensions() != arraySize) arraySize = -1;
        clashTypes.add(clashType);
    }
    if (arraySize == 1) {
        for (int x=0;x<clashTypes.size();++x) {
            clashTypes.set(x, clashTypes.get(x).removeAnArrayIndirection());
        }
    }
    Pair<Boolean, JavaTypeInstance> newlyResolved = collapseTypeClash2(clashTypes);
    //noinspection ConstantConditions
    if (newlyResolved == null) return;

    // Ignore the first part of the pair - we have to resolve here, so do our best.
    if (!newlyResolved.getFirst() && !force) return;
    resolved = true;
    type = newlyResolved.getSecond();
    if (arraySize == 1) {
        type = new JavaArrayTypeInstance(1, type);
    }
}
 
Example 10
Source Project: cfr   File: InternalDumperFactoryImpl.java    License: MIT License 5 votes vote down vote up
public Dumper getNewTopLevelDumper(JavaTypeInstance classType, SummaryDumper summaryDumper, TypeUsageInformation typeUsageInformation, IllegalIdentifierDump illegalIdentifierDump) {
    Pair<String, Boolean> targetInfo = getPathAndClobber();

    if (targetInfo == null) return new StdIODumper(typeUsageInformation, options, illegalIdentifierDump, new MovableDumperContext());

    FileDumper res = new FileDumper(targetInfo.getFirst() + prefix, targetInfo.getSecond(), classType, summaryDumper, typeUsageInformation, options, illegalIdentifierDump);
    if (checkDupes) {
        if (!seen.add(res.getFileName().toLowerCase())) {
            seenCaseDupe = true;
        }
    }
    return res;
}
 
Example 11
Source Project: cfr   File: AttributeInnerClasses.java    License: MIT License 5 votes vote down vote up
public AttributeInnerClasses(ByteData raw, ConstantPool cp) {
    Boolean forbidMethodScopedClasses = cp.getDCCommonState().getOptions().getOption(OptionsImpl.FORBID_METHOD_SCOPED_CLASSES);
    Boolean forbidAnonymousClasses = cp.getDCCommonState().getOptions().getOption(OptionsImpl.FORBID_ANONYMOUS_CLASSES);
    this.length = raw.getS4At(OFFSET_OF_ATTRIBUTE_LENGTH);
    int numberInnerClasses = raw.getU2At(OFFSET_OF_NUMBER_OF_CLASSES);
    long offset = OFFSET_OF_CLASS_ARRAY;
    for (int x = 0; x < numberInnerClasses; ++x) {
        int innerClassInfoIdx = raw.getU2At(offset);
        offset += 2;
        int outerClassInfoIdx = raw.getU2At(offset);
        offset += 2;
        int innerNameIdx = raw.getU2At(offset);
        offset += 2;
        int innerAccessFlags = raw.getU2At(offset);
        offset += 2;
        Pair<JavaTypeInstance, JavaTypeInstance> innerOuter = getInnerOuter(innerClassInfoIdx, outerClassInfoIdx, cp);
        JavaTypeInstance innerClassType = innerOuter.getFirst();
        JavaTypeInstance outerClassType = innerOuter.getSecond();
        // MarkAnonymous feels like a bit of a hack, but otherwise we need to propagate this information
        // the whole way down the type creation path, and this is the only place we care about it.
        // May add that in later.
        if (outerClassType == null) {
            // This option has to be set manually, because it affects state generated
            // which is shared between fallback passes.
            if (forbidMethodScopedClasses) {
                outerClassType = innerClassType.getInnerClassHereInfo().getOuterClass();
            } else {
                boolean isAnonymous = !forbidAnonymousClasses && innerNameIdx == 0;
                innerClassType.getInnerClassHereInfo().markMethodScoped(isAnonymous);
            }
        }
        innerClassAttributeInfoList.add(new InnerClassAttributeInfo(
                innerClassType,
                outerClassType,
                getOptName(innerNameIdx, cp),
                AccessFlag.build(innerAccessFlags)
        ));
    }
}
 
Example 12
Source Project: cfr   File: Op02WithProcessedDataAndRefs.java    License: MIT License 5 votes vote down vote up
private Statement mkAssign(VariableFactory variableFactory) {
    Pair<JavaTypeInstance, Integer> storageTypeAndIdx = getStorageType();
    int slot = storageTypeAndIdx.getSecond();
    Ident ident = localVariablesBySlot.get(slot);

    AssignmentSimple res = new AssignmentSimple(variableFactory.localVariable(slot, ident, originalRawOffset), getStackRValue(0));
    return res;
}
 
Example 13
Source Project: cfr   File: ConstantPoolUtils.java    License: MIT License 5 votes vote down vote up
public static ClassSignature parseClassSignature(ConstantPoolEntryUTF8 signature, ConstantPool cp) {
    final String sig = signature.getValue();
    int curridx = 0;

    /*
     * Optional formal type parameters
     */
    Pair<Integer, List<FormalTypeParameter>> formalTypeParametersRes = parseFormalTypeParameters(sig, cp, curridx);
    curridx = formalTypeParametersRes.getFirst();
    List<FormalTypeParameter> formalTypeParameters = formalTypeParametersRes.getSecond();

    /*
     * Superclass signature.
     */
    String superClassSignatureTok = getNextTypeTok(sig, curridx);
    curridx += superClassSignatureTok.length();
    JavaTypeInstance superClassSignature = decodeTypeTok(superClassSignatureTok, cp);

    List<JavaTypeInstance> interfaceClassSignatures = ListFactory.newList();
    while (curridx < sig.length()) {
        String interfaceSignatureTok = getNextTypeTok(sig, curridx);
        curridx += interfaceSignatureTok.length();
        interfaceClassSignatures.add(decodeTypeTok(interfaceSignatureTok, cp));
    }

    return new ClassSignature(formalTypeParameters, superClassSignature, interfaceClassSignatures);
}
 
Example 14
Source Project: cfr   File: Op02WithProcessedDataAndRefs.java    License: MIT License 5 votes vote down vote up
private Statement mkRetrieve(VariableFactory variableFactory) {
    Pair<JavaTypeInstance, Integer> storageTypeAndIdx = getRetrieveType();
    int slot = storageTypeAndIdx.getSecond();
    Ident ident = localVariablesBySlot.get(slot);

    LValue lValue = variableFactory.localVariable(slot, ident, originalRawOffset);
    return new AssignmentSimple(getStackLValue(0), new LValueExpression(lValue));
}
 
Example 15
Source Project: cfr   File: AbstractLValueScopeDiscoverer.java    License: MIT License 5 votes vote down vote up
ScopeDefinition(int depth, Stack<StatementContainer<StructuredStatement>> nestedScope, StatementContainer<StructuredStatement> exactStatement,
                LValue lValue, JavaTypeInstance type, NamedVariable name, StatementContainer<StructuredStatement> hint, boolean immediate) {
    this.depth = depth;
    this.immediate = immediate;
    Pair< List<StatementContainer<StructuredStatement>>, StatementContainer<StructuredStatement>> adjustedScope = getBestScopeFor(lValue, nestedScope, exactStatement);
    this.nestedScope = adjustedScope.getFirst();
    this.exactStatement = adjustedScope.getSecond();
    this.lValue = lValue;
    this.lValueType = type;
    this.name = name;
    this.localHint = hint;
    this.scopeKey = new ScopeKey(lValue, type);
}
 
Example 16
Source Project: cfr   File: ConditionalRewriter.java    License: MIT License 5 votes vote down vote up
private static boolean detectAndRemarkJumpIntoOther(Set<BlockIdentifier> blocksAtStart, Set<BlockIdentifier> blocksAtEnd, Op03SimpleStatement realEnd, Op03SimpleStatement ifStatement) {
    if (blocksAtEnd.size() != blocksAtStart.size() + 1) return false;

    List<BlockIdentifier> diff =  SetUtil.differenceAtakeBtoList(blocksAtEnd, blocksAtStart);
    BlockIdentifier testBlock = diff.get(0);
    if (testBlock.getBlockType() != BlockType.SIMPLE_IF_TAKEN) return false;

    // If the difference is a simple-if, AND the statement AFTER realEnd is the target of BOTH
    // realEnd AND the source if statement... AND the if statement is inside our potential range,
    // we can convert THAT to a block exit, and remove that conditional.
    List<Op03SimpleStatement> realEndTargets = realEnd.getTargets();
    if (!(realEndTargets.size() == 1 && realEndTargets.get(0).getLinearlyPrevious() == realEnd)) return false;

    Op03SimpleStatement afterRealEnd = realEndTargets.get(0);
    List<Op03SimpleStatement> areSources = afterRealEnd.getSources();
    if (areSources.size() != 2) return false;
    Op03SimpleStatement other = areSources.get(0) == realEnd ? areSources.get(1) : areSources.get(0);
    // If other is the conditional for testBlock, we can change that jump into a break, as long as
    // the new conditional is a labelled block.
    Statement otherStatement = other.getStatement();
    if (!other.getIndex().isBackJumpTo(ifStatement)) return false;

    if (!(otherStatement instanceof IfStatement)) return false;

    Pair<BlockIdentifier, BlockIdentifier> knownBlocks = ((IfStatement) otherStatement).getBlocks();
    if (!(knownBlocks.getFirst() == testBlock && knownBlocks.getSecond() == null)) return false;

    ((IfStatement) otherStatement).setJumpType(JumpType.BREAK_ANONYMOUS);
    // And we need to unmark anything which is in testBlock.
    Op03SimpleStatement current = other.getLinearlyNext();
    while (current != null && current.getBlockIdentifiers().contains(testBlock)) {
        current.getBlockIdentifiers().remove(testBlock);
        current = current.getLinearlyNext();
    }
    return true;
}
 
Example 17
Source Project: cfr   File: FileDumper.java    License: MIT License 5 votes vote down vote up
private String mkFilename(String dir, Pair<String, String> names, SummaryDumper summaryDumper) {
    String packageName = names.getFirst();
    String className = names.getSecond();
    if (className.length() > MAX_FILE_LEN_MINUS_EXT) {
        /*
         * Have to try to find a replacement name.
         */
        className = className.substring(0, TRUNC_PREFIX_LEN) + "_cfr_" + (truncCount++);
        summaryDumper.notify("Class name " + names.getSecond() + " was shortened to " + className + " due to filesystem limitations.");
    }

    return dir + File.separator + packageName.replace(".", File.separator) +
            ((packageName.length() == 0) ? "" : File.separator) +
            className + ".java";
}
 
Example 18
Source Project: cfr   File: GetOptParser.java    License: MIT License 5 votes vote down vote up
public <T> Pair<List<String>, T> parse(String[] args, GetOptSinkFactory<T> getOptSinkFactory) {
    Pair<List<String>, Map<String, String>> processed = process(args, getOptSinkFactory);
    final List<String> positional = processed.getFirst();
    Map<String, String> named = processed.getSecond();
    /*
     * A bit of a hack, but if no positional arguments are specified, and 'help' is, then
     * we don't want to blow up, so work around this.
     */
    if (positional.isEmpty() && named.containsKey(OptionsImpl.HELP.getName())) {
        positional.add("ignoreMe.class");
    }
    T res = getOptSinkFactory.create(named);
    return Pair.make(positional, res);
}
 
Example 19
Source Project: cfr   File: AttributeAnnotationDefault.java    License: MIT License 4 votes vote down vote up
public AttributeAnnotationDefault(ByteData raw, ConstantPool cp) {
    this.length = raw.getS4At(OFFSET_OF_ATTRIBUTE_LENGTH);
    Pair<Long, ElementValue> tmp = AnnotationHelpers.getElementValue(raw, OFFSET_OF_REMAINDER, cp);
    this.elementValue = tmp.getSecond();
}
 
Example 20
Source Project: cfr   File: Block.java    License: MIT License 4 votes vote down vote up
public Optional<Op04StructuredStatement> getMaybeJustOneStatement() {
    Pair<Boolean, Op04StructuredStatement> tmp = getOneStatementIfPresent();
    return tmp.getSecond() == null ? Optional.<Op04StructuredStatement>empty() : Optional.of(tmp.getSecond());
}