org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair Java Examples

The following examples show how to use org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair. 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 File: AbstractLValueScopeDiscoverer.java    From cfr with MIT License 6 votes vote down vote up
private Pair< List<StatementContainer<StructuredStatement>>, StatementContainer<StructuredStatement>> getBestScopeFor(
                             LValue lValue,
                             Collection<StatementContainer<StructuredStatement>> nestedScope,
                             StatementContainer<StructuredStatement> exactStatement) {
    if (nestedScope == null) return Pair.make(null, exactStatement);
    List<StatementContainer<StructuredStatement>> scope = ListFactory.newList(nestedScope);
    if (exactStatement != null && exactStatement.getStatement().alwaysDefines(lValue)) return Pair.make(scope, exactStatement);
    if (scope.isEmpty()) return Pair.make(scope, exactStatement);
    for (int x=scope.size()-1;x>=0;--x) {
        StatementContainer<StructuredStatement> scopeTest = scope.get(x);
        if (scopeTest.getStatement().canDefine(lValue, factCache)) break;
        scope.remove(x);
    }
    if (scope.size() == nestedScope.size()) return Pair.make(scope, exactStatement);
    if (scope.isEmpty()) return Pair.make(null, exactStatement);
    exactStatement = scope.get(scope.size()-1);

    return Pair.make(scope, exactStatement);
}
 
Example #2
Source File: ClassFileDumperEnum.java    From cfr with 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 #3
Source File: AnnotationHelpers.java    From cfr with MIT License 6 votes vote down vote up
private static Pair<Long, TypeAnnotationTargetInfo> readTypeAnnotationTargetInfo(TypeAnnotationEntryKind kind, ByteData raw, long offset) {
    switch (kind) {
        case type_parameter_target:
            return TypeAnnotationTargetInfo.TypeAnnotationParameterTarget.Read(raw, offset);
        case supertype_target:
            return TypeAnnotationTargetInfo.TypeAnnotationSupertypeTarget.Read(raw, offset);
        case type_parameter_bound_target:
            return TypeAnnotationTargetInfo.TypeAnnotationParameterBoundTarget.Read(raw, offset);
        case empty_target:
            return TypeAnnotationTargetInfo.TypeAnnotationEmptyTarget.Read(raw, offset);
        case method_formal_parameter_target:
            return TypeAnnotationTargetInfo.TypeAnnotationFormalParameterTarget.Read(raw, offset);
        case throws_target:
            return TypeAnnotationTargetInfo.TypeAnnotationThrowsTarget.Read(raw, offset);
        case localvar_target:
            return TypeAnnotationTargetInfo.TypeAnnotationLocalVarTarget.Read(raw, offset);
        case catch_target:
            return TypeAnnotationTargetInfo.TypeAnnotationCatchTarget.Read(raw, offset);
        case offset_target:
            return TypeAnnotationTargetInfo.TypeAnnotationOffsetTarget.Read(raw, offset);
        case type_argument_target:
            return TypeAnnotationTargetInfo.TypeAnnotationTypeArgumentTarget.Read(raw, offset);
        default:
            throw new BadAttributeException();
    }
}
 
Example #4
Source File: Op02WithProcessedDataAndRefs.java    From cfr with MIT License 6 votes vote down vote up
private static NavigableMap<Integer, JavaTypeInstance> assignIdentsAndGetMissingMap(SSAIdentifierFactory<Slot, StackType> ssaIdentifierFactory, Method method, List<Op02WithProcessedDataAndRefs> statements, BytecodeMeta bytecodeMeta, boolean useProtoArgs) {
    assignSSAIdentifiersInner(ssaIdentifierFactory, method, statements, bytecodeMeta, useProtoArgs);

    /*
     * We can walk all the reads to see if there are any reads of 'uninitialised' slots.
     * These are masking hidden parameters. (usually synthetic ones?).
     */
    NavigableMap<Integer, JavaTypeInstance> missing = MapFactory.newTreeMap();

    for (Op02WithProcessedDataAndRefs op02 : statements) {
        Pair<JavaTypeInstance, Integer> load = op02.getRetrieveType();
        if (load == null) continue;

        SSAIdent ident = op02.ssaIdentifiers.getSSAIdentOnExit(new Slot(load.getFirst(), load.getSecond()));
        if (ident == null) {
            missing.put(load.getSecond(), load.getFirst());
        }
    }
    return missing;
}
 
