Search in sources :

Example 6 with ExceptionWithContext

use of org.jf.util.ExceptionWithContext in project smali by JesusFreke.

the class CodeItem method makeAnnotator.

@Nonnull
public static SectionAnnotator makeAnnotator(@Nonnull DexAnnotator annotator, @Nonnull MapItem mapItem) {
    return new SectionAnnotator(annotator, mapItem) {

        private SectionAnnotator debugInfoAnnotator = null;

        @Override
        public void annotateSection(@Nonnull AnnotatedBytes out) {
            debugInfoAnnotator = annotator.getAnnotator(ItemType.DEBUG_INFO_ITEM);
            super.annotateSection(out);
        }

        @Nonnull
        @Override
        public String getItemName() {
            return "code_item";
        }

        @Override
        public int getItemAlignment() {
            return 4;
        }

        @Override
        public void annotateItem(@Nonnull AnnotatedBytes out, int itemIndex, @Nullable String itemIdentity) {
            try {
                DexReader reader = dexFile.readerAt(out.getCursor());
                int registers = reader.readUshort();
                out.annotate(2, "registers_size = %d", registers);
                int inSize = reader.readUshort();
                out.annotate(2, "ins_size = %d", inSize);
                int outSize = reader.readUshort();
                out.annotate(2, "outs_size = %d", outSize);
                int triesCount = reader.readUshort();
                out.annotate(2, "tries_size = %d", triesCount);
                int debugInfoOffset = reader.readInt();
                out.annotate(4, "debug_info_off = 0x%x", debugInfoOffset);
                if (debugInfoOffset > 0) {
                    addDebugInfoIdentity(debugInfoOffset, itemIdentity);
                }
                int instructionSize = reader.readSmallUint();
                out.annotate(4, "insns_size = 0x%x", instructionSize);
                out.annotate(0, "instructions:");
                out.indent();
                out.setLimit(out.getCursor(), out.getCursor() + instructionSize * 2);
                int end = reader.getOffset() + instructionSize * 2;
                try {
                    while (reader.getOffset() < end) {
                        Instruction instruction = DexBackedInstruction.readFrom(reader);
                        // if we read past the end of the instruction list
                        if (reader.getOffset() > end) {
                            out.annotateTo(end, "truncated instruction");
                            reader.setOffset(end);
                        } else {
                            switch(instruction.getOpcode().format) {
                                case Format10x:
                                    annotateInstruction10x(out, instruction);
                                    break;
                                case Format35c:
                                    annotateInstruction35c(out, (Instruction35c) instruction);
                                    break;
                                case Format3rc:
                                    annotateInstruction3rc(out, (Instruction3rc) instruction);
                                    break;
                                case ArrayPayload:
                                    annotateArrayPayload(out, (ArrayPayload) instruction);
                                    break;
                                case PackedSwitchPayload:
                                    annotatePackedSwitchPayload(out, (PackedSwitchPayload) instruction);
                                    break;
                                case SparseSwitchPayload:
                                    annotateSparseSwitchPayload(out, (SparseSwitchPayload) instruction);
                                    break;
                                default:
                                    annotateDefaultInstruction(out, instruction);
                                    break;
                            }
                        }
                        assert reader.getOffset() == out.getCursor();
                    }
                } catch (ExceptionWithContext ex) {
                    ex.printStackTrace(System.err);
                    out.annotate(0, "annotation error: %s", ex.getMessage());
                    out.moveTo(end);
                    reader.setOffset(end);
                } finally {
                    out.clearLimit();
                    out.deindent();
                }
                if (triesCount > 0) {
                    if ((reader.getOffset() % 4) != 0) {
                        reader.readUshort();
                        out.annotate(2, "padding");
                    }
                    out.annotate(0, "try_items:");
                    out.indent();
                    try {
                        for (int i = 0; i < triesCount; i++) {
                            out.annotate(0, "try_item[%d]:", i);
                            out.indent();
                            try {
                                int startAddr = reader.readSmallUint();
                                out.annotate(4, "start_addr = 0x%x", startAddr);
                                int instructionCount = reader.readUshort();
                                out.annotate(2, "insn_count = 0x%x", instructionCount);
                                int handlerOffset = reader.readUshort();
                                out.annotate(2, "handler_off = 0x%x", handlerOffset);
                            } finally {
                                out.deindent();
                            }
                        }
                    } finally {
                        out.deindent();
                    }
                    int handlerListCount = reader.readSmallUleb128();
                    out.annotate(0, "encoded_catch_handler_list:");
                    out.annotateTo(reader.getOffset(), "size = %d", handlerListCount);
                    out.indent();
                    try {
                        for (int i = 0; i < handlerListCount; i++) {
                            out.annotate(0, "encoded_catch_handler[%d]", i);
                            out.indent();
                            try {
                                int handlerCount = reader.readSleb128();
                                out.annotateTo(reader.getOffset(), "size = %d", handlerCount);
                                boolean hasCatchAll = handlerCount <= 0;
                                handlerCount = Math.abs(handlerCount);
                                if (handlerCount != 0) {
                                    out.annotate(0, "handlers:");
                                    out.indent();
                                    try {
                                        for (int j = 0; j < handlerCount; j++) {
                                            out.annotate(0, "encoded_type_addr_pair[%d]", i);
                                            out.indent();
                                            try {
                                                int typeIndex = reader.readSmallUleb128();
                                                out.annotateTo(reader.getOffset(), TypeIdItem.getReferenceAnnotation(dexFile, typeIndex));
                                                int handlerAddress = reader.readSmallUleb128();
                                                out.annotateTo(reader.getOffset(), "addr = 0x%x", handlerAddress);
                                            } finally {
                                                out.deindent();
                                            }
                                        }
                                    } finally {
                                        out.deindent();
                                    }
                                }
                                if (hasCatchAll) {
                                    int catchAllAddress = reader.readSmallUleb128();
                                    out.annotateTo(reader.getOffset(), "catch_all_addr = 0x%x", catchAllAddress);
                                }
                            } finally {
                                out.deindent();
                            }
                        }
                    } finally {
                        out.deindent();
                    }
                }
            } catch (ExceptionWithContext ex) {
                out.annotate(0, "annotation error: %s", ex.getMessage());
            }
        }

        private String formatRegister(int registerNum) {
            return String.format("v%d", registerNum);
        }

        private void annotateInstruction10x(@Nonnull AnnotatedBytes out, @Nonnull Instruction instruction) {
            out.annotate(2, instruction.getOpcode().name);
        }

        private void annotateInstruction35c(@Nonnull AnnotatedBytes out, @Nonnull Instruction35c instruction) {
            List<String> args = Lists.newArrayList();
            int registerCount = instruction.getRegisterCount();
            if (registerCount == 1) {
                args.add(formatRegister(instruction.getRegisterC()));
            } else if (registerCount == 2) {
                args.add(formatRegister(instruction.getRegisterC()));
                args.add(formatRegister(instruction.getRegisterD()));
            } else if (registerCount == 3) {
                args.add(formatRegister(instruction.getRegisterC()));
                args.add(formatRegister(instruction.getRegisterD()));
                args.add(formatRegister(instruction.getRegisterE()));
            } else if (registerCount == 4) {
                args.add(formatRegister(instruction.getRegisterC()));
                args.add(formatRegister(instruction.getRegisterD()));
                args.add(formatRegister(instruction.getRegisterE()));
                args.add(formatRegister(instruction.getRegisterF()));
            } else if (registerCount == 5) {
                args.add(formatRegister(instruction.getRegisterC()));
                args.add(formatRegister(instruction.getRegisterD()));
                args.add(formatRegister(instruction.getRegisterE()));
                args.add(formatRegister(instruction.getRegisterF()));
                args.add(formatRegister(instruction.getRegisterG()));
            }
            String reference = ReferenceUtil.getReferenceString(instruction.getReference());
            out.annotate(6, String.format("%s {%s}, %s", instruction.getOpcode().name, Joiner.on(", ").join(args), reference));
        }

        private void annotateInstruction3rc(@Nonnull AnnotatedBytes out, @Nonnull Instruction3rc instruction) {
            int startRegister = instruction.getStartRegister();
            int endRegister = startRegister + instruction.getRegisterCount() - 1;
            String reference = ReferenceUtil.getReferenceString(instruction.getReference());
            out.annotate(6, String.format("%s {%s .. %s}, %s", instruction.getOpcode().name, formatRegister(startRegister), formatRegister(endRegister), reference));
        }

        private void annotateDefaultInstruction(@Nonnull AnnotatedBytes out, @Nonnull Instruction instruction) {
            List<String> args = Lists.newArrayList();
            if (instruction instanceof OneRegisterInstruction) {
                args.add(formatRegister(((OneRegisterInstruction) instruction).getRegisterA()));
                if (instruction instanceof TwoRegisterInstruction) {
                    args.add(formatRegister(((TwoRegisterInstruction) instruction).getRegisterB()));
                    if (instruction instanceof ThreeRegisterInstruction) {
                        args.add(formatRegister(((ThreeRegisterInstruction) instruction).getRegisterC()));
                    }
                }
            } else if (instruction instanceof VerificationErrorInstruction) {
                String verificationError = VerificationError.getVerificationErrorName(((VerificationErrorInstruction) instruction).getVerificationError());
                if (verificationError != null) {
                    args.add(verificationError);
                } else {
                    args.add("invalid verification error type");
                }
            }
            if (instruction instanceof ReferenceInstruction) {
                args.add(ReferenceUtil.getReferenceString(((ReferenceInstruction) instruction).getReference()));
            } else if (instruction instanceof OffsetInstruction) {
                int offset = ((OffsetInstruction) instruction).getCodeOffset();
                String sign = offset >= 0 ? "+" : "-";
                args.add(String.format("%s0x%x", sign, Math.abs(offset)));
            } else if (instruction instanceof NarrowLiteralInstruction) {
                int value = ((NarrowLiteralInstruction) instruction).getNarrowLiteral();
                if (NumberUtils.isLikelyFloat(value)) {
                    args.add(String.format("%d # %f", value, Float.intBitsToFloat(value)));
                } else {
                    args.add(String.format("%d", value));
                }
            } else if (instruction instanceof WideLiteralInstruction) {
                long value = ((WideLiteralInstruction) instruction).getWideLiteral();
                if (NumberUtils.isLikelyDouble(value)) {
                    args.add(String.format("%d # %f", value, Double.longBitsToDouble(value)));
                } else {
                    args.add(String.format("%d", value));
                }
            } else if (instruction instanceof FieldOffsetInstruction) {
                int fieldOffset = ((FieldOffsetInstruction) instruction).getFieldOffset();
                args.add(String.format("field@0x%x", fieldOffset));
            } else if (instruction instanceof VtableIndexInstruction) {
                int vtableIndex = ((VtableIndexInstruction) instruction).getVtableIndex();
                args.add(String.format("vtable@%d", vtableIndex));
            } else if (instruction instanceof InlineIndexInstruction) {
                int inlineIndex = ((InlineIndexInstruction) instruction).getInlineIndex();
                args.add(String.format("inline@%d", inlineIndex));
            }
            out.annotate(instruction.getCodeUnits() * 2, "%s %s", instruction.getOpcode().name, Joiner.on(", ").join(args));
        }

        private void annotateArrayPayload(@Nonnull AnnotatedBytes out, @Nonnull ArrayPayload instruction) {
            List<Number> elements = instruction.getArrayElements();
            int elementWidth = instruction.getElementWidth();
            out.annotate(2, instruction.getOpcode().name);
            out.indent();
            out.annotate(2, "element_width = %d", elementWidth);
            out.annotate(4, "size = %d", elements.size());
            out.annotate(0, "elements:");
            out.indent();
            for (int i = 0; i < elements.size(); i++) {
                if (elementWidth == 8) {
                    long value = elements.get(i).longValue();
                    if (NumberUtils.isLikelyDouble(value)) {
                        out.annotate(elementWidth, "element[%d] = %d # %f", i, value, Double.longBitsToDouble(value));
                    } else {
                        out.annotate(elementWidth, "element[%d] = %d", i, value);
                    }
                } else {
                    int value = elements.get(i).intValue();
                    if (NumberUtils.isLikelyFloat(value)) {
                        out.annotate(elementWidth, "element[%d] = %d # %f", i, value, Float.intBitsToFloat(value));
                    } else {
                        out.annotate(elementWidth, "element[%d] = %d", i, value);
                    }
                }
            }
            if (out.getCursor() % 2 != 0) {
                out.annotate(1, "padding");
            }
            out.deindent();
            out.deindent();
        }

        private void annotatePackedSwitchPayload(@Nonnull AnnotatedBytes out, @Nonnull PackedSwitchPayload instruction) {
            List<? extends SwitchElement> elements = instruction.getSwitchElements();
            out.annotate(2, instruction.getOpcode().name);
            out.indent();
            out.annotate(2, "size = %d", elements.size());
            if (elements.size() == 0) {
                out.annotate(4, "first_key");
            } else {
                out.annotate(4, "first_key = %d", elements.get(0).getKey());
                out.annotate(0, "targets:");
                out.indent();
                for (int i = 0; i < elements.size(); i++) {
                    out.annotate(4, "target[%d] = %d", i, elements.get(i).getOffset());
                }
                out.deindent();
            }
            out.deindent();
        }

        private void annotateSparseSwitchPayload(@Nonnull AnnotatedBytes out, @Nonnull SparseSwitchPayload instruction) {
            List<? extends SwitchElement> elements = instruction.getSwitchElements();
            out.annotate(2, instruction.getOpcode().name);
            out.indent();
            out.annotate(2, "size = %d", elements.size());
            if (elements.size() > 0) {
                out.annotate(0, "keys:");
                out.indent();
                for (int i = 0; i < elements.size(); i++) {
                    out.annotate(4, "key[%d] = %d", i, elements.get(i).getKey());
                }
                out.deindent();
                out.annotate(0, "targets:");
                out.indent();
                for (int i = 0; i < elements.size(); i++) {
                    out.annotate(4, "target[%d] = %d", i, elements.get(i).getOffset());
                }
                out.deindent();
            }
            out.deindent();
        }

        private void addDebugInfoIdentity(int debugInfoOffset, String methodString) {
            if (debugInfoAnnotator != null) {
                debugInfoAnnotator.setItemIdentity(debugInfoOffset, methodString);
            }
        }
    };
}
Also used : DexReader(org.jf.dexlib2.dexbacked.DexReader) DexBackedInstruction(org.jf.dexlib2.dexbacked.instruction.DexBackedInstruction) ExceptionWithContext(org.jf.util.ExceptionWithContext) Nonnull(javax.annotation.Nonnull) AnnotatedBytes(org.jf.dexlib2.util.AnnotatedBytes) Nullable(javax.annotation.Nullable) Nonnull(javax.annotation.Nonnull)

