code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.Format; import org.jf.baksmali.Adaptors.MethodDefinition; import org.jf.dexlib.Code.Format.*; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.CodeItem; public class InstructionMethodItemFactory { private InstructionMethodItemFactory() { } public static InstructionMethodItem makeInstructionFormatMethodItem( MethodDefinition methodDefinition, CodeItem codeItem, int codeAddress, Instruction instruction) { if (instruction instanceof OffsetInstruction) { return new OffsetInstructionFormatMethodItem(methodDefinition.getLabelCache(), codeItem, codeAddress, (OffsetInstruction)instruction); } switch (instruction.getFormat()) { case ArrayData: return new ArrayDataMethodItem(codeItem, codeAddress, (ArrayDataPseudoInstruction)instruction); case PackedSwitchData: return new PackedSwitchMethodItem(methodDefinition, codeItem, codeAddress, (PackedSwitchDataPseudoInstruction)instruction); case SparseSwitchData: return new SparseSwitchMethodItem(methodDefinition, codeItem, codeAddress, (SparseSwitchDataPseudoInstruction)instruction); case UnresolvedOdexInstruction: return new UnresolvedOdexInstructionMethodItem(codeItem, codeAddress, (UnresolvedOdexInstruction)instruction); default: return new InstructionMethodItem<Instruction>(codeItem, codeAddress, instruction); } } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/Format/InstructionMethodItemFactory.java
Java
asf20
3,197
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.Format; import org.jf.baksmali.Adaptors.LabelMethodItem; import org.jf.baksmali.Adaptors.MethodDefinition; import org.jf.util.IndentingWriter; import org.jf.baksmali.Renderers.IntegerRenderer; import org.jf.dexlib.Code.Format.PackedSwitchDataPseudoInstruction; import org.jf.dexlib.CodeItem; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class PackedSwitchMethodItem extends InstructionMethodItem<PackedSwitchDataPseudoInstruction> { private final List<PackedSwitchTarget> targets; public PackedSwitchMethodItem(MethodDefinition methodDefinition, CodeItem codeItem, int codeAddress, PackedSwitchDataPseudoInstruction instruction) { super(codeItem, codeAddress, instruction); int baseCodeAddress = methodDefinition.getPackedSwitchBaseAddress(codeAddress); targets = new ArrayList<PackedSwitchTarget>(); Iterator<PackedSwitchDataPseudoInstruction.PackedSwitchTarget> iterator = instruction.iterateKeysAndTargets(); if (baseCodeAddress >= 0) { while (iterator.hasNext()) { PackedSwitchDataPseudoInstruction.PackedSwitchTarget target = iterator.next(); PackedSwitchLabelTarget packedSwitchLabelTarget = new PackedSwitchLabelTarget(); LabelMethodItem label = new LabelMethodItem(baseCodeAddress + target.targetAddressOffset, "pswitch_"); label = methodDefinition.getLabelCache().internLabel(label); packedSwitchLabelTarget.Target = label; targets.add(packedSwitchLabelTarget); } } else { while (iterator.hasNext()) { PackedSwitchDataPseudoInstruction.PackedSwitchTarget target = iterator.next(); PackedSwitchOffsetTarget packedSwitchOffsetTarget = new PackedSwitchOffsetTarget(); packedSwitchOffsetTarget.Target = target.targetAddressOffset; targets.add(packedSwitchOffsetTarget); } } } @Override public boolean writeTo(IndentingWriter writer) throws IOException { writer.write(".packed-switch "); IntegerRenderer.writeTo(writer, instruction.getFirstKey()); writer.indent(4); writer.write('\n'); for (PackedSwitchTarget target: targets) { target.writeTargetTo(writer); writer.write('\n'); } writer.deindent(4); writer.write(".end packed-switch"); return true; } private static abstract class PackedSwitchTarget { public abstract void writeTargetTo(IndentingWriter writer) throws IOException; } private static class PackedSwitchLabelTarget extends PackedSwitchTarget { public LabelMethodItem Target; public void writeTargetTo(IndentingWriter writer) throws IOException { Target.writeTo(writer); } } private static class PackedSwitchOffsetTarget extends PackedSwitchTarget { public int Target; public void writeTargetTo(IndentingWriter writer) throws IOException { if (Target >= 0) { writer.write('+'); } writer.printSignedIntAsDec(Target); } } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/Format/PackedSwitchMethodItem.java
Java
asf20
4,819
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.Format; import org.jf.util.IndentingWriter; import org.jf.baksmali.Renderers.ByteRenderer; import org.jf.dexlib.Code.Format.ArrayDataPseudoInstruction; import org.jf.dexlib.CodeItem; import java.io.IOException; import java.util.Iterator; public class ArrayDataMethodItem extends InstructionMethodItem<ArrayDataPseudoInstruction> { public ArrayDataMethodItem(CodeItem codeItem, int codeAddress, ArrayDataPseudoInstruction instruction) { super(codeItem, codeAddress, instruction); } public boolean writeTo(IndentingWriter writer) throws IOException { writer.write(".array-data 0x"); writer.printUnsignedLongAsHex(instruction.getElementWidth()); writer.write('\n'); writer.indent(4); Iterator<ArrayDataPseudoInstruction.ArrayElement> iterator = instruction.getElements(); while (iterator.hasNext()) { ArrayDataPseudoInstruction.ArrayElement element = iterator.next(); for (int i=0; i<element.elementWidth; i++) { if (i!=0) { writer.write(' '); } ByteRenderer.writeUnsignedTo(writer, element.buffer[element.bufferIndex+i]); } writer.write('\n'); } writer.deindent(4); writer.write(".end array-data"); return true; } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/Format/ArrayDataMethodItem.java
Java
asf20
2,875
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.Format; import org.jf.baksmali.Adaptors.MethodItem; import org.jf.baksmali.Adaptors.ReferenceFormatter; import org.jf.baksmali.Adaptors.RegisterFormatter; import org.jf.dexlib.Code.Format.Instruction20bc; import org.jf.dexlib.Code.Format.UnknownInstruction; import org.jf.util.IndentingWriter; import org.jf.baksmali.Renderers.LongRenderer; import org.jf.dexlib.Code.*; import org.jf.dexlib.CodeItem; import org.jf.dexlib.Item; import java.io.IOException; public class InstructionMethodItem<T extends Instruction> extends MethodItem { protected final CodeItem codeItem; protected final T instruction; public InstructionMethodItem(CodeItem codeItem, int codeAddress, T instruction) { super(codeAddress); this.codeItem = codeItem; this.instruction = instruction; } public double getSortOrder() { //instructions should appear after everything except an "end try" label and .catch directive return 100; } @Override public boolean writeTo(IndentingWriter writer) throws IOException { switch (instruction.getFormat()) { case Format10t: writeOpcode(writer); writer.write(' '); writeTargetLabel(writer); return true; case Format10x: if (instruction instanceof UnknownInstruction) { writer.write("#unknown opcode: 0x"); writer.printUnsignedLongAsHex(((UnknownInstruction) instruction).getOriginalOpcode() & 0xFFFF); writer.write('\n'); } writeOpcode(writer); return true; case Format11n: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeLiteral(writer); return true; case Format11x: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); return true; case Format12x: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeSecondRegister(writer); return true; case Format20bc: writeOpcode(writer); writer.write(' '); writeVerificationErrorType(writer); writer.write(", "); writeReference(writer); return true; case Format20t: case Format30t: writeOpcode(writer); writer.write(' '); writeTargetLabel(writer); return true; case Format21c: case Format31c: case Format41c: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeReference(writer); return true; case Format21h: case Format21s: case Format31i: case Format51l: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeLiteral(writer); return true; case Format21t: case Format31t: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeTargetLabel(writer); return true; case Format22b: case Format22s: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeSecondRegister(writer); writer.write(", "); writeLiteral(writer); return true; case Format22c: case Format52c: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeSecondRegister(writer); writer.write(", "); writeReference(writer); return true; case Format22cs: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeSecondRegister(writer); writer.write(", "); writeFieldOffset(writer); return true; case Format22t: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeSecondRegister(writer); writer.write(", "); writeTargetLabel(writer); return true; case Format22x: case Format32x: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeSecondRegister(writer); return true; case Format23x: writeOpcode(writer); writer.write(' '); writeFirstRegister(writer); writer.write(", "); writeSecondRegister(writer); writer.write(", "); writeThirdRegister(writer); return true; case Format35c: writeOpcode(writer); writer.write(' '); writeInvokeRegisters(writer); writer.write(", "); writeReference(writer); return true; case Format35mi: writeOpcode(writer); writer.write(' '); writeInvokeRegisters(writer); writer.write(", "); writeInlineIndex(writer); return true; case Format35ms: writeOpcode(writer); writer.write(' '); writeInvokeRegisters(writer); writer.write(", "); writeVtableIndex(writer); return true; case Format3rc: case Format5rc: writeOpcode(writer); writer.write(' '); writeInvokeRangeRegisters(writer); writer.write(", "); writeReference(writer); return true; case Format3rmi: writeOpcode(writer); writer.write(' '); writeInvokeRangeRegisters(writer); writer.write(", "); writeInlineIndex(writer); return true; case Format3rms: writeOpcode(writer); writer.write(' '); writeInvokeRangeRegisters(writer); writer.write(", "); writeVtableIndex(writer); return true; } assert false; return false; } protected void writeOpcode(IndentingWriter writer) throws IOException { writer.write(instruction.opcode.name); } protected void writeTargetLabel(IndentingWriter writer) throws IOException { //this method is overrided by OffsetInstructionMethodItem, and should only be called for the formats that //have a target throw new RuntimeException(); } protected void writeRegister(IndentingWriter writer, int registerNumber) throws IOException { RegisterFormatter.writeTo(writer, codeItem, registerNumber); } protected void writeFirstRegister(IndentingWriter writer) throws IOException { writeRegister(writer, ((SingleRegisterInstruction)instruction).getRegisterA()); } protected void writeSecondRegister(IndentingWriter writer) throws IOException { writeRegister(writer, ((TwoRegisterInstruction)instruction).getRegisterB()); } protected void writeThirdRegister(IndentingWriter writer) throws IOException { writeRegister(writer, ((ThreeRegisterInstruction)instruction).getRegisterC()); } protected void writeInvokeRegisters(IndentingWriter writer) throws IOException { FiveRegisterInstruction instruction = (FiveRegisterInstruction)this.instruction; final int regCount = instruction.getRegCount(); writer.write('{'); switch (regCount) { case 1: writeRegister(writer, instruction.getRegisterD()); break; case 2: writeRegister(writer, instruction.getRegisterD()); writer.write(", "); writeRegister(writer, instruction.getRegisterE()); break; case 3: writeRegister(writer, instruction.getRegisterD()); writer.write(", "); writeRegister(writer, instruction.getRegisterE()); writer.write(", "); writeRegister(writer, instruction.getRegisterF()); break; case 4: writeRegister(writer, instruction.getRegisterD()); writer.write(", "); writeRegister(writer, instruction.getRegisterE()); writer.write(", "); writeRegister(writer, instruction.getRegisterF()); writer.write(", "); writeRegister(writer, instruction.getRegisterG()); break; case 5: writeRegister(writer, instruction.getRegisterD()); writer.write(", "); writeRegister(writer, instruction.getRegisterE()); writer.write(", "); writeRegister(writer, instruction.getRegisterF()); writer.write(", "); writeRegister(writer, instruction.getRegisterG()); writer.write(", "); writeRegister(writer, instruction.getRegisterA()); break; } writer.write('}'); } protected void writeInvokeRangeRegisters(IndentingWriter writer) throws IOException { RegisterRangeInstruction instruction = (RegisterRangeInstruction)this.instruction; int regCount = instruction.getRegCount(); if (regCount == 0) { writer.write("{}"); } else { int startRegister = instruction.getStartRegister(); RegisterFormatter.writeRegisterRange(writer, codeItem, startRegister, startRegister+regCount-1); } } protected void writeLiteral(IndentingWriter writer) throws IOException { LongRenderer.writeSignedIntOrLongTo(writer, ((LiteralInstruction)instruction).getLiteral()); } protected void writeFieldOffset(IndentingWriter writer) throws IOException { writer.write("field@0x"); writer.printUnsignedLongAsHex(((OdexedFieldAccess) instruction).getFieldOffset()); } protected void writeInlineIndex(IndentingWriter writer) throws IOException { writer.write("inline@0x"); writer.printUnsignedLongAsHex(((OdexedInvokeInline) instruction).getInlineIndex()); } protected void writeVtableIndex(IndentingWriter writer) throws IOException { writer.write("vtable@0x"); writer.printUnsignedLongAsHex(((OdexedInvokeVirtual) instruction).getVtableIndex()); } protected void writeReference(IndentingWriter writer) throws IOException { Item item = ((InstructionWithReference)instruction).getReferencedItem(); ReferenceFormatter.writeReference(writer, item); } protected void writeVerificationErrorType(IndentingWriter writer) throws IOException { VerificationErrorType validationErrorType = ((Instruction20bc)instruction).getValidationErrorType(); writer.write(validationErrorType.getName()); } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/Format/InstructionMethodItem.java
Java
asf20
13,682
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.util.IndentingWriter; import org.jf.baksmali.baksmali; import org.jf.baksmali.main; import org.jf.dexlib.ClassDataItem; import org.jf.dexlib.Code.Analysis.AnalyzedInstruction; import org.jf.dexlib.Code.Analysis.MethodAnalyzer; import org.jf.dexlib.Code.Analysis.RegisterType; import org.jf.dexlib.Code.*; import org.jf.dexlib.Util.AccessFlags; import java.io.IOException; import java.util.BitSet; public class PreInstructionRegisterInfoMethodItem extends MethodItem { private static AnalyzedInstruction lastInstruction; private final AnalyzedInstruction analyzedInstruction; private final MethodAnalyzer methodAnalyzer; public PreInstructionRegisterInfoMethodItem(AnalyzedInstruction analyzedInstruction, MethodAnalyzer methodAnalyzer, int codeAddress) { super(codeAddress); this.analyzedInstruction = analyzedInstruction; this.methodAnalyzer = methodAnalyzer; } @Override public double getSortOrder() { return 99.9; } @Override public boolean writeTo(IndentingWriter writer) throws IOException { int registerInfo = baksmali.registerInfo; int registerCount = analyzedInstruction.getRegisterCount(); BitSet registers = new BitSet(registerCount); if ((registerInfo & main.ALL) != 0) { registers.set(0, registerCount); } else { if ((registerInfo & main.ALLPRE) != 0) { registers.set(0, registerCount); } else { if ((registerInfo & main.ARGS) != 0) { addArgsRegs(registers); } if ((registerInfo & main.DIFFPRE) != 0) { addDiffRegs(registers); } if ((registerInfo & main.MERGE) != 0) { addMergeRegs(registers, registerCount); } else if ((registerInfo & main.FULLMERGE) != 0 && (analyzedInstruction.isBeginningInstruction())) { addParamRegs(registers, registerCount); } } } boolean printedSomething = false; if ((registerInfo & main.FULLMERGE) != 0) { printedSomething = writeFullMergeRegs(writer, registers, registerCount); } printedSomething |= writeRegisterInfo(writer, registers, printedSomething); return printedSomething; } private void addArgsRegs(BitSet registers) { if (analyzedInstruction.getInstruction() instanceof RegisterRangeInstruction) { RegisterRangeInstruction instruction = (RegisterRangeInstruction)analyzedInstruction.getInstruction(); registers.set(instruction.getStartRegister(), instruction.getStartRegister() + instruction.getRegCount()); } else if (analyzedInstruction.getInstruction() instanceof FiveRegisterInstruction) { FiveRegisterInstruction instruction = (FiveRegisterInstruction)analyzedInstruction.getInstruction(); int regCount = instruction.getRegCount(); switch (regCount) { case 5: registers.set(instruction.getRegisterA()); //fall through case 4: registers.set(instruction.getRegisterG()); //fall through case 3: registers.set(instruction.getRegisterF()); //fall through case 2: registers.set(instruction.getRegisterE()); //fall through case 1: registers.set(instruction.getRegisterD()); } } else if (analyzedInstruction.getInstruction() instanceof ThreeRegisterInstruction) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.getInstruction(); registers.set(instruction.getRegisterA()); registers.set(instruction.getRegisterB()); registers.set(instruction.getRegisterC()); } else if (analyzedInstruction.getInstruction() instanceof TwoRegisterInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.getInstruction(); registers.set(instruction.getRegisterA()); registers.set(instruction.getRegisterB()); } else if (analyzedInstruction.getInstruction() instanceof SingleRegisterInstruction) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.getInstruction(); registers.set(instruction.getRegisterA()); } } private void addDiffRegs(BitSet registers) { if (!analyzedInstruction.isBeginningInstruction()) { for (int i = 0; i < analyzedInstruction.getRegisterCount(); i++) { if (lastInstruction.getPreInstructionRegisterType(i).category != analyzedInstruction.getPreInstructionRegisterType(i).category) { registers.set(i); } } } lastInstruction = analyzedInstruction; } private void addMergeRegs(BitSet registers, int registerCount) { if (analyzedInstruction.isBeginningInstruction()) { addParamRegs(registers, registerCount); } if (analyzedInstruction.getPredecessorCount() <= 1) { //in the common case of an instruction that only has a single predecessor which is the previous //instruction, the pre-instruction registers will always match the previous instruction's //post-instruction registers return; } for (int registerNum=0; registerNum<registerCount; registerNum++) { RegisterType mergedRegisterType = analyzedInstruction.getPreInstructionRegisterType(registerNum); for (AnalyzedInstruction predecessor: analyzedInstruction.getPredecessors()) { if (predecessor.getPostInstructionRegisterType(registerNum) != mergedRegisterType) { registers.set(registerNum); continue; } } } } private void addParamRegs(BitSet registers, int registerCount) { ClassDataItem.EncodedMethod encodedMethod = methodAnalyzer.getMethod(); int parameterRegisterCount = encodedMethod.method.getPrototype().getParameterRegisterCount(); if ((encodedMethod.accessFlags & AccessFlags.STATIC.getValue()) == 0) { parameterRegisterCount++; } registers.set(registerCount-parameterRegisterCount, registerCount); } private boolean writeFullMergeRegs(IndentingWriter writer, BitSet registers, int registerCount) throws IOException { if (analyzedInstruction.getPredecessorCount() <= 1) { return false; } ClassDataItem.EncodedMethod encodedMethod = methodAnalyzer.getMethod(); boolean firstRegister = true; for (int registerNum=0; registerNum<registerCount; registerNum++) { RegisterType mergedRegisterType = analyzedInstruction.getPreInstructionRegisterType(registerNum); boolean addRegister = false; for (AnalyzedInstruction predecessor: analyzedInstruction.getPredecessors()) { RegisterType predecessorRegisterType = predecessor.getPostInstructionRegisterType(registerNum); if (predecessorRegisterType.category != RegisterType.Category.Unknown && predecessorRegisterType != mergedRegisterType) { addRegister = true; break; } } if (!addRegister) { continue; } if (firstRegister) { firstRegister = false; } else { writer.write('\n'); } writer.write('#'); RegisterFormatter.writeTo(writer, encodedMethod.codeItem, registerNum); writer.write('='); analyzedInstruction.getPreInstructionRegisterType(registerNum).writeTo(writer); writer.write(":merge{"); boolean first = true; for (AnalyzedInstruction predecessor: analyzedInstruction.getPredecessors()) { RegisterType predecessorRegisterType = predecessor.getPostInstructionRegisterType(registerNum); if (!first) { writer.write(','); } if (predecessor.getInstructionIndex() == -1) { //the fake "StartOfMethod" instruction writer.write("Start:"); } else { writer.write("0x"); writer.printUnsignedLongAsHex(methodAnalyzer.getInstructionAddress(predecessor)); writer.write(':'); } predecessorRegisterType.writeTo(writer); first = false; } writer.write('}'); registers.clear(registerNum); } return !firstRegister; } private boolean writeRegisterInfo(IndentingWriter writer, BitSet registers, boolean addNewline) throws IOException { ClassDataItem.EncodedMethod encodedMethod = methodAnalyzer.getMethod(); int registerNum = registers.nextSetBit(0); if (registerNum < 0) { return false; } if (addNewline) { writer.write('\n'); } writer.write('#'); for (; registerNum >= 0; registerNum = registers.nextSetBit(registerNum + 1)) { RegisterType registerType = analyzedInstruction.getPreInstructionRegisterType(registerNum); RegisterFormatter.writeTo(writer, encodedMethod.codeItem, registerNum); writer.write('='); if (registerType == null) { writer.write("null"); } else { registerType.writeTo(writer); } writer.write(';'); } return true; } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/PreInstructionRegisterInfoMethodItem.java
Java
asf20
11,734
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.util.IndentingWriter; import java.io.IOException; public class CommentMethodItem extends MethodItem { //private final StringTemplate template; private final String comment; private final double sortOrder; public CommentMethodItem(String comment, int codeAddress, double sortOrder) { super(codeAddress); this.comment = comment; this.sortOrder = sortOrder; } public double getSortOrder() { return sortOrder; } public boolean writeTo(IndentingWriter writer) throws IOException { writer.write('#'); writer.write(comment); return true; } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/CommentMethodItem.java
Java
asf20
2,183
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.baksmali.Adaptors.EncodedValue.AnnotationEncodedValueAdaptor; import org.jf.util.IndentingWriter; import org.jf.dexlib.AnnotationItem; import org.jf.dexlib.AnnotationSetItem; import java.io.IOException; public class AnnotationFormatter { public static void writeTo(IndentingWriter writer, AnnotationSetItem annotationSet) throws IOException { boolean first = true; for (AnnotationItem annotationItem: annotationSet.getAnnotations()) { if (!first) { writer.write('\n'); } first = false; writeTo(writer, annotationItem); } } public static void writeTo(IndentingWriter writer, AnnotationItem annotationItem) throws IOException { writer.write(".annotation "); writer.write(annotationItem.getVisibility().visibility); writer.write(' '); ReferenceFormatter.writeTypeReference(writer, annotationItem.getEncodedAnnotation().annotationType); writer.write('\n'); AnnotationEncodedValueAdaptor.writeElementsTo(writer, annotationItem.getEncodedAnnotation()); writer.write(".end annotation\n"); } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/AnnotationFormatter.java
Java
asf20
2,705
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.EncodedValue; import org.jf.baksmali.Adaptors.ReferenceFormatter; import org.jf.util.IndentingWriter; import org.jf.dexlib.EncodedValue.AnnotationEncodedSubValue; import java.io.IOException; public abstract class AnnotationEncodedValueAdaptor { public static void writeTo(IndentingWriter writer, AnnotationEncodedSubValue encodedAnnotation) throws IOException { writer.write(".subannotation "); ReferenceFormatter.writeTypeReference(writer, encodedAnnotation.annotationType); writer.write('\n'); writeElementsTo(writer, encodedAnnotation); writer.write(".end subannotation"); } public static void writeElementsTo(IndentingWriter writer, AnnotationEncodedSubValue encodedAnnotation) throws IOException { writer.indent(4); for (int i=0; i<encodedAnnotation.names.length; i++) { writer.write(encodedAnnotation.names[i].getStringValue()); writer.write(" = "); EncodedValueAdaptor.writeTo(writer, encodedAnnotation.values[i]); writer.write('\n'); } writer.deindent(4); } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/EncodedValue/AnnotationEncodedValueAdaptor.java
Java
asf20
2,709
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.EncodedValue; import org.jf.util.IndentingWriter; import org.jf.dexlib.EncodedValue.ArrayEncodedValue; import org.jf.dexlib.EncodedValue.EncodedValue; import java.io.IOException; public class ArrayEncodedValueAdaptor { public static void writeTo(IndentingWriter writer, ArrayEncodedValue encodedArray) throws IOException { writer.write('{'); EncodedValue[] values = encodedArray.values; if (values == null || values.length == 0) { writer.write('}'); return; } writer.write('\n'); writer.indent(4); boolean first = true; for (EncodedValue encodedValue: encodedArray.values) { if (!first) { writer.write(",\n"); } first = false; EncodedValueAdaptor.writeTo(writer, encodedValue); } writer.deindent(4); writer.write("\n}"); } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/EncodedValue/ArrayEncodedValueAdaptor.java
Java
asf20
2,449
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.EncodedValue; import org.jf.baksmali.Adaptors.ReferenceFormatter; import org.jf.util.IndentingWriter; import org.jf.baksmali.Renderers.*; import org.jf.dexlib.EncodedValue.*; import java.io.IOException; public abstract class EncodedValueAdaptor { public static void writeTo(IndentingWriter writer, EncodedValue encodedValue) throws IOException { switch (encodedValue.getValueType()) { case VALUE_ANNOTATION: AnnotationEncodedValueAdaptor.writeTo(writer, (AnnotationEncodedValue)encodedValue); return; case VALUE_ARRAY: ArrayEncodedValueAdaptor.writeTo(writer, (ArrayEncodedValue)encodedValue); return; case VALUE_BOOLEAN: BooleanRenderer.writeTo(writer, ((BooleanEncodedValue)encodedValue).value); return; case VALUE_BYTE: ByteRenderer.writeTo(writer, ((ByteEncodedValue)encodedValue).value); return; case VALUE_CHAR: CharRenderer.writeTo(writer, ((CharEncodedValue)encodedValue).value); return; case VALUE_DOUBLE: DoubleRenderer.writeTo(writer, ((DoubleEncodedValue)encodedValue).value); return; case VALUE_ENUM: EnumEncodedValueAdaptor.writeTo(writer, ((EnumEncodedValue)encodedValue).value); return; case VALUE_FIELD: ReferenceFormatter.writeFieldReference(writer, ((FieldEncodedValue)encodedValue).value); return; case VALUE_FLOAT: FloatRenderer.writeTo(writer, ((FloatEncodedValue)encodedValue).value); return; case VALUE_INT: IntegerRenderer.writeTo(writer, ((IntEncodedValue)encodedValue).value); return; case VALUE_LONG: LongRenderer.writeTo(writer, ((LongEncodedValue)encodedValue).value); return; case VALUE_METHOD: ReferenceFormatter.writeMethodReference(writer, ((MethodEncodedValue)encodedValue).value); return; case VALUE_NULL: writer.write("null"); return; case VALUE_SHORT: ShortRenderer.writeTo(writer, ((ShortEncodedValue)encodedValue).value); return; case VALUE_STRING: ReferenceFormatter.writeStringReference(writer, ((StringEncodedValue)encodedValue).value); return; case VALUE_TYPE: ReferenceFormatter.writeTypeReference(writer, ((TypeEncodedValue)encodedValue).value); } } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/EncodedValue/EncodedValueAdaptor.java
Java
asf20
4,248
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.EncodedValue; import org.jf.baksmali.Adaptors.ReferenceFormatter; import org.jf.util.IndentingWriter; import org.jf.dexlib.FieldIdItem; import java.io.IOException; public class EnumEncodedValueAdaptor { public static void writeTo(IndentingWriter writer, FieldIdItem item) throws IOException { writer.write(".enum "); ReferenceFormatter.writeFieldReference(writer, item); } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/EncodedValue/EnumEncodedValueAdaptor.java
Java
asf20
1,937
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.util.IndentingWriter; import org.jf.baksmali.baksmali; import org.jf.dexlib.CodeItem; import org.jf.dexlib.Util.AccessFlags; import java.io.IOException; /** * This class contains the logic used for formatting registers */ public class RegisterFormatter { /** * Write out the register range value used by Format3rc. If baksmali.noParameterRegisters is true, it will always * output the registers in the v<n> format. But if false, then it will check if *both* registers are parameter * registers, and if so, use the p<n> format for both. If only the last register is a parameter register, it will * use the v<n> format for both, otherwise it would be confusing to have something like {v20 .. p1} * @param writer the <code>IndentingWriter</code> to write to * @param codeItem the <code>CodeItem</code> that the register is from * @param startRegister the first register in the range * @param lastRegister the last register in the range */ public static void writeRegisterRange(IndentingWriter writer, CodeItem codeItem, int startRegister, int lastRegister) throws IOException { assert lastRegister >= startRegister; if (!baksmali.noParameterRegisters) { int parameterRegisterCount = codeItem.getParent().method.getPrototype().getParameterRegisterCount() + (((codeItem.getParent().accessFlags & AccessFlags.STATIC.getValue())==0)?1:0); int registerCount = codeItem.getRegisterCount(); assert startRegister <= lastRegister; if (startRegister >= registerCount - parameterRegisterCount) { writer.write("{p"); writer.printSignedIntAsDec(startRegister - (registerCount - parameterRegisterCount)); writer.write(" .. p"); writer.printSignedIntAsDec(lastRegister - (registerCount - parameterRegisterCount)); writer.write('}'); return; } } writer.write("{v"); writer.printSignedIntAsDec(startRegister); writer.write(" .. v"); writer.printSignedIntAsDec(lastRegister); writer.write('}'); } /** * Writes a register with the appropriate format. If baksmali.noParameterRegisters is true, then it will always * output a register in the v<n> format. If false, then it determines if the register is a parameter register, * and if so, formats it in the p<n> format instead. * * @param writer the <code>IndentingWriter</code> to write to * @param codeItem the <code>CodeItem</code> that the register is from * @param register the register number */ public static void writeTo(IndentingWriter writer, CodeItem codeItem, int register) throws IOException { if (!baksmali.noParameterRegisters) { int parameterRegisterCount = codeItem.getParent().method.getPrototype().getParameterRegisterCount() + (((codeItem.getParent().accessFlags & AccessFlags.STATIC.getValue())==0)?1:0); int registerCount = codeItem.getRegisterCount(); if (register >= registerCount - parameterRegisterCount) { writer.write('p'); writer.printSignedIntAsDec((register - (registerCount - parameterRegisterCount))); return; } } writer.write('v'); writer.printSignedIntAsDec(register); } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/RegisterFormatter.java
Java
asf20
5,028
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.baksmali.Adaptors.EncodedValue.EncodedValueAdaptor; import org.jf.util.IndentingWriter; import org.jf.dexlib.AnnotationSetItem; import org.jf.dexlib.ClassDataItem; import org.jf.dexlib.EncodedValue.EncodedValue; import org.jf.dexlib.EncodedValue.NullEncodedValue; import org.jf.dexlib.Util.AccessFlags; import java.io.IOException; public class FieldDefinition { public static void writeTo(IndentingWriter writer, ClassDataItem.EncodedField encodedField, EncodedValue initialValue, AnnotationSetItem annotationSet, boolean setInStaticConstructor) throws IOException { String fieldTypeDescriptor = encodedField.field.getFieldType().getTypeDescriptor(); if (setInStaticConstructor && encodedField.isStatic() && (encodedField.accessFlags & AccessFlags.FINAL.getValue()) != 0 && initialValue != null && ( //it's a primitive type, or it's an array/reference type and the initial value isn't null fieldTypeDescriptor.length() == 1 || initialValue != NullEncodedValue.NullValue )) { writer.write("#the value of this static final field might be set in the static constructor\n"); } writer.write(".field "); writeAccessFlags(writer, encodedField); writer.write(encodedField.field.getFieldName().getStringValue()); writer.write(':'); writer.write(encodedField.field.getFieldType().getTypeDescriptor()); if (initialValue != null) { writer.write(" = "); EncodedValueAdaptor.writeTo(writer, initialValue); } writer.write('\n'); if (annotationSet != null) { writer.indent(4); AnnotationFormatter.writeTo(writer, annotationSet); writer.deindent(4); writer.write(".end field\n"); } } private static void writeAccessFlags(IndentingWriter writer, ClassDataItem.EncodedField encodedField) throws IOException { for (AccessFlags accessFlag: AccessFlags.getAccessFlagsForField(encodedField.accessFlags)) { writer.write(accessFlag.toString()); writer.write(' '); } } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/FieldDefinition.java
Java
asf20
3,950
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.dexlib.Util.Utf8Utils; import org.jf.util.CommentingIndentingWriter; import org.jf.util.IndentingWriter; import org.jf.dexlib.*; import org.jf.dexlib.Code.Analysis.ValidationException; import org.jf.dexlib.Code.Format.Instruction21c; import org.jf.dexlib.Code.Format.Instruction41c; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.EncodedValue.EncodedValue; import org.jf.dexlib.Util.AccessFlags; import org.jf.dexlib.Util.SparseArray; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; public class ClassDefinition { private ClassDefItem classDefItem; @Nullable private ClassDataItem classDataItem; private SparseArray<FieldIdItem> fieldsSetInStaticConstructor; protected boolean validationErrors; public ClassDefinition(ClassDefItem classDefItem) { this.classDefItem = classDefItem; this.classDataItem = classDefItem.getClassData(); findFieldsSetInStaticConstructor(); } public boolean hadValidationErrors() { return validationErrors; } private void findFieldsSetInStaticConstructor() { fieldsSetInStaticConstructor = new SparseArray<FieldIdItem>(); if (classDataItem == null) { return; } for (ClassDataItem.EncodedMethod directMethod: classDataItem.getDirectMethods()) { if (directMethod.method.getMethodName().getStringValue().equals("<clinit>") && directMethod.codeItem != null) { for (Instruction instruction: directMethod.codeItem.getInstructions()) { switch (instruction.opcode) { case SPUT: case SPUT_BOOLEAN: case SPUT_BYTE: case SPUT_CHAR: case SPUT_OBJECT: case SPUT_SHORT: case SPUT_WIDE: { Instruction21c ins = (Instruction21c)instruction; FieldIdItem fieldIdItem = (FieldIdItem)ins.getReferencedItem(); fieldsSetInStaticConstructor.put(fieldIdItem.getIndex(), fieldIdItem); break; } case SPUT_JUMBO: case SPUT_BOOLEAN_JUMBO: case SPUT_BYTE_JUMBO: case SPUT_CHAR_JUMBO: case SPUT_OBJECT_JUMBO: case SPUT_SHORT_JUMBO: case SPUT_WIDE_JUMBO: { Instruction41c ins = (Instruction41c)instruction; FieldIdItem fieldIdItem = (FieldIdItem)ins.getReferencedItem(); fieldsSetInStaticConstructor.put(fieldIdItem.getIndex(), fieldIdItem); break; } } } } } } public void writeTo(IndentingWriter writer) throws IOException { writeClass(writer); writeSuper(writer); writeSourceFile(writer); writeInterfaces(writer); writeAnnotations(writer); writeStaticFields(writer); writeInstanceFields(writer); writeDirectMethods(writer); writeVirtualMethods(writer); } private void writeClass(IndentingWriter writer) throws IOException { writer.write(".class "); writeAccessFlags(writer); writer.write(classDefItem.getClassType().getTypeDescriptor()); writer.write('\n'); } private void writeAccessFlags(IndentingWriter writer) throws IOException { for (AccessFlags accessFlag: AccessFlags.getAccessFlagsForClass(classDefItem.getAccessFlags())) { writer.write(accessFlag.toString()); writer.write(' '); } } private void writeSuper(IndentingWriter writer) throws IOException { TypeIdItem superClass = classDefItem.getSuperclass(); if (superClass != null) { writer.write(".super "); writer.write(superClass.getTypeDescriptor()); writer.write('\n'); } } private void writeSourceFile(IndentingWriter writer) throws IOException { StringIdItem sourceFile = classDefItem.getSourceFile(); if (sourceFile != null) { writer.write(".source \""); Utf8Utils.writeEscapedString(writer, sourceFile.getStringValue()); writer.write("\"\n"); } } private void writeInterfaces(IndentingWriter writer) throws IOException { TypeListItem interfaceList = classDefItem.getInterfaces(); if (interfaceList == null) { return; } List<TypeIdItem> interfaces = interfaceList.getTypes(); if (interfaces == null || interfaces.size() == 0) { return; } writer.write('\n'); writer.write("# interfaces\n"); for (TypeIdItem typeIdItem: interfaceList.getTypes()) { writer.write(".implements "); writer.write(typeIdItem.getTypeDescriptor()); writer.write('\n'); } } private void writeAnnotations(IndentingWriter writer) throws IOException { AnnotationDirectoryItem annotationDirectory = classDefItem.getAnnotations(); if (annotationDirectory == null) { return; } AnnotationSetItem annotationSet = annotationDirectory.getClassAnnotations(); if (annotationSet == null) { return; } writer.write("\n\n"); writer.write("# annotations\n"); AnnotationFormatter.writeTo(writer, annotationSet); } private void writeStaticFields(IndentingWriter writer) throws IOException { if (classDataItem == null) { return; } //if classDataItem is not null, then classDefItem won't be null either assert(classDefItem != null); EncodedArrayItem encodedStaticInitializers = classDefItem.getStaticFieldInitializers(); EncodedValue[] staticInitializers; if (encodedStaticInitializers != null) { staticInitializers = encodedStaticInitializers.getEncodedArray().values; } else { staticInitializers = new EncodedValue[0]; } List<ClassDataItem.EncodedField> encodedFields = classDataItem.getStaticFields(); if (encodedFields.size() == 0) { return; } writer.write("\n\n"); writer.write("# static fields\n"); for (int i=0; i<encodedFields.size(); i++) { if (i > 0) { writer.write('\n'); } ClassDataItem.EncodedField field = encodedFields.get(i); EncodedValue encodedValue = null; if (i < staticInitializers.length) { encodedValue = staticInitializers[i]; } AnnotationSetItem fieldAnnotations = null; AnnotationDirectoryItem annotations = classDefItem.getAnnotations(); if (annotations != null) { fieldAnnotations = annotations.getFieldAnnotations(field.field); } IndentingWriter fieldWriter = writer; // the encoded fields are sorted, so we just have to compare with the previous one to detect duplicates if (i > 0 && field.equals(encodedFields.get(i-1))) { fieldWriter = new CommentingIndentingWriter(writer, "#"); fieldWriter.write("Ignoring field with duplicate signature\n"); System.err.println(String.format("Warning: class %s has duplicate static field %s, Ignoring.", classDefItem.getClassType().getTypeDescriptor(), field.field.getShortFieldString())); } boolean setInStaticConstructor = fieldsSetInStaticConstructor.get(field.field.getIndex()) != null; FieldDefinition.writeTo(fieldWriter, field, encodedValue, fieldAnnotations, setInStaticConstructor); } } private void writeInstanceFields(IndentingWriter writer) throws IOException { if (classDataItem == null) { return; } List<ClassDataItem.EncodedField> encodedFields = classDataItem.getInstanceFields(); if (encodedFields.size() == 0) { return; } writer.write("\n\n"); writer.write("# instance fields\n"); for (int i=0; i<encodedFields.size(); i++) { ClassDataItem.EncodedField field = encodedFields.get(i); if (i > 0) { writer.write('\n'); } AnnotationSetItem fieldAnnotations = null; AnnotationDirectoryItem annotations = classDefItem.getAnnotations(); if (annotations != null) { fieldAnnotations = annotations.getFieldAnnotations(field.field); } IndentingWriter fieldWriter = writer; // the encoded fields are sorted, so we just have to compare with the previous one to detect duplicates if (i > 0 && field.equals(encodedFields.get(i-1))) { fieldWriter = new CommentingIndentingWriter(writer, "#"); fieldWriter.write("Ignoring field with duplicate signature\n"); System.err.println(String.format("Warning: class %s has duplicate instance field %s, Ignoring.", classDefItem.getClassType().getTypeDescriptor(), field.field.getShortFieldString())); } FieldDefinition.writeTo(fieldWriter, field, null, fieldAnnotations, false); } } private void writeDirectMethods(IndentingWriter writer) throws IOException { if (classDataItem == null) { return; } List<ClassDataItem.EncodedMethod> directMethods = classDataItem.getDirectMethods(); if (directMethods.size() == 0) { return; } writer.write("\n\n"); writer.write("# direct methods\n"); writeMethods(writer, directMethods); } private void writeVirtualMethods(IndentingWriter writer) throws IOException { if (classDataItem == null) { return; } List<ClassDataItem.EncodedMethod> virtualMethods = classDataItem.getVirtualMethods(); if (virtualMethods.size() == 0) { return; } writer.write("\n\n"); writer.write("# virtual methods\n"); writeMethods(writer, virtualMethods); } private void writeMethods(IndentingWriter writer, List<ClassDataItem.EncodedMethod> methods) throws IOException { for (int i=0; i<methods.size(); i++) { ClassDataItem.EncodedMethod method = methods.get(i); if (i > 0) { writer.write('\n'); } AnnotationSetItem methodAnnotations = null; AnnotationSetRefList parameterAnnotations = null; AnnotationDirectoryItem annotations = classDefItem.getAnnotations(); if (annotations != null) { methodAnnotations = annotations.getMethodAnnotations(method.method); parameterAnnotations = annotations.getParameterAnnotations(method.method); } IndentingWriter methodWriter = writer; // the encoded methods are sorted, so we just have to compare with the previous one to detect duplicates if (i > 0 && method.equals(methods.get(i-1))) { methodWriter = new CommentingIndentingWriter(writer, "#"); methodWriter.write("Ignoring method with duplicate signature\n"); System.err.println(String.format("Warning: class %s has duplicate method %s, Ignoring.", classDefItem.getClassType().getTypeDescriptor(), method.method.getShortMethodString())); } MethodDefinition methodDefinition = new MethodDefinition(method); methodDefinition.writeTo(methodWriter, methodAnnotations, parameterAnnotations); ValidationException validationException = methodDefinition.getValidationException(); if (validationException != null) { System.err.println(String.format("Error while disassembling method %s. Continuing.", method.method.getMethodString())); validationException.printStackTrace(System.err); this.validationErrors = true; } } } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/ClassDefinition.java
Java
asf20
14,076
/* * [The "BSD licence"] * Copyright (c) 2011 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.dexlib.Code.Analysis.SyntheticAccessorResolver; import static org.jf.dexlib.Code.Analysis.SyntheticAccessorResolver.AccessedMember; import org.jf.util.IndentingWriter; import java.io.IOException; public class SyntheticAccessCommentMethodItem extends MethodItem { private final AccessedMember accessedMember; public SyntheticAccessCommentMethodItem(AccessedMember accessedMember, int codeAddress) { super(codeAddress); this.accessedMember = accessedMember; } public double getSortOrder() { //just before the pre-instruction register information, if any return 99.8; } public boolean writeTo(IndentingWriter writer) throws IOException { writer.write('#'); if (accessedMember.accessedMemberType == SyntheticAccessorResolver.METHOD) { writer.write("calls: "); } else if (accessedMember.accessedMemberType == SyntheticAccessorResolver.GETTER) { writer.write("getter for: "); } else { writer.write("setter for: "); } ReferenceFormatter.writeReference(writer, accessedMember.accessedMember); return true; } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/SyntheticAccessCommentMethodItem.java
Java
asf20
2,697
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.util.IndentingWriter; import org.jf.baksmali.baksmali; import org.jf.baksmali.main; import org.jf.dexlib.ClassDataItem; import org.jf.dexlib.Code.Analysis.AnalyzedInstruction; import org.jf.dexlib.Code.Analysis.MethodAnalyzer; import org.jf.dexlib.Code.Analysis.RegisterType; import java.io.IOException; import java.util.BitSet; public class PostInstructionRegisterInfoMethodItem extends MethodItem { private final AnalyzedInstruction analyzedInstruction; private final MethodAnalyzer methodAnalyzer; public PostInstructionRegisterInfoMethodItem(AnalyzedInstruction analyzedInstruction, MethodAnalyzer methodAnalyzer, int codeAddress) { super(codeAddress); this.analyzedInstruction = analyzedInstruction; this.methodAnalyzer = methodAnalyzer; } @Override public double getSortOrder() { return 100.1; } @Override public boolean writeTo(IndentingWriter writer) throws IOException { int registerInfo = baksmali.registerInfo; int registerCount = analyzedInstruction.getRegisterCount(); BitSet registers = new BitSet(registerCount); if ((registerInfo & main.ALL) != 0) { registers.set(0, registerCount); } else { if ((registerInfo & main.ALLPOST) != 0) { registers.set(0, registerCount); } else if ((registerInfo & main.DEST) != 0) { addDestRegs(registers, registerCount); } } return writeRegisterInfo(writer, registers); } private void addDestRegs(BitSet printPostRegister, int registerCount) { for (int registerNum=0; registerNum<registerCount; registerNum++) { if (analyzedInstruction.getPreInstructionRegisterType(registerNum) != analyzedInstruction.getPostInstructionRegisterType(registerNum)) { printPostRegister.set(registerNum); } } } private boolean writeRegisterInfo(IndentingWriter writer, BitSet registers) throws IOException { ClassDataItem.EncodedMethod encodedMethod = methodAnalyzer.getMethod(); int registerNum = registers.nextSetBit(0); if (registerNum < 0) { return false; } writer.write('#'); for (; registerNum >= 0; registerNum = registers.nextSetBit(registerNum + 1)) { RegisterType registerType = analyzedInstruction.getPostInstructionRegisterType(registerNum); RegisterFormatter.writeTo(writer, encodedMethod.codeItem, registerNum); writer.write('='); if (registerType == null) { writer.write("null"); } else { registerType.writeTo(writer); } writer.write(';'); } return true; } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/PostInstructionRegisterInfoMethodItem.java
Java
asf20
4,393
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; import org.jf.util.IndentingWriter; import org.jf.dexlib.TypeIdItem; import java.io.IOException; public class CatchMethodItem extends MethodItem { private final TypeIdItem exceptionType; private final LabelMethodItem tryStartLabel; private final LabelMethodItem tryEndLabel; private final LabelMethodItem handlerLabel; public CatchMethodItem(MethodDefinition.LabelCache labelCache, int codeAddress, TypeIdItem exceptionType, int startAddress, int endAddress, int handlerAddress) { super(codeAddress); this.exceptionType = exceptionType; tryStartLabel = labelCache.internLabel(new LabelMethodItem(startAddress, "try_start_")); //use the address from the last covered instruction, but make the label //name refer to the address of the next instruction tryEndLabel = labelCache.internLabel(new EndTryLabelMethodItem(codeAddress, endAddress)); if (exceptionType == null) { handlerLabel = labelCache.internLabel(new LabelMethodItem(handlerAddress, "catchall_")); } else { handlerLabel = labelCache.internLabel(new LabelMethodItem(handlerAddress, "catch_")); } } public LabelMethodItem getTryStartLabel() { return tryStartLabel; } public LabelMethodItem getTryEndLabel() { return tryEndLabel; } public LabelMethodItem getHandlerLabel() { return handlerLabel; } public double getSortOrder() { //sort after instruction and end_try label return 102; } @Override public boolean writeTo(IndentingWriter writer) throws IOException { if (exceptionType == null) { writer.write(".catchall"); } else { writer.write(".catch "); ReferenceFormatter.writeTypeReference(writer, exceptionType); } writer.write(" {"); tryStartLabel.writeTo(writer); writer.write(" .. "); tryEndLabel.writeTo(writer); writer.write("} "); handlerLabel.writeTo(writer); return true; } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/CatchMethodItem.java
Java
asf20
3,640
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors; public class EndTryLabelMethodItem extends LabelMethodItem { private int endTryAddress; public EndTryLabelMethodItem(int codeAddress, int endTryAddress) { super(codeAddress, "try_end_"); this.endTryAddress = endTryAddress; } public double getSortOrder() { //sort after instruction, but before catch directive return 101; } public int getLabelAddress() { return endTryAddress; } }
zztobat-apktool
brut.apktool.smali/baksmali/src/main/java/org/jf/baksmali/Adaptors/EndTryLabelMethodItem.java
Java
asf20
1,988
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.util; import java.io.IOException; import java.io.Writer; public class IndentingWriter extends Writer { protected final Writer writer; protected final char[] buffer = new char[16]; protected int indentLevel = 0; private boolean beginningOfLine = true; private static final String newLine = System.getProperty("line.separator"); public IndentingWriter(Writer writer) { this.writer = writer; } protected void writeLineStart() throws IOException { } protected void writeIndent() throws IOException { for (int i=0; i<indentLevel; i++) { writer.write(' '); } } @Override public void write(int chr) throws IOException { //synchronized(lock) { if (beginningOfLine) { writeLineStart(); } if (chr == '\n') { writer.write(newLine); beginningOfLine = true; } else { if (beginningOfLine) { writeIndent(); } beginningOfLine = false; writer.write(chr); } //} } @Override public void write(char[] chars) throws IOException { //synchronized(lock) { for (char chr: chars) { write(chr); } //} } @Override public void write(char[] chars, int start, int len) throws IOException { //synchronized(lock) { len = start+len; while (start < len) { write(chars[start++]); } //} } @Override public void write(String s) throws IOException { //synchronized (lock) { for (int i=0; i<s.length(); i++) { write(s.charAt(i)); } //} } @Override public void write(String str, int start, int len) throws IOException { //synchronized(lock) { len = start+len; while (start < len) { write(str.charAt(start++)); } //} } @Override public Writer append(CharSequence charSequence) throws IOException { write(charSequence.toString()); return this; } @Override public Writer append(CharSequence charSequence, int start, int len) throws IOException { write(charSequence.subSequence(start, len).toString()); return this; } @Override public Writer append(char c) throws IOException { write(c); return this; } @Override public void flush() throws IOException { //synchronized(lock) { writer.flush(); //} } @Override public void close() throws IOException { //synchronized(lock) { writer.close(); //} } public void indent(int indentAmount) { //synchronized(lock) { this.indentLevel += indentAmount; if (indentLevel < 0) { indentLevel = 0; } //} } public void deindent(int indentAmount) { //synchronized(lock) { this.indentLevel -= indentAmount; if (indentLevel < 0) { indentLevel = 0; } //} } public void printUnsignedLongAsHex(long value) throws IOException { int bufferIndex = 0; do { int digit = (int)(value & 15); if (digit < 10) { buffer[bufferIndex++] = (char)(digit + '0'); } else { buffer[bufferIndex++] = (char)((digit - 10) + 'a'); } value >>>= 4; } while (value != 0); while (bufferIndex>0) { write(buffer[--bufferIndex]); } } public void printSignedIntAsDec(int value) throws IOException { int bufferIndex = 0; if (value < 0) { value *= -1; write('-'); } do { int digit = value % 10; buffer[bufferIndex++] = (char)(digit + '0'); value = value / 10; } while (value != 0); while (bufferIndex>0) { write(buffer[--bufferIndex]); } } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/org/jf/util/IndentingWriter.java
Java
asf20
5,719
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.util; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import java.io.PrintWriter; public class SmaliHelpFormatter extends HelpFormatter { public void printHelp(String cmdLineSyntax, String header, Options options, Options debugOptions) { super.printHelp(cmdLineSyntax, header, options, ""); if (debugOptions != null) { System.out.println(); System.out.println("Debug Options:"); PrintWriter pw = new PrintWriter(System.out); super.printOptions(pw, getWidth(), debugOptions, getLeftPadding(), getDescPadding()); pw.flush(); } } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/org/jf/util/SmaliHelpFormatter.java
Java
asf20
2,177
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.util; import java.io.File; import java.io.IOException; import java.util.ArrayList; public class PathUtil { private PathUtil() { } public static File getRelativeFile(File baseFile, File fileToRelativize) throws IOException { if (baseFile.isFile()) { baseFile = baseFile.getParentFile(); } return new File(getRelativeFileInternal(baseFile.getCanonicalFile(), fileToRelativize.getCanonicalFile())); } public static String getRelativePath(String basePath, String pathToRelativize) throws IOException { File baseFile = new File(basePath); if (baseFile.isFile()) { baseFile = baseFile.getParentFile(); } return getRelativeFileInternal(baseFile.getCanonicalFile(), new File(pathToRelativize).getCanonicalFile()); } static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { ArrayList<String> basePath = getPathComponents(canonicalBaseFile); ArrayList<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); //if the roots aren't the same (i.e. different drives on a windows machine), we can't construct a relative //path from one to the other, so just return the canonical file if (!basePath.get(0).equals(pathToRelativize.get(0))) { return canonicalFileToRelativize.getPath(); } int commonDirs; StringBuilder sb = new StringBuilder(); for (commonDirs=1; commonDirs<basePath.size() && commonDirs<pathToRelativize.size(); commonDirs++) { if (!basePath.get(commonDirs).equals(pathToRelativize.get(commonDirs))) { break; } } boolean first = true; for (int i=commonDirs; i<basePath.size(); i++) { if (!first) { sb.append(File.separatorChar); } else { first = false; } sb.append(".."); } first = true; for (int i=commonDirs; i<pathToRelativize.size(); i++) { if (first) { if (sb.length() != 0) { sb.append(File.separatorChar); } first = false; } else { sb.append(File.separatorChar); } sb.append(pathToRelativize.get(i)); } if (sb.length() == 0) { return "."; } return sb.toString(); } private static ArrayList<String> getPathComponents(File file) { ArrayList<String> path = new ArrayList<String>(); while (file != null) { File parentFile = file.getParentFile(); if (parentFile == null) { path.add(0, file.getPath()); } else { path.add(0, file.getName()); } file = parentFile; } return path; } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/org/jf/util/PathUtil.java
Java
asf20
4,463
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.util; import java.io.IOException; import java.io.Writer; public class CommentingIndentingWriter extends IndentingWriter { private final String commentStr; public CommentingIndentingWriter(Writer writer, String commentStr) { super(writer); this.commentStr = commentStr; } protected void writeLineStart() throws IOException { writer.write(commentStr); } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/org/jf/util/CommentingIndentingWriter.java
Java
asf20
1,981
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConsoleUtil { /** * Attempt to find the width of the console. If it can't get the width, return a default of 80 * @return */ public static int getConsoleWidth() { if (System.getProperty("os.name").toLowerCase().contains("windows")) { try { return attemptMode(); } catch (Exception ex) { } } else { try { return attemptStty(); } catch (Exception ex) { } } return 80; } private static int attemptStty() { String output = attemptCommand(new String[]{"sh", "-c", "stty size < /dev/tty"}); if (output == null) { return 80; } String[] vals = output.split(" "); if (vals.length < 2) { return 80; } return Integer.parseInt(vals[1]); } private static int attemptMode() { String output = attemptCommand(new String[]{"mode", "con"}); if (output == null) { return 80; } Pattern pattern = Pattern.compile("Columns:[ \t]*(\\d+)"); Matcher m = pattern.matcher(output); if (!m.find()) { return 80; } return Integer.parseInt(m.group(1)); } private static String attemptCommand(String[] command) { StringBuffer buffer = null; try { Process p = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (buffer == null) { buffer = new StringBuffer(); } buffer.append(line); } if (buffer != null) { return buffer.toString(); } return null; } catch (Exception ex) { return null; } } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/org/jf/util/ConsoleUtil.java
Java
asf20
3,635
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.util; import ds.tree.RadixTree; import ds.tree.RadixTreeImpl; import java.io.*; import java.nio.CharBuffer; import java.util.regex.Pattern; /** * This class checks for case-insensitive file systems, and generates file names based on a given class name, that are * guaranteed to be unique. When "colliding" class names are found, it appends a numeric identifier to the end of the * class name to distinguish it from another class with a name that differes only by case. i.e. a.smali and a_2.smali */ public class ClassFileNameHandler { private PackageNameEntry top; private String fileExtension; private boolean modifyWindowsReservedFilenames; public ClassFileNameHandler(File path, String fileExtension) { this.top = new PackageNameEntry(path); this.fileExtension = fileExtension; this.modifyWindowsReservedFilenames = testForWindowsReservedFileNames(path); } public File getUniqueFilenameForClass(String className) { //class names should be passed in the normal dalvik style, with a leading L, a trailing ;, and using //'/' as a separator. if (className.charAt(0) != 'L' || className.charAt(className.length()-1) != ';') { throw new RuntimeException("Not a valid dalvik class name"); } int packageElementCount = 1; for (int i=1; i<className.length()-1; i++) { if (className.charAt(i) == '/') { packageElementCount++; } } String packageElement; String[] packageElements = new String[packageElementCount]; int elementIndex = 0; int elementStart = 1; for (int i=1; i<className.length()-1; i++) { if (className.charAt(i) == '/') { //if the first char after the initial L is a '/', or if there are //two consecutive '/' if (i-elementStart==0) { throw new RuntimeException("Not a valid dalvik class name"); } packageElement = className.substring(elementStart, i); if (modifyWindowsReservedFilenames && isReservedFileName(packageElement)) { packageElement += "#"; } packageElements[elementIndex++] = packageElement; elementStart = ++i; } } //at this point, we have added all the package elements to packageElements, but still need to add //the final class name. elementStart should point to the beginning of the class name //this will be true if the class ends in a '/', i.e. Lsome/package/className/; if (elementStart >= className.length()-1) { throw new RuntimeException("Not a valid dalvik class name"); } packageElement = className.substring(elementStart, className.length()-1); if (modifyWindowsReservedFilenames && isReservedFileName(packageElement)) { packageElement += "#"; } packageElements[elementIndex] = packageElement; return top.addUniqueChild(packageElements, 0); } private static boolean testForWindowsReservedFileNames(File path) { File f = new File(path, "aux.smali"); if (f.exists()) { return false; } try { FileWriter writer = new FileWriter(f); // writer.write("test"); writer.flush(); writer.close(); f.delete(); //doesn't throw IOException return false; } catch (IOException ex) { //if an exception occured, it's likely that we're on a windows system. return true; } } private static Pattern reservedFileNameRegex = Pattern.compile("^CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]$", Pattern.CASE_INSENSITIVE); private static boolean isReservedFileName(String className) { return reservedFileNameRegex.matcher(className).matches(); } private abstract class FileSystemEntry { public final File file; public FileSystemEntry(File file) { this.file = file; } public abstract File addUniqueChild(String[] pathElements, int pathElementsIndex); public FileSystemEntry makeVirtual(File parent) { return new VirtualGroupEntry(this, parent); } } private class PackageNameEntry extends FileSystemEntry { //this contains the FileSystemEntries for all of this package's children //the associated keys are all lowercase private RadixTree<FileSystemEntry> children = new RadixTreeImpl<FileSystemEntry>(); public PackageNameEntry(File parent, String name) { super(new File(parent, name)); } public PackageNameEntry(File path) { super(path); } @Override public File addUniqueChild(String[] pathElements, int pathElementsIndex) { String elementName; String elementNameLower; if (pathElementsIndex == pathElements.length - 1) { elementName = pathElements[pathElementsIndex]; elementName += fileExtension; } else { elementName = pathElements[pathElementsIndex]; } elementNameLower = elementName.toLowerCase(); FileSystemEntry existingEntry = children.find(elementNameLower); if (existingEntry != null) { FileSystemEntry virtualEntry = existingEntry; //if there is already another entry with the same name but different case, we need to //add a virtual group, and then add the existing entry and the new entry to that group if (!(existingEntry instanceof VirtualGroupEntry)) { if (existingEntry.file.getName().equals(elementName)) { if (pathElementsIndex == pathElements.length - 1) { return existingEntry.file; } else { return existingEntry.addUniqueChild(pathElements, pathElementsIndex + 1); } } else { virtualEntry = existingEntry.makeVirtual(file); children.replace(elementNameLower, virtualEntry); } } return virtualEntry.addUniqueChild(pathElements, pathElementsIndex); } if (pathElementsIndex == pathElements.length - 1) { ClassNameEntry classNameEntry = new ClassNameEntry(file, elementName); children.insert(elementNameLower, classNameEntry); return classNameEntry.file; } else { PackageNameEntry packageNameEntry = new PackageNameEntry(file, elementName); children.insert(elementNameLower, packageNameEntry); return packageNameEntry.addUniqueChild(pathElements, pathElementsIndex + 1); } } } /** * A virtual group that groups together file system entries with the same name, differing only in case */ private class VirtualGroupEntry extends FileSystemEntry { //this contains the FileSystemEntries for all of the files/directories in this group //the key is the unmodified name of the entry, before it is modified to be made unique (if needed). private RadixTree<FileSystemEntry> groupEntries = new RadixTreeImpl<FileSystemEntry>(); //whether the containing directory is case sensitive or not. //-1 = unset //0 = false; //1 = true; private int isCaseSensitive = -1; public VirtualGroupEntry(FileSystemEntry firstChild, File parent) { super(parent); //use the name of the first child in the group as-is groupEntries.insert(firstChild.file.getName(), firstChild); } @Override public File addUniqueChild(String[] pathElements, int pathElementsIndex) { String elementName = pathElements[pathElementsIndex]; if (pathElementsIndex == pathElements.length - 1) { elementName = elementName + fileExtension; } FileSystemEntry existingEntry = groupEntries.find(elementName); if (existingEntry != null) { if (pathElementsIndex == pathElements.length - 1) { return existingEntry.file; } else { return existingEntry.addUniqueChild(pathElements, pathElementsIndex+1); } } if (pathElementsIndex == pathElements.length - 1) { String fileName; if (!isCaseSensitive()) { fileName = pathElements[pathElementsIndex] + "." + (groupEntries.getSize()+1) + fileExtension; } else { fileName = elementName; } ClassNameEntry classNameEntry = new ClassNameEntry(file, fileName); groupEntries.insert(elementName, classNameEntry); return classNameEntry.file; } else { String fileName; if (!isCaseSensitive()) { fileName = pathElements[pathElementsIndex] + "." + (groupEntries.getSize()+1); } else { fileName = elementName; } PackageNameEntry packageNameEntry = new PackageNameEntry(file, fileName); groupEntries.insert(elementName, packageNameEntry); return packageNameEntry.addUniqueChild(pathElements, pathElementsIndex + 1); } } private boolean isCaseSensitive() { if (isCaseSensitive != -1) { return isCaseSensitive == 1; } File path = file; if (path.exists() && path.isFile()) { path = path.getParentFile(); } if ((!file.exists() && !file.mkdirs())) { return false; } try { boolean result = testCaseSensitivity(path); isCaseSensitive = result?1:0; return result; } catch (IOException ex) { return false; } } private boolean testCaseSensitivity(File path) throws IOException { int num = 1; File f, f2; do { f = new File(path, "test." + num); f2 = new File(path, "TEST." + num++); } while(f.exists() || f2.exists()); try { try { FileWriter writer = new FileWriter(f); writer.write("test"); writer.flush(); writer.close(); } catch (IOException ex) { try {f.delete();} catch (Exception ex2) {} throw ex; } if (f2.exists()) { return false; } if (f2.createNewFile()) { return true; } //the above 2 tests should catch almost all cases. But maybe there was a failure while creating f2 //that isn't related to case sensitivity. Let's see if we can open the file we just created using //f2 try { CharBuffer buf = CharBuffer.allocate(32); FileReader reader = new FileReader(f2); while (reader.read(buf) != -1 && buf.length() < 4); if (buf.length() == 4 && buf.toString().equals("test")) { return false; } else { //we probably shouldn't get here. If the filesystem was case-sensetive, creating a new //FileReader should have thrown a FileNotFoundException. Otherwise, we should have opened //the file and read in the string "test". It's remotely possible that someone else modified //the file after we created it. Let's be safe and return false here as well assert(false); return false; } } catch (FileNotFoundException ex) { return true; } } finally { try { f.delete(); } catch (Exception ex) {} try { f2.delete(); } catch (Exception ex) {} } } @Override public FileSystemEntry makeVirtual(File parent) { return this; } } private class ClassNameEntry extends FileSystemEntry { public ClassNameEntry(File parent, String name) { super(new File(parent, name)); } @Override public File addUniqueChild(String[] pathElements, int pathElementsIndex) { assert false; return file; } } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/org/jf/util/ClassFileNameHandler.java
Java
asf20
14,610
package ds.tree; /** * A simple standard implementation for a {@link visitor}. * * @author Dennis Heidsiek * @param <T,R> */ public abstract class VisitorImpl<T, R> implements Visitor<T, R> { protected R result; public VisitorImpl() { this.result = null; } public VisitorImpl(R initialValue) { this.result = initialValue; } public R getResult() { return result; } abstract public void visit(String key, RadixTreeNode<T> parent, RadixTreeNode<T> node); }
zztobat-apktool
brut.apktool.smali/util/src/main/java/ds/tree/VisitorImpl.java
Java
asf20
521
/* The MIT License Copyright (c) 2008 Tahseen Ur Rehman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ds.tree; import java.util.ArrayList; import java.util.List; /** * Represents a node of a Radix tree {@link RadixTreeImpl} * * @author Tahseen Ur Rehman * @email tahseen.ur.rehman {at.spam.me.not} gmail.com * @param <T> */ class RadixTreeNode<T> { private String key; private List<RadixTreeNode<T>> childern; private boolean real; private T value; /** * intailize the fields with default values to avoid null reference checks * all over the places */ public RadixTreeNode() { key = ""; childern = new ArrayList<RadixTreeNode<T>>(); real = false; } public T getValue() { return value; } public void setValue(T data) { this.value = data; } public String getKey() { return key; } public void setKey(String value) { this.key = value; } public boolean isReal() { return real; } public void setReal(boolean datanode) { this.real = datanode; } public List<RadixTreeNode<T>> getChildern() { return childern; } public void setChildern(List<RadixTreeNode<T>> childern) { this.childern = childern; } public int getNumberOfMatchingCharacters(String key) { int numberOfMatchingCharacters = 0; while (numberOfMatchingCharacters < key.length() && numberOfMatchingCharacters < this.getKey().length()) { if (key.charAt(numberOfMatchingCharacters) != this.getKey().charAt(numberOfMatchingCharacters)) { break; } numberOfMatchingCharacters++; } return numberOfMatchingCharacters; } @Override public String toString() { return key; } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/ds/tree/RadixTreeNode.java
Java
asf20
2,837
/* The MIT License Copyright (c) 2008 Tahseen Ur Rehman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ds.tree; import java.util.ArrayList; /** * This interface represent the operation of a radix tree. A radix tree, * Patricia trie/tree, or crit bit tree is a specialized set data structure * based on the trie that is used to store a set of strings. In contrast with a * regular trie, the edges of a Patricia trie are labelled with sequences of * characters rather than with single characters. These can be strings of * characters, bit strings such as integers or IP addresses, or generally * arbitrary sequences of objects in lexicographical order. Sometimes the names * radix tree and crit bit tree are only applied to trees storing integers and * Patricia trie is retained for more general inputs, but the structure works * the same way in all cases. * * @author Tahseen Ur Rehman * email: tahseen.ur.rehman {at.spam.me.not} gmail.com */ public interface RadixTree<T> { /** * Insert a new string key and its value to the tree. * * @param key * The string key of the object * @param value * The value that need to be stored corresponding to the given * key. * @throws DuplicateKeyException */ public void insert(String key, T value); /** * Delete a key and its associated value from the tree. * @param key The key of the node that need to be deleted * @return */ public boolean delete(String key); /** * Find a value based on its corresponding key. * * @param key The key for which to search the tree. * @return The value corresponding to the key. null if iot can not find the key */ public T find(String key); /** * Find an existing entry and replace it's value. If no existing entry, do nothing * * @param key The key for which to search the tree. * @param value The value to set for the entry * @return true if an entry was found for the given key, false if not found */ public boolean replace(String key, final T value); /** * Check if the tree contains any entry corresponding to the given key. * * @param key The key that needto be searched in the tree. * @return retun true if the key is present in the tree otherwise false */ public boolean contains(String key); /** * Search for all the keys that start with given prefix. limiting the results based on the supplied limit. * * @param prefix The prefix for which keys need to be search * @param recordLimit The limit for the results * @return The list of values those key start with the given prefix */ public ArrayList<T> searchPrefix(String prefix, int recordLimit); /** * Return the size of the Radix tree * @return the size of the tree */ public long getSize(); /** * Complete the a prefix to the point where ambiguity starts. * * Example: * If a tree contain "blah1", "blah2" * complete("b") -> return "blah" * * @param prefix The prefix we want to complete * @return The unambiguous completion of the string. */ public String complete(String prefix); }
zztobat-apktool
brut.apktool.smali/util/src/main/java/ds/tree/RadixTree.java
Java
asf20
4,267
/* The MIT License Copyright (c) 2008 Tahseen Ur Rehman Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ds.tree; /** * excepion thrown if a duplicate key is inserted in a {@link RadixTree} * * @author Tahseen Ur Rehman * email: tahseen.ur.rehman {at.spam.me.not} gmail.com */ public class DuplicateKeyException extends RuntimeException { private static final long serialVersionUID = 3141795907493885706L; public DuplicateKeyException(String msg) { super(msg); } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/ds/tree/DuplicateKeyException.java
Java
asf20
1,508
/* The MIT License Copyright (c) 2008 Tahseen Ur Rehman, Javid Jamae http://code.google.com/p/radixtree/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ds.tree; import java.util.ArrayList; import java.util.Formattable; import java.util.Formatter; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * Implementation for Radix tree {@link RadixTree} * * @author Tahseen Ur Rehman (tahseen.ur.rehman {at.spam.me.not} gmail.com) * @author Javid Jamae * @author Dennis Heidsiek */ public class RadixTreeImpl<T> implements RadixTree<T>, Formattable { protected RadixTreeNode<T> root; protected long size; /** * Create a Radix Tree with only the default node root. */ public RadixTreeImpl() { root = new RadixTreeNode<T>(); root.setKey(""); size = 0; } public T find(String key) { Visitor<T,T> visitor = new VisitorImpl<T,T>() { public void visit(String key, RadixTreeNode<T> parent, RadixTreeNode<T> node) { if (node.isReal()) result = node.getValue(); } }; visit(key, visitor); return visitor.getResult(); } public boolean replace(String key, final T value) { Visitor<T,T> visitor = new VisitorImpl<T,T>() { public void visit(String key, RadixTreeNode<T> parent, RadixTreeNode<T> node) { if (node.isReal()) { node.setValue(value); result = value; } else { result = null; } } }; visit(key, visitor); return visitor.getResult() != null; } public boolean delete(String key) { Visitor<T, Boolean> visitor = new VisitorImpl<T, Boolean>(Boolean.FALSE) { public void visit(String key, RadixTreeNode<T> parent, RadixTreeNode<T> node) { result = node.isReal(); // if it is a real node if (result) { // If there no children of the node we need to // delete it from the its parent children list if (node.getChildern().size() == 0) { Iterator<RadixTreeNode<T>> it = parent.getChildern() .iterator(); while (it.hasNext()) { if (it.next().getKey().equals(node.getKey())) { it.remove(); break; } } // if parent is not real node and has only one child // then they need to be merged. if (parent.getChildern().size() == 1 && parent.isReal() == false) { mergeNodes(parent, parent.getChildern().get(0)); } } else if (node.getChildern().size() == 1) { // we need to merge the only child of this node with // itself mergeNodes(node, node.getChildern().get(0)); } else { // we jus need to mark the node as non real. node.setReal(false); } } } /** * Merge a child into its parent node. Operation only valid if it is * only child of the parent node and parent node is not a real node. * * @param parent * The parent Node * @param child * The child Node */ private void mergeNodes(RadixTreeNode<T> parent, RadixTreeNode<T> child) { parent.setKey(parent.getKey() + child.getKey()); parent.setReal(child.isReal()); parent.setValue(child.getValue()); parent.setChildern(child.getChildern()); } }; visit(key, visitor); if(visitor.getResult()) { size--; } return visitor.getResult().booleanValue(); } /* * (non-Javadoc) * @see ds.tree.RadixTree#insert(java.lang.String, java.lang.Object) */ public void insert(String key, T value) throws DuplicateKeyException { try { insert(key, root, value); } catch (DuplicateKeyException e) { // re-throw the exception with 'key' in the message throw new DuplicateKeyException("Duplicate key: '" + key + "'"); } size++; } /** * Recursively insert the key in the radix tree. * * @param key The key to be inserted * @param node The current node * @param value The value associated with the key * @throws DuplicateKeyException If the key already exists in the database. */ private void insert(String key, RadixTreeNode<T> node, T value) throws DuplicateKeyException { int numberOfMatchingCharacters = node.getNumberOfMatchingCharacters(key); // we are either at the root node // or we need to go down the tree if (node.getKey().equals("") == true || numberOfMatchingCharacters == 0 || (numberOfMatchingCharacters < key.length() && numberOfMatchingCharacters >= node.getKey().length())) { boolean flag = false; String newText = key.substring(numberOfMatchingCharacters, key.length()); for (RadixTreeNode<T> child : node.getChildern()) { if (child.getKey().startsWith(newText.charAt(0) + "")) { flag = true; insert(newText, child, value); break; } } // just add the node as the child of the current node if (flag == false) { RadixTreeNode<T> n = new RadixTreeNode<T>(); n.setKey(newText); n.setReal(true); n.setValue(value); node.getChildern().add(n); } } // there is a exact match just make the current node as data node else if (numberOfMatchingCharacters == key.length() && numberOfMatchingCharacters == node.getKey().length()) { if (node.isReal() == true) { throw new DuplicateKeyException("Duplicate key"); } node.setReal(true); node.setValue(value); } // This node need to be split as the key to be inserted // is a prefix of the current node key else if (numberOfMatchingCharacters > 0 && numberOfMatchingCharacters < node.getKey().length()) { RadixTreeNode<T> n1 = new RadixTreeNode<T>(); n1.setKey(node.getKey().substring(numberOfMatchingCharacters, node.getKey().length())); n1.setReal(node.isReal()); n1.setValue(node.getValue()); n1.setChildern(node.getChildern()); node.setKey(key.substring(0, numberOfMatchingCharacters)); node.setReal(false); node.setChildern(new ArrayList<RadixTreeNode<T>>()); node.getChildern().add(n1); if(numberOfMatchingCharacters < key.length()) { RadixTreeNode<T> n2 = new RadixTreeNode<T>(); n2.setKey(key.substring(numberOfMatchingCharacters, key.length())); n2.setReal(true); n2.setValue(value); node.getChildern().add(n2); } else { node.setValue(value); node.setReal(true); } } // this key need to be added as the child of the current node else { RadixTreeNode<T> n = new RadixTreeNode<T>(); n.setKey(node.getKey().substring(numberOfMatchingCharacters, node.getKey().length())); n.setChildern(node.getChildern()); n.setReal(node.isReal()); n.setValue(node.getValue()); node.setKey(key); node.setReal(true); node.setValue(value); node.getChildern().add(n); } } public ArrayList<T> searchPrefix(String key, int recordLimit) { ArrayList<T> keys = new ArrayList<T>(); RadixTreeNode<T> node = searchPefix(key, root); if (node != null) { if (node.isReal()) { keys.add(node.getValue()); } getNodes(node, keys, recordLimit); } return keys; } private void getNodes(RadixTreeNode<T> parent, ArrayList<T> keys, int limit) { Queue<RadixTreeNode<T>> queue = new LinkedList<RadixTreeNode<T>>(); queue.addAll(parent.getChildern()); while (!queue.isEmpty()) { RadixTreeNode<T> node = queue.remove(); if (node.isReal() == true) { keys.add(node.getValue()); } if (keys.size() == limit) { break; } queue.addAll(node.getChildern()); } } private RadixTreeNode<T> searchPefix(String key, RadixTreeNode<T> node) { RadixTreeNode<T> result = null; int numberOfMatchingCharacters = node.getNumberOfMatchingCharacters(key); if (numberOfMatchingCharacters == key.length() && numberOfMatchingCharacters <= node.getKey().length()) { result = node; } else if (node.getKey().equals("") == true || (numberOfMatchingCharacters < key.length() && numberOfMatchingCharacters >= node.getKey().length())) { String newText = key.substring(numberOfMatchingCharacters, key.length()); for (RadixTreeNode<T> child : node.getChildern()) { if (child.getKey().startsWith(newText.charAt(0) + "")) { result = searchPefix(newText, child); break; } } } return result; } public boolean contains(String key) { Visitor<T, Boolean> visitor = new VisitorImpl<T,Boolean>(Boolean.FALSE) { public void visit(String key, RadixTreeNode<T> parent, RadixTreeNode<T> node) { result = node.isReal(); } }; visit(key, visitor); return visitor.getResult().booleanValue(); } /** * visit the node those key matches the given key * @param key The key that need to be visited * @param visitor The visitor object */ public <R> void visit(String key, Visitor<T, R> visitor) { if (root != null) { visit(key, visitor, null, root); } } /** * recursively visit the tree based on the supplied "key". calls the Visitor * for the node those key matches the given prefix * * @param prefix * The key o prefix to search in the tree * @param visitor * The Visitor that will be called if a node with "key" as its * key is found * @param node * The Node from where onward to search */ private <R> void visit(String prefix, Visitor<T, R> visitor, RadixTreeNode<T> parent, RadixTreeNode<T> node) { int numberOfMatchingCharacters = node.getNumberOfMatchingCharacters(prefix); // if the node key and prefix match, we found a match! if (numberOfMatchingCharacters == prefix.length() && numberOfMatchingCharacters == node.getKey().length()) { visitor.visit(prefix, parent, node); } else if (node.getKey().equals("") == true // either we are at the // root || (numberOfMatchingCharacters < prefix.length() && numberOfMatchingCharacters >= node.getKey().length())) { // OR we need to // traverse the childern String newText = prefix.substring(numberOfMatchingCharacters, prefix.length()); for (RadixTreeNode<T> child : node.getChildern()) { // recursively search the child nodes if (child.getKey().startsWith(newText.charAt(0) + "")) { visit(newText, visitor, node, child); break; } } } } public long getSize() { return size; } /** * Display the Trie on console. * * WARNING! Do not use this for a large Trie, it's for testing purpose only. * @see formatTo */ @Deprecated public void display() { formatNodeTo(new Formatter(System.out), 0, root); } @Deprecated private void display(int level, RadixTreeNode<T> node) { formatNodeTo(new Formatter(System.out), level, node); } /** * WARNING! Do not use this for a large Trie, it's for testing purpose only. */ private void formatNodeTo(Formatter f, int level, RadixTreeNode<T> node) { for (int i = 0; i < level; i++) { f.format(" "); } f.format("|"); for (int i = 0; i < level; i++) { f.format("-"); } if (node.isReal() == true) f.format("%s[%s]*%n", node.getKey(), node.getValue()); else f.format("%s%n", node.getKey()); for (RadixTreeNode<T> child : node.getChildern()) { formatNodeTo(f, level + 1, child); } } /** * Writes a textual representation of this tree to the given formatter. * * Currently, all options are simply ignored. * * WARNING! Do not use this for a large Trie, it's for testing purpose only. */ public void formatTo(Formatter formatter, int flags, int width, int precision) { formatNodeTo(formatter, 0, root); } /** * Complete the a prefix to the point where ambiguity starts. * * Example: * If a tree contain "blah1", "blah2" * complete("b") -> return "blah" * * @param prefix The prefix we want to complete * @return The unambiguous completion of the string. */ public String complete(String prefix) { return complete(prefix, root, ""); } private String complete(String key, RadixTreeNode<T> node, String base) { int i = 0; int keylen = key.length(); int nodelen = node.getKey().length(); while (i < keylen && i < nodelen) { if (key.charAt(i) != node.getKey().charAt(i)) { break; } i++; } if (i == keylen && i <= nodelen) { return base + node.getKey(); } else if (nodelen == 0 || (i < keylen && i >= nodelen)) { String beginning = key.substring(0, i); String ending = key.substring(i, keylen); for (RadixTreeNode<T> child : node.getChildern()) { if (child.getKey().startsWith(ending.charAt(0) + "")) { return complete(ending, child, base + beginning); } } } return ""; } }
zztobat-apktool
brut.apktool.smali/util/src/main/java/ds/tree/RadixTreeImpl.java
Java
asf20
16,049
/* The MIT License Copyright (c) 2008 Tahseen Ur Rehman, Javid Jamae http://code.google.com/p/radixtree/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package ds.tree; /** * The visitor interface that is used by {@link RadixTreeImpl} for perfroming * task on a searched node. * * @author Tahseen Ur Rehman (tahseen.ur.rehman {at.spam.me.not} gmail.com) * @author Javid Jamae * @author Dennis Heidsiek * @param <T,R> */ public interface Visitor<T, R> { /** * This method gets called by {@link RadixTreeImpl#visit(String, Visitor) visit} * when it finds a node matching the key given to it. * * @param key The key that matched the node * @param parent The parent of the node being visited * @param node The node that is being visited */ public void visit(String key, RadixTreeNode<T> parent, RadixTreeNode<T> node); /** * The visitor can store any type of result object, depending on the context of * what it is being used for. * * @return The result captured by the visitor. */ public R getResult(); }
zztobat-apktool
brut.apktool.smali/util/src/main/java/ds/tree/Visitor.java
Java
asf20
2,071
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib; import org.jf.dexlib.Util.Input; import java.io.UnsupportedEncodingException; public class OdexDependencies { public final int modificationTime; public final int crc; public final int dalvikBuild; private final String[] dependencies; private final byte[][] dependencyChecksums; public OdexDependencies (Input in) { modificationTime = in.readInt(); crc = in.readInt(); dalvikBuild = in.readInt(); int dependencyCount = in.readInt(); dependencies = new String[dependencyCount]; dependencyChecksums = new byte[dependencyCount][]; for (int i=0; i<dependencyCount; i++) { int stringLength = in.readInt(); try { dependencies[i] = new String(in.readBytes(stringLength), 0, stringLength-1, "US-ASCII"); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } dependencyChecksums[i] = in.readBytes(20); } } public int getDependencyCount() { return dependencies.length; } public String getDependency(int index) { return dependencies[index]; } public byte[] getDependencyChecksum(int index) { return dependencyChecksums[index].clone(); } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/OdexDependencies.java
Java
asf20
2,807
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface RegisterRangeInstruction extends InvokeInstruction { int getStartRegister(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/RegisterRangeInstruction.java
Java
asf20
1,631
/* * [The "BSD licence"] * Copyright (c) 2011 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface InvokeInstruction { int getRegCount(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/InvokeInstruction.java
Java
asf20
1,580
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface TwoRegisterInstruction extends SingleRegisterInstruction { int getRegisterA(); int getRegisterB(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/TwoRegisterInstruction.java
Java
asf20
1,658
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.Code.*; import org.jf.dexlib.Item; import org.jf.dexlib.ItemType; import org.jf.dexlib.MethodIdItem; import org.jf.dexlib.Util.ExceptionWithContext; import java.util.*; public class AnalyzedInstruction implements Comparable<AnalyzedInstruction> { /** * The actual instruction */ protected Instruction instruction; /** * The index of the instruction, where the first instruction in the method is at index 0, and so on */ protected final int instructionIndex; /** * Instructions that can pass on execution to this one during normal execution */ protected final TreeSet<AnalyzedInstruction> predecessors = new TreeSet<AnalyzedInstruction>(); /** * Instructions that can execution could pass on to next during normal execution */ protected final LinkedList<AnalyzedInstruction> successors = new LinkedList<AnalyzedInstruction>(); /** * This contains the register types *before* the instruction has executed */ protected final RegisterType[] preRegisterMap; /** * This contains the register types *after* the instruction has executed */ protected final RegisterType[] postRegisterMap; /** * When deodexing, we might need to deodex this instruction multiple times, when we merge in new register * information. When this happens, we need to restore the original (odexed) instruction, so we can deodex it again */ protected final Instruction originalInstruction; /** * An analyzed instruction's "deadness" is set during analysis (i.e. MethodAnalyzer.analyzer()). A dead instruction * is one that the analyzer never reaches. This occurs either with natural "dead code" - code that simply has no * code path that can ever reach it, or code that follows an odexed instruction that can't be deodexed. */ protected boolean dead = false; public AnalyzedInstruction(Instruction instruction, int instructionIndex, int registerCount) { this.instruction = instruction; this.originalInstruction = instruction; this.instructionIndex = instructionIndex; this.postRegisterMap = new RegisterType[registerCount]; this.preRegisterMap = new RegisterType[registerCount]; RegisterType unknown = RegisterType.getRegisterType(RegisterType.Category.Unknown, null); for (int i=0; i<registerCount; i++) { preRegisterMap[i] = unknown; postRegisterMap[i] = unknown; } } public int getInstructionIndex() { return instructionIndex; } public int getPredecessorCount() { return predecessors.size(); } public SortedSet<AnalyzedInstruction> getPredecessors() { return Collections.unmodifiableSortedSet(predecessors); } protected boolean addPredecessor(AnalyzedInstruction predecessor) { return predecessors.add(predecessor); } protected void addSuccessor(AnalyzedInstruction successor) { successors.add(successor); } protected void setDeodexedInstruction(Instruction instruction) { assert originalInstruction.opcode.odexOnly(); this.instruction = instruction; } protected void restoreOdexedInstruction() { assert originalInstruction.opcode.odexOnly(); instruction = originalInstruction; } public int getSuccessorCount() { return successors.size(); } public List<AnalyzedInstruction> getSuccesors() { return Collections.unmodifiableList(successors); } public Instruction getInstruction() { return instruction; } public Instruction getOriginalInstruction() { return originalInstruction; } public boolean isDead() { return dead; } /** * Is this instruction a "beginning instruction". A beginning instruction is defined to be an instruction * that can be the first successfully executed instruction in the method. The first instruction is always a * beginning instruction. If the first instruction can throw an exception, and is covered by a try block, then * the first instruction of any exception handler for that try block is also a beginning instruction. And likewise, * if any of those instructions can throw an exception and are covered by try blocks, the first instruction of the * corresponding exception handler is a beginning instruction, etc. * * To determine this, we simply check if the first predecessor is the fake "StartOfMethod" instruction, which has * an instruction index of -1. * @return a boolean value indicating whether this instruction is a beginning instruction */ public boolean isBeginningInstruction() { //if this instruction has no predecessors, it is either the fake "StartOfMethod" instruction or it is an //unreachable instruction. if (predecessors.size() == 0) { return false; } if (predecessors.first().instructionIndex == -1) { return true; } return false; } /* * Merges the given register type into the specified pre-instruction register, and also sets the post-instruction * register type accordingly if it isn't a destination register for this instruction * @param registerNumber Which register to set * @param registerType The register type * @returns true If the post-instruction register type was changed. This might be false if either the specified * register is a destination register for this instruction, or if the pre-instruction register type didn't change * after merging in the given register type */ protected boolean mergeRegister(int registerNumber, RegisterType registerType, BitSet verifiedInstructions) { assert registerNumber >= 0 && registerNumber < postRegisterMap.length; assert registerType != null; RegisterType oldRegisterType = preRegisterMap[registerNumber]; RegisterType mergedRegisterType = oldRegisterType.merge(registerType); if (mergedRegisterType == oldRegisterType) { return false; } preRegisterMap[registerNumber] = mergedRegisterType; verifiedInstructions.clear(instructionIndex); if (!setsRegister(registerNumber)) { postRegisterMap[registerNumber] = mergedRegisterType; return true; } return false; } /** * Iterates over the predecessors of this instruction, and merges all the post-instruction register types for the * given register. Any dead, unreachable, or odexed predecessor is ignored * @param registerNumber the register number * @return The register type resulting from merging the post-instruction register types from all predecessors */ protected RegisterType mergePreRegisterTypeFromPredecessors(int registerNumber) { RegisterType mergedRegisterType = null; for (AnalyzedInstruction predecessor: predecessors) { RegisterType predecessorRegisterType = predecessor.postRegisterMap[registerNumber]; assert predecessorRegisterType != null; mergedRegisterType = predecessorRegisterType.merge(mergedRegisterType); } return mergedRegisterType; } /* * Sets the "post-instruction" register type as indicated. * @param registerNumber Which register to set * @param registerType The "post-instruction" register type * @returns true if the given register type is different than the existing post-instruction register type */ protected boolean setPostRegisterType(int registerNumber, RegisterType registerType) { assert registerNumber >= 0 && registerNumber < postRegisterMap.length; assert registerType != null; RegisterType oldRegisterType = postRegisterMap[registerNumber]; if (oldRegisterType == registerType) { return false; } postRegisterMap[registerNumber] = registerType; return true; } protected boolean isInvokeInit() { if (instruction == null || !instruction.opcode.canInitializeReference()) { return false; } //TODO: check access flags instead of name? InstructionWithReference instruction = (InstructionWithReference)this.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_METHOD_ID_ITEM; MethodIdItem method = (MethodIdItem)item; if (!method.getMethodName().getStringValue().equals("<init>")) { return false; } return true; } public boolean setsRegister() { return instruction.opcode.setsRegister(); } public boolean setsWideRegister() { return instruction.opcode.setsWideRegister(); } public boolean setsRegister(int registerNumber) { //When constructing a new object, the register type will be an uninitialized reference after the new-instance //instruction, but becomes an initialized reference once the <init> method is called. So even though invoke //instructions don't normally change any registers, calling an <init> method will change the type of its //object register. If the uninitialized reference has been copied to other registers, they will be initialized //as well, so we need to check for that too if (isInvokeInit()) { int destinationRegister; if (instruction instanceof FiveRegisterInstruction) { destinationRegister = ((FiveRegisterInstruction)instruction).getRegisterD(); } else { assert instruction instanceof RegisterRangeInstruction; RegisterRangeInstruction rangeInstruction = (RegisterRangeInstruction)instruction; assert rangeInstruction.getRegCount() > 0; destinationRegister = rangeInstruction.getStartRegister(); } if (registerNumber == destinationRegister) { return true; } RegisterType preInstructionDestRegisterType = getPreInstructionRegisterType(registerNumber); if (preInstructionDestRegisterType.category != RegisterType.Category.UninitRef && preInstructionDestRegisterType.category != RegisterType.Category.UninitThis) { return false; } //check if the uninit ref has been copied to another register if (getPreInstructionRegisterType(registerNumber) == preInstructionDestRegisterType) { return true; } return false; } if (!setsRegister()) { return false; } int destinationRegister = getDestinationRegister(); if (registerNumber == destinationRegister) { return true; } if (setsWideRegister() && registerNumber == (destinationRegister + 1)) { return true; } return false; } public int getDestinationRegister() { if (!this.instruction.opcode.setsRegister()) { throw new ExceptionWithContext("Cannot call getDestinationRegister() for an instruction that doesn't " + "store a value"); } return ((SingleRegisterInstruction)instruction).getRegisterA(); } public int getRegisterCount() { return postRegisterMap.length; } public RegisterType getPostInstructionRegisterType(int registerNumber) { return postRegisterMap[registerNumber]; } public RegisterType getPreInstructionRegisterType(int registerNumber) { return preRegisterMap[registerNumber]; } public int compareTo(AnalyzedInstruction analyzedInstruction) { //TODO: out of curiosity, check the disassembly of this to see if it retrieves the value of analyzedInstruction.instructionIndex for every access. It should, because the field is final. What about if we set the field to non-final? if (instructionIndex < analyzedInstruction.instructionIndex) { return -1; } else if (instructionIndex == analyzedInstruction.instructionIndex) { return 0; } else { return 1; } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/AnalyzedInstruction.java
Java
asf20
13,876
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.*; import org.jf.dexlib.Util.AccessFlags; import org.jf.dexlib.Util.ExceptionWithContext; import org.jf.dexlib.Util.SparseArray; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.jf.dexlib.ClassDataItem.EncodedField; import static org.jf.dexlib.ClassDataItem.EncodedMethod; public class ClassPath { private static ClassPath theClassPath = null; /** * The current version of dalvik in master(AOSP) has a slight change to the way the * virtual tables are computed. This should be set to true to use the new logic. * TODO: set this based on api level, once it's present in a released version of Android */ private boolean checkPackagePrivateAccess; private final HashMap<String, ClassDef> classDefs; protected ClassDef javaLangObjectClassDef; //cached ClassDef for Ljava/lang/Object; // Contains the classes that we haven't loaded yet private HashMap<String, UnresolvedClassInfo> unloadedClasses; private static final Pattern dalvikCacheOdexPattern = Pattern.compile("@([^@]+)@classes.dex$"); /** * Initialize the class path using the dependencies from an odex file * @param classPathDirs The directories to search for boot class path files * @param extraBootClassPathEntries any extra entries that should be added after the entries that are read * from the odex file * @param dexFilePath The path of the dex file (used for error reporting purposes only) * @param dexFile The DexFile to load - it must represents an odex file */ public static void InitializeClassPathFromOdex(String[] classPathDirs, String[] extraBootClassPathEntries, String dexFilePath, DexFile dexFile, boolean checkPackagePrivateAccess) { if (!dexFile.isOdex()) { throw new ExceptionWithContext("Cannot use InitialiazeClassPathFromOdex with a non-odex DexFile"); } if (theClassPath != null) { throw new ExceptionWithContext("Cannot initialize ClassPath multiple times"); } OdexDependencies odexDependencies = dexFile.getOdexDependencies(); String[] bootClassPath = new String[odexDependencies.getDependencyCount()]; for (int i=0; i<bootClassPath.length; i++) { String dependency = odexDependencies.getDependency(i); if (dependency.endsWith(".odex")) { int slashIndex = dependency.lastIndexOf("/"); if (slashIndex != -1) { dependency = dependency.substring(slashIndex+1); } } else if (dependency.endsWith("@classes.dex")) { Matcher m = dalvikCacheOdexPattern.matcher(dependency); if (!m.find()) { throw new ExceptionWithContext(String.format("Cannot parse dependency value %s", dependency)); } dependency = m.group(1); } else { throw new ExceptionWithContext(String.format("Cannot parse dependency value %s", dependency)); } bootClassPath[i] = dependency; } theClassPath = new ClassPath(); theClassPath.initClassPath(classPathDirs, bootClassPath, extraBootClassPathEntries, dexFilePath, dexFile, checkPackagePrivateAccess); } /** * Initialize the class path using the given boot class path entries * @param classPathDirs The directories to search for boot class path files * @param bootClassPath A list of the boot class path entries to search for and load * @param dexFilePath The path of the dex file (used for error reporting purposes only) * @param dexFile the DexFile to load * classes */ public static void InitializeClassPath(String[] classPathDirs, String[] bootClassPath, String[] extraBootClassPathEntries, String dexFilePath, DexFile dexFile, boolean checkPackagePrivateAccess) { if (theClassPath != null) { throw new ExceptionWithContext("Cannot initialize ClassPath multiple times"); } theClassPath = new ClassPath(); theClassPath.initClassPath(classPathDirs, bootClassPath, extraBootClassPathEntries, dexFilePath, dexFile, checkPackagePrivateAccess); } private ClassPath() { classDefs = new HashMap<String, ClassDef>(); } private void initClassPath(String[] classPathDirs, String[] bootClassPath, String[] extraBootClassPathEntries, String dexFilePath, DexFile dexFile, boolean checkPackagePrivateAccess) { this.checkPackagePrivateAccess = checkPackagePrivateAccess; unloadedClasses = new LinkedHashMap<String, UnresolvedClassInfo>(); if (bootClassPath != null) { for (String bootClassPathEntry: bootClassPath) { loadBootClassPath(classPathDirs, bootClassPathEntry); } } if (extraBootClassPathEntries != null) { for (String bootClassPathEntry: extraBootClassPathEntries) { loadBootClassPath(classPathDirs, bootClassPathEntry); } } if (dexFile != null) { loadDexFile(dexFilePath, dexFile); } javaLangObjectClassDef = getClassDef("Ljava/lang/Object;", false); for (String primitiveType: new String[]{"Z", "B", "S", "C", "I", "J", "F", "D"}) { ClassDef classDef = new PrimitiveClassDef(primitiveType); classDefs.put(primitiveType, classDef); } } private void loadBootClassPath(String[] classPathDirs, String bootClassPathEntry) { for (String classPathDir: classPathDirs) { File file = null; DexFile dexFile = null; int extIndex = bootClassPathEntry.lastIndexOf("."); String baseEntry; if (extIndex == -1) { baseEntry = bootClassPathEntry; } else { baseEntry = bootClassPathEntry.substring(0, extIndex); } for (String ext: new String[]{"", ".odex", ".jar", ".apk", ".zip"}) { if (ext.length() == 0) { file = new File(classPathDir, bootClassPathEntry); } else { file = new File(classPathDir, baseEntry + ext); } if (file.exists()) { if (!file.canRead()) { System.err.println(String.format("warning: cannot open %s for reading. Will continue " + "looking.", file.getPath())); continue; } try { dexFile = new DexFile(file, false, true); } catch (DexFile.NoClassesDexException ex) { continue; } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "Error while reading boot class path entry \"" + bootClassPathEntry + "\"."); } } } if (dexFile == null) { continue; } try { loadDexFile(file.getPath(), dexFile); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, String.format("Error while loading boot classpath entry %s", bootClassPathEntry)); } return; } throw new ExceptionWithContext(String.format("Cannot locate boot class path file %s", bootClassPathEntry)); } private void loadDexFile(String dexFilePath, DexFile dexFile) { for (ClassDefItem classDefItem: dexFile.ClassDefsSection.getItems()) { try { UnresolvedClassInfo unresolvedClassInfo = new UnresolvedClassInfo(dexFilePath, classDefItem); if (!unloadedClasses.containsKey(unresolvedClassInfo.classType)) { unloadedClasses.put(unresolvedClassInfo.classType, unresolvedClassInfo); } } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, String.format("Error while loading class %s", classDefItem.getClassType().getTypeDescriptor())); } } } /** * This method loads the given class (and any dependent classes, as needed), removing them from unloadedClasses * @param classType the class to load * @return the newly loaded ClassDef object for the given class, or null if the class cannot be found */ @Nullable private static ClassDef loadClassDef(String classType) { ClassDef classDef = null; UnresolvedClassInfo classInfo = theClassPath.unloadedClasses.get(classType); if (classInfo == null) { return null; } try { classDef = new ClassDef(classInfo); theClassPath.classDefs.put(classDef.classType, classDef); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, String.format("Error while loading class %s from file %s", classInfo.classType, classInfo.dexFilePath)); } theClassPath.unloadedClasses.remove(classType); return classDef; } @Nonnull public static ClassDef getClassDef(String classType, boolean createUnresolvedClassDef) { ClassDef classDef = theClassPath.classDefs.get(classType); if (classDef == null) { //if it's an array class, try to create it if (classType.charAt(0) == '[') { return theClassPath.createArrayClassDef(classType); } else { try { classDef = loadClassDef(classType); if (classDef == null) { throw new ExceptionWithContext( String.format("Could not find definition for class %s", classType)); } } catch (Exception ex) { RuntimeException exWithContext = ExceptionWithContext.withContext(ex, String.format("Error while loading ClassPath class %s", classType)); if (createUnresolvedClassDef) { //TODO: add warning message return theClassPath.createUnresolvedClassDef(classType); } else { throw exWithContext; } } } } return classDef; } public static ClassDef getClassDef(String classType) { return getClassDef(classType, true); } public static ClassDef getClassDef(TypeIdItem classType) { return getClassDef(classType.getTypeDescriptor()); } public static ClassDef getClassDef(TypeIdItem classType, boolean creatUnresolvedClassDef) { return getClassDef(classType.getTypeDescriptor(), creatUnresolvedClassDef); } //256 [ characters private static final String arrayPrefix = "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["; private static ClassDef getArrayClassDefByElementClassAndDimension(ClassDef classDef, int arrayDimension) { return getClassDef(arrayPrefix.substring(256 - arrayDimension) + classDef.classType); } private static ClassDef unresolvedObjectClassDef = null; public static ClassDef getUnresolvedObjectClassDef() { if (unresolvedObjectClassDef == null) { unresolvedObjectClassDef = new UnresolvedClassDef("Ljava/lang/Object;"); } return unresolvedObjectClassDef; } private ClassDef createUnresolvedClassDef(String classType) { assert classType.charAt(0) == 'L'; UnresolvedClassDef unresolvedClassDef = new UnresolvedClassDef(classType); classDefs.put(classType, unresolvedClassDef); return unresolvedClassDef; } private ClassDef createArrayClassDef(String arrayClassName) { assert arrayClassName != null; assert arrayClassName.charAt(0) == '['; ArrayClassDef arrayClassDef = new ArrayClassDef(arrayClassName); if (arrayClassDef.elementClass == null) { return null; } classDefs.put(arrayClassName, arrayClassDef); return arrayClassDef; } public static ClassDef getCommonSuperclass(ClassDef class1, ClassDef class2) { if (class1 == class2) { return class1; } if (class1 == null) { return class2; } if (class2 == null) { return class1; } //TODO: do we want to handle primitive types here? I don't think so.. (if not, add assert) if (class2.isInterface) { if (class1.implementsInterface(class2)) { return class2; } return theClassPath.javaLangObjectClassDef; } if (class1.isInterface) { if (class2.implementsInterface(class1)) { return class1; } return theClassPath.javaLangObjectClassDef; } if (class1 instanceof ArrayClassDef && class2 instanceof ArrayClassDef) { return getCommonArraySuperclass((ArrayClassDef)class1, (ArrayClassDef)class2); } //we've got two non-array reference types. Find the class depth of each, and then move up the longer one //so that both classes are at the same class depth, and then move each class up until they match //we don't strictly need to keep track of the class depth separately, but it's probably slightly faster //to do so, rather than calling getClassDepth() many times int class1Depth = class1.getClassDepth(); int class2Depth = class2.getClassDepth(); while (class1Depth > class2Depth) { class1 = class1.superclass; class1Depth--; } while (class2Depth > class1Depth) { class2 = class2.superclass; class2Depth--; } while (class1Depth > 0) { if (class1 == class2) { return class1; } class1 = class1.superclass; class1Depth--; class2 = class2.superclass; class2Depth--; } return class1; } private static ClassDef getCommonArraySuperclass(ArrayClassDef class1, ArrayClassDef class2) { assert class1 != class2; //If one of the arrays is a primitive array, then the only option is to return java.lang.Object //TODO: might it be possible to merge something like int[] and short[] into int[]? (I don't think so..) if (class1.elementClass instanceof PrimitiveClassDef || class2.elementClass instanceof PrimitiveClassDef) { return theClassPath.javaLangObjectClassDef; } //if the two arrays have the same number of dimensions, then we should return an array class with the //same number of dimensions, for the common superclass of the 2 element classes if (class1.arrayDimensions == class2.arrayDimensions) { ClassDef commonElementClass; if (class1.elementClass instanceof UnresolvedClassDef || class2.elementClass instanceof UnresolvedClassDef) { commonElementClass = ClassPath.getUnresolvedObjectClassDef(); } else { commonElementClass = getCommonSuperclass(class1.elementClass, class2.elementClass); } return getArrayClassDefByElementClassAndDimension(commonElementClass, class1.arrayDimensions); } //something like String[][][] and String[][] should be merged to Object[][] //this also holds when the element classes aren't the same (but are both reference types) int dimensions = Math.min(class1.arrayDimensions, class2.arrayDimensions); return getArrayClassDefByElementClassAndDimension(theClassPath.javaLangObjectClassDef, dimensions); } public static class ArrayClassDef extends ClassDef { private final ClassDef elementClass; private final int arrayDimensions; protected ArrayClassDef(String arrayClassType) { super(arrayClassType, ClassDef.ArrayClassDef); assert arrayClassType.charAt(0) == '['; int i=0; while (arrayClassType.charAt(i) == '[') i++; String elementClassType = arrayClassType.substring(i); if (i>256) { throw new ExceptionWithContext("Error while creating array class for element type " + elementClassType + " with " + i + " dimensions. The maximum number of dimensions is 256"); } try { elementClass = ClassPath.getClassDef(arrayClassType.substring(i)); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "Error while creating array class " + arrayClassType); } arrayDimensions = i; } /** * Returns the "base" element class of the array. * * For example, for a multi-dimensional array of strings ([[Ljava/lang/String;), this method would return * Ljava/lang/String; * @return the "base" element class of the array */ public ClassDef getBaseElementClass() { return elementClass; } /** * Returns the "immediate" element class of the array. * * For example, for a multi-dimensional array of stings with 2 dimensions ([[Ljava/lang/String;), this method * would return [Ljava/lang/String; * @return the immediate element class of the array */ public ClassDef getImmediateElementClass() { if (arrayDimensions == 1) { return elementClass; } return getArrayClassDefByElementClassAndDimension(elementClass, arrayDimensions - 1); } public int getArrayDimensions() { return arrayDimensions; } @Override public boolean extendsClass(ClassDef superclassDef) { if (!(superclassDef instanceof ArrayClassDef)) { if (superclassDef == ClassPath.theClassPath.javaLangObjectClassDef) { return true; } else if (superclassDef.isInterface) { return this.implementsInterface(superclassDef); } return false; } ArrayClassDef arraySuperclassDef = (ArrayClassDef)superclassDef; if (this.arrayDimensions == arraySuperclassDef.arrayDimensions) { ClassDef baseElementClass = arraySuperclassDef.getBaseElementClass(); if (baseElementClass.isInterface) { return true; } return baseElementClass.extendsClass(arraySuperclassDef.getBaseElementClass()); } else if (this.arrayDimensions > arraySuperclassDef.arrayDimensions) { ClassDef baseElementClass = arraySuperclassDef.getBaseElementClass(); if (baseElementClass.isInterface) { return true; } if (baseElementClass == ClassPath.theClassPath.javaLangObjectClassDef) { return true; } return false; } return false; } } public static class PrimitiveClassDef extends ClassDef { protected PrimitiveClassDef(String primitiveClassType) { super(primitiveClassType, ClassDef.PrimitiveClassDef); assert primitiveClassType.charAt(0) != 'L' && primitiveClassType.charAt(0) != '['; } } public static class UnresolvedClassDef extends ClassDef { protected UnresolvedClassDef(String unresolvedClassDef) { super(unresolvedClassDef, ClassDef.UnresolvedClassDef); assert unresolvedClassDef.charAt(0) == 'L'; } protected ValidationException unresolvedValidationException() { return new ValidationException(String.format("class %s cannot be resolved.", this.getClassType())); } public ClassDef getSuperclass() { return theClassPath.javaLangObjectClassDef; } public int getClassDepth() { throw unresolvedValidationException(); } public boolean isInterface() { throw unresolvedValidationException(); } public boolean extendsClass(ClassDef superclassDef) { if (superclassDef != theClassPath.javaLangObjectClassDef && superclassDef != this) { throw unresolvedValidationException(); } return true; } public boolean implementsInterface(ClassDef interfaceDef) { throw unresolvedValidationException(); } public boolean hasVirtualMethod(String method) { if (!super.hasVirtualMethod(method)) { throw unresolvedValidationException(); } return true; } } public static class FieldDef { public final String definingClass; public final String name; public final String type; public FieldDef(String definingClass, String name, String type) { this.definingClass = definingClass; this.name = name; this.type = type; } } public static class ClassDef implements Comparable<ClassDef> { private final String classType; private final ClassDef superclass; /** * This is a list of all of the interfaces that a class implements, either directly or indirectly. It includes * all interfaces implemented by the superclass, and all super-interfaces of any implemented interface. The * intention is to make it easier to determine whether the class implements a given interface or not. */ private final TreeSet<ClassDef> implementedInterfaces; private final boolean isInterface; private final int classDepth; // classes can only be public or package-private. Internally, any private/protected inner class is actually // package-private. private final boolean isPublic; private final VirtualMethod[] vtable; //this maps a method name of the form method(III)Ljava/lang/String; to an integer //If the value is non-negative, it is a vtable index //If it is -1, it is a non-static direct method, //If it is -2, it is a static method private final HashMap<String, Integer> methodLookup; private final SparseArray<FieldDef> instanceFields; public final static int ArrayClassDef = 0; public final static int PrimitiveClassDef = 1; public final static int UnresolvedClassDef = 2; private final static int DirectMethod = -1; private final static int StaticMethod = -2; /** * The following fields are used only during the initial loading of classes, and are set to null afterwards * TODO: free these */ //This is only the virtual methods that this class declares itself. private VirtualMethod[] virtualMethods; //this is a list of all the interfaces that the class implements directory, or any super interfaces of those //interfaces. It is generated in such a way that it is ordered in the same way as dalvik's ClassObject.iftable, private LinkedHashMap<String, ClassDef> interfaceTable; /** * This constructor is used for the ArrayClassDef, PrimitiveClassDef and UnresolvedClassDef subclasses * @param classType the class type * @param classFlavor one of ArrayClassDef, PrimitiveClassDef or UnresolvedClassDef */ protected ClassDef(String classType, int classFlavor) { if (classFlavor == ArrayClassDef) { assert classType.charAt(0) == '['; this.classType = classType; this.superclass = ClassPath.theClassPath.javaLangObjectClassDef; implementedInterfaces = new TreeSet<ClassDef>(); implementedInterfaces.add(ClassPath.getClassDef("Ljava/lang/Cloneable;")); implementedInterfaces.add(ClassPath.getClassDef("Ljava/io/Serializable;")); isInterface = false; isPublic = true; vtable = superclass.vtable; methodLookup = superclass.methodLookup; instanceFields = superclass.instanceFields; classDepth = 1; //1 off from java.lang.Object virtualMethods = null; interfaceTable = null; } else if (classFlavor == PrimitiveClassDef) { //primitive type assert classType.charAt(0) != '[' && classType.charAt(0) != 'L'; this.classType = classType; this.superclass = null; implementedInterfaces = null; isInterface = false; isPublic = true; vtable = null; methodLookup = null; instanceFields = null; classDepth = 0; //TODO: maybe use -1 to indicate not applicable? virtualMethods = null; interfaceTable = null; } else /*if (classFlavor == UnresolvedClassDef)*/ { assert classType.charAt(0) == 'L'; this.classType = classType; this.superclass = ClassPath.getClassDef("Ljava/lang/Object;"); implementedInterfaces = new TreeSet<ClassDef>(); isInterface = false; isPublic = true; vtable = superclass.vtable; methodLookup = superclass.methodLookup; instanceFields = superclass.instanceFields; classDepth = 1; //1 off from java.lang.Object virtualMethods = null; interfaceTable = null; } } protected ClassDef(UnresolvedClassInfo classInfo) { classType = classInfo.classType; isPublic = classInfo.isPublic; isInterface = classInfo.isInterface; superclass = loadSuperclass(classInfo); if (superclass == null) { classDepth = 0; } else { classDepth = superclass.classDepth + 1; } implementedInterfaces = loadAllImplementedInterfaces(classInfo); //TODO: we can probably get away with only creating the interface table for interface types interfaceTable = loadInterfaceTable(classInfo); virtualMethods = classInfo.virtualMethods; vtable = loadVtable(classInfo); int directMethodCount = 0; if (classInfo.directMethods != null) { directMethodCount = classInfo.directMethods.length; } methodLookup = new HashMap<String, Integer>((int)Math.ceil(((vtable.length + directMethodCount)/ .7f)), .75f); for (int i=0; i<vtable.length; i++) { methodLookup.put(vtable[i].method, i); } if (directMethodCount > 0) { for (int i=0; i<classInfo.directMethods.length; i++) { if (classInfo.staticMethods[i]) { methodLookup.put(classInfo.directMethods[i], StaticMethod); } else { methodLookup.put(classInfo.directMethods[i], DirectMethod); } } } instanceFields = loadFields(classInfo); } public String getClassType() { return classType; } public ClassDef getSuperclass() { return superclass; } public int getClassDepth() { return classDepth; } public boolean isInterface() { return this.isInterface; } public boolean isPublic() { return this.isPublic; } public boolean extendsClass(ClassDef superclassDef) { if (superclassDef == null) { return false; } if (this == superclassDef) { return true; } if (superclassDef instanceof UnresolvedClassDef) { throw ((UnresolvedClassDef)superclassDef).unresolvedValidationException(); } int superclassDepth = superclassDef.classDepth; ClassDef ancestor = this; while (ancestor.classDepth > superclassDepth) { ancestor = ancestor.getSuperclass(); } return ancestor == superclassDef; } /** * Returns true if this class implements the given interface. This searches the interfaces that this class * directly implements, any interface implemented by this class's superclasses, and any super-interface of * any of these interfaces. * @param interfaceDef the interface * @return true if this class implements the given interface */ public boolean implementsInterface(ClassDef interfaceDef) { assert !(interfaceDef instanceof UnresolvedClassDef); return implementedInterfaces.contains(interfaceDef); } public boolean hasVirtualMethod(String method) { Integer val = methodLookup.get(method); if (val == null || val < 0) { return false; } return true; } public int getMethodType(String method) { Integer val = methodLookup.get(method); if (val == null) { return -1; } if (val >= 0) { return DeodexUtil.Virtual; } if (val == DirectMethod) { return DeodexUtil.Direct; } if (val == StaticMethod) { return DeodexUtil.Static; } throw new RuntimeException("Unexpected method type"); } public FieldDef getInstanceField(int fieldOffset) { return this.instanceFields.get(fieldOffset, null); } public String getVirtualMethod(int vtableIndex) { if (vtableIndex < 0 || vtableIndex >= vtable.length) { return null; } return this.vtable[vtableIndex].method; } private void swap(byte[] fieldTypes, FieldDef[] fields, int position1, int position2) { byte tempType = fieldTypes[position1]; fieldTypes[position1] = fieldTypes[position2]; fieldTypes[position2] = tempType; FieldDef tempField = fields[position1]; fields[position1] = fields[position2]; fields[position2] = tempField; } private ClassDef loadSuperclass(UnresolvedClassInfo classInfo) { if (classInfo.classType.equals("Ljava/lang/Object;")) { if (classInfo.superclassType != null) { throw new ExceptionWithContext("Invalid superclass " + classInfo.superclassType + " for Ljava/lang/Object;. " + "The Object class cannot have a superclass"); } return null; } else { String superclassType = classInfo.superclassType; if (superclassType == null) { throw new ExceptionWithContext(classInfo.classType + " has no superclass"); } ClassDef superclass; try { superclass = ClassPath.getClassDef(superclassType); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, String.format("Could not find superclass %s", superclassType)); } if (!isInterface && superclass.isInterface) { throw new ValidationException("Class " + classType + " has the interface " + superclass.classType + " as its superclass"); } if (isInterface && !superclass.isInterface && superclass != ClassPath.theClassPath.javaLangObjectClassDef) { throw new ValidationException("Interface " + classType + " has the non-interface class " + superclass.classType + " as its superclass"); } return superclass; } } private TreeSet<ClassDef> loadAllImplementedInterfaces(UnresolvedClassInfo classInfo) { assert classType != null; assert classType.equals("Ljava/lang/Object;") || superclass != null; assert classInfo != null; TreeSet<ClassDef> implementedInterfaceSet = new TreeSet<ClassDef>(); if (superclass != null) { for (ClassDef interfaceDef: superclass.implementedInterfaces) { implementedInterfaceSet.add(interfaceDef); } } if (classInfo.interfaces != null) { for (String interfaceType: classInfo.interfaces) { ClassDef interfaceDef; try { interfaceDef = ClassPath.getClassDef(interfaceType); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, String.format("Could not find interface %s", interfaceType)); } assert interfaceDef.isInterface(); implementedInterfaceSet.add(interfaceDef); interfaceDef = interfaceDef.getSuperclass(); while (!interfaceDef.getClassType().equals("Ljava/lang/Object;")) { assert interfaceDef.isInterface(); implementedInterfaceSet.add(interfaceDef); interfaceDef = interfaceDef.getSuperclass(); } } } return implementedInterfaceSet; } private LinkedHashMap<String, ClassDef> loadInterfaceTable(UnresolvedClassInfo classInfo) { if (classInfo.interfaces == null) { return null; } LinkedHashMap<String, ClassDef> interfaceTable = new LinkedHashMap<String, ClassDef>(); for (String interfaceType: classInfo.interfaces) { if (!interfaceTable.containsKey(interfaceType)) { ClassDef interfaceDef; try { interfaceDef = ClassPath.getClassDef(interfaceType); } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, String.format("Could not find interface %s", interfaceType)); } interfaceTable.put(interfaceType, interfaceDef); if (interfaceDef.interfaceTable != null) { for (ClassDef superInterface: interfaceDef.interfaceTable.values()) { if (!interfaceTable.containsKey(superInterface.classType)) { interfaceTable.put(superInterface.classType, superInterface); } } } } } return interfaceTable; } //TODO: check the case when we have a package private method that overrides an interface method private VirtualMethod[] loadVtable(UnresolvedClassInfo classInfo) { //TODO: it might be useful to keep track of which class's implementation is used for each virtual method. In other words, associate the implementing class type with each vtable entry List<VirtualMethod> virtualMethodList = new LinkedList<VirtualMethod>(); //copy the virtual methods from the superclass int methodIndex = 0; if (superclass != null) { for (int i=0; i<superclass.vtable.length; i++) { virtualMethodList.add(superclass.vtable[i]); } assert superclass.instanceFields != null; } //iterate over the virtual methods in the current class, and only add them when we don't already have the //method (i.e. if it was implemented by the superclass) if (!this.isInterface) { if (classInfo.virtualMethods != null) { addToVtable(classInfo.virtualMethods, virtualMethodList); } if (interfaceTable != null) { for (ClassDef interfaceDef: interfaceTable.values()) { if (interfaceDef.virtualMethods == null) { continue; } addToVtable(interfaceDef.virtualMethods, virtualMethodList); } } } VirtualMethod[] vtable = new VirtualMethod[virtualMethodList.size()]; for (int i=0; i<virtualMethodList.size(); i++) { vtable[i] = virtualMethodList.get(i); } return vtable; } private void addToVtable(VirtualMethod[] localMethods, List<VirtualMethod> vtable) { for (VirtualMethod virtualMethod: localMethods) { boolean found = false; for (int i=0; i<vtable.size(); i++) { VirtualMethod superMethod = vtable.get(i); if (superMethod.method.equals(virtualMethod.method)) { if (!ClassPath.theClassPath.checkPackagePrivateAccess || this.canAccess(superMethod)) { found = true; vtable.set(i, virtualMethod); break; } } } if (!found) { vtable.add(virtualMethod); } } } private boolean canAccess(VirtualMethod virtualMethod) { if (!virtualMethod.isPackagePrivate) { return true; } String otherPackage = getPackage(virtualMethod.containingClass); String ourPackage = getPackage(this.classType); return otherPackage.equals(ourPackage); } private String getPackage(String classType) { int lastSlash = classType.lastIndexOf('/'); if (lastSlash < 0) { return ""; } return classType.substring(1, lastSlash); } private int getNextFieldOffset() { if (instanceFields == null || instanceFields.size() == 0) { return 8; } int lastItemIndex = instanceFields.size()-1; int fieldOffset = instanceFields.keyAt(lastItemIndex); FieldDef lastField = instanceFields.valueAt(lastItemIndex); switch (lastField.type.charAt(0)) { case 'J': case 'D': return fieldOffset + 8; default: return fieldOffset + 4; } } private SparseArray<FieldDef> loadFields(UnresolvedClassInfo classInfo) { //This is a bit of an "involved" operation. We need to follow the same algorithm that dalvik uses to //arrange fields, so that we end up with the same field offsets (which is needed for deodexing). //See mydroid/dalvik/vm/oo/Class.c - computeFieldOffsets() final byte REFERENCE = 0; final byte WIDE = 1; final byte OTHER = 2; FieldDef[] fields = null; //the "type" for each field in fields. 0=reference,1=wide,2=other byte[] fieldTypes = null; if (classInfo.instanceFields != null) { fields = new FieldDef[classInfo.instanceFields.length]; fieldTypes = new byte[fields.length]; for (int i=0; i<fields.length; i++) { String[] fieldInfo = classInfo.instanceFields[i]; String fieldName = fieldInfo[0]; String fieldType = fieldInfo[1]; fieldTypes[i] = getFieldType(fieldType); fields[i] = new FieldDef(classInfo.classType, fieldName, fieldType); } } if (fields == null) { fields = new FieldDef[0]; fieldTypes = new byte[0]; } //The first operation is to move all of the reference fields to the front. To do this, find the first //non-reference field, then find the last reference field, swap them and repeat int back = fields.length - 1; int front; for (front = 0; front<fields.length; front++) { if (fieldTypes[front] != REFERENCE) { while (back > front) { if (fieldTypes[back] == REFERENCE) { swap(fieldTypes, fields, front, back--); break; } back--; } } if (fieldTypes[front] != REFERENCE) { break; } } int startFieldOffset = 8; if (this.superclass != null) { startFieldOffset = this.superclass.getNextFieldOffset(); } int fieldIndexMod; if ((startFieldOffset % 8) == 0) { fieldIndexMod = 0; } else { fieldIndexMod = 1; } //next, we need to group all the wide fields after the reference fields. But the wide fields have to be //8-byte aligned. If we're on an odd field index, we need to insert a 32-bit field. If the next field //is already a 32-bit field, use that. Otherwise, find the first 32-bit field from the end and swap it in. //If there are no 32-bit fields, do nothing for now. We'll add padding when calculating the field offsets if (front < fields.length && (front % 2) != fieldIndexMod) { if (fieldTypes[front] == WIDE) { //we need to swap in a 32-bit field, so the wide fields will be correctly aligned back = fields.length - 1; while (back > front) { if (fieldTypes[back] == OTHER) { swap(fieldTypes, fields, front++, back); break; } back--; } } else { //there's already a 32-bit field here that we can use front++; } } //do the swap thing for wide fields back = fields.length - 1; for (; front<fields.length; front++) { if (fieldTypes[front] != WIDE) { while (back > front) { if (fieldTypes[back] == WIDE) { swap(fieldTypes, fields, front, back--); break; } back--; } } if (fieldTypes[front] != WIDE) { break; } } int superFieldCount = 0; if (superclass != null) { superFieldCount = superclass.instanceFields.size(); } //now the fields are in the correct order. Add them to the SparseArray and lookup, and calculate the offsets int totalFieldCount = superFieldCount + fields.length; SparseArray<FieldDef> instanceFields = new SparseArray<FieldDef>(totalFieldCount); int fieldOffset; if (superclass != null && superFieldCount > 0) { for (int i=0; i<superFieldCount; i++) { instanceFields.append(superclass.instanceFields.keyAt(i), superclass.instanceFields.valueAt(i)); } fieldOffset = instanceFields.keyAt(superFieldCount-1); FieldDef lastSuperField = superclass.instanceFields.valueAt(superFieldCount-1); char fieldType = lastSuperField.type.charAt(0); if (fieldType == 'J' || fieldType == 'D') { fieldOffset += 8; } else { fieldOffset += 4; } } else { //the field values start at 8 bytes into the DataObject dalvik structure fieldOffset = 8; } boolean gotDouble = false; for (int i=0; i<fields.length; i++) { FieldDef field = fields[i]; //add padding to align the wide fields, if needed if (fieldTypes[i] == WIDE && !gotDouble) { if (!gotDouble) { if (fieldOffset % 8 != 0) { assert fieldOffset % 8 == 4; fieldOffset += 4; } gotDouble = true; } } instanceFields.append(fieldOffset, field); if (fieldTypes[i] == WIDE) { fieldOffset += 8; } else { fieldOffset += 4; } } return instanceFields; } private byte getFieldType(String fieldType) { switch (fieldType.charAt(0)) { case '[': case 'L': return 0; //REFERENCE case 'J': case 'D': return 1; //WIDE default: return 2; //OTHER } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ClassDef)) return false; ClassDef classDef = (ClassDef) o; return classType.equals(classDef.classType); } @Override public int hashCode() { return classType.hashCode(); } public int compareTo(ClassDef classDef) { return classType.compareTo(classDef.classType); } } private static class VirtualMethod { public String containingClass; public String method; public boolean isPackagePrivate; } /** * This aggregates the basic information about a class in an easy-to-use format, without requiring references * to any other class. */ private static class UnresolvedClassInfo { public final String dexFilePath; public final String classType; public final boolean isPublic; public final boolean isInterface; public final String superclassType; public final String[] interfaces; public final boolean[] staticMethods; public final String[] directMethods; public final VirtualMethod[] virtualMethods; public final String[][] instanceFields; public UnresolvedClassInfo(String dexFilePath, ClassDefItem classDefItem) { this.dexFilePath = dexFilePath; classType = classDefItem.getClassType().getTypeDescriptor(); isPublic = (classDefItem.getAccessFlags() & AccessFlags.PUBLIC.getValue()) != 0; isInterface = (classDefItem.getAccessFlags() & AccessFlags.INTERFACE.getValue()) != 0; TypeIdItem superclassType = classDefItem.getSuperclass(); if (superclassType == null) { this.superclassType = null; } else { this.superclassType = superclassType.getTypeDescriptor(); } interfaces = loadInterfaces(classDefItem); ClassDataItem classDataItem = classDefItem.getClassData(); if (classDataItem != null) { boolean[][] _staticMethods = new boolean[1][]; directMethods = loadDirectMethods(classDataItem, _staticMethods); staticMethods = _staticMethods[0]; virtualMethods = loadVirtualMethods(classDataItem); instanceFields = loadInstanceFields(classDataItem); } else { staticMethods = null; directMethods = null; virtualMethods = null; instanceFields = null; } } private String[] loadInterfaces(ClassDefItem classDefItem) { TypeListItem typeList = classDefItem.getInterfaces(); if (typeList != null) { List<TypeIdItem> types = typeList.getTypes(); if (types != null && types.size() > 0) { String[] interfaces = new String[types.size()]; for (int i=0; i<interfaces.length; i++) { interfaces[i] = types.get(i).getTypeDescriptor(); } return interfaces; } } return null; } private String[] loadDirectMethods(ClassDataItem classDataItem, boolean[][] _staticMethods) { List<EncodedMethod> encodedMethods = classDataItem.getDirectMethods(); if (encodedMethods.size() > 0) { boolean[] staticMethods = new boolean[encodedMethods.size()]; String[] directMethods = new String[encodedMethods.size()]; for (int i=0; i<encodedMethods.size(); i++) { EncodedMethod encodedMethod = encodedMethods.get(i); if ((encodedMethod.accessFlags & AccessFlags.STATIC.getValue()) != 0) { staticMethods[i] = true; } directMethods[i] = encodedMethod.method.getShortMethodString(); } _staticMethods[0] = staticMethods; return directMethods; } return null; } private VirtualMethod[] loadVirtualMethods(ClassDataItem classDataItem) { List<EncodedMethod> encodedMethods = classDataItem.getVirtualMethods(); if (encodedMethods.size() > 0) { VirtualMethod[] virtualMethods = new VirtualMethod[encodedMethods.size()]; for (int i=0; i<encodedMethods.size(); i++) { virtualMethods[i] = new VirtualMethod(); EncodedMethod encodedMethod = encodedMethods.get(i); virtualMethods[i].isPackagePrivate = methodIsPackagePrivate(encodedMethod.accessFlags); virtualMethods[i].containingClass = classDataItem.getParentType().getTypeDescriptor(); virtualMethods[i].method = encodedMethods.get(i).method.getShortMethodString(); } return virtualMethods; } return null; } private static boolean methodIsPackagePrivate(int accessFlags) { return (accessFlags & (AccessFlags.PRIVATE.getValue() | AccessFlags.PROTECTED.getValue() | AccessFlags.PUBLIC.getValue())) == 0; } private String[][] loadInstanceFields(ClassDataItem classDataItem) { List<EncodedField> encodedFields = classDataItem.getInstanceFields(); if (encodedFields.size() > 0) { String[][] instanceFields = new String[encodedFields.size()][2]; for (int i=0; i<encodedFields.size(); i++) { EncodedField encodedField = encodedFields.get(i); instanceFields[i][0] = encodedField.field.getFieldName().getStringValue(); instanceFields[i][1] = encodedField.field.getFieldType().getTypeDescriptor(); } return instanceFields; } return null; } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/ClassPath.java
Java
asf20
54,703
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.Code.OdexedInvokeInline; import org.jf.dexlib.Code.OdexedInvokeVirtual; import static org.jf.dexlib.Code.Analysis.DeodexUtil.Static; import static org.jf.dexlib.Code.Analysis.DeodexUtil.Virtual; import static org.jf.dexlib.Code.Analysis.DeodexUtil.Direct; public abstract class InlineMethodResolver { public static InlineMethodResolver createInlineMethodResolver(DeodexUtil deodexUtil, int odexVersion) { if (odexVersion == 35) { return new InlineMethodResolver_version35(deodexUtil); } else if (odexVersion == 36) { return new InlineMethodResolver_version36(deodexUtil); } else { throw new RuntimeException(String.format("odex version %d is not supported yet", odexVersion)); } } protected InlineMethodResolver() { } public abstract DeodexUtil.InlineMethod resolveExecuteInline(AnalyzedInstruction instruction); private static class InlineMethodResolver_version35 extends InlineMethodResolver { private final DeodexUtil.InlineMethod[] inlineMethods; public InlineMethodResolver_version35(DeodexUtil deodexUtil) { inlineMethods = new DeodexUtil.InlineMethod[] { new DeodexUtil.InlineMethod(Static, "Lorg/apache/harmony/dalvik/NativeTestTarget;", "emptyInlineMethod", "", "V"), new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "charAt", "I", "C"), new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "compareTo", "Ljava/lang/String;", "I"), new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "equals", "Ljava/lang/Object;", "Z"), new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "length", "", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "I", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "J", "J"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "F", "F"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "min", "II", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "max", "II", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "sqrt", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "cos", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "sin", "D", "D") }; } @Override public DeodexUtil.InlineMethod resolveExecuteInline(AnalyzedInstruction analyzedInstruction) { assert analyzedInstruction.instruction instanceof OdexedInvokeInline; OdexedInvokeInline instruction = (OdexedInvokeInline)analyzedInstruction.instruction; int inlineIndex = instruction.getInlineIndex(); if (inlineIndex < 0 || inlineIndex >= inlineMethods.length) { throw new RuntimeException("Invalid inline index: " + inlineIndex); } return inlineMethods[inlineIndex]; } } private static class InlineMethodResolver_version36 extends InlineMethodResolver { private final DeodexUtil.InlineMethod[] inlineMethods; private final DeodexUtil.InlineMethod indexOfIMethod; private final DeodexUtil.InlineMethod indexOfIIMethod; private final DeodexUtil.InlineMethod fastIndexOfMethod; private final DeodexUtil.InlineMethod isEmptyMethod; public InlineMethodResolver_version36(DeodexUtil deodexUtil) { //The 5th and 6th entries differ between froyo and gingerbread. We have to look at the parameters being //passed to distinguish between them. //froyo indexOfIMethod = new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "indexOf", "I", "I"); indexOfIIMethod = new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "indexOf", "II", "I"); //gingerbread fastIndexOfMethod = new DeodexUtil.InlineMethod(Direct, "Ljava/lang/String;", "fastIndexOf", "II", "I"); isEmptyMethod = new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "isEmpty", "", "Z"); inlineMethods = new DeodexUtil.InlineMethod[] { new DeodexUtil.InlineMethod(Static, "Lorg/apache/harmony/dalvik/NativeTestTarget;", "emptyInlineMethod", "", "V"), new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "charAt", "I", "C"), new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "compareTo", "Ljava/lang/String;", "I"), new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "equals", "Ljava/lang/Object;", "Z"), //froyo: deodexUtil.new InlineMethod(Virtual, "Ljava/lang/String;", "indexOf", "I", "I"), //gingerbread: deodexUtil.new InlineMethod(Virtual, "Ljava/lang/String;", "fastIndexOf", "II", "I"), null, //froyo: deodexUtil.new InlineMethod(Virtual, "Ljava/lang/String;", "indexOf", "II", "I"), //gingerbread: deodexUtil.new InlineMethod(Virtual, "Ljava/lang/String;", "isEmpty", "", "Z"), null, new DeodexUtil.InlineMethod(Virtual, "Ljava/lang/String;", "length", "", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "I", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "J", "J"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "F", "F"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "abs", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "min", "II", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "max", "II", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "sqrt", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "cos", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Math;", "sin", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Float;", "floatToIntBits", "F", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Float;", "floatToRawIntBits", "F", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Float;", "intBitsToFloat", "I", "F"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Double;", "doubleToLongBits", "D", "J"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Double;", "doubleToRawLongBits", "D", "J"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/Double;", "longBitsToDouble", "J", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/StrictMath;", "abs", "I", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/StrictMath;", "abs", "J", "J"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/StrictMath;", "abs", "F", "F"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/StrictMath;", "abs", "D", "D"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/StrictMath;", "min", "II", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/StrictMath;", "max", "II", "I"), new DeodexUtil.InlineMethod(Static, "Ljava/lang/StrictMath;", "sqrt", "D", "D"), }; } @Override public DeodexUtil.InlineMethod resolveExecuteInline(AnalyzedInstruction analyzedInstruction) { assert analyzedInstruction.instruction instanceof OdexedInvokeInline; OdexedInvokeInline instruction = (OdexedInvokeInline)analyzedInstruction.instruction; int inlineIndex = instruction.getInlineIndex(); if (inlineIndex < 0 || inlineIndex >= inlineMethods.length) { throw new RuntimeException("Invalid method index: " + inlineIndex); } if (inlineIndex == 4) { int parameterCount = getParameterCount(instruction); if (parameterCount == 2) { return indexOfIMethod; } else if (parameterCount == 3) { return fastIndexOfMethod; } else { throw new RuntimeException("Could not determine the correct inline method to use"); } } else if (inlineIndex == 5) { int parameterCount = getParameterCount(instruction); if (parameterCount == 3) { return indexOfIIMethod; } else if (parameterCount == 1) { return isEmptyMethod; } else { throw new RuntimeException("Could not determine the correct inline method to use"); } } return inlineMethods[inlineIndex]; } private int getParameterCount(OdexedInvokeInline instruction) { return instruction.getRegCount(); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/InlineMethodResolver.java
Java
asf20
10,722
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DeodexUtil { public static final int Virtual = 0; public static final int Direct = 1; public static final int Static = 2; private final InlineMethodResolver inlineMethodResolver; public final DexFile dexFile; public DeodexUtil(DexFile dexFile) { this.dexFile = dexFile; OdexHeader odexHeader = dexFile.getOdexHeader(); if (odexHeader == null) { //if there isn't an odex header, why are we creating an DeodexUtil object? assert false; throw new RuntimeException("Cannot create a DeodexUtil object for a dex file without an odex header"); } inlineMethodResolver = InlineMethodResolver.createInlineMethodResolver(this, odexHeader.version); } public DeodexUtil(DexFile dexFile, InlineMethodResolver inlineMethodResolver) { this.dexFile = dexFile; this.inlineMethodResolver = inlineMethodResolver; } public InlineMethod lookupInlineMethod(AnalyzedInstruction instruction) { return inlineMethodResolver.resolveExecuteInline(instruction); } public FieldIdItem lookupField(ClassPath.ClassDef accessingClass, ClassPath.ClassDef instanceClass, int fieldOffset) { ClassPath.FieldDef field = instanceClass.getInstanceField(fieldOffset); if (field == null) { return null; } return parseAndResolveField(accessingClass, instanceClass, field); } private static final Pattern shortMethodPattern = Pattern.compile("([^(]+)\\(([^)]*)\\)(.+)"); public MethodIdItem lookupVirtualMethod(ClassPath.ClassDef accessingClass, ClassPath.ClassDef instanceClass, int methodIndex) { String method = instanceClass.getVirtualMethod(methodIndex); if (method == null) { return null; } Matcher m = shortMethodPattern.matcher(method); if (!m.matches()) { assert false; throw new RuntimeException("Invalid method descriptor: " + method); } String methodName = m.group(1); String methodParams = m.group(2); String methodRet = m.group(3); if (instanceClass instanceof ClassPath.UnresolvedClassDef) { //if this is an unresolved class, the only way getVirtualMethod could have found a method is if the virtual //method being looked up was a method on java.lang.Object. instanceClass = ClassPath.getClassDef("Ljava/lang/Object;"); } else if (instanceClass.isInterface()) { instanceClass = instanceClass.getSuperclass(); assert instanceClass != null; } return parseAndResolveMethod(accessingClass, instanceClass, methodName, methodParams, methodRet); } private MethodIdItem parseAndResolveMethod(ClassPath.ClassDef accessingClass, ClassPath.ClassDef definingClass, String methodName, String methodParams, String methodRet) { StringIdItem methodNameItem = StringIdItem.lookupStringIdItem(dexFile, methodName); if (methodNameItem == null) { return null; } LinkedList<TypeIdItem> paramList = new LinkedList<TypeIdItem>(); for (int i=0; i<methodParams.length(); i++) { TypeIdItem typeIdItem; switch (methodParams.charAt(i)) { case 'Z': case 'B': case 'S': case 'C': case 'I': case 'J': case 'F': case 'D': typeIdItem = TypeIdItem.lookupTypeIdItem(dexFile, methodParams.substring(i,i+1)); break; case 'L': { int end = methodParams.indexOf(';', i); if (end == -1) { throw new RuntimeException("invalid parameter in the method"); } typeIdItem = TypeIdItem.lookupTypeIdItem(dexFile, methodParams.substring(i, end+1)); i = end; break; } case '[': { int end; int typeStart = i+1; while (typeStart < methodParams.length() && methodParams.charAt(typeStart) == '[') { typeStart++; } switch (methodParams.charAt(typeStart)) { case 'Z': case 'B': case 'S': case 'C': case 'I': case 'J': case 'F': case 'D': end = typeStart; break; case 'L': end = methodParams.indexOf(';', typeStart); if (end == -1) { throw new RuntimeException("invalid parameter in the method"); } break; default: throw new RuntimeException("invalid parameter in the method"); } typeIdItem = TypeIdItem.lookupTypeIdItem(dexFile, methodParams.substring(i, end+1)); i = end; break; } default: throw new RuntimeException("invalid parameter in the method"); } if (typeIdItem == null) { return null; } paramList.add(typeIdItem); } TypeListItem paramListItem = null; if (paramList.size() > 0) { paramListItem = TypeListItem.lookupTypeListItem(dexFile, paramList); if (paramListItem == null) { return null; } } TypeIdItem retType = TypeIdItem.lookupTypeIdItem(dexFile, methodRet); if (retType == null) { return null; } ProtoIdItem protoItem = ProtoIdItem.lookupProtoIdItem(dexFile, retType, paramListItem); if (protoItem == null) { return null; } ClassPath.ClassDef methodClassDef = definingClass; do { TypeIdItem classTypeItem = TypeIdItem.lookupTypeIdItem(dexFile, methodClassDef.getClassType()); if (classTypeItem != null) { MethodIdItem methodIdItem = MethodIdItem.lookupMethodIdItem(dexFile, classTypeItem, protoItem, methodNameItem); if (methodIdItem != null && checkClassAccess(accessingClass, methodClassDef)) { return methodIdItem; } } methodClassDef = methodClassDef.getSuperclass(); } while (methodClassDef != null); return null; } private static boolean checkClassAccess(ClassPath.ClassDef accessingClass, ClassPath.ClassDef definingClass) { return definingClass.isPublic() || getPackage(accessingClass.getClassType()).equals(getPackage(definingClass.getClassType())); } private static String getPackage(String classRef) { int lastSlash = classRef.lastIndexOf('/'); if (lastSlash < 0) { return ""; } return classRef.substring(1, lastSlash); } /** * * @param accessingClass The class that contains the field reference. I.e. the class being deodexed * @param instanceClass The inferred class type of the object that the field is being accessed on * @param field The field being accessed * @return The FieldIdItem of the resolved field */ private FieldIdItem parseAndResolveField(ClassPath.ClassDef accessingClass, ClassPath.ClassDef instanceClass, ClassPath.FieldDef field) { String definingClass = field.definingClass; String fieldName = field.name; String fieldType = field.type; StringIdItem fieldNameItem = StringIdItem.lookupStringIdItem(dexFile, fieldName); if (fieldNameItem == null) { return null; } TypeIdItem fieldTypeItem = TypeIdItem.lookupTypeIdItem(dexFile, fieldType); if (fieldTypeItem == null) { return null; } ClassPath.ClassDef fieldClass = instanceClass; ArrayList<ClassPath.ClassDef> parents = new ArrayList<ClassPath.ClassDef>(); parents.add(fieldClass); while (fieldClass != null && !fieldClass.getClassType().equals(definingClass)) { fieldClass = fieldClass.getSuperclass(); parents.add(fieldClass); } for (int i=parents.size()-1; i>=0; i--) { fieldClass = parents.get(i); TypeIdItem classTypeItem = TypeIdItem.lookupTypeIdItem(dexFile, fieldClass.getClassType()); if (classTypeItem == null) { continue; } FieldIdItem fieldIdItem = FieldIdItem.lookupFieldIdItem(dexFile, classTypeItem, fieldTypeItem, fieldNameItem); if (fieldIdItem != null && checkClassAccess(accessingClass, fieldClass)) { return fieldIdItem; } } return null; } public static class InlineMethod { public final int methodType; public final String classType; public final String methodName; public final String parameters; public final String returnType; private MethodIdItem methodIdItem = null; InlineMethod(int methodType, String classType, String methodName, String parameters, String returnType) { this.methodType = methodType; this.classType = classType; this.methodName = methodName; this.parameters = parameters; this.returnType = returnType; } public MethodIdItem getMethodIdItem(DeodexUtil deodexUtil) { if (methodIdItem == null) { loadMethod(deodexUtil); } return methodIdItem; } private void loadMethod(DeodexUtil deodexUtil) { ClassPath.ClassDef classDef = ClassPath.getClassDef(classType); this.methodIdItem = deodexUtil.parseAndResolveMethod(classDef, classDef, methodName, parameters, returnType); } public String getMethodString() { return String.format("%s->%s(%s)%s", classType, methodName, parameters, returnType); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/DeodexUtil.java
Java
asf20
12,384
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.Util.ExceptionWithContext; public class ValidationException extends ExceptionWithContext { private int codeAddress; public ValidationException(int codeAddress, String errorMessage) { super(errorMessage); this.codeAddress = codeAddress; } public ValidationException(String errorMessage) { super(errorMessage); } public void setCodeAddress(int codeAddress) { this.codeAddress = codeAddress; } public int getCodeAddress() { return codeAddress; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/ValidationException.java
Java
asf20
2,087
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.Code.OdexedInvokeInline; import org.jf.dexlib.Code.OdexedInvokeVirtual; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CustomInlineMethodResolver extends InlineMethodResolver { private DeodexUtil.InlineMethod[] inlineMethods; public CustomInlineMethodResolver(String inlineTable) { FileReader fr = null; try { fr = new FileReader(inlineTable); } catch (FileNotFoundException ex) { throw new RuntimeException("Could not find inline table file: " + inlineTable); } List<String> lines = new ArrayList<String>(); BufferedReader br = new BufferedReader(fr); try { String line = br.readLine(); while (line != null) { if (line.length() > 0) { lines.add(line); } line = br.readLine(); } } catch (IOException ex) { throw new RuntimeException("Error while reading file: " + inlineTable, ex); } inlineMethods = new DeodexUtil.InlineMethod[lines.size()]; for (int i=0; i<inlineMethods.length; i++) { inlineMethods[i] = parseAndResolveInlineMethod(lines.get(i)); } } @Override public DeodexUtil.InlineMethod resolveExecuteInline(AnalyzedInstruction analyzedInstruction) { assert analyzedInstruction.instruction instanceof OdexedInvokeInline; OdexedInvokeInline instruction = (OdexedInvokeInline)analyzedInstruction.instruction; int methodIndex = instruction.getInlineIndex(); if (methodIndex < 0 || methodIndex >= inlineMethods.length) { throw new RuntimeException("Invalid method index: " + methodIndex); } return inlineMethods[methodIndex]; } private static final Pattern longMethodPattern = Pattern.compile("(L[^;]+;)->([^(]+)\\(([^)]*)\\)(.+)"); private DeodexUtil.InlineMethod parseAndResolveInlineMethod(String inlineMethod) { Matcher m = longMethodPattern.matcher(inlineMethod); if (!m.matches()) { assert false; throw new RuntimeException("Invalid method descriptor: " + inlineMethod); } String className = m.group(1); String methodName = m.group(2); String methodParams = m.group(3); String methodRet = m.group(4); ClassPath.ClassDef classDef = ClassPath.getClassDef(className, false); int methodType = classDef.getMethodType(String.format("%s(%s)%s", methodName, methodParams, methodRet)); if (methodType == -1) { throw new RuntimeException("Cannot resolve inline method: " + inlineMethod); } return new DeodexUtil.InlineMethod(methodType, className, methodName, methodParams, methodRet); } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/CustomInlineMethodResolver.java
Java
asf20
4,507
/* * [The "BSD licence"] * Copyright (c) 2011 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.*; import org.jf.dexlib.Code.Format.Instruction22c; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Util.AccessFlags; import java.util.HashMap; public class SyntheticAccessorResolver { public static final int METHOD = 0; public static final int GETTER = 1; public static final int SETTER = 2; private final DexFileClassMap classMap; private final HashMap<MethodIdItem, AccessedMember> resolvedAccessors = new HashMap<MethodIdItem, AccessedMember>(); public SyntheticAccessorResolver(DexFile dexFile) { classMap = new DexFileClassMap(dexFile); } public static boolean looksLikeSyntheticAccessor(MethodIdItem methodIdItem) { return methodIdItem.getMethodName().getStringValue().startsWith("access$"); } public AccessedMember getAccessedMember(MethodIdItem methodIdItem) { AccessedMember accessedMember = resolvedAccessors.get(methodIdItem); if (accessedMember != null) { return accessedMember; } ClassDefItem classDefItem = classMap.getClassDefByType(methodIdItem.getContainingClass()); if (classDefItem == null) { return null; } ClassDataItem classDataItem = classDefItem.getClassData(); if (classDataItem == null) { return null; } ClassDataItem.EncodedMethod encodedMethod = classDataItem.findDirectMethodByMethodId(methodIdItem); if (encodedMethod == null) { return null; } //A synthetic accessor will be marked synthetic if ((encodedMethod.accessFlags & AccessFlags.SYNTHETIC.getValue()) == 0) { return null; } Instruction[] instructions = encodedMethod.codeItem.getInstructions(); //TODO: add support for odexed formats switch (instructions[0].opcode.format) { case Format35c: case Format3rc: { //a synthetic method access should be either 2 or 3 instructions, depending on if the method returns //anything or not if (instructions.length < 2 || instructions.length > 3) { return null; } InstructionWithReference instruction = (InstructionWithReference)instructions[0]; Item referencedItem = instruction.getReferencedItem(); if (!(referencedItem instanceof MethodIdItem)) { return null; } MethodIdItem referencedMethodIdItem = (MethodIdItem)referencedItem; accessedMember = new AccessedMember(METHOD, referencedMethodIdItem); resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } case Format22c: { //a synthetic field access should be exactly 2 instructions. The set/put, and then the return if (instructions.length != 2) { return null; } Instruction22c instruction = (Instruction22c)instructions[0]; Item referencedItem = instruction.getReferencedItem(); if (!(referencedItem instanceof FieldIdItem)) { return null; } FieldIdItem referencedFieldIdItem = (FieldIdItem)referencedItem; if (instruction.opcode.setsRegister() || instruction.opcode.setsWideRegister()) { //If the instruction sets a register, that means it is a getter - it gets the field value and //stores it in the register accessedMember = new AccessedMember(GETTER, referencedFieldIdItem); } else { accessedMember = new AccessedMember(SETTER, referencedFieldIdItem); } resolvedAccessors.put(methodIdItem, accessedMember); return accessedMember; } default: return null; } } public static class AccessedMember { public final int accessedMemberType; public final Item accessedMember; public AccessedMember(int accessedMemberType, Item accessedMember) { this.accessedMemberType = accessedMemberType; this.accessedMember = accessedMember; } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/SyntheticAccessorResolver.java
Java
asf20
5,946
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.Code.Opcode; public class OdexedFieldInstructionMapper { private static Opcode[][][][] opcodeMap = new Opcode[][][][] { //get opcodes new Opcode[][][] { //iget quick new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.IGET_QUICK, /*B*/ Opcode.IGET_QUICK, /*S*/ Opcode.IGET_QUICK, /*C*/ Opcode.IGET_QUICK, /*I,F*/ Opcode.IGET_QUICK, /*J,D*/ Opcode.IGET_WIDE_QUICK, /*L,[*/ Opcode.IGET_OBJECT_QUICK }, //deodexed new Opcode[] { /*Z*/ Opcode.IGET_BOOLEAN, /*B*/ Opcode.IGET_BYTE, /*S*/ Opcode.IGET_SHORT, /*C*/ Opcode.IGET_CHAR, /*I,F*/ Opcode.IGET, /*J,D*/ Opcode.IGET_WIDE, /*L,[*/ Opcode.IGET_OBJECT } }, //iget volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.IGET_VOLATILE, /*B*/ Opcode.IGET_VOLATILE, /*S*/ Opcode.IGET_VOLATILE, /*C*/ Opcode.IGET_VOLATILE, /*I,F*/ Opcode.IGET_VOLATILE, /*J,D*/ Opcode.IGET_WIDE_VOLATILE, /*L,[*/ Opcode.IGET_OBJECT_VOLATILE }, //deodexed new Opcode[] { /*Z*/ Opcode.IGET_BOOLEAN, /*B*/ Opcode.IGET_BYTE, /*S*/ Opcode.IGET_SHORT, /*C*/ Opcode.IGET_CHAR, /*I,F*/ Opcode.IGET, /*J,D*/ Opcode.IGET_WIDE, /*L,[*/ Opcode.IGET_OBJECT } }, //sget volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.SGET_VOLATILE, /*B*/ Opcode.SGET_VOLATILE, /*S*/ Opcode.SGET_VOLATILE, /*C*/ Opcode.SGET_VOLATILE, /*I,F*/ Opcode.SGET_VOLATILE, /*J,D*/ Opcode.SGET_WIDE_VOLATILE, /*L,[*/ Opcode.SGET_OBJECT_VOLATILE }, //deodexed new Opcode[] { /*Z*/ Opcode.SGET_BOOLEAN, /*B*/ Opcode.SGET_BYTE, /*S*/ Opcode.SGET_SHORT, /*C*/ Opcode.SGET_CHAR, /*I,F*/ Opcode.SGET, /*J,D*/ Opcode.SGET_WIDE, /*L,[*/ Opcode.SGET_OBJECT } } }, //put opcodes new Opcode[][][] { //iput quick new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.IPUT_QUICK, /*B*/ Opcode.IPUT_QUICK, /*S*/ Opcode.IPUT_QUICK, /*C*/ Opcode.IPUT_QUICK, /*I,F*/ Opcode.IPUT_QUICK, /*J,D*/ Opcode.IPUT_WIDE_QUICK, /*L,[*/ Opcode.IPUT_OBJECT_QUICK }, //deodexed new Opcode[] { /*Z*/ Opcode.IPUT_BOOLEAN, /*B*/ Opcode.IPUT_BYTE, /*S*/ Opcode.IPUT_SHORT, /*C*/ Opcode.IPUT_CHAR, /*I,F*/ Opcode.IPUT, /*J,D*/ Opcode.IPUT_WIDE, /*L,[*/ Opcode.IPUT_OBJECT } }, //iput volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.IPUT_VOLATILE, /*B*/ Opcode.IPUT_VOLATILE, /*S*/ Opcode.IPUT_VOLATILE, /*C*/ Opcode.IPUT_VOLATILE, /*I,F*/ Opcode.IPUT_VOLATILE, /*J,D*/ Opcode.IPUT_WIDE_VOLATILE, /*L,[*/ Opcode.IPUT_OBJECT_VOLATILE }, //deodexed new Opcode[] { /*Z*/ Opcode.IPUT_BOOLEAN, /*B*/ Opcode.IPUT_BYTE, /*S*/ Opcode.IPUT_SHORT, /*C*/ Opcode.IPUT_CHAR, /*I,F*/ Opcode.IPUT, /*J,D*/ Opcode.IPUT_WIDE, /*L,[*/ Opcode.IPUT_OBJECT } }, //sput volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.SPUT_VOLATILE, /*B*/ Opcode.SPUT_VOLATILE, /*S*/ Opcode.SPUT_VOLATILE, /*C*/ Opcode.SPUT_VOLATILE, /*I,F*/ Opcode.SPUT_VOLATILE, /*J,D*/ Opcode.SPUT_WIDE_VOLATILE, /*L,[*/ Opcode.SPUT_OBJECT_VOLATILE }, //deodexed new Opcode[] { /*Z*/ Opcode.SPUT_BOOLEAN, /*B*/ Opcode.SPUT_BYTE, /*S*/ Opcode.SPUT_SHORT, /*C*/ Opcode.SPUT_CHAR, /*I,F*/ Opcode.SPUT, /*J,D*/ Opcode.SPUT_WIDE, /*L,[*/ Opcode.SPUT_OBJECT } } } }; private static Opcode[][][][] jumboOpcodeMap = new Opcode[][][][] { //get opcodes new Opcode[][][] { //iget volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.IGET_VOLATILE_JUMBO, /*B*/ Opcode.IGET_VOLATILE_JUMBO, /*S*/ Opcode.IGET_VOLATILE_JUMBO, /*C*/ Opcode.IGET_VOLATILE_JUMBO, /*I,F*/ Opcode.IGET_VOLATILE_JUMBO, /*J,D*/ Opcode.IGET_WIDE_VOLATILE_JUMBO, /*L,[*/ Opcode.IGET_OBJECT_VOLATILE_JUMBO }, //deodexed new Opcode[] { /*Z*/ Opcode.IGET_BOOLEAN_JUMBO, /*B*/ Opcode.IGET_BYTE_JUMBO, /*S*/ Opcode.IGET_SHORT_JUMBO, /*C*/ Opcode.IGET_CHAR_JUMBO, /*I,F*/ Opcode.IGET_JUMBO, /*J,D*/ Opcode.IGET_WIDE_JUMBO, /*L,[*/ Opcode.IGET_OBJECT_JUMBO } }, //sget volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.SGET_VOLATILE_JUMBO, /*B*/ Opcode.SGET_VOLATILE_JUMBO, /*S*/ Opcode.SGET_VOLATILE_JUMBO, /*C*/ Opcode.SGET_VOLATILE_JUMBO, /*I,F*/ Opcode.SGET_VOLATILE_JUMBO, /*J,D*/ Opcode.SGET_WIDE_VOLATILE_JUMBO, /*L,[*/ Opcode.SGET_OBJECT_VOLATILE_JUMBO }, //deodexed new Opcode[] { /*Z*/ Opcode.SGET_BOOLEAN_JUMBO, /*B*/ Opcode.SGET_BYTE_JUMBO, /*S*/ Opcode.SGET_SHORT_JUMBO, /*C*/ Opcode.SGET_CHAR_JUMBO, /*I,F*/ Opcode.SGET_JUMBO, /*J,D*/ Opcode.SGET_WIDE_JUMBO, /*L,[*/ Opcode.SGET_OBJECT_JUMBO } } }, //put opcodes new Opcode[][][] { //iput volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.IPUT_VOLATILE_JUMBO, /*B*/ Opcode.IPUT_VOLATILE_JUMBO, /*S*/ Opcode.IPUT_VOLATILE_JUMBO, /*C*/ Opcode.IPUT_VOLATILE_JUMBO, /*I,F*/ Opcode.IPUT_VOLATILE_JUMBO, /*J,D*/ Opcode.IPUT_WIDE_VOLATILE_JUMBO, /*L,[*/ Opcode.IPUT_OBJECT_VOLATILE_JUMBO }, //deodexed new Opcode[] { /*Z*/ Opcode.IPUT_BOOLEAN_JUMBO, /*B*/ Opcode.IPUT_BYTE_JUMBO, /*S*/ Opcode.IPUT_SHORT_JUMBO, /*C*/ Opcode.IPUT_CHAR_JUMBO, /*I,F*/ Opcode.IPUT_JUMBO, /*J,D*/ Opcode.IPUT_WIDE_JUMBO, /*L,[*/ Opcode.IPUT_OBJECT_JUMBO } }, //sput volatile new Opcode[][] { //odexed new Opcode[] { /*Z*/ Opcode.SPUT_VOLATILE_JUMBO, /*B*/ Opcode.SPUT_VOLATILE_JUMBO, /*S*/ Opcode.SPUT_VOLATILE_JUMBO, /*C*/ Opcode.SPUT_VOLATILE_JUMBO, /*I,F*/ Opcode.SPUT_VOLATILE_JUMBO, /*J,D*/ Opcode.SPUT_WIDE_VOLATILE_JUMBO, /*L,[*/ Opcode.SPUT_OBJECT_VOLATILE_JUMBO }, //deodexed new Opcode[] { /*Z*/ Opcode.SPUT_BOOLEAN_JUMBO, /*B*/ Opcode.SPUT_BYTE_JUMBO, /*S*/ Opcode.SPUT_SHORT_JUMBO, /*C*/ Opcode.SPUT_CHAR_JUMBO, /*I,F*/ Opcode.SPUT_JUMBO, /*J,D*/ Opcode.SPUT_WIDE_JUMBO, /*L,[*/ Opcode.SPUT_OBJECT_JUMBO } } } }; private static int getTypeIndex(char type) { switch (type) { case 'Z': return 0; case 'B': return 1; case 'S': return 2; case 'C': return 3; case 'I': case 'F': return 4; case 'J': case 'D': return 5; case 'L': case '[': return 6; default: } throw new RuntimeException(String.format("Unknown type %s: ", type)); } private static int getOpcodeSubtype(Opcode opcode) { if (opcode.isOdexedInstanceQuick()) { return 0; } else if (opcode.isOdexedInstanceVolatile()) { return 1; } else if (opcode.isOdexedStaticVolatile()) { return 2; } throw new RuntimeException(String.format("Not an odexed field access opcode: %s", opcode.name)); } static Opcode getAndCheckDeodexedOpcodeForOdexedOpcode(String fieldType, Opcode odexedOpcode) { boolean jumbo = odexedOpcode.isJumboOpcode(); int opcodeType = odexedOpcode.setsRegister()?0:1; int opcodeSubType = getOpcodeSubtype(odexedOpcode); int typeIndex = getTypeIndex(fieldType.charAt(0)); Opcode correctOdexedOpcode, deodexedOpcode; if (jumbo) { correctOdexedOpcode = jumboOpcodeMap[opcodeType][opcodeSubType-1][0][typeIndex]; deodexedOpcode = jumboOpcodeMap[opcodeType][opcodeSubType-1][1][typeIndex]; } else { correctOdexedOpcode = opcodeMap[opcodeType][opcodeSubType][0][typeIndex]; deodexedOpcode = opcodeMap[opcodeType][opcodeSubType][1][typeIndex]; } if (correctOdexedOpcode != odexedOpcode) { throw new ValidationException(String.format("Incorrect field type \"%s\" for %s", fieldType, odexedOpcode.name)); } return deodexedOpcode; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/OdexedFieldInstructionMapper.java
Java
asf20
16,054
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.*; import org.jf.dexlib.Code.*; import org.jf.dexlib.Code.Format.*; import org.jf.dexlib.Util.AccessFlags; import org.jf.dexlib.Util.ExceptionWithContext; import org.jf.dexlib.Util.SparseArray; import java.util.BitSet; import java.util.EnumSet; import java.util.List; /** * The MethodAnalyzer performs several functions. It "analyzes" the instructions and infers the register types * for each register, it can deodex odexed instructions, and it can verify the bytecode. The analysis and verification * are done in two separate passes, because the analysis has to process instructions multiple times in some cases, and * there's no need to perform the verification multiple times, so we wait until the method is fully analyzed and then * verify it. * * Before calling the analyze() method, you must have initialized the ClassPath by calling * ClassPath.InitializeClassPath */ public class MethodAnalyzer { private final ClassDataItem.EncodedMethod encodedMethod; private final DeodexUtil deodexUtil; private SparseArray<AnalyzedInstruction> instructions; private static final int NOT_ANALYZED = 0; private static final int ANALYZED = 1; private static final int VERIFIED = 2; private int analyzerState = NOT_ANALYZED; private BitSet analyzedInstructions; private ValidationException validationException = null; //This is a dummy instruction that occurs immediately before the first real instruction. We can initialize the //register types for this instruction to the parameter types, in order to have them propagate to all of its //successors, e.g. the first real instruction, the first instructions in any exception handlers covering the first //instruction, etc. private AnalyzedInstruction startOfMethod; public MethodAnalyzer(ClassDataItem.EncodedMethod encodedMethod, boolean deodex, InlineMethodResolver inlineResolver) { if (encodedMethod == null) { throw new IllegalArgumentException("encodedMethod cannot be null"); } if (encodedMethod.codeItem == null || encodedMethod.codeItem.getInstructions().length == 0) { throw new IllegalArgumentException("The method has no code"); } this.encodedMethod = encodedMethod; if (deodex) { if (inlineResolver != null) { this.deodexUtil = new DeodexUtil(encodedMethod.method.getDexFile(), inlineResolver); } else { this.deodexUtil = new DeodexUtil(encodedMethod.method.getDexFile()); } } else { this.deodexUtil = null; } //override AnalyzedInstruction and provide custom implementations of some of the methods, so that we don't //have to handle the case this special case of instruction being null, in the main class startOfMethod = new AnalyzedInstruction(null, -1, encodedMethod.codeItem.getRegisterCount()) { public boolean setsRegister() { return false; } @Override public boolean setsWideRegister() { return false; } @Override public boolean setsRegister(int registerNumber) { return false; } @Override public int getDestinationRegister() { assert false; return -1; }; }; buildInstructionList(); analyzedInstructions = new BitSet(instructions.size()); } public boolean isAnalyzed() { return analyzerState >= ANALYZED; } public boolean isVerified() { return analyzerState == VERIFIED; } public void analyze() { assert encodedMethod != null; assert encodedMethod.codeItem != null; if (analyzerState >= ANALYZED) { //the instructions have already been analyzed, so there is nothing to do return; } CodeItem codeItem = encodedMethod.codeItem; MethodIdItem methodIdItem = encodedMethod.method; int totalRegisters = codeItem.getRegisterCount(); int parameterRegisters = methodIdItem.getPrototype().getParameterRegisterCount(); int nonParameterRegisters = totalRegisters - parameterRegisters; for (AnalyzedInstruction instruction: instructions.getValues()) { instruction.dead = true; } //if this isn't a static method, determine which register is the "this" register and set the type to the //current class if ((encodedMethod.accessFlags & AccessFlags.STATIC.getValue()) == 0) { nonParameterRegisters--; int thisRegister = totalRegisters - parameterRegisters - 1; //if this is a constructor, then set the "this" register to an uninitialized reference of the current class if ((encodedMethod.accessFlags & AccessFlags.CONSTRUCTOR.getValue()) != 0) { setPostRegisterTypeAndPropagateChanges(startOfMethod, thisRegister, RegisterType.getRegisterType(RegisterType.Category.UninitThis, ClassPath.getClassDef(methodIdItem.getContainingClass()))); } else { setPostRegisterTypeAndPropagateChanges(startOfMethod, thisRegister, RegisterType.getRegisterType(RegisterType.Category.Reference, ClassPath.getClassDef(methodIdItem.getContainingClass()))); } } TypeListItem parameters = methodIdItem.getPrototype().getParameters(); if (parameters != null) { RegisterType[] parameterTypes = getParameterTypes(parameters, parameterRegisters); for (int i=0; i<parameterTypes.length; i++) { RegisterType registerType = parameterTypes[i]; int registerNum = (totalRegisters - parameterRegisters) + i; setPostRegisterTypeAndPropagateChanges(startOfMethod, registerNum, registerType); } } RegisterType uninit = RegisterType.getRegisterType(RegisterType.Category.Uninit, null); for (int i=0; i<nonParameterRegisters; i++) { setPostRegisterTypeAndPropagateChanges(startOfMethod, i, uninit); } BitSet instructionsToAnalyze = new BitSet(instructions.size()); //make sure all of the "first instructions" are marked for processing for (AnalyzedInstruction successor: startOfMethod.successors) { instructionsToAnalyze.set(successor.instructionIndex); } BitSet undeodexedInstructions = new BitSet(instructions.size()); do { boolean didSomething = false; while (!instructionsToAnalyze.isEmpty()) { for(int i=instructionsToAnalyze.nextSetBit(0); i>=0; i=instructionsToAnalyze.nextSetBit(i+1)) { instructionsToAnalyze.clear(i); if (analyzedInstructions.get(i)) { continue; } AnalyzedInstruction instructionToAnalyze = instructions.valueAt(i); instructionToAnalyze.dead = false; try { if (instructionToAnalyze.originalInstruction.opcode.odexOnly()) { //if we had deodexed an odex instruction in a previous pass, we might have more specific //register information now, so let's restore the original odexed instruction and //re-deodex it instructionToAnalyze.restoreOdexedInstruction(); } if (!analyzeInstruction(instructionToAnalyze)) { undeodexedInstructions.set(i); continue; } else { didSomething = true; undeodexedInstructions.clear(i); } } catch (ValidationException ex) { this.validationException = ex; int codeAddress = getInstructionAddress(instructionToAnalyze); ex.setCodeAddress(codeAddress); ex.addContext(String.format("opcode: %s", instructionToAnalyze.instruction.opcode.name)); ex.addContext(String.format("CodeAddress: %d", codeAddress)); ex.addContext(String.format("Method: %s", encodedMethod.method.getMethodString())); break; } analyzedInstructions.set(instructionToAnalyze.getInstructionIndex()); for (AnalyzedInstruction successor: instructionToAnalyze.successors) { instructionsToAnalyze.set(successor.getInstructionIndex()); } } if (validationException != null) { break; } } if (!didSomething) { break; } if (!undeodexedInstructions.isEmpty()) { for (int i=undeodexedInstructions.nextSetBit(0); i>=0; i=undeodexedInstructions.nextSetBit(i+1)) { instructionsToAnalyze.set(i); } } } while (true); //Now, go through and fix up any unresolvable odex instructions. These are usually odex instructions //that operate on a null register, and thus always throw an NPE. They can also be any sort of odex instruction //that occurs after an unresolvable odex instruction. We deodex if possible, or replace with an //UnresolvableOdexInstruction for (int i=0; i<instructions.size(); i++) { AnalyzedInstruction analyzedInstruction = instructions.valueAt(i); Instruction instruction = analyzedInstruction.getInstruction(); if (instruction.opcode.odexOnly()) { int objectRegisterNumber; switch (instruction.getFormat()) { case Format10x: analyzeReturnVoidBarrier(analyzedInstruction, false); continue; case Format21c: case Format22c: analyzePutGetVolatile(analyzedInstruction, false); continue; case Format35c: analyzeInvokeDirectEmpty(analyzedInstruction, false); continue; case Format3rc: analyzeInvokeObjectInitRange(analyzedInstruction, false); continue; case Format22cs: objectRegisterNumber = ((Instruction22cs)instruction).getRegisterB(); break; case Format35mi: case Format35ms: objectRegisterNumber = ((FiveRegisterInstruction)instruction).getRegisterD(); break; case Format3rmi: case Format3rms: objectRegisterNumber = ((RegisterRangeInstruction)instruction).getStartRegister(); break; default: continue; } analyzedInstruction.setDeodexedInstruction(new UnresolvedOdexInstruction(instruction, objectRegisterNumber)); } } analyzerState = ANALYZED; } public void verify() { if (analyzerState < ANALYZED) { throw new ExceptionWithContext("You must call analyze() before calling verify()."); } if (analyzerState == VERIFIED) { //we've already verified the bytecode. nothing to do return; } BitSet instructionsToVerify = new BitSet(instructions.size()); BitSet verifiedInstructions = new BitSet(instructions.size()); //make sure all of the "first instructions" are marked for processing for (AnalyzedInstruction successor: startOfMethod.successors) { instructionsToVerify.set(successor.instructionIndex); } while (!instructionsToVerify.isEmpty()) { for (int i=instructionsToVerify.nextSetBit(0); i>=0; i=instructionsToVerify.nextSetBit(i+1)) { instructionsToVerify.clear(i); if (verifiedInstructions.get(i)) { continue; } AnalyzedInstruction instructionToVerify = instructions.valueAt(i); try { verifyInstruction(instructionToVerify); } catch (ValidationException ex) { this.validationException = ex; int codeAddress = getInstructionAddress(instructionToVerify); ex.setCodeAddress(codeAddress); ex.addContext(String.format("opcode: %s", instructionToVerify.instruction.opcode.name)); ex.addContext(String.format("CodeAddress: %d", codeAddress)); ex.addContext(String.format("Method: %s", encodedMethod.method.getMethodString())); break; } verifiedInstructions.set(instructionToVerify.getInstructionIndex()); for (AnalyzedInstruction successor: instructionToVerify.successors) { instructionsToVerify.set(successor.getInstructionIndex()); } } if (validationException != null) { break; } } analyzerState = VERIFIED; } private int getThisRegister() { assert (encodedMethod.accessFlags & AccessFlags.STATIC.getValue()) == 0; CodeItem codeItem = encodedMethod.codeItem; assert codeItem != null; MethodIdItem methodIdItem = encodedMethod.method; assert methodIdItem != null; int totalRegisters = codeItem.getRegisterCount(); if (totalRegisters == 0) { throw new ValidationException("A non-static method must have at least 1 register"); } int parameterRegisters = methodIdItem.getPrototype().getParameterRegisterCount(); return totalRegisters - parameterRegisters - 1; } private boolean isInstanceConstructor() { return (encodedMethod.accessFlags & AccessFlags.STATIC.getValue()) == 0 && (encodedMethod.accessFlags & AccessFlags.CONSTRUCTOR.getValue()) != 0; } private boolean isStaticConstructor() { return (encodedMethod.accessFlags & AccessFlags.STATIC.getValue()) != 0 && (encodedMethod.accessFlags & AccessFlags.CONSTRUCTOR.getValue()) != 0; } public AnalyzedInstruction getStartOfMethod() { return startOfMethod; } /** * @return a read-only list containing the instructions for tihs method. */ public List<AnalyzedInstruction> getInstructions() { return instructions.getValues(); } public ClassDataItem.EncodedMethod getMethod() { return this.encodedMethod; } public ValidationException getValidationException() { return validationException; } private static RegisterType[] getParameterTypes(TypeListItem typeListItem, int parameterRegisterCount) { assert typeListItem != null; assert parameterRegisterCount == typeListItem.getRegisterCount(); RegisterType[] registerTypes = new RegisterType[parameterRegisterCount]; int registerNum = 0; for (TypeIdItem type: typeListItem.getTypes()) { if (type.getRegisterCount() == 2) { registerTypes[registerNum++] = RegisterType.getWideRegisterTypeForTypeIdItem(type, true); registerTypes[registerNum++] = RegisterType.getWideRegisterTypeForTypeIdItem(type, false); } else { registerTypes[registerNum++] = RegisterType.getRegisterTypeForTypeIdItem(type); } } return registerTypes; } public int getInstructionAddress(AnalyzedInstruction instruction) { return instructions.keyAt(instruction.instructionIndex); } private void setDestinationRegisterTypeAndPropagateChanges(AnalyzedInstruction analyzedInstruction, RegisterType registerType) { setPostRegisterTypeAndPropagateChanges(analyzedInstruction, analyzedInstruction.getDestinationRegister(), registerType); } private void setPostRegisterTypeAndPropagateChanges(AnalyzedInstruction analyzedInstruction, int registerNumber, RegisterType registerType) { BitSet changedInstructions = new BitSet(instructions.size()); if (!analyzedInstruction.setPostRegisterType(registerNumber, registerType)) { return; } propagateRegisterToSuccessors(analyzedInstruction, registerNumber, changedInstructions); //Using a for loop inside the while loop optimizes for the common case of the successors of an instruction //occurring after the instruction. Any successors that occur prior to the instruction will be picked up on //the next iteration of the while loop. //This could also be done recursively, but in large methods it would likely cause very deep recursion, //which requires the user to specify a larger stack size. This isn't really a problem, but it is slightly //annoying. while (!changedInstructions.isEmpty()) { for (int instructionIndex=changedInstructions.nextSetBit(0); instructionIndex>=0; instructionIndex=changedInstructions.nextSetBit(instructionIndex+1)) { changedInstructions.clear(instructionIndex); propagateRegisterToSuccessors(instructions.valueAt(instructionIndex), registerNumber, changedInstructions); } } if (registerType.category == RegisterType.Category.LongLo) { checkWidePair(registerNumber, analyzedInstruction); setPostRegisterTypeAndPropagateChanges(analyzedInstruction, registerNumber+1, RegisterType.getRegisterType(RegisterType.Category.LongHi, null)); } else if (registerType.category == RegisterType.Category.DoubleLo) { checkWidePair(registerNumber, analyzedInstruction); setPostRegisterTypeAndPropagateChanges(analyzedInstruction, registerNumber+1, RegisterType.getRegisterType(RegisterType.Category.DoubleHi, null)); } } private void propagateRegisterToSuccessors(AnalyzedInstruction instruction, int registerNumber, BitSet changedInstructions) { RegisterType postRegisterType = instruction.getPostInstructionRegisterType(registerNumber); for (AnalyzedInstruction successor: instruction.successors) { if (successor.mergeRegister(registerNumber, postRegisterType, analyzedInstructions)) { changedInstructions.set(successor.instructionIndex); } } } private void buildInstructionList() { assert encodedMethod != null; assert encodedMethod.codeItem != null; int registerCount = encodedMethod.codeItem.getRegisterCount(); Instruction[] insns = encodedMethod.codeItem.getInstructions(); instructions = new SparseArray<AnalyzedInstruction>(insns.length); //first, create all the instructions and populate the instructionAddresses array int currentCodeAddress = 0; for (int i=0; i<insns.length; i++) { instructions.append(currentCodeAddress, new AnalyzedInstruction(insns[i], i, registerCount)); assert instructions.indexOfKey(currentCodeAddress) == i; currentCodeAddress += insns[i].getSize(currentCodeAddress); } //next, populate the exceptionHandlers array. The array item for each instruction that can throw an exception //and is covered by a try block should be set to a list of the first instructions of each exception handler //for the try block covering the instruction CodeItem.TryItem[] tries = encodedMethod.codeItem.getTries(); int triesIndex = 0; CodeItem.TryItem currentTry = null; AnalyzedInstruction[] currentExceptionHandlers = null; AnalyzedInstruction[][] exceptionHandlers = new AnalyzedInstruction[insns.length][]; if (tries != null) { for (int i=0; i<instructions.size(); i++) { AnalyzedInstruction instruction = instructions.valueAt(i); Opcode instructionOpcode = instruction.instruction.opcode; currentCodeAddress = getInstructionAddress(instruction); //check if we have gone past the end of the current try if (currentTry != null) { if (currentTry.getStartCodeAddress() + currentTry.getTryLength() <= currentCodeAddress) { currentTry = null; triesIndex++; } } //check if the next try is applicable yet if (currentTry == null && triesIndex < tries.length) { CodeItem.TryItem tryItem = tries[triesIndex]; if (tryItem.getStartCodeAddress() <= currentCodeAddress) { assert(tryItem.getStartCodeAddress() + tryItem.getTryLength() > currentCodeAddress); currentTry = tryItem; currentExceptionHandlers = buildExceptionHandlerArray(tryItem); } } //if we're inside a try block, and the instruction can throw an exception, then add the exception handlers //for the current instruction if (currentTry != null && instructionOpcode.canThrow()) { exceptionHandlers[i] = currentExceptionHandlers; } } } //finally, populate the successors and predecessors for each instruction. We start at the fake "StartOfMethod" //instruction and follow the execution path. Any unreachable code won't have any predecessors or successors, //and no reachable code will have an unreachable predessor or successor assert instructions.size() > 0; BitSet instructionsToProcess = new BitSet(insns.length); addPredecessorSuccessor(startOfMethod, instructions.valueAt(0), exceptionHandlers, instructionsToProcess); while (!instructionsToProcess.isEmpty()) { int currentInstructionIndex = instructionsToProcess.nextSetBit(0); instructionsToProcess.clear(currentInstructionIndex); AnalyzedInstruction instruction = instructions.valueAt(currentInstructionIndex); Opcode instructionOpcode = instruction.instruction.opcode; int instructionCodeAddress = getInstructionAddress(instruction); if (instruction.instruction.opcode.canContinue()) { if (instruction.instruction.opcode != Opcode.NOP || !instruction.instruction.getFormat().variableSizeFormat) { if (currentInstructionIndex == instructions.size() - 1) { throw new ValidationException("Execution can continue past the last instruction"); } AnalyzedInstruction nextInstruction = instructions.valueAt(currentInstructionIndex+1); addPredecessorSuccessor(instruction, nextInstruction, exceptionHandlers, instructionsToProcess); } } if (instruction.instruction instanceof OffsetInstruction) { OffsetInstruction offsetInstruction = (OffsetInstruction)instruction.instruction; if (instructionOpcode == Opcode.PACKED_SWITCH || instructionOpcode == Opcode.SPARSE_SWITCH) { MultiOffsetInstruction switchDataInstruction = (MultiOffsetInstruction)instructions.get(instructionCodeAddress + offsetInstruction.getTargetAddressOffset()).instruction; for (int targetAddressOffset: switchDataInstruction.getTargets()) { AnalyzedInstruction targetInstruction = instructions.get(instructionCodeAddress + targetAddressOffset); addPredecessorSuccessor(instruction, targetInstruction, exceptionHandlers, instructionsToProcess); } } else { int targetAddressOffset = offsetInstruction.getTargetAddressOffset(); AnalyzedInstruction targetInstruction = instructions.get(instructionCodeAddress + targetAddressOffset); addPredecessorSuccessor(instruction, targetInstruction, exceptionHandlers, instructionsToProcess); } } } } private void addPredecessorSuccessor(AnalyzedInstruction predecessor, AnalyzedInstruction successor, AnalyzedInstruction[][] exceptionHandlers, BitSet instructionsToProcess) { addPredecessorSuccessor(predecessor, successor, exceptionHandlers, instructionsToProcess, false); } private void addPredecessorSuccessor(AnalyzedInstruction predecessor, AnalyzedInstruction successor, AnalyzedInstruction[][] exceptionHandlers, BitSet instructionsToProcess, boolean allowMoveException) { if (!allowMoveException && successor.instruction.opcode == Opcode.MOVE_EXCEPTION) { throw new ValidationException("Execution can pass from the " + predecessor.instruction.opcode.name + " instruction at code address 0x" + Integer.toHexString(getInstructionAddress(predecessor)) + " to the move-exception instruction at address 0x" + Integer.toHexString(getInstructionAddress(successor))); } if (!successor.addPredecessor(predecessor)) { return; } predecessor.addSuccessor(successor); instructionsToProcess.set(successor.getInstructionIndex()); //if the successor can throw an instruction, then we need to add the exception handlers as additional //successors to the predecessor (and then apply this same logic recursively if needed) //Technically, we should handle the monitor-exit instruction as a special case. The exception is actually //thrown *after* the instruction executes, instead of "before" the instruction executes, lke for any other //instruction. But since it doesn't modify any registers, we can treat it like any other instruction. AnalyzedInstruction[] exceptionHandlersForSuccessor = exceptionHandlers[successor.instructionIndex]; if (exceptionHandlersForSuccessor != null) { //the item for this instruction in exceptionHandlersForSuccessor should only be set if this instruction //can throw an exception assert successor.instruction.opcode.canThrow(); for (AnalyzedInstruction exceptionHandler: exceptionHandlersForSuccessor) { addPredecessorSuccessor(predecessor, exceptionHandler, exceptionHandlers, instructionsToProcess, true); } } } private AnalyzedInstruction[] buildExceptionHandlerArray(CodeItem.TryItem tryItem) { int exceptionHandlerCount = tryItem.encodedCatchHandler.handlers.length; int catchAllHandler = tryItem.encodedCatchHandler.getCatchAllHandlerAddress(); if (catchAllHandler != -1) { exceptionHandlerCount++; } AnalyzedInstruction[] exceptionHandlers = new AnalyzedInstruction[exceptionHandlerCount]; for (int i=0; i<tryItem.encodedCatchHandler.handlers.length; i++) { exceptionHandlers[i] = instructions.get(tryItem.encodedCatchHandler.handlers[i].getHandlerAddress()); } if (catchAllHandler != -1) { exceptionHandlers[exceptionHandlers.length - 1] = instructions.get(catchAllHandler); } return exceptionHandlers; } /** * @return false if analyzedInstruction is an odex instruction that couldn't be deodexed, due to its * object register being null */ private boolean analyzeInstruction(AnalyzedInstruction analyzedInstruction) { Instruction instruction = analyzedInstruction.instruction; switch (instruction.opcode) { case NOP: return true; case MOVE: case MOVE_FROM16: case MOVE_16: case MOVE_WIDE: case MOVE_WIDE_FROM16: case MOVE_WIDE_16: case MOVE_OBJECT: case MOVE_OBJECT_FROM16: case MOVE_OBJECT_16: analyzeMove(analyzedInstruction); return true; case MOVE_RESULT: case MOVE_RESULT_WIDE: case MOVE_RESULT_OBJECT: analyzeMoveResult(analyzedInstruction); return true; case MOVE_EXCEPTION: analyzeMoveException(analyzedInstruction); return true; case RETURN_VOID: case RETURN: case RETURN_WIDE: case RETURN_OBJECT: return true; case RETURN_VOID_BARRIER: analyzeReturnVoidBarrier(analyzedInstruction); return true; case CONST_4: case CONST_16: case CONST: analyzeConst(analyzedInstruction); return true; case CONST_HIGH16: analyzeConstHigh16(analyzedInstruction); return true; case CONST_WIDE_16: case CONST_WIDE_32: case CONST_WIDE: case CONST_WIDE_HIGH16: analyzeWideConst(analyzedInstruction); return true; case CONST_STRING: case CONST_STRING_JUMBO: analyzeConstString(analyzedInstruction); return true; case CONST_CLASS: case CONST_CLASS_JUMBO: analyzeConstClass(analyzedInstruction); return true; case MONITOR_ENTER: case MONITOR_EXIT: return true; case CHECK_CAST: case CHECK_CAST_JUMBO: analyzeCheckCast(analyzedInstruction); return true; case INSTANCE_OF: case INSTANCE_OF_JUMBO: analyzeInstanceOf(analyzedInstruction); return true; case ARRAY_LENGTH: analyzeArrayLength(analyzedInstruction); return true; case NEW_INSTANCE: case NEW_INSTANCE_JUMBO: analyzeNewInstance(analyzedInstruction); return true; case NEW_ARRAY: case NEW_ARRAY_JUMBO: analyzeNewArray(analyzedInstruction); return true; case FILLED_NEW_ARRAY: case FILLED_NEW_ARRAY_RANGE: case FILLED_NEW_ARRAY_JUMBO: return true; case FILL_ARRAY_DATA: analyzeArrayDataOrSwitch(analyzedInstruction); case THROW: case GOTO: case GOTO_16: case GOTO_32: return true; case PACKED_SWITCH: case SPARSE_SWITCH: analyzeArrayDataOrSwitch(analyzedInstruction); return true; case CMPL_FLOAT: case CMPG_FLOAT: case CMPL_DOUBLE: case CMPG_DOUBLE: case CMP_LONG: analyzeFloatWideCmp(analyzedInstruction); return true; case IF_EQ: case IF_NE: case IF_LT: case IF_GE: case IF_GT: case IF_LE: case IF_EQZ: case IF_NEZ: case IF_LTZ: case IF_GEZ: case IF_GTZ: case IF_LEZ: return true; case AGET: analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Integer); return true; case AGET_BOOLEAN: analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Boolean); return true; case AGET_BYTE: analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Byte); return true; case AGET_CHAR: analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Char); return true; case AGET_SHORT: analyze32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Short); return true; case AGET_WIDE: analyzeAgetWide(analyzedInstruction); return true; case AGET_OBJECT: analyzeAgetObject(analyzedInstruction); return true; case APUT: case APUT_BOOLEAN: case APUT_BYTE: case APUT_CHAR: case APUT_SHORT: case APUT_WIDE: case APUT_OBJECT: return true; case IGET: case IGET_JUMBO: analyze32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Integer); return true; case IGET_BOOLEAN: case IGET_BOOLEAN_JUMBO: analyze32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Boolean); return true; case IGET_BYTE: case IGET_BYTE_JUMBO: analyze32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Byte); return true; case IGET_CHAR: case IGET_CHAR_JUMBO: analyze32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Char); return true; case IGET_SHORT: case IGET_SHORT_JUMBO: analyze32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Short); return true; case IGET_WIDE: case IGET_WIDE_JUMBO: case IGET_OBJECT: case IGET_OBJECT_JUMBO: analyzeIgetWideObject(analyzedInstruction); return true; case IPUT: case IPUT_JUMBO: case IPUT_BOOLEAN: case IPUT_BOOLEAN_JUMBO: case IPUT_BYTE: case IPUT_BYTE_JUMBO: case IPUT_CHAR: case IPUT_CHAR_JUMBO: case IPUT_SHORT: case IPUT_SHORT_JUMBO: case IPUT_WIDE: case IPUT_WIDE_JUMBO: case IPUT_OBJECT: case IPUT_OBJECT_JUMBO: return true; case SGET: case SGET_JUMBO: analyze32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Integer); return true; case SGET_BOOLEAN: case SGET_BOOLEAN_JUMBO: analyze32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Boolean); return true; case SGET_BYTE: case SGET_BYTE_JUMBO: analyze32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Byte); return true; case SGET_CHAR: case SGET_CHAR_JUMBO: analyze32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Char); return true; case SGET_SHORT: case SGET_SHORT_JUMBO: analyze32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Short); return true; case SGET_WIDE: case SGET_WIDE_JUMBO: case SGET_OBJECT: case SGET_OBJECT_JUMBO: analyzeSgetWideObject(analyzedInstruction); return true; case SPUT: case SPUT_JUMBO: case SPUT_BOOLEAN: case SPUT_BOOLEAN_JUMBO: case SPUT_BYTE: case SPUT_BYTE_JUMBO: case SPUT_CHAR: case SPUT_CHAR_JUMBO: case SPUT_SHORT: case SPUT_SHORT_JUMBO: case SPUT_WIDE: case SPUT_WIDE_JUMBO: case SPUT_OBJECT: case SPUT_OBJECT_JUMBO: return true; case INVOKE_VIRTUAL: case INVOKE_SUPER: return true; case INVOKE_DIRECT: analyzeInvokeDirect(analyzedInstruction); return true; case INVOKE_STATIC: case INVOKE_INTERFACE: case INVOKE_VIRTUAL_RANGE: case INVOKE_VIRTUAL_JUMBO: case INVOKE_SUPER_RANGE: case INVOKE_SUPER_JUMBO: return true; case INVOKE_DIRECT_RANGE: case INVOKE_DIRECT_JUMBO: analyzeInvokeDirectRange(analyzedInstruction); return true; case INVOKE_STATIC_RANGE: case INVOKE_STATIC_JUMBO: case INVOKE_INTERFACE_RANGE: case INVOKE_INTERFACE_JUMBO: return true; case NEG_INT: case NOT_INT: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Integer); return true; case NEG_LONG: case NOT_LONG: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.LongLo); return true; case NEG_FLOAT: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Float); return true; case NEG_DOUBLE: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.DoubleLo); return true; case INT_TO_LONG: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.LongLo); return true; case INT_TO_FLOAT: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Float); return true; case INT_TO_DOUBLE: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.DoubleLo); return true; case LONG_TO_INT: case DOUBLE_TO_INT: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Integer); return true; case LONG_TO_FLOAT: case DOUBLE_TO_FLOAT: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Float); return true; case LONG_TO_DOUBLE: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.DoubleLo); return true; case FLOAT_TO_INT: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Integer); return true; case FLOAT_TO_LONG: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.LongLo); return true; case FLOAT_TO_DOUBLE: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.DoubleLo); return true; case DOUBLE_TO_LONG: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.LongLo); return true; case INT_TO_BYTE: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Byte); return true; case INT_TO_CHAR: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Char); return true; case INT_TO_SHORT: analyzeUnaryOp(analyzedInstruction, RegisterType.Category.Short); return true; case ADD_INT: case SUB_INT: case MUL_INT: case DIV_INT: case REM_INT: case SHL_INT: case SHR_INT: case USHR_INT: analyzeBinaryOp(analyzedInstruction, RegisterType.Category.Integer, false); return true; case AND_INT: case OR_INT: case XOR_INT: analyzeBinaryOp(analyzedInstruction, RegisterType.Category.Integer, true); return true; case ADD_LONG: case SUB_LONG: case MUL_LONG: case DIV_LONG: case REM_LONG: case AND_LONG: case OR_LONG: case XOR_LONG: case SHL_LONG: case SHR_LONG: case USHR_LONG: analyzeBinaryOp(analyzedInstruction, RegisterType.Category.LongLo, false); return true; case ADD_FLOAT: case SUB_FLOAT: case MUL_FLOAT: case DIV_FLOAT: case REM_FLOAT: analyzeBinaryOp(analyzedInstruction, RegisterType.Category.Float, false); return true; case ADD_DOUBLE: case SUB_DOUBLE: case MUL_DOUBLE: case DIV_DOUBLE: case REM_DOUBLE: analyzeBinaryOp(analyzedInstruction, RegisterType.Category.DoubleLo, false); return true; case ADD_INT_2ADDR: case SUB_INT_2ADDR: case MUL_INT_2ADDR: case DIV_INT_2ADDR: case REM_INT_2ADDR: case SHL_INT_2ADDR: case SHR_INT_2ADDR: case USHR_INT_2ADDR: analyzeBinary2AddrOp(analyzedInstruction, RegisterType.Category.Integer, false); return true; case AND_INT_2ADDR: case OR_INT_2ADDR: case XOR_INT_2ADDR: analyzeBinary2AddrOp(analyzedInstruction, RegisterType.Category.Integer, true); return true; case ADD_LONG_2ADDR: case SUB_LONG_2ADDR: case MUL_LONG_2ADDR: case DIV_LONG_2ADDR: case REM_LONG_2ADDR: case AND_LONG_2ADDR: case OR_LONG_2ADDR: case XOR_LONG_2ADDR: case SHL_LONG_2ADDR: case SHR_LONG_2ADDR: case USHR_LONG_2ADDR: analyzeBinary2AddrOp(analyzedInstruction, RegisterType.Category.LongLo, false); return true; case ADD_FLOAT_2ADDR: case SUB_FLOAT_2ADDR: case MUL_FLOAT_2ADDR: case DIV_FLOAT_2ADDR: case REM_FLOAT_2ADDR: analyzeBinary2AddrOp(analyzedInstruction, RegisterType.Category.Float, false); return true; case ADD_DOUBLE_2ADDR: case SUB_DOUBLE_2ADDR: case MUL_DOUBLE_2ADDR: case DIV_DOUBLE_2ADDR: case REM_DOUBLE_2ADDR: analyzeBinary2AddrOp(analyzedInstruction, RegisterType.Category.DoubleLo, false); return true; case ADD_INT_LIT16: case RSUB_INT: case MUL_INT_LIT16: case DIV_INT_LIT16: case REM_INT_LIT16: analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.Category.Integer, false); return true; case AND_INT_LIT16: case OR_INT_LIT16: case XOR_INT_LIT16: analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.Category.Integer, true); return true; case ADD_INT_LIT8: case RSUB_INT_LIT8: case MUL_INT_LIT8: case DIV_INT_LIT8: case REM_INT_LIT8: case SHL_INT_LIT8: analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.Category.Integer, false); return true; case AND_INT_LIT8: case OR_INT_LIT8: case XOR_INT_LIT8: analyzeLiteralBinaryOp(analyzedInstruction, RegisterType.Category.Integer, true); return true; case SHR_INT_LIT8: analyzeLiteralBinaryOp(analyzedInstruction, getDestTypeForLiteralShiftRight(analyzedInstruction, true), false); return true; case USHR_INT_LIT8: analyzeLiteralBinaryOp(analyzedInstruction, getDestTypeForLiteralShiftRight(analyzedInstruction, false), false); return true; /*odexed instructions*/ case IGET_VOLATILE: case IPUT_VOLATILE: case SGET_VOLATILE: case SPUT_VOLATILE: case IGET_OBJECT_VOLATILE: case IGET_WIDE_VOLATILE: case IPUT_WIDE_VOLATILE: case SGET_WIDE_VOLATILE: case SPUT_WIDE_VOLATILE: analyzePutGetVolatile(analyzedInstruction); return true; case THROW_VERIFICATION_ERROR: return true; case EXECUTE_INLINE: analyzeExecuteInline(analyzedInstruction); return true; case EXECUTE_INLINE_RANGE: analyzeExecuteInlineRange(analyzedInstruction); return true; case INVOKE_DIRECT_EMPTY: analyzeInvokeDirectEmpty(analyzedInstruction); return true; case INVOKE_OBJECT_INIT_RANGE: analyzeInvokeObjectInitRange(analyzedInstruction); return true; case IGET_QUICK: case IGET_WIDE_QUICK: case IGET_OBJECT_QUICK: case IPUT_QUICK: case IPUT_WIDE_QUICK: case IPUT_OBJECT_QUICK: return analyzeIputIgetQuick(analyzedInstruction); case INVOKE_VIRTUAL_QUICK: return analyzeInvokeVirtualQuick(analyzedInstruction, false, false); case INVOKE_SUPER_QUICK: return analyzeInvokeVirtualQuick(analyzedInstruction, true, false); case INVOKE_VIRTUAL_QUICK_RANGE: return analyzeInvokeVirtualQuick(analyzedInstruction, false, true); case INVOKE_SUPER_QUICK_RANGE: return analyzeInvokeVirtualQuick(analyzedInstruction, true, true); case IPUT_OBJECT_VOLATILE: case SGET_OBJECT_VOLATILE: case SPUT_OBJECT_VOLATILE: analyzePutGetVolatile(analyzedInstruction); return true; case INVOKE_OBJECT_INIT_JUMBO: analyzeInvokeObjectInitJumbo(analyzedInstruction); return true; case IGET_VOLATILE_JUMBO: case IGET_WIDE_VOLATILE_JUMBO: case IGET_OBJECT_VOLATILE_JUMBO: case IPUT_VOLATILE_JUMBO: case IPUT_WIDE_VOLATILE_JUMBO: case IPUT_OBJECT_VOLATILE_JUMBO: case SGET_VOLATILE_JUMBO: case SGET_WIDE_VOLATILE_JUMBO: case SGET_OBJECT_VOLATILE_JUMBO: case SPUT_VOLATILE_JUMBO: case SPUT_WIDE_VOLATILE_JUMBO: case SPUT_OBJECT_VOLATILE_JUMBO: analyzePutGetVolatile(analyzedInstruction); return true; default: assert false; return true; } } private void verifyInstruction(AnalyzedInstruction analyzedInstruction) { Instruction instruction = analyzedInstruction.instruction; switch (instruction.opcode) { case NOP: return; case MOVE: case MOVE_FROM16: case MOVE_16: verifyMove(analyzedInstruction, Primitive32BitCategories); return; case MOVE_WIDE: case MOVE_WIDE_FROM16: case MOVE_WIDE_16: verifyMove(analyzedInstruction, WideLowCategories); return; case MOVE_OBJECT: case MOVE_OBJECT_FROM16: case MOVE_OBJECT_16: verifyMove(analyzedInstruction, ReferenceOrUninitCategories); return; case MOVE_RESULT: verifyMoveResult(analyzedInstruction, Primitive32BitCategories); return; case MOVE_RESULT_WIDE: verifyMoveResult(analyzedInstruction, WideLowCategories); return; case MOVE_RESULT_OBJECT: verifyMoveResult(analyzedInstruction, ReferenceCategories); return; case MOVE_EXCEPTION: verifyMoveException(analyzedInstruction); return; case RETURN_VOID: case RETURN_VOID_BARRIER: verifyReturnVoid(analyzedInstruction); return; case RETURN: verifyReturn(analyzedInstruction, Primitive32BitCategories); return; case RETURN_WIDE: verifyReturn(analyzedInstruction, WideLowCategories); return; case RETURN_OBJECT: verifyReturn(analyzedInstruction, ReferenceCategories); return; case CONST_4: case CONST_16: case CONST: case CONST_HIGH16: case CONST_WIDE_16: case CONST_WIDE_32: case CONST_WIDE: case CONST_WIDE_HIGH16: case CONST_STRING: case CONST_STRING_JUMBO: return; case CONST_CLASS: case CONST_CLASS_JUMBO: verifyConstClass(analyzedInstruction); return; case MONITOR_ENTER: case MONITOR_EXIT: verifyMonitor(analyzedInstruction); return; case CHECK_CAST: case CHECK_CAST_JUMBO: verifyCheckCast(analyzedInstruction); return; case INSTANCE_OF: case INSTANCE_OF_JUMBO: verifyInstanceOf(analyzedInstruction); return; case ARRAY_LENGTH: verifyArrayLength(analyzedInstruction); return; case NEW_INSTANCE: case NEW_INSTANCE_JUMBO: verifyNewInstance(analyzedInstruction); return; case NEW_ARRAY: verifyNewArray(analyzedInstruction); return; case FILLED_NEW_ARRAY: verifyFilledNewArray(analyzedInstruction); return; case FILLED_NEW_ARRAY_RANGE: verifyFilledNewArrayRange(analyzedInstruction); return; case FILL_ARRAY_DATA: verifyFillArrayData(analyzedInstruction); return; case THROW: verifyThrow(analyzedInstruction); return; case GOTO: case GOTO_16: case GOTO_32: return; case PACKED_SWITCH: verifySwitch(analyzedInstruction, Format.PackedSwitchData); return; case SPARSE_SWITCH: verifySwitch(analyzedInstruction, Format.SparseSwitchData); return; case CMPL_FLOAT: case CMPG_FLOAT: verifyFloatWideCmp(analyzedInstruction, Primitive32BitCategories); return; case CMPL_DOUBLE: case CMPG_DOUBLE: case CMP_LONG: verifyFloatWideCmp(analyzedInstruction, WideLowCategories); return; case IF_EQ: case IF_NE: verifyIfEqNe(analyzedInstruction); return; case IF_LT: case IF_GE: case IF_GT: case IF_LE: verifyIf(analyzedInstruction); return; case IF_EQZ: case IF_NEZ: verifyIfEqzNez(analyzedInstruction); return; case IF_LTZ: case IF_GEZ: case IF_GTZ: case IF_LEZ: verifyIfz(analyzedInstruction); return; case AGET: verify32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Integer); return; case AGET_BOOLEAN: verify32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Boolean); return; case AGET_BYTE: verify32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Byte); return; case AGET_CHAR: verify32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Char); return; case AGET_SHORT: verify32BitPrimitiveAget(analyzedInstruction, RegisterType.Category.Short); return; case AGET_WIDE: verifyAgetWide(analyzedInstruction); return; case AGET_OBJECT: verifyAgetObject(analyzedInstruction); return; case APUT: verify32BitPrimitiveAput(analyzedInstruction, RegisterType.Category.Integer); return; case APUT_BOOLEAN: verify32BitPrimitiveAput(analyzedInstruction, RegisterType.Category.Boolean); return; case APUT_BYTE: verify32BitPrimitiveAput(analyzedInstruction, RegisterType.Category.Byte); return; case APUT_CHAR: verify32BitPrimitiveAput(analyzedInstruction, RegisterType.Category.Char); return; case APUT_SHORT: verify32BitPrimitiveAput(analyzedInstruction, RegisterType.Category.Short); return; case APUT_WIDE: verifyAputWide(analyzedInstruction); return; case APUT_OBJECT: verifyAputObject(analyzedInstruction); return; case IGET: verify32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Integer); return; case IGET_BOOLEAN: verify32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Boolean); return; case IGET_BYTE: verify32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Byte); return; case IGET_CHAR: verify32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Char); return; case IGET_SHORT: verify32BitPrimitiveIget(analyzedInstruction, RegisterType.Category.Short); return; case IGET_WIDE: verifyIgetWide(analyzedInstruction); return; case IGET_OBJECT: verifyIgetObject(analyzedInstruction); return; case IPUT: verify32BitPrimitiveIput(analyzedInstruction, RegisterType.Category.Integer); return; case IPUT_BOOLEAN: verify32BitPrimitiveIput(analyzedInstruction, RegisterType.Category.Boolean); return; case IPUT_BYTE: verify32BitPrimitiveIput(analyzedInstruction, RegisterType.Category.Byte); return; case IPUT_CHAR: verify32BitPrimitiveIput(analyzedInstruction, RegisterType.Category.Char); return; case IPUT_SHORT: verify32BitPrimitiveIput(analyzedInstruction, RegisterType.Category.Short); return; case IPUT_WIDE: verifyIputWide(analyzedInstruction); return; case IPUT_OBJECT: verifyIputObject(analyzedInstruction); return; case SGET: verify32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Integer); return; case SGET_BOOLEAN: verify32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Boolean); return; case SGET_BYTE: verify32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Byte); return; case SGET_CHAR: verify32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Char); return; case SGET_SHORT: verify32BitPrimitiveSget(analyzedInstruction, RegisterType.Category.Short); return; case SGET_WIDE: verifySgetWide(analyzedInstruction); return; case SGET_OBJECT: verifySgetObject(analyzedInstruction); return; case SPUT: verify32BitPrimitiveSput(analyzedInstruction, RegisterType.Category.Integer); return; case SPUT_BOOLEAN: verify32BitPrimitiveSput(analyzedInstruction, RegisterType.Category.Boolean); return; case SPUT_BYTE: verify32BitPrimitiveSput(analyzedInstruction, RegisterType.Category.Byte); return; case SPUT_CHAR: verify32BitPrimitiveSput(analyzedInstruction, RegisterType.Category.Char); return; case SPUT_SHORT: verify32BitPrimitiveSput(analyzedInstruction, RegisterType.Category.Short); return; case SPUT_WIDE: verifySputWide(analyzedInstruction); return; case SPUT_OBJECT: verifySputObject(analyzedInstruction); return; case INVOKE_VIRTUAL: verifyInvoke(analyzedInstruction, INVOKE_VIRTUAL); return; case INVOKE_SUPER: verifyInvoke(analyzedInstruction, INVOKE_SUPER); return; case INVOKE_DIRECT: verifyInvoke(analyzedInstruction, INVOKE_DIRECT); return; case INVOKE_STATIC: verifyInvoke(analyzedInstruction, INVOKE_STATIC); return; case INVOKE_INTERFACE: verifyInvoke(analyzedInstruction, INVOKE_INTERFACE); return; case INVOKE_VIRTUAL_RANGE: verifyInvokeRange(analyzedInstruction, INVOKE_VIRTUAL); return; case INVOKE_SUPER_RANGE: verifyInvokeRange(analyzedInstruction, INVOKE_SUPER); return; case INVOKE_DIRECT_RANGE: verifyInvokeRange(analyzedInstruction, INVOKE_DIRECT); return; case INVOKE_STATIC_RANGE: verifyInvokeRange(analyzedInstruction, INVOKE_STATIC); return; case INVOKE_INTERFACE_RANGE: verifyInvokeRange(analyzedInstruction, INVOKE_INTERFACE); return; case NEG_INT: case NOT_INT: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case NEG_LONG: case NOT_LONG: verifyUnaryOp(analyzedInstruction, WideLowCategories); return; case NEG_FLOAT: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case NEG_DOUBLE: verifyUnaryOp(analyzedInstruction, WideLowCategories); return; case INT_TO_LONG: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case INT_TO_FLOAT: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case INT_TO_DOUBLE: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case LONG_TO_INT: case DOUBLE_TO_INT: verifyUnaryOp(analyzedInstruction, WideLowCategories); return; case LONG_TO_FLOAT: case DOUBLE_TO_FLOAT: verifyUnaryOp(analyzedInstruction, WideLowCategories); return; case LONG_TO_DOUBLE: verifyUnaryOp(analyzedInstruction, WideLowCategories); return; case FLOAT_TO_INT: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case FLOAT_TO_LONG: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case FLOAT_TO_DOUBLE: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case DOUBLE_TO_LONG: verifyUnaryOp(analyzedInstruction, WideLowCategories); return; case INT_TO_BYTE: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case INT_TO_CHAR: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case INT_TO_SHORT: verifyUnaryOp(analyzedInstruction, Primitive32BitCategories); return; case ADD_INT: case SUB_INT: case MUL_INT: case DIV_INT: case REM_INT: case SHL_INT: case SHR_INT: case USHR_INT: case AND_INT: case OR_INT: case XOR_INT: verifyBinaryOp(analyzedInstruction, Primitive32BitCategories, Primitive32BitCategories); return; case ADD_LONG: case SUB_LONG: case MUL_LONG: case DIV_LONG: case REM_LONG: case AND_LONG: case OR_LONG: case XOR_LONG: verifyBinaryOp(analyzedInstruction, WideLowCategories, WideLowCategories); return; case SHL_LONG: case SHR_LONG: case USHR_LONG: verifyBinaryOp(analyzedInstruction, WideLowCategories, Primitive32BitCategories); return; case ADD_FLOAT: case SUB_FLOAT: case MUL_FLOAT: case DIV_FLOAT: case REM_FLOAT: verifyBinaryOp(analyzedInstruction, Primitive32BitCategories, Primitive32BitCategories); return; case ADD_DOUBLE: case SUB_DOUBLE: case MUL_DOUBLE: case DIV_DOUBLE: case REM_DOUBLE: verifyBinaryOp(analyzedInstruction, WideLowCategories, WideLowCategories); return; case ADD_INT_2ADDR: case SUB_INT_2ADDR: case MUL_INT_2ADDR: case DIV_INT_2ADDR: case REM_INT_2ADDR: case SHL_INT_2ADDR: case SHR_INT_2ADDR: case USHR_INT_2ADDR: case AND_INT_2ADDR: case OR_INT_2ADDR: case XOR_INT_2ADDR: verifyBinary2AddrOp(analyzedInstruction, Primitive32BitCategories, Primitive32BitCategories); return; case ADD_LONG_2ADDR: case SUB_LONG_2ADDR: case MUL_LONG_2ADDR: case DIV_LONG_2ADDR: case REM_LONG_2ADDR: case AND_LONG_2ADDR: case OR_LONG_2ADDR: case XOR_LONG_2ADDR: verifyBinary2AddrOp(analyzedInstruction, WideLowCategories, WideLowCategories); return; case SHL_LONG_2ADDR: case SHR_LONG_2ADDR: case USHR_LONG_2ADDR: verifyBinary2AddrOp(analyzedInstruction, WideLowCategories, Primitive32BitCategories); return; case ADD_FLOAT_2ADDR: case SUB_FLOAT_2ADDR: case MUL_FLOAT_2ADDR: case DIV_FLOAT_2ADDR: case REM_FLOAT_2ADDR: verifyBinary2AddrOp(analyzedInstruction, Primitive32BitCategories, Primitive32BitCategories); return; case ADD_DOUBLE_2ADDR: case SUB_DOUBLE_2ADDR: case MUL_DOUBLE_2ADDR: case DIV_DOUBLE_2ADDR: case REM_DOUBLE_2ADDR: verifyBinary2AddrOp(analyzedInstruction, WideLowCategories, WideLowCategories); return; case ADD_INT_LIT16: case RSUB_INT: case MUL_INT_LIT16: case DIV_INT_LIT16: case REM_INT_LIT16: verifyLiteralBinaryOp(analyzedInstruction); return; case AND_INT_LIT16: case OR_INT_LIT16: case XOR_INT_LIT16: verifyLiteralBinaryOp(analyzedInstruction); return; case ADD_INT_LIT8: case RSUB_INT_LIT8: case MUL_INT_LIT8: case DIV_INT_LIT8: case REM_INT_LIT8: case SHL_INT_LIT8: verifyLiteralBinaryOp(analyzedInstruction); return; case AND_INT_LIT8: case OR_INT_LIT8: case XOR_INT_LIT8: verifyLiteralBinaryOp(analyzedInstruction); return; case SHR_INT_LIT8: verifyLiteralBinaryOp(analyzedInstruction); return; case USHR_INT_LIT8: verifyLiteralBinaryOp(analyzedInstruction); return; case IGET_VOLATILE: case IPUT_VOLATILE: case SGET_VOLATILE: case SPUT_VOLATILE: case IGET_OBJECT_VOLATILE: case IGET_WIDE_VOLATILE: case IPUT_WIDE_VOLATILE: case SGET_WIDE_VOLATILE: case SPUT_WIDE_VOLATILE: case THROW_VERIFICATION_ERROR: case EXECUTE_INLINE: case EXECUTE_INLINE_RANGE: case INVOKE_DIRECT_EMPTY: case INVOKE_OBJECT_INIT_RANGE: case IGET_QUICK: case IGET_WIDE_QUICK: case IGET_OBJECT_QUICK: case IPUT_QUICK: case IPUT_WIDE_QUICK: case IPUT_OBJECT_QUICK: case INVOKE_VIRTUAL_QUICK: case INVOKE_SUPER_QUICK: case INVOKE_VIRTUAL_QUICK_RANGE: case INVOKE_SUPER_QUICK_RANGE: case IPUT_OBJECT_VOLATILE: case SGET_OBJECT_VOLATILE: case SPUT_OBJECT_VOLATILE: case INVOKE_OBJECT_INIT_JUMBO: case IGET_VOLATILE_JUMBO: case IGET_WIDE_VOLATILE_JUMBO: case IGET_OBJECT_VOLATILE_JUMBO: case IPUT_VOLATILE_JUMBO: case IPUT_WIDE_VOLATILE_JUMBO: case IPUT_OBJECT_VOLATILE_JUMBO: case SGET_VOLATILE_JUMBO: case SGET_WIDE_VOLATILE_JUMBO: case SGET_OBJECT_VOLATILE_JUMBO: case SPUT_VOLATILE_JUMBO: case SPUT_WIDE_VOLATILE_JUMBO: case SPUT_OBJECT_VOLATILE_JUMBO: //TODO: throw validation exception? default: assert false; return; } } private static final EnumSet<RegisterType.Category> Primitive32BitCategories = EnumSet.of( RegisterType.Category.Null, RegisterType.Category.One, RegisterType.Category.Boolean, RegisterType.Category.Byte, RegisterType.Category.PosByte, RegisterType.Category.Short, RegisterType.Category.PosShort, RegisterType.Category.Char, RegisterType.Category.Integer, RegisterType.Category.Float); private static final EnumSet<RegisterType.Category> WideLowCategories = EnumSet.of( RegisterType.Category.LongLo, RegisterType.Category.DoubleLo); private static final EnumSet<RegisterType.Category> WideHighCategories = EnumSet.of( RegisterType.Category.LongHi, RegisterType.Category.DoubleHi); private static final EnumSet<RegisterType.Category> ReferenceCategories = EnumSet.of( RegisterType.Category.Null, RegisterType.Category.Reference); private static final EnumSet<RegisterType.Category> ReferenceOrUninitThisCategories = EnumSet.of( RegisterType.Category.Null, RegisterType.Category.UninitThis, RegisterType.Category.Reference); private static final EnumSet<RegisterType.Category> ReferenceOrUninitCategories = EnumSet.of( RegisterType.Category.Null, RegisterType.Category.UninitRef, RegisterType.Category.UninitThis, RegisterType.Category.Reference); private static final EnumSet<RegisterType.Category> ReferenceAndPrimitive32BitCategories = EnumSet.of( RegisterType.Category.Null, RegisterType.Category.One, RegisterType.Category.Boolean, RegisterType.Category.Byte, RegisterType.Category.PosByte, RegisterType.Category.Short, RegisterType.Category.PosShort, RegisterType.Category.Char, RegisterType.Category.Integer, RegisterType.Category.Float, RegisterType.Category.Reference); private static final EnumSet<RegisterType.Category> BooleanCategories = EnumSet.of( RegisterType.Category.Null, RegisterType.Category.One, RegisterType.Category.Boolean); private void analyzeMove(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType sourceRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, sourceRegisterType); } private void verifyMove(AnalyzedInstruction analyzedInstruction, EnumSet validCategories) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), validCategories); } private void analyzeMoveResult(AnalyzedInstruction analyzedInstruction) { AnalyzedInstruction previousInstruction = instructions.valueAt(analyzedInstruction.instructionIndex-1); if (!previousInstruction.instruction.opcode.setsResult()) { throw new ValidationException(analyzedInstruction.instruction.opcode.name + " must occur after an " + "invoke-*/fill-new-array instruction"); } RegisterType resultRegisterType; InstructionWithReference invokeInstruction = (InstructionWithReference)previousInstruction.instruction; Item item = invokeInstruction.getReferencedItem(); if (item.getItemType() == ItemType.TYPE_METHOD_ID_ITEM) { resultRegisterType = RegisterType.getRegisterTypeForTypeIdItem( ((MethodIdItem)item).getPrototype().getReturnType()); } else { assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; resultRegisterType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); } setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, resultRegisterType); } private void verifyMoveResult(AnalyzedInstruction analyzedInstruction, EnumSet<RegisterType.Category> allowedCategories) { if (analyzedInstruction.instructionIndex == 0) { throw new ValidationException(analyzedInstruction.instruction.opcode.name + " cannot be the first " + "instruction in a method. It must occur after an invoke-*/fill-new-array instruction"); } AnalyzedInstruction previousInstruction = instructions.valueAt(analyzedInstruction.instructionIndex-1); if (!previousInstruction.instruction.opcode.setsResult()) { throw new ValidationException(analyzedInstruction.instruction.opcode.name + " must occur after an " + "invoke-*/fill-new-array instruction"); } //TODO: does dalvik allow a move-result after an invoke with a void return type? RegisterType resultRegisterType; InstructionWithReference invokeInstruction = (InstructionWithReference)previousInstruction.getInstruction(); Item item = invokeInstruction.getReferencedItem(); if (item instanceof MethodIdItem) { resultRegisterType = RegisterType.getRegisterTypeForTypeIdItem( ((MethodIdItem)item).getPrototype().getReturnType()); } else { assert item instanceof TypeIdItem; resultRegisterType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); } if (!allowedCategories.contains(resultRegisterType.category)) { throw new ValidationException(String.format("Wrong move-result* instruction for return value %s", resultRegisterType.toString())); } } private void analyzeMoveException(AnalyzedInstruction analyzedInstruction) { CodeItem.TryItem[] tries = encodedMethod.codeItem.getTries(); int instructionAddress = getInstructionAddress(analyzedInstruction); if (tries == null) { throw new ValidationException("move-exception must be the first instruction in an exception handler block"); } RegisterType exceptionType = null; for (CodeItem.TryItem tryItem: encodedMethod.codeItem.getTries()) { if (tryItem.encodedCatchHandler.getCatchAllHandlerAddress() == instructionAddress) { exceptionType = RegisterType.getRegisterType(RegisterType.Category.Reference, ClassPath.getClassDef("Ljava/lang/Throwable;")); break; } for (CodeItem.EncodedTypeAddrPair handler: tryItem.encodedCatchHandler.handlers) { if (handler.getHandlerAddress() == instructionAddress) { exceptionType = RegisterType.getRegisterTypeForTypeIdItem(handler.exceptionType) .merge(exceptionType); } } } if (exceptionType == null) { throw new ValidationException("move-exception must be the first instruction in an exception handler block"); } setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, exceptionType); } private void verifyMoveException(AnalyzedInstruction analyzedInstruction) { CodeItem.TryItem[] tries = encodedMethod.codeItem.getTries(); int instructionAddress = getInstructionAddress(analyzedInstruction); if (tries == null) { throw new ValidationException("move-exception must be the first instruction in an exception handler block"); } RegisterType exceptionType = null; for (CodeItem.TryItem tryItem: encodedMethod.codeItem.getTries()) { if (tryItem.encodedCatchHandler.getCatchAllHandlerAddress() == instructionAddress) { exceptionType = RegisterType.getRegisterType(RegisterType.Category.Reference, ClassPath.getClassDef("Ljava/lang/Throwable;")); break; } for (CodeItem.EncodedTypeAddrPair handler: tryItem.encodedCatchHandler.handlers) { if (handler.getHandlerAddress() == instructionAddress) { exceptionType = RegisterType.getRegisterTypeForTypeIdItem(handler.exceptionType) .merge(exceptionType); } } } if (exceptionType == null) { throw new ValidationException("move-exception must be the first instruction in an exception handler block"); } //TODO: check if the type is a throwable. Should we throw a ValidationException or print a warning? (does dalvik validate that it's a throwable? It doesn't in CodeVerify.c, but it might check in DexSwapVerify.c) if (exceptionType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Exception type %s is not a reference type", exceptionType.toString())); } } private void analyzeReturnVoidBarrier(AnalyzedInstruction analyzedInstruction) { analyzeReturnVoidBarrier(analyzedInstruction, true); } private void analyzeReturnVoidBarrier(AnalyzedInstruction analyzedInstruction, boolean analyzeResult) { Instruction10x instruction = (Instruction10x)analyzedInstruction.instruction; Instruction10x deodexedInstruction = new Instruction10x(Opcode.RETURN_VOID); analyzedInstruction.setDeodexedInstruction(deodexedInstruction); if (analyzeResult) { analyzeInstruction(analyzedInstruction); } } private void verifyReturnVoid(AnalyzedInstruction analyzedInstruction) { TypeIdItem returnType = encodedMethod.method.getPrototype().getReturnType(); if (returnType.getTypeDescriptor().charAt(0) != 'V') { //TODO: could add which return-* variation should be used instead throw new ValidationException("Cannot use return-void with a non-void return type (" + returnType.getTypeDescriptor() + ")"); } } private void verifyReturn(AnalyzedInstruction analyzedInstruction, EnumSet validCategories) { /*if (this.isInstanceConstructor()) { checkConstructorReturn(analyzedInstruction); }*/ SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; int returnRegister = instruction.getRegisterA(); RegisterType returnRegisterType = getAndCheckSourceRegister(analyzedInstruction, returnRegister, validCategories); TypeIdItem returnType = encodedMethod.method.getPrototype().getReturnType(); if (returnType.getTypeDescriptor().charAt(0) == 'V') { throw new ValidationException("Cannot use return with a void return type. Use return-void instead"); } RegisterType methodReturnRegisterType = RegisterType.getRegisterTypeForTypeIdItem(returnType); if (!validCategories.contains(methodReturnRegisterType.category)) { //TODO: could add which return-* variation should be used instead throw new ValidationException(String.format("Cannot use %s with return type %s", analyzedInstruction.instruction.opcode.name, returnType.getTypeDescriptor())); } if (validCategories == ReferenceCategories) { if (methodReturnRegisterType.type.isInterface()) { if (returnRegisterType.category != RegisterType.Category.Null && !returnRegisterType.type.implementsInterface(methodReturnRegisterType.type)) { //TODO: how to handle warnings? } } else { if (returnRegisterType.category == RegisterType.Category.Reference && !returnRegisterType.type.extendsClass(methodReturnRegisterType.type)) { throw new ValidationException(String.format("The return value in register v%d (%s) is not " + "compatible with the method's return type %s", returnRegister, returnRegisterType.type.getClassType(), methodReturnRegisterType.type.getClassType())); } } } } private void analyzeConst(AnalyzedInstruction analyzedInstruction) { LiteralInstruction instruction = (LiteralInstruction)analyzedInstruction.instruction; RegisterType newDestinationRegisterType = RegisterType.getRegisterTypeForLiteral(instruction.getLiteral()); //we assume that the literal value is a valid value for the given instruction type, because it's impossible //to store an invalid literal with the instruction. so we don't need to check the type of the literal setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, newDestinationRegisterType); } private void analyzeConstHigh16(AnalyzedInstruction analyzedInstruction) { //the literal value stored in the instruction is a 16-bit value. When shifted left by 16, it will always be an //integer setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.Integer, null)); } private void analyzeWideConst(AnalyzedInstruction analyzedInstruction) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.LongLo, null)); } private void analyzeConstString(AnalyzedInstruction analyzedInstruction) { ClassPath.ClassDef stringClassDef = ClassPath.getClassDef("Ljava/lang/String;"); RegisterType stringType = RegisterType.getRegisterType(RegisterType.Category.Reference, stringClassDef); setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, stringType); } private void analyzeConstClass(AnalyzedInstruction analyzedInstruction) { ClassPath.ClassDef classClassDef = ClassPath.getClassDef("Ljava/lang/Class;"); RegisterType classType = RegisterType.getRegisterType(RegisterType.Category.Reference, classClassDef); setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, classType); } private void verifyConstClass(AnalyzedInstruction analyzedInstruction) { ClassPath.ClassDef classClassDef = ClassPath.getClassDef("Ljava/lang/Class;"); RegisterType classType = RegisterType.getRegisterType(RegisterType.Category.Reference, classClassDef); InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; //TODO: need to check class access //make sure the referenced class is resolvable ClassPath.getClassDef((TypeIdItem)item); } private void verifyMonitor(AnalyzedInstruction analyzedInstruction) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), ReferenceCategories); } private void analyzeCheckCast(AnalyzedInstruction analyzedInstruction) { InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; RegisterType castRegisterType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, castRegisterType); } private void verifyCheckCast(AnalyzedInstruction analyzedInstruction) { { //ensure the "source" register is a reference type SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; RegisterType registerType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), ReferenceCategories); } { //resolve and verify the class that we're casting to InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; //TODO: need to check class access RegisterType castRegisterType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); if (castRegisterType.category != RegisterType.Category.Reference) { //TODO: verify that dalvik allows a non-reference type.. //TODO: print a warning, but don't re-throw the exception. dalvik allows a non-reference type during validation (but throws an exception at runtime) } } } private void analyzeInstanceOf(AnalyzedInstruction analyzedInstruction) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.Boolean, null)); } private void verifyInstanceOf(AnalyzedInstruction analyzedInstruction) { { //ensure the register that is being checks is a reference type TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceCategories); } { //resolve and verify the class that we're checking against InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; RegisterType registerType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); if (registerType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use instance-of with a non-reference type %s", registerType.toString())); } //TODO: is it valid to use an array type? //TODO: could probably do an even more sophisticated check, where we check the possible register types against the specified type. In some cases, we could determine that it always fails, and print a warning to that effect. } } private void analyzeArrayLength(AnalyzedInstruction analyzedInstruction) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.Integer, null)); } private void verifyArrayLength(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; int arrayRegisterNumber = instruction.getRegisterB(); RegisterType arrayRegisterType = getAndCheckSourceRegister(analyzedInstruction, arrayRegisterNumber, ReferenceCategories); if (arrayRegisterType.type != null) { if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use array-length with non-array type %s", arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; } } private void analyzeNewInstance(AnalyzedInstruction analyzedInstruction) { InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; int register = ((SingleRegisterInstruction)analyzedInstruction.instruction).getRegisterA(); RegisterType destRegisterType = analyzedInstruction.getPostInstructionRegisterType(register); if (destRegisterType.category != RegisterType.Category.Unknown) { assert destRegisterType.category == RegisterType.Category.UninitRef; //the post-instruction destination register will only be set if we have already analyzed this instruction //at least once. If this is the case, then the uninit reference has already been propagated to all //successors and nothing else needs to be done. return; } Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; RegisterType classType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getUnitializedReference(classType.type)); } private void verifyNewInstance(AnalyzedInstruction analyzedInstruction) { InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; int register = ((SingleRegisterInstruction)analyzedInstruction.instruction).getRegisterA(); RegisterType destRegisterType = analyzedInstruction.postRegisterMap[register]; if (destRegisterType.category != RegisterType.Category.Unknown) { assert destRegisterType.category == RegisterType.Category.UninitRef; //the "post-instruction" destination register will only be set if we've gone over //this instruction at least once before. If this is the case, then we need to check //all the other registers, and make sure that none of them contain the same //uninitialized reference that is in the destination register. for (int i=0; i<analyzedInstruction.postRegisterMap.length; i++) { if (i==register) { continue; } if (analyzedInstruction.getPreInstructionRegisterType(i) == destRegisterType) { throw new ValidationException(String.format("Register v%d contains an uninitialized reference " + "that was created by this new-instance instruction.", i)); } } return; } Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; //TODO: need to check class access RegisterType classType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); if (classType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use new-instance with a non-reference type %s", classType.toString())); } if (((TypeIdItem)item).getTypeDescriptor().charAt(0) == '[') { throw new ValidationException("Cannot use array type \"" + ((TypeIdItem)item).getTypeDescriptor() + "\" with new-instance. Use new-array instead."); } } private void analyzeNewArray(AnalyzedInstruction analyzedInstruction) { InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; RegisterType arrayType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); assert arrayType.type instanceof ClassPath.ArrayClassDef; setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, arrayType); } private void verifyNewArray(AnalyzedInstruction analyzedInstruction) { { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), Primitive32BitCategories); } InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; RegisterType arrayType = RegisterType.getRegisterTypeForTypeIdItem((TypeIdItem)item); assert arrayType.type instanceof ClassPath.ArrayClassDef; if (arrayType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use new-array with a non-reference type %s", arrayType.toString())); } if (arrayType.type.getClassType().charAt(0) != '[') { throw new ValidationException("Cannot use non-array type \"" + arrayType.type.getClassType() + "\" with new-array. Use new-instance instead."); } } private void verifyFilledNewArrayCommon(AnalyzedInstruction analyzedInstruction, RegisterIterator registerIterator) { InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; RegisterType arrayType; RegisterType arrayImmediateElementType; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_TYPE_ID_ITEM; ClassPath.ClassDef classDef = ClassPath.getClassDef((TypeIdItem)item); if (classDef.getClassType().charAt(0) != '[') { throw new ValidationException("Cannot use non-array type \"" + classDef.getClassType() + "\" with new-array. Use new-instance instead."); } ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)classDef; arrayType = RegisterType.getRegisterType(RegisterType.Category.Reference, classDef); arrayImmediateElementType = RegisterType.getRegisterTypeForType( arrayClassDef.getImmediateElementClass().getClassType()); String baseElementType = arrayClassDef.getBaseElementClass().getClassType(); if (baseElementType.charAt(0) == 'J' || baseElementType.charAt(0) == 'D') { throw new ValidationException("Cannot use filled-new-array to create an array of wide values " + "(long or double)"); } do { int register = registerIterator.getRegister(); RegisterType elementType = analyzedInstruction.getPreInstructionRegisterType(register); assert elementType != null; if (!elementType.canBeAssignedTo(arrayImmediateElementType)) { throw new ValidationException("Register v" + Integer.toString(register) + " is of type " + elementType.toString() + " and is incompatible with the array type " + arrayType.type.getClassType()); } } while (registerIterator.moveNext()); } private void verifyFilledNewArray(AnalyzedInstruction analyzedInstruction) { FiveRegisterInstruction instruction = (FiveRegisterInstruction)analyzedInstruction.instruction; verifyFilledNewArrayCommon(analyzedInstruction, new Format35cRegisterIterator(instruction)); } private void verifyFilledNewArrayRange(AnalyzedInstruction analyzedInstruction) { RegisterRangeInstruction instruction = (RegisterRangeInstruction)analyzedInstruction.instruction; //instruction.getStartRegister() and instruction.getRegCount() both return an int value, but are actually //unsigned 16 bit values, so we don't have to worry about overflowing an int when adding them together if (instruction.getStartRegister() + instruction.getRegCount() >= 1<<16) { throw new ValidationException(String.format("Invalid register range {v%d .. v%d}. The ending register " + "is larger than the largest allowed register of v65535.", instruction.getStartRegister(), instruction.getStartRegister() + instruction.getRegCount() - 1)); } verifyFilledNewArrayCommon(analyzedInstruction, new Format3rcRegisterIterator(instruction)); } private void verifyFillArrayData(AnalyzedInstruction analyzedInstruction) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; int register = instruction.getRegisterA(); RegisterType registerType = analyzedInstruction.getPreInstructionRegisterType(register); assert registerType != null; if (registerType.category == RegisterType.Category.Null) { return; } if (registerType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use fill-array-data with non-array register v%d of " + "type %s", register, registerType.toString())); } assert registerType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)registerType.type; if (arrayClassDef.getArrayDimensions() != 1) { throw new ValidationException(String.format("Cannot use fill-array-data with array type %s. It can only " + "be used with a one-dimensional array of primitives.", arrayClassDef.getClassType())); } int elementWidth; switch (arrayClassDef.getBaseElementClass().getClassType().charAt(0)) { case 'Z': case 'B': elementWidth = 1; break; case 'C': case 'S': elementWidth = 2; break; case 'I': case 'F': elementWidth = 4; break; case 'J': case 'D': elementWidth = 8; break; default: throw new ValidationException(String.format("Cannot use fill-array-data with array type %s. It can " + "only be used with a one-dimensional array of primitives.", arrayClassDef.getClassType())); } int arrayDataAddressOffset = ((OffsetInstruction)analyzedInstruction.instruction).getTargetAddressOffset(); int arrayDataCodeAddress = getInstructionAddress(analyzedInstruction) + arrayDataAddressOffset; AnalyzedInstruction arrayDataInstruction = this.instructions.get(arrayDataCodeAddress); if (arrayDataInstruction == null || arrayDataInstruction.instruction.getFormat() != Format.ArrayData) { throw new ValidationException(String.format("Could not find an array data structure at code address 0x%x", arrayDataCodeAddress)); } ArrayDataPseudoInstruction arrayDataPseudoInstruction = (ArrayDataPseudoInstruction)arrayDataInstruction.instruction; if (elementWidth != arrayDataPseudoInstruction.getElementWidth()) { throw new ValidationException(String.format("The array data at code address 0x%x does not have the " + "correct element width for array type %s. Expecting element width %d, got element width %d.", arrayDataCodeAddress, arrayClassDef.getClassType(), elementWidth, arrayDataPseudoInstruction.getElementWidth())); } } private void verifyThrow(AnalyzedInstruction analyzedInstruction) { int register = ((SingleRegisterInstruction)analyzedInstruction.instruction).getRegisterA(); RegisterType registerType = analyzedInstruction.getPreInstructionRegisterType(register); assert registerType != null; if (registerType.category == RegisterType.Category.Null) { return; } if (registerType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use throw with non-reference type %s in register v%d", registerType.toString(), register)); } assert registerType.type != null; if (!registerType.type.extendsClass(ClassPath.getClassDef("Ljava/lang/Throwable;"))) { throw new ValidationException(String.format("Cannot use throw with non-throwable type %s in register v%d", registerType.type.getClassType(), register)); } } private void analyzeArrayDataOrSwitch(AnalyzedInstruction analyzedInstruction) { int dataAddressOffset = ((OffsetInstruction)analyzedInstruction.instruction).getTargetAddressOffset(); int dataCodeAddress = this.getInstructionAddress(analyzedInstruction) + dataAddressOffset; AnalyzedInstruction dataAnalyzedInstruction = instructions.get(dataCodeAddress); if (dataAnalyzedInstruction != null) { dataAnalyzedInstruction.dead = false; //if there is a preceding nop, it's deadness should be the same AnalyzedInstruction priorInstruction = instructions.valueAt(dataAnalyzedInstruction.getInstructionIndex()-1); if (priorInstruction.getInstruction().opcode == Opcode.NOP && !priorInstruction.getInstruction().getFormat().variableSizeFormat) { priorInstruction.dead = false; } } } private void verifySwitch(AnalyzedInstruction analyzedInstruction, Format expectedSwitchDataFormat) { int register = ((SingleRegisterInstruction)analyzedInstruction.instruction).getRegisterA(); int switchCodeAddressOffset = ((OffsetInstruction)analyzedInstruction.instruction).getTargetAddressOffset(); getAndCheckSourceRegister(analyzedInstruction, register, Primitive32BitCategories); int switchDataCodeAddress = this.getInstructionAddress(analyzedInstruction) + switchCodeAddressOffset; AnalyzedInstruction switchDataAnalyzedInstruction = instructions.get(switchDataCodeAddress); if (switchDataAnalyzedInstruction == null || switchDataAnalyzedInstruction.instruction.getFormat() != expectedSwitchDataFormat) { throw new ValidationException(String.format("There is no %s structure at code address 0x%x", expectedSwitchDataFormat.name(), switchDataCodeAddress)); } } private void analyzeFloatWideCmp(AnalyzedInstruction analyzedInstruction) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.Byte, null)); } private void verifyFloatWideCmp(AnalyzedInstruction analyzedInstruction, EnumSet validCategories) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), validCategories); getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), validCategories); } private void verifyIfEqNe(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType registerType1 = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterA()); assert registerType1 != null; RegisterType registerType2 = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert registerType2 != null; if (!( (ReferenceCategories.contains(registerType1.category) && ReferenceCategories.contains(registerType2.category)) || (Primitive32BitCategories.contains(registerType1.category) && Primitive32BitCategories.contains(registerType2.category)) )) { throw new ValidationException(String.format("%s cannot be used on registers of dissimilar types %s and " + "%s. They must both be a reference type or a primitive 32 bit type.", analyzedInstruction.instruction.opcode.name, registerType1.toString(), registerType2.toString())); } } private void verifyIf(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), Primitive32BitCategories); getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), Primitive32BitCategories); } private void verifyIfEqzNez(AnalyzedInstruction analyzedInstruction) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), ReferenceAndPrimitive32BitCategories); } private void verifyIfz(AnalyzedInstruction analyzedInstruction) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), Primitive32BitCategories); } private void analyze32BitPrimitiveAget(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(instructionCategory, null)); } private void verify32BitPrimitiveAget(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), Primitive32BitCategories); RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { if (arrayRegisterType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use %s with non-array type %s", analyzedInstruction.instruction.opcode.name, arrayRegisterType.category.toString())); } assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use %s with non-array type %s", analyzedInstruction.instruction.opcode.name, arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; if (arrayClassDef.getArrayDimensions() != 1) { throw new ValidationException(String.format("Cannot use %s with multi-dimensional array type %s", analyzedInstruction.instruction.opcode.name, arrayRegisterType.type.getClassType())); } RegisterType arrayBaseType = RegisterType.getRegisterTypeForType(arrayClassDef.getBaseElementClass().getClassType()); if (!checkArrayFieldAssignment(arrayBaseType.category, instructionCategory)) { throw new ValidationException(String.format("Cannot use %s with array type %s. Incorrect array type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, arrayRegisterType.type.getClassType())); } } } private void analyzeAgetWide(AnalyzedInstruction analyzedInstruction) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use aget-wide with non-array type %s", arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; char arrayBaseType = arrayClassDef.getBaseElementClass().getClassType().charAt(0); if (arrayBaseType == 'J') { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.LongLo, null)); } else if (arrayBaseType == 'D') { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.DoubleLo, null)); } else { throw new ValidationException(String.format("Cannot use aget-wide with array type %s. Incorrect " + "array type for the instruction.", arrayRegisterType.type.getClassType())); } } else { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.LongLo, null)); } } private void verifyAgetWide(AnalyzedInstruction analyzedInstruction) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), Primitive32BitCategories); RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { if (arrayRegisterType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use aget-wide with non-array type %s", arrayRegisterType.category.toString())); } assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use aget-wide with non-array type %s", arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; if (arrayClassDef.getArrayDimensions() != 1) { throw new ValidationException(String.format("Cannot use aget-wide with multi-dimensional array type %s", arrayRegisterType.type.getClassType())); } char arrayBaseType = arrayClassDef.getBaseElementClass().getClassType().charAt(0); if (arrayBaseType != 'J' && arrayBaseType != 'D') { throw new ValidationException(String.format("Cannot use aget-wide with array type %s. Incorrect " + "array type for the instruction.", arrayRegisterType.type.getClassType())); } } } private void analyzeAgetObject(AnalyzedInstruction analyzedInstruction) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use aget-object with non-array type %s", arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; ClassPath.ClassDef elementClassDef = arrayClassDef.getImmediateElementClass(); char elementTypePrefix = elementClassDef.getClassType().charAt(0); if (elementTypePrefix != 'L' && elementTypePrefix != '[') { throw new ValidationException(String.format("Cannot use aget-object with array type %s. Incorrect " + "array type for the instruction.", arrayRegisterType.type.getClassType())); } setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.Reference, elementClassDef)); } else { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(RegisterType.Category.Null, null)); } } private void verifyAgetObject(AnalyzedInstruction analyzedInstruction) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), Primitive32BitCategories); RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { if (arrayRegisterType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use aget-object with non-array type %s", arrayRegisterType.category.toString())); } assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use aget-object with non-array type %s", arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; ClassPath.ClassDef elementClassDef = arrayClassDef.getImmediateElementClass(); char elementTypePrefix = elementClassDef.getClassType().charAt(0); if (elementTypePrefix != 'L' && elementTypePrefix != '[') { throw new ValidationException(String.format("Cannot use aget-object with array type %s. Incorrect " + "array type for the instruction.", arrayRegisterType.type.getClassType())); } } } private void verify32BitPrimitiveAput(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), Primitive32BitCategories); RegisterType sourceRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterA()); assert sourceRegisterType != null; RegisterType instructionRegisterType = RegisterType.getRegisterType(instructionCategory, null); if (!sourceRegisterType.canBeAssignedTo(instructionRegisterType)) { throw new ValidationException(String.format("Cannot use %s with source register type %s.", analyzedInstruction.instruction.opcode.name, sourceRegisterType.toString())); } RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { if (arrayRegisterType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use %s with non-array type %s", analyzedInstruction.instruction.opcode.name, arrayRegisterType.category.toString())); } assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use %s with non-array type %s", analyzedInstruction.instruction.opcode.name, arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; if (arrayClassDef.getArrayDimensions() != 1) { throw new ValidationException(String.format("Cannot use %s with multi-dimensional array type %s", analyzedInstruction.instruction.opcode.name, arrayRegisterType.type.getClassType())); } RegisterType arrayBaseType = RegisterType.getRegisterTypeForType(arrayClassDef.getBaseElementClass().getClassType()); if (!checkArrayFieldAssignment(arrayBaseType.category, instructionCategory)) { throw new ValidationException(String.format("Cannot use %s with array type %s. Incorrect array type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, arrayRegisterType.type.getClassType())); } } } private void verifyAputWide(AnalyzedInstruction analyzedInstruction) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), Primitive32BitCategories); getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), WideLowCategories); RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { if (arrayRegisterType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use aput-wide with non-array type %s", arrayRegisterType.category.toString())); } assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use aput-wide with non-array type %s", arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; if (arrayClassDef.getArrayDimensions() != 1) { throw new ValidationException(String.format("Cannot use aput-wide with multi-dimensional array type %s", arrayRegisterType.type.getClassType())); } char arrayBaseType = arrayClassDef.getBaseElementClass().getClassType().charAt(0); if (arrayBaseType != 'J' && arrayBaseType != 'D') { throw new ValidationException(String.format("Cannot use aput-wide with array type %s. Incorrect " + "array type for the instruction.", arrayRegisterType.type.getClassType())); } } } private void verifyAputObject(AnalyzedInstruction analyzedInstruction) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), Primitive32BitCategories); RegisterType sourceRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterA()); assert sourceRegisterType != null; //TODO: ensure sourceRegisterType is a Reference type? RegisterType arrayRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); assert arrayRegisterType != null; if (arrayRegisterType.category != RegisterType.Category.Null) { //don't check the source type against the array type, just make sure it is an array of reference types if (arrayRegisterType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use aget-object with non-array type %s", arrayRegisterType.category.toString())); } assert arrayRegisterType.type != null; if (arrayRegisterType.type.getClassType().charAt(0) != '[') { throw new ValidationException(String.format("Cannot use aget-object with non-array type %s", arrayRegisterType.type.getClassType())); } assert arrayRegisterType.type instanceof ClassPath.ArrayClassDef; ClassPath.ArrayClassDef arrayClassDef = (ClassPath.ArrayClassDef)arrayRegisterType.type; ClassPath.ClassDef elementClassDef = arrayClassDef.getImmediateElementClass(); char elementTypePrefix = elementClassDef.getClassType().charAt(0); if (elementTypePrefix != 'L' && elementTypePrefix != '[') { throw new ValidationException(String.format("Cannot use aget-object with array type %s. Incorrect " + "array type for the instruction.", arrayRegisterType.type.getClassType())); } } } private void analyze32BitPrimitiveIget(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(instructionCategory, null)); } private void verify32BitPrimitiveIget(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitThisCategories); //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; if (objectRegisterType.category != RegisterType.Category.Null && !objectRegisterType.type.extendsClass(ClassPath.getClassDef(field.getContainingClass()))) { throw new ValidationException(String.format("Cannot access field %s through type %s", field.getFieldString(), objectRegisterType.type.getClassType())); } RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (!checkArrayFieldAssignment(fieldType.category, instructionCategory)) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void analyzeIgetWideObject(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, fieldType); } private void verifyIgetWide(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitThisCategories); //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; if (objectRegisterType.category != RegisterType.Category.Null && !objectRegisterType.type.extendsClass(ClassPath.getClassDef(field.getContainingClass()))) { throw new ValidationException(String.format("Cannot access field %s through type %s", field.getFieldString(), objectRegisterType.type.getClassType())); } RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (!WideLowCategories.contains(fieldType.category)) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verifyIgetObject(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitThisCategories); //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; if (objectRegisterType.category != RegisterType.Category.Null && !objectRegisterType.type.extendsClass(ClassPath.getClassDef(field.getContainingClass()))) { throw new ValidationException(String.format("Cannot access field %s through type %s", field.getFieldString(), objectRegisterType.type.getClassType())); } RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (fieldType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verify32BitPrimitiveIput(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitThisCategories); RegisterType sourceRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterA()); assert sourceRegisterType != null; //per CodeVerify.c in dalvik: //java generates synthetic functions that write byte values into boolean fields if (sourceRegisterType.category == RegisterType.Category.Byte && instructionCategory == RegisterType.Category.Boolean) { sourceRegisterType = RegisterType.getRegisterType(RegisterType.Category.Boolean, null); } RegisterType instructionRegisterType = RegisterType.getRegisterType(instructionCategory, null); if (!sourceRegisterType.canBeAssignedTo(instructionRegisterType)) { throw new ValidationException(String.format("Cannot use %s with source register type %s.", analyzedInstruction.instruction.opcode.name, sourceRegisterType.toString())); } //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; if (objectRegisterType.category != RegisterType.Category.Null && !objectRegisterType.type.extendsClass(ClassPath.getClassDef(field.getContainingClass()))) { throw new ValidationException(String.format("Cannot access field %s through type %s", field.getFieldString(), objectRegisterType.type.getClassType())); } RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (!checkArrayFieldAssignment(fieldType.category, instructionCategory)) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verifyIputWide(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitThisCategories); getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), WideLowCategories); //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; if (objectRegisterType.category != RegisterType.Category.Null && !objectRegisterType.type.extendsClass(ClassPath.getClassDef(field.getContainingClass()))) { throw new ValidationException(String.format("Cannot access field %s through type %s", field.getFieldString(), objectRegisterType.type.getClassType())); } RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (!WideLowCategories.contains(fieldType.category)) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verifyIputObject(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitThisCategories); RegisterType sourceRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), ReferenceCategories); //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; if (objectRegisterType.category != RegisterType.Category.Null && !objectRegisterType.type.extendsClass(ClassPath.getClassDef(field.getContainingClass()))) { throw new ValidationException(String.format("Cannot access field %s through type %s", field.getFieldString(), objectRegisterType.type.getClassType())); } RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (fieldType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } if (sourceRegisterType.category != RegisterType.Category.Null && !fieldType.type.isInterface() && !sourceRegisterType.type.extendsClass(fieldType.type)) { throw new ValidationException(String.format("Cannot store a value of type %s into a field of type %s", sourceRegisterType.type.getClassType(), fieldType.type.getClassType())); } } private void analyze32BitPrimitiveSget(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(instructionCategory, null)); } private void verify32BitPrimitiveSget(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (!checkArrayFieldAssignment(fieldType.category, instructionCategory)) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void analyzeSgetWideObject(AnalyzedInstruction analyzedInstruction) { Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, fieldType); } private void verifySgetWide(AnalyzedInstruction analyzedInstruction) { //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (fieldType.category != RegisterType.Category.LongLo && fieldType.category != RegisterType.Category.DoubleLo) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verifySgetObject(AnalyzedInstruction analyzedInstruction) { //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (fieldType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verify32BitPrimitiveSput(AnalyzedInstruction analyzedInstruction, RegisterType.Category instructionCategory) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; RegisterType sourceRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterA()); assert sourceRegisterType != null; //per CodeVerify.c in dalvik: //java generates synthetic functions that write byte values into boolean fields if (sourceRegisterType.category == RegisterType.Category.Byte && instructionCategory == RegisterType.Category.Boolean) { sourceRegisterType = RegisterType.getRegisterType(RegisterType.Category.Boolean, null); } RegisterType instructionRegisterType = RegisterType.getRegisterType(instructionCategory, null); if (!sourceRegisterType.canBeAssignedTo(instructionRegisterType)) { throw new ValidationException(String.format("Cannot use %s with source register type %s.", analyzedInstruction.instruction.opcode.name, sourceRegisterType.toString())); } //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (!checkArrayFieldAssignment(fieldType.category, instructionCategory)) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verifySputWide(AnalyzedInstruction analyzedInstruction) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), WideLowCategories); //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (!WideLowCategories.contains(fieldType.category)) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } } private void verifySputObject(AnalyzedInstruction analyzedInstruction) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; RegisterType sourceRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), ReferenceCategories); //TODO: check access Item referencedItem = ((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem(); assert referencedItem instanceof FieldIdItem; FieldIdItem field = (FieldIdItem)referencedItem; RegisterType fieldType = RegisterType.getRegisterTypeForTypeIdItem(field.getFieldType()); if (fieldType.category != RegisterType.Category.Reference) { throw new ValidationException(String.format("Cannot use %s with field %s. Incorrect field type " + "for the instruction.", analyzedInstruction.instruction.opcode.name, field.getFieldString())); } if (sourceRegisterType.category != RegisterType.Category.Null && !fieldType.type.isInterface() && !sourceRegisterType.type.extendsClass(fieldType.type)) { throw new ValidationException(String.format("Cannot store a value of type %s into a field of type %s", sourceRegisterType.type.getClassType(), fieldType.type.getClassType())); } } private void analyzeInvokeDirect(AnalyzedInstruction analyzedInstruction) { FiveRegisterInstruction instruction = (FiveRegisterInstruction)analyzedInstruction.instruction; analyzeInvokeDirectCommon(analyzedInstruction, new Format35cRegisterIterator(instruction)); } private void verifyInvoke(AnalyzedInstruction analyzedInstruction, int invokeType) { FiveRegisterInstruction instruction = (FiveRegisterInstruction)analyzedInstruction.instruction; verifyInvokeCommon(analyzedInstruction, false, invokeType, new Format35cRegisterIterator(instruction)); } private void analyzeInvokeDirectRange(AnalyzedInstruction analyzedInstruction) { RegisterRangeInstruction instruction = (RegisterRangeInstruction)analyzedInstruction.instruction; analyzeInvokeDirectCommon(analyzedInstruction, new Format3rcRegisterIterator(instruction)); } private void verifyInvokeRange(AnalyzedInstruction analyzedInstruction, int invokeType) { RegisterRangeInstruction instruction = (RegisterRangeInstruction)analyzedInstruction.instruction; verifyInvokeCommon(analyzedInstruction, true, invokeType, new Format3rcRegisterIterator(instruction)); } private static final int INVOKE_VIRTUAL = 0x01; private static final int INVOKE_SUPER = 0x02; private static final int INVOKE_DIRECT = 0x04; private static final int INVOKE_INTERFACE = 0x08; private static final int INVOKE_STATIC = 0x10; private void analyzeInvokeDirectCommon(AnalyzedInstruction analyzedInstruction, RegisterIterator registers) { //the only time that an invoke instruction changes a register type is when using invoke-direct on a //constructor (<init>) method, which changes the uninitialized reference (and any register that the same //uninit reference has been copied to) to an initialized reference InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_METHOD_ID_ITEM; MethodIdItem methodIdItem = (MethodIdItem)item; if (!methodIdItem.getMethodName().getStringValue().equals("<init>")) { return; } RegisterType objectRegisterType; //the object register is always the first register int objectRegister = registers.getRegister(); objectRegisterType = analyzedInstruction.getPreInstructionRegisterType(objectRegister); assert objectRegisterType != null; if (objectRegisterType.category != RegisterType.Category.UninitRef && objectRegisterType.category != RegisterType.Category.UninitThis) { return; } setPostRegisterTypeAndPropagateChanges(analyzedInstruction, objectRegister, RegisterType.getRegisterType(RegisterType.Category.Reference, objectRegisterType.type)); for (int i=0; i<analyzedInstruction.postRegisterMap.length; i++) { RegisterType postInstructionRegisterType = analyzedInstruction.postRegisterMap[i]; if (postInstructionRegisterType.category == RegisterType.Category.Unknown) { RegisterType preInstructionRegisterType = analyzedInstruction.getPreInstructionRegisterType(i); if (preInstructionRegisterType.category == RegisterType.Category.UninitRef || preInstructionRegisterType.category == RegisterType.Category.UninitThis) { RegisterType registerType; if (preInstructionRegisterType == objectRegisterType) { registerType = analyzedInstruction.postRegisterMap[objectRegister]; } else { registerType = preInstructionRegisterType; } setPostRegisterTypeAndPropagateChanges(analyzedInstruction, i, registerType); } } } } private void verifyInvokeCommon(AnalyzedInstruction analyzedInstruction, boolean isRange, int invokeType, RegisterIterator registers) { InstructionWithReference instruction = (InstructionWithReference)analyzedInstruction.instruction; //TODO: check access Item item = instruction.getReferencedItem(); assert item.getItemType() == ItemType.TYPE_METHOD_ID_ITEM; MethodIdItem methodIdItem = (MethodIdItem)item; TypeIdItem methodClass = methodIdItem.getContainingClass(); boolean isInit = false; if (methodIdItem.getMethodName().getStringValue().charAt(0) == '<') { if ((invokeType & INVOKE_DIRECT) != 0) { isInit = true; } else { throw new ValidationException(String.format("Cannot call constructor %s with %s", methodIdItem.getMethodString(), analyzedInstruction.instruction.opcode.name)); } } ClassPath.ClassDef methodClassDef = ClassPath.getClassDef(methodClass); if ((invokeType & INVOKE_INTERFACE) != 0) { if (!methodClassDef.isInterface()) { throw new ValidationException(String.format("Cannot call method %s with %s. %s is not an interface " + "class.", methodIdItem.getMethodString(), analyzedInstruction.instruction.opcode.name, methodClassDef.getClassType())); } } else { if (methodClassDef.isInterface()) { throw new ValidationException(String.format("Cannot call method %s with %s. %s is an interface class." + " Use invoke-interface or invoke-interface/range instead.", methodIdItem.getMethodString(), analyzedInstruction.instruction.opcode.name, methodClassDef.getClassType())); } } if ((invokeType & INVOKE_SUPER) != 0) { ClassPath.ClassDef currentMethodClassDef = ClassPath.getClassDef(encodedMethod.method.getContainingClass()); if (currentMethodClassDef.getSuperclass() == null) { throw new ValidationException(String.format("Cannot call method %s with %s. %s has no superclass", methodIdItem.getMethodString(), analyzedInstruction.instruction.opcode.name, methodClassDef.getSuperclass().getClassType())); } if (!currentMethodClassDef.getSuperclass().extendsClass(methodClassDef)) { throw new ValidationException(String.format("Cannot call method %s with %s. %s is not an ancestor " + "of the current class %s", methodIdItem.getMethodString(), analyzedInstruction.instruction.opcode.name, methodClass.getTypeDescriptor(), encodedMethod.method.getContainingClass().getTypeDescriptor())); } if (!currentMethodClassDef.getSuperclass().hasVirtualMethod(methodIdItem.getShortMethodString())) { throw new ValidationException(String.format("Cannot call method %s with %s. The superclass %s has" + "no such method", methodIdItem.getMethodString(), analyzedInstruction.instruction.opcode.name, methodClassDef.getSuperclass().getClassType())); } } assert isRange || registers.getCount() <= 5; TypeListItem typeListItem = methodIdItem.getPrototype().getParameters(); int methodParameterRegisterCount; if (typeListItem == null) { methodParameterRegisterCount = 0; } else { methodParameterRegisterCount = typeListItem.getRegisterCount(); } if ((invokeType & INVOKE_STATIC) == 0) { methodParameterRegisterCount++; } if (methodParameterRegisterCount != registers.getCount()) { throw new ValidationException(String.format("The number of registers does not match the number of " + "parameters for method %s. Expecting %d registers, got %d.", methodIdItem.getMethodString(), methodParameterRegisterCount + 1, registers.getCount())); } RegisterType objectRegisterType = null; int objectRegister = 0; if ((invokeType & INVOKE_STATIC) == 0) { objectRegister = registers.getRegister(); registers.moveNext(); objectRegisterType = analyzedInstruction.getPreInstructionRegisterType(objectRegister); assert objectRegisterType != null; if (objectRegisterType.category == RegisterType.Category.UninitRef || objectRegisterType.category == RegisterType.Category.UninitThis) { if (!isInit) { throw new ValidationException(String.format("Cannot invoke non-<init> method %s on uninitialized " + "reference type %s", methodIdItem.getMethodString(), objectRegisterType.type.getClassType())); } } else if (objectRegisterType.category == RegisterType.Category.Reference) { if (isInit) { throw new ValidationException(String.format("Cannot invoke %s on initialized reference type %s", methodIdItem.getMethodString(), objectRegisterType.type.getClassType())); } } else if (objectRegisterType.category == RegisterType.Category.Null) { if (isInit) { throw new ValidationException(String.format("Cannot invoke %s on a null reference", methodIdItem.getMethodString())); } } else { throw new ValidationException(String.format("Cannot invoke %s on non-reference type %s", methodIdItem.getMethodString(), objectRegisterType.toString())); } if (isInit) { if (objectRegisterType.type.getSuperclass() == methodClassDef) { if (!encodedMethod.method.getMethodName().getStringValue().equals("<init>")) { throw new ValidationException(String.format("Cannot call %s on type %s. The object type must " + "match the method type exactly", methodIdItem.getMethodString(), objectRegisterType.type.getClassType())); } } } if ((invokeType & INVOKE_INTERFACE) == 0 && objectRegisterType.category != RegisterType.Category.Null && !objectRegisterType.type.extendsClass(methodClassDef)) { throw new ValidationException(String.format("Cannot call method %s on an object of type %s, which " + "does not extend %s.", methodIdItem.getMethodString(), objectRegisterType.type.getClassType(), methodClassDef.getClassType())); } } if (typeListItem != null) { List<TypeIdItem> parameterTypes = typeListItem.getTypes(); int parameterTypeIndex = 0; while (!registers.pastEnd()) { assert parameterTypeIndex < parameterTypes.size(); RegisterType parameterType = RegisterType.getRegisterTypeForTypeIdItem(parameterTypes.get(parameterTypeIndex)); int register = registers.getRegister(); RegisterType parameterRegisterType; if (WideLowCategories.contains(parameterType.category)) { parameterRegisterType = getAndCheckSourceRegister(analyzedInstruction, register, WideLowCategories); if (!registers.moveNext()) { throw new ValidationException(String.format("No 2nd register specified for wide register pair v%d", parameterTypeIndex+1)); } int nextRegister = registers.getRegister(); if (nextRegister != register + 1) { throw new ValidationException(String.format("Invalid wide register pair (v%d, v%d). Registers " + "must be consecutive.", register, nextRegister)); } } else { parameterRegisterType = analyzedInstruction.getPreInstructionRegisterType(register); } assert parameterRegisterType != null; if (!parameterRegisterType.canBeAssignedTo(parameterType)) { throw new ValidationException( String.format("Invalid register type %s for parameter %d %s.", parameterRegisterType.toString(), parameterTypeIndex+1, parameterType.toString())); } parameterTypeIndex++; registers.moveNext(); } } } private void analyzeUnaryOp(AnalyzedInstruction analyzedInstruction, RegisterType.Category destRegisterCategory) { setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(destRegisterCategory, null)); } private void verifyUnaryOp(AnalyzedInstruction analyzedInstruction, EnumSet validSourceCategories) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), validSourceCategories); } private void analyzeBinaryOp(AnalyzedInstruction analyzedInstruction, RegisterType.Category destRegisterCategory, boolean checkForBoolean) { if (checkForBoolean) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; RegisterType source1RegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); RegisterType source2RegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterC()); if (BooleanCategories.contains(source1RegisterType.category) && BooleanCategories.contains(source2RegisterType.category)) { destRegisterCategory = RegisterType.Category.Boolean; } } setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(destRegisterCategory, null)); } private void verifyBinaryOp(AnalyzedInstruction analyzedInstruction, EnumSet validSource1Categories, EnumSet validSource2Categories) { ThreeRegisterInstruction instruction = (ThreeRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), validSource1Categories); getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterC(), validSource2Categories); } private void analyzeBinary2AddrOp(AnalyzedInstruction analyzedInstruction, RegisterType.Category destRegisterCategory, boolean checkForBoolean) { if (checkForBoolean) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType source1RegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterA()); RegisterType source2RegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); if (BooleanCategories.contains(source1RegisterType.category) && BooleanCategories.contains(source2RegisterType.category)) { destRegisterCategory = RegisterType.Category.Boolean; } } setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(destRegisterCategory, null)); } private void verifyBinary2AddrOp(AnalyzedInstruction analyzedInstruction, EnumSet validSource1Categories, EnumSet validSource2Categories) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterA(), validSource1Categories); getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), validSource2Categories); } private void analyzeLiteralBinaryOp(AnalyzedInstruction analyzedInstruction, RegisterType.Category destRegisterCategory, boolean checkForBoolean) { if (checkForBoolean) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType sourceRegisterType = analyzedInstruction.getPreInstructionRegisterType(instruction.getRegisterB()); if (BooleanCategories.contains(sourceRegisterType.category)) { long literal = ((LiteralInstruction)analyzedInstruction.instruction).getLiteral(); if (literal == 0 || literal == 1) { destRegisterCategory = RegisterType.Category.Boolean; } } } setDestinationRegisterTypeAndPropagateChanges(analyzedInstruction, RegisterType.getRegisterType(destRegisterCategory, null)); } private void verifyLiteralBinaryOp(AnalyzedInstruction analyzedInstruction) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), Primitive32BitCategories); } private RegisterType.Category getDestTypeForLiteralShiftRight(AnalyzedInstruction analyzedInstruction, boolean signedShift) { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; RegisterType sourceRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), Primitive32BitCategories); long literalShift = ((LiteralInstruction)analyzedInstruction.instruction).getLiteral(); if (literalShift == 0) { return sourceRegisterType.category; } RegisterType.Category destRegisterCategory; if (!signedShift) { destRegisterCategory = RegisterType.Category.Integer; } else { destRegisterCategory = sourceRegisterType.category; } if (literalShift >= 32) { //TODO: add warning return destRegisterCategory; } switch (sourceRegisterType.category) { case Integer: case Float: if (!signedShift) { if (literalShift > 24) { return RegisterType.Category.PosByte; } if (literalShift >= 16) { return RegisterType.Category.Char; } } else { if (literalShift >= 24) { return RegisterType.Category.Byte; } if (literalShift >= 16) { return RegisterType.Category.Short; } } break; case Short: if (signedShift && literalShift >= 8) { return RegisterType.Category.Byte; } break; case PosShort: if (literalShift >= 8) { return RegisterType.Category.PosByte; } break; case Char: if (literalShift > 8) { return RegisterType.Category.PosByte; } break; case Byte: break; case PosByte: return RegisterType.Category.PosByte; case Null: case One: case Boolean: return RegisterType.Category.Null; default: assert false; } return destRegisterCategory; } private void analyzeExecuteInline(AnalyzedInstruction analyzedInstruction) { if (deodexUtil == null) { throw new ValidationException("Cannot analyze an odexed instruction unless we are deodexing"); } Instruction35mi instruction = (Instruction35mi)analyzedInstruction.instruction; DeodexUtil.InlineMethod inlineMethod = deodexUtil.lookupInlineMethod(analyzedInstruction); MethodIdItem inlineMethodIdItem = inlineMethod.getMethodIdItem(deodexUtil); if (inlineMethodIdItem == null) { throw new ValidationException(String.format("Cannot load inline method with index %d", instruction.getInlineIndex())); } Opcode deodexedOpcode = null; switch (inlineMethod.methodType) { case DeodexUtil.Direct: deodexedOpcode = Opcode.INVOKE_DIRECT; break; case DeodexUtil.Static: deodexedOpcode = Opcode.INVOKE_STATIC; break; case DeodexUtil.Virtual: deodexedOpcode = Opcode.INVOKE_VIRTUAL; break; default: assert false; } Instruction35c deodexedInstruction = new Instruction35c(deodexedOpcode, instruction.getRegCount(), instruction.getRegisterD(), instruction.getRegisterE(), instruction.getRegisterF(), instruction.getRegisterG(), instruction.getRegisterA(), inlineMethodIdItem); analyzedInstruction.setDeodexedInstruction(deodexedInstruction); analyzeInstruction(analyzedInstruction); } private void analyzeExecuteInlineRange(AnalyzedInstruction analyzedInstruction) { if (deodexUtil == null) { throw new ValidationException("Cannot analyze an odexed instruction unless we are deodexing"); } Instruction3rmi instruction = (Instruction3rmi)analyzedInstruction.instruction; DeodexUtil.InlineMethod inlineMethod = deodexUtil.lookupInlineMethod(analyzedInstruction); MethodIdItem inlineMethodIdItem = inlineMethod.getMethodIdItem(deodexUtil); if (inlineMethodIdItem == null) { throw new ValidationException(String.format("Cannot load inline method with index %d", instruction.getInlineIndex())); } Opcode deodexedOpcode = null; switch (inlineMethod.methodType) { case DeodexUtil.Direct: deodexedOpcode = Opcode.INVOKE_DIRECT_RANGE; break; case DeodexUtil.Static: deodexedOpcode = Opcode.INVOKE_STATIC_RANGE; break; case DeodexUtil.Virtual: deodexedOpcode = Opcode.INVOKE_VIRTUAL_RANGE; break; default: assert false; } Instruction3rc deodexedInstruction = new Instruction3rc(deodexedOpcode, (short)instruction.getRegCount(), instruction.getStartRegister(), inlineMethodIdItem); analyzedInstruction.setDeodexedInstruction(deodexedInstruction); analyzeInstruction(analyzedInstruction); } private void analyzeInvokeDirectEmpty(AnalyzedInstruction analyzedInstruction) { analyzeInvokeDirectEmpty(analyzedInstruction, true); } private void analyzeInvokeDirectEmpty(AnalyzedInstruction analyzedInstruction, boolean analyzeResult) { Instruction35c instruction = (Instruction35c)analyzedInstruction.instruction; Instruction35c deodexedInstruction = new Instruction35c(Opcode.INVOKE_DIRECT, instruction.getRegCount(), instruction.getRegisterD(), instruction.getRegisterE(), instruction.getRegisterF(), instruction.getRegisterG(), instruction.getRegisterA(), instruction.getReferencedItem()); analyzedInstruction.setDeodexedInstruction(deodexedInstruction); if (analyzeResult) { analyzeInstruction(analyzedInstruction); } } private void analyzeInvokeObjectInitRange(AnalyzedInstruction analyzedInstruction) { analyzeInvokeObjectInitRange(analyzedInstruction, true); } private void analyzeInvokeObjectInitRange(AnalyzedInstruction analyzedInstruction, boolean analyzeResult) { Instruction3rc instruction = (Instruction3rc)analyzedInstruction.instruction; Instruction3rc deodexedInstruction = new Instruction3rc(Opcode.INVOKE_DIRECT_RANGE, (short)instruction.getRegCount(), instruction.getStartRegister(), instruction.getReferencedItem()); analyzedInstruction.setDeodexedInstruction(deodexedInstruction); if (analyzeResult) { analyzeInstruction(analyzedInstruction); } } private boolean analyzeIputIgetQuick(AnalyzedInstruction analyzedInstruction) { Instruction22cs instruction = (Instruction22cs)analyzedInstruction.instruction; int fieldOffset = instruction.getFieldOffset(); RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, instruction.getRegisterB(), ReferenceOrUninitCategories); if (objectRegisterType.category == RegisterType.Category.Null) { return false; } ClassPath.ClassDef accessingClass = ClassPath.getClassDef(this.encodedMethod.method.getContainingClass(), false); if (accessingClass == null) { throw new ExceptionWithContext(String.format("Could not find ClassDef for current class: %s", this.encodedMethod.method.getContainingClass())); } FieldIdItem fieldIdItem = deodexUtil.lookupField(accessingClass, objectRegisterType.type, fieldOffset); if (fieldIdItem == null) { throw new ValidationException(String.format("Could not resolve the field in class %s at offset %d", objectRegisterType.type.getClassType(), fieldOffset)); } String fieldType = fieldIdItem.getFieldType().getTypeDescriptor(); Opcode opcode = OdexedFieldInstructionMapper.getAndCheckDeodexedOpcodeForOdexedOpcode(fieldType, instruction.opcode); Instruction22c deodexedInstruction = new Instruction22c(opcode, (byte)instruction.getRegisterA(), (byte)instruction.getRegisterB(), fieldIdItem); analyzedInstruction.setDeodexedInstruction(deodexedInstruction); analyzeInstruction(analyzedInstruction); return true; } private boolean analyzeInvokeVirtualQuick(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.getRegisterD(); } RegisterType objectRegisterType = getAndCheckSourceRegister(analyzedInstruction, objectRegister, ReferenceOrUninitCategories); if (objectRegisterType.category == RegisterType.Category.Null) { return false; } MethodIdItem methodIdItem = null; ClassPath.ClassDef accessingClass = ClassPath.getClassDef(this.encodedMethod.method.getContainingClass(), false); if (accessingClass == null) { throw new ExceptionWithContext(String.format("Could not find ClassDef for current class: %s", this.encodedMethod.method.getContainingClass())); } if (isSuper) { if (accessingClass.getSuperclass() != null) { methodIdItem = deodexUtil.lookupVirtualMethod(accessingClass, accessingClass.getSuperclass(), methodIndex); } if (methodIdItem == null) { //it's possible that the pre-odexed instruction had used the method from the current class instead //of from the superclass (although the superclass method is still what would actually be called). //And so the MethodIdItem for the superclass method may not be in the dex file. Let's try to get the //MethodIdItem for the method in the current class instead methodIdItem = deodexUtil.lookupVirtualMethod(accessingClass, accessingClass, methodIndex); } } else{ methodIdItem = deodexUtil.lookupVirtualMethod(accessingClass, objectRegisterType.type, methodIndex); } if (methodIdItem == null) { throw new ValidationException(String.format("Could not resolve the method in class %s at index %d", objectRegisterType.type.getClassType(), methodIndex)); } 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 Instruction3rc(opcode, (short)instruction.getRegCount(), instruction.getStartRegister(), methodIdItem); } else { Instruction35ms instruction = (Instruction35ms)analyzedInstruction.instruction; Opcode opcode; if (isSuper) { opcode = Opcode.INVOKE_SUPER; } else { opcode = Opcode.INVOKE_VIRTUAL; } deodexedInstruction = new Instruction35c(opcode, instruction.getRegCount(), instruction.getRegisterD(), instruction.getRegisterE(), instruction.getRegisterF(), instruction.getRegisterG(), instruction.getRegisterA(), methodIdItem); } analyzedInstruction.setDeodexedInstruction(deodexedInstruction); analyzeInstruction(analyzedInstruction); return true; } private boolean analyzePutGetVolatile(AnalyzedInstruction analyzedInstruction) { return analyzePutGetVolatile(analyzedInstruction, true); } private boolean analyzePutGetVolatile(AnalyzedInstruction analyzedInstruction, boolean analyzeResult) { FieldIdItem fieldIdItem = (FieldIdItem)(((InstructionWithReference)analyzedInstruction.instruction).getReferencedItem()); String fieldType = fieldIdItem.getFieldType().getTypeDescriptor(); Opcode opcode = OdexedFieldInstructionMapper.getAndCheckDeodexedOpcodeForOdexedOpcode(fieldType, analyzedInstruction.instruction.opcode); Instruction deodexedInstruction; if (analyzedInstruction.instruction.opcode.isOdexedStaticVolatile()) { SingleRegisterInstruction instruction = (SingleRegisterInstruction)analyzedInstruction.instruction; if (analyzedInstruction.instruction.opcode.format == Format.Format21c) { deodexedInstruction = new Instruction21c(opcode, (byte)instruction.getRegisterA(), fieldIdItem); } else { assert(analyzedInstruction.instruction.opcode.format == Format.Format41c); deodexedInstruction = new Instruction41c(opcode, (byte)instruction.getRegisterA(), fieldIdItem); } } else { TwoRegisterInstruction instruction = (TwoRegisterInstruction)analyzedInstruction.instruction; if (analyzedInstruction.instruction.opcode.format == Format.Format22c) { deodexedInstruction = new Instruction22c(opcode, (byte)instruction.getRegisterA(), (byte)instruction.getRegisterB(), fieldIdItem); } else { assert(analyzedInstruction.instruction.opcode.format == Format.Format52c); deodexedInstruction = new Instruction52c(opcode, (byte)instruction.getRegisterA(), (byte)instruction.getRegisterB(), fieldIdItem); } } analyzedInstruction.setDeodexedInstruction(deodexedInstruction); if (analyzeResult) { analyzeInstruction(analyzedInstruction); } return true; } private void analyzeInvokeObjectInitJumbo(AnalyzedInstruction analyzedInstruction) { Instruction5rc instruction = (Instruction5rc)analyzedInstruction.instruction; Instruction5rc deodexedInstruction = new Instruction5rc(Opcode.INVOKE_DIRECT_JUMBO, instruction.getRegCount(), instruction.getStartRegister(), instruction.getReferencedItem()); analyzedInstruction.setDeodexedInstruction(deodexedInstruction); analyzeInstruction(analyzedInstruction); } private static boolean checkArrayFieldAssignment(RegisterType.Category arrayFieldCategory, RegisterType.Category instructionCategory) { if (arrayFieldCategory == instructionCategory) { return true; } if ((arrayFieldCategory == RegisterType.Category.Integer && instructionCategory == RegisterType.Category.Float) || (arrayFieldCategory == RegisterType.Category.Float && instructionCategory == RegisterType.Category.Integer)) { return true; } return false; } private static RegisterType getAndCheckSourceRegister(AnalyzedInstruction analyzedInstruction, int registerNumber, EnumSet validCategories) { assert registerNumber >= 0 && registerNumber < analyzedInstruction.postRegisterMap.length; RegisterType registerType = analyzedInstruction.getPreInstructionRegisterType(registerNumber); assert registerType != null; checkRegister(registerType, registerNumber, validCategories); if (validCategories == WideLowCategories) { checkRegister(registerType, registerNumber, WideLowCategories); checkWidePair(registerNumber, analyzedInstruction); RegisterType secondRegisterType = analyzedInstruction.getPreInstructionRegisterType(registerNumber + 1); assert secondRegisterType != null; checkRegister(secondRegisterType, registerNumber+1, WideHighCategories); } return registerType; } private static void checkRegister(RegisterType registerType, int registerNumber, EnumSet validCategories) { if (!validCategories.contains(registerType.category)) { throw new ValidationException(String.format("Invalid register type %s for register v%d.", registerType.toString(), registerNumber)); } } private static void checkWidePair(int registerNumber, AnalyzedInstruction analyzedInstruction) { if (registerNumber + 1 >= analyzedInstruction.postRegisterMap.length) { throw new ValidationException(String.format("v%d cannot be used as the first register in a wide register" + "pair because it is the last register.", registerNumber)); } } private static interface RegisterIterator { int getRegister(); boolean moveNext(); int getCount(); boolean pastEnd(); } private static class Format35cRegisterIterator implements RegisterIterator { private final int registerCount; private final int[] registers; private int currentRegister = 0; public Format35cRegisterIterator(FiveRegisterInstruction instruction) { registerCount = instruction.getRegCount(); registers = new int[]{instruction.getRegisterD(), instruction.getRegisterE(), instruction.getRegisterF(), instruction.getRegisterG(), instruction.getRegisterA()}; } public int getRegister() { return registers[currentRegister]; } public boolean moveNext() { currentRegister++; return !pastEnd(); } public int getCount() { return registerCount; } public boolean pastEnd() { return currentRegister >= registerCount; } } private static class Format3rcRegisterIterator implements RegisterIterator { private final int startRegister; private final int registerCount; private int currentRegister = 0; public Format3rcRegisterIterator(RegisterRangeInstruction instruction) { startRegister = instruction.getStartRegister(); registerCount = instruction.getRegCount(); } public int getRegister() { return startRegister + currentRegister; } public boolean moveNext() { currentRegister++; return !pastEnd(); } public int getCount() { return registerCount; } public boolean pastEnd() { return currentRegister >= registerCount; } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/MethodAnalyzer.java
Java
asf20
180,638
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.TypeIdItem; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import static org.jf.dexlib.Code.Analysis.ClassPath.ClassDef; public class RegisterType { private final static HashMap<RegisterType, RegisterType> internedRegisterTypes = new HashMap<RegisterType, RegisterType>(); public final Category category; public final ClassDef type; private RegisterType(Category category, ClassDef type) { assert ((category == Category.Reference || category == Category.UninitRef || category == Category.UninitThis) && type != null) || ((category != Category.Reference && category != Category.UninitRef && category != Category.UninitThis) && type == null); this.category = category; this.type = type; } @Override public String toString() { return "(" + category.name() + (type==null?"":("," + type.getClassType())) + ")"; } public void writeTo(Writer writer) throws IOException { writer.write('('); writer.write(category.name()); if (type != null) { writer.write(','); writer.write(type.getClassType()); } writer.write(')'); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RegisterType that = (RegisterType) o; if (category != that.category) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; return true; } @Override public int hashCode() { int result = category.hashCode(); result = 31 * result + (type != null ? type.hashCode() : 0); return result; } public static enum Category { //the Unknown category denotes a register type that hasn't been determined yet Unknown, Uninit, Null, One, Boolean, Byte, PosByte, Short, PosShort, Char, Integer, Float, LongLo, LongHi, DoubleLo, DoubleHi, //the UninitRef category is used after a new-instance operation, and before the corresponding <init> is called UninitRef, //the UninitThis category is used the "this" register inside an <init> method, before the superclass' <init> //method is called UninitThis, Reference, //This is used when there are multiple incoming execution paths that have incompatible register types. For //example if the register's type is an Integer on one incomming code path, but is a Reference type on another //incomming code path. There is no register type that can hold either an Integer or a Reference. Conflicted; //this table is used when merging register types. For example, if a particular register can be either a Byte //or a Char, then the "merged" type of that register would be Integer, because it is the "smallest" type can //could hold either type of value. protected static Category[][] mergeTable = { /* Unknown Uninit Null One, Boolean Byte PosByte Short PosShort Char Integer, Float, LongLo LongHi DoubleLo DoubleHi UninitRef UninitThis Reference Conflicted*/ /*Unknown*/ {Unknown, Uninit, Null, One, Boolean, Byte, PosByte, Short, PosShort, Char, Integer, Float, LongLo, LongHi, DoubleLo, DoubleHi, UninitRef, UninitThis, Reference, Conflicted}, /*Uninit*/ {Uninit, Uninit, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*Null*/ {Null, Conflicted, Null, Boolean, Boolean, Byte, PosByte, Short, PosShort, Char, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Reference, Conflicted}, /*One*/ {One, Conflicted, Boolean, One, Boolean, Byte, PosByte, Short, PosShort, Char, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*Boolean*/ {Boolean, Conflicted, Boolean, Boolean, Boolean, Byte, PosByte, Short, PosShort, Char, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*Byte*/ {Byte, Conflicted, Byte, Byte, Byte, Byte, Byte, Short, Short, Integer, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*PosByte*/ {PosByte, Conflicted, PosByte, PosByte, PosByte, Byte, PosByte, Short, PosShort, Char, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*Short*/ {Short, Conflicted, Short, Short, Short, Short, Short, Short, Short, Integer, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*PosShort*/ {PosShort, Conflicted, PosShort, PosShort, PosShort, Short, PosShort, Short, PosShort, Char, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*Char*/ {Char, Conflicted, Char, Char, Char, Integer, Char, Integer, Char, Char, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*Integer*/ {Integer, Conflicted, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*Float*/ {Float, Conflicted, Float, Float, Float, Float, Float, Float, Float, Float, Integer, Float, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*LongLo*/ {LongLo, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, LongLo, Conflicted, LongLo, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*LongHi*/ {LongHi, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, LongHi, Conflicted, LongHi, Conflicted, Conflicted, Conflicted, Conflicted}, /*DoubleLo*/ {DoubleLo, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, LongLo, Conflicted, DoubleLo, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*DoubleHi*/ {DoubleHi, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, LongHi, Conflicted, DoubleHi, Conflicted, Conflicted, Conflicted, Conflicted}, /*UninitRef*/ {UninitRef, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted}, /*UninitThis*/ {UninitThis, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, UninitThis, Conflicted, Conflicted}, /*Reference*/ {Reference, Conflicted, Reference, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Reference, Conflicted}, /*Conflicted*/ {Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted, Conflicted} }; //this table is used to denote whether a given value type can be assigned to a "slot" of a certain type. For //example, to determine if you can assign a Boolean value to a particular array "slot", where the array is an //array of Integers, you would look up assignmentTable[Boolean.ordinal()][Integer.ordinal()] //Note that not all slot types in the table are expected to be used. For example, it doesn't make sense to //check if a value can be assigned to an uninitialized reference slot - because there is no such thing. protected static boolean[][] assigmentTable = { /* Unknown Uninit Null One, Boolean Byte PosByte Short PosShort Char Integer, Float, LongLo LongHi DoubleLo DoubleHi UninitRef UninitThis Reference Conflicted |slot type*/ /*Unknown*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}, /*Uninit*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}, /*Null*/ {false, false, true, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, false}, /*One*/ {false, false, false, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false}, /*Boolean*/ {false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false}, /*Byte*/ {false, false, false, false, false, true, false, true, true, false, true, true, false, false, false, false, false, false, false, false}, /*PosByte*/ {false, false, false, false, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false}, /*Short*/ {false, false, false, false, false, false, false, true, false, false, true, true, false, false, false, false, false, false, false, false}, /*PosShort*/ {false, false, false, false, false, false, false, true, true, true, true, true, false, false, false, false, false, false, false, false}, /*Char*/ {false, false, false, false, false, false, false, false, false, true, true, true, false, false, false, false, false, false, false, false}, /*Integer*/ {false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false}, /*Float*/ {false, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false}, /*LongLo*/ {false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false, false, false, false, false}, /*LongHi*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false, false, false, false}, /*DoubleLo*/ {false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false, false, false, false, false}, /*DoubleHi*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false, false, false, false}, /*UninitRef*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}, /*UninitThis*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}, /*Reference*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false}, /*Conflicted*/ {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false} /*----------*/ /*value type*/ }; } public static RegisterType getRegisterTypeForType(String type) { switch (type.charAt(0)) { case 'V': throw new ValidationException("The V type can only be used as a method return type"); case 'Z': return getRegisterType(Category.Boolean, null); case 'B': return getRegisterType(Category.Byte, null); case 'S': return getRegisterType(Category.Short, null); case 'C': return getRegisterType(Category.Char, null); case 'I': return getRegisterType(Category.Integer, null); case 'F': return getRegisterType(Category.Float, null); case 'J': return getRegisterType(Category.LongLo, null); case 'D': return getRegisterType(Category.DoubleLo, null); case 'L': case '[': return getRegisterType(Category.Reference, ClassPath.getClassDef(type)); default: throw new RuntimeException("Invalid type: " + type); } } public static RegisterType getRegisterTypeForTypeIdItem(TypeIdItem typeIdItem) { return getRegisterTypeForType(typeIdItem.getTypeDescriptor()); } public static RegisterType getWideRegisterTypeForTypeIdItem(TypeIdItem typeIdItem, boolean firstRegister) { if (typeIdItem.getRegisterCount() == 1) { throw new RuntimeException("Cannot use this method for non-wide register type: " + typeIdItem.getTypeDescriptor()); } switch (typeIdItem.getTypeDescriptor().charAt(0)) { case 'J': if (firstRegister) { return getRegisterType(Category.LongLo, null); } else { return getRegisterType(Category.LongHi, null); } case 'D': if (firstRegister) { return getRegisterType(Category.DoubleLo, null); } else { return getRegisterType(Category.DoubleHi, null); } default: throw new RuntimeException("Invalid type: " + typeIdItem.getTypeDescriptor()); } } public static RegisterType getRegisterTypeForLiteral(long literalValue) { if (literalValue < -32768) { return getRegisterType(Category.Integer, null); } if (literalValue < -128) { return getRegisterType(Category.Short, null); } if (literalValue < 0) { return getRegisterType(Category.Byte, null); } if (literalValue == 0) { return getRegisterType(Category.Null, null); } if (literalValue == 1) { return getRegisterType(Category.One, null); } if (literalValue < 128) { return getRegisterType(Category.PosByte, null); } if (literalValue < 32768) { return getRegisterType(Category.PosShort, null); } if (literalValue < 65536) { return getRegisterType(Category.Char, null); } return getRegisterType(Category.Integer, null); } public RegisterType merge(RegisterType type) { if (type == null || type == this) { return this; } Category mergedCategory = Category.mergeTable[this.category.ordinal()][type.category.ordinal()]; ClassDef mergedType = null; if (mergedCategory == Category.Reference) { if (this.type instanceof ClassPath.UnresolvedClassDef || type.type instanceof ClassPath.UnresolvedClassDef) { mergedType = ClassPath.getUnresolvedObjectClassDef(); } else { mergedType = ClassPath.getCommonSuperclass(this.type, type.type); } } else if (mergedCategory == Category.UninitRef || mergedCategory == Category.UninitThis) { if (this.category == Category.Unknown) { return type; } assert type.category == Category.Unknown; return this; } return RegisterType.getRegisterType(mergedCategory, mergedType); } public boolean canBeAssignedTo(RegisterType slotType) { if (Category.assigmentTable[this.category.ordinal()][slotType.category.ordinal()]) { if (this.category == Category.Reference && slotType.category == Category.Reference) { if (!slotType.type.isInterface()) { return this.type.extendsClass(slotType.type); } //for verification, we assume all objects implement all interfaces, so we don't verify the type if //slotType is an interface } return true; } return false; } public static RegisterType getUnitializedReference(ClassDef classType) { //We always create a new RegisterType instance for an uninit ref. Each unique uninit RegisterType instance //is used to track a specific uninitialized reference, so that if multiple registers contain the same //uninitialized reference, then they can all be upgraded to an initialized reference when the appropriate //<init> is invoked return new RegisterType(Category.UninitRef, classType); } public static RegisterType getRegisterType(Category category, ClassDef classType) { RegisterType newRegisterType = new RegisterType(category, classType); RegisterType internedRegisterType = internedRegisterTypes.get(newRegisterType); if (internedRegisterType == null) { internedRegisterTypes.put(newRegisterType, newRegisterType); return newRegisterType; } return internedRegisterType; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/RegisterType.java
Java
asf20
22,735
/* * [The "BSD licence"] * Copyright (c) 2011 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Analysis; import org.jf.dexlib.ClassDefItem; import org.jf.dexlib.DexFile; import org.jf.dexlib.TypeIdItem; import java.util.HashMap; /** * Keeps a simple map of classes defined in a dex file, allowing you to look them up by TypeIdItem or name */ public class DexFileClassMap { private final HashMap<String, ClassDefItem> definedClasses = new HashMap<String, ClassDefItem>(); public DexFileClassMap(DexFile dexFile) { for (ClassDefItem classDefItem: dexFile.ClassDefsSection.getItems()) { definedClasses.put(classDefItem.getClassType().getTypeDescriptor(), classDefItem); } } public ClassDefItem getClassDefByName(String typeName) { return definedClasses.get(typeName); } public ClassDefItem getClassDefByType(TypeIdItem typeIdItem) { return definedClasses.get(typeIdItem.getTypeDescriptor()); } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Analysis/DexFileClassMap.java
Java
asf20
2,394
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public abstract class OffsetInstruction extends Instruction { protected OffsetInstruction(Opcode opcode) { super(opcode); } public abstract int getTargetAddressOffset(); public abstract void updateTargetAddressOffset(int targetAddressOffset); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/OffsetInstruction.java
Java
asf20
1,801
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; import org.jf.dexlib.*; public enum ReferenceType { string(-1), type(0), field(1), method(2), none(-1); private int validationErrorReferenceType; private ReferenceType(int validationErrorReferenceType) { this.validationErrorReferenceType = validationErrorReferenceType; } public boolean checkItem(Item item) { switch (this) { case string: return item instanceof StringIdItem; case type: return item instanceof TypeIdItem; case field: return item instanceof FieldIdItem; case method: return item instanceof MethodIdItem; } return false; } public static ReferenceType fromValidationErrorReferenceType(int validationErrorReferenceType) { switch (validationErrorReferenceType) { case 0: return type; case 1: return field; case 2: return method; } return null; } public int getValidationErrorReferenceType() { if (validationErrorReferenceType == -1) { throw new RuntimeException("This reference type cannot be referenced from a throw-validation-error" + " instruction"); } return validationErrorReferenceType; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/ReferenceType.java
Java
asf20
2,910
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; import org.jf.dexlib.Code.Format.Format; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; public abstract class Instruction { public final Opcode opcode; /** * Returns the size of this instruction in code blocks, assuming the instruction is located at the given address * @param codeAddress the code address where the instruction is located * @return The size of this instruction in code blocks **/ public int getSize(int codeAddress) { return opcode.format.size/2; } protected Instruction(Opcode opcode) { this.opcode = opcode; } public abstract Format getFormat(); public int write(AnnotatedOutput out, int currentCodeAddress) { if (out.annotates()) { annotateInstruction(out, currentCodeAddress); } writeInstruction(out, currentCodeAddress); return currentCodeAddress + getSize(currentCodeAddress); } protected void annotateInstruction(AnnotatedOutput out, int currentCodeAddress) { out.annotate(getSize(currentCodeAddress)*2, "[0x" + Integer.toHexString(currentCodeAddress) + "] " + opcode.name + " instruction"); } protected abstract void writeInstruction(AnnotatedOutput out, int currentCodeAddress); public static interface InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex); } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Instruction.java
Java
asf20
2,988
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface EncodedLiteralInstruction extends LiteralInstruction { long getDecodedLiteral(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/EncodedLiteralInstruction.java
Java
asf20
1,697
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface LiteralInstruction { long getLiteral(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/LiteralInstruction.java
Java
asf20
1,594
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface FiveRegisterInstruction extends InvokeInstruction { byte getRegisterA(); byte getRegisterD(); byte getRegisterE(); byte getRegisterF(); byte getRegisterG(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/FiveRegisterInstruction.java
Java
asf20
1,727
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface OdexedFieldAccess { int getFieldOffset(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/OdexedFieldAccess.java
Java
asf20
1,596
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface SingleRegisterInstruction { int getRegisterA(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/SingleRegisterInstruction.java
Java
asf20
1,602
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; import org.jf.dexlib.*; import org.jf.dexlib.Util.NumberUtils; public abstract class InstructionWithReference extends Instruction { private Item referencedItem; private ReferenceType referenceType; protected InstructionWithReference(Opcode opcode, Item referencedItem) { super(opcode); this.referencedItem = referencedItem; this.referenceType = opcode.referenceType; checkReferenceType(); } protected InstructionWithReference(Opcode opcode, Item referencedItem, ReferenceType referenceType) { super(opcode); this.referencedItem = referencedItem; this.referenceType = referenceType; checkReferenceType(); } protected InstructionWithReference(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.referenceType = readReferenceType(opcode, buffer, bufferIndex); int itemIndex = getReferencedItemIndex(buffer, bufferIndex); lookupReferencedItem(dexFile, opcode, itemIndex); } protected int getReferencedItemIndex(byte[] buffer, int bufferIndex) { return NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); } public ReferenceType getReferenceType() { return referenceType; } public Item getReferencedItem() { return referencedItem; } protected ReferenceType readReferenceType(Opcode opcode, byte[] buffer, int bufferIndex) { return opcode.referenceType; } private void lookupReferencedItem(DexFile dexFile, Opcode opcode, int itemIndex) { switch (referenceType) { case field: referencedItem = dexFile.FieldIdsSection.getItemByIndex(itemIndex); return; case method: referencedItem = dexFile.MethodIdsSection.getItemByIndex(itemIndex); return; case type: referencedItem = dexFile.TypeIdsSection.getItemByIndex(itemIndex); return; case string: referencedItem = dexFile.StringIdsSection.getItemByIndex(itemIndex); } } private void checkReferenceType() { switch (referenceType) { case field: if (!(referencedItem instanceof FieldIdItem)) { throw new RuntimeException(referencedItem.getClass().getSimpleName() + " is the wrong item type for opcode " + opcode.name + ". Expecting FieldIdItem."); } return; case method: if (!(referencedItem instanceof MethodIdItem)) { throw new RuntimeException(referencedItem.getClass().getSimpleName() + " is the wrong item type for opcode " + opcode.name + ". Expecting MethodIdItem."); } return; case type: if (!(referencedItem instanceof TypeIdItem)) { throw new RuntimeException(referencedItem.getClass().getSimpleName() + " is the wrong item type for opcode " + opcode.name + ". Expecting TypeIdItem."); } return; case string: if (!(referencedItem instanceof StringIdItem)) { throw new RuntimeException(referencedItem.getClass().getSimpleName() + " is the wrong item type for opcode " + opcode.name + ". Expecting StringIdItem."); } return; default: if (referencedItem != null) { throw new RuntimeException(referencedItem.getClass().getSimpleName() + " is invalid for opcode " + opcode.name + ". This opcode does not reference an item"); } } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/InstructionWithReference.java
Java
asf20
5,379
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction21t extends OffsetInstruction implements SingleRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private short targetAddressOffset; public Instruction21t(Opcode opcode, short regA, short offB) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } if (offB == 0) { throw new RuntimeException("The address offset cannot be 0."); } this.regA = (byte)regA; this.targetAddressOffset = offB; } private Instruction21t(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); assert buffer[bufferIndex] == opcode.value; regA = buffer[bufferIndex + 1]; targetAddressOffset = NumberUtils.decodeShort(buffer, bufferIndex + 2); assert targetAddressOffset != 0; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeShort(targetAddressOffset); } public void updateTargetAddressOffset(int targetAddressOffset) { if (targetAddressOffset < Short.MIN_VALUE || targetAddressOffset > Short.MAX_VALUE) { throw new RuntimeException("The address offset " + targetAddressOffset + " is out of range. It must be in [-32768, 32767]"); } if (targetAddressOffset == 0) { throw new RuntimeException("The address offset cannot be 0"); } this.targetAddressOffset = (short) targetAddressOffset; } public Format getFormat() { return Format.Format21t; } public int getRegisterA() { return regA & 0xFF; } public int getTargetAddressOffset() { return targetAddressOffset; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction21t(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction21t.java
Java
asf20
4,011
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OdexedFieldAccess; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction22cs extends Instruction implements TwoRegisterInstruction, OdexedFieldAccess { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private byte regB; private short fieldOffset; public Instruction22cs(Opcode opcode, byte regA, byte regB, int fieldOffset) { super(opcode); if (regA >= 1 << 4 || regB >= 1 << 4) { throw new RuntimeException("The register number must be less than v16"); } if (fieldOffset >= 1 << 16) { throw new RuntimeException("The field offset must be less than 65536"); } this.regA = regA; this.regB = regB; this.fieldOffset = (short)fieldOffset; } private Instruction22cs(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.regB = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); this.fieldOffset = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte((regB << 4) | regA); out.writeShort(fieldOffset); } public Format getFormat() { return Format.Format22cs; } public int getRegisterA() { return regA; } public int getRegisterB() { return regB; } public int getFieldOffset() { return fieldOffset & 0xFFFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction22cs(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction22cs.java
Java
asf20
3,703
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; public interface InstructionWithJumboVariant { Instruction makeJumbo(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/InstructionWithJumboVariant.java
Java
asf20
1,718
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction11x extends Instruction implements SingleRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; public Instruction11x(Opcode opcode, short regA) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; } private Instruction11x(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = (byte)NumberUtils.decodeUnsignedByte(buffer[bufferIndex + 1]); } public void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); } public Format getFormat() { return Format.Format11x; } public int getRegisterA() { return regA & 0xFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction11x(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction11x.java
Java
asf20
2,968
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; public enum Format { Format10t(Instruction10t.Factory, 2), Format10x(Instruction10x.Factory, 2), Format11n(Instruction11n.Factory, 2), Format11x(Instruction11x.Factory, 2), Format12x(Instruction12x.Factory, 2), Format20bc(Instruction20bc.Factory, 4), Format20t(Instruction20t.Factory, 4), Format21c(Instruction21c.Factory, 4), Format21h(Instruction21h.Factory, 4), Format21s(Instruction21s.Factory, 4), Format21t(Instruction21t.Factory, 4), Format22b(Instruction22b.Factory, 4), Format22c(Instruction22c.Factory, 4), Format22cs(Instruction22cs.Factory, 4), Format22s(Instruction22s.Factory, 4), Format22t(Instruction22t.Factory, 4), Format22x(Instruction22x.Factory, 4), Format23x(Instruction23x.Factory, 4), Format30t(Instruction30t.Factory, 6), Format31c(Instruction31c.Factory, 6), Format31i(Instruction31i.Factory, 6), Format31t(Instruction31t.Factory, 6), Format32x(Instruction32x.Factory, 6), Format35c(Instruction35c.Factory, 6), Format35mi(Instruction35mi.Factory, 6), Format35ms(Instruction35ms.Factory, 6), Format3rc(Instruction3rc.Factory, 6), Format3rmi(Instruction3rmi.Factory, 6), Format3rms(Instruction3rms.Factory, 6), Format41c(Instruction41c.Factory, 8), Format51l(Instruction51l.Factory, 10), Format52c(Instruction52c.Factory, 10), Format5rc(Instruction5rc.Factory, 10), ArrayData(null, -1, true), PackedSwitchData(null, -1, true), SparseSwitchData(null, -1, true), UnresolvedOdexInstruction(null, -1, false), ; public final Instruction.InstructionFactory Factory; public final int size; public final boolean variableSizeFormat; private Format(Instruction.InstructionFactory factory, int size) { this(factory, size, false); } private Format(Instruction.InstructionFactory factory, int size, boolean variableSizeFormat) { this.Factory = factory; this.size = size; this.variableSizeFormat = variableSizeFormat; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Format.java
Java
asf20
3,626
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.LiteralInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction21s extends Instruction implements SingleRegisterInstruction, LiteralInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private short litB; public Instruction21s(Opcode opcode, short regA, short litB) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; this.litB = litB; } private Instruction21s(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = buffer[bufferIndex + 1]; this.litB = NumberUtils.decodeShort(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeShort(litB); } public Format getFormat() { return Format.Format21s; } public int getRegisterA() { return regA & 0xFF; } public long getLiteral() { return litB; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction21s(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction21s.java
Java
asf20
3,220
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.LiteralInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction11n extends Instruction implements SingleRegisterInstruction, LiteralInstruction { public static final InstructionFactory Factory = new Factory(); private byte regA; private byte litB; public Instruction11n(Opcode opcode, byte regA, byte litB) { super(opcode); if (regA >= 1 << 4) { throw new RuntimeException("The register number must be less than v16"); } if (litB < -(1 << 3) || litB >= 1 << 3) { throw new RuntimeException("The literal value must be between -8 and 7 inclusive"); } this.regA = regA; this.litB = litB; } private Instruction11n(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.litB = NumberUtils.decodeHighSignedNibble(buffer[bufferIndex + 1]); } public void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte((litB << 4) | regA); } public Format getFormat() { return Format.Format11n; } public int getRegisterA() { return regA; } public long getLiteral() { return litB; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction11n(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction11n.java
Java
asf20
3,392
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Opcode; public class UnknownInstruction extends Instruction10x { private short originalOpcode; public UnknownInstruction(short originalOpcode) { super(Opcode.NOP); this.originalOpcode = originalOpcode; } public short getOriginalOpcode() { return originalOpcode; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/UnknownInstruction.java
Java
asf20
1,939
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.FiveRegisterInstruction; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.MethodIdItem; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; import static org.jf.dexlib.Code.Opcode.*; public class Instruction35c extends InstructionWithReference implements FiveRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regCount; private byte regA; private byte regD; private byte regE; private byte regF; private byte regG; public Instruction35c(Opcode opcode, int regCount, byte regD, byte regE, byte regF, byte regG, byte regA, Item referencedItem) { super(opcode, referencedItem); if (regCount > 5) { throw new RuntimeException("regCount cannot be greater than 5"); } if (regD >= 1 << 4 || regE >= 1 << 4 || regF >= 1 << 4 || regG >= 1 << 4 || regA >= 1 << 4) { throw new RuntimeException("All register args must fit in 4 bits"); } checkItem(opcode, referencedItem, regCount); this.regCount = (byte)regCount; this.regA = regA; this.regD = regD; this.regE = regE; this.regF = regF; this.regG = regG; } protected Instruction35c(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); this.regCount = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.regD = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 4]); this.regE = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 4]); this.regF = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 5]); this.regG = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 5]); if (getRegCount() > 5) { throw new RuntimeException("regCount cannot be greater than 5"); } checkItem(opcode, getReferencedItem(), getRegCount()); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { if(getReferencedItem().getIndex() > 0xFFFF) { if (opcode.hasJumboOpcode()) { throw new RuntimeException(String.format("%s index is too large. Use the %s instruction instead.", opcode.referenceType.name(), opcode.getJumboOpcode().name)); } else { throw new RuntimeException(String.format("%s index is too large.", opcode.referenceType.name())); } } out.writeByte(opcode.value); out.writeByte((regCount << 4) | regA); out.writeShort(getReferencedItem().getIndex()); out.writeByte((regE << 4) | regD); out.writeByte((regG << 4) | regF); } public Format getFormat() { return Format.Format35c; } public int getRegCount() { return regCount; } public byte getRegisterA() { return regA; } public byte getRegisterD() { return regD; } public byte getRegisterE() { return regE; } public byte getRegisterF() { return regF; } public byte getRegisterG() { return regG; } private static void checkItem(Opcode opcode, Item item, int regCount) { if (opcode == FILLED_NEW_ARRAY) { //check data for filled-new-array opcode String type = ((TypeIdItem) item).getTypeDescriptor(); if (type.charAt(0) != '[') { throw new RuntimeException("The type must be an array type"); } if (type.charAt(1) == 'J' || type.charAt(1) == 'D') { throw new RuntimeException("The type cannot be an array of longs or doubles"); } } else if (opcode.value >= INVOKE_VIRTUAL.value && opcode.value <= INVOKE_INTERFACE.value || opcode == INVOKE_DIRECT_EMPTY) { //check data for invoke-* opcodes MethodIdItem methodIdItem = (MethodIdItem) item; int parameterRegisterCount = methodIdItem.getPrototype().getParameterRegisterCount(); if (opcode != INVOKE_STATIC) { parameterRegisterCount++; } if (parameterRegisterCount != regCount) { throw new RuntimeException("regCount does not match the number of arguments of the method"); } } } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction35c(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction35c.java
Java
asf20
6,618
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction52c extends InstructionWithJumboReference implements TwoRegisterInstruction { public static final InstructionFactory Factory = new Factory(); private short regA; private short regB; public Instruction52c(Opcode opcode, int regA, int regB, Item referencedItem) { super(opcode, referencedItem); if (regA >= 1 << 16) { throw new RuntimeException("The register number must be less than v65536"); } if (regB >= 1 << 16) { throw new RuntimeException("The register number must be less than v65536"); } this.regA = (short)regA; this.regB = (short)regB; } private Instruction52c(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); this.regA = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 6); this.regB = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 8); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(0xFF); out.writeByte(opcode.value); out.writeInt(getReferencedItem().getIndex()); out.writeShort(getRegisterA()); out.writeShort(getRegisterB()); } public Format getFormat() { return Format.Format52c; } public int getRegisterA() { return regA & 0xFFFF; } public int getRegisterB() { return regB & 0xFFFF; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction52c(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction52c.java
Java
asf20
3,632
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; public class Instruction10x extends Instruction { public static final InstructionFactory Factory = new Factory(); public Instruction10x(Opcode opcode) { super(opcode); } public Instruction10x(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); assert (buffer[bufferIndex] & 0xFF) == opcode.value; assert buffer[bufferIndex + 1] == 0x00; } public void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(0); } public Format getFormat() { return Format.Format10x; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction10x(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction10x.java
Java
asf20
2,574
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction30t extends OffsetInstruction { public static final InstructionFactory Factory = new Factory(); private int targetAddressOffset; public Instruction30t(Opcode opcode, int offA) { super(opcode); this.targetAddressOffset = offA; } private Instruction30t(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); assert buffer[bufferIndex] == opcode.value; this.targetAddressOffset = NumberUtils.decodeInt(buffer, bufferIndex+2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(0x00); out.writeInt(targetAddressOffset); } public void updateTargetAddressOffset(int targetAddressOffset) { this.targetAddressOffset = targetAddressOffset; } public Format getFormat() { return Format.Format30t; } public int getTargetAddressOffset() { return targetAddressOffset; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction30t(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction30t.java
Java
asf20
3,045
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.EncodedLiteralInstruction; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction21h extends Instruction implements SingleRegisterInstruction, EncodedLiteralInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private short litB; public Instruction21h(Opcode opcode, short regA, short litB) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; this.litB = litB; } private Instruction21h(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = buffer[bufferIndex + 1]; this.litB = NumberUtils.decodeShort(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeShort(litB); } public Format getFormat() { return Format.Format21h; } public int getRegisterA() { return regA & 0xFF; } public long getLiteral() { return litB; } public long getDecodedLiteral() { if (opcode == Opcode.CONST_HIGH16) { return litB << 16; } else { assert opcode == Opcode.CONST_WIDE_HIGH16; return ((long)litB) << 48; } } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction21h(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction21h.java
Java
asf20
3,476
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.ThreeRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; public class Instruction23x extends Instruction implements ThreeRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private byte regB; private byte regC; public Instruction23x(Opcode opcode, short regA, short regB, short regC) { super(opcode); if (regA >= 1 << 8 || regB >= 1 << 8 || regC >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; this.regB = (byte)regB; this.regC = (byte)regC; } private Instruction23x(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = buffer[bufferIndex + 1]; this.regB = buffer[bufferIndex + 2]; this.regC = buffer[bufferIndex + 3]; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeByte(regB); out.writeByte(regC); } public Format getFormat() { return Format.Format23x; } public int getRegisterA() { return regA & 0xFF; } public int getRegisterB() { return regB & 0xFF; } public int getRegisterC() { return regC & 0xFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction23x(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction23x.java
Java
asf20
3,376
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction22x extends Instruction implements TwoRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private short regB; public Instruction22x(Opcode opcode, short regA, int regB) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v16"); } if (regB >= 1 << 16) { throw new RuntimeException("The register number must be less than v65536"); } this.regA = (byte)regA; this.regB = (short)regB; } private Instruction22x(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = buffer[bufferIndex + 1]; this.regB = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeShort(regB); } public Format getFormat() { return Format.Format22x; } public int getRegisterA() { return regA & 0xFF; } public int getRegisterB() { return regB & 0xFFFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction22x(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction22x.java
Java
asf20
3,307
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.LiteralInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction31i extends Instruction implements SingleRegisterInstruction, LiteralInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private int litB; public Instruction31i(Opcode opcode, short regA, int litB) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; this.litB = litB; } private Instruction31i(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = (byte)NumberUtils.decodeUnsignedByte(buffer[bufferIndex + 1]); this.litB = NumberUtils.decodeInt(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeInt(litB); } public Format getFormat() { return Format.Format31i; } public int getRegisterA() { return regA & 0xFF; } public long getLiteral() { return litB; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction31i(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction31i.java
Java
asf20
3,250
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.LiteralInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction22s extends Instruction implements TwoRegisterInstruction, LiteralInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private byte regB; private short litC; public Instruction22s(Opcode opcode, byte regA, byte regB, short litC) { super(opcode); if (regA >= 1 << 4 || regB >= 1 << 4) { throw new RuntimeException("The register number must be less than v16"); } this.regA = regA; this.regB = regB; this.litC = litC; } private Instruction22s(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.regB = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); this.litC = NumberUtils.decodeShort(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte((regB << 4) | regA); out.writeShort(litC); } public Format getFormat() { return Format.Format22s; } public int getRegisterA() { return regA; } public int getRegisterB() { return regB; } public long getLiteral() { return litC; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction22s(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction22s.java
Java
asf20
3,487
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction20t extends OffsetInstruction { public static final InstructionFactory Factory = new Factory(); private int targetAddressOffset; public Instruction20t(Opcode opcode, int offA) { super(opcode); this.targetAddressOffset = offA; if (targetAddressOffset == 0) { throw new RuntimeException("The address offset cannot be 0. Use goto/32 instead."); } //allow out of range address offsets here, so we have the option of replacing this instruction //with goto/16 or goto/32 later } private Instruction20t(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); assert buffer[bufferIndex] == opcode.value; this.targetAddressOffset = NumberUtils.decodeShort(buffer, bufferIndex+2); assert targetAddressOffset != 0; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { if (targetAddressOffset == 0) { throw new RuntimeException("The address offset cannot be 0. Use goto/32 instead"); } if (targetAddressOffset < -32768 || targetAddressOffset > 32767) { throw new RuntimeException("The address offset is out of range. It must be in [-32768,-1] or [1, 32768]"); } out.writeByte(opcode.value); out.writeByte(0x00); out.writeShort(targetAddressOffset); } public void updateTargetAddressOffset(int targetAddressOffset) { this.targetAddressOffset = targetAddressOffset; } public Format getFormat() { return Format.Format20t; } public int getTargetAddressOffset() { return targetAddressOffset; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction20t(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction20t.java
Java
asf20
3,732
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction22c extends InstructionWithReference implements TwoRegisterInstruction, InstructionWithJumboVariant { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private byte regB; public Instruction22c(Opcode opcode, byte regA, byte regB, Item referencedItem) { super(opcode, referencedItem); if (regA >= 1 << 4 || regB >= 1 << 4) { throw new RuntimeException("The register number must be less than v16"); } this.regA = regA; this.regB = regB; } private Instruction22c(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.regB = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { if(getReferencedItem().getIndex() > 0xFFFF) { if (opcode.hasJumboOpcode()) { throw new RuntimeException(String.format("%s index is too large. Use the %s instruction instead.", opcode.referenceType.name(), opcode.getJumboOpcode().name)); } else { throw new RuntimeException(String.format("%s index is too large.", opcode.referenceType.name())); } } out.writeByte(opcode.value); out.writeByte((regB << 4) | regA); out.writeShort(getReferencedItem().getIndex()); } public Format getFormat() { return Format.Format22c; } public int getRegisterA() { return regA; } public int getRegisterB() { return regB; } public Instruction makeJumbo() { Opcode jumboOpcode = opcode.getJumboOpcode(); if (jumboOpcode == null) { return null; } return new Instruction52c(jumboOpcode, getRegisterA(), getRegisterB(), getReferencedItem()); } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction22c(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction22c.java
Java
asf20
4,205
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction12x extends Instruction implements TwoRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private int regA; private int regB; public Instruction12x(Opcode opcode, byte regA, byte regB) { super(opcode); if (regA >= 1 << 4 || regB >= 1 << 4) { throw new RuntimeException("The register number must be less than v16"); } this.regA = regA; this.regB = regB; } private Instruction12x(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.regB = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); } public void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte((regB << 4) | regA); } public Format getFormat() { return Format.Format12x; } public int getRegisterA() { return regA; } public int getRegisterB() { return regB; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction12x(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction12x.java
Java
asf20
3,194
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; import java.util.Iterator; public class ArrayDataPseudoInstruction extends Instruction { public static final Instruction.InstructionFactory Factory = new Factory(); private int elementWidth; private byte[] encodedValues; @Override public int getSize(int codeAddress) { return ((encodedValues.length + 1)/2) + 4 + (codeAddress % 2); } public ArrayDataPseudoInstruction(int elementWidth, byte[] encodedValues) { super(Opcode.NOP); if (encodedValues.length % elementWidth != 0) { throw new RuntimeException("There are not a whole number of " + elementWidth + " byte elements"); } this.elementWidth = elementWidth; this.encodedValues = encodedValues; } public ArrayDataPseudoInstruction(byte[] buffer, int bufferIndex) { super(Opcode.NOP); byte opcodeByte = buffer[bufferIndex]; if (opcodeByte != 0x00) { throw new RuntimeException("Invalid opcode byte for an ArrayData pseudo-instruction"); } byte subopcodeByte = buffer[bufferIndex+1]; if (subopcodeByte != 0x03) { throw new RuntimeException("Invalid sub-opcode byte for an ArrayData pseudo-instruction"); } this.elementWidth = NumberUtils.decodeUnsignedShort(buffer, bufferIndex+2); int elementCount = NumberUtils.decodeInt(buffer, bufferIndex+4); this.encodedValues = new byte[elementCount * elementWidth]; System.arraycopy(buffer, bufferIndex+8, encodedValues, 0, elementCount * elementWidth); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.alignTo(4); int elementCount = encodedValues.length / elementWidth; out.writeByte(0x00); out.writeByte(0x03); out.writeShort(elementWidth); out.writeInt(elementCount); out.write(encodedValues); //make sure we're written out an even number of bytes out.alignTo(2); } protected void annotateInstruction(AnnotatedOutput out, int currentCodeAddress) { out.annotate(getSize(currentCodeAddress)*2, "[0x" + Integer.toHexString(currentCodeAddress) + "] " + "fill-array-data instruction"); } public Format getFormat() { return Format.ArrayData; } public int getElementWidth() { return elementWidth; } public int getElementCount() { return encodedValues.length / elementWidth; } public static class ArrayElement { public final byte[] buffer; public int bufferIndex; public final int elementWidth; public ArrayElement(byte[] buffer, int elementWidth) { this.buffer = buffer; this.elementWidth = elementWidth; } } public Iterator<ArrayElement> getElements() { return new Iterator<ArrayElement>() { final int elementCount = getElementCount(); int i=0; int position=0; final ArrayElement arrayElement = new ArrayElement(encodedValues, getElementWidth()); public boolean hasNext() { return i<elementCount; } public ArrayElement next() { arrayElement.bufferIndex = position; position += arrayElement.elementWidth; i++; return arrayElement; } public void remove() { } }; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { if (opcode != Opcode.NOP) { throw new RuntimeException("The opcode for an ArrayDataPseudoInstruction must be NOP"); } return new ArrayDataPseudoInstruction(buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/ArrayDataPseudoInstruction.java
Java
asf20
5,636
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction41c extends InstructionWithJumboReference implements SingleRegisterInstruction { public static final InstructionFactory Factory = new Factory(); private short regA; public Instruction41c(Opcode opcode, int regA, Item referencedItem) { super(opcode, referencedItem); if (regA >= 1 << 16) { throw new RuntimeException("The register number must be less than v65536"); } if (opcode == Opcode.NEW_INSTANCE_JUMBO) { assert referencedItem instanceof TypeIdItem; if (((TypeIdItem)referencedItem).getTypeDescriptor().charAt(0) != 'L') { throw new RuntimeException("Only class references can be used with the new-instance/jumbo opcode"); } } this.regA = (short)regA; } private Instruction41c(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); if (opcode == Opcode.NEW_INSTANCE_JUMBO && ((TypeIdItem)this.getReferencedItem()).getTypeDescriptor().charAt(0) != 'L') { throw new RuntimeException("Only class references can be used with the new-instance/jumbo opcode"); } this.regA = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 6); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(0xFF); out.writeByte(opcode.value); out.writeInt(getReferencedItem().getIndex()); out.writeShort(getRegisterA()); } public Format getFormat() { return Format.Format41c; } public int getRegisterA() { return regA & 0xFFFF; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction41c(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction41c.java
Java
asf20
3,936
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.RegisterRangeInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.MethodIdItem; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; import static org.jf.dexlib.Code.Opcode.*; public class Instruction5rc extends InstructionWithJumboReference implements RegisterRangeInstruction { public static final InstructionFactory Factory = new Factory(); private short regCount; private short startReg; public Instruction5rc(Opcode opcode, int regCount, int startReg, Item referencedItem) { super(opcode, referencedItem); if (regCount >= 1 << 16) { throw new RuntimeException("regCount must be less than 65536"); } if (regCount < 0) { throw new RuntimeException("regCount cannot be negative"); } if (startReg >= 1 << 16) { throw new RuntimeException("The beginning register of the range must be less than 65536"); } if (startReg < 0) { throw new RuntimeException("The beginning register of the range cannot be negative"); } this.regCount = (short)regCount; this.startReg = (short)startReg; checkItem(opcode, referencedItem, regCount); } private Instruction5rc(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); this.regCount = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 6); this.startReg = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 8); checkItem(opcode, getReferencedItem(), getRegCount()); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(0xff); out.writeByte(opcode.value); out.writeInt(this.getReferencedItem().getIndex()); out.writeShort(regCount); out.writeShort(startReg); } public Format getFormat() { return Format.Format5rc; } public int getRegCount() { return regCount & 0xFFFF; } public int getStartRegister() { return startReg & 0xFFFF; } private static void checkItem(Opcode opcode, Item item, int regCount) { if (opcode == FILLED_NEW_ARRAY_JUMBO) { //check data for filled-new-array/jumbo opcode String type = ((TypeIdItem) item).getTypeDescriptor(); if (type.charAt(0) != '[') { throw new RuntimeException("The type must be an array type"); } if (type.charAt(1) == 'J' || type.charAt(1) == 'D') { throw new RuntimeException("The type cannot be an array of longs or doubles"); } } else if (opcode.value >= INVOKE_VIRTUAL_JUMBO.value && opcode.value <= INVOKE_INTERFACE_JUMBO.value || opcode == INVOKE_OBJECT_INIT_JUMBO) { //check data for invoke-*/range opcodes MethodIdItem methodIdItem = (MethodIdItem) item; int parameterRegisterCount = methodIdItem.getPrototype().getParameterRegisterCount(); if (opcode != INVOKE_STATIC_JUMBO) { parameterRegisterCount++; } if (parameterRegisterCount != regCount) { throw new RuntimeException("regCount does not match the number of arguments of the method"); } } } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction5rc(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction5rc.java
Java
asf20
5,453
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.MultiOffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; import java.util.Iterator; public class SparseSwitchDataPseudoInstruction extends Instruction implements MultiOffsetInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private int[] keys; private int[] targets; @Override public int getSize(int codeAddress) { return getTargetCount() * 4 + 2 + (codeAddress % 2); } public SparseSwitchDataPseudoInstruction(int[] keys, int[] targets) { super(Opcode.NOP); if (keys.length != targets.length) { throw new RuntimeException("The number of keys and targets don't match"); } if (targets.length == 0) { throw new RuntimeException("The sparse-switch data must contain at least 1 key/target"); } if (targets.length > 0xFFFF) { throw new RuntimeException("The sparse-switch data contains too many elements. " + "The maximum number of switch elements is 65535"); } this.keys = keys; this.targets = targets; } public SparseSwitchDataPseudoInstruction(byte[] buffer, int bufferIndex) { super(Opcode.NOP); byte opcodeByte = buffer[bufferIndex]; if (opcodeByte != 0x00) { throw new RuntimeException("Invalid opcode byte for a SparseSwitchData pseudo-instruction"); } byte subopcodeByte = buffer[bufferIndex+1]; if (subopcodeByte != 0x02) { throw new RuntimeException("Invalid sub-opcode byte for a SparseSwitchData pseudo-instruction"); } int targetCount = NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); keys = new int[targetCount]; targets = new int[targetCount]; for (int i=0; i<targetCount; i++) { keys[i] = NumberUtils.decodeInt(buffer, bufferIndex + 4 + i*4); targets[i] = NumberUtils.decodeInt(buffer, bufferIndex + 4 + targetCount*4 + i*4); } } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.alignTo(4); out.writeByte(0x00); out.writeByte(0x02); out.writeShort(targets.length); if (targets.length > 0) { int key = keys[0]; out.writeInt(key); for (int i = 1; i < keys.length; i++) { key = keys[i]; assert key >= keys[i - 1]; out.writeInt(key); } for (int target : targets) { out.writeInt(target); } } } protected void annotateInstruction(AnnotatedOutput out, int currentCodeAddress) { out.annotate(getSize(currentCodeAddress)*2, "[0x" + Integer.toHexString(currentCodeAddress) + "] " + "sparse-switch-data instruction"); } public void updateTarget(int targetIndex, int targetAddressOffset) { targets[targetIndex] = targetAddressOffset; } public Format getFormat() { return Format.SparseSwitchData; } public int getTargetCount() { return targets.length; } public int[] getTargets() { return targets; } public int[] getKeys() { return keys; } public static class SparseSwitchTarget { public int key; public int targetAddressOffset; } public Iterator<SparseSwitchTarget> iterateKeysAndTargets() { return new Iterator<SparseSwitchTarget>() { final int targetCount = getTargetCount(); int i = 0; SparseSwitchTarget sparseSwitchTarget = new SparseSwitchTarget(); public boolean hasNext() { return i<targetCount; } public SparseSwitchTarget next() { sparseSwitchTarget.key = keys[i]; sparseSwitchTarget.targetAddressOffset = targets[i]; i++; return sparseSwitchTarget; } public void remove() { } }; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { if (opcode != Opcode.NOP) { throw new RuntimeException("The opcode for a SparseSwitchDataPseudoInstruction must be NOP"); } return new SparseSwitchDataPseudoInstruction(buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/SparseSwitchDataPseudoInstruction.java
Java
asf20
6,229
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.FiveRegisterInstruction; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OdexedInvokeVirtual; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction35ms extends Instruction implements FiveRegisterInstruction, OdexedInvokeVirtual { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regCount; private byte regA; private byte regD; private byte regE; private byte regF; private byte regG; private short vtableIndex; public Instruction35ms(Opcode opcode, int regCount, byte regD, byte regE, byte regF, byte regG, byte regA, int vtableIndex) { super(opcode); if (regCount > 5) { throw new RuntimeException("regCount cannot be greater than 5"); } if (regD >= 1 << 4 || regE >= 1 << 4 || regF >= 1 << 4 || regG >= 1 << 4 || regA >= 1 << 4) { throw new RuntimeException("All register args must fit in 4 bits"); } if (vtableIndex >= 1 << 16) { throw new RuntimeException("The method index must be less than 65536"); } this.regCount = (byte)regCount; this.regA = regA; this.regD = regD; this.regE = regE; this.regF = regF; this.regG = regG; this.vtableIndex = (short)vtableIndex; } private Instruction35ms(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regCount = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.regD = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 4]); this.regE = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 4]); this.regF = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 5]); this.regG = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 5]); this.vtableIndex = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte((regCount << 4) | regA); out.writeShort(vtableIndex); out.writeByte((regE << 4) | regD); out.writeByte((regG << 4) | regF); } public Format getFormat() { return Format.Format35ms; } public int getRegCount() { return regCount; } public byte getRegisterA() { return regA; } public byte getRegisterD() { return regD; } public byte getRegisterE() { return regE; } public byte getRegisterF() { return regF; } public byte getRegisterG() { return regG; } public int getVtableIndex() { return vtableIndex & 0xFFFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction35ms(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction35ms.java
Java
asf20
4,882
/* * [The "BSD licence"] * Copyright (c) 2011 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.*; import org.jf.dexlib.Code.*; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction20bc extends InstructionWithReference { public static final Instruction.InstructionFactory Factory = new Factory(); private VerificationErrorType validationErrorType; public Instruction20bc(Opcode opcode, VerificationErrorType validationErrorType, Item referencedItem) { super(opcode, referencedItem, getReferenceType(referencedItem)); this.validationErrorType = validationErrorType; } private static ReferenceType getReferenceType(Item item) { if (item instanceof TypeIdItem) { return ReferenceType.type; } if (item instanceof FieldIdItem) { return ReferenceType.field; } if (item instanceof MethodIdItem) { return ReferenceType.method; } return null; } private Instruction20bc(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); short val = NumberUtils.decodeUnsignedByte(buffer[bufferIndex+1]); validationErrorType = VerificationErrorType.getValidationErrorType(val & 0x3f); } protected ReferenceType readReferenceType(Opcode opcode, byte[] buffer, int bufferIndex) { short val = NumberUtils.decodeUnsignedByte(buffer[bufferIndex+1]); short referenceType = (short)(val >> 6); return ReferenceType.fromValidationErrorReferenceType(referenceType); } @Override public Format getFormat() { return Format.Format20bc; } @Override protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { if(opcode == Opcode.CONST_STRING && getReferencedItem().getIndex() > 0xFFFF) { throw new RuntimeException("String offset is too large for const-string. Use string-const/jumbo instead."); } out.writeByte(opcode.value); out.writeByte((this.getReferenceType().getValidationErrorReferenceType() << 6) & validationErrorType.getValue()); out.writeShort(getReferencedItem().getIndex()); } public VerificationErrorType getValidationErrorType() { return validationErrorType; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction20bc(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction20bc.java
Java
asf20
4,125
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction31t extends OffsetInstruction implements SingleRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private int targetAddressOffset; public Instruction31t(Opcode opcode, short regA, int offB) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; this.targetAddressOffset = offB; } private Instruction31t(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = buffer[bufferIndex + 1]; this.targetAddressOffset = NumberUtils.decodeInt(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); //align the address offset so that the absolute address is aligned on a 4-byte boundary (2 code block boundary) out.writeInt(targetAddressOffset + ((currentCodeAddress + targetAddressOffset) % 2)); } public void updateTargetAddressOffset(int targetAddressOffset) { this.targetAddressOffset = targetAddressOffset; } public Format getFormat() { return Format.Format31t; } public int getRegisterA() { return regA & 0xFF; } public int getTargetAddressOffset() { return targetAddressOffset; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction31t(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction31t.java
Java
asf20
3,586
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.Util.AnnotatedOutput; public class Instruction21c extends InstructionWithReference implements SingleRegisterInstruction, InstructionWithJumboVariant { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; public Instruction21c(Opcode opcode, short regA, Item referencedItem) { super(opcode, referencedItem); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } if (opcode == Opcode.NEW_INSTANCE) { assert referencedItem instanceof TypeIdItem; if (((TypeIdItem)referencedItem).getTypeDescriptor().charAt(0) != 'L') { throw new RuntimeException("Only class references can be used with the new-instance opcode"); } } this.regA = (byte)regA; } private Instruction21c(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); if (opcode == Opcode.NEW_INSTANCE && ((TypeIdItem)this.getReferencedItem()).getTypeDescriptor().charAt(0) != 'L') { throw new RuntimeException("Only class references can be used with the new-instance opcode"); } this.regA = buffer[bufferIndex + 1]; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { if(getReferencedItem().getIndex() > 0xFFFF) { if (opcode.hasJumboOpcode()) { throw new RuntimeException(String.format("%s index is too large. Use the %s instruction instead.", opcode.referenceType.name(), opcode.getJumboOpcode().name)); } else { throw new RuntimeException(String.format("%s index is too large", opcode.referenceType.name())); } } out.writeByte(opcode.value); out.writeByte(regA); out.writeShort(getReferencedItem().getIndex()); } public Format getFormat() { return Format.Format21c; } public int getRegisterA() { return regA & 0xFF; } public Instruction makeJumbo() { Opcode jumboOpcode = opcode.getJumboOpcode(); if (jumboOpcode == null) { return null; } if (jumboOpcode.format == Format.Format31c) { return new Instruction31c(jumboOpcode, (short)getRegisterA(), getReferencedItem()); } return new Instruction41c(jumboOpcode, getRegisterA(), getReferencedItem()); } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction21c(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction21c.java
Java
asf20
4,668
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction31c extends InstructionWithJumboReference implements SingleRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; public Instruction31c(Opcode opcode, short regA, Item referencedItem) { super(opcode, referencedItem); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; } private Instruction31c(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); this.regA = buffer[bufferIndex + 1]; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeInt(getReferencedItem().getIndex()); } public Format getFormat() { return Format.Format31c; } public int getRegisterA() { return regA & 0xFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction31c(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction31c.java
Java
asf20
3,177
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; public class Instruction10t extends OffsetInstruction { public static final InstructionFactory Factory = new Factory(); private int targetAddressOffset; public Instruction10t(Opcode opcode, int offA) { super(opcode); this.targetAddressOffset = offA; if (targetAddressOffset == 0) { throw new RuntimeException("The address offset cannot be 0. Use goto/32 instead."); } //allow out of range address offsets here, so we have the option of replacing this instruction //with goto/16 or goto/32 later } private Instruction10t(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); assert buffer[bufferIndex] == opcode.value; this.targetAddressOffset = buffer[bufferIndex + 1]; assert targetAddressOffset != 0; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { if (targetAddressOffset == 0) { throw new RuntimeException("The address offset cannot be 0. Use goto/32 instead"); } if (targetAddressOffset < -128 || targetAddressOffset > 127) { throw new RuntimeException("The address offset is out of range. It must be in [-128,-1] or [1, 127]"); } out.writeByte(opcode.value); out.writeByte(targetAddressOffset); } public void updateTargetAddressOffset(int targetAddressOffset) { this.targetAddressOffset = targetAddressOffset; } public Format getFormat() { return Format.Format10t; } public int getTargetAddressOffset() { return targetAddressOffset; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction10t(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction10t.java
Java
asf20
3,632
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Util.AnnotatedOutput; /** * This represents a "fixed" odexed instruction, where the object register is always null and so the correct type * can't be determined. Typically, these are replaced by an equivalent instruction that would have the same * effect (namely, an NPE) */ public class UnresolvedOdexInstruction extends Instruction { public final Instruction OriginalInstruction; //the register number that holds the (null) reference type that the instruction operates on public final int ObjectRegisterNum; public UnresolvedOdexInstruction(Instruction originalInstruction, int objectRegisterNumber) { super(originalInstruction.opcode); this.OriginalInstruction = originalInstruction; this.ObjectRegisterNum = objectRegisterNumber; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { throw new RuntimeException("Cannot rewrite an instruction that couldn't be deodexed"); } @Override public int getSize(int codeAddress) { return OriginalInstruction.getSize(codeAddress); } public Format getFormat() { return Format.UnresolvedOdexInstruction; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/UnresolvedOdexInstruction.java
Java
asf20
2,779
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.ReferenceType; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.Util.NumberUtils; public abstract class InstructionWithJumboReference extends InstructionWithReference { protected InstructionWithJumboReference(Opcode opcode, Item referencedItem) { super(opcode, referencedItem); } protected InstructionWithJumboReference(Opcode opcode, Item referencedItem, ReferenceType referenceType) { super(opcode, referencedItem, referenceType); } protected InstructionWithJumboReference(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); } protected int getReferencedItemIndex(byte[] buffer, int bufferIndex) { return NumberUtils.decodeInt(buffer, bufferIndex + 2); } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/InstructionWithJumboReference.java
Java
asf20
2,524
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction32x extends Instruction implements TwoRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private short regA; private short regB; public Instruction32x(Opcode opcode, int regA, int regB) { super(opcode); if (regA >= 1<<16 || regB >= 1<<16) { throw new RuntimeException("The register number must be less than v65536"); } this.regA = (short)regA; this.regB = (short)regB; } private Instruction32x(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); this.regB = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 4); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(0); out.writeShort(regA); out.writeShort(regB); } public Format getFormat() { return Format.Format32x; } public int getRegisterA() { return regA & 0xFFFF; } public int getRegisterB() { return regB & 0xFFFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction32x(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction32x.java
Java
asf20
3,277
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OdexedInvokeVirtual; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.RegisterRangeInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction3rms extends Instruction implements RegisterRangeInstruction, OdexedInvokeVirtual { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regCount; private short startReg; private short vtableIndex; public Instruction3rms(Opcode opcode, short regCount, int startReg, int vtableIndex) { super(opcode); if (regCount >= 1 << 8) { throw new RuntimeException("regCount must be less than 256"); } if (regCount < 0) { throw new RuntimeException("regCount cannot be negative"); } if (startReg >= 1 << 16) { throw new RuntimeException("The beginning register of the range must be less than 65536"); } if (startReg < 0) { throw new RuntimeException("The beginning register of the range cannot be negative"); } if (vtableIndex >= 1 << 16) { throw new RuntimeException("The method index must be less than 65536"); } this.regCount = (byte)regCount; this.startReg = (short)startReg; this.vtableIndex = (short)vtableIndex; } private Instruction3rms(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regCount = (byte)NumberUtils.decodeUnsignedByte(buffer[bufferIndex + 1]); this.vtableIndex = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); this.startReg = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 4); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regCount); out.writeShort(vtableIndex); out.writeShort(startReg); } public Format getFormat() { return Format.Format3rms; } public int getRegCount() { return (short)(regCount & 0xFF); } public int getStartRegister() { return startReg & 0xFFFF; } public int getVtableIndex() { return vtableIndex & 0xFFFF; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction3rms(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction3rms.java
Java
asf20
4,178
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.InstructionWithReference; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.RegisterRangeInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Item; import org.jf.dexlib.MethodIdItem; import org.jf.dexlib.TypeIdItem; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; import static org.jf.dexlib.Code.Opcode.*; public class Instruction3rc extends InstructionWithReference implements RegisterRangeInstruction, InstructionWithJumboVariant { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regCount; private short startReg; public Instruction3rc(Opcode opcode, short regCount, int startReg, Item referencedItem) { super(opcode, referencedItem); if (regCount >= 1 << 8) { throw new RuntimeException("regCount must be less than 256"); } if (regCount < 0) { throw new RuntimeException("regCount cannot be negative"); } if (startReg >= 1 << 16) { throw new RuntimeException("The beginning register of the range must be less than 65536"); } if (startReg < 0) { throw new RuntimeException("The beginning register of the range cannot be negative"); } this.regCount = (byte)regCount; this.startReg = (short)startReg; checkItem(opcode, referencedItem, regCount); } private Instruction3rc(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { super(dexFile, opcode, buffer, bufferIndex); this.regCount = (byte)NumberUtils.decodeUnsignedByte(buffer[bufferIndex + 1]); this.startReg = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 4); checkItem(opcode, getReferencedItem(), getRegCount()); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { if(getReferencedItem().getIndex() > 0xFFFF) { if (opcode.hasJumboOpcode()) { throw new RuntimeException(String.format("%s index is too large. Use the %s instruction instead.", opcode.referenceType.name(), opcode.getJumboOpcode().name)); } else { throw new RuntimeException(String.format("%s index is too large.", opcode.referenceType.name())); } } out.writeByte(opcode.value); out.writeByte(regCount); out.writeShort(this.getReferencedItem().getIndex()); out.writeShort(startReg); } public Format getFormat() { return Format.Format3rc; } public int getRegCount() { return (short)(regCount & 0xFF); } public int getStartRegister() { return startReg & 0xFFFF; } private static void checkItem(Opcode opcode, Item item, int regCount) { if (opcode == FILLED_NEW_ARRAY_RANGE) { //check data for filled-new-array/range opcode String type = ((TypeIdItem) item).getTypeDescriptor(); if (type.charAt(0) != '[') { throw new RuntimeException("The type must be an array type"); } if (type.charAt(1) == 'J' || type.charAt(1) == 'D') { throw new RuntimeException("The type cannot be an array of longs or doubles"); } } else if (opcode.value >= INVOKE_VIRTUAL_RANGE.value && opcode.value <= INVOKE_INTERFACE_RANGE.value || opcode == INVOKE_OBJECT_INIT_RANGE) { //check data for invoke-*/range opcodes MethodIdItem methodIdItem = (MethodIdItem) item; int parameterRegisterCount = methodIdItem.getPrototype().getParameterRegisterCount(); if (opcode != INVOKE_STATIC_RANGE) { parameterRegisterCount++; } if (parameterRegisterCount != regCount) { throw new RuntimeException("regCount does not match the number of arguments of the method"); } } } public Instruction makeJumbo() { Opcode jumboOpcode = opcode.getJumboOpcode(); if (jumboOpcode == null) { return null; } return new Instruction5rc(jumboOpcode, getRegCount(), getStartRegister(), getReferencedItem()); } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction3rc(dexFile, opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction3rc.java
Java
asf20
6,152
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.OffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction22t extends OffsetInstruction implements TwoRegisterInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private byte regB; private short targetAddressOffset; public Instruction22t(Opcode opcode, byte regA, byte regB, short offC) { super(opcode); if (regA >= 16 || regB >= 16) { throw new RuntimeException("The register number must be less than v16"); } if (offC == 0) { throw new RuntimeException("The address offset cannot be 0."); } this.regA = regA; this.regB = regB; this.targetAddressOffset = offC; } private Instruction22t(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); assert buffer[bufferIndex] == opcode.value; regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); regB = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); targetAddressOffset = NumberUtils.decodeShort(buffer, bufferIndex + 2); assert targetAddressOffset != 0; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte((regB << 4) | regA); out.writeShort(targetAddressOffset); } public void updateTargetAddressOffset(int targetAddressOffset) { if (targetAddressOffset < -32768 || targetAddressOffset > 32767) { throw new RuntimeException("The address offset " + targetAddressOffset + " is out of range. It must be in [-32768, 32767]"); } if (targetAddressOffset == 0) { throw new RuntimeException("The address offset cannot be 0"); } this.targetAddressOffset = (short)targetAddressOffset; } public Format getFormat() { return Format.Format22t; } public int getRegisterA() { return regA; } public int getRegisterB() { return regB; } public int getTargetAddressOffset() { return targetAddressOffset; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction22t(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction22t.java
Java
asf20
4,245
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.LiteralInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.TwoRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; public class Instruction22b extends Instruction implements TwoRegisterInstruction, LiteralInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private byte regB; private byte litC; public Instruction22b(Opcode opcode, short regA, short regB, byte litC) { super(opcode); if (regA >= 1 << 8 || regB >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; this.regB = (byte)regB; this.litC = litC; } private Instruction22b(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regA = buffer[bufferIndex + 1]; this.regB = buffer[bufferIndex + 2]; this.litC = buffer[bufferIndex + 3]; } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeByte(regB); out.writeByte(litC); } public Format getFormat() { return Format.Format22b; } public int getRegisterA() { return regA & 0xFF; } public int getRegisterB() { return regB & 0xFF; } public long getLiteral() { return litC; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction22b(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction22b.java
Java
asf20
3,389
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.LiteralInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.Code.SingleRegisterInstruction; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction51l extends Instruction implements SingleRegisterInstruction, LiteralInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private byte regA; private long litB; public Instruction51l(Opcode opcode, short regA, long litB) { super(opcode); if (regA >= 1 << 8) { throw new RuntimeException("The register number must be less than v256"); } this.regA = (byte)regA; this.litB = litB; } private Instruction51l(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); regA = (byte)NumberUtils.decodeUnsignedByte(buffer[bufferIndex + 1]); litB = NumberUtils.decodeLong(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regA); out.writeLong(litB); } public Format getFormat() { return Format.Format51l; } public int getRegisterA() { return regA & 0xFF; } public long getLiteral() { return litB; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction51l(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction51l.java
Java
asf20
3,244
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.*; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction35mi extends Instruction implements FiveRegisterInstruction, OdexedInvokeInline { public static final InstructionFactory Factory = new Factory(); private byte regCount; private byte regA; private byte regD; private byte regE; private byte regF; private byte regG; private short inlineIndex; public Instruction35mi(Opcode opcode, int regCount, byte regD, byte regE, byte regF, byte regG, byte regA, int inlineIndex) { super(opcode); if (regCount > 5) { throw new RuntimeException("regCount cannot be greater than 5"); } if (regD >= 1 << 4 || regE >= 1 << 4 || regF >= 1 << 4 || regG >= 1 << 4 || regA >= 1 << 4) { throw new RuntimeException("All register args must fit in 4 bits"); } if (inlineIndex >= 1 << 16) { throw new RuntimeException("The method index must be less than 65536"); } this.regCount = (byte)regCount; this.regA = regA; this.regD = regD; this.regE = regE; this.regF = regF; this.regG = regG; this.inlineIndex = (short)inlineIndex; } private Instruction35mi(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regCount = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 1]); this.regA = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 1]); this.regD = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 4]); this.regE = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 4]); this.regF = NumberUtils.decodeLowUnsignedNibble(buffer[bufferIndex + 5]); this.regG = NumberUtils.decodeHighUnsignedNibble(buffer[bufferIndex + 5]); this.inlineIndex = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte((regCount << 4) | regA); out.writeShort(inlineIndex); out.writeByte((regE << 4) | regD); out.writeByte((regG << 4) | regF); } public Format getFormat() { return Format.Format35mi; } public int getRegCount() { return regCount; } public byte getRegisterA() { return regA; } public byte getRegisterD() { return regD; } public byte getRegisterE() { return regE; } public byte getRegisterF() { return regF; } public byte getRegisterG() { return regG; } public int getInlineIndex() { return inlineIndex & 0xFFFF; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction35mi(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction35mi.java
Java
asf20
4,778
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.Instruction; import org.jf.dexlib.Code.MultiOffsetInstruction; import org.jf.dexlib.Code.Opcode; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; import java.util.Iterator; public class PackedSwitchDataPseudoInstruction extends Instruction implements MultiOffsetInstruction { public static final Instruction.InstructionFactory Factory = new Factory(); private int firstKey; private int[] targets; @Override public int getSize(int codeAddress) { return getTargetCount() * 2 + 4 + (codeAddress % 2); } public PackedSwitchDataPseudoInstruction(int firstKey, int[] targets) { super(Opcode.NOP); if (targets.length > 0xFFFF) { throw new RuntimeException("The packed-switch data contains too many elements. " + "The maximum number of switch elements is 65535"); } this.firstKey = firstKey; this.targets = targets; } public PackedSwitchDataPseudoInstruction(byte[] buffer, int bufferIndex) { super(Opcode.NOP); byte opcodeByte = buffer[bufferIndex]; if (opcodeByte != 0x00) { throw new RuntimeException("Invalid opcode byte for a PackedSwitchData pseudo-instruction"); } byte subopcodeByte = buffer[bufferIndex+1]; if (subopcodeByte != 0x01) { throw new RuntimeException("Invalid sub-opcode byte for a PackedSwitchData pseudo-instruction"); } int targetCount = NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); this.firstKey = NumberUtils.decodeInt(buffer, bufferIndex + 4); this.targets = new int[targetCount]; for (int i = 0; i<targetCount; i++) { targets[i] = NumberUtils.decodeInt(buffer, bufferIndex + 8 + 4*i); } } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.alignTo(4); out.writeByte(0x00); out.writeByte(0x01); out.writeShort(targets.length); out.writeInt(firstKey); for (int target : targets) { out.writeInt(target); } } protected void annotateInstruction(AnnotatedOutput out, int currentCodeAddress) { out.annotate(getSize(currentCodeAddress)*2, "[0x" + Integer.toHexString(currentCodeAddress) + "] " + "packed-switch-data instruction"); } public void updateTarget(int targetIndex, int targetAddressOffset) { targets[targetIndex] = targetAddressOffset; } public Format getFormat() { return Format.PackedSwitchData; } public int getTargetCount() { return targets.length; } public int getFirstKey() { return firstKey; } public int[] getTargets() { return targets; } public static class PackedSwitchTarget { public int value; public int targetAddressOffset; } public Iterator<PackedSwitchTarget> iterateKeysAndTargets() { return new Iterator<PackedSwitchTarget>() { final int targetCount = getTargetCount(); int i = 0; int value = getFirstKey(); PackedSwitchTarget packedSwitchTarget = new PackedSwitchTarget(); public boolean hasNext() { return i<targetCount; } public PackedSwitchTarget next() { packedSwitchTarget.value = value++; packedSwitchTarget.targetAddressOffset = targets[i]; i++; return packedSwitchTarget; } public void remove() { } }; } private static class Factory implements Instruction.InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { if (opcode != Opcode.NOP) { throw new RuntimeException("The opcode for a PackedSwitchDataPseudoInstruction must be NOP"); } return new PackedSwitchDataPseudoInstruction(buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/PackedSwitchDataPseudoInstruction.java
Java
asf20
5,687
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code.Format; import org.jf.dexlib.Code.*; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.AnnotatedOutput; import org.jf.dexlib.Util.NumberUtils; public class Instruction3rmi extends Instruction implements RegisterRangeInstruction, OdexedInvokeInline { public static final InstructionFactory Factory = new Factory(); private byte regCount; private short startReg; private short inlineIndex; public Instruction3rmi(Opcode opcode, short regCount, int startReg, int inlineIndex) { super(opcode); if (regCount >= 1 << 8) { throw new RuntimeException("regCount must be less than 256"); } if (regCount < 0) { throw new RuntimeException("regCount cannot be negative"); } if (startReg >= 1 << 16) { throw new RuntimeException("The beginning register of the range must be less than 65536"); } if (startReg < 0) { throw new RuntimeException("The beginning register of the range cannot be negative"); } if (inlineIndex >= 1 << 16) { throw new RuntimeException("The method index must be less than 65536"); } this.regCount = (byte)regCount; this.startReg = (short)startReg; this.inlineIndex = (short)inlineIndex; } private Instruction3rmi(Opcode opcode, byte[] buffer, int bufferIndex) { super(opcode); this.regCount = (byte)NumberUtils.decodeUnsignedByte(buffer[bufferIndex + 1]); this.inlineIndex = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 2); this.startReg = (short)NumberUtils.decodeUnsignedShort(buffer, bufferIndex + 4); } protected void writeInstruction(AnnotatedOutput out, int currentCodeAddress) { out.writeByte(opcode.value); out.writeByte(regCount); out.writeShort(inlineIndex); out.writeShort(startReg); } public Format getFormat() { return Format.Format3rmi; } public int getRegCount() { return (short)(regCount & 0xFF); } public int getStartRegister() { return startReg & 0xFFFF; } public int getInlineIndex() { return inlineIndex & 0xFFFF; } private static class Factory implements InstructionFactory { public Instruction makeInstruction(DexFile dexFile, Opcode opcode, byte[] buffer, int bufferIndex) { return new Instruction3rmi(opcode, buffer, bufferIndex); } } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Format/Instruction3rmi.java
Java
asf20
4,072
/* * [The "BSD licence"] * Copyright (c) 2011 Ben Gruver * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; import java.util.HashMap; public enum VerificationErrorType { None(0, "no-error"), Generic(1, "generic-error"), NoClass(2, "no-such-class"), NoField(3, "no-such-field"), NoMethod(4, "no-such-method"), AccessClass(5, "illegal-class-access"), AccessField(6, "illegal-field-access"), AccessMethod(7, "illegal-method-access"), ClassChange(8, "class-change-error"), Instantiation(9, "instantiation-error"); private static HashMap<String, VerificationErrorType> verificationErrorTypesByName; static { verificationErrorTypesByName = new HashMap<String, VerificationErrorType>(); for (VerificationErrorType verificationErrorType: VerificationErrorType.values()) { verificationErrorTypesByName.put(verificationErrorType.getName(), verificationErrorType); } } private int value; private String name; private VerificationErrorType(int value, String name) { this.value = value; this.name = name; } public int getValue() { return value; } public String getName() { return name; } public static VerificationErrorType fromString(String validationErrorType) { return verificationErrorTypesByName.get(validationErrorType); } public static VerificationErrorType getValidationErrorType(int validationErrorType) { switch (validationErrorType) { case 0: return None; case 1: return Generic; case 2: return NoClass; case 3: return NoField; case 4: return NoMethod; case 5: return AccessClass; case 6: return AccessField; case 7: return AccessMethod; case 8: return ClassChange; case 9: return Instantiation; } return null; } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/VerificationErrorType.java
Java
asf20
3,512
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; import org.jf.dexlib.Code.Format.*; import org.jf.dexlib.DexFile; import org.jf.dexlib.Util.ExceptionWithContext; import org.jf.dexlib.Util.Hex; public class InstructionIterator { public static void IterateInstructions(DexFile dexFile, byte[] insns, ProcessInstructionDelegate delegate) { int insnsPosition = 0; while (insnsPosition < insns.length) { try { short opcodeValue = (short)(insns[insnsPosition] & 0xFF); if (opcodeValue == 0xFF) { opcodeValue = (short)((0xFF << 8) | insns[insnsPosition+1]); } Opcode opcode = Opcode.getOpcodeByValue(opcodeValue); Instruction instruction = null; if (opcode == null) { System.err.println(String.format("unknown opcode encountered - %x. Treating as nop.", (opcodeValue & 0xFFFF))); instruction = new UnknownInstruction(opcodeValue); } else { if (opcode == Opcode.NOP) { byte secondByte = insns[insnsPosition + 1]; switch (secondByte) { case 0: { instruction = new Instruction10x(Opcode.NOP, insns, insnsPosition); break; } case 1: { instruction = new PackedSwitchDataPseudoInstruction(insns, insnsPosition); break; } case 2: { instruction = new SparseSwitchDataPseudoInstruction(insns, insnsPosition); break; } case 3: { instruction = new ArrayDataPseudoInstruction(insns, insnsPosition); break; } } } else { instruction = opcode.format.Factory.makeInstruction(dexFile, opcode, insns, insnsPosition); } } assert instruction != null; delegate.ProcessInstruction(insnsPosition/2, instruction); insnsPosition += instruction.getSize(insnsPosition/2)*2; } catch (Exception ex) { throw ExceptionWithContext.withContext(ex, "Error occured at code address " + insnsPosition * 2); } } } public static interface ProcessInstructionDelegate { public void ProcessInstruction(int codeAddress, Instruction instruction); } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/InstructionIterator.java
Java
asf20
4,415
/* * Copyright 2011, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface OdexedInvokeInline extends InvokeInstruction { int getInlineIndex(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/OdexedInvokeInline.java
Java
asf20
1,685
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; import org.jf.dexlib.Code.Format.Format; import java.util.HashMap; public enum Opcode { NOP((short)0x00, "nop", ReferenceType.none, Format.Format10x, Opcode.CAN_CONTINUE), MOVE((short)0x01, "move", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_FROM16((short)0x02, "move/from16", ReferenceType.none, Format.Format22x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_16((short)0x03, "move/16", ReferenceType.none, Format.Format32x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_WIDE((short)0x04, "move-wide", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MOVE_WIDE_FROM16((short)0x05, "move-wide/from16", ReferenceType.none, Format.Format22x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MOVE_WIDE_16((short)0x06, "move-wide/16", ReferenceType.none, Format.Format32x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MOVE_OBJECT((short)0x07, "move-object", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_OBJECT_FROM16((short)0x08, "move-object/from16", ReferenceType.none, Format.Format22x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_OBJECT_16((short)0x09, "move-object/16", ReferenceType.none, Format.Format32x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_RESULT((short)0x0a, "move-result", ReferenceType.none, Format.Format11x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_RESULT_WIDE((short)0x0b, "move-result-wide", ReferenceType.none, Format.Format11x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MOVE_RESULT_OBJECT((short)0x0c, "move-result-object", ReferenceType.none, Format.Format11x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MOVE_EXCEPTION((short)0x0d, "move-exception", ReferenceType.none, Format.Format11x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), RETURN_VOID((short)0x0e, "return-void", ReferenceType.none, Format.Format10x), RETURN((short)0x0f, "return", ReferenceType.none, Format.Format11x), RETURN_WIDE((short)0x10, "return-wide", ReferenceType.none, Format.Format11x), RETURN_OBJECT((short)0x11, "return-object", ReferenceType.none, Format.Format11x), CONST_4((short)0x12, "const/4", ReferenceType.none, Format.Format11n, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CONST_16((short)0x13, "const/16", ReferenceType.none, Format.Format21s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CONST((short)0x14, "const", ReferenceType.none, Format.Format31i, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CONST_HIGH16((short)0x15, "const/high16", ReferenceType.none, Format.Format21h, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CONST_WIDE_16((short)0x16, "const-wide/16", ReferenceType.none, Format.Format21s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), CONST_WIDE_32((short)0x17, "const-wide/32", ReferenceType.none, Format.Format31i, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), CONST_WIDE((short)0x18, "const-wide", ReferenceType.none, Format.Format51l, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), CONST_WIDE_HIGH16((short)0x19, "const-wide/high16", ReferenceType.none, Format.Format21h, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), CONST_STRING((short)0x1a, "const-string", ReferenceType.string, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0x1b), CONST_STRING_JUMBO((short)0x1b, "const-string/jumbo", ReferenceType.string, Format.Format31c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CONST_CLASS((short)0x1c, "const-class", ReferenceType.type, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff00), MONITOR_ENTER((short)0x1d, "monitor-enter", ReferenceType.none, Format.Format11x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), MONITOR_EXIT((short)0x1e, "monitor-exit", ReferenceType.none, Format.Format11x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), CHECK_CAST((short)0x1f, "check-cast", ReferenceType.type, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff01), INSTANCE_OF((short)0x20, "instance-of", ReferenceType.type, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff02), ARRAY_LENGTH((short)0x21, "array-length", ReferenceType.none, Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), NEW_INSTANCE((short)0x22, "new-instance", ReferenceType.type, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff03), NEW_ARRAY((short)0x23, "new-array", ReferenceType.type, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff04), FILLED_NEW_ARRAY((short)0x24, "filled-new-array", ReferenceType.type, Format.Format35c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), FILLED_NEW_ARRAY_RANGE((short)0x25, "filled-new-array/range", ReferenceType.type, Format.Format3rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT, (short)0xff05), FILL_ARRAY_DATA((short)0x26, "fill-array-data", ReferenceType.none, Format.Format31t, Opcode.CAN_CONTINUE), THROW((short)0x27, "throw", ReferenceType.none, Format.Format11x, Opcode.CAN_THROW), GOTO((short)0x28, "goto", ReferenceType.none, Format.Format10t), GOTO_16((short)0x29, "goto/16", ReferenceType.none, Format.Format20t), GOTO_32((short)0x2a, "goto/32", ReferenceType.none, Format.Format30t), PACKED_SWITCH((short)0x2b, "packed-switch", ReferenceType.none, Format.Format31t, Opcode.CAN_CONTINUE), SPARSE_SWITCH((short)0x2c, "sparse-switch", ReferenceType.none, Format.Format31t, Opcode.CAN_CONTINUE), CMPL_FLOAT((short)0x2d, "cmpl-float", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CMPG_FLOAT((short)0x2e, "cmpg-float", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CMPL_DOUBLE((short)0x2f, "cmpl-double", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CMPG_DOUBLE((short)0x30, "cmpg-double", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), CMP_LONG((short)0x31, "cmp-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), IF_EQ((short)0x32, "if-eq", ReferenceType.none, Format.Format22t, Opcode.CAN_CONTINUE), IF_NE((short)0x33, "if-ne", ReferenceType.none, Format.Format22t, Opcode.CAN_CONTINUE), IF_LT((short)0x34, "if-lt", ReferenceType.none, Format.Format22t, Opcode.CAN_CONTINUE), IF_GE((short)0x35, "if-ge", ReferenceType.none, Format.Format22t, Opcode.CAN_CONTINUE), IF_GT((short)0x36, "if-gt", ReferenceType.none, Format.Format22t, Opcode.CAN_CONTINUE), IF_LE((short)0x37, "if-le", ReferenceType.none, Format.Format22t, Opcode.CAN_CONTINUE), IF_EQZ((short)0x38, "if-eqz", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), IF_NEZ((short)0x39, "if-nez", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), IF_LTZ((short)0x3a, "if-ltz", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), IF_GEZ((short)0x3b, "if-gez", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), IF_GTZ((short)0x3c, "if-gtz", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), IF_LEZ((short)0x3d, "if-lez", ReferenceType.none, Format.Format21t, Opcode.CAN_CONTINUE), AGET((short)0x44, "aget", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AGET_WIDE((short)0x45, "aget-wide", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), AGET_OBJECT((short)0x46, "aget-object", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AGET_BOOLEAN((short)0x47, "aget-boolean", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AGET_BYTE((short)0x48, "aget-byte", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AGET_CHAR((short)0x49, "aget-char", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AGET_SHORT((short)0x4a, "aget-short", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), APUT((short)0x4b, "aput", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), APUT_WIDE((short)0x4c, "aput-wide", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), APUT_OBJECT((short)0x4d, "aput-object", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), APUT_BOOLEAN((short)0x4e, "aput-boolean", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), APUT_BYTE((short)0x4f, "aput-byte", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), APUT_CHAR((short)0x50, "aput-char", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), APUT_SHORT((short)0x51, "aput-short", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE), IGET((short)0x52, "iget", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff06), IGET_WIDE((short)0x53, "iget-wide", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER, (short)0xff07), IGET_OBJECT((short)0x54, "iget-object", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff08), IGET_BOOLEAN((short)0x55, "iget-boolean", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff09), IGET_BYTE((short)0x56, "iget-byte", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff0a), IGET_CHAR((short)0x57, "iget-char", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff0b), IGET_SHORT((short)0x58, "iget-short", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff0c), IPUT((short)0x59, "iput", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff0d), IPUT_WIDE((short)0x5a, "iput-wide", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff0e), IPUT_OBJECT((short)0x5b, "iput-object", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff0f), IPUT_BOOLEAN((short)0x5c, "iput-boolean", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff10), IPUT_BYTE((short)0x5d, "iput-byte", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff11), IPUT_CHAR((short)0x5e, "iput-char", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff12), IPUT_SHORT((short)0x5f, "iput-short", ReferenceType.field, Format.Format22c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff13), SGET((short)0x60, "sget", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff14), SGET_WIDE((short)0x61, "sget-wide", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER, (short)0xff15), SGET_OBJECT((short)0x62, "sget-object", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff16), SGET_BOOLEAN((short)0x63, "sget-boolean", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff17), SGET_BYTE((short)0x64, "sget-byte", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff18), SGET_CHAR((short)0x65, "sget-char", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff19), SGET_SHORT((short)0x66, "sget-short", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER, (short)0xff1a), SPUT((short)0x67, "sput", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff1b), SPUT_WIDE((short)0x68, "sput-wide", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff1c), SPUT_OBJECT((short)0x69, "sput-object", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff1d), SPUT_BOOLEAN((short)0x6a, "sput-boolean", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff1e), SPUT_BYTE((short)0x6b, "sput-byte", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff1f), SPUT_CHAR((short)0x6c, "sput-char", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff20), SPUT_SHORT((short)0x6d, "sput-short", ReferenceType.field, Format.Format21c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE, (short)0xff21), INVOKE_VIRTUAL((short)0x6e, "invoke-virtual", ReferenceType.method, Format.Format35c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_SUPER((short)0x6f, "invoke-super", ReferenceType.method, Format.Format35c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_DIRECT((short)0x70, "invoke-direct", ReferenceType.method, Format.Format35c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.CAN_INITIALIZE_REFERENCE), INVOKE_STATIC((short)0x71, "invoke-static", ReferenceType.method, Format.Format35c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_INTERFACE((short)0x72, "invoke-interface", ReferenceType.method, Format.Format35c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_VIRTUAL_RANGE((short)0x74, "invoke-virtual/range", ReferenceType.method, Format.Format3rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT, (short)0xff22), INVOKE_SUPER_RANGE((short)0x75, "invoke-super/range", ReferenceType.method, Format.Format3rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT, (short)0xff23), INVOKE_DIRECT_RANGE((short)0x76, "invoke-direct/range", ReferenceType.method, Format.Format3rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.CAN_INITIALIZE_REFERENCE, (short)0xff24), INVOKE_STATIC_RANGE((short)0x77, "invoke-static/range", ReferenceType.method, Format.Format3rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT, (short)0xff25), INVOKE_INTERFACE_RANGE((short)0x78, "invoke-interface/range", ReferenceType.method, Format.Format3rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT, (short)0xff26), NEG_INT((short)0x7b, "neg-int", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), NOT_INT((short)0x7c, "not-int", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), NEG_LONG((short)0x7d, "neg-long", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), NOT_LONG((short)0x7e, "not-long", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), NEG_FLOAT((short)0x7f, "neg-float", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), NEG_DOUBLE((short)0x80, "neg-double", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), INT_TO_LONG((short)0x81, "int-to-long", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), INT_TO_FLOAT((short)0x82, "int-to-float", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), INT_TO_DOUBLE((short)0x83, "int-to-double", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), LONG_TO_INT((short)0x84, "long-to-int", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), LONG_TO_FLOAT((short)0x85, "long-to-float", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), LONG_TO_DOUBLE((short)0x86, "long-to-double", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), FLOAT_TO_INT((short)0x87, "float-to-int", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), FLOAT_TO_LONG((short)0x88, "float-to-long", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), FLOAT_TO_DOUBLE((short)0x89, "float-to-double", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), DOUBLE_TO_INT((short)0x8a, "double-to-int", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), DOUBLE_TO_LONG((short)0x8b, "double-to-long", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), DOUBLE_TO_FLOAT((short)0x8c, "double-to-float", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), INT_TO_BYTE((short)0x8d, "int-to-byte", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), INT_TO_CHAR((short)0x8e, "int-to-char", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), INT_TO_SHORT((short)0x8f, "int-to-short", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), ADD_INT((short)0x90, "add-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SUB_INT((short)0x91, "sub-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MUL_INT((short)0x92, "mul-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), DIV_INT((short)0x93, "div-int", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), REM_INT((short)0x94, "rem-int", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AND_INT((short)0x95, "and-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), OR_INT((short)0x96, "or-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), XOR_INT((short)0x97, "xor-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SHL_INT((short)0x98, "shl-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SHR_INT((short)0x99, "shr-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), USHR_INT((short)0x9a, "ushr-int", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), ADD_LONG((short)0x9b, "add-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SUB_LONG((short)0x9c, "sub-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MUL_LONG((short)0x9d, "mul-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), DIV_LONG((short)0x9e, "div-long", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), REM_LONG((short)0x9f, "rem-long", ReferenceType.none, Format.Format23x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), AND_LONG((short)0xa0, "and-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), OR_LONG((short)0xa1, "or-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), XOR_LONG((short)0xa2, "xor-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SHL_LONG((short)0xa3, "shl-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SHR_LONG((short)0xa4, "shr-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), USHR_LONG((short)0xa5, "ushr-long", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), ADD_FLOAT((short)0xa6, "add-float", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SUB_FLOAT((short)0xa7, "sub-float", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MUL_FLOAT((short)0xa8, "mul-float", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), DIV_FLOAT((short)0xa9, "div-float", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), REM_FLOAT((short)0xaa, "rem-float", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), ADD_DOUBLE((short)0xab, "add-double", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SUB_DOUBLE((short)0xac, "sub-double", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MUL_DOUBLE((short)0xad, "mul-double", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), DIV_DOUBLE((short)0xae, "div-double", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), REM_DOUBLE((short)0xaf, "rem-double", ReferenceType.none, Format.Format23x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), ADD_INT_2ADDR((short)0xb0, "add-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SUB_INT_2ADDR((short)0xb1, "sub-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MUL_INT_2ADDR((short)0xb2, "mul-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), DIV_INT_2ADDR((short)0xb3, "div-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), REM_INT_2ADDR((short)0xb4, "rem-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AND_INT_2ADDR((short)0xb5, "and-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), OR_INT_2ADDR((short)0xb6, "or-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), XOR_INT_2ADDR((short)0xb7, "xor-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SHL_INT_2ADDR((short)0xb8, "shl-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SHR_INT_2ADDR((short)0xb9, "shr-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), USHR_INT_2ADDR((short)0xba, "ushr-int/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), ADD_LONG_2ADDR((short)0xbb, "add-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SUB_LONG_2ADDR((short)0xbc, "sub-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MUL_LONG_2ADDR((short)0xbd, "mul-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), DIV_LONG_2ADDR((short)0xbe, "div-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), REM_LONG_2ADDR((short)0xbf, "rem-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), AND_LONG_2ADDR((short)0xc0, "and-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), OR_LONG_2ADDR((short)0xc1, "or-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), XOR_LONG_2ADDR((short)0xc2, "xor-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SHL_LONG_2ADDR((short)0xc3, "shl-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SHR_LONG_2ADDR((short)0xc4, "shr-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), USHR_LONG_2ADDR((short)0xc5, "ushr-long/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), ADD_FLOAT_2ADDR((short)0xc6, "add-float/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SUB_FLOAT_2ADDR((short)0xc7, "sub-float/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MUL_FLOAT_2ADDR((short)0xc8, "mul-float/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), DIV_FLOAT_2ADDR((short)0xc9, "div-float/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), REM_FLOAT_2ADDR((short)0xca, "rem-float/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), ADD_DOUBLE_2ADDR((short)0xcb, "add-double/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SUB_DOUBLE_2ADDR((short)0xcc, "sub-double/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), MUL_DOUBLE_2ADDR((short)0xcd, "mul-double/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), DIV_DOUBLE_2ADDR((short)0xce, "div-double/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), REM_DOUBLE_2ADDR((short)0xcf, "rem-double/2addr", ReferenceType.none, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), ADD_INT_LIT16((short)0xd0, "add-int/lit16", ReferenceType.none, Format.Format22s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), RSUB_INT((short)0xd1, "rsub-int", ReferenceType.none, Format.Format22s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MUL_INT_LIT16((short)0xd2, "mul-int/lit16", ReferenceType.none, Format.Format22s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), DIV_INT_LIT16((short)0xd3, "div-int/lit16", ReferenceType.none, Format.Format22s, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), REM_INT_LIT16((short)0xd4, "rem-int/lit16", ReferenceType.none, Format.Format22s, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AND_INT_LIT16((short)0xd5, "and-int/lit16", ReferenceType.none, Format.Format22s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), OR_INT_LIT16((short)0xd6, "or-int/lit16", ReferenceType.none, Format.Format22s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), XOR_INT_LIT16((short)0xd7, "xor-int/lit16", ReferenceType.none, Format.Format22s, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), ADD_INT_LIT8((short)0xd8, "add-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), RSUB_INT_LIT8((short)0xd9, "rsub-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), MUL_INT_LIT8((short)0xda, "mul-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), DIV_INT_LIT8((short)0xdb, "div-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), REM_INT_LIT8((short)0xdc, "rem-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), AND_INT_LIT8((short)0xdd, "and-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), OR_INT_LIT8((short)0xde, "or-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), XOR_INT_LIT8((short)0xdf, "xor-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SHL_INT_LIT8((short)0xe0, "shl-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SHR_INT_LIT8((short)0xe1, "shr-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), USHR_INT_LIT8((short)0xe2, "ushr-int/lit8", ReferenceType.none, Format.Format22b, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), IGET_VOLATILE((short)0xe3, "iget-volatile", ReferenceType.field, Format.Format22c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), IPUT_VOLATILE((short)0xe4, "iput-volatile", ReferenceType.field, Format.Format22c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), SGET_VOLATILE((short)0xe5, "sget-volatile", ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SPUT_VOLATILE((short)0xe6, "sput-volatile", ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), IGET_OBJECT_VOLATILE((short)0xe7, "iget-object-volatile", ReferenceType.field, Format.Format22c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), IGET_WIDE_VOLATILE((short)0xe8, "iget-wide-volatile", ReferenceType.field, Format.Format22c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), IPUT_WIDE_VOLATILE((short)0xe9, "iput-wide-volatile", ReferenceType.field, Format.Format22c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), SGET_WIDE_VOLATILE((short)0xea, "sget-wide-volatile", ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), SPUT_WIDE_VOLATILE((short)0xeb, "sput-wide-volatile", ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), THROW_VERIFICATION_ERROR((short)0xed, "throw-verification-error", ReferenceType.none, Format.Format20bc, Opcode.ODEX_ONLY | Opcode.CAN_THROW), EXECUTE_INLINE((short)0xee, "execute-inline", ReferenceType.none, Format.Format35mi, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), EXECUTE_INLINE_RANGE((short)0xef, "execute-inline/range", ReferenceType.none, Format.Format3rmi, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_DIRECT_EMPTY((short)0xf0, "invoke-direct-empty", ReferenceType.method, Format.Format35c, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.CAN_INITIALIZE_REFERENCE), INVOKE_OBJECT_INIT_RANGE((short)0xf0, "invoke-object-init/range", ReferenceType.method, Format.Format3rc, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.CAN_INITIALIZE_REFERENCE), RETURN_VOID_BARRIER((short)0xf1, "return-void-barrier", ReferenceType.none, Format.Format10x, Opcode.ODEX_ONLY), IGET_QUICK((short)0xf2, "iget-quick", ReferenceType.none, Format.Format22cs, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_QUICK | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), IGET_WIDE_QUICK((short)0xf3, "iget-wide-quick", ReferenceType.none, Format.Format22cs, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_QUICK | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER), IGET_OBJECT_QUICK((short)0xf4, "iget-object-quick", ReferenceType.none, Format.Format22cs, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_QUICK | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), IPUT_QUICK((short)0xf5, "iput-quick", ReferenceType.none, Format.Format22cs, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_QUICK | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), IPUT_WIDE_QUICK((short)0xf6, "iput-wide-quick", ReferenceType.none, Format.Format22cs, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_QUICK | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), IPUT_OBJECT_QUICK((short)0xf7, "iput-object-quick", ReferenceType.none, Format.Format22cs, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_QUICK | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), INVOKE_VIRTUAL_QUICK((short)0xf8, "invoke-virtual-quick", ReferenceType.none, Format.Format35ms, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_VIRTUAL_QUICK_RANGE((short)0xf9, "invoke-virtual-quick/range", ReferenceType.none, Format.Format3rms, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_SUPER_QUICK((short)0xfa, "invoke-super-quick", ReferenceType.none, Format.Format35ms, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), INVOKE_SUPER_QUICK_RANGE((short)0xfb, "invoke-super-quick/range", ReferenceType.none, Format.Format3rms, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT), IPUT_OBJECT_VOLATILE((short)0xfc, "iput-object-volatile", ReferenceType.field, Format.Format22c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), SGET_OBJECT_VOLATILE((short)0xfd, "sget-object-volatile", ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER), SPUT_OBJECT_VOLATILE((short)0xfe, "sput-object-volatile", ReferenceType.field, Format.Format21c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE), CONST_CLASS_JUMBO((short)0xff00, "const-class/jumbo", ReferenceType.type, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), CHECK_CAST_JUMBO((short)0xff01, "check-cast/jumbo", ReferenceType.type, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), INSTANCE_OF_JUMBO((short)0xff02, "instance-of/jumbo", ReferenceType.type, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), NEW_INSTANCE_JUMBO((short)0xff03, "new-instance/jumbo", ReferenceType.type, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), NEW_ARRAY_JUMBO((short)0xff04, "new-array/jumbo", ReferenceType.type, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), FILLED_NEW_ARRAY_JUMBO((short)0xff05, "filled-new-array/jumbo", ReferenceType.type, Format.Format5rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.JUMBO_OPCODE), IGET_JUMBO((short)0xff06, "iget/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IGET_WIDE_JUMBO((short)0xff07, "iget-wide/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER | Opcode.JUMBO_OPCODE), IGET_OBJECT_JUMBO((short)0xff08, "iget-object/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IGET_BOOLEAN_JUMBO((short)0xff09, "iget-boolean/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IGET_BYTE_JUMBO((short)0xff0a, "iget-byte/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IGET_CHAR_JUMBO((short)0xff0b, "iget-char/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IGET_SHORT_JUMBO((short)0xff0c, "iget-short/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IPUT_JUMBO((short)0xff0d, "iput/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_WIDE_JUMBO((short)0xff0e, "iput-wide/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_OBJECT_JUMBO((short)0xff0f, "iput-object/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_BOOLEAN_JUMBO((short)0xff10, "iput-boolean/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_BYTE_JUMBO((short)0xff11, "iput-byte/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_CHAR_JUMBO((short)0xff12, "iput-char/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_SHORT_JUMBO((short)0xff13, "iput-short/jumbo", ReferenceType.field, Format.Format52c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SGET_JUMBO((short)0xff14, "sget/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SGET_WIDE_JUMBO((short)0xff15, "sget-wide/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER | Opcode.JUMBO_OPCODE), SGET_OBJECT_JUMBO((short)0xff16, "sget-object/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SGET_BOOLEAN_JUMBO((short)0xff17, "sget-boolean/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SGET_BYTE_JUMBO((short)0xff18, "sget-byte/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SGET_CHAR_JUMBO((short)0xff19, "sget-char/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SGET_SHORT_JUMBO((short)0xff1a, "sget-short/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SPUT_JUMBO((short)0xff1b, "sput/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_WIDE_JUMBO((short)0xff1c, "sput-wide/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_OBJECT_JUMBO((short)0xff1d, "sput-object/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_BOOLEAN_JUMBO((short)0xff1e, "sput-boolean/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_BYTE_JUMBO((short)0xff1f, "sput-byte/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_CHAR_JUMBO((short)0xff20, "sput-char/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_SHORT_JUMBO((short)0xff21, "sput-short/jumbo", ReferenceType.field, Format.Format41c, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), INVOKE_VIRTUAL_JUMBO((short)0xff22, "invoke-virtual/jumbo", ReferenceType.method, Format.Format5rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.JUMBO_OPCODE), INVOKE_SUPER_JUMBO((short)0xff23, "invoke-super/jumbo", ReferenceType.method, Format.Format5rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.JUMBO_OPCODE), INVOKE_DIRECT_JUMBO((short)0xff24, "invoke-direct/jumbo", ReferenceType.method, Format.Format5rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.JUMBO_OPCODE | Opcode.CAN_INITIALIZE_REFERENCE), INVOKE_STATIC_JUMBO((short)0xff25, "invoke-static/jumbo", ReferenceType.method, Format.Format5rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.JUMBO_OPCODE), INVOKE_INTERFACE_JUMBO((short)0xff26, "invoke-interface/jumbo", ReferenceType.method, Format.Format5rc, Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.JUMBO_OPCODE), INVOKE_OBJECT_INIT_JUMBO((short)0xfff2, "invoke-object-init/jumbo", ReferenceType.method, Format.Format5rc, Opcode.ODEX_ONLY | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_RESULT | Opcode.JUMBO_OPCODE | Opcode.CAN_INITIALIZE_REFERENCE), IGET_VOLATILE_JUMBO((short)0xfff3, "iget-volatile/jumbo", ReferenceType.field, Format.Format52c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IGET_WIDE_VOLATILE_JUMBO((short)0xfff4, "iget-wide-volatile/jumbo", ReferenceType.field, Format.Format52c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER | Opcode.JUMBO_OPCODE), IGET_OBJECT_VOLATILE_JUMBO((short)0xfff5, "iget-object-volatile/jumbo", ReferenceType.field, Format.Format52c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), IPUT_VOLATILE_JUMBO((short)0xfff6, "iput-volatile/jumbo", ReferenceType.field, Format.Format52c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_WIDE_VOLATILE_JUMBO((short)0xfff7, "iput-wide-volatile/jumbo", ReferenceType.field, Format.Format52c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), IPUT_OBJECT_VOLATILE_JUMBO((short)0xfff8, "iput-object-volatile/jumbo", ReferenceType.field, Format.Format52c, Opcode.ODEX_ONLY | Opcode.ODEXED_INSTANCE_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SGET_VOLATILE_JUMBO((short)0xfff9, "sget-volatile/jumbo", ReferenceType.field, Format.Format41c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SGET_WIDE_VOLATILE_JUMBO((short)0xfffa, "sget-wide-volatile/jumbo", ReferenceType.field, Format.Format41c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.SETS_WIDE_REGISTER | Opcode.JUMBO_OPCODE), SGET_OBJECT_VOLATILE_JUMBO((short)0xfffb, "sget-object-volatile/jumbo", ReferenceType.field, Format.Format41c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.SETS_REGISTER | Opcode.JUMBO_OPCODE), SPUT_VOLATILE_JUMBO((short)0xfffc, "sput-volatile/jumbo", ReferenceType.field, Format.Format41c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_WIDE_VOLATILE_JUMBO((short)0xfffd, "sput-wide-volatile/jumbo", ReferenceType.field, Format.Format41c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE), SPUT_OBJECT_VOLATILE_JUMBO((short)0xfffe, "sput-object-volatile/jumbo", ReferenceType.field, Format.Format41c, Opcode.ODEX_ONLY | Opcode.ODEXED_STATIC_VOLATILE | Opcode.CAN_THROW | Opcode.CAN_CONTINUE | Opcode.JUMBO_OPCODE); private static Opcode[] opcodesByValue; private static Opcode[] expandedOpcodesByValue; private static HashMap<Integer, Opcode> opcodesByName; //if the instruction can throw an exception public static final int CAN_THROW = 0x1; //if the instruction is an odex only instruction public static final int ODEX_ONLY = 0x2; //if execution can continue to the next instruction public static final int CAN_CONTINUE = 0x4; //if the instruction sets the "hidden" result register public static final int SETS_RESULT = 0x8; //if the instruction sets the value of it's first register public static final int SETS_REGISTER = 0x10; //if the instruction sets the value of it's first register to a wide type public static final int SETS_WIDE_REGISTER = 0x20; //if the instruction is an odexed iget-quick/iput-quick instruction public static final int ODEXED_INSTANCE_QUICK = 0x40; //if the instruction is an odexed iget-volatile/iput-volatile instruction public static final int ODEXED_INSTANCE_VOLATILE = 0x80; //if the instruction is an odexed sget-volatile/sput-volatile instruction public static final int ODEXED_STATIC_VOLATILE = 0x100; //if the instruction is a jumbo instruction public static final int JUMBO_OPCODE = 0x200; //if the instruction can initialize an uninitialized object reference public static final int CAN_INITIALIZE_REFERENCE = 0x400; static { opcodesByValue = new Opcode[256]; expandedOpcodesByValue = new Opcode[256]; opcodesByName = new HashMap<Integer, Opcode>(); for (Opcode opcode: Opcode.values()) { //INVOKE_DIRECT_EMPTY was changed to INVOKE_OBJECT_INIT_RANGE in ICS if (opcode != INVOKE_DIRECT_EMPTY) { if (((opcode.value >> 8) & 0xFF) == 0x00) { opcodesByValue[opcode.value & 0xFF] = opcode; } else { assert ((opcode.value >> 8) & 0xFF) == 0xFF; expandedOpcodesByValue[opcode.value & 0xFF] = opcode; } opcodesByName.put(opcode.name.hashCode(), opcode); } } } public static Opcode getOpcodeByName(String opcodeName) { return opcodesByName.get(opcodeName.toLowerCase().hashCode()); } public static Opcode getOpcodeByValue(short opcodeValue) { if (((opcodeValue >> 8) & 0xFF) == 0x00) { return opcodesByValue[opcodeValue & 0xFF]; } else { assert ((opcodeValue >> 8) & 0xFF) == 0xFF; return expandedOpcodesByValue[opcodeValue & 0xFF]; } } private static void removeOpcodes(Opcode... toRemove) { for (Opcode opcode: toRemove) { opcodesByName.remove(opcode.name.toLowerCase().hashCode()); if (((opcode.value >> 8) & 0xFF) == 0x00) { opcodesByValue[opcode.value] = null; } else { expandedOpcodesByValue[opcode.value & 0xFF] = null; } } } private static void addOpcodes(Opcode... toAdd) { for (Opcode opcode: toAdd) { if (((opcode.value >> 8) & 0xFF) == 0x00) { opcodesByValue[opcode.value & 0xFF] = opcode; } else { assert ((opcode.value >> 8) & 0xFF) == 0xFF; expandedOpcodesByValue[opcode.value & 0xFF] = opcode; } opcodesByName.put(opcode.name.hashCode(), opcode); } } /** * This will add/remove/replace various opcodes in the value/name maps as needed, * based on the idiosyncrasies of that api level * @param apiLevel */ public static void updateMapsForApiLevel(int apiLevel, boolean includeJumbo) { if (apiLevel < 5) { removeOpcodes(THROW_VERIFICATION_ERROR); } if (apiLevel < 8) { removeOpcodes(EXECUTE_INLINE_RANGE); } if (apiLevel < 9) { removeOpcodes(IGET_VOLATILE, IPUT_VOLATILE, SGET_VOLATILE, SPUT_VOLATILE, IGET_OBJECT_VOLATILE, IGET_WIDE_VOLATILE, IPUT_WIDE_VOLATILE, SGET_WIDE_VOLATILE, SPUT_WIDE_VOLATILE, IPUT_OBJECT_VOLATILE, SGET_OBJECT_VOLATILE, SPUT_OBJECT_VOLATILE); } if (apiLevel < 11) { removeOpcodes(RETURN_VOID_BARRIER); } if (apiLevel < 14) { removeOpcodes(INVOKE_OBJECT_INIT_RANGE); addOpcodes(INVOKE_DIRECT_EMPTY); } if (apiLevel < 14 || !includeJumbo) { removeOpcodes(CONST_CLASS_JUMBO, CHECK_CAST_JUMBO, INSTANCE_OF_JUMBO, NEW_INSTANCE_JUMBO, NEW_ARRAY_JUMBO, FILLED_NEW_ARRAY_JUMBO, IGET_JUMBO, IGET_WIDE_JUMBO, IGET_OBJECT_JUMBO, IGET_BOOLEAN_JUMBO, IGET_BYTE_JUMBO, IGET_CHAR_JUMBO, IGET_SHORT_JUMBO, IPUT_JUMBO, IPUT_WIDE_JUMBO, IPUT_OBJECT_JUMBO, IPUT_BOOLEAN_JUMBO, IPUT_BYTE_JUMBO, IPUT_CHAR_JUMBO, IPUT_SHORT_JUMBO, SGET_JUMBO, SGET_WIDE_JUMBO, SGET_OBJECT_JUMBO, SGET_BOOLEAN_JUMBO, SGET_BYTE_JUMBO, SGET_CHAR_JUMBO, SGET_SHORT_JUMBO, SPUT_JUMBO, SPUT_WIDE_JUMBO, SPUT_OBJECT_JUMBO, SPUT_BOOLEAN_JUMBO, SPUT_BYTE_JUMBO, SPUT_CHAR_JUMBO, SPUT_SHORT_JUMBO, INVOKE_VIRTUAL_JUMBO, INVOKE_SUPER_JUMBO, INVOKE_DIRECT_JUMBO, INVOKE_STATIC_JUMBO, INVOKE_INTERFACE_JUMBO, INVOKE_OBJECT_INIT_JUMBO, IGET_VOLATILE_JUMBO, IGET_WIDE_VOLATILE_JUMBO, IGET_OBJECT_VOLATILE_JUMBO, IPUT_VOLATILE_JUMBO, IPUT_WIDE_VOLATILE_JUMBO, IPUT_OBJECT_VOLATILE_JUMBO, SGET_VOLATILE_JUMBO, SGET_WIDE_VOLATILE_JUMBO, SGET_OBJECT_VOLATILE_JUMBO, SPUT_VOLATILE_JUMBO, SPUT_WIDE_VOLATILE_JUMBO, SPUT_OBJECT_VOLATILE_JUMBO); } } public final short value; public final String name; public final ReferenceType referenceType; public final Format format; public final int flags; private final short jumboOpcode; Opcode(short opcodeValue, String opcodeName, ReferenceType referenceType, Format format) { this(opcodeValue, opcodeName, referenceType, format, 0); } Opcode(short opcodeValue, String opcodeName, ReferenceType referenceType, Format format, int flags) { this(opcodeValue, opcodeName, referenceType, format, flags, (short)-1); } Opcode(short opcodeValue, String opcodeName, ReferenceType referenceType, Format format, int flags, short jumboOpcodeValue) { this.value = opcodeValue; this.name = opcodeName; this.referenceType = referenceType; this.format = format; this.flags = flags; this.jumboOpcode = jumboOpcodeValue; } public final boolean canThrow() { return (flags & CAN_THROW) != 0; } public final boolean odexOnly() { return (flags & ODEX_ONLY) != 0; } public final boolean canContinue() { return (flags & CAN_CONTINUE) != 0; } public final boolean setsResult() { return (flags & SETS_RESULT) != 0; } public final boolean setsRegister() { return (flags & SETS_REGISTER) != 0; } public final boolean setsWideRegister() { return (flags & SETS_WIDE_REGISTER) != 0; } public final boolean isOdexedInstanceQuick() { return (flags & ODEXED_INSTANCE_QUICK) != 0; } public final boolean isOdexedInstanceVolatile() { return (flags & ODEXED_INSTANCE_VOLATILE) != 0; } public final boolean isOdexedStaticVolatile() { return (flags & ODEXED_STATIC_VOLATILE) != 0; } public final boolean isJumboOpcode() { return (flags & JUMBO_OPCODE) != 0; } public final boolean canInitializeReference() { return (flags & CAN_INITIALIZE_REFERENCE) != 0; } public final boolean hasJumboOpcode() { return jumboOpcode != -1 && Opcode.getOpcodeByValue(jumboOpcode) != null; } public final Opcode getJumboOpcode() { return Opcode.getOpcodeByValue(jumboOpcode); } }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/Opcode.java
Java
asf20
55,113
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib.Code; public interface OdexedInvokeVirtual { int getVtableIndex(); }
zztobat-apktool
brut.apktool.smali/dexlib/src/main/java/org/jf/dexlib/Code/OdexedInvokeVirtual.java
Java
asf20
1,598