Example #5
Source File: Main.java    From cfr with 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 #6
Source File: ClassCache.java    From cfr with MIT License 6 votes vote down vote up
public Pair<JavaRefTypeInstance, JavaRefTypeInstance> getRefClassForInnerOuterPair(String rawInnerName, String rawOuterName) {
    String innerName = ClassNameUtils.convertFromPath(rawInnerName);
    String outerName = ClassNameUtils.convertFromPath(rawOuterName);
    JavaRefTypeInstance inner = refClassTypeCache.get(innerName);
    JavaRefTypeInstance outer = refClassTypeCache.get(outerName);
    if (inner != null && outer != null) return Pair.make(inner, outer);
    Pair<JavaRefTypeInstance, JavaRefTypeInstance> pair = JavaRefTypeInstance.createKnownInnerOuter(innerName, outerName, outer, dcCommonState);
    if (inner == null) {
        add(innerName, pair.getFirst());
        inner = pair.getFirst();
    }
    if (outer == null) {
        add(outerName, pair.getSecond());
        outer = pair.getSecond();
    }
    return Pair.make(inner, outer);

}
 
Example #7
Source File: AttributeTypeAnnotations.java    From cfr with MIT License 6 votes vote down vote up
AttributeTypeAnnotations(ByteData raw, ConstantPool cp) {
    this.length = raw.getS4At(OFFSET_OF_ATTRIBUTE_LENGTH);
    int numAnnotations = raw.getU2At(OFFSET_OF_NUMBER_OF_ANNOTATIONS);
    long offset = OFFSET_OF_ANNOTATION_TABLE;

    Map<TypeAnnotationEntryValue, List<AnnotationTableTypeEntry>> entryData = MapFactory.newLazyMap(annotationTableEntryData, new UnaryFunction<TypeAnnotationEntryValue, List<AnnotationTableTypeEntry>>() {
        @Override
        public List<AnnotationTableTypeEntry> invoke(TypeAnnotationEntryValue arg) {
            return ListFactory.newList();
        }
    });

    for (int x = 0; x < numAnnotations; ++x) {
        Pair<Long, AnnotationTableTypeEntry> ape = AnnotationHelpers.getTypeAnnotation(raw, offset, cp);
        offset = ape.getFirst();
        AnnotationTableTypeEntry entry = ape.getSecond();
        entryData.get(entry.getValue()).add(entry);
    }
}
 
Example #8
Source File: TypeUsageInformationImpl.java    From cfr with MIT License 6 votes vote down vote up
private void initialiseFrom(Set<JavaRefTypeInstance> usedRefTypes) {
    List<JavaRefTypeInstance> usedRefs = ListFactory.newList(usedRefTypes);
    Collections.sort(usedRefs, new Comparator<JavaRefTypeInstance>() {
        @Override
        public int compare(JavaRefTypeInstance a, JavaRefTypeInstance b) {
            return a.getRawName(iid).compareTo(b.getRawName(iid));
        }
    });
    this.usedRefTypes.addAll(usedRefs);

    Pair<List<JavaRefTypeInstance>, List<JavaRefTypeInstance>> types = Functional.partition(usedRefs, new Predicate<JavaRefTypeInstance>() {
        @Override
        public boolean test(JavaRefTypeInstance in) {
            return in.getInnerClassHereInfo().isTransitiveInnerClassOf(analysisType);
        }
    });
    this.usedLocalInnerTypes.addAll(types.getFirst());
    addDisplayNames(usedRefTypes);
}
 
Example #9
Source File: ConstantPoolUtils.java    From cfr with MIT License 6 votes vote down vote up
private static Pair<Integer, List<FormalTypeParameter>> parseFormalTypeParameters(String proto, ConstantPool cp, int curridx) {
    List<FormalTypeParameter> formalTypeParameters = null;
    FormalTypeParameter last = null;
    if (proto.charAt(curridx) == '<') {
        formalTypeParameters = ListFactory.newList();
        curridx++;
        while (proto.charAt(curridx) != '>') {
            String formalTypeTok = getNextFormalTypeTok(proto, curridx);
            FormalTypeParameter typeTok = decodeFormalTypeTok(formalTypeTok, cp);
            if (typeTok.getName().equals("")) {
                // previous type was an intersection type!
                if (last != null) {
                    last.add(typeTok);
                } // else no idea - have to skip.
            } else {
                formalTypeParameters.add(typeTok);
                last = typeTok;
            }
            curridx += formalTypeTok.length();
        }
        curridx++;
    }
    return Pair.make(curridx, formalTypeParameters);
}
 