Example 7 with ExceptionWithContext

use of org.jf.util.ExceptionWithContext in project smali by JesusFreke.

the class BaseDexReader method readUleb128.

private int readUleb128(boolean allowLarge) {
    int end = dexBuf.baseOffset + offset;
    int currentByteValue;
    int result;
    byte[] buf = dexBuf.buf;
    result = buf[end++] & 0xff;
    if (result > 0x7f) {
        currentByteValue = buf[end++] & 0xff;
        result = (result & 0x7f) | ((currentByteValue & 0x7f) << 7);
        if (currentByteValue > 0x7f) {
            currentByteValue = buf[end++] & 0xff;
            result |= (currentByteValue & 0x7f) << 14;
            if (currentByteValue > 0x7f) {
                currentByteValue = buf[end++] & 0xff;
                result |= (currentByteValue & 0x7f) << 21;
                if (currentByteValue > 0x7f) {
                    currentByteValue = buf[end++];
                    // MSB shouldn't be set on last byte
                    if (currentByteValue < 0) {
                        throw new ExceptionWithContext("Invalid uleb128 integer encountered at offset 0x%x", offset);
                    } else if ((currentByteValue & 0xf) > 0x07) {
                        if (!allowLarge) {
                            // set, so that it can fit into a signed integer without wrapping
                            throw new ExceptionWithContext("Encountered valid uleb128 that is out of range at offset 0x%x", offset);
                        }
                    }
                    result |= currentByteValue << 28;
                }
            }
        }
    }
    offset = end - dexBuf.baseOffset;
    return result;
}
Also used : ExceptionWithContext(org.jf.util.ExceptionWithContext)

Example 8 with ExceptionWithContext

use of org.jf.util.ExceptionWithContext in project atlas by alibaba.

the class InstructionMethodItem method writeTo.

@Override
public boolean writeTo(IndentingWriter writer) throws IOException {
    Opcode opcode = instruction.getOpcode();
    String verificationErrorName = null;
    String referenceString = null;
    boolean commentOutInstruction = false;
    if (instruction instanceof Instruction20bc) {
        int verificationError = ((Instruction20bc) instruction).getVerificationError();
        verificationErrorName = VerificationError.getVerificationErrorName(verificationError);
        if (verificationErrorName == null) {
            writer.write("#was invalid verification error type: ");
            writer.printSignedIntAsDec(verificationError);
            writer.write("\n");
            verificationErrorName = "generic-error";
        }
    }
    if (instruction instanceof ReferenceInstruction) {
        ReferenceInstruction referenceInstruction = (ReferenceInstruction) instruction;
        try {
            Reference reference = referenceInstruction.getReference();
            String classContext = null;
            if (methodDef.classDef.options.useImplicitReferences) {
                classContext = methodDef.method.getDefiningClass();
            }
            referenceString = ReferenceUtil.getReferenceString(reference, classContext);
            if (methodDef.method.getName().equals("<clinit>")) {
                String clazz = methodDef.method.getDefiningClass();
                if (DexDiffInfo.getModifiedClasses(clazz) != null) {
                    referenceString = referenceString.replace(clazz, TypeGenUtil.newType(clazz));
                }
            }
            if (!methodDef.classDef.fullMethod) {
                if (reference instanceof MethodReference) {
                    MethodReference methodReference = (MethodReference) reference;
                    //                        String className = methodReference.getDefiningClass();
                    //                        String out1 = TypeGenUtil.getOuterClass(className);
                    //                        String out2 = TypeGenUtil.getOuterClass(ApkPatch.currentClassType);
                    //                        if (out1.equalsIgnoreCase(out2)) {
                    DexDiffInfo.addUsedMethods(methodReference);
                //                        }
                } else if (reference instanceof TypeReference) {
                    TypeReference typeReference = (TypeReference) reference;
                    DexDiffInfo.addUsedClass(typeReference.getType());
                } else if (reference instanceof FieldReference) {
                    FieldReference fieldReference = (FieldReference) reference;
                    DexDiffInfo.addUsedClass(fieldReference.getDefiningClass());
                }
            }
            assert referenceString != null;
        } catch (InvalidItemIndex ex) {
            writer.write("#");
            writer.write(ex.getMessage());
            writer.write("\n");
            commentOutInstruction = true;
            referenceString = String.format("%s@%d", ReferenceType.toString(referenceInstruction.getReferenceType()), ex.getInvalidIndex());
        } catch (ReferenceType.InvalidReferenceTypeException ex) {
            writer.write("#invalid reference type: ");
            writer.printSignedIntAsDec(ex.getReferenceType());
            commentOutInstruction = true;
            referenceString = "invalid_reference";
        }
    }
    if (instruction instanceof Instruction31t) {
        boolean validPayload = true;
        switch(instruction.getOpcode()) {
            case PACKED_SWITCH:
                int baseAddress = methodDef.getPackedSwitchBaseAddress(this.codeAddress + ((Instruction31t) instruction).getCodeOffset());
                if (baseAddress == -1) {
                    validPayload = false;
                }
                break;
            case SPARSE_SWITCH:
                baseAddress = methodDef.getSparseSwitchBaseAddress(this.codeAddress + ((Instruction31t) instruction).getCodeOffset());
                if (baseAddress == -1) {
                    validPayload = false;
                }
                break;
            case FILL_ARRAY_DATA:
                try {
                    methodDef.findPayloadOffset(this.codeAddress + ((Instruction31t) instruction).getCodeOffset(), Opcode.ARRAY_PAYLOAD);
                } catch (MethodDefinition.InvalidSwitchPayload ex) {
                    validPayload = false;
                }
                break;
            default:
                throw new ExceptionWithContext("Invalid 31t opcode: %s", instruction.getOpcode());
        }
        if (!validPayload) {
            writer.write("#invalid payload reference\n");
            commentOutInstruction = true;
        }
    }
    if (opcode.odexOnly()) {
        if (!isAllowedOdex(opcode)) {
            writer.write("#disallowed odex opcode\n");
            commentOutInstruction = true;
        }
    }
    if (commentOutInstruction) {
        writer.write("#");
    }
    switch(instruction.getOpcode().format) {
        case Format10t:
            writeOpcode(writer);
            writer.write(' ');
            writeTargetLabel(writer);
            break;
        case Format10x:
            if (instruction instanceof UnknownInstruction) {
                writer.write("#unknown opcode: 0x");
                writer.printUnsignedLongAsHex(((UnknownInstruction) instruction).getOriginalOpcode());
                writer.write('\n');
            }
            writeOpcode(writer);
            break;
        case Format11n:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeLiteral(writer);
            break;
        case Format11x:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            break;
        case Format12x:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeSecondRegister(writer);
            break;
        case Format20bc:
            writeOpcode(writer);
            writer.write(' ');
            writer.write(verificationErrorName);
            writer.write(", ");
            writer.write(referenceString);
            break;
        case Format20t:
        case Format30t:
            writeOpcode(writer);
            writer.write(' ');
            writeTargetLabel(writer);
            break;
        case Format21c:
        case Format31c:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writer.write(referenceString);
            break;
        case Format21ih:
        case Format21lh:
        case Format21s:
        case Format31i:
        case Format51l:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeLiteral(writer);
            if (instruction.getOpcode().setsWideRegister()) {
                writeCommentIfLikelyDouble(writer);
            } else {
                boolean isResourceId = writeCommentIfResourceId(writer);
                if (!isResourceId)
                    writeCommentIfLikelyFloat(writer);
            }
            break;
        case Format21t:
        case Format31t:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeTargetLabel(writer);
            break;
        case Format22b:
        case Format22s:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeSecondRegister(writer);
            writer.write(", ");
            writeLiteral(writer);
            break;
        case Format22c:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeSecondRegister(writer);
            writer.write(", ");
            writer.write(referenceString);
            break;
        case Format22cs:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeSecondRegister(writer);
            writer.write(", ");
            writeFieldOffset(writer);
            break;
        case Format22t:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeSecondRegister(writer);
            writer.write(", ");
            writeTargetLabel(writer);
            break;
        case Format22x:
        case Format32x:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeSecondRegister(writer);
            break;
        case Format23x:
            writeOpcode(writer);
            writer.write(' ');
            writeFirstRegister(writer);
            writer.write(", ");
            writeSecondRegister(writer);
            writer.write(", ");
            writeThirdRegister(writer);
            break;
        case Format25x:
            writeOpcode(writer);
            writer.write(' ');
            // vC, {vD, ...}
            writeInvoke25xRegisters(writer);
            break;
        case Format35c:
            writeOpcode(writer);
            writer.write(' ');
            writeInvokeRegisters(writer);
            writer.write(", ");
            writer.write(referenceString);
            break;
        case Format35mi:
            writeOpcode(writer);
            writer.write(' ');
            writeInvokeRegisters(writer);
            writer.write(", ");
            writeInlineIndex(writer);
            break;
        case Format35ms:
            writeOpcode(writer);
            writer.write(' ');
            writeInvokeRegisters(writer);
            writer.write(", ");
            writeVtableIndex(writer);
            break;
        case Format3rc:
            writeOpcode(writer);
            writer.write(' ');
            writeInvokeRangeRegisters(writer);
            writer.write(", ");
            writer.write(referenceString);
            break;
        case Format3rmi:
            writeOpcode(writer);
            writer.write(' ');
            writeInvokeRangeRegisters(writer);
            writer.write(", ");
            writeInlineIndex(writer);
            break;
        case Format3rms:
            writeOpcode(writer);
            writer.write(' ');
            writeInvokeRangeRegisters(writer);
            writer.write(", ");
            writeVtableIndex(writer);
            break;
        default:
            assert false;
            return false;
    }
    if (commentOutInstruction) {
        writer.write("\nnop");
    }
    return true;
}
Also used : InvalidItemIndex(org.jf.dexlib2.dexbacked.DexBackedDexFile.InvalidItemIndex) FieldReference(org.jf.dexlib2.iface.reference.FieldReference) TypeReference(org.jf.dexlib2.iface.reference.TypeReference) Reference(org.jf.dexlib2.iface.reference.Reference) FieldReference(org.jf.dexlib2.iface.reference.FieldReference) MethodReference(org.jf.dexlib2.iface.reference.MethodReference) Opcode(org.jf.dexlib2.Opcode) ReferenceInstruction(org.jf.dexlib2.iface.instruction.ReferenceInstruction) ReferenceType(org.jf.dexlib2.ReferenceType) UnknownInstruction(org.jf.dexlib2.iface.instruction.formats.UnknownInstruction) Instruction20bc(org.jf.dexlib2.iface.instruction.formats.Instruction20bc) ExceptionWithContext(org.jf.util.ExceptionWithContext) MethodDefinition(com.taobao.android.baksmali.adaptors.MethodDefinition) MethodReference(org.jf.dexlib2.iface.reference.MethodReference) TypeReference(org.jf.dexlib2.iface.reference.TypeReference) Instruction31t(org.jf.dexlib2.iface.instruction.formats.Instruction31t)