Example #10
Source File: ClassFile.java    From cfr with 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 #11
Source File: ClassFile.java    From cfr with MIT License 6 votes vote down vote up
public void dumpNamedInnerClasses(Dumper d) {
    if (innerClassesByTypeInfo == null || innerClassesByTypeInfo.isEmpty()) return;

    for (Pair<InnerClassAttributeInfo, ClassFile> innerClassEntry : innerClassesByTypeInfo.values()) {
        // catchy!
        InnerClassInfo innerClassInfo = innerClassEntry.getFirst().getInnerClassInfo().getInnerClassHereInfo();
        if (innerClassInfo.isSyntheticFriendClass()) {
            continue;
        }
        if (innerClassInfo.isMethodScopedClass()) {
            continue;
        }
        ClassFile classFile = innerClassEntry.getSecond();
        if (classFile.hiddenInnerClass) {
            continue;
        }
        TypeUsageInformation typeUsageInformation = d.getTypeUsageInformation();
        TypeUsageInformation innerclassTypeUsageInformation = new InnerClassTypeUsageInformation(typeUsageInformation, (JavaRefTypeInstance) classFile.getClassType());
        d.newln();
        Dumper d2 = d.withTypeUsageInformation(innerclassTypeUsageInformation);
        classFile.dumpHelper.dump(classFile, ClassFileDumper.InnerClassDumpType.INNER_CLASS, d2);
    }
}
 
Example #12
Source File: Block.java    From cfr with MIT License 5 votes vote down vote up
public Pair<Boolean, Op04StructuredStatement> getOneStatementIfPresent() {
    Op04StructuredStatement res = null;
    for (Op04StructuredStatement statement : containedStatements) {
        if (!(statement.getStatement() instanceof StructuredComment)) {
            if (res == null) {
                res = statement;
            } else {
                return Pair.make(Boolean.FALSE, null);
            }
        }
    }
    return Pair.make(res==null, res);
}
 
Example #13
Source File: SwitchExpressionRewriter.java    From cfr with MIT License 5 votes vote down vote up
private SwitchExpressionTransformer(LValue target, BlockIdentifier blockIdentifier, List<Pair<Op04StructuredStatement, StructuredStatement>> replacements, boolean last) {
    this.target = target;
    this.rewriter = new UsageCheck(target);
    this.blockIdentifier = blockIdentifier;
    this.replacements = replacements;
    this.last = last;
}
 
Example #14
Source File: LambdaCleaner.java    From cfr with MIT License 5 votes vote down vote up
@Override
public Expression rewriteExpression(Expression expression, SSAIdentifiers ssaIdentifiers, StatementContainer statementContainer, ExpressionRewriterFlags flags) {
    if (expression instanceof LambdaExpression) {
        LambdaExpression lambda = (LambdaExpression)expression;
        Expression result = lambda.getResult();
        if (result instanceof StructuredStatementExpression) {
            StructuredStatementExpression structuredStatementExpression = (StructuredStatementExpression)result;
            StructuredStatement content = structuredStatementExpression.getContent();
            if (content instanceof Block) {
                Block block = (Block)content;
                Pair<Boolean, Op04StructuredStatement> singleStatement = block.getOneStatementIfPresent();
                if (singleStatement.getSecond() != null) {
                    StructuredStatement statement = singleStatement.getSecond().getStatement();
                    if (statement instanceof StructuredReturn) {
                        expression = rebuildLambda(lambda, ((StructuredReturn)statement).getValue());
                    } else if (statement instanceof StructuredExpressionStatement) {
                        expression = rebuildLambda(lambda, ((StructuredExpressionStatement) statement).getExpression());
                    }
                } else {
                    if (singleStatement.getFirst()) {
                        Expression empty = new StructuredStatementExpression(expression.getInferredJavaType(), new Block(new LinkedList<Op04StructuredStatement>(), true));
                        expression = rebuildLambda(lambda, empty);
                    }
                }
            }
        }
    }
    return expression.applyExpressionRewriter(this, ssaIdentifiers, statementContainer, flags);
}
 