Example 9 with ExceptionWithContext

use of org.jf.util.ExceptionWithContext in project smali by JesusFreke.

the class MethodAnalyzer method analyzeIputIgetQuick.

private boolean analyzeIputIgetQuick(@Nonnull AnalyzedInstruction analyzedInstruction) {
    Instruction22cs instruction = (Instruction22cs) analyzedInstruction.instruction;
    int fieldOffset = instruction.getFieldOffset();
    RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitCategories);
    if (objectRegisterType.category == RegisterType.NULL) {
        return false;
    }
    TypeProto objectRegisterTypeProto = objectRegisterType.type;
    assert objectRegisterTypeProto != null;
    TypeProto classTypeProto = classPath.getClass(objectRegisterTypeProto.getType());
    FieldReference resolvedField = classTypeProto.getFieldByOffset(fieldOffset);
    if (resolvedField == null) {
        throw new AnalysisException("Could not resolve the field in class %s at offset %d", objectRegisterType.type.getType(), fieldOffset);
    }
    ClassDef thisClass = classPath.getClassDef(method.getDefiningClass());
    if (!TypeUtils.canAccessClass(thisClass.getType(), classPath.getClassDef(resolvedField.getDefiningClass()))) {
        // the class is not accessible. So we start looking at objectRegisterTypeProto (which may be different
        // than resolvedField.getDefiningClass()), and walk up the class hierarchy.
        ClassDef fieldClass = classPath.getClassDef(objectRegisterTypeProto.getType());
        while (!TypeUtils.canAccessClass(thisClass.getType(), fieldClass)) {
            String superclass = fieldClass.getSuperclass();
            if (superclass == null) {
                throw new ExceptionWithContext("Couldn't find accessible class while resolving field %s", ReferenceUtil.getShortFieldDescriptor(resolvedField));
            }
            fieldClass = classPath.getClassDef(superclass);
        }
        // fieldClass is now the first accessible class found. Now. we need to make sure that the field is
        // actually valid for this class
        FieldReference newResolvedField = classPath.getClass(fieldClass.getType()).getFieldByOffset(fieldOffset);
        if (newResolvedField == null) {
            throw new ExceptionWithContext("Couldn't find accessible class while resolving field %s", ReferenceUtil.getShortFieldDescriptor(resolvedField));
        }
        resolvedField = new ImmutableFieldReference(fieldClass.getType(), newResolvedField.getName(), newResolvedField.getType());
    }
    String fieldType = resolvedField.getType();
    Opcode opcode = classPath.getFieldInstructionMapper().getAndCheckDeodexedOpcode(fieldType, instruction.getOpcode());
    Instruction22c deodexedInstruction = new ImmutableInstruction22c(opcode, (byte) instruction.getRegisterA(), (byte) instruction.getRegisterB(), resolvedField);
    analyzedInstruction.setDeodexedInstruction(deodexedInstruction);
    analyzeInstruction(analyzedInstruction);
    return true;
}
Also used : FieldReference(org.jf.dexlib2.iface.reference.FieldReference) ImmutableFieldReference(org.jf.dexlib2.immutable.reference.ImmutableFieldReference) ImmutableFieldReference(org.jf.dexlib2.immutable.reference.ImmutableFieldReference) Opcode(org.jf.dexlib2.Opcode) ExceptionWithContext(org.jf.util.ExceptionWithContext)

Example 10 with ExceptionWithContext

use of org.jf.util.ExceptionWithContext in project smali by JesusFreke.

the class MethodAnalyzer method analyzeInvokeVirtualQuick.

private boolean analyzeInvokeVirtualQuick(@Nonnull AnalyzedInstruction analyzedInstruction, boolean isSuper, boolean isRange) {
    int methodIndex;
    int objectRegister;
    if (isRange) {
        Instruction3rms instruction = (Instruction3rms) analyzedInstruction.instruction;
        methodIndex = instruction.getVtableIndex();
        objectRegister = instruction.getStartRegister();
    } else {
        Instruction35ms instruction = (Instruction35ms) analyzedInstruction.instruction;
        methodIndex = instruction.getVtableIndex();
        objectRegister = instruction.getRegisterC();
    }
    RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, objectRegister, ReferenceOrUninitCategories);
    TypeProto objectRegisterTypeProto = objectRegisterType.type;
    if (objectRegisterType.category == RegisterType.NULL) {
        return false;
    }
    assert objectRegisterTypeProto != null;
    MethodReference resolvedMethod;
    if (isSuper) {
        // invoke-super is only used for the same class that we're currently in
        TypeProto typeProto = classPath.getClass(method.getDefiningClass());
        TypeProto superType;
        String superclassType = typeProto.getSuperclass();
        if (superclassType != null) {
            superType = classPath.getClass(superclassType);
        } else {
            // This is either java.lang.Object, or an UnknownClassProto
            superType = typeProto;
        }
        resolvedMethod = superType.getMethodByVtableIndex(methodIndex);
    } else {
        resolvedMethod = objectRegisterTypeProto.getMethodByVtableIndex(methodIndex);
    }
    if (resolvedMethod == null) {
        throw new AnalysisException("Could not resolve the method in class %s at index %d", objectRegisterType.type.getType(), methodIndex);
    }
    // no need to check class access for invoke-super. A class can obviously access its superclass.
    ClassDef thisClass = classPath.getClassDef(method.getDefiningClass());
    if (classPath.getClass(resolvedMethod.getDefiningClass()).isInterface()) {
        resolvedMethod = new ReparentedMethodReference(resolvedMethod, objectRegisterTypeProto.getType());
    } else if (!isSuper && !TypeUtils.canAccessClass(thisClass.getType(), classPath.getClassDef(resolvedMethod.getDefiningClass()))) {
        // the class is not accessible. So we start looking at objectRegisterTypeProto (which may be different
        // than resolvedMethod.getDefiningClass()), and walk up the class hierarchy.
        ClassDef methodClass = classPath.getClassDef(objectRegisterTypeProto.getType());
        while (!TypeUtils.canAccessClass(thisClass.getType(), methodClass)) {
            String superclass = methodClass.getSuperclass();
            if (superclass == null) {
                throw new ExceptionWithContext("Couldn't find accessible class while resolving method %s", ReferenceUtil.getMethodDescriptor(resolvedMethod, true));
            }
            methodClass = classPath.getClassDef(superclass);
        }
        // methodClass is now the first accessible class found. Now. we need to make sure that the method is
        // actually valid for this class
        MethodReference newResolvedMethod = classPath.getClass(methodClass.getType()).getMethodByVtableIndex(methodIndex);
        if (newResolvedMethod == null) {
            throw new ExceptionWithContext("Couldn't find accessible class while resolving method %s", ReferenceUtil.getMethodDescriptor(resolvedMethod, true));
        }
        resolvedMethod = newResolvedMethod;
        resolvedMethod = new ImmutableMethodReference(methodClass.getType(), resolvedMethod.getName(), resolvedMethod.getParameterTypes(), resolvedMethod.getReturnType());
    }
    if (normalizeVirtualMethods) {
        MethodReference replacementMethod = normalizeMethodReference(resolvedMethod);
        if (replacementMethod != null) {
            resolvedMethod = replacementMethod;
        }
    }
    Instruction deodexedInstruction;
    if (isRange) {
        Instruction3rms instruction = (Instruction3rms) analyzedInstruction.instruction;
        Opcode opcode;
        if (isSuper) {
            opcode = Opcode.INVOKE_SUPER_RANGE;
        } else {
            opcode = Opcode.INVOKE_VIRTUAL_RANGE;
        }
        deodexedInstruction = new ImmutableInstruction3rc(opcode, instruction.getStartRegister(), instruction.getRegisterCount(), resolvedMethod);
    } else {
        Instruction35ms instruction = (Instruction35ms) analyzedInstruction.instruction;
        Opcode opcode;
        if (isSuper) {
            opcode = Opcode.INVOKE_SUPER;
        } else {
            opcode = Opcode.INVOKE_VIRTUAL;
        }
        deodexedInstruction = new ImmutableInstruction35c(opcode, instruction.getRegisterCount(), instruction.getRegisterC(), instruction.getRegisterD(), instruction.getRegisterE(), instruction.getRegisterF(), instruction.getRegisterG(), resolvedMethod);
    }
    analyzedInstruction.setDeodexedInstruction(deodexedInstruction);
    analyzeInstruction(analyzedInstruction);
    return true;
}
Also used : ImmutableMethodReference(org.jf.dexlib2.immutable.reference.ImmutableMethodReference) Opcode(org.jf.dexlib2.Opcode) ExceptionWithContext(org.jf.util.ExceptionWithContext) BaseMethodReference(org.jf.dexlib2.base.reference.BaseMethodReference) ImmutableMethodReference(org.jf.dexlib2.immutable.reference.ImmutableMethodReference) MethodReference(org.jf.dexlib2.iface.reference.MethodReference)