Example #15
Source File: Op02WithProcessedDataAndRefs.java    From cfr with MIT License 5 votes vote down vote up
private void collectLocallyMutatedVariables(SSAIdentifierFactory<Slot, StackType> ssaIdentifierFactory) {
    Pair<JavaTypeInstance, Integer> storage = getStorageType();
    if (storage != null) {
        ssaIdentifiers = new SSAIdentifiers<Slot>(new Slot(storage.getFirst(), storage.getSecond()), ssaIdentifierFactory);
        return;
    }

    ssaIdentifiers = new SSAIdentifiers<Slot>();
}
 
Example #16
Source File: ConditionalRewriter.java    From cfr with 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 File: Op02WithProcessedDataAndRefs.java    From cfr with 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 #18
Source File: Op02WithProcessedDataAndRefs.java    From cfr with 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 #19
Source File: ConstantPoolEntryClass.java    From cfr with MIT License 5 votes vote down vote up
public JavaTypeInstance getTypeInstanceKnownInner(ConstantPoolEntryClass inner) {
    if (javaTypeInstance != null) {
        return javaTypeInstance;
    }
    String thisInnerType = getClassNameString(inner.nameIndex);
    String thisOuterType = getClassNameString(nameIndex);
    Pair<JavaRefTypeInstance, JavaRefTypeInstance> pair = getCp().getClassCache().getRefClassForInnerOuterPair(thisInnerType, thisOuterType);
    javaTypeInstance = pair.getSecond();
    return javaTypeInstance;
}
 
Example #20
Source File: StructuredSwitch.java    From cfr with MIT License 5 votes vote down vote up
public boolean isOnlyEmptyDefault() {
    StructuredStatement stm = getBody().getStatement();
    if (!(stm instanceof Block)) return false;
    Pair<Boolean, Op04StructuredStatement> onestm = ((Block) stm).getOneStatementIfPresent();
    if (onestm.getSecond() == null) return false;
    StructuredStatement single = onestm.getSecond().getStatement();
    // should be!
    if (!(single instanceof StructuredCase)) return false;
    StructuredCase cs = (StructuredCase)single;
    if (!cs.isDefault()) return false;
    StructuredStatement caseBody = cs.getBody().getStatement();
    if (!(caseBody instanceof Block)) return false;
    return caseBody.isEffectivelyNOP();
}
 
Example #21
Source File: ReturnRewriter.java    From cfr with MIT License 5 votes vote down vote up
private static void replaceReturningIf(Op03SimpleStatement ifStatement, boolean aggressive) {
    if (!(ifStatement.getStatement().getClass() == IfStatement.class)) return;
    IfStatement innerIf = (IfStatement) ifStatement.getStatement();
    Op03SimpleStatement tgt = ifStatement.getTargets().get(1);
    final Op03SimpleStatement origtgt = tgt;
    boolean requireJustOneSource = !aggressive;
    do {
        Op03SimpleStatement next = Misc.followNopGoto(tgt, requireJustOneSource, aggressive);
        if (next == tgt) break;
        tgt = next;
    } while (true);
    Statement tgtStatement = tgt.getStatement();
    if (tgtStatement instanceof ReturnStatement) {
        ifStatement.replaceStatement(new IfExitingStatement(innerIf.getCondition(), tgtStatement));
        Op03SimpleStatement origfall = ifStatement.getTargets().get(0);
        origfall.setFirstStatementInThisBlock(null);
        BlockIdentifier ifBlock = innerIf.getKnownIfBlock();
        Pair<Set<Op03SimpleStatement>, Set<Op03SimpleStatement>> blockReachableAndExits = Misc.GraphVisitorBlockReachable.getBlockReachableAndExits(origfall, ifBlock);
        for (Op03SimpleStatement stm : blockReachableAndExits.getFirst()) {
            stm.getBlockIdentifiers().remove(ifBlock);
        }
    } else {
        return;
    }
    origtgt.removeSource(ifStatement);
    ifStatement.removeTarget(origtgt);
}
 
Example #22
Source File: SwitchExpressionRewriter.java    From cfr with MIT License 5 votes vote down vote up
private Expression extractSwitchEntry(LValue target, BlockIdentifier blockIdentifier, Op04StructuredStatement body, List<Pair<Op04StructuredStatement, StructuredStatement>> replacements, boolean last) {
    SwitchExpressionTransformer transformer = new SwitchExpressionTransformer(target, blockIdentifier, replacements, last);
    body.transform(transformer, new StructuredScope());
    if (transformer.failed) return null;
    if (!transformer.lastMarked) return null;
    if (transformer.lastAssign && !last) return null;
    if (transformer.totalStatements == 1 && transformer.singleValue != null) {
        return transformer.singleValue;
    }

    return new StructuredStatementExpression(target.getInferredJavaType(), body.getStatement());
}
 
Example #23
Source File: SwitchExpressionRewriter.java    From cfr with MIT License 5 votes vote down vote up
private Pair<StructuredCase, Expression> extractSwitchEntryPair(LValue target, BlockIdentifier blockIdentifier, Op04StructuredStatement item, List<Pair<Op04StructuredStatement, StructuredStatement>> replacements, boolean last) {
    StructuredStatement stm = item.getStatement();
    if (!(stm instanceof StructuredCase)) {
        return null;
    }
    StructuredCase sc = (StructuredCase)stm;
    Expression res = extractSwitchEntry(target, blockIdentifier, sc.getBody(), replacements, last);
    if (res == null) {
        return null;
    }
    return Pair.make(sc, res);
}
 
Example #24
Source File: AnnotationHelpers.java    From cfr with MIT License 5 votes vote down vote up
private static long getElementValuePair(ByteData raw, long offset, ConstantPool cp, Map<String, ElementValue> res) {
    ConstantPoolEntryUTF8 elementName = cp.getUTF8Entry(raw.getU2At(offset));
    offset += 2;
    Pair<Long, ElementValue> elementValueP = getElementValue(raw, offset, cp);
    offset = elementValueP.getFirst();
    res.put(elementName.getValue(), elementValueP.getSecond());
    return offset;
}
 
Example #25
Source File: ConstantPoolEntryClass.java    From cfr with MIT License 5 votes vote down vote up
public JavaTypeInstance getTypeInstanceKnownOuter(ConstantPoolEntryClass outer) {
    if (javaTypeInstance != null) {
        return javaTypeInstance;
    }
    String thisInnerType = getClassNameString(nameIndex);
    String thisOuterType = getClassNameString(outer.nameIndex);
    Pair<JavaRefTypeInstance, JavaRefTypeInstance> pair = getCp().getClassCache().getRefClassForInnerOuterPair(thisInnerType, thisOuterType);
    javaTypeInstance = pair.getFirst();
    return javaTypeInstance;
}
 
Example #26
Source File: ConstantPoolUtils.java    From cfr with MIT License 5 votes vote down vote up
private static Pair<List<JavaTypeInstance>, Integer> parseTypeList(String proto, ConstantPool cp) {
    int curridx = 0;
    int len = proto.length();
    List<JavaTypeInstance> res = ListFactory.newList();
    while (curridx < len && proto.charAt(curridx) != '>') {
        String typeTok = getNextTypeTok(proto, curridx);
        res.add(decodeTypeTok(typeTok, cp));
        curridx += typeTok.length();
    }
    return Pair.make(res, curridx);
}
 
Example #27
Source File: InternalDumperFactoryImpl.java    From cfr with 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 #28
Source File: ConstantPoolUtils.java    From cfr with 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 #29
Source File: ClassSource.java    From Recaf with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public Pair<byte[], String> getClassFileContent(String inputPath) {
	String className = inputPath.substring(0, inputPath.indexOf(".class"));
	byte[] code = controller.getWorkspace().getRawClass(className);
	// Strip debug if config says so
	if (controller.config().decompile().stripDebug)
		code = ClassUtil.stripDebugForDecompile(code);
	// Fetch code from runtime if not in workspace
	if (code == null) {
		code = Objects.requireNonNull(ClassUtil.fromRuntime(className),
				"Failed to load class from runtime: " + className).b;
	}
	return new Pair<>(code, inputPath);
}
 
Example #30
Source File: FileDumper.java    From cfr with 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";
}