Aggregations

ExceptionWithContext (org.jf.util.ExceptionWithContext)14 Opcode (org.jf.dexlib2.Opcode)4 Instruction (org.jf.dexlib2.iface.instruction.Instruction)4 ReferenceInstruction (org.jf.dexlib2.iface.instruction.ReferenceInstruction)4 Nonnull (javax.annotation.Nonnull)2 ReferenceType (org.jf.dexlib2.ReferenceType)2 MutableMethodImplementation (org.jf.dexlib2.builder.MutableMethodImplementation)2 InvalidItemIndex (org.jf.dexlib2.dexbacked.DexBackedDexFile.InvalidItemIndex)2 DexBackedInstruction (org.jf.dexlib2.dexbacked.instruction.DexBackedInstruction)2 ExceptionHandler (org.jf.dexlib2.iface.ExceptionHandler)2 OneRegisterInstruction (org.jf.dexlib2.iface.instruction.OneRegisterInstruction)2 Instruction20bc (org.jf.dexlib2.iface.instruction.formats.Instruction20bc)2 Instruction31t (org.jf.dexlib2.iface.instruction.formats.Instruction31t)2 UnknownInstruction (org.jf.dexlib2.iface.instruction.formats.UnknownInstruction)2 FieldReference (org.jf.dexlib2.iface.reference.FieldReference)2 MethodReference (org.jf.dexlib2.iface.reference.MethodReference)2 Reference (org.jf.dexlib2.iface.reference.Reference)2 MethodDefinition (com.taobao.android.baksmali.adaptors.MethodDefinition)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 Map (java.util.Map)1