diff options
Diffstat (limited to 'plugins/java-decompiler/engine')
265 files changed, 41119 insertions, 0 deletions
diff --git a/plugins/java-decompiler/engine/.gitattributes b/plugins/java-decompiler/engine/.gitattributes new file mode 100644 index 000000000000..f1df734f9f0b --- /dev/null +++ b/plugins/java-decompiler/engine/.gitattributes @@ -0,0 +1 @@ +*.dec text diff --git a/plugins/java-decompiler/engine/build.xml b/plugins/java-decompiler/engine/build.xml new file mode 100644 index 000000000000..8dde32e6adda --- /dev/null +++ b/plugins/java-decompiler/engine/build.xml @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project name="Fernflower" default="dist" basedir="."> + + <target name="init"> + <property name="src" value="${basedir}/src"/> + <property name="out" value="${basedir}/out/production"/> + <property name="dist" value="${basedir}/fernflower.jar"/> + <property name="test-src" value="${basedir}/test"/> + <property name="test-out" value="${basedir}/out/test"/> + </target> + + <!-- external dependencies, adjust to your own --> + <path id="junit"> + <file name="${basedir}/../../../lib/junit-4.11.jar"/> + <file name="${basedir}/../../../lib/hamcrest-core-1.3.jar"/> + <file name="${basedir}/../../../lib/hamcrest-library-1.3.jar"/> + </path> + + <target name="clean" depends="init"> + <delete includeemptydirs="true" failonerror="false"> + <fileset dir="${out}"/> + <fileset dir="${test-out}"/> + <fileset file="${dist}"/> + </delete> + </target> + + <target name="compile" depends="init,clean"> + <mkdir dir="${out}"/> + <javac srcdir="${src}" destdir="${out}" source="1.6" target="1.6" encoding="UTF-8" debug="true" includeantruntime="false"/> + </target> + + <target name="dist" depends="init,compile"> + <jar jarfile="${dist}" compress="true" basedir="${out}" includes="**/*.class"> + <manifest> + <attribute name="Main-Class" value="org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler"/> + </manifest> + </jar> + </target> + + <target name="test-compile" depends="init,compile"> + <mkdir dir="${test-out}"/> + <javac srcdir="${test-src}" destdir="${test-out}" source="1.6" target="1.6" encoding="UTF-8" debug="true" includeantruntime="false"> + <classpath path="${out}"/> + <classpath refid="junit"/> + </javac> + </target> + + <target name="test" depends="init,test-compile"> + <junit printsummary="true" haltonfailure="true"> + <classpath path="${test-out}:${out}"/> + <classpath refid="junit"/> + <batchtest> + <fileset dir="${test-src}" includes="**/*Test.java"/> + </batchtest> + </junit> + </target> + +</project> diff --git a/plugins/java-decompiler/engine/readme.txt b/plugins/java-decompiler/engine/readme.txt new file mode 100644 index 000000000000..b0ea2733f6f3 --- /dev/null +++ b/plugins/java-decompiler/engine/readme.txt @@ -0,0 +1,88 @@ +1. About the decompiler + +Fernflower is the first actually working analytical decompiler for Java and +probably for a high-level programming language in general. Naturally it is still +under development, please send your bug reports and improvement suggestions at +fernflower.decompiler@gmail.com + + +2. License + +http://www.apache.org/licenses/LICENSE-2.0 + + +3. Running from the command line + +java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination> + +* means 0 or more times ++ means 1 or more times + +<source>: file or directory with files to be decompiled. Directories are recursively scanned. Allowed file extensions are class, zip and jar. + Sources prefixed with -e= mean "library" files that won't be decompiled, but taken into account when analysing relationships between + classes or methods. Especially renaming of identifiers (s. option 'ren') can benefit from information about external classes. +<destination>: destination directory +<option>,<value>: command line option with the corresponding value, see 4. + +Examples: + +java -jar fernflower.jar -hes=0 -hdc=0 c:\Temp\binary\ -e=c:\Java\rt.jar c:\Temp\source\ + +java -jar fernflower.jar -dgs=1 c:\Temp\binary\library.jar c:\Temp\binary\Boot.class c:\Temp\source\ + + +4. Command line options + +With the exception of mpm and urc the value of 1 means the option is activated, 0 - deactivated. Default +value, if any, is given between parentheses. + +Typically, the following options will be changed by user, if any: hes, hdc, dgs, mpm, ren, urc +The rest of options can be left as they are: they are aimed at professional reverse engineers. + +rbr (1): hide bridge methods +rsy (0): hide synthetic class members +din (1): decompile inner classes +dc4 (1): collapse 1.4 class references +das (1): decompile assertions +hes (1): hide empty super invocation +hdc (1): hide empty default constructor +dgs (0): decompile generic signatures +ner (1): assume return not throwing exceptions +den (1): decompile enumerations +rgn (1): remove getClass() invocation, when it is part of a qualified new statement +lit (0): output numeric literals "as-is" +asc (0): encode non-ASCII characters in string and character literals as Unicode escapes +bto (1): interpret int 1 as boolean true (workaround to a compiler bug) +nns (1): allow for not set synthetic attribute (workaround to a compiler bug) +uto (1): consider nameless types as java.lang.Object (workaround to a compiler architecture flaw) +udv (1): reconstruct variable names from debug information, if present +rer (1): remove empty exception ranges +fdi (1): de-inline finally structures +mpm (0): maximum allowed processing time per decompiled method, in seconds. 0 means no upper limit +ren (0): rename ambiguous (resp. obfuscated) classes and class elements +urc : full name of user-supplied class implementing IIdentifierRenamer. It is used to determine which class identifiers + should be renamed and provides new identifier names. For more information see section 5 +inn (1): check for IntelliJ IDEA-specific @NotNull annotation and remove inserted code if found +lac (0): decompile lambda expressions to anonymous classes +nls (0): define new line character to be used for output. 0 - '\r\n' (Windows), 1 - '\n' (Linux), default is OS-dependent +ind : indentation string (default is " " (3 spaces)) + +The default logging level is INFO. This value can be overwritten by setting the option 'log' as follows: +log (INFO): possible values TRACE, INFO, WARN, ERROR + + +5. Renaming identifiers + +Some obfuscators give classes and their member elements short, meaningless and above all ambiguous names. Recompiling of such +code leads to a great number of conflicts. Therefore it is advisable to let the decompiler rename elements in its turn, +ensuring uniqueness of each identifier. + +Option 'ren' (i.e. -ren=1) activates renaming functionality. Default renaming strategy goes as follows: +- rename an element if its name is a reserved word or is shorter than 3 characters +- new names are built according to a simple pattern: (class|method|field)_<consecutive unique number> +You can overwrite this rules by providing your own implementation of the 4 key methods invoked by the decompiler while renaming. Simply +pass a class that implements org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer in the option 'urc' +(e.g. -urc=com.mypackage.MyRenamer) to Fernflower. The class must be available on the application classpath. + +The meaning of each method should be clear from naming: toBeRenamed determine whether the element will be renamed, while the other three +provide new names for classes, methods and fields respectively. diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/CodeConstants.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/CodeConstants.java new file mode 100644 index 000000000000..4a7ef0fc1815 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/CodeConstants.java @@ -0,0 +1,370 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +public interface CodeConstants { + + // ---------------------------------------------------------------------- + // BYTECODE VERSIONS + // ---------------------------------------------------------------------- + + int BYTECODE_JAVA_LE_4 = 1; + int BYTECODE_JAVA_5 = 2; + int BYTECODE_JAVA_6 = 3; + int BYTECODE_JAVA_7 = 4; + int BYTECODE_JAVA_8 = 5; + + // ---------------------------------------------------------------------- + // VARIABLE TYPES + // ---------------------------------------------------------------------- + + int TYPE_BYTE = 0; + int TYPE_CHAR = 1; + int TYPE_DOUBLE = 2; + int TYPE_FLOAT = 3; + int TYPE_INT = 4; + int TYPE_LONG = 5; + int TYPE_SHORT = 6; + int TYPE_BOOLEAN = 7; + int TYPE_OBJECT = 8; + int TYPE_ADDRESS = 9; + int TYPE_VOID = 10; + int TYPE_ANY = 11; + int TYPE_GROUP2EMPTY = 12; + int TYPE_NULL = 13; + int TYPE_NOTINITIALIZED = 14; + int TYPE_BYTECHAR = 15; + int TYPE_SHORTCHAR = 16; + int TYPE_UNKNOWN = 17; + int TYPE_GENVAR = 18; + + // ---------------------------------------------------------------------- + // VARIABLE TYPE FAMILIES + // ---------------------------------------------------------------------- + + int TYPE_FAMILY_UNKNOWN = 0; + int TYPE_FAMILY_BOOLEAN = 1; + int TYPE_FAMILY_INTEGER = 2; + int TYPE_FAMILY_FLOAT = 3; + int TYPE_FAMILY_LONG = 4; + int TYPE_FAMILY_DOUBLE = 5; + int TYPE_FAMILY_OBJECT = 6; + + // ---------------------------------------------------------------------- + // MODULE CONSTANTS + // ---------------------------------------------------------------------- + + int STACKSIZE_SIMPLE = 1; + int STACKSIZE_DOUBLE = 2; + + int VAR_LOCAL = 0; + int VAR_STACK = 1; + + int VAR_WRITE = 0; + int VAR_READ = 1; + + + // ---------------------------------------------------------------------- + // ACCESS FLAGS + // ---------------------------------------------------------------------- + + int ACC_PUBLIC = 0x0001; + int ACC_PRIVATE = 0x0002; + int ACC_PROTECTED = 0x0004; + int ACC_STATIC = 0x0008; + int ACC_FINAL = 0x0010; + int ACC_SYNCHRONIZED = 0x0020; + int ACC_NATIVE = 0x0100; + int ACC_ABSTRACT = 0x0400; + int ACC_STRICT = 0x0800; + int ACC_VOLATILE = 0x0040; + int ACC_BRIDGE = 0x0040; + int ACC_TRANSIENT = 0x0080; + int ACC_VARARGS = 0x0080; + int ACC_SYNTHETIC = 0x1000; + int ACC_ANNOTATION = 0x2000; + int ACC_ENUM = 0x4000; + + // ---------------------------------------------------------------------- + // CLASS FLAGS + // ---------------------------------------------------------------------- + + int ACC_SUPER = 0x0020; + int ACC_INTERFACE = 0x0200; + + + // ---------------------------------------------------------------------- + // DEPENDENCY CONSTANTS + // ---------------------------------------------------------------------- + + int DEP_CONSTANT = 0; + int DEP_UNKNOWN = 1; + int DEP_GENERAL = 2; + int DEP_PARAMS = 4; + int DEP_STATIC = 8; + + // ---------------------------------------------------------------------- + // INSTRUCTION GROUPS + // ---------------------------------------------------------------------- + + int GROUP_GENERAL = 1; + int GROUP_JUMP = 2; + int GROUP_SWITCH = 3; + int GROUP_INVOCATION = 4; + int GROUP_FIELDACCESS = 5; + int GROUP_RETURN = 6; + + // ---------------------------------------------------------------------- + // POOL CONSTANTS + // ---------------------------------------------------------------------- + + int CONSTANT_Utf8 = 1; + int CONSTANT_Integer = 3; + int CONSTANT_Float = 4; + int CONSTANT_Long = 5; + int CONSTANT_Double = 6; + int CONSTANT_Class = 7; + int CONSTANT_String = 8; + int CONSTANT_Fieldref = 9; + int CONSTANT_Methodref = 10; + int CONSTANT_InterfaceMethodref = 11; + int CONSTANT_NameAndType = 12; + int CONSTANT_MethodHandle = 15; + int CONSTANT_MethodType = 16; + int CONSTANT_InvokeDynamic = 18; + + // ---------------------------------------------------------------------- + // MethodHandle reference_kind values + // ---------------------------------------------------------------------- + + int CONSTANT_MethodHandle_REF_getField = 1; + int CONSTANT_MethodHandle_REF_getStatic = 2; + int CONSTANT_MethodHandle_REF_putField = 3; + int CONSTANT_MethodHandle_REF_putStatic = 4; + int CONSTANT_MethodHandle_REF_invokeVirtual = 5; + int CONSTANT_MethodHandle_REF_invokeStatic = 6; + int CONSTANT_MethodHandle_REF_invokeSpecial = 7; + int CONSTANT_MethodHandle_REF_newInvokeSpecial = 8; + int CONSTANT_MethodHandle_REF_invokeInterface = 9; + + // ---------------------------------------------------------------------- + // VM OPCODES + // ---------------------------------------------------------------------- + + int opc_nop = 0; + int opc_aconst_null = 1; + int opc_iconst_m1 = 2; + int opc_iconst_0 = 3; + int opc_iconst_1 = 4; + int opc_iconst_2 = 5; + int opc_iconst_3 = 6; + int opc_iconst_4 = 7; + int opc_iconst_5 = 8; + int opc_lconst_0 = 9; + int opc_lconst_1 = 10; + int opc_fconst_0 = 11; + int opc_fconst_1 = 12; + int opc_fconst_2 = 13; + int opc_dconst_0 = 14; + int opc_dconst_1 = 15; + int opc_bipush = 16; + int opc_sipush = 17; + int opc_ldc = 18; + int opc_ldc_w = 19; + int opc_ldc2_w = 20; + int opc_iload = 21; + int opc_lload = 22; + int opc_fload = 23; + int opc_dload = 24; + int opc_aload = 25; + int opc_iload_0 = 26; + int opc_iload_1 = 27; + int opc_iload_2 = 28; + int opc_iload_3 = 29; + int opc_lload_0 = 30; + int opc_lload_1 = 31; + int opc_lload_2 = 32; + int opc_lload_3 = 33; + int opc_fload_0 = 34; + int opc_fload_1 = 35; + int opc_fload_2 = 36; + int opc_fload_3 = 37; + int opc_dload_0 = 38; + int opc_dload_1 = 39; + int opc_dload_2 = 40; + int opc_dload_3 = 41; + int opc_aload_0 = 42; + int opc_aload_1 = 43; + int opc_aload_2 = 44; + int opc_aload_3 = 45; + int opc_iaload = 46; + int opc_laload = 47; + int opc_faload = 48; + int opc_daload = 49; + int opc_aaload = 50; + int opc_baload = 51; + int opc_caload = 52; + int opc_saload = 53; + int opc_istore = 54; + int opc_lstore = 55; + int opc_fstore = 56; + int opc_dstore = 57; + int opc_astore = 58; + int opc_istore_0 = 59; + int opc_istore_1 = 60; + int opc_istore_2 = 61; + int opc_istore_3 = 62; + int opc_lstore_0 = 63; + int opc_lstore_1 = 64; + int opc_lstore_2 = 65; + int opc_lstore_3 = 66; + int opc_fstore_0 = 67; + int opc_fstore_1 = 68; + int opc_fstore_2 = 69; + int opc_fstore_3 = 70; + int opc_dstore_0 = 71; + int opc_dstore_1 = 72; + int opc_dstore_2 = 73; + int opc_dstore_3 = 74; + int opc_astore_0 = 75; + int opc_astore_1 = 76; + int opc_astore_2 = 77; + int opc_astore_3 = 78; + int opc_iastore = 79; + int opc_lastore = 80; + int opc_fastore = 81; + int opc_dastore = 82; + int opc_aastore = 83; + int opc_bastore = 84; + int opc_castore = 85; + int opc_sastore = 86; + int opc_pop = 87; + int opc_pop2 = 88; + int opc_dup = 89; + int opc_dup_x1 = 90; + int opc_dup_x2 = 91; + int opc_dup2 = 92; + int opc_dup2_x1 = 93; + int opc_dup2_x2 = 94; + int opc_swap = 95; + int opc_iadd = 96; + int opc_ladd = 97; + int opc_fadd = 98; + int opc_dadd = 99; + int opc_isub = 100; + int opc_lsub = 101; + int opc_fsub = 102; + int opc_dsub = 103; + int opc_imul = 104; + int opc_lmul = 105; + int opc_fmul = 106; + int opc_dmul = 107; + int opc_idiv = 108; + int opc_ldiv = 109; + int opc_fdiv = 110; + int opc_ddiv = 111; + int opc_irem = 112; + int opc_lrem = 113; + int opc_frem = 114; + int opc_drem = 115; + int opc_ineg = 116; + int opc_lneg = 117; + int opc_fneg = 118; + int opc_dneg = 119; + int opc_ishl = 120; + int opc_lshl = 121; + int opc_ishr = 122; + int opc_lshr = 123; + int opc_iushr = 124; + int opc_lushr = 125; + int opc_iand = 126; + int opc_land = 127; + int opc_ior = 128; + int opc_lor = 129; + int opc_ixor = 130; + int opc_lxor = 131; + int opc_iinc = 132; + int opc_i2l = 133; + int opc_i2f = 134; + int opc_i2d = 135; + int opc_l2i = 136; + int opc_l2f = 137; + int opc_l2d = 138; + int opc_f2i = 139; + int opc_f2l = 140; + int opc_f2d = 141; + int opc_d2i = 142; + int opc_d2l = 143; + int opc_d2f = 144; + int opc_i2b = 145; + int opc_i2c = 146; + int opc_i2s = 147; + int opc_lcmp = 148; + int opc_fcmpl = 149; + int opc_fcmpg = 150; + int opc_dcmpl = 151; + int opc_dcmpg = 152; + int opc_ifeq = 153; + int opc_ifne = 154; + int opc_iflt = 155; + int opc_ifge = 156; + int opc_ifgt = 157; + int opc_ifle = 158; + int opc_if_icmpeq = 159; + int opc_if_icmpne = 160; + int opc_if_icmplt = 161; + int opc_if_icmpge = 162; + int opc_if_icmpgt = 163; + int opc_if_icmple = 164; + int opc_if_acmpeq = 165; + int opc_if_acmpne = 166; + int opc_goto = 167; + int opc_jsr = 168; + int opc_ret = 169; + int opc_tableswitch = 170; + int opc_lookupswitch = 171; + int opc_ireturn = 172; + int opc_lreturn = 173; + int opc_freturn = 174; + int opc_dreturn = 175; + int opc_areturn = 176; + int opc_return = 177; + int opc_getstatic = 178; + int opc_putstatic = 179; + int opc_getfield = 180; + int opc_putfield = 181; + int opc_invokevirtual = 182; + int opc_invokespecial = 183; + int opc_invokestatic = 184; + int opc_invokeinterface = 185; + int opc_invokedynamic = 186; + int opc_xxxunusedxxx = 186; + int opc_new = 187; + int opc_newarray = 188; + int opc_anewarray = 189; + int opc_arraylength = 190; + int opc_athrow = 191; + int opc_checkcast = 192; + int opc_instanceof = 193; + int opc_monitorenter = 194; + int opc_monitorexit = 195; + int opc_wide = 196; + int opc_multianewarray = 197; + int opc_ifnull = 198; + int opc_ifnonnull = 199; + int opc_goto_w = 200; + int opc_jsr_w = 201; +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ConstantsUtil.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ConstantsUtil.java new file mode 100644 index 000000000000..79eecdffa673 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ConstantsUtil.java @@ -0,0 +1,482 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import org.jetbrains.java.decompiler.code.optinstructions.*; + +public class ConstantsUtil { + + public static String getName(int opcode) { + return opcodeNames[opcode]; + } + + public static Instruction getInstructionInstance(int opcode, boolean wide, int group, int bytecode_version, int[] operands) { + + Instruction instr = getInstructionInstance(opcode, bytecode_version); + instr.wide = wide; + instr.group = group; + instr.bytecode_version = bytecode_version; + instr.setOperands(operands); + + return instr; + } + + private static Instruction getInstructionInstance(int opcode, int bytecode_version) { + try { + Instruction instr; + + if ((opcode >= CodeConstants.opc_ifeq && + opcode <= CodeConstants.opc_if_acmpne) || + opcode == CodeConstants.opc_ifnull || + opcode == CodeConstants.opc_ifnonnull) { + instr = new IfInstruction(); + } + else { + + Class cl = opcodeClasses[opcode]; + + if (opcode == CodeConstants.opc_invokedynamic && bytecode_version < CodeConstants.BYTECODE_JAVA_7) { + cl = null; // instruction unused in Java 6 and before + } + + if (cl == null) { + instr = new Instruction(); + } + else { + instr = (Instruction)cl.newInstance(); + } + } + + instr.opcode = opcode; + return instr; + } + catch (Exception ex) { + return null; + } + } + + + private static String[] opcodeNames = { + "nop", // "nop", + "aconst_null", // "aconst_null", + "iconst_m1", // "iconst_m1", + "iconst_0", // "iconst_0", + "iconst_1", // "iconst_1", + "iconst_2", // "iconst_2", + "iconst_3", // "iconst_3", + "iconst_4", // "iconst_4", + "iconst_5", // "iconst_5", + "lconst_0", // "lconst_0", + "lconst_1", // "lconst_1", + "fconst_0", // "fconst_0", + "fconst_1", // "fconst_1", + "fconst_2", // "fconst_2", + "dconst_0", // "dconst_0", + "dconst_1", // "dconst_1", + "bipush", // "bipush", + "sipush", // "sipush", + "ldc", // "ldc", + "ldc_w", // "ldc_w", + "ldc2_w", // "ldc2_w", + "iload", // "iload", + "lload", // "lload", + "fload", // "fload", + "dload", // "dload", + "aload", // "aload", + "iload_0", // "iload_0", + "iload_1", // "iload_1", + "iload_2", // "iload_2", + "iload_3", // "iload_3", + "lload_0", // "lload_0", + "lload_1", // "lload_1", + "lload_2", // "lload_2", + "lload_3", // "lload_3", + "fload_0", // "fload_0", + "fload_1", // "fload_1", + "fload_2", // "fload_2", + "fload_3", // "fload_3", + "dload_0", // "dload_0", + "dload_1", // "dload_1", + "dload_2", // "dload_2", + "dload_3", // "dload_3", + "aload_0", // "aload_0", + "aload_1", // "aload_1", + "aload_2", // "aload_2", + "aload_3", // "aload_3", + "iaload", // "iaload", + "laload", // "laload", + "faload", // "faload", + "daload", // "daload", + "aaload", // "aaload", + "baload", // "baload", + "caload", // "caload", + "saload", // "saload", + "istore", // "istore", + "lstore", // "lstore", + "fstore", // "fstore", + "dstore", // "dstore", + "astore", // "astore", + "istore_0", // "istore_0", + "istore_1", // "istore_1", + "istore_2", // "istore_2", + "istore_3", // "istore_3", + "lstore_0", // "lstore_0", + "lstore_1", // "lstore_1", + "lstore_2", // "lstore_2", + "lstore_3", // "lstore_3", + "fstore_0", // "fstore_0", + "fstore_1", // "fstore_1", + "fstore_2", // "fstore_2", + "fstore_3", // "fstore_3", + "dstore_0", // "dstore_0", + "dstore_1", // "dstore_1", + "dstore_2", // "dstore_2", + "dstore_3", // "dstore_3", + "astore_0", // "astore_0", + "astore_1", // "astore_1", + "astore_2", // "astore_2", + "astore_3", // "astore_3", + "iastore", // "iastore", + "lastore", // "lastore", + "fastore", // "fastore", + "dastore", // "dastore", + "aastore", // "aastore", + "bastore", // "bastore", + "castore", // "castore", + "sastore", // "sastore", + "pop", // "pop", + "pop2", // "pop2", + "dup", // "dup", + "dup_x1", // "dup_x1", + "dup_x2", // "dup_x2", + "dup2", // "dup2", + "dup2_x1", // "dup2_x1", + "dup2_x2", // "dup2_x2", + "swap", // "swap", + "iadd", // "iadd", + "ladd", // "ladd", + "fadd", // "fadd", + "dadd", // "dadd", + "isub", // "isub", + "lsub", // "lsub", + "fsub", // "fsub", + "dsub", // "dsub", + "imul", // "imul", + "lmul", // "lmul", + "fmul", // "fmul", + "dmul", // "dmul", + "idiv", // "idiv", + "ldiv", // "ldiv", + "fdiv", // "fdiv", + "ddiv", // "ddiv", + "irem", // "irem", + "lrem", // "lrem", + "frem", // "frem", + "drem", // "drem", + "ineg", // "ineg", + "lneg", // "lneg", + "fneg", // "fneg", + "dneg", // "dneg", + "ishl", // "ishl", + "lshl", // "lshl", + "ishr", // "ishr", + "lshr", // "lshr", + "iushr", // "iushr", + "lushr", // "lushr", + "iand", // "iand", + "land", // "land", + "ior", // "ior", + "lor", // "lor", + "ixor", // "ixor", + "lxor", // "lxor", + "iinc", // "iinc", + "i2l", // "i2l", + "i2f", // "i2f", + "i2d", // "i2d", + "l2i", // "l2i", + "l2f", // "l2f", + "l2d", // "l2d", + "f2i", // "f2i", + "f2l", // "f2l", + "f2d", // "f2d", + "d2i", // "d2i", + "d2l", // "d2l", + "d2f", // "d2f", + "i2b", // "i2b", + "i2c", // "i2c", + "i2s", // "i2s", + "lcmp", // "lcmp", + "fcmpl", // "fcmpl", + "fcmpg", // "fcmpg", + "dcmpl", // "dcmpl", + "dcmpg", // "dcmpg", + "ifeq", // "ifeq", + "ifne", // "ifne", + "iflt", // "iflt", + "ifge", // "ifge", + "ifgt", // "ifgt", + "ifle", // "ifle", + "if_icmpeq", // "if_icmpeq", + "if_icmpne", // "if_icmpne", + "if_icmplt", // "if_icmplt", + "if_icmpge", // "if_icmpge", + "if_icmpgt", // "if_icmpgt", + "if_icmple", // "if_icmple", + "if_acmpeq", // "if_acmpeq", + "if_acmpne", // "if_acmpne", + "goto", // "goto", + "jsr", // "jsr", + "ret", // "ret", + "tableswitch", // "tableswitch", + "lookupswitch", // "lookupswitch", + "ireturn", // "ireturn", + "lreturn", // "lreturn", + "freturn", // "freturn", + "dreturn", // "dreturn", + "areturn", // "areturn", + "return", // "return", + "getstatic", // "getstatic", + "putstatic", // "putstatic", + "getfield", // "getfield", + "putfield", // "putfield", + "invokevirtual", // "invokevirtual", + "invokespecial", // "invokespecial", + "invokestatic", // "invokestatic", + "invokeinterface", // "invokeinterface", + //"xxxunusedxxx", // "xxxunusedxxx", Java 6 and before + "invokedynamic", // "invokedynamic", Java 7 and later + "new", // "new", + "newarray", // "newarray", + "anewarray", // "anewarray", + "arraylength", // "arraylength", + "athrow", // "athrow", + "checkcast", // "checkcast", + "instanceof", // "instanceof", + "monitorenter", // "monitorenter", + "monitorexit", // "monitorexit", + "wide", // "wide", + "multianewarray", // "multianewarray", + "ifnull", // "ifnull", + "ifnonnull", // "ifnonnull", + "goto_w", // "goto_w", + "jsr_w" // "jsr_w" + }; + + private static Class[] opcodeClasses = { + null, // "nop", + null, // "aconst_null", + null, // "iconst_m1", + null, // "iconst_0", + null, // "iconst_1", + null, // "iconst_2", + null, // "iconst_3", + null, // "iconst_4", + null, // "iconst_5", + null, // "lconst_0", + null, // "lconst_1", + null, // "fconst_0", + null, // "fconst_1", + null, // "fconst_2", + null, // "dconst_0", + null, // "dconst_1", + BIPUSH.class, // "bipush", + SIPUSH.class, // "sipush", + LDC.class, // "ldc", + LDC_W.class, // "ldc_w", + LDC2_W.class, // "ldc2_w", + ILOAD.class, // "iload", + LLOAD.class, // "lload", + FLOAD.class, // "fload", + DLOAD.class, // "dload", + ALOAD.class, // "aload", + null, // "iload_0", + null, // "iload_1", + null, // "iload_2", + null, // "iload_3", + null, // "lload_0", + null, // "lload_1", + null, // "lload_2", + null, // "lload_3", + null, // "fload_0", + null, // "fload_1", + null, // "fload_2", + null, // "fload_3", + null, // "dload_0", + null, // "dload_1", + null, // "dload_2", + null, // "dload_3", + null, // "aload_0", + null, // "aload_1", + null, // "aload_2", + null, // "aload_3", + null, // "iaload", + null, // "laload", + null, // "faload", + null, // "daload", + null, // "aaload", + null, // "baload", + null, // "caload", + null, // "saload", + ISTORE.class, // "istore", + LSTORE.class, // "lstore", + FSTORE.class, // "fstore", + DSTORE.class, // "dstore", + ASTORE.class, // "astore", + null, // "istore_0", + null, // "istore_1", + null, // "istore_2", + null, // "istore_3", + null, // "lstore_0", + null, // "lstore_1", + null, // "lstore_2", + null, // "lstore_3", + null, // "fstore_0", + null, // "fstore_1", + null, // "fstore_2", + null, // "fstore_3", + null, // "dstore_0", + null, // "dstore_1", + null, // "dstore_2", + null, // "dstore_3", + null, // "astore_0", + null, // "astore_1", + null, // "astore_2", + null, // "astore_3", + null, // "iastore", + null, // "lastore", + null, // "fastore", + null, // "dastore", + null, // "aastore", + null, // "bastore", + null, // "castore", + null, // "sastore", + null, // "pop", + null, // "pop2", + null, // "dup", + null, // "dup_x1", + null, // "dup_x2", + null, // "dup2", + null, // "dup2_x1", + null, // "dup2_x2", + null, // "swap", + null, // "iadd", + null, // "ladd", + null, // "fadd", + null, // "dadd", + null, // "isub", + null, // "lsub", + null, // "fsub", + null, // "dsub", + null, // "imul", + null, // "lmul", + null, // "fmul", + null, // "dmul", + null, // "idiv", + null, // "ldiv", + null, // "fdiv", + null, // "ddiv", + null, // "irem", + null, // "lrem", + null, // "frem", + null, // "drem", + null, // "ineg", + null, // "lneg", + null, // "fneg", + null, // "dneg", + null, // "ishl", + null, // "lshl", + null, // "ishr", + null, // "lshr", + null, // "iushr", + null, // "lushr", + null, // "iand", + null, // "land", + null, // "ior", + null, // "lor", + null, // "ixor", + null, // "lxor", + IINC.class, // "iinc", + null, // "i2l", + null, // "i2f", + null, // "i2d", + null, // "l2i", + null, // "l2f", + null, // "l2d", + null, // "f2i", + null, // "f2l", + null, // "f2d", + null, // "d2i", + null, // "d2l", + null, // "d2f", + null, // "i2b", + null, // "i2c", + null, // "i2s", + null, // "lcmp", + null, // "fcmpl", + null, // "fcmpg", + null, // "dcmpl", + null, // "dcmpg", + null, // "ifeq", + null, // "ifne", + null, // "iflt", + null, // "ifge", + null, // "ifgt", + null, // "ifle", + null, // "if_icmpeq", + null, // "if_icmpne", + null, // "if_icmplt", + null, // "if_icmpge", + null, // "if_icmpgt", + null, // "if_icmple", + null, // "if_acmpeq", + null, // "if_acmpne", + GOTO.class, // "goto", + JSR.class, // "jsr", + RET.class, // "ret", + TABLESWITCH.class, // "tableswitch", + LOOKUPSWITCH.class, // "lookupswitch", + null, // "ireturn", + null, // "lreturn", + null, // "freturn", + null, // "dreturn", + null, // "areturn", + null, // "return", + GETSTATIC.class, // "getstatic", + PUTSTATIC.class, // "putstatic", + GETFIELD.class, // "getfield", + PUTFIELD.class, // "putfield", + INVOKEVIRTUAL.class, // "invokevirtual", + INVOKESPECIAL.class, // "invokespecial", + INVOKESTATIC.class, // "invokestatic", + INVOKEINTERFACE.class, // "invokeinterface", + INVOKEDYNAMIC.class, // "xxxunusedxxx" Java 6 and before, "invokedynamic" Java 7 and later + NEW.class, // "new", + NEWARRAY.class, // "newarray", + ANEWARRAY.class, // "anewarray", + null, // "arraylength", + null, // "athrow", + CHECKCAST.class, // "checkcast", + INSTANCEOF.class, // "instanceof", + null, // "monitorenter", + null, // "monitorexit", + null, // "wide", + MULTIANEWARRAY.class, // "multianewarray", + null, // "ifnull", + null, // "ifnonnull", + GOTO_W.class, // "goto_w", + JSR_W.class // "jsr_w" + }; +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ExceptionHandler.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ExceptionHandler.java new file mode 100644 index 000000000000..2927294d8d4a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ExceptionHandler.java @@ -0,0 +1,61 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import org.jetbrains.java.decompiler.main.DecompilerContext; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class ExceptionHandler { + + public int from = 0; + public int to = 0; + public int handler = 0; + + public int from_instr = 0; + public int to_instr = 0; + public int handler_instr = 0; + + public int class_index = 0; + public String exceptionClass = null; + + public ExceptionHandler() { + } + + public ExceptionHandler(int from_raw, int to_raw, int handler_raw, String exceptionClass) { + this.from = from_raw; + this.to = to_raw; + this.handler = handler_raw; + this.exceptionClass = exceptionClass; + } + + public void writeToStream(DataOutputStream out) throws IOException { + out.writeShort(from); + out.writeShort(to); + out.writeShort(handler); + out.writeShort(class_index); + } + + public String toString() { + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + return "from: " + from + " to: " + to + " handler: " + handler + new_line_separator + + "from_instr: " + from_instr + " to_instr: " + to_instr + " handler_instr: " + handler_instr + new_line_separator + + "exceptionClass: " + exceptionClass + new_line_separator; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ExceptionTable.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ExceptionTable.java new file mode 100644 index 000000000000..e828a7f9dc97 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/ExceptionTable.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import org.jetbrains.java.decompiler.code.interpreter.Util; +import org.jetbrains.java.decompiler.struct.StructContext; + +import java.util.ArrayList; +import java.util.List; + +public class ExceptionTable { + + private List<ExceptionHandler> handlers = new ArrayList<ExceptionHandler>(); + + public ExceptionTable() { + } + + public ExceptionTable(List<ExceptionHandler> handlers) { + this.handlers = handlers; + } + + + public ExceptionHandler getHandlerByClass(StructContext context, int line, String valclass, boolean withany) { + + ExceptionHandler res = null; // no handler found + + for (ExceptionHandler handler : handlers) { + if (handler.from <= line && handler.to > line) { + String name = handler.exceptionClass; + + if ((withany && name == null) || // any -> finally or synchronized handler + (name != null && Util.instanceOf(context, valclass, name))) { + res = handler; + break; + } + } + } + + return res; + } + + public List<ExceptionHandler> getHandlers() { + return handlers; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/FullInstructionSequence.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/FullInstructionSequence.java new file mode 100644 index 000000000000..eb8f8192e29f --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/FullInstructionSequence.java @@ -0,0 +1,38 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import org.jetbrains.java.decompiler.util.VBStyleCollection; + + +public class FullInstructionSequence extends InstructionSequence { + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public FullInstructionSequence(VBStyleCollection<Instruction, Integer> collinstr, ExceptionTable extable) { + this.collinstr = collinstr; + this.exceptionTable = extable; + + // translate raw exception handlers to instr + for (ExceptionHandler handler : extable.getHandlers()) { + handler.from_instr = this.getPointerByAbsOffset(handler.from); + handler.to_instr = this.getPointerByAbsOffset(handler.to); + handler.handler_instr = this.getPointerByAbsOffset(handler.handler); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/IfInstruction.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/IfInstruction.java new file mode 100644 index 000000000000..1d4bf6c535bd --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/IfInstruction.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import java.io.DataOutputStream; +import java.io.IOException; + +/* + * opc_ifeq, opc_ifne, opc_iflt, opc_ifge, opc_ifgt, opc_ifle, opc_if_icmpeq, opc_if_icmpne, opc_if_icmplt, + * opc_if_icmpge, opc_if_icmpgt, opc_if_icmple, opc_if_acmpeq, opc_if_acmpne, opc_ifnull, opc_ifnonnull + */ + +public class IfInstruction extends JumpInstruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opcode); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/Instruction.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/Instruction.java new file mode 100644 index 000000000000..d77f3b4f4ede --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/Instruction.java @@ -0,0 +1,126 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class Instruction implements CodeConstants { + + // ***************************************************************************** + // public fields + // ***************************************************************************** + + public int opcode; + + public int group = CodeConstants.GROUP_GENERAL; + + public boolean wide = false; + + public int bytecode_version = BYTECODE_JAVA_LE_4; + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private int[] operands = null; + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public Instruction() { + } + + public int length() { + return 1; + } + + public int operandsCount() { + return (operands == null) ? 0 : operands.length; + } + + public int getOperand(int index) { + return operands[index]; + } + + public Instruction clone() { + return ConstantsUtil.getInstructionInstance(opcode, wide, group, bytecode_version, operands == null ? null : operands.clone()); + } + + public String toString() { + + String res = wide ? "@wide " : ""; + res += "@" + ConstantsUtil.getName(opcode); + + int len = operandsCount(); + for (int i = 0; i < len; i++) { + int op = operands[i]; + if (op < 0) { + res += " -" + Integer.toHexString(-op); + } + else { + res += " " + Integer.toHexString(op); + } + } + + return res; + } + + public boolean canFallthrough() { + return opcode != opc_goto && opcode != opc_goto_w && opcode != opc_ret && + !(opcode >= opc_ireturn && opcode <= opc_return) && opcode != opc_athrow + && opcode != opc_jsr && opcode != opc_tableswitch && opcode != opc_lookupswitch; + } + + public boolean equalsInstruction(Instruction instr) { + if (opcode != instr.opcode || wide != instr.wide + || operandsCount() != instr.operandsCount()) { + return false; + } + + if (operands != null) { + for (int i = 0; i < operands.length; i++) { + if (operands[i] != instr.getOperand(i)) { + return false; + } + } + } + + return true; + } + + // should be overwritten by subclasses + public void initInstruction(InstructionSequence seq) { + } + + // should be overwritten by subclasses + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opcode); + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public int[] getOperands() { + return operands; + } + + public void setOperands(int[] operands) { + this.operands = operands; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/InstructionSequence.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/InstructionSequence.java new file mode 100644 index 000000000000..709a85da3952 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/InstructionSequence.java @@ -0,0 +1,227 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import org.jetbrains.java.decompiler.code.interpreter.Util; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.struct.StructContext; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + + +public abstract class InstructionSequence { + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + protected VBStyleCollection<Instruction, Integer> collinstr = new VBStyleCollection<Instruction, Integer>(); + + protected int pointer = 0; + + protected ExceptionTable exceptionTable = new ExceptionTable(); + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + // to nbe overwritten + public InstructionSequence clone() { + return null; + } + + public void clear() { + collinstr.clear(); + pointer = 0; + exceptionTable = new ExceptionTable(); + } + + public void addInstruction(Instruction inst, int offset) { + collinstr.addWithKey(inst, offset); + } + + public void addInstruction(int index, Instruction inst, int offset) { + collinstr.addWithKeyAndIndex(index, inst, offset); + } + + public void addSequence(InstructionSequence seq) { + for (int i = 0; i < seq.length(); i++) { + addInstruction(seq.getInstr(i), -1); // TODO: any sensible value possible? + } + } + + public void removeInstruction(int index) { + collinstr.remove(index); + } + + public Instruction getCurrentInstr() { + return collinstr.get(pointer); + } + + public Instruction getInstr(int index) { + return collinstr.get(index); + } + + public Instruction getLastInstr() { + return collinstr.getLast(); + } + + public int getCurrentOffset() { + return collinstr.getKey(pointer).intValue(); + } + +public int getOffset(int index) { + return collinstr.getKey(index).intValue(); + } + + public int getPointerByAbsOffset(int offset) { + Integer absoffset = new Integer(offset); + if (collinstr.containsKey(absoffset)) { + return collinstr.getIndexByKey(absoffset); + } + else { + return -1; + } + } + + public int getPointerByRelOffset(int offset) { + Integer absoffset = new Integer(collinstr.getKey(pointer).intValue() + offset); + if (collinstr.containsKey(absoffset)) { + return collinstr.getIndexByKey(absoffset); + } + else { + return -1; + } + } + + public void setPointerByAbsOffset(int offset) { + Integer absoffset = new Integer(collinstr.getKey(pointer).intValue() + offset); + if (collinstr.containsKey(absoffset)) { + pointer = collinstr.getIndexByKey(absoffset); + } + } + + public int length() { + return collinstr.size(); + } + + public boolean isEmpty() { + return collinstr.isEmpty(); + } + + public void addToPointer(int diff) { + this.pointer += diff; + } + + public String toString() { + return toString(0); + } + + public String toString(int indent) { + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + + for (int i = 0; i < collinstr.size(); i++) { + buf.append(InterpreterUtil.getIndentString(indent)); + buf.append(collinstr.getKey(i).intValue()); + buf.append(": "); + buf.append(collinstr.get(i).toString()); + buf.append(new_line_separator); + } + + return buf.toString(); + } + + public void writeCodeToStream(DataOutputStream out) throws IOException { + + for (int i = 0; i < collinstr.size(); i++) { + collinstr.get(i).writeToStream(out, collinstr.getKey(i).intValue()); + } + } + + public void writeExceptionsToStream(DataOutputStream out) throws IOException { + + List<ExceptionHandler> handlers = exceptionTable.getHandlers(); + + out.writeShort(handlers.size()); + for (int i = 0; i < handlers.size(); i++) { + handlers.get(i).writeToStream(out); + } + } + + public void sortHandlers(final StructContext context) { + + Collections.sort(exceptionTable.getHandlers(), new Comparator<ExceptionHandler>() { + + public int compare(ExceptionHandler handler0, ExceptionHandler handler1) { + + if (handler0.to == handler1.to) { + if (handler0.exceptionClass == null) { + return 1; + } + else { + if (handler1.exceptionClass == null) { + return -1; + } + else if (handler0.exceptionClass.equals(handler1.exceptionClass)) { + return (handler0.from > handler1.from) ? -1 : 1; // invalid code + } + else { + if (Util.instanceOf(context, handler0.exceptionClass, handler1.exceptionClass)) { + return -1; + } + else { + return 1; + } + } + } + } + else { + return (handler0.to > handler1.to) ? 1 : -1; + } + } + }); + } + + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public int getPointer() { + return pointer; + } + + public void setPointer(int pointer) { + this.pointer = pointer; + } + + public ExceptionTable getExceptionTable() { + return exceptionTable; + } + + public void setExceptionTable(ExceptionTable exceptionTable) { + this.exceptionTable = exceptionTable; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/JumpInstruction.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/JumpInstruction.java new file mode 100644 index 000000000000..44f4ff9a9b11 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/JumpInstruction.java @@ -0,0 +1,42 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +/* + * opc_ifeq, opc_ifne, opc_iflt, opc_ifge, opc_ifgt, opc_ifle, opc_if_icmpeq, opc_if_icmpne, opc_if_icmplt, + * opc_if_icmpge, opc_if_icmpgt, opc_if_icmple, opc_if_acmpeq, opc_if_acmpne, opc_ifnull, opc_ifnonnull + * opc_goto, opc_jsr, opc_goto_w, opc_jsr_w + */ + + +public class JumpInstruction extends Instruction { + + public int destination; + + public JumpInstruction() { + } + + public void initInstruction(InstructionSequence seq) { + destination = seq.getPointerByRelOffset(this.getOperand(0)); + } + + public JumpInstruction clone() { + JumpInstruction newinstr = (JumpInstruction)super.clone(); + + newinstr.destination = destination; + return newinstr; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/SimpleInstructionSequence.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/SimpleInstructionSequence.java new file mode 100644 index 000000000000..bcc3c4a8da96 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/SimpleInstructionSequence.java @@ -0,0 +1,39 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +public class SimpleInstructionSequence extends InstructionSequence { + + public SimpleInstructionSequence() { + } + + public SimpleInstructionSequence(VBStyleCollection<Instruction, Integer> collinstr) { + this.collinstr = collinstr; + } + + public SimpleInstructionSequence clone() { + SimpleInstructionSequence newseq = new SimpleInstructionSequence(collinstr.clone()); + newseq.setPointer(this.getPointer()); + + return newseq; + } + + public void removeInstruction(int index) { + collinstr.remove(index); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/SwitchInstruction.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/SwitchInstruction.java new file mode 100644 index 000000000000..6aa6a7f7eb34 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/SwitchInstruction.java @@ -0,0 +1,97 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code; + +/* + * opc_tableswitch, lookupswitch + */ + +public class SwitchInstruction extends Instruction { + + private int[] destinations; + + private int[] values; + + private int defaultdest; + + public SwitchInstruction() { + } + + + public void initInstruction(InstructionSequence seq) { + + int pref = (opcode == CodeConstants.opc_tableswitch ? 3 : 2); + int len = this.getOperands().length - pref; + defaultdest = seq.getPointerByRelOffset(this.getOperand(0)); + + int low = 0; + + if (opcode == CodeConstants.opc_lookupswitch) { + len /= 2; + } + else { + low = this.getOperand(1); + } + + destinations = new int[len]; + values = new int[len]; + + for (int i = 0, k = 0; i < len; i++, k++) { + if (opcode == CodeConstants.opc_lookupswitch) { + values[i] = this.getOperand(pref + k); + k++; + } + else { + values[i] = low + k; + } + destinations[i] = seq.getPointerByRelOffset(this.getOperand(pref + k)); + } + } + + public SwitchInstruction clone() { + SwitchInstruction newinstr = (SwitchInstruction)super.clone(); + + newinstr.defaultdest = defaultdest; + newinstr.destinations = destinations.clone(); + newinstr.values = values.clone(); + + return newinstr; + } + + public int[] getDestinations() { + return destinations; + } + + public void setDestinations(int[] destinations) { + this.destinations = destinations; + } + + public int getDefaultdest() { + return defaultdest; + } + + public void setDefaultdest(int defaultdest) { + this.defaultdest = defaultdest; + } + + public int[] getValues() { + return values; + } + + public void setValues(int[] values) { + this.values = values; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/BasicBlock.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/BasicBlock.java new file mode 100644 index 000000000000..61b0a63fd4da --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/BasicBlock.java @@ -0,0 +1,266 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.cfg; + +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.code.InstructionSequence; +import org.jetbrains.java.decompiler.code.SimpleInstructionSequence; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.decompose.IGraphNode; + +import java.util.ArrayList; +import java.util.List; + +public class BasicBlock implements IGraphNode { + + // ***************************************************************************** + // public fields + // ***************************************************************************** + + public int id = 0; + + public int mark = 0; + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private InstructionSequence seq = new SimpleInstructionSequence(); + + private List<BasicBlock> preds = new ArrayList<BasicBlock>(); + + private List<BasicBlock> succs = new ArrayList<BasicBlock>(); + + private List<Integer> instrOldOffsets = new ArrayList<Integer>(); + + private List<BasicBlock> predExceptions = new ArrayList<BasicBlock>(); + + private List<BasicBlock> succExceptions = new ArrayList<BasicBlock>(); + + + public BasicBlock() { + } + + public BasicBlock(int id) { + this.id = id; + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public Object clone() { + + BasicBlock block = new BasicBlock(); + block.id = id; + block.setSeq(seq.clone()); + block.setInstrOldOffsets(new ArrayList<Integer>(instrOldOffsets)); + + return block; + } + + public void free() { + preds.clear(); + succs.clear(); + instrOldOffsets.clear(); + succExceptions.clear(); + seq = new SimpleInstructionSequence(); + } + + public Instruction getInstruction(int index) { + return seq.getInstr(index); + } + + public Instruction getLastInstruction() { + if (seq.isEmpty()) { + return null; + } + else { + return seq.getLastInstr(); + } + } + + public int size() { + return seq.length(); + } + + public void addPredecessor(BasicBlock block) { + preds.add(block); + } + + public void removePredecessor(BasicBlock block) { + while (preds.remove(block)) ; + } + + public void addSuccessor(BasicBlock block) { + succs.add(block); + block.addPredecessor(this); + } + + public void removeSuccessor(BasicBlock block) { + while (succs.remove(block)) ; + block.removePredecessor(this); + } + + // FIXME: unify block comparisons: id or direkt equality + public void replaceSuccessor(BasicBlock oldBlock, BasicBlock newBlock) { + for (int i = 0; i < succs.size(); i++) { + if (succs.get(i).id == oldBlock.id) { + succs.set(i, newBlock); + oldBlock.removePredecessor(this); + newBlock.addPredecessor(this); + } + } + + for (int i = 0; i < succExceptions.size(); i++) { + if (succExceptions.get(i).id == oldBlock.id) { + succExceptions.set(i, newBlock); + oldBlock.removePredecessorException(this); + newBlock.addPredecessorException(this); + } + } + } + + public void addPredecessorException(BasicBlock block) { + predExceptions.add(block); + } + + public void removePredecessorException(BasicBlock block) { + while (predExceptions.remove(block)) ; + } + + public void addSuccessorException(BasicBlock block) { + if (!succExceptions.contains(block)) { + succExceptions.add(block); + block.addPredecessorException(this); + } + } + + public void removeSuccessorException(BasicBlock block) { + while (succExceptions.remove(block)) ; + block.removePredecessorException(this); + } + + public String toString() { + return toString(0); + } + + public String toString(int indent) { + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + return id + ":" + new_line_separator + seq.toString(indent); + } + + public String toStringOldIndices() { + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + + for (int i = 0; i < seq.length(); i++) { + if (i < instrOldOffsets.size()) { + buf.append(instrOldOffsets.get(i)); + } + else { + buf.append("-1"); + } + buf.append(": "); + buf.append(seq.getInstr(i).toString()); + buf.append(new_line_separator); + } + + return buf.toString(); + } + + public boolean isSuccessor(BasicBlock block) { + for (BasicBlock succ : succs) { + if (succ.id == block.id) { + return true; + } + } + return false; + } + + public boolean isPredecessor(BasicBlock block) { + for (int i = 0; i < preds.size(); i++) { + if (preds.get(i).id == block.id) { + return true; + } + } + return false; + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public List<Integer> getInstrOldOffsets() { + return instrOldOffsets; + } + + public void setInstrOldOffsets(List<Integer> instrInds) { + this.instrOldOffsets = instrInds; + } + + public List<? extends IGraphNode> getPredecessors() { + List<BasicBlock> lst = new ArrayList<BasicBlock>(preds); + lst.addAll(predExceptions); + return lst; + } + + public List<BasicBlock> getPreds() { + return preds; + } + + public void setPreds(List<BasicBlock> preds) { + this.preds = preds; + } + + public InstructionSequence getSeq() { + return seq; + } + + public void setSeq(InstructionSequence seq) { + this.seq = seq; + } + + public List<BasicBlock> getSuccs() { + return succs; + } + + public void setSuccs(List<BasicBlock> succs) { + this.succs = succs; + } + + + public List<BasicBlock> getSuccExceptions() { + return succExceptions; + } + + + public void setSuccExceptions(List<BasicBlock> succExceptions) { + this.succExceptions = succExceptions; + } + + public List<BasicBlock> getPredExceptions() { + return predExceptions; + } + + public void setPredExceptions(List<BasicBlock> predExceptions) { + this.predExceptions = predExceptions; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/ControlFlowGraph.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/ControlFlowGraph.java new file mode 100644 index 000000000000..44c58f04e196 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/ControlFlowGraph.java @@ -0,0 +1,884 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.cfg; + +import org.jetbrains.java.decompiler.code.*; +import org.jetbrains.java.decompiler.code.interpreter.InstructionImpact; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.code.DeadCodeHelper; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.struct.gen.DataPoint; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.ListStack; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.*; +import java.util.Map.Entry; + +public class ControlFlowGraph implements CodeConstants { + + public int last_id = 0; + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private VBStyleCollection<BasicBlock, Integer> blocks; + + private BasicBlock first; + + private BasicBlock last; + + private List<ExceptionRangeCFG> exceptions; + + private Map<BasicBlock, BasicBlock> subroutines; + + private Set<BasicBlock> finallyExits = new HashSet<BasicBlock>(); + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public ControlFlowGraph(InstructionSequence seq) { + buildBlocks(seq); + } + + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public void free() { + + for (BasicBlock block : blocks) { + block.free(); + } + + blocks.clear(); + first = null; + last = null; + exceptions.clear(); + finallyExits.clear(); + } + + public void removeMarkers() { + for (BasicBlock block : blocks) { + block.mark = 0; + } + } + + public String toString() { + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + + for (BasicBlock block : blocks) { + buf.append("----- Block ").append(block.id).append(" -----").append(new_line_separator); + buf.append(block.toString()); + buf.append("----- Edges -----").append(new_line_separator); + + List<BasicBlock> suc = block.getSuccs(); + for (int j = 0; j < suc.size(); j++) { + buf.append(">>>>>>>>(regular) Block ").append(suc.get(j).id).append(new_line_separator); + } + suc = block.getSuccExceptions(); + for (int j = 0; j < suc.size(); j++) { + BasicBlock handler = suc.get(j); + ExceptionRangeCFG range = getExceptionRange(handler, block); + + if (range == null) { + buf.append(">>>>>>>>(exception) Block ").append(handler.id).append("\t").append("ERROR: range not found!") + .append(new_line_separator); + } + else { + List<String> exceptionTypes = range.getExceptionTypes(); + if (exceptionTypes == null) { + buf.append(">>>>>>>>(exception) Block ").append(handler.id).append("\t").append("NULL").append(new_line_separator); + } + else { + for (String exceptionType : exceptionTypes) { + buf.append(">>>>>>>>(exception) Block ").append(handler.id).append("\t").append(exceptionType).append(new_line_separator); + } + } + } + } + buf.append("----- ----- -----").append(new_line_separator); + } + + return buf.toString(); + } + + public void inlineJsr(StructMethod mt) { + processJsr(); + removeJsr(mt); + + removeMarkers(); + + DeadCodeHelper.removeEmptyBlocks(this); + } + + public void removeBlock(BasicBlock block) { + + while (block.getSuccs().size() > 0) { + block.removeSuccessor(block.getSuccs().get(0)); + } + + while (block.getSuccExceptions().size() > 0) { + block.removeSuccessorException(block.getSuccExceptions().get(0)); + } + + while (block.getPreds().size() > 0) { + block.getPreds().get(0).removeSuccessor(block); + } + + while (block.getPredExceptions().size() > 0) { + block.getPredExceptions().get(0).removeSuccessorException(block); + } + + last.removePredecessor(block); + + blocks.removeWithKey(block.id); + + for (int i = exceptions.size() - 1; i >= 0; i--) { + ExceptionRangeCFG range = exceptions.get(i); + if (range.getHandler() == block) { + exceptions.remove(i); + } + else { + List<BasicBlock> lstRange = range.getProtectedRange(); + lstRange.remove(block); + + if (lstRange.isEmpty()) { + exceptions.remove(i); + } + } + } + + Iterator<Entry<BasicBlock, BasicBlock>> it = subroutines.entrySet().iterator(); + while (it.hasNext()) { + Entry<BasicBlock, BasicBlock> ent = it.next(); + if (ent.getKey() == block || ent.getValue() == block) { + it.remove(); + } + } + } + + public ExceptionRangeCFG getExceptionRange(BasicBlock handler, BasicBlock block) { + + //List<ExceptionRangeCFG> ranges = new ArrayList<ExceptionRangeCFG>(); + + for (int i = exceptions.size() - 1; i >= 0; i--) { + ExceptionRangeCFG range = exceptions.get(i); + if (range.getHandler() == handler && range.getProtectedRange().contains(block)) { + return range; + //ranges.add(range); + } + } + + return null; + //return ranges.isEmpty() ? null : ranges; + } + + // public String getExceptionsUniqueString(BasicBlock handler, BasicBlock block) { + // + // List<ExceptionRangeCFG> ranges = getExceptionRange(handler, block); + // + // if(ranges == null) { + // return null; + // } else { + // Set<String> setExceptionStrings = new HashSet<String>(); + // for(ExceptionRangeCFG range : ranges) { + // setExceptionStrings.add(range.getExceptionType()); + // } + // + // String ret = ""; + // for(String exception : setExceptionStrings) { + // ret += exception; + // } + // + // return ret; + // } + // } + + + // ***************************************************************************** + // private methods + // ***************************************************************************** + + private void buildBlocks(InstructionSequence instrseq) { + + short[] states = findStartInstructions(instrseq); + + Map<Integer, BasicBlock> mapInstrBlocks = new HashMap<Integer, BasicBlock>(); + VBStyleCollection<BasicBlock, Integer> colBlocks = createBasicBlocks(states, instrseq, mapInstrBlocks); + + blocks = colBlocks; + + connectBlocks(colBlocks, mapInstrBlocks); + + setExceptionEdges(instrseq, mapInstrBlocks); + + setSubroutineEdges(); + + setFirstAndLastBlocks(); + } + + private static short[] findStartInstructions(InstructionSequence seq) { + + int len = seq.length(); + short[] inststates = new short[len]; + + Set<Integer> excSet = new HashSet<Integer>(); + + for (ExceptionHandler handler : seq.getExceptionTable().getHandlers()) { + excSet.add(handler.from_instr); + excSet.add(handler.to_instr); + excSet.add(handler.handler_instr); + } + + + for (int i = 0; i < len; i++) { + + // exception blocks + if (excSet.contains(new Integer(i))) { + inststates[i] = 1; + } + + Instruction instr = seq.getInstr(i); + switch (instr.group) { + case GROUP_JUMP: + inststates[((JumpInstruction)instr).destination] = 1; + case GROUP_RETURN: + if (i + 1 < len) { + inststates[i + 1] = 1; + } + break; + case GROUP_SWITCH: + SwitchInstruction swinstr = (SwitchInstruction)instr; + int[] dests = swinstr.getDestinations(); + for (int j = dests.length - 1; j >= 0; j--) { + inststates[dests[j]] = 1; + } + inststates[swinstr.getDefaultdest()] = 1; + if (i + 1 < len) { + inststates[i + 1] = 1; + } + } + } + + // first instruction + inststates[0] = 1; + + return inststates; + } + + + private VBStyleCollection<BasicBlock, Integer> createBasicBlocks(short[] startblock, + InstructionSequence instrseq, + Map<Integer, BasicBlock> mapInstrBlocks) { + + VBStyleCollection<BasicBlock, Integer> col = new VBStyleCollection<BasicBlock, Integer>(); + + InstructionSequence currseq = null; + ArrayList<Integer> lstOffs = null; + + int len = startblock.length; + short counter = 0; + int blockoffset = 0; + + BasicBlock currentBlock = null; + for (int i = 0; i < len; i++) { + + if (startblock[i] == 1) { + currentBlock = new BasicBlock(); + currentBlock.id = ++counter; + + currseq = new SimpleInstructionSequence(); + lstOffs = new ArrayList<Integer>(); + + currentBlock.setSeq(currseq); + currentBlock.setInstrOldOffsets(lstOffs); + col.addWithKey(currentBlock, currentBlock.id); + + blockoffset = instrseq.getOffset(i); + } + + startblock[i] = counter; + mapInstrBlocks.put(i, currentBlock); + + currseq.addInstruction(instrseq.getInstr(i), instrseq.getOffset(i) - blockoffset); + lstOffs.add(instrseq.getOffset(i)); + } + + last_id = counter; + + return col; + } + + + private static void connectBlocks(List<BasicBlock> lstbb, Map<Integer, BasicBlock> mapInstrBlocks) { + + for (int i = 0; i < lstbb.size(); i++) { + + BasicBlock block = lstbb.get(i); + Instruction instr = block.getLastInstruction(); + + boolean fallthrough = instr.canFallthrough(); + BasicBlock bTemp; + + switch (instr.group) { + case GROUP_JUMP: + int dest = ((JumpInstruction)instr).destination; + bTemp = mapInstrBlocks.get(dest); + block.addSuccessor(bTemp); + + break; + case GROUP_SWITCH: + SwitchInstruction sinstr = (SwitchInstruction)instr; + int[] dests = sinstr.getDestinations(); + + bTemp = mapInstrBlocks.get(((SwitchInstruction)instr).getDefaultdest()); + block.addSuccessor(bTemp); + for (int j = 0; j < dests.length; j++) { + bTemp = mapInstrBlocks.get(dests[j]); + block.addSuccessor(bTemp); + } + } + + if (fallthrough && i < lstbb.size() - 1) { + BasicBlock defaultBlock = lstbb.get(i + 1); + block.addSuccessor(defaultBlock); + } + } + } + + private void setExceptionEdges(InstructionSequence instrseq, Map<Integer, BasicBlock> instrBlocks) { + + exceptions = new ArrayList<ExceptionRangeCFG>(); + + Map<String, ExceptionRangeCFG> mapRanges = new HashMap<String, ExceptionRangeCFG>(); + + for (ExceptionHandler handler : instrseq.getExceptionTable().getHandlers()) { + + BasicBlock from = instrBlocks.get(handler.from_instr); + BasicBlock to = instrBlocks.get(handler.to_instr); + BasicBlock handle = instrBlocks.get(handler.handler_instr); + + String key = from.id + ":" + to.id + ":" + handle.id; + + if (mapRanges.containsKey(key)) { + ExceptionRangeCFG range = mapRanges.get(key); + range.addExceptionType(handler.exceptionClass); + } + else { + + List<BasicBlock> protectedRange = new ArrayList<BasicBlock>(); + for (int j = from.id; j < to.id; j++) { + BasicBlock block = blocks.getWithKey(j); + protectedRange.add(block); + block.addSuccessorException(handle); + } + + ExceptionRangeCFG range = new ExceptionRangeCFG(protectedRange, handle, handler.exceptionClass == null + ? null + : Arrays.asList(handler.exceptionClass)); + mapRanges.put(key, range); + + exceptions.add(range); + } + } + } + + private void setSubroutineEdges() { + + final Map<BasicBlock, BasicBlock> subroutines = new HashMap<BasicBlock, BasicBlock>(); + + for (BasicBlock block : blocks) { + + if (block.getSeq().getLastInstr().opcode == CodeConstants.opc_jsr) { + + LinkedList<BasicBlock> stack = new LinkedList<BasicBlock>(); + LinkedList<LinkedList<BasicBlock>> stackJsrStacks = new LinkedList<LinkedList<BasicBlock>>(); + + Set<BasicBlock> setVisited = new HashSet<BasicBlock>(); + + stack.add(block); + stackJsrStacks.add(new LinkedList<BasicBlock>()); + + while (!stack.isEmpty()) { + + BasicBlock node = stack.removeFirst(); + LinkedList<BasicBlock> jsrstack = stackJsrStacks.removeFirst(); + + setVisited.add(node); + + switch (node.getSeq().getLastInstr().opcode) { + case CodeConstants.opc_jsr: + jsrstack.add(node); + break; + case CodeConstants.opc_ret: + BasicBlock enter = jsrstack.getLast(); + BasicBlock exit = blocks.getWithKey(enter.id + 1); // FIXME: find successor in a better way + + if (exit != null) { + if (!node.isSuccessor(exit)) { + node.addSuccessor(exit); + } + jsrstack.removeLast(); + subroutines.put(enter, exit); + } + else { + throw new RuntimeException("ERROR: last instruction jsr"); + } + } + + if (!jsrstack.isEmpty()) { + for (BasicBlock succ : node.getSuccs()) { + if (!setVisited.contains(succ)) { + stack.add(succ); + stackJsrStacks.add(new LinkedList<BasicBlock>(jsrstack)); + } + } + } + } + } + } + + this.subroutines = subroutines; + } + + private void processJsr() { + while (true) { + if (processJsrRanges() == 0) break; + } + } + + private static class JsrRecord { + private final BasicBlock jsr; + private final Set<BasicBlock> range; + private final BasicBlock ret; + + private JsrRecord(BasicBlock jsr, Set<BasicBlock> range, BasicBlock ret) { + this.jsr = jsr; + this.range = range; + this.ret = ret; + } + } + + private int processJsrRanges() { + + List<JsrRecord> lstJsrAll = new ArrayList<JsrRecord>(); + + // get all jsr ranges + for (Entry<BasicBlock, BasicBlock> ent : subroutines.entrySet()) { + BasicBlock jsr = ent.getKey(); + BasicBlock ret = ent.getValue(); + + lstJsrAll.add(new JsrRecord(jsr, getJsrRange(jsr, ret), ret)); + } + + // sort ranges + // FIXME: better sort order + List<JsrRecord> lstJsr = new ArrayList<JsrRecord>(); + for (JsrRecord arr : lstJsrAll) { + int i = 0; + for (; i < lstJsr.size(); i++) { + JsrRecord arrJsr = lstJsr.get(i); + if (arrJsr.range.contains(arr.jsr)) { + break; + } + } + lstJsr.add(i, arr); + } + + // find the first intersection + for (int i = 0; i < lstJsr.size(); i++) { + JsrRecord arr = lstJsr.get(i); + Set<BasicBlock> set = arr.range; + + for (int j = i + 1; j < lstJsr.size(); j++) { + JsrRecord arr1 = lstJsr.get(j); + Set<BasicBlock> set1 = arr1.range; + + if (!set.contains(arr1.jsr) && !set1.contains(arr.jsr)) { // rang 0 doesn't contain entry 1 and vice versa + Set<BasicBlock> setc = new HashSet<BasicBlock>(set); + setc.retainAll(set1); + + if (!setc.isEmpty()) { + splitJsrRange(arr.jsr, arr.ret, setc); + return 1; + } + } + } + } + + return 0; + } + + private Set<BasicBlock> getJsrRange(BasicBlock jsr, BasicBlock ret) { + + Set<BasicBlock> blocks = new HashSet<BasicBlock>(); + + List<BasicBlock> lstNodes = new LinkedList<BasicBlock>(); + lstNodes.add(jsr); + + BasicBlock dom = jsr.getSuccs().get(0); + + while (!lstNodes.isEmpty()) { + + BasicBlock node = lstNodes.remove(0); + + for (int j = 0; j < 2; j++) { + List<BasicBlock> lst; + if (j == 0) { + if (node.getLastInstruction().opcode == CodeConstants.opc_ret) { + if (node.getSuccs().contains(ret)) { + continue; + } + } + lst = node.getSuccs(); + } + else { + if (node == jsr) { + continue; + } + lst = node.getSuccExceptions(); + } + + CHILD: + for (int i = lst.size() - 1; i >= 0; i--) { + + BasicBlock child = lst.get(i); + if (!blocks.contains(child)) { + + if (node != jsr) { + for (int k = 0; k < child.getPreds().size(); k++) { + if (!DeadCodeHelper.isDominator(this, child.getPreds().get(k), dom)) { + continue CHILD; + } + } + + for (int k = 0; k < child.getPredExceptions().size(); k++) { + if (!DeadCodeHelper.isDominator(this, child.getPredExceptions().get(k), dom)) { + continue CHILD; + } + } + } + + // last block is a dummy one + if (child != last) { + blocks.add(child); + } + + lstNodes.add(child); + } + } + } + } + + return blocks; + } + + private void splitJsrRange(BasicBlock jsr, BasicBlock ret, Set<BasicBlock> common_blocks) { + + List<BasicBlock> lstNodes = new LinkedList<BasicBlock>(); + Map<Integer, BasicBlock> mapNewNodes = new HashMap<Integer, BasicBlock>(); + + lstNodes.add(jsr); + mapNewNodes.put(jsr.id, jsr); + + while (!lstNodes.isEmpty()) { + + BasicBlock node = lstNodes.remove(0); + + for (int j = 0; j < 2; j++) { + List<BasicBlock> lst; + if (j == 0) { + if (node.getLastInstruction().opcode == CodeConstants.opc_ret) { + if (node.getSuccs().contains(ret)) { + continue; + } + } + lst = node.getSuccs(); + } + else { + if (node == jsr) { + continue; + } + lst = node.getSuccExceptions(); + } + + + for (int i = lst.size() - 1; i >= 0; i--) { + + BasicBlock child = lst.get(i); + Integer childid = child.id; + + if (mapNewNodes.containsKey(childid)) { + node.replaceSuccessor(child, mapNewNodes.get(childid)); + } + else if (common_blocks.contains(child)) { + + // make a copy of the current block + BasicBlock copy = (BasicBlock)child.clone(); + copy.id = ++last_id; + // copy all successors + if (copy.getLastInstruction().opcode == CodeConstants.opc_ret && + child.getSuccs().contains(ret)) { + copy.addSuccessor(ret); + child.removeSuccessor(ret); + } + else { + for (int k = 0; k < child.getSuccs().size(); k++) { + copy.addSuccessor(child.getSuccs().get(k)); + } + } + for (int k = 0; k < child.getSuccExceptions().size(); k++) { + copy.addSuccessorException(child.getSuccExceptions().get(k)); + } + + lstNodes.add(copy); + mapNewNodes.put(childid, copy); + + if (last.getPreds().contains(child)) { + last.addPredecessor(copy); + } + + node.replaceSuccessor(child, copy); + blocks.addWithKey(copy, copy.id); + } + else { + // stop at the first fixed node + //lstNodes.add(child); + mapNewNodes.put(childid, child); + } + } + } + } + + // note: subroutines won't be copied! + splitJsrExceptionRanges(common_blocks, mapNewNodes); + } + + private void splitJsrExceptionRanges(Set<BasicBlock> common_blocks, Map<Integer, BasicBlock> mapNewNodes) { + + for (int i = exceptions.size() - 1; i >= 0; i--) { + + ExceptionRangeCFG range = exceptions.get(i); + List<BasicBlock> lstRange = range.getProtectedRange(); + + HashSet<BasicBlock> setBoth = new HashSet<BasicBlock>(common_blocks); + setBoth.retainAll(lstRange); + + if (setBoth.size() > 0) { + List<BasicBlock> lstNewRange; + + if (setBoth.size() == lstRange.size()) { + lstNewRange = new ArrayList<BasicBlock>(); + ExceptionRangeCFG newRange = new ExceptionRangeCFG(lstNewRange, + mapNewNodes.get(range.getHandler().id), range.getExceptionTypes()); + exceptions.add(newRange); + } + else { + lstNewRange = lstRange; + } + + for (BasicBlock block : setBoth) { + lstNewRange.add(mapNewNodes.get(block.id)); + } + } + } + } + + private void removeJsr(StructMethod mt) { + removeJsrInstructions(mt.getClassStruct().getPool(), first, DataPoint.getInitialDataPoint(mt)); + } + + private static void removeJsrInstructions(ConstantPool pool, BasicBlock block, DataPoint data) { + + ListStack<VarType> stack = data.getStack(); + + InstructionSequence seq = block.getSeq(); + for (int i = 0; i < seq.length(); i++) { + Instruction instr = seq.getInstr(i); + + VarType var = null; + if (instr.opcode == CodeConstants.opc_astore || instr.opcode == CodeConstants.opc_pop) { + var = stack.getByOffset(-1); + } + + InstructionImpact.stepTypes(data, instr, pool); + + switch (instr.opcode) { + case CodeConstants.opc_jsr: + case CodeConstants.opc_ret: + seq.removeInstruction(i); + i--; + break; + case CodeConstants.opc_astore: + case CodeConstants.opc_pop: + if (var.type == CodeConstants.TYPE_ADDRESS) { + seq.removeInstruction(i); + i--; + } + } + } + + block.mark = 1; + + for (int i = 0; i < block.getSuccs().size(); i++) { + BasicBlock suc = block.getSuccs().get(i); + if (suc.mark != 1) { + removeJsrInstructions(pool, suc, data.copy()); + } + } + + for (int i = 0; i < block.getSuccExceptions().size(); i++) { + BasicBlock suc = block.getSuccExceptions().get(i); + if (suc.mark != 1) { + + DataPoint point = new DataPoint(); + point.setLocalVariables(new ArrayList<VarType>(data.getLocalVariables())); + point.getStack().push(new VarType(CodeConstants.TYPE_OBJECT, 0, null)); + + removeJsrInstructions(pool, suc, point); + } + } + } + + private void setFirstAndLastBlocks() { + + first = blocks.get(0); + + last = new BasicBlock(); + last.id = ++last_id; + last.setSeq(new SimpleInstructionSequence()); + + for (BasicBlock block : blocks) { + if (block.getSuccs().isEmpty()) { + last.addPredecessor(block); + } + } + } + + public List<BasicBlock> getReversePostOrder() { + + List<BasicBlock> res = new LinkedList<BasicBlock>(); + addToReversePostOrderListIterative(first, res); + + return res; + } + + private static void addToReversePostOrderListIterative(BasicBlock root, List<BasicBlock> lst) { + + LinkedList<BasicBlock> stackNode = new LinkedList<BasicBlock>(); + LinkedList<Integer> stackIndex = new LinkedList<Integer>(); + + Set<BasicBlock> setVisited = new HashSet<BasicBlock>(); + + stackNode.add(root); + stackIndex.add(0); + + while (!stackNode.isEmpty()) { + + BasicBlock node = stackNode.getLast(); + int index = stackIndex.removeLast(); + + setVisited.add(node); + + List<BasicBlock> lstSuccs = new ArrayList<BasicBlock>(node.getSuccs()); + lstSuccs.addAll(node.getSuccExceptions()); + + for (; index < lstSuccs.size(); index++) { + BasicBlock succ = lstSuccs.get(index); + + if (!setVisited.contains(succ)) { + stackIndex.add(index + 1); + + stackNode.add(succ); + stackIndex.add(0); + + break; + } + } + + if (index == lstSuccs.size()) { + lst.add(0, node); + + stackNode.removeLast(); + } + } + } + + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public VBStyleCollection<BasicBlock, Integer> getBlocks() { + return blocks; + } + + public void setBlocks(VBStyleCollection<BasicBlock, Integer> blocks) { + this.blocks = blocks; + } + + public BasicBlock getFirst() { + return first; + } + + public void setFirst(BasicBlock first) { + this.first = first; + } + + public List<BasicBlock> getEndBlocks() { + return last.getPreds(); + } + + public List<ExceptionRangeCFG> getExceptions() { + return exceptions; + } + + public void setExceptions(List<ExceptionRangeCFG> exceptions) { + this.exceptions = exceptions; + } + + public BasicBlock getLast() { + return last; + } + + public void setLast(BasicBlock last) { + this.last = last; + } + + public Map<BasicBlock, BasicBlock> getSubroutines() { + return subroutines; + } + + public void setSubroutines(Map<BasicBlock, BasicBlock> subroutines) { + this.subroutines = subroutines; + } + + public Set<BasicBlock> getFinallyExits() { + return finallyExits; + } + + public void setFinallyExits(HashSet<BasicBlock> finallyExits) { + this.finallyExits = finallyExits; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/ExceptionRangeCFG.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/ExceptionRangeCFG.java new file mode 100644 index 000000000000..47e0e211424f --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/cfg/ExceptionRangeCFG.java @@ -0,0 +1,129 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.cfg; + +import org.jetbrains.java.decompiler.main.DecompilerContext; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class ExceptionRangeCFG { + + private List<BasicBlock> protectedRange = new ArrayList<BasicBlock>(); // FIXME: replace with set + + private BasicBlock handler; + + private List<String> exceptionTypes; + + public ExceptionRangeCFG(List<BasicBlock> protectedRange, BasicBlock handler, List<String> exceptionType) { + this.protectedRange = protectedRange; + this.handler = handler; + + if (exceptionType != null) { + this.exceptionTypes = new ArrayList<String>(exceptionType); + } + } + + public boolean isCircular() { + return protectedRange.contains(handler); + } + + public String toString() { + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + + buf.append("exceptionType:"); + for (String exception_type : exceptionTypes) { + buf.append(" ").append(exception_type); + } + buf.append(new_line_separator); + + buf.append("handler: ").append(handler.id).append(new_line_separator); + buf.append("range: "); + for (int i = 0; i < protectedRange.size(); i++) { + buf.append(protectedRange.get(i).id).append(" "); + } + buf.append(new_line_separator); + + return buf.toString(); + } + + public BasicBlock getHandler() { + return handler; + } + + public void setHandler(BasicBlock handler) { + this.handler = handler; + } + + public List<BasicBlock> getProtectedRange() { + return protectedRange; + } + + public void setProtectedRange(List<BasicBlock> protectedRange) { + this.protectedRange = protectedRange; + } + + public List<String> getExceptionTypes() { + return this.exceptionTypes; + } + + public void addExceptionType(String exceptionType) { + + if (this.exceptionTypes == null) { + return; + } + + if (exceptionType == null) { + this.exceptionTypes = null; + } + else { + this.exceptionTypes.add(exceptionType); + } + } + + public String getUniqueExceptionsString() { + + if (exceptionTypes == null) { + return null; + } + + Set<String> setExceptionStrings = new HashSet<String>(); + + for (String exceptionType : exceptionTypes) { // normalize order + setExceptionStrings.add(exceptionType); + } + + String ret = ""; + for (String exception : setExceptionStrings) { + if (!ret.isEmpty()) { + ret += ":"; + } + ret += exception; + } + + return ret; + } + + + // public void setExceptionType(String exceptionType) { + // this.exceptionType = exceptionType; + // } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/interpreter/InstructionImpact.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/interpreter/InstructionImpact.java new file mode 100644 index 000000000000..1af23a4cdb27 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/interpreter/InstructionImpact.java @@ -0,0 +1,527 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.interpreter; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.struct.consts.LinkConstant; +import org.jetbrains.java.decompiler.struct.consts.PrimitiveConstant; +import org.jetbrains.java.decompiler.struct.gen.DataPoint; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.ListStack; + +public class InstructionImpact { + + // {read, write} + private static final int[][][] stack_impact = { + + {null, null}, // public final static int opc_nop = 0; + null, // public final static int opc_aconst_null = 1; + null, // public final static int opc_iconst_m1 = 2; + null, // public final static int opc_iconst_0 = 3; + null, // public final static int opc_iconst_1 = 4; + null, // public final static int opc_iconst_2 = 5; + null, // public final static int opc_iconst_3 = 6; + null, // public final static int opc_iconst_4 = 7; + null, // public final static int opc_iconst_5 = 8; + {null, {CodeConstants.TYPE_LONG}}, // public final static int opc_lconst_0 = 9; + {null, {CodeConstants.TYPE_LONG}}, // public final static int opc_lconst_1 = 10; + {null, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_fconst_0 = 11; + {null, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_fconst_1 = 12; + {null, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_fconst_2 = 13; + {null, {CodeConstants.TYPE_DOUBLE}}, // public final static int opc_dconst_0 = 14; + {null, {CodeConstants.TYPE_DOUBLE}}, // public final static int opc_dconst_1 = 15; + {null, {CodeConstants.TYPE_INT}}, // public final static int opc_bipush = 16; + {null, {CodeConstants.TYPE_INT}}, // public final static int opc_sipush = 17; + null, // public final static int opc_ldc = 18; + null, // public final static int opc_ldc_w = 19; + null, // public final static int opc_ldc2_w = 20; + {null, {CodeConstants.TYPE_INT}}, // public final static int opc_iload = 21; + {null, {CodeConstants.TYPE_LONG}}, // public final static int opc_lload = 22; + {null, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_fload = 23; + {null, {CodeConstants.TYPE_DOUBLE}}, // public final static int opc_dload = 24; + null, // public final static int opc_aload = 25; + null, // public final static int opc_iload_0 = 26; + null, // public final static int opc_iload_1 = 27; + null, // public final static int opc_iload_2 = 28; + null, // public final static int opc_iload_3 = 29; + null, // public final static int opc_lload_0 = 30; + null, // public final static int opc_lload_1 = 31; + null, // public final static int opc_lload_2 = 32; + null, // public final static int opc_lload_3 = 33; + null, // public final static int opc_fload_0 = 34; + null, // public final static int opc_fload_1 = 35; + null, // public final static int opc_fload_2 = 36; + null, // public final static int opc_fload_3 = 37; + null, // public final static int opc_dload_0 = 38; + null, // public final static int opc_dload_1 = 39; + null, // public final static int opc_dload_2 = 40; + null, // public final static int opc_dload_3 = 41; + null, // public final static int opc_aload_0 = 42; + null, // public final static int opc_aload_1 = 43; + null, // public final static int opc_aload_2 = 44; + null, // public final static int opc_aload_3 = 45; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_iaload = 46; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_laload = 47; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_FLOAT}}, + // public final static int opc_faload = 48; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_DOUBLE}}, + // public final static int opc_daload = 49; + null, // public final static int opc_aaload = 50; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_baload = 51; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_caload = 52; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_saload = 53; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_istore = 54; + {{CodeConstants.TYPE_LONG}, null}, // public final static int opc_lstore = 55; + {{CodeConstants.TYPE_FLOAT}, null}, // public final static int opc_fstore = 56; + {{CodeConstants.TYPE_DOUBLE}, null}, // public final static int opc_dstore = 57; + null, // public final static int opc_astore = 58; + null, // public final static int opc_istore_0 = 59; + null, // public final static int opc_istore_1 = 60; + null, // public final static int opc_istore_2 = 61; + null, // public final static int opc_istore_3 = 62; + null, // public final static int opc_lstore_0 = 63; + null, // public final static int opc_lstore_1 = 64; + null, // public final static int opc_lstore_2 = 65; + null, // public final static int opc_lstore_3 = 66; + null, // public final static int opc_fstore_0 = 67; + null, // public final static int opc_fstore_1 = 68; + null, // public final static int opc_fstore_2 = 69; + null, // public final static int opc_fstore_3 = 70; + null, // public final static int opc_dstore_0 = 71; + null, // public final static int opc_dstore_1 = 72; + null, // public final static int opc_dstore_2 = 73; + null, // public final static int opc_dstore_3 = 74; + null, // public final static int opc_astore_0 = 75; + null, // public final static int opc_astore_1 = 76; + null, // public final static int opc_astore_2 = 77; + null, // public final static int opc_astore_3 = 78; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, + // public final static int opc_iastore = 79; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_LONG}, null}, + // public final static int opc_lastore = 80; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_FLOAT}, null}, + // public final static int opc_fastore = 81; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_DOUBLE}, null}, + // public final static int opc_dastore = 82; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_OBJECT}, null}, + // public final static int opc_aastore = 83; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, + // public final static int opc_bastore = 84; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, + // public final static int opc_castore = 85; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, + // public final static int opc_sastore = 86; + {{CodeConstants.TYPE_ANY}, null}, // public final static int opc_pop = 87; + {{CodeConstants.TYPE_ANY, CodeConstants.TYPE_ANY}, null}, // public final static int opc_pop2 = 88; + null, // public final static int opc_dup = 89; + null, // public final static int opc_dup_x1 = 90; + null, // public final static int opc_dup_x2 = 91; + null, // public final static int opc_dup2 = 92; + null, // public final static int opc_dup2_x1 = 93; + null, // public final static int opc_dup2_x2 = 94; + null, // public final static int opc_swap = 95; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_iadd = 96; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_ladd = 97; + {{CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_FLOAT}}, + // public final static int opc_fadd = 98; + {{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_DOUBLE}}, + // public final static int opc_dadd = 99; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_isub = 100; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lsub = 101; + {{CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_FLOAT}}, + // public final static int opc_fsub = 102; + {{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_DOUBLE}}, + // public final static int opc_dsub = 103; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_imul = 104; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lmul = 105; + {{CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_FLOAT}}, + // public final static int opc_fmul = 106; + {{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_DOUBLE}}, + // public final static int opc_dmul = 107; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_idiv = 108; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_ldiv = 109; + {{CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_FLOAT}}, + // public final static int opc_fdiv = 110; + {{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_DOUBLE}}, + // public final static int opc_ddiv = 111; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_irem = 112; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lrem = 113; + {{CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_FLOAT}}, + // public final static int opc_frem = 114; + {{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_DOUBLE}}, + // public final static int opc_drem = 115; + {{CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, // public final static int opc_ineg = 116; + {{CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, // public final static int opc_lneg = 117; + {{CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_fneg = 118; + {{CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_DOUBLE}}, // public final static int opc_dneg = 119; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_ishl = 120; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lshl = 121; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_ishr = 122; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lshr = 123; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_iushr = 124; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lushr = 125; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_iand = 126; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_land = 127; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_ior = 128; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lor = 129; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_ixor = 130; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_LONG}}, + // public final static int opc_lxor = 131; + {null, null}, // public final static int opc_iinc = 132; + {{CodeConstants.TYPE_INT}, {CodeConstants.TYPE_LONG}}, // public final static int opc_i2l = 133; + {{CodeConstants.TYPE_INT}, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_i2f = 134; + {{CodeConstants.TYPE_INT}, {CodeConstants.TYPE_DOUBLE}}, // public final static int opc_i2d = 135; + {{CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_INT}}, // public final static int opc_l2i = 136; + {{CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_l2f = 137; + {{CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_DOUBLE}}, // public final static int opc_l2d = 138; + {{CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_INT}}, // public final static int opc_f2i = 139; + {{CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_LONG}}, // public final static int opc_f2l = 140; + {{CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_DOUBLE}}, // public final static int opc_f2d = 141; + {{CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_INT}}, // public final static int opc_d2i = 142; + {{CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_LONG}}, // public final static int opc_d2l = 143; + {{CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_FLOAT}}, // public final static int opc_d2f = 144; + {{CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, // public final static int opc_i2b = 145; + {{CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, // public final static int opc_i2c = 146; + {{CodeConstants.TYPE_INT}, {CodeConstants.TYPE_INT}}, // public final static int opc_i2s = 147; + {{CodeConstants.TYPE_LONG, CodeConstants.TYPE_LONG}, {CodeConstants.TYPE_INT}}, + // public final static int opc_lcmp = 148; + {{CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_fcmpl = 149; + {{CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_FLOAT}, {CodeConstants.TYPE_INT}}, + // public final static int opc_fcmpg = 150; + {{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_INT}}, + // public final static int opc_dcmpl = 151; + {{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_DOUBLE}, {CodeConstants.TYPE_INT}}, + // public final static int opc_dcmpg = 152; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_ifeq = 153; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_ifne = 154; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_iflt = 155; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_ifge = 156; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_ifgt = 157; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_ifle = 158; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, // public final static int opc_if_icmpeq = 159; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, // public final static int opc_if_icmpne = 160; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, // public final static int opc_if_icmplt = 161; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, // public final static int opc_if_icmpge = 162; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, // public final static int opc_if_icmpgt = 163; + {{CodeConstants.TYPE_INT, CodeConstants.TYPE_INT}, null}, // public final static int opc_if_icmple = 164; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_OBJECT}, null}, + // public final static int opc_if_acmpeq = 165; + {{CodeConstants.TYPE_OBJECT, CodeConstants.TYPE_OBJECT}, null}, + // public final static int opc_if_acmpne = 166; + {null, null}, // public final static int opc_goto = 167; + {null, {CodeConstants.TYPE_ADDRESS}}, // public final static int opc_jsr = 168; + {null, null}, // public final static int opc_ret = 169; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_tableswitch = 170; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_lookupswitch = 171; + {{CodeConstants.TYPE_INT}, null}, // public final static int opc_ireturn = 172; + {{CodeConstants.TYPE_LONG}, null}, // public final static int opc_lreturn = 173; + {{CodeConstants.TYPE_FLOAT}, null}, // public final static int opc_freturn = 174; + {{CodeConstants.TYPE_DOUBLE}, null}, // public final static int opc_dreturn = 175; + {{CodeConstants.TYPE_OBJECT}, null}, // public final static int opc_areturn = 176; + {null, null}, // public final static int opc_return = 177; + null, // public final static int opc_getstatic = 178; + null, // public final static int opc_putstatic = 179; + null, // public final static int opc_getfield = 180; + null, // public final static int opc_putfield = 181; + null, // public final static int opc_invokevirtual = 182; + null, // public final static int opc_invokespecial = 183; + null, // public final static int opc_invokestatic = 184; + null, // public final static int opc_invokeinterface = 185; + null, // public final static int opc_xxxunusedxxx = 186; + null, // public final static int opc_new = 187; + null, // public final static int opc_newarray = 188; + null, // public final static int opc_anewarray = 189; + {{CodeConstants.TYPE_OBJECT}, {CodeConstants.TYPE_INT}}, // public final static int opc_arraylength = 190; + null, + // public final static int opc_athrow = 191; + null, + // public final static int opc_checkcast = 192; + null, + // public final static int opc_instanceof = 193; + {{CodeConstants.TYPE_OBJECT}, null}, // public final static int opc_monitorenter = 194; + {{CodeConstants.TYPE_OBJECT}, null}, // public final static int opc_monitorexit = 195; + null, + // public final static int opc_wide = 196; + null, + // public final static int opc_multianewarray = 197; + {{CodeConstants.TYPE_OBJECT}, null}, // public final static int opc_ifnull = 198; + {{CodeConstants.TYPE_OBJECT}, null}, // public final static int opc_ifnonnull = 199; + {null, null}, // public final static int opc_goto_w = 200; + {null, {CodeConstants.TYPE_ADDRESS}}, // public final static int opc_jsr_w = 201; + }; + + private static final int[] arr_type = new int[]{ + CodeConstants.TYPE_BOOLEAN, + CodeConstants.TYPE_CHAR, + CodeConstants.TYPE_FLOAT, + CodeConstants.TYPE_DOUBLE, + CodeConstants.TYPE_BYTE, + CodeConstants.TYPE_SHORT, + CodeConstants.TYPE_INT, + CodeConstants.TYPE_LONG + }; + + + // Sonderbehandlung + // null, // public final static int opc_aconst_null = 1; + // null, // public final static int opc_ldc = 18; + // null, // public final static int opc_ldc_w = 19; + // null, // public final static int opc_ldc2_w = 20; + // null, // public final static int opc_aload = 25; + // null, // public final static int opc_aaload = 50; + // null, // public final static int opc_astore = 58; + // null, // public final static int opc_dup = 89; + // null, // public final static int opc_dup_x1 = 90; + // null, // public final static int opc_dup_x2 = 91; + // null, // public final static int opc_dup2 = 92; + // null, // public final static int opc_dup2_x1 = 93; + // null, // public final static int opc_dup2_x2 = 94; + // null, // public final static int opc_swap = 95; + // null, // public final static int opc_getstatic = 178; + // null, // public final static int opc_putstatic = 179; + // null, // public final static int opc_getfield = 180; + // null, // public final static int opc_putfield = 181; + // null, // public final static int opc_invokevirtual = 182; + // null, // public final static int opc_invokespecial = 183; + // null, // public final static int opc_invokestatic = 184; + // null, // public final static int opc_invokeinterface = 185; + // null, // public final static int opc_new = 187; + // null, // public final static int opc_newarray = 188; + // null, // public final static int opc_anewarray = 189; + // null, // public final static int opc_athrow = 191; + // null, // public final static int opc_checkcast = 192; + // null, // public final static int opc_instanceof = 193; + // null, // public final static int opc_multianewarray = 197; + + + public static void stepTypes(DataPoint data, Instruction instr, ConstantPool pool) { + + ListStack<VarType> stack = data.getStack(); + int[][] arr = stack_impact[instr.opcode]; + + if (arr != null) { + // simple types only + + int[] read = arr[0]; + int[] write = arr[1]; + + if (read != null) { + int depth = 0; + for (int i = 0; i < read.length; i++) { + int type = read[i]; + depth++; + if (type == CodeConstants.TYPE_LONG || + type == CodeConstants.TYPE_DOUBLE) { + depth++; + } + } + + stack.removeMultiple(depth); + } + + if (write != null) { + for (int i = 0; i < write.length; i++) { + int type = write[i]; + stack.push(new VarType(type)); + if (type == CodeConstants.TYPE_LONG || + type == CodeConstants.TYPE_DOUBLE) { + stack.push(new VarType(CodeConstants.TYPE_GROUP2EMPTY)); + } + } + } + } + else { + // Sonderbehandlung + processSpecialInstructions(data, instr, pool); + } + } + + private static void processSpecialInstructions(DataPoint data, Instruction instr, ConstantPool pool) { + + VarType var1; + PrimitiveConstant cn; + LinkConstant ck; + + ListStack<VarType> stack = data.getStack(); + + switch (instr.opcode) { + case CodeConstants.opc_aconst_null: + stack.push(new VarType(CodeConstants.TYPE_NULL, 0, null)); + break; + case CodeConstants.opc_ldc: + case CodeConstants.opc_ldc_w: + case CodeConstants.opc_ldc2_w: + cn = pool.getPrimitiveConstant(instr.getOperand(0)); + switch (cn.type) { + case CodeConstants.CONSTANT_Integer: + stack.push(new VarType(CodeConstants.TYPE_INT)); + break; + case CodeConstants.CONSTANT_Float: + stack.push(new VarType(CodeConstants.TYPE_FLOAT)); + break; + case CodeConstants.CONSTANT_Long: + stack.push(new VarType(CodeConstants.TYPE_LONG)); + stack.push(new VarType(CodeConstants.TYPE_GROUP2EMPTY)); + break; + case CodeConstants.CONSTANT_Double: + stack.push(new VarType(CodeConstants.TYPE_DOUBLE)); + stack.push(new VarType(CodeConstants.TYPE_GROUP2EMPTY)); + break; + case CodeConstants.CONSTANT_String: + stack.push(new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/String")); + break; + case CodeConstants.CONSTANT_Class: + stack.push(new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/Class")); + break; + } + break; + case CodeConstants.opc_aload: + var1 = data.getVariable(instr.getOperand(0)); + if (var1 != null) { + stack.push(var1); + } + else { + stack.push(new VarType(CodeConstants.TYPE_OBJECT, 0, null)); + } + break; + case CodeConstants.opc_aaload: + var1 = stack.pop(2); + stack.push(new VarType(var1.type, var1.arraydim - 1, var1.value)); + break; + case CodeConstants.opc_astore: + data.setVariable(instr.getOperand(0), stack.pop()); + break; + case CodeConstants.opc_dup: + case CodeConstants.opc_dup_x1: + case CodeConstants.opc_dup_x2: + int depth1 = 88 - instr.opcode; + stack.insertByOffset(depth1, stack.getByOffset(-1).copy()); + break; + case CodeConstants.opc_dup2: + case CodeConstants.opc_dup2_x1: + case CodeConstants.opc_dup2_x2: + int depth2 = 90 - instr.opcode; + stack.insertByOffset(depth2, stack.getByOffset(-2).copy()); + stack.insertByOffset(depth2, stack.getByOffset(-1).copy()); + break; + case CodeConstants.opc_swap: + var1 = stack.pop(); + stack.insertByOffset(-1, var1); + break; + case CodeConstants.opc_getfield: + stack.pop(); + case CodeConstants.opc_getstatic: + ck = pool.getLinkConstant(instr.getOperand(0)); + var1 = new VarType(ck.descriptor); + stack.push(var1); + if (var1.stack_size == 2) { + stack.push(new VarType(CodeConstants.TYPE_GROUP2EMPTY)); + } + break; + case CodeConstants.opc_putfield: + stack.pop(); + case CodeConstants.opc_putstatic: + ck = pool.getLinkConstant(instr.getOperand(0)); + var1 = new VarType(ck.descriptor); + stack.pop(var1.stack_size); + break; + case CodeConstants.opc_invokevirtual: + case CodeConstants.opc_invokespecial: + case CodeConstants.opc_invokeinterface: + stack.pop(); + case CodeConstants.opc_invokestatic: + case CodeConstants.opc_invokedynamic: + if (instr.opcode != CodeConstants.opc_invokedynamic || instr.bytecode_version >= CodeConstants.BYTECODE_JAVA_7) { + ck = pool.getLinkConstant(instr.getOperand(0)); + MethodDescriptor md = MethodDescriptor.parseDescriptor(ck.descriptor); + for (int i = 0; i < md.params.length; i++) { + stack.pop(md.params[i].stack_size); + } + if (md.ret.type != CodeConstants.TYPE_VOID) { + stack.push(md.ret); + if (md.ret.stack_size == 2) { + stack.push(new VarType(CodeConstants.TYPE_GROUP2EMPTY)); + } + } + } + break; + case CodeConstants.opc_new: + cn = pool.getPrimitiveConstant(instr.getOperand(0)); + stack.push(new VarType(CodeConstants.TYPE_OBJECT, 0, cn.getString())); + break; + case CodeConstants.opc_newarray: + stack.pop(); + var1 = new VarType(arr_type[instr.getOperand(0) - 4]); + var1.arraydim = 1; + stack.push(var1); + break; + case CodeConstants.opc_athrow: + var1 = stack.pop(); + stack.clear(); + stack.push(var1); + break; + case CodeConstants.opc_checkcast: + case CodeConstants.opc_instanceof: + stack.pop(); + cn = pool.getPrimitiveConstant(instr.getOperand(0)); + stack.push(new VarType(CodeConstants.TYPE_OBJECT, 0, cn.getString())); + break; + case CodeConstants.opc_anewarray: + case CodeConstants.opc_multianewarray: + int dimensions = (instr.opcode == CodeConstants.opc_anewarray) ? 1 : instr.getOperand(1); + stack.pop(dimensions); + cn = pool.getPrimitiveConstant(instr.getOperand(0)); + if (cn.isArray) { + var1 = new VarType(CodeConstants.TYPE_OBJECT, 0, cn.getString()); + var1.arraydim += dimensions; + stack.push(var1); + } + else { + stack.push(new VarType(CodeConstants.TYPE_OBJECT, dimensions, cn.getString())); + } + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/interpreter/Util.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/interpreter/Util.java new file mode 100644 index 000000000000..bf1e5eb8d9d4 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/interpreter/Util.java @@ -0,0 +1,286 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.interpreter; + +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructContext; + + +// FIXME: move to StructContext +public class Util { + + private static final String[][] runtime_exceptions = { + + null, // public final static int opc_nop = 0; + null, // public final static int opc_aconst_null = 1; + null, // public final static int opc_iconst_m1 = 2; + null, // public final static int opc_iconst_0 = 3; + null, // public final static int opc_iconst_1 = 4; + null, // public final static int opc_iconst_2 = 5; + null, // public final static int opc_iconst_3 = 6; + null, // public final static int opc_iconst_4 = 7; + null, // public final static int opc_iconst_5 = 8; + null, // public final static int opc_lconst_0 = 9; + null, // public final static int opc_lconst_1 = 10; + null, // public final static int opc_fconst_0 = 11; + null, // public final static int opc_fconst_1 = 12; + null, // public final static int opc_fconst_2 = 13; + null, // public final static int opc_dconst_0 = 14; + null, // public final static int opc_dconst_1 = 15; + null, // public final static int opc_bipush = 16; + null, // public final static int opc_sipush = 17; + null, // public final static int opc_ldc = 18; + null, // public final static int opc_ldc_w = 19; + null, // public final static int opc_ldc2_w = 20; + null, // public final static int opc_iload = 21; + null, // public final static int opc_lload = 22; + null, // public final static int opc_fload = 23; + null, // public final static int opc_dload = 24; + null, // public final static int opc_aload = 25; + null, // public final static int opc_iload_0 = 26; + null, // public final static int opc_iload_1 = 27; + null, // public final static int opc_iload_2 = 28; + null, // public final static int opc_iload_3 = 29; + null, // public final static int opc_lload_0 = 30; + null, // public final static int opc_lload_1 = 31; + null, // public final static int opc_lload_2 = 32; + null, // public final static int opc_lload_3 = 33; + null, // public final static int opc_fload_0 = 34; + null, // public final static int opc_fload_1 = 35; + null, // public final static int opc_fload_2 = 36; + null, // public final static int opc_fload_3 = 37; + null, // public final static int opc_dload_0 = 38; + null, // public final static int opc_dload_1 = 39; + null, // public final static int opc_dload_2 = 40; + null, // public final static int opc_dload_3 = 41; + null, // public final static int opc_aload_0 = 42; + null, // public final static int opc_aload_1 = 43; + null, // public final static int opc_aload_2 = 44; + null, // public final static int opc_aload_3 = 45; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_iaload = 46; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_laload = 47; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_faload = 48; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_daload = 49; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_aaload = 50; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_baload = 51; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_caload = 52; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_saload = 53; + null, // public final static int opc_istore = 54; + null, // public final static int opc_lstore = 55; + null, // public final static int opc_fstore = 56; + null, // public final static int opc_dstore = 57; + null, // public final static int opc_astore = 58; + null, // public final static int opc_istore_0 = 59; + null, // public final static int opc_istore_1 = 60; + null, // public final static int opc_istore_2 = 61; + null, // public final static int opc_istore_3 = 62; + null, // public final static int opc_lstore_0 = 63; + null, // public final static int opc_lstore_1 = 64; + null, // public final static int opc_lstore_2 = 65; + null, // public final static int opc_lstore_3 = 66; + null, // public final static int opc_fstore_0 = 67; + null, // public final static int opc_fstore_1 = 68; + null, // public final static int opc_fstore_2 = 69; + null, // public final static int opc_fstore_3 = 70; + null, // public final static int opc_dstore_0 = 71; + null, // public final static int opc_dstore_1 = 72; + null, // public final static int opc_dstore_2 = 73; + null, // public final static int opc_dstore_3 = 74; + null, // public final static int opc_astore_0 = 75; + null, // public final static int opc_astore_1 = 76; + null, // public final static int opc_astore_2 = 77; + null, // public final static int opc_astore_3 = 78; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_iastore = 79; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_lastore = 80; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_fastore = 81; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_dastore = 82; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException", "java/lang/ArrayStoreException"}, + // public final static int opc_aastore = 83; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_bastore = 84; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_castore = 85; + {"java/lang/NullPointerException", "java/lang/ArrayIndexOutOfBoundsException"}, + // public final static int opc_sastore = 86; + null, // public final static int opc_pop = 87; + null, // public final static int opc_pop2 = 88; + null, // public final static int opc_dup = 89; + null, // public final static int opc_dup_x1 = 90; + null, // public final static int opc_dup_x2 = 91; + null, // public final static int opc_dup2 = 92; + null, // public final static int opc_dup2_x1 = 93; + null, // public final static int opc_dup2_x2 = 94; + null, // public final static int opc_swap = 95; + null, // public final static int opc_iadd = 96; + null, // public final static int opc_ladd = 97; + null, // public final static int opc_fadd = 98; + null, // public final static int opc_dadd = 99; + null, // public final static int opc_isub = 100; + null, // public final static int opc_lsub = 101; + null, // public final static int opc_fsub = 102; + null, // public final static int opc_dsub = 103; + null, // public final static int opc_imul = 104; + null, // public final static int opc_lmul = 105; + null, // public final static int opc_fmul = 106; + null, // public final static int opc_dmul = 107; + {"java/lang/ArithmeticException"}, // public final static int opc_idiv = 108; + {"java/lang/ArithmeticException"}, // public final static int opc_ldiv = 109; + null, // public final static int opc_fdiv = 110; + null, // public final static int opc_ddiv = 111; + {"java/lang/ArithmeticException"}, // public final static int opc_irem = 112; + {"java/lang/ArithmeticException"}, // public final static int opc_lrem = 113; + null, // public final static int opc_frem = 114; + null, // public final static int opc_drem = 115; + null, // public final static int opc_ineg = 116; + null, // public final static int opc_lneg = 117; + null, // public final static int opc_fneg = 118; + null, // public final static int opc_dneg = 119; + null, // public final static int opc_ishl = 120; + null, // public final static int opc_lshl = 121; + null, // public final static int opc_ishr = 122; + null, // public final static int opc_lshr = 123; + null, // public final static int opc_iushr = 124; + null, // public final static int opc_lushr = 125; + null, // public final static int opc_iand = 126; + null, // public final static int opc_land = 127; + null, // public final static int opc_ior = 128; + null, // public final static int opc_lor = 129; + null, // public final static int opc_ixor = 130; + null, // public final static int opc_lxor = 131; + null, // public final static int opc_iinc = 132; + null, // public final static int opc_i2l = 133; + null, // public final static int opc_i2f = 134; + null, // public final static int opc_i2d = 135; + null, // public final static int opc_l2i = 136; + null, // public final static int opc_l2f = 137; + null, // public final static int opc_l2d = 138; + null, // public final static int opc_f2i = 139; + null, // public final static int opc_f2l = 140; + null, // public final static int opc_f2d = 141; + null, // public final static int opc_d2i = 142; + null, // public final static int opc_d2l = 143; + null, // public final static int opc_d2f = 144; + null, // public final static int opc_i2b = 145; + null, // public final static int opc_i2c = 146; + null, // public final static int opc_i2s = 147; + null, // public final static int opc_lcmp = 148; + null, // public final static int opc_fcmpl = 149; + null, // public final static int opc_fcmpg = 150; + null, // public final static int opc_dcmpl = 151; + null, // public final static int opc_dcmpg = 152; + null, // public final static int opc_ifeq = 153; + null, // public final static int opc_ifne = 154; + null, // public final static int opc_iflt = 155; + null, // public final static int opc_ifge = 156; + null, // public final static int opc_ifgt = 157; + null, // public final static int opc_ifle = 158; + null, // public final static int opc_if_icmpeq = 159; + null, // public final static int opc_if_icmpne = 160; + null, // public final static int opc_if_icmplt = 161; + null, // public final static int opc_if_icmpge = 162; + null, // public final static int opc_if_icmpgt = 163; + null, // public final static int opc_if_icmple = 164; + null, // public final static int opc_if_acmpeq = 165; + null, // public final static int opc_if_acmpne = 166; + null, // public final static int opc_goto = 167; + null, // public final static int opc_jsr = 168; + null, // public final static int opc_ret = 169; + null, // public final static int opc_tableswitch = 170; + null, // public final static int opc_lookupswitch = 171; + {"java/lang/IllegalMonitorStateException"}, // public final static int opc_ireturn = 172; + {"java/lang/IllegalMonitorStateException"}, // public final static int opc_lreturn = 173; + {"java/lang/IllegalMonitorStateException"}, // public final static int opc_freturn = 174; + {"java/lang/IllegalMonitorStateException"}, // public final static int opc_dreturn = 175; + {"java/lang/IllegalMonitorStateException"}, // public final static int opc_areturn = 176; + {"java/lang/IllegalMonitorStateException"}, // public final static int opc_return = 177; + null, // public final static int opc_getstatic = 178; + null, // public final static int opc_putstatic = 179; + {"java/lang/NullPointerException"}, // public final static int opc_getfield = 180; + {"java/lang/NullPointerException"}, // public final static int opc_putfield = 181; + {"java/lang/NullPointerException", "java/lang/AbstractMethodError", "java/lang/UnsatisfiedLinkError"}, + // public final static int opc_invokevirtual = 182; + {"java/lang/NullPointerException", "java/lang/UnsatisfiedLinkError"}, + // public final static int opc_invokespecial = 183; + {"java/lang/UnsatisfiedLinkError"}, // public final static int opc_invokestatic = 184; + {"java/lang/NullPointerException", "java/lang/IncompatibleClassChangeError", "java/lang/IllegalAccessError", + "java/lang/java/lang/AbstractMethodError", "java/lang/UnsatisfiedLinkError"}, + // public final static int opc_invokeinterface = 185; + null, // public final static int opc_xxxunusedxxx = 186; + null, // public final static int opc_new = 187; + {"java/lang/NegativeArraySizeException"}, // public final static int opc_newarray = 188; + {"java/lang/NegativeArraySizeException"}, // public final static int opc_anewarray = 189; + {"java/lang/NullPointerException"}, // public final static int opc_arraylength = 190; + {"java/lang/NullPointerException", "java/lang/IllegalMonitorStateException"}, + // public final static int opc_athrow = 191; + {"java/lang/ClassCastException"}, // public final static int opc_checkcast = 192; + null, // public final static int opc_instanceof = 193; + {"java/lang/NullPointerException"}, // public final static int opc_monitorenter = 194; + {"java/lang/NullPointerException", "java/lang/IllegalMonitorStateException"}, + // public final static int opc_monitorexit = 195; + null, // public final static int opc_wide = 196; + {"java/lang/NegativeArraySizeException"}, // public final static int opc_multianewarray = 197; + null, // public final static int opc_ifnull = 198; + null, // public final static int opc_ifnonnull = 199; + null, // public final static int opc_goto_w = 200; + null, // public final static int opc_jsr_w = 201; + }; + + + public static boolean instanceOf(StructContext context, String valclass, String refclass) { + + if (valclass.equals(refclass)) { + return true; + } + + StructClass cl = context.getClass(valclass); + if (cl == null) { + return false; + } + + if (cl.superClass != null && instanceOf(context, cl.superClass.getString(), refclass)) { + return true; + } + + int[] interfaces = cl.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + String intfc = cl.getPool().getPrimitiveConstant(interfaces[i]).getString(); + + if (instanceOf(context, intfc, refclass)) { + return true; + } + } + + return false; + } + + + public static String[] getRuntimeExceptions(Instruction instr) { + return runtime_exceptions[instr.opcode]; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ALOAD.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ALOAD.java new file mode 100644 index 000000000000..788795e6fe7d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ALOAD.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class ALOAD extends Instruction { + + private static int[] opcodes = new int[]{opc_aload_0, opc_aload_1, opc_aload_2, opc_aload_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_aload); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + if (wide) { + return 4; + } + else { + return 2; + } + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ANEWARRAY.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ANEWARRAY.java new file mode 100644 index 000000000000..d514ffe9f772 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ANEWARRAY.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class ANEWARRAY extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_anewarray); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ASTORE.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ASTORE.java new file mode 100644 index 000000000000..40336f483edf --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ASTORE.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class ASTORE extends Instruction { + + private static int[] opcodes = new int[]{opc_astore_0, opc_astore_1, opc_astore_2, opc_astore_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_astore); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + if (wide) { + return 4; + } + else { + return 2; + } + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/BIPUSH.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/BIPUSH.java new file mode 100644 index 000000000000..4686051cfe18 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/BIPUSH.java @@ -0,0 +1,48 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class BIPUSH extends Instruction { + + private static int[] opcodes = + new int[]{opc_iconst_m1, opc_iconst_0, opc_iconst_1, opc_iconst_2, opc_iconst_3, opc_iconst_4, opc_iconst_5}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int value = getOperand(0); + if (value < -1 || value > 5) { + out.writeByte(opc_bipush); + out.writeByte(value); + } + else { + out.writeByte(opcodes[value + 1]); + } + } + + public int length() { + int value = getOperand(0); + if (value < -1 || value > 5) { + return 2; + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/CHECKCAST.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/CHECKCAST.java new file mode 100644 index 000000000000..9a42f656ed00 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/CHECKCAST.java @@ -0,0 +1,34 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class CHECKCAST extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_checkcast); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} + diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/DLOAD.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/DLOAD.java new file mode 100644 index 000000000000..7630185b45bc --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/DLOAD.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class DLOAD extends Instruction { + + private static int[] opcodes = new int[]{opc_dload_0, opc_dload_1, opc_dload_2, opc_dload_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_dload); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + if (wide) { + return 4; + } + else { + return 2; + } + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/DSTORE.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/DSTORE.java new file mode 100644 index 000000000000..2bdb74911305 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/DSTORE.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class DSTORE extends Instruction { + + private static int[] opcodes = new int[]{opc_dstore_0, opc_dstore_1, opc_dstore_2, opc_dstore_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_dstore); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + if (wide) { + return 4; + } + else { + return 2; + } + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/FLOAD.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/FLOAD.java new file mode 100644 index 000000000000..8a89dfff66fc --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/FLOAD.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class FLOAD extends Instruction { + + private static int[] opcodes = new int[]{opc_fload_0, opc_fload_1, opc_fload_2, opc_fload_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_fload); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + if (wide) { + return 4; + } + else { + return 2; + } + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/FSTORE.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/FSTORE.java new file mode 100644 index 000000000000..9061913c0032 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/FSTORE.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class FSTORE extends Instruction { + + private static int[] opcodes = new int[]{opc_fstore_0, opc_fstore_1, opc_fstore_2, opc_fstore_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_fstore); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + if (wide) { + return 4; + } + else { + return 2; + } + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GETFIELD.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GETFIELD.java new file mode 100644 index 000000000000..6b95aaf91668 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GETFIELD.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class GETFIELD extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_getfield); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GETSTATIC.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GETSTATIC.java new file mode 100644 index 000000000000..c1401a6128c8 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GETSTATIC.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class GETSTATIC extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_getstatic); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GOTO.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GOTO.java new file mode 100644 index 000000000000..97374c081cb9 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GOTO.java @@ -0,0 +1,46 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.JumpInstruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class GOTO extends JumpInstruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int operand = getOperand(0); + if (operand < -32768 || operand > 32767) { + out.writeByte(opc_goto_w); + out.writeInt(operand); + } + else { + out.writeByte(opc_goto); + out.writeShort(operand); + } + } + + public int length() { + int operand = getOperand(0); + if (operand < -32768 || operand > 32767) { + return 5; + } + else { + return 3; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GOTO_W.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GOTO_W.java new file mode 100644 index 000000000000..56ba9e8d59fb --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/GOTO_W.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.JumpInstruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class GOTO_W extends JumpInstruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_goto_w); + out.writeInt(getOperand(0)); + } + + public int length() { + return 5; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/IINC.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/IINC.java new file mode 100644 index 000000000000..05b446c861c9 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/IINC.java @@ -0,0 +1,43 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class IINC extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_iinc); + if (wide) { + out.writeShort(getOperand(0)); + out.writeShort(getOperand(1)); + } + else { + out.writeByte(getOperand(0)); + out.writeByte(getOperand(1)); + } + } + + public int length() { + return wide ? 6 : 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ILOAD.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ILOAD.java new file mode 100644 index 000000000000..24b95ffbea8d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ILOAD.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class ILOAD extends Instruction { + + private static int[] opcodes = new int[]{opc_iload_0, opc_iload_1, opc_iload_2, opc_iload_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_iload); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + return wide ? 4 : 2; + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INSTANCEOF.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INSTANCEOF.java new file mode 100644 index 000000000000..f93d5b892105 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INSTANCEOF.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class INSTANCEOF extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_instanceof); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEDYNAMIC.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEDYNAMIC.java new file mode 100644 index 000000000000..917c5bde038d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEDYNAMIC.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class INVOKEDYNAMIC extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_invokedynamic); + out.writeShort(getOperand(0)); + out.writeByte(0); + out.writeByte(0); + } + + public int length() { + return 5; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEINTERFACE.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEINTERFACE.java new file mode 100644 index 000000000000..51259ff03eb5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEINTERFACE.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class INVOKEINTERFACE extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_invokeinterface); + out.writeShort(getOperand(0)); + out.writeByte(getOperand(1)); + out.writeByte(0); + } + + public int length() { + return 5; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKESPECIAL.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKESPECIAL.java new file mode 100644 index 000000000000..2436803541fd --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKESPECIAL.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class INVOKESPECIAL extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_invokespecial); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKESTATIC.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKESTATIC.java new file mode 100644 index 000000000000..f036a1d90d79 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKESTATIC.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class INVOKESTATIC extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_invokestatic); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEVIRTUAL.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEVIRTUAL.java new file mode 100644 index 000000000000..ca3bcd3809ec --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/INVOKEVIRTUAL.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class INVOKEVIRTUAL extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_invokevirtual); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ISTORE.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ISTORE.java new file mode 100644 index 000000000000..5907538389b5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/ISTORE.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class ISTORE extends Instruction { + + private static int[] opcodes = new int[]{opc_istore_0, opc_istore_1, opc_istore_2, opc_istore_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_istore); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + return wide ? 4 : 2; + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/JSR.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/JSR.java new file mode 100644 index 000000000000..bb000a7ad08a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/JSR.java @@ -0,0 +1,46 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.JumpInstruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class JSR extends JumpInstruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int operand = getOperand(0); + if (operand < -32768 || operand > 32767) { + out.writeByte(opc_jsr_w); + out.writeInt(operand); + } + else { + out.writeByte(opc_jsr); + out.writeShort(operand); + } + } + + public int length() { + int operand = getOperand(0); + if (operand < -32768 || operand > 32767) { + return 5; + } + else { + return 3; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/JSR_W.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/JSR_W.java new file mode 100644 index 000000000000..fb04ed97e913 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/JSR_W.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.JumpInstruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class JSR_W extends JumpInstruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_jsr_w); + out.writeInt(getOperand(0)); + } + + public int length() { + return 5; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC.java new file mode 100644 index 000000000000..ae7b3c6b8802 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class LDC extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_ldc); + out.writeByte(getOperand(0)); + } + + public int length() { + return 2; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC2_W.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC2_W.java new file mode 100644 index 000000000000..6ba19649bdaf --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC2_W.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class LDC2_W extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_ldc2_w); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC_W.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC_W.java new file mode 100644 index 000000000000..71e5fe021bbd --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LDC_W.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class LDC_W extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_ldc_w); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LLOAD.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LLOAD.java new file mode 100644 index 000000000000..6e506593197f --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LLOAD.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class LLOAD extends Instruction { + + private static int[] opcodes = new int[]{opc_lload_0, opc_lload_1, opc_lload_2, opc_lload_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_lload); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + return wide ? 4 : 2; + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LOOKUPSWITCH.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LOOKUPSWITCH.java new file mode 100644 index 000000000000..418316886d29 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LOOKUPSWITCH.java @@ -0,0 +1,42 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.SwitchInstruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class LOOKUPSWITCH extends SwitchInstruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + + out.writeByte(opc_lookupswitch); + + int padding = 3 - (offset % 4); + for (int i = 0; i < padding; i++) { + out.writeByte(0); + } + + for (int i = 0; i < operandsCount(); i++) { + out.writeInt(getOperand(i)); + } + } + + public int length() { + return 1 + operandsCount() * 4; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LSTORE.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LSTORE.java new file mode 100644 index 000000000000..9095f04ea883 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/LSTORE.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class LSTORE extends Instruction { + + private static int[] opcodes = new int[]{opc_lstore_0, opc_lstore_1, opc_lstore_2, opc_lstore_3}; + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + int index = getOperand(0); + if (index > 3) { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_lstore); + if (wide) { + out.writeShort(index); + } + else { + out.writeByte(index); + } + } + else { + out.writeByte(opcodes[index]); + } + } + + public int length() { + int index = getOperand(0); + if (index > 3) { + return wide ? 4 : 2; + } + else { + return 1; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/MULTIANEWARRAY.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/MULTIANEWARRAY.java new file mode 100644 index 000000000000..b6835e80c761 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/MULTIANEWARRAY.java @@ -0,0 +1,34 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class MULTIANEWARRAY extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_multianewarray); + out.writeShort(getOperand(0)); + out.writeByte(getOperand(1)); + } + + public int length() { + return 4; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/NEW.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/NEW.java new file mode 100644 index 000000000000..2e8854f30877 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/NEW.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class NEW extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_new); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/NEWARRAY.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/NEWARRAY.java new file mode 100644 index 000000000000..f2f8e4d5a433 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/NEWARRAY.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class NEWARRAY extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_newarray); + out.writeByte(getOperand(0)); + } + + public int length() { + return 2; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/PUTFIELD.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/PUTFIELD.java new file mode 100644 index 000000000000..c1e3e9241985 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/PUTFIELD.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class PUTFIELD extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_putfield); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/PUTSTATIC.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/PUTSTATIC.java new file mode 100644 index 000000000000..0fe0240242ed --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/PUTSTATIC.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class PUTSTATIC extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_putstatic); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/RET.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/RET.java new file mode 100644 index 000000000000..93f62ff1bced --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/RET.java @@ -0,0 +1,41 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class RET extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + if (wide) { + out.writeByte(opc_wide); + } + out.writeByte(opc_ret); + if (wide) { + out.writeShort(getOperand(0)); + } + else { + out.writeByte(getOperand(0)); + } + } + + public int length() { + return wide ? 4 : 2; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/SIPUSH.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/SIPUSH.java new file mode 100644 index 000000000000..08b10a51725e --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/SIPUSH.java @@ -0,0 +1,33 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.Instruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class SIPUSH extends Instruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + out.writeByte(opc_sipush); + out.writeShort(getOperand(0)); + } + + public int length() { + return 3; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/TABLESWITCH.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/TABLESWITCH.java new file mode 100644 index 000000000000..0b41ecf232fe --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/code/optinstructions/TABLESWITCH.java @@ -0,0 +1,42 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.code.optinstructions; + +import org.jetbrains.java.decompiler.code.SwitchInstruction; + +import java.io.DataOutputStream; +import java.io.IOException; + +public class TABLESWITCH extends SwitchInstruction { + + public void writeToStream(DataOutputStream out, int offset) throws IOException { + + out.writeByte(opc_tableswitch); + + int padding = 3 - (offset % 4); + for (int i = 0; i < padding; i++) { + out.writeByte(0); + } + + for (int i = 0; i < operandsCount(); i++) { + out.writeInt(getOperand(i)); + } + } + + public int length() { + return 1 + operandsCount() * 4; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/AssertProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/AssertProcessor.java new file mode 100644 index 000000000000..a58b68903563 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/AssertProcessor.java @@ -0,0 +1,310 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.main.rels.ClassWrapper; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.SecondaryFunctionsHelper; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class AssertProcessor { + + private static final VarType CLASS_ASSERTION_ERROR = new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/AssertionError"); + + public static void buildAssertions(ClassNode node) { + + ClassWrapper wrapper = node.wrapper; + + StructField field = findAssertionField(node); + + if (field != null) { + + String key = InterpreterUtil.makeUniqueKey(field.getName(), field.getDescriptor()); + + boolean res = false; + + for (MethodWrapper meth : wrapper.getMethods()) { + RootStatement root = meth.root; + if (root != null) { + res |= replaceAssertions(root, wrapper.getClassStruct().qualifiedName, key); + } + } + + if (res) { + // hide the helper field + wrapper.getHiddenMembers().add(key); + } + } + } + + private static StructField findAssertionField(ClassNode node) { + + ClassWrapper wrapper = node.wrapper; + + boolean noSynthFlag = DecompilerContext.getOption(IFernflowerPreferences.SYNTHETIC_NOT_SET); + + for (StructField fd : wrapper.getClassStruct().getFields()) { + + String keyField = InterpreterUtil.makeUniqueKey(fd.getName(), fd.getDescriptor()); + + // initializer exists + if (wrapper.getStaticFieldInitializers().containsKey(keyField)) { + + // access flags set + if (fd.hasModifier(CodeConstants.ACC_STATIC) && fd.hasModifier(CodeConstants.ACC_FINAL) && (noSynthFlag || fd.isSynthetic())) { + + // field type boolean + FieldDescriptor fdescr = FieldDescriptor.parseDescriptor(fd.getDescriptor()); + if (VarType.VARTYPE_BOOLEAN.equals(fdescr.type)) { + + Exprent initializer = wrapper.getStaticFieldInitializers().getWithKey(keyField); + if (initializer.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent fexpr = (FunctionExprent)initializer; + + if (fexpr.getFunctype() == FunctionExprent.FUNCTION_BOOLNOT && + fexpr.getLstOperands().get(0).type == Exprent.EXPRENT_INVOCATION) { + + InvocationExprent invexpr = (InvocationExprent)fexpr.getLstOperands().get(0); + + if (invexpr.getInstance() != null && + invexpr.getInstance().type == Exprent.EXPRENT_CONST && + "desiredAssertionStatus".equals(invexpr.getName()) && + "java/lang/Class".equals(invexpr.getClassname()) && + invexpr.getLstParameters().isEmpty()) { + + ConstExprent cexpr = (ConstExprent)invexpr.getInstance(); + if (VarType.VARTYPE_CLASS.equals(cexpr.getConsttype())) { + + ClassNode nd = node; + while (nd != null) { + if (nd.wrapper.getClassStruct().qualifiedName.equals(cexpr.getValue())) { + break; + } + nd = nd.parent; + } + + if (nd != null) { // found enclosing class with the same name + return fd; + } + } + } + } + } + } + } + } + } + + + return null; + } + + + private static boolean replaceAssertions(Statement statement, String classname, String key) { + + boolean res = false; + + for (Statement st : statement.getStats()) { + res |= replaceAssertions(st, classname, key); + } + + boolean replaced = true; + while (replaced) { + replaced = false; + + for (Statement st : statement.getStats()) { + if (st.type == Statement.TYPE_IF) { + if (replaceAssertion(statement, (IfStatement)st, classname, key)) { + replaced = true; + break; + } + } + } + + res |= replaced; + } + + return res; + } + + private static boolean replaceAssertion(Statement parent, IfStatement stat, String classname, String key) { + + Statement ifstat = stat.getIfstat(); + InvocationExprent throwError = isAssertionError(ifstat); + + if (throwError == null) { + return false; + } + + Object[] exprres = getAssertionExprent(stat.getHeadexprent().getCondition().copy(), classname, key); + if (!(Boolean)exprres[1]) { + return false; + } + + List<Exprent> lstParams = new ArrayList<Exprent>(); + + Exprent ascond = null, retcond = null; + if (exprres[0] != null) { + ascond = new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, + Arrays.asList(new Exprent[]{(Exprent)exprres[0]})); + retcond = SecondaryFunctionsHelper.propagateBoolNot(ascond); + } + + lstParams.add(retcond == null ? ascond : retcond); + if (!throwError.getLstParameters().isEmpty()) { + lstParams.add(throwError.getLstParameters().get(0)); + } + + AssertExprent asexpr = new AssertExprent(lstParams); + + Statement newstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + newstat.setExprents(Arrays.asList(new Exprent[]{asexpr})); + + Statement first = stat.getFirst(); + + if (stat.iftype == IfStatement.IFTYPE_IFELSE || (first.getExprents() != null && + !first.getExprents().isEmpty())) { + + first.removeSuccessor(stat.getIfEdge()); + first.removeSuccessor(stat.getElseEdge()); + + List<Statement> lstStatements = new ArrayList<Statement>(); + if (first.getExprents() != null && !first.getExprents().isEmpty()) { + lstStatements.add(first); + } + lstStatements.add(newstat); + if (stat.iftype == IfStatement.IFTYPE_IFELSE) { + lstStatements.add(stat.getElsestat()); + } + + SequenceStatement sequence = new SequenceStatement(lstStatements); + sequence.setAllParent(); + + for (int i = 0; i < sequence.getStats().size() - 1; i++) { + sequence.getStats().get(i).addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, + sequence.getStats().get(i), sequence.getStats().get(i + 1))); + } + + if (stat.iftype == IfStatement.IFTYPE_IFELSE) { + Statement ifelse = stat.getElsestat(); + + List<StatEdge> lstSuccs = ifelse.getAllSuccessorEdges(); + if (!lstSuccs.isEmpty()) { + StatEdge endedge = lstSuccs.get(0); + if (endedge.closure == stat) { + sequence.addLabeledEdge(endedge); + } + } + } + + newstat = sequence; + } + + newstat.getVarDefinitions().addAll(stat.getVarDefinitions()); + parent.replaceStatement(stat, newstat); + + return true; + } + + private static InvocationExprent isAssertionError(Statement stat) { + + if (stat == null || stat.getExprents() == null || stat.getExprents().size() != 1) { + return null; + } + + Exprent expr = stat.getExprents().get(0); + + if (expr.type == Exprent.EXPRENT_EXIT) { + ExitExprent exexpr = (ExitExprent)expr; + if (exexpr.getExittype() == ExitExprent.EXIT_THROW && exexpr.getValue().type == Exprent.EXPRENT_NEW) { + NewExprent nexpr = (NewExprent)exexpr.getValue(); + if (CLASS_ASSERTION_ERROR.equals(nexpr.getNewtype()) && nexpr.getConstructor() != null) { + return nexpr.getConstructor(); + } + } + } + + return null; + } + + private static Object[] getAssertionExprent(Exprent exprent, String classname, String key) { + + if (exprent.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent fexpr = (FunctionExprent)exprent; + if (fexpr.getFunctype() == FunctionExprent.FUNCTION_CADD) { + + for (int i = 0; i < 2; i++) { + Exprent param = fexpr.getLstOperands().get(i); + + if (isAssertionField(param, classname, key)) { + return new Object[]{fexpr.getLstOperands().get(1 - i), true}; + } + } + + for (int i = 0; i < 2; i++) { + Exprent param = fexpr.getLstOperands().get(i); + + Object[] res = getAssertionExprent(param, classname, key); + if ((Boolean)res[1]) { + if (param != res[0]) { + fexpr.getLstOperands().set(i, (Exprent)res[0]); + } + return new Object[]{fexpr, true}; + } + } + } + else if (isAssertionField(fexpr, classname, key)) { + // assert false; + return new Object[]{null, true}; + } + } + + return new Object[]{exprent, false}; + } + + private static boolean isAssertionField(Exprent exprent, String classname, String key) { + + if (exprent.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent fparam = (FunctionExprent)exprent; + if (fparam.getFunctype() == FunctionExprent.FUNCTION_BOOLNOT && + fparam.getLstOperands().get(0).type == Exprent.EXPRENT_FIELD) { + FieldExprent fdparam = (FieldExprent)fparam.getLstOperands().get(0); + if (classname.equals(fdparam.getClassname()) + && key.equals(InterpreterUtil.makeUniqueKey(fdparam.getName(), fdparam.getDescriptor().descriptorString))) { + return true; + } + } + } + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassReference14Processor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassReference14Processor.java new file mode 100644 index 000000000000..3807d2e80a27 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassReference14Processor.java @@ -0,0 +1,296 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.main.rels.ClassWrapper; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.stats.BasicBlockStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.*; +import java.util.Map.Entry; + +public class ClassReference14Processor { + + public ExitExprent bodyexprent; + + public ExitExprent handlerexprent; + + + public ClassReference14Processor() { + + InvocationExprent invfor = new InvocationExprent(); + invfor.setName("forName"); + invfor.setClassname("java/lang/Class"); + invfor.setStringDescriptor("(Ljava/lang/String;)Ljava/lang/Class;"); + invfor.setDescriptor(MethodDescriptor.parseDescriptor("(Ljava/lang/String;)Ljava/lang/Class;")); + invfor.setStatic(true); + invfor.setLstParameters(Arrays.asList(new Exprent[]{new VarExprent(0, VarType.VARTYPE_STRING, null)})); + + bodyexprent = new ExitExprent(ExitExprent.EXIT_RETURN, + invfor, + VarType.VARTYPE_CLASS); + + InvocationExprent constr = new InvocationExprent(); + constr.setName("<init>"); + constr.setClassname("java/lang/NoClassDefFoundError"); + constr.setStringDescriptor("()V"); + constr.setFunctype(InvocationExprent.TYP_INIT); + constr.setDescriptor(MethodDescriptor.parseDescriptor("()V")); + + NewExprent newexpr = + new NewExprent(new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/NoClassDefFoundError"), new ArrayList<Exprent>()); + newexpr.setConstructor(constr); + + InvocationExprent invcause = new InvocationExprent(); + invcause.setName("initCause"); + invcause.setClassname("java/lang/NoClassDefFoundError"); + invcause.setStringDescriptor("(Ljava/lang/Throwable;)Ljava/lang/Throwable;"); + invcause.setDescriptor(MethodDescriptor.parseDescriptor("(Ljava/lang/Throwable;)Ljava/lang/Throwable;")); + invcause.setInstance(newexpr); + invcause.setLstParameters( + Arrays.asList(new Exprent[]{new VarExprent(2, new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/ClassNotFoundException"), null)})); + + handlerexprent = new ExitExprent(ExitExprent.EXIT_THROW, + invcause, + null); + } + + + public void processClassReferences(ClassNode node) { + + ClassWrapper wrapper = node.wrapper; + + // int major_version = wrapper.getClassStruct().major_version; + // int minor_version = wrapper.getClassStruct().minor_version; + // + // if(major_version > 48 || (major_version == 48 && minor_version > 0)) { + // // version 1.5 or above + // return; + // } + + if (wrapper.getClassStruct().isVersionGE_1_5()) { + // version 1.5 or above + return; + } + + // find the synthetic method Class class$(String) if present + HashMap<ClassWrapper, MethodWrapper> mapClassMeths = new HashMap<ClassWrapper, MethodWrapper>(); + mapClassMethods(node, mapClassMeths); + + if (mapClassMeths.isEmpty()) { + return; + } + + HashSet<ClassWrapper> setFound = new HashSet<ClassWrapper>(); + processClassRec(node, mapClassMeths, setFound); + + if (!setFound.isEmpty()) { + for (ClassWrapper wrp : setFound) { + StructMethod mt = mapClassMeths.get(wrp).methodStruct; + wrp.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(mt.getName(), mt.getDescriptor())); + } + } + } + + private static void processClassRec(ClassNode node, + final HashMap<ClassWrapper, MethodWrapper> mapClassMeths, + final HashSet<ClassWrapper> setFound) { + + final ClassWrapper wrapper = node.wrapper; + + // search code + for (MethodWrapper meth : wrapper.getMethods()) { + + RootStatement root = meth.root; + if (root != null) { + + DirectGraph graph = meth.getOrBuildGraph(); + + graph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + for (Entry<ClassWrapper, MethodWrapper> ent : mapClassMeths.entrySet()) { + if (replaceInvocations(exprent, ent.getKey(), ent.getValue())) { + setFound.add(ent.getKey()); + } + } + return 0; + } + }); + } + } + + // search initializers + for (int j = 0; j < 2; j++) { + VBStyleCollection<Exprent, String> initializers = + j == 0 ? wrapper.getStaticFieldInitializers() : wrapper.getDynamicFieldInitializers(); + + for (int i = 0; i < initializers.size(); i++) { + for (Entry<ClassWrapper, MethodWrapper> ent : mapClassMeths.entrySet()) { + Exprent exprent = initializers.get(i); + if (replaceInvocations(exprent, ent.getKey(), ent.getValue())) { + setFound.add(ent.getKey()); + } + + String cl = isClass14Invocation(exprent, ent.getKey(), ent.getValue()); + if (cl != null) { + initializers.set(i, new ConstExprent(VarType.VARTYPE_CLASS, cl.replace('.', '/'))); + setFound.add(ent.getKey()); + } + } + } + } + + // iterate nested classes + for (ClassNode nd : node.nested) { + processClassRec(nd, mapClassMeths, setFound); + } + } + + private void mapClassMethods(ClassNode node, Map<ClassWrapper, MethodWrapper> map) { + boolean noSynthFlag = DecompilerContext.getOption(IFernflowerPreferences.SYNTHETIC_NOT_SET); + + ClassWrapper wrapper = node.wrapper; + + for (MethodWrapper method : wrapper.getMethods()) { + StructMethod mt = method.methodStruct; + + if ((noSynthFlag || mt.isSynthetic()) && + mt.getDescriptor().equals("(Ljava/lang/String;)Ljava/lang/Class;") && + mt.hasModifier(CodeConstants.ACC_STATIC)) { + + RootStatement root = method.root; + if (root != null && root.getFirst().type == Statement.TYPE_TRYCATCH) { + CatchStatement cst = (CatchStatement)root.getFirst(); + if (cst.getStats().size() == 2 && cst.getFirst().type == Statement.TYPE_BASICBLOCK && + cst.getStats().get(1).type == Statement.TYPE_BASICBLOCK && + cst.getVars().get(0).getVartype().equals(new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/ClassNotFoundException"))) { + + BasicBlockStatement body = (BasicBlockStatement)cst.getFirst(); + BasicBlockStatement handler = (BasicBlockStatement)cst.getStats().get(1); + + if (body.getExprents().size() == 1 && handler.getExprents().size() == 1) { + if (bodyexprent.equals(body.getExprents().get(0)) && + handlerexprent.equals(handler.getExprents().get(0))) { + map.put(wrapper, method); + break; + } + } + } + } + } + } + + // iterate nested classes + for (ClassNode nd : node.nested) { + mapClassMethods(nd, map); + } + } + + + private static boolean replaceInvocations(Exprent exprent, ClassWrapper wrapper, MethodWrapper meth) { + + boolean res = false; + + while (true) { + + boolean found = false; + + for (Exprent expr : exprent.getAllExprents()) { + String cl = isClass14Invocation(expr, wrapper, meth); + if (cl != null) { + exprent.replaceExprent(expr, new ConstExprent(VarType.VARTYPE_CLASS, cl.replace('.', '/'))); + found = true; + res = true; + break; + } + + res |= replaceInvocations(expr, wrapper, meth); + } + + if (!found) { + break; + } + } + + return res; + } + + + private static String isClass14Invocation(Exprent exprent, ClassWrapper wrapper, MethodWrapper meth) { + + if (exprent.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent fexpr = (FunctionExprent)exprent; + if (fexpr.getFunctype() == FunctionExprent.FUNCTION_IIF) { + if (fexpr.getLstOperands().get(0).type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent headexpr = (FunctionExprent)fexpr.getLstOperands().get(0); + if (headexpr.getFunctype() == FunctionExprent.FUNCTION_EQ) { + if (headexpr.getLstOperands().get(0).type == Exprent.EXPRENT_FIELD && + headexpr.getLstOperands().get(1).type == Exprent.EXPRENT_CONST && + ((ConstExprent)headexpr.getLstOperands().get(1)).getConsttype().equals(VarType.VARTYPE_NULL)) { + + FieldExprent field = (FieldExprent)headexpr.getLstOperands().get(0); + ClassNode fieldnode = DecompilerContext.getClassProcessor().getMapRootClasses().get(field.getClassname()); + + if (fieldnode != null && fieldnode.classStruct.qualifiedName.equals(wrapper.getClassStruct().qualifiedName)) { // source class + StructField fd = + wrapper.getClassStruct().getField(field.getName(), field.getDescriptor().descriptorString); // FIXME: can be null! why?? + + if (fd != null && fd.hasModifier(CodeConstants.ACC_STATIC) && + (fd.isSynthetic() || DecompilerContext.getOption(IFernflowerPreferences.SYNTHETIC_NOT_SET))) { + + if (fexpr.getLstOperands().get(1).type == Exprent.EXPRENT_ASSIGNMENT && fexpr.getLstOperands().get(2).equals(field)) { + AssignmentExprent asexpr = (AssignmentExprent)fexpr.getLstOperands().get(1); + + if (asexpr.getLeft().equals(field) && asexpr.getRight().type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent invexpr = (InvocationExprent)asexpr.getRight(); + + if (invexpr.getClassname().equals(wrapper.getClassStruct().qualifiedName) && + invexpr.getName().equals(meth.methodStruct.getName()) && + invexpr.getStringDescriptor().equals(meth.methodStruct.getDescriptor())) { + + if (invexpr.getLstParameters().get(0).type == Exprent.EXPRENT_CONST) { + wrapper.getHiddenMembers() + .add(InterpreterUtil.makeUniqueKey(fd.getName(), fd.getDescriptor())); // hide synthetic field + return ((ConstExprent)invexpr.getLstParameters().get(0)).getValue().toString(); + } + } + } + } + } + } + } + } + } + } + } + + return null; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassWriter.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassWriter.java new file mode 100644 index 000000000000..856ad225d0e1 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassWriter.java @@ -0,0 +1,987 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.main.rels.ClassWrapper; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.exps.AnnotationExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.ConstExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.NewExprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarTypeProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.modules.renamer.PoolInterceptor; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.StructMember; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.attr.*; +import org.jetbrains.java.decompiler.struct.consts.PrimitiveConstant; +import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.struct.gen.generics.*; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class ClassWriter { + + private ClassReference14Processor ref14processor; + private PoolInterceptor interceptor; + + public ClassWriter() { + ref14processor = new ClassReference14Processor(); + interceptor = DecompilerContext.getPoolInterceptor(); + } + + private void invokeProcessors(ClassNode node) { + ClassWrapper wrapper = node.wrapper; + StructClass cl = wrapper.getClassStruct(); + + InitializerProcessor.extractInitializers(wrapper); + + if (node.type == ClassNode.CLASS_ROOT && DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_CLASS_1_4)) { + ref14processor.processClassReferences(node); + } + + if (cl.hasModifier(CodeConstants.ACC_ENUM) && DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_ENUM)) { + EnumProcessor.clearEnum(wrapper); + } + + if (DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_ASSERTIONS)) { + AssertProcessor.buildAssertions(node); + } + } + + public void classLambdaToJava(ClassNode node, StringBuilder buffer, Exprent method_object, int indent) { + // get the class node with the content method + ClassNode classNode = node; + while (classNode != null && classNode.type == ClassNode.CLASS_LAMBDA) { + classNode = classNode.parent; + } + if (classNode == null) { + return; + } + + boolean lambdaToAnonymous = DecompilerContext.getOption(IFernflowerPreferences.LAMBDA_TO_ANONYMOUS_CLASS); + + ClassNode outerNode = (ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE); + DecompilerContext.setProperty(DecompilerContext.CURRENT_CLASS_NODE, node); + + try { + ClassWrapper wrapper = classNode.wrapper; + StructClass cl = wrapper.getClassStruct(); + + DecompilerContext.getLogger().startWriteClass(node.simpleName); + + if (node.lambda_information.is_method_reference) { + if (!node.lambda_information.is_content_method_static && method_object != null) { + // reference to a virtual method + buffer.append(method_object.toJava(indent)); + } + else { + // reference to a static method + buffer.append(ExprProcessor.getCastTypeName(new VarType(node.lambda_information.content_class_name, false))); + } + + buffer.append("::"); + buffer.append(node.lambda_information.content_method_name); + } + else { + // lambda method + StructMethod mt = cl.getMethod(node.lambda_information.content_method_key); + MethodWrapper methodWrapper = wrapper.getMethodWrapper(mt.getName(), mt.getDescriptor()); + MethodDescriptor md_content = MethodDescriptor.parseDescriptor(node.lambda_information.content_method_descriptor); + MethodDescriptor md_lambda = MethodDescriptor.parseDescriptor(node.lambda_information.method_descriptor); + + if (!lambdaToAnonymous) { + buffer.append('('); + + boolean firstParameter = true; + int index = node.lambda_information.is_content_method_static ? 0 : 1; + int start_index = md_content.params.length - md_lambda.params.length; + + for (int i = 0; i < md_content.params.length; i++) { + if (i >= start_index) { + if (!firstParameter) { + buffer.append(", "); + } + + String parameterName = methodWrapper.varproc.getVarName(new VarVersionPaar(index, 0)); + buffer.append(parameterName == null ? "param" + index : parameterName); // null iff decompiled with errors + + firstParameter = false; + } + + index += md_content.params[i].stack_size; + } + + buffer.append(") ->"); + } + + buffer.append(" {"); + buffer.append(DecompilerContext.getNewLineSeparator()); + + methodLambdaToJava(node, classNode, mt, buffer, indent + 1, !lambdaToAnonymous); + + InterpreterUtil.appendIndent(buffer, indent); + buffer.append("}"); + } + } + finally { + DecompilerContext.setProperty(DecompilerContext.CURRENT_CLASS_NODE, outerNode); + } + + DecompilerContext.getLogger().endWriteClass(); + } + + public void classToJava(ClassNode node, StringBuilder buffer, int indent) { + ClassNode outerNode = (ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE); + DecompilerContext.setProperty(DecompilerContext.CURRENT_CLASS_NODE, node); + + try { + // last minute processing + invokeProcessors(node); + + ClassWrapper wrapper = node.wrapper; + StructClass cl = wrapper.getClassStruct(); + + DecompilerContext.getLogger().startWriteClass(cl.qualifiedName); + + String lineSeparator = DecompilerContext.getNewLineSeparator(); + + writeClassDefinition(node, buffer, indent); + + boolean hasContent = false; + + // fields + boolean enumFields = false; + + for (StructField fd : cl.getFields()) { + boolean hide = fd.isSynthetic() && DecompilerContext.getOption(IFernflowerPreferences.REMOVE_SYNTHETIC) || + wrapper.getHiddenMembers().contains(InterpreterUtil.makeUniqueKey(fd.getName(), fd.getDescriptor())); + if (hide) continue; + + boolean isEnum = fd.hasModifier(CodeConstants.ACC_ENUM) && DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_ENUM); + if (isEnum) { + if (enumFields) { + buffer.append(','); + buffer.append(lineSeparator); + } + enumFields = true; + } + else if (enumFields) { + buffer.append(';'); + buffer.append(lineSeparator); + buffer.append(lineSeparator); + enumFields = false; + } + + fieldToJava(wrapper, cl, fd, buffer, indent + 1); + + hasContent = true; + } + + if (enumFields) { + buffer.append(';'); + buffer.append(lineSeparator); + } + + // methods + for (StructMethod mt : cl.getMethods()) { + boolean hide = mt.isSynthetic() && DecompilerContext.getOption(IFernflowerPreferences.REMOVE_SYNTHETIC) || + mt.hasModifier(CodeConstants.ACC_BRIDGE) && DecompilerContext.getOption(IFernflowerPreferences.REMOVE_BRIDGE) || + wrapper.getHiddenMembers().contains(InterpreterUtil.makeUniqueKey(mt.getName(), mt.getDescriptor())); + if (hide) continue; + + int position = buffer.length(); + if (hasContent) { + buffer.append(lineSeparator); + } + boolean methodSkipped = !methodToJava(node, mt, buffer, indent + 1); + if (!methodSkipped) { + hasContent = true; + } + else { + buffer.setLength(position); + } + } + + // member classes + for (ClassNode inner : node.nested) { + if (inner.type == ClassNode.CLASS_MEMBER) { + StructClass innerCl = inner.classStruct; + boolean isSynthetic = (inner.access & CodeConstants.ACC_SYNTHETIC) != 0 || innerCl.isSynthetic(); + boolean hide = isSynthetic && DecompilerContext.getOption(IFernflowerPreferences.REMOVE_SYNTHETIC) || + wrapper.getHiddenMembers().contains(innerCl.qualifiedName); + if (hide) continue; + + if (hasContent) { + buffer.append(lineSeparator); + } + classToJava(inner, buffer, indent + 1); + + hasContent = true; + } + } + + InterpreterUtil.appendIndent(buffer, indent); + buffer.append('}'); + + if (node.type != ClassNode.CLASS_ANONYMOUS) { + buffer.append(lineSeparator); + } + } + finally { + DecompilerContext.setProperty(DecompilerContext.CURRENT_CLASS_NODE, outerNode); + } + + DecompilerContext.getLogger().endWriteClass(); + } + + private void writeClassDefinition(ClassNode node, StringBuilder buffer, int indent) { + String lineSeparator = DecompilerContext.getNewLineSeparator(); + String indentString = InterpreterUtil.getIndentString(indent); + + if (node.type == ClassNode.CLASS_ANONYMOUS) { + buffer.append(" {"); + buffer.append(lineSeparator); + return; + } + + ClassWrapper wrapper = node.wrapper; + StructClass cl = wrapper.getClassStruct(); + + int flags = node.type == ClassNode.CLASS_ROOT ? cl.getAccessFlags() : node.access; + boolean isDeprecated = cl.getAttributes().containsKey("Deprecated"); + boolean isSynthetic = (flags & CodeConstants.ACC_SYNTHETIC) != 0 || cl.getAttributes().containsKey("Synthetic"); + boolean isEnum = DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_ENUM) && (flags & CodeConstants.ACC_ENUM) != 0; + boolean isInterface = (flags & CodeConstants.ACC_INTERFACE) != 0; + boolean isAnnotation = (flags & CodeConstants.ACC_ANNOTATION) != 0; + + if (isDeprecated) { + appendDeprecation(buffer, indentString, lineSeparator); + } + + if (interceptor != null) { + String oldName = interceptor.getOldName(cl.qualifiedName); + appendRenameComment(buffer, oldName, MType.CLASS, indent, lineSeparator); + } + + if (isSynthetic) { + appendComment(buffer, "synthetic class", indentString, lineSeparator); + } + + appendAnnotations(buffer, cl, indent, lineSeparator); + + buffer.append(indentString); + + if (isEnum) { + // remove abstract and final flags (JLS 8.9 Enums) + flags &= ~CodeConstants.ACC_ABSTRACT; + flags &= ~CodeConstants.ACC_FINAL; + } + + appendModifiers(buffer, flags, CLASS_ALLOWED, isInterface, CLASS_EXCLUDED); + + if (isEnum) { + buffer.append("enum "); + } + else if (isInterface) { + if (isAnnotation) { + buffer.append('@'); + } + buffer.append("interface "); + } + else { + buffer.append("class "); + } + + GenericClassDescriptor descriptor = null; + if (DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES)) { + StructGenericSignatureAttribute attr = (StructGenericSignatureAttribute)cl.getAttributes().getWithKey("Signature"); + if (attr != null) { + descriptor = GenericMain.parseClassSignature(attr.getSignature()); + } + } + + buffer.append(node.simpleName); + + if (descriptor != null && !descriptor.fparameters.isEmpty()) { + appendTypeParameters(buffer, descriptor.fparameters, descriptor.fbounds); + } + + buffer.append(' '); + + if (!isEnum && !isInterface && cl.superClass != null) { + VarType supertype = new VarType(cl.superClass.getString(), true); + if (!VarType.VARTYPE_OBJECT.equals(supertype)) { + buffer.append("extends "); + if (descriptor != null) { + buffer.append(GenericMain.getGenericCastTypeName(descriptor.superclass)); + } + else { + buffer.append(ExprProcessor.getCastTypeName(supertype)); + } + buffer.append(' '); + } + } + + if (!isAnnotation) { + int[] interfaces = cl.getInterfaces(); + if (interfaces.length > 0) { + buffer.append(isInterface ? "extends " : "implements "); + for (int i = 0; i < interfaces.length; i++) { + if (i > 0) { + buffer.append(", "); + } + if (descriptor != null) { + buffer.append(GenericMain.getGenericCastTypeName(descriptor.superinterfaces.get(i))); + } + else { + buffer.append(ExprProcessor.getCastTypeName(new VarType(cl.getInterface(i), true))); + } + } + buffer.append(' '); + } + } + + buffer.append('{'); + buffer.append(lineSeparator); + } + + private void fieldToJava(ClassWrapper wrapper, StructClass cl, StructField fd, StringBuilder buffer, int indent) { + String indentString = InterpreterUtil.getIndentString(indent); + String lineSeparator = DecompilerContext.getNewLineSeparator(); + + boolean isInterface = cl.hasModifier(CodeConstants.ACC_INTERFACE); + boolean isDeprecated = fd.getAttributes().containsKey("Deprecated"); + boolean isEnum = fd.hasModifier(CodeConstants.ACC_ENUM) && DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_ENUM); + + if (isDeprecated) { + appendDeprecation(buffer, indentString, lineSeparator); + } + + if (interceptor != null) { + String oldName = interceptor.getOldName(cl.qualifiedName + " " + fd.getName() + " " + fd.getDescriptor()); + appendRenameComment(buffer, oldName, MType.FIELD, indent, lineSeparator); + } + + if (fd.isSynthetic()) { + appendComment(buffer, "synthetic field", indentString, lineSeparator); + } + + appendAnnotations(buffer, fd, indent, lineSeparator); + + buffer.append(indentString); + + if (!isEnum) { + appendModifiers(buffer, fd.getAccessFlags(), FIELD_ALLOWED, isInterface, FIELD_EXCLUDED); + } + + VarType fieldType = new VarType(fd.getDescriptor(), false); + + GenericFieldDescriptor descriptor = null; + if (DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES)) { + StructGenericSignatureAttribute attr = (StructGenericSignatureAttribute)fd.getAttributes().getWithKey("Signature"); + if (attr != null) { + descriptor = GenericMain.parseFieldSignature(attr.getSignature()); + } + } + + if (!isEnum) { + if (descriptor != null) { + buffer.append(GenericMain.getGenericCastTypeName(descriptor.type)); + } + else { + buffer.append(ExprProcessor.getCastTypeName(fieldType)); + } + buffer.append(' '); + } + + buffer.append(fd.getName()); + + Exprent initializer; + if (fd.hasModifier(CodeConstants.ACC_STATIC)) { + initializer = wrapper.getStaticFieldInitializers().getWithKey(InterpreterUtil.makeUniqueKey(fd.getName(), fd.getDescriptor())); + } + else { + initializer = wrapper.getDynamicFieldInitializers().getWithKey(InterpreterUtil.makeUniqueKey(fd.getName(), fd.getDescriptor())); + } + if (initializer != null) { + if (isEnum && initializer.type == Exprent.EXPRENT_NEW) { + NewExprent nexpr = (NewExprent)initializer; + nexpr.setEnumconst(true); + buffer.append(nexpr.toJava(indent)); + } + else { + buffer.append(" = "); + buffer.append(initializer.toJava(indent)); + } + } + else if (fd.hasModifier(CodeConstants.ACC_FINAL) && fd.hasModifier(CodeConstants.ACC_STATIC)) { + StructConstantValueAttribute attr = + (StructConstantValueAttribute)fd.getAttributes().getWithKey(StructGeneralAttribute.ATTRIBUTE_CONSTANT_VALUE); + if (attr != null) { + PrimitiveConstant constant = cl.getPool().getPrimitiveConstant(attr.getIndex()); + buffer.append(" = "); + buffer.append(new ConstExprent(fieldType, constant.value).toJava(indent)); + } + } + + if (!isEnum) { + buffer.append(";"); + buffer.append(lineSeparator); + } + } + + private static void methodLambdaToJava(ClassNode lambdaNode, + ClassNode classNode, + StructMethod mt, + StringBuilder buffer, + int indent, + boolean codeOnly) { + ClassWrapper classWrapper = classNode.wrapper; + MethodWrapper methodWrapper = classWrapper.getMethodWrapper(mt.getName(), mt.getDescriptor()); + + MethodWrapper outerWrapper = (MethodWrapper)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD_WRAPPER); + DecompilerContext.setProperty(DecompilerContext.CURRENT_METHOD_WRAPPER, methodWrapper); + + try { + String method_name = lambdaNode.lambda_information.method_name; + MethodDescriptor md_content = MethodDescriptor.parseDescriptor(lambdaNode.lambda_information.content_method_descriptor); + MethodDescriptor md_lambda = MethodDescriptor.parseDescriptor(lambdaNode.lambda_information.method_descriptor); + + if (!codeOnly) { + InterpreterUtil.appendIndent(buffer, indent); + buffer.append("public "); + buffer.append(method_name); + buffer.append("("); + + boolean firstParameter = true; + int index = lambdaNode.lambda_information.is_content_method_static ? 0 : 1; + int start_index = md_content.params.length - md_lambda.params.length; + + for (int i = 0; i < md_content.params.length; i++) { + if (i >= start_index) { + if (!firstParameter) { + buffer.append(", "); + } + + String typeName = ExprProcessor.getCastTypeName(md_content.params[i].copy()); + if (ExprProcessor.UNDEFINED_TYPE_STRING.equals(typeName) && + DecompilerContext.getOption(IFernflowerPreferences.UNDEFINED_PARAM_TYPE_OBJECT)) { + typeName = ExprProcessor.getCastTypeName(VarType.VARTYPE_OBJECT); + } + + buffer.append(typeName); + buffer.append(" "); + + String parameterName = methodWrapper.varproc.getVarName(new VarVersionPaar(index, 0)); + buffer.append(parameterName == null ? "param" + index : parameterName); // null iff decompiled with errors + + firstParameter = false; + } + + index += md_content.params[i].stack_size; + } + + buffer.append(") {"); + buffer.append(DecompilerContext.getNewLineSeparator()); + + indent += 1; + } + + if (!methodWrapper.decompiledWithErrors) { + RootStatement root = classWrapper.getMethodWrapper(mt.getName(), mt.getDescriptor()).root; + if (root != null) { // check for existence + try { + buffer.append(root.toJava(indent)); + } + catch (Throwable ex) { + DecompilerContext.getLogger().writeMessage("Method " + mt.getName() + " " + mt.getDescriptor() + " couldn't be written.", ex); + methodWrapper.decompiledWithErrors = true; + } + } + } + + if (methodWrapper.decompiledWithErrors) { + InterpreterUtil.appendIndent(buffer, indent); + buffer.append("// $FF: Couldn't be decompiled"); + buffer.append(DecompilerContext.getNewLineSeparator()); + } + + if (!codeOnly) { + indent -= 1; + + InterpreterUtil.appendIndent(buffer, indent); + buffer.append('}'); + buffer.append(DecompilerContext.getNewLineSeparator()); + } + } + finally { + DecompilerContext.setProperty(DecompilerContext.CURRENT_METHOD_WRAPPER, outerWrapper); + } + } + + private boolean methodToJava(ClassNode node, StructMethod mt, StringBuilder buffer, int indent) { + ClassWrapper wrapper = node.wrapper; + StructClass cl = wrapper.getClassStruct(); + MethodWrapper methodWrapper = wrapper.getMethodWrapper(mt.getName(), mt.getDescriptor()); + + boolean hideMethod = false; + + MethodWrapper outerWrapper = (MethodWrapper)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD_WRAPPER); + DecompilerContext.setProperty(DecompilerContext.CURRENT_METHOD_WRAPPER, methodWrapper); + + try { + boolean isInterface = cl.hasModifier(CodeConstants.ACC_INTERFACE); + boolean isAnnotation = cl.hasModifier(CodeConstants.ACC_ANNOTATION); + boolean isEnum = cl.hasModifier(CodeConstants.ACC_ENUM) && DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_ENUM); + boolean isDeprecated = mt.getAttributes().containsKey("Deprecated"); + boolean clinit = false, init = false, dinit = false; + + String indentString = InterpreterUtil.getIndentString(indent); + String lineSeparator = DecompilerContext.getNewLineSeparator(); + + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + + int flags = mt.getAccessFlags(); + if ((flags & CodeConstants.ACC_NATIVE) != 0) { + flags &= ~CodeConstants.ACC_STRICT; // compiler bug: a strictfp class sets all methods to strictfp + } + if ("<clinit>".equals(mt.getName())) { + flags &= CodeConstants.ACC_STATIC; // ignore all modifiers except 'static' in a static initializer + } + + if (isDeprecated) { + appendDeprecation(buffer, indentString, lineSeparator); + } + + if (interceptor != null) { + String oldName = interceptor.getOldName(cl.qualifiedName + " " + mt.getName() + " " + mt.getDescriptor()); + appendRenameComment(buffer, oldName, MType.METHOD, indent, lineSeparator); + } + + boolean isSynthetic = (flags & CodeConstants.ACC_SYNTHETIC) != 0 || mt.getAttributes().containsKey("Synthetic"); + boolean isBridge = (flags & CodeConstants.ACC_BRIDGE) != 0; + if (isSynthetic) { + appendComment(buffer, "synthetic method", indentString, lineSeparator); + } + if (isBridge) { + appendComment(buffer, "bridge method", indentString, lineSeparator); + } + + appendAnnotations(buffer, mt, indent, lineSeparator); + + buffer.append(indentString); + + appendModifiers(buffer, flags, METHOD_ALLOWED, isInterface, METHOD_EXCLUDED); + + if (isInterface && mt.containsCode()) { + // 'default' modifier (Java 8) + buffer.append("default "); + } + + String name = mt.getName(); + if ("<init>".equals(name)) { + if (node.type == ClassNode.CLASS_ANONYMOUS) { + name = ""; + dinit = true; + } + else { + name = node.simpleName; + init = true; + } + } + else if ("<clinit>".equals(name)) { + name = ""; + clinit = true; + } + + GenericMethodDescriptor descriptor = null; + if (DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES)) { + StructGenericSignatureAttribute attr = (StructGenericSignatureAttribute)mt.getAttributes().getWithKey("Signature"); + if (attr != null) { + descriptor = GenericMain.parseMethodSignature(attr.getSignature()); + if (descriptor != null) { + int actualParams = md.params.length; + if (isEnum && init) actualParams -= 2; + if (actualParams != descriptor.params.size()) { + String message = "Inconsistent generic signature in method " + mt.getName() + " " + mt.getDescriptor(); + DecompilerContext.getLogger().writeMessage(message, IFernflowerLogger.Severity.WARN); + descriptor = null; + } + } + } + } + + boolean throwsExceptions = false; + int paramCount = 0; + + if (!clinit && !dinit) { + boolean thisVar = !mt.hasModifier(CodeConstants.ACC_STATIC); + + if (descriptor != null && !descriptor.fparameters.isEmpty()) { + appendTypeParameters(buffer, descriptor.fparameters, descriptor.fbounds); + buffer.append(' '); + } + + if (!init) { + if (descriptor != null) { + buffer.append(GenericMain.getGenericCastTypeName(descriptor.ret)); + } + else { + buffer.append(ExprProcessor.getCastTypeName(md.ret)); + } + buffer.append(' '); + } + + buffer.append(name); + buffer.append('('); + + // parameters + List<VarVersionPaar> signFields = methodWrapper.signatureFields; + + int lastVisibleParameterIndex = -1; + for (int i = 0; i < md.params.length; i++) { + if (signFields == null || signFields.get(i) == null) { + lastVisibleParameterIndex = i; + } + } + + boolean firstParameter = true; + int index = isEnum && init ? 3 : thisVar ? 1 : 0; + int start = isEnum && init && descriptor == null ? 2 : 0; + int params = descriptor == null ? md.params.length : descriptor.params.size(); + for (int i = start; i < params; i++) { + if (signFields == null || signFields.get(i) == null) { + if (!firstParameter) { + buffer.append(", "); + } + + appendParameterAnnotations(buffer, mt, paramCount); + + if (methodWrapper.varproc.getVarFinal(new VarVersionPaar(index, 0)) == VarTypeProcessor.VAR_FINALEXPLICIT) { + buffer.append("final "); + } + + if (descriptor != null) { + GenericType parameterType = descriptor.params.get(i); + + boolean isVarArg = (i == lastVisibleParameterIndex && mt.hasModifier(CodeConstants.ACC_VARARGS) && parameterType.arraydim > 0); + if (isVarArg) { + parameterType.arraydim--; + } + + String typeName = GenericMain.getGenericCastTypeName(parameterType); + if (ExprProcessor.UNDEFINED_TYPE_STRING.equals(typeName) && + DecompilerContext.getOption(IFernflowerPreferences.UNDEFINED_PARAM_TYPE_OBJECT)) { + typeName = ExprProcessor.getCastTypeName(VarType.VARTYPE_OBJECT); + } + + buffer.append(typeName); + + if (isVarArg) { + buffer.append("..."); + } + } + else { + VarType parameterType = md.params[i].copy(); + + boolean isVarArg = (i == lastVisibleParameterIndex && mt.hasModifier(CodeConstants.ACC_VARARGS) && parameterType.arraydim > 0); + if (isVarArg) { + parameterType.decArrayDim(); + } + + String typeName = ExprProcessor.getCastTypeName(parameterType); + if (ExprProcessor.UNDEFINED_TYPE_STRING.equals(typeName) && + DecompilerContext.getOption(IFernflowerPreferences.UNDEFINED_PARAM_TYPE_OBJECT)) { + typeName = ExprProcessor.getCastTypeName(VarType.VARTYPE_OBJECT); + } + + buffer.append(typeName); + + if (isVarArg) { + buffer.append("..."); + } + } + + buffer.append(' '); + String parameterName = methodWrapper.varproc.getVarName(new VarVersionPaar(index, 0)); + buffer.append(parameterName == null ? "param" + index : parameterName); // null iff decompiled with errors + + firstParameter = false; + paramCount++; + } + + index += md.params[i].stack_size; + } + + buffer.append(')'); + + StructExceptionsAttribute attr = (StructExceptionsAttribute)mt.getAttributes().getWithKey("Exceptions"); + if ((descriptor != null && !descriptor.exceptions.isEmpty()) || attr != null) { + throwsExceptions = true; + buffer.append(" throws "); + + for (int i = 0; i < attr.getThrowsExceptions().size(); i++) { + if (i > 0) { + buffer.append(", "); + } + if (descriptor != null && !descriptor.exceptions.isEmpty()) { + GenericType type = descriptor.exceptions.get(i); + buffer.append(GenericMain.getGenericCastTypeName(type)); + } + else { + VarType type = new VarType(attr.getExcClassname(i, cl.getPool()), true); + buffer.append(ExprProcessor.getCastTypeName(type)); + } + } + } + } + + if ((flags & (CodeConstants.ACC_ABSTRACT | CodeConstants.ACC_NATIVE)) != 0) { // native or abstract method (explicit or interface) + if (isAnnotation) { + StructAnnDefaultAttribute attr = (StructAnnDefaultAttribute)mt.getAttributes().getWithKey("AnnotationDefault"); + if (attr != null) { + buffer.append(" default "); + buffer.append(attr.getDefaultValue().toJava(indent + 1)); + } + } + + buffer.append(';'); + buffer.append(lineSeparator); + } + else { + if (!clinit && !dinit) { + buffer.append(' '); + } + + buffer.append('{'); + buffer.append(lineSeparator); + + RootStatement root = wrapper.getMethodWrapper(mt.getName(), mt.getDescriptor()).root; + + if (root != null && !methodWrapper.decompiledWithErrors) { // check for existence + try { + String code = root.toJava(indent + 1); + + hideMethod = (clinit || dinit || hideConstructor(wrapper, init, throwsExceptions, paramCount)) && code.length() == 0; + + buffer.append(code); + } + catch (Throwable ex) { + DecompilerContext.getLogger().writeMessage("Method " + mt.getName() + " " + mt.getDescriptor() + " couldn't be written.", ex); + methodWrapper.decompiledWithErrors = true; + } + } + + if (methodWrapper.decompiledWithErrors) { + buffer.append(InterpreterUtil.getIndentString(indent + 1)); + buffer.append("// $FF: Couldn't be decompiled"); + buffer.append(lineSeparator); + } + + buffer.append(indentString); + buffer.append('}'); + buffer.append(lineSeparator); + } + } + finally { + DecompilerContext.setProperty(DecompilerContext.CURRENT_METHOD_WRAPPER, outerWrapper); + } + + return !hideMethod; + } + + private static boolean hideConstructor(ClassWrapper wrapper, boolean init, boolean throwsExceptions, int paramCount) { + if (!init || throwsExceptions || paramCount > 0 || !DecompilerContext.getOption(IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR)) { + return false; + } + + int count = 0; + for (StructMethod mt : wrapper.getClassStruct().getMethods()) { + if ("<init>".equals(mt.getName())) { + if (++count > 1) { + return false; + } + } + } + + return true; + } + + private static void appendDeprecation(StringBuilder buffer, String indentString, String lineSeparator) { + buffer.append(indentString).append("/** @deprecated */").append(lineSeparator); + } + + private enum MType {CLASS, FIELD, METHOD} + + private static void appendRenameComment(StringBuilder buffer, String oldName, MType type, int indent, String lineSeparator) { + if (oldName == null) return; + + InterpreterUtil.appendIndent(buffer, indent); + buffer.append("// $FF: renamed from: "); + + switch (type) { + case CLASS: + buffer.append(ExprProcessor.buildJavaClassName(oldName)); + break; + + case FIELD: + String[] fParts = oldName.split(" "); + FieldDescriptor fd = FieldDescriptor.parseDescriptor(fParts[2]); + buffer.append(fParts[1]); + buffer.append(' '); + buffer.append(getTypePrintOut(fd.type)); + break; + + default: + String[] mParts = oldName.split(" "); + MethodDescriptor md = MethodDescriptor.parseDescriptor(mParts[2]); + buffer.append(mParts[1]); + buffer.append(" ("); + boolean first = true; + for (VarType paramType : md.params) { + if (!first) { + buffer.append(", "); + } + first = false; + buffer.append(getTypePrintOut(paramType)); + } + buffer.append(") "); + buffer.append(getTypePrintOut(md.ret)); + } + + buffer.append(lineSeparator); + } + + private static String getTypePrintOut(VarType type) { + String typeText = ExprProcessor.getCastTypeName(type, false); + if (ExprProcessor.UNDEFINED_TYPE_STRING.equals(typeText) && + DecompilerContext.getOption(IFernflowerPreferences.UNDEFINED_PARAM_TYPE_OBJECT)) { + typeText = ExprProcessor.getCastTypeName(VarType.VARTYPE_OBJECT, false); + } + return typeText; + } + + private static void appendComment(StringBuilder buffer, String comment, String indentString, String lineSeparator) { + buffer.append(indentString).append("// $FF: ").append(comment).append(lineSeparator); + } + + private static final String[] ANNOTATION_ATTRIBUTES = { + StructGeneralAttribute.ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS, StructGeneralAttribute.ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS}; + + private static void appendAnnotations(StringBuilder buffer, StructMember mb, int indent, String lineSeparator) { + for (String name : ANNOTATION_ATTRIBUTES) { + StructAnnotationAttribute attribute = (StructAnnotationAttribute)mb.getAttributes().getWithKey(name); + if (attribute != null) { + for (AnnotationExprent annotation : attribute.getAnnotations()) { + buffer.append(annotation.toJava(indent)).append(lineSeparator); + } + } + } + } + + private static final String[] PARAMETER_ANNOTATION_ATTRIBUTES = { + StructGeneralAttribute.ATTRIBUTE_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS, StructGeneralAttribute.ATTRIBUTE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS}; + + private static void appendParameterAnnotations(StringBuilder buffer, StructMethod mt, int param) { + for (String name : PARAMETER_ANNOTATION_ATTRIBUTES) { + StructAnnotationParameterAttribute attribute = (StructAnnotationParameterAttribute)mt.getAttributes().getWithKey(name); + if (attribute != null) { + List<List<AnnotationExprent>> annotations = attribute.getParamAnnotations(); + if (param < annotations.size()) { + for (AnnotationExprent annotation : annotations.get(param)) { + buffer.append(annotation.toJava(0)).append(' '); + } + } + } + } + } + + private static final Map<Integer, String> MODIFIERS = new LinkedHashMap<Integer, String>() {{ + put(CodeConstants.ACC_PUBLIC, "public"); + put(CodeConstants.ACC_PROTECTED, "protected"); + put(CodeConstants.ACC_PRIVATE, "private"); + put(CodeConstants.ACC_ABSTRACT, "abstract"); + put(CodeConstants.ACC_STATIC, "static"); + put(CodeConstants.ACC_FINAL, "final"); + put(CodeConstants.ACC_STRICT, "strictfp"); + put(CodeConstants.ACC_TRANSIENT, "transient"); + put(CodeConstants.ACC_VOLATILE, "volatile"); + put(CodeConstants.ACC_SYNCHRONIZED, "synchronized"); + put(CodeConstants.ACC_NATIVE, "native"); + }}; + + private static final int CLASS_ALLOWED = + CodeConstants.ACC_PUBLIC | CodeConstants.ACC_PROTECTED | CodeConstants.ACC_PRIVATE | CodeConstants.ACC_ABSTRACT | + CodeConstants.ACC_STATIC | CodeConstants.ACC_FINAL | CodeConstants.ACC_STRICT; + private static final int FIELD_ALLOWED = + CodeConstants.ACC_PUBLIC | CodeConstants.ACC_PROTECTED | CodeConstants.ACC_PRIVATE | CodeConstants.ACC_STATIC | + CodeConstants.ACC_FINAL | CodeConstants.ACC_TRANSIENT | CodeConstants.ACC_VOLATILE; + private static final int METHOD_ALLOWED = + CodeConstants.ACC_PUBLIC | CodeConstants.ACC_PROTECTED | CodeConstants.ACC_PRIVATE | CodeConstants.ACC_ABSTRACT | + CodeConstants.ACC_STATIC | CodeConstants.ACC_FINAL | CodeConstants.ACC_SYNCHRONIZED | CodeConstants.ACC_NATIVE | CodeConstants.ACC_STRICT; + + private static final int CLASS_EXCLUDED = CodeConstants.ACC_ABSTRACT | CodeConstants.ACC_STATIC; + private static final int FIELD_EXCLUDED = CodeConstants.ACC_PUBLIC | CodeConstants.ACC_STATIC | CodeConstants.ACC_FINAL; + private static final int METHOD_EXCLUDED = CodeConstants.ACC_PUBLIC | CodeConstants.ACC_ABSTRACT; + + private static void appendModifiers(StringBuilder buffer, int flags, int allowed, boolean isInterface, int excluded) { + flags &= allowed; + if (!isInterface) excluded = 0; + for (int modifier : MODIFIERS.keySet()) { + if ((flags & modifier) == modifier && (modifier & excluded) == 0) { + buffer.append(MODIFIERS.get(modifier)).append(' '); + } + } + } + + private static void appendTypeParameters(StringBuilder buffer, List<String> parameters, List<List<GenericType>> bounds) { + buffer.append('<'); + + for (int i = 0; i < parameters.size(); i++) { + if (i > 0) { + buffer.append(", "); + } + + buffer.append(parameters.get(i)); + + List<GenericType> parameterBounds = bounds.get(i); + if (parameterBounds.size() > 1 || !"java/lang/Object".equals(parameterBounds.get(0).value)) { + buffer.append(" extends "); + buffer.append(GenericMain.getGenericCastTypeName(parameterBounds.get(0))); + for (int j = 1; j < parameterBounds.size(); j++) { + buffer.append(" & "); + buffer.append(GenericMain.getGenericCastTypeName(parameterBounds.get(j))); + } + } + } + + buffer.append('>'); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassesProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassesProcessor.java new file mode 100644 index 000000000000..6faad08ae09e --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/ClassesProcessor.java @@ -0,0 +1,431 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.collectors.ImportCollector; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer; +import org.jetbrains.java.decompiler.main.rels.ClassWrapper; +import org.jetbrains.java.decompiler.main.rels.LambdaProcessor; +import org.jetbrains.java.decompiler.main.rels.NestedClassProcessor; +import org.jetbrains.java.decompiler.main.rels.NestedMemberAccess; +import org.jetbrains.java.decompiler.modules.decompiler.exps.InvocationExprent; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructContext; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.attr.StructInnerClassesAttribute; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; + +public class ClassesProcessor { + + private Map<String, ClassNode> mapRootClasses = new HashMap<String, ClassNode>(); + + public ClassesProcessor(StructContext context) { + + HashMap<String, Object[]> mapInnerClasses = new HashMap<String, Object[]>(); + + HashMap<String, HashSet<String>> mapNestedClassReferences = new HashMap<String, HashSet<String>>(); + HashMap<String, HashSet<String>> mapEnclosingClassReferences = new HashMap<String, HashSet<String>>(); + + HashMap<String, String> mapNewSimpleNames = new HashMap<String, String>(); + + boolean bDecompileInner = DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_INNER); + + // create class nodes + for (StructClass cl : context.getClasses().values()) { + if (cl.isOwn() && !mapRootClasses.containsKey(cl.qualifiedName)) { + + if (bDecompileInner) { + StructInnerClassesAttribute inner = (StructInnerClassesAttribute)cl.getAttributes().getWithKey("InnerClasses"); + if (inner != null) { + + for (int i = 0; i < inner.getClassEntries().size(); i++) { + + int[] entry = inner.getClassEntries().get(i); + String[] strentry = inner.getStringEntries().get(i); + + Object[] arr = new Object[4]; // arr[0] not used + + String innername = strentry[0]; + + // nested class type + arr[2] = entry[1] == 0 ? (entry[2] == 0 ? ClassNode.CLASS_ANONYMOUS : ClassNode.CLASS_LOCAL) : ClassNode.CLASS_MEMBER; + + // original simple name + String simpleName = strentry[2]; + String savedName = mapNewSimpleNames.get(innername); + + if (savedName != null) { + simpleName = savedName; + } + else if (simpleName != null && DecompilerContext.getOption(IFernflowerPreferences.RENAME_ENTITIES)) { + IIdentifierRenamer renamer = DecompilerContext.getPoolInterceptor().getHelper(); + if (renamer.toBeRenamed(IIdentifierRenamer.ELEMENT_CLASS, simpleName, null, null)) { + simpleName = renamer.getNextClassname(innername, simpleName); + mapNewSimpleNames.put(innername, simpleName); + } + } + + arr[1] = simpleName; + + // original access flags + arr[3] = entry[3]; + + // enclosing class + String enclClassName; + if (entry[1] != 0) { + enclClassName = strentry[1]; + } + else { + enclClassName = cl.qualifiedName; + } + + if (!innername.equals(enclClassName)) { // self reference + StructClass enclosing_class = context.getClasses().get(enclClassName); + if (enclosing_class != null && enclosing_class.isOwn()) { // own classes only + + Object[] arrold = mapInnerClasses.get(innername); + if (arrold == null) { + mapInnerClasses.put(innername, arr); + } + else { + if (!InterpreterUtil.equalObjectArrays(arrold, arr)) { + DecompilerContext.getLogger() + .writeMessage("Inconsistent inner class entries for " + innername + "!", IFernflowerLogger.Severity.WARN); + } + } + + // reference to the nested class + HashSet<String> set = mapNestedClassReferences.get(enclClassName); + if (set == null) { + mapNestedClassReferences.put(enclClassName, set = new HashSet<String>()); + } + set.add(innername); + + // reference to the enclosing class + set = mapEnclosingClassReferences.get(innername); + if (set == null) { + mapEnclosingClassReferences.put(innername, set = new HashSet<String>()); + } + set.add(enclClassName); + } + } + } + } + } + + ClassNode node = new ClassNode(ClassNode.CLASS_ROOT, cl); + node.access = cl.getAccessFlags(); + mapRootClasses.put(cl.qualifiedName, node); + } + } + + if (bDecompileInner) { + + // connect nested classes + for (Entry<String, ClassNode> ent : mapRootClasses.entrySet()) { + // root class? + if (!mapInnerClasses.containsKey(ent.getKey())) { + + HashSet<String> setVisited = new HashSet<String>(); + LinkedList<String> stack = new LinkedList<String>(); + + stack.add(ent.getKey()); + setVisited.add(ent.getKey()); + + while (!stack.isEmpty()) { + + String superClass = stack.removeFirst(); + ClassNode supernode = mapRootClasses.get(superClass); + + HashSet<String> setNestedClasses = mapNestedClassReferences.get(superClass); + if (setNestedClasses != null) { + + StructClass scl = supernode.classStruct; + StructInnerClassesAttribute inner = (StructInnerClassesAttribute)scl.getAttributes().getWithKey("InnerClasses"); + for (int i = 0; i < inner.getStringEntries().size(); i++) { + String nestedClass = inner.getStringEntries().get(i)[0]; + if (!setNestedClasses.contains(nestedClass)) { + continue; + } + + if (setVisited.contains(nestedClass)) { + continue; + } + setVisited.add(nestedClass); + + ClassNode nestednode = mapRootClasses.get(nestedClass); + if (nestednode == null) { + DecompilerContext.getLogger().writeMessage("Nested class " + nestedClass + " missing!", + IFernflowerLogger.Severity.WARN); + continue; + } + + Object[] arr = mapInnerClasses.get(nestedClass); + + //if ((Integer)arr[2] == ClassNode.CLASS_MEMBER) { + // FIXME: check for consistent naming + //} + + nestednode.type = (Integer)arr[2]; + nestednode.simpleName = (String)arr[1]; + nestednode.access = (Integer)arr[3]; + + if (nestednode.type == ClassNode.CLASS_ANONYMOUS) { + StructClass cl = nestednode.classStruct; + + // remove static if anonymous class + // a common compiler bug + nestednode.access &= ~CodeConstants.ACC_STATIC; + + int[] interfaces = cl.getInterfaces(); + + if (interfaces.length > 0) { + if (interfaces.length > 1) { + DecompilerContext.getLogger() + .writeMessage("Inconsistent anonymous class definition: " + cl.qualifiedName, IFernflowerLogger.Severity.WARN); + } + nestednode.anonimousClassType = new VarType(cl.getInterface(0), true); + } + else { + nestednode.anonimousClassType = new VarType(cl.superClass.getString(), true); + } + } + else if (nestednode.type == ClassNode.CLASS_LOCAL) { + // only abstract and final are permitted + // a common compiler bug + nestednode.access &= (CodeConstants.ACC_ABSTRACT | CodeConstants.ACC_FINAL); + } + + supernode.nested.add(nestednode); + nestednode.parent = supernode; + + nestednode.enclosingClasses.addAll(mapEnclosingClassReferences.get(nestedClass)); + + stack.add(nestedClass); + } + } + } + } + } + } + } + + public void writeClass(StructClass cl, StringBuilder buffer) throws IOException { + ClassNode root = mapRootClasses.get(cl.qualifiedName); + if (root.type != ClassNode.CLASS_ROOT) { + return; + } + + try { + ImportCollector importCollector = new ImportCollector(root); + DecompilerContext.setImportCollector(importCollector); + DecompilerContext.setCounterContainer(new CounterContainer()); + + new LambdaProcessor().processClass(root); + + // add simple class names to implicit import + addClassnameToImport(root, importCollector); + + // build wrappers for all nested classes (that's where actual processing takes place) + initWrappers(root); + + new NestedClassProcessor().processClass(root, root); + + new NestedMemberAccess().propagateMemberAccess(root); + + StringBuilder classBuffer = new StringBuilder(); + new ClassWriter().classToJava(root, classBuffer, 0); + + String lineSeparator = DecompilerContext.getNewLineSeparator(); + + int index = cl.qualifiedName.lastIndexOf("/"); + if (index >= 0) { + String packageName = cl.qualifiedName.substring(0, index).replace('/', '.'); + buffer.append("package "); + buffer.append(packageName); + buffer.append(";"); + buffer.append(lineSeparator); + buffer.append(lineSeparator); + } + + if (importCollector.writeImports(buffer)) { + buffer.append(lineSeparator); + } + + buffer.append(classBuffer); + } + finally { + destroyWrappers(root); + } + } + + private static void initWrappers(ClassNode node) throws IOException { + + if (node.type == ClassNode.CLASS_LAMBDA) { + return; + } + + ClassWrapper wrapper = new ClassWrapper(node.classStruct); + wrapper.init(); + + node.wrapper = wrapper; + + for (ClassNode nd : node.nested) { + initWrappers(nd); + } + } + + private static void addClassnameToImport(ClassNode node, ImportCollector imp) { + + if (node.simpleName != null && node.simpleName.length() > 0) { + imp.getShortName(node.type == ClassNode.CLASS_ROOT ? node.classStruct.qualifiedName : node.simpleName, false); + } + + for (ClassNode nd : node.nested) { + addClassnameToImport(nd, imp); + } + } + + private static void destroyWrappers(ClassNode node) { + + node.wrapper = null; + node.classStruct.releaseResources(); + + for (ClassNode nd : node.nested) { + destroyWrappers(nd); + } + } + + public Map<String, ClassNode> getMapRootClasses() { + return mapRootClasses; + } + + + public static class ClassNode { + + public static final int CLASS_ROOT = 0; + public static final int CLASS_MEMBER = 1; + public static final int CLASS_ANONYMOUS = 2; + public static final int CLASS_LOCAL = 4; + public static final int CLASS_LAMBDA = 8; + + public int type; + + public int access; + + public String simpleName; + + public StructClass classStruct; + + public ClassWrapper wrapper; + + public String enclosingMethod; + + public InvocationExprent superInvocation; + + public HashMap<String, VarVersionPaar> mapFieldsToVars = new HashMap<String, VarVersionPaar>(); + + public VarType anonimousClassType; + + public List<ClassNode> nested = new ArrayList<ClassNode>(); + + public Set<String> enclosingClasses = new HashSet<String>(); + + public ClassNode parent; + + public LambdaInformation lambda_information; + + public ClassNode(String content_class_name, + String content_method_name, + String content_method_descriptor, + int content_method_invocation_type, + String lambda_class_name, + String lambda_method_name, + String lambda_method_descriptor, + StructClass classStruct) { // lambda class constructor + this.type = CLASS_LAMBDA; + this.classStruct = classStruct; // 'parent' class containing the static function + + lambda_information = new LambdaInformation(); + + lambda_information.class_name = lambda_class_name; + lambda_information.method_name = lambda_method_name; + lambda_information.method_descriptor = lambda_method_descriptor; + + lambda_information.content_class_name = content_class_name; + lambda_information.content_method_name = content_method_name; + lambda_information.content_method_descriptor = content_method_descriptor; + lambda_information.content_method_invocation_type = content_method_invocation_type; + + lambda_information.content_method_key = + InterpreterUtil.makeUniqueKey(lambda_information.content_method_name, lambda_information.content_method_descriptor); + + anonimousClassType = new VarType(lambda_class_name, true); + + boolean is_method_reference = (content_class_name != classStruct.qualifiedName); + if (!is_method_reference) { // content method in the same class, check synthetic flag + StructMethod mt = classStruct.getMethod(content_method_name, content_method_descriptor); + is_method_reference = !mt.isSynthetic(); // if not synthetic -> method reference + } + + lambda_information.is_method_reference = is_method_reference; + lambda_information.is_content_method_static = + (lambda_information.content_method_invocation_type == CodeConstants.CONSTANT_MethodHandle_REF_invokeStatic); // FIXME: redundant? + } + + public ClassNode(int type, StructClass classStruct) { + this.type = type; + this.classStruct = classStruct; + + simpleName = classStruct.qualifiedName.substring(classStruct.qualifiedName.lastIndexOf('/') + 1); + } + + public ClassNode getClassNode(String qualifiedName) { + for (ClassNode node : nested) { + if (qualifiedName.equals(node.classStruct.qualifiedName)) { + return node; + } + } + return null; + } + + public static class LambdaInformation { + public String class_name; + public String method_name; + public String method_descriptor; + + public String content_class_name; + public String content_method_name; + public String content_method_descriptor; + public int content_method_invocation_type; // values from CONSTANT_MethodHandle_REF_* + + public String content_method_key; + + public boolean is_method_reference; + public boolean is_content_method_static; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/DecompilerContext.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/DecompilerContext.java new file mode 100644 index 000000000000..b600250d0b78 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/DecompilerContext.java @@ -0,0 +1,150 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.collectors.ImportCollector; +import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.renamer.PoolInterceptor; +import org.jetbrains.java.decompiler.struct.StructContext; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public class DecompilerContext { + public static final String CURRENT_CLASS = "CURRENT_CLASS"; + public static final String CURRENT_CLASS_NODE = "CURRENT_CLASS_NODE"; + public static final String CURRENT_METHOD = "CURRENT_METHOD"; + public static final String CURRENT_METHOD_DESCRIPTOR = "CURRENT_METHOD_DESCRIPTOR"; + public static final String CURRENT_METHOD_WRAPPER = "CURRENT_METHOD_WRAPPER"; + public static final String CURRENT_VAR_PROCESSOR = "CURRENT_VAR_PROCESSOR"; + + private static ThreadLocal<DecompilerContext> currentContext = new ThreadLocal<DecompilerContext>(); + + private final Map<String, Object> properties; + private StructContext structContext; + private ImportCollector importCollector; + private VarNamesCollector varNamescollector; + private CounterContainer counterContainer; + private ClassesProcessor classProcessor; + private PoolInterceptor poolInterceptor; + private IFernflowerLogger logger; + + private DecompilerContext(Map<String, Object> properties) { + this.properties = properties; + } + + public static void initContext(Map<String, Object> propertiesCustom) { + Map<String, Object> properties = new HashMap<String, Object>(IFernflowerPreferences.DEFAULTS); + if (propertiesCustom != null) { + properties.putAll(propertiesCustom); + } + currentContext.set(new DecompilerContext(properties)); + } + + public static DecompilerContext getCurrentContext() { + return currentContext.get(); + } + + public static void setCurrentContext(DecompilerContext context) { + currentContext.set(context); + } + + public static Object getProperty(String key) { + return getCurrentContext().properties.get(key); + } + + public static void setProperty(String key, Object value) { + getCurrentContext().properties.put(key, value); + } + + public static boolean getOption(String key) { + return "1".equals(getCurrentContext().properties.get(key)); + } + + public static ImportCollector getImportCollector() { + return getCurrentContext().importCollector; + } + + public static void setImportCollector(ImportCollector importCollector) { + getCurrentContext().importCollector = importCollector; + } + + public static VarNamesCollector getVarNamesCollector() { + return getCurrentContext().varNamescollector; + } + + public static void setVarNamesCollector(VarNamesCollector varNamesCollector) { + getCurrentContext().varNamescollector = varNamesCollector; + } + + public static StructContext getStructContext() { + return getCurrentContext().structContext; + } + + public static void setStructContext(StructContext structContext) { + getCurrentContext().structContext = structContext; + } + + public static CounterContainer getCounterContainer() { + return getCurrentContext().counterContainer; + } + + public static void setCounterContainer(CounterContainer counterContainer) { + getCurrentContext().counterContainer = counterContainer; + } + + public static ClassesProcessor getClassProcessor() { + return getCurrentContext().classProcessor; + } + + public static void setClassProcessor(ClassesProcessor classProcessor) { + getCurrentContext().classProcessor = classProcessor; + } + + public static PoolInterceptor getPoolInterceptor() { + return getCurrentContext().poolInterceptor; + } + + public static void setPoolInterceptor(PoolInterceptor poolinterceptor) { + getCurrentContext().poolInterceptor = poolinterceptor; + } + + public static IFernflowerLogger getLogger() { + return getCurrentContext().logger; + } + + public static void setLogger(IFernflowerLogger logger) { + if (logger != null) { + String level = (String)getProperty(IFernflowerPreferences.LOG_LEVEL); + if (level != null) { + try { + logger.setSeverity(IFernflowerLogger.Severity.valueOf(level.toUpperCase(Locale.US))); + } + catch (IllegalArgumentException ignore) { } + } + } + getCurrentContext().logger = logger; + } + + public static String getNewLineSeparator() { + return getOption(IFernflowerPreferences.NEW_LINE_SEPARATOR) ? + IFernflowerPreferences.LINE_SEPARATOR_LIN : IFernflowerPreferences.LINE_SEPARATOR_WIN; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/EnumProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/EnumProcessor.java new file mode 100644 index 000000000000..be408e8bbc3b --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/EnumProcessor.java @@ -0,0 +1,118 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.main.rels.ClassWrapper; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.InvocationExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +public class EnumProcessor { + + public static void clearEnum(ClassWrapper wrapper) { + StructClass cl = wrapper.getClassStruct(); + + // hide values/valueOf methods and super() invocations + for (MethodWrapper method : wrapper.getMethods()) { + StructMethod mt = method.methodStruct; + String name = mt.getName(); + String descriptor = mt.getDescriptor(); + + if ("values".equals(name)) { + if (descriptor.equals("()[L" + cl.qualifiedName + ";")) { + wrapper.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(name, descriptor)); + } + } + else if ("valueOf".equals(name)) { + if (descriptor.equals("(Ljava/lang/String;)L" + cl.qualifiedName + ";")) { + wrapper.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(name, descriptor)); + } + } + else if ("<init>".equals(name)) { + Statement firstData = findFirstData(method.root); + if (firstData != null && !firstData.getExprents().isEmpty()) { + Exprent exprent = firstData.getExprents().get(0); + if (exprent.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent invexpr = (InvocationExprent)exprent; + if (isInvocationSuperConstructor(invexpr, method, wrapper)) { + firstData.getExprents().remove(0); + } + } + } + } + } + + // hide synthetic fields of enum and it's constants + for (StructField fd : cl.getFields()) { + String descriptor = fd.getDescriptor(); + if (fd.isSynthetic() && descriptor.equals("[L" + cl.qualifiedName + ";")) { + wrapper.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(fd.getName(), descriptor)); + } + } + } + + // FIXME: move to a util class (see also InitializerProcessor) + private static Statement findFirstData(Statement stat) { + + if (stat.getExprents() != null) { + return stat; + } + else { + if (stat.isLabeled()) { + return null; + } + + switch (stat.type) { + case Statement.TYPE_SEQUENCE: + case Statement.TYPE_IF: + case Statement.TYPE_ROOT: + case Statement.TYPE_SWITCH: + case Statement.TYPE_SYNCRONIZED: + return findFirstData(stat.getFirst()); + default: + return null; + } + } + } + + // FIXME: move to util class (see also InitializerProcessor) + private static boolean isInvocationSuperConstructor(InvocationExprent inv, MethodWrapper meth, ClassWrapper wrapper) { + + if (inv.getFunctype() == InvocationExprent.TYP_INIT) { + if (inv.getInstance().type == Exprent.EXPRENT_VAR) { + VarExprent instvar = (VarExprent)inv.getInstance(); + VarVersionPaar varpaar = new VarVersionPaar(instvar); + + String classname = meth.varproc.getThisvars().get(varpaar); + + if (classname != null) { // any this instance. TODO: Restrict to current class? + if (!wrapper.getClassStruct().qualifiedName.equals(inv.getClassname())) { + return true; + } + } + } + } + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/Fernflower.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/Fernflower.java new file mode 100644 index 000000000000..62b8ee4f61f2 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/Fernflower.java @@ -0,0 +1,94 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IResultSaver; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.renamer.IdentifierConverter; +import org.jetbrains.java.decompiler.struct.IDecompiledData; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructContext; +import org.jetbrains.java.decompiler.struct.lazy.LazyLoader; + +import java.util.Map; + +public class Fernflower implements IDecompiledData { + + private StructContext structContext; + private ClassesProcessor classesProcessor; + + public Fernflower(IBytecodeProvider provider, IResultSaver saver, Map<String, Object> options, IFernflowerLogger logger) { + structContext = new StructContext(saver, this, new LazyLoader(provider)); + DecompilerContext.initContext(options); + DecompilerContext.setCounterContainer(new CounterContainer()); + DecompilerContext.setLogger(logger); + } + + public void decompileContext() { + if (DecompilerContext.getOption(IFernflowerPreferences.RENAME_ENTITIES)) { + new IdentifierConverter().rename(structContext); + } + + classesProcessor = new ClassesProcessor(structContext); + + DecompilerContext.setClassProcessor(classesProcessor); + DecompilerContext.setStructContext(structContext); + + structContext.saveContext(); + } + + public void clearContext() { + DecompilerContext.setCurrentContext(null); + } + + public StructContext getStructContext() { + return structContext; + } + + @Override + public String getClassEntryName(StructClass cl, String entryName) { + ClassNode node = classesProcessor.getMapRootClasses().get(cl.qualifiedName); + if (node.type != ClassNode.CLASS_ROOT) { + return null; + } + else { + if (DecompilerContext.getOption(IFernflowerPreferences.RENAME_ENTITIES)) { + String simple_classname = cl.qualifiedName.substring(cl.qualifiedName.lastIndexOf('/') + 1); + return entryName.substring(0, entryName.lastIndexOf('/') + 1) + simple_classname + ".java"; + } + else { + return entryName.substring(0, entryName.lastIndexOf(".class")) + ".java"; + } + } + } + + @Override + public String getClassContent(StructClass cl) { + try { + StringBuilder buffer = new StringBuilder(); + classesProcessor.writeClass(cl, buffer); + return buffer.toString(); + } + catch (Throwable ex) { + DecompilerContext.getLogger().writeMessage("Class " + cl.qualifiedName + " couldn't be fully decompiled.", ex); + return null; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/InitializerProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/InitializerProcessor.java new file mode 100644 index 000000000000..aabea15d1ef2 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/InitializerProcessor.java @@ -0,0 +1,323 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.main.rels.ClassWrapper; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class InitializerProcessor { + + public static void extractInitializers(ClassWrapper wrapper) { + + MethodWrapper meth = wrapper.getMethodWrapper("<clinit>", "()V"); + if (meth != null && meth.root != null) { // successfully decompiled static constructor + extractStaticInitializers(wrapper, meth); + } + + extractDynamicInitializers(wrapper); + + // required e.g. if anonymous class is being decompiled as a standard one. + // This can happen if InnerClasses attributes are erased + liftConstructor(wrapper); + + if (DecompilerContext.getOption(IFernflowerPreferences.HIDE_EMPTY_SUPER)) { + hideEmptySuper(wrapper); + } + } + + + private static void liftConstructor(ClassWrapper wrapper) { + + for (MethodWrapper meth : wrapper.getMethods()) { + if ("<init>".equals(meth.methodStruct.getName()) && meth.root != null) { + Statement firstdata = findFirstData(meth.root); + if (firstdata == null) { + return; + } + + + int index = 0; + List<Exprent> lstExprents = firstdata.getExprents(); + + for (Exprent exprent : lstExprents) { + + int action = 0; + + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asexpr = (AssignmentExprent)exprent; + if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD && asexpr.getRight().type == Exprent.EXPRENT_VAR) { + FieldExprent fexpr = (FieldExprent)asexpr.getLeft(); + if (fexpr.getClassname().equals(wrapper.getClassStruct().qualifiedName)) { + StructField structField = wrapper.getClassStruct().getField(fexpr.getName(), fexpr.getDescriptor().descriptorString); + if (structField != null && structField.hasModifier(CodeConstants.ACC_FINAL)) { + action = 1; + } + } + } + } + else if (index > 0 && exprent.type == Exprent.EXPRENT_INVOCATION && + isInvocationInitConstructor((InvocationExprent)exprent, meth, wrapper, true)) { + // this() or super() + lstExprents.add(0, lstExprents.remove(index)); + action = 2; + } + + if (action != 1) { + break; + } + + index++; + } + } + } + } + + + private static void hideEmptySuper(ClassWrapper wrapper) { + + for (MethodWrapper meth : wrapper.getMethods()) { + if ("<init>".equals(meth.methodStruct.getName()) && meth.root != null) { + Statement firstdata = findFirstData(meth.root); + if (firstdata == null || firstdata.getExprents().isEmpty()) { + return; + } + + Exprent exprent = firstdata.getExprents().get(0); + if (exprent.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent invexpr = (InvocationExprent)exprent; + if (isInvocationInitConstructor(invexpr, meth, wrapper, false) && invexpr.getLstParameters().isEmpty()) { + firstdata.getExprents().remove(0); + } + } + } + } + } + + private static void extractStaticInitializers(ClassWrapper wrapper, MethodWrapper meth) { + + RootStatement root = meth.root; + StructClass cl = wrapper.getClassStruct(); + + Statement firstdata = findFirstData(root); + if (firstdata != null) { + while (!firstdata.getExprents().isEmpty()) { + Exprent exprent = firstdata.getExprents().get(0); + + boolean found = false; + + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asexpr = (AssignmentExprent)exprent; + if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD) { + FieldExprent fexpr = (FieldExprent)asexpr.getLeft(); + if (fexpr.isStatic() && fexpr.getClassname().equals(cl.qualifiedName) && + cl.hasField(fexpr.getName(), fexpr.getDescriptor().descriptorString)) { + + if (isExprentIndependent(asexpr.getRight(), meth)) { + + String keyField = InterpreterUtil.makeUniqueKey(fexpr.getName(), fexpr.getDescriptor().descriptorString); + if (!wrapper.getStaticFieldInitializers().containsKey(keyField)) { + wrapper.getStaticFieldInitializers().addWithKey(asexpr.getRight(), keyField); + firstdata.getExprents().remove(0); + found = true; + } + } + } + } + } + + if (!found) { + break; + } + } + } + } + + private static void extractDynamicInitializers(ClassWrapper wrapper) { + + StructClass cl = wrapper.getClassStruct(); + + boolean isAnonymous = DecompilerContext.getClassProcessor().getMapRootClasses().get(cl.qualifiedName).type == ClassNode.CLASS_ANONYMOUS; + + List<List<Exprent>> lstFirst = new ArrayList<List<Exprent>>(); + List<MethodWrapper> lstMethWrappers = new ArrayList<MethodWrapper>(); + + for (MethodWrapper meth : wrapper.getMethods()) { + if ("<init>".equals(meth.methodStruct.getName()) && meth.root != null) { // successfully decompiled constructor + Statement firstdata = findFirstData(meth.root); + if (firstdata == null || firstdata.getExprents().isEmpty()) { + return; + } + lstFirst.add(firstdata.getExprents()); + lstMethWrappers.add(meth); + + Exprent exprent = firstdata.getExprents().get(0); + if (!isAnonymous) { // FIXME: doesn't make sense + if (exprent.type != Exprent.EXPRENT_INVOCATION || + !isInvocationInitConstructor((InvocationExprent)exprent, meth, wrapper, false)) { + return; + } + } + } + } + + if (lstFirst.isEmpty()) { + return; + } + + while (true) { + + String fieldWithDescr = null; + Exprent value = null; + + for (int i = 0; i < lstFirst.size(); i++) { + + List<Exprent> lst = lstFirst.get(i); + + if (lst.size() < (isAnonymous ? 1 : 2)) { + return; + } + + Exprent exprent = lst.get(isAnonymous ? 0 : 1); + + boolean found = false; + + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asexpr = (AssignmentExprent)exprent; + if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD) { + FieldExprent fexpr = (FieldExprent)asexpr.getLeft(); + if (!fexpr.isStatic() && fexpr.getClassname().equals(cl.qualifiedName) && + cl.hasField(fexpr.getName(), fexpr + .getDescriptor().descriptorString)) { // check for the physical existence of the field. Could be defined in a superclass. + + if (isExprentIndependent(asexpr.getRight(), lstMethWrappers.get(i))) { + String fieldKey = InterpreterUtil.makeUniqueKey(fexpr.getName(), fexpr.getDescriptor().descriptorString); + if (fieldWithDescr == null) { + fieldWithDescr = fieldKey; + value = asexpr.getRight(); + } + else { + if (!fieldWithDescr.equals(fieldKey) || + !value.equals(asexpr.getRight())) { + return; + } + } + found = true; + } + } + } + } + + if (!found) { + return; + } + } + + if (!wrapper.getDynamicFieldInitializers().containsKey(fieldWithDescr)) { + wrapper.getDynamicFieldInitializers().addWithKey(value, fieldWithDescr); + + for (List<Exprent> lst : lstFirst) { + lst.remove(isAnonymous ? 0 : 1); + } + } + else { + return; + } + } + } + + private static boolean isExprentIndependent(Exprent exprent, MethodWrapper meth) { + + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + switch (expr.type) { + case Exprent.EXPRENT_VAR: + VarVersionPaar varpaar = new VarVersionPaar((VarExprent)expr); + if (!meth.varproc.getExternvars().contains(varpaar)) { + String varname = meth.varproc.getVarName(varpaar); + + if (!varname.equals("this") && !varname.endsWith(".this")) { // FIXME: remove direct comparison with strings + return false; + } + } + break; + case Exprent.EXPRENT_FIELD: + return false; + } + } + + return true; + } + + + private static Statement findFirstData(Statement stat) { + + if (stat.getExprents() != null) { + return stat; + } + else { + if (stat.isLabeled()) { // FIXME: Why?? + return null; + } + + switch (stat.type) { + case Statement.TYPE_SEQUENCE: + case Statement.TYPE_IF: + case Statement.TYPE_ROOT: + case Statement.TYPE_SWITCH: + case Statement.TYPE_SYNCRONIZED: + return findFirstData(stat.getFirst()); + default: + return null; + } + } + } + + private static boolean isInvocationInitConstructor(InvocationExprent inv, MethodWrapper meth, ClassWrapper wrapper, boolean withThis) { + + if (inv.getFunctype() == InvocationExprent.TYP_INIT) { + if (inv.getInstance().type == Exprent.EXPRENT_VAR) { + VarExprent instvar = (VarExprent)inv.getInstance(); + VarVersionPaar varpaar = new VarVersionPaar(instvar); + + String classname = meth.varproc.getThisvars().get(varpaar); + + if (classname != null) { // any this instance. TODO: Restrict to current class? + if (withThis || !wrapper.getClassStruct().qualifiedName.equals(inv.getClassname())) { + return true; + } + } + } + } + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/CounterContainer.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/CounterContainer.java new file mode 100644 index 000000000000..04d50a7512e1 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/CounterContainer.java @@ -0,0 +1,37 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.collectors; + +public class CounterContainer { + + public static final int STATEMENT_COUNTER = 0; + public static final int EXPRENT_COUNTER = 1; + public static final int VAR_COUNTER = 2; + + private int[] values = new int[]{1, 1, 1}; + + public void setCounter(int counter, int value) { + values[counter] = value; + } + + public int getCounter(int counter) { + return values[counter]; + } + + public int getCounterAndIncrement(int counter) { + return values[counter]++; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java new file mode 100644 index 000000000000..9b6f7edb0019 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/ImportCollector.java @@ -0,0 +1,148 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.collectors; + +import org.jetbrains.java.decompiler.main.ClassesProcessor; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.struct.StructContext; + +import java.util.*; +import java.util.Map.Entry; + + +public class ImportCollector { + + private static final String JAVA_LANG_PACKAGE = "java.lang"; + + private Map<String, String> mapSimpleNames = new HashMap<String, String>(); + private Set<String> setNotImportedNames = new HashSet<String>(); + private String currentPackageSlash = ""; + private String currentPackagePoint = ""; + + public ImportCollector(ClassNode root) { + + String clname = root.classStruct.qualifiedName; + int index = clname.lastIndexOf("/"); + if (index >= 0) { + currentPackageSlash = clname.substring(0, index); + currentPackagePoint = currentPackageSlash.replace('/', '.'); + currentPackageSlash += "/"; + } + } + + public String getShortName(String fullname) { + return getShortName(fullname, true); + } + + public String getShortName(String fullname, boolean imported) { + + ClassesProcessor clproc = DecompilerContext.getClassProcessor(); + ClassNode node = clproc.getMapRootClasses().get(fullname.replace('.', '/')); + + String retname = null; + + if (node != null && node.classStruct.isOwn()) { + + retname = node.simpleName; + + while (node.parent != null && node.type == ClassNode.CLASS_MEMBER) { + retname = node.parent.simpleName + "." + retname; + node = node.parent; + } + + if (node.type == ClassNode.CLASS_ROOT) { + fullname = node.classStruct.qualifiedName; + fullname = fullname.replace('/', '.'); + } + else { + return retname; + } + } + else { + fullname = fullname.replace('$', '.'); + } + + String nshort = fullname; + String npackage = ""; + + int lastpoint = fullname.lastIndexOf("."); + + if (lastpoint >= 0) { + nshort = fullname.substring(lastpoint + 1); + npackage = fullname.substring(0, lastpoint); + } + + StructContext context = DecompilerContext.getStructContext(); + + boolean existsDefaultClass = (context.getClass(currentPackageSlash + nshort) != null + && !npackage.equals(currentPackagePoint)) // current package + || (context.getClass(nshort) != null); // default package + + if (existsDefaultClass || + (mapSimpleNames.containsKey(nshort) && !npackage.equals(mapSimpleNames.get(nshort)))) { + return fullname; + } + else if (!mapSimpleNames.containsKey(nshort)) { + mapSimpleNames.put(nshort, npackage); + + if (!imported) { + setNotImportedNames.add(nshort); + } + } + + return retname == null ? nshort : retname; + } + + public boolean writeImports(StringBuilder buffer) { + List<String> imports = packImports(); + + for (String s : imports) { + buffer.append("import "); + buffer.append(s); + buffer.append(";"); + buffer.append(DecompilerContext.getNewLineSeparator()); + } + + return imports.size() > 0; + } + + private List<String> packImports() { + List<Entry<String, String>> lst = new ArrayList<Entry<String, String>>(mapSimpleNames.entrySet()); + + Collections.sort(lst, new Comparator<Entry<String, String>>() { + public int compare(Entry<String, String> par0, Entry<String, String> par1) { + int res = par0.getValue().compareTo(par1.getValue()); + if (res == 0) { + res = par0.getKey().compareTo(par1.getKey()); + } + return res; + } + }); + + List<String> res = new ArrayList<String>(); + for (Entry<String, String> ent : lst) { + // exclude a current class or one of the nested ones, java.lang and empty packages + if (!setNotImportedNames.contains(ent.getKey()) && + !JAVA_LANG_PACKAGE.equals(ent.getValue()) && + !ent.getValue().isEmpty()) { + res.add(ent.getValue() + "." + ent.getKey()); + } + } + + return res; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/VarNamesCollector.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/VarNamesCollector.java new file mode 100644 index 000000000000..dfde971ac628 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/collectors/VarNamesCollector.java @@ -0,0 +1,51 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.collectors; + +import java.util.HashSet; + +public class VarNamesCollector { + + private HashSet<String> usedNames = new HashSet<String>(); + + public VarNamesCollector() { + } + + public VarNamesCollector(HashSet<String> setNames) { + usedNames.addAll(setNames); + } + + public void addName(String value) { + usedNames.add(value); + } + + public String getFreeName(int index) { + return getFreeName("var" + index); + } + + public String getFreeName(String proposition) { + + while (usedNames.contains(proposition)) { + proposition += "x"; + } + usedNames.add(proposition); + return proposition; + } + + public HashSet<String> getUsedNames() { + return usedNames; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/BaseDecompiler.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/BaseDecompiler.java new file mode 100644 index 000000000000..07b857838e5a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/BaseDecompiler.java @@ -0,0 +1,47 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.decompiler; + +import org.jetbrains.java.decompiler.main.Fernflower; +import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IResultSaver; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +public class BaseDecompiler { + + private final Fernflower fernflower; + + public BaseDecompiler(IBytecodeProvider provider, IResultSaver saver, Map<String, Object> options, IFernflowerLogger logger) { + fernflower = new Fernflower(provider, saver, options, logger); + } + + public void addSpace(File file, boolean isOwn) throws IOException { + fernflower.getStructContext().addSpace(file, isOwn); + } + + public void decompileContext() { + try { + fernflower.decompileContext(); + } + finally { + fernflower.clearContext(); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/ConsoleDecompiler.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/ConsoleDecompiler.java new file mode 100644 index 000000000000..a486d9f83ee1 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/ConsoleDecompiler.java @@ -0,0 +1,299 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.decompiler; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.Fernflower; +import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IResultSaver; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.io.*; +import java.util.*; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +public class ConsoleDecompiler implements IBytecodeProvider, IResultSaver { + + @SuppressWarnings("UseOfSystemOutOrSystemErr") + public static void main(String[] args) { + if (args.length < 2) { + System.out.println( + "Usage: java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>\n" + + "Example: java -jar fernflower.jar -dgs=true c:\\my\\source\\ c:\\my.jar d:\\decompiled\\"); + return; + } + + Map<String, Object> mapOptions = new HashMap<String, Object>(); + List<String> lstSources = new ArrayList<String>(); + List<String> lstLibraries = new ArrayList<String>(); + + boolean isOption = true; + for (int i = 0; i < args.length - 1; ++i) { // last parameter - destination + String arg = args[i]; + + if (isOption && arg.startsWith("-") && + arg.length() > 5 && arg.charAt(4) == '=') { + String value = arg.substring(5).toUpperCase(Locale.US); + if ("TRUE".equals(value)) { + value = "1"; + } + else if ("FALSE".equals(value)) { + value = "0"; + } + + mapOptions.put(arg.substring(1, 4), value); + } + else { + isOption = false; + + if (arg.startsWith("-e=")) { + lstLibraries.add(arg.substring(3)); + } + else { + lstSources.add(arg); + } + } + } + + if (lstSources.isEmpty()) { + System.out.println("error: no sources given"); + return; + } + + File destination = new File(args[args.length - 1]); + if (!destination.isDirectory()) { + System.out.println("error: destination '" + destination + "' is not a directory"); + return; + } + + PrintStreamLogger logger = new PrintStreamLogger(System.out); + ConsoleDecompiler decompiler = new ConsoleDecompiler(destination, mapOptions, logger); + + for (String source : lstSources) { + decompiler.addSpace(new File(source), true); + } + for (String library : lstLibraries) { + decompiler.addSpace(new File(library), false); + } + + decompiler.decompileContext(); + } + + // ******************************************************************* + // Implementation + // ******************************************************************* + + private final File root; + private final Fernflower fernflower; + private Map<String, ZipOutputStream> mapArchiveStreams = new HashMap<String, ZipOutputStream>(); + private Map<String, Set<String>> mapArchiveEntries = new HashMap<String, Set<String>>(); + + @SuppressWarnings("UseOfSystemOutOrSystemErr") + public ConsoleDecompiler(File destination, Map<String, Object> options) { + this(destination, options, new PrintStreamLogger(System.out)); + } + + protected ConsoleDecompiler(File destination, Map<String, Object> options, IFernflowerLogger logger) { + root = destination; + fernflower = new Fernflower(this, this, options, logger); + } + + public void addSpace(File file, boolean isOwn) { + fernflower.getStructContext().addSpace(file, isOwn); + } + + public void decompileContext() { + try { + fernflower.decompileContext(); + } + finally { + fernflower.clearContext(); + } + } + + // ******************************************************************* + // Interface IBytecodeProvider + // ******************************************************************* + + @Override + public byte[] getBytecode(String externalPath, String internalPath) throws IOException { + File file = new File(externalPath); + if (internalPath == null) { + return InterpreterUtil.getBytes(file); + } + else { + ZipFile archive = new ZipFile(file); + try { + ZipEntry entry = archive.getEntry(internalPath); + if (entry == null) { + throw new IOException("Entry not found: " + internalPath); + } + return InterpreterUtil.getBytes(archive, entry); + } + finally { + archive.close(); + } + } + } + + // ******************************************************************* + // Interface IResultSaver + // ******************************************************************* + + private String getAbsolutePath(String path) { + return new File(root, path).getAbsolutePath(); + } + + @Override + public void saveFolder(String path) { + File dir = new File(getAbsolutePath(path)); + if (!(dir.mkdirs() || dir.isDirectory())) { + throw new RuntimeException("Cannot create directory " + dir); + } + } + + @Override + public void copyFile(String source, String path, String entryName) { + try { + InterpreterUtil.copyFile(new File(source), new File(getAbsolutePath(path), entryName)); + } + catch (IOException ex) { + DecompilerContext.getLogger().writeMessage("Cannot copy " + source + " to " + entryName, ex); + } + } + + @Override + public void saveClassFile(String path, String qualifiedName, String entryName, String content) { + File file = new File(getAbsolutePath(path), entryName); + try { + Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF8"); + try { + out.write(content); + } + finally { + out.close(); + } + } + catch (IOException ex) { + DecompilerContext.getLogger().writeMessage("Cannot write class file " + file, ex); + } + } + + @Override + public void createArchive(String path, String archiveName, Manifest manifest) { + File file = new File(getAbsolutePath(path), archiveName); + try { + if (!(file.createNewFile() || file.isFile())) { + throw new IOException("Cannot create file " + file); + } + + FileOutputStream fileStream = new FileOutputStream(file); + @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") + ZipOutputStream zipStream = manifest != null ? new JarOutputStream(fileStream, manifest) : new ZipOutputStream(fileStream); + mapArchiveStreams.put(file.getPath(), zipStream); + } + catch (IOException ex) { + DecompilerContext.getLogger().writeMessage("Cannot create archive " + file, ex); + } + } + + @Override + public void saveDirEntry(String path, String archiveName, String entryName) { + saveClassEntry(path, archiveName, null, entryName, null); + } + + @Override + public void copyEntry(String source, String path, String archiveName, String entryName) { + String file = new File(getAbsolutePath(path), archiveName).getPath(); + + if (!checkEntry(entryName, file)) { + return; + } + + try { + ZipFile srcArchive = new ZipFile(new File(source)); + try { + ZipEntry entry = srcArchive.getEntry(entryName); + if (entry != null) { + InputStream in = srcArchive.getInputStream(entry); + ZipOutputStream out = mapArchiveStreams.get(file); + out.putNextEntry(new ZipEntry(entryName)); + InterpreterUtil.copyStream(in, out); + in.close(); + } + } + finally { + srcArchive.close(); + } + } + catch (IOException ex) { + String message = "Cannot copy entry " + entryName + " from " + source + " to " + file; + DecompilerContext.getLogger().writeMessage(message, ex); + } + } + + @Override + public void saveClassEntry(String path, String archiveName, String qualifiedName, String entryName, String content) { + String file = new File(getAbsolutePath(path), archiveName).getPath(); + + if (!checkEntry(entryName, file)) { + return; + } + + try { + ZipOutputStream out = mapArchiveStreams.get(file); + out.putNextEntry(new ZipEntry(entryName)); + if (content != null) { + out.write(content.getBytes("UTF-8")); + } + } + catch (IOException ex) { + String message = "Cannot write entry " + entryName + " to " + file; + DecompilerContext.getLogger().writeMessage(message, ex); + } + } + + private boolean checkEntry(String entryName, String file) { + Set<String> set = mapArchiveEntries.get(file); + if (set == null) { + mapArchiveEntries.put(file, set = new HashSet<String>()); + } + + boolean added = set.add(entryName); + if (!added) { + String message = "Zip entry " + entryName + " already exists in " + file; + DecompilerContext.getLogger().writeMessage(message, IFernflowerLogger.Severity.WARN); + } + return added; + } + + @Override + public void closeArchive(String path, String archiveName) { + String file = new File(getAbsolutePath(path), archiveName).getPath(); + try { + mapArchiveEntries.remove(file); + mapArchiveStreams.remove(file).close(); + } + catch (IOException ex) { + DecompilerContext.getLogger().writeMessage("Cannot close " + file, IFernflowerLogger.Severity.WARN); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/PrintStreamLogger.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/PrintStreamLogger.java new file mode 100644 index 000000000000..7bbcc192fcd3 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/decompiler/PrintStreamLogger.java @@ -0,0 +1,80 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.decompiler; + +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.io.PrintStream; + +public class PrintStreamLogger extends IFernflowerLogger { + + private final PrintStream stream; + private int indent; + + public PrintStreamLogger(PrintStream printStream) { + stream = printStream; + indent = 0; + } + + @Override + public void writeMessage(String message, Severity severity) { + if (accepts(severity)) { + stream.println(InterpreterUtil.getIndentString(indent) + severity.name() + ": " + message); + } + } + + @Override + public void writeMessage(String message, Throwable t) { + writeMessage(message, Severity.ERROR); + if (accepts(Severity.ERROR)) { + t.printStackTrace(stream); + } + } + + @Override + public void startClass(String className) { + writeMessage("Processing class " + className + " ...", Severity.INFO); + ++indent; + } + + @Override + public void endClass() { + --indent; + writeMessage("... proceeded.", Severity.INFO); + } + + @Override + public void startWriteClass(String className) { + writeMessage("Writing class " + className + " ...", Severity.INFO); + ++indent; + } + + @Override + public void endWriteClass() { + --indent; + writeMessage("... written.", Severity.INFO); + } + + @Override + public void startMethod(String methodName) { + writeMessage("Processing method " + methodName + " ...", Severity.INFO); + } + + public void endMethod() { + writeMessage("... proceeded.", Severity.INFO); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IBytecodeProvider.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IBytecodeProvider.java new file mode 100644 index 000000000000..adf32707379e --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IBytecodeProvider.java @@ -0,0 +1,22 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.extern; + +import java.io.IOException; + +public interface IBytecodeProvider { + byte[] getBytecode(String externalPath, String internalPath) throws IOException; +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IFernflowerLogger.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IFernflowerLogger.java new file mode 100644 index 000000000000..65b2c6da8641 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IFernflowerLogger.java @@ -0,0 +1,49 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.extern; + +public abstract class IFernflowerLogger { + + public enum Severity { + TRACE, INFO, WARN, ERROR + } + + private Severity severity = Severity.INFO; + + public boolean accepts(Severity severity) { + return severity.ordinal() >= this.severity.ordinal(); + } + + public void setSeverity(Severity severity) { + this.severity = severity; + } + + public abstract void writeMessage(String message, Severity severity); + + public abstract void writeMessage(String message, Throwable t); + + public void startClass(String className) { } + + public void endClass() { } + + public void startWriteClass(String className) { } + + public void endWriteClass() { } + + public void startMethod(String methodName) { } + + public void endMethod() { } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IFernflowerPreferences.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IFernflowerPreferences.java new file mode 100644 index 000000000000..69dd218a0340 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IFernflowerPreferences.java @@ -0,0 +1,86 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.extern; + +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public interface IFernflowerPreferences { + String REMOVE_BRIDGE = "rbr"; + String REMOVE_SYNTHETIC = "rsy"; + String DECOMPILE_INNER = "din"; + String DECOMPILE_CLASS_1_4 = "dc4"; + String DECOMPILE_ASSERTIONS = "das"; + String HIDE_EMPTY_SUPER = "hes"; + String HIDE_DEFAULT_CONSTRUCTOR = "hdc"; + String DECOMPILE_GENERIC_SIGNATURES = "dgs"; + String NO_EXCEPTIONS_RETURN = "ner"; + String DECOMPILE_ENUM = "den"; + String REMOVE_GET_CLASS_NEW = "rgn"; + String LITERALS_AS_IS = "lit"; + String BOOLEAN_TRUE_ONE = "bto"; + String ASCII_STRING_CHARACTERS = "asc"; + String SYNTHETIC_NOT_SET = "nns"; + String UNDEFINED_PARAM_TYPE_OBJECT = "uto"; + String USE_DEBUG_VAR_NAMES = "udv"; + String REMOVE_EMPTY_RANGES = "rer"; + String FINALLY_DEINLINE = "fdi"; + String IDEA_NOT_NULL_ANNOTATION = "inn"; + String LAMBDA_TO_ANONYMOUS_CLASS = "lac"; + + String LOG_LEVEL = "log"; + String MAX_PROCESSING_METHOD = "mpm"; + String RENAME_ENTITIES = "ren"; + String USER_RENAMER_CLASS = "urc"; + String NEW_LINE_SEPARATOR = "nls"; + String INDENT_STRING = "ind"; + + String LINE_SEPARATOR_WIN = "\r\n"; + String LINE_SEPARATOR_LIN = "\n"; + + Map<String, Object> DEFAULTS = Collections.unmodifiableMap(new HashMap<String, Object>() {{ + put(REMOVE_BRIDGE, "1"); + put(REMOVE_SYNTHETIC, "0"); + put(DECOMPILE_INNER, "1"); + put(DECOMPILE_CLASS_1_4, "1"); + put(DECOMPILE_ASSERTIONS, "1"); + put(HIDE_EMPTY_SUPER, "1"); + put(HIDE_DEFAULT_CONSTRUCTOR, "1"); + put(DECOMPILE_GENERIC_SIGNATURES, "0"); + put(NO_EXCEPTIONS_RETURN, "1"); + put(DECOMPILE_ENUM, "1"); + put(REMOVE_GET_CLASS_NEW, "1"); + put(LITERALS_AS_IS, "0"); + put(BOOLEAN_TRUE_ONE, "1"); + put(ASCII_STRING_CHARACTERS, "0"); + put(SYNTHETIC_NOT_SET, "1"); + put(UNDEFINED_PARAM_TYPE_OBJECT, "1"); + put(USE_DEBUG_VAR_NAMES, "1"); + put(REMOVE_EMPTY_RANGES, "1"); + put(FINALLY_DEINLINE, "1"); + put(IDEA_NOT_NULL_ANNOTATION, "1"); + put(LAMBDA_TO_ANONYMOUS_CLASS, "0"); + + put(LOG_LEVEL, IFernflowerLogger.Severity.INFO.name()); + put(MAX_PROCESSING_METHOD, "0"); + put(RENAME_ENTITIES, "0"); + put(NEW_LINE_SEPARATOR, (InterpreterUtil.IS_WINDOWS ? "0" : "1")); + put(INDENT_STRING, " "); + }}); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IIdentifierRenamer.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IIdentifierRenamer.java new file mode 100644 index 000000000000..fc0971e10612 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IIdentifierRenamer.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.extern; + + +public interface IIdentifierRenamer { + + int ELEMENT_CLASS = 1; + + int ELEMENT_FIELD = 2; + + int ELEMENT_METHOD = 3; + + + boolean toBeRenamed(int element_type, String classname, String element, String descriptor); + + String getNextClassname(String fullname, String shortname); + + String getNextFieldname(String classname, String field, String descriptor); + + String getNextMethodname(String classname, String method, String descriptor); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IResultSaver.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IResultSaver.java new file mode 100644 index 000000000000..1e6a7d4262a5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/extern/IResultSaver.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.extern; + +import java.util.jar.Manifest; + +public interface IResultSaver { + void saveFolder(String path); + + void copyFile(String source, String path, String entryName); + + void saveClassFile(String path, String qualifiedName, String entryName, String content); + + void createArchive(String path, String archiveName, Manifest manifest); + + void saveDirEntry(String path, String archiveName, String entryName); + + void copyEntry(String source, String path, String archiveName, String entry); + + void saveClassEntry(String path, String archiveName, String qualifiedName, String entryName, String content); + + void closeArchive(String path, String archiveName); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/ClassWrapper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/ClassWrapper.java new file mode 100644 index 000000000000..4a321799bc4b --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/ClassWrapper.java @@ -0,0 +1,207 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.rels; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; +import org.jetbrains.java.decompiler.struct.attr.StructLocalVariableTableAttribute; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +public class ClassWrapper { + + private StructClass classStruct; + private Set<String> hiddenMembers = new HashSet<String>(); + private VBStyleCollection<Exprent, String> staticFieldInitializers = new VBStyleCollection<Exprent, String>(); + private VBStyleCollection<Exprent, String> dynamicFieldInitializers = new VBStyleCollection<Exprent, String>(); + private VBStyleCollection<MethodWrapper, String> methods = new VBStyleCollection<MethodWrapper, String>(); + + + public ClassWrapper(StructClass classStruct) { + this.classStruct = classStruct; + } + + public void init() throws IOException { + + DecompilerContext.setProperty(DecompilerContext.CURRENT_CLASS, classStruct); + + DecompilerContext.getLogger().startClass(classStruct.qualifiedName); + + // collect field names + HashSet<String> setFieldNames = new HashSet<String>(); + for (StructField fd : classStruct.getFields()) { + setFieldNames.add(fd.getName()); + } + + int maxsec = Integer.parseInt(DecompilerContext.getProperty(IFernflowerPreferences.MAX_PROCESSING_METHOD).toString()); + + for (StructMethod mt : classStruct.getMethods()) { + + DecompilerContext.getLogger().startMethod(mt.getName() + " " + mt.getDescriptor()); + + VarNamesCollector vc = new VarNamesCollector(); + DecompilerContext.setVarNamesCollector(vc); + + CounterContainer counter = new CounterContainer(); + DecompilerContext.setCounterContainer(counter); + + DecompilerContext.setProperty(DecompilerContext.CURRENT_METHOD, mt); + DecompilerContext.setProperty(DecompilerContext.CURRENT_METHOD_DESCRIPTOR, MethodDescriptor.parseDescriptor(mt.getDescriptor())); + + VarProcessor varproc = new VarProcessor(); + DecompilerContext.setProperty(DecompilerContext.CURRENT_VAR_PROCESSOR, varproc); + + RootStatement root = null; + + boolean isError = false; + + try { + if (mt.containsCode()) { + + if (maxsec == 0) { // blocking wait + root = MethodProcessorThread.codeToJava(mt, varproc); + } + else { + MethodProcessorThread mtproc = new MethodProcessorThread(mt, varproc, DecompilerContext.getCurrentContext()); + Thread mtthread = new Thread(mtproc); + long stopAt = System.currentTimeMillis() + maxsec * 1000; + + mtthread.start(); + + while (mtthread.isAlive()) { + + synchronized (mtproc.lock) { + mtproc.lock.wait(100); + } + + if (System.currentTimeMillis() >= stopAt) { + String message = "Processing time limit exceeded for method " + mt.getName() + ", execution interrupted."; + DecompilerContext.getLogger().writeMessage(message, IFernflowerLogger.Severity.ERROR); + killThread(mtthread); + isError = true; + break; + } + } + + if (!isError) { + root = mtproc.getResult(); + } + } + } + else { + boolean thisvar = !mt.hasModifier(CodeConstants.ACC_STATIC); + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + + int paramcount = 0; + if (thisvar) { + varproc.getThisvars().put(new VarVersionPaar(0, 0), classStruct.qualifiedName); + paramcount = 1; + } + paramcount += md.params.length; + + int varindex = 0; + for (int i = 0; i < paramcount; i++) { + varproc.setVarName(new VarVersionPaar(varindex, 0), vc.getFreeName(varindex)); + + if (thisvar) { + if (i == 0) { + varindex++; + } + else { + varindex += md.params[i - 1].stack_size; + } + } + else { + varindex += md.params[i].stack_size; + } + } + } + } + catch (Throwable ex) { + DecompilerContext.getLogger().writeMessage("Method " + mt.getName() + " " + mt.getDescriptor() + " couldn't be decompiled.", ex); + isError = true; + } + + MethodWrapper meth = new MethodWrapper(root, varproc, mt, counter); + meth.decompiledWithErrors = isError; + + methods.addWithKey(meth, InterpreterUtil.makeUniqueKey(mt.getName(), mt.getDescriptor())); + + // rename vars so that no one has the same name as a field + varproc.refreshVarNames(new VarNamesCollector(setFieldNames)); + + // if debug information present and should be used + if (DecompilerContext.getOption(IFernflowerPreferences.USE_DEBUG_VAR_NAMES)) { + StructLocalVariableTableAttribute attr = (StructLocalVariableTableAttribute)mt.getAttributes().getWithKey( + StructGeneralAttribute.ATTRIBUTE_LOCAL_VARIABLE_TABLE); + + if (attr != null) { + varproc.setDebugVarNames(attr.getMapVarNames()); + } + } + + DecompilerContext.getLogger().endMethod(); + } + + DecompilerContext.getLogger().endClass(); + } + + @SuppressWarnings("deprecation") + private static void killThread(Thread thread) { + thread.stop(); + } + + public MethodWrapper getMethodWrapper(String name, String descriptor) { + return methods.getWithKey(InterpreterUtil.makeUniqueKey(name, descriptor)); + } + + public StructClass getClassStruct() { + return classStruct; + } + + public VBStyleCollection<MethodWrapper, String> getMethods() { + return methods; + } + + public Set<String> getHiddenMembers() { + return hiddenMembers; + } + + public VBStyleCollection<Exprent, String> getStaticFieldInitializers() { + return staticFieldInitializers; + } + + public VBStyleCollection<Exprent, String> getDynamicFieldInitializers() { + return dynamicFieldInitializers; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/LambdaProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/LambdaProcessor.java new file mode 100644 index 000000000000..743ce1215381 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/LambdaProcessor.java @@ -0,0 +1,151 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.rels; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.code.InstructionSequence; +import org.jetbrains.java.decompiler.main.ClassesProcessor; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.attr.StructBootstrapMethodsAttribute; +import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; +import org.jetbrains.java.decompiler.struct.consts.LinkConstant; +import org.jetbrains.java.decompiler.struct.consts.PooledConstant; +import org.jetbrains.java.decompiler.struct.consts.PrimitiveConstant; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.io.IOException; +import java.util.*; + +public class LambdaProcessor { + + private static final String JAVAC_LAMBDA_CLASS = "java/lang/invoke/LambdaMetafactory"; + private static final String JAVAC_LAMBDA_METHOD = "metafactory"; + private static final String JAVAC_LAMBDA_METHOD_DESCRIPTOR = + "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"; + + public void processClass(ClassNode node) throws IOException { + + for (ClassNode child : node.nested) { + processClass(child); + } + + if (node.nested.isEmpty()) { + hasLambda(node); + } + } + + public boolean hasLambda(ClassNode node) throws IOException { + + ClassesProcessor clprocessor = DecompilerContext.getClassProcessor(); + StructClass cl = node.classStruct; + + if (cl.getBytecodeVersion() < CodeConstants.BYTECODE_JAVA_8) { // lamda beginning with Java 8 + return false; + } + + StructBootstrapMethodsAttribute bootstrap = + (StructBootstrapMethodsAttribute)cl.getAttributes().getWithKey(StructGeneralAttribute.ATTRIBUTE_BOOTSTRAP_METHODS); + if (bootstrap == null || bootstrap.getMethodsNumber() == 0) { + return false; // no bootstrap constants in pool + } + + Set<Integer> lambda_methods = new HashSet<Integer>(); + + // find lambda bootstrap constants + for (int i = 0; i < bootstrap.getMethodsNumber(); ++i) { + LinkConstant method_ref = bootstrap.getMethodReference(i); // method handle + + if (JAVAC_LAMBDA_CLASS.equals(method_ref.classname) && + JAVAC_LAMBDA_METHOD.equals(method_ref.elementname) && + JAVAC_LAMBDA_METHOD_DESCRIPTOR + .equals(method_ref.descriptor)) { // check for javac lambda structure. FIXME: extend for Eclipse etc. at some point + lambda_methods.add(i); + } + } + + if (lambda_methods.isEmpty()) { + return false; // no lambda bootstrap constant found + } + + Map<String, String> mapMethodsLambda = new HashMap<String, String>(); + + // iterate over code and find invocations of bootstrap methods. Replace them with anonymous classes. + for (StructMethod mt : cl.getMethods()) { + mt.expandData(); + + InstructionSequence seq = mt.getInstructionSequence(); + if (seq != null && seq.length() > 0) { + int len = seq.length(); + + for (int i = 0; i < len; ++i) { + Instruction instr = seq.getInstr(i); + + if (instr.opcode == CodeConstants.opc_invokedynamic) { + LinkConstant invoke_dynamic = cl.getPool().getLinkConstant(instr.getOperand(0)); + + if (lambda_methods.contains(invoke_dynamic.index1)) { // lambda invocation found + + List<PooledConstant> bootstrap_arguments = bootstrap.getMethodArguments(invoke_dynamic.index1); + MethodDescriptor md = MethodDescriptor.parseDescriptor(invoke_dynamic.descriptor); + + String lambda_class_name = md.ret.value; + String lambda_method_name = invoke_dynamic.elementname; + String lambda_method_descriptor = ((PrimitiveConstant)bootstrap_arguments.get(2)).getString(); // method type + + LinkConstant content_method_handle = (LinkConstant)bootstrap_arguments.get(1); + + ClassNode node_lambda = new ClassNode(content_method_handle.classname, content_method_handle.elementname, + content_method_handle.descriptor, content_method_handle.index1, + lambda_class_name, lambda_method_name, lambda_method_descriptor, cl); + node_lambda.simpleName = cl.qualifiedName + "##Lambda_" + invoke_dynamic.index1 + "_" + invoke_dynamic.index2; + node_lambda.enclosingMethod = InterpreterUtil.makeUniqueKey(mt.getName(), mt.getDescriptor()); + + node.nested.add(node_lambda); + node_lambda.parent = node; + + clprocessor.getMapRootClasses().put(node_lambda.simpleName, node_lambda); + mapMethodsLambda.put(node_lambda.lambda_information.content_method_key, node_lambda.simpleName); + } + } + } + } + + mt.releaseResources(); + } + + // build class hierarchy on lambda + for (ClassNode nd : node.nested) { + if (nd.type == ClassNode.CLASS_LAMBDA) { + String parent_class_name = mapMethodsLambda.get(nd.enclosingMethod); + if (parent_class_name != null) { + ClassNode parent_class = clprocessor.getMapRootClasses().get(parent_class_name); + + parent_class.nested.add(nd); + nd.parent = parent_class; + } + } + } + + // FIXME: mixed hierarchy? + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/MethodProcessorThread.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/MethodProcessorThread.java new file mode 100644 index 000000000000..2f98cf82ce08 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/MethodProcessorThread.java @@ -0,0 +1,259 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.rels; + +import org.jetbrains.java.decompiler.code.InstructionSequence; +import org.jetbrains.java.decompiler.code.cfg.ControlFlowGraph; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.code.DeadCodeHelper; +import org.jetbrains.java.decompiler.modules.decompiler.*; +import org.jetbrains.java.decompiler.modules.decompiler.deobfuscator.ExceptionDeobfuscator; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructMethod; + +import java.io.IOException; + +public class MethodProcessorThread implements Runnable { + + public final Object lock = new Object(); + + private final StructMethod method; + private final VarProcessor varproc; + private final DecompilerContext parentContext; + + private volatile RootStatement root; + private volatile Throwable error; + + public MethodProcessorThread(StructMethod method, VarProcessor varproc, DecompilerContext parentContext) { + this.method = method; + this.varproc = varproc; + this.parentContext = parentContext; + } + + public void run() { + + DecompilerContext.setCurrentContext(parentContext); + + error = null; + root = null; + + try { + root = codeToJava(method, varproc); + + synchronized (lock) { + lock.notifyAll(); + } + } + catch (ThreadDeath ex) { + throw ex; + } + catch (Throwable ex) { + error = ex; + } + } + + public static RootStatement codeToJava(StructMethod mt, VarProcessor varproc) throws IOException { + + StructClass cl = mt.getClassStruct(); + + boolean isInitializer = "<clinit>".equals(mt.getName()); // for now static initializer only + + mt.expandData(); + InstructionSequence seq = mt.getInstructionSequence(); + ControlFlowGraph graph = new ControlFlowGraph(seq); + + // System.out.println(graph.toString()); + + + // if(mt.getName().endsWith("_getActiveServers")) { + // System.out.println(); + // } + + //DotExporter.toDotFile(graph, new File("c:\\Temp\\fern1.dot"), true); + + DeadCodeHelper.removeDeadBlocks(graph); + graph.inlineJsr(mt); + + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern4.dot"), true); + + // TODO: move to the start, before jsr inlining + DeadCodeHelper.connectDummyExitBlock(graph); + + DeadCodeHelper.removeGotos(graph); + ExceptionDeobfuscator.removeCircularRanges(graph); + //DeadCodeHelper.removeCircularRanges(graph); + + + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern3.dot"), true); + + ExceptionDeobfuscator.restorePopRanges(graph); + + if (DecompilerContext.getOption(IFernflowerPreferences.REMOVE_EMPTY_RANGES)) { + ExceptionDeobfuscator.removeEmptyRanges(graph); + } + + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern3.dot"), true); + + if (DecompilerContext.getOption(IFernflowerPreferences.NO_EXCEPTIONS_RETURN)) { + // special case: single return instruction outside of a protected range + DeadCodeHelper.incorporateValueReturns(graph); + } + + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern5.dot"), true); + + // ExceptionDeobfuscator.restorePopRanges(graph); + ExceptionDeobfuscator.insertEmptyExceptionHandlerBlocks(graph); + + DeadCodeHelper.mergeBasicBlocks(graph); + + DecompilerContext.getCounterContainer().setCounter(CounterContainer.VAR_COUNTER, mt.getLocalVariables()); + + //DotExporter.toDotFile(graph, new File("c:\\Temp\\fern3.dot"), true); + //System.out.println(graph.toString()); + + if (ExceptionDeobfuscator.hasObfuscatedExceptions(graph)) { + DecompilerContext.getLogger().writeMessage("Heavily obfuscated exception ranges found!", IFernflowerLogger.Severity.WARN); + } + + RootStatement root = DomHelper.parseGraph(graph); + + FinallyProcessor fproc = new FinallyProcessor(varproc); + while (fproc.iterateGraph(mt, root, graph)) { + + //DotExporter.toDotFile(graph, new File("c:\\Temp\\fern2.dot"), true); + //System.out.println(graph.toString()); + //System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + root = DomHelper.parseGraph(graph); + } + + // remove synchronized exception handler + // not until now because of comparison between synchronized statements in the finally cycle + DomHelper.removeSynchronizedHandler(root); + + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern3.dot"), true); + // System.out.println(graph.toString()); + + // LabelHelper.lowContinueLabels(root, new HashSet<StatEdge>()); + + SequenceHelper.condenseSequences(root); + + ClearStructHelper.clearStatements(root); + + ExprProcessor proc = new ExprProcessor(); + proc.processStatement(root, cl); + + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern3.dot"), true); + // System.out.println(graph.toString()); + + //System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + while (true) { + StackVarsProcessor stackproc = new StackVarsProcessor(); + stackproc.simplifyStackVars(root, mt, cl); + + //System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + varproc.setVarVersions(root); + + // System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + if (!new PPandMMHelper().findPPandMM(root)) { + break; + } + } + + while (true) { + + LabelHelper.cleanUpEdges(root); + + while (true) { + + MergeHelper.enhanceLoops(root); + + if (LoopExtractHelper.extractLoops(root)) { + continue; + } + + if (!IfHelper.mergeAllIfs(root)) { + break; + } + } + + if (DecompilerContext.getOption(IFernflowerPreferences.IDEA_NOT_NULL_ANNOTATION)) { + + if (IdeaNotNullHelper.removeHardcodedChecks(root, mt)) { + + SequenceHelper.condenseSequences(root); + + StackVarsProcessor stackproc = new StackVarsProcessor(); + stackproc.simplifyStackVars(root, mt, cl); + + varproc.setVarVersions(root); + } + } + + LabelHelper.identifyLabels(root); + + // System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + if (InlineSingleBlockHelper.inlineSingleBlocks(root)) { + continue; + } + + // initializer may have at most one return point, so no transformation of method exits permitted + if (isInitializer || !ExitHelper.condenseExits(root)) { + break; + } + + // FIXME: !! + // if(!EliminateLoopsHelper.eliminateLoops(root)) { + // break; + // } + } + + ExitHelper.removeRedundantReturns(root); + + SecondaryFunctionsHelper.identifySecondaryFunctions(root); + + varproc.setVarDefinitions(root); + + // must be the last invocation, because it makes the statement structure inconsistent + // FIXME: new edge type needed + LabelHelper.replaceContinueWithBreak(root); + + mt.releaseResources(); + + // System.out.println("++++++++++++++++++++++/// \r\n"+root.toJava()); + + return root; + } + + public RootStatement getResult() throws Throwable { + Throwable t = error; + if (t != null) throw t; + return root; + } + + public Throwable getError() { + return error; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/MethodWrapper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/MethodWrapper.java new file mode 100644 index 000000000000..d36b8bc578fd --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/MethodWrapper.java @@ -0,0 +1,62 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.rels; + +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructMethod; + +import java.util.HashSet; +import java.util.List; + + +public class MethodWrapper { + + public RootStatement root; + + public VarProcessor varproc; + + public StructMethod methodStruct; + + public CounterContainer counter; + + public DirectGraph graph; + + public List<VarVersionPaar> signatureFields; + + public boolean decompiledWithErrors; + + public HashSet<String> setOuterVarNames = new HashSet<String>(); + + public MethodWrapper(RootStatement root, VarProcessor varproc, StructMethod methodStruct, CounterContainer counter) { + this.root = root; + this.varproc = varproc; + this.methodStruct = methodStruct; + this.counter = counter; + } + + public DirectGraph getOrBuildGraph() { + if (graph == null && root != null) { + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + graph = flatthelper.buildDirectGraph(root); + } + return graph; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedClassProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedClassProcessor.java new file mode 100644 index 000000000000..2e839461125c --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedClassProcessor.java @@ -0,0 +1,1030 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.rels; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectNode; +import org.jetbrains.java.decompiler.modules.decompiler.stats.DoStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarTypeProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.attr.StructEnclosingMethodAttribute; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.*; +import java.util.Map.Entry; + +public class NestedClassProcessor { + + + public void processClass(ClassNode root, ClassNode node) { + + // hide synthetic lambda content methods + if (node.type == ClassNode.CLASS_LAMBDA && !node.lambda_information.is_method_reference) { + ClassNode node_content = DecompilerContext.getClassProcessor().getMapRootClasses().get(node.classStruct.qualifiedName); + if (node_content != null && node_content.wrapper != null) { + node_content.wrapper.getHiddenMembers().add(node.lambda_information.content_method_key); + } + } + + if (node.nested.isEmpty()) { + return; + } + + if (node.type != ClassNode.CLASS_LAMBDA) { + + computeLocalVarsAndDefinitions(node); + + // for each local or anonymous class ensure not empty enclosing method + checkNotFoundClasses(root, node); + } + + int nameless = 0, synthetics = 0; + for (ClassNode child : node.nested) { + // ensure not-empty class name + if ((child.type == ClassNode.CLASS_LOCAL || child.type == ClassNode.CLASS_MEMBER) && child.simpleName == null) { + StructClass cl = child.classStruct; + if ((child.access & CodeConstants.ACC_SYNTHETIC) != 0 || cl.isSynthetic()) { + child.simpleName = "SyntheticClass_" + (++synthetics); + } + else { + DecompilerContext.getLogger().writeMessage("Nameless local or member class " + cl.qualifiedName + "!", + IFernflowerLogger.Severity.WARN); + child.simpleName = "NamelessClass_" + (++nameless); + } + } + } + + for (ClassNode child : node.nested) { + if (child.type == ClassNode.CLASS_LAMBDA) { + setLambdaVars(node, child); + } + else { + if (child.type != ClassNode.CLASS_MEMBER || (child.access & CodeConstants.ACC_STATIC) == 0) { + insertLocalVars(node, child); + + if (child.type == ClassNode.CLASS_LOCAL) { + setLocalClassDefinition(node.wrapper.getMethods().getWithKey(child.enclosingMethod), child); + } + } + } + } + + for (ClassNode child : node.nested) { + processClass(root, child); + } + } + + private static void setLambdaVars(ClassNode parent, ClassNode child) { + + if (child.lambda_information.is_method_reference) { // method reference, no code and no parameters + return; + } + + final MethodWrapper meth = parent.wrapper.getMethods().getWithKey(child.lambda_information.content_method_key); + final MethodWrapper encmeth = parent.wrapper.getMethods().getWithKey(child.enclosingMethod); + + MethodDescriptor md_lambda = MethodDescriptor.parseDescriptor(child.lambda_information.method_descriptor); + final MethodDescriptor md_content = MethodDescriptor.parseDescriptor(child.lambda_information.content_method_descriptor); + + final int vars_count = md_content.params.length - md_lambda.params.length; + // if(vars_count < 0) { // should not happen, but just in case... + // vars_count = 0; + // } + + final boolean is_static_lambda_content = child.lambda_information.is_content_method_static; + + final String parent_class_name = parent.wrapper.getClassStruct().qualifiedName; + final String lambda_class_name = child.simpleName; + + final VarType lambda_class_type = new VarType(lambda_class_name, true); + + // this pointer + if (!is_static_lambda_content && DecompilerContext.getOption(IFernflowerPreferences.LAMBDA_TO_ANONYMOUS_CLASS)) { + meth.varproc.getThisvars().put(new VarVersionPaar(0, 0), parent_class_name); + meth.varproc.setVarName(new VarVersionPaar(0, 0), parent.simpleName + ".this"); + } + + // local variables + DirectGraph graph = encmeth.getOrBuildGraph(); + + final HashMap<VarVersionPaar, String> mapNewNames = new HashMap<VarVersionPaar, String>(); + + graph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + + if (expr.type == Exprent.EXPRENT_NEW) { + NewExprent new_expr = (NewExprent)expr; + if (new_expr.isLambda() && lambda_class_type.equals(new_expr.getNewtype())) { + + InvocationExprent inv_dynamic = new_expr.getConstructor(); + + int param_index = is_static_lambda_content ? 0 : 1; + int varindex = is_static_lambda_content ? 0 : 1; + + for (int i = 0; i < vars_count; ++i) { + + Exprent param = inv_dynamic.getLstParameters().get(param_index + i); + + if (param.type == Exprent.EXPRENT_VAR) { + VarVersionPaar enc_varpaar = new VarVersionPaar((VarExprent)param); + String enc_varname = encmeth.varproc.getVarName(enc_varpaar); + + //meth.varproc.setVarName(new VarVersionPaar(varindex, 0), enc_varname); + mapNewNames.put(new VarVersionPaar(varindex, 0), enc_varname); + } + + varindex += md_content.params[i].stack_size; + } + } + } + } + + return 0; + } + }); + + // update names of local variables + HashSet<String> setNewOuterNames = new HashSet<String>(mapNewNames.values()); + setNewOuterNames.removeAll(meth.setOuterVarNames); + + meth.varproc.refreshVarNames(new VarNamesCollector(setNewOuterNames)); + meth.setOuterVarNames.addAll(setNewOuterNames); + + for (Entry<VarVersionPaar, String> entr : mapNewNames.entrySet()) { + meth.varproc.setVarName(entr.getKey(), entr.getValue()); + } + } + + private static void checkNotFoundClasses(ClassNode root, ClassNode node) { + + List<ClassNode> lstChildren = new ArrayList<ClassNode>(node.nested); + + for (ClassNode child : lstChildren) { + + if ((child.type == ClassNode.CLASS_LOCAL || child.type == ClassNode.CLASS_ANONYMOUS) && child.enclosingMethod == null) { + + Set<String> setEnclosing = child.enclosingClasses; + + if (setEnclosing.size() == 1) { + StructEnclosingMethodAttribute attr = + (StructEnclosingMethodAttribute)child.classStruct.getAttributes().getWithKey("EnclosingMethod"); + if (attr != null && attr.getMethodName() != null) { + if (node.classStruct.qualifiedName.equals(attr.getClassName()) && + node.classStruct.getMethod(attr.getMethodName(), attr.getMethodDescriptor()) != null) { + child.enclosingMethod = InterpreterUtil.makeUniqueKey(attr.getMethodName(), attr.getMethodDescriptor()); + continue; + } + } + } + + node.nested.remove(child); + child.parent = null; + setEnclosing.remove(node.classStruct.qualifiedName); + + boolean hasEnclosing = !setEnclosing.isEmpty(); + if (hasEnclosing) { + hasEnclosing = insertNestedClass(root, child); + } + + if (!hasEnclosing) { + if (child.type == ClassNode.CLASS_ANONYMOUS) { + DecompilerContext.getLogger() + .writeMessage("Unreferenced anonymous class " + child.classStruct.qualifiedName + "!", IFernflowerLogger.Severity.WARN); + } + else if (child.type == ClassNode.CLASS_LOCAL) { + DecompilerContext.getLogger() + .writeMessage("Unreferenced local class " + child.classStruct.qualifiedName + "!", IFernflowerLogger.Severity.WARN); + } + } + } + } + } + + private static boolean insertNestedClass(ClassNode root, ClassNode child) { + + Set<String> setEnclosing = child.enclosingClasses; + + LinkedList<ClassNode> stack = new LinkedList<ClassNode>(); + stack.add(root); + + while (!stack.isEmpty()) { + + ClassNode node = stack.removeFirst(); + + if (setEnclosing.contains(node.classStruct.qualifiedName)) { + node.nested.add(child); + child.parent = node; + + return true; + } + + // note: ordered list + stack.addAll(node.nested); + } + + return false; + } + + + private static void computeLocalVarsAndDefinitions(final ClassNode node) { + + // local var masks + // class name, constructor descriptor, field mask + final HashMap<String, HashMap<String, List<VarFieldPair>>> mapVarMasks = new HashMap<String, HashMap<String, List<VarFieldPair>>>(); + + int cltypes = 0; + + for (ClassNode nd : node.nested) { + if (nd.type != ClassNode.CLASS_LAMBDA) { + if ((nd.access & CodeConstants.ACC_STATIC) == 0 && (nd.access & CodeConstants.ACC_INTERFACE) == 0) { + + cltypes |= nd.type; + + HashMap<String, List<VarFieldPair>> mask = getMaskLocalVars(nd.wrapper); + if (mask.isEmpty()) { + DecompilerContext.getLogger() + .writeMessage("Nested class " + nd.classStruct.qualifiedName + " has no constructor!", IFernflowerLogger.Severity.WARN); + } + else { + mapVarMasks.put(nd.classStruct.qualifiedName, mask); + } + } + } + } + + // local var masks + final HashMap<String, HashMap<String, List<VarFieldPair>>> mapVarFieldPairs = + new HashMap<String, HashMap<String, List<VarFieldPair>>>(); + + if (cltypes != ClassNode.CLASS_MEMBER) { + + // iterate enclosing class + for (final MethodWrapper meth : node.wrapper.getMethods()) { + + if (meth.root != null) { // neither abstract, nor native + DirectGraph graph = meth.getOrBuildGraph(); + + graph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + + if (expr.type == Exprent.EXPRENT_NEW) { + InvocationExprent constr = ((NewExprent)expr).getConstructor(); + + if (constr != null && mapVarMasks.containsKey(constr.getClassname())) { // non-static inner class constructor + + String refclname = constr.getClassname(); + + ClassNode nestedClassNode = node.getClassNode(refclname); + + if (nestedClassNode.type != ClassNode.CLASS_MEMBER) { + + List<VarFieldPair> mask = mapVarMasks.get(refclname).get(constr.getStringDescriptor()); + + if (!mapVarFieldPairs.containsKey(refclname)) { + mapVarFieldPairs.put(refclname, new HashMap<String, List<VarFieldPair>>()); + } + + List<VarFieldPair> lstTemp = new ArrayList<VarFieldPair>(); + + for (int i = 0; i < mask.size(); i++) { + Exprent param = constr.getLstParameters().get(i); + VarFieldPair pair = null; + + if (param.type == Exprent.EXPRENT_VAR && mask.get(i) != null) { + VarVersionPaar varpaar = new VarVersionPaar((VarExprent)param); + + // FIXME: final flags of variables are wrong! Correct the entire final functionality. + // if(meth.varproc.getVarFinal(varpaar) != VarTypeProcessor.VAR_NONFINAL) { + pair = new VarFieldPair(mask.get(i).keyfield, varpaar); + // } + } + + lstTemp.add(pair); + } + + List<VarFieldPair> pairmask = mapVarFieldPairs.get(refclname).get(constr.getStringDescriptor()); + + if (pairmask == null) { + pairmask = lstTemp; + } + else { + for (int i = 0; i < pairmask.size(); i++) { + if (!InterpreterUtil.equalObjects(pairmask.get(i), lstTemp.get(i))) { + pairmask.set(i, null); + } + } + } + + mapVarFieldPairs.get(refclname).put(constr.getStringDescriptor(), pairmask); + nestedClassNode.enclosingMethod = + InterpreterUtil.makeUniqueKey(meth.methodStruct.getName(), meth.methodStruct.getDescriptor()); + } + } + } + } + return 0; + } + }); + } + } + } + + // merge var masks + for (Entry<String, HashMap<String, List<VarFieldPair>>> entcl : mapVarMasks.entrySet()) { + + ClassNode nestedNode = node.getClassNode(entcl.getKey()); + + // intersection + List<VarFieldPair> intrPairMask = null; + // merge referenced constructors + if (mapVarFieldPairs.containsKey(entcl.getKey())) { + for (List<VarFieldPair> mask : mapVarFieldPairs.get(entcl.getKey()).values()) { + if (intrPairMask == null) { + intrPairMask = new ArrayList<VarFieldPair>(mask); + } + else { + mergeListSignatures(intrPairMask, mask, false); + } + } + } + + List<VarFieldPair> intrMask = null; + // merge all constructors + for (List<VarFieldPair> mask : entcl.getValue().values()) { + if (intrMask == null) { + intrMask = new ArrayList<VarFieldPair>(mask); + } + else { + mergeListSignatures(intrMask, mask, false); + } + } + + if (intrPairMask == null) { // member or local and never instantiated + intrPairMask = new ArrayList<VarFieldPair>(intrMask); + + boolean found = false; + + for (int i = 0; i < intrPairMask.size(); i++) { + if (intrPairMask.get(i) != null) { + if (found) { + intrPairMask.set(i, null); + } + found = true; + } + } + } + + mergeListSignatures(intrPairMask, intrMask, true); + + for (int i = 0; i < intrPairMask.size(); i++) { + VarFieldPair pair = intrPairMask.get(i); + if (pair != null && pair.keyfield.length() > 0) { + nestedNode.mapFieldsToVars.put(pair.keyfield, pair.varpaar); + } + } + + // set resulting constructor signatures + for (Entry<String, List<VarFieldPair>> entmt : entcl.getValue().entrySet()) { + mergeListSignatures(entmt.getValue(), intrPairMask, false); + + MethodWrapper meth = nestedNode.wrapper.getMethodWrapper("<init>", entmt.getKey()); + meth.signatureFields = new ArrayList<VarVersionPaar>(); + + for (VarFieldPair pair : entmt.getValue()) { + meth.signatureFields.add(pair == null ? null : pair.varpaar); + } + } + } + } + + private static void insertLocalVars(final ClassNode parent, final ClassNode child) { + + // enclosing method, is null iff member class + MethodWrapper encmeth = parent.wrapper.getMethods().getWithKey(child.enclosingMethod); + + // iterate all child methods + for (final MethodWrapper meth : child.wrapper.getMethods()) { + + if (meth.root != null) { // neither abstract nor native + + // local var names + HashMap<VarVersionPaar, String> mapNewNames = new HashMap<VarVersionPaar, String>(); + // local var types + HashMap<VarVersionPaar, VarType> mapNewTypes = new HashMap<VarVersionPaar, VarType>(); + + final HashMap<Integer, VarVersionPaar> mapParamsToNewVars = new HashMap<Integer, VarVersionPaar>(); + if (meth.signatureFields != null) { + int index = 0; + int varindex = 1; + MethodDescriptor md = MethodDescriptor.parseDescriptor(meth.methodStruct.getDescriptor()); + + for (VarVersionPaar paar : meth.signatureFields) { + if (paar != null) { + VarVersionPaar newvar = new VarVersionPaar(meth.counter.getCounterAndIncrement(CounterContainer.VAR_COUNTER), 0); + + mapParamsToNewVars.put(varindex, newvar); + + String varname = null; + VarType vartype = null; + + if (child.type != ClassNode.CLASS_MEMBER) { + varname = encmeth.varproc.getVarName(paar); + vartype = encmeth.varproc.getVarType(paar); + + encmeth.varproc.setVarFinal(paar, VarTypeProcessor.VAR_FINALEXPLICIT); + } + + if (paar.var == -1 || "this".equals(varname)) { + if (parent.simpleName == null) { + // anonymous enclosing class, no access to this + varname = VarExprent.VAR_NAMELESS_ENCLOSURE; + } + else { + varname = parent.simpleName + ".this"; + } + meth.varproc.getThisvars().put(newvar, parent.classStruct.qualifiedName); + } + + mapNewNames.put(newvar, varname); + mapNewTypes.put(newvar, vartype); + } + varindex += md.params[index++].stack_size; + } + } + + // new vars + final HashMap<String, VarVersionPaar> mapFieldsToNewVars = new HashMap<String, VarVersionPaar>(); + + for (ClassNode clnode = child; clnode != null; clnode = clnode.parent) { + + for (Entry<String, VarVersionPaar> entr : clnode.mapFieldsToVars.entrySet()) { + VarVersionPaar newvar = new VarVersionPaar(meth.counter.getCounterAndIncrement(CounterContainer.VAR_COUNTER), 0); + + mapFieldsToNewVars.put(InterpreterUtil.makeUniqueKey(clnode.classStruct.qualifiedName, entr.getKey()), newvar); + + String varname = null; + VarType vartype = null; + + if (clnode.type != ClassNode.CLASS_MEMBER) { + + MethodWrapper enclosing_method = clnode.parent.wrapper.getMethods().getWithKey(clnode.enclosingMethod); + + varname = enclosing_method.varproc.getVarName(entr.getValue()); + vartype = enclosing_method.varproc.getVarType(entr.getValue()); + + enclosing_method.varproc.setVarFinal(entr.getValue(), VarTypeProcessor.VAR_FINALEXPLICIT); + } + + if (entr.getValue().var == -1 || "this".equals(varname)) { + if (clnode.parent.simpleName == null) { + // anonymous enclosing class, no access to this + varname = VarExprent.VAR_NAMELESS_ENCLOSURE; + } + else { + varname = clnode.parent.simpleName + ".this"; + } + meth.varproc.getThisvars().put(newvar, clnode.parent.classStruct.qualifiedName); + } + + mapNewNames.put(newvar, varname); + mapNewTypes.put(newvar, vartype); + + // hide synthetic field + if (clnode == child) { // fields higher up the chain were already handled with their classes + StructField fd = child.classStruct.getFields().getWithKey(entr.getKey()); + child.wrapper.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(fd.getName(), fd.getDescriptor())); + } + } + } + + HashSet<String> setNewOuterNames = new HashSet<String>(mapNewNames.values()); + setNewOuterNames.removeAll(meth.setOuterVarNames); + + meth.varproc.refreshVarNames(new VarNamesCollector(setNewOuterNames)); + meth.setOuterVarNames.addAll(setNewOuterNames); + + for (Entry<VarVersionPaar, String> entr : mapNewNames.entrySet()) { + VarVersionPaar varpaar = entr.getKey(); + VarType vartype = mapNewTypes.get(varpaar); + + meth.varproc.setVarName(varpaar, entr.getValue()); + if (vartype != null) { + meth.varproc.setVarType(varpaar, vartype); + } + } + + DirectGraph graph = meth.getOrBuildGraph(); + + graph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asexpr = (AssignmentExprent)exprent; + if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD) { + FieldExprent fexpr = (FieldExprent)asexpr.getLeft(); + + if (fexpr.getClassname().equals(child.classStruct.qualifiedName) && // process this class only + mapFieldsToNewVars.containsKey(InterpreterUtil.makeUniqueKey(child.classStruct.qualifiedName, + InterpreterUtil.makeUniqueKey(fexpr.getName(), fexpr + .getDescriptor().descriptorString)))) { + return 2; + } + + //if(fexpr.getClassname().equals(child.classStruct.qualifiedName) && + // mapFieldsToNewVars.containsKey(InterpreterUtil.makeUniqueKey(fexpr.getName(), fexpr.getDescriptor().descriptorString))) { + // return 2; + //} + } + } + + if (child.type == ClassNode.CLASS_ANONYMOUS && "<init>".equals(meth.methodStruct.getName()) + && exprent.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent invexpr = (InvocationExprent)exprent; + if (invexpr.getFunctype() == InvocationExprent.TYP_INIT) { + // invocation of the super constructor in an anonymous class + child.superInvocation = invexpr; // FIXME: save original names of parameters + return 2; + } + } + + replaceExprent(exprent); + + return 0; + } + + private Exprent replaceExprent(Exprent exprent) { + + if (exprent.type == Exprent.EXPRENT_VAR) { + int varindex = ((VarExprent)exprent).getIndex(); + if (mapParamsToNewVars.containsKey(varindex)) { + VarVersionPaar newvar = mapParamsToNewVars.get(varindex); + meth.varproc.getExternvars().add(newvar); + return new VarExprent(newvar.var, meth.varproc.getVarType(newvar), meth.varproc); + } + } + else if (exprent.type == Exprent.EXPRENT_FIELD) { + FieldExprent fexpr = (FieldExprent)exprent; + + String keyField = InterpreterUtil.makeUniqueKey(fexpr.getClassname(), InterpreterUtil + .makeUniqueKey(fexpr.getName(), fexpr.getDescriptor().descriptorString)); + + if (mapFieldsToNewVars.containsKey(keyField)) { + //if(fexpr.getClassname().equals(child.classStruct.qualifiedName) && + // mapFieldsToNewVars.containsKey(keyField)) { + VarVersionPaar newvar = mapFieldsToNewVars.get(keyField); + meth.varproc.getExternvars().add(newvar); + return new VarExprent(newvar.var, meth.varproc.getVarType(newvar), meth.varproc); + } + } + + boolean replaced = true; + while (replaced) { + replaced = false; + + for (Exprent expr : exprent.getAllExprents()) { + Exprent retexpr = replaceExprent(expr); + if (retexpr != null) { + exprent.replaceExprent(expr, retexpr); + replaced = true; + break; + } + } + } + + return null; + } + }); + } + } + } + + private static HashMap<String, List<VarFieldPair>> getMaskLocalVars(ClassWrapper wrapper) { + + HashMap<String, List<VarFieldPair>> mapMasks = new HashMap<String, List<VarFieldPair>>(); + + StructClass cl = wrapper.getClassStruct(); + + // iterate over constructors + for (StructMethod mt : cl.getMethods()) { + if ("<init>".equals(mt.getName())) { + + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + + MethodWrapper meth = wrapper.getMethodWrapper("<init>", mt.getDescriptor()); + DirectGraph graph = meth.getOrBuildGraph(); + + if (graph != null) { // something gone wrong, should not be null + List<VarFieldPair> fields = new ArrayList<VarFieldPair>(); + + int varindex = 1; + for (int i = 0; i < md.params.length; i++) { // no static methods allowed + String keyField = getEnclosingVarField(cl, meth, graph, varindex); + fields.add(keyField == null ? null : new VarFieldPair(keyField, new VarVersionPaar(-1, 0))); // TODO: null? + varindex += md.params[i].stack_size; + } + mapMasks.put(mt.getDescriptor(), fields); + } + } + } + + return mapMasks; + } + + private static String getEnclosingVarField(StructClass cl, MethodWrapper meth, DirectGraph graph, final int index) { + + String field = ""; + + // parameter variable final + if (meth.varproc.getVarFinal(new VarVersionPaar(index, 0)) == VarTypeProcessor.VAR_NONFINAL) { + return null; + } + + boolean noSynthFlag = DecompilerContext.getOption(IFernflowerPreferences.SYNTHETIC_NOT_SET); + + // no loop at the begin + DirectNode firstnode = graph.first; + if (firstnode.preds.isEmpty()) { + // assignment to a final synthetic field? + for (Exprent exprent : firstnode.exprents) { + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asexpr = (AssignmentExprent)exprent; + if (asexpr.getRight().type == Exprent.EXPRENT_VAR && ((VarExprent)asexpr.getRight()).getIndex() == index) { + if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD) { + + FieldExprent left = (FieldExprent)asexpr.getLeft(); + StructField fd = cl.getField(left.getName(), left.getDescriptor().descriptorString); + + if (fd != null) { // local (== not inherited) field + if (cl.qualifiedName.equals(left.getClassname()) && + fd.hasModifier(CodeConstants.ACC_FINAL) && + (fd.isSynthetic() || (noSynthFlag && fd.hasModifier(CodeConstants.ACC_PRIVATE)))) { + field = InterpreterUtil.makeUniqueKey(left.getName(), left.getDescriptor().descriptorString); + break; + } + } + } + } + } + } + } + + return field; + } + + private static void mergeListSignatures(List<VarFieldPair> first, List<VarFieldPair> second, boolean both) { + + int i = 1; + while (true) { + if (first.size() <= i || second.size() <= i) { + break; + } + + VarFieldPair fobj = first.get(first.size() - i); + VarFieldPair sobj = second.get(second.size() - i); + + boolean eq = false; + if (fobj == null || sobj == null) { + eq = (fobj == sobj); + } + else { + eq = true; + if (fobj.keyfield.length() == 0) { + fobj.keyfield = sobj.keyfield; + } + else if (sobj.keyfield.length() == 0) { + if (both) { + sobj.keyfield = fobj.keyfield; + } + } + else { + eq = fobj.keyfield.equals(sobj.keyfield); + } + } + + if (!eq) { + first.set(first.size() - i, null); + if (both) { + second.set(second.size() - i, null); + } + } + else { + if (fobj != null) { + if (fobj.varpaar.var == -1) { + fobj.varpaar = sobj.varpaar; + } + else { + sobj.varpaar = fobj.varpaar; + } + } + } + i++; + } + + for (int j = 1; j <= first.size() - i; j++) { + first.set(j, null); + } + + if (both) { + for (int j = 1; j <= second.size() - i; j++) { + second.set(j, null); + } + } + + // first + if (first.isEmpty()) { + if (!second.isEmpty() && both) { + second.set(0, null); + } + } + else if (second.isEmpty()) { + first.set(0, null); + } + else { + VarFieldPair fobj = first.get(0); + VarFieldPair sobj = second.get(0); + + boolean eq = false; + if (fobj == null || sobj == null) { + eq = (fobj == sobj); + } + else { + eq = true; + if (fobj.keyfield.length() == 0) { + fobj.keyfield = sobj.keyfield; + } + else if (sobj.keyfield.length() == 0) { + if (both) { + sobj.keyfield = fobj.keyfield; + } + } + else { + eq = fobj.keyfield.equals(sobj.keyfield); + } + } + + if (!eq) { + first.set(0, null); + if (both) { + second.set(0, null); + } + } + else if (fobj != null) { + if (fobj.varpaar.var == -1) { + fobj.varpaar = sobj.varpaar; + } + else { + sobj.varpaar = fobj.varpaar; + } + } + } + } + + + private static void setLocalClassDefinition(MethodWrapper meth, ClassNode node) { + + RootStatement root = meth.root; + + HashSet<Statement> setStats = new HashSet<Statement>(); + VarType classtype = new VarType(node.classStruct.qualifiedName, true); + + Statement stdef = getDefStatement(root, classtype, setStats); + if (stdef == null) { + // unreferenced local class + stdef = root.getFirst(); + } + + Statement first = findFirstBlock(stdef, setStats); + + List<Exprent> lst; + if (first == null) { + lst = stdef.getVarDefinitions(); + } + else if (first.getExprents() == null) { + lst = first.getVarDefinitions(); + } + else { + lst = first.getExprents(); + } + + + int addindex = 0; + for (Exprent expr : lst) { + if (searchForClass(expr, classtype)) { + break; + } + addindex++; + } + + VarExprent var = new VarExprent(meth.counter.getCounterAndIncrement(CounterContainer.VAR_COUNTER), + classtype, meth.varproc); + var.setDefinition(true); + var.setClassdef(true); + + lst.add(addindex, var); + } + + + private static Statement findFirstBlock(Statement stat, HashSet<Statement> setStats) { + + LinkedList<Statement> stack = new LinkedList<Statement>(); + stack.add(stat); + + while (!stack.isEmpty()) { + Statement st = stack.remove(0); + + if (stack.isEmpty() || setStats.contains(st)) { + + if (st.isLabeled() && !stack.isEmpty()) { + return st; + } + + if (st.getExprents() != null) { + return st; + } + else { + stack.clear(); + + switch (st.type) { + case Statement.TYPE_SEQUENCE: + stack.addAll(0, st.getStats()); + break; + case Statement.TYPE_IF: + case Statement.TYPE_ROOT: + case Statement.TYPE_SWITCH: + case Statement.TYPE_SYNCRONIZED: + stack.add(st.getFirst()); + break; + default: + return st; + } + } + } + } + + return null; + } + + + private static Statement getDefStatement(Statement stat, VarType classtype, HashSet<Statement> setStats) { + + List<Exprent> condlst = new ArrayList<Exprent>(); + Statement retstat = null; + + if (stat.getExprents() == null) { + int counter = 0; + + for (Object obj : stat.getSequentialObjects()) { + if (obj instanceof Statement) { + Statement st = (Statement)obj; + + Statement stTemp = getDefStatement(st, classtype, setStats); + + if (stTemp != null) { + if (counter == 1) { + retstat = stat; + break; + } + retstat = stTemp; + counter++; + } + + if (st.type == DoStatement.TYPE_DO) { + DoStatement dost = (DoStatement)st; + + condlst.addAll(dost.getInitExprentList()); + condlst.addAll(dost.getConditionExprentList()); + } + } + else if (obj instanceof Exprent) { + condlst.add((Exprent)obj); + } + } + } + else { + condlst = stat.getExprents(); + } + + if (retstat != stat) { + for (Exprent exprent : condlst) { + if (exprent != null && searchForClass(exprent, classtype)) { + retstat = stat; + break; + } + } + } + + if (retstat != null) { + setStats.add(stat); + } + + return retstat; + } + + private static boolean searchForClass(Exprent exprent, VarType classtype) { + + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + String classname = classtype.value; + + for (Exprent expr : lst) { + + boolean res = false; + + switch (expr.type) { + case Exprent.EXPRENT_CONST: + ConstExprent cexpr = (ConstExprent)expr; + res = (VarType.VARTYPE_CLASS.equals(cexpr.getConsttype()) && classname.equals(cexpr.getValue()) || + classtype.equals(cexpr.getConsttype())); + break; + case Exprent.EXPRENT_FIELD: + res = classname.equals(((FieldExprent)expr).getClassname()); + break; + case Exprent.EXPRENT_INVOCATION: + res = classname.equals(((InvocationExprent)expr).getClassname()); + break; + case Exprent.EXPRENT_NEW: + VarType newType = expr.getExprType(); + res = newType.type == CodeConstants.TYPE_OBJECT && classname.equals(newType.value); + break; + case Exprent.EXPRENT_VAR: + VarExprent vexpr = (VarExprent)expr; + if (vexpr.isDefinition()) { + VarType vtype = vexpr.getVartype(); + if (classtype.equals(vtype) || (vtype.arraydim > 0 && classtype.value.equals(vtype.value))) { + res = true; + } + } + } + + if (res) { + return true; + } + } + + return false; + } + + + private static class VarFieldPair { + + public String keyfield = ""; + public VarVersionPaar varpaar; + + public VarFieldPair(String field, VarVersionPaar varpaar) { + this.keyfield = field; + this.varpaar = varpaar; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof VarFieldPair)) return false; + + VarFieldPair pair = (VarFieldPair)o; + return keyfield.equals(pair.keyfield) && varpaar.equals(pair.varpaar); + } + + @Override + public int hashCode() { + return keyfield.hashCode() + varpaar.hashCode(); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedMemberAccess.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedMemberAccess.java new file mode 100644 index 000000000000..7e5eaa54326a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedMemberAccess.java @@ -0,0 +1,449 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.main.rels; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectNode; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Map; + +public class NestedMemberAccess { + + private static final int METHOD_ACCESS_NORMAL = 1; + private static final int METHOD_ACCESS_FIELD_GET = 2; + private static final int METHOD_ACCESS_FIELD_SET = 3; + private static final int METHOD_ACCESS_METHOD = 4; + + private boolean noSynthFlag; + private Map<MethodWrapper, Integer> mapMethodType = new HashMap<MethodWrapper, Integer>(); + + + public void propagateMemberAccess(ClassNode root) { + if (root.nested.isEmpty()) { + return; + } + + noSynthFlag = DecompilerContext.getOption(IFernflowerPreferences.SYNTHETIC_NOT_SET); + + computeMethodTypes(root); + + eliminateStaticAccess(root); + } + + + private void computeMethodTypes(ClassNode node) { + if (node.type == ClassNode.CLASS_LAMBDA) { + return; + } + + for (ClassNode nd : node.nested) { + computeMethodTypes(nd); + } + + for (MethodWrapper method : node.wrapper.getMethods()) { + computeMethodType(node, method); + } + } + + private void computeMethodType(ClassNode node, MethodWrapper method) { + int type = METHOD_ACCESS_NORMAL; + + if (method.root != null) { + DirectGraph graph = method.getOrBuildGraph(); + + StructMethod mt = method.methodStruct; + if ((noSynthFlag || mt.isSynthetic()) && mt.hasModifier(CodeConstants.ACC_STATIC)) { + if (graph.nodes.size() == 2) { // incl. dummy exit node + if (graph.first.exprents.size() == 1) { + Exprent exprent = graph.first.exprents.get(0); + + MethodDescriptor mtdesc = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + int parcount = mtdesc.params.length; + + Exprent exprCore = exprent; + + if (exprent.type == Exprent.EXPRENT_EXIT) { + ExitExprent exexpr = (ExitExprent)exprent; + if (exexpr.getExittype() == ExitExprent.EXIT_RETURN && exexpr.getValue() != null) { + exprCore = exexpr.getValue(); + } + } + + switch (exprCore.type) { + case Exprent.EXPRENT_FIELD: + FieldExprent fexpr = (FieldExprent)exprCore; + if ((parcount == 1 && !fexpr.isStatic()) || + (parcount == 0 && fexpr.isStatic())) { + if (fexpr.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field + if (fexpr.isStatic() || + (fexpr.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpr.getInstance()).getIndex() == 0)) { + type = METHOD_ACCESS_FIELD_GET; + } + } + } + break; + case Exprent.EXPRENT_VAR: // qualified this + if (parcount == 1) { + // this or final variable + if (((VarExprent)exprCore).getIndex() != 0) { + type = METHOD_ACCESS_FIELD_GET; + } + } + + break; + case Exprent.EXPRENT_INVOCATION: + type = METHOD_ACCESS_METHOD; + break; + case Exprent.EXPRENT_ASSIGNMENT: + AssignmentExprent asexpr = (AssignmentExprent)exprCore; + if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD && asexpr.getRight().type == Exprent.EXPRENT_VAR) { + FieldExprent fexpras = (FieldExprent)asexpr.getLeft(); + if ((parcount == 2 && !fexpras.isStatic()) || + (parcount == 1 && fexpras.isStatic())) { + if (fexpras.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field + if (fexpras.isStatic() || + (fexpras.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpras.getInstance()).getIndex() == 0)) { + if (((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) { + type = METHOD_ACCESS_FIELD_SET; + } + } + } + } + } + } + + + if (type == METHOD_ACCESS_METHOD) { // FIXME: check for private flag of the method + + type = METHOD_ACCESS_NORMAL; + + InvocationExprent invexpr = (InvocationExprent)exprCore; + + if ((invexpr.isStatic() && invexpr.getLstParameters().size() == parcount) || + (!invexpr.isStatic() && invexpr.getInstance().type == Exprent.EXPRENT_VAR + && ((VarExprent)invexpr.getInstance()).getIndex() == 0 && invexpr.getLstParameters().size() == parcount - 1)) { + + boolean equalpars = true; + + for (int i = 0; i < invexpr.getLstParameters().size(); i++) { + Exprent parexpr = invexpr.getLstParameters().get(i); + if (parexpr.type != Exprent.EXPRENT_VAR || + ((VarExprent)parexpr).getIndex() != i + (invexpr.isStatic() ? 0 : 1)) { + equalpars = false; + break; + } + } + + if (equalpars) { + type = METHOD_ACCESS_METHOD; + } + } + } + } + else if (graph.first.exprents.size() == 2) { + Exprent exprentFirst = graph.first.exprents.get(0); + Exprent exprentSecond = graph.first.exprents.get(1); + + if (exprentFirst.type == Exprent.EXPRENT_ASSIGNMENT && + exprentSecond.type == Exprent.EXPRENT_EXIT) { + + MethodDescriptor mtdesc = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + int parcount = mtdesc.params.length; + + AssignmentExprent asexpr = (AssignmentExprent)exprentFirst; + if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD && asexpr.getRight().type == Exprent.EXPRENT_VAR) { + FieldExprent fexpras = (FieldExprent)asexpr.getLeft(); + if ((parcount == 2 && !fexpras.isStatic()) || + (parcount == 1 && fexpras.isStatic())) { + if (fexpras.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field + if (fexpras.isStatic() || + (fexpras.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpras.getInstance()).getIndex() == 0)) { + if (((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) { + + ExitExprent exexpr = (ExitExprent)exprentSecond; + if (exexpr.getExittype() == ExitExprent.EXIT_RETURN && exexpr.getValue() != null) { + if (exexpr.getValue().type == Exprent.EXPRENT_VAR && + ((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) { + type = METHOD_ACCESS_FIELD_SET; + } + } + } + } + } + } + } + } + } + } + } + } + + if (type != METHOD_ACCESS_NORMAL) { + mapMethodType.put(method, type); + } + else { + mapMethodType.remove(method); + } + } + + + private void eliminateStaticAccess(ClassNode node) { + + if (node.type == ClassNode.CLASS_LAMBDA) { + return; + } + + for (MethodWrapper meth : node.wrapper.getMethods()) { + + if (meth.root != null) { + + boolean replaced = false; + + DirectGraph graph = meth.getOrBuildGraph(); + + HashSet<DirectNode> setVisited = new HashSet<DirectNode>(); + LinkedList<DirectNode> stack = new LinkedList<DirectNode>(); + stack.add(graph.first); + + while (!stack.isEmpty()) { // TODO: replace with interface iterator? + + DirectNode nd = stack.removeFirst(); + + if (setVisited.contains(nd)) { + continue; + } + setVisited.add(nd); + + for (int i = 0; i < nd.exprents.size(); i++) { + Exprent exprent = nd.exprents.get(i); + + replaced |= replaceInvocations(node, meth, exprent); + + if (exprent.type == Exprent.EXPRENT_INVOCATION) { + Exprent ret = replaceAccessExprent(node, meth, (InvocationExprent)exprent); + + if (ret != null) { + nd.exprents.set(i, ret); + replaced = true; + } + } + } + + for (DirectNode ndx : nd.succs) { + stack.add(ndx); + } + } + + if (replaced) { + computeMethodType(node, meth); + } + } + } + + for (ClassNode child : node.nested) { + eliminateStaticAccess(child); + } + } + + + private boolean replaceInvocations(ClassNode caller, MethodWrapper meth, Exprent exprent) { + + boolean res = false; + + for (Exprent expr : exprent.getAllExprents()) { + res |= replaceInvocations(caller, meth, expr); + } + + while (true) { + + boolean found = false; + + for (Exprent expr : exprent.getAllExprents()) { + if (expr.type == Exprent.EXPRENT_INVOCATION) { + Exprent newexpr = replaceAccessExprent(caller, meth, (InvocationExprent)expr); + if (newexpr != null) { + exprent.replaceExprent(expr, newexpr); + found = true; + res = true; + break; + } + } + } + + if (!found) { + break; + } + } + + return res; + } + + private static boolean sameTree(ClassNode caller, ClassNode callee) { + + if (caller.classStruct.qualifiedName.equals(callee.classStruct.qualifiedName)) { + return false; + } + + while (caller.parent != null) { + caller = caller.parent; + } + + while (callee.parent != null) { + callee = callee.parent; + } + + return caller == callee; + } + + private Exprent replaceAccessExprent(ClassNode caller, MethodWrapper methdest, InvocationExprent invexpr) { + + ClassNode node = DecompilerContext.getClassProcessor().getMapRootClasses().get(invexpr.getClassname()); + + MethodWrapper methsource = null; + if (node != null && node.wrapper != null) { + methsource = node.wrapper.getMethodWrapper(invexpr.getName(), invexpr.getStringDescriptor()); + } + + if (methsource == null || !mapMethodType.containsKey(methsource)) { + return null; + } + + // if same method, return + if (node.classStruct.qualifiedName.equals(caller.classStruct.qualifiedName) && + methsource.methodStruct.getName().equals(methdest.methodStruct.getName()) && + methsource.methodStruct.getDescriptor().equals(methdest.methodStruct.getDescriptor())) { + // no recursive invocations permitted! + return null; + } + + int type = mapMethodType.get(methsource); + + // // FIXME: impossible case. METHOD_ACCESS_NORMAL is not saved in the map + // if(type == METHOD_ACCESS_NORMAL) { + // return null; + // } + + if (!sameTree(caller, node)) { + return null; + } + + DirectGraph graph = methsource.getOrBuildGraph(); + Exprent source = graph.first.exprents.get(0); + + Exprent retexprent = null; + + switch (type) { + case METHOD_ACCESS_FIELD_GET: + ExitExprent exsource = (ExitExprent)source; + if (exsource.getValue().type == Exprent.EXPRENT_VAR) { // qualified this + VarExprent var = (VarExprent)exsource.getValue(); + String varname = methsource.varproc.getVarName(new VarVersionPaar(var)); + + if (!methdest.setOuterVarNames.contains(varname)) { + VarNamesCollector vnc = new VarNamesCollector(); + vnc.addName(varname); + + methdest.varproc.refreshVarNames(vnc); + methdest.setOuterVarNames.add(varname); + } + + int index = methdest.counter.getCounterAndIncrement(CounterContainer.VAR_COUNTER); + VarExprent ret = new VarExprent(index, var.getVartype(), methdest.varproc); + methdest.varproc.setVarName(new VarVersionPaar(index, 0), varname); + + retexprent = ret; + } + else { // field + FieldExprent ret = (FieldExprent)exsource.getValue().copy(); + if (!ret.isStatic()) { + ret.replaceExprent(ret.getInstance(), invexpr.getLstParameters().get(0)); + } + retexprent = ret; + } + break; + case METHOD_ACCESS_FIELD_SET: + AssignmentExprent ret; + if (source.type == Exprent.EXPRENT_EXIT) { + ExitExprent extex = (ExitExprent)source; + ret = (AssignmentExprent)extex.getValue().copy(); + } + else { + ret = (AssignmentExprent)source.copy(); + } + FieldExprent fexpr = (FieldExprent)ret.getLeft(); + + if (fexpr.isStatic()) { + ret.replaceExprent(ret.getRight(), invexpr.getLstParameters().get(0)); + } + else { + ret.replaceExprent(ret.getRight(), invexpr.getLstParameters().get(1)); + fexpr.replaceExprent(fexpr.getInstance(), invexpr.getLstParameters().get(0)); + } + retexprent = ret; + break; + case METHOD_ACCESS_METHOD: + if (source.type == Exprent.EXPRENT_EXIT) { + source = ((ExitExprent)source).getValue(); + } + + InvocationExprent invret = (InvocationExprent)source.copy(); + + int index = 0; + if (!invret.isStatic()) { + invret.replaceExprent(invret.getInstance(), invexpr.getLstParameters().get(0)); + index = 1; + } + + for (int i = 0; i < invret.getLstParameters().size(); i++) { + invret.replaceExprent(invret.getLstParameters().get(i), invexpr.getLstParameters().get(i + index)); + } + + retexprent = invret; + } + + + if (retexprent != null) { + // hide synthetic access method + boolean hide = true; + + if (node.type == ClassNode.CLASS_ROOT || (node.access & CodeConstants.ACC_STATIC) != 0) { + StructMethod mt = methsource.methodStruct; + if (!mt.isSynthetic()) { + hide = false; + } + } + if (hide) { + node.wrapper.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(invexpr.getName(), invexpr.getStringDescriptor())); + } + } + + return retexprent; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/code/DeadCodeHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/code/DeadCodeHelper.java new file mode 100644 index 000000000000..c7dd8ca1c173 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/code/DeadCodeHelper.java @@ -0,0 +1,436 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.code; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.code.InstructionSequence; +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.code.cfg.ControlFlowGraph; +import org.jetbrains.java.decompiler.code.cfg.ExceptionRangeCFG; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; + +import java.util.*; + +public class DeadCodeHelper { + + public static void removeDeadBlocks(ControlFlowGraph graph) { + + LinkedList<BasicBlock> stack = new LinkedList<BasicBlock>(); + HashSet<BasicBlock> setStacked = new HashSet<BasicBlock>(); + + stack.add(graph.getFirst()); + setStacked.add(graph.getFirst()); + + while (!stack.isEmpty()) { + BasicBlock block = stack.removeFirst(); + + List<BasicBlock> lstSuccs = new ArrayList<BasicBlock>(block.getSuccs()); + lstSuccs.addAll(block.getSuccExceptions()); + + for (BasicBlock succ : lstSuccs) { + if (!setStacked.contains(succ)) { + stack.add(succ); + setStacked.add(succ); + } + } + } + + HashSet<BasicBlock> setAllBlocks = new HashSet<BasicBlock>(graph.getBlocks()); + setAllBlocks.removeAll(setStacked); + + for (BasicBlock block : setAllBlocks) { + graph.removeBlock(block); + } + } + + public static void removeEmptyBlocks(ControlFlowGraph graph) { + + List<BasicBlock> blocks = graph.getBlocks(); + + boolean cont; + do { + cont = false; + + for (int i = blocks.size() - 1; i >= 0; i--) { + BasicBlock block = blocks.get(i); + + if (removeEmptyBlock(graph, block, false)) { + cont = true; + break; + } + } + } + while (cont); + } + + private static boolean removeEmptyBlock(ControlFlowGraph graph, BasicBlock block, boolean merging) { + + boolean deletedRanges = false; + + if (block.getSeq().isEmpty()) { + + if (block.getSuccs().size() > 1) { + if (block.getPreds().size() > 1) { + // ambiguous block + throw new RuntimeException("ERROR: empty block with multiple predecessors and successors found"); + } + else if (!merging) { + throw new RuntimeException("ERROR: empty block with multiple successors found"); + } + } + + HashSet<BasicBlock> setExits = new HashSet<BasicBlock>(graph.getLast().getPreds()); + + if (block.getPredExceptions().isEmpty() && + (!setExits.contains(block) || block.getPreds().size() == 1)) { + + if (setExits.contains(block)) { + BasicBlock pred = block.getPreds().get(0); + + // FIXME: flag in the basic block + if (pred.getSuccs().size() != 1 || (!pred.getSeq().isEmpty() + && pred.getSeq().getLastInstr().group == CodeConstants.GROUP_SWITCH)) { + return false; + } + } + + HashSet<BasicBlock> setPreds = new HashSet<BasicBlock>(block.getPreds()); + HashSet<BasicBlock> setSuccs = new HashSet<BasicBlock>(block.getSuccs()); + + // collect common exception ranges of predecessors and successors + HashSet<BasicBlock> setCommonExceptionHandlers = null; + for (int i = 0; i < 2; ++i) { + for (BasicBlock pred : i == 0 ? setPreds : setSuccs) { + if (setCommonExceptionHandlers == null) { + setCommonExceptionHandlers = new HashSet<BasicBlock>(pred.getSuccExceptions()); + } + else { + setCommonExceptionHandlers.retainAll(pred.getSuccExceptions()); + } + } + } + + // check the block to be in each of the common ranges + if (setCommonExceptionHandlers != null && !setCommonExceptionHandlers.isEmpty()) { + for (BasicBlock handler : setCommonExceptionHandlers) { + if (!block.getSuccExceptions().contains(handler)) { + return false; + } + } + } + + // remove ranges consisting of this one block + List<ExceptionRangeCFG> lstRanges = graph.getExceptions(); + for (int i = lstRanges.size() - 1; i >= 0; i--) { + ExceptionRangeCFG range = lstRanges.get(i); + List<BasicBlock> lst = range.getProtectedRange(); + + if (lst.size() == 1 && lst.get(0) == block) { + if (DecompilerContext.getOption(IFernflowerPreferences.REMOVE_EMPTY_RANGES)) { + block.removeSuccessorException(range.getHandler()); + lstRanges.remove(i); + + deletedRanges = true; + } + else { + return false; + } + } + } + + + // connect remaining nodes + if (merging) { + BasicBlock pred = block.getPreds().get(0); + pred.removeSuccessor(block); + + List<BasicBlock> lstSuccs = new ArrayList<BasicBlock>(block.getSuccs()); + for (BasicBlock succ : lstSuccs) { + block.removeSuccessor(succ); + pred.addSuccessor(succ); + } + } + else { + for (BasicBlock pred : setPreds) { + for (BasicBlock succ : setSuccs) { + pred.replaceSuccessor(block, succ); + } + } + } + + // finally exit edges + Set<BasicBlock> setFinallyExits = graph.getFinallyExits(); + if (setFinallyExits.contains(block)) { + setFinallyExits.remove(block); + setFinallyExits.add(setPreds.iterator().next()); + } + + // replace first if necessary + if (graph.getFirst() == block) { + if (setSuccs.size() != 1) { + throw new RuntimeException("multiple or no entry blocks!"); + } + else { + graph.setFirst(setSuccs.iterator().next()); + } + } + + // remove this block + graph.removeBlock(block); + + if (deletedRanges) { + removeDeadBlocks(graph); + } + } + } + + return deletedRanges; + } + + + public static boolean isDominator(ControlFlowGraph graph, BasicBlock block, BasicBlock dom) { + + HashSet<BasicBlock> marked = new HashSet<BasicBlock>(); + + if (block == dom) { + return true; + } + + LinkedList<BasicBlock> lstNodes = new LinkedList<BasicBlock>(); + lstNodes.add(block); + + while (!lstNodes.isEmpty()) { + + BasicBlock node = lstNodes.remove(0); + if (marked.contains(node)) { + continue; + } + else { + marked.add(node); + } + + if (node == graph.getFirst()) { + return false; + } + + for (int i = 0; i < node.getPreds().size(); i++) { + BasicBlock pred = node.getPreds().get(i); + if (!marked.contains(pred) && pred != dom) { + lstNodes.add(pred); + } + } + + for (int i = 0; i < node.getPredExceptions().size(); i++) { + BasicBlock pred = node.getPredExceptions().get(i); + if (!marked.contains(pred) && pred != dom) { + lstNodes.add(pred); + } + } + } + + return true; + } + + public static void removeGotos(ControlFlowGraph graph) { + + for (BasicBlock block : graph.getBlocks()) { + Instruction instr = block.getLastInstruction(); + + if (instr != null && instr.opcode == CodeConstants.opc_goto) { + block.getSeq().removeInstruction(block.getSeq().length() - 1); + } + } + + removeEmptyBlocks(graph); + } + + public static void connectDummyExitBlock(ControlFlowGraph graph) { + + BasicBlock exit = graph.getLast(); + for (BasicBlock block : new HashSet<BasicBlock>(exit.getPreds())) { + exit.removePredecessor(block); + block.addSuccessor(exit); + } + } + + public static void incorporateValueReturns(ControlFlowGraph graph) { + + for (BasicBlock block : graph.getBlocks()) { + InstructionSequence seq = block.getSeq(); + + int len = seq.length(); + if (len > 0 && len < 3) { + + boolean ok = false; + + if (seq.getLastInstr().opcode >= CodeConstants.opc_ireturn && seq.getLastInstr().opcode <= CodeConstants.opc_return) { + if (len == 1) { + ok = true; + } + else if (seq.getLastInstr().opcode != CodeConstants.opc_return) { + switch (seq.getInstr(0).opcode) { + case CodeConstants.opc_iload: + case CodeConstants.opc_lload: + case CodeConstants.opc_fload: + case CodeConstants.opc_dload: + case CodeConstants.opc_aload: + case CodeConstants.opc_aconst_null: + case CodeConstants.opc_bipush: + case CodeConstants.opc_sipush: + case CodeConstants.opc_lconst_0: + case CodeConstants.opc_lconst_1: + case CodeConstants.opc_fconst_0: + case CodeConstants.opc_fconst_1: + case CodeConstants.opc_fconst_2: + case CodeConstants.opc_dconst_0: + case CodeConstants.opc_dconst_1: + case CodeConstants.opc_ldc: + case CodeConstants.opc_ldc_w: + case CodeConstants.opc_ldc2_w: + ok = true; + } + } + } + + if (ok) { + + if (!block.getPreds().isEmpty()) { + + HashSet<BasicBlock> setPredHandlersUnion = new HashSet<BasicBlock>(); + HashSet<BasicBlock> setPredHandlersIntersection = new HashSet<BasicBlock>(); + + boolean firstpred = true; + for (BasicBlock pred : block.getPreds()) { + if (firstpred) { + setPredHandlersIntersection.addAll(pred.getSuccExceptions()); + firstpred = false; + } + else { + setPredHandlersIntersection.retainAll(pred.getSuccExceptions()); + } + + setPredHandlersUnion.addAll(pred.getSuccExceptions()); + } + + // add exception ranges from predecessors + setPredHandlersIntersection.removeAll(block.getSuccExceptions()); + BasicBlock predecessor = block.getPreds().get(0); + + for (BasicBlock handler : setPredHandlersIntersection) { + ExceptionRangeCFG range = graph.getExceptionRange(handler, predecessor); + + range.getProtectedRange().add(block); + block.addSuccessorException(handler); + } + + // remove redundant ranges + HashSet<BasicBlock> setRangesToBeRemoved = new HashSet<BasicBlock>(block.getSuccExceptions()); + setRangesToBeRemoved.removeAll(setPredHandlersUnion); + + for (BasicBlock handler : setRangesToBeRemoved) { + ExceptionRangeCFG range = graph.getExceptionRange(handler, block); + + if (range.getProtectedRange().size() > 1) { + range.getProtectedRange().remove(block); + block.removeSuccessorException(handler); + } + } + } + + + if (block.getPreds().size() == 1 && block.getPredExceptions().isEmpty()) { + + BasicBlock bpred = block.getPreds().get(0); + if (bpred.getSuccs().size() == 1) { + + // add exception ranges of predecessor + for (BasicBlock succ : bpred.getSuccExceptions()) { + if (!block.getSuccExceptions().contains(succ)) { + ExceptionRangeCFG range = graph.getExceptionRange(succ, bpred); + + range.getProtectedRange().add(block); + block.addSuccessorException(succ); + } + } + + // remove superfluous ranges from successors + for (BasicBlock succ : new HashSet<BasicBlock>(block.getSuccExceptions())) { + if (!bpred.getSuccExceptions().contains(succ)) { + ExceptionRangeCFG range = graph.getExceptionRange(succ, block); + + if (range.getProtectedRange().size() > 1) { + range.getProtectedRange().remove(block); + block.removeSuccessorException(succ); + } + } + } + } + } + } + } + } + } + + + public static void mergeBasicBlocks(ControlFlowGraph graph) { + + while (true) { + + boolean merged = false; + + for (BasicBlock block : graph.getBlocks()) { + + InstructionSequence seq = block.getSeq(); + + if (block.getSuccs().size() == 1) { + BasicBlock next = block.getSuccs().get(0); + + if (next != graph.getLast() && (seq.isEmpty() || seq.getLastInstr().group != CodeConstants.GROUP_SWITCH)) { + + if (next.getPreds().size() == 1 && next.getPredExceptions().isEmpty() + && next != graph.getFirst()) { + // TODO: implement a dummy start block + boolean sameRanges = true; + for (ExceptionRangeCFG range : graph.getExceptions()) { + if (range.getProtectedRange().contains(block) ^ + range.getProtectedRange().contains(next)) { + sameRanges = false; + break; + } + } + + if (sameRanges) { + seq.addSequence(next.getSeq()); + next.getSeq().clear(); + + removeEmptyBlock(graph, next, true); + + merged = true; + break; + } + } + } + } + } + + if (!merged) { + break; + } + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ClearStructHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ClearStructHelper.java new file mode 100644 index 000000000000..c6495e6ad13f --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ClearStructHelper.java @@ -0,0 +1,40 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.LinkedList; + + +public class ClearStructHelper { + + public static void clearStatements(RootStatement root) { + + LinkedList<Statement> stack = new LinkedList<Statement>(); + stack.add(root); + + while (!stack.isEmpty()) { + + Statement stat = stack.removeFirst(); + + stat.clearTempInformation(); + + stack.addAll(stat.getStats()); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ConcatenationHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ConcatenationHelper.java new file mode 100644 index 000000000000..1b641a695f2e --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ConcatenationHelper.java @@ -0,0 +1,209 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.util.ArrayList; +import java.util.List; + +public class ConcatenationHelper { + + private static final String builderClass = "java/lang/StringBuilder"; + private static final String bufferClass = "java/lang/StringBuffer"; + private static final String stringClass = "java/lang/String"; + + private static final VarType builderType = new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/StringBuilder"); + private static final VarType bufferType = new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/StringBuffer"); + + + public static Exprent contractStringConcat(Exprent expr) { + + Exprent exprTmp = null; + VarType cltype = null; + + // first quick test + if (expr.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent iex = (InvocationExprent)expr; + if ("toString".equals(iex.getName())) { + if (builderClass.equals(iex.getClassname())) { + cltype = builderType; + } + else if (bufferClass.equals(iex.getClassname())) { + cltype = bufferType; + } + if (cltype != null) { + exprTmp = iex.getInstance(); + } + } + } + + if (exprTmp == null) { + return expr; + } + + + // iterate in depth, collecting possible operands + List<Exprent> lstOperands = new ArrayList<Exprent>(); + + while (true) { + + int found = 0; + + switch (exprTmp.type) { + case Exprent.EXPRENT_INVOCATION: + InvocationExprent iex = (InvocationExprent)exprTmp; + if (isAppendConcat(iex, cltype)) { + lstOperands.add(0, iex.getLstParameters().get(0)); + exprTmp = iex.getInstance(); + found = 1; + } + break; + case Exprent.EXPRENT_NEW: + NewExprent nex = (NewExprent)exprTmp; + if (isNewConcat(nex, cltype)) { + VarType[] params = nex.getConstructor().getDescriptor().params; + if (params.length == 1) { + lstOperands.add(0, nex.getConstructor().getLstParameters().get(0)); + } + found = 2; + } + } + + if (found == 0) { + return expr; + } + else if (found == 2) { + break; + } + } + + int first2str = 0; + int index = 0; + while (index < lstOperands.size() && index < 2) { + if (lstOperands.get(index).getExprType().equals(VarType.VARTYPE_STRING)) { + first2str |= (index + 1); + } + index++; + } + + if (first2str == 0) { + lstOperands.add(0, new ConstExprent(VarType.VARTYPE_STRING, "")); + } + + // remove redundant String.valueOf + for (int i = 0; i < lstOperands.size(); i++) { + Exprent rep = removeStringValueOf(lstOperands.get(i)); + + boolean ok = (i > 1); + if (!ok) { + boolean isstr = rep.getExprType().equals(VarType.VARTYPE_STRING); + ok = isstr || first2str != i + 1; + + if (i == 0) { + first2str &= 2; + } + } + + if (ok) { + lstOperands.set(i, rep); + } + } + + // build exprent to return + Exprent func = lstOperands.get(0); + + for (int i = 1; i < lstOperands.size(); i++) { + List<Exprent> lstTmp = new ArrayList<Exprent>(); + lstTmp.add(func); + lstTmp.add(lstOperands.get(i)); + func = new FunctionExprent(FunctionExprent.FUNCTION_STRCONCAT, lstTmp); + } + + return func; + } + + private static boolean isAppendConcat(InvocationExprent expr, VarType cltype) { + + if ("append".equals(expr.getName())) { + MethodDescriptor md = expr.getDescriptor(); + if (md.ret.equals(cltype) && md.params.length == 1) { + VarType param = md.params[0]; + switch (param.type) { + case CodeConstants.TYPE_OBJECT: + if (!param.equals(VarType.VARTYPE_STRING) && + !param.equals(VarType.VARTYPE_OBJECT)) { + break; + } + case CodeConstants.TYPE_BOOLEAN: + case CodeConstants.TYPE_CHAR: + case CodeConstants.TYPE_DOUBLE: + case CodeConstants.TYPE_FLOAT: + case CodeConstants.TYPE_INT: + case CodeConstants.TYPE_LONG: + return true; + default: + } + } + } + + return false; + } + + private static boolean isNewConcat(NewExprent expr, VarType cltype) { + + if (expr.getNewtype().equals(cltype)) { + VarType[] params = expr.getConstructor().getDescriptor().params; + if (params.length == 0 || (params.length == 1 && + params[0].equals(VarType.VARTYPE_STRING))) { + return true; + } + } + + return false; + } + + private static Exprent removeStringValueOf(Exprent exprent) { + + if (exprent.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent iex = (InvocationExprent)exprent; + if ("valueOf".equals(iex.getName()) && stringClass.equals(iex.getClassname())) { + MethodDescriptor md = iex.getDescriptor(); + if (md.params.length == 1) { + VarType param = md.params[0]; + switch (param.type) { + case CodeConstants.TYPE_OBJECT: + if (!param.equals(VarType.VARTYPE_OBJECT)) { + break; + } + case CodeConstants.TYPE_BOOLEAN: + case CodeConstants.TYPE_CHAR: + case CodeConstants.TYPE_DOUBLE: + case CodeConstants.TYPE_FLOAT: + case CodeConstants.TYPE_INT: + case CodeConstants.TYPE_LONG: + return iex.getLstParameters().get(0); + } + } + } + } + + return exprent; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DecHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DecHelper.java new file mode 100644 index 000000000000..9c719dbc9141 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DecHelper.java @@ -0,0 +1,218 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.*; + + +public class DecHelper { + + public static boolean checkStatementExceptions(List<Statement> lst) { + + Set<Statement> all = new HashSet<Statement>(lst); + + Set<Statement> handlers = new HashSet<Statement>(); + Set<Statement> intersection = null; + + for (Statement stat : lst) { + Set<Statement> setNew = stat.getNeighboursSet(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_FORWARD); + + if (intersection == null) { + intersection = setNew; + } + else { + HashSet<Statement> interclone = new HashSet<Statement>(intersection); + interclone.removeAll(setNew); + + intersection.retainAll(setNew); + + setNew.removeAll(intersection); + + handlers.addAll(interclone); + handlers.addAll(setNew); + } + } + + for (Statement stat : handlers) { + if (!all.contains(stat) || !all.containsAll(stat.getNeighbours(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_BACKWARD))) { + return false; + } + } + + // check for other handlers (excluding head) + for (int i = 1; i < lst.size(); i++) { + Statement stat = lst.get(i); + if (!stat.getPredecessorEdges(StatEdge.TYPE_EXCEPTION).isEmpty() && !handlers.contains(stat)) { + return false; + } + } + + return true; + } + + public static boolean isChoiceStatement(Statement head, List<Statement> lst) { + + Statement post = null; + + Set<Statement> setDest = head.getNeighboursSet(StatEdge.TYPE_REGULAR, Statement.DIRECTION_FORWARD); + + if (setDest.contains(head)) { + return false; + } + + while (true) { + + lst.clear(); + + boolean repeat = false; + + setDest.remove(post); + + for (Statement stat : setDest) { + if (stat.getLastBasicType() != Statement.LASTBASICTYPE_GENERAL) { + if (post == null) { + post = stat; + repeat = true; + break; + } + else { + return false; + } + } + + // preds + Set<Statement> setPred = stat.getNeighboursSet(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD); + setPred.remove(head); + if (setPred.contains(stat)) { + return false; + } + + if (!setDest.containsAll(setPred) || setPred.size() > 1) { + if (post == null) { + post = stat; + repeat = true; + break; + } + else { + return false; + } + } + else if (setPred.size() == 1) { + Statement pred = setPred.iterator().next(); + while (lst.contains(pred)) { + Set<Statement> setPredTemp = pred.getNeighboursSet(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD); + setPredTemp.remove(head); + + if (!setPredTemp.isEmpty()) { // at most 1 predecessor + pred = setPredTemp.iterator().next(); + if (pred == stat) { + return false; // loop found + } + } + else { + break; + } + } + } + + // succs + List<StatEdge> lstEdges = stat.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL); + if (lstEdges.size() > 1) { + Set<Statement> setSucc = stat.getNeighboursSet(Statement.STATEDGE_DIRECT_ALL, Statement.DIRECTION_FORWARD); + setSucc.retainAll(setDest); + + if (setSucc.size() > 0) { + return false; + } + else { + if (post == null) { + post = stat; + repeat = true; + break; + } + else { + return false; + } + } + } + else if (lstEdges.size() == 1) { + + StatEdge edge = lstEdges.get(0); + if (edge.getType() == StatEdge.TYPE_REGULAR) { + Statement statd = edge.getDestination(); + if (head == statd) { + return false; + } + if (!setDest.contains(statd) && post != statd) { + if (post != null) { + return false; + } + else { + Set<Statement> set = statd.getNeighboursSet(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD); + if (set.size() > 1) { + post = statd; + repeat = true; + break; + } + else { + return false; + } + } + } + } + } + + lst.add(stat); + } + + if (!repeat) { + break; + } + } + + lst.add(head); + lst.remove(post); + + lst.add(0, post); + + return true; + } + + + public static HashSet<Statement> getUniquePredExceptions(Statement head) { + + HashSet<Statement> setHandlers = new HashSet<Statement>(head.getNeighbours(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_FORWARD)); + + Iterator<Statement> it = setHandlers.iterator(); + while (it.hasNext()) { + if (it.next().getPredecessorEdges(StatEdge.TYPE_EXCEPTION).size() > 1) { + it.remove(); + } + } + return setHandlers; + } + + public static List<Exprent> copyExprentList(List<Exprent> lst) { + List<Exprent> ret = new ArrayList<Exprent>(); + for (Exprent expr : lst) { + ret.add(expr.copy()); + } + return ret; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DomHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DomHelper.java new file mode 100644 index 000000000000..3bb45840f91d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/DomHelper.java @@ -0,0 +1,707 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.code.cfg.ControlFlowGraph; +import org.jetbrains.java.decompiler.code.cfg.ExceptionRangeCFG; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.modules.decompiler.decompose.FastExtendedPostdominanceHelper; +import org.jetbrains.java.decompiler.modules.decompiler.deobfuscator.IrreducibleCFGDeobfuscator; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; +import org.jetbrains.java.decompiler.util.FastFixedSetFactory; +import org.jetbrains.java.decompiler.util.FastFixedSetFactory.FastFixedSet; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.*; + +public class DomHelper { + + + private static RootStatement graphToStatement(ControlFlowGraph graph) { + + VBStyleCollection<Statement, Integer> stats = new VBStyleCollection<Statement, Integer>(); + VBStyleCollection<BasicBlock, Integer> blocks = graph.getBlocks(); + + for (BasicBlock block : blocks) { + stats.addWithKey(new BasicBlockStatement(block), block.id); + } + + BasicBlock firstblock = graph.getFirst(); + // head statement + Statement firstst = stats.getWithKey(firstblock.id); + // dummy exit statement + Statement dummyexit = new Statement(); + dummyexit.type = Statement.TYPE_DUMMYEXIT; + + Statement general; + if (stats.size() > 1 || firstblock.isSuccessor(firstblock)) { // multiple basic blocks or an infinite loop of one block + general = new GeneralStatement(firstst, stats, null); + } + else { // one straightforward basic block + RootStatement root = new RootStatement(firstst, dummyexit); + firstst.addSuccessor(new StatEdge(StatEdge.TYPE_BREAK, firstst, dummyexit, root)); + + return root; + } + + for (BasicBlock block : blocks) { + Statement stat = stats.getWithKey(block.id); + + for (BasicBlock succ : block.getSuccs()) { + Statement stsucc = stats.getWithKey(succ.id); + + int type; + if (stsucc == firstst) { + type = StatEdge.TYPE_CONTINUE; + } + else if (graph.getFinallyExits().contains(block)) { + type = StatEdge.TYPE_FINALLYEXIT; + stsucc = dummyexit; + } + else if (succ.id == graph.getLast().id) { + type = StatEdge.TYPE_BREAK; + stsucc = dummyexit; + } + else { + type = StatEdge.TYPE_REGULAR; + } + + stat.addSuccessor(new StatEdge(type, stat, (type == StatEdge.TYPE_CONTINUE) ? general : stsucc, + (type == StatEdge.TYPE_REGULAR) ? null : general)); + } + + // exceptions edges + for (BasicBlock succex : block.getSuccExceptions()) { + Statement stsuccex = stats.getWithKey(succex.id); + + ExceptionRangeCFG range = graph.getExceptionRange(succex, block); + if (!range.isCircular()) { + stat.addSuccessor(new StatEdge(stat, stsuccex, range.getExceptionTypes())); + } + } + } + + general.buildContinueSet(); + general.buildMonitorFlags(); + return new RootStatement(general, dummyexit); + } + + public static VBStyleCollection<List<Integer>, Integer> calcPostDominators(Statement container) { + + HashMap<Statement, FastFixedSet<Statement>> lists = new HashMap<Statement, FastFixedSet<Statement>>(); + + StrongConnectivityHelper schelper = new StrongConnectivityHelper(container); + List<List<Statement>> components = schelper.getComponents(); + + List<Statement> lstStats = container.getPostReversePostOrderList(StrongConnectivityHelper.getExitReps(components)); + + FastFixedSetFactory<Statement> factory = new FastFixedSetFactory<Statement>(lstStats); + + FastFixedSet<Statement> setFlagNodes = factory.spawnEmptySet(); + setFlagNodes.setAllElements(); + + FastFixedSet<Statement> initSet = factory.spawnEmptySet(); + initSet.setAllElements(); + + for (List<Statement> lst : components) { + FastFixedSet<Statement> tmpSet; + + if (StrongConnectivityHelper.isExitComponent(lst)) { + tmpSet = factory.spawnEmptySet(); + tmpSet.addAll(lst); + } + else { + tmpSet = initSet.getCopy(); + } + + for (Statement stat : lst) { + lists.put(stat, tmpSet); + } + } + + do { + + for (Statement stat : lstStats) { + + if (!setFlagNodes.contains(stat)) { + continue; + } + setFlagNodes.remove(stat); + + FastFixedSet<Statement> doms = lists.get(stat); + FastFixedSet<Statement> domsSuccs = factory.spawnEmptySet(); + + List<Statement> lstSuccs = stat.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_FORWARD); + for (int j = 0; j < lstSuccs.size(); j++) { + Statement succ = lstSuccs.get(j); + FastFixedSet<Statement> succlst = lists.get(succ); + + if (j == 0) { + domsSuccs.union(succlst); + } + else { + domsSuccs.intersection(succlst); + } + } + + if (!domsSuccs.contains(stat)) { + domsSuccs.add(stat); + } + + if (!InterpreterUtil.equalObjects(domsSuccs, doms)) { + + lists.put(stat, domsSuccs); + + List<Statement> lstPreds = stat.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD); + for (Statement pred : lstPreds) { + setFlagNodes.add(pred); + } + } + } + } + while (!setFlagNodes.isEmpty()); + + VBStyleCollection<List<Integer>, Integer> ret = new VBStyleCollection<List<Integer>, Integer>(); + List<Statement> lstRevPost = container.getReversePostOrderList(); // sort order crucial! + + final HashMap<Integer, Integer> mapSortOrder = new HashMap<Integer, Integer>(); + for (int i = 0; i < lstRevPost.size(); i++) { + mapSortOrder.put(lstRevPost.get(i).id, i); + } + + for (Statement st : lstStats) { + + List<Integer> lstPosts = new ArrayList<Integer>(); + for (Statement stt : lists.get(st)) { + lstPosts.add(stt.id); + } + + Collections.sort(lstPosts, new Comparator<Integer>() { + public int compare(Integer o1, Integer o2) { + return mapSortOrder.get(o1).compareTo(mapSortOrder.get(o2)); + } + }); + + if (lstPosts.size() > 1 && lstPosts.get(0).intValue() == st.id) { + lstPosts.add(lstPosts.remove(0)); + } + + ret.addWithKey(lstPosts, st.id); + } + + return ret; + } + + public static RootStatement parseGraph(ControlFlowGraph graph) { + + RootStatement root = graphToStatement(graph); + + if (!processStatement(root, new HashMap<Integer, Set<Integer>>())) { + DecompilerContext.getLogger().writeMessage("parsing failure!", IFernflowerLogger.Severity.ERROR); + + // try { + // DotExporter.toDotFile(root.getFirst().getStats().get(13), new File("c:\\Temp\\stat1.dot")); + // } catch (Exception ex) { + // ex.printStackTrace(); + // } + throw new RuntimeException("parsing failure!"); + } + + LabelHelper.lowContinueLabels(root, new HashSet<StatEdge>()); + + SequenceHelper.condenseSequences(root); + root.buildMonitorFlags(); + + // build synchronized statements + buildSynchronized(root); + + return root; + } + + public static void removeSynchronizedHandler(Statement stat) { + + for (Statement st : stat.getStats()) { + removeSynchronizedHandler(st); + } + + if (stat.type == Statement.TYPE_SYNCRONIZED) { + ((SynchronizedStatement)stat).removeExc(); + } + } + + + private static void buildSynchronized(Statement stat) { + + for (Statement st : stat.getStats()) { + buildSynchronized(st); + } + + if (stat.type == Statement.TYPE_SEQUENCE) { + + while (true) { + + boolean found = false; + + List<Statement> lst = stat.getStats(); + for (int i = 0; i < lst.size() - 1; i++) { + Statement current = lst.get(i); // basic block + + if (current.isMonitorEnter()) { + + Statement next = lst.get(i + 1); + Statement nextDirect = next; + + while (next.type == Statement.TYPE_SEQUENCE) { + next = next.getFirst(); + } + + if (next.type == Statement.TYPE_CATCHALL) { + + CatchAllStatement ca = (CatchAllStatement)next; + + if (ca.getFirst().isContainsMonitorExit() && ca.getHandler().isContainsMonitorExit()) { + + // remove the head block from sequence + current.removeSuccessor(current.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL).get(0)); + + for (StatEdge edge : current.getPredecessorEdges(Statement.STATEDGE_DIRECT_ALL)) { + current.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, nextDirect); + nextDirect.addPredecessor(edge); + } + + stat.getStats().removeWithKey(current.id); + stat.setFirst(stat.getStats().get(0)); + + // new statement + SynchronizedStatement sync = new SynchronizedStatement(current, ca.getFirst(), ca.getHandler()); + sync.setAllParent(); + + for (StatEdge edge : new HashSet<StatEdge>(ca.getLabelEdges())) { + sync.addLabeledEdge(edge); + } + + current.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, current, ca.getFirst())); + + ca.getParent().replaceStatement(ca, sync); + found = true; + break; + } + } + } + } + + if (!found) { + break; + } + } + } + } + + private static boolean processStatement(Statement general, HashMap<Integer, Set<Integer>> mapExtPost) { + + if (general.type == Statement.TYPE_ROOT) { + Statement stat = general.getFirst(); + if (stat.type != Statement.TYPE_GENERAL) { + return true; + } + else { + boolean complete = processStatement(stat, mapExtPost); + if (complete) { + // replace general purpose statement with simple one + general.replaceStatement(stat, stat.getFirst()); + } + return complete; + } + } + + boolean mapRefreshed = mapExtPost.isEmpty(); + + for (int mapstage = 0; mapstage < 2; mapstage++) { + + for (int reducibility = 0; + reducibility < 5; + reducibility++) { // FIXME: implement proper node splitting. For now up to 5 nodes in sequence are splitted. + + if (reducibility > 0) { + + // try { + // DotExporter.toDotFile(general, new File("c:\\Temp\\stat1.dot")); + // } catch(Exception ex) {ex.printStackTrace();} + + // take care of irreducible control flow graphs + if (IrreducibleCFGDeobfuscator.isStatementIrreducible(general)) { + if (!IrreducibleCFGDeobfuscator.splitIrreducibleNode(general)) { + DecompilerContext.getLogger().writeMessage("Irreducible statement cannot be decomposed!", IFernflowerLogger.Severity.ERROR); + break; + } + } + else { + if (mapstage == 2 || mapRefreshed) { // last chance lost + DecompilerContext.getLogger().writeMessage("Statement cannot be decomposed although reducible!", + IFernflowerLogger.Severity.ERROR); + } + break; + } + + // try { + // DotExporter.toDotFile(general, new File("c:\\Temp\\stat1.dot")); + // } catch(Exception ex) {ex.printStackTrace();} + + mapExtPost = new HashMap<Integer, Set<Integer>>(); + mapRefreshed = true; + } + + for (int i = 0; i < 2; i++) { + + boolean forceall = i != 0; + + while (true) { + + if (findSimpleStatements(general, mapExtPost)) { + reducibility = 0; + } + + if (general.type == Statement.TYPE_PLACEHOLDER) { + return true; + } + + Statement stat = findGeneralStatement(general, forceall, mapExtPost); + + if (stat != null) { + boolean complete = processStatement(stat, general.getFirst() == stat ? mapExtPost : new HashMap<Integer, Set<Integer>>()); + + if (complete) { + // replace general purpose statement with simple one + general.replaceStatement(stat, stat.getFirst()); + } + else { + return false; + } + + mapExtPost = new HashMap<Integer, Set<Integer>>(); + mapRefreshed = true; + reducibility = 0; + } + else { + break; + } + } + } + + // try { + // DotExporter.toDotFile(general, new File("c:\\Temp\\stat1.dot")); + // } catch (Exception ex) { + // ex.printStackTrace(); + // } + } + + if (mapRefreshed) { + break; + } + else { + mapExtPost = new HashMap<Integer, Set<Integer>>(); + } + } + + return false; + } + + private static Statement findGeneralStatement(Statement stat, boolean forceall, HashMap<Integer, Set<Integer>> mapExtPost) { + + VBStyleCollection<Statement, Integer> stats = stat.getStats(); + VBStyleCollection<List<Integer>, Integer> vbPost; + + if (mapExtPost.isEmpty()) { + FastExtendedPostdominanceHelper extpost = new FastExtendedPostdominanceHelper(); + mapExtPost.putAll(extpost.getExtendedPostdominators(stat)); + } + + if (forceall) { + vbPost = new VBStyleCollection<List<Integer>, Integer>(); + List<Statement> lstAll = stat.getPostReversePostOrderList(); + + for (Statement st : lstAll) { + Set<Integer> set = mapExtPost.get(st.id); + if (set != null) { + vbPost.addWithKey(new ArrayList<Integer>(set), st.id); // FIXME: sort order!! + } + } + + // tail statements + Set<Integer> setFirst = mapExtPost.get(stat.getFirst().id); + if (setFirst != null) { + for (Integer id : setFirst) { + List<Integer> lst = vbPost.getWithKey(id); + if (lst == null) { + vbPost.addWithKey(lst = new ArrayList<Integer>(), id); + } + lst.add(id); + } + } + } + else { + vbPost = calcPostDominators(stat); + } + + for (int k = 0; k < vbPost.size(); k++) { + + Integer headid = vbPost.getKey(k); + List<Integer> posts = vbPost.get(k); + + if (!mapExtPost.containsKey(headid) && + !(posts.size() == 1 && posts.get(0).equals(headid))) { + continue; + } + + Statement head = stats.getWithKey(headid); + + Set<Integer> setExtPosts = mapExtPost.get(headid); + + for (int i = 0; i < posts.size(); i++) { + + Integer postid = posts.get(i); + if (!postid.equals(headid) && !setExtPosts.contains(postid)) { + continue; + } + + Statement post = stats.getWithKey(postid); + + if (post == null) { // possible in case of an inherited postdominance set + continue; + } + + boolean same = (post == head); + + HashSet<Statement> setNodes = new HashSet<Statement>(); + HashSet<Statement> setPreds = new HashSet<Statement>(); + + // collect statement nodes + HashSet<Statement> setHandlers = new HashSet<Statement>(); + setHandlers.add(head); + while (true) { + + boolean hdfound = false; + for (Statement handler : setHandlers) { + if (setNodes.contains(handler)) { + continue; + } + + boolean addhd = (setNodes.size() == 0); // first handler == head + if (!addhd) { + List<Statement> hdsupp = handler.getNeighbours(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_BACKWARD); + addhd = (setNodes.containsAll(hdsupp) && (setNodes.size() > hdsupp.size() + || setNodes.size() == 1)); // strict subset + } + + if (addhd) { + LinkedList<Statement> lstStack = new LinkedList<Statement>(); + lstStack.add(handler); + + while (!lstStack.isEmpty()) { + Statement st = lstStack.remove(0); + + if (!(setNodes.contains(st) || (!same && st == post))) { + setNodes.add(st); + if (st != head) { + // record predeccessors except for the head + setPreds.addAll(st.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD)); + } + + // put successors on the stack + lstStack.addAll(st.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_FORWARD)); + + // exception edges + setHandlers.addAll(st.getNeighbours(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_FORWARD)); + } + } + + hdfound = true; + setHandlers.remove(handler); + break; + } + } + + if (!hdfound) { + break; + } + } + + // check exception handlers + setHandlers.clear(); + for (Statement st : setNodes) { + setHandlers.addAll(st.getNeighbours(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_FORWARD)); + } + setHandlers.removeAll(setNodes); + + boolean excok = true; + for (Statement handler : setHandlers) { + if (!handler.getNeighbours(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_BACKWARD).containsAll(setNodes)) { + excok = false; + break; + } + } + + // build statement and return + if (excok) { + Statement res = null; + + setPreds.removeAll(setNodes); + if (setPreds.size() == 0) { + if ((setNodes.size() > 1 || + head.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD).contains(head)) + && setNodes.size() < stats.size()) { + if (checkSynchronizedCompleteness(head, setNodes)) { + res = new GeneralStatement(head, setNodes, same ? null : post); + stat.collapseNodesToStatement(res); + + return res; + } + } + } + } + } + } + + return null; + } + + private static boolean checkSynchronizedCompleteness(Statement head, HashSet<Statement> setNodes) { + + // check exit nodes + for (Statement stat : setNodes) { + if (stat.isMonitorEnter()) { + List<StatEdge> lstSuccs = stat.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL); + if (lstSuccs.size() != 1 || lstSuccs.get(0).getType() != StatEdge.TYPE_REGULAR) { + return false; + } + + if (!setNodes.contains(lstSuccs.get(0).getDestination())) { + return false; + } + } + } + + return true; + } + + private static boolean findSimpleStatements(Statement stat, HashMap<Integer, Set<Integer>> mapExtPost) { + + boolean found, success = false; + + do { + found = false; + + List<Statement> lstStats = stat.getPostReversePostOrderList(); + for (Statement st : lstStats) { + + Statement result = detectStatement(st); + + if (result != null) { + + if (stat.type == Statement.TYPE_GENERAL && result.getFirst() == stat.getFirst() && + stat.getStats().size() == result.getStats().size()) { + // mark general statement + stat.type = Statement.TYPE_PLACEHOLDER; + } + + stat.collapseNodesToStatement(result); + + // update the postdominator map + if (!mapExtPost.isEmpty()) { + HashSet<Integer> setOldNodes = new HashSet<Integer>(); + for (Statement old : result.getStats()) { + setOldNodes.add(old.id); + } + + Integer newid = result.id; + + for (Integer key : new ArrayList<Integer>(mapExtPost.keySet())) { + Set<Integer> set = mapExtPost.get(key); + + int oldsize = set.size(); + set.removeAll(setOldNodes); + + if (setOldNodes.contains(key)) { + Set<Integer> setNew = mapExtPost.get(newid); + if (setNew == null) { + mapExtPost.put(newid, setNew = new HashSet<Integer>()); + } + setNew.addAll(set); + + mapExtPost.remove(key); + } + else { + if (set.size() < oldsize) { + set.add(newid); + } + } + } + } + + + found = true; + break; + } + } + + if (found) { + success = true; + } + } + while (found); + + return success; + } + + + private static Statement detectStatement(Statement head) { + + Statement res; + + if ((res = DoStatement.isHead(head)) != null) { + return res; + } + + if ((res = SwitchStatement.isHead(head)) != null) { + return res; + } + + if ((res = IfStatement.isHead(head)) != null) { + return res; + } + + // synchronized statements will be identified later + // right now they are recognized as catchall + + if ((res = SequenceStatement.isHead2Block(head)) != null) { + return res; + } + + if ((res = CatchStatement.isHead(head)) != null) { + return res; + } + + if ((res = CatchAllStatement.isHead(head)) != null) { + return res; + } + + return null; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/EliminateLoopsHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/EliminateLoopsHelper.java new file mode 100644 index 000000000000..16f7da084534 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/EliminateLoopsHelper.java @@ -0,0 +1,214 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.stats.DoStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + + +public class EliminateLoopsHelper { + + + // public static boolean eliminateLoops(Statement root) { + // + // boolean ret = eliminateLoopsRec(root); + // + // if(ret) { + // SequenceHelper.condenseSequences(root); + // + // HashSet<Integer> setReorderedIfs = new HashSet<Integer>(); + // + // SimplifyExprentsHelper sehelper = new SimplifyExprentsHelper(false); + // while(sehelper.simplifyStackVarsStatement(root, setReorderedIfs, null)) { + // SequenceHelper.condenseSequences(root); + // } + // } + // + // return ret; + // } + + private static boolean eliminateLoopsRec(Statement stat) { + + for (Statement st : stat.getStats()) { + if (eliminateLoopsRec(st)) { + return true; + } + } + + if (stat.type == Statement.TYPE_DO && isLoopRedundant((DoStatement)stat)) { + return true; + } + + return false; + } + + private static boolean isLoopRedundant(DoStatement loop) { + + if (loop.getLooptype() != DoStatement.LOOP_DO) { + return false; + } + + // get parent loop if exists + Statement parentloop = loop.getParent(); + while (parentloop != null && parentloop.type != Statement.TYPE_DO) { + parentloop = parentloop.getParent(); + } + + if (parentloop == null || parentloop.getBasichead() != loop.getBasichead()) { + return false; + } + + // collect relevant break edges + List<StatEdge> lstBreakEdges = new ArrayList<StatEdge>(); + for (StatEdge edge : loop.getLabelEdges()) { + if (edge.getType() == StatEdge.TYPE_BREAK) { // all break edges are explicit because of LOOP_DO type + lstBreakEdges.add(edge); + } + } + + + Statement loopcontent = loop.getFirst(); + + boolean firstok = loopcontent.getAllSuccessorEdges().isEmpty(); + if (!firstok) { + StatEdge edge = loopcontent.getAllSuccessorEdges().get(0); + firstok = (edge.closure == loop && edge.getType() == StatEdge.TYPE_BREAK); + if (firstok) { + lstBreakEdges.remove(edge); + } + } + + + if (!lstBreakEdges.isEmpty()) { + if (firstok) { + + HashMap<Integer, Boolean> statLabeled = new HashMap<Integer, Boolean>(); + List<Statement> lstEdgeClosures = new ArrayList<Statement>(); + + for (StatEdge edge : lstBreakEdges) { + Statement minclosure = LowBreakHelper.getMinClosure(loopcontent, edge.getSource()); + lstEdgeClosures.add(minclosure); + } + + int precount = loop.isLabeled() ? 1 : 0; + for (Statement st : lstEdgeClosures) { + if (!statLabeled.containsKey(st.id)) { + boolean btemp = st.isLabeled(); + precount += btemp ? 1 : 0; + statLabeled.put(st.id, btemp); + } + } + + for (int i = 0; i < lstBreakEdges.size(); i++) { + Statement st = lstEdgeClosures.get(i); + statLabeled.put(st.id, LowBreakHelper.isBreakEdgeLabeled(lstBreakEdges.get(i).getSource(), st) | statLabeled.get(st.id)); + } + + for (int i = 0; i < lstBreakEdges.size(); i++) { + lstEdgeClosures.set(i, getMaxBreakLift(lstEdgeClosures.get(i), lstBreakEdges.get(i), statLabeled, loop)); + } + + statLabeled.clear(); + for (Statement st : lstEdgeClosures) { + statLabeled.put(st.id, st.isLabeled()); + } + + for (int i = 0; i < lstBreakEdges.size(); i++) { + Statement st = lstEdgeClosures.get(i); + statLabeled.put(st.id, LowBreakHelper.isBreakEdgeLabeled(lstBreakEdges.get(i).getSource(), st) | statLabeled.get(st.id)); + } + + int postcount = 0; + for (Boolean val : statLabeled.values()) { + postcount += val ? 1 : 0; + } + + if (precount <= postcount) { + return false; + } + else { + for (int i = 0; i < lstBreakEdges.size(); i++) { + lstEdgeClosures.get(i).addLabeledEdge(lstBreakEdges.get(i)); + } + } + } + else { + return false; + } + } + + eliminateLoop(loop, parentloop); + + return true; + } + + private static Statement getMaxBreakLift(Statement stat, StatEdge edge, HashMap<Integer, Boolean> statLabeled, Statement max) { + + Statement closure = stat; + Statement newclosure = stat; + + while ((newclosure = getNextBreakLift(newclosure, edge, statLabeled, max)) != null) { + closure = newclosure; + } + + return closure; + } + + private static Statement getNextBreakLift(Statement stat, StatEdge edge, HashMap<Integer, Boolean> statLabeled, Statement max) { + + Statement closure = stat.getParent(); + + while (closure != null && closure != max && !closure.containsStatementStrict(edge.getDestination())) { + + boolean edge_labeled = LowBreakHelper.isBreakEdgeLabeled(edge.getSource(), closure); + boolean stat_labeled = statLabeled.containsKey(closure.id) ? statLabeled.get(closure.id) : closure.isLabeled(); + + if (stat_labeled || !edge_labeled) { + return closure; + } + + closure = closure.getParent(); + } + + return null; + } + + private static void eliminateLoop(Statement loop, Statement parentloop) { + + // move continue edges to the parent loop + List<StatEdge> lst = new ArrayList<StatEdge>(loop.getLabelEdges()); + for (StatEdge edge : lst) { + loop.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, parentloop); + parentloop.addPredecessor(edge); + + parentloop.addLabeledEdge(edge); + } + + // remove the last break edge, if exists + Statement loopcontent = loop.getFirst(); + if (!loopcontent.getAllSuccessorEdges().isEmpty()) { + loopcontent.removeSuccessor(loopcontent.getAllSuccessorEdges().get(0)); + } + + // replace loop with its content + loop.getParent().replaceStatement(loop, loopcontent); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExitHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExitHelper.java new file mode 100644 index 000000000000..af7358456ce5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExitHelper.java @@ -0,0 +1,345 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.exps.ExitExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +public class ExitHelper { + + + public static boolean condenseExits(RootStatement root) { + + int changed = integrateExits(root); + + if (changed > 0) { + + cleanUpUnreachableBlocks(root); + + SequenceHelper.condenseSequences(root); + } + + return (changed > 0); + } + + + private static void cleanUpUnreachableBlocks(Statement stat) { + + boolean found; + do { + + found = false; + + for (int i = 0; i < stat.getStats().size(); i++) { + + Statement st = stat.getStats().get(i); + + cleanUpUnreachableBlocks(st); + + if (st.type == Statement.TYPE_SEQUENCE && st.getStats().size() > 1) { + + Statement last = st.getStats().getLast(); + Statement secondlast = st.getStats().get(st.getStats().size() - 2); + + if (last.getExprents() == null || !last.getExprents().isEmpty()) { + if (!secondlast.hasBasicSuccEdge()) { + + Set<Statement> set = last.getNeighboursSet(Statement.STATEDGE_DIRECT_ALL, Statement.DIRECTION_BACKWARD); + set.remove(secondlast); + + if (set.isEmpty()) { + last.setExprents(new ArrayList<Exprent>()); + found = true; + break; + } + } + } + } + } + } + while (found); + } + + + private static int integrateExits(Statement stat) { + + int ret = 0; + Statement dest = null; + + if (stat.getExprents() == null) { + + while (true) { + + int changed = 0; + + for (Statement st : stat.getStats()) { + changed = integrateExits(st); + if (changed > 0) { + ret = 1; + break; + } + } + + if (changed == 0) { + break; + } + } + + + switch (stat.type) { + case Statement.TYPE_IF: + IfStatement ifst = (IfStatement)stat; + if (ifst.getIfstat() == null) { + StatEdge ifedge = ifst.getIfEdge(); + dest = isExitEdge(ifedge); + if (dest != null) { + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + bstat.setExprents(DecHelper.copyExprentList(dest.getExprents())); + + ifst.getFirst().removeSuccessor(ifedge); + StatEdge newedge = new StatEdge(StatEdge.TYPE_REGULAR, ifst.getFirst(), bstat); + ifst.getFirst().addSuccessor(newedge); + ifst.setIfEdge(newedge); + ifst.setIfstat(bstat); + ifst.getStats().addWithKey(bstat, bstat.id); + bstat.setParent(ifst); + + StatEdge oldexitedge = dest.getAllSuccessorEdges().get(0); + StatEdge newexitedge = new StatEdge(StatEdge.TYPE_BREAK, bstat, oldexitedge.getDestination()); + bstat.addSuccessor(newexitedge); + oldexitedge.closure.addLabeledEdge(newexitedge); + ret = 1; + } + } + } + } + + + if (stat.getAllSuccessorEdges().size() == 1 && + stat.getAllSuccessorEdges().get(0).getType() == StatEdge.TYPE_BREAK && + stat.getLabelEdges().isEmpty()) { + Statement parent = stat.getParent(); + if (stat != parent.getFirst() || (parent.type != Statement.TYPE_IF && + parent.type != Statement.TYPE_SWITCH)) { + + StatEdge destedge = stat.getAllSuccessorEdges().get(0); + dest = isExitEdge(destedge); + if (dest != null) { + stat.removeSuccessor(destedge); + + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + bstat.setExprents(DecHelper.copyExprentList(dest.getExprents())); + + StatEdge oldexitedge = dest.getAllSuccessorEdges().get(0); + StatEdge newexitedge = new StatEdge(StatEdge.TYPE_BREAK, bstat, oldexitedge.getDestination()); + bstat.addSuccessor(newexitedge); + oldexitedge.closure.addLabeledEdge(newexitedge); + + SequenceStatement block = new SequenceStatement(Arrays.asList(stat, bstat)); + block.setAllParent(); + + parent.replaceStatement(stat, block); + // LabelHelper.lowContinueLabels not applicable because of forward continue edges + // LabelHelper.lowContinueLabels(block, new HashSet<StatEdge>()); + // do it by hand + for (StatEdge prededge : block.getPredecessorEdges(StatEdge.TYPE_CONTINUE)) { + + block.removePredecessor(prededge); + prededge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, prededge, stat); + stat.addPredecessor(prededge); + + stat.addLabeledEdge(prededge); + } + + + stat.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, stat, bstat)); + + for (StatEdge edge : dest.getAllPredecessorEdges()) { + if (!edge.explicit && stat.containsStatementStrict(edge.getSource()) && + MergeHelper.isDirectPath(edge.getSource().getParent(), bstat)) { + + dest.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, bstat); + bstat.addPredecessor(edge); + + if (!stat.containsStatementStrict(edge.closure)) { + stat.addLabeledEdge(edge); + } + } + } + + ret = 2; + } + } + } + + return ret; + } + + private static Statement isExitEdge(StatEdge edge) { + + Statement dest = edge.getDestination(); + + if (edge.getType() == StatEdge.TYPE_BREAK && dest.type == Statement.TYPE_BASICBLOCK + && edge.explicit && (edge.labeled || isOnlyEdge(edge))) { + List<Exprent> data = dest.getExprents(); + + if (data != null && data.size() == 1) { + if (data.get(0).type == Exprent.EXPRENT_EXIT) { + return dest; + } + } + } + + return null; + } + + private static boolean isOnlyEdge(StatEdge edge) { + + Statement stat = edge.getDestination(); + + for (StatEdge ed : stat.getAllPredecessorEdges()) { + if (ed != edge) { + if (ed.getType() == StatEdge.TYPE_REGULAR) { + Statement source = ed.getSource(); + + if (source.type == Statement.TYPE_BASICBLOCK || (source.type == Statement.TYPE_IF && + ((IfStatement)source).iftype == IfStatement.IFTYPE_IF) || + (source.type == Statement.TYPE_DO && ((DoStatement)source).getLooptype() != DoStatement.LOOP_DO)) { + return false; + } + } + else { + return false; + } + } + } + + return true; + } + + public static boolean removeRedundantReturns(RootStatement root) { + + boolean res = false; + + for (StatEdge edge : root.getDummyExit().getAllPredecessorEdges()) { + if (!edge.explicit) { + Statement source = edge.getSource(); + List<Exprent> lstExpr = source.getExprents(); + if (lstExpr != null && !lstExpr.isEmpty()) { + Exprent expr = lstExpr.get(lstExpr.size() - 1); + if (expr.type == Exprent.EXPRENT_EXIT) { + ExitExprent ex = (ExitExprent)expr; + if (ex.getExittype() == ExitExprent.EXIT_RETURN && ex.getValue() == null) { + // remove redundant return + lstExpr.remove(lstExpr.size() - 1); + res = true; + } + } + } + } + } + + return res; + } + + public static boolean handleReturnFromInitializer(RootStatement root) { + + boolean res = false; + + Statement exit = root.getDummyExit(); + Statement top = root.getFirst(); + Statement newret = null; + + boolean sharedcreated = false; + + for (StatEdge edge : exit.getAllPredecessorEdges()) { + if (edge.explicit) { + + if (!sharedcreated) { + newret = addSharedInitializerReturn(root); + sharedcreated = true; + } + + Statement source = edge.getSource(); + List<Exprent> lstExpr = source.getExprents(); + if (lstExpr != null && !lstExpr.isEmpty()) { + Exprent expr = lstExpr.get(lstExpr.size() - 1); + if (expr.type == Exprent.EXPRENT_EXIT) { + ExitExprent ex = (ExitExprent)expr; + if (ex.getExittype() == ExitExprent.EXIT_RETURN && ex.getValue() == null) { + lstExpr.remove(lstExpr.size() - 1); + + source.removeSuccessor(edge); + source.addSuccessor(new StatEdge(StatEdge.TYPE_BREAK, source, newret, top)); + + res = true; + } + } + } + } + } + + return res; + } + + private static Statement addSharedInitializerReturn(RootStatement root) { + + Statement exit = root.getDummyExit(); + Statement top = root.getFirst(); + + // build a new statement with the single instruction 'return' + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + + ExitExprent retexpr = new ExitExprent(ExitExprent.EXIT_RETURN, null, + ((MethodDescriptor)DecompilerContext + .getProperty(DecompilerContext.CURRENT_METHOD_DESCRIPTOR)).ret); + // a changeable list needed + bstat.setExprents(new ArrayList<Exprent>(Arrays.asList(new Exprent[]{retexpr}))); + + // build sequence to replace the former top statement + SequenceStatement seq = new SequenceStatement(Arrays.asList(top, bstat)); + top.setParent(seq); + bstat.setParent(seq); + seq.setParent(root); + + root.getStats().removeWithKey(top.id); + root.getStats().addWithKeyAndIndex(0, seq, seq.id); + root.setFirst(seq); + + for (StatEdge succedge : top.getAllSuccessorEdges()) { + top.removeSuccessor(succedge); + } + + top.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, top, bstat)); + bstat.addSuccessor(new StatEdge(StatEdge.TYPE_BREAK, bstat, exit, seq)); + + return bstat; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExprProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExprProcessor.java new file mode 100644 index 000000000000..0dc660ddf722 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExprProcessor.java @@ -0,0 +1,913 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.code.InstructionSequence; +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectNode; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper.FinallyPathWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.attr.StructBootstrapMethodsAttribute; +import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.struct.consts.LinkConstant; +import org.jetbrains.java.decompiler.struct.consts.PooledConstant; +import org.jetbrains.java.decompiler.struct.consts.PrimitiveConstant; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.*; + +public class ExprProcessor implements CodeConstants { + + public static final String UNDEFINED_TYPE_STRING = "<undefinedtype>"; + public static final String UNKNOWN_TYPE_STRING = "<unknown>"; + public static final String NULL_TYPE_STRING = "<null>"; + + private static final HashMap<Integer, Integer> mapConsts = new HashMap<Integer, Integer>(); + + static { + + // mapConsts.put(new Integer(opc_i2l), new + // Integer(FunctionExprent.FUNCTION_I2L)); + // mapConsts.put(new Integer(opc_i2f), new + // Integer(FunctionExprent.FUNCTION_I2F)); + // mapConsts.put(new Integer(opc_i2d), new + // Integer(FunctionExprent.FUNCTION_I2D)); + // mapConsts.put(new Integer(opc_l2i), new + // Integer(FunctionExprent.FUNCTION_L2I)); + // mapConsts.put(new Integer(opc_l2f), new + // Integer(FunctionExprent.FUNCTION_L2F)); + // mapConsts.put(new Integer(opc_l2d), new + // Integer(FunctionExprent.FUNCTION_L2D)); + // mapConsts.put(new Integer(opc_f2i), new + // Integer(FunctionExprent.FUNCTION_F2I)); + // mapConsts.put(new Integer(opc_f2l), new + // Integer(FunctionExprent.FUNCTION_F2L)); + // mapConsts.put(new Integer(opc_f2d), new + // Integer(FunctionExprent.FUNCTION_F2D)); + // mapConsts.put(new Integer(opc_d2i), new + // Integer(FunctionExprent.FUNCTION_D2I)); + // mapConsts.put(new Integer(opc_d2l), new + // Integer(FunctionExprent.FUNCTION_D2L)); + // mapConsts.put(new Integer(opc_d2f), new + // Integer(FunctionExprent.FUNCTION_D2F)); + // mapConsts.put(new Integer(opc_i2b), new + // Integer(FunctionExprent.FUNCTION_I2B)); + // mapConsts.put(new Integer(opc_i2c), new + // Integer(FunctionExprent.FUNCTION_I2C)); + // mapConsts.put(new Integer(opc_i2s), new + // Integer(FunctionExprent.FUNCTION_I2S)); + + mapConsts.put(new Integer(opc_arraylength), new Integer(FunctionExprent.FUNCTION_ARRAYLENGTH)); + mapConsts.put(new Integer(opc_checkcast), new Integer(FunctionExprent.FUNCTION_CAST)); + mapConsts.put(new Integer(opc_instanceof), new Integer(FunctionExprent.FUNCTION_INSTANCEOF)); + } + + private static final VarType[] consts = + new VarType[]{VarType.VARTYPE_INT, VarType.VARTYPE_FLOAT, VarType.VARTYPE_LONG, VarType.VARTYPE_DOUBLE, VarType.VARTYPE_CLASS, + VarType.VARTYPE_STRING}; + + private static final VarType[] vartypes = + new VarType[]{VarType.VARTYPE_INT, VarType.VARTYPE_LONG, VarType.VARTYPE_FLOAT, VarType.VARTYPE_DOUBLE, VarType.VARTYPE_OBJECT}; + + private static final VarType[] arrtypes = + new VarType[]{VarType.VARTYPE_INT, VarType.VARTYPE_LONG, VarType.VARTYPE_FLOAT, VarType.VARTYPE_DOUBLE, VarType.VARTYPE_OBJECT, + VarType.VARTYPE_BOOLEAN, VarType.VARTYPE_CHAR, VarType.VARTYPE_SHORT}; + + private static final int[] func1 = + new int[]{FunctionExprent.FUNCTION_ADD, FunctionExprent.FUNCTION_SUB, FunctionExprent.FUNCTION_MUL, FunctionExprent.FUNCTION_DIV, + FunctionExprent.FUNCTION_REM}; + + private static final int[] func2 = + new int[]{FunctionExprent.FUNCTION_SHL, FunctionExprent.FUNCTION_SHR, FunctionExprent.FUNCTION_USHR, FunctionExprent.FUNCTION_AND, + FunctionExprent.FUNCTION_OR, FunctionExprent.FUNCTION_XOR}; + + private static final int[] func3 = + new int[]{FunctionExprent.FUNCTION_I2L, FunctionExprent.FUNCTION_I2F, FunctionExprent.FUNCTION_I2D, FunctionExprent.FUNCTION_L2I, + FunctionExprent.FUNCTION_L2F, FunctionExprent.FUNCTION_L2D, FunctionExprent.FUNCTION_F2I, FunctionExprent.FUNCTION_F2L, + FunctionExprent.FUNCTION_F2D, + FunctionExprent.FUNCTION_D2I, FunctionExprent.FUNCTION_D2L, FunctionExprent.FUNCTION_D2F, FunctionExprent.FUNCTION_I2B, + FunctionExprent.FUNCTION_I2C, + FunctionExprent.FUNCTION_I2S}; + + private static final int[] func4 = + new int[]{FunctionExprent.FUNCTION_LCMP, FunctionExprent.FUNCTION_FCMPL, FunctionExprent.FUNCTION_FCMPG, FunctionExprent.FUNCTION_DCMPL, + FunctionExprent.FUNCTION_DCMPG}; + + private static final int[] func5 = + new int[]{IfExprent.IF_EQ, IfExprent.IF_NE, IfExprent.IF_LT, IfExprent.IF_GE, IfExprent.IF_GT, IfExprent.IF_LE}; + + private static final int[] func6 = + new int[]{IfExprent.IF_ICMPEQ, IfExprent.IF_ICMPNE, IfExprent.IF_ICMPLT, IfExprent.IF_ICMPGE, IfExprent.IF_ICMPGT, IfExprent.IF_ICMPLE, + IfExprent.IF_ACMPEQ, IfExprent.IF_ACMPNE}; + + private static final int[] func7 = new int[]{IfExprent.IF_NULL, IfExprent.IF_NONNULL}; + + private static final int[] func8 = new int[]{MonitorExprent.MONITOR_ENTER, MonitorExprent.MONITOR_EXIT}; + + private static final int[] arr_type = + new int[]{CodeConstants.TYPE_BOOLEAN, CodeConstants.TYPE_CHAR, CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_DOUBLE, + CodeConstants.TYPE_BYTE, CodeConstants.TYPE_SHORT, CodeConstants.TYPE_INT, CodeConstants.TYPE_LONG}; + + private static final int[] negifs = + new int[]{IfExprent.IF_NE, IfExprent.IF_EQ, IfExprent.IF_GE, IfExprent.IF_LT, IfExprent.IF_LE, IfExprent.IF_GT, IfExprent.IF_NONNULL, + IfExprent.IF_NULL, IfExprent.IF_ICMPNE, IfExprent.IF_ICMPEQ, IfExprent.IF_ICMPGE, IfExprent.IF_ICMPLT, IfExprent.IF_ICMPLE, + IfExprent.IF_ICMPGT, IfExprent.IF_ACMPNE, + IfExprent.IF_ACMPEQ}; + + private static final String[] typeNames = new String[]{"byte", "char", "double", "float", "int", "long", "short", "boolean",}; + + private VarProcessor varProcessor = (VarProcessor)DecompilerContext.getProperty(DecompilerContext.CURRENT_VAR_PROCESSOR); + + public void processStatement(RootStatement root, StructClass cl) { + + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + DirectGraph dgraph = flatthelper.buildDirectGraph(root); + + // try { + // DotExporter.toDotFile(dgraph, new File("c:\\Temp\\gr12_my.dot")); + // } catch (Exception ex) { + // ex.printStackTrace(); + // } + + // collect finally entry points + Set<String> setFinallyShortRangeEntryPoints = new HashSet<String>(); + for (List<FinallyPathWrapper> lst : dgraph.mapShortRangeFinallyPaths.values()) { + for (FinallyPathWrapper finwrap : lst) { + setFinallyShortRangeEntryPoints.add(finwrap.entry); + } + } + + Set<String> setFinallyLongRangeEntryPaths = new HashSet<String>(); + for (List<FinallyPathWrapper> lst : dgraph.mapLongRangeFinallyPaths.values()) { + for (FinallyPathWrapper finwrap : lst) { + setFinallyLongRangeEntryPaths.add(finwrap.source + "##" + finwrap.entry); + } + } + + Map<String, VarExprent> mapCatch = new HashMap<String, VarExprent>(); + collectCatchVars(root, flatthelper, mapCatch); + + Map<DirectNode, Map<String, PrimitiveExprsList>> mapData = new HashMap<DirectNode, Map<String, PrimitiveExprsList>>(); + + LinkedList<DirectNode> stack = new LinkedList<DirectNode>(); + LinkedList<LinkedList<String>> stackEntryPoint = new LinkedList<LinkedList<String>>(); + + stack.add(dgraph.first); + stackEntryPoint.add(new LinkedList<String>()); + + Map<String, PrimitiveExprsList> map = new HashMap<String, PrimitiveExprsList>(); + map.put(null, new PrimitiveExprsList()); + mapData.put(dgraph.first, map); + + while (!stack.isEmpty()) { + + DirectNode node = stack.removeFirst(); + LinkedList<String> entrypoints = stackEntryPoint.removeFirst(); + + PrimitiveExprsList data; + if (mapCatch.containsKey(node.id)) { + data = getExpressionData(mapCatch.get(node.id)); + } + else { + data = mapData.get(node).get(buildEntryPointKey(entrypoints)); + } + + BasicBlockStatement block = node.block; + if (block != null) { + processBlock(block, data, cl); + block.setExprents(data.getLstExprents()); + } + + String currentEntrypoint = entrypoints.isEmpty() ? null : entrypoints.getLast(); + + for (DirectNode nd : node.succs) { + + boolean isSuccessor = true; + if (currentEntrypoint != null && dgraph.mapLongRangeFinallyPaths.containsKey(node.id)) { + isSuccessor = false; + for (FinallyPathWrapper finwraplong : dgraph.mapLongRangeFinallyPaths.get(node.id)) { + if (finwraplong.source.equals(currentEntrypoint) && finwraplong.destination.equals(nd.id)) { + isSuccessor = true; + break; + } + } + } + + if (isSuccessor) { + + Map<String, PrimitiveExprsList> mapSucc = mapData.get(nd); + if (mapSucc == null) { + mapData.put(nd, mapSucc = new HashMap<String, PrimitiveExprsList>()); + } + + LinkedList<String> ndentrypoints = new LinkedList<String>(entrypoints); + + if (setFinallyLongRangeEntryPaths.contains(node.id + "##" + nd.id)) { + ndentrypoints.addLast(node.id); + } + else if (!setFinallyShortRangeEntryPoints.contains(nd.id) && dgraph.mapLongRangeFinallyPaths.containsKey(node.id)) { + ndentrypoints.removeLast(); // currentEntrypoint should + // not be null at this point + } + + // handling of entry point loops + int succ_entry_index = ndentrypoints.indexOf(nd.id); + if (succ_entry_index >= + 0) { // we are in a loop (e.g. continue in a finally block), drop all entry points in the list beginning with succ_entry_index + for (int elements_to_remove = ndentrypoints.size() - succ_entry_index; elements_to_remove > 0; elements_to_remove--) { + ndentrypoints.removeLast(); + } + } + + String ndentrykey = buildEntryPointKey(ndentrypoints); + if (!mapSucc.containsKey(ndentrykey)) { + + mapSucc.put(ndentrykey, copyVarExprents(data.copyStack())); + + stack.add(nd); + stackEntryPoint.add(ndentrypoints); + } + } + } + } + + initStatementExprents(root); + } + + // FIXME: Ugly code, to be rewritten. A tuple class is needed. + private static String buildEntryPointKey(LinkedList<String> entrypoints) { + if (entrypoints.isEmpty()) { + return null; + } + else { + StringBuilder buffer = new StringBuilder(); + for (String point : entrypoints) { + buffer.append(point); + buffer.append(":"); + } + return buffer.toString(); + } + } + + private static PrimitiveExprsList copyVarExprents(PrimitiveExprsList data) { + ExprentStack stack = data.getStack(); + for (int i = 0; i < stack.size(); i++) { + stack.set(i, stack.get(i).copy()); + } + return data; + } + + private static void collectCatchVars(Statement stat, FlattenStatementsHelper flatthelper, Map<String, VarExprent> map) { + + List<VarExprent> lst = null; + + if (stat.type == Statement.TYPE_CATCHALL) { + CatchAllStatement catchall = (CatchAllStatement)stat; + if (!catchall.isFinally()) { + lst = catchall.getVars(); + } + } + else if (stat.type == Statement.TYPE_TRYCATCH) { + lst = ((CatchStatement)stat).getVars(); + } + + if (lst != null) { + for (int i = 1; i < stat.getStats().size(); i++) { + map.put(flatthelper.getMapDestinationNodes().get(stat.getStats().get(i).id)[0], lst.get(i - 1)); + } + } + + for (Statement st : stat.getStats()) { + collectCatchVars(st, flatthelper, map); + } + } + + private static void initStatementExprents(Statement stat) { + stat.initExprents(); + + for (Statement st : stat.getStats()) { + initStatementExprents(st); + } + } + + public void processBlock(BasicBlockStatement stat, PrimitiveExprsList data, StructClass cl) { + + ConstantPool pool = cl.getPool(); + StructBootstrapMethodsAttribute bootstrap = + (StructBootstrapMethodsAttribute)cl.getAttributes().getWithKey(StructGeneralAttribute.ATTRIBUTE_BOOTSTRAP_METHODS); + + BasicBlock block = stat.getBlock(); + + ExprentStack stack = data.getStack(); + List<Exprent> exprlist = data.getLstExprents(); + + InstructionSequence seq = block.getSeq(); + + for (int i = 0; i < seq.length(); i++) { + + Instruction instr = seq.getInstr(i); + + switch (instr.opcode) { + case opc_aconst_null: + pushEx(stack, exprlist, new ConstExprent(VarType.VARTYPE_NULL, null)); + break; + case opc_bipush: + case opc_sipush: + pushEx(stack, exprlist, new ConstExprent(instr.getOperand(0), true)); + break; + case opc_lconst_0: + case opc_lconst_1: + pushEx(stack, exprlist, new ConstExprent(VarType.VARTYPE_LONG, new Long(instr.opcode - opc_lconst_0))); + break; + case opc_fconst_0: + case opc_fconst_1: + case opc_fconst_2: + pushEx(stack, exprlist, new ConstExprent(VarType.VARTYPE_FLOAT, new Float(instr.opcode - opc_fconst_0))); + break; + case opc_dconst_0: + case opc_dconst_1: + pushEx(stack, exprlist, new ConstExprent(VarType.VARTYPE_DOUBLE, new Double(instr.opcode - opc_dconst_0))); + break; + case opc_ldc: + case opc_ldc_w: + case opc_ldc2_w: + PrimitiveConstant cn = pool.getPrimitiveConstant(instr.getOperand(0)); + pushEx(stack, exprlist, new ConstExprent(consts[cn.type - CONSTANT_Integer], cn.value)); + break; + case opc_iload: + case opc_lload: + case opc_fload: + case opc_dload: + case opc_aload: + pushEx(stack, exprlist, new VarExprent(instr.getOperand(0), vartypes[instr.opcode - opc_iload], varProcessor)); + break; + case opc_iaload: + case opc_laload: + case opc_faload: + case opc_daload: + case opc_aaload: + case opc_baload: + case opc_caload: + case opc_saload: + Exprent index = stack.pop(); + Exprent arr = stack.pop(); + + VarType vartype = null; + switch (instr.opcode) { + case opc_laload: + vartype = VarType.VARTYPE_LONG; + break; + case opc_daload: + vartype = VarType.VARTYPE_DOUBLE; + } + pushEx(stack, exprlist, new ArrayExprent(arr, index, arrtypes[instr.opcode - opc_iaload]), vartype); + break; + case opc_istore: + case opc_lstore: + case opc_fstore: + case opc_dstore: + case opc_astore: + Exprent top = stack.pop(); + int varindex = instr.getOperand(0); + AssignmentExprent assign = + new AssignmentExprent(new VarExprent(varindex, vartypes[instr.opcode - opc_istore], varProcessor), top); + exprlist.add(assign); + break; + case opc_iastore: + case opc_lastore: + case opc_fastore: + case opc_dastore: + case opc_aastore: + case opc_bastore: + case opc_castore: + case opc_sastore: + Exprent value = stack.pop(); + Exprent index_store = stack.pop(); + Exprent arr_store = stack.pop(); + AssignmentExprent arrassign = + new AssignmentExprent(new ArrayExprent(arr_store, index_store, arrtypes[instr.opcode - opc_iastore]), value); + exprlist.add(arrassign); + break; + case opc_iadd: + case opc_ladd: + case opc_fadd: + case opc_dadd: + case opc_isub: + case opc_lsub: + case opc_fsub: + case opc_dsub: + case opc_imul: + case opc_lmul: + case opc_fmul: + case opc_dmul: + case opc_idiv: + case opc_ldiv: + case opc_fdiv: + case opc_ddiv: + case opc_irem: + case opc_lrem: + case opc_frem: + case opc_drem: + pushEx(stack, exprlist, new FunctionExprent(func1[(instr.opcode - opc_iadd) / 4], stack)); + break; + case opc_ishl: + case opc_lshl: + case opc_ishr: + case opc_lshr: + case opc_iushr: + case opc_lushr: + case opc_iand: + case opc_land: + case opc_ior: + case opc_lor: + case opc_ixor: + case opc_lxor: + pushEx(stack, exprlist, new FunctionExprent(func2[(instr.opcode - opc_ishl) / 2], stack)); + break; + case opc_ineg: + case opc_lneg: + case opc_fneg: + case opc_dneg: + pushEx(stack, exprlist, new FunctionExprent(FunctionExprent.FUNCTION_NEG, stack)); + break; + case opc_iinc: + VarExprent vevar = new VarExprent(instr.getOperand(0), VarType.VARTYPE_INT, varProcessor); + exprlist.add(new AssignmentExprent(vevar, new FunctionExprent( + instr.getOperand(1) < 0 ? FunctionExprent.FUNCTION_SUB : FunctionExprent.FUNCTION_ADD, Arrays + .asList(new Exprent[]{vevar.copy(), new ConstExprent(VarType.VARTYPE_INT, new Integer(Math.abs(instr.getOperand(1))))})))); + break; + case opc_i2l: + case opc_i2f: + case opc_i2d: + case opc_l2i: + case opc_l2f: + case opc_l2d: + case opc_f2i: + case opc_f2l: + case opc_f2d: + case opc_d2i: + case opc_d2l: + case opc_d2f: + case opc_i2b: + case opc_i2c: + case opc_i2s: + pushEx(stack, exprlist, new FunctionExprent(func3[instr.opcode - opc_i2l], stack)); + break; + case opc_lcmp: + case opc_fcmpl: + case opc_fcmpg: + case opc_dcmpl: + case opc_dcmpg: + pushEx(stack, exprlist, new FunctionExprent(func4[instr.opcode - opc_lcmp], stack)); + break; + case opc_ifeq: + case opc_ifne: + case opc_iflt: + case opc_ifge: + case opc_ifgt: + case opc_ifle: + exprlist.add(new IfExprent(negifs[func5[instr.opcode - opc_ifeq]], stack)); + break; + case opc_if_icmpeq: + case opc_if_icmpne: + case opc_if_icmplt: + case opc_if_icmpge: + case opc_if_icmpgt: + case opc_if_icmple: + case opc_if_acmpeq: + case opc_if_acmpne: + exprlist.add(new IfExprent(negifs[func6[instr.opcode - opc_if_icmpeq]], stack)); + break; + case opc_ifnull: + case opc_ifnonnull: + exprlist.add(new IfExprent(negifs[func7[instr.opcode - opc_ifnull]], stack)); + break; + case opc_tableswitch: + case opc_lookupswitch: + exprlist.add(new SwitchExprent(stack.pop())); + break; + case opc_ireturn: + case opc_lreturn: + case opc_freturn: + case opc_dreturn: + case opc_areturn: + case opc_return: + case opc_athrow: + exprlist.add(new ExitExprent(instr.opcode == opc_athrow ? ExitExprent.EXIT_THROW : ExitExprent.EXIT_RETURN, + instr.opcode == opc_return ? null : stack.pop(), + instr.opcode == opc_athrow + ? null + : ((MethodDescriptor)DecompilerContext + .getProperty(DecompilerContext.CURRENT_METHOD_DESCRIPTOR)).ret)); + break; + case opc_monitorenter: + case opc_monitorexit: + exprlist.add(new MonitorExprent(func8[instr.opcode - opc_monitorenter], stack.pop())); + break; + case opc_checkcast: + case opc_instanceof: + stack.push(new ConstExprent(new VarType(pool.getPrimitiveConstant(instr.getOperand(0)).getString(), true), null)); + case opc_arraylength: + pushEx(stack, exprlist, new FunctionExprent(mapConsts.get(instr.opcode).intValue(), stack)); + break; + case opc_getstatic: + case opc_getfield: + pushEx(stack, exprlist, + new FieldExprent(pool.getLinkConstant(instr.getOperand(0)), instr.opcode == opc_getstatic ? null : stack.pop())); + break; + case opc_putstatic: + case opc_putfield: + Exprent valfield = stack.pop(); + Exprent exprfield = + new FieldExprent(pool.getLinkConstant(instr.getOperand(0)), instr.opcode == opc_putstatic ? null : stack.pop()); + exprlist.add(new AssignmentExprent(exprfield, valfield)); + break; + case opc_invokevirtual: + case opc_invokespecial: + case opc_invokestatic: + case opc_invokeinterface: + case opc_invokedynamic: + if (instr.opcode != opc_invokedynamic || instr.bytecode_version >= CodeConstants.BYTECODE_JAVA_7) { + + LinkConstant invoke_constant = pool.getLinkConstant(instr.getOperand(0)); + int dynamic_invokation_type = -1; + + if (instr.opcode == opc_invokedynamic && bootstrap != null) { + List<PooledConstant> bootstrap_arguments = bootstrap.getMethodArguments(invoke_constant.index1); + LinkConstant content_method_handle = (LinkConstant)bootstrap_arguments.get(1); + + dynamic_invokation_type = content_method_handle.index1; + } + + InvocationExprent exprinv = new InvocationExprent(instr.opcode, invoke_constant, stack, dynamic_invokation_type); + if (exprinv.getDescriptor().ret.type == CodeConstants.TYPE_VOID) { + exprlist.add(exprinv); + } + else { + pushEx(stack, exprlist, exprinv); + } + } + break; + case opc_new: + case opc_anewarray: + case opc_multianewarray: + int arrdims = (instr.opcode == opc_new) ? 0 : (instr.opcode == opc_anewarray) ? 1 : instr.getOperand(1); + VarType arrtype = new VarType(pool.getPrimitiveConstant(instr.getOperand(0)).getString(), true); + if (instr.opcode != opc_multianewarray) { + arrtype.arraydim += arrdims; + } + pushEx(stack, exprlist, new NewExprent(arrtype, stack, arrdims)); + break; + case opc_newarray: + pushEx(stack, exprlist, new NewExprent(new VarType(arr_type[instr.getOperand(0) - 4], 1), stack, 1)); + break; + case opc_dup: + pushEx(stack, exprlist, stack.getByOffset(-1).copy()); + break; + case opc_dup_x1: + insertByOffsetEx(-2, stack, exprlist, -1); + break; + case opc_dup_x2: + if (stack.getByOffset(-2).getExprType().stack_size == 2) { + insertByOffsetEx(-2, stack, exprlist, -1); + } + else { + insertByOffsetEx(-3, stack, exprlist, -1); + } + break; + case opc_dup2: + if (stack.getByOffset(-1).getExprType().stack_size == 2) { + pushEx(stack, exprlist, stack.getByOffset(-1).copy()); + } + else { + pushEx(stack, exprlist, stack.getByOffset(-2).copy()); + pushEx(stack, exprlist, stack.getByOffset(-2).copy()); + } + break; + case opc_dup2_x1: + if (stack.getByOffset(-1).getExprType().stack_size == 2) { + insertByOffsetEx(-2, stack, exprlist, -1); + } + else { + insertByOffsetEx(-3, stack, exprlist, -2); + insertByOffsetEx(-3, stack, exprlist, -1); + } + break; + case opc_dup2_x2: + if (stack.getByOffset(-1).getExprType().stack_size == 2) { + if (stack.getByOffset(-2).getExprType().stack_size == 2) { + insertByOffsetEx(-2, stack, exprlist, -1); + } + else { + insertByOffsetEx(-3, stack, exprlist, -1); + } + } + else { + if (stack.getByOffset(-3).getExprType().stack_size == 2) { + insertByOffsetEx(-3, stack, exprlist, -2); + insertByOffsetEx(-3, stack, exprlist, -1); + } + else { + insertByOffsetEx(-4, stack, exprlist, -2); + insertByOffsetEx(-4, stack, exprlist, -1); + } + } + break; + case opc_swap: + insertByOffsetEx(-2, stack, exprlist, -1); + stack.pop(); + break; + case opc_pop: + case opc_pop2: + stack.pop(); + } + } + } + + private void pushEx(ExprentStack stack, List<Exprent> exprlist, Exprent exprent) { + pushEx(stack, exprlist, exprent, null); + } + + private void pushEx(ExprentStack stack, List<Exprent> exprlist, Exprent exprent, VarType vartype) { + int varindex = VarExprent.STACK_BASE + stack.size(); + VarExprent var = new VarExprent(varindex, vartype == null ? exprent.getExprType() : vartype, varProcessor); + var.setStack(true); + + exprlist.add(new AssignmentExprent(var, exprent)); + stack.push(var.copy()); + } + + private void insertByOffsetEx(int offset, ExprentStack stack, List<Exprent> exprlist, int copyoffset) { + + int base = VarExprent.STACK_BASE + stack.size(); + + LinkedList<VarExprent> lst = new LinkedList<VarExprent>(); + + for (int i = -1; i >= offset; i--) { + Exprent varex = stack.pop(); + VarExprent varnew = new VarExprent(base + i + 1, varex.getExprType(), varProcessor); + varnew.setStack(true); + exprlist.add(new AssignmentExprent(varnew, varex)); + lst.add(0, (VarExprent)varnew.copy()); + } + + Exprent exprent = lst.get(lst.size() + copyoffset).copy(); + VarExprent var = new VarExprent(base + offset, exprent.getExprType(), varProcessor); + var.setStack(true); + exprlist.add(new AssignmentExprent(var, exprent)); + lst.add(0, (VarExprent)var.copy()); + + for (VarExprent expr : lst) { + stack.push(expr); + } + } + + public static String getTypeName(VarType type) { + return getTypeName(type, true); + } + + public static String getTypeName(VarType type, boolean getShort) { + + int tp = type.type; + if (tp <= CodeConstants.TYPE_BOOLEAN) { + return typeNames[tp]; + } + else if (tp == CodeConstants.TYPE_UNKNOWN) { + return UNKNOWN_TYPE_STRING; // INFO: should not occur + } + else if (tp == CodeConstants.TYPE_NULL) { + return NULL_TYPE_STRING; // INFO: should not occur + } + else if (tp == CodeConstants.TYPE_VOID) { + return "void"; + } + else if (tp == CodeConstants.TYPE_OBJECT) { + String ret = buildJavaClassName(type.value); + if (getShort) { + ret = DecompilerContext.getImportCollector().getShortName(ret); + } + + if (ret == null) { + // FIXME: a warning should be logged + ret = UNDEFINED_TYPE_STRING; + } + return ret; + } + + throw new RuntimeException("invalid type"); + } + + public static String getCastTypeName(VarType type) { + return getCastTypeName(type, true); + } + + public static String getCastTypeName(VarType type, boolean getShort) { + String s = getTypeName(type, getShort); + int dim = type.arraydim; + while (dim-- > 0) { + s += "[]"; + } + return s; + } + + public static PrimitiveExprsList getExpressionData(VarExprent var) { + PrimitiveExprsList prlst = new PrimitiveExprsList(); + VarExprent vartmp = new VarExprent(VarExprent.STACK_BASE, var.getExprType(), var.getProcessor()); + vartmp.setStack(true); + + prlst.getLstExprents().add(new AssignmentExprent(vartmp, var.copy())); + prlst.getStack().push(vartmp.copy()); + return prlst; + } + + public static boolean endsWithSemikolon(Exprent expr) { + int type = expr.type; + return !(type == Exprent.EXPRENT_SWITCH || + type == Exprent.EXPRENT_MONITOR || + type == Exprent.EXPRENT_IF || + (type == Exprent.EXPRENT_VAR && ((VarExprent)expr) + .isClassdef())); + } + + public static String jmpWrapper(Statement stat, int indent, boolean semicolon) { + StringBuilder buf = new StringBuilder(stat.toJava(indent)); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + List<StatEdge> lstSuccs = stat.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL); + if (lstSuccs.size() == 1) { + StatEdge edge = lstSuccs.get(0); + if (edge.getType() != StatEdge.TYPE_REGULAR && edge.explicit && edge.getDestination().type != Statement.TYPE_DUMMYEXIT) { + buf.append(InterpreterUtil.getIndentString(indent)); + + switch (edge.getType()) { + case StatEdge.TYPE_BREAK: + buf.append("break"); + break; + case StatEdge.TYPE_CONTINUE: + buf.append("continue"); + } + + if (edge.labeled) { + buf.append(" label").append(edge.closure.id); + } + buf.append(";").append(new_line_separator); + } + } + + if (buf.length() == 0 && semicolon) { + buf.append(InterpreterUtil.getIndentString(indent)).append(";").append(new_line_separator); + } + + return buf.toString(); + } + + public static String buildJavaClassName(String name) { + String res = name.replace('/', '.'); + + if (res.contains("$")) { // attempt to invoke foreign member + // classes correctly + StructClass cl = DecompilerContext.getStructContext().getClass(name); + if (cl == null || !cl.isOwn()) { + res = res.replace('$', '.'); + } + } + + return res; + } + + public static String listToJava(List<Exprent> lst, int indent) { + if (lst == null || lst.isEmpty()) { + return ""; + } + + String indstr = InterpreterUtil.getIndentString(indent); + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + + for (Exprent expr : lst) { + String content = expr.toJava(indent); + if (content.length() > 0) { + if (expr.type != Exprent.EXPRENT_VAR || !((VarExprent)expr).isClassdef()) { + buf.append(indstr); + } + buf.append(content); + if (expr.type == Exprent.EXPRENT_MONITOR && ((MonitorExprent)expr).getMontype() == MonitorExprent.MONITOR_ENTER) { + buf.append("{}"); // empty synchronized block + } + if (endsWithSemikolon(expr)) { + buf.append(";"); + } + buf.append(new_line_separator); + } + } + + return buf.toString(); + } + + public static ConstExprent getDefaultArrayValue(VarType arrtype) { + + ConstExprent defaultval; + if (arrtype.type == CodeConstants.TYPE_OBJECT || arrtype.arraydim > 0) { + defaultval = new ConstExprent(VarType.VARTYPE_NULL, null); + } + else if (arrtype.type == CodeConstants.TYPE_FLOAT) { + defaultval = new ConstExprent(VarType.VARTYPE_FLOAT, new Float(0)); + } + else if (arrtype.type == CodeConstants.TYPE_LONG) { + defaultval = new ConstExprent(VarType.VARTYPE_LONG, new Long(0)); + } + else if (arrtype.type == CodeConstants.TYPE_DOUBLE) { + defaultval = new ConstExprent(VarType.VARTYPE_DOUBLE, new Double(0)); + } + else { // integer types + defaultval = new ConstExprent(0, true); + } + + return defaultval; + } + + public static boolean getCastedExprent(Exprent exprent, VarType leftType, StringBuilder buffer, int indent, boolean castNull) { + return getCastedExprent(exprent, leftType, buffer, indent, castNull, false); + } + + public static boolean getCastedExprent(Exprent exprent, + VarType leftType, + StringBuilder buffer, + int indent, + boolean castNull, + boolean castAlways) { + + boolean ret = false; + VarType rightType = exprent.getExprType(); + + String res = exprent.toJava(indent); + + boolean cast = + !leftType.isSuperset(rightType) && (rightType.equals(VarType.VARTYPE_OBJECT) || leftType.type != CodeConstants.TYPE_OBJECT); + cast |= castAlways; + + if (!cast && castNull && rightType.type == CodeConstants.TYPE_NULL) { + // check for a nameless anonymous class + cast = !UNDEFINED_TYPE_STRING.equals(getTypeName(leftType)); + } + if (!cast) { + cast = isIntConstant(exprent) && VarType.VARTYPE_INT.isStrictSuperset(leftType); + } + + if (cast) { + if (exprent.getPrecedence() >= FunctionExprent.getPrecedence(FunctionExprent.FUNCTION_CAST)) { + res = "(" + res + ")"; + } + + res = "(" + getCastTypeName(leftType) + ")" + res; + ret = true; + } + + buffer.append(res); + + return ret; + } + + private static boolean isIntConstant(Exprent exprent) { + + if (exprent.type == Exprent.EXPRENT_CONST) { + ConstExprent cexpr = (ConstExprent)exprent; + switch (cexpr.getConsttype().type) { + case CodeConstants.TYPE_BYTE: + case CodeConstants.TYPE_BYTECHAR: + case CodeConstants.TYPE_SHORT: + case CodeConstants.TYPE_SHORTCHAR: + case CodeConstants.TYPE_INT: + return true; + } + } + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExprentStack.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExprentStack.java new file mode 100644 index 000000000000..c4cded20428d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/ExprentStack.java @@ -0,0 +1,45 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.util.ListStack; + +public class ExprentStack extends ListStack<Exprent> { + + public ExprentStack() { + } + + public ExprentStack(ListStack<Exprent> list) { + super(list); + pointer = list.getPointer(); + } + + public Exprent push(Exprent item) { + super.push(item); + + return item; + } + + public Exprent pop() { + + return this.remove(--pointer); + } + + public ExprentStack clone() { + return new ExprentStack(this); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/FinallyProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/FinallyProcessor.java new file mode 100644 index 000000000000..6198da1b21bf --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/FinallyProcessor.java @@ -0,0 +1,1087 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.*; +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.code.cfg.ControlFlowGraph; +import org.jetbrains.java.decompiler.code.cfg.ExceptionRangeCFG; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.code.DeadCodeHelper; +import org.jetbrains.java.decompiler.modules.decompiler.exps.AssignmentExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.ExitExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectNode; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.SSAConstructorSparseEx; +import org.jetbrains.java.decompiler.modules.decompiler.stats.BasicBlockStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchAllStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.*; +import java.util.Map.Entry; + +public class FinallyProcessor { + + private Map<Integer, Integer> finallyBlockIDs = new HashMap<Integer, Integer>(); + private Map<Integer, Integer> catchallBlockIDs = new HashMap<Integer, Integer>(); + + private VarProcessor varprocessor; + + public FinallyProcessor(VarProcessor varprocessor) { + this.varprocessor = varprocessor; + } + + public boolean iterateGraph(StructMethod mt, RootStatement root, ControlFlowGraph graph) { + // return processStatement(mt, root, graph, root); + return processStatementEx(mt, root, graph); + } + + private boolean processStatementEx(StructMethod mt, RootStatement root, ControlFlowGraph graph) { + + int bytecode_version = mt.getClassStruct().getBytecodeVersion(); + + LinkedList<Statement> stack = new LinkedList<Statement>(); + stack.add(root); + + while (!stack.isEmpty()) { + + Statement stat = stack.removeLast(); + + Statement parent = stat.getParent(); + if (parent != null && parent.type == Statement.TYPE_CATCHALL && + stat == parent.getFirst() && !parent.isCopied()) { + + CatchAllStatement fin = (CatchAllStatement)parent; + BasicBlock head = fin.getBasichead().getBlock(); + BasicBlock handler = fin.getHandler().getBasichead().getBlock(); + + if (catchallBlockIDs.containsKey(handler.id)) { + // do nothing + } + else if (finallyBlockIDs.containsKey(handler.id)) { + + fin.setFinally(true); + + Integer var = finallyBlockIDs.get(handler.id); + fin.setMonitor(var == null ? null : new VarExprent(var.intValue(), VarType.VARTYPE_INT, varprocessor)); + } + else { + + Record inf = getFinallyInformation(mt, root, fin); + + if (inf == null) { // inconsistent finally + catchallBlockIDs.put(handler.id, null); + } + else { + + if (DecompilerContext.getOption(IFernflowerPreferences.FINALLY_DEINLINE) && verifyFinallyEx(graph, fin, inf)) { + finallyBlockIDs.put(handler.id, null); + } + else { + + int varindex = DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER); + insertSemaphore(graph, getAllBasicBlocks(fin.getFirst()), head, handler, varindex, inf, bytecode_version); + + finallyBlockIDs.put(handler.id, varindex); + } + + DeadCodeHelper.removeDeadBlocks(graph); // e.g. multiple return blocks after a nested finally + DeadCodeHelper.removeEmptyBlocks(graph); + DeadCodeHelper.mergeBasicBlocks(graph); + } + + return true; + } + } + + stack.addAll(stat.getStats()); + } + + return false; + } + + + // private boolean processStatement(StructMethod mt, RootStatement root, ControlFlowGraph graph, Statement stat) { + // + // boolean res = false; + // + // for(int i=stat.getStats().size()-1;i>=0;i--) { + // if(processStatement(mt, root, graph, stat.getStats().get(i))) { + // return true; + // } + // } + // + // + // if(stat.type == Statement.TYPE_CATCHALL && !stat.isCopied()) { + // + // CatchAllStatement fin = (CatchAllStatement)stat; + // BasicBlock head = fin.getBasichead().getBlock(); + // BasicBlock handler = fin.getHandler().getBasichead().getBlock(); + // + // if(catchallBlockIDs.containsKey(handler.id)) { + // ; // do nothing + // }else if(finallyBlockIDs.containsKey(handler.id)) { + // + // fin.setFinally(true); + // + // Integer var = finallyBlockIDs.get(handler.id); + // fin.setMonitor(var==null?null:new VarExprent(var.intValue(), VarType.VARTYPE_INT, varprocessor)); + // + // } else { + // + // Object[] inf = getFinallyInformation(mt, root, fin); + // + // if(inf == null) { // inconsistent finally + // catchallBlockIDs.put(handler.id, null); + // } else { + // + // if(DecompilerContext.getOption(IFernflowerPreferences.FINALLY_DEINLINE) && verifyFinallyEx(graph, fin, inf)) { + // finallyBlockIDs.put(handler.id, null); + // } else { + // + // int varindex = DecompilerContext.getCountercontainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER); + // insertSemaphore(graph, getAllBasicBlocks(fin.getFirst()), head, handler, varindex, inf); + // + // finallyBlockIDs.put(handler.id, varindex); + // } + // + // DeadCodeHelper.removeEmptyBlocks(graph); + // DeadCodeHelper.mergeBasicBlocks(graph); + // } + // + // res = true; + // } + // } + // + // return res; + // } + + private static class Record { + private final int firstCode; + private final Map<BasicBlock, Boolean> mapLast; + + private Record(int firstCode, Map<BasicBlock, Boolean> mapLast) { + this.firstCode = firstCode; + this.mapLast = mapLast; + } + } + + + private static Record getFinallyInformation(StructMethod mt, RootStatement root, CatchAllStatement fstat) { + + Map<BasicBlock, Boolean> mapLast = new HashMap<BasicBlock, Boolean>(); + + BasicBlockStatement firstBlockStatement = fstat.getHandler().getBasichead(); + BasicBlock firstBasicBlock = firstBlockStatement.getBlock(); + Instruction instrFirst = firstBasicBlock.getInstruction(0); + + int firstcode = 0; + + switch (instrFirst.opcode) { + case CodeConstants.opc_pop: + firstcode = 1; + break; + case CodeConstants.opc_astore: + firstcode = 2; + } + + ExprProcessor proc = new ExprProcessor(); + proc.processStatement(root, mt.getClassStruct()); + + SSAConstructorSparseEx ssa = new SSAConstructorSparseEx(); + ssa.splitVariables(root, mt); + + List<Exprent> lstExprents = firstBlockStatement.getExprents(); + + VarVersionPaar varpaar = new VarVersionPaar((VarExprent)((AssignmentExprent)lstExprents.get(firstcode == 2 ? 1 : 0)).getLeft()); + + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + DirectGraph dgraph = flatthelper.buildDirectGraph(root); + + LinkedList<DirectNode> stack = new LinkedList<DirectNode>(); + stack.add(dgraph.first); + + Set<DirectNode> setVisited = new HashSet<DirectNode>(); + + while (!stack.isEmpty()) { + + DirectNode node = stack.removeFirst(); + + if (setVisited.contains(node)) { + continue; + } + setVisited.add(node); + + BasicBlockStatement blockStatement = null; + if (node.block != null) { + blockStatement = node.block; + } + else if (node.preds.size() == 1) { + blockStatement = node.preds.get(0).block; + } + + boolean isTrueExit = true; + + if (firstcode != 1) { + + isTrueExit = false; + + for (int i = 0; i < node.exprents.size(); i++) { + Exprent exprent = node.exprents.get(i); + + if (firstcode == 0) { + List<Exprent> lst = exprent.getAllExprents(); + lst.add(exprent); + + boolean found = false; + for (Exprent expr : lst) { + if (expr.type == Exprent.EXPRENT_VAR && new VarVersionPaar((VarExprent)expr).equals(varpaar)) { + found = true; + break; + } + } + + if (found) { + found = false; + if (exprent.type == Exprent.EXPRENT_EXIT) { + ExitExprent exexpr = (ExitExprent)exprent; + if (exexpr.getExittype() == ExitExprent.EXIT_THROW && exexpr.getValue().type == Exprent.EXPRENT_VAR) { + found = true; + } + } + + if (!found) { + return null; + } + else { + isTrueExit = true; + } + } + } + else if (firstcode == 2) { + // search for a load instruction + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent assexpr = (AssignmentExprent)exprent; + if (assexpr.getRight().type == Exprent.EXPRENT_VAR && + new VarVersionPaar((VarExprent)assexpr.getRight()).equals(varpaar)) { + + Exprent next = null; + if (i == node.exprents.size() - 1) { + if (node.succs.size() == 1) { + DirectNode nd = node.succs.get(0); + if (!nd.exprents.isEmpty()) { + next = nd.exprents.get(0); + } + } + } + else { + next = node.exprents.get(i + 1); + } + + boolean found = false; + if (next != null && next.type == Exprent.EXPRENT_EXIT) { + ExitExprent exexpr = (ExitExprent)next; + if (exexpr.getExittype() == ExitExprent.EXIT_THROW && exexpr.getValue().type == Exprent.EXPRENT_VAR + && assexpr.getLeft().equals(exexpr.getValue())) { + found = true; + } + } + + if (!found) { + return null; + } + else { + isTrueExit = true; + } + } + } + } + } + } + + // find finally exits + if (blockStatement != null && blockStatement.getBlock() != null) { + Statement handler = fstat.getHandler(); + for (StatEdge edge : blockStatement.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL)) { + if (edge.getType() != StatEdge.TYPE_REGULAR && handler.containsStatement(blockStatement) + && !handler.containsStatement(edge.getDestination())) { + Boolean existingFlag = mapLast.get(blockStatement.getBlock()); + // note: the dummy node is also processed! + if (existingFlag == null || !existingFlag) { + mapLast.put(blockStatement.getBlock(), isTrueExit); + break; + } + } + } + } + + stack.addAll(node.succs); + } + + // empty finally block? + if (fstat.getHandler().type == Statement.TYPE_BASICBLOCK) { + + boolean isEmpty = false; + boolean isFirstLast = mapLast.containsKey(firstBasicBlock); + InstructionSequence seq = firstBasicBlock.getSeq(); + + switch (firstcode) { + case 0: + isEmpty = isFirstLast && seq.length() == 1; + break; + case 1: + isEmpty = seq.length() == 1; + break; + case 2: + isEmpty = isFirstLast ? seq.length() == 3 : seq.length() == 1; + } + + if (isEmpty) { + firstcode = 3; + } + } + + return new Record(firstcode, mapLast); + } + + private static void insertSemaphore(ControlFlowGraph graph, + Set<BasicBlock> setTry, + BasicBlock head, + BasicBlock handler, + int var, + Record information, + int bytecode_version) { + + Set<BasicBlock> setCopy = new HashSet<BasicBlock>(setTry); + + int finallytype = information.firstCode; + Map<BasicBlock, Boolean> mapLast = information.mapLast; + + // first and last statements + removeExceptionInstructionsEx(handler, 1, finallytype); + for (Entry<BasicBlock, Boolean> entry : mapLast.entrySet()) { + BasicBlock last = entry.getKey(); + + if (entry.getValue()) { + removeExceptionInstructionsEx(last, 2, finallytype); + graph.getFinallyExits().add(last); + } + } + + // disable semaphore at statement exit points + for (BasicBlock block : setTry) { + + List<BasicBlock> lstSucc = block.getSuccs(); + for (BasicBlock dest : lstSucc) { + + // break out + if (!setCopy.contains(dest) && dest != graph.getLast()) { + // disable semaphore + SimpleInstructionSequence seq = new SimpleInstructionSequence(); + + seq.addInstruction(ConstantsUtil + .getInstructionInstance(CodeConstants.opc_bipush, false, CodeConstants.GROUP_GENERAL, bytecode_version, + new int[]{0}), -1); + seq.addInstruction(ConstantsUtil + .getInstructionInstance(CodeConstants.opc_istore, false, CodeConstants.GROUP_GENERAL, bytecode_version, + new int[]{var}), -1); + + // build a separate block + BasicBlock newblock = new BasicBlock(++graph.last_id); + newblock.setSeq(seq); + + // insert between block and dest + block.replaceSuccessor(dest, newblock); + newblock.addSuccessor(dest); + setCopy.add(newblock); + graph.getBlocks().addWithKey(newblock, newblock.id); + + // exception ranges + // FIXME: special case synchronized + + // copy exception edges and extend protected ranges + for (int j = 0; j < block.getSuccExceptions().size(); j++) { + BasicBlock hd = block.getSuccExceptions().get(j); + newblock.addSuccessorException(hd); + + ExceptionRangeCFG range = graph.getExceptionRange(hd, block); + range.getProtectedRange().add(newblock); + } + } + } + } + + // enable semaphor at the statement entrance + SimpleInstructionSequence seq = new SimpleInstructionSequence(); + seq.addInstruction( + ConstantsUtil.getInstructionInstance(CodeConstants.opc_bipush, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{1}), + -1); + seq.addInstruction( + ConstantsUtil.getInstructionInstance(CodeConstants.opc_istore, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{var}), + -1); + + BasicBlock newhead = new BasicBlock(++graph.last_id); + newhead.setSeq(seq); + + insertBlockBefore(graph, head, newhead); + + // initialize semaphor with false + seq = new SimpleInstructionSequence(); + seq.addInstruction( + ConstantsUtil.getInstructionInstance(CodeConstants.opc_bipush, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{0}), + -1); + seq.addInstruction( + ConstantsUtil.getInstructionInstance(CodeConstants.opc_istore, false, CodeConstants.GROUP_GENERAL, bytecode_version, new int[]{var}), + -1); + + BasicBlock newheadinit = new BasicBlock(++graph.last_id); + newheadinit.setSeq(seq); + + insertBlockBefore(graph, newhead, newheadinit); + + setCopy.add(newhead); + setCopy.add(newheadinit); + + for (BasicBlock hd : new HashSet<BasicBlock>(newheadinit.getSuccExceptions())) { + ExceptionRangeCFG range = graph.getExceptionRange(hd, newheadinit); + + if (setCopy.containsAll(range.getProtectedRange())) { + newheadinit.removeSuccessorException(hd); + range.getProtectedRange().remove(newheadinit); + } + } + } + + + private static void insertBlockBefore(ControlFlowGraph graph, BasicBlock oldblock, BasicBlock newblock) { + + List<BasicBlock> lstTemp = new ArrayList<BasicBlock>(); + lstTemp.addAll(oldblock.getPreds()); + lstTemp.addAll(oldblock.getPredExceptions()); + + // replace predecessors + for (BasicBlock pred : lstTemp) { + pred.replaceSuccessor(oldblock, newblock); + } + + // copy exception edges and extend protected ranges + for (BasicBlock hd : oldblock.getSuccExceptions()) { + newblock.addSuccessorException(hd); + + ExceptionRangeCFG range = graph.getExceptionRange(hd, oldblock); + range.getProtectedRange().add(newblock); + } + + // replace handler + for (ExceptionRangeCFG range : graph.getExceptions()) { + if (range.getHandler() == oldblock) { + range.setHandler(newblock); + } + } + + newblock.addSuccessor(oldblock); + graph.getBlocks().addWithKey(newblock, newblock.id); + if (graph.getFirst() == oldblock) { + graph.setFirst(newblock); + } + } + + private static HashSet<BasicBlock> getAllBasicBlocks(Statement stat) { + + List<Statement> lst = new LinkedList<Statement>(); + lst.add(stat); + + int index = 0; + do { + Statement st = lst.get(index); + + if (st.type == Statement.TYPE_BASICBLOCK) { + index++; + } + else { + lst.addAll(st.getStats()); + lst.remove(index); + } + } + while (index < lst.size()); + + HashSet<BasicBlock> res = new HashSet<BasicBlock>(); + + for (Statement st : lst) { + res.add(((BasicBlockStatement)st).getBlock()); + } + + return res; + } + + + private boolean verifyFinallyEx(ControlFlowGraph graph, CatchAllStatement fstat, Record information) { + + HashSet<BasicBlock> tryBlocks = getAllBasicBlocks(fstat.getFirst()); + HashSet<BasicBlock> catchBlocks = getAllBasicBlocks(fstat.getHandler()); + + int finallytype = information.firstCode; + Map<BasicBlock, Boolean> mapLast = information.mapLast; + + BasicBlock first = fstat.getHandler().getBasichead().getBlock(); + boolean skippedFirst = false; + + if (finallytype == 3) { + // empty finally + removeExceptionInstructionsEx(first, 3, finallytype); + + if (mapLast.containsKey(first)) { + graph.getFinallyExits().add(first); + } + + return true; + } + else { + if (first.getSeq().length() == 1 && finallytype > 0) { + BasicBlock firstsuc = first.getSuccs().get(0); + if (catchBlocks.contains(firstsuc)) { + first = firstsuc; + skippedFirst = true; + } + } + } + + // identify start blocks + HashSet<BasicBlock> startBlocks = new HashSet<BasicBlock>(); + for (BasicBlock block : tryBlocks) { + startBlocks.addAll(block.getSuccs()); + } + // throw in the try body will point directly to the dummy exit + // so remove dummy exit + startBlocks.remove(graph.getLast()); + startBlocks.removeAll(tryBlocks); + + List<Area> lstAreas = new ArrayList<Area>(); + + for (BasicBlock start : startBlocks) { + + Area arr = compareSubgraphsEx(graph, start, catchBlocks, first, finallytype, mapLast, skippedFirst); + if (arr == null) { + return false; + } + + lstAreas.add(arr); + } + + // try { + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern5.dot"), true); + // } catch(Exception ex){ex.printStackTrace();} + + // delete areas + for (Area area : lstAreas) { + deleteArea(graph, area); + } + + // try { + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern5.dot"), true); + // } catch(Exception ex){ex.printStackTrace();} + + // INFO: empty basic blocks may remain in the graph! + for (Entry<BasicBlock, Boolean> entry : mapLast.entrySet()) { + BasicBlock last = entry.getKey(); + + if (entry.getValue()) { + removeExceptionInstructionsEx(last, 2, finallytype); + graph.getFinallyExits().add(last); + } + } + + removeExceptionInstructionsEx(fstat.getHandler().getBasichead().getBlock(), 1, finallytype); + + return true; + } + + private static class Area { + private final BasicBlock start; + private final Set<BasicBlock> sample; + private final BasicBlock next; + + private Area(BasicBlock start, Set<BasicBlock> sample, BasicBlock next) { + this.start = start; + this.sample = sample; + this.next = next; + } + } + + private Area compareSubgraphsEx(ControlFlowGraph graph, + BasicBlock startSample, + HashSet<BasicBlock> catchBlocks, + BasicBlock startCatch, + int finallytype, + Map<BasicBlock, Boolean> mapLast, + boolean skippedFirst) { + + class BlockStackEntry { + public BasicBlock blockCatch; + public BasicBlock blockSample; + + // TODO: correct handling (merging) of multiple paths + public List<int[]> lstStoreVars; + + public BlockStackEntry(BasicBlock blockCatch, BasicBlock blockSample, List<int[]> lstStoreVars) { + this.blockCatch = blockCatch; + this.blockSample = blockSample; + this.lstStoreVars = new ArrayList<int[]>(lstStoreVars); + } + } + + List<BlockStackEntry> stack = new LinkedList<BlockStackEntry>(); + + Set<BasicBlock> setSample = new HashSet<BasicBlock>(); + + Map<String, BasicBlock[]> mapNext = new HashMap<String, BasicBlock[]>(); + + stack.add(new BlockStackEntry(startCatch, startSample, new ArrayList<int[]>())); + + while (!stack.isEmpty()) { + + BlockStackEntry entry = stack.remove(0); + BasicBlock blockCatch = entry.blockCatch; + BasicBlock blockSample = entry.blockSample; + + boolean isFirstBlock = !skippedFirst && blockCatch == startCatch; + boolean isLastBlock = mapLast.containsKey(blockCatch); + boolean isTrueLastBlock = isLastBlock && mapLast.get(blockCatch); + + if (!compareBasicBlocksEx(graph, blockCatch, blockSample, (isFirstBlock ? 1 : 0) | (isTrueLastBlock ? 2 : 0), finallytype, + entry.lstStoreVars)) { + return null; + } + + if (blockSample.getSuccs().size() != blockCatch.getSuccs().size()) { + return null; + } + + setSample.add(blockSample); + + // direct successors + for (int i = 0; i < blockCatch.getSuccs().size(); i++) { + BasicBlock sucCatch = blockCatch.getSuccs().get(i); + BasicBlock sucSample = blockSample.getSuccs().get(i); + + if (catchBlocks.contains(sucCatch) && !setSample.contains(sucSample)) { + stack.add(new BlockStackEntry(sucCatch, sucSample, entry.lstStoreVars)); + } + } + + + // exception successors + if (isLastBlock && blockSample.getSeq().isEmpty()) { + // do nothing, blockSample will be removed anyway + } + else { + if (blockCatch.getSuccExceptions().size() == blockSample.getSuccExceptions().size()) { + for (int i = 0; i < blockCatch.getSuccExceptions().size(); i++) { + BasicBlock sucCatch = blockCatch.getSuccExceptions().get(i); + BasicBlock sucSample = blockSample.getSuccExceptions().get(i); + + String excCatch = graph.getExceptionRange(sucCatch, blockCatch).getUniqueExceptionsString(); + String excSample = graph.getExceptionRange(sucSample, blockSample).getUniqueExceptionsString(); + + // FIXME: compare handlers if possible + boolean equalexc = excCatch == null ? excSample == null : excCatch.equals(excSample); + + if (equalexc) { + if (catchBlocks.contains(sucCatch) && !setSample.contains(sucSample)) { + + List<int[]> lst = entry.lstStoreVars; + + if (sucCatch.getSeq().length() > 0 && sucSample.getSeq().length() > 0) { + Instruction instrCatch = sucCatch.getSeq().getInstr(0); + Instruction instrSample = sucSample.getSeq().getInstr(0); + + if (instrCatch.opcode == CodeConstants.opc_astore && + instrSample.opcode == CodeConstants.opc_astore) { + lst = new ArrayList<int[]>(lst); + lst.add(new int[]{instrCatch.getOperand(0), instrSample.getOperand(0)}); + } + } + + stack.add(new BlockStackEntry(sucCatch, sucSample, lst)); + } + } + else { + return null; + } + } + } + else { + return null; + } + } + + if (isLastBlock) { + Set<BasicBlock> setSuccs = new HashSet<BasicBlock>(blockSample.getSuccs()); + setSuccs.removeAll(setSample); + + for (BlockStackEntry stackent : stack) { + setSuccs.remove(stackent.blockSample); + } + + for (BasicBlock succ : setSuccs) { + if (graph.getLast() != succ) { // FIXME: why? + mapNext.put(blockSample.id + "#" + succ.id, new BasicBlock[]{blockSample, succ, isTrueLastBlock ? succ : null}); + } + } + } + } + + return new Area(startSample, setSample, getUniqueNext(graph, new HashSet<BasicBlock[]>(mapNext.values()))); + } + + private static BasicBlock getUniqueNext(ControlFlowGraph graph, Set<BasicBlock[]> setNext) { + + // precondition: there is at most one true exit path in a finally statement + + BasicBlock next = null; + boolean multiple = false; + + for (BasicBlock[] arr : setNext) { + + if (arr[2] != null) { + next = arr[1]; + multiple = false; + break; + } + else { + if (next == null) { + next = arr[1]; + } + else if (next != arr[1]) { + multiple = true; + } + + if (arr[1].getPreds().size() == 1) { + next = arr[1]; + } + } + } + + if (multiple) { // TODO: generic solution + for (BasicBlock[] arr : setNext) { + BasicBlock block = arr[1]; + + if (block != next) { + if (InterpreterUtil.equalSets(next.getSuccs(), block.getSuccs())) { + InstructionSequence seqNext = next.getSeq(); + InstructionSequence seqBlock = block.getSeq(); + + if (seqNext.length() == seqBlock.length()) { + for (int i = 0; i < seqNext.length(); i++) { + Instruction instrNext = seqNext.getInstr(i); + Instruction instrBlock = seqBlock.getInstr(i); + + if (instrNext.opcode != instrBlock.opcode || instrNext.wide != instrBlock.wide + || instrNext.operandsCount() != instrBlock.operandsCount()) { + return null; + } + + for (int j = 0; j < instrNext.getOperands().length; j++) { + if (instrNext.getOperand(j) != instrBlock.getOperand(j)) { + return null; + } + } + } + } + else { + return null; + } + } + else { + return null; + } + } + } + + // try { + // DotExporter.toDotFile(graph, new File("c:\\Temp\\fern5.dot"), true); + // } catch(IOException ex) { + // ex.printStackTrace(); + // } + + for (BasicBlock[] arr : setNext) { + if (arr[1] != next) { + // FIXME: exception edge possible? + arr[0].removeSuccessor(arr[1]); + arr[0].addSuccessor(next); + } + } + + DeadCodeHelper.removeDeadBlocks(graph); + } + + return next; + } + + private boolean compareBasicBlocksEx(ControlFlowGraph graph, + BasicBlock pattern, + BasicBlock sample, + int type, + int finallytype, + List<int[]> lstStoreVars) { + + InstructionSequence seqPattern = pattern.getSeq(); + InstructionSequence seqSample = sample.getSeq(); + + if (type != 0) { + seqPattern = seqPattern.clone(); + + if ((type & 1) > 0) { // first + if (finallytype > 0) { + seqPattern.removeInstruction(0); + } + } + + if ((type & 2) > 0) { // last + if (finallytype == 0 || finallytype == 2) { + seqPattern.removeInstruction(seqPattern.length() - 1); + } + + if (finallytype == 2) { + seqPattern.removeInstruction(seqPattern.length() - 1); + } + } + } + + if (seqPattern.length() > seqSample.length()) { + return false; + } + + for (int i = 0; i < seqPattern.length(); i++) { + Instruction instrPattern = seqPattern.getInstr(i); + Instruction instrSample = seqSample.getInstr(i); + + // compare instructions with respect to jumps + if (!equalInstructions(instrPattern, instrSample, lstStoreVars)) { + return false; + } + } + + if (seqPattern.length() < seqSample.length()) { // split in two blocks + + SimpleInstructionSequence seq = new SimpleInstructionSequence(); + for (int i = seqSample.length() - 1; i >= seqPattern.length(); i--) { + seq.addInstruction(0, seqSample.getInstr(i), -1); + seqSample.removeInstruction(i); + } + + BasicBlock newblock = new BasicBlock(++graph.last_id); + newblock.setSeq(seq); + + List<BasicBlock> lstTemp = new ArrayList<BasicBlock>(); + lstTemp.addAll(sample.getSuccs()); + + // move successors + for (BasicBlock suc : lstTemp) { + sample.removeSuccessor(suc); + newblock.addSuccessor(suc); + } + + sample.addSuccessor(newblock); + + graph.getBlocks().addWithKey(newblock, newblock.id); + + Set<BasicBlock> setFinallyExits = graph.getFinallyExits(); + if (setFinallyExits.contains(sample)) { + setFinallyExits.remove(sample); + setFinallyExits.add(newblock); + } + + // copy exception edges and extend protected ranges + for (int j = 0; j < sample.getSuccExceptions().size(); j++) { + BasicBlock hd = sample.getSuccExceptions().get(j); + newblock.addSuccessorException(hd); + + ExceptionRangeCFG range = graph.getExceptionRange(hd, sample); + range.getProtectedRange().add(newblock); + } + } + + return true; + } + + public boolean equalInstructions(Instruction first, Instruction second, List<int[]> lstStoreVars) { + if (first.opcode != second.opcode || first.wide != second.wide + || first.operandsCount() != second.operandsCount()) { + return false; + } + + if (first.group != CodeConstants.GROUP_JUMP && first.getOperands() != null) { // FIXME: switch comparison + for (int i = 0; i < first.getOperands().length; i++) { + + int firstOp = first.getOperand(i); + int secondOp = second.getOperand(i); + + if (firstOp != secondOp) { + + // a-load/store instructions + if (first.opcode == CodeConstants.opc_aload || first.opcode == CodeConstants.opc_astore) { + for (int[] arr : lstStoreVars) { + if (arr[0] == firstOp && arr[1] == secondOp) { + return true; + } + } + } + + return false; + } + } + } + + return true; + } + + private static void deleteArea(ControlFlowGraph graph, Area area) { + + BasicBlock start = area.start; + BasicBlock next = area.next; + + if (start == next) { + return; + } + + if (next == null) { + // dummy exit block + next = graph.getLast(); + } + + // collect common exception ranges of predecessors and successors + Set<BasicBlock> setCommonExceptionHandlers = new HashSet<BasicBlock>(next.getSuccExceptions()); + for (BasicBlock pred : start.getPreds()) { + setCommonExceptionHandlers.retainAll(pred.getSuccExceptions()); + } + + boolean is_outside_range = false; + + Set<BasicBlock> setPredecessors = new HashSet<BasicBlock>(start.getPreds()); + + // replace start with next + for (BasicBlock pred : setPredecessors) { + pred.replaceSuccessor(start, next); + } + + Set<BasicBlock> setBlocks = area.sample; + + Set<ExceptionRangeCFG> setCommonRemovedExceptionRanges = null; + + // remove all the blocks inbetween + for (BasicBlock block : setBlocks) { + + // artificial basic blocks (those resulted from splitting) + // can belong to more than one area + if (graph.getBlocks().containsKey(block.id)) { + + if (!block.getSuccExceptions().containsAll(setCommonExceptionHandlers)) { + is_outside_range = true; + } + + Set<ExceptionRangeCFG> setRemovedExceptionRanges = new HashSet<ExceptionRangeCFG>(); + for (BasicBlock handler : block.getSuccExceptions()) { + setRemovedExceptionRanges.add(graph.getExceptionRange(handler, block)); + } + + if (setCommonRemovedExceptionRanges == null) { + setCommonRemovedExceptionRanges = setRemovedExceptionRanges; + } + else { + setCommonRemovedExceptionRanges.retainAll(setRemovedExceptionRanges); + } + + // shift extern edges on splitted blocks + if (block.getSeq().isEmpty() && block.getSuccs().size() == 1) { + BasicBlock succs = block.getSuccs().get(0); + for (BasicBlock pred : new ArrayList<BasicBlock>(block.getPreds())) { + if (!setBlocks.contains(pred)) { + pred.replaceSuccessor(block, succs); + } + } + + if (graph.getFirst() == block) { + graph.setFirst(succs); + } + } + + graph.removeBlock(block); + } + } + + if (is_outside_range) { + + // new empty block + BasicBlock emptyblock = new BasicBlock(++graph.last_id); + emptyblock.setSeq(new SimpleInstructionSequence()); + graph.getBlocks().addWithKey(emptyblock, emptyblock.id); + + // add to ranges if necessary + if (setCommonRemovedExceptionRanges != null) { + for (ExceptionRangeCFG range : setCommonRemovedExceptionRanges) { + emptyblock.addSuccessorException(range.getHandler()); + range.getProtectedRange().add(emptyblock); + } + } + + // insert between predecessors and next + emptyblock.addSuccessor(next); + for (BasicBlock pred : setPredecessors) { + pred.replaceSuccessor(next, emptyblock); + } + } + } + + private static void removeExceptionInstructionsEx(BasicBlock block, int blocktype, int finallytype) { + + InstructionSequence seq = block.getSeq(); + + if (finallytype == 3) { // empty finally handler + for (int i = seq.length() - 1; i >= 0; i--) { + seq.removeInstruction(i); + } + } + else { + if ((blocktype & 1) > 0) { // first + if (finallytype == 2 || finallytype == 1) { // astore or pop + seq.removeInstruction(0); + } + } + + if ((blocktype & 2) > 0) { // last + if (finallytype == 2 || finallytype == 0) { + seq.removeInstruction(seq.length() - 1); + } + + if (finallytype == 2) { // astore + seq.removeInstruction(seq.length() - 1); + } + } + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/IdeaNotNullHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/IdeaNotNullHelper.java new file mode 100644 index 000000000000..0f5141a7aa52 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/IdeaNotNullHelper.java @@ -0,0 +1,336 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.stats.IfStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.SequenceStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.attr.StructAnnotationAttribute; +import org.jetbrains.java.decompiler.struct.attr.StructAnnotationParameterAttribute; +import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.List; + +public class IdeaNotNullHelper { + + + public static boolean removeHardcodedChecks(Statement root, StructMethod mt) { + + boolean checks_removed = false; + + // parameter @NotNull annotations + while (findAndRemoveParameterCheck(root, mt)) { // iterate until nothing found. Each invocation removes one parameter check. + checks_removed = true; + } + + // method @NotNull annotation + while (findAndRemoveReturnCheck(root, mt)) { // iterate until nothing found. Each invocation handles one method exit check. + checks_removed = true; + } + + return checks_removed; + } + + private static boolean findAndRemoveParameterCheck(Statement stat, StructMethod mt) { + + Statement st = stat.getFirst(); + while (st.type == Statement.TYPE_SEQUENCE) { + st = st.getFirst(); + } + + if (st.type == Statement.TYPE_IF) { + + IfStatement ifstat = (IfStatement)st; + Statement ifbranch = ifstat.getIfstat(); + + Exprent if_condition = ifstat.getHeadexprent().getCondition(); + + boolean is_notnull_check = false; + + // TODO: FUNCTION_NE also possible if reversed order (in theory) + if (ifbranch != null && + if_condition.type == Exprent.EXPRENT_FUNCTION && + ((FunctionExprent)if_condition).getFunctype() == FunctionExprent.FUNCTION_EQ && + ifbranch.type == Statement.TYPE_BASICBLOCK && + ifbranch.getExprents().size() == 1 && + ifbranch.getExprents().get(0).type == Exprent.EXPRENT_EXIT) { + + FunctionExprent func = (FunctionExprent)if_condition; + Exprent first_param = func.getLstOperands().get(0); + Exprent second_param = func.getLstOperands().get(1); + + if (second_param.type == Exprent.EXPRENT_CONST && + second_param.getExprType().type == CodeConstants.TYPE_NULL) { // TODO: reversed parameter order + if (first_param.type == Exprent.EXPRENT_VAR) { + VarExprent var = (VarExprent)first_param; + + boolean thisvar = !mt.hasModifier(CodeConstants.ACC_STATIC); + + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + VBStyleCollection<StructGeneralAttribute, String> attributes = mt.getAttributes(); + + // parameter annotations + StructAnnotationParameterAttribute param_annotations = (StructAnnotationParameterAttribute)attributes + .getWithKey(StructGeneralAttribute.ATTRIBUTE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS); + if (param_annotations != null) { + + List<List<AnnotationExprent>> param_annotations_lists = param_annotations.getParamAnnotations(); + int method_param_number = md.params.length; + + int index = thisvar ? 1 : 0; + for (int i = 0; i < method_param_number; i++) { + + if (index == var.getIndex()) { + if (param_annotations_lists.size() >= method_param_number - i) { + int shift = method_param_number - + param_annotations_lists + .size(); // NOTE: workaround for compiler bug, count annotations starting with the last parameter + + List<AnnotationExprent> annotations = param_annotations_lists.get(i - shift); + + for (AnnotationExprent ann : annotations) { + if (ann.getClassname().equals("org/jetbrains/annotations/NotNull")) { + is_notnull_check = true; + } + } + } + + break; + } + + index += md.params[i].stack_size; + } + } + } + } + } + + if (!is_notnull_check) { + return false; + } + + removeParameterCheck(stat, mt); + + return true; + } + + return false; + } + + private static void removeParameterCheck(Statement stat, StructMethod mt) { + + Statement st = stat.getFirst(); + while (st.type == Statement.TYPE_SEQUENCE) { + st = st.getFirst(); + } + + IfStatement ifstat = (IfStatement)st; + + if (ifstat.getElsestat() == null) { // if + // TODO: + } + else { // if - else + + StatEdge ifedge = ifstat.getIfEdge(); + StatEdge elseedge = ifstat.getElseEdge(); + + Statement ifbranch = ifstat.getIfstat(); + Statement elsebranch = ifstat.getElsestat(); + + ifstat.getFirst().removeSuccessor(ifedge); + ifstat.getFirst().removeSuccessor(elseedge); + + ifstat.getStats().removeWithKey(ifbranch.id); + ifstat.getStats().removeWithKey(elsebranch.id); + + if (!ifbranch.getAllSuccessorEdges().isEmpty()) { + ifbranch.removeSuccessor(ifbranch.getAllSuccessorEdges().get(0)); + } + + ifstat.getParent().replaceStatement(ifstat, elsebranch); + ifstat.getParent().setAllParent(); + } + } + + private static boolean findAndRemoveReturnCheck(Statement stat, StructMethod mt) { + + VBStyleCollection<StructGeneralAttribute, String> attributes = mt.getAttributes(); + + boolean is_notnull_check = false; + + // method annotation, refers to the return value + StructAnnotationAttribute attr = + (StructAnnotationAttribute)attributes.getWithKey(StructGeneralAttribute.ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS); + if (attr != null) { + List<AnnotationExprent> annotations = attr.getAnnotations(); + + for (AnnotationExprent ann : annotations) { + if (ann.getClassname().equals("org/jetbrains/annotations/NotNull")) { + is_notnull_check = true; + } + } + } + + if (is_notnull_check) { + return removeReturnCheck(stat, mt); + } + + return false; + } + + + private static boolean removeReturnCheck(Statement stat, StructMethod mt) { + + Statement parent = stat.getParent(); + + if (parent != null && parent.type == Statement.TYPE_IF && stat.type == Statement.TYPE_BASICBLOCK && stat.getExprents().size() == 1) { + Exprent exprent = stat.getExprents().get(0); + if (exprent.type == Exprent.EXPRENT_EXIT) { + ExitExprent exit_exprent = (ExitExprent)exprent; + if (exit_exprent.getExittype() == ExitExprent.EXIT_RETURN) { + Exprent exprent_value = exit_exprent.getValue(); + //if(exprent_value.type == Exprent.EXPRENT_VAR) { + // VarExprent var_value = (VarExprent)exprent_value; + + IfStatement ifparent = (IfStatement)parent; + Exprent if_condition = ifparent.getHeadexprent().getCondition(); + + if (ifparent.getElsestat() == stat && if_condition.type == Exprent.EXPRENT_FUNCTION && + ((FunctionExprent)if_condition).getFunctype() == FunctionExprent.FUNCTION_EQ) { // TODO: reversed order possible (in theory) + + FunctionExprent func = (FunctionExprent)if_condition; + Exprent first_param = func.getLstOperands().get(0); + Exprent second_param = func.getLstOperands().get(1); + + StatEdge ifedge = ifparent.getIfEdge(); + StatEdge elseedge = ifparent.getElseEdge(); + + Statement ifbranch = ifparent.getIfstat(); + Statement elsebranch = ifparent.getElsestat(); + + if (second_param.type == Exprent.EXPRENT_CONST && + second_param.getExprType().type == CodeConstants.TYPE_NULL) { // TODO: reversed parameter order + //if(first_param.type == Exprent.EXPRENT_VAR && ((VarExprent)first_param).getIndex() == var_value.getIndex()) { + if (first_param.equals(exprent_value)) { // TODO: check for absence of side effects like method invocations etc. + if (ifbranch.type == Statement.TYPE_BASICBLOCK && + ifbranch.getExprents().size() == 1 && + // TODO: special check for IllegalStateException + ifbranch.getExprents().get(0).type == Exprent.EXPRENT_EXIT) { + + ifparent.getFirst().removeSuccessor(ifedge); + ifparent.getFirst().removeSuccessor(elseedge); + + ifparent.getStats().removeWithKey(ifbranch.id); + ifparent.getStats().removeWithKey(elsebranch.id); + + if (!ifbranch.getAllSuccessorEdges().isEmpty()) { + ifbranch.removeSuccessor(ifbranch.getAllSuccessorEdges().get(0)); + } + + if (!ifparent.getFirst().getExprents().isEmpty()) { + elsebranch.getExprents().addAll(0, ifparent.getFirst().getExprents()); + } + + ifparent.getParent().replaceStatement(ifparent, elsebranch); + ifparent.getParent().setAllParent(); + + return true; + } + } + } + } + //} + } + } + } + else if (parent != null && + parent.type == Statement.TYPE_SEQUENCE && + stat.type == Statement.TYPE_BASICBLOCK && + stat.getExprents().size() == 1) { + Exprent exprent = stat.getExprents().get(0); + if (exprent.type == Exprent.EXPRENT_EXIT) { + ExitExprent exit_exprent = (ExitExprent)exprent; + if (exit_exprent.getExittype() == ExitExprent.EXIT_RETURN) { + Exprent exprent_value = exit_exprent.getValue(); + + SequenceStatement sequence = (SequenceStatement)parent; + int sequence_stats_number = sequence.getStats().size(); + + if (sequence_stats_number > 1 && + sequence.getStats().getLast() == stat && + sequence.getStats().get(sequence_stats_number - 2).type == Statement.TYPE_IF) { + + IfStatement ifstat = (IfStatement)sequence.getStats().get(sequence_stats_number - 2); + Exprent if_condition = ifstat.getHeadexprent().getCondition(); + + if (ifstat.iftype == IfStatement.IFTYPE_IF && if_condition.type == Exprent.EXPRENT_FUNCTION && + ((FunctionExprent)if_condition).getFunctype() == FunctionExprent.FUNCTION_EQ) { // TODO: reversed order possible (in theory) + + FunctionExprent func = (FunctionExprent)if_condition; + Exprent first_param = func.getLstOperands().get(0); + Exprent second_param = func.getLstOperands().get(1); + + Statement ifbranch = ifstat.getIfstat(); + + if (second_param.type == Exprent.EXPRENT_CONST && + second_param.getExprType().type == CodeConstants.TYPE_NULL) { // TODO: reversed parameter order + if (first_param.equals(exprent_value)) { // TODO: check for absence of side effects like method invocations etc. + if (ifbranch.type == Statement.TYPE_BASICBLOCK && + ifbranch.getExprents().size() == 1 && + // TODO: special check for IllegalStateException + ifbranch.getExprents().get(0).type == Exprent.EXPRENT_EXIT) { + + ifstat.removeSuccessor(ifstat.getAllSuccessorEdges().get(0)); // remove 'else' edge + + if (!ifstat.getFirst().getExprents().isEmpty()) { + stat.getExprents().addAll(0, ifstat.getFirst().getExprents()); + } + + for (StatEdge edge : ifstat.getAllPredecessorEdges()) { + + ifstat.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, stat); + stat.addPredecessor(edge); + } + + sequence.getStats().removeWithKey(ifstat.id); + sequence.setFirst(sequence.getStats().get(0)); + + return true; + } + } + } + } + } + } + } + } + + + for (Statement st : stat.getStats()) { + if (removeReturnCheck(st, mt)) { + return true; + } + } + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/IfHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/IfHelper.java new file mode 100644 index 000000000000..b1a955cfd528 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/IfHelper.java @@ -0,0 +1,750 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.FunctionExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.IfExprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.IfStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.SequenceStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + + +public class IfHelper { + + + public static boolean mergeAllIfs(RootStatement root) { + + boolean res = mergeAllIfsRec(root, new HashSet<Integer>()); + + if (res) { + SequenceHelper.condenseSequences(root); + } + + return res; + } + + + private static boolean mergeAllIfsRec(Statement stat, HashSet<Integer> setReorderedIfs) { + + boolean res = false; + + if (stat.getExprents() == null) { + + while (true) { + + boolean changed = false; + + for (Statement st : stat.getStats()) { + + res |= mergeAllIfsRec(st, setReorderedIfs); + + // collapse composed if's + if (changed = mergeIfs(st, setReorderedIfs)) { + break; + } + } + + res |= changed; + + if (!changed) { + break; + } + } + } + + return res; + } + + + public static boolean mergeIfs(Statement statement, HashSet<Integer> setReorderedIfs) { + + if (statement.type != Statement.TYPE_IF && statement.type != Statement.TYPE_SEQUENCE) { + return false; + } + + boolean res = false; + + while (true) { + + boolean updated = false; + + List<Statement> lst = new ArrayList<Statement>(); + if (statement.type == Statement.TYPE_IF) { + lst.add(statement); + } + else { + lst.addAll(statement.getStats()); + } + + boolean stsingle = (lst.size() == 1); + + for (Statement stat : lst) { + + if (stat.type == Statement.TYPE_IF) { + IfNode rtnode = buildGraph((IfStatement)stat, stsingle); + + if (rtnode == null) { + continue; + } + + if (updated = collapseIfIf(rtnode)) { + break; + } + + if (!setReorderedIfs.contains(stat.id)) { + + if (updated = collapseIfElse(rtnode)) { + break; + } + + if (updated = collapseElse(rtnode)) { + break; + } + } + + if (updated = reorderIf((IfStatement)stat)) { + setReorderedIfs.add(stat.id); + break; + } + } + } + + if (!updated) { + break; + } + + res |= updated; + } + + return res; + } + + private static boolean collapseIfIf(IfNode rtnode) { + + if (rtnode.edgetypes.get(0) == 0) { + IfNode ifbranch = rtnode.succs.get(0); + if (ifbranch.succs.size() == 2) { + + // if-if branch + if (ifbranch.succs.get(1).value == rtnode.succs.get(1).value) { + + IfStatement ifparent = (IfStatement)rtnode.value; + IfStatement ifchild = (IfStatement)ifbranch.value; + Statement ifinner = ifbranch.succs.get(0).value; + + if (ifchild.getFirst().getExprents().isEmpty()) { + + ifparent.getFirst().removeSuccessor(ifparent.getIfEdge()); + ifchild.removeSuccessor(ifchild.getAllSuccessorEdges().get(0)); + ifparent.getStats().removeWithKey(ifchild.id); + + if (ifbranch.edgetypes.get(0).intValue() == 1) { // target null + + ifparent.setIfstat(null); + + StatEdge ifedge = ifchild.getIfEdge(); + + ifchild.getFirst().removeSuccessor(ifedge); + ifedge.setSource(ifparent.getFirst()); + + if (ifedge.closure == ifchild) { + ifedge.closure = null; + } + ifparent.getFirst().addSuccessor(ifedge); + + ifparent.setIfEdge(ifedge); + } + else { + ifchild.getFirst().removeSuccessor(ifchild.getIfEdge()); + + StatEdge ifedge = new StatEdge(StatEdge.TYPE_REGULAR, ifparent.getFirst(), ifinner); + ifparent.getFirst().addSuccessor(ifedge); + ifparent.setIfEdge(ifedge); + ifparent.setIfstat(ifinner); + + ifparent.getStats().addWithKey(ifinner, ifinner.id); + ifinner.setParent(ifparent); + + if (!ifinner.getAllSuccessorEdges().isEmpty()) { + StatEdge edge = ifinner.getAllSuccessorEdges().get(0); + if (edge.closure == ifchild) { + edge.closure = null; + } + } + } + + // merge if conditions + IfExprent statexpr = ifparent.getHeadexprent(); + + List<Exprent> lstOperands = new ArrayList<Exprent>(); + lstOperands.add(statexpr.getCondition()); + lstOperands.add(ifchild.getHeadexprent().getCondition()); + + statexpr.setCondition(new FunctionExprent(FunctionExprent.FUNCTION_CADD, lstOperands)); + + return true; + } + } + } + } + + return false; + } + + private static boolean collapseIfElse(IfNode rtnode) { + + if (rtnode.edgetypes.get(0).intValue() == 0) { + IfNode ifbranch = rtnode.succs.get(0); + if (ifbranch.succs.size() == 2) { + + // if-else branch + if (ifbranch.succs.get(0).value == rtnode.succs.get(1).value) { + + IfStatement ifparent = (IfStatement)rtnode.value; + IfStatement ifchild = (IfStatement)ifbranch.value; + + if (ifchild.getFirst().getExprents().isEmpty()) { + + ifparent.getFirst().removeSuccessor(ifparent.getIfEdge()); + ifchild.getFirst().removeSuccessor(ifchild.getIfEdge()); + ifparent.getStats().removeWithKey(ifchild.id); + + if (ifbranch.edgetypes.get(1).intValue() == 1 && + ifbranch.edgetypes.get(0).intValue() == 1) { // target null + + ifparent.setIfstat(null); + + StatEdge ifedge = ifchild.getAllSuccessorEdges().get(0); + + ifchild.removeSuccessor(ifedge); + ifedge.setSource(ifparent.getFirst()); + ifparent.getFirst().addSuccessor(ifedge); + + ifparent.setIfEdge(ifedge); + } + else { + throw new RuntimeException("inconsistent if structure!"); + } + + // merge if conditions + IfExprent statexpr = ifparent.getHeadexprent(); + + List<Exprent> lstOperands = new ArrayList<Exprent>(); + lstOperands.add(statexpr.getCondition()); + lstOperands.add(new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, + Arrays.asList(new Exprent[]{ifchild.getHeadexprent().getCondition()}))); + statexpr.setCondition(new FunctionExprent(FunctionExprent.FUNCTION_CADD, lstOperands)); + + return true; + } + } + } + } + + return false; + } + + + private static boolean collapseElse(IfNode rtnode) { + + if (rtnode.edgetypes.get(1).intValue() == 0) { + IfNode elsebranch = rtnode.succs.get(1); + if (elsebranch.succs.size() == 2) { + + // else-if or else-else branch + int path = elsebranch.succs.get(1).value == rtnode.succs.get(0).value ? 2 : + (elsebranch.succs.get(0).value == rtnode.succs.get(0).value ? 1 : 0); + + if (path > 0) { + + IfStatement firstif = (IfStatement)rtnode.value; + IfStatement secondif = (IfStatement)elsebranch.value; + Statement parent = firstif.getParent(); + + if (secondif.getFirst().getExprents().isEmpty()) { + + firstif.getFirst().removeSuccessor(firstif.getIfEdge()); + + // remove first if + firstif.removeAllSuccessors(secondif); + + for (StatEdge edge : firstif.getAllPredecessorEdges()) { + if (!firstif.containsStatementStrict(edge.getSource())) { + firstif.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, secondif); + secondif.addPredecessor(edge); + } + } + + parent.getStats().removeWithKey(firstif.id); + if (parent.getFirst() == firstif) { + parent.setFirst(secondif); + } + + // merge if conditions + IfExprent statexpr = secondif.getHeadexprent(); + + List<Exprent> lstOperands = new ArrayList<Exprent>(); + lstOperands.add(firstif.getHeadexprent().getCondition()); + + if (path == 2) { + lstOperands.set(0, new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, + Arrays.asList(new Exprent[]{lstOperands.get(0)}))); + } + + lstOperands.add(statexpr.getCondition()); + + statexpr + .setCondition(new FunctionExprent(path == 1 ? FunctionExprent.FUNCTION_COR : FunctionExprent.FUNCTION_CADD, lstOperands)); + + if (secondif.getFirst().getExprents().isEmpty() && + !firstif.getFirst().getExprents().isEmpty()) { + + secondif.replaceStatement(secondif.getFirst(), firstif.getFirst()); + } + + return true; + } + } + } + else if (elsebranch.succs.size() == 1) { + + if (elsebranch.succs.get(0).value == rtnode.succs.get(0).value) { + + IfStatement firstif = (IfStatement)rtnode.value; + Statement second = elsebranch.value; + + firstif.removeAllSuccessors(second); + + for (StatEdge edge : second.getAllSuccessorEdges()) { + second.removeSuccessor(edge); + edge.setSource(firstif); + firstif.addSuccessor(edge); + } + + StatEdge ifedge = firstif.getIfEdge(); + firstif.getFirst().removeSuccessor(ifedge); + + second.addSuccessor(new StatEdge(ifedge.getType(), second, ifedge.getDestination(), ifedge.closure)); + + StatEdge newifedge = new StatEdge(StatEdge.TYPE_REGULAR, firstif.getFirst(), second); + firstif.getFirst().addSuccessor(newifedge); + firstif.setIfstat(second); + + firstif.getStats().addWithKey(second, second.id); + second.setParent(firstif); + + firstif.getParent().getStats().removeWithKey(second.id); + + // negate the if condition + IfExprent statexpr = firstif.getHeadexprent(); + statexpr + .setCondition(new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, Arrays.asList(new Exprent[]{statexpr.getCondition()}))); + + return true; + } + } + } + + return false; + } + + + private static IfNode buildGraph(IfStatement stat, boolean stsingle) { + + if (stat.iftype == IfStatement.IFTYPE_IFELSE) { + return null; + } + + IfNode res = new IfNode(stat); + + // if branch + Statement ifchild = stat.getIfstat(); + if (ifchild == null) { + StatEdge edge = stat.getIfEdge(); + res.addChild(new IfNode(edge.getDestination()), 1); + } + else { + IfNode ifnode = new IfNode(ifchild); + res.addChild(ifnode, 0); + if (ifchild.type == Statement.TYPE_IF && ((IfStatement)ifchild).iftype == IfStatement.IFTYPE_IF) { + IfStatement stat2 = (IfStatement)ifchild; + Statement ifchild2 = stat2.getIfstat(); + if (ifchild2 == null) { + StatEdge edge = stat2.getIfEdge(); + ifnode.addChild(new IfNode(edge.getDestination()), 1); + } + else { + ifnode.addChild(new IfNode(ifchild2), 0); + } + } + + if (!ifchild.getAllSuccessorEdges().isEmpty()) { + ifnode.addChild(new IfNode(ifchild.getAllSuccessorEdges().get(0).getDestination()), 1); + } + } + + // else branch + StatEdge edge = stat.getAllSuccessorEdges().get(0); + Statement elsechild = edge.getDestination(); + IfNode elsenode = new IfNode(elsechild); + + if (stsingle || edge.getType() != StatEdge.TYPE_REGULAR) { + res.addChild(elsenode, 1); + } + else { + res.addChild(elsenode, 0); + if (elsechild.type == Statement.TYPE_IF && ((IfStatement)elsechild).iftype == IfStatement.IFTYPE_IF) { + IfStatement stat2 = (IfStatement)elsechild; + Statement ifchild2 = stat2.getIfstat(); + if (ifchild2 == null) { + elsenode.addChild(new IfNode(stat2.getIfEdge().getDestination()), 1); + } + else { + elsenode.addChild(new IfNode(ifchild2), 0); + } + } + + if (!elsechild.getAllSuccessorEdges().isEmpty()) { + elsenode.addChild(new IfNode(elsechild.getAllSuccessorEdges().get(0).getDestination()), 1); + } + } + + return res; + } + + + // FIXME: rewrite the entire method!!! keep in mind finally exits!! + private static boolean reorderIf(IfStatement ifstat) { + + if (ifstat.iftype == IfStatement.IFTYPE_IFELSE) { + return false; + } + + boolean ifdirect = false, elsedirect = false; + boolean noifstat = false, noelsestat = false; + boolean ifdirectpath = false, elsedirectpath = false; + + Statement parent = ifstat.getParent(); + Statement from = parent.type == Statement.TYPE_SEQUENCE ? parent : ifstat; + + Statement next = getNextStatement(from); + + if (ifstat.getIfstat() == null) { + noifstat = true; + + if (ifstat.getIfEdge().getType() == StatEdge.TYPE_FINALLYEXIT) { + ifdirect = true; + } + else { + ifdirect = MergeHelper.isDirectPath(from, ifstat.getIfEdge().getDestination()); + } + } + else { + List<StatEdge> lstSuccs = ifstat.getIfstat().getAllSuccessorEdges(); + if (!lstSuccs.isEmpty() && lstSuccs.get(0).getType() == StatEdge.TYPE_FINALLYEXIT) { + ifdirect = true; + } + else { + ifdirect = hasDirectEndEdge(ifstat.getIfstat(), from); + } + } + + Statement last = parent.type == Statement.TYPE_SEQUENCE ? parent.getStats().getLast() : ifstat; + noelsestat = (last == ifstat); + + if (!last.getAllSuccessorEdges().isEmpty() && last.getAllSuccessorEdges().get(0).getType() == StatEdge.TYPE_FINALLYEXIT) { + elsedirect = true; + } + else { + elsedirect = hasDirectEndEdge(last, from); + } + + if (!noelsestat && existsPath(ifstat, ifstat.getAllSuccessorEdges().get(0).getDestination())) { + return false; + } + + if (!ifdirect && !noifstat) { + ifdirectpath = existsPath(ifstat, next); + } + + if (!elsedirect && !noelsestat) { + SequenceStatement sequence = (SequenceStatement)parent; + + for (int i = sequence.getStats().size() - 1; i >= 0; i--) { + Statement sttemp = sequence.getStats().get(i); + if (sttemp == ifstat) { + break; + } + else { + if (elsedirectpath = existsPath(sttemp, next)) { + break; + } + } + } + } + + if ((ifdirect || ifdirectpath) && (elsedirect || elsedirectpath) && !noifstat && !noelsestat) { // if - then - else + + SequenceStatement sequence = (SequenceStatement)parent; + + // build and cut the new else statement + List<Statement> lst = new ArrayList<Statement>(); + for (int i = sequence.getStats().size() - 1; i >= 0; i--) { + Statement sttemp = sequence.getStats().get(i); + if (sttemp == ifstat) { + break; + } + else { + lst.add(0, sttemp); + } + } + + Statement stelse; + if (lst.size() == 1) { + stelse = lst.get(0); + } + else { + stelse = new SequenceStatement(lst); + stelse.setAllParent(); + } + + ifstat.removeSuccessor(ifstat.getAllSuccessorEdges().get(0)); + for (Statement st : lst) { + sequence.getStats().removeWithKey(st.id); + } + + StatEdge elseedge = new StatEdge(StatEdge.TYPE_REGULAR, ifstat.getFirst(), stelse); + ifstat.getFirst().addSuccessor(elseedge); + ifstat.setElsestat(stelse); + ifstat.setElseEdge(elseedge); + + ifstat.getStats().addWithKey(stelse, stelse.id); + stelse.setParent(ifstat); + + // if(next.type != Statement.TYPE_DUMMYEXIT && (ifdirect || elsedirect)) { + // StatEdge breakedge = new StatEdge(StatEdge.TYPE_BREAK, ifstat, next); + // sequence.addLabeledEdge(breakedge); + // ifstat.addSuccessor(breakedge); + // } + + ifstat.iftype = IfStatement.IFTYPE_IFELSE; + } + else if (ifdirect && (!elsedirect || (noifstat && !noelsestat))) { // if - then + + // negate the if condition + IfExprent statexpr = ifstat.getHeadexprent(); + statexpr.setCondition(new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, Arrays.asList(new Exprent[]{statexpr.getCondition()}))); + + if (noelsestat) { + StatEdge ifedge = ifstat.getIfEdge(); + StatEdge elseedge = ifstat.getAllSuccessorEdges().get(0); + + if (noifstat) { + ifstat.getFirst().removeSuccessor(ifedge); + ifstat.removeSuccessor(elseedge); + + ifedge.setSource(ifstat); + elseedge.setSource(ifstat.getFirst()); + + ifstat.addSuccessor(ifedge); + ifstat.getFirst().addSuccessor(elseedge); + + ifstat.setIfEdge(elseedge); + } + else { + Statement ifbranch = ifstat.getIfstat(); + SequenceStatement newseq = new SequenceStatement(Arrays.asList(ifstat, ifbranch)); + + ifstat.getFirst().removeSuccessor(ifedge); + ifstat.getStats().removeWithKey(ifbranch.id); + ifstat.setIfstat(null); + + ifstat.removeSuccessor(elseedge); + elseedge.setSource(ifstat.getFirst()); + ifstat.getFirst().addSuccessor(elseedge); + + ifstat.setIfEdge(elseedge); + + ifstat.getParent().replaceStatement(ifstat, newseq); + newseq.setAllParent(); + + ifstat.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, ifstat, ifbranch)); + } + } + else { + + SequenceStatement sequence = (SequenceStatement)parent; + + // build and cut the new else statement + List<Statement> lst = new ArrayList<Statement>(); + for (int i = sequence.getStats().size() - 1; i >= 0; i--) { + Statement sttemp = sequence.getStats().get(i); + if (sttemp == ifstat) { + break; + } + else { + lst.add(0, sttemp); + } + } + + Statement stelse; + if (lst.size() == 1) { + stelse = lst.get(0); + } + else { + stelse = new SequenceStatement(lst); + stelse.setAllParent(); + } + + ifstat.removeSuccessor(ifstat.getAllSuccessorEdges().get(0)); + for (Statement st : lst) { + sequence.getStats().removeWithKey(st.id); + } + + if (noifstat) { + StatEdge ifedge = ifstat.getIfEdge(); + + ifstat.getFirst().removeSuccessor(ifedge); + ifedge.setSource(ifstat); + ifstat.addSuccessor(ifedge); + } + else { + Statement ifbranch = ifstat.getIfstat(); + + ifstat.getFirst().removeSuccessor(ifstat.getIfEdge()); + ifstat.getStats().removeWithKey(ifbranch.id); + + ifstat.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, ifstat, ifbranch)); + + sequence.getStats().addWithKey(ifbranch, ifbranch.id); + ifbranch.setParent(sequence); + } + + StatEdge newifedge = new StatEdge(StatEdge.TYPE_REGULAR, ifstat.getFirst(), stelse); + ifstat.getFirst().addSuccessor(newifedge); + ifstat.setIfstat(stelse); + ifstat.setIfEdge(newifedge); + + ifstat.getStats().addWithKey(stelse, stelse.id); + stelse.setParent(ifstat); + } + } + else { + return false; + } + + return true; + } + + private static boolean hasDirectEndEdge(Statement stat, Statement from) { + + for (StatEdge edge : stat.getAllSuccessorEdges()) { + if (MergeHelper.isDirectPath(from, edge.getDestination())) { + return true; + } + } + + if (stat.getExprents() == null) { + switch (stat.type) { + case Statement.TYPE_SEQUENCE: + return hasDirectEndEdge(stat.getStats().getLast(), from); + case Statement.TYPE_CATCHALL: + case Statement.TYPE_TRYCATCH: + for (Statement st : stat.getStats()) { + if (hasDirectEndEdge(st, from)) { + return true; + } + } + break; + case Statement.TYPE_IF: + IfStatement ifstat = (IfStatement)stat; + if (ifstat.iftype == IfStatement.IFTYPE_IFELSE) { + return hasDirectEndEdge(ifstat.getIfstat(), from) || + hasDirectEndEdge(ifstat.getElsestat(), from); + } + break; + case Statement.TYPE_SYNCRONIZED: + return hasDirectEndEdge(stat.getStats().get(1), from); + case Statement.TYPE_SWITCH: + for (Statement st : stat.getStats()) { + if (hasDirectEndEdge(st, from)) { + return true; + } + } + } + } + + return false; + } + + + private static Statement getNextStatement(Statement stat) { + + Statement parent = stat.getParent(); + switch (parent.type) { + case Statement.TYPE_ROOT: + return ((RootStatement)parent).getDummyExit(); + case Statement.TYPE_DO: + return parent; + case Statement.TYPE_SEQUENCE: + SequenceStatement sequence = (SequenceStatement)parent; + if (sequence.getStats().getLast() != stat) { + for (int i = sequence.getStats().size() - 1; i >= 0; i--) { + if (sequence.getStats().get(i) == stat) { + return sequence.getStats().get(i + 1); + } + } + } + } + + return getNextStatement(parent); + } + + private static boolean existsPath(Statement from, Statement to) { + + for (StatEdge edge : to.getAllPredecessorEdges()) { + if (from.containsStatementStrict(edge.getSource())) { + return true; + } + } + + return false; + } + + private static class IfNode { + public Statement value; + + public List<IfNode> succs = new ArrayList<IfNode>(); + public List<Integer> edgetypes = new ArrayList<Integer>(); + + public IfNode(Statement value) { + this.value = value; + } + + public void addChild(IfNode child, int type) { + succs.add(child); + edgetypes.add(new Integer(type)); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/InlineSingleBlockHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/InlineSingleBlockHelper.java new file mode 100644 index 000000000000..adeda024151b --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/InlineSingleBlockHelper.java @@ -0,0 +1,220 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; + +import java.util.ArrayList; +import java.util.List; + + +public class InlineSingleBlockHelper { + + + public static boolean inlineSingleBlocks(RootStatement root) { + + boolean res = inlineSingleBlocksRec(root); + + if (res) { + SequenceHelper.condenseSequences(root); + } + + return res; + } + + private static boolean inlineSingleBlocksRec(Statement stat) { + + boolean res = false; + + for (Statement st : stat.getStats()) { + res |= inlineSingleBlocksRec(st); + } + + if (stat.type == Statement.TYPE_SEQUENCE) { + + SequenceStatement seq = (SequenceStatement)stat; + for (int i = 1; i < seq.getStats().size(); i++) { + if (isInlineable(seq, i)) { + inlineBlock(seq, i); + return true; + } + } + } + + return res; + } + + private static void inlineBlock(SequenceStatement seq, int index) { + + Statement first = seq.getStats().get(index); + Statement pre = seq.getStats().get(index - 1); + pre.removeSuccessor(pre.getAllSuccessorEdges().get(0)); // single regular edge + + StatEdge edge = first.getPredecessorEdges(StatEdge.TYPE_BREAK).get(0); + Statement source = edge.getSource(); + Statement parent = source.getParent(); + source.removeSuccessor(edge); + + List<Statement> lst = new ArrayList<Statement>(); + for (int i = seq.getStats().size() - 1; i >= index; i--) { + lst.add(0, seq.getStats().remove(i)); + } + + if (parent.type == Statement.TYPE_IF && ((IfStatement)parent).iftype == IfStatement.IFTYPE_IF && + source == parent.getFirst()) { + IfStatement ifparent = (IfStatement)parent; + SequenceStatement block = new SequenceStatement(lst); + block.setAllParent(); + + StatEdge newedge = new StatEdge(StatEdge.TYPE_REGULAR, source, block); + source.addSuccessor(newedge); + ifparent.setIfEdge(newedge); + ifparent.setIfstat(block); + + ifparent.getStats().addWithKey(block, block.id); + block.setParent(ifparent); + } + else { + lst.add(0, source); + + SequenceStatement block = new SequenceStatement(lst); + block.setAllParent(); + + parent.replaceStatement(source, block); + + // LabelHelper.lowContinueLabels not applicable because of forward continue edges + // LabelHelper.lowContinueLabels(block, new HashSet<StatEdge>()); + // do it by hand + for (StatEdge prededge : block.getPredecessorEdges(StatEdge.TYPE_CONTINUE)) { + + block.removePredecessor(prededge); + prededge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, prededge, source); + source.addPredecessor(prededge); + + source.addLabeledEdge(prededge); + } + + + if (parent.type == Statement.TYPE_SWITCH) { + ((SwitchStatement)parent).sortEdgesAndNodes(); + } + + source.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, source, first)); + } + } + + private static boolean isInlineable(SequenceStatement seq, int index) { + + Statement first = seq.getStats().get(index); + Statement pre = seq.getStats().get(index - 1); + + if (pre.hasBasicSuccEdge()) { + return false; + } + + + List<StatEdge> lst = first.getPredecessorEdges(StatEdge.TYPE_BREAK); + + if (lst.size() == 1) { + StatEdge edge = lst.get(0); + + if (sameCatchRanges(edge)) { + if (edge.explicit) { + return true; + } + else { + for (int i = index; i < seq.getStats().size(); i++) { + if (!noExitLabels(seq.getStats().get(i), seq)) { + return false; + } + } + return true; + } + } + // FIXME: count labels properly + } + + return false; + } + + private static boolean sameCatchRanges(StatEdge edge) { + + Statement from = edge.getSource(); + Statement to = edge.getDestination(); + + while (true) { + + Statement parent = from.getParent(); + if (parent.containsStatementStrict(to)) { + break; + } + + if (parent.type == Statement.TYPE_TRYCATCH || + parent.type == Statement.TYPE_CATCHALL) { + if (parent.getFirst() == from) { + return false; + } + } + else if (parent.type == Statement.TYPE_SYNCRONIZED) { + if (parent.getStats().get(1) == from) { + return false; + } + } + + from = parent; + } + + return true; + } + + private static boolean noExitLabels(Statement block, Statement sequence) { + + for (StatEdge edge : block.getAllSuccessorEdges()) { + if (edge.getType() != StatEdge.TYPE_REGULAR && edge.getDestination().type != Statement.TYPE_DUMMYEXIT) { + if (!sequence.containsStatementStrict(edge.getDestination())) { + return false; + } + } + } + + for (Statement st : block.getStats()) { + if (!noExitLabels(st, sequence)) { + return false; + } + } + + return true; + } + + public static boolean isBreakEdgeLabeled(Statement source, Statement closure) { + + if (closure.type == Statement.TYPE_DO || closure.type == Statement.TYPE_SWITCH) { + + Statement parent = source.getParent(); + + if (parent == closure) { + return false; + } + else { + return parent.type == Statement.TYPE_DO || parent.type == Statement.TYPE_SWITCH || + isBreakEdgeLabeled(parent, closure); + } + } + else { + return true; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LabelHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LabelHelper.java new file mode 100644 index 000000000000..1f4b5eea0e22 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LabelHelper.java @@ -0,0 +1,506 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; + +import java.util.*; +import java.util.Map.Entry; + + +public class LabelHelper { + + + public static void cleanUpEdges(RootStatement root) { + + resetAllEdges(root); + + removeNonImmediateEdges(root); + + liftClosures(root); + + lowContinueLabels(root, new HashSet<StatEdge>()); + + lowClosures(root); + } + + public static void identifyLabels(RootStatement root) { + + setExplicitEdges(root); + + hideDefaultSwitchEdges(root); + + processStatementLabel(root); + + setRetEdgesUnlabeled(root); + } + + private static void liftClosures(Statement stat) { + + for (StatEdge edge : stat.getAllSuccessorEdges()) { + switch (edge.getType()) { + case StatEdge.TYPE_CONTINUE: + if (edge.getDestination() != edge.closure) { + edge.getDestination().addLabeledEdge(edge); + } + break; + case StatEdge.TYPE_BREAK: + Statement dest = edge.getDestination(); + if (dest.type != Statement.TYPE_DUMMYEXIT) { + Statement parent = dest.getParent(); + + List<Statement> lst = new ArrayList<Statement>(); + if (parent.type == Statement.TYPE_SEQUENCE) { + lst.addAll(parent.getStats()); + } + else if (parent.type == Statement.TYPE_SWITCH) { + lst.addAll(((SwitchStatement)parent).getCaseStatements()); + } + + for (int i = 0; i < lst.size(); i++) { + if (lst.get(i) == dest) { + lst.get(i - 1).addLabeledEdge(edge); + break; + } + } + } + } + } + + for (Statement st : stat.getStats()) { + liftClosures(st); + } + } + + private static void removeNonImmediateEdges(Statement stat) { + + for (Statement st : stat.getStats()) { + removeNonImmediateEdges(st); + } + + if (!stat.hasBasicSuccEdge()) { + for (StatEdge edge : stat.getSuccessorEdges(StatEdge.TYPE_CONTINUE | StatEdge.TYPE_BREAK)) { + stat.removeSuccessor(edge); + } + } + } + + public static void lowContinueLabels(Statement stat, HashSet<StatEdge> edges) { + + boolean ok = (stat.type != Statement.TYPE_DO); + if (!ok) { + DoStatement dostat = (DoStatement)stat; + ok = dostat.getLooptype() == DoStatement.LOOP_DO || + dostat.getLooptype() == DoStatement.LOOP_WHILE || + (dostat.getLooptype() == DoStatement.LOOP_FOR && dostat.getIncExprent() == null); + } + + if (ok) { + edges.addAll(stat.getPredecessorEdges(StatEdge.TYPE_CONTINUE)); + } + + if (ok && stat.type == Statement.TYPE_DO) { + for (StatEdge edge : edges) { + if (stat.containsStatementStrict(edge.getSource())) { + + edge.getDestination().removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, stat); + stat.addPredecessor(edge); + + stat.addLabeledEdge(edge); + } + } + } + + for (Statement st : stat.getStats()) { + if (st == stat.getFirst()) { + lowContinueLabels(st, edges); + } + else { + lowContinueLabels(st, new HashSet<StatEdge>()); + } + } + } + + public static void lowClosures(Statement stat) { + + for (StatEdge edge : new ArrayList<StatEdge>(stat.getLabelEdges())) { + + if (edge.getType() == StatEdge.TYPE_BREAK) { // FIXME: ? + for (Statement st : stat.getStats()) { + if (st.containsStatementStrict(edge.getSource())) { + if (MergeHelper.isDirectPath(st, edge.getDestination())) { + st.addLabeledEdge(edge); + } + } + } + } + } + + for (Statement st : stat.getStats()) { + lowClosures(st); + } + } + + private static void resetAllEdges(Statement stat) { + + for (Statement st : stat.getStats()) { + resetAllEdges(st); + } + + for (StatEdge edge : stat.getAllSuccessorEdges()) { + edge.explicit = true; + edge.labeled = true; + } + } + + private static void setRetEdgesUnlabeled(RootStatement root) { + Statement exit = root.getDummyExit(); + for (StatEdge edge : exit.getAllPredecessorEdges()) { + List<Exprent> lst = edge.getSource().getExprents(); + if (edge.getType() == StatEdge.TYPE_FINALLYEXIT || (lst != null && !lst.isEmpty() && + lst.get(lst.size() - 1).type == Exprent.EXPRENT_EXIT)) { + edge.labeled = false; + } + } + } + + private static HashMap<Statement, List<StatEdge>> setExplicitEdges(Statement stat) { + + HashMap<Statement, List<StatEdge>> mapEdges = new HashMap<Statement, List<StatEdge>>(); + + if (stat.getExprents() != null) { + return mapEdges; + } + + + switch (stat.type) { + case Statement.TYPE_TRYCATCH: + case Statement.TYPE_CATCHALL: + + for (Statement st : stat.getStats()) { + HashMap<Statement, List<StatEdge>> mapEdges1 = setExplicitEdges(st); + processEdgesWithNext(st, mapEdges1, null); + + if (stat.type == Statement.TYPE_TRYCATCH || st == stat.getFirst()) { // edges leaving a finally catch block are always explicit + // merge the maps + if (mapEdges1 != null) { + for (Entry<Statement, List<StatEdge>> entr : mapEdges1.entrySet()) { + if (mapEdges.containsKey(entr.getKey())) { + mapEdges.get(entr.getKey()).addAll(entr.getValue()); + } + else { + mapEdges.put(entr.getKey(), entr.getValue()); + } + } + } + } + } + + break; + case Statement.TYPE_DO: + mapEdges = setExplicitEdges(stat.getFirst()); + processEdgesWithNext(stat.getFirst(), mapEdges, stat); + break; + case Statement.TYPE_IF: + IfStatement ifstat = (IfStatement)stat; + // head statement is a basic block + if (ifstat.getIfstat() == null) { // empty if + processEdgesWithNext(ifstat.getFirst(), mapEdges, null); + } + else { + mapEdges = setExplicitEdges(ifstat.getIfstat()); + processEdgesWithNext(ifstat.getIfstat(), mapEdges, null); + + HashMap<Statement, List<StatEdge>> mapEdges1 = null; + if (ifstat.getElsestat() != null) { + mapEdges1 = setExplicitEdges(ifstat.getElsestat()); + processEdgesWithNext(ifstat.getElsestat(), mapEdges1, null); + } + + // merge the maps + if (mapEdges1 != null) { + for (Entry<Statement, List<StatEdge>> entr : mapEdges1.entrySet()) { + if (mapEdges.containsKey(entr.getKey())) { + mapEdges.get(entr.getKey()).addAll(entr.getValue()); + } + else { + mapEdges.put(entr.getKey(), entr.getValue()); + } + } + } + } + break; + case Statement.TYPE_ROOT: + mapEdges = setExplicitEdges(stat.getFirst()); + processEdgesWithNext(stat.getFirst(), mapEdges, ((RootStatement)stat).getDummyExit()); + break; + case Statement.TYPE_SEQUENCE: + int index = 0; + while (index < stat.getStats().size() - 1) { + Statement st = stat.getStats().get(index); + processEdgesWithNext(st, setExplicitEdges(st), stat.getStats().get(index + 1)); + index++; + } + + Statement st = stat.getStats().get(index); + mapEdges = setExplicitEdges(st); + processEdgesWithNext(st, mapEdges, null); + break; + case Statement.TYPE_SWITCH: + SwitchStatement swst = (SwitchStatement)stat; + + for (int i = 0; i < swst.getCaseStatements().size() - 1; i++) { + Statement stt = swst.getCaseStatements().get(i); + Statement stnext = swst.getCaseStatements().get(i + 1); + + if (stnext.getExprents() != null && stnext.getExprents().isEmpty()) { + stnext = stnext.getAllSuccessorEdges().get(0).getDestination(); + } + processEdgesWithNext(stt, setExplicitEdges(stt), stnext); + } + + int last = swst.getCaseStatements().size() - 1; + if (last >= 0) { // empty switch possible + Statement stlast = swst.getCaseStatements().get(last); + if (stlast.getExprents() != null && stlast.getExprents().isEmpty()) { + StatEdge edge = stlast.getAllSuccessorEdges().get(0); + mapEdges.put(edge.getDestination(), new ArrayList<StatEdge>(Arrays.asList(new StatEdge[]{edge}))); + } + else { + mapEdges = setExplicitEdges(stlast); + processEdgesWithNext(stlast, mapEdges, null); + } + } + + break; + case Statement.TYPE_SYNCRONIZED: + SynchronizedStatement synstat = (SynchronizedStatement)stat; + + processEdgesWithNext(synstat.getFirst(), setExplicitEdges(stat.getFirst()), synstat.getBody()); // FIXME: basic block? + mapEdges = setExplicitEdges(synstat.getBody()); + processEdgesWithNext(synstat.getBody(), mapEdges, null); + } + + + return mapEdges; + } + + private static void processEdgesWithNext(Statement stat, HashMap<Statement, List<StatEdge>> mapEdges, Statement next) { + + StatEdge statedge = null; + + List<StatEdge> lstSuccs = stat.getAllSuccessorEdges(); + if (!lstSuccs.isEmpty()) { + statedge = lstSuccs.get(0); + + if (statedge.getDestination() == next) { + statedge.explicit = false; + statedge = null; + } + else { + next = statedge.getDestination(); + } + } + + // no next for a do statement + if (stat.type == Statement.TYPE_DO && ((DoStatement)stat).getLooptype() == DoStatement.LOOP_DO) { + next = null; + } + + if (next == null) { + if (mapEdges.size() == 1) { + List<StatEdge> lstEdges = mapEdges.values().iterator().next(); + if (lstEdges.size() > 1 && mapEdges.keySet().iterator().next().type != Statement.TYPE_DUMMYEXIT) { + StatEdge edge_example = lstEdges.get(0); + + Statement closure = stat.getParent(); + if (!closure.containsStatementStrict(edge_example.closure)) { + closure = edge_example.closure; + } + + StatEdge newedge = new StatEdge(edge_example.getType(), stat, edge_example.getDestination(), closure); + stat.addSuccessor(newedge); + + for (StatEdge edge : lstEdges) { + edge.explicit = false; + } + + mapEdges.put(newedge.getDestination(), new ArrayList<StatEdge>(Arrays.asList(new StatEdge[]{newedge}))); + } + } + } + else { + + boolean implfound = false; + + for (Entry<Statement, List<StatEdge>> entr : mapEdges.entrySet()) { + if (entr.getKey() == next) { + for (StatEdge edge : entr.getValue()) { + edge.explicit = false; + } + implfound = true; + break; + } + } + + if (stat.getAllSuccessorEdges().isEmpty() && !implfound) { + List<StatEdge> lstEdges = null; + for (Entry<Statement, List<StatEdge>> entr : mapEdges.entrySet()) { + if (entr.getKey().type != Statement.TYPE_DUMMYEXIT && + (lstEdges == null || entr.getValue().size() > lstEdges.size())) { + lstEdges = entr.getValue(); + } + } + + if (lstEdges != null && lstEdges.size() > 1) { + StatEdge edge_example = lstEdges.get(0); + + Statement closure = stat.getParent(); + if (!closure.containsStatementStrict(edge_example.closure)) { + closure = edge_example.closure; + } + + StatEdge newedge = new StatEdge(edge_example.getType(), stat, edge_example.getDestination(), closure); + stat.addSuccessor(newedge); + + for (StatEdge edge : lstEdges) { + edge.explicit = false; + } + } + } + + mapEdges.clear(); + } + + if (statedge != null) { + mapEdges.put(statedge.getDestination(), new ArrayList<StatEdge>(Arrays.asList(new StatEdge[]{statedge}))); + } + } + + private static void hideDefaultSwitchEdges(Statement stat) { + + if (stat.type == Statement.TYPE_SWITCH) { + SwitchStatement swst = (SwitchStatement)stat; + + int last = swst.getCaseStatements().size() - 1; + if (last >= 0) { // empty switch possible + Statement stlast = swst.getCaseStatements().get(last); + + if (stlast.getExprents() != null && stlast.getExprents().isEmpty()) { + if (!stlast.getAllSuccessorEdges().get(0).explicit) { + List<StatEdge> lstEdges = swst.getCaseEdges().get(last); + lstEdges.remove(swst.getDefault_edge()); + + if (lstEdges.isEmpty()) { + swst.getCaseStatements().remove(last); + swst.getCaseEdges().remove(last); + } + } + } + } + } + + for (Statement st : stat.getStats()) { + hideDefaultSwitchEdges(st); + } + } + + private static void processStatementLabel(Statement stat) { + processStatementLabel(stat, new HashSet<Statement>(), new HashSet<Statement>()); + } + + private static void processStatementLabel(Statement stat, Set<Statement> setBreak, Set<Statement> setContinue) { + if (stat.getExprents() == null) { + for (Statement st : stat.getStats()) { + processStatementLabel(st, setBreak, setContinue); + } + + boolean shieldtype = (stat.type == Statement.TYPE_DO || stat.type == Statement.TYPE_SWITCH); + + for (StatEdge edge : stat.getLabelEdges()) { + if (edge.explicit) { + if (shieldtype && ((edge.getType() == StatEdge.TYPE_BREAK && setBreak.contains(edge.getSource())) || + (edge.getType() == StatEdge.TYPE_CONTINUE && setContinue.contains(edge.getSource())))) { + edge.labeled = false; + } + } + } + + switch (stat.type) { + case Statement.TYPE_DO: + setContinue.clear(); + case Statement.TYPE_SWITCH: + setBreak.clear(); + } + } + + setBreak.add(stat); + setContinue.add(stat); + } + + public static void replaceContinueWithBreak(Statement stat) { + + if (stat.type == Statement.TYPE_DO) { + + List<StatEdge> lst = stat.getPredecessorEdges(StatEdge.TYPE_CONTINUE); + + for (StatEdge edge : lst) { + + if (edge.explicit) { + Statement minclosure = getMinContinueClosure(edge); + + if (minclosure != edge.closure && + !InlineSingleBlockHelper.isBreakEdgeLabeled(edge.getSource(), minclosure)) { + edge.getSource().changeEdgeType(Statement.DIRECTION_FORWARD, edge, StatEdge.TYPE_BREAK); + edge.labeled = false; + minclosure.addLabeledEdge(edge); + } + } + } + } + + for (Statement st : stat.getStats()) { + replaceContinueWithBreak(st); + } + } + + private static Statement getMinContinueClosure(StatEdge edge) { + + Statement closure = edge.closure; + while (true) { + + boolean found = false; + + for (Statement st : closure.getStats()) { + if (st.containsStatementStrict(edge.getSource())) { + if (MergeHelper.isDirectPath(st, edge.getDestination())) { + closure = st; + found = true; + break; + } + } + } + + if (!found) { + break; + } + } + + return closure; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LoopExtractHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LoopExtractHelper.java new file mode 100644 index 000000000000..d5c9e8f20aee --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LoopExtractHelper.java @@ -0,0 +1,206 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.stats.DoStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.IfStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.SequenceStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Set; + + +public class LoopExtractHelper { + + + public static boolean extractLoops(Statement root) { + + boolean res = (extractLoopsRec(root) != 0); + + if (res) { + SequenceHelper.condenseSequences(root); + } + + return res; + } + + + private static int extractLoopsRec(Statement stat) { + + boolean res = false; + + while (true) { + + boolean updated = false; + + for (Statement st : stat.getStats()) { + int extr = extractLoopsRec(st); + res |= (extr != 0); + + if (extr == 2) { + updated = true; + break; + } + } + + if (!updated) { + break; + } + } + + if (stat.type == Statement.TYPE_DO) { + if (extractLoop((DoStatement)stat)) { + return 2; + } + } + + return res ? 1 : 0; + } + + + private static boolean extractLoop(DoStatement stat) { + + if (stat.getLooptype() != DoStatement.LOOP_DO) { + return false; + } + + for (StatEdge edge : stat.getLabelEdges()) { + if (edge.getType() != StatEdge.TYPE_CONTINUE && edge.getDestination().type != Statement.TYPE_DUMMYEXIT) { + return false; + } + } + + if (!extractLastIf(stat)) { + return extractFirstIf(stat); + } + else { + return true; + } + } + + private static boolean extractLastIf(DoStatement stat) { + + // search for an if condition at the end of the loop + Statement last = stat.getFirst(); + while (last.type == Statement.TYPE_SEQUENCE) { + last = last.getStats().getLast(); + } + + if (last.type == Statement.TYPE_IF) { + IfStatement lastif = (IfStatement)last; + if (lastif.iftype == IfStatement.IFTYPE_IF && lastif.getIfstat() != null) { + Statement ifstat = lastif.getIfstat(); + StatEdge elseedge = lastif.getAllSuccessorEdges().get(0); + + if (elseedge.getType() == StatEdge.TYPE_CONTINUE && elseedge.closure == stat) { + + Set<Statement> set = stat.getNeighboursSet(StatEdge.TYPE_CONTINUE, Statement.DIRECTION_BACKWARD); + set.remove(last); + + if (set.isEmpty()) { // no direct continues in a do{}while loop + if (isExternStatement(stat, ifstat, ifstat)) { + extractIfBlock(stat, lastif); + return true; + } + } + } + } + } + return false; + } + + private static boolean extractFirstIf(DoStatement stat) { + + // search for an if condition at the entrance of the loop + Statement first = stat.getFirst(); + while (first.type == Statement.TYPE_SEQUENCE) { + first = first.getFirst(); + } + + // found an if statement + if (first.type == Statement.TYPE_IF) { + IfStatement firstif = (IfStatement)first; + + if (firstif.getFirst().getExprents().isEmpty()) { + + if (firstif.iftype == IfStatement.IFTYPE_IF && firstif.getIfstat() != null) { + Statement ifstat = firstif.getIfstat(); + + if (isExternStatement(stat, ifstat, ifstat)) { + extractIfBlock(stat, firstif); + return true; + } + } + } + } + return false; + } + + + private static boolean isExternStatement(DoStatement loop, Statement block, Statement stat) { + + for (StatEdge edge : stat.getAllSuccessorEdges()) { + if (loop.containsStatement(edge.getDestination()) && + !block.containsStatement(edge.getDestination())) { + return false; + } + } + + for (Statement st : stat.getStats()) { + if (!isExternStatement(loop, block, st)) { + return false; + } + } + + return true; + } + + + private static void extractIfBlock(DoStatement loop, IfStatement ifstat) { + + Statement target = ifstat.getIfstat(); + StatEdge ifedge = ifstat.getIfEdge(); + + ifstat.setIfstat(null); + ifedge.getSource().changeEdgeType(Statement.DIRECTION_FORWARD, ifedge, StatEdge.TYPE_BREAK); + ifedge.closure = loop; + ifstat.getStats().removeWithKey(target.id); + + loop.addLabeledEdge(ifedge); + + SequenceStatement block = new SequenceStatement(Arrays.asList(loop, target)); + loop.getParent().replaceStatement(loop, block); + block.setAllParent(); + + loop.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, loop, target)); + + for (StatEdge edge : new ArrayList<StatEdge>(block.getLabelEdges())) { + if (edge.getType() == StatEdge.TYPE_CONTINUE || edge == ifedge) { + loop.addLabeledEdge(edge); + } + } + + for (StatEdge edge : block.getPredecessorEdges(StatEdge.TYPE_CONTINUE)) { + if (loop.containsStatementStrict(edge.getSource())) { + block.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, loop); + loop.addPredecessor(edge); + } + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LowBreakHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LowBreakHelper.java new file mode 100644 index 000000000000..67e9248d0f83 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/LowBreakHelper.java @@ -0,0 +1,208 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.stats.IfStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.SynchronizedStatement; + +import java.util.List; + +public class LowBreakHelper { + + public static void lowBreakLabels(Statement root) { + + lowBreakLabelsRec(root); + + liftBreakLabels(root); + } + + private static void lowBreakLabelsRec(Statement stat) { + + while (true) { + + boolean found = false; + + for (StatEdge edge : stat.getLabelEdges()) { + if (edge.getType() == StatEdge.TYPE_BREAK) { + Statement minclosure = getMinClosure(stat, edge.getSource()); + if (minclosure != stat) { + minclosure.addLabeledEdge(edge); + edge.labeled = isBreakEdgeLabeled(edge.getSource(), minclosure); + found = true; + break; + } + } + } + + if (!found) { + break; + } + } + + for (Statement st : stat.getStats()) { + lowBreakLabelsRec(st); + } + } + + public static boolean isBreakEdgeLabeled(Statement source, Statement closure) { + + if (closure.type == Statement.TYPE_DO || closure.type == Statement.TYPE_SWITCH) { + + Statement parent = source.getParent(); + + if (parent == closure) { + return false; + } + else { + return isBreakEdgeLabeled(parent, closure) || + (parent.type == Statement.TYPE_DO || parent.type == Statement.TYPE_SWITCH); + } + } + else { + return true; + } + } + + public static Statement getMinClosure(Statement closure, Statement source) { + + while (true) { + + Statement newclosure = null; + + switch (closure.type) { + case Statement.TYPE_SEQUENCE: + Statement last = closure.getStats().getLast(); + + if (isOkClosure(closure, source, last)) { + newclosure = last; + } + break; + case Statement.TYPE_IF: + IfStatement ifclosure = (IfStatement)closure; + if (isOkClosure(closure, source, ifclosure.getIfstat())) { + newclosure = ifclosure.getIfstat(); + } + else if (isOkClosure(closure, source, ifclosure.getElsestat())) { + newclosure = ifclosure.getElsestat(); + } + break; + case Statement.TYPE_TRYCATCH: + for (Statement st : closure.getStats()) { + if (isOkClosure(closure, source, st)) { + newclosure = st; + break; + } + } + break; + case Statement.TYPE_SYNCRONIZED: + Statement body = ((SynchronizedStatement)closure).getBody(); + + if (isOkClosure(closure, source, body)) { + newclosure = body; + } + } + + if (newclosure == null) { + break; + } + + closure = newclosure; + } + + return closure; + } + + private static boolean isOkClosure(Statement closure, Statement source, Statement stat) { + + boolean ok = false; + + if (stat != null && stat.containsStatementStrict(source)) { + + List<StatEdge> lst = stat.getAllSuccessorEdges(); + + ok = lst.isEmpty(); + if (!ok) { + StatEdge edge = lst.get(0); + ok = (edge.closure == closure && edge.getType() == StatEdge.TYPE_BREAK); + } + } + + return ok; + } + + + private static void liftBreakLabels(Statement stat) { + + for (Statement st : stat.getStats()) { + liftBreakLabels(st); + } + + + while (true) { + + boolean found = false; + + for (StatEdge edge : stat.getLabelEdges()) { + if (edge.explicit && edge.labeled && edge.getType() == StatEdge.TYPE_BREAK) { + + Statement newclosure = getMaxBreakLift(stat, edge); + + if (newclosure != null) { + newclosure.addLabeledEdge(edge); + edge.labeled = isBreakEdgeLabeled(edge.getSource(), newclosure); + + found = true; + break; + } + } + } + + if (!found) { + break; + } + } + } + + private static Statement getMaxBreakLift(Statement stat, StatEdge edge) { + + Statement closure = null; + Statement newclosure = stat; + + while ((newclosure = getNextBreakLift(newclosure, edge)) != null) { + closure = newclosure; + } + + return closure; + } + + private static Statement getNextBreakLift(Statement stat, StatEdge edge) { + + Statement closure = stat.getParent(); + + while (closure != null && !closure.containsStatementStrict(edge.getDestination())) { + + boolean labeled = isBreakEdgeLabeled(edge.getSource(), closure); + if (closure.isLabeled() || !labeled) { + return closure; + } + + closure = closure.getParent(); + } + + return null; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/MergeHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/MergeHelper.java new file mode 100644 index 000000000000..71d3d7991287 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/MergeHelper.java @@ -0,0 +1,421 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.IfExprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class MergeHelper { + + public static void enhanceLoops(Statement root) { + + while (enhanceLoopsRec(root)) ; + + SequenceHelper.condenseSequences(root); + } + + private static boolean enhanceLoopsRec(Statement stat) { + + boolean res = false; + + for (Statement st : stat.getStats()) { + if (st.getExprents() == null) { + res |= enhanceLoopsRec(st); + } + } + + if (stat.type == Statement.TYPE_DO) { + res |= enhanceLoop((DoStatement)stat); + } + + return res; + } + + private static boolean enhanceLoop(DoStatement stat) { + + int oldloop = stat.getLooptype(); + + switch (oldloop) { + case DoStatement.LOOP_DO: + + // identify a while loop + if (matchWhile(stat)) { + // identify a for loop - subtype of while + matchFor(stat); + } + else { + // identify a do{}while loop + matchDoWhile(stat); + } + + break; + case DoStatement.LOOP_WHILE: + matchFor(stat); + } + + return (stat.getLooptype() != oldloop); + } + + private static boolean matchDoWhile(DoStatement stat) { + + // search for an if condition at the end of the loop + Statement last = stat.getFirst(); + while (last.type == Statement.TYPE_SEQUENCE) { + last = last.getStats().getLast(); + } + + if (last.type == Statement.TYPE_IF) { + IfStatement lastif = (IfStatement)last; + if (lastif.iftype == IfStatement.IFTYPE_IF && lastif.getIfstat() == null) { + StatEdge ifedge = lastif.getIfEdge(); + StatEdge elseedge = lastif.getAllSuccessorEdges().get(0); + + if ((ifedge.getType() == StatEdge.TYPE_BREAK && elseedge.getType() == StatEdge.TYPE_CONTINUE && elseedge.closure == stat + && isDirectPath(stat, ifedge.getDestination())) || + (ifedge.getType() == StatEdge.TYPE_CONTINUE && elseedge.getType() == StatEdge.TYPE_BREAK && ifedge.closure == stat + && isDirectPath(stat, elseedge.getDestination()))) { + + Set<Statement> set = stat.getNeighboursSet(StatEdge.TYPE_CONTINUE, Statement.DIRECTION_BACKWARD); + set.remove(last); + + if (!set.isEmpty()) { + return false; + } + + + stat.setLooptype(DoStatement.LOOP_DOWHILE); + + IfExprent ifexpr = (IfExprent)lastif.getHeadexprent().copy(); + if (ifedge.getType() == StatEdge.TYPE_BREAK) { + ifexpr.negateIf(); + } + stat.setConditionExprent(ifexpr.getCondition()); + lastif.getFirst().removeSuccessor(ifedge); + lastif.removeSuccessor(elseedge); + + // remove empty if + if (lastif.getFirst().getExprents().isEmpty()) { + removeLastEmptyStatement(stat, lastif); + } + else { + lastif.setExprents(lastif.getFirst().getExprents()); + + StatEdge newedge = new StatEdge(StatEdge.TYPE_CONTINUE, lastif, stat); + lastif.addSuccessor(newedge); + stat.addLabeledEdge(newedge); + } + + if (stat.getAllSuccessorEdges().isEmpty()) { + StatEdge edge = elseedge.getType() == StatEdge.TYPE_CONTINUE ? ifedge : elseedge; + + edge.setSource(stat); + if (edge.closure == stat) { + edge.closure = stat.getParent(); + } + stat.addSuccessor(edge); + } + + return true; + } + } + } + return false; + } + + private static boolean matchWhile(DoStatement stat) { + + // search for an if condition at the entrance of the loop + Statement first = stat.getFirst(); + while (first.type == Statement.TYPE_SEQUENCE) { + first = first.getFirst(); + } + + // found an if statement + if (first.type == Statement.TYPE_IF) { + IfStatement firstif = (IfStatement)first; + + if (firstif.getFirst().getExprents().isEmpty()) { + + if (firstif.iftype == IfStatement.IFTYPE_IF) { + if (firstif.getIfstat() == null) { + StatEdge ifedge = firstif.getIfEdge(); + if (isDirectPath(stat, ifedge.getDestination())) { + // exit condition identified + stat.setLooptype(DoStatement.LOOP_WHILE); + + // negate condition (while header) + IfExprent ifexpr = (IfExprent)firstif.getHeadexprent().copy(); + ifexpr.negateIf(); + stat.setConditionExprent(ifexpr.getCondition()); + + // remove edges + firstif.getFirst().removeSuccessor(ifedge); + firstif.removeSuccessor(firstif.getAllSuccessorEdges().get(0)); + + if (stat.getAllSuccessorEdges().isEmpty()) { + ifedge.setSource(stat); + if (ifedge.closure == stat) { + ifedge.closure = stat.getParent(); + } + stat.addSuccessor(ifedge); + } + + // remove empty if statement as it is now part of the loop + if (firstif == stat.getFirst()) { + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + bstat.setExprents(new ArrayList<Exprent>()); + stat.replaceStatement(firstif, bstat); + } + else { + // precondition: sequence must contain more than one statement! + Statement sequence = firstif.getParent(); + sequence.getStats().removeWithKey(firstif.id); + sequence.setFirst(sequence.getStats().get(0)); + } + + return true; + } + } + else { + StatEdge elseedge = firstif.getAllSuccessorEdges().get(0); + if (isDirectPath(stat, elseedge.getDestination())) { + // exit condition identified + stat.setLooptype(DoStatement.LOOP_WHILE); + + // no need to negate the while condition + stat.setConditionExprent(((IfExprent)firstif.getHeadexprent().copy()).getCondition()); + + // remove edges + StatEdge ifedge = firstif.getIfEdge(); + firstif.getFirst().removeSuccessor(ifedge); + firstif.removeSuccessor(elseedge); + + if (stat.getAllSuccessorEdges().isEmpty()) { + + elseedge.setSource(stat); + if (elseedge.closure == stat) { + elseedge.closure = stat.getParent(); + } + stat.addSuccessor(elseedge); + } + + if (firstif.getIfstat() == null) { + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + bstat.setExprents(new ArrayList<Exprent>()); + + ifedge.setSource(bstat); + bstat.addSuccessor(ifedge); + + stat.replaceStatement(firstif, bstat); + } + else { + // replace the if statement with its content + first.getParent().replaceStatement(first, firstif.getIfstat()); + + // lift closures + for (StatEdge prededge : elseedge.getDestination().getPredecessorEdges(StatEdge.TYPE_BREAK)) { + if (stat.containsStatementStrict(prededge.closure)) { + stat.addLabeledEdge(prededge); + } + } + + LabelHelper.lowClosures(stat); + } + + return true; + } + } + } + } + } + return false; + } + + public static boolean isDirectPath(Statement stat, Statement endstat) { + + Set<Statement> setStat = stat.getNeighboursSet(Statement.STATEDGE_DIRECT_ALL, Statement.DIRECTION_FORWARD); + if (setStat.isEmpty()) { + Statement parent = stat.getParent(); + if (parent == null) { + return false; + } + else { + switch (parent.type) { + case Statement.TYPE_ROOT: + return endstat.type == Statement.TYPE_DUMMYEXIT; + case Statement.TYPE_DO: + return (endstat == parent); + case Statement.TYPE_SWITCH: + SwitchStatement swst = (SwitchStatement)parent; + for (int i = 0; i < swst.getCaseStatements().size() - 1; i++) { + Statement stt = swst.getCaseStatements().get(i); + if (stt == stat) { + Statement stnext = swst.getCaseStatements().get(i + 1); + + if (stnext.getExprents() != null && stnext.getExprents().isEmpty()) { + stnext = stnext.getAllSuccessorEdges().get(0).getDestination(); + } + return (endstat == stnext); + } + } + default: + return isDirectPath(parent, endstat); + } + } + } + else { + return setStat.contains(endstat); + } + } + + private static boolean matchFor(DoStatement stat) { + + Exprent lastDoExprent = null, initDoExprent = null; + Statement lastData = null, preData = null; + + // get last exprent + lastData = getLastDirectData(stat.getFirst()); + if (lastData == null || lastData.getExprents().isEmpty()) { + return false; + } + + List<Exprent> lstExpr = lastData.getExprents(); + lastDoExprent = lstExpr.get(lstExpr.size() - 1); + + boolean issingle = false; + if (lstExpr.size() == 1) { // single exprent + if (lastData.getAllPredecessorEdges().size() > 1) { // break edges + issingle = true; + } + } + + boolean haslast = issingle || (lastDoExprent.type == Exprent.EXPRENT_ASSIGNMENT || + lastDoExprent.type == Exprent.EXPRENT_FUNCTION); + + if (!haslast) { + return false; + } + + boolean hasinit = false; + + // search for an initializing exprent + Statement current = stat; + while (true) { + Statement parent = current.getParent(); + if (parent == null) { + break; + } + + if (parent.type == Statement.TYPE_SEQUENCE) { + if (current == parent.getFirst()) { + current = parent; + } + else { + preData = current.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD).get(0); + preData = getLastDirectData(preData); + if (preData != null && !preData.getExprents().isEmpty()) { + initDoExprent = preData.getExprents().get(preData.getExprents().size() - 1); + if (initDoExprent.type == Exprent.EXPRENT_ASSIGNMENT) { + hasinit = true; + } + } + break; + } + } + else { + break; + } + } + + if ((hasinit && haslast) || issingle) { // FIXME: issingle sufficient? + + Set<Statement> set = stat.getNeighboursSet(StatEdge.TYPE_CONTINUE, Statement.DIRECTION_BACKWARD); + set.remove(lastData); + + if (!set.isEmpty()) { + return false; + } + + stat.setLooptype(DoStatement.LOOP_FOR); + if (hasinit) { + stat.setInitExprent(preData.getExprents().remove(preData.getExprents().size() - 1)); + } + stat.setIncExprent(lastData.getExprents().remove(lastData.getExprents().size() - 1)); + } + + if (lastData.getExprents().isEmpty()) { + List<StatEdge> lst = lastData.getAllSuccessorEdges(); + if (!lst.isEmpty()) { + lastData.removeSuccessor(lst.get(0)); + } + removeLastEmptyStatement(stat, lastData); + } + + return true; + } + + private static void removeLastEmptyStatement(DoStatement dostat, Statement stat) { + + if (stat == dostat.getFirst()) { + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + bstat.setExprents(new ArrayList<Exprent>()); + dostat.replaceStatement(stat, bstat); + } + else { + for (StatEdge edge : stat.getAllPredecessorEdges()) { + edge.getSource().changeEdgeType(Statement.DIRECTION_FORWARD, edge, StatEdge.TYPE_CONTINUE); + + stat.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, dostat); + dostat.addPredecessor(edge); + + dostat.addLabeledEdge(edge); + } + + // parent is a sequence statement + stat.getParent().getStats().removeWithKey(stat.id); + } + } + + private static Statement getLastDirectData(Statement stat) { + + if (stat.getExprents() != null) { + return stat; + } + + switch (stat.type) { + case Statement.TYPE_SEQUENCE: + for (int i = stat.getStats().size() - 1; i >= 0; i--) { + Statement tmp = getLastDirectData(stat.getStats().get(i)); + if (tmp == null || !tmp.getExprents().isEmpty()) { + return tmp; + } + } + } + return null; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/PPandMMHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/PPandMMHelper.java new file mode 100644 index 000000000000..aacb61f339ab --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/PPandMMHelper.java @@ -0,0 +1,154 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.AssignmentExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.ConstExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.FunctionExprent; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectNode; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +public class PPandMMHelper { + + private boolean exprentReplaced; + + public boolean findPPandMM(RootStatement root) { + + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + DirectGraph dgraph = flatthelper.buildDirectGraph(root); + + LinkedList<DirectNode> stack = new LinkedList<DirectNode>(); + stack.add(dgraph.first); + + HashSet<DirectNode> setVisited = new HashSet<DirectNode>(); + + boolean res = false; + + while (!stack.isEmpty()) { + + DirectNode node = stack.removeFirst(); + + if (setVisited.contains(node)) { + continue; + } + setVisited.add(node); + + res |= processExprentList(node.exprents); + + stack.addAll(node.succs); + } + + return res; + } + + private boolean processExprentList(List<Exprent> lst) { + + boolean result = false; + + for (int i = 0; i < lst.size(); i++) { + Exprent exprent = lst.get(i); + exprentReplaced = false; + + Exprent retexpr = processExprentRecursive(exprent); + if (retexpr != null) { + lst.set(i, retexpr); + + result = true; + i--; // process the same exprent again + } + + result |= exprentReplaced; + } + + return result; + } + + private Exprent processExprentRecursive(Exprent exprent) { + + boolean replaced = true; + while (replaced) { + replaced = false; + + for (Exprent expr : exprent.getAllExprents()) { + Exprent retexpr = processExprentRecursive(expr); + if (retexpr != null) { + exprent.replaceExprent(expr, retexpr); + replaced = true; + exprentReplaced = true; + break; + } + } + } + + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent as = (AssignmentExprent)exprent; + + if (as.getRight().type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent func = (FunctionExprent)as.getRight(); + + VarType midlayer = null; + if (func.getFunctype() >= FunctionExprent.FUNCTION_I2L && + func.getFunctype() <= FunctionExprent.FUNCTION_I2S) { + midlayer = func.getSimpleCastType(); + if (func.getLstOperands().get(0).type == Exprent.EXPRENT_FUNCTION) { + func = (FunctionExprent)func.getLstOperands().get(0); + } + else { + return null; + } + } + + if (func.getFunctype() == FunctionExprent.FUNCTION_ADD || + func.getFunctype() == FunctionExprent.FUNCTION_SUB) { + Exprent econd = func.getLstOperands().get(0); + Exprent econst = func.getLstOperands().get(1); + + if (econst.type != Exprent.EXPRENT_CONST && econd.type == Exprent.EXPRENT_CONST && + func.getFunctype() == FunctionExprent.FUNCTION_ADD) { + econd = econst; + econst = func.getLstOperands().get(0); + } + + if (econst.type == Exprent.EXPRENT_CONST && ((ConstExprent)econst).hasValueOne()) { + Exprent left = as.getLeft(); + + VarType condtype = econd.getExprType(); + if (left.equals(econd) && (midlayer == null || midlayer.equals(condtype))) { + FunctionExprent ret = new FunctionExprent( + func.getFunctype() == FunctionExprent.FUNCTION_ADD ? FunctionExprent.FUNCTION_PPI : FunctionExprent.FUNCTION_MMI, + Arrays.asList(new Exprent[]{econd})); + ret.setImplicitType(condtype); + + exprentReplaced = true; + return ret; + } + } + } + } + } + + return null; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/PrimitiveExprsList.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/PrimitiveExprsList.java new file mode 100644 index 000000000000..6dbc887e348b --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/PrimitiveExprsList.java @@ -0,0 +1,49 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; + +import java.util.ArrayList; +import java.util.List; + +public class PrimitiveExprsList { + + private List<Exprent> lstExprents = new ArrayList<Exprent>(); + + private ExprentStack stack = new ExprentStack(); + + public PrimitiveExprsList() { + } + + public PrimitiveExprsList copyStack() { + PrimitiveExprsList prlst = new PrimitiveExprsList(); + prlst.setStack(stack.clone()); + return prlst; + } + + public List<Exprent> getLstExprents() { + return lstExprents; + } + + public ExprentStack getStack() { + return stack; + } + + public void setStack(ExprentStack stack) { + this.stack = stack; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SecondaryFunctionsHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SecondaryFunctionsHelper.java new file mode 100644 index 000000000000..5643f228e024 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SecondaryFunctionsHelper.java @@ -0,0 +1,432 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.stats.IfStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class SecondaryFunctionsHelper { + + private static final int[] funcsnot = new int[]{ + FunctionExprent.FUNCTION_NE, + FunctionExprent.FUNCTION_EQ, + FunctionExprent.FUNCTION_GE, + FunctionExprent.FUNCTION_LT, + FunctionExprent.FUNCTION_LE, + FunctionExprent.FUNCTION_GT, + FunctionExprent.FUNCTION_COR, + FunctionExprent.FUNCTION_CADD + }; + + private static final HashMap<Integer, Integer[]> mapNumComparisons = new HashMap<Integer, Integer[]>(); + + static { + mapNumComparisons.put(FunctionExprent.FUNCTION_EQ, + new Integer[]{FunctionExprent.FUNCTION_LT, FunctionExprent.FUNCTION_EQ, FunctionExprent.FUNCTION_GT}); + mapNumComparisons.put(FunctionExprent.FUNCTION_NE, + new Integer[]{FunctionExprent.FUNCTION_GE, FunctionExprent.FUNCTION_NE, FunctionExprent.FUNCTION_LE}); + mapNumComparisons.put(FunctionExprent.FUNCTION_GT, new Integer[]{FunctionExprent.FUNCTION_GE, FunctionExprent.FUNCTION_GT, null}); + mapNumComparisons.put(FunctionExprent.FUNCTION_GE, new Integer[]{null, FunctionExprent.FUNCTION_GE, FunctionExprent.FUNCTION_GT}); + mapNumComparisons.put(FunctionExprent.FUNCTION_LT, new Integer[]{null, FunctionExprent.FUNCTION_LT, FunctionExprent.FUNCTION_LE}); + mapNumComparisons.put(FunctionExprent.FUNCTION_LE, new Integer[]{FunctionExprent.FUNCTION_LT, FunctionExprent.FUNCTION_LE, null}); + } + + + public static boolean identifySecondaryFunctions(Statement stat) { + + if (stat.getExprents() == null) { + // if(){;}else{...} -> if(!){...} + if (stat.type == Statement.TYPE_IF) { + IfStatement ifelsestat = (IfStatement)stat; + Statement ifstat = ifelsestat.getIfstat(); + + if (ifelsestat.iftype == IfStatement.IFTYPE_IFELSE && ifstat.getExprents() != null && + ifstat.getExprents().isEmpty() && (ifstat.getAllSuccessorEdges().isEmpty() || !ifstat.getAllSuccessorEdges().get(0).explicit)) { + + // move else to the if position + ifelsestat.getStats().removeWithKey(ifstat.id); + + ifelsestat.iftype = IfStatement.IFTYPE_IF; + ifelsestat.setIfstat(ifelsestat.getElsestat()); + ifelsestat.setElsestat(null); + + if (ifelsestat.getAllSuccessorEdges().isEmpty() && !ifstat.getAllSuccessorEdges().isEmpty()) { + StatEdge endedge = ifstat.getAllSuccessorEdges().get(0); + + ifstat.removeSuccessor(endedge); + endedge.setSource(ifelsestat); + if (endedge.closure != null) { + ifelsestat.getParent().addLabeledEdge(endedge); + } + ifelsestat.addSuccessor(endedge); + } + + ifelsestat.getFirst().removeSuccessor(ifelsestat.getIfEdge()); + + ifelsestat.setIfEdge(ifelsestat.getElseEdge()); + ifelsestat.setElseEdge(null); + + // negate head expression + ifelsestat.setNegated(!ifelsestat.isNegated()); + ifelsestat.getHeadexprentList().set(0, ((IfExprent)ifelsestat.getHeadexprent().copy()).negateIf()); + + return true; + } + } + } + + + boolean replaced = true; + while (replaced) { + replaced = false; + + List<Object> lstObjects = new ArrayList<Object>(stat.getExprents() == null ? stat.getSequentialObjects() : stat.getExprents()); + + for (int i = 0; i < lstObjects.size(); i++) { + Object obj = lstObjects.get(i); + + if (obj instanceof Statement) { + if (identifySecondaryFunctions((Statement)obj)) { + replaced = true; + break; + } + } + else if (obj instanceof Exprent) { + Exprent retexpr = identifySecondaryFunctions((Exprent)obj, true); + if (retexpr != null) { + if (stat.getExprents() == null) { + // only head expressions can be replaced! + stat.replaceExprent((Exprent)obj, retexpr); + } + else { + stat.getExprents().set(i, retexpr); + } + replaced = true; + break; + } + } + } + } + + return false; + } + + + private static Exprent identifySecondaryFunctions(Exprent exprent, boolean statement_level) { + + if (exprent.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent fexpr = (FunctionExprent)exprent; + + switch (fexpr.getFunctype()) { + case FunctionExprent.FUNCTION_BOOLNOT: + + Exprent retparam = propagateBoolNot(fexpr); + + if (retparam != null) { + return retparam; + } + + break; + case FunctionExprent.FUNCTION_EQ: + case FunctionExprent.FUNCTION_NE: + case FunctionExprent.FUNCTION_GT: + case FunctionExprent.FUNCTION_GE: + case FunctionExprent.FUNCTION_LT: + case FunctionExprent.FUNCTION_LE: + Exprent expr1 = fexpr.getLstOperands().get(0); + Exprent expr2 = fexpr.getLstOperands().get(1); + + if (expr1.type == Exprent.EXPRENT_CONST) { + expr2 = expr1; + expr1 = fexpr.getLstOperands().get(1); + } + + if (expr1.type == Exprent.EXPRENT_FUNCTION && expr2.type == Exprent.EXPRENT_CONST) { + FunctionExprent funcexpr = (FunctionExprent)expr1; + ConstExprent cexpr = (ConstExprent)expr2; + + int functype = funcexpr.getFunctype(); + if (functype == FunctionExprent.FUNCTION_LCMP || functype == FunctionExprent.FUNCTION_FCMPG || + functype == FunctionExprent.FUNCTION_FCMPL || functype == FunctionExprent.FUNCTION_DCMPG || + functype == FunctionExprent.FUNCTION_DCMPL) { + + int desttype = -1; + + Integer[] destcons = mapNumComparisons.get(fexpr.getFunctype()); + if (destcons != null) { + int index = cexpr.getIntValue() + 1; + if (index >= 0 && index <= 2) { + Integer destcon = destcons[index]; + if (destcon != null) { + desttype = destcon.intValue(); + } + } + } + + if (desttype >= 0) { + return new FunctionExprent(desttype, funcexpr.getLstOperands()); + } + } + } + } + } + + + boolean replaced = true; + while (replaced) { + replaced = false; + + for (Exprent expr : exprent.getAllExprents()) { + Exprent retexpr = identifySecondaryFunctions(expr, false); + if (retexpr != null) { + exprent.replaceExprent(expr, retexpr); + replaced = true; + break; + } + } + } + + switch (exprent.type) { + case Exprent.EXPRENT_FUNCTION: + FunctionExprent fexpr = (FunctionExprent)exprent; + List<Exprent> lstOperands = fexpr.getLstOperands(); + + switch (fexpr.getFunctype()) { + case FunctionExprent.FUNCTION_XOR: + for (int i = 0; i < 2; i++) { + Exprent operand = lstOperands.get(i); + VarType operandtype = operand.getExprType(); + + if (operand.type == Exprent.EXPRENT_CONST && + operandtype.type != CodeConstants.TYPE_BOOLEAN) { + ConstExprent cexpr = (ConstExprent)operand; + long val; + if (operandtype.type == CodeConstants.TYPE_LONG) { + val = ((Long)cexpr.getValue()).longValue(); + } + else { + val = ((Integer)cexpr.getValue()).intValue(); + } + + if (val == -1) { + List<Exprent> lstBitNotOperand = new ArrayList<Exprent>(); + lstBitNotOperand.add(lstOperands.get(1 - i)); + return new FunctionExprent(FunctionExprent.FUNCTION_BITNOT, lstBitNotOperand); + } + } + } + break; + case FunctionExprent.FUNCTION_EQ: + case FunctionExprent.FUNCTION_NE: + if (lstOperands.get(0).getExprType().type == CodeConstants.TYPE_BOOLEAN && + lstOperands.get(1).getExprType().type == CodeConstants.TYPE_BOOLEAN) { + for (int i = 0; i < 2; i++) { + if (lstOperands.get(i).type == Exprent.EXPRENT_CONST) { + ConstExprent cexpr = (ConstExprent)lstOperands.get(i); + int val = ((Integer)cexpr.getValue()).intValue(); + + if ((fexpr.getFunctype() == FunctionExprent.FUNCTION_EQ && val == 1) || + (fexpr.getFunctype() == FunctionExprent.FUNCTION_NE && val == 0)) { + return lstOperands.get(1 - i); + } + else { + List<Exprent> lstNotOperand = new ArrayList<Exprent>(); + lstNotOperand.add(lstOperands.get(1 - i)); + return new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, lstNotOperand); + } + } + } + } + break; + case FunctionExprent.FUNCTION_BOOLNOT: + if (lstOperands.get(0).type == Exprent.EXPRENT_CONST) { + int val = ((ConstExprent)lstOperands.get(0)).getIntValue(); + if (val == 0) { + return new ConstExprent(VarType.VARTYPE_BOOLEAN, new Integer(1)); + } + else { + return new ConstExprent(VarType.VARTYPE_BOOLEAN, new Integer(0)); + } + } + break; + case FunctionExprent.FUNCTION_IIF: + Exprent expr1 = lstOperands.get(1); + Exprent expr2 = lstOperands.get(2); + + if (expr1.type == Exprent.EXPRENT_CONST && expr2.type == Exprent.EXPRENT_CONST) { + ConstExprent cexpr1 = (ConstExprent)expr1; + ConstExprent cexpr2 = (ConstExprent)expr2; + + if (cexpr1.getExprType().type == CodeConstants.TYPE_BOOLEAN && + cexpr2.getExprType().type == CodeConstants.TYPE_BOOLEAN) { + + if (cexpr1.getIntValue() == 0 && cexpr2.getIntValue() != 0) { + return new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, Arrays.asList(new Exprent[]{lstOperands.get(0)})); + } + else if (cexpr1.getIntValue() != 0 && cexpr2.getIntValue() == 0) { + return lstOperands.get(0); + } + } + } + break; + case FunctionExprent.FUNCTION_LCMP: + case FunctionExprent.FUNCTION_FCMPL: + case FunctionExprent.FUNCTION_FCMPG: + case FunctionExprent.FUNCTION_DCMPL: + case FunctionExprent.FUNCTION_DCMPG: + int var = DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER); + VarType type = lstOperands.get(0).getExprType(); + VarProcessor processor = (VarProcessor)DecompilerContext.getProperty(DecompilerContext.CURRENT_VAR_PROCESSOR); + + FunctionExprent iff = new FunctionExprent(FunctionExprent.FUNCTION_IIF, Arrays.asList(new Exprent[]{ + new FunctionExprent(FunctionExprent.FUNCTION_LT, Arrays.asList(new Exprent[]{new VarExprent(var, type, processor), + ConstExprent.getZeroConstant(type.type)})), + new ConstExprent(VarType.VARTYPE_INT, new Integer(-1)), + new ConstExprent(VarType.VARTYPE_INT, new Integer(1))})); + + FunctionExprent head = new FunctionExprent(FunctionExprent.FUNCTION_EQ, Arrays.asList(new Exprent[]{ + new AssignmentExprent(new VarExprent(var, type, processor), new FunctionExprent(FunctionExprent.FUNCTION_SUB, + Arrays.asList( + new Exprent[]{lstOperands.get(0), + lstOperands.get(1)}))), + ConstExprent.getZeroConstant(type.type)})); + + processor.setVarType(new VarVersionPaar(var, 0), type); + + return new FunctionExprent(FunctionExprent.FUNCTION_IIF, Arrays.asList(new Exprent[]{ + head, new ConstExprent(VarType.VARTYPE_INT, new Integer(0)), iff})); + } + break; + case Exprent.EXPRENT_ASSIGNMENT: // check for conditional assignment + AssignmentExprent asexpr = (AssignmentExprent)exprent; + Exprent right = asexpr.getRight(); + Exprent left = asexpr.getLeft(); + + if (right.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent func = (FunctionExprent)right; + + VarType midlayer = null; + if (func.getFunctype() >= FunctionExprent.FUNCTION_I2L && + func.getFunctype() <= FunctionExprent.FUNCTION_I2S) { + right = func.getLstOperands().get(0); + midlayer = func.getSimpleCastType(); + if (right.type == Exprent.EXPRENT_FUNCTION) { + func = (FunctionExprent)right; + } + else { + return null; + } + } + + List<Exprent> lstFuncOperands = func.getLstOperands(); + + Exprent cond = null; + + switch (func.getFunctype()) { + case FunctionExprent.FUNCTION_ADD: + case FunctionExprent.FUNCTION_AND: + case FunctionExprent.FUNCTION_OR: + case FunctionExprent.FUNCTION_XOR: + if (left.equals(lstFuncOperands.get(1))) { + cond = lstFuncOperands.get(0); + break; + } + case FunctionExprent.FUNCTION_SUB: + case FunctionExprent.FUNCTION_MUL: + case FunctionExprent.FUNCTION_DIV: + case FunctionExprent.FUNCTION_REM: + case FunctionExprent.FUNCTION_SHL: + case FunctionExprent.FUNCTION_SHR: + case FunctionExprent.FUNCTION_USHR: + if (left.equals(lstFuncOperands.get(0))) { + cond = lstFuncOperands.get(1); + } + } + + if (cond != null && (midlayer == null || midlayer.equals(cond.getExprType()))) { + asexpr.setRight(cond); + asexpr.setCondtype(func.getFunctype()); + } + } + break; + case Exprent.EXPRENT_INVOCATION: + if (!statement_level) { // simplify if exprent is a real expression. The opposite case is pretty absurd, can still happen however (and happened at least once). + Exprent retexpr = ConcatenationHelper.contractStringConcat(exprent); + if (!exprent.equals(retexpr)) { + return retexpr; + } + } + } + + return null; + } + + public static Exprent propagateBoolNot(Exprent exprent) { + + if (exprent.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent fexpr = (FunctionExprent)exprent; + + if (fexpr.getFunctype() == FunctionExprent.FUNCTION_BOOLNOT) { + + Exprent param = fexpr.getLstOperands().get(0); + + if (param.type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent fparam = (FunctionExprent)param; + + int ftype = fparam.getFunctype(); + switch (ftype) { + case FunctionExprent.FUNCTION_BOOLNOT: + Exprent newexpr = fparam.getLstOperands().get(0); + Exprent retexpr = propagateBoolNot(newexpr); + return retexpr == null ? newexpr : retexpr; + case FunctionExprent.FUNCTION_CADD: + case FunctionExprent.FUNCTION_COR: + List<Exprent> operands = fparam.getLstOperands(); + for (int i = 0; i < operands.size(); i++) { + Exprent newparam = new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, + Arrays.asList(new Exprent[]{operands.get(i)})); + + Exprent retparam = propagateBoolNot(newparam); + operands.set(i, retparam == null ? newparam : retparam); + } + case FunctionExprent.FUNCTION_EQ: + case FunctionExprent.FUNCTION_NE: + case FunctionExprent.FUNCTION_LT: + case FunctionExprent.FUNCTION_GE: + case FunctionExprent.FUNCTION_GT: + case FunctionExprent.FUNCTION_LE: + fparam.setFunctype(funcsnot[ftype - FunctionExprent.FUNCTION_EQ]); + return fparam; + } + } + } + } + + return null; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SequenceHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SequenceHelper.java new file mode 100644 index 000000000000..063d201f81f0 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SequenceHelper.java @@ -0,0 +1,327 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.BasicBlockStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.SequenceStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + + +public class SequenceHelper { + + + public static void condenseSequences(Statement root) { + condenseSequencesRec(root); + } + + private static void condenseSequencesRec(Statement stat) { + + if (stat.type == Statement.TYPE_SEQUENCE) { + + List<Statement> lst = new ArrayList<Statement>(); + lst.addAll(stat.getStats()); + + boolean unfolded = false; + + // unfold blocks + for (int i = 0; i < lst.size(); i++) { + Statement st = lst.get(i); + if (st.type == Statement.TYPE_SEQUENCE) { + + removeEmptyStatements((SequenceStatement)st); + + if (i == lst.size() - 1 || isSequenceDisbandable(st, lst.get(i + 1))) { + // move predecessors + Statement first = st.getFirst(); + for (StatEdge edge : st.getAllPredecessorEdges()) { + st.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, first); + first.addPredecessor(edge); + } + + // move successors + Statement last = st.getStats().getLast(); + if (last.getAllSuccessorEdges().isEmpty() && i < lst.size() - 1) { + last.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, last, lst.get(i + 1))); + } + else { + for (StatEdge edge : last.getAllSuccessorEdges()) { + if (i == lst.size() - 1) { + if (edge.closure == st) { + stat.addLabeledEdge(edge); + } + } + else { + edge.getSource().changeEdgeType(Statement.DIRECTION_FORWARD, edge, StatEdge.TYPE_REGULAR); + edge.closure.getLabelEdges().remove(edge); + edge.closure = null; + } + } + } + + for (StatEdge edge : st.getAllSuccessorEdges()) { + st.removeSuccessor(edge); + } + + for (StatEdge edge : new HashSet<StatEdge>(st.getLabelEdges())) { + if (edge.getSource() != last) { + last.addLabeledEdge(edge); + } + } + + lst.remove(i); + lst.addAll(i, st.getStats()); + i--; + + unfolded = true; + } + } + } + + if (unfolded) { + SequenceStatement sequence = new SequenceStatement(lst); + sequence.setAllParent(); + + stat.getParent().replaceStatement(stat, sequence); + + stat = sequence; + } + } + + // sequence consisting of one statement -> disband + if (stat.type == Statement.TYPE_SEQUENCE) { + + removeEmptyStatements((SequenceStatement)stat); + + if (stat.getStats().size() == 1) { + + Statement st = stat.getFirst(); + + boolean ok = st.getAllSuccessorEdges().isEmpty(); + if (!ok) { + StatEdge edge = st.getAllSuccessorEdges().get(0); + + ok = stat.getAllSuccessorEdges().isEmpty(); + if (!ok) { + StatEdge statedge = stat.getAllSuccessorEdges().get(0); + ok = (edge.getDestination() == statedge.getDestination()); + + if (ok) { + st.removeSuccessor(edge); + } + } + } + + if (ok) { + stat.getParent().replaceStatement(stat, st); + stat = st; + } + } + } + + // replace flat statements with synthetic basic blocks + outer: + while (true) { + for (Statement st : stat.getStats()) { + if ((st.getStats().isEmpty() || st.getExprents() != null) && st.type != Statement.TYPE_BASICBLOCK) { + destroyAndFlattenStatement(st); + continue outer; + } + } + break; + } + + // recursion + for (int i = 0; i < stat.getStats().size(); i++) { + condenseSequencesRec(stat.getStats().get(i)); + } + } + + private static boolean isSequenceDisbandable(Statement block, Statement next) { + + Statement last = block.getStats().getLast(); + List<StatEdge> lstSuccs = last.getAllSuccessorEdges(); + if (!lstSuccs.isEmpty()) { + if (lstSuccs.get(0).getDestination() != next) { + return false; + } + } + + for (StatEdge edge : next.getPredecessorEdges(StatEdge.TYPE_BREAK)) { + if (last != edge.getSource() && !last.containsStatementStrict(edge.getSource())) { + return false; + } + } + + return true; + } + + private static void removeEmptyStatements(SequenceStatement sequence) { + + if (sequence.getStats().size() <= 1) { + return; + } + + mergeFlatStatements(sequence); + + while (true) { + + boolean found = false; + + for (Statement st : sequence.getStats()) { + + if (st.getExprents() != null && st.getExprents().isEmpty()) { + + if (st.getAllSuccessorEdges().isEmpty()) { + List<StatEdge> lstBreaks = st.getPredecessorEdges(StatEdge.TYPE_BREAK); + + if (lstBreaks.isEmpty()) { + for (StatEdge edge : st.getAllPredecessorEdges()) { + edge.getSource().removeSuccessor(edge); + } + found = true; + } + } + else { + StatEdge sucedge = st.getAllSuccessorEdges().get(0); + if (sucedge.getType() != StatEdge.TYPE_FINALLYEXIT) { + st.removeSuccessor(sucedge); + + for (StatEdge edge : st.getAllPredecessorEdges()) { + if (sucedge.getType() != StatEdge.TYPE_REGULAR) { + edge.getSource().changeEdgeType(Statement.DIRECTION_FORWARD, edge, sucedge.getType()); + } + + st.removePredecessor(edge); + edge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, edge, sucedge.getDestination()); + sucedge.getDestination().addPredecessor(edge); + + if (sucedge.closure != null) { + sucedge.closure.addLabeledEdge(edge); + } + } + found = true; + } + } + + if (found) { + sequence.getStats().removeWithKey(st.id); + break; + } + } + } + + if (!found) { + break; + } + } + + sequence.setFirst(sequence.getStats().get(0)); + } + + private static void mergeFlatStatements(SequenceStatement sequence) { + + while (true) { + + Statement next = null; + Statement current = null; + + boolean found = false; + + for (int i = sequence.getStats().size() - 1; i >= 0; i--) { + + next = current; + current = sequence.getStats().get(i); + + if (next != null && current.getExprents() != null && !current.getExprents().isEmpty()) { + if (next.getExprents() != null) { + next.getExprents().addAll(0, current.getExprents()); + current.getExprents().clear(); + found = true; + } + else { + Statement first = getFirstExprentlist(next); + if (first != null) { + first.getExprents().addAll(0, current.getExprents()); + current.getExprents().clear(); + found = true; + } + } + } + } + + if (!found) { + break; + } + } + } + + private static Statement getFirstExprentlist(Statement stat) { + + if (stat.getExprents() != null) { + return stat; + } + + switch (stat.type) { + case Statement.TYPE_IF: + case Statement.TYPE_SEQUENCE: + case Statement.TYPE_SWITCH: + case Statement.TYPE_SYNCRONIZED: + return getFirstExprentlist(stat.getFirst()); + } + + return null; + } + + + public static void destroyAndFlattenStatement(Statement stat) { + + destroyStatementContent(stat, false); + + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + if (stat.getExprents() == null) { + bstat.setExprents(new ArrayList<Exprent>()); + } + else { + bstat.setExprents(DecHelper.copyExprentList(stat.getExprents())); + } + + stat.getParent().replaceStatement(stat, bstat); + } + + public static void destroyStatementContent(Statement stat, boolean self) { + + for (Statement st : stat.getStats()) { + destroyStatementContent(st, true); + } + stat.getStats().clear(); + + if (self) { + for (StatEdge edge : stat.getAllSuccessorEdges()) { + stat.removeSuccessor(edge); + } + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SimplifyExprentsHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SimplifyExprentsHelper.java new file mode 100644 index 000000000000..90ebe2f8218d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/SimplifyExprentsHelper.java @@ -0,0 +1,853 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.SSAConstructorSparseEx; +import org.jetbrains.java.decompiler.modules.decompiler.stats.IfStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory.FastSparseSet; + +import java.util.*; +import java.util.Map.Entry; + +public class SimplifyExprentsHelper { + + private boolean firstInvocation; + + public SimplifyExprentsHelper(boolean firstInvocation) { + this.firstInvocation = firstInvocation; + } + + public boolean simplifyStackVarsStatement(Statement stat, HashSet<Integer> setReorderedIfs, SSAConstructorSparseEx ssa, StructClass cl) { + + boolean res = false; + + if (stat.getExprents() == null) { + + while (true) { + + boolean changed = false; + + for (Statement st : stat.getStats()) { + res |= simplifyStackVarsStatement(st, setReorderedIfs, ssa, cl); + + // collapse composed if's + if (changed = IfHelper.mergeIfs(st, setReorderedIfs)) { + break; + } + + // collapse iff ?: statement + if (changed = buildIff(st, ssa)) { + break; + } + } + + res |= changed; + + if (!changed) { + break; + } + } + } + else { + res |= simplifyStackVarsExprents(stat.getExprents(), cl); + } + + return res; + } + + private boolean simplifyStackVarsExprents(List<Exprent> list, StructClass cl) { + + boolean res = false; + + int index = 0; + + while (index < list.size()) { + + Exprent current = list.get(index); + + Exprent ret = isSimpleConstructorInvocation(current); + if (ret != null) { + list.set(index, ret); + res = true; + + continue; + } + + // lambda expression (Java 8) + ret = isLambda(current, cl); + if (ret != null) { + list.set(index, ret); + res = true; + + continue; + } + + // remove monitor exit + if (isMonitorExit(current)) { + list.remove(index); + res = true; + + continue; + } + + // trivial assignment of a stack variable + if (isTrivialStackAssignment(current)) { + list.remove(index); + res = true; + + continue; + } + + if (index == list.size() - 1) { + break; + } + + + Exprent next = list.get(index + 1); + + + // constructor invocation + if (isConstructorInvocationRemote(list, index)) { + list.remove(index); + res = true; + + continue; + } + + // remove getClass() invocation, which is part of a qualified new + if (DecompilerContext.getOption(IFernflowerPreferences.REMOVE_GET_CLASS_NEW)) { + if (isQualifiedNewGetClass(current, next)) { + list.remove(index); + res = true; + + continue; + } + } + + // direct initialization of an array + int arrcount = isArrayInitializer(list, index); + if (arrcount > 0) { + for (int i = 0; i < arrcount; i++) { + list.remove(index + 1); + } + res = true; + + continue; + } + + // add array initializer expression + if (addArrayInitializer(current, next)) { + list.remove(index + 1); + res = true; + + continue; + } + + // integer ++expr and --expr (except for vars!) + Exprent func = isPPIorMMI(current); + if (func != null) { + list.set(index, func); + res = true; + + continue; + } + + // expr++ and expr-- + if (isIPPorIMM(current, next)) { + list.remove(index + 1); + res = true; + + continue; + } + + // assignment on stack + if (isStackAssignement(current, next)) { + list.remove(index + 1); + res = true; + + continue; + } + + if (!firstInvocation && isStackAssignement2(current, next)) { + list.remove(index + 1); + res = true; + + continue; + } + + index++; + } + + return res; + } + + private static boolean addArrayInitializer(Exprent first, Exprent second) { + + if (first.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent as = (AssignmentExprent)first; + + if (as.getRight().type == Exprent.EXPRENT_NEW && as.getLeft().type == Exprent.EXPRENT_VAR) { + NewExprent newex = (NewExprent)as.getRight(); + + if (!newex.getLstArrayElements().isEmpty()) { + + VarExprent arrvar = (VarExprent)as.getLeft(); + + if (second.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent aas = (AssignmentExprent)second; + if (aas.getLeft().type == Exprent.EXPRENT_ARRAY) { + ArrayExprent arrex = (ArrayExprent)aas.getLeft(); + if (arrex.getArray().type == Exprent.EXPRENT_VAR && arrvar.equals(arrex.getArray()) + && arrex.getIndex().type == Exprent.EXPRENT_CONST) { + + int constvalue = ((ConstExprent)arrex.getIndex()).getIntValue(); + + if (constvalue < newex.getLstArrayElements().size()) { + Exprent init = newex.getLstArrayElements().get(constvalue); + if (init.type == Exprent.EXPRENT_CONST) { + ConstExprent cinit = (ConstExprent)init; + + VarType arrtype = newex.getNewtype().copy(); + arrtype.decArrayDim(); + + ConstExprent defaultval = ExprProcessor.getDefaultArrayValue(arrtype); + + if (cinit.equals(defaultval)) { + + Exprent tempexpr = aas.getRight(); + + if (!tempexpr.containsExprent(arrvar)) { + newex.getLstArrayElements().set(constvalue, tempexpr); + + if (tempexpr.type == Exprent.EXPRENT_NEW) { + NewExprent tempnewex = (NewExprent)tempexpr; + int dims = newex.getNewtype().arraydim; + if (dims > 1 && !tempnewex.getLstArrayElements().isEmpty()) { + tempnewex.setDirectArrayInit(true); + } + } + + return true; + } + } + } + } + } + } + } + } + } + } + + return false; + } + + + private static int isArrayInitializer(List<Exprent> list, int index) { + + Exprent current = list.get(index); + if (current.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent as = (AssignmentExprent)current; + + if (as.getRight().type == Exprent.EXPRENT_NEW && as.getLeft().type == Exprent.EXPRENT_VAR) { + NewExprent newex = (NewExprent)as.getRight(); + + if (newex.getExprType().arraydim > 0 && newex.getLstDims().size() == 1 && newex.getLstArrayElements().isEmpty() && + newex.getLstDims().get(0).type == Exprent.EXPRENT_CONST) { + + int size = ((Integer)((ConstExprent)newex.getLstDims().get(0)).getValue()).intValue(); + if (size == 0) { + return 0; + } + + VarExprent arrvar = (VarExprent)as.getLeft(); + + HashMap<Integer, Exprent> mapInit = new HashMap<Integer, Exprent>(); + + int i = 1; + while (index + i < list.size() && i <= size) { + boolean found = false; + + Exprent expr = list.get(index + i); + if (expr.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent aas = (AssignmentExprent)expr; + if (aas.getLeft().type == Exprent.EXPRENT_ARRAY) { + ArrayExprent arrex = (ArrayExprent)aas.getLeft(); + if (arrex.getArray().type == Exprent.EXPRENT_VAR && arrvar.equals(arrex.getArray()) + && arrex.getIndex().type == Exprent.EXPRENT_CONST) { + + int constvalue = ((ConstExprent)arrex.getIndex()) + .getIntValue(); // TODO: check for a number type. Failure extremely improbable, but nevertheless... + + if (constvalue < size && !mapInit.containsKey(constvalue)) { + + if (!aas.getRight().containsExprent(arrvar)) { + mapInit.put(constvalue, aas.getRight()); + found = true; + } + } + } + } + } + + if (!found) { + break; + } + + i++; + } + + double fraction = ((double)mapInit.size()) / size; + + if ((arrvar.isStack() && fraction > 0) || (size <= 7 && fraction >= 0.3) || + (size > 7 && fraction >= 0.7)) { + + List<Exprent> lstRet = new ArrayList<Exprent>(); + + VarType arrtype = newex.getNewtype().copy(); + arrtype.decArrayDim(); + + ConstExprent defaultval = ExprProcessor.getDefaultArrayValue(arrtype); + + for (int j = 0; j < size; j++) { + lstRet.add(defaultval.copy()); + } + + int dims = newex.getNewtype().arraydim; + for (Entry<Integer, Exprent> ent : mapInit.entrySet()) { + Exprent tempexpr = ent.getValue(); + lstRet.set(ent.getKey(), tempexpr); + + if (tempexpr.type == Exprent.EXPRENT_NEW) { + NewExprent tempnewex = (NewExprent)tempexpr; + if (dims > 1 && !tempnewex.getLstArrayElements().isEmpty()) { + tempnewex.setDirectArrayInit(true); + } + } + } + + newex.setLstArrayElements(lstRet); + + return mapInit.size(); + } + } + } + } + + return 0; + } + + private static boolean isTrivialStackAssignment(Exprent first) { + + if (first.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asf = (AssignmentExprent)first; + + if (asf.getLeft().type == Exprent.EXPRENT_VAR && asf.getRight().type == Exprent.EXPRENT_VAR) { + VarExprent varleft = (VarExprent)asf.getLeft(); + VarExprent varright = (VarExprent)asf.getRight(); + + if (varleft.getIndex() == varright.getIndex() && varleft.isStack() && + varright.isStack()) { + return true; + } + } + } + + return false; + } + + private static boolean isStackAssignement2(Exprent first, Exprent second) { // e.g. 1.4-style class invocation + + if (first.type == Exprent.EXPRENT_ASSIGNMENT && second.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asf = (AssignmentExprent)first; + AssignmentExprent ass = (AssignmentExprent)second; + + if (asf.getLeft().type == Exprent.EXPRENT_VAR && ass.getRight().type == Exprent.EXPRENT_VAR && + asf.getLeft().equals(ass.getRight()) && ((VarExprent)asf.getLeft()).isStack()) { + if (ass.getLeft().type != Exprent.EXPRENT_VAR || !((VarExprent)ass.getLeft()).isStack()) { + asf.setRight(new AssignmentExprent(ass.getLeft(), asf.getRight())); + return true; + } + } + } + + return false; + } + + private static boolean isStackAssignement(Exprent first, Exprent second) { + + if (first.type == Exprent.EXPRENT_ASSIGNMENT && second.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent asf = (AssignmentExprent)first; + AssignmentExprent ass = (AssignmentExprent)second; + + while (true) { + if (asf.getRight().equals(ass.getRight())) { + if ((asf.getLeft().type == Exprent.EXPRENT_VAR && ((VarExprent)asf.getLeft()).isStack()) && + (ass.getLeft().type != Exprent.EXPRENT_VAR || !((VarExprent)ass.getLeft()).isStack())) { + + if (!ass.getLeft().containsExprent(asf.getLeft())) { + asf.setRight(ass); + return true; + } + } + } + if (asf.getRight().type == Exprent.EXPRENT_ASSIGNMENT) { + asf = (AssignmentExprent)asf.getRight(); + } + else { + break; + } + } + } + + return false; + } + + private static Exprent isPPIorMMI(Exprent first) { + + if (first.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent as = (AssignmentExprent)first; + + if (as.getRight().type == Exprent.EXPRENT_FUNCTION) { + FunctionExprent func = (FunctionExprent)as.getRight(); + + if (func.getFunctype() == FunctionExprent.FUNCTION_ADD || + func.getFunctype() == FunctionExprent.FUNCTION_SUB) { + Exprent econd = func.getLstOperands().get(0); + Exprent econst = func.getLstOperands().get(1); + + if (econst.type != Exprent.EXPRENT_CONST && econd.type == Exprent.EXPRENT_CONST && + func.getFunctype() == FunctionExprent.FUNCTION_ADD) { + econd = econst; + econst = func.getLstOperands().get(0); + } + + if (econst.type == Exprent.EXPRENT_CONST && ((ConstExprent)econst).hasValueOne()) { + Exprent left = as.getLeft(); + + if (left.type != Exprent.EXPRENT_VAR && left.equals(econd)) { + FunctionExprent ret = new FunctionExprent( + func.getFunctype() == FunctionExprent.FUNCTION_ADD ? FunctionExprent.FUNCTION_PPI : FunctionExprent.FUNCTION_MMI, + Arrays.asList(new Exprent[]{econd})); + ret.setImplicitType(VarType.VARTYPE_INT); + return ret; + } + } + } + } + } + + return null; + } + + private static boolean isIPPorIMM(Exprent first, Exprent second) { + + if (first.type == Exprent.EXPRENT_ASSIGNMENT && second.type == Exprent.EXPRENT_FUNCTION) { + AssignmentExprent as = (AssignmentExprent)first; + FunctionExprent in = (FunctionExprent)second; + + if ((in.getFunctype() == FunctionExprent.FUNCTION_MMI || in.getFunctype() == FunctionExprent.FUNCTION_PPI) && + in.getLstOperands().get(0).equals(as.getRight())) { + + if (in.getFunctype() == FunctionExprent.FUNCTION_MMI) { + in.setFunctype(FunctionExprent.FUNCTION_IMM); + } + else { + in.setFunctype(FunctionExprent.FUNCTION_IPP); + } + as.setRight(in); + + return true; + } + } + + return false; + } + + private static boolean isMonitorExit(Exprent first) { + if (first.type == Exprent.EXPRENT_MONITOR) { + MonitorExprent monexpr = (MonitorExprent)first; + if (monexpr.getMontype() == MonitorExprent.MONITOR_EXIT && monexpr.getValue().type == Exprent.EXPRENT_VAR + && !((VarExprent)monexpr.getValue()).isStack()) { + return true; + } + } + + return false; + } + + private static boolean isQualifiedNewGetClass(Exprent first, Exprent second) { + + if (first.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent invexpr = (InvocationExprent)first; + + if (!invexpr.isStatic() && invexpr.getInstance().type == Exprent.EXPRENT_VAR && invexpr.getName().equals("getClass") && + invexpr.getStringDescriptor().equals("()Ljava/lang/Class;")) { + + List<Exprent> lstExprents = second.getAllExprents(); + lstExprents.add(second); + + for (Exprent expr : lstExprents) { + if (expr.type == Exprent.EXPRENT_NEW) { + NewExprent nexpr = (NewExprent)expr; + if (nexpr.getConstructor() != null && !nexpr.getConstructor().getLstParameters().isEmpty() && + nexpr.getConstructor().getLstParameters().get(0).equals(invexpr.getInstance())) { + + String classname = nexpr.getNewtype().value; + ClassNode node = DecompilerContext.getClassProcessor().getMapRootClasses().get(classname); + if (node != null && node.type != ClassNode.CLASS_ROOT) { + return true; + } + } + } + } + } + } + + return false; + } + + // private static boolean isConstructorInvocationRemote(List<Exprent> list, int index) { + // + // Exprent current = list.get(index); + // + // if(current.type == Exprent.EXPRENT_ASSIGNMENT) { + // AssignmentExprent as = (AssignmentExprent)current; + // + // if(as.getLeft().type == Exprent.EXPRENT_VAR && as.getRight().type == Exprent.EXPRENT_NEW) { + // + // NewExprent newexpr = (NewExprent)as.getRight(); + // VarType newtype = newexpr.getNewtype(); + // VarVersionPaar leftPaar = new VarVersionPaar((VarExprent)as.getLeft()); + // + // if(newtype.type == CodeConstants.TYPE_OBJECT && newtype.arraydim == 0 && + // newexpr.getConstructor() == null) { + // + // Set<VarVersionPaar> setChangedVars = new HashSet<VarVersionPaar>(); + // + // for(int i = index + 1; i < list.size(); i++) { + // Exprent remote = list.get(i); + // + // if(remote.type == Exprent.EXPRENT_INVOCATION) { + // InvocationExprent in = (InvocationExprent)remote; + // + // if(in.getFunctype() == InvocationExprent.TYP_INIT && in.getInstance().type == Exprent.EXPRENT_VAR + // && as.getLeft().equals(in.getInstance())) { + // + // Set<VarVersionPaar> setVars = remote.getAllVariables(); + // setVars.remove(leftPaar); + // setVars.retainAll(setChangedVars); + // + // if(setVars.isEmpty()) { + // + // newexpr.setConstructor(in); + // in.setInstance(null); + // + // if(!setChangedVars.isEmpty()) { // some exprents inbetween + // list.add(index+1, as.copy()); + // list.remove(i+1); + // } else { + // list.set(i, as.copy()); + // } + // + // return true; + // } + // } + // } + // + // boolean isTempAssignment = false; + // + // if(remote.type == Exprent.EXPRENT_ASSIGNMENT) { // ugly solution + // AssignmentExprent asremote = (AssignmentExprent)remote; + // if(asremote.getLeft().type == Exprent.EXPRENT_VAR && + // asremote.getRight().type == Exprent.EXPRENT_VAR) { + // setChangedVars.add(new VarVersionPaar((VarExprent)asremote.getLeft())); + // isTempAssignment = true; + // } + // + // // FIXME: needs to be rewritten + // // propagate (var = new X) forward to the <init> invokation and then reduce + // + //// if(asremote.getLeft().type == Exprent.EXPRENT_VAR) { + //// List<Exprent> lstRightExprents = asremote.getRight().getAllExprents(true); + //// lstRightExprents.add(asremote.getRight()); + //// + //// Set<VarVersionPaar> setTempChangedVars = new HashSet<VarVersionPaar>(); + //// boolean isTemp = true; + //// + //// for(Exprent expr : lstRightExprents) { + //// if(expr.type != Exprent.EXPRENT_VAR && expr.type != Exprent.EXPRENT_FIELD) { + //// isTemp = false; + //// break; + //// } else if(expr.type == Exprent.EXPRENT_VAR) { + //// setTempChangedVars.add(new VarVersionPaar((VarExprent)expr)); + //// } + //// } + //// + //// if(isTemp) { + //// setChangedVars.addAll(setTempChangedVars); + //// isTempAssignment = true; + //// } + //// } + //// } else if(remote.type == Exprent.EXPRENT_FUNCTION) { + //// FunctionExprent fexpr = (FunctionExprent)remote; + //// if(fexpr.getFunctype() == FunctionExprent.FUNCTION_IPP || fexpr.getFunctype() == FunctionExprent.FUNCTION_IMM + //// || fexpr.getFunctype() == FunctionExprent.FUNCTION_PPI || fexpr.getFunctype() == FunctionExprent.FUNCTION_MMI) { + //// if(fexpr.getLstOperands().get(0).type == Exprent.EXPRENT_VAR) { + //// setChangedVars.add(new VarVersionPaar((VarExprent)fexpr.getLstOperands().get(0))); + //// isTempAssignment = true; + //// } + //// } + // } + // + // if(!isTempAssignment) { + // Set<VarVersionPaar> setVars = remote.getAllVariables(); + // if(setVars.contains(leftPaar)) { + // return false; + // } else { + // setChangedVars.addAll(setVars); + // } + // } + // } + // } + // } + // } + // + // return false; + // } + + // propagate (var = new X) forward to the <init> invokation + private static boolean isConstructorInvocationRemote(List<Exprent> list, int index) { + + Exprent current = list.get(index); + + if (current.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent as = (AssignmentExprent)current; + + if (as.getLeft().type == Exprent.EXPRENT_VAR && as.getRight().type == Exprent.EXPRENT_NEW) { + + NewExprent newexpr = (NewExprent)as.getRight(); + VarType newtype = newexpr.getNewtype(); + VarVersionPaar leftPaar = new VarVersionPaar((VarExprent)as.getLeft()); + + if (newtype.type == CodeConstants.TYPE_OBJECT && newtype.arraydim == 0 && newexpr.getConstructor() == null) { + + for (int i = index + 1; i < list.size(); i++) { + Exprent remote = list.get(i); + + // <init> invocation + if (remote.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent in = (InvocationExprent)remote; + + if (in.getFunctype() == InvocationExprent.TYP_INIT && + in.getInstance().type == Exprent.EXPRENT_VAR && + as.getLeft().equals(in.getInstance())) { + + newexpr.setConstructor(in); + in.setInstance(null); + + list.set(i, as.copy()); + + return true; + } + } + + // check for variable in use + Set<VarVersionPaar> setVars = remote.getAllVariables(); + if (setVars.contains(leftPaar)) { // variable used somewhere in between -> exit, need a better reduced code + return false; + } + } + } + } + } + + return false; + } + + private static Exprent isLambda(Exprent exprent, StructClass cl) { + + List<Exprent> lst = exprent.getAllExprents(); + for (Exprent expr : lst) { + Exprent ret = isLambda(expr, cl); + if (ret != null) { + exprent.replaceExprent(expr, ret); + } + } + + if (exprent.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent in = (InvocationExprent)exprent; + + if (in.getInvocationTyp() == InvocationExprent.INVOKE_DYNAMIC) { + + String lambda_class_name = cl.qualifiedName + in.getInvokeDynamicClassSuffix(); + ClassNode lambda_class = DecompilerContext.getClassProcessor().getMapRootClasses().get(lambda_class_name); + + if (lambda_class != null) { // real lambda class found, replace invocation with an anonymous class + + NewExprent newexp = new NewExprent(new VarType(lambda_class_name, true), null, 0); + newexp.setConstructor(in); + // note: we don't set the instance to null with in.setInstance(null) like it is done for a common constructor invokation + // lambda can also be a reference to a virtual method (e.g. String x; ...(x::toString);) + // in this case instance will hold the corresponding object + + return newexp; + } + } + } + + return null; + } + + + private static Exprent isSimpleConstructorInvocation(Exprent exprent) { + + List<Exprent> lst = exprent.getAllExprents(); + for (Exprent expr : lst) { + Exprent ret = isSimpleConstructorInvocation(expr); + if (ret != null) { + exprent.replaceExprent(expr, ret); + } + } + + if (exprent.type == Exprent.EXPRENT_INVOCATION) { + InvocationExprent in = (InvocationExprent)exprent; + if (in.getFunctype() == InvocationExprent.TYP_INIT && in.getInstance().type == Exprent.EXPRENT_NEW) { + NewExprent newexp = (NewExprent)in.getInstance(); + newexp.setConstructor(in); + in.setInstance(null); + return newexp; + } + } + + return null; + } + + + private static boolean buildIff(Statement stat, SSAConstructorSparseEx ssa) { + + if (stat.type == Statement.TYPE_IF && stat.getExprents() == null) { + IfStatement stif = (IfStatement)stat; + if (stif.iftype == IfStatement.IFTYPE_IFELSE) { + Statement ifstat = stif.getIfstat(); + Statement elsestat = stif.getElsestat(); + + if (ifstat.getExprents() != null && ifstat.getExprents().size() == 1 + && elsestat.getExprents() != null && elsestat.getExprents().size() == 1 + && ifstat.getAllSuccessorEdges().size() == 1 && elsestat.getAllSuccessorEdges().size() == 1 + && ifstat.getAllSuccessorEdges().get(0).getDestination() == elsestat.getAllSuccessorEdges().get(0).getDestination()) { + + Exprent ifexpr = ifstat.getExprents().get(0); + Exprent elseexpr = elsestat.getExprents().get(0); + + if (ifexpr.type == Exprent.EXPRENT_ASSIGNMENT && elseexpr.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent ifas = (AssignmentExprent)ifexpr; + AssignmentExprent elseas = (AssignmentExprent)elseexpr; + + if (ifas.getLeft().type == Exprent.EXPRENT_VAR && elseas.getLeft().type == Exprent.EXPRENT_VAR) { + VarExprent ifvar = (VarExprent)ifas.getLeft(); + VarExprent elsevar = (VarExprent)elseas.getLeft(); + + if (ifvar.getIndex() == elsevar.getIndex() && ifvar.isStack()) { // ifvar.getIndex() >= VarExprent.STACK_BASE) { + + boolean found = false; + + for (Entry<VarVersionPaar, FastSparseSet<Integer>> ent : ssa.getPhi().entrySet()) { + if (ent.getKey().var == ifvar.getIndex()) { + if (ent.getValue().contains(ifvar.getVersion()) && ent.getValue().contains(elsevar.getVersion())) { + found = true; + break; + } + } + } + + if (found) { + List<Exprent> data = new ArrayList<Exprent>(); + data.addAll(stif.getFirst().getExprents()); + + data.add(new AssignmentExprent(ifvar, new FunctionExprent(FunctionExprent.FUNCTION_IIF, + Arrays.asList(new Exprent[]{ + stif.getHeadexprent().getCondition(), + ifas.getRight(), + elseas.getRight()})))); + stif.setExprents(data); + + if (stif.getAllSuccessorEdges().isEmpty()) { + StatEdge ifedge = ifstat.getAllSuccessorEdges().get(0); + StatEdge edge = new StatEdge(ifedge.getType(), stif, ifedge.getDestination()); + + stif.addSuccessor(edge); + if (ifedge.closure != null) { + ifedge.closure.addLabeledEdge(edge); + } + } + + SequenceHelper.destroyAndFlattenStatement(stif); + + return true; + } + } + } + } + else if (ifexpr.type == Exprent.EXPRENT_EXIT && elseexpr.type == Exprent.EXPRENT_EXIT) { + ExitExprent ifex = (ExitExprent)ifexpr; + ExitExprent elseex = (ExitExprent)elseexpr; + + if (ifex.getExittype() == elseex.getExittype() && ifex.getValue() != null && elseex.getValue() != null && + ifex.getExittype() == ExitExprent.EXIT_RETURN) { + + // throw is dangerous, because of implicit casting to a common superclass + // e.g. throws IOException and throw true?new RuntimeException():new IOException(); won't work + if (ifex.getExittype() == ExitExprent.EXIT_THROW && + !ifex.getValue().getExprType().equals(elseex.getValue().getExprType())) { // note: getExprType unreliable at this point! + return false; + } + + List<Exprent> data = new ArrayList<Exprent>(); + data.addAll(stif.getFirst().getExprents()); + + data.add(new ExitExprent(ifex.getExittype(), new FunctionExprent(FunctionExprent.FUNCTION_IIF, + Arrays.asList(new Exprent[]{ + stif.getHeadexprent().getCondition(), + ifex.getValue(), + elseex.getValue()})), ifex.getRettype())); + stif.setExprents(data); + + StatEdge retedge = ifstat.getAllSuccessorEdges().get(0); + stif.addSuccessor(new StatEdge(StatEdge.TYPE_BREAK, stif, retedge.getDestination(), + retedge.closure == stif ? stif.getParent() : retedge.closure)); + + SequenceHelper.destroyAndFlattenStatement(stif); + + return true; + } + } + } + } + } + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StackVarsProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StackVarsProcessor.java new file mode 100644 index 000000000000..109490cc8ef9 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StackVarsProcessor.java @@ -0,0 +1,735 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.*; +import org.jetbrains.java.decompiler.modules.decompiler.stats.DoStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionEdge; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionNode; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionsGraph; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory.FastSparseSet; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.SFormsFastMapDirect; + +import java.util.*; +import java.util.Map.Entry; + + +public class StackVarsProcessor { + + public void simplifyStackVars(RootStatement root, StructMethod mt, StructClass cl) { + + HashSet<Integer> setReorderedIfs = new HashSet<Integer>(); + + SSAUConstructorSparseEx ssau = null; + + while (true) { + + boolean found = false; + + // System.out.println("--------------- \r\n"+root.toJava()); + + SSAConstructorSparseEx ssa = new SSAConstructorSparseEx(); + ssa.splitVariables(root, mt); + + // System.out.println("--------------- \r\n"+root.toJava()); + + + SimplifyExprentsHelper sehelper = new SimplifyExprentsHelper(ssau == null); + while (sehelper.simplifyStackVarsStatement(root, setReorderedIfs, ssa, cl)) { + // System.out.println("--------------- \r\n"+root.toJava()); + found = true; + } + + + // System.out.println("=============== \r\n"+root.toJava()); + + setVersionsToNull(root); + + SequenceHelper.condenseSequences(root); + + ssau = new SSAUConstructorSparseEx(); + ssau.splitVariables(root, mt); + + // try { + // DotExporter.toDotFile(ssau.getSsuversions(), new File("c:\\Temp\\gr12_my.dot")); + // } catch(Exception ex) { + // ex.printStackTrace(); + // } + + // System.out.println("++++++++++++++++ \r\n"+root.toJava()); + + + if (iterateStatements(root, ssau)) { + found = true; + } + + // System.out.println("***************** \r\n"+root.toJava()); + + setVersionsToNull(root); + + if (!found) { + break; + } + } + + // remove unused assignments + ssau = new SSAUConstructorSparseEx(); + ssau.splitVariables(root, mt); + + // try { + // DotExporter.toDotFile(ssau.getSsuversions(), new File("c:\\Temp\\gr12_my.dot")); + // } catch(Exception ex) { + // ex.printStackTrace(); + // } + + iterateStatements(root, ssau); + + // System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + setVersionsToNull(root); + } + + private static void setVersionsToNull(Statement stat) { + + if (stat.getExprents() == null) { + for (Object obj : stat.getSequentialObjects()) { + if (obj instanceof Statement) { + setVersionsToNull((Statement)obj); + } + else if (obj instanceof Exprent) { + setExprentVersionsToNull((Exprent)obj); + } + } + } + else { + for (Exprent exprent : stat.getExprents()) { + setExprentVersionsToNull(exprent); + } + } + } + + private static void setExprentVersionsToNull(Exprent exprent) { + + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + if (expr.type == Exprent.EXPRENT_VAR) { + ((VarExprent)expr).setVersion(0); + } + } + } + + + private boolean iterateStatements(RootStatement root, SSAUConstructorSparseEx ssa) { + + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + DirectGraph dgraph = flatthelper.buildDirectGraph(root); + + boolean res = false; + + HashSet<DirectNode> setVisited = new HashSet<DirectNode>(); + LinkedList<DirectNode> stack = new LinkedList<DirectNode>(); + LinkedList<HashMap<VarVersionPaar, Exprent>> stackMaps = new LinkedList<HashMap<VarVersionPaar, Exprent>>(); + + stack.add(dgraph.first); + stackMaps.add(new HashMap<VarVersionPaar, Exprent>()); + + while (!stack.isEmpty()) { + + DirectNode nd = stack.removeFirst(); + HashMap<VarVersionPaar, Exprent> mapVarValues = stackMaps.removeFirst(); + + if (setVisited.contains(nd)) { + continue; + } + setVisited.add(nd); + + List<List<Exprent>> lstLists = new ArrayList<List<Exprent>>(); + + if (!nd.exprents.isEmpty()) { + lstLists.add(nd.exprents); + } + + if (nd.succs.size() == 1) { + DirectNode ndsucc = nd.succs.get(0); + if (ndsucc.type == DirectNode.NODE_TAIL && !ndsucc.exprents.isEmpty()) { + lstLists.add(nd.succs.get(0).exprents); + nd = ndsucc; + } + } + + for (int i = 0; i < lstLists.size(); i++) { + List<Exprent> lst = lstLists.get(i); + + int index = 0; + while (index < lst.size()) { + Exprent next = null; + if (index == lst.size() - 1) { + if (i < lstLists.size() - 1) { + next = lstLists.get(i + 1).get(0); + } + } + else { + next = lst.get(index + 1); + } + + int[] ret = iterateExprent(lst, index, next, mapVarValues, ssa); + + //System.out.println("***************** \r\n"+root.toJava()); + + if (ret[0] >= 0) { + index = ret[0]; + } + else { + index++; + } + res |= (ret[1] == 1); + } + } + + for (DirectNode ndx : nd.succs) { + stack.add(ndx); + stackMaps.add(new HashMap<VarVersionPaar, Exprent>(mapVarValues)); + } + + // make sure the 3 special exprent lists in a loop (init, condition, increment) are not empty + // change loop type if necessary + if (nd.exprents.isEmpty() && + (nd.type == DirectNode.NODE_INIT || nd.type == DirectNode.NODE_CONDITION || nd.type == DirectNode.NODE_INCREMENT)) { + nd.exprents.add(null); + + if (nd.statement.type == Statement.TYPE_DO) { + DoStatement loop = (DoStatement)nd.statement; + + if (loop.getLooptype() == DoStatement.LOOP_FOR && + loop.getInitExprent() == null && + loop.getIncExprent() == null) { // "downgrade" loop to 'while' + loop.setLooptype(DoStatement.LOOP_WHILE); + } + } + } + } + + return res; + } + + + private static Exprent isReplaceableVar(Exprent exprent, HashMap<VarVersionPaar, Exprent> mapVarValues, SSAUConstructorSparseEx ssau) { + + Exprent dest = null; + + if (exprent.type == Exprent.EXPRENT_VAR) { + VarExprent var = (VarExprent)exprent; + dest = mapVarValues.get(new VarVersionPaar(var)); + } + + return dest; + } + + private static void replaceSingleVar(Exprent parent, VarExprent var, Exprent dest, SSAUConstructorSparseEx ssau) { + + parent.replaceExprent(var, dest); + + // live sets + SFormsFastMapDirect livemap = ssau.getLiveVarVersionsMap(new VarVersionPaar(var)); + HashSet<VarVersionPaar> setVars = getAllVersions(dest); + + for (VarVersionPaar varpaar : setVars) { + VarVersionNode node = ssau.getSsuversions().nodes.getWithKey(varpaar); + + for (Iterator<Entry<Integer, FastSparseSet<Integer>>> itent = node.live.entryList().iterator(); itent.hasNext(); ) { + Entry<Integer, FastSparseSet<Integer>> ent = itent.next(); + + Integer key = ent.getKey(); + + if (!livemap.containsKey(key)) { + itent.remove(); + } + else { + FastSparseSet<Integer> set = ent.getValue(); + + set.complement(livemap.get(key)); + if (set.isEmpty()) { + itent.remove(); + } + } + } + } + } + + private int[] iterateExprent(List<Exprent> lstExprents, int index, Exprent next, HashMap<VarVersionPaar, + Exprent> mapVarValues, SSAUConstructorSparseEx ssau) { + + Exprent exprent = lstExprents.get(index); + + int changed = 0; + + for (Exprent expr : exprent.getAllExprents()) { + while (true) { + Object[] arr = iterateChildExprent(expr, exprent, next, mapVarValues, ssau); + Exprent retexpr = (Exprent)arr[0]; + changed |= (Boolean)arr[1] ? 1 : 0; + + boolean isReplaceable = (Boolean)arr[2]; + if (retexpr != null) { + if (isReplaceable) { + replaceSingleVar(exprent, (VarExprent)expr, retexpr, ssau); + expr = retexpr; + } + else { + exprent.replaceExprent(expr, retexpr); + } + changed = 1; + } + + if (!isReplaceable) { + break; + } + } + } + + // no var on the highest level, so no replacing + + VarExprent left = null; + Exprent right = null; + + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent as = (AssignmentExprent)exprent; + if (as.getLeft().type == Exprent.EXPRENT_VAR) { + left = (VarExprent)as.getLeft(); + right = as.getRight(); + } + } + + if (left == null) { + return new int[]{-1, changed}; + } + + VarVersionPaar leftpaar = new VarVersionPaar(left); + + List<VarVersionNode> usedVers = new ArrayList<VarVersionNode>(); + boolean notdom = getUsedVersions(ssau, leftpaar, usedVers); + + if (!notdom && usedVers.isEmpty()) { + if (left.isStack() && (right.type == Exprent.EXPRENT_INVOCATION || + right.type == Exprent.EXPRENT_ASSIGNMENT || right.type == Exprent.EXPRENT_NEW)) { + if (right.type == Exprent.EXPRENT_NEW) { + // new Object(); permitted + NewExprent nexpr = (NewExprent)right; + if (nexpr.isAnonymous() || nexpr.getNewtype().arraydim > 0 + || nexpr.getNewtype().type != CodeConstants.TYPE_OBJECT) { + return new int[]{-1, changed}; + } + } + + lstExprents.set(index, right); + return new int[]{index + 1, 1}; + } + else if (right.type == Exprent.EXPRENT_VAR) { + lstExprents.remove(index); + return new int[]{index, 1}; + } + else { + return new int[]{-1, changed}; + } + } + + int useflags = right.getExprentUse(); + + // stack variables only + if (!left.isStack() && + (right.type != Exprent.EXPRENT_VAR || ((VarExprent)right).isStack())) { // special case catch(... ex) + return new int[]{-1, changed}; + } + + if ((useflags & Exprent.MULTIPLE_USES) == 0 && (notdom || usedVers.size() > 1)) { + return new int[]{-1, changed}; + } + + HashMap<Integer, HashSet<VarVersionPaar>> mapVars = getAllVarVersions(leftpaar, right, ssau); + + boolean isSelfReference = mapVars.containsKey(leftpaar.var); + if (isSelfReference && notdom) { + return new int[]{-1, changed}; + } + + HashSet<VarVersionPaar> setNextVars = next == null ? null : getAllVersions(next); + + // FIXME: fix the entire method! + if (right.type != Exprent.EXPRENT_CONST && + right.type != Exprent.EXPRENT_VAR && + setNextVars != null && + mapVars.containsKey(leftpaar.var)) { + for (VarVersionNode usedvar : usedVers) { + if (!setNextVars.contains(new VarVersionPaar(usedvar.var, usedvar.version))) { + return new int[]{-1, changed}; + } + } + } + + mapVars.remove(leftpaar.var); + + boolean vernotreplaced = false; + boolean verreplaced = false; + + + HashSet<VarVersionPaar> setTempUsedVers = new HashSet<VarVersionPaar>(); + + for (VarVersionNode usedvar : usedVers) { + VarVersionPaar usedver = new VarVersionPaar(usedvar.var, usedvar.version); + if (isVersionToBeReplaced(usedver, mapVars, ssau, leftpaar) && + (right.type == Exprent.EXPRENT_CONST || right.type == Exprent.EXPRENT_VAR || right.type == Exprent.EXPRENT_FIELD + || setNextVars == null || setNextVars.contains(usedver))) { + + setTempUsedVers.add(usedver); + verreplaced = true; + } + else { + vernotreplaced = true; + } + } + + if (isSelfReference && vernotreplaced) { + return new int[]{-1, changed}; + } + else { + for (VarVersionPaar usedver : setTempUsedVers) { + Exprent copy = right.copy(); + if (right.type == Exprent.EXPRENT_FIELD && ssau.getMapFieldVars().containsKey(right.id)) { + ssau.getMapFieldVars().put(copy.id, ssau.getMapFieldVars().get(right.id)); + } + + mapVarValues.put(usedver, copy); + } + } + + if (!notdom && !vernotreplaced) { + // remove assignment + lstExprents.remove(index); + return new int[]{index, 1}; + } + else if (verreplaced) { + return new int[]{index + 1, changed}; + } + else { + return new int[]{-1, changed}; + } + } + + private static HashSet<VarVersionPaar> getAllVersions(Exprent exprent) { + + HashSet<VarVersionPaar> res = new HashSet<VarVersionPaar>(); + + List<Exprent> listTemp = new ArrayList<Exprent>(exprent.getAllExprents(true)); + listTemp.add(exprent); + + for (Exprent expr : listTemp) { + if (expr.type == Exprent.EXPRENT_VAR) { + VarExprent var = (VarExprent)expr; + res.add(new VarVersionPaar(var)); + } + } + + return res; + } + + private static Object[] iterateChildExprent(Exprent exprent, + Exprent parent, + Exprent next, + HashMap<VarVersionPaar, Exprent> mapVarValues, + SSAUConstructorSparseEx ssau) { + + boolean changed = false; + + for (Exprent expr : exprent.getAllExprents()) { + while (true) { + Object[] arr = iterateChildExprent(expr, parent, next, mapVarValues, ssau); + Exprent retexpr = (Exprent)arr[0]; + changed |= (Boolean)arr[1]; + + boolean isReplaceable = (Boolean)arr[2]; + if (retexpr != null) { + if (isReplaceable) { + replaceSingleVar(exprent, (VarExprent)expr, retexpr, ssau); + expr = retexpr; + } + else { + exprent.replaceExprent(expr, retexpr); + } + changed = true; + } + + if (!isReplaceable) { + break; + } + } + } + + Exprent dest = isReplaceableVar(exprent, mapVarValues, ssau); + if (dest != null) { + return new Object[]{dest, true, true}; + } + + + VarExprent left = null; + Exprent right = null; + + if (exprent.type == Exprent.EXPRENT_ASSIGNMENT) { + AssignmentExprent as = (AssignmentExprent)exprent; + if (as.getLeft().type == Exprent.EXPRENT_VAR) { + left = (VarExprent)as.getLeft(); + right = as.getRight(); + } + } + + if (left == null) { + return new Object[]{null, changed, false}; + } + + boolean isHeadSynchronized = false; + if (next == null && parent.type == Exprent.EXPRENT_MONITOR) { + MonitorExprent monexpr = (MonitorExprent)parent; + if (monexpr.getMontype() == MonitorExprent.MONITOR_ENTER && exprent.equals(monexpr.getValue())) { + isHeadSynchronized = true; + } + } + + // stack variable or synchronized head exprent + if (!left.isStack() && !isHeadSynchronized) { + return new Object[]{null, changed, false}; + } + + VarVersionPaar leftpaar = new VarVersionPaar(left); + + List<VarVersionNode> usedVers = new ArrayList<VarVersionNode>(); + boolean notdom = getUsedVersions(ssau, leftpaar, usedVers); + + if (!notdom && usedVers.isEmpty()) { + return new Object[]{right, changed, false}; + } + + // stack variables only + if (!left.isStack()) { + return new Object[]{null, changed, false}; + } + + int useflags = right.getExprentUse(); + + if ((useflags & Exprent.BOTH_FLAGS) != Exprent.BOTH_FLAGS) { + return new Object[]{null, changed, false}; + } + + HashMap<Integer, HashSet<VarVersionPaar>> mapVars = getAllVarVersions(leftpaar, right, ssau); + + if (mapVars.containsKey(leftpaar.var) && notdom) { + return new Object[]{null, changed, false}; + } + + + mapVars.remove(leftpaar.var); + + HashSet<VarVersionPaar> setAllowedVars = getAllVersions(parent); + if (next != null) { + setAllowedVars.addAll(getAllVersions(next)); + } + + boolean vernotreplaced = false; + + HashSet<VarVersionPaar> setTempUsedVers = new HashSet<VarVersionPaar>(); + + for (VarVersionNode usedvar : usedVers) { + VarVersionPaar usedver = new VarVersionPaar(usedvar.var, usedvar.version); + if (isVersionToBeReplaced(usedver, mapVars, ssau, leftpaar) && + (right.type == Exprent.EXPRENT_VAR || setAllowedVars.contains(usedver))) { + + setTempUsedVers.add(usedver); + } + else { + vernotreplaced = true; + } + } + + if (!notdom && !vernotreplaced) { + + for (VarVersionPaar usedver : setTempUsedVers) { + Exprent copy = right.copy(); + if (right.type == Exprent.EXPRENT_FIELD && ssau.getMapFieldVars().containsKey(right.id)) { + ssau.getMapFieldVars().put(copy.id, ssau.getMapFieldVars().get(right.id)); + } + + mapVarValues.put(usedver, copy); + } + + // remove assignment + return new Object[]{right, changed, false}; + } + + return new Object[]{null, changed, false}; + } + + private static boolean getUsedVersions(SSAUConstructorSparseEx ssa, VarVersionPaar var, List<VarVersionNode> res) { + + VarVersionsGraph ssuversions = ssa.getSsuversions(); + VarVersionNode varnode = ssuversions.nodes.getWithKey(var); + + HashSet<VarVersionNode> setVisited = new HashSet<VarVersionNode>(); + + HashSet<VarVersionNode> setNotDoms = new HashSet<VarVersionNode>(); + + LinkedList<VarVersionNode> stack = new LinkedList<VarVersionNode>(); + stack.add(varnode); + + while (!stack.isEmpty()) { + + VarVersionNode nd = stack.remove(0); + setVisited.add(nd); + + if (nd != varnode && (nd.flags & VarVersionNode.FLAG_PHANTOM_FINEXIT) == 0) { + res.add(nd); + } + + for (VarVersionEdge edge : nd.succs) { + VarVersionNode succ = edge.dest; + + if (!setVisited.contains(edge.dest)) { + + boolean isDominated = true; + for (VarVersionEdge prededge : succ.preds) { + if (!setVisited.contains(prededge.source)) { + isDominated = false; + break; + } + } + + if (isDominated) { + stack.add(succ); + } + else { + setNotDoms.add(succ); + } + } + } + } + + setNotDoms.removeAll(setVisited); + + return !setNotDoms.isEmpty(); + } + + private static boolean isVersionToBeReplaced(VarVersionPaar usedvar, + HashMap<Integer, HashSet<VarVersionPaar>> mapVars, + SSAUConstructorSparseEx ssau, + VarVersionPaar leftpaar) { + + VarVersionsGraph ssuversions = ssau.getSsuversions(); + + SFormsFastMapDirect mapLiveVars = ssau.getLiveVarVersionsMap(usedvar); + if (mapLiveVars == null) { + // dummy version, predecessor of a phi node + return false; + } + + // compare protected ranges + if (!InterpreterUtil.equalObjects(ssau.getMapVersionFirstRange().get(leftpaar), + ssau.getMapVersionFirstRange().get(usedvar))) { + return false; + } + + for (Entry<Integer, HashSet<VarVersionPaar>> ent : mapVars.entrySet()) { + FastSparseSet<Integer> liveverset = mapLiveVars.get(ent.getKey()); + if (liveverset == null) { + return false; + } + + HashSet<VarVersionNode> domset = new HashSet<VarVersionNode>(); + for (VarVersionPaar verpaar : ent.getValue()) { + domset.add(ssuversions.nodes.getWithKey(verpaar)); + } + + boolean isdom = false; + + for (Integer livever : liveverset) { + VarVersionNode node = ssuversions.nodes.getWithKey(new VarVersionPaar(ent.getKey().intValue(), livever.intValue())); + + if (ssuversions.isDominatorSet(node, domset)) { + isdom = true; + break; + } + } + + if (!isdom) { + return false; + } + } + + return true; + } + + private static HashMap<Integer, HashSet<VarVersionPaar>> getAllVarVersions(VarVersionPaar leftvar, + Exprent exprent, + SSAUConstructorSparseEx ssau) { + + HashMap<Integer, HashSet<VarVersionPaar>> map = new HashMap<Integer, HashSet<VarVersionPaar>>(); + SFormsFastMapDirect mapLiveVars = ssau.getLiveVarVersionsMap(leftvar); + + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + if (expr.type == Exprent.EXPRENT_VAR) { + int varindex = ((VarExprent)expr).getIndex(); + if (leftvar.var != varindex) { + if (mapLiveVars.containsKey(varindex)) { + HashSet<VarVersionPaar> verset = new HashSet<VarVersionPaar>(); + for (Integer vers : mapLiveVars.get(varindex)) { + verset.add(new VarVersionPaar(varindex, vers.intValue())); + } + map.put(varindex, verset); + } + else { + throw new RuntimeException("inkonsistent live map!"); + } + } + else { + map.put(varindex, null); + } + } + else if (expr.type == Exprent.EXPRENT_FIELD) { + if (ssau.getMapFieldVars().containsKey(expr.id)) { + int varindex = ssau.getMapFieldVars().get(expr.id); + if (mapLiveVars.containsKey(varindex)) { + HashSet<VarVersionPaar> verset = new HashSet<VarVersionPaar>(); + for (Integer vers : mapLiveVars.get(varindex)) { + verset.add(new VarVersionPaar(varindex, vers.intValue())); + } + map.put(varindex, verset); + } + } + } + } + + return map; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StatEdge.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StatEdge.java new file mode 100644 index 000000000000..26d427b93770 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StatEdge.java @@ -0,0 +1,104 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.ArrayList; +import java.util.List; + +public class StatEdge { + + public static final int TYPE_ALL = 0xFF; + + public static final int TYPE_REGULAR = 1; + public static final int TYPE_EXCEPTION = 2; + public static final int TYPE_BREAK = 4; + public static final int TYPE_CONTINUE = 8; + public static final int TYPE_FINALLYEXIT = 32; + + public static final int[] TYPES = new int[]{ + TYPE_REGULAR, + TYPE_EXCEPTION, + TYPE_BREAK, + TYPE_CONTINUE, + TYPE_FINALLYEXIT + }; + + private int type; + + private Statement source; + + private Statement destination; + + private List<String> exceptions; + + public Statement closure; + + public boolean labeled = true; + + public boolean explicit = true; + + public StatEdge(int type, Statement source, Statement destination, Statement closure) { + this(type, source, destination); + this.closure = closure; + } + + public StatEdge(int type, Statement source, Statement destination) { + this.type = type; + this.source = source; + this.destination = destination; + } + + public StatEdge(Statement source, Statement destination, List<String> exceptions) { + this(TYPE_EXCEPTION, source, destination); + if (exceptions != null) { + this.exceptions = new ArrayList<String>(exceptions); + } + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public Statement getSource() { + return source; + } + + public void setSource(Statement source) { + this.source = source; + } + + public Statement getDestination() { + return destination; + } + + public void setDestination(Statement destination) { + this.destination = destination; + } + + public List<String> getExceptions() { + return this.exceptions; + } + + // public void setException(String exception) { + // this.exception = exception; + // } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StrongConnectivityHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StrongConnectivityHelper.java new file mode 100644 index 000000000000..23f778daea97 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/StrongConnectivityHelper.java @@ -0,0 +1,207 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler; + +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.util.ListStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +// -------------------------------------------------------------------- +// Algorithm +// -------------------------------------------------------------------- +// DFS(G) +// { +// make a new vertex x with edges x->v for all v +// initialize a counter N to zero +// initialize list L to empty +// build directed tree T, initially a single vertex {x} +// visit(x) +// } +// +// visit(p) +// { +// add p to L +// dfsnum(p) = N +// increment N +// low(p) = dfsnum(p) +// for each edge p->q +// if q is not already in T +// { +// add p->q to T +// visit(q) +// low(p) = min(low(p), low(q)) +// } else low(p) = min(low(p), dfsnum(q)) +// +// if low(p)=dfsnum(p) +// { +// output "component:" +// repeat +// remove last element v from L +// output v +// remove v from G +// until v=p +// } +// } +// -------------------------------------------------------------------- + +public class StrongConnectivityHelper { + + private ListStack<Statement> lstack; + + private int ncounter; + + private HashSet<Statement> tset; + private HashMap<Statement, Integer> dfsnummap; + private HashMap<Statement, Integer> lowmap; + + private List<List<Statement>> components; + + private HashSet<Statement> setProcessed; + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public StrongConnectivityHelper() { + } + + public StrongConnectivityHelper(Statement stat) { + findComponents(stat); + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public List<List<Statement>> findComponents(Statement stat) { + + components = new ArrayList<List<Statement>>(); + setProcessed = new HashSet<Statement>(); + + visitTree(stat.getFirst()); + + for (Statement st : stat.getStats()) { + if (!setProcessed.contains(st) && st.getPredecessorEdges(Statement.STATEDGE_DIRECT_ALL).isEmpty()) { + visitTree(st); + } + } + + // should not find any more nodes! FIXME: ?? + for (Statement st : stat.getStats()) { + if (!setProcessed.contains(st)) { + visitTree(st); + } + } + + return components; + } + + public static boolean isExitComponent(List<Statement> lst) { + + HashSet<Statement> set = new HashSet<Statement>(); + for (Statement stat : lst) { + set.addAll(stat.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_FORWARD)); + } + set.removeAll(lst); + + return (set.size() == 0); + } + + public static List<Statement> getExitReps(List<List<Statement>> lst) { + + List<Statement> res = new ArrayList<Statement>(); + + for (List<Statement> comp : lst) { + if (isExitComponent(comp)) { + res.add(comp.get(0)); + } + } + + return res; + } + + // ***************************************************************************** + // private methods + // ***************************************************************************** + + private void visitTree(Statement stat) { + lstack = new ListStack<Statement>(); + ncounter = 0; + tset = new HashSet<Statement>(); + dfsnummap = new HashMap<Statement, Integer>(); + lowmap = new HashMap<Statement, Integer>(); + + visit(stat); + + setProcessed.addAll(tset); + setProcessed.add(stat); + } + + private void visit(Statement stat) { + + lstack.push(stat); + dfsnummap.put(stat, ncounter); + lowmap.put(stat, ncounter); + ncounter++; + + List<Statement> lstSuccs = stat.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_FORWARD); // TODO: set? + lstSuccs.removeAll(setProcessed); + + for (int i = 0; i < lstSuccs.size(); i++) { + Statement succ = lstSuccs.get(i); + int secvalue; + + if (tset.contains(succ)) { + secvalue = dfsnummap.get(succ); + } + else { + tset.add(succ); + visit(succ); + secvalue = lowmap.get(succ); + } + lowmap.put(stat, Math.min(lowmap.get(stat), secvalue)); + } + + + if (lowmap.get(stat).intValue() == dfsnummap.get(stat).intValue()) { + List<Statement> lst = new ArrayList<Statement>(); + Statement v; + do { + v = lstack.pop(); + lst.add(v); + } + while (v != stat); + components.add(lst); + } + } + + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public List<List<Statement>> getComponents() { + return components; + } + + public void setComponents(List<List<Statement>> components) { + this.components = components; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/DominatorEngine.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/DominatorEngine.java new file mode 100644 index 000000000000..aeab0d2cf948 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/DominatorEngine.java @@ -0,0 +1,128 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.decompose; + +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.List; + +public class DominatorEngine { + + private Statement statement; + + private VBStyleCollection<Integer, Integer> colOrderedIDoms = new VBStyleCollection<Integer, Integer>(); + + + public DominatorEngine(Statement statement) { + this.statement = statement; + } + + public void initialize() { + calcIDoms(); + } + + private void orderStatements() { + + for (Statement stat : statement.getReversePostOrderList()) { + colOrderedIDoms.addWithKey(null, stat.id); + } + } + + private static Integer getCommonIDom(Integer key1, Integer key2, VBStyleCollection<Integer, Integer> orderedIDoms) { + + if (key1 == null) { + return key2; + } + else if (key2 == null) { + return key1; + } + + int index1 = orderedIDoms.getIndexByKey(key1); + int index2 = orderedIDoms.getIndexByKey(key2); + + while (index1 != index2) { + if (index1 > index2) { + key1 = orderedIDoms.getWithKey(key1); + index1 = orderedIDoms.getIndexByKey(key1); + } + else { + key2 = orderedIDoms.getWithKey(key2); + index2 = orderedIDoms.getIndexByKey(key2); + } + } + + return key1; + } + + private void calcIDoms() { + + orderStatements(); + + colOrderedIDoms.putWithKey(statement.getFirst().id, statement.getFirst().id); + + // exclude first statement + List<Integer> lstIds = colOrderedIDoms.getLstKeys().subList(1, colOrderedIDoms.getLstKeys().size()); + + while (true) { + + boolean changed = false; + + for (Integer id : lstIds) { + + Statement stat = statement.getStats().getWithKey(id); + Integer idom = null; + + for (StatEdge edge : stat.getAllPredecessorEdges()) { + if (colOrderedIDoms.getWithKey(edge.getSource().id) != null) { + idom = getCommonIDom(idom, edge.getSource().id, colOrderedIDoms); + } + } + + Integer oldidom = colOrderedIDoms.putWithKey(idom, id); + if (!idom.equals(oldidom)) { + changed = true; + } + } + + if (!changed) { + break; + } + } + } + + public VBStyleCollection<Integer, Integer> getOrderedIDoms() { + return colOrderedIDoms; + } + + public boolean isDominator(Integer node, Integer dom) { + + while (!node.equals(dom)) { + + Integer idom = colOrderedIDoms.getWithKey(node); + + if (idom.equals(node)) { + return false; // root node + } + else { + node = idom; + } + } + + return true; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/DominatorTreeExceptionFilter.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/DominatorTreeExceptionFilter.java new file mode 100644 index 000000000000..c11d5bf0c67e --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/DominatorTreeExceptionFilter.java @@ -0,0 +1,184 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.decompose; + +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.*; +import java.util.Map.Entry; + +public class DominatorTreeExceptionFilter { + + private Statement statement; + + // idom, nodes + private Map<Integer, Set<Integer>> mapTreeBranches = new HashMap<Integer, Set<Integer>>(); + + // handler, range nodes + private Map<Integer, Set<Integer>> mapExceptionRanges = new HashMap<Integer, Set<Integer>>(); + + // handler, head dom + private Map<Integer, Integer> mapExceptionDoms = new HashMap<Integer, Integer>(); + + // statement, handler, exit nodes + private Map<Integer, Map<Integer, Integer>> mapExceptionRangeUniqueExit = new HashMap<Integer, Map<Integer, Integer>>(); + + private DominatorEngine domEngine; + + public DominatorTreeExceptionFilter(Statement statement) { + this.statement = statement; + } + + public void initialize() { + + domEngine = new DominatorEngine(statement); + domEngine.initialize(); + + buildDominatorTree(); + + buildExceptionRanges(); + + buildFilter(statement.getFirst().id); + + // free resources + mapTreeBranches.clear(); + mapExceptionRanges.clear(); + } + + public boolean acceptStatementPair(Integer head, Integer exit) { + + Map<Integer, Integer> filter = mapExceptionRangeUniqueExit.get(head); + for (Entry<Integer, Integer> entry : filter.entrySet()) { + if (!head.equals(mapExceptionDoms.get(entry.getKey()))) { + Integer filterExit = entry.getValue(); + if (filterExit.intValue() == -1 || !filterExit.equals(exit)) { + return false; + } + } + } + + return true; + } + + private void buildDominatorTree() { + + VBStyleCollection<Integer, Integer> orderedIDoms = domEngine.getOrderedIDoms(); + + List<Integer> lstKeys = orderedIDoms.getLstKeys(); + for (int index = lstKeys.size() - 1; index >= 0; index--) { + Integer key = lstKeys.get(index); + Integer idom = orderedIDoms.get(index); + + Set<Integer> set = mapTreeBranches.get(idom); + if (set == null) { + mapTreeBranches.put(idom, set = new HashSet<Integer>()); + } + set.add(key); + } + + Integer firstid = statement.getFirst().id; + mapTreeBranches.get(firstid).remove(firstid); + } + + private void buildExceptionRanges() { + + for (Statement stat : statement.getStats()) { + List<Statement> lstPreds = stat.getNeighbours(StatEdge.TYPE_EXCEPTION, Statement.DIRECTION_BACKWARD); + if (!lstPreds.isEmpty()) { + + Set<Integer> set = new HashSet<Integer>(); + + for (Statement st : lstPreds) { + set.add(st.id); + } + + mapExceptionRanges.put(stat.id, set); + } + } + + mapExceptionDoms = buildExceptionDoms(statement.getFirst().id); + } + + private Map<Integer, Integer> buildExceptionDoms(Integer id) { + + Map<Integer, Integer> map = new HashMap<Integer, Integer>(); + + Set<Integer> children = mapTreeBranches.get(id); + if (children != null) { + for (Integer childid : children) { + Map<Integer, Integer> mapChild = buildExceptionDoms(childid); + for (Integer handler : mapChild.keySet()) { + map.put(handler, map.containsKey(handler) ? id : mapChild.get(handler)); + } + } + } + + for (Entry<Integer, Set<Integer>> entry : mapExceptionRanges.entrySet()) { + if (entry.getValue().contains(id)) { + map.put(entry.getKey(), id); + } + } + + return map; + } + + + private void buildFilter(Integer id) { + + Map<Integer, Integer> map = new HashMap<Integer, Integer>(); + + Set<Integer> children = mapTreeBranches.get(id); + if (children != null) { + for (Integer childid : children) { + + buildFilter(childid); + + Map<Integer, Integer> mapChild = mapExceptionRangeUniqueExit.get(childid); + + for (Entry<Integer, Set<Integer>> entry : mapExceptionRanges.entrySet()) { + + Integer handler = entry.getKey(); + Set<Integer> range = entry.getValue(); + + if (range.contains(id)) { + + Integer exit = null; + + if (!range.contains(childid)) { + exit = childid; + } + else { + // exit = map.containsKey(handler)?-1:mapChild.get(handler); FIXME: Eclipse bug? + exit = map.containsKey(handler) ? new Integer(-1) : mapChild.get(handler); + } + + if (exit != null) { + map.put(handler, exit); + } + } + } + } + } + + mapExceptionRangeUniqueExit.put(id, map); + } + + public DominatorEngine getDomEngine() { + return domEngine; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/FastExtendedPostdominanceHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/FastExtendedPostdominanceHelper.java new file mode 100644 index 000000000000..f029016e5efe --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/FastExtendedPostdominanceHelper.java @@ -0,0 +1,355 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.decompose; + +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.util.FastFixedSetFactory; +import org.jetbrains.java.decompiler.util.FastFixedSetFactory.FastFixedSet; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.*; +import java.util.Map.Entry; + +public class FastExtendedPostdominanceHelper { + + private List<Statement> lstReversePostOrderList; + + private HashMap<Integer, FastFixedSet<Integer>> mapSupportPoints = new HashMap<Integer, FastFixedSet<Integer>>(); + + private HashMap<Integer, FastFixedSet<Integer>> mapExtPostdominators = new HashMap<Integer, FastFixedSet<Integer>>(); + + private Statement statement; + + private FastFixedSetFactory<Integer> factory; + + public HashMap<Integer, Set<Integer>> getExtendedPostdominators(Statement statement) { + + this.statement = statement; + + HashSet<Integer> set = new HashSet<Integer>(); + for (Statement st : statement.getStats()) { + set.add(st.id); + } + this.factory = new FastFixedSetFactory<Integer>(set); + + lstReversePostOrderList = statement.getReversePostOrderList(); + + // try { + // DotExporter.toDotFile(statement, new File("c:\\Temp\\stat1.dot")); + // } catch (Exception ex) { + // ex.printStackTrace(); + // } + + calcDefaultReachableSets(); + + removeErroneousNodes(); + + DominatorTreeExceptionFilter filter = new DominatorTreeExceptionFilter(statement); + filter.initialize(); + + filterOnExceptionRanges(filter); + + filterOnDominance(filter); + + HashMap<Integer, Set<Integer>> res = new HashMap<Integer, Set<Integer>>(); + for (Entry<Integer, FastFixedSet<Integer>> entry : mapExtPostdominators.entrySet()) { + res.put(entry.getKey(), entry.getValue().toPlainSet()); + } + + return res; + } + + + private void filterOnDominance(DominatorTreeExceptionFilter filter) { + + DominatorEngine engine = filter.getDomEngine(); + + for (Integer head : new HashSet<Integer>(mapExtPostdominators.keySet())) { + + FastFixedSet<Integer> setPostdoms = mapExtPostdominators.get(head); + + LinkedList<Statement> stack = new LinkedList<Statement>(); + LinkedList<FastFixedSet<Integer>> stackPath = new LinkedList<FastFixedSet<Integer>>(); + + stack.add(statement.getStats().getWithKey(head)); + stackPath.add(factory.spawnEmptySet()); + + Set<Statement> setVisited = new HashSet<Statement>(); + + while (!stack.isEmpty()) { + + Statement stat = stack.removeFirst(); + FastFixedSet<Integer> path = stackPath.removeFirst(); + + if (setPostdoms.contains(stat.id)) { + path.add(stat.id); + } + + if (path.contains(setPostdoms)) { + continue; + } + + setVisited.add(stat); + + int domflag = 0; + + for (Iterator<Integer> it = setPostdoms.iterator(); it.hasNext(); ) { + Integer post = it.next(); + + if (!path.contains(post)) { + if (domflag == 0) { + domflag = engine.isDominator(stat.id, head) ? 2 : 1; + } + + if (domflag == 1) { // not a dominator + it.remove(); + } + } + } + + for (StatEdge edge : stat.getSuccessorEdges(StatEdge.TYPE_REGULAR)) { + if (!setVisited.contains(edge.getDestination())) { + stack.add(edge.getDestination()); + stackPath.add(path.getCopy()); + } + } + } + + if (setPostdoms.isEmpty()) { + mapExtPostdominators.remove(head); + } + } + } + + + private void filterOnExceptionRanges(DominatorTreeExceptionFilter filter) { + + + for (Integer head : new HashSet<Integer>(mapExtPostdominators.keySet())) { + + FastFixedSet<Integer> set = mapExtPostdominators.get(head); + for (Iterator<Integer> it = set.iterator(); it.hasNext(); ) { + if (!filter.acceptStatementPair(head, it.next())) { + it.remove(); + } + } + if (set.isEmpty()) { + mapExtPostdominators.remove(head); + } + } + } + + + private void removeErroneousNodes() { + + mapSupportPoints = new HashMap<Integer, FastFixedSet<Integer>>(); + + calcReachabilitySuppPoints(StatEdge.TYPE_REGULAR); + + iterateReachability(new IReachabilityAction() { + public boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets) { + + Integer nodeid = node.id; + + FastFixedSet<Integer> setReachability = mapSets.get(nodeid); + List<FastFixedSet<Integer>> lstPredSets = new ArrayList<FastFixedSet<Integer>>(); + + for (StatEdge prededge : node.getPredecessorEdges(StatEdge.TYPE_REGULAR)) { + FastFixedSet<Integer> setPred = mapSets.get(prededge.getSource().id); + if (setPred == null) { + setPred = mapSupportPoints.get(prededge.getSource().id); + } + + // setPred cannot be empty as it is a reachability set + lstPredSets.add(setPred); + } + + for (Integer id : setReachability.toPlainSet()) { + + FastFixedSet<Integer> setReachabilityCopy = setReachability.getCopy(); + + FastFixedSet<Integer> setIntersection = factory.spawnEmptySet(); + boolean isIntersectionInitialized = false; + + for (FastFixedSet<Integer> predset : lstPredSets) { + if (predset.contains(id)) { + if (!isIntersectionInitialized) { + setIntersection.union(predset); + isIntersectionInitialized = true; + } + else { + setIntersection.intersection(predset); + } + } + } + + if (nodeid != id.intValue()) { + setIntersection.add(nodeid); + } + else { + setIntersection.remove(nodeid); + } + + setReachabilityCopy.complement(setIntersection); + + mapExtPostdominators.get(id).complement(setReachabilityCopy); + } + + return false; + } + }, StatEdge.TYPE_REGULAR); + + // exception handlers cannot be postdominator nodes + // TODO: replace with a standard set? + FastFixedSet<Integer> setHandlers = factory.spawnEmptySet(); + boolean handlerfound = false; + + for (Statement stat : statement.getStats()) { + if (stat.getPredecessorEdges(Statement.STATEDGE_DIRECT_ALL).isEmpty() && + !stat.getPredecessorEdges(StatEdge.TYPE_EXCEPTION).isEmpty()) { // exception handler + setHandlers.add(stat.id); + handlerfound = true; + } + } + + if (handlerfound) { + for (FastFixedSet<Integer> set : mapExtPostdominators.values()) { + set.complement(setHandlers); + } + } + } + + + private void calcDefaultReachableSets() { + + int edgetype = StatEdge.TYPE_REGULAR | StatEdge.TYPE_EXCEPTION; + + calcReachabilitySuppPoints(edgetype); + + for (Statement stat : statement.getStats()) { + mapExtPostdominators.put(stat.id, factory.spawnEmptySet()); + } + + iterateReachability(new IReachabilityAction() { + public boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets) { + + Integer nodeid = node.id; + FastFixedSet<Integer> setReachability = mapSets.get(nodeid); + + for (Integer id : setReachability.toPlainSet()) { + mapExtPostdominators.get(id).add(nodeid); + } + + return false; + } + }, edgetype); + } + + + private void calcReachabilitySuppPoints(final int edgetype) { + + iterateReachability(new IReachabilityAction() { + public boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets) { + + // consider to be a support point + for (StatEdge sucedge : node.getAllSuccessorEdges()) { + if ((sucedge.getType() & edgetype) != 0) { + if (mapSets.containsKey(sucedge.getDestination().id)) { + FastFixedSet<Integer> setReachability = mapSets.get(node.id); + + if (!InterpreterUtil.equalObjects(setReachability, mapSupportPoints.get(node.id))) { + mapSupportPoints.put(node.id, setReachability); + return true; + } + } + } + } + + return false; + } + }, edgetype); + } + + private void iterateReachability(IReachabilityAction action, int edgetype) { + + while (true) { + + boolean iterate = false; + + HashMap<Integer, FastFixedSet<Integer>> mapSets = new HashMap<Integer, FastFixedSet<Integer>>(); + + for (Statement stat : lstReversePostOrderList) { + + FastFixedSet<Integer> set = factory.spawnEmptySet(); + set.add(stat.id); + + for (StatEdge prededge : stat.getAllPredecessorEdges()) { + if ((prededge.getType() & edgetype) != 0) { + Statement pred = prededge.getSource(); + + FastFixedSet<Integer> setPred = mapSets.get(pred.id); + if (setPred == null) { + setPred = mapSupportPoints.get(pred.id); + } + + if (setPred != null) { + set.union(setPred); + } + } + } + + mapSets.put(stat.id, set); + + if (action != null) { + iterate |= action.action(stat, mapSets); + } + + // remove reachability information of fully processed nodes (saves memory) + for (StatEdge prededge : stat.getAllPredecessorEdges()) { + if ((prededge.getType() & edgetype) != 0) { + Statement pred = prededge.getSource(); + + if (mapSets.containsKey(pred.id)) { + boolean remstat = true; + for (StatEdge sucedge : pred.getAllSuccessorEdges()) { + if ((sucedge.getType() & edgetype) != 0) { + if (!mapSets.containsKey(sucedge.getDestination().id)) { + remstat = false; + break; + } + } + } + + if (remstat) { + mapSets.put(pred.id, null); + } + } + } + } + } + + if (!iterate) { + break; + } + } + } + + + private interface IReachabilityAction { + boolean action(Statement node, HashMap<Integer, FastFixedSet<Integer>> mapSets); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/GenericDominatorEngine.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/GenericDominatorEngine.java new file mode 100644 index 000000000000..c6eb35722eb6 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/GenericDominatorEngine.java @@ -0,0 +1,152 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.decompose; + +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.List; +import java.util.Set; + +public class GenericDominatorEngine { + + private IGraph graph; + + private VBStyleCollection<IGraphNode, IGraphNode> colOrderedIDoms = new VBStyleCollection<IGraphNode, IGraphNode>(); + + private Set<? extends IGraphNode> setRoots; + + public GenericDominatorEngine(IGraph graph) { + this.graph = graph; + } + + public void initialize() { + calcIDoms(); + } + + private void orderNodes() { + + setRoots = graph.getRoots(); + + for (IGraphNode node : graph.getReversePostOrderList()) { + colOrderedIDoms.addWithKey(null, node); + } + } + + private static IGraphNode getCommonIDom(IGraphNode node1, IGraphNode node2, VBStyleCollection<IGraphNode, IGraphNode> orderedIDoms) { + + IGraphNode nodeOld; + + if (node1 == null) { + return node2; + } + else if (node2 == null) { + return node1; + } + + int index1 = orderedIDoms.getIndexByKey(node1); + int index2 = orderedIDoms.getIndexByKey(node2); + + while (index1 != index2) { + if (index1 > index2) { + nodeOld = node1; + node1 = orderedIDoms.getWithKey(node1); + + if (nodeOld == node1) { // no idom - root or merging point + return null; + } + + index1 = orderedIDoms.getIndexByKey(node1); + } + else { + nodeOld = node2; + node2 = orderedIDoms.getWithKey(node2); + + if (nodeOld == node2) { // no idom - root or merging point + return null; + } + + index2 = orderedIDoms.getIndexByKey(node2); + } + } + + return node1; + } + + private void calcIDoms() { + + orderNodes(); + + List<IGraphNode> lstNodes = colOrderedIDoms.getLstKeys(); + + while (true) { + + boolean changed = false; + + for (IGraphNode node : lstNodes) { + + IGraphNode idom = null; + + if (!setRoots.contains(node)) { + for (IGraphNode pred : node.getPredecessors()) { + if (colOrderedIDoms.getWithKey(pred) != null) { + idom = getCommonIDom(idom, pred, colOrderedIDoms); + if (idom == null) { + break; // no idom found: merging point of two trees + } + } + } + } + + if (idom == null) { + idom = node; + } + + IGraphNode oldidom = colOrderedIDoms.putWithKey(idom, node); + if (!idom.equals(oldidom)) { // oldidom is null iff the node is touched for the first time + changed = true; + } + } + + if (!changed) { + break; + } + } + } + + public VBStyleCollection<IGraphNode, IGraphNode> getOrderedIDoms() { + return colOrderedIDoms; + } + + public boolean isDominator(IGraphNode node, IGraphNode dom) { + + while (!node.equals(dom)) { + + IGraphNode idom = colOrderedIDoms.getWithKey(node); + + if (idom == node) { + return false; // root node or merging point + } + else if (idom == null) { + throw new RuntimeException("Inconsistent idom sequence discovered!"); + } + else { + node = idom; + } + } + + return true; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/IGraph.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/IGraph.java new file mode 100644 index 000000000000..faaf4c6b66cf --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/IGraph.java @@ -0,0 +1,26 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.decompose; + +import java.util.List; +import java.util.Set; + +public interface IGraph { + + List<? extends IGraphNode> getReversePostOrderList(); + + Set<? extends IGraphNode> getRoots(); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/IGraphNode.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/IGraphNode.java new file mode 100644 index 000000000000..19d59b5acb32 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/decompose/IGraphNode.java @@ -0,0 +1,23 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.decompose; + +import java.util.List; + +public interface IGraphNode { + + List<? extends IGraphNode> getPredecessors(); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/deobfuscator/ExceptionDeobfuscator.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/deobfuscator/ExceptionDeobfuscator.java new file mode 100644 index 000000000000..7614807c99a4 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/deobfuscator/ExceptionDeobfuscator.java @@ -0,0 +1,330 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.deobfuscator; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.code.InstructionSequence; +import org.jetbrains.java.decompiler.code.SimpleInstructionSequence; +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.code.cfg.ControlFlowGraph; +import org.jetbrains.java.decompiler.code.cfg.ExceptionRangeCFG; +import org.jetbrains.java.decompiler.modules.decompiler.decompose.GenericDominatorEngine; +import org.jetbrains.java.decompiler.modules.decompiler.decompose.IGraph; +import org.jetbrains.java.decompiler.modules.decompiler.decompose.IGraphNode; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.*; +import java.util.Map.Entry; + +public class ExceptionDeobfuscator { + + private static class Range { + private final BasicBlock handler; + private final String uniqueStr; + private final Set<BasicBlock> protectedRange; + private final ExceptionRangeCFG rangeCFG; + + private Range(BasicBlock handler, String uniqueStr, Set<BasicBlock> protectedRange, ExceptionRangeCFG rangeCFG) { + this.handler = handler; + this.uniqueStr = uniqueStr; + this.protectedRange = protectedRange; + this.rangeCFG = rangeCFG; + } + } + + public static void restorePopRanges(ControlFlowGraph graph) { + + List<Range> lstRanges = new ArrayList<Range>(); + + // aggregate ranges + for (ExceptionRangeCFG range : graph.getExceptions()) { + boolean found = false; + for (Range arr : lstRanges) { + if (arr.handler == range.getHandler() && InterpreterUtil.equalObjects(range.getUniqueExceptionsString(), arr.uniqueStr)) { + arr.protectedRange.addAll(range.getProtectedRange()); + found = true; + break; + } + } + + if (!found) { + // doesn't matter, which range chosen + lstRanges.add(new Range(range.getHandler(), range.getUniqueExceptionsString(), new HashSet<BasicBlock>(range.getProtectedRange()), range)); + } + } + + // process aggregated ranges + for (Range range : lstRanges) { + + if (range.uniqueStr != null) { + + BasicBlock handler = range.handler; + InstructionSequence seq = handler.getSeq(); + + Instruction firstinstr; + if (seq.length() > 0) { + firstinstr = seq.getInstr(0); + + if (firstinstr.opcode == CodeConstants.opc_pop || + firstinstr.opcode == CodeConstants.opc_astore) { + Set<BasicBlock> setrange = new HashSet<BasicBlock>(range.protectedRange); + + for (Range range_super : lstRanges) { // finally or strict superset + + if (range != range_super) { + + Set<BasicBlock> setrange_super = new HashSet<BasicBlock>(range_super.protectedRange); + + if (!setrange.contains(range_super.handler) && !setrange_super.contains(handler) + && (range_super.uniqueStr == null || setrange_super.containsAll(setrange))) { + + if (range_super.uniqueStr == null) { + setrange_super.retainAll(setrange); + } + else { + setrange_super.removeAll(setrange); + } + + if (!setrange_super.isEmpty()) { + + BasicBlock newblock = handler; + + // split the handler + if (seq.length() > 1) { + newblock = new BasicBlock(++graph.last_id); + InstructionSequence newseq = new SimpleInstructionSequence(); + newseq.addInstruction(firstinstr.clone(), -1); + + newblock.setSeq(newseq); + graph.getBlocks().addWithKey(newblock, newblock.id); + + + List<BasicBlock> lstTemp = new ArrayList<BasicBlock>(); + lstTemp.addAll(handler.getPreds()); + lstTemp.addAll(handler.getPredExceptions()); + + // replace predecessors + for (BasicBlock pred : lstTemp) { + pred.replaceSuccessor(handler, newblock); + } + + // replace handler + for (ExceptionRangeCFG range_ext : graph.getExceptions()) { + if (range_ext.getHandler() == handler) { + range_ext.setHandler(newblock); + } + else if (range_ext.getProtectedRange().contains(handler)) { + newblock.addSuccessorException(range_ext.getHandler()); + range_ext.getProtectedRange().add(newblock); + } + } + + newblock.addSuccessor(handler); + if (graph.getFirst() == handler) { + graph.setFirst(newblock); + } + + // remove the first pop in the handler + seq.removeInstruction(0); + } + + newblock.addSuccessorException(range_super.handler); + range_super.rangeCFG.getProtectedRange().add(newblock); + + handler = range.rangeCFG.getHandler(); + seq = handler.getSeq(); + } + } + } + } + } + } + } + } + } + + public static void insertEmptyExceptionHandlerBlocks(ControlFlowGraph graph) { + + Set<BasicBlock> setVisited = new HashSet<BasicBlock>(); + + for (ExceptionRangeCFG range : graph.getExceptions()) { + BasicBlock handler = range.getHandler(); + + if (setVisited.contains(handler)) { + continue; + } + setVisited.add(handler); + + BasicBlock emptyblock = new BasicBlock(++graph.last_id); + graph.getBlocks().addWithKey(emptyblock, emptyblock.id); + + List<BasicBlock> lstTemp = new ArrayList<BasicBlock>(); + // only exception predecessors considered + lstTemp.addAll(handler.getPredExceptions()); + + // replace predecessors + for (BasicBlock pred : lstTemp) { + pred.replaceSuccessor(handler, emptyblock); + } + + // replace handler + for (ExceptionRangeCFG range_ext : graph.getExceptions()) { + if (range_ext.getHandler() == handler) { + range_ext.setHandler(emptyblock); + } + else if (range_ext.getProtectedRange().contains(handler)) { + emptyblock.addSuccessorException(range_ext.getHandler()); + range_ext.getProtectedRange().add(emptyblock); + } + } + + emptyblock.addSuccessor(handler); + if (graph.getFirst() == handler) { + graph.setFirst(emptyblock); + } + } + } + + public static void removeEmptyRanges(ControlFlowGraph graph) { + + List<ExceptionRangeCFG> lstRanges = graph.getExceptions(); + for (int i = lstRanges.size() - 1; i >= 0; i--) { + ExceptionRangeCFG range = lstRanges.get(i); + + boolean isEmpty = true; + for (BasicBlock block : range.getProtectedRange()) { + if (!block.getSeq().isEmpty()) { + isEmpty = false; + break; + } + } + + if (isEmpty) { + for (BasicBlock block : range.getProtectedRange()) { + block.removeSuccessorException(range.getHandler()); + } + + lstRanges.remove(i); + } + } + } + + public static void removeCircularRanges(final ControlFlowGraph graph) { + + GenericDominatorEngine engine = new GenericDominatorEngine(new IGraph() { + public List<? extends IGraphNode> getReversePostOrderList() { + return graph.getReversePostOrder(); + } + + public Set<? extends IGraphNode> getRoots() { + return new HashSet<IGraphNode>(Arrays.asList(new IGraphNode[]{graph.getFirst()})); + } + }); + + engine.initialize(); + + List<ExceptionRangeCFG> lstRanges = graph.getExceptions(); + for (int i = lstRanges.size() - 1; i >= 0; i--) { + ExceptionRangeCFG range = lstRanges.get(i); + + BasicBlock handler = range.getHandler(); + List<BasicBlock> rangeList = range.getProtectedRange(); + + if (rangeList.contains(handler)) { // TODO: better removing strategy + + List<BasicBlock> lstRemBlocks = getReachableBlocksRestricted(range, engine); + + if (lstRemBlocks.size() < rangeList.size() || rangeList.size() == 1) { + for (BasicBlock block : lstRemBlocks) { + block.removeSuccessorException(handler); + rangeList.remove(block); + } + } + + if (rangeList.isEmpty()) { + lstRanges.remove(i); + } + } + } + } + + private static List<BasicBlock> getReachableBlocksRestricted(ExceptionRangeCFG range, GenericDominatorEngine engine) { + + List<BasicBlock> lstRes = new ArrayList<BasicBlock>(); + + LinkedList<BasicBlock> stack = new LinkedList<BasicBlock>(); + Set<BasicBlock> setVisited = new HashSet<BasicBlock>(); + + BasicBlock handler = range.getHandler(); + stack.addFirst(handler); + + while (!stack.isEmpty()) { + BasicBlock block = stack.removeFirst(); + + setVisited.add(block); + + if (range.getProtectedRange().contains(block) && engine.isDominator(block, handler)) { + lstRes.add(block); + + List<BasicBlock> lstSuccs = new ArrayList<BasicBlock>(block.getSuccs()); + lstSuccs.addAll(block.getSuccExceptions()); + + for (BasicBlock succ : lstSuccs) { + if (!setVisited.contains(succ)) { + stack.add(succ); + } + } + } + } + + return lstRes; + } + + + public static boolean hasObfuscatedExceptions(ControlFlowGraph graph) { + + Map<BasicBlock, Set<BasicBlock>> mapRanges = new HashMap<BasicBlock, Set<BasicBlock>>(); + for (ExceptionRangeCFG range : graph.getExceptions()) { + Set<BasicBlock> set = mapRanges.get(range.getHandler()); + if (set == null) { + mapRanges.put(range.getHandler(), set = new HashSet<BasicBlock>()); + } + set.addAll(range.getProtectedRange()); + } + + for (Entry<BasicBlock, Set<BasicBlock>> ent : mapRanges.entrySet()) { + Set<BasicBlock> setEntries = new HashSet<BasicBlock>(); + + for (BasicBlock block : ent.getValue()) { + Set<BasicBlock> setTemp = new HashSet<BasicBlock>(block.getPreds()); + setTemp.removeAll(ent.getValue()); + + if (!setTemp.isEmpty()) { + setEntries.add(block); + } + } + + if (!setEntries.isEmpty()) { + if (setEntries.size() > 1 /*|| ent.getValue().contains(first)*/) { + return true; + } + } + } + + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/deobfuscator/IrreducibleCFGDeobfuscator.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/deobfuscator/IrreducibleCFGDeobfuscator.java new file mode 100644 index 000000000000..31e171e214d5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/deobfuscator/IrreducibleCFGDeobfuscator.java @@ -0,0 +1,245 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.deobfuscator; + +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.stats.BasicBlockStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + + +public class IrreducibleCFGDeobfuscator { + + + public static boolean isStatementIrreducible(Statement statement) { + + class Node { + public Integer id; + public Set<Node> preds = new HashSet<Node>(); + public Set<Node> succs = new HashSet<Node>(); + + public Node(Integer id) { + this.id = id; + } + } + + HashMap<Integer, Node> mapNodes = new HashMap<Integer, Node>(); + + // checking exceptions and creating nodes + for (Statement stat : statement.getStats()) { + if (!stat.getSuccessorEdges(StatEdge.TYPE_EXCEPTION).isEmpty()) { + return false; + } + + mapNodes.put(stat.id, new Node(stat.id)); + } + + // connecting nodes + for (Statement stat : statement.getStats()) { + Node node = mapNodes.get(stat.id); + + for (Statement succ : stat.getNeighbours(StatEdge.TYPE_REGULAR, Statement.DIRECTION_FORWARD)) { + Node nodeSucc = mapNodes.get(succ.id); + + node.succs.add(nodeSucc); + nodeSucc.preds.add(node); + } + } + + // transforming and reducing the graph + while (true) { + int ttype = 0; + Node node = null; + + for (Node nd : mapNodes.values()) { + if (nd.succs.contains(nd)) { // T1 + ttype = 1; + } + else if (nd.preds.size() == 1) { // T2 + ttype = 2; + } + + if (ttype != 0) { + node = nd; + break; + } + } + + if (node != null) { + if (ttype == 1) { + node.succs.remove(node); + node.preds.remove(node); + } + else { + Node pred = node.preds.iterator().next(); + + pred.succs.addAll(node.succs); + pred.succs.remove(node); + + for (Node succ : node.succs) { + succ.preds.remove(node); + succ.preds.add(pred); + } + + mapNodes.remove(node.id); + } + } + else { // no transformation applicable + return mapNodes.size() > 1; // reducible iff one node remains + } + } + } + + + private static Statement getCandidateForSplitting(Statement statement) { + + Statement candidateForSplitting = null; + int sizeCandidateForSplitting = Integer.MAX_VALUE; + int succsCandidateForSplitting = Integer.MAX_VALUE; + + for (Statement stat : statement.getStats()) { + + Set<Statement> setPreds = stat.getNeighboursSet(StatEdge.TYPE_REGULAR, Statement.DIRECTION_BACKWARD); + + if (setPreds.size() > 1) { + int succCount = stat.getNeighboursSet(StatEdge.TYPE_REGULAR, Statement.DIRECTION_FORWARD).size(); + if (succCount <= succsCandidateForSplitting) { + int size = getStatementSize(stat) * (setPreds.size() - 1); + + if (succCount < succsCandidateForSplitting || + size < sizeCandidateForSplitting) { + candidateForSplitting = stat; + sizeCandidateForSplitting = size; + succsCandidateForSplitting = succCount; + } + } + } + } + + return candidateForSplitting; + } + + public static boolean splitIrreducibleNode(Statement statement) { + + Statement splitnode = getCandidateForSplitting(statement); + if (splitnode == null) { + return false; + } + + StatEdge enteredge = splitnode.getPredecessorEdges(StatEdge.TYPE_REGULAR).iterator().next(); + + // copy the smallest statement + Statement splitcopy = copyStatement(splitnode, null, new HashMap<Statement, Statement>()); + initCopiedStatement(splitcopy); + + // insert the copy + splitcopy.setParent(statement); + statement.getStats().addWithKey(splitcopy, splitcopy.id); + + // switch input edges + for (StatEdge prededge : splitnode.getPredecessorEdges(Statement.STATEDGE_DIRECT_ALL)) { + if (prededge.getSource() == enteredge.getSource() || + prededge.closure == enteredge.getSource()) { + splitnode.removePredecessor(prededge); + prededge.getSource().changeEdgeNode(Statement.DIRECTION_FORWARD, prededge, splitcopy); + splitcopy.addPredecessor(prededge); + } + } + + // connect successors + for (StatEdge succ : splitnode.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL)) { + splitcopy.addSuccessor(new StatEdge(succ.getType(), splitcopy, succ.getDestination(), succ.closure)); + } + + return true; + } + + private static int getStatementSize(Statement statement) { + + int res = 0; + + if (statement.type == Statement.TYPE_BASICBLOCK) { + res = ((BasicBlockStatement)statement).getBlock().getSeq().length(); + } + else { + for (Statement stat : statement.getStats()) { + res += getStatementSize(stat); + } + } + + return res; + } + + private static Statement copyStatement(Statement from, Statement to, HashMap<Statement, Statement> mapAltToCopies) { + + if (to == null) { + // first outer invocation + to = from.getSimpleCopy(); + mapAltToCopies.put(from, to); + } + + // copy statements + for (Statement st : from.getStats()) { + Statement stcopy = st.getSimpleCopy(); + + to.getStats().addWithKey(stcopy, stcopy.id); + mapAltToCopies.put(st, stcopy); + } + + // copy edges + for (int i = 0; i < from.getStats().size(); i++) { + Statement stold = from.getStats().get(i); + Statement stnew = to.getStats().get(i); + + for (StatEdge edgeold : stold.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL)) { + // type cannot be TYPE_EXCEPTION (checked in isIrreducibleTriangle) + StatEdge edgenew = new StatEdge(edgeold.getType(), stnew, + mapAltToCopies.containsKey(edgeold.getDestination()) + ? mapAltToCopies.get(edgeold.getDestination()) + : edgeold.getDestination(), + mapAltToCopies.containsKey(edgeold.closure) + ? mapAltToCopies.get(edgeold.closure) + : edgeold.closure); + + stnew.addSuccessor(edgenew); + } + } + + // recurse statements + for (int i = 0; i < from.getStats().size(); i++) { + Statement stold = from.getStats().get(i); + Statement stnew = to.getStats().get(i); + + copyStatement(stold, stnew, mapAltToCopies); + } + + return to; + } + + private static void initCopiedStatement(Statement statement) { + + statement.initSimpleCopy(); + statement.setCopied(true); + + for (Statement st : statement.getStats()) { + st.setParent(statement); + initCopiedStatement(st); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AnnotationExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AnnotationExprent.java new file mode 100644 index 000000000000..9383d76559a5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AnnotationExprent.java @@ -0,0 +1,114 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.List; + + +public class AnnotationExprent extends Exprent { + + public static final int ANNOTATION_NORMAL = 1; + public static final int ANNOTATION_MARKER = 2; + public static final int ANNOTATION_SINGLE_ELEMENT = 3; + + + private String classname; + + private List<String> parnames; + + private List<Exprent> parvalues; + + { + this.type = EXPRENT_ANNOTATION; + } + + public AnnotationExprent(String classname, List<String> parnames, List<Exprent> parvalues) { + this.classname = classname; + this.parnames = parnames; + this.parvalues = parvalues; + } + + public String toJava(int indent) { + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buffer = new StringBuilder(); + String indstr = InterpreterUtil.getIndentString(indent); + + buffer.append(indstr); + buffer.append("@"); + buffer.append(DecompilerContext.getImportCollector().getShortName(ExprProcessor.buildJavaClassName(classname))); + + if (!parnames.isEmpty()) { + buffer.append("("); + if (parnames.size() == 1 && "value".equals(parnames.get(0))) { + buffer.append(parvalues.get(0).toJava(indent + 1)); + } + else { + String indstr1 = InterpreterUtil.getIndentString(indent + 1); + + for (int i = 0; i < parnames.size(); i++) { + buffer.append(new_line_separator).append(indstr1); + buffer.append(parnames.get(i)); + buffer.append(" = "); + buffer.append(parvalues.get(i).toJava(indent + 2)); + + if (i < parnames.size() - 1) { + buffer.append(","); + } + } + buffer.append(new_line_separator).append(indstr); + } + + buffer.append(")"); + } + + return buffer.toString(); + } + + public int getAnnotationType() { + + if (parnames.isEmpty()) { + return ANNOTATION_MARKER; + } + else { + if (parnames.size() == 1 && "value".equals(parnames.get(0))) { + return ANNOTATION_SINGLE_ELEMENT; + } + else { + return ANNOTATION_NORMAL; + } + } + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof AnnotationExprent)) return false; + + AnnotationExprent ann = (AnnotationExprent)o; + return classname.equals(ann.classname) && + InterpreterUtil.equalLists(parnames, ann.parnames) && + InterpreterUtil.equalLists(parvalues, ann.parvalues); + } + + public String getClassname() { + return classname; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ArrayExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ArrayExprent.java new file mode 100644 index 000000000000..e5ead9d7c184 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ArrayExprent.java @@ -0,0 +1,126 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class ArrayExprent extends Exprent { + + private Exprent array; + + private Exprent index; + + private VarType hardtype; + + { + this.type = EXPRENT_ARRAY; + } + + public ArrayExprent(Exprent array, Exprent index, VarType hardtype) { + this.array = array; + this.index = index; + this.hardtype = hardtype; + } + + public Exprent copy() { + return new ArrayExprent(array.copy(), index.copy(), hardtype); + } + + public VarType getExprType() { + VarType exprType = array.getExprType().copy(); + if (exprType.equals(VarType.VARTYPE_NULL)) { + exprType = hardtype.copy(); + } + else { + exprType.decArrayDim(); + } + + return exprType; + } + + public int getExprentUse() { + return array.getExprentUse() & index.getExprentUse() & Exprent.MULTIPLE_USES; + } + + public CheckTypesResult checkExprTypeBounds() { + CheckTypesResult result = new CheckTypesResult(); + + result.addMinTypeExprent(index, VarType.VARTYPE_BYTECHAR); + result.addMaxTypeExprent(index, VarType.VARTYPE_INT); + + return result; + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + lst.add(array); + lst.add(index); + return lst; + } + + + public String toJava(int indent) { + String res = array.toJava(indent); + + if (array.getPrecedence() > getPrecedence()) { // array precedence equals 0 + res = "(" + res + ")"; + } + + VarType arrtype = array.getExprType(); + if (arrtype.arraydim == 0) { + VarType objarr = VarType.VARTYPE_OBJECT.copy(); + objarr.arraydim = 1; // type family does not change + + res = "((" + ExprProcessor.getCastTypeName(objarr) + ")" + res + ")"; + } + + return res + "[" + index.toJava(indent) + "]"; + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof ArrayExprent)) return false; + + ArrayExprent arr = (ArrayExprent)o; + return InterpreterUtil.equalObjects(array, arr.getArray()) && + InterpreterUtil.equalObjects(index, arr.getIndex()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == array) { + array = newexpr; + } + + if (oldexpr == index) { + index = newexpr; + } + } + + public Exprent getArray() { + return array; + } + + public Exprent getIndex() { + return index; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AssertExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AssertExprent.java new file mode 100644 index 000000000000..0983dad0cd9d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AssertExprent.java @@ -0,0 +1,51 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import java.util.List; + +public class AssertExprent extends Exprent { + + private List<Exprent> parameters; + + { + this.type = EXPRENT_ASSERT; + } + + public AssertExprent(List<Exprent> parameters) { + this.parameters = parameters; + } + + public String toJava(int indent) { + + StringBuilder buffer = new StringBuilder(); + + buffer.append("assert "); + + if (parameters.get(0) == null) { + buffer.append("false"); + } + else { + buffer.append(parameters.get(0).toJava(indent)); + } + if (parameters.size() > 1) { + buffer.append(" : "); + buffer.append(parameters.get(1).toJava(indent)); + } + + return buffer.toString(); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AssignmentExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AssignmentExprent.java new file mode 100644 index 000000000000..8ff9fe5a448a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/AssignmentExprent.java @@ -0,0 +1,204 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class AssignmentExprent extends Exprent { + + public static final int CONDITION_NONE = -1; + + private static final String[] funceq = new String[]{ + " += ", // FUNCTION_ADD + " -= ", // FUNCTION_SUB + " *= ", // FUNCTION_MUL + " /= ", // FUNCTION_DIV + " &= ", // FUNCTION_AND + " |= ", // FUNCTION_OR + " ^= ", // FUNCTION_XOR + " %= ", // FUNCTION_REM + " <<= ", // FUNCTION_SHL + " >>= ", // FUNCTION_SHR + " >>>= " // FUNCTION_USHR + }; + + + private Exprent left; + + private Exprent right; + + private int condtype = CONDITION_NONE; + + { + this.type = EXPRENT_ASSIGNMENT; + } + + + public AssignmentExprent(Exprent left, Exprent right) { + this.left = left; + this.right = right; + } + + + public VarType getExprType() { + return left.getExprType(); + } + + + public CheckTypesResult checkExprTypeBounds() { + CheckTypesResult result = new CheckTypesResult(); + + VarType typeleft = left.getExprType(); + VarType typeright = right.getExprType(); + + if (typeleft.type_family > typeright.type_family) { + result.addMinTypeExprent(right, VarType.getMinTypeInFamily(typeleft.type_family)); + } + else if (typeleft.type_family < typeright.type_family) { + result.addMinTypeExprent(left, typeright); + } + else { + result.addMinTypeExprent(left, VarType.getCommonSupertype(typeleft, typeright)); + } + + return result; + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + lst.add(left); + lst.add(right); + return lst; + } + + public Exprent copy() { + return new AssignmentExprent(left.copy(), right.copy()); + } + + public int getPrecedence() { + return 13; + } + + public String toJava(int indent) { + VarType leftType = left.getExprType(); + VarType rightType = right.getExprType(); + + boolean fieldInClassInit = false, hiddenField = false; + if (left.type == Exprent.EXPRENT_FIELD) { // first assignment to a final field. Field name without "this" in front of it + FieldExprent field = (FieldExprent)left; + ClassNode node = ((ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE)); + if (node != null) { + StructField fd = node.classStruct.getField(field.getName(), field.getDescriptor().descriptorString); + if (fd != null) { + if (field.isStatic() && fd.hasModifier(CodeConstants.ACC_FINAL)) { + fieldInClassInit = true; + } + if (node.wrapper.getHiddenMembers().contains(InterpreterUtil.makeUniqueKey(fd.getName(), fd.getDescriptor()))) { + hiddenField = true; + } + } + } + } + + if (hiddenField) { + return ""; + } + + StringBuilder buffer = new StringBuilder(); + + if (fieldInClassInit) { + buffer.append(((FieldExprent)left).getName()); + } + else { + buffer.append(left.toJava(indent)); + } + + String res = right.toJava(indent); + + if (condtype == CONDITION_NONE && + !leftType.isSuperset(rightType) && + (rightType.equals(VarType.VARTYPE_OBJECT) || leftType.type != CodeConstants.TYPE_OBJECT)) { + if (right.getPrecedence() >= FunctionExprent.getPrecedence(FunctionExprent.FUNCTION_CAST)) { + res = "(" + res + ")"; + } + + res = "(" + ExprProcessor.getCastTypeName(leftType) + ")" + res; + } + + buffer.append(condtype == CONDITION_NONE ? " = " : funceq[condtype]).append(res); + + return buffer.toString(); + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof AssignmentExprent)) return false; + + AssignmentExprent as = (AssignmentExprent)o; + return InterpreterUtil.equalObjects(left, as.getLeft()) && + InterpreterUtil.equalObjects(right, as.getRight()) && + condtype == as.getCondtype(); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == left) { + left = newexpr; + } + + if (oldexpr == right) { + right = newexpr; + } + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public Exprent getLeft() { + return left; + } + + public void setLeft(Exprent left) { + this.left = left; + } + + public Exprent getRight() { + return right; + } + + public void setRight(Exprent right) { + this.right = right; + } + + public int getCondtype() { + return condtype; + } + + public void setCondtype(int condtype) { + this.condtype = condtype; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ConstExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ConstExprent.java new file mode 100644 index 000000000000..a45429a85803 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ConstExprent.java @@ -0,0 +1,402 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class ConstExprent extends Exprent { + private static final HashMap<Integer, String> escapes = new HashMap<Integer, String>(); + + static { + escapes.put(new Integer(0x8), "\\b"); /* \u0008: backspace BS */ + escapes.put(new Integer(0x9), "\\t"); /* \u0009: horizontal tab HT */ + escapes.put(new Integer(0xA), "\\n"); /* \u000a: linefeed LF */ + escapes.put(new Integer(0xC), "\\f"); /* \u000c: form feed FF */ + escapes.put(new Integer(0xD), "\\r"); /* \u000d: carriage return CR */ + escapes.put(new Integer(0x22), "\\\""); /* \u0022: double quote " */ + escapes.put(new Integer(0x27), "\\\'"); /* \u0027: single quote ' */ + escapes.put(new Integer(0x5C), "\\\\"); /* \u005c: backslash \ */ + } + + + private VarType consttype; + + private Object value; + + private boolean boolPermitted; + + { + this.type = EXPRENT_CONST; + } + + public ConstExprent(int val, boolean boolPermitted) { + + this.boolPermitted = boolPermitted; + if (boolPermitted) { + consttype = VarType.VARTYPE_BOOLEAN; + if (val != 0 && val != 1) { + consttype = consttype.copy(); + consttype.convinfo |= VarType.FALSEBOOLEAN; + } + } + else { + if (0 <= val && val <= 127) { + consttype = VarType.VARTYPE_BYTECHAR; + } + else if (-128 <= val && val <= 127) { + consttype = VarType.VARTYPE_BYTE; + } + else if (0 <= val && val <= 32767) { + consttype = VarType.VARTYPE_SHORTCHAR; + } + else if (-32768 <= val && val <= 32767) { + consttype = VarType.VARTYPE_SHORT; + } + else if (0 <= val && val <= 0xFFFF) { + consttype = VarType.VARTYPE_CHAR; + } + else { + consttype = VarType.VARTYPE_INT; + } + } + value = new Integer(val); + } + + public ConstExprent(VarType consttype, Object value) { + this.consttype = consttype; + this.value = value; + } + + public Exprent copy() { + return new ConstExprent(consttype, value); + } + + public VarType getExprType() { + return consttype; + } + + public int getExprentUse() { + return Exprent.MULTIPLE_USES | Exprent.SIDE_EFFECTS_FREE; + } + + public List<Exprent> getAllExprents() { + return new ArrayList<Exprent>(); + } + + public String toJava(int indent) { + boolean literal = DecompilerContext.getOption(IFernflowerPreferences.LITERALS_AS_IS); + boolean ascii = DecompilerContext.getOption(IFernflowerPreferences.ASCII_STRING_CHARACTERS); + + if (consttype.type != CodeConstants.TYPE_NULL && value == null) { + return ExprProcessor.getCastTypeName(consttype); + } + else { + switch (consttype.type) { + case CodeConstants.TYPE_BOOLEAN: + return Boolean.toString(((Integer)value).intValue() != 0); + case CodeConstants.TYPE_CHAR: + Integer val = (Integer)value; + String ret = escapes.get(val); + if (ret == null) { + char c = (char)val.intValue(); + if (c >= 32 && c < 127 || !ascii && InterpreterUtil.isPrintableUnicode(c)) { + ret = String.valueOf(c); + } + else { + ret = InterpreterUtil.charToUnicodeLiteral(c); + } + } + return "\'" + ret + "\'"; + case CodeConstants.TYPE_BYTE: + case CodeConstants.TYPE_BYTECHAR: + case CodeConstants.TYPE_SHORT: + case CodeConstants.TYPE_SHORTCHAR: + case CodeConstants.TYPE_INT: + int ival = ((Integer)value).intValue(); + + String intfield; + if (literal) { + return value.toString(); + } + else if (ival == Integer.MAX_VALUE) { + intfield = "MAX_VALUE"; + } + else if (ival == Integer.MIN_VALUE) { + intfield = "MIN_VALUE"; + } + else { + return value.toString(); + } + return new FieldExprent(intfield, "java/lang/Integer", true, null, FieldDescriptor.INTEGER_DESCRIPTOR).toJava(0); + case CodeConstants.TYPE_LONG: + long lval = ((Long)value).longValue(); + + String longfield; + if (literal) { + return value.toString() + "L"; + } + else if (lval == Long.MAX_VALUE) { + longfield = "MAX_VALUE"; + } + else if (lval == Long.MIN_VALUE) { + longfield = "MIN_VALUE"; + } + else { + return value.toString() + "L"; + } + return new FieldExprent(longfield, "java/lang/Long", true, null, FieldDescriptor.LONG_DESCRIPTOR).toJava(0); + case CodeConstants.TYPE_DOUBLE: + double dval = ((Double)value).doubleValue(); + + String doublefield; + if (literal) { + if (Double.isNaN(dval)) { + return "0.0D / 0.0"; + } + else if (dval == Double.POSITIVE_INFINITY) { + return "1.0D / 0.0"; + } + else if (dval == Double.NEGATIVE_INFINITY) { + return "-1.0D / 0.0"; + } + else { + return value.toString() + "D"; + } + } + else if (Double.isNaN(dval)) { + doublefield = "NaN"; + } + else if (dval == Double.POSITIVE_INFINITY) { + doublefield = "POSITIVE_INFINITY"; + } + else if (dval == Double.NEGATIVE_INFINITY) { + doublefield = "NEGATIVE_INFINITY"; + } + else if (dval == Double.MAX_VALUE) { + doublefield = "MAX_VALUE"; + } + else if (dval == Double.MIN_VALUE) { + doublefield = "MIN_VALUE"; + } + else { + return value.toString() + "D"; + } + return new FieldExprent(doublefield, "java/lang/Double", true, null, FieldDescriptor.DOUBLE_DESCRIPTOR).toJava(0); + case CodeConstants.TYPE_FLOAT: + float fval = ((Float)value).floatValue(); + + String floatfield; + if (literal) { + if (Double.isNaN(fval)) { + return "0.0F / 0.0"; + } + else if (fval == Double.POSITIVE_INFINITY) { + return "1.0F / 0.0"; + } + else if (fval == Double.NEGATIVE_INFINITY) { + return "-1.0F / 0.0"; + } + else { + return value.toString() + "F"; + } + } + else if (Float.isNaN(fval)) { + floatfield = "NaN"; + } + else if (fval == Float.POSITIVE_INFINITY) { + floatfield = "POSITIVE_INFINITY"; + } + else if (fval == Float.NEGATIVE_INFINITY) { + floatfield = "NEGATIVE_INFINITY"; + } + else if (fval == Float.MAX_VALUE) { + floatfield = "MAX_VALUE"; + } + else if (fval == Float.MIN_VALUE) { + floatfield = "MIN_VALUE"; + } + else { + return value.toString() + "F"; + } + return new FieldExprent(floatfield, "java/lang/Float", true, null, FieldDescriptor.FLOAT_DESCRIPTOR).toJava(0); + case CodeConstants.TYPE_NULL: + return "null"; + case CodeConstants.TYPE_OBJECT: + if (consttype.equals(VarType.VARTYPE_STRING)) { + return "\"" + convertStringToJava(value.toString(), ascii) + "\""; + } + else if (consttype.equals(VarType.VARTYPE_CLASS)) { + String strval = value.toString(); + + VarType classtype; + if (strval.startsWith("[")) { // array of simple type + classtype = new VarType(strval, false); + } + else { // class + classtype = new VarType(strval, true); + } + + return ExprProcessor.getCastTypeName(classtype) + ".class"; + } + } + } + + throw new RuntimeException("invalid constant type"); + } + + private static String convertStringToJava(String value, boolean ascii) { + char[] arr = value.toCharArray(); + StringBuilder buffer = new StringBuilder(arr.length); + + for (char c : arr) { + switch (c) { + case '\\': // u005c: backslash \ + buffer.append("\\\\"); + break; + case 0x8: // "\\\\b"); // u0008: backspace BS + buffer.append("\\b"); + break; + case 0x9: //"\\\\t"); // u0009: horizontal tab HT + buffer.append("\\t"); + break; + case 0xA: //"\\\\n"); // u000a: linefeed LF + buffer.append("\\n"); + break; + case 0xC: //"\\\\f"); // u000c: form feed FF + buffer.append("\\f"); + break; + case 0xD: //"\\\\r"); // u000d: carriage return CR + buffer.append("\\r"); + break; + case 0x22: //"\\\\\""); // u0022: double quote " + buffer.append("\\\""); + break; + case 0x27: //"\\\\'"); // u0027: single quote ' + buffer.append("\\\'"); + break; + default: + if (c >= 32 && c < 127 || !ascii && InterpreterUtil.isPrintableUnicode(c)) { + buffer.append(c); + } + else { + buffer.append(InterpreterUtil.charToUnicodeLiteral(c)); + } + } + } + + return buffer.toString(); + } + + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof ConstExprent)) return false; + + ConstExprent cn = (ConstExprent)o; + return InterpreterUtil.equalObjects(consttype, cn.getConsttype()) && + InterpreterUtil.equalObjects(value, cn.getValue()); + } + + public boolean hasBooleanValue() { + + switch (consttype.type) { + case CodeConstants.TYPE_BOOLEAN: + case CodeConstants.TYPE_CHAR: + case CodeConstants.TYPE_BYTE: + case CodeConstants.TYPE_BYTECHAR: + case CodeConstants.TYPE_SHORT: + case CodeConstants.TYPE_SHORTCHAR: + case CodeConstants.TYPE_INT: + Integer ival = (Integer)value; + return ival.intValue() == 0 || + (DecompilerContext.getOption(IFernflowerPreferences.BOOLEAN_TRUE_ONE) && ival.intValue() == 1); + } + + return false; + } + + public boolean hasValueOne() { + + switch (consttype.type) { + case CodeConstants.TYPE_BOOLEAN: + case CodeConstants.TYPE_CHAR: + case CodeConstants.TYPE_BYTE: + case CodeConstants.TYPE_BYTECHAR: + case CodeConstants.TYPE_SHORT: + case CodeConstants.TYPE_SHORTCHAR: + case CodeConstants.TYPE_INT: + return ((Integer)value).intValue() == 1; + case CodeConstants.TYPE_LONG: + return ((Long)value).intValue() == 1; + case CodeConstants.TYPE_DOUBLE: + return ((Double)value).intValue() == 1; + case CodeConstants.TYPE_FLOAT: + return ((Float)value).intValue() == 1; + } + + return false; + } + + public static ConstExprent getZeroConstant(int type) { + + switch (type) { + case CodeConstants.TYPE_INT: + return new ConstExprent(VarType.VARTYPE_INT, new Integer(0)); + case CodeConstants.TYPE_LONG: + return new ConstExprent(VarType.VARTYPE_LONG, new Long(0)); + case CodeConstants.TYPE_DOUBLE: + return new ConstExprent(VarType.VARTYPE_DOUBLE, new Double(0)); + case CodeConstants.TYPE_FLOAT: + return new ConstExprent(VarType.VARTYPE_FLOAT, new Float(0)); + } + + throw new RuntimeException("Invalid argument!"); + } + + public VarType getConsttype() { + return consttype; + } + + public void setConsttype(VarType consttype) { + this.consttype = consttype; + } + + public Object getValue() { + return value; + } + + public int getIntValue() { + return ((Integer)value).intValue(); + } + + public boolean isBoolPermitted() { + return boolPermitted; + } + + public void setBoolPermitted(boolean boolPermitted) { + this.boolPermitted = boolPermitted; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ExitExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ExitExprent.java new file mode 100644 index 000000000000..7a5013432952 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/ExitExprent.java @@ -0,0 +1,151 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.struct.attr.StructExceptionsAttribute; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class ExitExprent extends Exprent { + + public static final int EXIT_RETURN = 0; + public static final int EXIT_THROW = 1; + + // return or throw statement + private int exittype; + + private Exprent value; + + private VarType rettype; + + { + this.type = EXPRENT_EXIT; + } + + public ExitExprent(int exittype, Exprent value, VarType rettype) { + this.exittype = exittype; + this.value = value; + this.rettype = rettype; + } + + public Exprent copy() { + return new ExitExprent(exittype, value == null ? null : value.copy(), rettype); + } + + public CheckTypesResult checkExprTypeBounds() { + CheckTypesResult result = new CheckTypesResult(); + + if (exittype == EXIT_RETURN && rettype.type != CodeConstants.TYPE_VOID) { + result.addMinTypeExprent(value, VarType.getMinTypeInFamily(rettype.type_family)); + result.addMaxTypeExprent(value, rettype); + } + + return result; + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + if (value != null) { + lst.add(value); + } + return lst; + } + + public String toJava(int indent) { + if (exittype == EXIT_RETURN) { + StringBuilder buffer = new StringBuilder(); + + if (rettype.type != CodeConstants.TYPE_VOID) { + buffer.append(" "); + ExprProcessor.getCastedExprent(value, rettype, buffer, indent, false); + } + + return "return" + buffer.toString(); + } + else { + + MethodWrapper meth = (MethodWrapper)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD_WRAPPER); + ClassNode node = ((ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE)); + + if (meth != null && node != null) { + StructExceptionsAttribute attr = (StructExceptionsAttribute)meth.methodStruct.getAttributes().getWithKey("Exceptions"); + + if (attr != null) { + String classname = null; + + for (int i = 0; i < attr.getThrowsExceptions().size(); i++) { + String excclassname = attr.getExcClassname(i, node.classStruct.getPool()); + if ("java/lang/Throwable".equals(excclassname)) { + classname = excclassname; + break; + } + else if ("java/lang/Exception".equals(excclassname)) { + classname = excclassname; + } + } + + if (classname != null) { + VarType exctype = new VarType(classname, true); + + StringBuilder buffer = new StringBuilder(); + ExprProcessor.getCastedExprent(value, exctype, buffer, indent, false); + + return "throw " + buffer.toString(); + } + } + } + + return "throw " + value.toJava(indent); + } + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof ExitExprent)) return false; + + ExitExprent et = (ExitExprent)o; + return exittype == et.getExittype() && + InterpreterUtil.equalObjects(value, et.getValue()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == value) { + value = newexpr; + } + } + + public int getExittype() { + return exittype; + } + + public Exprent getValue() { + return value; + } + + public VarType getRettype() { + return rettype; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/Exprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/Exprent.java new file mode 100644 index 000000000000..99712d574ab7 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/Exprent.java @@ -0,0 +1,133 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + + +public class Exprent { + + public static final int MULTIPLE_USES = 1; + public static final int SIDE_EFFECTS_FREE = 2; + public static final int BOTH_FLAGS = 3; + + + public static final int EXPRENT_ARRAY = 1; + public static final int EXPRENT_ASSIGNMENT = 2; + public static final int EXPRENT_CONST = 3; + public static final int EXPRENT_EXIT = 4; + public static final int EXPRENT_FIELD = 5; + public static final int EXPRENT_FUNCTION = 6; + public static final int EXPRENT_IF = 7; + public static final int EXPRENT_INVOCATION = 8; + public static final int EXPRENT_MONITOR = 9; + public static final int EXPRENT_NEW = 10; + public static final int EXPRENT_SWITCH = 11; + public static final int EXPRENT_VAR = 12; + public static final int EXPRENT_ANNOTATION = 13; + public static final int EXPRENT_ASSERT = 14; + + public int type; + + public int id; + + { + // set exprent id + id = DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.EXPRENT_COUNTER); + } + + public int getPrecedence() { + return 0; // the highest precedence + } + + public VarType getExprType() { + return VarType.VARTYPE_VOID; + } + + public int getExprentUse() { + return 0; + } + + public CheckTypesResult checkExprTypeBounds() { + return new CheckTypesResult(); + } + + public boolean containsExprent(Exprent exprent) { + + List<Exprent> listTemp = new ArrayList<Exprent>(getAllExprents(true)); + listTemp.add(this); + + for (Exprent lstexpr : listTemp) { + if (lstexpr.equals(exprent)) { + return true; + } + } + + return false; + } + + public List<Exprent> getAllExprents(boolean recursive) { + List<Exprent> lst = getAllExprents(); + + if (recursive) { + for (int i = lst.size() - 1; i >= 0; i--) { + lst.addAll(lst.get(i).getAllExprents(true)); + } + } + + return lst; + } + + public Set<VarVersionPaar> getAllVariables() { + + HashSet<VarVersionPaar> set = new HashSet<VarVersionPaar>(); + + List<Exprent> lstAllExprents = getAllExprents(true); + lstAllExprents.add(this); + + for (Exprent expr : lstAllExprents) { + if (expr.type == EXPRENT_VAR) { + set.add(new VarVersionPaar((VarExprent)expr)); + } + } + + return set; + } + + public List<Exprent> getAllExprents() { + throw new RuntimeException("not implemented"); + } + + public Exprent copy() { + throw new RuntimeException("not implemented"); + } + + public String toJava(int indent) { + throw new RuntimeException("not implemented"); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/FieldExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/FieldExprent.java new file mode 100644 index 000000000000..aa180b038798 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/FieldExprent.java @@ -0,0 +1,200 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.consts.LinkConstant; +import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class FieldExprent extends Exprent { + + private String name; + + private String classname; + + private boolean isStatic; + + private Exprent instance; + + private FieldDescriptor descriptor; + + { + this.type = EXPRENT_FIELD; + } + + public FieldExprent(LinkConstant cn, Exprent instance) { + + this.instance = instance; + + if (instance == null) { + isStatic = true; + } + + classname = cn.classname; + name = cn.elementname; + descriptor = FieldDescriptor.parseDescriptor(cn.descriptor); + } + + public FieldExprent(String name, String classname, boolean isStatic, Exprent instance, FieldDescriptor descriptor) { + this.name = name; + this.classname = classname; + this.isStatic = isStatic; + this.instance = instance; + this.descriptor = descriptor; + } + + public VarType getExprType() { + return descriptor.type; + } + + public int getExprentUse() { + if (instance == null) { + return Exprent.MULTIPLE_USES; + } + else { + return instance.getExprentUse() & Exprent.MULTIPLE_USES; + } + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + if (instance != null) { + lst.add(instance); + } + return lst; + } + + public Exprent copy() { + return new FieldExprent(name, classname, isStatic, instance == null ? null : instance.copy(), descriptor); + } + + public String toJava(int indent) { + StringBuilder buf = new StringBuilder(); + + + if (isStatic) { + ClassNode node = (ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE); + if (node == null || !classname.equals(node.classStruct.qualifiedName)) { + buf.append(DecompilerContext.getImportCollector().getShortName(ExprProcessor.buildJavaClassName(classname))); + buf.append("."); + } + } + else { + + String super_qualifier = null; + + if (instance != null && instance.type == Exprent.EXPRENT_VAR) { + VarExprent instvar = (VarExprent)instance; + VarVersionPaar varpaar = new VarVersionPaar(instvar); + + MethodWrapper current_meth = (MethodWrapper)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD_WRAPPER); + + if (current_meth != null) { // FIXME: remove + String this_classname = current_meth.varproc.getThisvars().get(varpaar); + + if (this_classname != null) { + if (!classname.equals(this_classname)) { // TODO: direct comparison to the super class? + super_qualifier = this_classname; + } + } + } + } + + if (super_qualifier != null) { + StructClass current_class = ((ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE)).classStruct; + + if (!super_qualifier.equals(current_class.qualifiedName)) { + buf.append(DecompilerContext.getImportCollector().getShortName(ExprProcessor.buildJavaClassName(super_qualifier))); + buf.append("."); + } + buf.append("super"); + } + else { + StringBuilder buff = new StringBuilder(); + boolean casted = ExprProcessor.getCastedExprent(instance, new VarType(CodeConstants.TYPE_OBJECT, 0, classname), buff, indent, true); + String res = buff.toString(); + + if (casted || instance.getPrecedence() > getPrecedence()) { + res = "(" + res + ")"; + } + + buf.append(res); + } + + if (buf.toString().equals( + VarExprent.VAR_NAMELESS_ENCLOSURE)) { // FIXME: workaround for field access of an anonymous enclosing class. Find a better way. + buf.setLength(0); + } + else { + buf.append("."); + } + } + + buf.append(name); + + return buf.toString(); + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof FieldExprent)) return false; + + FieldExprent ft = (FieldExprent)o; + return InterpreterUtil.equalObjects(name, ft.getName()) && + InterpreterUtil.equalObjects(classname, ft.getClassname()) && + isStatic == ft.isStatic() && + InterpreterUtil.equalObjects(instance, ft.getInstance()) && + InterpreterUtil.equalObjects(descriptor, ft.getDescriptor()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == instance) { + instance = newexpr; + } + } + + public String getClassname() { + return classname; + } + + public FieldDescriptor getDescriptor() { + return descriptor; + } + + public Exprent getInstance() { + return instance; + } + + public boolean isStatic() { + return isStatic; + } + + public String getName() { + return name; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/FunctionExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/FunctionExprent.java new file mode 100644 index 000000000000..4fa2ab385cee --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/FunctionExprent.java @@ -0,0 +1,615 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.ListStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + + +public class FunctionExprent extends Exprent { + + public static final int FUNCTION_ADD = 0; + public static final int FUNCTION_SUB = 1; + public static final int FUNCTION_MUL = 2; + public static final int FUNCTION_DIV = 3; + + public static final int FUNCTION_AND = 4; + public static final int FUNCTION_OR = 5; + public static final int FUNCTION_XOR = 6; + + public static final int FUNCTION_REM = 7; + + public static final int FUNCTION_SHL = 8; + public static final int FUNCTION_SHR = 9; + public static final int FUNCTION_USHR = 10; + + public static final int FUNCTION_BITNOT = 11; + public static final int FUNCTION_BOOLNOT = 12; + public static final int FUNCTION_NEG = 13; + + public final static int FUNCTION_I2L = 14; + public final static int FUNCTION_I2F = 15; + public final static int FUNCTION_I2D = 16; + public final static int FUNCTION_L2I = 17; + public final static int FUNCTION_L2F = 18; + public final static int FUNCTION_L2D = 19; + public final static int FUNCTION_F2I = 20; + public final static int FUNCTION_F2L = 21; + public final static int FUNCTION_F2D = 22; + public final static int FUNCTION_D2I = 23; + public final static int FUNCTION_D2L = 24; + public final static int FUNCTION_D2F = 25; + public final static int FUNCTION_I2B = 26; + public final static int FUNCTION_I2C = 27; + public final static int FUNCTION_I2S = 28; + + public final static int FUNCTION_CAST = 29; + public final static int FUNCTION_INSTANCEOF = 30; + + public final static int FUNCTION_ARRAYLENGTH = 31; + + public final static int FUNCTION_IMM = 32; + public final static int FUNCTION_MMI = 33; + + public final static int FUNCTION_IPP = 34; + public final static int FUNCTION_PPI = 35; + + public final static int FUNCTION_IIF = 36; + + public final static int FUNCTION_LCMP = 37; + public final static int FUNCTION_FCMPL = 38; + public final static int FUNCTION_FCMPG = 39; + public final static int FUNCTION_DCMPL = 40; + public final static int FUNCTION_DCMPG = 41; + + public static final int FUNCTION_EQ = 42; + public static final int FUNCTION_NE = 43; + public static final int FUNCTION_LT = 44; + public static final int FUNCTION_GE = 45; + public static final int FUNCTION_GT = 46; + public static final int FUNCTION_LE = 47; + + public static final int FUNCTION_CADD = 48; + public static final int FUNCTION_COR = 49; + + public static final int FUNCTION_STRCONCAT = 50; + + private static final VarType[] types = new VarType[]{ + VarType.VARTYPE_LONG, + VarType.VARTYPE_FLOAT, + VarType.VARTYPE_DOUBLE, + VarType.VARTYPE_INT, + VarType.VARTYPE_FLOAT, + VarType.VARTYPE_DOUBLE, + VarType.VARTYPE_INT, + VarType.VARTYPE_LONG, + VarType.VARTYPE_DOUBLE, + VarType.VARTYPE_INT, + VarType.VARTYPE_LONG, + VarType.VARTYPE_FLOAT, + VarType.VARTYPE_BYTE, + VarType.VARTYPE_CHAR, + VarType.VARTYPE_SHORT + }; + + private static final String[] operators = new String[]{ + " + ", + " - ", + " * ", + " / ", + " & ", + " | ", + " ^ ", + " % ", + " << ", + " >> ", + " >>> ", + " == ", + " != ", + " < ", + " >= ", + " > ", + " <= ", + " && ", + " || ", + " + " + }; + + private static final int[] precedence = new int[]{ + 3, // FUNCTION_ADD + 3, // FUNCTION_SUB + 2, // FUNCTION_MUL + 2, // FUNCTION_DIV + 7, // FUNCTION_AND + 9, // FUNCTION_OR + 8, // FUNCTION_XOR + 2, // FUNCTION_REM + 4, // FUNCTION_SHL + 4, // FUNCTION_SHR + 4, // FUNCTION_USHR + 1, // FUNCTION_BITNOT + 1, // FUNCTION_BOOLNOT + 1, // FUNCTION_NEG + 1, // FUNCTION_I2L + 1, // FUNCTION_I2F + 1, // FUNCTION_I2D + 1, // FUNCTION_L2I + 1, // FUNCTION_L2F + 1, // FUNCTION_L2D + 1, // FUNCTION_F2I + 1, // FUNCTION_F2L + 1, // FUNCTION_F2D + 1, // FUNCTION_D2I + 1, // FUNCTION_D2L + 1, // FUNCTION_D2F + 1, // FUNCTION_I2B + 1, // FUNCTION_I2C + 1, // FUNCTION_I2S + 1, // FUNCTION_CAST + 6, // FUNCTION_INSTANCEOF + 0, // FUNCTION_ARRAYLENGTH + 1, // FUNCTION_IMM + 1, // FUNCTION_MMI + 1, // FUNCTION_IPP + 1, // FUNCTION_PPI + 12, // FUNCTION_IFF + -1, // FUNCTION_LCMP + -1, // FUNCTION_FCMPL + -1, // FUNCTION_FCMPG + -1, // FUNCTION_DCMPL + -1, // FUNCTION_DCMPG + 6, // FUNCTION_EQ = 41; + 6, // FUNCTION_NE = 42; + 5, // FUNCTION_LT = 43; + 5, // FUNCTION_GE = 44; + 5, // FUNCTION_GT = 45; + 5, // FUNCTION_LE = 46; + 10, // FUNCTION_CADD = 47; + 11, // FUNCTION_COR = 48; + 3 // FUNCTION_STRCONCAT = 49; + }; + + private static final HashSet<Integer> associativity = + new HashSet<Integer>(Arrays.asList(new Integer[]{FUNCTION_ADD, FUNCTION_MUL, FUNCTION_AND, + FUNCTION_OR, FUNCTION_XOR, FUNCTION_CADD, FUNCTION_COR, FUNCTION_STRCONCAT})); + + private int functype; + + private VarType implicitType; + + private List<Exprent> lstOperands = new ArrayList<Exprent>(); + + { + this.type = EXPRENT_FUNCTION; + } + + public FunctionExprent(int functype, ListStack<Exprent> stack) { + this.functype = functype; + if (functype >= FUNCTION_BITNOT && functype <= FUNCTION_PPI && functype != FUNCTION_CAST + && functype != FUNCTION_INSTANCEOF) { + lstOperands.add(stack.pop()); + } + else if (functype == FUNCTION_IIF) { + throw new RuntimeException("no direct instantiation possible"); + } + else { + Exprent expr = stack.pop(); + lstOperands.add(stack.pop()); + lstOperands.add(expr); + } + } + + public FunctionExprent(int functype, List<Exprent> operands) { + this.functype = functype; + this.lstOperands = operands; + } + + public VarType getExprType() { + VarType exprType = null; + + if (functype <= FUNCTION_NEG || functype == FUNCTION_IPP || functype == FUNCTION_PPI + || functype == FUNCTION_IMM || functype == FUNCTION_MMI) { + + VarType type1 = lstOperands.get(0).getExprType(); + VarType type2 = null; + if (lstOperands.size() > 1) { + type2 = lstOperands.get(1).getExprType(); + } + + switch (functype) { + case FUNCTION_IMM: + case FUNCTION_MMI: + case FUNCTION_IPP: + case FUNCTION_PPI: + exprType = implicitType; + break; + case FUNCTION_BOOLNOT: + exprType = VarType.VARTYPE_BOOLEAN; + break; + case FUNCTION_SHL: + case FUNCTION_SHR: + case FUNCTION_USHR: + case FUNCTION_BITNOT: + case FUNCTION_NEG: + exprType = getMaxVarType(new VarType[]{type1}); + break; + case FUNCTION_ADD: + case FUNCTION_SUB: + case FUNCTION_MUL: + case FUNCTION_DIV: + case FUNCTION_REM: + exprType = getMaxVarType(new VarType[]{type1, type2}); + break; + case FUNCTION_AND: + case FUNCTION_OR: + case FUNCTION_XOR: + if (type1.type == CodeConstants.TYPE_BOOLEAN & type2.type == CodeConstants.TYPE_BOOLEAN) { + exprType = VarType.VARTYPE_BOOLEAN; + } + else { + exprType = getMaxVarType(new VarType[]{type1, type2}); + } + } + } + else if (functype == FUNCTION_CAST) { + exprType = lstOperands.get(1).getExprType(); + } + else if (functype == FUNCTION_IIF) { + Exprent param1 = lstOperands.get(1); + Exprent param2 = lstOperands.get(2); + VarType supertype = VarType.getCommonSupertype(param1.getExprType(), param2.getExprType()); + + if (param1.type == Exprent.EXPRENT_CONST && param2.type == Exprent.EXPRENT_CONST && + supertype.type != CodeConstants.TYPE_BOOLEAN && VarType.VARTYPE_INT.isSuperset(supertype)) { + exprType = VarType.VARTYPE_INT; + } + else { + exprType = supertype; + } + } + else if (functype == FUNCTION_STRCONCAT) { + exprType = VarType.VARTYPE_STRING; + } + else if (functype >= FUNCTION_EQ || functype == FUNCTION_INSTANCEOF) { + exprType = VarType.VARTYPE_BOOLEAN; + } + else if (functype >= FUNCTION_ARRAYLENGTH) { + exprType = VarType.VARTYPE_INT; + } + else { + exprType = types[functype - FUNCTION_I2L]; + } + + return exprType; + } + + public int getExprentUse() { + + if (functype >= FUNCTION_IMM && functype <= FUNCTION_PPI) { + return 0; + } + else { + int ret = Exprent.MULTIPLE_USES | Exprent.SIDE_EFFECTS_FREE; + for (Exprent expr : lstOperands) { + ret &= expr.getExprentUse(); + } + return ret; + } + } + + public CheckTypesResult checkExprTypeBounds() { + CheckTypesResult result = new CheckTypesResult(); + + Exprent param1 = lstOperands.get(0); + VarType type1 = param1.getExprType(); + Exprent param2 = null; + VarType type2 = null; + + if (lstOperands.size() > 1) { + param2 = lstOperands.get(1); + type2 = param2.getExprType(); + } + + switch (functype) { + case FUNCTION_IIF: + VarType supertype = getExprType(); + if (supertype == null) { + supertype = getExprType(); + } + result.addMinTypeExprent(param1, VarType.VARTYPE_BOOLEAN); + result.addMinTypeExprent(param2, VarType.getMinTypeInFamily(supertype.type_family)); + result.addMinTypeExprent(lstOperands.get(2), VarType.getMinTypeInFamily(supertype.type_family)); + break; + case FUNCTION_I2L: + case FUNCTION_I2F: + case FUNCTION_I2D: + case FUNCTION_I2B: + case FUNCTION_I2C: + case FUNCTION_I2S: + result.addMinTypeExprent(param1, VarType.VARTYPE_BYTECHAR); + result.addMaxTypeExprent(param1, VarType.VARTYPE_INT); + break; + case FUNCTION_IMM: + case FUNCTION_IPP: + case FUNCTION_MMI: + case FUNCTION_PPI: + result.addMinTypeExprent(param1, implicitType); + result.addMaxTypeExprent(param1, implicitType); + break; + case FUNCTION_ADD: + case FUNCTION_SUB: + case FUNCTION_MUL: + case FUNCTION_DIV: + case FUNCTION_REM: + case FUNCTION_SHL: + case FUNCTION_SHR: + case FUNCTION_USHR: + case FUNCTION_LT: + case FUNCTION_GE: + case FUNCTION_GT: + case FUNCTION_LE: + result.addMinTypeExprent(param2, VarType.VARTYPE_BYTECHAR); + case FUNCTION_BITNOT: + // case FUNCTION_BOOLNOT: + case FUNCTION_NEG: + result.addMinTypeExprent(param1, VarType.VARTYPE_BYTECHAR); + break; + case FUNCTION_AND: + case FUNCTION_OR: + case FUNCTION_XOR: + case FUNCTION_EQ: + case FUNCTION_NE: { + if (type1.type == CodeConstants.TYPE_BOOLEAN) { + + if (type2.isStrictSuperset(type1)) { + + result.addMinTypeExprent(param1, VarType.VARTYPE_BYTECHAR); + } + else { // both are booleans + + boolean param1_false_boolean = + type1.isFalseBoolean() || (param1.type == Exprent.EXPRENT_CONST && !((ConstExprent)param1).hasBooleanValue()); + boolean param2_false_boolean = + type1.isFalseBoolean() || (param2.type == Exprent.EXPRENT_CONST && !((ConstExprent)param2).hasBooleanValue()); + + if (param1_false_boolean || param2_false_boolean) { + result.addMinTypeExprent(param1, VarType.VARTYPE_BYTECHAR); + result.addMinTypeExprent(param2, VarType.VARTYPE_BYTECHAR); + } + } + } + else if (type2.type == CodeConstants.TYPE_BOOLEAN) { + + if (type1.isStrictSuperset(type2)) { + result.addMinTypeExprent(param2, VarType.VARTYPE_BYTECHAR); + } + } + } + } + + return result; + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + lst.addAll(lstOperands); + return lst; + } + + public Exprent copy() { + List<Exprent> lst = new ArrayList<Exprent>(); + for (Exprent expr : lstOperands) { + lst.add(expr.copy()); + } + FunctionExprent func = new FunctionExprent(functype, lst); + func.setImplicitType(implicitType); + + return func; + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof FunctionExprent)) return false; + + FunctionExprent fe = (FunctionExprent)o; + return functype == fe.getFunctype() && + InterpreterUtil.equalLists(lstOperands, fe.getLstOperands()); // TODO: order of operands insignificant + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + for (int i = 0; i < lstOperands.size(); i++) { + if (oldexpr == lstOperands.get(i)) { + lstOperands.set(i, newexpr); + } + } + } + + public String toJava(int indent) { + + if (functype <= FUNCTION_USHR) { + return wrapOperandString(lstOperands.get(0), false, indent) + operators[functype] + + wrapOperandString(lstOperands.get(1), true, indent); + } + + if (functype >= FUNCTION_EQ) { + return wrapOperandString(lstOperands.get(0), false, indent) + operators[functype - FUNCTION_EQ + 11] + + wrapOperandString(lstOperands.get(1), true, indent); + } + + switch (functype) { + case FUNCTION_BITNOT: + return "~" + wrapOperandString(lstOperands.get(0), true, indent); + case FUNCTION_BOOLNOT: + return "!" + wrapOperandString(lstOperands.get(0), true, indent); + case FUNCTION_NEG: + return "-" + wrapOperandString(lstOperands.get(0), true, indent); + case FUNCTION_CAST: + return "(" + lstOperands.get(1).toJava(indent) + ")" + wrapOperandString(lstOperands.get(0), true, indent); + case FUNCTION_ARRAYLENGTH: + Exprent arr = lstOperands.get(0); + + String res = wrapOperandString(arr, false, indent); + if (arr.getExprType().arraydim == 0) { + VarType objarr = VarType.VARTYPE_OBJECT.copy(); + objarr.arraydim = 1; // type family does not change + + res = "((" + ExprProcessor.getCastTypeName(objarr) + ")" + res + ")"; + } + return res + ".length"; + case FUNCTION_IIF: + return wrapOperandString(lstOperands.get(0), true, indent) + "?" + wrapOperandString(lstOperands.get(1), true, indent) + ":" + + wrapOperandString(lstOperands.get(2), true, indent); + case FUNCTION_IPP: + return wrapOperandString(lstOperands.get(0), true, indent) + "++"; + case FUNCTION_PPI: + return "++" + wrapOperandString(lstOperands.get(0), true, indent); + case FUNCTION_IMM: + return wrapOperandString(lstOperands.get(0), true, indent) + "--"; + case FUNCTION_MMI: + return "--" + wrapOperandString(lstOperands.get(0), true, indent); + case FUNCTION_INSTANCEOF: + return wrapOperandString(lstOperands.get(0), true, indent) + " instanceof " + wrapOperandString(lstOperands.get(1), true, indent); + case FUNCTION_LCMP: // shouldn't appear in the final code + return "__lcmp__(" + + wrapOperandString(lstOperands.get(0), true, indent) + + "," + + wrapOperandString(lstOperands.get(1), true, indent) + + ")"; + case FUNCTION_FCMPL: // shouldn't appear in the final code + return "__fcmpl__(" + + wrapOperandString(lstOperands.get(0), true, indent) + + "," + + wrapOperandString(lstOperands.get(1), true, indent) + + ")"; + case FUNCTION_FCMPG: // shouldn't appear in the final code + return "__fcmpg__(" + + wrapOperandString(lstOperands.get(0), true, indent) + + "," + + wrapOperandString(lstOperands.get(1), true, indent) + + ")"; + case FUNCTION_DCMPL: // shouldn't appear in the final code + return "__dcmpl__(" + + wrapOperandString(lstOperands.get(0), true, indent) + + "," + + wrapOperandString(lstOperands.get(1), true, indent) + + ")"; + case FUNCTION_DCMPG: // shouldn't appear in the final code + return "__dcmpg__(" + + wrapOperandString(lstOperands.get(0), true, indent) + + "," + + wrapOperandString(lstOperands.get(1), true, indent) + + ")"; + } + + if (functype <= FUNCTION_I2S) { + return "(" + ExprProcessor.getTypeName(types[functype - FUNCTION_I2L]) + ")" + wrapOperandString(lstOperands.get(0), true, indent); + } + + // return "<unknown function>"; + throw new RuntimeException("invalid function"); + } + + public int getPrecedence() { + return getPrecedence(functype); + } + + public static int getPrecedence(int func) { + return precedence[func]; + } + + public VarType getSimpleCastType() { + return types[functype - FUNCTION_I2L]; + } + + private String wrapOperandString(Exprent expr, boolean eq, int indent) { + + int myprec = getPrecedence(); + int exprprec = expr.getPrecedence(); + + boolean parentheses = exprprec > myprec; + if (!parentheses && eq) { + parentheses = (exprprec == myprec); + if (parentheses) { + if (expr.type == Exprent.EXPRENT_FUNCTION && + ((FunctionExprent)expr).getFunctype() == functype) { + parentheses = !associativity.contains(functype); + } + } + } + + String res = expr.toJava(indent); + + if (parentheses) { + res = "(" + res + ")"; + } + + return res; + } + + private static VarType getMaxVarType(VarType[] arr) { + + int[] types = new int[]{CodeConstants.TYPE_DOUBLE, CodeConstants.TYPE_FLOAT, CodeConstants.TYPE_LONG}; + VarType[] vartypes = new VarType[]{VarType.VARTYPE_DOUBLE, VarType.VARTYPE_FLOAT, VarType.VARTYPE_LONG}; + + for (int i = 0; i < types.length; i++) { + for (int j = 0; j < arr.length; j++) { + if (arr[j].type == types[i]) { + return vartypes[i]; + } + } + } + + return VarType.VARTYPE_INT; + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public int getFunctype() { + return functype; + } + + public void setFunctype(int functype) { + this.functype = functype; + } + + public List<Exprent> getLstOperands() { + return lstOperands; + } + + public void setLstOperands(List<Exprent> lstOperands) { + this.lstOperands = lstOperands; + } + + public VarType getImplicitType() { + return implicitType; + } + + public void setImplicitType(VarType implicitType) { + this.implicitType = implicitType; + } +} + diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/IfExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/IfExprent.java new file mode 100644 index 000000000000..66e63c0e7fc6 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/IfExprent.java @@ -0,0 +1,145 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.ListStack; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + + +public class IfExprent extends Exprent { + + public static final int IF_EQ = 0; + public static final int IF_NE = 1; + public static final int IF_LT = 2; + public static final int IF_GE = 3; + public static final int IF_GT = 4; + public static final int IF_LE = 5; + + public static final int IF_NULL = 6; + public static final int IF_NONNULL = 7; + + public static final int IF_ICMPEQ = 8; + public static final int IF_ICMPNE = 9; + public static final int IF_ICMPLT = 10; + public static final int IF_ICMPGE = 11; + public static final int IF_ICMPGT = 12; + public static final int IF_ICMPLE = 13; + public static final int IF_ACMPEQ = 14; + public static final int IF_ACMPNE = 15; + + public static final int IF_CAND = 16; + public static final int IF_COR = 17; + + public static final int IF_NOT = 18; + public static final int IF_VALUE = 19; + + private static final int[] functypes = new int[]{ + FunctionExprent.FUNCTION_EQ, + FunctionExprent.FUNCTION_NE, + FunctionExprent.FUNCTION_LT, + FunctionExprent.FUNCTION_GE, + FunctionExprent.FUNCTION_GT, + FunctionExprent.FUNCTION_LE, + FunctionExprent.FUNCTION_EQ, + FunctionExprent.FUNCTION_NE, + FunctionExprent.FUNCTION_EQ, + FunctionExprent.FUNCTION_NE, + FunctionExprent.FUNCTION_LT, + FunctionExprent.FUNCTION_GE, + FunctionExprent.FUNCTION_GT, + FunctionExprent.FUNCTION_LE, + FunctionExprent.FUNCTION_EQ, + FunctionExprent.FUNCTION_NE, + FunctionExprent.FUNCTION_CADD, + FunctionExprent.FUNCTION_COR, + FunctionExprent.FUNCTION_BOOLNOT, + -1 + }; + + private Exprent condition; + + { + this.type = EXPRENT_IF; + } + + public IfExprent(int iftype, ListStack<Exprent> stack) { + + if (iftype <= IF_LE) { + stack.push(new ConstExprent(0, true)); + } + else if (iftype <= IF_NONNULL) { + stack.push(new ConstExprent(VarType.VARTYPE_NULL, null)); + } + + if (iftype == IF_VALUE) { + condition = stack.pop(); + } + else { + condition = new FunctionExprent(functypes[iftype], stack); + } + } + + private IfExprent(Exprent condition) { + this.condition = condition; + } + + public Exprent copy() { + return new IfExprent(condition.copy()); + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + lst.add(condition); + return lst; + } + + public String toJava(int indent) { + return "if(" + condition.toJava(indent) + ")"; + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof IfExprent)) return false; + + IfExprent ie = (IfExprent)o; + return InterpreterUtil.equalObjects(condition, ie.getCondition()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == condition) { + condition = newexpr; + } + } + + public IfExprent negateIf() { + condition = new FunctionExprent(FunctionExprent.FUNCTION_BOOLNOT, + Arrays.asList(new Exprent[]{condition})); + return this; + } + + public Exprent getCondition() { + return condition; + } + + public void setCondition(Exprent condition) { + this.condition = condition; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/InvocationExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/InvocationExprent.java new file mode 100644 index 000000000000..04758dc0492d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/InvocationExprent.java @@ -0,0 +1,515 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.main.rels.MethodWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.consts.LinkConstant; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.ListStack; + +import java.util.*; + + +public class InvocationExprent extends Exprent { + + public static final int INVOKE_SPECIAL = 1; + public static final int INVOKE_VIRTUAL = 2; + public static final int INVOKE_STATIC = 3; + public static final int INVOKE_INTERFACE = 4; + public static final int INVOKE_DYNAMIC = 5; + + public static final int TYP_GENERAL = 1; + public static final int TYP_INIT = 2; + public static final int TYP_CLINIT = 3; + + public static final int CONSTRUCTOR_NOT = 0; + public static final int CONSTRUCTOR_THIS = 1; + public static final int CONSTRUCTOR_SUPER = 2; + + private String name; + + private String classname; + + private boolean isStatic; + + private int functype = TYP_GENERAL; + + private Exprent instance; + + private MethodDescriptor descriptor; + + private String stringDescriptor; + + private String invoke_dynamic_classsuffix; + + private int invocationTyp = INVOKE_VIRTUAL; + + private List<Exprent> lstParameters = new ArrayList<Exprent>(); + + { + this.type = EXPRENT_INVOCATION; + } + + public InvocationExprent() { + } + + public InvocationExprent(int opcode, LinkConstant cn, ListStack<Exprent> stack, int dynamic_invokation_type) { + + name = cn.elementname; + classname = cn.classname; + + switch (opcode) { + case CodeConstants.opc_invokestatic: + invocationTyp = INVOKE_STATIC; + break; + case CodeConstants.opc_invokespecial: + invocationTyp = INVOKE_SPECIAL; + break; + case CodeConstants.opc_invokevirtual: + invocationTyp = INVOKE_VIRTUAL; + break; + case CodeConstants.opc_invokeinterface: + invocationTyp = INVOKE_INTERFACE; + break; + case CodeConstants.opc_invokedynamic: + invocationTyp = INVOKE_DYNAMIC; + + classname = "java/lang/Class"; // dummy class name + invoke_dynamic_classsuffix = "##Lambda_" + cn.index1 + "_" + cn.index2; + } + + if ("<init>".equals(name)) { + functype = TYP_INIT; + } + else if ("<clinit>".equals(name)) { + functype = TYP_CLINIT; + } + + stringDescriptor = cn.descriptor; + descriptor = MethodDescriptor.parseDescriptor(cn.descriptor); + + for (int i = 0; i < descriptor.params.length; i++) { + lstParameters.add(0, stack.pop()); + } + + if (opcode == CodeConstants.opc_invokedynamic) { + if (dynamic_invokation_type == CodeConstants.CONSTANT_MethodHandle_REF_invokeStatic) { + isStatic = true; + } + else { + instance = lstParameters + .get(0); // FIXME: remove the first parameter completely from the list. It's the object type for a virtual lambda method. + } + } + else if (opcode == CodeConstants.opc_invokestatic) { + isStatic = true; + } + else { + instance = stack.pop(); + } + } + + private InvocationExprent(InvocationExprent expr) { + name = expr.getName(); + classname = expr.getClassname(); + isStatic = expr.isStatic(); + functype = expr.getFunctype(); + instance = expr.getInstance(); + if (instance != null) { + instance = instance.copy(); + } + invocationTyp = expr.getInvocationTyp(); + stringDescriptor = expr.getStringDescriptor(); + descriptor = expr.getDescriptor(); + lstParameters = new ArrayList<Exprent>(expr.getLstParameters()); + for (int i = 0; i < lstParameters.size(); i++) { + lstParameters.set(i, lstParameters.get(i).copy()); + } + } + + + public VarType getExprType() { + return descriptor.ret; + } + + public CheckTypesResult checkExprTypeBounds() { + CheckTypesResult result = new CheckTypesResult(); + + for (int i = 0; i < lstParameters.size(); i++) { + Exprent parameter = lstParameters.get(i); + + VarType leftType = descriptor.params[i]; + + result.addMinTypeExprent(parameter, VarType.getMinTypeInFamily(leftType.type_family)); + result.addMaxTypeExprent(parameter, leftType); + } + + return result; + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + if (instance != null) { + lst.add(instance); + } + lst.addAll(lstParameters); + return lst; + } + + + public Exprent copy() { + return new InvocationExprent(this); + } + + public String toJava(int indent) { + StringBuilder buf = new StringBuilder(""); + + String super_qualifier = null; + boolean isInstanceThis = false; + + if (invocationTyp == INVOKE_DYNAMIC) { + // ClassNode node = (ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASSNODE); + // + // if(node != null) { + // ClassNode lambda_node = DecompilerContext.getClassprocessor().getMapRootClasses().get(node.classStruct.qualifiedName + invoke_dynamic_classsuffix); + // if(lambda_node != null) { + // + // String typename = ExprProcessor.getCastTypeName(lambda_node.anonimousClassType); + // + // StringWriter strwriter = new StringWriter(); + // BufferedWriter bufstrwriter = new BufferedWriter(strwriter); + // + // ClassWriter clwriter = new ClassWriter(); + // + // try { + // bufstrwriter.write("new " + typename + "() {"); + // bufstrwriter.newLine(); + // + // + // + // bufstrwriter.flush(); + // } catch(IOException ex) { + // throw new RuntimeException(ex); + // } + // + // buf.append(strwriter.toString()); + // + // } + // } + + } + else if (isStatic) { + + ClassNode node = (ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE); + if (node == null || !classname.equals(node.classStruct.qualifiedName)) { + buf.append(DecompilerContext.getImportCollector().getShortName(ExprProcessor.buildJavaClassName(classname))); + } + } + else { + + if (instance != null && instance.type == Exprent.EXPRENT_VAR) { + VarExprent instvar = (VarExprent)instance; + VarVersionPaar varpaar = new VarVersionPaar(instvar); + + VarProcessor vproc = instvar.getProcessor(); + if (vproc == null) { + MethodWrapper current_meth = (MethodWrapper)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD_WRAPPER); + if (current_meth != null) { + vproc = current_meth.varproc; + } + } + + String this_classname = null; + if (vproc != null) { + this_classname = vproc.getThisvars().get(varpaar); + } + + if (this_classname != null) { + isInstanceThis = true; + + if (invocationTyp == INVOKE_SPECIAL) { + if (!classname.equals(this_classname)) { // TODO: direct comparison to the super class? + super_qualifier = this_classname; + } + } + } + } + + if (functype == TYP_GENERAL) { + if (super_qualifier != null) { + StructClass current_class = ((ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE)).classStruct; + + if (!super_qualifier.equals(current_class.qualifiedName)) { + buf.append(DecompilerContext.getImportCollector().getShortName(ExprProcessor.buildJavaClassName(super_qualifier))); + buf.append("."); + } + buf.append("super"); + } + else { + String res = instance.toJava(indent); + + VarType rightType = instance.getExprType(); + VarType leftType = new VarType(CodeConstants.TYPE_OBJECT, 0, classname); + + if (rightType.equals(VarType.VARTYPE_OBJECT) && !leftType.equals(rightType)) { + buf.append("((").append(ExprProcessor.getCastTypeName(leftType)).append(")"); + + if (instance.getPrecedence() >= FunctionExprent.getPrecedence(FunctionExprent.FUNCTION_CAST)) { + res = "(" + res + ")"; + } + buf.append(res).append(")"); + } + else if (instance.getPrecedence() > getPrecedence()) { + buf.append("(").append(res).append(")"); + } + else { + buf.append(res); + } + } + } + } + + switch (functype) { + case TYP_GENERAL: + if (VarExprent.VAR_NAMELESS_ENCLOSURE.equals(buf.toString())) { + buf = new StringBuilder(""); + } + + if (buf.length() > 0) { + buf.append("."); + } + + buf.append(name); + if (invocationTyp == INVOKE_DYNAMIC) { + buf.append("<invokedynamic>"); + } + buf.append("("); + + break; + case TYP_CLINIT: + throw new RuntimeException("Explicite invocation of <clinit>"); + case TYP_INIT: + if (super_qualifier != null) { + buf.append("super("); + } + else if (isInstanceThis) { + buf.append("this("); + } + else { + buf.append(instance.toJava(indent)); + buf.append(".<init>("); + // throw new RuntimeException("Unrecognized invocation of <init>"); // FIXME: activate + } + } + + List<VarVersionPaar> sigFields = null; + boolean isEnum = false; + if (functype == TYP_INIT) { + ClassNode newNode = DecompilerContext.getClassProcessor().getMapRootClasses().get(classname); + + if (newNode != null) { // own class + if (newNode.wrapper != null) { + sigFields = newNode.wrapper.getMethodWrapper("<init>", stringDescriptor).signatureFields; + } + else { + if (newNode.type == ClassNode.CLASS_MEMBER && (newNode.access & CodeConstants.ACC_STATIC) == 0) { // non-static member class + sigFields = new ArrayList<VarVersionPaar>(Collections.nCopies(lstParameters.size(), (VarVersionPaar)null)); + sigFields.set(0, new VarVersionPaar(-1, 0)); + } + } + isEnum = newNode.classStruct.hasModifier(CodeConstants.ACC_ENUM) && DecompilerContext.getOption(IFernflowerPreferences.DECOMPILE_ENUM); + } + } + + Set<Integer> setAmbiguousParameters = getAmbiguousParameters(); + + boolean firstpar = true; + int start = isEnum ? 2 : 0; + for (int i = start; i < lstParameters.size(); i++) { + if (sigFields == null || sigFields.get(i) == null) { + if (!firstpar) { + buf.append(", "); + } + + StringBuilder buff = new StringBuilder(); + ExprProcessor.getCastedExprent(lstParameters.get(i), descriptor.params[i], buff, indent, true, setAmbiguousParameters.contains(i)); + + buf.append(buff); + firstpar = false; + } + } + buf.append(")"); + + return buf.toString(); + } + + private Set<Integer> getAmbiguousParameters() { + + Set<Integer> ret = new HashSet<Integer>(); + + StructClass cstr = DecompilerContext.getStructContext().getClass(classname); + if (cstr != null) { + List<MethodDescriptor> lstMethods = new ArrayList<MethodDescriptor>(); + for (StructMethod meth : cstr.getMethods()) { + if (name.equals(meth.getName())) { + MethodDescriptor md = MethodDescriptor.parseDescriptor(meth.getDescriptor()); + if (md.params.length == descriptor.params.length) { + boolean equals = true; + for (int i = 0; i < md.params.length; i++) { + if (md.params[i].type_family != descriptor.params[i].type_family) { + equals = false; + break; + } + } + + if (equals) { + lstMethods.add(md); + } + } + } + } + + if (lstMethods.size() > 1) { + for (int i = 0; i < descriptor.params.length; i++) { + VarType partype = descriptor.params[i]; + + for (MethodDescriptor md : lstMethods) { + if (!partype.equals(md.params[i])) { + ret.add(i); + break; + } + } + } + } + } + + return ret; + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof InvocationExprent)) return false; + + InvocationExprent it = (InvocationExprent)o; + return InterpreterUtil.equalObjects(name, it.getName()) && + InterpreterUtil.equalObjects(classname, it.getClassname()) && + isStatic == it.isStatic() && + InterpreterUtil.equalObjects(instance, it.getInstance()) && + InterpreterUtil.equalObjects(descriptor, it.getDescriptor()) && + functype == it.getFunctype() && + InterpreterUtil.equalLists(lstParameters, it.getLstParameters()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == instance) { + instance = newexpr; + } + + for (int i = 0; i < lstParameters.size(); i++) { + if (oldexpr == lstParameters.get(i)) { + lstParameters.set(i, newexpr); + } + } + } + + public List<Exprent> getLstParameters() { + return lstParameters; + } + + public void setLstParameters(List<Exprent> lstParameters) { + this.lstParameters = lstParameters; + } + + public MethodDescriptor getDescriptor() { + return descriptor; + } + + public void setDescriptor(MethodDescriptor descriptor) { + this.descriptor = descriptor; + } + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + public int getFunctype() { + return functype; + } + + public void setFunctype(int functype) { + this.functype = functype; + } + + public Exprent getInstance() { + return instance; + } + + public void setInstance(Exprent instance) { + this.instance = instance; + } + + public boolean isStatic() { + return isStatic; + } + + public void setStatic(boolean isStatic) { + this.isStatic = isStatic; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStringDescriptor() { + return stringDescriptor; + } + + public void setStringDescriptor(String stringDescriptor) { + this.stringDescriptor = stringDescriptor; + } + + public int getInvocationTyp() { + return invocationTyp; + } + + public void setInvocationTyp(int invocationTyp) { + this.invocationTyp = invocationTyp; + } + + public String getInvokeDynamicClassSuffix() { + return invoke_dynamic_classsuffix; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/MonitorExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/MonitorExprent.java new file mode 100644 index 000000000000..9a1945e85ac7 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/MonitorExprent.java @@ -0,0 +1,83 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class MonitorExprent extends Exprent { + + public static final int MONITOR_ENTER = 0; + public static final int MONITOR_EXIT = 1; + + private int montype; + + private Exprent value; + + { + this.type = EXPRENT_MONITOR; + } + + public MonitorExprent(int montype, Exprent value) { + this.montype = montype; + this.value = value; + } + + public Exprent copy() { + return new MonitorExprent(montype, value.copy()); + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + lst.add(value); + return lst; + } + + public String toJava(int indent) { + if (montype == MONITOR_ENTER) { + return "synchronized(" + value.toJava(indent) + ")"; + } + else { + return ""; + } + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof MonitorExprent)) return false; + + MonitorExprent me = (MonitorExprent)o; + return montype == me.getMontype() && + InterpreterUtil.equalObjects(value, me.getValue()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == value) { + value = newexpr; + } + } + + public int getMontype() { + return montype; + } + + public Exprent getValue() { + return value; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/NewExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/NewExprent.java new file mode 100644 index 000000000000..416b831283f1 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/NewExprent.java @@ -0,0 +1,504 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassWriter; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.ListStack; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class NewExprent extends Exprent { + + private InvocationExprent constructor; + + private VarType newtype; + + private List<Exprent> lstDims = new ArrayList<Exprent>(); + + private List<Exprent> lstArrayElements = new ArrayList<Exprent>(); + + private boolean directArrayInit; + + private boolean anonymous; + + private boolean lambda; + + private boolean enumconst; + + { + this.type = EXPRENT_NEW; + } + + public NewExprent(VarType newtype, ListStack<Exprent> stack, int arraydim) { + this.newtype = newtype; + for (int i = 0; i < arraydim; i++) { + lstDims.add(0, stack.pop()); + } + + setAnonymous(); + } + + public NewExprent(VarType newtype, List<Exprent> lstDims) { + this.newtype = newtype; + this.lstDims = lstDims; + + setAnonymous(); + } + + private void setAnonymous() { + + anonymous = false; + lambda = false; + + if (newtype.type == CodeConstants.TYPE_OBJECT && newtype.arraydim == 0) { + ClassNode node = DecompilerContext.getClassProcessor().getMapRootClasses().get(newtype.value); + + if (node != null && (node.type == ClassNode.CLASS_ANONYMOUS || node.type == ClassNode.CLASS_LAMBDA)) { + anonymous = true; + + if (node.type == ClassNode.CLASS_LAMBDA) { + lambda = true; + } + } + } + } + + public VarType getExprType() { + + if (anonymous) { + ClassNode node = DecompilerContext.getClassProcessor().getMapRootClasses().get(newtype.value); + + return node.anonimousClassType; + } + else { + return newtype; + } + } + + public CheckTypesResult checkExprTypeBounds() { + CheckTypesResult result = new CheckTypesResult(); + + if (newtype.arraydim != 0) { + for (Exprent dim : lstDims) { + result.addMinTypeExprent(dim, VarType.VARTYPE_BYTECHAR); + result.addMaxTypeExprent(dim, VarType.VARTYPE_INT); + } + + if (newtype.arraydim == 1) { + + VarType leftType = newtype.copy(); + leftType.decArrayDim(); + + for (Exprent element : lstArrayElements) { + result.addMinTypeExprent(element, VarType.getMinTypeInFamily(leftType.type_family)); + result.addMaxTypeExprent(element, leftType); + } + } + } + else { + if (constructor != null) { + return constructor.checkExprTypeBounds(); + } + } + + return result; + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + if (newtype.arraydim == 0) { + if (constructor != null) { + Exprent constructor_instance = constructor.getInstance(); + + if (constructor_instance != null) { // should be true only for a lambda expression with a virtual content method + lst.add(constructor_instance); + } + + lst.addAll(constructor.getLstParameters()); + } + } + else { + lst.addAll(lstDims); + lst.addAll(lstArrayElements); + } + + return lst; + } + + public Exprent copy() { + List<Exprent> lst = new ArrayList<Exprent>(); + for (Exprent expr : lstDims) { + lst.add(expr.copy()); + } + + NewExprent ret = new NewExprent(newtype, lst); + ret.setConstructor(constructor == null ? null : (InvocationExprent)constructor.copy()); + ret.setLstArrayElements(lstArrayElements); + ret.setDirectArrayInit(directArrayInit); + ret.setAnonymous(anonymous); + ret.setEnumconst(enumconst); + return ret; + } + + public int getPrecedence() { + return 1; // precedence of new + } + + public String toJava(int indent) { + StringBuilder buf = new StringBuilder(); + + if (anonymous) { + + ClassNode child = DecompilerContext.getClassProcessor().getMapRootClasses().get(newtype.value); + + buf.append("("); + + if (!lambda && constructor != null) { + + InvocationExprent invsuper = child.superInvocation; + + ClassNode newnode = DecompilerContext.getClassProcessor().getMapRootClasses().get(invsuper.getClassname()); + + List<VarVersionPaar> sigFields = null; + if (newnode != null) { // own class + if (newnode.wrapper != null) { + sigFields = newnode.wrapper.getMethodWrapper("<init>", invsuper.getStringDescriptor()).signatureFields; + } + else { + if (newnode.type == ClassNode.CLASS_MEMBER && (newnode.access & CodeConstants.ACC_STATIC) == 0 && + !constructor.getLstParameters().isEmpty()) { // member non-static class invoked with enclosing class instance + sigFields = new ArrayList<VarVersionPaar>(Collections.nCopies(constructor.getLstParameters().size(), (VarVersionPaar)null)); + sigFields.set(0, new VarVersionPaar(-1, 0)); + } + } + } + + boolean firstpar = true; + int start = 0, end = invsuper.getLstParameters().size(); + if (enumconst) { + start += 2; + end -= 1; + } + for (int i = start; i < end; i++) { + if (sigFields == null || sigFields.get(i) == null) { + if (!firstpar) { + buf.append(", "); + } + + Exprent param = invsuper.getLstParameters().get(i); + if (param.type == Exprent.EXPRENT_VAR) { + int varindex = ((VarExprent)param).getIndex(); + if (varindex > 0 && varindex <= constructor.getLstParameters().size()) { + param = constructor.getLstParameters().get(varindex - 1); + } + } + + StringBuilder buff = new StringBuilder(); + ExprProcessor.getCastedExprent(param, invsuper.getDescriptor().params[i], buff, indent, true); + + buf.append(buff); + firstpar = false; + } + } + } + + if (!enumconst) { + String enclosing = null; + if (!lambda && constructor != null) { + enclosing = getQualifiedNewInstance(child.anonimousClassType.value, constructor.getLstParameters(), indent); + } + + String typename = ExprProcessor.getCastTypeName(child.anonimousClassType); + + if (enclosing != null) { + ClassNode anonimousNode = DecompilerContext.getClassProcessor().getMapRootClasses().get(child.anonimousClassType.value); + if (anonimousNode != null) { + typename = anonimousNode.simpleName; + } + else { + typename = typename.substring(typename.lastIndexOf('.') + 1); + } + } + buf.insert(0, "new " + typename); + + if (enclosing != null) { + buf.insert(0, enclosing + "."); + } + } + + buf.append(")"); + + if (enumconst && buf.length() == 2) { + buf.setLength(0); + } + + if (lambda) { + if (!DecompilerContext.getOption(IFernflowerPreferences.LAMBDA_TO_ANONYMOUS_CLASS)) { + buf.setLength(0); // remove the usual 'new <class>()', it will be replaced with lambda style '() ->' + } + Exprent methodObject = constructor == null ? null : constructor.getInstance(); + new ClassWriter().classLambdaToJava(child, buf, methodObject, indent); + } + else { + new ClassWriter().classToJava(child, buf, indent); + } + } + else if (directArrayInit) { + VarType leftType = newtype.copy(); + leftType.decArrayDim(); + + buf.append("{"); + for (int i = 0; i < lstArrayElements.size(); i++) { + if (i > 0) { + buf.append(", "); + } + ExprProcessor.getCastedExprent(lstArrayElements.get(i), leftType, buf, indent, false); + } + buf.append("}"); + } + else { + if (newtype.arraydim == 0) { + + if (constructor != null) { + + List<Exprent> lstParameters = constructor.getLstParameters(); + + ClassNode newnode = DecompilerContext.getClassProcessor().getMapRootClasses().get(constructor.getClassname()); + + List<VarVersionPaar> sigFields = null; + if (newnode != null) { // own class + if (newnode.wrapper != null) { + sigFields = newnode.wrapper.getMethodWrapper("<init>", constructor.getStringDescriptor()).signatureFields; + } + else { + if (newnode.type == ClassNode.CLASS_MEMBER && (newnode.access & CodeConstants.ACC_STATIC) == 0 && + !constructor.getLstParameters().isEmpty()) { // member non-static class invoked with enclosing class instance + sigFields = new ArrayList<VarVersionPaar>(Collections.nCopies(lstParameters.size(), (VarVersionPaar)null)); + sigFields.set(0, new VarVersionPaar(-1, 0)); + } + } + } + + int start = enumconst ? 2 : 0; + if (!enumconst || start < lstParameters.size()) { + buf.append("("); + + boolean firstpar = true; + for (int i = start; i < lstParameters.size(); i++) { + if (sigFields == null || sigFields.get(i) == null) { + if (!firstpar) { + buf.append(", "); + } + + StringBuilder buff = new StringBuilder(); + ExprProcessor.getCastedExprent(lstParameters.get(i), constructor.getDescriptor().params[i], buff, indent, true); + + buf.append(buff); + firstpar = false; + } + } + buf.append(")"); + } + } + + if (!enumconst) { + String enclosing = null; + if (constructor != null) { + enclosing = getQualifiedNewInstance(newtype.value, constructor.getLstParameters(), indent); + } + + String typename = ExprProcessor.getTypeName(newtype); + + if (enclosing != null) { + ClassNode newNode = DecompilerContext.getClassProcessor().getMapRootClasses().get(newtype.value); + if (newNode != null) { + typename = newNode.simpleName; + } + else { + typename = typename.substring(typename.lastIndexOf('.') + 1); + } + } + buf.insert(0, "new " + typename); + + if (enclosing != null) { + buf.insert(0, enclosing + "."); + } + } + } + else { + buf.append("new ").append(ExprProcessor.getTypeName(newtype)); + + if (lstArrayElements.isEmpty()) { + for (int i = 0; i < newtype.arraydim; i++) { + buf.append("[").append(i < lstDims.size() ? lstDims.get(i).toJava(indent) : "").append("]"); + } + } + else { + for (int i = 0; i < newtype.arraydim; i++) { + buf.append("[]"); + } + + VarType leftType = newtype.copy(); + leftType.decArrayDim(); + + buf.append("{"); + for (int i = 0; i < lstArrayElements.size(); i++) { + if (i > 0) { + buf.append(", "); + } + StringBuilder buff = new StringBuilder(); + ExprProcessor.getCastedExprent(lstArrayElements.get(i), leftType, buff, indent, false); + + buf.append(buff); + } + buf.append("}"); + } + } + } + return buf.toString(); + } + + private static String getQualifiedNewInstance(String classname, List<Exprent> lstParams, int indent) { + + ClassNode node = DecompilerContext.getClassProcessor().getMapRootClasses().get(classname); + + if (node != null && node.type != ClassNode.CLASS_ROOT && (node.access & CodeConstants.ACC_STATIC) == 0) { + if (!lstParams.isEmpty()) { + Exprent enclosing = lstParams.get(0); + + boolean isQualifiedNew = false; + + if (enclosing.type == Exprent.EXPRENT_VAR) { + VarExprent varEnclosing = (VarExprent)enclosing; + + StructClass current_class = ((ClassNode)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS_NODE)).classStruct; + String this_classname = varEnclosing.getProcessor().getThisvars().get(new VarVersionPaar(varEnclosing)); + + if (!current_class.qualifiedName.equals(this_classname)) { + isQualifiedNew = true; + } + } + else { + isQualifiedNew = true; + } + + if (isQualifiedNew) { + return enclosing.toJava(indent); + } + } + } + + return null; + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof NewExprent)) return false; + + NewExprent ne = (NewExprent)o; + return InterpreterUtil.equalObjects(newtype, ne.getNewtype()) && + InterpreterUtil.equalLists(lstDims, ne.getLstDims()) && + InterpreterUtil.equalObjects(constructor, ne.getConstructor()) && + directArrayInit == ne.directArrayInit && + InterpreterUtil.equalLists(lstArrayElements, ne.getLstArrayElements()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == constructor) { + constructor = (InvocationExprent)newexpr; + } + + if (constructor != null) { + constructor.replaceExprent(oldexpr, newexpr); + } + + for (int i = 0; i < lstDims.size(); i++) { + if (oldexpr == lstDims.get(i)) { + lstDims.set(i, newexpr); + } + } + + for (int i = 0; i < lstArrayElements.size(); i++) { + if (oldexpr == lstArrayElements.get(i)) { + lstArrayElements.set(i, newexpr); + } + } + } + + public InvocationExprent getConstructor() { + return constructor; + } + + public void setConstructor(InvocationExprent constructor) { + this.constructor = constructor; + } + + public List<Exprent> getLstDims() { + return lstDims; + } + + public VarType getNewtype() { + return newtype; + } + + public List<Exprent> getLstArrayElements() { + return lstArrayElements; + } + + public void setLstArrayElements(List<Exprent> lstArrayElements) { + this.lstArrayElements = lstArrayElements; + } + + public boolean isDirectArrayInit() { + return directArrayInit; + } + + public void setDirectArrayInit(boolean directArrayInit) { + this.directArrayInit = directArrayInit; + } + + public boolean isLambda() { + return lambda; + } + + public boolean isAnonymous() { + return anonymous; + } + + public void setAnonymous(boolean anonymous) { + this.anonymous = anonymous; + } + + public boolean isEnumconst() { + return enumconst; + } + + public void setEnumconst(boolean enumconst) { + this.enumconst = enumconst; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/SwitchExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/SwitchExprent.java new file mode 100644 index 000000000000..36bead20490d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/SwitchExprent.java @@ -0,0 +1,114 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class SwitchExprent extends Exprent { + + private Exprent value; + + private List<List<ConstExprent>> caseValues = new ArrayList<List<ConstExprent>>(); + + { + this.type = EXPRENT_SWITCH; + } + + public SwitchExprent(Exprent value) { + this.value = value; + } + + public Exprent copy() { + SwitchExprent swexpr = new SwitchExprent(value.copy()); + + List<List<ConstExprent>> lstCaseValues = new ArrayList<List<ConstExprent>>(); + for (List<ConstExprent> lst : caseValues) { + lstCaseValues.add(new ArrayList<ConstExprent>(lst)); + } + swexpr.setCaseValues(lstCaseValues); + + return swexpr; + } + + public VarType getExprType() { + return value.getExprType(); + } + + public CheckTypesResult checkExprTypeBounds() { + CheckTypesResult result = new CheckTypesResult(); + + result.addMinTypeExprent(value, VarType.VARTYPE_BYTECHAR); + result.addMaxTypeExprent(value, VarType.VARTYPE_INT); + + VarType valtype = value.getExprType(); + for (List<ConstExprent> lst : caseValues) { + for (ConstExprent expr : lst) { + if (expr != null) { + VarType casetype = expr.getExprType(); + if (!casetype.equals(valtype)) { + valtype = VarType.getCommonSupertype(casetype, valtype); + result.addMinTypeExprent(value, valtype); + } + } + } + } + + return result; + } + + public List<Exprent> getAllExprents() { + List<Exprent> lst = new ArrayList<Exprent>(); + lst.add(value); + return lst; + } + + public String toJava(int indent) { + return "switch(" + value.toJava(indent) + ")"; + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } + + if (o == null || !(o instanceof SwitchExprent)) { + return false; + } + + SwitchExprent sw = (SwitchExprent)o; + return InterpreterUtil.equalObjects(value, sw.getValue()); + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (oldexpr == value) { + value = newexpr; + } + } + + public Exprent getValue() { + return value; + } + + public void setCaseValues(List<List<ConstExprent>> caseValues) { + this.caseValues = caseValues; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/VarExprent.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/VarExprent.java new file mode 100644 index 000000000000..352350171a7a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/exps/VarExprent.java @@ -0,0 +1,182 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.exps; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.ClassWriter; +import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarTypeProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + +public class VarExprent extends Exprent { + + public static final int STACK_BASE = 10000; + + public static final String VAR_NAMELESS_ENCLOSURE = "<VAR_NAMELESS_ENCLOSURE>"; + + private int index; + + private VarType vartype; + + private boolean definition = false; + + private VarProcessor processor; + + private int version = 0; + + private boolean classdef = false; + + private boolean stack = false; + + { + this.type = EXPRENT_VAR; + } + + public VarExprent(int index, VarType vartype, VarProcessor processor) { + this.index = index; + this.vartype = vartype; + this.processor = processor; + } + + public VarType getExprType() { + return getVartype(); + } + + public int getExprentUse() { + return Exprent.MULTIPLE_USES | Exprent.SIDE_EFFECTS_FREE; + } + + public List<Exprent> getAllExprents() { + return new ArrayList<Exprent>(); + } + + public Exprent copy() { + VarExprent var = new VarExprent(index, getVartype(), processor); + var.setDefinition(definition); + var.setVersion(version); + var.setClassdef(classdef); + var.setStack(stack); + return var; + } + + public String toJava(int indent) { + StringBuilder buffer = new StringBuilder(); + + if (classdef) { + ClassNode child = DecompilerContext.getClassProcessor().getMapRootClasses().get(vartype.value); + new ClassWriter().classToJava(child, buffer, indent); + } + else { + String name = null; + if (processor != null) { + name = processor.getVarName(new VarVersionPaar(index, version)); + } + + if (definition) { + if (processor != null && processor.getVarFinal(new VarVersionPaar(index, version)) == VarTypeProcessor.VAR_FINALEXPLICIT) { + buffer.append("final "); + } + buffer.append(ExprProcessor.getCastTypeName(getVartype())).append(" "); + } + buffer.append(name == null ? ("var" + index + (version == 0 ? "" : "_" + version)) : name); + } + + return buffer.toString(); + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof VarExprent)) return false; + + VarExprent ve = (VarExprent)o; + return index == ve.getIndex() && + version == ve.getVersion() && + InterpreterUtil.equalObjects(getVartype(), ve.getVartype()); // FIXME: vartype comparison redundant? + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public VarType getVartype() { + VarType vt = null; + if (processor != null) { + vt = processor.getVarType(new VarVersionPaar(index, version)); + } + + if (vt == null || (vartype != null && vartype.type != CodeConstants.TYPE_UNKNOWN)) { + vt = vartype; + } + + return vt == null ? VarType.VARTYPE_UNKNOWN : vt; + } + + public void setVartype(VarType vartype) { + this.vartype = vartype; + } + + public boolean isDefinition() { + return definition; + } + + public void setDefinition(boolean definition) { + this.definition = definition; + } + + public VarProcessor getProcessor() { + return processor; + } + + public void setProcessor(VarProcessor processor) { + this.processor = processor; + } + + public int getVersion() { + return version; + } + + public void setVersion(int version) { + this.version = version; + } + + public boolean isClassdef() { + return classdef; + } + + public void setClassdef(boolean classdef) { + this.classdef = classdef; + } + + public boolean isStack() { + return stack; + } + + public void setStack(boolean stack) { + this.stack = stack; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/DirectGraph.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/DirectGraph.java new file mode 100644 index 000000000000..b24b72c261ea --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/DirectGraph.java @@ -0,0 +1,136 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.sforms; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper.FinallyPathWrapper; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + + +public class DirectGraph { + + public VBStyleCollection<DirectNode, String> nodes = new VBStyleCollection<DirectNode, String>(); + + public DirectNode first; + + // exit, [source, destination] + public HashMap<String, List<FinallyPathWrapper>> mapShortRangeFinallyPaths = new HashMap<String, List<FinallyPathWrapper>>(); + + // exit, [source, destination] + public HashMap<String, List<FinallyPathWrapper>> mapLongRangeFinallyPaths = new HashMap<String, List<FinallyPathWrapper>>(); + + // negative if branches (recorded for handling of && and ||) + public HashMap<String, String> mapNegIfBranch = new HashMap<String, String>(); + + // nodes, that are exception exits of a finally block with monitor variable + public HashMap<String, String> mapFinallyMonitorExceptionPathExits = new HashMap<String, String>(); + + public void sortReversePostOrder() { + LinkedList<DirectNode> res = new LinkedList<DirectNode>(); + addToReversePostOrderListIterative(first, res); + + nodes.clear(); + for (DirectNode node : res) { + nodes.addWithKey(node, node.id); + } + } + + private static void addToReversePostOrderListIterative(DirectNode root, List<DirectNode> lst) { + + LinkedList<DirectNode> stackNode = new LinkedList<DirectNode>(); + LinkedList<Integer> stackIndex = new LinkedList<Integer>(); + + HashSet<DirectNode> setVisited = new HashSet<DirectNode>(); + + stackNode.add(root); + stackIndex.add(0); + + while (!stackNode.isEmpty()) { + + DirectNode node = stackNode.getLast(); + int index = stackIndex.removeLast(); + + setVisited.add(node); + + for (; index < node.succs.size(); index++) { + DirectNode succ = node.succs.get(index); + + if (!setVisited.contains(succ)) { + stackIndex.add(index + 1); + + stackNode.add(succ); + stackIndex.add(0); + + break; + } + } + + if (index == node.succs.size()) { + lst.add(0, node); + + stackNode.removeLast(); + } + } + } + + + public boolean iterateExprents(ExprentIterator iter) { + + LinkedList<DirectNode> stack = new LinkedList<DirectNode>(); + stack.add(first); + + HashSet<DirectNode> setVisited = new HashSet<DirectNode>(); + + while (!stack.isEmpty()) { + + DirectNode node = stack.removeFirst(); + + if (setVisited.contains(node)) { + continue; + } + setVisited.add(node); + + for (int i = 0; i < node.exprents.size(); i++) { + int res = iter.processExprent(node.exprents.get(i)); + + if (res == 1) { + return false; + } + + if (res == 2) { + node.exprents.remove(i); + i--; + } + } + + stack.addAll(node.succs); + } + + return true; + } + + public interface ExprentIterator { + // 0 - success, do nothing + // 1 - cancel iteration + // 2 - success, delete exprent + int processExprent(Exprent exprent); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/DirectNode.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/DirectNode.java new file mode 100644 index 000000000000..73303ec6a6d4 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/DirectNode.java @@ -0,0 +1,67 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.sforms; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.BasicBlockStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; + +import java.util.ArrayList; +import java.util.List; + + +public class DirectNode { + + public static final int NODE_DIRECT = 1; + public static final int NODE_TAIL = 2; + public static final int NODE_INIT = 3; + public static final int NODE_CONDITION = 4; + public static final int NODE_INCREMENT = 5; + public static final int NODE_TRY = 6; + + public int type; + + public String id; + + public BasicBlockStatement block; + + public Statement statement; + + public List<Exprent> exprents = new ArrayList<Exprent>(); + + public List<DirectNode> succs = new ArrayList<DirectNode>(); + + public List<DirectNode> preds = new ArrayList<DirectNode>(); + + public DirectNode(int type, Statement statement, String id) { + this.type = type; + this.statement = statement; + this.id = id; + } + + public DirectNode(int type, Statement statement, BasicBlockStatement block) { + this.type = type; + this.statement = statement; + + this.id = block.id.toString(); + this.block = block; + } + + @Override + public String toString() { + return id; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/FlattenStatementsHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/FlattenStatementsHelper.java new file mode 100644 index 000000000000..05d2f33b27e5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/FlattenStatementsHelper.java @@ -0,0 +1,574 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.sforms; + +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; + +import java.util.*; +import java.util.Map.Entry; + + +public class FlattenStatementsHelper { + + // statement.id, node.id(direct), node.id(continue) + private Map<Integer, String[]> mapDestinationNodes = new HashMap<Integer, String[]>(); + + // node.id(source), statement.id(destination), edge type + private List<Edge> listEdges = new ArrayList<Edge>(); + + // node.id(exit), [node.id(source), statement.id(destination)] + private Map<String, List<String[]>> mapShortRangeFinallyPathIds = new HashMap<String, List<String[]>>(); + + // node.id(exit), [node.id(source), statement.id(destination)] + private Map<String, List<String[]>> mapLongRangeFinallyPathIds = new HashMap<String, List<String[]>>(); + + // positive if branches + private Map<String, Integer> mapPosIfBranch = new HashMap<String, Integer>(); + + private DirectGraph graph; + + private RootStatement root; + + public DirectGraph buildDirectGraph(RootStatement root) { + + this.root = root; + + graph = new DirectGraph(); + + flattenStatement(); + + // dummy exit node + Statement dummyexit = root.getDummyExit(); + DirectNode node = new DirectNode(DirectNode.NODE_DIRECT, dummyexit, dummyexit.id.toString()); + node.exprents = new ArrayList<Exprent>(); + graph.nodes.addWithKey(node, node.id); + mapDestinationNodes.put(dummyexit.id, new String[]{node.id, null}); + + setEdges(); + + graph.first = graph.nodes.getWithKey(mapDestinationNodes.get(root.id)[0]); + graph.sortReversePostOrder(); + + return graph; + } + + private void flattenStatement() { + + class StatementStackEntry { + public Statement statement; + public LinkedList<StackEntry> stackFinally; + public List<Exprent> tailExprents; + + public int statementIndex; + public int edgeIndex; + public List<StatEdge> succEdges; + + public StatementStackEntry(Statement statement, LinkedList<StackEntry> stackFinally, List<Exprent> tailExprents) { + this.statement = statement; + this.stackFinally = stackFinally; + this.tailExprents = tailExprents; + } + } + + LinkedList<StatementStackEntry> lstStackStatements = new LinkedList<StatementStackEntry>(); + + lstStackStatements.add(new StatementStackEntry(root, new LinkedList<StackEntry>(), null)); + + mainloop: + while (!lstStackStatements.isEmpty()) { + + StatementStackEntry statEntry = lstStackStatements.removeFirst(); + + Statement stat = statEntry.statement; + LinkedList<StackEntry> stackFinally = statEntry.stackFinally; + int statementBreakIndex = statEntry.statementIndex; + + DirectNode node, nd; + + List<StatEdge> lstSuccEdges = new ArrayList<StatEdge>(); + DirectNode sourcenode = null; + + if (statEntry.succEdges == null) { + + switch (stat.type) { + case Statement.TYPE_BASICBLOCK: + node = new DirectNode(DirectNode.NODE_DIRECT, stat, (BasicBlockStatement)stat); + if (stat.getExprents() != null) { + node.exprents = stat.getExprents(); + } + graph.nodes.putWithKey(node, node.id); + mapDestinationNodes.put(stat.id, new String[]{node.id, null}); + + lstSuccEdges.addAll(stat.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL)); + sourcenode = node; + + List<Exprent> tailExprentList = statEntry.tailExprents; + + if (tailExprentList != null) { + DirectNode tail = new DirectNode(DirectNode.NODE_TAIL, stat, stat.id + "_tail"); + tail.exprents = tailExprentList; + graph.nodes.putWithKey(tail, tail.id); + + mapDestinationNodes.put(-stat.id, new String[]{tail.id, null}); + listEdges.add(new Edge(node.id, -stat.id, StatEdge.TYPE_REGULAR)); + + sourcenode = tail; + } + + // 'if' statement: record positive branch + if (stat.getLastBasicType() == Statement.LASTBASICTYPE_IF) { + mapPosIfBranch.put(sourcenode.id, lstSuccEdges.get(0).getDestination().id); + } + + break; + case Statement.TYPE_CATCHALL: + case Statement.TYPE_TRYCATCH: + DirectNode firstnd = new DirectNode(DirectNode.NODE_TRY, stat, stat.id + "_try"); + + mapDestinationNodes.put(stat.id, new String[]{firstnd.id, null}); + graph.nodes.putWithKey(firstnd, firstnd.id); + + LinkedList<StatementStackEntry> lst = new LinkedList<StatementStackEntry>(); + + for (Statement st : stat.getStats()) { + listEdges.add(new Edge(firstnd.id, st.id, StatEdge.TYPE_REGULAR)); + + LinkedList<StackEntry> stack = stackFinally; + if (stat.type == Statement.TYPE_CATCHALL && ((CatchAllStatement)stat).isFinally()) { + stack = new LinkedList<StackEntry>(stackFinally); + + if (st == stat.getFirst()) { // catch head + stack.add(new StackEntry((CatchAllStatement)stat, Boolean.FALSE)); + } + else { // handler + stack.add(new StackEntry((CatchAllStatement)stat, Boolean.TRUE, StatEdge.TYPE_BREAK, + root.getDummyExit(), st, st, firstnd, firstnd, true)); + } + } + lst.add(new StatementStackEntry(st, stack, null)); + } + + lstStackStatements.addAll(0, lst); + break; + case Statement.TYPE_DO: + if (statementBreakIndex == 0) { + statEntry.statementIndex = 1; + lstStackStatements.addFirst(statEntry); + lstStackStatements.addFirst(new StatementStackEntry(stat.getFirst(), stackFinally, null)); + + continue mainloop; + } + + nd = graph.nodes.getWithKey(mapDestinationNodes.get(stat.getFirst().id)[0]); + + DoStatement dostat = (DoStatement)stat; + int looptype = dostat.getLooptype(); + + if (looptype == DoStatement.LOOP_DO) { + mapDestinationNodes.put(stat.id, new String[]{nd.id, nd.id}); + break; + } + + lstSuccEdges.add(stat.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL).get(0)); // exactly one edge + + switch (looptype) { + case DoStatement.LOOP_WHILE: + case DoStatement.LOOP_DOWHILE: + node = new DirectNode(DirectNode.NODE_CONDITION, stat, stat.id + "_cond"); + node.exprents = dostat.getConditionExprentList(); + graph.nodes.putWithKey(node, node.id); + + listEdges.add(new Edge(node.id, stat.getFirst().id, StatEdge.TYPE_REGULAR)); + + if (looptype == DoStatement.LOOP_WHILE) { + mapDestinationNodes.put(stat.id, new String[]{node.id, node.id}); + } + else { + mapDestinationNodes.put(stat.id, new String[]{nd.id, node.id}); + + boolean found = false; + for (Edge edge : listEdges) { + if (edge.statid.equals(stat.id) && edge.edgetype == StatEdge.TYPE_CONTINUE) { + found = true; + break; + } + } + if (!found) { + listEdges.add(new Edge(nd.id, stat.id, StatEdge.TYPE_CONTINUE)); + } + } + sourcenode = node; + break; + case DoStatement.LOOP_FOR: + DirectNode nodeinit = new DirectNode(DirectNode.NODE_INIT, stat, stat.id + "_init"); + if (dostat.getInitExprent() != null) { + nodeinit.exprents = dostat.getInitExprentList(); + } + graph.nodes.putWithKey(nodeinit, nodeinit.id); + + DirectNode nodecond = new DirectNode(DirectNode.NODE_CONDITION, stat, stat.id + "_cond"); + nodecond.exprents = dostat.getConditionExprentList(); + graph.nodes.putWithKey(nodecond, nodecond.id); + + DirectNode nodeinc = new DirectNode(DirectNode.NODE_INCREMENT, stat, stat.id + "_inc"); + nodeinc.exprents = dostat.getIncExprentList(); + graph.nodes.putWithKey(nodeinc, nodeinc.id); + + mapDestinationNodes.put(stat.id, new String[]{nodeinit.id, nodeinc.id}); + mapDestinationNodes.put(-stat.id, new String[]{nodecond.id, null}); + + listEdges.add(new Edge(nodecond.id, stat.getFirst().id, StatEdge.TYPE_REGULAR)); + listEdges.add(new Edge(nodeinit.id, -stat.id, StatEdge.TYPE_REGULAR)); + listEdges.add(new Edge(nodeinc.id, -stat.id, StatEdge.TYPE_REGULAR)); + + boolean found = false; + for (Edge edge : listEdges) { + if (edge.statid.equals(stat.id) && edge.edgetype == StatEdge.TYPE_CONTINUE) { + found = true; + break; + } + } + if (!found) { + listEdges.add(new Edge(nd.id, stat.id, StatEdge.TYPE_CONTINUE)); + } + + sourcenode = nodecond; + } + break; + case Statement.TYPE_SYNCRONIZED: + case Statement.TYPE_SWITCH: + case Statement.TYPE_IF: + case Statement.TYPE_SEQUENCE: + case Statement.TYPE_ROOT: + int statsize = stat.getStats().size(); + if (stat.type == Statement.TYPE_SYNCRONIZED) { + statsize = 2; // exclude the handler if synchronized + } + + if (statementBreakIndex <= statsize) { + List<Exprent> tailexprlst = null; + + switch (stat.type) { + case Statement.TYPE_SYNCRONIZED: + tailexprlst = ((SynchronizedStatement)stat).getHeadexprentList(); + break; + case Statement.TYPE_SWITCH: + tailexprlst = ((SwitchStatement)stat).getHeadexprentList(); + break; + case Statement.TYPE_IF: + tailexprlst = ((IfStatement)stat).getHeadexprentList(); + } + + for (int i = statementBreakIndex; i < statsize; i++) { + statEntry.statementIndex = i + 1; + lstStackStatements.addFirst(statEntry); + lstStackStatements.addFirst( + new StatementStackEntry(stat.getStats().get(i), stackFinally, + (i == 0 && tailexprlst != null && tailexprlst.get(0) != null) ? tailexprlst : null)); + + continue mainloop; + } + + node = graph.nodes.getWithKey(mapDestinationNodes.get(stat.getFirst().id)[0]); + mapDestinationNodes.put(stat.id, new String[]{node.id, null}); + + if (stat.type == Statement.TYPE_IF && ((IfStatement)stat).iftype == IfStatement.IFTYPE_IF) { + lstSuccEdges.add(stat.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL).get(0)); // exactly one edge + sourcenode = tailexprlst.get(0) == null ? node : graph.nodes.getWithKey(node.id + "_tail"); + } + } + } + } + + // no successor edges + if (sourcenode != null) { + + if (statEntry.succEdges != null) { + lstSuccEdges = statEntry.succEdges; + } + + for (int edgeindex = statEntry.edgeIndex; edgeindex < lstSuccEdges.size(); edgeindex++) { + + StatEdge edge = lstSuccEdges.get(edgeindex); + + LinkedList<StackEntry> stack = new LinkedList<StackEntry>(stackFinally); + + int edgetype = edge.getType(); + Statement destination = edge.getDestination(); + + DirectNode finallyShortRangeSource = sourcenode; + DirectNode finallyLongRangeSource = sourcenode; + Statement finallyShortRangeEntry = null; + Statement finallyLongRangeEntry = null; + + boolean isFinallyMonitorExceptionPath = false; + + boolean isFinallyExit = false; + + while (true) { + + StackEntry entry = null; + if (!stack.isEmpty()) { + entry = stack.getLast(); + } + + boolean created = true; + + if (entry == null) { + saveEdge(sourcenode, destination, edgetype, isFinallyExit ? finallyShortRangeSource : null, finallyLongRangeSource, + finallyShortRangeEntry, finallyLongRangeEntry, isFinallyMonitorExceptionPath); + } + else { + + CatchAllStatement catchall = entry.catchstatement; + + if (entry.state) { // finally handler statement + if (edgetype == StatEdge.TYPE_FINALLYEXIT) { + + stack.removeLast(); + destination = entry.destination; + edgetype = entry.edgetype; + + finallyShortRangeSource = entry.finallyShortRangeSource; + finallyLongRangeSource = entry.finallyLongRangeSource; + finallyShortRangeEntry = entry.finallyShortRangeEntry; + finallyLongRangeEntry = entry.finallyLongRangeEntry; + + isFinallyExit = true; + isFinallyMonitorExceptionPath = (catchall.getMonitor() != null) & entry.isFinallyExceptionPath; + + created = false; + } + else { + if (!catchall.containsStatementStrict(destination)) { + stack.removeLast(); + created = false; + } + else { + saveEdge(sourcenode, destination, edgetype, isFinallyExit ? finallyShortRangeSource : null, finallyLongRangeSource, + finallyShortRangeEntry, finallyLongRangeEntry, isFinallyMonitorExceptionPath); + } + } + } + else { // finally protected try statement + if (!catchall.containsStatementStrict(destination)) { + saveEdge(sourcenode, catchall.getHandler(), StatEdge.TYPE_REGULAR, isFinallyExit ? finallyShortRangeSource : null, + finallyLongRangeSource, finallyShortRangeEntry, finallyLongRangeEntry, isFinallyMonitorExceptionPath); + + stack.removeLast(); + stack.add(new StackEntry(catchall, Boolean.TRUE, edgetype, destination, catchall.getHandler(), + finallyLongRangeEntry == null ? catchall.getHandler() : finallyLongRangeEntry, + sourcenode, finallyLongRangeSource, false)); + + statEntry.edgeIndex = edgeindex + 1; + statEntry.succEdges = lstSuccEdges; + lstStackStatements.addFirst(statEntry); + lstStackStatements.addFirst(new StatementStackEntry(catchall.getHandler(), stack, null)); + + continue mainloop; + } + else { + saveEdge(sourcenode, destination, edgetype, isFinallyExit ? finallyShortRangeSource : null, finallyLongRangeSource, + finallyShortRangeEntry, finallyLongRangeEntry, isFinallyMonitorExceptionPath); + } + } + } + + if (created) { + break; + } + } + } + } + } + } + + private void saveEdge(DirectNode sourcenode, + Statement destination, + int edgetype, + DirectNode finallyShortRangeSource, + DirectNode finallyLongRangeSource, + Statement finallyShortRangeEntry, + Statement finallyLongRangeEntry, + boolean isFinallyMonitorExceptionPath) { + + if (edgetype != StatEdge.TYPE_FINALLYEXIT) { + listEdges.add(new Edge(sourcenode.id, destination.id, edgetype)); + } + + if (finallyShortRangeSource != null) { + + boolean isContinueEdge = (edgetype == StatEdge.TYPE_CONTINUE); + + List<String[]> lst = mapShortRangeFinallyPathIds.get(sourcenode.id); + if (lst == null) { + mapShortRangeFinallyPathIds.put(sourcenode.id, lst = new ArrayList<String[]>()); + } + lst.add(new String[]{finallyShortRangeSource.id, destination.id.toString(), finallyShortRangeEntry.id.toString(), + isFinallyMonitorExceptionPath ? "1" : null, isContinueEdge ? "1" : null}); + + lst = mapLongRangeFinallyPathIds.get(sourcenode.id); + if (lst == null) { + mapLongRangeFinallyPathIds.put(sourcenode.id, lst = new ArrayList<String[]>()); + } + lst.add(new String[]{finallyLongRangeSource.id, destination.id.toString(), finallyLongRangeEntry.id.toString(), + isContinueEdge ? "1" : null}); + } + } + + private void setEdges() { + + for (Edge edge : listEdges) { + + String sourceid = edge.sourceid; + Integer statid = edge.statid; + + DirectNode source = graph.nodes.getWithKey(sourceid); + + DirectNode dest = graph.nodes.getWithKey(mapDestinationNodes.get(statid)[edge.edgetype == StatEdge.TYPE_CONTINUE ? 1 : 0]); + + if (!source.succs.contains(dest)) { + source.succs.add(dest); + } + + if (!dest.preds.contains(source)) { + dest.preds.add(source); + } + + if (mapPosIfBranch.containsKey(sourceid) && !statid.equals(mapPosIfBranch.get(sourceid))) { + graph.mapNegIfBranch.put(sourceid, dest.id); + } + } + + for (int i = 0; i < 2; i++) { + for (Entry<String, List<String[]>> ent : (i == 0 ? mapShortRangeFinallyPathIds : mapLongRangeFinallyPathIds).entrySet()) { + + List<FinallyPathWrapper> newLst = new ArrayList<FinallyPathWrapper>(); + + List<String[]> lst = ent.getValue(); + for (String[] arr : lst) { + + boolean isContinueEdge = arr[i == 0 ? 4 : 3] != null; + + DirectNode dest = graph.nodes.getWithKey(mapDestinationNodes.get(Integer.parseInt(arr[1]))[isContinueEdge ? 1 : 0]); + DirectNode enter = graph.nodes.getWithKey(mapDestinationNodes.get(Integer.parseInt(arr[2]))[0]); + + newLst.add(new FinallyPathWrapper(arr[0], dest.id, enter.id)); + + if (i == 0 && arr[3] != null) { + graph.mapFinallyMonitorExceptionPathExits.put(ent.getKey(), dest.id); + } + } + + if (!newLst.isEmpty()) { + (i == 0 ? graph.mapShortRangeFinallyPaths : graph.mapLongRangeFinallyPaths).put(ent.getKey(), + new ArrayList<FinallyPathWrapper>( + new HashSet<FinallyPathWrapper>(newLst))); + } + } + } + } + + public Map<Integer, String[]> getMapDestinationNodes() { + return mapDestinationNodes; + } + + public static class FinallyPathWrapper { + public String source; + public String destination; + public String entry; + + private FinallyPathWrapper(String source, String destination, String entry) { + this.source = source; + this.destination = destination; + this.entry = entry; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof FinallyPathWrapper)) return false; + + FinallyPathWrapper fpw = (FinallyPathWrapper)o; + return (source + ":" + destination + ":" + entry).equals(fpw.source + ":" + fpw.destination + ":" + fpw.entry); + } + + @Override + public int hashCode() { + return (source + ":" + destination + ":" + entry).hashCode(); + } + + @Override + public String toString() { + return source + "->(" + entry + ")->" + destination; + } + } + + + private static class StackEntry { + + public CatchAllStatement catchstatement; + public boolean state; + public int edgetype; + public boolean isFinallyExceptionPath; + + public Statement destination; + public Statement finallyShortRangeEntry; + public Statement finallyLongRangeEntry; + public DirectNode finallyShortRangeSource; + public DirectNode finallyLongRangeSource; + + public StackEntry(CatchAllStatement catchstatement, + boolean state, + int edgetype, + Statement destination, + Statement finallyShortRangeEntry, + Statement finallyLongRangeEntry, + DirectNode finallyShortRangeSource, + DirectNode finallyLongRangeSource, + boolean isFinallyExceptionPath) { + + this.catchstatement = catchstatement; + this.state = state; + this.edgetype = edgetype; + this.isFinallyExceptionPath = isFinallyExceptionPath; + + this.destination = destination; + this.finallyShortRangeEntry = finallyShortRangeEntry; + this.finallyLongRangeEntry = finallyLongRangeEntry; + this.finallyShortRangeSource = finallyShortRangeSource; + this.finallyLongRangeSource = finallyLongRangeSource; + } + + public StackEntry(CatchAllStatement catchstatement, boolean state) { + this(catchstatement, state, -1, null, null, null, null, null, false); + } + } + + private static class Edge { + public String sourceid; + public Integer statid; + public int edgetype; + + public Edge(String sourceid, Integer statid, int edgetype) { + this.sourceid = sourceid; + this.statid = statid; + this.edgetype = edgetype; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/SSAConstructorSparseEx.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/SSAConstructorSparseEx.java new file mode 100644 index 000000000000..dbec7937c77a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/SSAConstructorSparseEx.java @@ -0,0 +1,529 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.sforms; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.modules.decompiler.exps.AssignmentExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.FunctionExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper.FinallyPathWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchAllStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory.FastSparseSet; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.SFormsFastMapDirect; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; + +public class SSAConstructorSparseEx { + + // node id, var, version + private HashMap<String, SFormsFastMapDirect> inVarVersions = new HashMap<String, SFormsFastMapDirect>(); + + // node id, var, version (direct branch) + private HashMap<String, SFormsFastMapDirect> outVarVersions = new HashMap<String, SFormsFastMapDirect>(); + + // node id, var, version (negative branch) + private HashMap<String, SFormsFastMapDirect> outNegVarVersions = new HashMap<String, SFormsFastMapDirect>(); + + // node id, var, version + private HashMap<String, SFormsFastMapDirect> extraVarVersions = new HashMap<String, SFormsFastMapDirect>(); + + // (var, version), version + private HashMap<VarVersionPaar, FastSparseSet<Integer>> phi = new HashMap<VarVersionPaar, FastSparseSet<Integer>>(); + + // var, version + private HashMap<Integer, Integer> lastversion = new HashMap<Integer, Integer>(); + + private List<VarVersionPaar> startVars = new ArrayList<VarVersionPaar>(); + + // set factory + private FastSparseSetFactory<Integer> factory; + + public void splitVariables(RootStatement root, StructMethod mt) { + + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + DirectGraph dgraph = flatthelper.buildDirectGraph(root); + + // try { + // DotExporter.toDotFile(dgraph, new File("c:\\Temp\\gr12_my.dot")); + // } catch(Exception ex) {ex.printStackTrace();} + + HashSet<Integer> setInit = new HashSet<Integer>(); + for (int i = 0; i < 64; i++) { + setInit.add(i); + } + factory = new FastSparseSetFactory<Integer>(setInit); + + SFormsFastMapDirect firstmap = createFirstMap(mt); + extraVarVersions.put(dgraph.first.id, firstmap); + + setCatchMaps(root, dgraph, flatthelper); + + HashSet<String> updated = new HashSet<String>(); + do { + // System.out.println("~~~~~~~~~~~~~ \r\n"+root.toJava()); + ssaStatements(dgraph, updated); + // System.out.println("~~~~~~~~~~~~~ \r\n"+root.toJava()); + } + while (!updated.isEmpty()); + } + + private void ssaStatements(DirectGraph dgraph, HashSet<String> updated) { + + // try { + // DotExporter.toDotFile(dgraph, new File("c:\\Temp\\gr1_my.dot")); + // } catch(Exception ex) {ex.printStackTrace();} + + for (DirectNode node : dgraph.nodes) { + + // if (node.id.endsWith("_inc")) { + // System.out.println(); + // + // try { + // DotExporter.toDotFile(dgraph, new File("c:\\Temp\\gr1_my.dot")); + // } catch (Exception ex) { + // ex.printStackTrace(); + // } + // } + + updated.remove(node.id); + mergeInVarMaps(node, dgraph); + + SFormsFastMapDirect varmap = inVarVersions.get(node.id); + varmap = new SFormsFastMapDirect(varmap); + + SFormsFastMapDirect[] varmaparr = new SFormsFastMapDirect[]{varmap, null}; + + if (node.exprents != null) { + for (Exprent expr : node.exprents) { + processExprent(expr, varmaparr); + } + } + + if (varmaparr[1] == null) { + varmaparr[1] = varmaparr[0]; + } + + boolean this_updated = !mapsEqual(varmaparr[0], outVarVersions.get(node.id)) + || (outNegVarVersions.containsKey(node.id) && !mapsEqual(varmaparr[1], outNegVarVersions.get(node.id))); + + if (this_updated) { + outVarVersions.put(node.id, varmaparr[0]); + if (dgraph.mapNegIfBranch.containsKey(node.id)) { + outNegVarVersions.put(node.id, varmaparr[1]); + } + + for (DirectNode nd : node.succs) { + updated.add(nd.id); + } + } + } + } + + private void processExprent(Exprent expr, SFormsFastMapDirect[] varmaparr) { + + if (expr == null) { + return; + } + + VarExprent varassign = null; + boolean finished = false; + + switch (expr.type) { + case Exprent.EXPRENT_ASSIGNMENT: + AssignmentExprent assexpr = (AssignmentExprent)expr; + if (assexpr.getCondtype() == AssignmentExprent.CONDITION_NONE) { + Exprent dest = assexpr.getLeft(); + if (dest.type == Exprent.EXPRENT_VAR) { + varassign = (VarExprent)dest; + } + } + break; + case Exprent.EXPRENT_FUNCTION: + FunctionExprent func = (FunctionExprent)expr; + switch (func.getFunctype()) { + case FunctionExprent.FUNCTION_IIF: + processExprent(func.getLstOperands().get(0), varmaparr); + + SFormsFastMapDirect varmapFalse; + if (varmaparr[1] == null) { + varmapFalse = new SFormsFastMapDirect(varmaparr[0]); + } + else { + varmapFalse = varmaparr[1]; + varmaparr[1] = null; + } + + processExprent(func.getLstOperands().get(1), varmaparr); + + SFormsFastMapDirect[] varmaparrNeg = new SFormsFastMapDirect[]{varmapFalse, null}; + processExprent(func.getLstOperands().get(2), varmaparrNeg); + + mergeMaps(varmaparr[0], varmaparrNeg[0]); + varmaparr[1] = null; + + finished = true; + break; + case FunctionExprent.FUNCTION_CADD: + processExprent(func.getLstOperands().get(0), varmaparr); + + SFormsFastMapDirect[] varmaparrAnd = new SFormsFastMapDirect[]{new SFormsFastMapDirect(varmaparr[0]), null}; + + processExprent(func.getLstOperands().get(1), varmaparrAnd); + + // false map + varmaparr[1] = mergeMaps(varmaparr[varmaparr[1] == null ? 0 : 1], varmaparrAnd[varmaparrAnd[1] == null ? 0 : 1]); + // true map + varmaparr[0] = varmaparrAnd[0]; + + finished = true; + break; + case FunctionExprent.FUNCTION_COR: + processExprent(func.getLstOperands().get(0), varmaparr); + + SFormsFastMapDirect[] varmaparrOr = + new SFormsFastMapDirect[]{new SFormsFastMapDirect(varmaparr[varmaparr[1] == null ? 0 : 1]), null}; + + processExprent(func.getLstOperands().get(1), varmaparrOr); + + // false map + varmaparr[1] = varmaparrOr[varmaparrOr[1] == null ? 0 : 1]; + // true map + varmaparr[0] = mergeMaps(varmaparr[0], varmaparrOr[0]); + + finished = true; + } + } + + if (finished) { + return; + } + + List<Exprent> lst = expr.getAllExprents(); + lst.remove(varassign); + + for (Exprent ex : lst) { + processExprent(ex, varmaparr); + } + + SFormsFastMapDirect varmap = varmaparr[0]; + + if (varassign != null) { + + Integer varindex = varassign.getIndex(); + + if (varassign.getVersion() == 0) { + // get next version + Integer nextver = getNextFreeVersion(varindex); + + // set version + varassign.setVersion(nextver); + + setCurrentVar(varmap, varindex, nextver); + } + else { + setCurrentVar(varmap, varindex, varassign.getVersion()); + } + } + else if (expr.type == Exprent.EXPRENT_VAR) { + + VarExprent vardest = (VarExprent)expr; + Integer varindex = vardest.getIndex(); + FastSparseSet<Integer> vers = varmap.get(varindex); + + int cardinality = vers.getCardinality(); + if (cardinality == 1) { // == 1 + // set version + Integer it = vers.iterator().next(); + vardest.setVersion(it.intValue()); + } + else if (cardinality == 2) { // size > 1 + Integer current_vers = vardest.getVersion(); + + VarVersionPaar currpaar = new VarVersionPaar(varindex, current_vers); + if (current_vers != 0 && phi.containsKey(currpaar)) { + setCurrentVar(varmap, varindex, current_vers); + // update phi node + phi.get(currpaar).union(vers); + } + else { + // increase version + Integer nextver = getNextFreeVersion(varindex); + // set version + vardest.setVersion(nextver); + + setCurrentVar(varmap, varindex, nextver); + // create new phi node + phi.put(new VarVersionPaar(varindex, nextver), vers); + } + } // 0 means uninitialized variable, which is impossible + } + } + + private Integer getNextFreeVersion(Integer var) { + Integer nextver = lastversion.get(var); + if (nextver == null) { + nextver = new Integer(1); + } + else { + nextver = new Integer(nextver.intValue() + 1); + } + lastversion.put(var, nextver); + return nextver; + } + + private void mergeInVarMaps(DirectNode node, DirectGraph dgraph) { + + SFormsFastMapDirect mapNew = new SFormsFastMapDirect(); + + for (DirectNode pred : node.preds) { + SFormsFastMapDirect mapOut = getFilteredOutMap(node.id, pred.id, dgraph, node.id); + if (mapNew.isEmpty()) { + mapNew = mapOut.getCopy(); + } + else { + mergeMaps(mapNew, mapOut); + } + } + + if (extraVarVersions.containsKey(node.id)) { + SFormsFastMapDirect mapExtra = extraVarVersions.get(node.id); + if (mapNew.isEmpty()) { + mapNew = mapExtra.getCopy(); + } + else { + mergeMaps(mapNew, mapExtra); + } + } + + inVarVersions.put(node.id, mapNew); + } + + private SFormsFastMapDirect getFilteredOutMap(String nodeid, String predid, DirectGraph dgraph, String destid) { + + SFormsFastMapDirect mapNew = new SFormsFastMapDirect(); + + if (nodeid.equals(dgraph.mapNegIfBranch.get(predid))) { + if (outNegVarVersions.containsKey(predid)) { + mapNew = outNegVarVersions.get(predid).getCopy(); + } + } + else if (outVarVersions.containsKey(predid)) { + mapNew = outVarVersions.get(predid).getCopy(); + } + + boolean isFinallyExit = dgraph.mapShortRangeFinallyPaths.containsKey(predid); + + if (isFinallyExit && !mapNew.isEmpty()) { + + SFormsFastMapDirect mapNewTemp = mapNew.getCopy(); + + SFormsFastMapDirect mapTrueSource = new SFormsFastMapDirect(); + + String exceptionDest = dgraph.mapFinallyMonitorExceptionPathExits.get(predid); + boolean isExceptionMonitorExit = (exceptionDest != null && !nodeid.equals(exceptionDest)); + + HashSet<String> setLongPathWrapper = new HashSet<String>(); + for (FinallyPathWrapper finwraplong : dgraph.mapLongRangeFinallyPaths.get(predid)) { + setLongPathWrapper.add(finwraplong.destination + "##" + finwraplong.source); + } + + for (FinallyPathWrapper finwrap : dgraph.mapShortRangeFinallyPaths.get(predid)) { + SFormsFastMapDirect map; + + boolean recFinally = dgraph.mapShortRangeFinallyPaths.containsKey(finwrap.source); + + if (recFinally) { + // recursion + map = getFilteredOutMap(finwrap.entry, finwrap.source, dgraph, destid); + } + else { + if (finwrap.entry.equals(dgraph.mapNegIfBranch.get(finwrap.source))) { + map = outNegVarVersions.get(finwrap.source); + } + else { + map = outVarVersions.get(finwrap.source); + } + } + + // false path? + boolean isFalsePath = true; + + if (recFinally) { + isFalsePath = !finwrap.destination.equals(nodeid); + } + else { + isFalsePath = !setLongPathWrapper.contains(destid + "##" + finwrap.source); + } + + if (isFalsePath) { + mapNewTemp.complement(map); + } + else { + if (mapTrueSource.isEmpty()) { + if (map != null) { + mapTrueSource = map.getCopy(); + } + } + else { + mergeMaps(mapTrueSource, map); + } + } + } + + if (isExceptionMonitorExit) { + + mapNew = mapTrueSource; + } + else { + + mapNewTemp.union(mapTrueSource); + + SFormsFastMapDirect oldInMap = inVarVersions.get(nodeid); + if (oldInMap != null) { + mapNewTemp.union(oldInMap); + } + + mapNew.intersection(mapNewTemp); + } + } + + return mapNew; + } + + private static SFormsFastMapDirect mergeMaps(SFormsFastMapDirect mapTo, SFormsFastMapDirect map2) { + + if (map2 != null && !map2.isEmpty()) { + mapTo.union(map2); + } + + return mapTo; + } + + private static boolean mapsEqual(SFormsFastMapDirect map1, SFormsFastMapDirect map2) { + + if (map1 == null) { + return map2 == null; + } + else if (map2 == null) { + return false; + } + + if (map1.size() != map2.size()) { + return false; + } + + for (Entry<Integer, FastSparseSet<Integer>> ent2 : map2.entryList()) { + if (!InterpreterUtil.equalObjects(map1.get(ent2.getKey()), ent2.getValue())) { + return false; + } + } + + return true; + } + + private void setCurrentVar(SFormsFastMapDirect varmap, Integer var, Integer vers) { + FastSparseSet<Integer> set = factory.spawnEmptySet(); + set.add(vers); + varmap.put(var, set); + } + + private void setCatchMaps(Statement stat, DirectGraph dgraph, FlattenStatementsHelper flatthelper) { + + SFormsFastMapDirect map; + + switch (stat.type) { + case Statement.TYPE_CATCHALL: + case Statement.TYPE_TRYCATCH: + + List<VarExprent> lstVars; + if (stat.type == Statement.TYPE_CATCHALL) { + lstVars = ((CatchAllStatement)stat).getVars(); + } + else { + lstVars = ((CatchStatement)stat).getVars(); + } + + for (int i = 1; i < stat.getStats().size(); i++) { + int varindex = lstVars.get(i - 1).getIndex(); + int version = getNextFreeVersion(varindex); // == 1 + + map = new SFormsFastMapDirect(); + setCurrentVar(map, varindex, version); + + extraVarVersions.put(dgraph.nodes.getWithKey(flatthelper.getMapDestinationNodes().get(stat.getStats().get(i).id)[0]).id, map); + startVars.add(new VarVersionPaar(varindex, version)); + } + } + + for (Statement st : stat.getStats()) { + setCatchMaps(st, dgraph, flatthelper); + } + } + + private SFormsFastMapDirect createFirstMap(StructMethod mt) { + boolean thisvar = !mt.hasModifier(CodeConstants.ACC_STATIC); + + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + + int paramcount = md.params.length + (thisvar ? 1 : 0); + + int varindex = 0; + SFormsFastMapDirect map = new SFormsFastMapDirect(); + for (int i = 0; i < paramcount; i++) { + int version = getNextFreeVersion(varindex); // == 1 + + FastSparseSet<Integer> set = factory.spawnEmptySet(); + set.add(version); + map.put(varindex, set); + startVars.add(new VarVersionPaar(varindex, version)); + + if (thisvar) { + if (i == 0) { + varindex++; + } + else { + varindex += md.params[i - 1].stack_size; + } + } + else { + varindex += md.params[i].stack_size; + } + } + + return map; + } + + public HashMap<VarVersionPaar, FastSparseSet<Integer>> getPhi() { + return phi; + } + + public List<VarVersionPaar> getStartVars() { + return startVars; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/SSAUConstructorSparseEx.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/SSAUConstructorSparseEx.java new file mode 100644 index 000000000000..fbd652cd442c --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/sforms/SSAUConstructorSparseEx.java @@ -0,0 +1,844 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.sforms; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper.FinallyPathWrapper; +import org.jetbrains.java.decompiler.modules.decompiler.stats.*; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionEdge; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionNode; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionsGraph; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory.FastSparseSet; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.SFormsFastMapDirect; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; + +public class SSAUConstructorSparseEx { + + // node id, var, version + private HashMap<String, SFormsFastMapDirect> inVarVersions = new HashMap<String, SFormsFastMapDirect>(); + //private HashMap<String, HashMap<Integer, FastSet<Integer>>> inVarVersions = new HashMap<String, HashMap<Integer, FastSet<Integer>>>(); + + // node id, var, version (direct branch) + private HashMap<String, SFormsFastMapDirect> outVarVersions = new HashMap<String, SFormsFastMapDirect>(); + //private HashMap<String, HashMap<Integer, FastSet<Integer>>> outVarVersions = new HashMap<String, HashMap<Integer, FastSet<Integer>>>(); + + // node id, var, version (negative branch) + private HashMap<String, SFormsFastMapDirect> outNegVarVersions = new HashMap<String, SFormsFastMapDirect>(); + //private HashMap<String, HashMap<Integer, FastSet<Integer>>> outNegVarVersions = new HashMap<String, HashMap<Integer, FastSet<Integer>>>(); + + // node id, var, version + private HashMap<String, SFormsFastMapDirect> extraVarVersions = new HashMap<String, SFormsFastMapDirect>(); + //private HashMap<String, HashMap<Integer, FastSet<Integer>>> extraVarVersions = new HashMap<String, HashMap<Integer, FastSet<Integer>>>(); + + // (var, version), version + private HashMap<VarVersionPaar, HashSet<Integer>> phi = new HashMap<VarVersionPaar, HashSet<Integer>>(); + + // var, version + private HashMap<Integer, Integer> lastversion = new HashMap<Integer, Integer>(); + + // version, protected ranges (catch, finally) + private HashMap<VarVersionPaar, Integer> mapVersionFirstRange = new HashMap<VarVersionPaar, Integer>(); + + // version, version + private HashMap<VarVersionPaar, VarVersionPaar> phantomppnodes = new HashMap<VarVersionPaar, VarVersionPaar>(); // ++ and -- + + // node.id, version, version + private HashMap<String, HashMap<VarVersionPaar, VarVersionPaar>> phantomexitnodes = + new HashMap<String, HashMap<VarVersionPaar, VarVersionPaar>>(); // finally exits + + // versions memory dependencies + private VarVersionsGraph ssuversions = new VarVersionsGraph(); + + // field access vars (exprent id, var id) + private HashMap<Integer, Integer> mapFieldVars = new HashMap<Integer, Integer>(); + + // field access counter + private int fieldvarcounter = -1; + + // set factory + private FastSparseSetFactory<Integer> factory; + + public void splitVariables(RootStatement root, StructMethod mt) { + + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + DirectGraph dgraph = flatthelper.buildDirectGraph(root); + + HashSet<Integer> setInit = new HashSet<Integer>(); + for (int i = 0; i < 64; i++) { + setInit.add(i); + } + factory = new FastSparseSetFactory<Integer>(setInit); + + extraVarVersions.put(dgraph.first.id, createFirstMap(mt, root)); + + setCatchMaps(root, dgraph, flatthelper); + + // try { + // DotExporter.toDotFile(dgraph, new File("c:\\Temp\\gr12_my.dot")); + // } catch(Exception ex) {ex.printStackTrace();} + + HashSet<String> updated = new HashSet<String>(); + do { + // System.out.println("~~~~~~~~~~~~~ \r\n"+root.toJava()); + ssaStatements(dgraph, updated, false); + // System.out.println("~~~~~~~~~~~~~ \r\n"+root.toJava()); + } + while (!updated.isEmpty()); + + + ssaStatements(dgraph, updated, true); + + ssuversions.initDominators(); + } + + private void ssaStatements(DirectGraph dgraph, HashSet<String> updated, boolean calcLiveVars) { + + for (DirectNode node : dgraph.nodes) { + + updated.remove(node.id); + mergeInVarMaps(node, dgraph); + + SFormsFastMapDirect varmap = new SFormsFastMapDirect(inVarVersions.get(node.id)); + + SFormsFastMapDirect[] varmaparr = new SFormsFastMapDirect[]{varmap, null}; + + if (node.exprents != null) { + for (Exprent expr : node.exprents) { + processExprent(expr, varmaparr, node.statement, calcLiveVars); + } + } + + if (varmaparr[1] == null) { + varmaparr[1] = varmaparr[0]; + } + + // quick solution: 'dummy' field variables should not cross basic block borders (otherwise problems e.g. with finally loops - usage without assignment in a loop) + // For the full solution consider adding a dummy assignment at the entry point of the method + boolean allow_field_propagation = node.succs.isEmpty() || (node.succs.size() == 1 && node.succs.get(0).preds.size() == 1); + + if (!allow_field_propagation && varmaparr[0] != null) { + varmaparr[0].removeAllFields(); + varmaparr[1].removeAllFields(); + } + + boolean this_updated = !mapsEqual(varmaparr[0], outVarVersions.get(node.id)) + || (outNegVarVersions.containsKey(node.id) && !mapsEqual(varmaparr[1], outNegVarVersions.get(node.id))); + + if (this_updated) { + + outVarVersions.put(node.id, varmaparr[0]); + if (dgraph.mapNegIfBranch.containsKey(node.id)) { + outNegVarVersions.put(node.id, varmaparr[1]); + } + + for (DirectNode nd : node.succs) { + updated.add(nd.id); + } + } + } + } + + + private void processExprent(Exprent expr, SFormsFastMapDirect[] varmaparr, Statement stat, boolean calcLiveVars) { + + if (expr == null) { + return; + } + + + VarExprent varassign = null; + boolean finished = false; + + switch (expr.type) { + case Exprent.EXPRENT_ASSIGNMENT: + AssignmentExprent assexpr = (AssignmentExprent)expr; + if (assexpr.getCondtype() == AssignmentExprent.CONDITION_NONE) { + Exprent dest = assexpr.getLeft(); + if (dest.type == Exprent.EXPRENT_VAR) { + varassign = (VarExprent)dest; + } + } + break; + case Exprent.EXPRENT_FUNCTION: + FunctionExprent func = (FunctionExprent)expr; + switch (func.getFunctype()) { + case FunctionExprent.FUNCTION_IIF: + processExprent(func.getLstOperands().get(0), varmaparr, stat, calcLiveVars); + + SFormsFastMapDirect varmapFalse; + if (varmaparr[1] == null) { + varmapFalse = new SFormsFastMapDirect(varmaparr[0]); + } + else { + varmapFalse = varmaparr[1]; + varmaparr[1] = null; + } + + processExprent(func.getLstOperands().get(1), varmaparr, stat, calcLiveVars); + + SFormsFastMapDirect[] varmaparrNeg = new SFormsFastMapDirect[]{varmapFalse, null}; + processExprent(func.getLstOperands().get(2), varmaparrNeg, stat, calcLiveVars); + + mergeMaps(varmaparr[0], varmaparrNeg[0]); + varmaparr[1] = null; + + finished = true; + break; + case FunctionExprent.FUNCTION_CADD: + processExprent(func.getLstOperands().get(0), varmaparr, stat, calcLiveVars); + + SFormsFastMapDirect[] varmaparrAnd = new SFormsFastMapDirect[]{new SFormsFastMapDirect(varmaparr[0]), null}; + + processExprent(func.getLstOperands().get(1), varmaparrAnd, stat, calcLiveVars); + + // false map + varmaparr[1] = mergeMaps(varmaparr[varmaparr[1] == null ? 0 : 1], varmaparrAnd[varmaparrAnd[1] == null ? 0 : 1]); + // true map + varmaparr[0] = varmaparrAnd[0]; + + finished = true; + break; + case FunctionExprent.FUNCTION_COR: + processExprent(func.getLstOperands().get(0), varmaparr, stat, calcLiveVars); + + SFormsFastMapDirect[] varmaparrOr = + new SFormsFastMapDirect[]{new SFormsFastMapDirect(varmaparr[varmaparr[1] == null ? 0 : 1]), null}; + + processExprent(func.getLstOperands().get(1), varmaparrOr, stat, calcLiveVars); + + // false map + varmaparr[1] = varmaparrOr[varmaparrOr[1] == null ? 0 : 1]; + // true map + varmaparr[0] = mergeMaps(varmaparr[0], varmaparrOr[0]); + + finished = true; + } + } + + if (!finished) { + List<Exprent> lst = expr.getAllExprents(); + lst.remove(varassign); + + for (Exprent ex : lst) { + processExprent(ex, varmaparr, stat, calcLiveVars); + } + } + + + SFormsFastMapDirect varmap = varmaparr[0]; + + // field access + if (expr.type == Exprent.EXPRENT_FIELD) { + + int index; + if (mapFieldVars.containsKey(expr.id)) { + index = mapFieldVars.get(expr.id); + } + else { + index = fieldvarcounter--; + mapFieldVars.put(expr.id, index); + + // ssu graph + ssuversions.createNode(new VarVersionPaar(index, 1)); + } + + setCurrentVar(varmap, index, 1); + } + else if (expr.type == Exprent.EXPRENT_INVOCATION || + (expr.type == Exprent.EXPRENT_ASSIGNMENT && ((AssignmentExprent)expr).getLeft().type == Exprent.EXPRENT_FIELD) || + (expr.type == Exprent.EXPRENT_NEW && ((NewExprent)expr).getNewtype().type == CodeConstants.TYPE_OBJECT) || + expr.type == Exprent.EXPRENT_FUNCTION) { + + boolean ismmpp = true; + + if (expr.type == Exprent.EXPRENT_FUNCTION) { + + ismmpp = false; + + FunctionExprent fexpr = (FunctionExprent)expr; + if (fexpr.getFunctype() >= FunctionExprent.FUNCTION_IMM && fexpr.getFunctype() <= FunctionExprent.FUNCTION_PPI) { + if (fexpr.getLstOperands().get(0).type == Exprent.EXPRENT_FIELD) { + ismmpp = true; + } + } + } + + if (ismmpp) { + varmap.removeAllFields(); + } + } + + + if (varassign != null) { + + Integer varindex = varassign.getIndex(); + + if (varassign.getVersion() == 0) { + // get next version + Integer nextver = getNextFreeVersion(varindex, stat); + + // set version + varassign.setVersion(nextver); + + // ssu graph + ssuversions.createNode(new VarVersionPaar(varindex, nextver)); + + setCurrentVar(varmap, varindex, nextver); + } + else { + if (calcLiveVars) { + varMapToGraph(new VarVersionPaar(varindex.intValue(), varassign.getVersion()), varmap); + } + setCurrentVar(varmap, varindex, varassign.getVersion()); + } + } + else if (expr.type == Exprent.EXPRENT_FUNCTION) { // MM or PP function + FunctionExprent func = (FunctionExprent)expr; + + switch (func.getFunctype()) { + case FunctionExprent.FUNCTION_IMM: + case FunctionExprent.FUNCTION_MMI: + case FunctionExprent.FUNCTION_IPP: + case FunctionExprent.FUNCTION_PPI: + + if (func.getLstOperands().get(0).type == Exprent.EXPRENT_VAR) { + VarExprent var = (VarExprent)func.getLstOperands().get(0); + Integer varindex = var.getIndex(); + VarVersionPaar varpaar = new VarVersionPaar(varindex.intValue(), var.getVersion()); + + // ssu graph + VarVersionPaar phantomver = phantomppnodes.get(varpaar); + if (phantomver == null) { + // get next version + Integer nextver = getNextFreeVersion(varindex, null); + phantomver = new VarVersionPaar(varindex, nextver); + //ssuversions.createOrGetNode(phantomver); + ssuversions.createNode(phantomver); + + VarVersionNode vernode = ssuversions.nodes.getWithKey(varpaar); + + FastSparseSet<Integer> vers = factory.spawnEmptySet(); + if (vernode.preds.size() == 1) { + vers.add(vernode.preds.iterator().next().source.version); + } + else { + for (VarVersionEdge edge : vernode.preds) { + vers.add(edge.source.preds.iterator().next().source.version); + } + } + vers.add(nextver); + createOrUpdatePhiNode(varpaar, vers, stat); + phantomppnodes.put(varpaar, phantomver); + } + if (calcLiveVars) { + varMapToGraph(varpaar, varmap); + } + setCurrentVar(varmap, varindex.intValue(), var.getVersion()); + } + } + } + else if (expr.type == Exprent.EXPRENT_VAR) { + + VarExprent vardest = (VarExprent)expr; + + Integer varindex = vardest.getIndex(); + Integer current_vers = vardest.getVersion(); + + FastSparseSet<Integer> vers = varmap.get(varindex); + + int cardinality = vers.getCardinality(); + if (cardinality == 1) { // size == 1 + if (current_vers.intValue() != 0) { + if (calcLiveVars) { + varMapToGraph(new VarVersionPaar(varindex, current_vers), varmap); + } + setCurrentVar(varmap, varindex, current_vers); + } + else { + // split last version + Integer usever = getNextFreeVersion(varindex, stat); + + // set version + vardest.setVersion(usever); + setCurrentVar(varmap, varindex, usever); + + // ssu graph + Integer lastver = vers.iterator().next(); + VarVersionNode prenode = ssuversions.nodes.getWithKey(new VarVersionPaar(varindex, lastver)); + VarVersionNode usenode = ssuversions.createNode(new VarVersionPaar(varindex, usever)); + VarVersionEdge edge = new VarVersionEdge(VarVersionEdge.EDGE_GENERAL, prenode, usenode); + prenode.addSuccessor(edge); + usenode.addPredecessor(edge); + } + } + else if (cardinality == 2) { // size > 1 + + if (current_vers.intValue() != 0) { + if (calcLiveVars) { + varMapToGraph(new VarVersionPaar(varindex, current_vers), varmap); + } + setCurrentVar(varmap, varindex, current_vers); + } + else { + // split version + Integer usever = getNextFreeVersion(varindex, stat); + // set version + vardest.setVersion(usever); + + // ssu node + ssuversions.createNode(new VarVersionPaar(varindex, usever)); + + setCurrentVar(varmap, varindex, usever); + + current_vers = usever; + } + + createOrUpdatePhiNode(new VarVersionPaar(varindex, current_vers), vers, stat); + } // vers.size() == 0 means uninitialized variable, which is impossible + } + } + + private void createOrUpdatePhiNode(VarVersionPaar phivar, FastSparseSet<Integer> vers, Statement stat) { + + FastSparseSet<Integer> versCopy = vers.getCopy(); + HashSet<Integer> phiVers = new HashSet<Integer>(); + + // take into account the corresponding mm/pp node if existing + int ppvers = phantomppnodes.containsKey(phivar) ? phantomppnodes.get(phivar).version : -1; + + // ssu graph + VarVersionNode phinode = ssuversions.nodes.getWithKey(phivar); + List<VarVersionEdge> lstPreds = new ArrayList<VarVersionEdge>(phinode.preds); + if (lstPreds.size() == 1) { + // not yet a phi node + VarVersionEdge edge = lstPreds.get(0); + edge.source.removeSuccessor(edge); + phinode.removePredecessor(edge); + } + else { + for (VarVersionEdge edge : lstPreds) { + int verssrc = edge.source.preds.iterator().next().source.version; + if (!vers.contains(verssrc) && verssrc != ppvers) { + edge.source.removeSuccessor(edge); + phinode.removePredecessor(edge); + } + else { + versCopy.remove(verssrc); + phiVers.add(verssrc); + } + } + } + + List<VarVersionNode> colnodes = new ArrayList<VarVersionNode>(); + List<VarVersionPaar> colpaars = new ArrayList<VarVersionPaar>(); + + for (Integer ver : versCopy) { + + VarVersionNode prenode = ssuversions.nodes.getWithKey(new VarVersionPaar(phivar.var, ver.intValue())); + + Integer tempver = getNextFreeVersion(phivar.var, stat); + + VarVersionNode tempnode = new VarVersionNode(phivar.var, tempver.intValue()); + + colnodes.add(tempnode); + colpaars.add(new VarVersionPaar(phivar.var, tempver.intValue())); + + VarVersionEdge edge = new VarVersionEdge(VarVersionEdge.EDGE_GENERAL, prenode, tempnode); + + prenode.addSuccessor(edge); + tempnode.addPredecessor(edge); + + + edge = new VarVersionEdge(VarVersionEdge.EDGE_GENERAL, tempnode, phinode); + tempnode.addSuccessor(edge); + phinode.addPredecessor(edge); + + phiVers.add(tempver); + } + + ssuversions.addNodes(colnodes, colpaars); + + // update phi node + phi.put(phivar, phiVers); + } + + private void varMapToGraph(VarVersionPaar varpaar, SFormsFastMapDirect varmap) { + + VBStyleCollection<VarVersionNode, VarVersionPaar> nodes = ssuversions.nodes; + + VarVersionNode node = nodes.getWithKey(varpaar); + + node.live = new SFormsFastMapDirect(varmap); + } + + private Integer getNextFreeVersion(Integer var, Statement stat) { + + Integer nextver = lastversion.get(var); + + if (nextver == null) { + nextver = new Integer(1); + } + else { + nextver = new Integer(nextver.intValue() + 1); + } + lastversion.put(var, nextver); + + // save the first protected range, containing current statement + if (stat != null) { // null iff phantom version + Integer firstRangeId = getFirstProtectedRange(stat); + if (firstRangeId != null) { + mapVersionFirstRange.put(new VarVersionPaar(var, nextver), firstRangeId); + } + } + + return nextver; + } + + private void mergeInVarMaps(DirectNode node, DirectGraph dgraph) { + + + SFormsFastMapDirect mapNew = new SFormsFastMapDirect(); + + for (DirectNode pred : node.preds) { + SFormsFastMapDirect mapOut = getFilteredOutMap(node.id, pred.id, dgraph, node.id); + if (mapNew.isEmpty()) { + mapNew = mapOut.getCopy(); + } + else { + mergeMaps(mapNew, mapOut); + } + } + + if (extraVarVersions.containsKey(node.id)) { + SFormsFastMapDirect mapExtra = extraVarVersions.get(node.id); + if (mapNew.isEmpty()) { + mapNew = mapExtra.getCopy(); + } + else { + mergeMaps(mapNew, mapExtra); + } + } + + inVarVersions.put(node.id, mapNew); + } + + private SFormsFastMapDirect getFilteredOutMap(String nodeid, String predid, DirectGraph dgraph, String destid) { + + SFormsFastMapDirect mapNew = new SFormsFastMapDirect(); + + boolean isFinallyExit = dgraph.mapShortRangeFinallyPaths.containsKey(predid); + + if (nodeid.equals(dgraph.mapNegIfBranch.get(predid))) { + if (outNegVarVersions.containsKey(predid)) { + mapNew = outNegVarVersions.get(predid).getCopy(); + } + } + else if (outVarVersions.containsKey(predid)) { + mapNew = outVarVersions.get(predid).getCopy(); + } + + if (isFinallyExit) { + + SFormsFastMapDirect mapNewTemp = mapNew.getCopy(); + + SFormsFastMapDirect mapTrueSource = new SFormsFastMapDirect(); + + String exceptionDest = dgraph.mapFinallyMonitorExceptionPathExits.get(predid); + boolean isExceptionMonitorExit = (exceptionDest != null && !nodeid.equals(exceptionDest)); + + HashSet<String> setLongPathWrapper = new HashSet<String>(); + for (List<FinallyPathWrapper> lstwrapper : dgraph.mapLongRangeFinallyPaths.values()) { + for (FinallyPathWrapper finwraplong : lstwrapper) { + setLongPathWrapper.add(finwraplong.destination + "##" + finwraplong.source); + } + } + + for (FinallyPathWrapper finwrap : dgraph.mapShortRangeFinallyPaths.get(predid)) { + SFormsFastMapDirect map; + + boolean recFinally = dgraph.mapShortRangeFinallyPaths.containsKey(finwrap.source); + + if (recFinally) { + // recursion + map = getFilteredOutMap(finwrap.entry, finwrap.source, dgraph, destid); + } + else { + if (finwrap.entry.equals(dgraph.mapNegIfBranch.get(finwrap.source))) { + map = outNegVarVersions.get(finwrap.source); + } + else { + map = outVarVersions.get(finwrap.source); + } + } + + // false path? + boolean isFalsePath = true; + + if (recFinally) { + isFalsePath = !finwrap.destination.equals(nodeid); + } + else { + isFalsePath = !setLongPathWrapper.contains(destid + "##" + finwrap.source); + } + + if (isFalsePath) { + mapNewTemp.complement(map); + } + else { + if (mapTrueSource.isEmpty()) { + if (map != null) { + mapTrueSource = map.getCopy(); + } + } + else { + mergeMaps(mapTrueSource, map); + } + } + } + + if (isExceptionMonitorExit) { + + mapNew = mapTrueSource; + } + else { + + mapNewTemp.union(mapTrueSource); + mapNew.intersection(mapNewTemp); + + if (!mapTrueSource.isEmpty() && !mapNew.isEmpty()) { // FIXME: what for?? + + // replace phi versions with corresponding phantom ones + HashMap<VarVersionPaar, VarVersionPaar> mapPhantom = phantomexitnodes.get(predid); + if (mapPhantom == null) { + mapPhantom = new HashMap<VarVersionPaar, VarVersionPaar>(); + } + + SFormsFastMapDirect mapExitVar = mapNew.getCopy(); + mapExitVar.complement(mapTrueSource); + + for (Entry<Integer, FastSparseSet<Integer>> ent : mapExitVar.entryList()) { + for (Integer version : ent.getValue()) { + + Integer varindex = ent.getKey(); + VarVersionPaar exitvar = new VarVersionPaar(varindex, version); + FastSparseSet<Integer> newSet = mapNew.get(varindex); + + // remove the actual exit version + newSet.remove(version); + + // get or create phantom version + VarVersionPaar phantomvar = mapPhantom.get(exitvar); + if (phantomvar == null) { + Integer newversion = getNextFreeVersion(exitvar.var, null); + phantomvar = new VarVersionPaar(exitvar.var, newversion.intValue()); + + VarVersionNode exitnode = ssuversions.nodes.getWithKey(exitvar); + VarVersionNode phantomnode = ssuversions.createNode(phantomvar); + phantomnode.flags |= VarVersionNode.FLAG_PHANTOM_FINEXIT; + + VarVersionEdge edge = new VarVersionEdge(VarVersionEdge.EDGE_PHANTOM, exitnode, phantomnode); + exitnode.addSuccessor(edge); + phantomnode.addPredecessor(edge); + + mapPhantom.put(exitvar, phantomvar); + } + + // add phantom version + newSet.add(phantomvar.version); + } + } + + if (!mapPhantom.isEmpty()) { + phantomexitnodes.put(predid, mapPhantom); + } + } + } + } + + return mapNew; + } + + private static SFormsFastMapDirect mergeMaps(SFormsFastMapDirect mapTo, SFormsFastMapDirect map2) { + + if (map2 != null && !map2.isEmpty()) { + mapTo.union(map2); + } + + return mapTo; + } + + private static boolean mapsEqual(SFormsFastMapDirect map1, SFormsFastMapDirect map2) { + + if (map1 == null) { + return map2 == null; + } + else if (map2 == null) { + return false; + } + + if (map1.size() != map2.size()) { + return false; + } + + for (Entry<Integer, FastSparseSet<Integer>> ent2 : map2.entryList()) { + if (!InterpreterUtil.equalObjects(map1.get(ent2.getKey()), ent2.getValue())) { + return false; + } + } + + return true; + } + + + private void setCurrentVar(SFormsFastMapDirect varmap, Integer var, Integer vers) { + FastSparseSet<Integer> set = factory.spawnEmptySet(); + set.add(vers); + varmap.put(var, set); + } + + private void setCatchMaps(Statement stat, DirectGraph dgraph, FlattenStatementsHelper flatthelper) { + + SFormsFastMapDirect map; + + switch (stat.type) { + case Statement.TYPE_CATCHALL: + case Statement.TYPE_TRYCATCH: + + List<VarExprent> lstVars; + if (stat.type == Statement.TYPE_CATCHALL) { + lstVars = ((CatchAllStatement)stat).getVars(); + } + else { + lstVars = ((CatchStatement)stat).getVars(); + } + + for (int i = 1; i < stat.getStats().size(); i++) { + int varindex = lstVars.get(i - 1).getIndex(); + int version = getNextFreeVersion(varindex, stat); // == 1 + + map = new SFormsFastMapDirect(); + setCurrentVar(map, varindex, version); + + extraVarVersions.put(dgraph.nodes.getWithKey(flatthelper.getMapDestinationNodes().get(stat.getStats().get(i).id)[0]).id, map); + //ssuversions.createOrGetNode(new VarVersionPaar(varindex, version)); + ssuversions.createNode(new VarVersionPaar(varindex, version)); + } + } + + for (Statement st : stat.getStats()) { + setCatchMaps(st, dgraph, flatthelper); + } + } + + private SFormsFastMapDirect createFirstMap(StructMethod mt, RootStatement root) { + boolean thisvar = !mt.hasModifier(CodeConstants.ACC_STATIC); + + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + + int paramcount = md.params.length + (thisvar ? 1 : 0); + + int varindex = 0; + SFormsFastMapDirect map = new SFormsFastMapDirect(); + for (int i = 0; i < paramcount; i++) { + int version = getNextFreeVersion(varindex, root); // == 1 + + FastSparseSet<Integer> set = factory.spawnEmptySet(); + set.add(version); + map.put(varindex, set); + ssuversions.createNode(new VarVersionPaar(varindex, version)); + + if (thisvar) { + if (i == 0) { + varindex++; + } + else { + varindex += md.params[i - 1].stack_size; + } + } + else { + varindex += md.params[i].stack_size; + } + } + + return map; + } + + private static Integer getFirstProtectedRange(Statement stat) { + + while (true) { + Statement parent = stat.getParent(); + + if (parent == null) { + break; + } + + if (parent.type == Statement.TYPE_CATCHALL || + parent.type == Statement.TYPE_TRYCATCH) { + if (parent.getFirst() == stat) { + return parent.id; + } + } + else if (parent.type == Statement.TYPE_SYNCRONIZED) { + if (((SynchronizedStatement)parent).getBody() == stat) { + return parent.id; + } + } + + stat = parent; + } + + return null; + } + + public HashMap<VarVersionPaar, HashSet<Integer>> getPhi() { + return phi; + } + + public VarVersionsGraph getSsuversions() { + return ssuversions; + } + + public SFormsFastMapDirect getLiveVarVersionsMap(VarVersionPaar varpaar) { + + + VarVersionNode node = ssuversions.nodes.getWithKey(varpaar); + if (node != null) { + return node.live; + } + + return null; + } + + public HashMap<VarVersionPaar, Integer> getMapVersionFirstRange() { + return mapVersionFirstRange; + } + + public HashMap<Integer, Integer> getMapFieldVars() { + return mapFieldVars; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/BasicBlockStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/BasicBlockStatement.java new file mode 100644 index 000000000000..91c1a4e23c84 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/BasicBlockStatement.java @@ -0,0 +1,96 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.Instruction; +import org.jetbrains.java.decompiler.code.SimpleInstructionSequence; +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; + +public class BasicBlockStatement extends Statement { + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private BasicBlock block; + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public BasicBlockStatement(BasicBlock block) { + + type = Statement.TYPE_BASICBLOCK; + + this.block = block; + + id = block.id; + CounterContainer coun = DecompilerContext.getCounterContainer(); + if (id >= coun.getCounter(CounterContainer.STATEMENT_COUNTER)) { + coun.setCounter(CounterContainer.STATEMENT_COUNTER, id + 1); + } + + Instruction instr = block.getLastInstruction(); + if (instr != null) { + if (instr.group == CodeConstants.GROUP_JUMP && instr.opcode != CodeConstants.opc_goto) { + lastBasicType = LASTBASICTYPE_IF; + } + else if (instr.group == CodeConstants.GROUP_SWITCH) { + lastBasicType = LASTBASICTYPE_SWITCH; + } + } + + // monitorenter and monitorexits + buildMonitorFlags(); + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public String toJava(int indent) { + return ExprProcessor.listToJava(varDefinitions, indent) + + ExprProcessor.listToJava(exprents, indent); + } + + public Statement getSimpleCopy() { + + BasicBlock newblock = new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER)); + + SimpleInstructionSequence seq = new SimpleInstructionSequence(); + for (int i = 0; i < block.getSeq().length(); i++) { + seq.addInstruction(block.getSeq().getInstr(i).clone(), -1); + } + + newblock.setSeq(seq); + + return new BasicBlockStatement(newblock); + } + + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public BasicBlock getBlock() { + return block; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/CatchAllStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/CatchAllStatement.java new file mode 100644 index 000000000000..15af3c604a2e --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/CatchAllStatement.java @@ -0,0 +1,233 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.DecHelper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +public class CatchAllStatement extends Statement { + + private Statement handler; + + private boolean isFinally; + + private VarExprent monitor; + + private List<VarExprent> vars = new ArrayList<VarExprent>(); + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + private CatchAllStatement() { + type = Statement.TYPE_CATCHALL; + } + + private CatchAllStatement(Statement head, Statement handler) { + + this(); + + first = head; + stats.addWithKey(head, head.id); + + this.handler = handler; + stats.addWithKey(handler, handler.id); + + List<StatEdge> lstSuccs = head.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (!lstSuccs.isEmpty()) { + StatEdge edge = lstSuccs.get(0); + if (edge.getType() == StatEdge.TYPE_REGULAR) { + post = edge.getDestination(); + } + } + + vars.add(new VarExprent(DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER), + new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/Throwable"), + (VarProcessor)DecompilerContext.getProperty(DecompilerContext.CURRENT_VAR_PROCESSOR))); + } + + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public static Statement isHead(Statement head) { + + if (head.getLastBasicType() != Statement.LASTBASICTYPE_GENERAL) { + return null; + } + + HashSet<Statement> setHandlers = DecHelper.getUniquePredExceptions(head); + + if (setHandlers.size() != 1) { + return null; + } + + for (StatEdge edge : head.getSuccessorEdges(StatEdge.TYPE_EXCEPTION)) { + Statement exc = edge.getDestination(); + + if (edge.getExceptions() == null && setHandlers.contains(exc) && exc.getLastBasicType() == LASTBASICTYPE_GENERAL) { + List<StatEdge> lstSuccs = exc.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (lstSuccs.isEmpty() || lstSuccs.get(0).getType() != StatEdge.TYPE_REGULAR) { + + if (head.isMonitorEnter() || exc.isMonitorEnter()) { + return null; + } + + if (DecHelper.checkStatementExceptions(Arrays.asList(head, exc))) { + return new CatchAllStatement(head, exc); + } + } + } + } + + return null; + } + + public String toJava(int indent) { + String indstr = InterpreterUtil.getIndentString(indent); + String indstr1 = null; + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + + buf.append(ExprProcessor.listToJava(varDefinitions, indent)); + + boolean labeled = isLabeled(); + if (labeled) { + buf.append(indstr).append("label").append(this.id).append(":").append(new_line_separator); + } + + List<StatEdge> lstSuccs = first.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (first.type == TYPE_TRYCATCH && first.varDefinitions.isEmpty() && isFinally && + !labeled && !first.isLabeled() && (lstSuccs.isEmpty() || !lstSuccs.get(0).explicit)) { + String content = ExprProcessor.jmpWrapper(first, indent, true); + content = content.substring(0, content.length() - new_line_separator.length()); + + buf.append(content); + } + else { + buf.append(indstr).append("try {").append(new_line_separator); + buf.append(ExprProcessor.jmpWrapper(first, indent + 1, true)); + buf.append(indstr).append("}"); + } + + buf.append(isFinally ? " finally" : + " catch (" + vars.get(0).toJava(indent) + ")").append(" {").append(new_line_separator); + + if (monitor != null) { + indstr1 = InterpreterUtil.getIndentString(indent + 1); + buf.append(indstr1).append("if(").append(monitor.toJava(indent)).append(") {").append(new_line_separator); + } + + buf.append(ExprProcessor.jmpWrapper(handler, indent + 1 + (monitor != null ? 1 : 0), true)); + + if (monitor != null) { + buf.append(indstr1).append("}").append(new_line_separator); + } + + buf.append(indstr).append("}").append(new_line_separator); + + return buf.toString(); + } + + public void replaceStatement(Statement oldstat, Statement newstat) { + + if (handler == oldstat) { + handler = newstat; + } + + super.replaceStatement(oldstat, newstat); + } + + public Statement getSimpleCopy() { + + CatchAllStatement cas = new CatchAllStatement(); + + cas.isFinally = this.isFinally; + + if (this.monitor != null) { + cas.monitor = new VarExprent(DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER), + VarType.VARTYPE_INT, + (VarProcessor)DecompilerContext.getProperty(DecompilerContext.CURRENT_VAR_PROCESSOR)); + } + + if (!this.vars.isEmpty()) { + // FIXME: WTF??? vars?! + vars.add(new VarExprent(DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER), + new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/Throwable"), + (VarProcessor)DecompilerContext.getProperty(DecompilerContext.CURRENT_VAR_PROCESSOR))); + } + + return cas; + } + + public void initSimpleCopy() { + first = stats.get(0); + handler = stats.get(1); + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public Statement getHandler() { + return handler; + } + + + public void setHandler(Statement handler) { + this.handler = handler; + } + + + public boolean isFinally() { + return isFinally; + } + + + public void setFinally(boolean isFinally) { + this.isFinally = isFinally; + } + + + public VarExprent getMonitor() { + return monitor; + } + + + public void setMonitor(VarExprent monitor) { + this.monitor = monitor; + } + + public List<VarExprent> getVars() { + return vars; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/CatchStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/CatchStatement.java new file mode 100644 index 000000000000..ea45bdda75d7 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/CatchStatement.java @@ -0,0 +1,210 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.DecHelper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.modules.decompiler.vars.VarProcessor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +public class CatchStatement extends Statement { + + private List<List<String>> exctstrings = new ArrayList<List<String>>(); + + private List<VarExprent> vars = new ArrayList<VarExprent>(); + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + private CatchStatement() { + type = TYPE_TRYCATCH; + } + + private CatchStatement(Statement head, Statement next, HashSet<Statement> setHandlers) { + + this(); + + first = head; + stats.addWithKey(first, first.id); + + for (StatEdge edge : head.getSuccessorEdges(StatEdge.TYPE_EXCEPTION)) { + Statement stat = edge.getDestination(); + + if (setHandlers.contains(stat)) { + stats.addWithKey(stat, stat.id); + exctstrings.add(new ArrayList<String>(edge.getExceptions())); + + vars.add(new VarExprent(DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER), + new VarType(CodeConstants.TYPE_OBJECT, 0, edge.getExceptions().get(0)), + // FIXME: for now simply the first type. Should get the first common superclass when possible. + (VarProcessor)DecompilerContext.getProperty(DecompilerContext.CURRENT_VAR_PROCESSOR))); + } + } + + if (next != null) { + post = next; + } + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public static Statement isHead(Statement head) { + + if (head.getLastBasicType() != LASTBASICTYPE_GENERAL) { + return null; + } + + HashSet<Statement> setHandlers = DecHelper.getUniquePredExceptions(head); + + if (!setHandlers.isEmpty()) { + + int hnextcount = 0; // either no statements with connection to next, or more than 1 + + Statement next = null; + List<StatEdge> lstHeadSuccs = head.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (!lstHeadSuccs.isEmpty() && lstHeadSuccs.get(0).getType() == StatEdge.TYPE_REGULAR) { + next = lstHeadSuccs.get(0).getDestination(); + hnextcount = 2; + } + + for (StatEdge edge : head.getSuccessorEdges(StatEdge.TYPE_EXCEPTION)) { + Statement stat = edge.getDestination(); + + boolean handlerok = true; + + if (edge.getExceptions() != null && setHandlers.contains(stat)) { + if (stat.getLastBasicType() != LASTBASICTYPE_GENERAL) { + handlerok = false; + } + else { + List<StatEdge> lstStatSuccs = stat.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (!lstStatSuccs.isEmpty() && lstStatSuccs.get(0).getType() == StatEdge.TYPE_REGULAR) { + + Statement statn = lstStatSuccs.get(0).getDestination(); + + if (next == null) { + next = statn; + } + else if (next != statn) { + handlerok = false; + } + + if (handlerok) { + hnextcount++; + } + } + } + } + else { + handlerok = false; + } + + if (!handlerok) { + setHandlers.remove(stat); + } + } + + if (hnextcount != 1 && !setHandlers.isEmpty()) { + List<Statement> lst = new ArrayList<Statement>(); + lst.add(head); + lst.addAll(setHandlers); + + for (Statement st : lst) { + if (st.isMonitorEnter()) { + return null; + } + } + + if (DecHelper.checkStatementExceptions(lst)) { + return new CatchStatement(head, next, setHandlers); + } + } + } + return null; + } + + public String toJava(int indent) { + String indstr = InterpreterUtil.getIndentString(indent); + StringBuilder buf = new StringBuilder(); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + buf.append(ExprProcessor.listToJava(varDefinitions, indent)); + + if (isLabeled()) { + buf.append(indstr).append("label").append(this.id).append(":").append(new_line_separator); + } + + buf.append(indstr).append("try {").append(new_line_separator); + buf.append(ExprProcessor.jmpWrapper(first, indent + 1, true)); + buf.append(indstr).append("}"); + + for (int i = 1; i < stats.size(); i++) { + List<String> exception_types = exctstrings.get(i - 1); + + buf.append(" catch ("); + if (exception_types.size() > 1) { // multi-catch, Java 7 style + for (int exc_index = 1; exc_index < exception_types.size(); ++exc_index) { + VarType exc_type = new VarType(CodeConstants.TYPE_OBJECT, 0, exception_types.get(exc_index)); + String exc_type_name = ExprProcessor.getCastTypeName(exc_type); + + buf.append(exc_type_name).append(" | "); + } + } + buf.append(vars.get(i - 1).toJava(indent)); + buf.append(") {").append(new_line_separator).append(ExprProcessor.jmpWrapper(stats.get(i), indent + 1, true)).append(indstr) + .append("}"); + } + buf.append(new_line_separator); + + return buf.toString(); + } + + public Statement getSimpleCopy() { + + CatchStatement cs = new CatchStatement(); + + for (List<String> exc : this.exctstrings) { + cs.exctstrings.add(new ArrayList<String>(exc)); + cs.vars.add(new VarExprent(DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.VAR_COUNTER), + new VarType(CodeConstants.TYPE_OBJECT, 0, exc.get(0)), + (VarProcessor)DecompilerContext.getProperty(DecompilerContext.CURRENT_VAR_PROCESSOR))); + } + + return cs; + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public List<VarExprent> getVars() { + return vars; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/DoStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/DoStatement.java new file mode 100644 index 000000000000..7c152c21eb1f --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/DoStatement.java @@ -0,0 +1,222 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class DoStatement extends Statement { + + public static final int LOOP_DO = 0; + public static final int LOOP_DOWHILE = 1; + public static final int LOOP_WHILE = 2; + public static final int LOOP_FOR = 3; + + private int looptype; + + private List<Exprent> initExprent = new ArrayList<Exprent>(); + private List<Exprent> conditionExprent = new ArrayList<Exprent>(); + private List<Exprent> incExprent = new ArrayList<Exprent>(); + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + private DoStatement() { + type = Statement.TYPE_DO; + looptype = LOOP_DO; + + initExprent.add(null); + conditionExprent.add(null); + incExprent.add(null); + } + + private DoStatement(Statement head) { + + this(); + + first = head; + stats.addWithKey(first, first.id); + + // post is always null! + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public static Statement isHead(Statement head) { + + if (head.getLastBasicType() == LASTBASICTYPE_GENERAL && !head.isMonitorEnter()) { + + // at most one outgoing edge + StatEdge edge = null; + List<StatEdge> lstSuccs = head.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (!lstSuccs.isEmpty()) { + edge = lstSuccs.get(0); + } + + // regular loop + if (edge != null && edge.getType() == StatEdge.TYPE_REGULAR && edge.getDestination() == head) { + return new DoStatement(head); + } + + // continues + if (head.type != TYPE_DO && (edge == null || edge.getType() != StatEdge.TYPE_REGULAR) && + head.getContinueSet().contains(head.getBasichead())) { + return new DoStatement(head); + } + } + + return null; + } + + public String toJava(int indent) { + String indstr = InterpreterUtil.getIndentString(indent); + StringBuilder buf = new StringBuilder(); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + buf.append(ExprProcessor.listToJava(varDefinitions, indent)); + + if (isLabeled()) { + buf.append(indstr).append("label").append(this.id).append(":").append(new_line_separator); + } + + switch (looptype) { + case LOOP_DO: + buf.append(indstr).append("while(true) {").append(new_line_separator); + buf.append(ExprProcessor.jmpWrapper(first, indent + 1, true)); + buf.append(indstr).append("}").append(new_line_separator); + break; + case LOOP_DOWHILE: + buf.append(indstr).append("do {").append(new_line_separator); + buf.append(ExprProcessor.jmpWrapper(first, indent + 1, true)); + buf.append(indstr).append("} while(").append(conditionExprent.get(0).toJava(indent)).append(");").append(new_line_separator); + break; + case LOOP_WHILE: + buf.append(indstr).append("while(").append(conditionExprent.get(0).toJava(indent)).append(") {").append(new_line_separator); + buf.append(ExprProcessor.jmpWrapper(first, indent + 1, true)); + buf.append(indstr).append("}").append(new_line_separator); + break; + case LOOP_FOR: + buf.append(indstr).append("for(").append(initExprent.get(0) == null ? "" : initExprent.get(0).toJava(indent)).append("; ") + .append(conditionExprent.get(0).toJava(indent)).append("; ").append(incExprent.get(0).toJava(indent)).append(") {") + .append(new_line_separator); + buf.append(ExprProcessor.jmpWrapper(first, indent + 1, true)); + buf.append(indstr).append("}").append(new_line_separator); + } + + return buf.toString(); + } + + public List<Object> getSequentialObjects() { + + List<Object> lst = new ArrayList<Object>(); + + switch (looptype) { + case LOOP_FOR: + if (getInitExprent() != null) { + lst.add(getInitExprent()); + } + case LOOP_WHILE: + lst.add(getConditionExprent()); + } + + lst.add(first); + + switch (looptype) { + case LOOP_DOWHILE: + lst.add(getConditionExprent()); + break; + case LOOP_FOR: + lst.add(getIncExprent()); + } + + return lst; + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (initExprent.get(0) == oldexpr) { + initExprent.set(0, newexpr); + } + if (conditionExprent.get(0) == oldexpr) { + conditionExprent.set(0, newexpr); + } + if (incExprent.get(0) == oldexpr) { + incExprent.set(0, newexpr); + } + } + + public Statement getSimpleCopy() { + return new DoStatement(); + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public List<Exprent> getInitExprentList() { + return initExprent; + } + + public List<Exprent> getConditionExprentList() { + return conditionExprent; + } + + public List<Exprent> getIncExprentList() { + return incExprent; + } + + public Exprent getConditionExprent() { + return conditionExprent.get(0); + } + + public void setConditionExprent(Exprent conditionExprent) { + this.conditionExprent.set(0, conditionExprent); + } + + public Exprent getIncExprent() { + return incExprent.get(0); + } + + public void setIncExprent(Exprent incExprent) { + this.incExprent.set(0, incExprent); + } + + public Exprent getInitExprent() { + return initExprent.get(0); + } + + public void setInitExprent(Exprent initExprent) { + this.initExprent.set(0, initExprent); + } + + public int getLooptype() { + return looptype; + } + + public void setLooptype(int looptype) { + this.looptype = looptype; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/GeneralStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/GeneralStatement.java new file mode 100644 index 000000000000..a11171ef3010 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/GeneralStatement.java @@ -0,0 +1,74 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.Collection; +import java.util.HashSet; + + +public class GeneralStatement extends Statement { + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + private GeneralStatement() { + type = Statement.TYPE_GENERAL; + } + + public GeneralStatement(Statement head, Collection<Statement> statements, Statement post) { + + this(); + + first = head; + stats.addWithKey(head, head.id); + + HashSet<Statement> set = new HashSet<Statement>(statements); + set.remove(head); + + for (Statement st : set) { + stats.addWithKey(st, st.id); + } + + this.post = post; + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public String toJava(int indent) { + String indstr = InterpreterUtil.getIndentString(indent); + StringBuilder buf = new StringBuilder(); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + if (isLabeled()) { + buf.append(indstr).append("label").append(this.id).append(":").append(new_line_separator); + } + + buf.append(indstr).append("abstract statement {").append(new_line_separator); + for (int i = 0; i < stats.size(); i++) { + buf.append(stats.get(i).toJava(indent + 1)); + } + buf.append(indstr).append("}"); + + return buf.toString(); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/IfStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/IfStatement.java new file mode 100644 index 000000000000..9ad812534c6c --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/IfStatement.java @@ -0,0 +1,416 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.DecHelper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.IfExprent; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class IfStatement extends Statement { + + public static int IFTYPE_IF = 0; + public static int IFTYPE_IFELSE = 1; + + public int iftype; + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private Statement ifstat; + private Statement elsestat; + + private StatEdge ifedge; + private StatEdge elseedge; + + private boolean negated = false; + + private boolean iffflag; + + private List<Exprent> headexprent = new ArrayList<Exprent>(); // contains IfExprent + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + private IfStatement() { + type = TYPE_IF; + + headexprent.add(null); + } + + private IfStatement(Statement head, int regedges, Statement postst) { + + this(); + + first = head; + stats.addWithKey(head, head.id); + + List<StatEdge> lstHeadSuccs = head.getSuccessorEdges(STATEDGE_DIRECT_ALL); + + switch (regedges) { + case 0: + ifstat = null; + elsestat = null; + + break; + case 1: + ifstat = null; + elsestat = null; + + StatEdge edgeif = lstHeadSuccs.get(1); + if (edgeif.getType() != StatEdge.TYPE_REGULAR) { + post = lstHeadSuccs.get(0).getDestination(); + } + else { + post = edgeif.getDestination(); + negated = true; + } + break; + case 2: + elsestat = lstHeadSuccs.get(0).getDestination(); + ifstat = lstHeadSuccs.get(1).getDestination(); + + List<StatEdge> lstSucc = ifstat.getSuccessorEdges(StatEdge.TYPE_REGULAR); + List<StatEdge> lstSucc1 = elsestat.getSuccessorEdges(StatEdge.TYPE_REGULAR); + + if (ifstat.getPredecessorEdges(StatEdge.TYPE_REGULAR).size() > 1 || lstSucc.size() > 1) { + post = ifstat; + } + else if (elsestat.getPredecessorEdges(StatEdge.TYPE_REGULAR).size() > 1 || lstSucc1.size() > 1) { + post = elsestat; + } + else { + if (lstSucc.size() == 0) { + post = elsestat; + } + else if (lstSucc1.size() == 0) { + post = ifstat; + } + } + + if (ifstat == post) { + if (elsestat != post) { + ifstat = elsestat; + negated = true; + } + else { + ifstat = null; + } + elsestat = null; + } + else if (elsestat == post) { + elsestat = null; + } + else { + post = postst; + } + + if (elsestat == null) { + regedges = 1; // if without else + } + } + + ifedge = lstHeadSuccs.get(negated ? 0 : 1); + elseedge = (regedges == 2) ? lstHeadSuccs.get(negated ? 1 : 0) : null; + + iftype = (regedges == 2) ? IFTYPE_IFELSE : IFTYPE_IF; + + if (iftype == IFTYPE_IF) { + if (regedges == 0) { + StatEdge edge = lstHeadSuccs.get(0); + head.removeSuccessor(edge); + edge.setSource(this); + this.addSuccessor(edge); + } + else if (regedges == 1) { + StatEdge edge = lstHeadSuccs.get(negated ? 1 : 0); + head.removeSuccessor(edge); + } + } + + if (ifstat != null) { + stats.addWithKey(ifstat, ifstat.id); + } + + if (elsestat != null) { + stats.addWithKey(elsestat, elsestat.id); + } + + if (post == head) { + post = this; + } + } + + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public static Statement isHead(Statement head) { + + if (head.type == TYPE_BASICBLOCK && head.getLastBasicType() == LASTBASICTYPE_IF) { + int regsize = head.getSuccessorEdges(StatEdge.TYPE_REGULAR).size(); + + Statement p = null; + + boolean ok = (regsize < 2); + if (!ok) { + List<Statement> lst = new ArrayList<Statement>(); + if (DecHelper.isChoiceStatement(head, lst)) { + p = lst.remove(0); + + for (Statement st : lst) { + if (st.isMonitorEnter()) { + return null; + } + } + + ok = DecHelper.checkStatementExceptions(lst); + } + } + + if (ok) { + return new IfStatement(head, regsize, p); + } + } + + return null; + } + + public String toJava(int indent) { + String indstr = InterpreterUtil.getIndentString(indent); + StringBuilder buf = new StringBuilder(); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + buf.append(ExprProcessor.listToJava(varDefinitions, indent)); + buf.append(first.toJava(indent)); + + if (isLabeled()) { + buf.append(indstr).append("label").append(this.id).append(":").append(new_line_separator); + } + + buf.append(indstr).append(headexprent.get(0).toJava(indent)).append(" {").append(new_line_separator); + + if (ifstat == null) { + buf.append(InterpreterUtil.getIndentString(indent + 1)); + + if (ifedge.explicit) { + if (ifedge.getType() == StatEdge.TYPE_BREAK) { + // break + buf.append("break"); + } + else { + // continue + buf.append("continue"); + } + + if (ifedge.labeled) { + buf.append(" label").append(ifedge.closure.id); + } + } + buf.append(";").append(new_line_separator); + } + else { + buf.append(ExprProcessor.jmpWrapper(ifstat, indent + 1, true)); + } + + boolean elseif = false; + + if (elsestat != null) { + if (elsestat.type == Statement.TYPE_IF + && elsestat.varDefinitions.isEmpty() && elsestat.getFirst().getExprents().isEmpty() && + !elsestat.isLabeled() && + (elsestat.getSuccessorEdges(STATEDGE_DIRECT_ALL).isEmpty() + || !elsestat.getSuccessorEdges(STATEDGE_DIRECT_ALL).get(0).explicit)) { // else if + String content = ExprProcessor.jmpWrapper(elsestat, indent, false); + content = content.substring(indstr.length()); + + buf.append(indstr).append("} else "); + buf.append(content); + + elseif = true; + } + else { + String content = ExprProcessor.jmpWrapper(elsestat, indent + 1, false); + + if (content.length() > 0) { + buf.append(indstr).append("} else {").append(new_line_separator); + buf.append(content); + } + } + } + + if (!elseif) { + buf.append(indstr).append("}").append(new_line_separator); + } + + return buf.toString(); + } + + public void initExprents() { + + IfExprent ifexpr = (IfExprent)first.getExprents().remove(first.getExprents().size() - 1); + + if (negated) { + ifexpr = (IfExprent)ifexpr.copy(); + ifexpr.negateIf(); + } + + headexprent.set(0, ifexpr); + } + + public List<Object> getSequentialObjects() { + + List<Object> lst = new ArrayList<Object>(stats); + lst.add(1, headexprent.get(0)); + + return lst; + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (headexprent.get(0) == oldexpr) { + headexprent.set(0, newexpr); + } + } + + public void replaceStatement(Statement oldstat, Statement newstat) { + + super.replaceStatement(oldstat, newstat); + + if (ifstat == oldstat) { + ifstat = newstat; + } + + if (elsestat == oldstat) { + elsestat = newstat; + } + + List<StatEdge> lstSuccs = first.getSuccessorEdges(STATEDGE_DIRECT_ALL); + + if (iftype == IFTYPE_IF) { + ifedge = lstSuccs.get(0); + elseedge = null; + } + else { + StatEdge edge0 = lstSuccs.get(0); + StatEdge edge1 = lstSuccs.get(1); + if (edge0.getDestination() == ifstat) { + ifedge = edge0; + elseedge = edge1; + } + else { + ifedge = edge1; + elseedge = edge0; + } + } + } + + public Statement getSimpleCopy() { + + IfStatement is = new IfStatement(); + is.iftype = this.iftype; + is.negated = this.negated; + is.iffflag = this.iffflag; + + return is; + } + + public void initSimpleCopy() { + + first = stats.get(0); + + List<StatEdge> lstSuccs = first.getSuccessorEdges(STATEDGE_DIRECT_ALL); + ifedge = lstSuccs.get((iftype == IFTYPE_IF || negated) ? 0 : 1); + if (stats.size() > 1) { + ifstat = stats.get(1); + } + + if (iftype == IFTYPE_IFELSE) { + elseedge = lstSuccs.get(negated ? 1 : 0); + elsestat = stats.get(2); + } + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public Statement getElsestat() { + return elsestat; + } + + public void setElsestat(Statement elsestat) { + this.elsestat = elsestat; + } + + public Statement getIfstat() { + return ifstat; + } + + public void setIfstat(Statement ifstat) { + this.ifstat = ifstat; + } + + public boolean isNegated() { + return negated; + } + + public void setNegated(boolean negated) { + this.negated = negated; + } + + public List<Exprent> getHeadexprentList() { + return headexprent; + } + + public IfExprent getHeadexprent() { + return (IfExprent)headexprent.get(0); + } + + public boolean isIffflag() { + return iffflag; + } + + public void setIffflag(boolean iffflag) { + this.iffflag = iffflag; + } + + public void setElseEdge(StatEdge elseedge) { + this.elseedge = elseedge; + } + + public void setIfEdge(StatEdge ifedge) { + this.ifedge = ifedge; + } + + public StatEdge getIfEdge() { + return ifedge; + } + + public StatEdge getElseEdge() { + return elseedge; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/RootStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/RootStatement.java new file mode 100644 index 000000000000..2a6944712ace --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/RootStatement.java @@ -0,0 +1,48 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; + + +public class RootStatement extends Statement { + + private Statement dummyExit; + + public RootStatement(Statement head, Statement dummyExit) { + + type = Statement.TYPE_ROOT; + + first = head; + this.dummyExit = dummyExit; + + stats.addWithKey(first, first.id); + first.setParent(this); + } + + public String toJava(int indent) { + return ExprProcessor.listToJava(varDefinitions, indent) + + first.toJava(indent); + } + + public Statement getDummyExit() { + return dummyExit; + } + + public void setDummyExit(Statement dummyExit) { + this.dummyExit = dummyExit; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SequenceStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SequenceStatement.java new file mode 100644 index 000000000000..eccce91fd051 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SequenceStatement.java @@ -0,0 +1,144 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.DecHelper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.Arrays; +import java.util.List; + + +public class SequenceStatement extends Statement { + + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + private SequenceStatement() { + type = Statement.TYPE_SEQUENCE; + } + + public SequenceStatement(List<Statement> lst) { + + this(); + + lastBasicType = lst.get(lst.size() - 1).getLastBasicType(); + + for (Statement st : lst) { + stats.addWithKey(st, st.id); + } + + first = stats.get(0); + } + + private SequenceStatement(Statement head, Statement tail) { + + this(Arrays.asList(head, tail)); + + List<StatEdge> lstSuccs = tail.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (!lstSuccs.isEmpty()) { + StatEdge edge = lstSuccs.get(0); + + if (edge.getType() == StatEdge.TYPE_REGULAR && edge.getDestination() != head) { + post = edge.getDestination(); + } + } + } + + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public static Statement isHead2Block(Statement head) { + + if (head.getLastBasicType() != Statement.LASTBASICTYPE_GENERAL) { + return null; + } + + // at most one outgoing edge + StatEdge edge = null; + List<StatEdge> lstSuccs = head.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (!lstSuccs.isEmpty()) { + edge = lstSuccs.get(0); + } + + if (edge != null && edge.getType() == StatEdge.TYPE_REGULAR) { + Statement stat = edge.getDestination(); + + if (stat != head && stat.getPredecessorEdges(StatEdge.TYPE_REGULAR).size() == 1 + && !stat.isMonitorEnter()) { + + if (stat.getLastBasicType() == Statement.LASTBASICTYPE_GENERAL) { + if (DecHelper.checkStatementExceptions(Arrays.asList(head, stat))) { + return new SequenceStatement(head, stat); + } + } + } + } + + return null; + } + + public String toJava(int indent) { + + StringBuilder buf = new StringBuilder(); + + String indstr = null; + boolean islabeled = isLabeled(); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + buf.append(ExprProcessor.listToJava(varDefinitions, indent)); + + if (islabeled) { + indstr = InterpreterUtil.getIndentString(indent); + indent++; + buf.append(indstr).append("label").append(this.id).append(": {").append(new_line_separator); + } + + boolean notempty = false; + + for (int i = 0; i < stats.size(); i++) { + + Statement st = stats.get(i); + + if (i > 0 && notempty) { + buf.append(new_line_separator); + } + + String str = ExprProcessor.jmpWrapper(st, indent, false); + buf.append(str); + + notempty = (str.trim().length() > 0); + } + + if (islabeled) { + buf.append(indstr).append("}").append(new_line_separator); + } + + return buf.toString(); + } + + public Statement getSimpleCopy() { + return new SequenceStatement(); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/Statement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/Statement.java new file mode 100644 index 000000000000..cbdb3b71ff22 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/Statement.java @@ -0,0 +1,863 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.code.InstructionSequence; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.StrongConnectivityHelper; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.*; + +public class Statement { + + public static final int STATEDGE_ALL = 1 << 31; + public static final int STATEDGE_DIRECT_ALL = 1 << 30; + + public static final int DIRECTION_BACKWARD = 0; + public static final int DIRECTION_FORWARD = 1; + + public static final int TYPE_GENERAL = 0; + public static final int TYPE_IF = 2; + public static final int TYPE_DO = 5; + public static final int TYPE_SWITCH = 6; + public static final int TYPE_TRYCATCH = 7; + public static final int TYPE_BASICBLOCK = 8; + public static final int TYPE_FINALLY = 9; + public static final int TYPE_SYNCRONIZED = 10; + public static final int TYPE_PLACEHOLDER = 11; + public static final int TYPE_CATCHALL = 12; + public static final int TYPE_ROOT = 13; + public static final int TYPE_DUMMYEXIT = 14; + public static final int TYPE_SEQUENCE = 15; + + + public static final int LASTBASICTYPE_IF = 0; + public static final int LASTBASICTYPE_SWITCH = 1; + public static final int LASTBASICTYPE_GENERAL = 2; + + + // ***************************************************************************** + // public fields + // ***************************************************************************** + + public int type; + + public Integer id; + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private Map<Integer, List<StatEdge>> mapSuccEdges = new HashMap<Integer, List<StatEdge>>(); + private Map<Integer, List<StatEdge>> mapPredEdges = new HashMap<Integer, List<StatEdge>>(); + + private Map<Integer, List<Statement>> mapSuccStates = new HashMap<Integer, List<Statement>>(); + private Map<Integer, List<Statement>> mapPredStates = new HashMap<Integer, List<Statement>>(); + + // statement as graph + protected VBStyleCollection<Statement, Integer> stats = new VBStyleCollection<Statement, Integer>(); + + protected Statement parent; + + protected Statement first; + + protected List<Exprent> exprents; + + protected HashSet<StatEdge> labelEdges = new HashSet<StatEdge>(); + + protected List<Exprent> varDefinitions = new ArrayList<Exprent>(); + + // copied statement, s. deobfuscating of irreducible CFGs + private boolean copied = false; + + // relevant for the first stage of processing only + // set to null after initializing of the statement structure + + protected Statement post; + + protected int lastBasicType = LASTBASICTYPE_GENERAL; + + protected boolean isMonitorEnter; + + protected boolean containsMonitorExit; + + protected HashSet<Statement> continueSet = new HashSet<Statement>(); + + // ***************************************************************************** + // initializers + // ***************************************************************************** + + { + // set statement id + id = DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER); + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public void clearTempInformation() { + + post = null; + continueSet = null; + + copied = false; + // FIXME: used in FlattenStatementsHelper.flattenStatement()! check and remove + //lastBasicType = LASTBASICTYPE_GENERAL; + isMonitorEnter = false; + containsMonitorExit = false; + + processMap(mapSuccEdges); + processMap(mapPredEdges); + processMap(mapSuccStates); + processMap(mapPredStates); + } + + private static <T> void processMap(Map<Integer, List<T>> map) { + map.remove(StatEdge.TYPE_EXCEPTION); + + List<T> lst = map.get(STATEDGE_DIRECT_ALL); + if (lst != null) { + map.put(STATEDGE_ALL, new ArrayList<T>(lst)); + } + else { + map.remove(STATEDGE_ALL); + } + } + + public void collapseNodesToStatement(Statement stat) { + + Statement head = stat.getFirst(); + Statement post = stat.getPost(); + + VBStyleCollection<Statement, Integer> setNodes = stat.getStats(); + + // post edges + if (post != null) { + for (StatEdge edge : post.getEdges(STATEDGE_DIRECT_ALL, DIRECTION_BACKWARD)) { + if (stat.containsStatementStrict(edge.getSource())) { + edge.getSource().changeEdgeType(DIRECTION_FORWARD, edge, StatEdge.TYPE_BREAK); + stat.addLabeledEdge(edge); + } + } + } + + // regular head edges + for (StatEdge prededge : head.getAllPredecessorEdges()) { + + if (prededge.getType() != StatEdge.TYPE_EXCEPTION && + stat.containsStatementStrict(prededge.getSource())) { + prededge.getSource().changeEdgeType(DIRECTION_FORWARD, prededge, StatEdge.TYPE_CONTINUE); + stat.addLabeledEdge(prededge); + } + + head.removePredecessor(prededge); + prededge.getSource().changeEdgeNode(DIRECTION_FORWARD, prededge, stat); + stat.addPredecessor(prededge); + } + + if (setNodes.containsKey(first.id)) { + first = stat; + } + + // exception edges + Set<Statement> setHandlers = new HashSet<Statement>(head.getNeighbours(StatEdge.TYPE_EXCEPTION, DIRECTION_FORWARD)); + for (Statement node : setNodes) { + setHandlers.retainAll(node.getNeighbours(StatEdge.TYPE_EXCEPTION, DIRECTION_FORWARD)); + } + + if (!setHandlers.isEmpty()) { + + for (StatEdge edge : head.getEdges(StatEdge.TYPE_EXCEPTION, DIRECTION_FORWARD)) { + Statement handler = edge.getDestination(); + + if (setHandlers.contains(handler)) { + if (!setNodes.containsKey(handler.id)) { + stat.addSuccessor(new StatEdge(stat, handler, edge.getExceptions())); + } + } + } + + for (Statement node : setNodes) { + for (StatEdge edge : node.getEdges(StatEdge.TYPE_EXCEPTION, DIRECTION_FORWARD)) { + if (setHandlers.contains(edge.getDestination())) { + node.removeSuccessor(edge); + } + } + } + } + + if (post != null && + !stat.getNeighbours(StatEdge.TYPE_EXCEPTION, DIRECTION_FORWARD).contains(post)) { // TODO: second condition redundant? + stat.addSuccessor(new StatEdge(StatEdge.TYPE_REGULAR, stat, post)); + } + + + // adjust statement collection + for (Statement st : setNodes) { + stats.removeWithKey(st.id); + } + + stats.addWithKey(stat, stat.id); + + stat.setAllParent(); + stat.setParent(this); + + stat.buildContinueSet(); + // monitorenter and monitorexit + stat.buildMonitorFlags(); + + if (stat.type == TYPE_SWITCH) { + // special case switch, sorting leaf nodes + ((SwitchStatement)stat).sortEdgesAndNodes(); + } + } + + public void setAllParent() { + for (Statement st : stats) { + st.setParent(this); + } + } + + public void addLabeledEdge(StatEdge edge) { + + if (edge.closure != null) { + edge.closure.getLabelEdges().remove(edge); + } + edge.closure = this; + this.getLabelEdges().add(edge); + } + + private void addEdgeDirectInternal(int direction, StatEdge edge, int edgetype) { + + Map<Integer, List<StatEdge>> mapEdges = direction == DIRECTION_BACKWARD ? mapPredEdges : mapSuccEdges; + Map<Integer, List<Statement>> mapStates = direction == DIRECTION_BACKWARD ? mapPredStates : mapSuccStates; + + List<StatEdge> lst = mapEdges.get(edgetype); + if (lst == null) { + mapEdges.put(edgetype, lst = new ArrayList<StatEdge>()); + } + lst.add(edge); + + List<Statement> lstStates = mapStates.get(edgetype); + if (lstStates == null) { + mapStates.put(edgetype, lstStates = new ArrayList<Statement>()); + } + lstStates.add(direction == DIRECTION_BACKWARD ? edge.getSource() : edge.getDestination()); + } + + private void addEdgeInternal(int direction, StatEdge edge) { + + int type = edge.getType(); + + int[] arrtypes; + if (type == StatEdge.TYPE_EXCEPTION) { + arrtypes = new int[]{STATEDGE_ALL, StatEdge.TYPE_EXCEPTION}; + } + else { + arrtypes = new int[]{STATEDGE_ALL, STATEDGE_DIRECT_ALL, type}; + } + + for (int edgetype : arrtypes) { + addEdgeDirectInternal(direction, edge, edgetype); + } + } + + private void removeEdgeDirectInternal(int direction, StatEdge edge, int edgetype) { + + Map<Integer, List<StatEdge>> mapEdges = direction == DIRECTION_BACKWARD ? mapPredEdges : mapSuccEdges; + Map<Integer, List<Statement>> mapStates = direction == DIRECTION_BACKWARD ? mapPredStates : mapSuccStates; + + List<StatEdge> lst = mapEdges.get(edgetype); + if (lst != null) { + int index = lst.indexOf(edge); + if (index >= 0) { + lst.remove(index); + mapStates.get(edgetype).remove(index); + } + } + } + + private void removeEdgeInternal(int direction, StatEdge edge) { + + int type = edge.getType(); + + int[] arrtypes; + if (type == StatEdge.TYPE_EXCEPTION) { + arrtypes = new int[]{STATEDGE_ALL, StatEdge.TYPE_EXCEPTION}; + } + else { + arrtypes = new int[]{STATEDGE_ALL, STATEDGE_DIRECT_ALL, type}; + } + + for (int edgetype : arrtypes) { + removeEdgeDirectInternal(direction, edge, edgetype); + } + } + + public void addPredecessor(StatEdge edge) { + addEdgeInternal(DIRECTION_BACKWARD, edge); + } + + public void removePredecessor(StatEdge edge) { + + if (edge == null) { // FIXME: redundant? + return; + } + + removeEdgeInternal(DIRECTION_BACKWARD, edge); + } + + public void addSuccessor(StatEdge edge) { + addEdgeInternal(DIRECTION_FORWARD, edge); + + if (edge.closure != null) { + edge.closure.getLabelEdges().add(edge); + } + + edge.getDestination().addPredecessor(edge); + } + + public void removeSuccessor(StatEdge edge) { + + if (edge == null) { + return; + } + + removeEdgeInternal(DIRECTION_FORWARD, edge); + + if (edge.closure != null) { + edge.closure.getLabelEdges().remove(edge); + } + + if (edge.getDestination() != null) { // TODO: redundant? + edge.getDestination().removePredecessor(edge); + } + } + + // TODO: make obsolete and remove + public void removeAllSuccessors(Statement stat) { + + if (stat == null) { + return; + } + + for (StatEdge edge : getAllSuccessorEdges()) { + if (edge.getDestination() == stat) { + removeSuccessor(edge); + } + } + } + + public HashSet<Statement> buildContinueSet() { + continueSet.clear(); + + for (Statement st : stats) { + continueSet.addAll(st.buildContinueSet()); + if (st != first) { + continueSet.remove(st.getBasichead()); + } + } + + for (StatEdge edge : getEdges(StatEdge.TYPE_CONTINUE, DIRECTION_FORWARD)) { + continueSet.add(edge.getDestination().getBasichead()); + } + + if (type == TYPE_DO) { + continueSet.remove(first.getBasichead()); + } + + return continueSet; + } + + public void buildMonitorFlags() { + + for (Statement st : stats) { + st.buildMonitorFlags(); + } + + switch (type) { + case TYPE_BASICBLOCK: + BasicBlockStatement bblock = (BasicBlockStatement)this; + InstructionSequence seq = bblock.getBlock().getSeq(); + + if (seq != null && seq.length() > 0) { + for (int i = 0; i < seq.length(); i++) { + if (seq.getInstr(i).opcode == CodeConstants.opc_monitorexit) { + containsMonitorExit = true; + break; + } + } + isMonitorEnter = (seq.getLastInstr().opcode == CodeConstants.opc_monitorenter); + } + break; + case TYPE_SEQUENCE: + case TYPE_IF: + containsMonitorExit = false; + for (Statement st : stats) { + containsMonitorExit |= st.isContainsMonitorExit(); + } + + break; + case TYPE_SYNCRONIZED: + case TYPE_ROOT: + case TYPE_GENERAL: + break; + default: + containsMonitorExit = false; + for (Statement st : stats) { + containsMonitorExit |= st.isContainsMonitorExit(); + } + } + } + + + public List<Statement> getReversePostOrderList() { + return getReversePostOrderList(first); + } + + public List<Statement> getReversePostOrderList(Statement stat) { + List<Statement> res = new ArrayList<Statement>(); + + addToReversePostOrderListIterative(stat, res); + + return res; + } + + public List<Statement> getPostReversePostOrderList() { + return getPostReversePostOrderList(null); + } + + public List<Statement> getPostReversePostOrderList(List<Statement> lstexits) { + + List<Statement> res = new ArrayList<Statement>(); + + if (lstexits == null) { + StrongConnectivityHelper schelper = new StrongConnectivityHelper(this); + lstexits = StrongConnectivityHelper.getExitReps(schelper.getComponents()); + } + + HashSet<Statement> setVisited = new HashSet<Statement>(); + + for (Statement exit : lstexits) { + addToPostReversePostOrderList(exit, res, setVisited); + } + + if (res.size() != stats.size()) { + DecompilerContext.getLogger().writeMessage("computing post reverse post order failed!", IFernflowerLogger.Severity.ERROR); + + throw new RuntimeException("parsing failure!"); + } + + return res; + } + + public boolean containsStatement(Statement stat) { + return this == stat || containsStatementStrict(stat); + } + + public boolean containsStatementStrict(Statement stat) { + + if (stats.contains(stat)) { + return true; + } + + for (int i = 0; i < stats.size(); i++) { + if (stats.get(i).containsStatementStrict(stat)) { + return true; + } + } + + return false; + } + + // to be overwritten + public String toJava() { + return toJava(0); + } + + public String toJava(int indent) { + throw new RuntimeException("not implemented"); + } + + // TODO: make obsolete and remove + public List<Object> getSequentialObjects() { + return new ArrayList<Object>(stats); + } + + public void initExprents() { + // do nothing + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + // do nothing + } + + public Statement getSimpleCopy() { + throw new RuntimeException("not implemented"); + } + + public void initSimpleCopy() { + if (!stats.isEmpty()) { + first = stats.get(0); + } + } + + public void replaceStatement(Statement oldstat, Statement newstat) { + + for (StatEdge edge : oldstat.getAllPredecessorEdges()) { + oldstat.removePredecessor(edge); + edge.getSource().changeEdgeNode(DIRECTION_FORWARD, edge, newstat); + newstat.addPredecessor(edge); + } + + for (StatEdge edge : oldstat.getAllSuccessorEdges()) { + oldstat.removeSuccessor(edge); + edge.setSource(newstat); + newstat.addSuccessor(edge); + } + + int statindex = stats.getIndexByKey(oldstat.id); + stats.removeWithKey(oldstat.id); + stats.addWithKeyAndIndex(statindex, newstat, newstat.id); + + newstat.setParent(this); + newstat.post = oldstat.post; + + if (first == oldstat) { + first = newstat; + } + + List<StatEdge> lst = new ArrayList<StatEdge>(oldstat.getLabelEdges()); + + for (int i = lst.size() - 1; i >= 0; i--) { + StatEdge edge = lst.get(i); + if (edge.getSource() != newstat) { + newstat.addLabeledEdge(edge); + } + else { + if (this == edge.getDestination() || this.containsStatementStrict(edge.getDestination())) { + edge.closure = null; + } + else { + this.addLabeledEdge(edge); + } + } + } + + oldstat.getLabelEdges().clear(); + } + + + // ***************************************************************************** + // private methods + // ***************************************************************************** + + private static void addToReversePostOrderListIterative(Statement root, List<Statement> lst) { + + LinkedList<Statement> stackNode = new LinkedList<Statement>(); + LinkedList<Integer> stackIndex = new LinkedList<Integer>(); + HashSet<Statement> setVisited = new HashSet<Statement>(); + + stackNode.add(root); + stackIndex.add(0); + + while (!stackNode.isEmpty()) { + + Statement node = stackNode.getLast(); + int index = stackIndex.removeLast(); + + setVisited.add(node); + + List<StatEdge> lstEdges = node.getAllSuccessorEdges(); + + for (; index < lstEdges.size(); index++) { + StatEdge edge = lstEdges.get(index); + Statement succ = edge.getDestination(); + + if (!setVisited.contains(succ) && + (edge.getType() == StatEdge.TYPE_REGULAR || edge.getType() == StatEdge.TYPE_EXCEPTION)) { // TODO: edge filter? + + stackIndex.add(index + 1); + + stackNode.add(succ); + stackIndex.add(0); + + break; + } + } + + if (index == lstEdges.size()) { + lst.add(0, node); + + stackNode.removeLast(); + } + } + } + + + private static void addToPostReversePostOrderList(Statement stat, List<Statement> lst, HashSet<Statement> setVisited) { + + if (setVisited.contains(stat)) { // because of not considered exception edges, s. isExitComponent. Should be rewritten, if possible. + return; + } + setVisited.add(stat); + + for (StatEdge prededge : stat.getEdges(StatEdge.TYPE_REGULAR | StatEdge.TYPE_EXCEPTION, DIRECTION_BACKWARD)) { + Statement pred = prededge.getSource(); + if (!setVisited.contains(pred)) { + addToPostReversePostOrderList(pred, lst, setVisited); + } + } + + lst.add(0, stat); + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public void changeEdgeNode(int direction, StatEdge edge, Statement value) { + + Map<Integer, List<StatEdge>> mapEdges = direction == DIRECTION_BACKWARD ? mapPredEdges : mapSuccEdges; + Map<Integer, List<Statement>> mapStates = direction == DIRECTION_BACKWARD ? mapPredStates : mapSuccStates; + + int type = edge.getType(); + + int[] arrtypes; + if (type == StatEdge.TYPE_EXCEPTION) { + arrtypes = new int[]{STATEDGE_ALL, StatEdge.TYPE_EXCEPTION}; + } + else { + arrtypes = new int[]{STATEDGE_ALL, STATEDGE_DIRECT_ALL, type}; + } + + for (int edgetype : arrtypes) { + List<StatEdge> lst = mapEdges.get(edgetype); + if (lst != null) { + int index = lst.indexOf(edge); + if (index >= 0) { + mapStates.get(edgetype).set(index, value); + } + } + } + + if (direction == DIRECTION_BACKWARD) { + edge.setSource(value); + } + else { + edge.setDestination(value); + } + } + + public void changeEdgeType(int direction, StatEdge edge, int newtype) { + + int oldtype = edge.getType(); + if (oldtype == newtype) { + return; + } + + if (oldtype == StatEdge.TYPE_EXCEPTION || newtype == StatEdge.TYPE_EXCEPTION) { + throw new RuntimeException("Invalid edge type!"); + } + + removeEdgeDirectInternal(direction, edge, oldtype); + addEdgeDirectInternal(direction, edge, newtype); + + if (direction == DIRECTION_FORWARD) { + edge.getDestination().changeEdgeType(DIRECTION_BACKWARD, edge, newtype); + } + + edge.setType(newtype); + } + + + private List<StatEdge> getEdges(int type, int direction) { + + Map<Integer, List<StatEdge>> map = direction == DIRECTION_BACKWARD ? mapPredEdges : mapSuccEdges; + + List<StatEdge> res; + if ((type & (type - 1)) == 0) { + res = map.get(type); + res = res == null ? new ArrayList<StatEdge>() : new ArrayList<StatEdge>(res); + } + else { + res = new ArrayList<StatEdge>(); + for (int edgetype : StatEdge.TYPES) { + if ((type & edgetype) != 0) { + List<StatEdge> lst = map.get(edgetype); + if (lst != null) { + res.addAll(lst); + } + } + } + } + + return res; + } + + public List<Statement> getNeighbours(int type, int direction) { + + Map<Integer, List<Statement>> map = direction == DIRECTION_BACKWARD ? mapPredStates : mapSuccStates; + + List<Statement> res; + if ((type & (type - 1)) == 0) { + res = map.get(type); + res = res == null ? new ArrayList<Statement>() : new ArrayList<Statement>(res); + } + else { + res = new ArrayList<Statement>(); + for (int edgetype : StatEdge.TYPES) { + if ((type & edgetype) != 0) { + List<Statement> lst = map.get(edgetype); + if (lst != null) { + res.addAll(lst); + } + } + } + } + + return res; + } + + public Set<Statement> getNeighboursSet(int type, int direction) { + return new HashSet<Statement>(getNeighbours(type, direction)); + } + + public List<StatEdge> getSuccessorEdges(int type) { + return getEdges(type, DIRECTION_FORWARD); + } + + public List<StatEdge> getPredecessorEdges(int type) { + return getEdges(type, DIRECTION_BACKWARD); + } + + public List<StatEdge> getAllSuccessorEdges() { + return getEdges(STATEDGE_ALL, DIRECTION_FORWARD); + } + + public List<StatEdge> getAllPredecessorEdges() { + return getEdges(STATEDGE_ALL, DIRECTION_BACKWARD); + } + + public Statement getFirst() { + return first; + } + + public void setFirst(Statement first) { + this.first = first; + } + + public Statement getPost() { + return post; + } + + public void setPost(Statement post) { + this.post = post; + } + + public VBStyleCollection<Statement, Integer> getStats() { + return stats; + } + + public int getLastBasicType() { + return lastBasicType; + } + + public HashSet<Statement> getContinueSet() { + return continueSet; + } + + public boolean isContainsMonitorExit() { + return containsMonitorExit; + } + + public boolean isMonitorEnter() { + return isMonitorEnter; + } + + public BasicBlockStatement getBasichead() { + if (type == TYPE_BASICBLOCK) { + return (BasicBlockStatement)this; + } + else { + return first.getBasichead(); + } + } + + public boolean isLabeled() { + + for (StatEdge edge : labelEdges) { + if (edge.labeled && edge.explicit) { // FIXME: consistent setting + return true; + } + } + return false; + } + + public boolean hasBasicSuccEdge() { + + // FIXME: default switch + + return type == TYPE_BASICBLOCK || (type == TYPE_IF && + ((IfStatement)this).iftype == IfStatement.IFTYPE_IF) || + (type == TYPE_DO && ((DoStatement)this).getLooptype() != DoStatement.LOOP_DO); + } + + + public Statement getParent() { + return parent; + } + + public void setParent(Statement parent) { + this.parent = parent; + } + + public HashSet<StatEdge> getLabelEdges() { // FIXME: why HashSet? + return labelEdges; + } + + public List<Exprent> getVarDefinitions() { + return varDefinitions; + } + + public List<Exprent> getExprents() { + return exprents; + } + + public void setExprents(List<Exprent> exprents) { + this.exprents = exprents; + } + + public boolean isCopied() { + return copied; + } + + public void setCopied(boolean copied) { + this.copied = copied; + } + + // helper methods + public String toString() { + return id.toString(); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SwitchStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SwitchStatement.java new file mode 100644 index 000000000000..b54642dfb58f --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SwitchStatement.java @@ -0,0 +1,367 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.code.SwitchInstruction; +import org.jetbrains.java.decompiler.code.cfg.BasicBlock; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.DecHelper; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.ConstExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.SwitchExprent; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.*; + +public class SwitchStatement extends Statement { + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private List<Statement> caseStatements = new ArrayList<Statement>(); + + private List<List<StatEdge>> caseEdges = new ArrayList<List<StatEdge>>(); + + private List<List<ConstExprent>> caseValues = new ArrayList<List<ConstExprent>>(); + + private StatEdge default_edge; + + private List<Exprent> headexprent = new ArrayList<Exprent>(); + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + private SwitchStatement() { + type = TYPE_SWITCH; + + headexprent.add(null); + } + + private SwitchStatement(Statement head, Statement poststat) { + + this(); + + first = head; + stats.addWithKey(head, head.id); + + // find post node + Set<Statement> lstNodes = new HashSet<Statement>(head.getNeighbours(StatEdge.TYPE_REGULAR, DIRECTION_FORWARD)); + + // cluster nodes + if (poststat != null) { + post = poststat; + lstNodes.remove(post); + } + + default_edge = head.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL).get(0); + + for (Statement st : lstNodes) { + stats.addWithKey(st, st.id); + } + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public static Statement isHead(Statement head) { + + if (head.type == Statement.TYPE_BASICBLOCK && head.getLastBasicType() == Statement.LASTBASICTYPE_SWITCH) { + + List<Statement> lst = new ArrayList<Statement>(); + if (DecHelper.isChoiceStatement(head, lst)) { + Statement post = lst.remove(0); + + for (Statement st : lst) { + if (st.isMonitorEnter()) { + return null; + } + } + + if (DecHelper.checkStatementExceptions(lst)) { + return new SwitchStatement(head, post); + } + } + } + + return null; + } + + public String toJava(int indent) { + + String indstr = InterpreterUtil.getIndentString(indent); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + buf.append(ExprProcessor.listToJava(varDefinitions, indent)); + buf.append(first.toJava(indent)); + + if (isLabeled()) { + buf.append(indstr).append("label").append(this.id).append(":").append(new_line_separator); + } + + buf.append(indstr).append(headexprent.get(0).toJava(indent)).append(" {").append(new_line_separator); + + VarType switch_type = headexprent.get(0).getExprType(); + + for (int i = 0; i < caseStatements.size(); i++) { + + Statement stat = caseStatements.get(i); + List<StatEdge> edges = caseEdges.get(i); + List<ConstExprent> values = caseValues.get(i); + + for (int j = 0; j < edges.size(); j++) { + if (edges.get(j) == default_edge) { + buf.append(indstr).append("default:").append(new_line_separator); + } + else { + ConstExprent value = (ConstExprent)values.get(j).copy(); + value.setConsttype(switch_type); + + buf.append(indstr).append("case ").append(value.toJava(indent)).append(":").append(new_line_separator); + } + } + + buf.append(ExprProcessor.jmpWrapper(stat, indent + 1, false)); + } + + buf.append(indstr).append("}").append(new_line_separator); + + return buf.toString(); + } + + public void initExprents() { + SwitchExprent swexpr = (SwitchExprent)first.getExprents().remove(first.getExprents().size() - 1); + swexpr.setCaseValues(caseValues); + + headexprent.set(0, swexpr); + } + + public List<Object> getSequentialObjects() { + + List<Object> lst = new ArrayList<Object>(stats); + lst.add(1, headexprent.get(0)); + + return lst; + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (headexprent.get(0) == oldexpr) { + headexprent.set(0, newexpr); + } + } + + public void replaceStatement(Statement oldstat, Statement newstat) { + + for (int i = 0; i < caseStatements.size(); i++) { + if (caseStatements.get(i) == oldstat) { + caseStatements.set(i, newstat); + } + } + + super.replaceStatement(oldstat, newstat); + } + + public Statement getSimpleCopy() { + return new SwitchStatement(); + } + + public void initSimpleCopy() { + first = stats.get(0); + default_edge = first.getSuccessorEdges(Statement.STATEDGE_DIRECT_ALL).get(0); + + sortEdgesAndNodes(); + } + + // ***************************************************************************** + // private methods + // ***************************************************************************** + + public void sortEdgesAndNodes() { + + HashMap<StatEdge, Integer> mapEdgeIndex = new HashMap<StatEdge, Integer>(); + + List<StatEdge> lstFirstSuccs = first.getSuccessorEdges(STATEDGE_DIRECT_ALL); + for (int i = 0; i < lstFirstSuccs.size(); i++) { + mapEdgeIndex.put(lstFirstSuccs.get(i), i == 0 ? lstFirstSuccs.size() : i); + } + + // case values + BasicBlockStatement bbstat = (BasicBlockStatement)first; + int[] values = ((SwitchInstruction)bbstat.getBlock().getLastInstruction()).getValues(); + + List<Statement> nodes = new ArrayList<Statement>(); + List<List<Integer>> edges = new ArrayList<List<Integer>>(); + + // collect regular edges + for (int i = 1; i < stats.size(); i++) { + + Statement stat = stats.get(i); + + List<Integer> lst = new ArrayList<Integer>(); + for (StatEdge edge : stat.getPredecessorEdges(StatEdge.TYPE_REGULAR)) { + if (edge.getSource() == first) { + lst.add(mapEdgeIndex.get(edge)); + } + } + Collections.sort(lst); + + nodes.add(stat); + edges.add(lst); + } + + // collect exit edges + List<StatEdge> lstExitEdges = first.getSuccessorEdges(StatEdge.TYPE_BREAK | StatEdge.TYPE_CONTINUE); + while (!lstExitEdges.isEmpty()) { + StatEdge edge = lstExitEdges.get(0); + + List<Integer> lst = new ArrayList<Integer>(); + for (int i = lstExitEdges.size() - 1; i >= 0; i--) { + StatEdge edgeTemp = lstExitEdges.get(i); + if (edgeTemp.getDestination() == edge.getDestination() && edgeTemp.getType() == edge.getType()) { + lst.add(mapEdgeIndex.get(edgeTemp)); + lstExitEdges.remove(i); + } + } + Collections.sort(lst); + + nodes.add(null); + edges.add(lst); + } + + // sort edges (bubblesort) + for (int i = 0; i < edges.size() - 1; i++) { + for (int j = edges.size() - 1; j > i; j--) { + if (edges.get(j - 1).get(0) > edges.get(j).get(0)) { + edges.set(j, edges.set(j - 1, edges.get(j))); + nodes.set(j, nodes.set(j - 1, nodes.get(j))); + } + } + } + + // sort statement cliques + for (int index = 0; index < nodes.size(); index++) { + Statement stat = nodes.get(index); + + if (stat != null) { + HashSet<Statement> setPreds = new HashSet<Statement>(stat.getNeighbours(StatEdge.TYPE_REGULAR, DIRECTION_BACKWARD)); + setPreds.remove(first); + + if (!setPreds.isEmpty()) { + Statement pred = + setPreds.iterator().next(); // assumption: at most one predecessor node besides the head. May not hold true for obfuscated code. + for (int j = 0; j < nodes.size(); j++) { + if (j != (index - 1) && nodes.get(j) == pred) { + nodes.add(j + 1, stat); + edges.add(j + 1, edges.get(index)); + + if (j > index) { + nodes.remove(index); + edges.remove(index); + index--; + } + else { + nodes.remove(index + 1); + edges.remove(index + 1); + } + break; + } + } + } + } + } + + // translate indices back into edges + List<List<StatEdge>> lstEdges = new ArrayList<List<StatEdge>>(); + List<List<ConstExprent>> lstValues = new ArrayList<List<ConstExprent>>(); + + for (List<Integer> lst : edges) { + List<StatEdge> lste = new ArrayList<StatEdge>(); + List<ConstExprent> lstv = new ArrayList<ConstExprent>(); + + List<StatEdge> lstSuccs = first.getSuccessorEdges(STATEDGE_DIRECT_ALL); + for (Integer in : lst) { + int index = in == lstSuccs.size() ? 0 : in; + + lste.add(lstSuccs.get(index)); + lstv.add(index == 0 ? null : new ConstExprent(values[index - 1], false)); + } + lstEdges.add(lste); + lstValues.add(lstv); + } + + // replace null statements with dummy basic blocks + for (int i = 0; i < nodes.size(); i++) { + if (nodes.get(i) == null) { + BasicBlockStatement bstat = new BasicBlockStatement(new BasicBlock( + DecompilerContext.getCounterContainer().getCounterAndIncrement(CounterContainer.STATEMENT_COUNTER))); + + StatEdge sample_edge = lstEdges.get(i).get(0); + + bstat.addSuccessor(new StatEdge(sample_edge.getType(), bstat, sample_edge.getDestination(), sample_edge.closure)); + + for (StatEdge edge : lstEdges.get(i)) { + + edge.getSource().changeEdgeType(DIRECTION_FORWARD, edge, StatEdge.TYPE_REGULAR); + edge.closure.getLabelEdges().remove(edge); + + edge.getDestination().removePredecessor(edge); + edge.getSource().changeEdgeNode(DIRECTION_FORWARD, edge, bstat); + bstat.addPredecessor(edge); + } + + nodes.set(i, bstat); + stats.addWithKey(bstat, bstat.id); + bstat.setParent(this); + } + } + + caseStatements = nodes; + caseEdges = lstEdges; + caseValues = lstValues; + } + + public List<Exprent> getHeadexprentList() { + return headexprent; + } + + public Exprent getHeadexprent() { + return headexprent.get(0); + } + + public List<List<StatEdge>> getCaseEdges() { + return caseEdges; + } + + public List<Statement> getCaseStatements() { + return caseStatements; + } + + public StatEdge getDefault_edge() { + return default_edge; + } + + public List<List<ConstExprent>> getCaseValues() { + return caseValues; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SynchronizedStatement.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SynchronizedStatement.java new file mode 100644 index 000000000000..6e3dc4704175 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/stats/SynchronizedStatement.java @@ -0,0 +1,153 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.stats; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor; +import org.jetbrains.java.decompiler.modules.decompiler.SequenceHelper; +import org.jetbrains.java.decompiler.modules.decompiler.StatEdge; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.util.ArrayList; +import java.util.List; + + +public class SynchronizedStatement extends Statement { + + private Statement body; + + private List<Exprent> headexprent = new ArrayList<Exprent>(); + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public SynchronizedStatement() { + type = TYPE_SYNCRONIZED; + + headexprent.add(null); + } + + public SynchronizedStatement(Statement head, Statement body, Statement exc) { + + this(); + + first = head; + stats.addWithKey(head, head.id); + + this.body = body; + stats.addWithKey(body, body.id); + + stats.addWithKey(exc, exc.id); + + List<StatEdge> lstSuccs = body.getSuccessorEdges(STATEDGE_DIRECT_ALL); + if (!lstSuccs.isEmpty()) { + StatEdge edge = lstSuccs.get(0); + if (edge.getType() == StatEdge.TYPE_REGULAR) { + post = edge.getDestination(); + } + } + } + + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public String toJava(int indent) { + String indstr = InterpreterUtil.getIndentString(indent); + + String new_line_separator = DecompilerContext.getNewLineSeparator(); + + StringBuilder buf = new StringBuilder(); + buf.append(ExprProcessor.listToJava(varDefinitions, indent)); + buf.append(first.toJava(indent)); + + if (isLabeled()) { + buf.append(indstr).append("label").append(this.id).append(":").append(new_line_separator); + } + + buf.append(indstr).append(headexprent.get(0).toJava(indent)).append(" {").append(new_line_separator); + buf.append(ExprProcessor.jmpWrapper(body, indent + 1, true)); + buf.append(indstr).append("}").append(new_line_separator); + + return buf.toString(); + } + + public void initExprents() { + headexprent.set(0, first.getExprents().remove(first.getExprents().size() - 1)); + } + + public List<Object> getSequentialObjects() { + + List<Object> lst = new ArrayList<Object>(stats); + lst.add(1, headexprent.get(0)); + + return lst; + } + + public void replaceExprent(Exprent oldexpr, Exprent newexpr) { + if (headexprent.get(0) == oldexpr) { + headexprent.set(0, newexpr); + } + } + + public void replaceStatement(Statement oldstat, Statement newstat) { + + if (body == oldstat) { + body = newstat; + } + + super.replaceStatement(oldstat, newstat); + } + + public void removeExc() { + Statement exc = stats.get(2); + SequenceHelper.destroyStatementContent(exc, true); + + stats.removeWithKey(exc.id); + } + + public Statement getSimpleCopy() { + return new SynchronizedStatement(); + } + + public void initSimpleCopy() { + first = stats.get(0); + body = stats.get(1); + } + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public Statement getBody() { + return body; + } + + public void setBody(Statement body) { + this.body = body; + } + + public List<Exprent> getHeadexprentList() { + return headexprent; + } + + public Exprent getHeadexprent() { + return headexprent.get(0); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/CheckTypesResult.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/CheckTypesResult.java new file mode 100644 index 000000000000..08c32ec398f9 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/CheckTypesResult.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.util.ArrayList; +import java.util.List; + +public class CheckTypesResult { + + private List<ExprentTypePair> lstMaxTypeExprents = new ArrayList<ExprentTypePair>(); + + private List<ExprentTypePair> lstMinTypeExprents = new ArrayList<ExprentTypePair>(); + + public void addMaxTypeExprent(Exprent exprent, VarType type) { + lstMaxTypeExprents.add(new ExprentTypePair(exprent, type, null)); + } + + public void addMinTypeExprent(Exprent exprent, VarType type) { + lstMinTypeExprents.add(new ExprentTypePair(exprent, type, null)); + } + + public List<ExprentTypePair> getLstMaxTypeExprents() { + return lstMaxTypeExprents; + } + + public List<ExprentTypePair> getLstMinTypeExprents() { + return lstMinTypeExprents; + } + + public static class ExprentTypePair { + public Exprent exprent; + public VarType type; + public VarType desttype; + + public ExprentTypePair(Exprent exprent, VarType type, VarType desttype) { + this.exprent = exprent; + this.type = type; + this.desttype = desttype; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarDefinitionHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarDefinitionHelper.java new file mode 100644 index 000000000000..fdd6cd5015f8 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarDefinitionHelper.java @@ -0,0 +1,355 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector; +import org.jetbrains.java.decompiler.modules.decompiler.exps.AssignmentExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchAllStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.DoStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; + +import java.util.*; +import java.util.Map.Entry; + +public class VarDefinitionHelper { + + private HashMap<Integer, Statement> mapVarDefStatements; + + // statement.id, defined vars + private HashMap<Integer, HashSet<Integer>> mapStatementVars; + + private HashSet<Integer> implDefVars; + + private VarProcessor varproc; + + public VarDefinitionHelper(Statement root, StructMethod mt, VarProcessor varproc) { + + mapVarDefStatements = new HashMap<Integer, Statement>(); + mapStatementVars = new HashMap<Integer, HashSet<Integer>>(); + implDefVars = new HashSet<Integer>(); + + this.varproc = varproc; + + VarNamesCollector vc = DecompilerContext.getVarNamesCollector(); + + boolean thisvar = !mt.hasModifier(CodeConstants.ACC_STATIC); + + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + + int paramcount = 0; + if (thisvar) { + paramcount = 1; + } + paramcount += md.params.length; + + + // method parameters are implicitly defined + int varindex = 0; + for (int i = 0; i < paramcount; i++) { + implDefVars.add(varindex); + varproc.setVarName(new VarVersionPaar(varindex, 0), vc.getFreeName(varindex)); + + if (thisvar) { + if (i == 0) { + varindex++; + } + else { + varindex += md.params[i - 1].stack_size; + } + } + else { + varindex += md.params[i].stack_size; + } + } + + if (thisvar) { + StructClass current_class = (StructClass)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS); + + varproc.getThisvars().put(new VarVersionPaar(0, 0), current_class.qualifiedName); + varproc.setVarName(new VarVersionPaar(0, 0), "this"); + vc.addName("this"); + } + + // catch variables are implicitly defined + LinkedList<Statement> stack = new LinkedList<Statement>(); + stack.add(root); + + while (!stack.isEmpty()) { + Statement st = stack.removeFirst(); + + List<VarExprent> lstVars = null; + if (st.type == Statement.TYPE_CATCHALL) { + lstVars = ((CatchAllStatement)st).getVars(); + } + else if (st.type == Statement.TYPE_TRYCATCH) { + lstVars = ((CatchStatement)st).getVars(); + } + + if (lstVars != null) { + for (VarExprent var : lstVars) { + implDefVars.add(var.getIndex()); + varproc.setVarName(new VarVersionPaar(var), vc.getFreeName(var.getIndex())); + var.setDefinition(true); + } + } + + stack.addAll(st.getStats()); + } + + initStatement(root); + } + + + public void setVarDefinitions() { + + VarNamesCollector vc = DecompilerContext.getVarNamesCollector(); + + for (Entry<Integer, Statement> en : mapVarDefStatements.entrySet()) { + Statement stat = en.getValue(); + Integer index = en.getKey(); + + if (implDefVars.contains(index)) { + // already implicitly defined + continue; + } + + varproc.setVarName(new VarVersionPaar(index.intValue(), 0), vc.getFreeName(index)); + + // special case for + if (stat.type == Statement.TYPE_DO) { + DoStatement dstat = (DoStatement)stat; + if (dstat.getLooptype() == DoStatement.LOOP_FOR) { + + if (dstat.getInitExprent() != null && setDefinition(dstat.getInitExprent(), index)) { + continue; + } + else { + List<Exprent> lstSpecial = Arrays.asList(dstat.getConditionExprent(), dstat.getIncExprent()); + for (VarExprent var : getAllVars(lstSpecial)) { + if (var.getIndex() == index.intValue()) { + stat = stat.getParent(); + break; + } + } + } + } + } + + + Statement first = findFirstBlock(stat, index); + + List<Exprent> lst; + if (first == null) { + lst = stat.getVarDefinitions(); + } + else if (first.getExprents() == null) { + lst = first.getVarDefinitions(); + } + else { + lst = first.getExprents(); + } + + + boolean defset = false; + + // search for the first assignement to var [index] + int addindex = 0; + for (Exprent expr : lst) { + if (setDefinition(expr, index)) { + defset = true; + break; + } + else { + boolean foundvar = false; + for (Exprent exp : expr.getAllExprents(true)) { + if (exp.type == Exprent.EXPRENT_VAR && ((VarExprent)exp).getIndex() == index) { + foundvar = true; + break; + } + } + if (foundvar) { + break; + } + } + addindex++; + } + + if (!defset) { + VarExprent var = new VarExprent(index.intValue(), varproc.getVarType(new VarVersionPaar(index.intValue(), 0)), varproc); + var.setDefinition(true); + + lst.add(addindex, var); + } + } + } + + + // ***************************************************************************** + // private methods + // ***************************************************************************** + + private Statement findFirstBlock(Statement stat, Integer varindex) { + + LinkedList<Statement> stack = new LinkedList<Statement>(); + stack.add(stat); + + while (!stack.isEmpty()) { + Statement st = stack.remove(0); + + if (stack.isEmpty() || mapStatementVars.get(st.id).contains(varindex)) { + + if (st.isLabeled() && !stack.isEmpty()) { + return st; + } + + if (st.getExprents() != null) { + return st; + } + else { + stack.clear(); + + switch (st.type) { + case Statement.TYPE_SEQUENCE: + stack.addAll(0, st.getStats()); + break; + case Statement.TYPE_IF: + case Statement.TYPE_ROOT: + case Statement.TYPE_SWITCH: + case Statement.TYPE_SYNCRONIZED: + stack.add(st.getFirst()); + break; + default: + return st; + } + } + } + } + + return null; + } + + private Set<Integer> initStatement(Statement stat) { + + HashMap<Integer, Integer> mapCount = new HashMap<Integer, Integer>(); + + List<VarExprent> condlst; + + if (stat.getExprents() == null) { + + // recurse on children statements + List<Integer> childVars = new ArrayList<Integer>(); + List<Exprent> currVars = new ArrayList<Exprent>(); + + for (Object obj : stat.getSequentialObjects()) { + if (obj instanceof Statement) { + Statement st = (Statement)obj; + childVars.addAll(initStatement(st)); + + if (st.type == DoStatement.TYPE_DO) { + DoStatement dost = (DoStatement)st; + if (dost.getLooptype() != DoStatement.LOOP_FOR && + dost.getLooptype() != DoStatement.LOOP_DO) { + currVars.add(dost.getConditionExprent()); + } + } + else if (st.type == DoStatement.TYPE_CATCHALL) { + CatchAllStatement fin = (CatchAllStatement)st; + if (fin.isFinally() && fin.getMonitor() != null) { + currVars.add(fin.getMonitor()); + } + } + } + else if (obj instanceof Exprent) { + currVars.add((Exprent)obj); + } + } + + // children statements + for (Integer index : childVars) { + Integer count = mapCount.get(index); + if (count == null) { + count = new Integer(0); + } + mapCount.put(index, new Integer(count.intValue() + 1)); + } + + condlst = getAllVars(currVars); + } + else { + condlst = getAllVars(stat.getExprents()); + } + + // this statement + for (VarExprent var : condlst) { + mapCount.put(new Integer(var.getIndex()), new Integer(2)); + } + + + HashSet<Integer> set = new HashSet<Integer>(mapCount.keySet()); + + // put all variables defined in this statement into the set + for (Entry<Integer, Integer> en : mapCount.entrySet()) { + if (en.getValue().intValue() > 1) { + mapVarDefStatements.put(en.getKey(), stat); + } + } + + mapStatementVars.put(stat.id, set); + + return set; + } + + private static List<VarExprent> getAllVars(List<Exprent> lst) { + + List<VarExprent> res = new ArrayList<VarExprent>(); + List<Exprent> listTemp = new ArrayList<Exprent>(); + + for (Exprent expr : lst) { + listTemp.addAll(expr.getAllExprents(true)); + listTemp.add(expr); + } + + for (Exprent exprent : listTemp) { + if (exprent.type == Exprent.EXPRENT_VAR) { + res.add((VarExprent)exprent); + } + } + + return res; + } + + private static boolean setDefinition(Exprent expr, Integer index) { + if (expr.type == Exprent.EXPRENT_ASSIGNMENT) { + Exprent left = ((AssignmentExprent)expr).getLeft(); + if (left.type == Exprent.EXPRENT_VAR) { + VarExprent var = (VarExprent)left; + if (var.getIndex() == index.intValue()) { + var.setDefinition(true); + return true; + } + } + } + return false; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarProcessor.java new file mode 100644 index 000000000000..266ba94e1cda --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarProcessor.java @@ -0,0 +1,129 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.util.*; +import java.util.Map.Entry; + + +public class VarProcessor { + + private HashMap<VarVersionPaar, String> mapVarNames = new HashMap<VarVersionPaar, String>(); + + private VarVersionsProcessor varvers; + + private HashMap<VarVersionPaar, String> thisvars = new HashMap<VarVersionPaar, String>(); + + private HashSet<VarVersionPaar> externvars = new HashSet<VarVersionPaar>(); + + public void setVarVersions(RootStatement root) { + + varvers = new VarVersionsProcessor(); + varvers.setVarVersions(root); + } + + public void setVarDefinitions(Statement root) { + mapVarNames = new HashMap<VarVersionPaar, String>(); + + VarDefinitionHelper defproc = new VarDefinitionHelper(root, + (StructMethod)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD), + this); + defproc.setVarDefinitions(); + } + + public void setDebugVarNames(Map<Integer, String> mapDebugVarNames) { + if (varvers == null) { + return; + } + + HashMap<Integer, Integer> mapOriginalVarIndices = varvers.getMapOriginalVarIndices(); + + List<VarVersionPaar> listVars = new ArrayList<VarVersionPaar>(mapVarNames.keySet()); + Collections.sort(listVars, new Comparator<VarVersionPaar>() { + public int compare(VarVersionPaar o1, VarVersionPaar o2) { + return o1.var > o2.var ? 1 : (o1.var == o2.var ? 0 : -1); + } + }); + + HashMap<String, Integer> mapNames = new HashMap<String, Integer>(); + + for (VarVersionPaar varpaar : listVars) { + String name = mapVarNames.get(varpaar); + + Integer orindex = mapOriginalVarIndices.get(varpaar.var); + if (orindex != null && mapDebugVarNames.containsKey(orindex)) { + name = mapDebugVarNames.get(orindex); + } + + Integer counter = mapNames.get(name); + mapNames.put(name, counter == null ? counter = new Integer(0) : ++counter); + + if (counter > 0) { + name += String.valueOf(counter); + } + + mapVarNames.put(varpaar, name); + } + } + + public void refreshVarNames(VarNamesCollector vc) { + + HashMap<VarVersionPaar, String> tempVarNames = new HashMap<VarVersionPaar, String>(mapVarNames); + for (Entry<VarVersionPaar, String> ent : tempVarNames.entrySet()) { + mapVarNames.put(ent.getKey(), vc.getFreeName(ent.getValue())); + } + } + + + public VarType getVarType(VarVersionPaar varpaar) { + return varvers == null ? null : varvers.getVarType(varpaar); + } + + public void setVarType(VarVersionPaar varpaar, VarType type) { + varvers.setVarType(varpaar, type); + } + + public String getVarName(VarVersionPaar varpaar) { + return mapVarNames == null ? null : mapVarNames.get(varpaar); + } + + public void setVarName(VarVersionPaar varpaar, String name) { + mapVarNames.put(varpaar, name); + } + + public int getVarFinal(VarVersionPaar varpaar) { + return varvers == null ? VarTypeProcessor.VAR_FINAL : varvers.getVarFinal(varpaar); + } + + public void setVarFinal(VarVersionPaar varpaar, int finaltype) { + varvers.setVarFinal(varpaar, finaltype); + } + + public HashMap<VarVersionPaar, String> getThisvars() { + return thisvars; + } + + public HashSet<VarVersionPaar> getExternvars() { + return externvars; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarTypeProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarTypeProcessor.java new file mode 100644 index 000000000000..a21d71f7e9f7 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarTypeProcessor.java @@ -0,0 +1,278 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchAllStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.CatchStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.modules.decompiler.stats.Statement; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; + +public class VarTypeProcessor { + + public static final int VAR_NONFINAL = 1; + public static final int VAR_FINALEXPLICIT = 2; + public static final int VAR_FINAL = 3; + + private HashMap<VarVersionPaar, VarType> mapExprentMinTypes = new HashMap<VarVersionPaar, VarType>(); + + private HashMap<VarVersionPaar, VarType> mapExprentMaxTypes = new HashMap<VarVersionPaar, VarType>(); + + private HashMap<VarVersionPaar, Integer> mapFinalVars = new HashMap<VarVersionPaar, Integer>(); + + private void setInitVars(RootStatement root) { + + StructMethod mt = (StructMethod)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD); + + // method descriptor + boolean thisvar = !mt.hasModifier(CodeConstants.ACC_STATIC); + + MethodDescriptor md = (MethodDescriptor)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD_DESCRIPTOR); + + if (thisvar) { + VarType cltype = new VarType(CodeConstants.TYPE_OBJECT, 0, + ((StructClass)DecompilerContext.getProperty(DecompilerContext.CURRENT_CLASS)).qualifiedName); + mapExprentMinTypes.put(new VarVersionPaar(0, 1), cltype); + mapExprentMaxTypes.put(new VarVersionPaar(0, 1), cltype); + } + + int varindex = 0; + for (int i = 0; i < md.params.length; i++) { + mapExprentMinTypes.put(new VarVersionPaar(varindex + (thisvar ? 1 : 0), 1), md.params[i]); + mapExprentMaxTypes.put(new VarVersionPaar(varindex + (thisvar ? 1 : 0), 1), md.params[i]); + varindex += md.params[i].stack_size; + } + + // catch variables + LinkedList<Statement> stack = new LinkedList<Statement>(); + stack.add(root); + + while (!stack.isEmpty()) { + Statement stat = stack.removeFirst(); + + List<VarExprent> lstVars = null; + if (stat.type == Statement.TYPE_CATCHALL) { + lstVars = ((CatchAllStatement)stat).getVars(); + } + else if (stat.type == Statement.TYPE_TRYCATCH) { + lstVars = ((CatchStatement)stat).getVars(); + } + + if (lstVars != null) { + for (VarExprent var : lstVars) { + mapExprentMinTypes.put(new VarVersionPaar(var.getIndex(), 1), var.getVartype()); + mapExprentMaxTypes.put(new VarVersionPaar(var.getIndex(), 1), var.getVartype()); + } + } + + stack.addAll(stat.getStats()); + } + } + + public void calculateVarTypes(RootStatement root, DirectGraph dgraph) { + + setInitVars(root); + + resetExprentTypes(dgraph); + + while (!processVarTypes(dgraph)) ; + } + + private static void resetExprentTypes(DirectGraph dgraph) { + + dgraph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + if (expr.type == Exprent.EXPRENT_VAR) { + ((VarExprent)expr).setVartype(VarType.VARTYPE_UNKNOWN); + } + else if (expr.type == Exprent.EXPRENT_CONST) { + ConstExprent cexpr = (ConstExprent)expr; + if (cexpr.getConsttype().type_family == CodeConstants.TYPE_FAMILY_INTEGER) { + cexpr.setConsttype(new ConstExprent(cexpr.getIntValue(), cexpr.isBoolPermitted()).getConsttype()); + } + } + } + return 0; + } + }); + } + + private boolean processVarTypes(DirectGraph dgraph) { + + return dgraph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + return checkTypeExprent(exprent) ? 0 : 1; + } + }); + } + + + private boolean checkTypeExprent(Exprent exprent) { + + for (Exprent expr : exprent.getAllExprents()) { + if (!checkTypeExprent(expr)) { + return false; + } + } + + if (exprent.type == Exprent.EXPRENT_CONST) { + ConstExprent cexpr = (ConstExprent)exprent; + if (cexpr.getConsttype().type_family <= CodeConstants.TYPE_FAMILY_INTEGER) { // boolean or integer + VarVersionPaar cpaar = new VarVersionPaar(cexpr.id, -1); + if (!mapExprentMinTypes.containsKey(cpaar)) { + mapExprentMinTypes.put(cpaar, cexpr.getConsttype()); + } + } + } + + CheckTypesResult result = exprent.checkExprTypeBounds(); + + for (CheckTypesResult.ExprentTypePair entry : result.getLstMaxTypeExprents()) { + if (entry.type.type_family != CodeConstants.TYPE_FAMILY_OBJECT) { + changeExprentType(entry.exprent, entry.type, 1); + } + } + + boolean res = true; + for (CheckTypesResult.ExprentTypePair entry : result.getLstMinTypeExprents()) { + res &= changeExprentType(entry.exprent, entry.type, 0); + } + + return res; + } + + + private boolean changeExprentType(Exprent exprent, VarType newtype, int minmax) { + + boolean res = true; + + switch (exprent.type) { + case Exprent.EXPRENT_CONST: + ConstExprent cexpr = (ConstExprent)exprent; + VarType consttype = cexpr.getConsttype(); + + if (newtype.type_family > CodeConstants.TYPE_FAMILY_INTEGER || consttype.type_family > CodeConstants.TYPE_FAMILY_INTEGER) { + return true; + } + else if (newtype.type_family == CodeConstants.TYPE_FAMILY_INTEGER) { + VarType mininteger = new ConstExprent((Integer)((ConstExprent)exprent).getValue(), false).getConsttype(); + if (mininteger.isStrictSuperset(newtype)) { + newtype = mininteger; + } + } + case Exprent.EXPRENT_VAR: + VarVersionPaar varpaar = null; + if (exprent.type == Exprent.EXPRENT_CONST) { + varpaar = new VarVersionPaar(((ConstExprent)exprent).id, -1); + } + else if (exprent.type == Exprent.EXPRENT_VAR) { + varpaar = new VarVersionPaar((VarExprent)exprent); + } + + if (minmax == 0) { // min + VarType currentMinType = mapExprentMinTypes.get(varpaar); + VarType newMinType; + if (currentMinType == null || newtype.type_family > currentMinType.type_family) { + newMinType = newtype; + } + else if (newtype.type_family < currentMinType.type_family) { + return true; + } + else { + newMinType = VarType.getCommonSupertype(currentMinType, newtype); + } + + mapExprentMinTypes.put(varpaar, newMinType); + if (exprent.type == Exprent.EXPRENT_CONST) { + ((ConstExprent)exprent).setConsttype(newMinType); + } + + if (currentMinType != null && (newMinType.type_family > currentMinType.type_family || + newMinType.isStrictSuperset(currentMinType))) { + return false; + } + } + else { // max + VarType currentMaxType = mapExprentMaxTypes.get(varpaar); + VarType newMaxType; + if (currentMaxType == null || newtype.type_family < currentMaxType.type_family) { + newMaxType = newtype; + } + else if (newtype.type_family > currentMaxType.type_family) { + return true; + } + else { + newMaxType = VarType.getCommonMinType(currentMaxType, newtype); + } + + mapExprentMaxTypes.put(varpaar, newMaxType); + } + break; + case Exprent.EXPRENT_ASSIGNMENT: + return changeExprentType(((AssignmentExprent)exprent).getRight(), newtype, minmax); + case Exprent.EXPRENT_FUNCTION: + FunctionExprent func = (FunctionExprent)exprent; + switch (func.getFunctype()) { + case FunctionExprent.FUNCTION_IIF: // FIXME: + res &= changeExprentType(func.getLstOperands().get(1), newtype, minmax); + res &= changeExprentType(func.getLstOperands().get(2), newtype, minmax); + break; + case FunctionExprent.FUNCTION_AND: + case FunctionExprent.FUNCTION_OR: + case FunctionExprent.FUNCTION_XOR: + res &= changeExprentType(func.getLstOperands().get(0), newtype, minmax); + res &= changeExprentType(func.getLstOperands().get(1), newtype, minmax); + } + } + + return res; + } + + public HashMap<VarVersionPaar, VarType> getMapExprentMaxTypes() { + return mapExprentMaxTypes; + } + + public HashMap<VarVersionPaar, VarType> getMapExprentMinTypes() { + return mapExprentMinTypes; + } + + public HashMap<VarVersionPaar, Integer> getMapFinalVars() { + return mapFinalVars; + } + + public void setVarType(VarVersionPaar varpaar, VarType type) { + mapExprentMinTypes.put(varpaar, type); + } + + public VarType getVarType(VarVersionPaar varpaar) { + return mapExprentMinTypes.get(varpaar); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionEdge.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionEdge.java new file mode 100644 index 000000000000..9d9798279d41 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionEdge.java @@ -0,0 +1,56 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +public class VarVersionEdge { // FIXME: can be removed? + + public static final int EDGE_GENERAL = 0; + public static final int EDGE_PHANTOM = 1; + + public int type; + + public VarVersionNode source; + + public VarVersionNode dest; + + private int hashCode; + + public VarVersionEdge(int type, VarVersionNode source, VarVersionNode dest) { + this.type = type; + this.source = source; + this.dest = dest; + this.hashCode = source.hashCode() ^ dest.hashCode() + type; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof VarVersionEdge)) return false; + + VarVersionEdge edge = (VarVersionEdge)o; + return type == edge.type && source == edge.source && dest == edge.dest; + } + + @Override + public int hashCode() { + return hashCode; + } + + @Override + public String toString() { + return source.toString() + " ->" + type + "-> " + dest.toString(); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionNode.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionNode.java new file mode 100644 index 000000000000..587c653dc3fb --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionNode.java @@ -0,0 +1,80 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.modules.decompiler.decompose.IGraphNode; +import org.jetbrains.java.decompiler.util.SFormsFastMapDirect; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class VarVersionNode implements IGraphNode { + + public static final int FLAG_PHANTOM_FINEXIT = 2; + + public int var; + + public int version; + + public Set<VarVersionEdge> succs = new HashSet<VarVersionEdge>(); + + public Set<VarVersionEdge> preds = new HashSet<VarVersionEdge>(); + + public int flags; + + public SFormsFastMapDirect live = new SFormsFastMapDirect(); + + + public VarVersionNode(int var, int version) { + this.var = var; + this.version = version; + } + + public VarVersionPaar getVarPaar() { + return new VarVersionPaar(var, version); + } + + public List<IGraphNode> getPredecessors() { + List<IGraphNode> lst = new ArrayList<IGraphNode>(preds.size()); + for (VarVersionEdge edge : preds) { + lst.add(edge.source); + } + return lst; + } + + public void removeSuccessor(VarVersionEdge edge) { + succs.remove(edge); + } + + public void removePredecessor(VarVersionEdge edge) { + preds.remove(edge); + } + + public void addSuccessor(VarVersionEdge edge) { + succs.add(edge); + } + + public void addPredecessor(VarVersionEdge edge) { + preds.add(edge); + } + + @Override + public String toString() { + return "(" + var + "_" + version + ")"; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionPaar.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionPaar.java new file mode 100644 index 000000000000..5f3e520a84d0 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionPaar.java @@ -0,0 +1,63 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; + +public class VarVersionPaar { + + public int var; + public int version; + + private int hashCode = -1; + + public VarVersionPaar(int var, int version) { + this.var = var; + this.version = version; + } + + public VarVersionPaar(Integer var, Integer version) { + this.var = var.intValue(); + this.version = version.intValue(); + } + + public VarVersionPaar(VarExprent var) { + this.var = var.getIndex(); + this.version = var.getVersion(); + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof VarVersionPaar)) return false; + + VarVersionPaar paar = (VarVersionPaar)o; + return var == paar.var && version == paar.version; + } + + @Override + public int hashCode() { + if (hashCode == -1) { + hashCode = this.var * 3 + this.version; + } + return hashCode; + } + + @Override + public String toString() { + return "(" + var + "," + version + ")"; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionsGraph.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionsGraph.java new file mode 100644 index 000000000000..f839a05819df --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionsGraph.java @@ -0,0 +1,167 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.modules.decompiler.decompose.GenericDominatorEngine; +import org.jetbrains.java.decompiler.modules.decompiler.decompose.IGraph; +import org.jetbrains.java.decompiler.modules.decompiler.decompose.IGraphNode; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.util.*; + + +public class VarVersionsGraph { + + public int counter = 0; + + public VBStyleCollection<VarVersionNode, VarVersionPaar> nodes = new VBStyleCollection<VarVersionNode, VarVersionPaar>(); + + private GenericDominatorEngine engine; + + public VarVersionNode createNode(VarVersionPaar ver) { + VarVersionNode node; + nodes.addWithKey(node = new VarVersionNode(ver.var, ver.version), ver); + return node; + } + + public void addNodes(Collection<VarVersionNode> colnodes, Collection<VarVersionPaar> colpaars) { + nodes.addAllWithKey(colnodes, colpaars); + } + + public boolean isDominatorSet(VarVersionNode node, HashSet<VarVersionNode> domnodes) { + + if (domnodes.size() == 1) { + return engine.isDominator(node, domnodes.iterator().next()); + } + else { + + HashSet<VarVersionNode> marked = new HashSet<VarVersionNode>(); + + if (domnodes.contains(node)) { + return true; + } + + LinkedList<VarVersionNode> lstNodes = new LinkedList<VarVersionNode>(); + lstNodes.add(node); + + while (!lstNodes.isEmpty()) { + + VarVersionNode nd = lstNodes.remove(0); + if (marked.contains(nd)) { + continue; + } + else { + marked.add(nd); + } + + if (nd.preds.isEmpty()) { + return false; + } + + for (VarVersionEdge edge : nd.preds) { + VarVersionNode pred = edge.source; + if (!marked.contains(pred) && !domnodes.contains(pred)) { + lstNodes.add(pred); + } + } + } + } + + return true; + } + + public void initDominators() { + + final HashSet<VarVersionNode> roots = new HashSet<VarVersionNode>(); + + for (VarVersionNode node : nodes) { + if (node.preds.isEmpty()) { + roots.add(node); + } + } + + engine = new GenericDominatorEngine(new IGraph() { + public List<? extends IGraphNode> getReversePostOrderList() { + return getReversedPostOrder(roots); + } + + public Set<? extends IGraphNode> getRoots() { + return new HashSet<IGraphNode>(roots); + } + }); + + engine.initialize(); + } + + private static LinkedList<VarVersionNode> getReversedPostOrder(Collection<VarVersionNode> roots) { + + LinkedList<VarVersionNode> lst = new LinkedList<VarVersionNode>(); + HashSet<VarVersionNode> setVisited = new HashSet<VarVersionNode>(); + + for (VarVersionNode root : roots) { + + LinkedList<VarVersionNode> lstTemp = new LinkedList<VarVersionNode>(); + addToReversePostOrderListIterative(root, lstTemp, setVisited); + + lst.addAll(lstTemp); + } + + return lst; + } + + private static void addToReversePostOrderListIterative(VarVersionNode root, List<VarVersionNode> lst, HashSet<VarVersionNode> setVisited) { + + HashMap<VarVersionNode, List<VarVersionEdge>> mapNodeSuccs = new HashMap<VarVersionNode, List<VarVersionEdge>>(); + + LinkedList<VarVersionNode> stackNode = new LinkedList<VarVersionNode>(); + LinkedList<Integer> stackIndex = new LinkedList<Integer>(); + + stackNode.add(root); + stackIndex.add(0); + + while (!stackNode.isEmpty()) { + + VarVersionNode node = stackNode.getLast(); + int index = stackIndex.removeLast(); + + setVisited.add(node); + + List<VarVersionEdge> lstSuccs = mapNodeSuccs.get(node); + if (lstSuccs == null) { + mapNodeSuccs.put(node, lstSuccs = new ArrayList<VarVersionEdge>(node.succs)); + } + + for (; index < lstSuccs.size(); index++) { + VarVersionNode succ = lstSuccs.get(index).dest; + + if (!setVisited.contains(succ)) { + stackIndex.add(index + 1); + + stackNode.add(succ); + stackIndex.add(0); + + break; + } + } + + if (index == lstSuccs.size()) { + lst.add(0, node); + + stackNode.removeLast(); + } + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionsProcessor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionsProcessor.java new file mode 100644 index 000000000000..06b7216c86fa --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionsProcessor.java @@ -0,0 +1,334 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.decompiler.vars; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.collectors.CounterContainer; +import org.jetbrains.java.decompiler.modules.decompiler.exps.ConstExprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper; +import org.jetbrains.java.decompiler.modules.decompiler.sforms.SSAConstructorSparseEx; +import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory.FastSparseSet; + +import java.util.*; +import java.util.Map.Entry; + +public class VarVersionsProcessor { + + private HashMap<Integer, Integer> mapOriginalVarIndices = new HashMap<Integer, Integer>(); + + private VarTypeProcessor typeproc; + + public void setVarVersions(RootStatement root) { + + StructMethod mt = (StructMethod)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD); + + SSAConstructorSparseEx ssa = new SSAConstructorSparseEx(); + ssa.splitVariables(root, mt); + + FlattenStatementsHelper flatthelper = new FlattenStatementsHelper(); + DirectGraph dgraph = flatthelper.buildDirectGraph(root); + + // System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + mergePhiVersions(ssa, dgraph); + + // System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava()); + + typeproc = new VarTypeProcessor(); + typeproc.calculateVarTypes(root, dgraph); + + simpleMerge(typeproc, dgraph, mt); + + // FIXME: advanced merging + + eliminateNonJavaTypes(typeproc); + + setNewVarIndices(typeproc, dgraph); + } + + private static void mergePhiVersions(SSAConstructorSparseEx ssa, DirectGraph dgraph) { + + // collect phi versions + List<HashSet<VarVersionPaar>> lst = new ArrayList<HashSet<VarVersionPaar>>(); + for (Entry<VarVersionPaar, FastSparseSet<Integer>> ent : ssa.getPhi().entrySet()) { + HashSet<VarVersionPaar> set = new HashSet<VarVersionPaar>(); + set.add(ent.getKey()); + for (Integer vers : ent.getValue()) { + set.add(new VarVersionPaar(ent.getKey().var, vers.intValue())); + } + + for (int i = lst.size() - 1; i >= 0; i--) { + HashSet<VarVersionPaar> tset = lst.get(i); + HashSet<VarVersionPaar> intersection = new HashSet<VarVersionPaar>(set); + intersection.retainAll(tset); + + if (!intersection.isEmpty()) { + set.addAll(tset); + lst.remove(i); + } + } + + lst.add(set); + } + + final HashMap<VarVersionPaar, Integer> phivers = new HashMap<VarVersionPaar, Integer>(); + for (HashSet<VarVersionPaar> set : lst) { + int min = Integer.MAX_VALUE; + for (VarVersionPaar paar : set) { + if (paar.version < min) { + min = paar.version; + } + } + + for (VarVersionPaar paar : set) { + phivers.put(new VarVersionPaar(paar.var, paar.version), min); + } + } + + + dgraph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + if (expr.type == Exprent.EXPRENT_VAR) { + VarExprent var = (VarExprent)expr; + Integer vers = phivers.get(new VarVersionPaar(var)); + if (vers != null) { + var.setVersion(vers); + } + } + } + return 0; + } + }); + } + + private static void eliminateNonJavaTypes(VarTypeProcessor typeproc) { + + HashMap<VarVersionPaar, VarType> mapExprentMaxTypes = typeproc.getMapExprentMaxTypes(); + HashMap<VarVersionPaar, VarType> mapExprentMinTypes = typeproc.getMapExprentMinTypes(); + + HashSet<VarVersionPaar> set = new HashSet<VarVersionPaar>(mapExprentMinTypes.keySet()); + for (VarVersionPaar paar : set) { + VarType type = mapExprentMinTypes.get(paar); + VarType maxtype = mapExprentMaxTypes.get(paar); + + if (type.type == CodeConstants.TYPE_BYTECHAR || type.type == CodeConstants.TYPE_SHORTCHAR) { + if (maxtype != null && maxtype.type == CodeConstants.TYPE_CHAR) { + type = VarType.VARTYPE_CHAR; + } + else { + type = type.type == CodeConstants.TYPE_BYTECHAR ? VarType.VARTYPE_BYTE : VarType.VARTYPE_SHORT; + } + mapExprentMinTypes.put(paar, type); + //} else if(type.type == CodeConstants.TYPE_CHAR && (maxtype == null || maxtype.type == CodeConstants.TYPE_INT)) { // when possible, lift char to int + // mapExprentMinTypes.put(paar, VarType.VARTYPE_INT); + } + else if (type.type == CodeConstants.TYPE_NULL) { + mapExprentMinTypes.put(paar, VarType.VARTYPE_OBJECT); + } + } + } + + private static void simpleMerge(VarTypeProcessor typeproc, DirectGraph dgraph, StructMethod mt) { + + HashMap<VarVersionPaar, VarType> mapExprentMaxTypes = typeproc.getMapExprentMaxTypes(); + HashMap<VarVersionPaar, VarType> mapExprentMinTypes = typeproc.getMapExprentMinTypes(); + + HashMap<Integer, HashSet<Integer>> mapVarVersions = new HashMap<Integer, HashSet<Integer>>(); + + for (VarVersionPaar varpaar : mapExprentMinTypes.keySet()) { + if (varpaar.version >= 0) { // don't merge constants + HashSet<Integer> set = mapVarVersions.get(varpaar.var); + if (set == null) { + set = new HashSet<Integer>(); + mapVarVersions.put(varpaar.var, set); + } + set.add(varpaar.version); + } + } + + boolean is_method_static = mt.hasModifier(CodeConstants.ACC_STATIC); + + final HashMap<VarVersionPaar, Integer> mapMergedVersions = new HashMap<VarVersionPaar, Integer>(); + + for (Entry<Integer, HashSet<Integer>> ent : mapVarVersions.entrySet()) { + + if (ent.getValue().size() > 1) { + List<Integer> lstVersions = new ArrayList<Integer>(ent.getValue()); + Collections.sort(lstVersions); + + for (int i = 0; i < lstVersions.size(); i++) { + VarVersionPaar firstpaar = new VarVersionPaar(ent.getKey(), lstVersions.get(i)); + VarType firsttype = mapExprentMinTypes.get(firstpaar); + + if (firstpaar.var == 0 && firstpaar.version == 1 && !is_method_static) { + continue; // don't merge 'this' variable + } + + for (int j = i + 1; j < lstVersions.size(); j++) { + VarVersionPaar secpaar = new VarVersionPaar(ent.getKey(), lstVersions.get(j)); + VarType sectype = mapExprentMinTypes.get(secpaar); + + if (firsttype.equals(sectype) || (firsttype.equals(VarType.VARTYPE_NULL) && sectype.type == CodeConstants.TYPE_OBJECT) + || (sectype.equals(VarType.VARTYPE_NULL) && firsttype.type == CodeConstants.TYPE_OBJECT)) { + + VarType firstMaxType = mapExprentMaxTypes.get(firstpaar); + VarType secMaxType = mapExprentMaxTypes.get(secpaar); + mapExprentMaxTypes.put(firstpaar, firstMaxType == null ? secMaxType : + (secMaxType == null ? firstMaxType : VarType.getCommonMinType(firstMaxType, secMaxType))); + + + mapMergedVersions.put(secpaar, firstpaar.version); + mapExprentMaxTypes.remove(secpaar); + mapExprentMinTypes.remove(secpaar); + + if (firsttype.equals(VarType.VARTYPE_NULL)) { + mapExprentMinTypes.put(firstpaar, sectype); + firsttype = sectype; + } + + typeproc.getMapFinalVars().put(firstpaar, VarTypeProcessor.VAR_NONFINAL); + + lstVersions.remove(j); + j--; + } + } + } + } + } + + if (!mapMergedVersions.isEmpty()) { + dgraph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + if (expr.type == Exprent.EXPRENT_VAR) { + VarExprent varex = (VarExprent)expr; + Integer newversion = mapMergedVersions.get(new VarVersionPaar(varex)); + if (newversion != null) { + varex.setVersion(newversion); + } + } + } + + return 0; + } + }); + } + } + + private void setNewVarIndices(VarTypeProcessor typeproc, DirectGraph dgraph) { + + final HashMap<VarVersionPaar, VarType> mapExprentMaxTypes = typeproc.getMapExprentMaxTypes(); + HashMap<VarVersionPaar, VarType> mapExprentMinTypes = typeproc.getMapExprentMinTypes(); + HashMap<VarVersionPaar, Integer> mapFinalVars = typeproc.getMapFinalVars(); + + CounterContainer ccon = DecompilerContext.getCounterContainer(); + + final HashMap<VarVersionPaar, Integer> mapVarPaar = new HashMap<VarVersionPaar, Integer>(); + HashMap<Integer, Integer> mapOriginalVarIndices = new HashMap<Integer, Integer>(); + + // map var-version paars on new var indexes + HashSet<VarVersionPaar> set = new HashSet<VarVersionPaar>(mapExprentMinTypes.keySet()); + for (VarVersionPaar vpaar : set) { + + if (vpaar.version >= 0) { + int newindex = vpaar.version == 1 ? vpaar.var : + ccon.getCounterAndIncrement(CounterContainer.VAR_COUNTER); + + VarVersionPaar newvar = new VarVersionPaar(newindex, 0); + + mapExprentMinTypes.put(newvar, mapExprentMinTypes.get(vpaar)); + mapExprentMaxTypes.put(newvar, mapExprentMaxTypes.get(vpaar)); + + if (mapFinalVars.containsKey(vpaar)) { + mapFinalVars.put(newvar, mapFinalVars.remove(vpaar)); + } + + mapVarPaar.put(vpaar, newindex); + mapOriginalVarIndices.put(newindex, vpaar.var); + } + } + + // set new vars + dgraph.iterateExprents(new DirectGraph.ExprentIterator() { + public int processExprent(Exprent exprent) { + List<Exprent> lst = exprent.getAllExprents(true); + lst.add(exprent); + + for (Exprent expr : lst) { + if (expr.type == Exprent.EXPRENT_VAR) { + VarExprent varex = (VarExprent)expr; + Integer newvarindex = mapVarPaar.get(new VarVersionPaar(varex)); + if (newvarindex != null) { + varex.setIndex(newvarindex); + varex.setVersion(0); + } + } + else if (expr.type == Exprent.EXPRENT_CONST) { + VarType maxType = mapExprentMaxTypes.get(new VarVersionPaar(expr.id, -1)); + if (maxType != null && maxType.equals(VarType.VARTYPE_CHAR)) { + ((ConstExprent)expr).setConsttype(maxType); + } + } + } + + return 0; + } + }); + + this.mapOriginalVarIndices = mapOriginalVarIndices; + } + + public VarType getVarType(VarVersionPaar varpaar) { + return typeproc == null ? null : typeproc.getVarType(varpaar); + } + + public void setVarType(VarVersionPaar varpaar, VarType type) { + typeproc.setVarType(varpaar, type); + } + + public int getVarFinal(VarVersionPaar varpaar) { + + int ret = VarTypeProcessor.VAR_FINAL; + if (typeproc != null) { + Integer fin = typeproc.getMapFinalVars().get(varpaar); + ret = fin == null ? VarTypeProcessor.VAR_FINAL : fin.intValue(); + } + + return ret; + } + + public void setVarFinal(VarVersionPaar varpaar, int finaltype) { + typeproc.getMapFinalVars().put(varpaar, finaltype); + } + + public HashMap<Integer, Integer> getMapOriginalVarIndices() { + return mapOriginalVarIndices; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/ClassWrapperNode.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/ClassWrapperNode.java new file mode 100644 index 000000000000..273579a56373 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/ClassWrapperNode.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.renamer; + +import org.jetbrains.java.decompiler.struct.StructClass; + +import java.util.ArrayList; +import java.util.List; + +public class ClassWrapperNode { + + private StructClass classStruct; + + private ClassWrapperNode superclass; + + private List<ClassWrapperNode> subclasses = new ArrayList<ClassWrapperNode>(); + + public ClassWrapperNode(StructClass cl) { + this.classStruct = cl; + } + + public void addSubclass(ClassWrapperNode node) { + node.setSuperclass(this); + subclasses.add(node); + } + + public StructClass getClassStruct() { + return classStruct; + } + + public List<ClassWrapperNode> getSubclasses() { + return subclasses; + } + + public ClassWrapperNode getSuperclass() { + return superclass; + } + + public void setSuperclass(ClassWrapperNode superclass) { + this.superclass = superclass; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/ConverterHelper.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/ConverterHelper.java new file mode 100644 index 000000000000..f2cb1ec0e657 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/ConverterHelper.java @@ -0,0 +1,143 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.renamer; + +import org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer; + +import java.util.HashSet; + +public class ConverterHelper implements IIdentifierRenamer { + + private static HashSet<String> setReserved = new HashSet<String>(); + + static { + setReserved.add("abstract"); + setReserved.add("do"); + setReserved.add("if"); + setReserved.add("package"); + setReserved.add("synchronized"); + setReserved.add("boolean"); + setReserved.add("double"); + setReserved.add("implements"); + setReserved.add("private"); + setReserved.add("this"); + setReserved.add("break"); + setReserved.add("else"); + setReserved.add("import"); + setReserved.add("protected"); + setReserved.add("throw"); + setReserved.add("byte"); + setReserved.add("extends"); + setReserved.add("instanceof"); + setReserved.add("public"); + setReserved.add("throws"); + setReserved.add("case"); + setReserved.add("false"); + setReserved.add("int"); + setReserved.add("return"); + setReserved.add("transient"); + setReserved.add("catch"); + setReserved.add("final"); + setReserved.add("interface"); + setReserved.add("short"); + setReserved.add("true"); + setReserved.add("char"); + setReserved.add("finally"); + setReserved.add("long"); + setReserved.add("static"); + setReserved.add("try"); + setReserved.add("class"); + setReserved.add("float"); + setReserved.add("native"); + setReserved.add("strictfp"); + setReserved.add("void"); + setReserved.add("const"); + setReserved.add("for"); + setReserved.add("new"); + setReserved.add("super"); + setReserved.add("volatile"); + setReserved.add("continue"); + setReserved.add("goto"); + setReserved.add("null"); + setReserved.add("switch"); + setReserved.add("while"); + setReserved.add("default"); + setReserved.add("assert"); + setReserved.add("enum"); + } + + private int class_counter = 0; + + private int field_counter = 0; + + private int method_counter = 0; + + private HashSet<String> setNonStandardClassNames = new HashSet<String>(); + + public boolean toBeRenamed(int element_type, String classname, String element, String descriptor) { + String value = (element_type == IIdentifierRenamer.ELEMENT_CLASS) ? classname : element; + return value == null || value.length() == 0 || value.length() <= 2 || setReserved.contains(value) || Character.isDigit(value.charAt(0)); + } + + // TODO: consider possible conflicts with not renamed classes, fields and methods! + // We should get all relevant information here. + public String getNextClassname(String fullname, String shortname) { + + if (shortname == null) { + return "class_" + (class_counter++); + } + + int index = 0; + while (Character.isDigit(shortname.charAt(index))) { + index++; + } + + if (index == 0 || index == shortname.length()) { + return "class_" + (class_counter++); + } + else { + String name = shortname.substring(index); + + if (setNonStandardClassNames.contains(name)) { + return "Inner" + name + "_" + (class_counter++); + } + else { + setNonStandardClassNames.add(name); + return "Inner" + name; + } + } + } + + public String getNextFieldname(String classname, String field, String descriptor) { + return "field_" + (field_counter++); + } + + public String getNextMethodname(String classname, String method, String descriptor) { + return "method_" + (method_counter++); + } + + // ***************************************************************************** + // static methods + // ***************************************************************************** + + public static String getSimpleClassName(String fullname) { + return fullname.substring(fullname.lastIndexOf('/') + 1); + } + + public static String replaceSimpleClassName(String fullname, String newname) { + return fullname.substring(0, fullname.lastIndexOf('/') + 1) + newname; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/IdentifierConverter.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/IdentifierConverter.java new file mode 100644 index 000000000000..9ed3578d3d55 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/IdentifierConverter.java @@ -0,0 +1,463 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.renamer; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; +import org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer; +import org.jetbrains.java.decompiler.struct.StructClass; +import org.jetbrains.java.decompiler.struct.StructContext; +import org.jetbrains.java.decompiler.struct.StructField; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.io.IOException; +import java.util.*; + +public class IdentifierConverter { + + private StructContext context; + + private IIdentifierRenamer helper; + + private PoolInterceptor interceptor; + + private List<ClassWrapperNode> rootClasses = new ArrayList<ClassWrapperNode>(); + + private List<ClassWrapperNode> rootInterfaces = new ArrayList<ClassWrapperNode>(); + + private HashMap<String, HashMap<String, String>> interfaceNameMaps = new HashMap<String, HashMap<String, String>>(); + + public void rename(StructContext context) { + + try { + this.context = context; + + String user_class = (String)DecompilerContext.getProperty(IFernflowerPreferences.USER_RENAMER_CLASS); + if (user_class != null) { + try { + helper = (IIdentifierRenamer)IdentifierConverter.class.getClassLoader().loadClass(user_class).newInstance(); + } + catch (Exception ex) { + // ignore errors + } + } + + if (helper == null) { + helper = new ConverterHelper(); + } + + interceptor = new PoolInterceptor(helper); + + buildInheritanceTree(); + + renameAllClasses(); + + renameInterfaces(); + + renameClasses(); + + DecompilerContext.setPoolInterceptor(interceptor); + context.reloadContext(); + } + catch (IOException ex) { + throw new RuntimeException("Renaming failed!"); + } + } + + private void renameClasses() { + + List<ClassWrapperNode> lstClasses = getReversePostOrderListIterative(rootClasses); + + HashMap<String, HashMap<String, String>> classNameMaps = new HashMap<String, HashMap<String, String>>(); + + for (ClassWrapperNode node : lstClasses) { + + StructClass cl = node.getClassStruct(); + HashMap<String, String> names = new HashMap<String, String>(); + + // merge informations on super class + if (cl.superClass != null) { + HashMap<String, String> mapClass = classNameMaps.get(cl.superClass.getString()); + if (mapClass != null) { + names.putAll(mapClass); + } + } + + // merge informations on interfaces + for (String intrName : cl.getInterfaceNames()) { + HashMap<String, String> mapInt = interfaceNameMaps.get(intrName); + if (mapInt != null) { + names.putAll(mapInt); + } + else { + StructClass clintr = context.getClass(intrName); + if (clintr != null) { + names.putAll(processExternalInterface(clintr)); + } + } + } + + renameClassIdentifiers(cl, names); + + if (!node.getSubclasses().isEmpty()) { + classNameMaps.put(cl.qualifiedName, names); + } + } + } + + private HashMap<String, String> processExternalInterface(StructClass cl) { + + HashMap<String, String> names = new HashMap<String, String>(); + + for (String intrName : cl.getInterfaceNames()) { + + HashMap<String, String> mapInt = interfaceNameMaps.get(intrName); + if (mapInt != null) { + names.putAll(mapInt); + } + else { + StructClass clintr = context.getClass(intrName); + if (clintr != null) { + names.putAll(processExternalInterface(clintr)); + } + } + } + + renameClassIdentifiers(cl, names); + + return names; + } + + private void renameInterfaces() { + + List<ClassWrapperNode> lstInterfaces = getReversePostOrderListIterative(rootInterfaces); + + HashMap<String, HashMap<String, String>> interfaceNameMaps = new HashMap<String, HashMap<String, String>>(); + + // rename methods and fields + for (ClassWrapperNode node : lstInterfaces) { + + StructClass cl = node.getClassStruct(); + HashMap<String, String> names = new HashMap<String, String>(); + + // merge informations on super interfaces + for (String intrName : cl.getInterfaceNames()) { + HashMap<String, String> mapInt = interfaceNameMaps.get(intrName); + if (mapInt != null) { + names.putAll(mapInt); + } + } + + renameClassIdentifiers(cl, names); + + interfaceNameMaps.put(cl.qualifiedName, names); + } + + this.interfaceNameMaps = interfaceNameMaps; + } + + private void renameAllClasses() { + + // order not important + List<ClassWrapperNode> lstAllClasses = new ArrayList<ClassWrapperNode>(getReversePostOrderListIterative(rootInterfaces)); + lstAllClasses.addAll(getReversePostOrderListIterative(rootClasses)); + + // rename all interfaces and classes + for (ClassWrapperNode node : lstAllClasses) { + renameClass(node.getClassStruct()); + } + } + + private void renameClass(StructClass cl) { + + if (!cl.isOwn()) { + return; + } + + String classOldFullName = cl.qualifiedName; + + // TODO: rename packages + String clsimplename = ConverterHelper.getSimpleClassName(classOldFullName); + if (helper.toBeRenamed(IIdentifierRenamer.ELEMENT_CLASS, clsimplename, null, null)) { + String classNewFullName; + + do { + classNewFullName = ConverterHelper.replaceSimpleClassName(classOldFullName, + helper.getNextClassname(classOldFullName, ConverterHelper + .getSimpleClassName(classOldFullName))); + } + while (context.getClasses().containsKey(classNewFullName)); + + interceptor.addName(classOldFullName, classNewFullName); + } + } + + private void renameClassIdentifiers(StructClass cl, HashMap<String, String> names) { + + // all classes are already renamed + String classOldFullName = cl.qualifiedName; + String classNewFullName = interceptor.getName(classOldFullName); + + if (classNewFullName == null) { + classNewFullName = classOldFullName; + } + + // methods + HashSet<String> setMethodNames = new HashSet<String>(); + for (StructMethod md : cl.getMethods()) { + setMethodNames.add(md.getName()); + } + + VBStyleCollection<StructMethod, String> methods = cl.getMethods(); + for (int i = 0; i < methods.size(); i++) { + + StructMethod mt = methods.get(i); + String key = methods.getKey(i); + + boolean isPrivate = mt.hasModifier(CodeConstants.ACC_PRIVATE); + + String name = mt.getName(); + if (!cl.isOwn() || mt.hasModifier(CodeConstants.ACC_NATIVE)) { + // external and native methods must not be renamed + if (!isPrivate) { + names.put(key, name); + } + } + else if (helper.toBeRenamed(IIdentifierRenamer.ELEMENT_METHOD, classOldFullName, name, mt.getDescriptor())) { + if (isPrivate || !names.containsKey(key)) { + do { + name = helper.getNextMethodname(classOldFullName, name, mt.getDescriptor()); + } + while (setMethodNames.contains(name)); + + if (!isPrivate) { + names.put(key, name); + } + } + else { + name = names.get(key); + } + + interceptor.addName(classOldFullName + " " + mt.getName() + " " + mt.getDescriptor(), + classNewFullName + " " + name + " " + buildNewDescriptor(false, mt.getDescriptor())); + } + } + + // external fields are not being renamed + if (!cl.isOwn()) { + return; + } + + // fields + // FIXME: should overloaded fields become the same name? + HashSet<String> setFieldNames = new HashSet<String>(); + for (StructField fd : cl.getFields()) { + setFieldNames.add(fd.getName()); + } + + for (StructField fd : cl.getFields()) { + if (helper.toBeRenamed(IIdentifierRenamer.ELEMENT_FIELD, classOldFullName, fd.getName(), fd.getDescriptor())) { + String newname; + + do { + newname = helper.getNextFieldname(classOldFullName, fd.getName(), fd.getDescriptor()); + } + while (setFieldNames.contains(newname)); + + interceptor.addName(classOldFullName + " " + fd.getName() + " " + fd.getDescriptor(), + classNewFullName + " " + newname + " " + buildNewDescriptor(true, fd.getDescriptor())); + } + } + } + + private String buildNewDescriptor(boolean isField, String descriptor) { + + boolean updated = false; + + if (isField) { + FieldDescriptor fd = FieldDescriptor.parseDescriptor(descriptor); + + VarType ftype = fd.type; + if (ftype.type == CodeConstants.TYPE_OBJECT) { + String newclname = interceptor.getName(ftype.value); + if (newclname != null) { + ftype.value = newclname; + updated = true; + } + } + + if (updated) { + return fd.getDescriptor(); + } + } + else { + + MethodDescriptor md = MethodDescriptor.parseDescriptor(descriptor); + // params + for (VarType partype : md.params) { + if (partype.type == CodeConstants.TYPE_OBJECT) { + String newclname = interceptor.getName(partype.value); + if (newclname != null) { + partype.value = newclname; + updated = true; + } + } + } + + // return value + if (md.ret.type == CodeConstants.TYPE_OBJECT) { + String newclname = interceptor.getName(md.ret.value); + if (newclname != null) { + md.ret.value = newclname; + updated = true; + } + } + + if (updated) { + return md.getDescriptor(); + } + } + + return descriptor; + } + + private static List<ClassWrapperNode> getReversePostOrderListIterative(List<ClassWrapperNode> roots) { + + List<ClassWrapperNode> res = new ArrayList<ClassWrapperNode>(); + + LinkedList<ClassWrapperNode> stackNode = new LinkedList<ClassWrapperNode>(); + LinkedList<Integer> stackIndex = new LinkedList<Integer>(); + + HashSet<ClassWrapperNode> setVisited = new HashSet<ClassWrapperNode>(); + + for (ClassWrapperNode root : roots) { + stackNode.add(root); + stackIndex.add(0); + } + + while (!stackNode.isEmpty()) { + + ClassWrapperNode node = stackNode.getLast(); + int index = stackIndex.removeLast(); + + setVisited.add(node); + + List<ClassWrapperNode> lstSubs = node.getSubclasses(); + + for (; index < lstSubs.size(); index++) { + ClassWrapperNode sub = lstSubs.get(index); + if (!setVisited.contains(sub)) { + stackIndex.add(index + 1); + + stackNode.add(sub); + stackIndex.add(0); + + break; + } + } + + if (index == lstSubs.size()) { + res.add(0, node); + + stackNode.removeLast(); + } + } + + return res; + } + + + private void buildInheritanceTree() { + + Map<String, ClassWrapperNode> nodes = new HashMap<String, ClassWrapperNode>(); + Map<String, StructClass> classes = context.getClasses(); + + List<ClassWrapperNode> rootClasses = new ArrayList<ClassWrapperNode>(); + List<ClassWrapperNode> rootInterfaces = new ArrayList<ClassWrapperNode>(); + + for (StructClass cl : classes.values()) { + + if (!cl.isOwn()) { + continue; + } + + LinkedList<StructClass> stack = new LinkedList<StructClass>(); + LinkedList<ClassWrapperNode> stackSubnodes = new LinkedList<ClassWrapperNode>(); + + stack.add(cl); + stackSubnodes.add(null); + + while (!stack.isEmpty()) { + + StructClass clstr = stack.removeFirst(); + ClassWrapperNode child = stackSubnodes.removeFirst(); + + ClassWrapperNode node = nodes.get(clstr.qualifiedName); + boolean isNewNode = (node == null); + + if (isNewNode) { + nodes.put(clstr.qualifiedName, node = new ClassWrapperNode(clstr)); + } + + if (child != null) { + node.addSubclass(child); + } + + if (!isNewNode) { + break; + } + else { + boolean isInterface = clstr.hasModifier(CodeConstants.ACC_INTERFACE); + boolean found_parent = false; + + if (isInterface) { + for (String intrName : clstr.getInterfaceNames()) { + StructClass clparent = classes.get(intrName); + if (clparent != null) { + stack.add(clparent); + stackSubnodes.add(node); + found_parent = true; + } + } + } + else { + if (clstr.superClass != null) { // null iff java/lang/Object + StructClass clparent = classes.get(clstr.superClass.getString()); + + if (clparent != null) { + stack.add(clparent); + stackSubnodes.add(node); + found_parent = true; + } + } + } + + if (!found_parent) { // no super class or interface + (isInterface ? rootInterfaces : rootClasses).add(node); + } + } + } + } + + this.rootClasses = rootClasses; + this.rootInterfaces = rootInterfaces; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/PoolInterceptor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/PoolInterceptor.java new file mode 100644 index 000000000000..74e2ed8e6fd3 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/renamer/PoolInterceptor.java @@ -0,0 +1,50 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.modules.renamer; + +import org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer; + +import java.util.HashMap; + +public class PoolInterceptor { + + private IIdentifierRenamer helper; + + private HashMap<String, String> mapOldToNewNames = new HashMap<String, String>(); + + private HashMap<String, String> mapNewToOldNames = new HashMap<String, String>(); + + public PoolInterceptor(IIdentifierRenamer helper) { + this.helper = helper; + } + + public void addName(String oldName, String newName) { + mapOldToNewNames.put(oldName, newName); + mapNewToOldNames.put(newName, oldName); + } + + public String getName(String oldName) { + return mapOldToNewNames.get(oldName); + } + + public String getOldName(String newName) { + return mapNewToOldNames.get(newName); + } + + public IIdentifierRenamer getHelper() { + return helper; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/ContextUnit.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/ContextUnit.java new file mode 100644 index 000000000000..819ae6446d07 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/ContextUnit.java @@ -0,0 +1,165 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct; + +import org.jetbrains.java.decompiler.main.extern.IResultSaver; +import org.jetbrains.java.decompiler.struct.lazy.LazyLoader; +import org.jetbrains.java.decompiler.struct.lazy.LazyLoader.Link; +import org.jetbrains.java.decompiler.util.DataInputFullStream; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +public class ContextUnit { + + public static final int TYPE_FOLDER = 0; + public static final int TYPE_JAR = 1; + public static final int TYPE_ZIP = 2; + + private final int type; + private final boolean own; + + private final String archivePath; // relative path to jar/zip + private final String filename; // folder: relative path, archive: file name + private final IResultSaver resultSaver; + private final IDecompiledData decompiledData; + + private final List<String> classEntries = new ArrayList<String>(); // class file or jar/zip entry + private final List<String> dirEntries = new ArrayList<String>(); + private final List<String[]> otherEntries = new ArrayList<String[]>(); + + private List<StructClass> classes = new ArrayList<StructClass>(); + private Manifest manifest; + + public ContextUnit(int type, String archivePath, String filename, boolean own, IResultSaver resultSaver, IDecompiledData decompiledData) { + this.type = type; + this.own = own; + this.archivePath = archivePath; + this.filename = filename; + this.resultSaver = resultSaver; + this.decompiledData = decompiledData; + } + + public void addClass(StructClass cl, String entryName) { + classes.add(cl); + classEntries.add(entryName); + } + + public void addDirEntry(String entry) { + dirEntries.add(entry); + } + + public void addOtherEntry(String fullPath, String entry) { + otherEntries.add(new String[]{fullPath, entry}); + } + + public void reload(LazyLoader loader) throws IOException { + List<StructClass> lstClasses = new ArrayList<StructClass>(); + + for (StructClass cl : classes) { + String oldName = cl.qualifiedName; + + StructClass newCl; + DataInputFullStream in = loader.getClassStream(oldName); + try { + newCl = new StructClass(in, cl.isOwn(), loader); + } + finally { + in.close(); + } + + lstClasses.add(newCl); + + Link lnk = loader.getClassLink(oldName); + loader.removeClassLink(oldName); + loader.addClassLink(newCl.qualifiedName, lnk); + } + + classes = lstClasses; + } + + public void save() { + switch (type) { + case TYPE_FOLDER: + // create folder + resultSaver.saveFolder(filename); + + // non-class files + for (String[] pair : otherEntries) { + resultSaver.copyFile(pair[0], filename, pair[1]); + } + + // classes + for (int i = 0; i < classes.size(); i++) { + StructClass cl = classes.get(i); + String entryName = decompiledData.getClassEntryName(cl, classEntries.get(i)); + if (entryName != null) { + String content = decompiledData.getClassContent(cl); + if (content != null) { + resultSaver.saveClassFile(filename, cl.qualifiedName, entryName, content); + } + } + } + + break; + + case TYPE_JAR: + case TYPE_ZIP: + // create archive file + resultSaver.saveFolder(archivePath); + resultSaver.createArchive(archivePath, filename, manifest); + + // directory entries + for (String dirEntry : dirEntries) { + resultSaver.saveDirEntry(archivePath, filename, dirEntry); + } + + // non-class entries + for (String[] pair : otherEntries) { + if (type != TYPE_JAR || !JarFile.MANIFEST_NAME.equalsIgnoreCase(pair[1])) { + resultSaver.copyEntry(pair[0], archivePath, filename, pair[1]); + } + } + + // classes + for (int i = 0; i < classes.size(); i++) { + StructClass cl = classes.get(i); + String entryName = decompiledData.getClassEntryName(cl, classEntries.get(i)); + if (entryName != null) { + String content = decompiledData.getClassContent(cl); + resultSaver.saveClassEntry(archivePath, filename, cl.qualifiedName, entryName, content); + } + } + + resultSaver.closeArchive(archivePath, filename); + } + } + + public void setManifest(Manifest manifest) { + this.manifest = manifest; + } + + public boolean isOwn() { + return own; + } + + public List<StructClass> getClasses() { + return classes; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/IDecompiledData.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/IDecompiledData.java new file mode 100644 index 000000000000..f309b0e17bc9 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/IDecompiledData.java @@ -0,0 +1,23 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct; + +public interface IDecompiledData { + + String getClassEntryName(StructClass cl, String entryname); + + String getClassContent(StructClass cl); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructClass.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructClass.java new file mode 100644 index 000000000000..cb24ff65db63 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructClass.java @@ -0,0 +1,195 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.struct.consts.PrimitiveConstant; +import org.jetbrains.java.decompiler.struct.lazy.LazyLoader; +import org.jetbrains.java.decompiler.util.DataInputFullStream; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.io.IOException; + +/* + class_file { + u4 magic; + u2 minor_version; + u2 major_version; + u2 constant_pool_count; + cp_info constant_pool[constant_pool_count-1]; + u2 access_flags; + u2 this_class; + u2 super_class; + u2 interfaces_count; + u2 interfaces[interfaces_count]; + u2 fields_count; + field_info fields[fields_count]; + u2 methods_count; + method_info methods[methods_count]; + u2 attributes_count; + attribute_info attributes[attributes_count]; + } +*/ +public class StructClass extends StructMember { + + public final String qualifiedName; + public final PrimitiveConstant superClass; + + private final boolean own; + private final LazyLoader loader; + private final int minorVersion; + private final int majorVersion; + private final int[] interfaces; + private final String[] interfaceNames; + private final VBStyleCollection<StructField, String> fields; + private final VBStyleCollection<StructMethod, String> methods; + + private ConstantPool pool; + + public StructClass(byte[] bytes, boolean own, LazyLoader loader) throws IOException { + this(new DataInputFullStream(bytes), own, loader); + } + + public StructClass(DataInputFullStream in, boolean own, LazyLoader loader) throws IOException { + this.own = own; + this.loader = loader; + + in.discard(4); + + minorVersion = in.readUnsignedShort(); + majorVersion = in.readUnsignedShort(); + + pool = new ConstantPool(in); + + accessFlags = in.readUnsignedShort(); + int thisClassIdx = in.readUnsignedShort(); + int superClassIdx = in.readUnsignedShort(); + qualifiedName = pool.getPrimitiveConstant(thisClassIdx).getString(); + superClass = pool.getPrimitiveConstant(superClassIdx); + + // interfaces + int length = in.readUnsignedShort(); + interfaces = new int[length]; + interfaceNames = new String[length]; + for (int i = 0; i < length; i++) { + interfaces[i] = in.readUnsignedShort(); + interfaceNames[i] = pool.getPrimitiveConstant(interfaces[i]).getString(); + } + + // fields + length = in.readUnsignedShort(); + fields = new VBStyleCollection<StructField, String>(); + for (int i = 0; i < length; i++) { + StructField field = new StructField(in, this); + fields.addWithKey(field, InterpreterUtil.makeUniqueKey(field.getName(), field.getDescriptor())); + } + + // methods + length = in.readUnsignedShort(); + methods = new VBStyleCollection<StructMethod, String>(); + for (int i = 0; i < length; i++) { + StructMethod method = new StructMethod(in, this); + methods.addWithKey(method, InterpreterUtil.makeUniqueKey(method.getName(), method.getDescriptor())); + } + + // attributes + attributes = readAttributes(in, pool); + + releaseResources(); + } + + public boolean hasField(String name, String descriptor) { + return getField(name, descriptor) != null; + } + + public StructField getField(String name, String descriptor) { + return fields.getWithKey(InterpreterUtil.makeUniqueKey(name, descriptor)); + } + + public StructMethod getMethod(String key) { + return methods.getWithKey(key); + } + + public StructMethod getMethod(String name, String descriptor) { + return methods.getWithKey(InterpreterUtil.makeUniqueKey(name, descriptor)); + } + + public String getInterface(int i) { + return interfaceNames[i]; + } + + public void releaseResources() { + if (loader != null) { + pool = null; + } + } + + public ConstantPool getPool() { + if (pool == null && loader != null) { + pool = loader.loadPool(qualifiedName); + } + return pool; + } + + public int[] getInterfaces() { + return interfaces; + } + + public String[] getInterfaceNames() { + return interfaceNames; + } + + public VBStyleCollection<StructMethod, String> getMethods() { + return methods; + } + + public VBStyleCollection<StructField, String> getFields() { + return fields; + } + + public boolean isOwn() { + return own; + } + + public LazyLoader getLoader() { + return loader; + } + + public boolean isVersionGE_1_5() { + return (majorVersion > 48 || (majorVersion == 48 && minorVersion > 0)); // FIXME: check second condition + } + + public boolean isVersionGE_1_7() { + return (majorVersion >= 51); + } + + public int getBytecodeVersion() { + switch (majorVersion) { + case 52: + return CodeConstants.BYTECODE_JAVA_8; + case 51: + return CodeConstants.BYTECODE_JAVA_7; + case 50: + return CodeConstants.BYTECODE_JAVA_6; + case 49: + return CodeConstants.BYTECODE_JAVA_5; + } + + return CodeConstants.BYTECODE_JAVA_LE_4; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructContext.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructContext.java new file mode 100644 index 000000000000..7bfb139ede30 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructContext.java @@ -0,0 +1,189 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IResultSaver; +import org.jetbrains.java.decompiler.struct.lazy.LazyLoader; +import org.jetbrains.java.decompiler.util.DataInputFullStream; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +import java.io.File; +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.jar.JarFile; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +public class StructContext { + + private final IResultSaver saver; + private final IDecompiledData decompiledData; + private final LazyLoader loader; + private final Map<String, ContextUnit> units = new HashMap<String, ContextUnit>(); + private final Map<String, StructClass> classes = new HashMap<String, StructClass>(); + + public StructContext(IResultSaver saver, IDecompiledData decompiledData, LazyLoader loader) { + this.saver = saver; + this.decompiledData = decompiledData; + this.loader = loader; + + ContextUnit defaultUnit = new ContextUnit(ContextUnit.TYPE_FOLDER, null, "", true, saver, decompiledData); + units.put("", defaultUnit); + } + + public StructClass getClass(String name) { + return classes.get(name); + } + + public void reloadContext() throws IOException { + for (ContextUnit unit : units.values()) { + for (StructClass cl : unit.getClasses()) { + classes.remove(cl.qualifiedName); + } + + unit.reload(loader); + + // adjust global class collection + for (StructClass cl : unit.getClasses()) { + classes.put(cl.qualifiedName, cl); + } + } + } + + public void saveContext() { + for (ContextUnit unit : units.values()) { + if (unit.isOwn()) { + unit.save(); + } + } + } + + public void addSpace(File file, boolean isOwn) { + addSpace("", file, isOwn, 0); + } + + private void addSpace(String path, File file, boolean isOwn, int level) { + if (file.isDirectory()) { + if (level == 1) path += file.getName(); + else if (level > 1) path += "/" + file.getName(); + + File[] files = file.listFiles(); + if (files != null) { + for (int i = files.length - 1; i >= 0; i--) { + addSpace(path, files[i], isOwn, level + 1); + } + } + } + else { + String filename = file.getName(); + + boolean isArchive = false; + try { + if (filename.endsWith(".jar")) { + isArchive = true; + addArchive(path, file, ContextUnit.TYPE_JAR, isOwn); + } + else if (filename.endsWith(".zip")) { + isArchive = true; + addArchive(path, file, ContextUnit.TYPE_ZIP, isOwn); + } + } + catch (IOException ex) { + String message = "Corrupted archive file: " + file; + DecompilerContext.getLogger().writeMessage(message, ex); + } + if (isArchive) { + return; + } + + ContextUnit unit = units.get(path); + if (unit == null) { + unit = new ContextUnit(ContextUnit.TYPE_FOLDER, null, path, isOwn, saver, decompiledData); + units.put(path, unit); + } + + if (filename.endsWith(".class")) { + try { + DataInputFullStream in = loader.getClassStream(file.getAbsolutePath(), null); + try { + StructClass cl = new StructClass(in, isOwn, loader); + classes.put(cl.qualifiedName, cl); + unit.addClass(cl, filename); + loader.addClassLink(cl.qualifiedName, new LazyLoader.Link(LazyLoader.Link.CLASS, file.getAbsolutePath(), null)); + } + finally { + in.close(); + } + } + catch (IOException ex) { + String message = "Corrupted class file: " + file; + DecompilerContext.getLogger().writeMessage(message, ex); + } + } + else { + unit.addOtherEntry(file.getAbsolutePath(), filename); + } + } + } + + private void addArchive(String path, File file, int type, boolean isOwn) throws IOException { + @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") + ZipFile archive = type == ContextUnit.TYPE_JAR ? new JarFile(file) : new ZipFile(file); + + try { + Enumeration<? extends ZipEntry> entries = archive.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + + ContextUnit unit = units.get(path + "/" + file.getName()); + if (unit == null) { + unit = new ContextUnit(type, path, file.getName(), isOwn, saver, decompiledData); + if (type == ContextUnit.TYPE_JAR) { + unit.setManifest(((JarFile)archive).getManifest()); + } + units.put(path + "/" + file.getName(), unit); + } + + String name = entry.getName(); + if (!entry.isDirectory()) { + if (name.endsWith(".class")) { + byte[] bytes = InterpreterUtil.getBytes(archive, entry); + StructClass cl = new StructClass(bytes, isOwn, loader); + classes.put(cl.qualifiedName, cl); + unit.addClass(cl, name); + loader.addClassLink(cl.qualifiedName, new LazyLoader.Link(LazyLoader.Link.ENTRY, file.getAbsolutePath(), name)); + } + else { + unit.addOtherEntry(file.getAbsolutePath(), name); + } + } + else { + unit.addDirEntry(name); + } + } + } + finally { + archive.close(); + } + } + + public Map<String, StructClass> getClasses() { + return classes; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructField.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructField.java new file mode 100644 index 000000000000..796d77f1c9a3 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructField.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.util.DataInputFullStream; + +import java.io.IOException; + +/* + field_info { + u2 access_flags; + u2 name_index; + u2 descriptor_index; + u2 attributes_count; + attribute_info attributes[attributes_count]; + } +*/ +public class StructField extends StructMember { + + private final String name; + private final String descriptor; + + + public StructField(DataInputFullStream in, StructClass clStruct) throws IOException { + accessFlags = in.readUnsignedShort(); + int nameIndex = in.readUnsignedShort(); + int descriptorIndex = in.readUnsignedShort(); + + ConstantPool pool = clStruct.getPool(); + String[] values = pool.getClassElement(ConstantPool.FIELD, clStruct.qualifiedName, nameIndex, descriptorIndex); + name = values[0]; + descriptor = values[1]; + + attributes = readAttributes(in, pool); + } + + public String getName() { + return name; + } + + public String getDescriptor() { + return descriptor; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructMember.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructMember.java new file mode 100644 index 000000000000..f681e19604b3 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructMember.java @@ -0,0 +1,87 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; +import org.jetbrains.java.decompiler.struct.attr.StructLocalVariableTableAttribute; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.util.DataInputFullStream; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.io.IOException; + +public class StructMember { + + protected int accessFlags; + protected VBStyleCollection<StructGeneralAttribute, String> attributes; + + + public int getAccessFlags() { + return accessFlags; + } + + public VBStyleCollection<StructGeneralAttribute, String> getAttributes() { + return attributes; + } + + public boolean hasModifier(int modifier) { + return (accessFlags & modifier) == modifier; + } + + public boolean isSynthetic() { + return hasModifier(CodeConstants.ACC_SYNTHETIC) || attributes.containsKey(StructGeneralAttribute.ATTRIBUTE_SYNTHETIC); + } + + protected VBStyleCollection<StructGeneralAttribute, String> readAttributes(DataInputFullStream in, ConstantPool pool) throws IOException { + VBStyleCollection<StructGeneralAttribute, String> attributes = new VBStyleCollection<StructGeneralAttribute, String>(); + + int length = in.readUnsignedShort(); + for (int i = 0; i < length; i++) { + int nameIndex = in.readUnsignedShort(); + String name = pool.getPrimitiveConstant(nameIndex).getString(); + + StructGeneralAttribute attribute = readAttribute(in, pool, name); + + if (attribute != null) { + if (StructGeneralAttribute.ATTRIBUTE_LOCAL_VARIABLE_TABLE.equals(name) && attributes.containsKey(name)) { + // merge all variable tables + StructLocalVariableTableAttribute table = (StructLocalVariableTableAttribute)attributes.getWithKey(name); + table.addLocalVariableTable((StructLocalVariableTableAttribute)attribute); + } + else { + attributes.addWithKey(attribute, attribute.getName()); + } + } + } + + return attributes; + } + + protected StructGeneralAttribute readAttribute(DataInputFullStream in, ConstantPool pool, String name) throws IOException { + StructGeneralAttribute attribute = StructGeneralAttribute.createAttribute(name); + if (attribute == null) { + in.discard(in.readInt()); + } + else { + byte[] data = new byte[in.readInt()]; + in.readFull(data); + attribute.setInfo(data); + attribute.initContent(pool); + } + return attribute; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructMethod.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructMethod.java new file mode 100644 index 000000000000..2b5249f59d5a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/StructMethod.java @@ -0,0 +1,392 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct; + +import org.jetbrains.java.decompiler.code.*; +import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.util.DataInputFullStream; +import org.jetbrains.java.decompiler.util.VBStyleCollection; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.jetbrains.java.decompiler.code.CodeConstants.*; + +/* + method_info { + u2 access_flags; + u2 name_index; + u2 descriptor_index; + u2 attributes_count; + attribute_info attributes[attributes_count]; + } +*/ +public class StructMethod extends StructMember { + + private static final int[] opr_iconst = {-1, 0, 1, 2, 3, 4, 5}; + private static final int[] opr_loadstore = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3}; + private static final int[] opcs_load = {opc_iload, opc_lload, opc_fload, opc_dload, opc_aload}; + private static final int[] opcs_store = {opc_istore, opc_lstore, opc_fstore, opc_dstore, opc_astore}; + + private final StructClass classStruct; + private final String name; + private final String descriptor; + + private boolean containsCode = false; + private int localVariables = 0; + private int codeLength = 0; + private int codeFullLength = 0; + private InstructionSequence seq; + private boolean expanded = false; + private VBStyleCollection<StructGeneralAttribute, String> codeAttributes; + + public StructMethod(DataInputFullStream in, StructClass clStruct) throws IOException { + classStruct = clStruct; + + accessFlags = in.readUnsignedShort(); + int nameIndex = in.readUnsignedShort(); + int descriptorIndex = in.readUnsignedShort(); + + ConstantPool pool = clStruct.getPool(); + String[] values = pool.getClassElement(ConstantPool.METHOD, clStruct.qualifiedName, nameIndex, descriptorIndex); + name = values[0]; + descriptor = values[1]; + + attributes = readAttributes(in, pool); + if (codeAttributes != null) { + attributes.addAllWithKey(codeAttributes); + codeAttributes = null; + } + } + + @Override + protected StructGeneralAttribute readAttribute(DataInputFullStream in, ConstantPool pool, String name) throws IOException { + if (StructGeneralAttribute.ATTRIBUTE_CODE.equals(name)) { + if (!classStruct.isOwn()) { + // skip code in foreign classes + in.discard(8); + in.discard(in.readInt()); + in.discard(8 * in.readUnsignedShort()); + } + else { + containsCode = true; + in.discard(6); + localVariables = in.readUnsignedShort(); + codeLength = in.readInt(); + in.discard(codeLength); + int excLength = in.readUnsignedShort(); + in.discard(excLength * 8); + codeFullLength = codeLength + excLength * 8 + 2; + } + + codeAttributes = readAttributes(in, pool); + + return null; + } + + return super.readAttribute(in, pool, name); + } + + public void expandData() throws IOException { + if (containsCode && !expanded) { + byte[] code = classStruct.getLoader().loadBytecode(this, codeFullLength); + seq = parseBytecode(new DataInputFullStream(code), codeLength, classStruct.getPool()); + expanded = true; + } + } + + public void releaseResources() throws IOException { + if (containsCode && expanded) { + seq = null; + expanded = false; + } + } + + @SuppressWarnings("AssignmentToForLoopParameter") + private InstructionSequence parseBytecode(DataInputFullStream in, int length, ConstantPool pool) throws IOException { + VBStyleCollection<Instruction, Integer> instructions = new VBStyleCollection<Instruction, Integer>(); + + int bytecode_version = classStruct.getBytecodeVersion(); + + for (int i = 0; i < length; ) { + + int offset = i; + + int opcode = in.readUnsignedByte(); + int group = GROUP_GENERAL; + + boolean wide = (opcode == opc_wide); + + if (wide) { + i++; + opcode = in.readUnsignedByte(); + } + + List<Integer> operands = new ArrayList<Integer>(); + + if (opcode >= opc_iconst_m1 && opcode <= opc_iconst_5) { + operands.add(new Integer(opr_iconst[opcode - opc_iconst_m1])); + opcode = opc_bipush; + } + else if (opcode >= opc_iload_0 && opcode <= opc_aload_3) { + operands.add(new Integer(opr_loadstore[opcode - opc_iload_0])); + opcode = opcs_load[(opcode - opc_iload_0) / 4]; + } + else if (opcode >= opc_istore_0 && opcode <= opc_astore_3) { + operands.add(new Integer(opr_loadstore[opcode - opc_istore_0])); + opcode = opcs_store[(opcode - opc_istore_0) / 4]; + } + else { + switch (opcode) { + case opc_bipush: + operands.add(new Integer(in.readByte())); + i++; + break; + case opc_ldc: + case opc_newarray: + operands.add(new Integer(in.readUnsignedByte())); + i++; + break; + case opc_sipush: + case opc_ifeq: + case opc_ifne: + case opc_iflt: + case opc_ifge: + case opc_ifgt: + case opc_ifle: + case opc_if_icmpeq: + case opc_if_icmpne: + case opc_if_icmplt: + case opc_if_icmpge: + case opc_if_icmpgt: + case opc_if_icmple: + case opc_if_acmpeq: + case opc_if_acmpne: + case opc_goto: + case opc_jsr: + case opc_ifnull: + case opc_ifnonnull: + if (opcode != opc_sipush) { + group = GROUP_JUMP; + } + operands.add(new Integer(in.readShort())); + i += 2; + break; + case opc_ldc_w: + case opc_ldc2_w: + case opc_getstatic: + case opc_putstatic: + case opc_getfield: + case opc_putfield: + case opc_invokevirtual: + case opc_invokespecial: + case opc_invokestatic: + case opc_new: + case opc_anewarray: + case opc_checkcast: + case opc_instanceof: + operands.add(new Integer(in.readUnsignedShort())); + i += 2; + if (opcode >= opc_getstatic && opcode <= opc_putfield) { + group = GROUP_FIELDACCESS; + } + else if (opcode >= opc_invokevirtual && opcode <= opc_invokestatic) { + group = GROUP_INVOCATION; + } + break; + case opc_invokedynamic: + if (classStruct.isVersionGE_1_7()) { // instruction unused in Java 6 and before + operands.add(new Integer(in.readUnsignedShort())); + in.discard(2); + group = GROUP_INVOCATION; + i += 4; + } + break; + case opc_iload: + case opc_lload: + case opc_fload: + case opc_dload: + case opc_aload: + case opc_istore: + case opc_lstore: + case opc_fstore: + case opc_dstore: + case opc_astore: + case opc_ret: + if (wide) { + operands.add(new Integer(in.readUnsignedShort())); + i += 2; + } + else { + operands.add(new Integer(in.readUnsignedByte())); + i++; + } + if (opcode == opc_ret) { + group = GROUP_RETURN; + } + break; + case opc_iinc: + if (wide) { + operands.add(new Integer(in.readUnsignedShort())); + operands.add(new Integer(in.readShort())); + i += 4; + } + else { + operands.add(new Integer(in.readUnsignedByte())); + operands.add(new Integer(in.readByte())); + i += 2; + } + break; + case opc_goto_w: + case opc_jsr_w: + opcode = opcode == opc_jsr_w ? opc_jsr : opc_goto; + operands.add(new Integer(in.readInt())); + group = GROUP_JUMP; + i += 4; + break; + case opc_invokeinterface: + operands.add(new Integer(in.readUnsignedShort())); + operands.add(new Integer(in.readUnsignedByte())); + in.discard(1); + group = GROUP_INVOCATION; + i += 4; + break; + case opc_multianewarray: + operands.add(new Integer(in.readUnsignedShort())); + operands.add(new Integer(in.readUnsignedByte())); + i += 3; + break; + case opc_tableswitch: + in.discard((4 - (i + 1) % 4) % 4); + i += ((4 - (i + 1) % 4) % 4); // padding + operands.add(new Integer(in.readInt())); + i += 4; + int low = in.readInt(); + operands.add(new Integer(low)); + i += 4; + int high = in.readInt(); + operands.add(new Integer(high)); + i += 4; + + for (int j = 0; j < high - low + 1; j++) { + operands.add(new Integer(in.readInt())); + i += 4; + } + group = GROUP_SWITCH; + + break; + case opc_lookupswitch: + in.discard((4 - (i + 1) % 4) % 4); + i += ((4 - (i + 1) % 4) % 4); // padding + operands.add(new Integer(in.readInt())); + i += 4; + int npairs = in.readInt(); + operands.add(new Integer(npairs)); + i += 4; + + for (int j = 0; j < npairs; j++) { + operands.add(new Integer(in.readInt())); + i += 4; + operands.add(new Integer(in.readInt())); + i += 4; + } + group = GROUP_SWITCH; + break; + case opc_ireturn: + case opc_lreturn: + case opc_freturn: + case opc_dreturn: + case opc_areturn: + case opc_return: + case opc_athrow: + group = GROUP_RETURN; + } + } + + int[] ops = new int[operands.size()]; + for (int j = 0; j < operands.size(); j++) { + ops[j] = operands.get(j).intValue(); + } + + Instruction instr = ConstantsUtil.getInstructionInstance(opcode, wide, group, bytecode_version, ops); + + instructions.addWithKey(instr, new Integer(offset)); + + i++; + } + + // initialize exception table + List<ExceptionHandler> lstHandlers = new ArrayList<ExceptionHandler>(); + + int exception_count = in.readUnsignedShort(); + for (int i = 0; i < exception_count; i++) { + ExceptionHandler handler = new ExceptionHandler(); + handler.from = in.readUnsignedShort(); + handler.to = in.readUnsignedShort(); + handler.handler = in.readUnsignedShort(); + + int excclass = in.readUnsignedShort(); + handler.class_index = excclass; + if (excclass != 0) { + handler.exceptionClass = pool.getPrimitiveConstant(excclass).getString(); + } + + lstHandlers.add(handler); + } + + InstructionSequence seq = new FullInstructionSequence(instructions, new ExceptionTable(lstHandlers)); + + // initialize instructions + int i = seq.length() - 1; + seq.setPointer(i); + + while (i >= 0) { + Instruction instr = seq.getInstr(i--); + if (instr.group != GROUP_GENERAL) { + instr.initInstruction(seq); + } + seq.addToPointer(-1); + } + + return seq; + } + + public StructClass getClassStruct() { + return classStruct; + } + + public String getName() { + return name; + } + + public String getDescriptor() { + return descriptor; + } + + public boolean containsCode() { + return containsCode; + } + + public int getLocalVariables() { + return localVariables; + } + + public InstructionSequence getInstructionSequence() { + return seq; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnDefaultAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnDefaultAttribute.java new file mode 100644 index 000000000000..fbad47e912db --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnDefaultAttribute.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; + +import java.io.IOException; + +public class StructAnnDefaultAttribute extends StructGeneralAttribute { + + private Exprent defaultValue; + + @Override + public void initContent(ConstantPool pool) throws IOException { + defaultValue = StructAnnotationAttribute.parseAnnotationElement(stream(), pool); + } + + public Exprent getDefaultValue() { + return defaultValue; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationAttribute.java new file mode 100644 index 000000000000..d04cb04166d5 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationAttribute.java @@ -0,0 +1,184 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.modules.decompiler.exps.*; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.struct.consts.PrimitiveConstant; +import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class StructAnnotationAttribute extends StructGeneralAttribute { + + private List<AnnotationExprent> annotations; + + @Override + public void initContent(ConstantPool pool) throws IOException { + annotations = parseAnnotations(pool, stream()); + } + + public static List<AnnotationExprent> parseAnnotations(ConstantPool pool, DataInputStream data) throws IOException { + int len = data.readUnsignedShort(); + if (len > 0) { + List<AnnotationExprent> annotations = new ArrayList<AnnotationExprent>(len); + for (int i = 0; i < len; i++) { + annotations.add(parseAnnotation(data, pool)); + } + return annotations; + } + else { + return Collections.emptyList(); + } + } + + public static AnnotationExprent parseAnnotation(DataInputStream data, ConstantPool pool) throws IOException { + String className = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); + + List<String> names; + List<Exprent> values; + int len = data.readUnsignedShort(); + if (len > 0) { + names = new ArrayList<String>(len); + values = new ArrayList<Exprent>(len); + for (int i = 0; i < len; i++) { + names.add(pool.getPrimitiveConstant(data.readUnsignedShort()).getString()); + values.add(parseAnnotationElement(data, pool)); + } + } + else { + names = Collections.emptyList(); + values = Collections.emptyList(); + } + + return new AnnotationExprent(new VarType(className).value, names, values); + } + + public static Exprent parseAnnotationElement(DataInputStream data, ConstantPool pool) throws IOException { + int tag = data.readUnsignedByte(); + + switch (tag) { + case 'e': // enum constant + String className = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); + String constName = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); + FieldDescriptor descr = FieldDescriptor.parseDescriptor(className); + return new FieldExprent(constName, descr.type.value, true, null, descr); + + case 'c': // class + String descriptor = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); + VarType type = FieldDescriptor.parseDescriptor(descriptor).type; + + String value; + switch (type.type) { + case CodeConstants.TYPE_OBJECT: + value = type.value; + break; + case CodeConstants.TYPE_BYTE: + value = byte.class.getName(); + break; + case CodeConstants.TYPE_CHAR: + value = char.class.getName(); + break; + case CodeConstants.TYPE_DOUBLE: + value = double.class.getName(); + break; + case CodeConstants.TYPE_FLOAT: + value = float.class.getName(); + break; + case CodeConstants.TYPE_INT: + value = int.class.getName(); + break; + case CodeConstants.TYPE_LONG: + value = long.class.getName(); + break; + case CodeConstants.TYPE_SHORT: + value = short.class.getName(); + break; + case CodeConstants.TYPE_BOOLEAN: + value = boolean.class.getName(); + break; + case CodeConstants.TYPE_VOID: + value = void.class.getName(); + break; + default: + throw new RuntimeException("invalid class type: " + type.type); + } + return new ConstExprent(VarType.VARTYPE_CLASS, value); + + case '[': // array + List<Exprent> elements = Collections.emptyList(); + int len = data.readUnsignedShort(); + if (len > 0) { + elements = new ArrayList<Exprent>(len); + for (int i = 0; i < len; i++) { + elements.add(parseAnnotationElement(data, pool)); + } + } + + VarType newType; + if (elements.isEmpty()) { + newType = new VarType(CodeConstants.TYPE_OBJECT, 1, "java/lang/Object"); + } + else { + VarType elementType = elements.get(0).getExprType(); + newType = new VarType(elementType.type, 1, elementType.value); + } + + NewExprent newExpr = new NewExprent(newType, Collections.<Exprent>emptyList()); + newExpr.setDirectArrayInit(true); + newExpr.setLstArrayElements(elements); + return newExpr; + + case '@': // annotation + return parseAnnotation(data, pool); + + default: + PrimitiveConstant cn = pool.getPrimitiveConstant(data.readUnsignedShort()); + switch (tag) { + case 'B': + return new ConstExprent(VarType.VARTYPE_BYTE, cn.value); + case 'C': + return new ConstExprent(VarType.VARTYPE_CHAR, cn.value); + case 'D': + return new ConstExprent(VarType.VARTYPE_DOUBLE, cn.value); + case 'F': + return new ConstExprent(VarType.VARTYPE_FLOAT, cn.value); + case 'I': + return new ConstExprent(VarType.VARTYPE_INT, cn.value); + case 'J': + return new ConstExprent(VarType.VARTYPE_LONG, cn.value); + case 'S': + return new ConstExprent(VarType.VARTYPE_SHORT, cn.value); + case 'Z': + return new ConstExprent(VarType.VARTYPE_BOOLEAN, cn.value); + case 's': + return new ConstExprent(VarType.VARTYPE_STRING, cn.value); + default: + throw new RuntimeException("invalid element type!"); + } + } + } + + public List<AnnotationExprent> getAnnotations() { + return annotations; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationParameterAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationParameterAttribute.java new file mode 100644 index 000000000000..a33c7bbebe06 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationParameterAttribute.java @@ -0,0 +1,51 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.AnnotationExprent; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class StructAnnotationParameterAttribute extends StructGeneralAttribute { + + private List<List<AnnotationExprent>> paramAnnotations; + + @Override + public void initContent(ConstantPool pool) throws IOException { + DataInputStream data = stream(); + + int len = data.readUnsignedByte(); + if (len > 0) { + paramAnnotations = new ArrayList<List<AnnotationExprent>>(len); + for (int i = 0; i < len; i++) { + List<AnnotationExprent> annotations = StructAnnotationAttribute.parseAnnotations(pool, data); + paramAnnotations.add(annotations); + } + } + else { + paramAnnotations = Collections.emptyList(); + } + } + + public List<List<AnnotationExprent>> getParamAnnotations() { + return paramAnnotations; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationTypeAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationTypeAttribute.java new file mode 100644 index 000000000000..59324e35654d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructAnnotationTypeAttribute.java @@ -0,0 +1,194 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.AnnotationExprent; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class StructAnnotationTypeAttribute extends StructGeneralAttribute { + + private static final int ANNOTATION_TARGET_TYPE_GENERIC_CLASS = 0x00; + private static final int ANNOTATION_TARGET_TYPE_GENERIC_METHOD = 0x01; + private static final int ANNOTATION_TARGET_TYPE_EXTENDS_IMPLEMENTS = 0x10; + private static final int ANNOTATION_TARGET_TYPE_GENERIC_CLASS_BOUND = 0x11; + private static final int ANNOTATION_TARGET_TYPE_GENERIC_METHOD_BOUND = 0x12; + private static final int ANNOTATION_TARGET_TYPE_FIELD = 0x13; + private static final int ANNOTATION_TARGET_TYPE_RETURN = 0x14; + private static final int ANNOTATION_TARGET_TYPE_RECEIVER = 0x15; + private static final int ANNOTATION_TARGET_TYPE_FORMAL = 0x16; + private static final int ANNOTATION_TARGET_TYPE_THROWS = 0x17; + private static final int ANNOTATION_TARGET_TYPE_LOCAL_VARIABLE = 0x40; + private static final int ANNOTATION_TARGET_TYPE_RESOURCE_VARIABLE = 0x41; + private static final int ANNOTATION_TARGET_TYPE_EXCEPTION = 0x42; + private static final int ANNOTATION_TARGET_TYPE_INSTANCEOF = 0x43; + private static final int ANNOTATION_TARGET_TYPE_NEW = 0x44; + private static final int ANNOTATION_TARGET_TYPE_DOUBLE_COLON_NEW = 0x45; + private static final int ANNOTATION_TARGET_TYPE_DOUBLE_COLON_ID = 0x46; + private static final int ANNOTATION_TARGET_TYPE_CAST = 0x47; + private static final int ANNOTATION_TARGET_TYPE_INVOCATION_CONSTRUCTOR = 0x48; + private static final int ANNOTATION_TARGET_TYPE_INVOCATION_METHOD = 0x49; + private static final int ANNOTATION_TARGET_TYPE_GENERIC_DOUBLE_COLON_NEW = 0x4A; + private static final int ANNOTATION_TARGET_TYPE_GENERIC_DOUBLE_COLON_ID = 0x4B; + + private static final int ANNOTATION_TARGET_UNION_TYPE_PARAMETER = 1; + private static final int ANNOTATION_TARGET_UNION_SUPERTYPE = 2; + private static final int ANNOTATION_TARGET_UNION_TYPE_PARAMETER_BOUND = 3; + private static final int ANNOTATION_TARGET_UNION_EMPTY = 4; + private static final int ANNOTATION_TARGET_UNION_FORMAL_PARAMETER = 5; + private static final int ANNOTATION_TARGET_UNION_THROWS = 6; + private static final int ANNOTATION_TARGET_UNION_LOCAL_VAR = 7; + private static final int ANNOTATION_TARGET_UNION_CATCH = 8; + private static final int ANNOTATION_TARGET_UNION_OFFSET = 9; + private static final int ANNOTATION_TARGET_UNION_TYPE_ARGUMENT = 10; + + @SuppressWarnings("FieldCanBeLocal") private List<AnnotationLocation> locations; + @SuppressWarnings("FieldCanBeLocal") private List<AnnotationExprent> annotations; + + @Override + public void initContent(ConstantPool pool) throws IOException { + DataInputStream data = stream(); + + int len = data.readUnsignedByte(); + if (len > 0) { + locations = new ArrayList<AnnotationLocation>(len); + annotations = new ArrayList<AnnotationExprent>(len); + for (int i = 0; i < len; i++) { + locations.add(parseAnnotationLocation(data)); + annotations.add(StructAnnotationAttribute.parseAnnotation(data, pool)); + } + } + else { + locations = Collections.emptyList(); + annotations = Collections.emptyList(); + } + } + + private static AnnotationLocation parseAnnotationLocation(DataInputStream data) throws IOException { + AnnotationLocation ann_location = new AnnotationLocation(); + + // target type + ann_location.target_type = data.readUnsignedByte(); + + // target union + switch (ann_location.target_type) { + case ANNOTATION_TARGET_TYPE_GENERIC_CLASS: + case ANNOTATION_TARGET_TYPE_GENERIC_METHOD: + ann_location.target_union = ANNOTATION_TARGET_UNION_TYPE_PARAMETER; + break; + case ANNOTATION_TARGET_TYPE_EXTENDS_IMPLEMENTS: + ann_location.target_union = ANNOTATION_TARGET_UNION_SUPERTYPE; + break; + case ANNOTATION_TARGET_TYPE_GENERIC_CLASS_BOUND: + case ANNOTATION_TARGET_TYPE_GENERIC_METHOD_BOUND: + ann_location.target_union = ANNOTATION_TARGET_UNION_TYPE_PARAMETER_BOUND; + break; + case ANNOTATION_TARGET_TYPE_FIELD: + case ANNOTATION_TARGET_TYPE_RETURN: + case ANNOTATION_TARGET_TYPE_RECEIVER: + ann_location.target_union = ANNOTATION_TARGET_UNION_EMPTY; + break; + case ANNOTATION_TARGET_TYPE_FORMAL: + ann_location.target_union = ANNOTATION_TARGET_UNION_FORMAL_PARAMETER; + break; + case ANNOTATION_TARGET_TYPE_THROWS: + ann_location.target_union = ANNOTATION_TARGET_UNION_THROWS; + break; + case ANNOTATION_TARGET_TYPE_LOCAL_VARIABLE: + case ANNOTATION_TARGET_TYPE_RESOURCE_VARIABLE: + ann_location.target_union = ANNOTATION_TARGET_UNION_LOCAL_VAR; + break; + case ANNOTATION_TARGET_TYPE_EXCEPTION: + ann_location.target_union = ANNOTATION_TARGET_UNION_CATCH; + break; + case ANNOTATION_TARGET_TYPE_INSTANCEOF: + case ANNOTATION_TARGET_TYPE_NEW: + case ANNOTATION_TARGET_TYPE_DOUBLE_COLON_NEW: + case ANNOTATION_TARGET_TYPE_DOUBLE_COLON_ID: + ann_location.target_union = ANNOTATION_TARGET_UNION_OFFSET; + break; + case ANNOTATION_TARGET_TYPE_CAST: + case ANNOTATION_TARGET_TYPE_INVOCATION_CONSTRUCTOR: + case ANNOTATION_TARGET_TYPE_INVOCATION_METHOD: + case ANNOTATION_TARGET_TYPE_GENERIC_DOUBLE_COLON_NEW: + case ANNOTATION_TARGET_TYPE_GENERIC_DOUBLE_COLON_ID: + ann_location.target_union = ANNOTATION_TARGET_UNION_TYPE_ARGUMENT; + break; + default: + throw new RuntimeException("Unknown target type in a type annotation!"); + } + + // target union data + + switch (ann_location.target_union) { + case ANNOTATION_TARGET_UNION_TYPE_PARAMETER: + case ANNOTATION_TARGET_UNION_FORMAL_PARAMETER: + ann_location.data = new int[]{data.readUnsignedByte()}; + break; + case ANNOTATION_TARGET_UNION_SUPERTYPE: + case ANNOTATION_TARGET_UNION_THROWS: + case ANNOTATION_TARGET_UNION_CATCH: + case ANNOTATION_TARGET_UNION_OFFSET: + ann_location.data = new int[]{data.readUnsignedShort()}; + break; + case ANNOTATION_TARGET_UNION_TYPE_PARAMETER_BOUND: + ann_location.data = new int[]{data.readUnsignedByte(), data.readUnsignedByte()}; + break; + case ANNOTATION_TARGET_UNION_EMPTY: + break; + case ANNOTATION_TARGET_UNION_LOCAL_VAR: + int table_length = data.readUnsignedShort(); + + ann_location.data = new int[table_length * 3 + 1]; + ann_location.data[0] = table_length; + + for (int i = 0; i < table_length; ++i) { + ann_location.data[3 * i + 1] = data.readUnsignedShort(); + ann_location.data[3 * i + 2] = data.readUnsignedShort(); + ann_location.data[3 * i + 3] = data.readUnsignedShort(); + } + break; + case ANNOTATION_TARGET_UNION_TYPE_ARGUMENT: + ann_location.data = new int[]{data.readUnsignedShort(), data.readUnsignedByte()}; + } + + // target path + int path_length = data.readUnsignedByte(); + + ann_location.target_path_kind = new int[path_length]; + ann_location.target_argument_index = new int[path_length]; + + for (int i = 0; i < path_length; ++i) { + ann_location.target_path_kind[i] = data.readUnsignedByte(); + ann_location.target_argument_index[i] = data.readUnsignedByte(); + } + + return ann_location; + } + + private static class AnnotationLocation { + public int target_type; + public int target_union; + public int[] data; + public int[] target_path_kind; + public int[] target_argument_index; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructBootstrapMethodsAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructBootstrapMethodsAttribute.java new file mode 100644 index 000000000000..840acc7456f4 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructBootstrapMethodsAttribute.java @@ -0,0 +1,66 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.struct.consts.LinkConstant; +import org.jetbrains.java.decompiler.struct.consts.PooledConstant; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class StructBootstrapMethodsAttribute extends StructGeneralAttribute { + + private List<LinkConstant> methodRefs = new ArrayList<LinkConstant>(); + private List<List<PooledConstant>> methodArguments = new ArrayList<List<PooledConstant>>(); + + @Override + public void initContent(ConstantPool pool) throws IOException { + DataInputStream data = stream(); + + int method_number = data.readUnsignedShort(); + + for (int i = 0; i < method_number; ++i) { + int bootstrap_method_ref = data.readUnsignedShort(); + int num_bootstrap_arguments = data.readUnsignedShort(); + + List<PooledConstant> list_arguments = new ArrayList<PooledConstant>(); + + for (int j = 0; j < num_bootstrap_arguments; ++j) { + int bootstrap_argument_ref = data.readUnsignedShort(); + + list_arguments.add(pool.getConstant(bootstrap_argument_ref)); + } + + methodRefs.add(pool.getLinkConstant(bootstrap_method_ref)); + methodArguments.add(list_arguments); + } + } + + public int getMethodsNumber() { + return methodRefs.size(); + } + + public LinkConstant getMethodReference(int index) { + return methodRefs.get(index); + } + + public List<PooledConstant> getMethodArguments(int index) { + return methodArguments.get(index); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructConstantValueAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructConstantValueAttribute.java new file mode 100644 index 000000000000..07a507329dba --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructConstantValueAttribute.java @@ -0,0 +1,34 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; + +import java.io.IOException; + +public class StructConstantValueAttribute extends StructGeneralAttribute { + + private int index; + + @Override + public void initContent(ConstantPool pool) throws IOException { + index = stream().readUnsignedShort(); + } + + public int getIndex() { + return index; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructEnclosingMethodAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructEnclosingMethodAttribute.java new file mode 100644 index 000000000000..c9b9ebb680ea --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructEnclosingMethodAttribute.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.struct.consts.LinkConstant; + +import java.io.DataInputStream; +import java.io.IOException; + +public class StructEnclosingMethodAttribute extends StructGeneralAttribute { + + private String className; + private String methodName; + private String methodDescriptor; + + @Override + public void initContent(ConstantPool pool) throws IOException { + DataInputStream data = stream(); + int classIndex = data.readUnsignedShort(); + int methodIndex = data.readUnsignedShort(); + + className = pool.getPrimitiveConstant(classIndex).getString(); + if (methodIndex != 0) { + LinkConstant lk = pool.getLinkConstant(methodIndex); + methodName = lk.elementname; + methodDescriptor = lk.descriptor; + } + } + + public String getClassName() { + return className; + } + + public String getMethodDescriptor() { + return methodDescriptor; + } + + public String getMethodName() { + return methodName; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructExceptionsAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructExceptionsAttribute.java new file mode 100644 index 000000000000..5eda047ca5f9 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructExceptionsAttribute.java @@ -0,0 +1,52 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class StructExceptionsAttribute extends StructGeneralAttribute { + + private List<Integer> throwsExceptions; + + @Override + public void initContent(ConstantPool pool) throws IOException { + DataInputStream data = stream(); + int len = data.readUnsignedShort(); + if (len > 0) { + throwsExceptions = new ArrayList<Integer>(len); + for (int i = 0; i < len; i++) { + throwsExceptions.add(data.readUnsignedShort()); + } + } + else { + throwsExceptions = Collections.emptyList(); + } + } + + public String getExcClassname(int index, ConstantPool pool) { + return pool.getPrimitiveConstant(throwsExceptions.get(index).intValue()).getString(); + } + + public List<Integer> getThrowsExceptions() { + return throwsExceptions; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructGeneralAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructGeneralAttribute.java new file mode 100644 index 000000000000..2cdc524e37a1 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructGeneralAttribute.java @@ -0,0 +1,118 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.util.DataInputFullStream; + +import java.io.IOException; + +/* + attribute_info { + u2 attribute_name_index; + u4 attribute_length; + u1 info[attribute_length]; + } +*/ +public class StructGeneralAttribute { + + public static final String ATTRIBUTE_CODE = "Code"; + public static final String ATTRIBUTE_INNER_CLASSES = "InnerClasses"; + public static final String ATTRIBUTE_SIGNATURE = "Signature"; + public static final String ATTRIBUTE_ANNOTATION_DEFAULT = "AnnotationDefault"; + public static final String ATTRIBUTE_EXCEPTIONS = "Exceptions"; + public static final String ATTRIBUTE_ENCLOSING_METHOD = "EnclosingMethod"; + public static final String ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS = "RuntimeVisibleAnnotations"; + public static final String ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS = "RuntimeInvisibleAnnotations"; + public static final String ATTRIBUTE_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS = "RuntimeVisibleParameterAnnotations"; + public static final String ATTRIBUTE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS = "RuntimeInvisibleParameterAnnotations"; + public static final String ATTRIBUTE_RUNTIME_VISIBLE_TYPE_ANNOTATIONS = "RuntimeVisibleTypeAnnotations"; + public static final String ATTRIBUTE_RUNTIME_INVISIBLE_TYPE_ANNOTATIONS = "RuntimeInvisibleTypeAnnotations"; + public static final String ATTRIBUTE_LOCAL_VARIABLE_TABLE = "LocalVariableTable"; + public static final String ATTRIBUTE_CONSTANT_VALUE = "ConstantValue"; + public static final String ATTRIBUTE_BOOTSTRAP_METHODS = "BootstrapMethods"; + public static final String ATTRIBUTE_SYNTHETIC = "Synthetic"; + public static final String ATTRIBUTE_DEPRECATED = "Deprecated"; + + private String name; + private byte[] info; + + public static StructGeneralAttribute createAttribute(String name) { + StructGeneralAttribute attr; + + if (ATTRIBUTE_INNER_CLASSES.equals(name)) { + attr = new StructInnerClassesAttribute(); + } + else if (ATTRIBUTE_CONSTANT_VALUE.equals(name)) { + attr = new StructConstantValueAttribute(); + } + else if (ATTRIBUTE_SIGNATURE.equals(name)) { + attr = new StructGenericSignatureAttribute(); + } + else if (ATTRIBUTE_ANNOTATION_DEFAULT.equals(name)) { + attr = new StructAnnDefaultAttribute(); + } + else if (ATTRIBUTE_EXCEPTIONS.equals(name)) { + attr = new StructExceptionsAttribute(); + } + else if (ATTRIBUTE_ENCLOSING_METHOD.equals(name)) { + attr = new StructEnclosingMethodAttribute(); + } + else if (ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS.equals(name) || + ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS.equals(name)) { + attr = new StructAnnotationAttribute(); + } + else if (ATTRIBUTE_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(name) || + ATTRIBUTE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(name)) { + attr = new StructAnnotationParameterAttribute(); + } + else if (ATTRIBUTE_RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(name) || + ATTRIBUTE_RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(name)) { + attr = new StructAnnotationTypeAttribute(); + } + else if (ATTRIBUTE_LOCAL_VARIABLE_TABLE.equals(name)) { + attr = new StructLocalVariableTableAttribute(); + } + else if (ATTRIBUTE_BOOTSTRAP_METHODS.equals(name)) { + attr = new StructBootstrapMethodsAttribute(); + } + else if (ATTRIBUTE_SYNTHETIC.equals(name) || + ATTRIBUTE_DEPRECATED.equals(name)) { + attr = new StructGeneralAttribute(); + } + else { + // unsupported attribute + return null; + } + + attr.name = name; + return attr; + } + + protected DataInputFullStream stream() { + return new DataInputFullStream(info); + } + + public void initContent(ConstantPool pool) throws IOException { } + + public void setInfo(byte[] info) { + this.info = info; + } + + public String getName() { + return name; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructGenericSignatureAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructGenericSignatureAttribute.java new file mode 100644 index 000000000000..62c892f83b1a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructGenericSignatureAttribute.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; + +import java.io.IOException; + +public class StructGenericSignatureAttribute extends StructGeneralAttribute { + + private String signature; + + @Override + public void initContent(ConstantPool pool) throws IOException { + int index = stream().readUnsignedShort(); + signature = pool.getPrimitiveConstant(index).getString(); + } + + public String getSignature() { + return signature; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructInnerClassesAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructInnerClassesAttribute.java new file mode 100644 index 000000000000..596948790460 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructInnerClassesAttribute.java @@ -0,0 +1,72 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class StructInnerClassesAttribute extends StructGeneralAttribute { + + private List<int[]> classEntries; + private List<String[]> stringEntries; + + @Override + public void initContent(ConstantPool pool) throws IOException { + DataInputStream data = stream(); + + int len = data.readUnsignedShort(); + if (len > 0) { + classEntries = new ArrayList<int[]>(len); + stringEntries = new ArrayList<String[]>(len); + + for (int i = 0; i < len; i++) { + int[] classEntry = new int[4]; + for (int j = 0; j < 4; j++) { + classEntry[j] = data.readUnsignedShort(); + } + classEntries.add(classEntry); + + // inner name, enclosing class, original simple name + String[] stringEntry = new String[3]; + stringEntry[0] = pool.getPrimitiveConstant(classEntry[0]).getString(); + if (classEntry[1] != 0) { + stringEntry[1] = pool.getPrimitiveConstant(classEntry[1]).getString(); + } + if (classEntry[2] != 0) { + stringEntry[2] = pool.getPrimitiveConstant(classEntry[2]).getString(); + } + stringEntries.add(stringEntry); + } + } + else { + classEntries = Collections.emptyList(); + stringEntries = Collections.emptyList(); + } + } + + public List<int[]> getClassEntries() { + return classEntries; + } + + public List<String[]> getStringEntries() { + return stringEntries; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructLocalVariableTableAttribute.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructLocalVariableTableAttribute.java new file mode 100644 index 000000000000..60e40c013db6 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/attr/StructLocalVariableTableAttribute.java @@ -0,0 +1,67 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.attr; + +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.util.DataInputFullStream; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/* + u2 local_variable_table_length; + local_variable { + u2 start_pc; + u2 length; + u2 name_index; + u2 descriptor_index; + u2 index; + } +*/ +public class StructLocalVariableTableAttribute extends StructGeneralAttribute { + + private Map<Integer, String> mapVarNames = new HashMap<Integer, String>(); + + @Override + public void initContent(ConstantPool pool) throws IOException { + DataInputFullStream data = stream(); + + int len = data.readUnsignedShort(); + if (len > 0) { + mapVarNames = new HashMap<Integer, String>(len); + for (int i = 0; i < len; i++) { + data.discard(4); + int nameIndex = data.readUnsignedShort(); + data.discard(2); + int varIndex = data.readUnsignedShort(); + mapVarNames.put(varIndex, pool.getPrimitiveConstant(nameIndex).getString()); + } + } + else { + mapVarNames = Collections.emptyMap(); + } + } + + public void addLocalVariableTable(StructLocalVariableTableAttribute attr) { + mapVarNames.putAll(attr.getMapVarNames()); + } + + public Map<Integer, String> getMapVarNames() { + return mapVarNames; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/ConstantPool.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/ConstantPool.java new file mode 100644 index 000000000000..d534e6df6d3c --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/ConstantPool.java @@ -0,0 +1,281 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.consts; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.modules.renamer.PoolInterceptor; +import org.jetbrains.java.decompiler.struct.gen.FieldDescriptor; +import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor; +import org.jetbrains.java.decompiler.struct.gen.VarType; +import org.jetbrains.java.decompiler.util.DataInputFullStream; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class ConstantPool { + + public static final int FIELD = 1; + public static final int METHOD = 2; + + private List<PooledConstant> pool = new ArrayList<PooledConstant>(); + private PoolInterceptor interceptor; + + + public ConstantPool(DataInputStream in) throws IOException { + int size = in.readUnsignedShort(); + int[] pass = new int[size]; + + // first dummy constant + pool.add(null); + + // first pass: read the elements + for (int i = 1; i < size; i++) { + byte tag = (byte)in.readUnsignedByte(); + + switch (tag) { + case CodeConstants.CONSTANT_Utf8: + pool.add(new PrimitiveConstant(CodeConstants.CONSTANT_Utf8, in.readUTF())); + break; + case CodeConstants.CONSTANT_Integer: + pool.add(new PrimitiveConstant(CodeConstants.CONSTANT_Integer, new Integer(in.readInt()))); + break; + case CodeConstants.CONSTANT_Float: + pool.add(new PrimitiveConstant(CodeConstants.CONSTANT_Float, new Float(in.readFloat()))); + break; + case CodeConstants.CONSTANT_Long: + pool.add(new PrimitiveConstant(CodeConstants.CONSTANT_Long, new Long(in.readLong()))); + pool.add(null); + i++; + break; + case CodeConstants.CONSTANT_Double: + pool.add(new PrimitiveConstant(CodeConstants.CONSTANT_Double, new Double(in.readDouble()))); + pool.add(null); + i++; + break; + case CodeConstants.CONSTANT_Class: + case CodeConstants.CONSTANT_String: + case CodeConstants.CONSTANT_MethodType: + pool.add(new PrimitiveConstant(tag, in.readUnsignedShort())); + pass[i] = 1; + break; + case CodeConstants.CONSTANT_Fieldref: + case CodeConstants.CONSTANT_Methodref: + case CodeConstants.CONSTANT_InterfaceMethodref: + case CodeConstants.CONSTANT_NameAndType: + case CodeConstants.CONSTANT_InvokeDynamic: + pool.add(new LinkConstant(tag, in.readUnsignedShort(), in.readUnsignedShort())); + if (tag == CodeConstants.CONSTANT_NameAndType) { + pass[i] = 1; + } + else { + pass[i] = 2; + } + break; + case CodeConstants.CONSTANT_MethodHandle: + pool.add(new LinkConstant(tag, in.readUnsignedByte(), in.readUnsignedShort())); + pass[i] = 3; + break; + } + } + + // resolving complex pool elements + for (int passIndex = 1; passIndex <= 3; passIndex++) { + for (int i = 1; i < size; i++) { + if (pass[i] == passIndex) { + pool.get(i).resolveConstant(this); + } + } + } + + // get global constant pool interceptor instance, if any available + interceptor = DecompilerContext.getPoolInterceptor(); + } + + public static void skipPool(DataInputFullStream in) throws IOException { + int size = in.readUnsignedShort(); + + for (int i = 1; i < size; i++) { + switch (in.readUnsignedByte()) { + case CodeConstants.CONSTANT_Utf8: + in.readUTF(); + break; + case CodeConstants.CONSTANT_Integer: + case CodeConstants.CONSTANT_Float: + case CodeConstants.CONSTANT_Fieldref: + case CodeConstants.CONSTANT_Methodref: + case CodeConstants.CONSTANT_InterfaceMethodref: + case CodeConstants.CONSTANT_NameAndType: + case CodeConstants.CONSTANT_InvokeDynamic: + in.discard(4); + break; + case CodeConstants.CONSTANT_Long: + case CodeConstants.CONSTANT_Double: + in.discard(8); + i++; + break; + case CodeConstants.CONSTANT_Class: + case CodeConstants.CONSTANT_String: + case CodeConstants.CONSTANT_MethodType: + in.discard(2); + break; + case CodeConstants.CONSTANT_MethodHandle: + in.discard(3); + } + } + } + + public int size() { + return pool.size(); + } + + public String[] getClassElement(int elementType, String className, int nameIndex, int descriptorIndex) { + String elementName = ((PrimitiveConstant)getConstant(nameIndex)).getString(); + String descriptor = ((PrimitiveConstant)getConstant(descriptorIndex)).getString(); + + if (interceptor != null) { + String newElement = interceptor.getName(className + " " + elementName + " " + descriptor); + if (newElement != null) { + elementName = newElement.split(" ")[1]; + } + + int type = elementType == FIELD ? CodeConstants.CONSTANT_Fieldref : CodeConstants.CONSTANT_Methodref; + String newDescriptor = buildNewDescriptor(type, descriptor); + if (newDescriptor != null) { + descriptor = newDescriptor; + } + } + + return new String[]{elementName, descriptor}; + } + + public PooledConstant getConstant(int index) { + return pool.get(index); + } + + public PrimitiveConstant getPrimitiveConstant(int index) { + PrimitiveConstant cn = (PrimitiveConstant)getConstant(index); + + if (cn != null && interceptor != null) { + if (cn.type == CodeConstants.CONSTANT_Class) { + String newName = buildNewClassname(cn.getString()); + if (newName != null) { + cn = new PrimitiveConstant(CodeConstants.CONSTANT_Class, newName); + } + } + } + + return cn; + } + + public LinkConstant getLinkConstant(int index) { + LinkConstant ln = (LinkConstant)getConstant(index); + + if (ln != null && interceptor != null && + (ln.type == CodeConstants.CONSTANT_Fieldref || + ln.type == CodeConstants.CONSTANT_Methodref || + ln.type == CodeConstants.CONSTANT_InterfaceMethodref)) { + String newClassName = buildNewClassname(ln.classname); + String newElement = interceptor.getName(ln.classname + " " + ln.elementname + " " + ln.descriptor); + String newDescriptor = buildNewDescriptor(ln.type, ln.descriptor); + + if (newClassName != null || newElement != null || newDescriptor != null) { + String className = newClassName == null ? ln.classname : newClassName; + String elementName = newElement == null ? ln.elementname : newElement.split(" ")[1]; + String descriptor = newDescriptor == null ? ln.descriptor : newDescriptor; + ln = new LinkConstant(ln.type, className, elementName, descriptor); + } + } + + return ln; + } + + private String buildNewClassname(String className) { + VarType vt = new VarType(className, true); + + String newName = interceptor.getName(vt.value); + if (newName != null) { + StringBuilder buffer = new StringBuilder(); + + if (vt.arraydim > 0) { + for (int i = 0; i < vt.arraydim; i++) { + buffer.append("["); + } + + buffer.append("L").append(newName).append(";"); + } + else { + buffer.append(newName); + } + + return buffer.toString(); + } + + return null; + } + + private String buildNewDescriptor(int type, String descriptor) { + boolean updated = false; + + if (type == CodeConstants.CONSTANT_Fieldref) { + FieldDescriptor fd = FieldDescriptor.parseDescriptor(descriptor); + + VarType fType = fd.type; + if (fType.type == CodeConstants.TYPE_OBJECT) { + String newClassName = buildNewClassname(fType.value); + if (newClassName != null) { + fType.value = newClassName; + updated = true; + } + } + + if (updated) { + return fd.getDescriptor(); + } + } + else { + MethodDescriptor md = MethodDescriptor.parseDescriptor(descriptor); + + // parameters + for (VarType paramType : md.params) { + if (paramType.type == CodeConstants.TYPE_OBJECT) { + String newClassName = buildNewClassname(paramType.value); + if (newClassName != null) { + paramType.value = newClassName; + updated = true; + } + } + } + + // return value + if (md.ret.type == CodeConstants.TYPE_OBJECT) { + String newClassName = buildNewClassname(md.ret.value); + if (newClassName != null) { + md.ret.value = newClassName; + updated = true; + } + } + + if (updated) { + return md.getDescriptor(); + } + } + + return null; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/LinkConstant.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/LinkConstant.java new file mode 100644 index 000000000000..71bf14615558 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/LinkConstant.java @@ -0,0 +1,165 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.consts; + +import java.io.DataOutputStream; +import java.io.IOException; + +/* + * NameAndType, FieldRef, MethodRef, InterfaceMethodref + * InvokeDynamic, MethodHandle + */ + +public class LinkConstant extends PooledConstant { + + // ***************************************************************************** + // public fields + // ***************************************************************************** + + public int index1, index2; + + public String classname; + + public String elementname; + + public String descriptor; + + public int paramCount = 0; + + public boolean isVoid = false; + + public boolean returnCategory2 = false; + + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public LinkConstant(int type, String classname, String elementname, String descriptor) { + this.type = type; + this.classname = classname; + this.elementname = elementname; + this.descriptor = descriptor; + + initConstant(); + } + + public LinkConstant(int type, int index1, int index2) { + this.type = type; + this.index1 = index1; + this.index2 = index2; + } + + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public void resolveConstant(ConstantPool pool) { + + if (type == CONSTANT_NameAndType) { + elementname = pool.getPrimitiveConstant(index1).getString(); + descriptor = pool.getPrimitiveConstant(index2).getString(); + } + else if (type == CONSTANT_MethodHandle) { + LinkConstant ref_info = pool.getLinkConstant(index2); + + classname = ref_info.classname; + elementname = ref_info.elementname; + descriptor = ref_info.descriptor; + } + else { + if (type != CONSTANT_InvokeDynamic) { + classname = pool.getPrimitiveConstant(index1).getString(); + } + + LinkConstant nametype = pool.getLinkConstant(index2); + elementname = nametype.elementname; + descriptor = nametype.descriptor; + } + + initConstant(); + } + + public void writeToStream(DataOutputStream out) throws IOException { + out.writeByte(type); + if (type == CONSTANT_MethodHandle) { + out.writeByte(index1); + } + else { + out.writeShort(index1); + } + out.writeShort(index2); + } + + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof LinkConstant)) return false; + + LinkConstant cn = (LinkConstant)o; + return this.type == cn.type && + this.elementname.equals(cn.elementname) && + this.descriptor.equals(cn.descriptor) && + (this.type != CONSTANT_NameAndType || this.classname.equals(cn.classname)); + } + + // ***************************************************************************** + // private methods + // ***************************************************************************** + + private void initConstant() { + + if (type == CONSTANT_Methodref || + type == CONSTANT_InterfaceMethodref || + type == CONSTANT_InvokeDynamic || + type == CONSTANT_MethodHandle) { + resolveDescriptor(descriptor); + } + else if (type == CONSTANT_Fieldref) { + returnCategory2 = ("D".equals(descriptor) || "J".equals(descriptor)); + } + } + + private void resolveDescriptor(String descr) { + + String[] arr = descr.split("[()]"); + String par = arr[1]; + + int index = 0, counter = 0; + int len = par.length(); + + while (index < len) { + + char c = par.charAt(index); + if (c == 'L') { + index = par.indexOf(";", index); + } + else if (c == '[') { + index++; + continue; + } + + counter++; + index++; + } + + paramCount = counter; + isVoid = "V".equals(arr[2]); + returnCategory2 = ("D".equals(arr[2]) || "J".equals(arr[2])); + } +} + diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/PooledConstant.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/PooledConstant.java new file mode 100644 index 000000000000..d3d30c0d1540 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/PooledConstant.java @@ -0,0 +1,117 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.consts; + +import org.jetbrains.java.decompiler.code.CodeConstants; + +import java.io.DataOutputStream; +import java.io.IOException; + +/* + cp_info { + u1 tag; + u1 info[]; + } + +*/ + +public class PooledConstant implements CodeConstants, VariableTypeEnum { + + // ***************************************************************************** + // public fields + // ***************************************************************************** + + public int type; + + public boolean own = false; + + public int returnType; + + + // ***************************************************************************** + // private fields + // ***************************************************************************** + + private Object[] values; + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public PooledConstant() { + } + + public PooledConstant(int type, Object[] values) { + this.type = type; + this.values = values; + this.returnType = poolTypeToIntern(type); + } + + public PooledConstant(int type, boolean own, Object[] values) { + this.type = type; + this.own = own; + this.values = values; + this.returnType = poolTypeToIntern(type); + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public void resolveConstant(ConstantPool pool) { + // to be overwritten + } + + public void writeToStream(DataOutputStream out) throws IOException { + // to be overwritten + } + + public int poolTypeToIntern(int type) { + + switch (type) { + case CONSTANT_Integer: + return INT; + case CONSTANT_Float: + return FLOAT; + case CONSTANT_Long: + return LONG; + case CONSTANT_Double: + return DOUBLE; + case CONSTANT_String: + case CONSTANT_Class: // 1.5 -> ldc class + return REFERENCE; + default: + throw new RuntimeException("Huh?? What are you trying to load?"); + } + } + + public Object getValue(int index) { + return values[index]; + } + + + // ***************************************************************************** + // getter and setter methods + // ***************************************************************************** + + public Object[] getValues() { + return values; + } + + public void setValues(Object[] values) { + this.values = values; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/PrimitiveConstant.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/PrimitiveConstant.java new file mode 100644 index 000000000000..4cd4dd88dff7 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/PrimitiveConstant.java @@ -0,0 +1,126 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.consts; + +import java.io.DataOutputStream; +import java.io.IOException; + +/* + * Integer, Long, Float, Double, String, Class, UTF8 + */ + +public class PrimitiveConstant extends PooledConstant { + + // ***************************************************************************** + // public fields + // ***************************************************************************** + + public int index; + + public Object value; + + public boolean isArray; + + // ***************************************************************************** + // constructors + // ***************************************************************************** + + public PrimitiveConstant(int type, Object value) { + this.type = type; + this.value = value; + + initConstant(); + } + + public PrimitiveConstant(int type, int index) { + this.type = type; + this.index = index; + } + + // ***************************************************************************** + // public methods + // ***************************************************************************** + + public int getInt() { + return ((Integer)value).intValue(); + } + + public long getLong() { + return ((Long)value).longValue(); + } + + public float getFloat() { + return ((Float)value).floatValue(); + } + + public double getDouble() { + return ((Double)value).doubleValue(); + } + + public String getString() { + return (String)value; + } + + public void resolveConstant(ConstantPool pool) { + + if (type == CONSTANT_Class || type == CONSTANT_String || type == CONSTANT_MethodType) { + value = pool.getPrimitiveConstant(index).getString(); + initConstant(); + } + } + + public void writeToStream(DataOutputStream out) throws IOException { + + out.writeByte(type); + switch (type) { + case CONSTANT_Integer: + out.writeInt(getInt()); + break; + case CONSTANT_Float: + out.writeFloat(getFloat()); + break; + case CONSTANT_Long: + out.writeLong(getLong()); + break; + case CONSTANT_Double: + out.writeDouble(getDouble()); + break; + case CONSTANT_Utf8: + out.writeUTF(getString()); + break; + default: // CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType + out.writeShort(index); + } + } + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof PrimitiveConstant)) return false; + + PrimitiveConstant cn = (PrimitiveConstant)o; + return this.type == cn.type && + this.isArray == cn.isArray && + this.value.equals(cn.value); + } + + private void initConstant() { + if (type == CONSTANT_Class) { + String className = getString(); + isArray = + (className.length() > 0 && className.charAt(0) == '['); // empty string for a class name seems to be possible in some android files + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/VariableTypeEnum.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/VariableTypeEnum.java new file mode 100644 index 000000000000..7950d5bad47b --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/consts/VariableTypeEnum.java @@ -0,0 +1,47 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.consts; + +public interface VariableTypeEnum { + + int BOOLEAN = 1; + int BYTE = 2; + int CHAR = 3; + int SHORT = 4; + int INT = 5; + int FLOAT = 6; + int LONG = 7; + int DOUBLE = 8; + int RETURN_ADDRESS = 9; + int REFERENCE = 10; + int INSTANCE_UNINITIALIZED = 11; + int VALUE_UNKNOWN = 12; + int VOID = 13; + + Integer BOOLEAN_OBJ = new Integer(BOOLEAN); + Integer BYTE_OBJ = new Integer(BYTE); + Integer CHAR_OBJ = new Integer(CHAR); + Integer SHORT_OBJ = new Integer(SHORT); + Integer INT_OBJ = new Integer(INT); + Integer FLOAT_OBJ = new Integer(FLOAT); + Integer LONG_OBJ = new Integer(LONG); + Integer DOUBLE_OBJ = new Integer(DOUBLE); + Integer RETURN_ADDRESS_OBJ = new Integer(RETURN_ADDRESS); + Integer REFERENCE_OBJ = new Integer(REFERENCE); + Integer INSTANCE_UNINITIALIZED_OBJ = new Integer(INSTANCE_UNINITIALIZED); + Integer VALUE_UNKNOWN_OBJ = new Integer(VALUE_UNKNOWN); + Integer VOID_OBJ = new Integer(VOID); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/DataPoint.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/DataPoint.java new file mode 100644 index 000000000000..65a621308087 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/DataPoint.java @@ -0,0 +1,100 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.util.ListStack; + +import java.util.ArrayList; +import java.util.List; + +public class DataPoint { + + private List<VarType> localVariables = new ArrayList<VarType>(); + + private ListStack<VarType> stack = new ListStack<VarType>(); + + + public void setVariable(int index, VarType value) { + if (index >= localVariables.size()) { + for (int i = localVariables.size(); i <= index; i++) { + localVariables.add(new VarType(CodeConstants.TYPE_NOTINITIALIZED)); + } + } + + localVariables.set(index, value); + } + + public VarType getVariable(int index) { + if (index < localVariables.size()) { + return localVariables.get(index); + } + else if (index < 0) { + throw new IndexOutOfBoundsException(); + } + else { + return new VarType(CodeConstants.TYPE_NOTINITIALIZED); + } + } + + public DataPoint copy() { + DataPoint point = new DataPoint(); + point.setLocalVariables(new ArrayList<VarType>(localVariables)); + point.setStack(stack.clone()); + return point; + } + + public static DataPoint getInitialDataPoint(StructMethod mt) { + + DataPoint point = new DataPoint(); + + MethodDescriptor md = MethodDescriptor.parseDescriptor(mt.getDescriptor()); + + int k = 0; + if (!mt.hasModifier(CodeConstants.ACC_STATIC)) { + point.setVariable(k++, new VarType(CodeConstants.TYPE_OBJECT, 0, null)); + } + + for (int i = 0; i < md.params.length; i++) { + VarType var = md.params[i]; + + point.setVariable(k++, var); + if (var.stack_size == 2) { + point.setVariable(k++, new VarType(CodeConstants.TYPE_GROUP2EMPTY)); + } + } + + return point; + } + + + public List<VarType> getLocalVariables() { + return localVariables; + } + + public void setLocalVariables(List<VarType> localVariables) { + this.localVariables = localVariables; + } + + public ListStack<VarType> getStack() { + return stack; + } + + public void setStack(ListStack<VarType> stack) { + this.stack = stack; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/FieldDescriptor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/FieldDescriptor.java new file mode 100644 index 000000000000..fd213f05293a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/FieldDescriptor.java @@ -0,0 +1,59 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen; + +public class FieldDescriptor { + + public static final FieldDescriptor INTEGER_DESCRIPTOR = parseDescriptor("Ljava/lang/Integer;"); + public static final FieldDescriptor LONG_DESCRIPTOR = parseDescriptor("Ljava/lang/Long;"); + public static final FieldDescriptor FLOAT_DESCRIPTOR = parseDescriptor("Ljava/lang/Float;"); + public static final FieldDescriptor DOUBLE_DESCRIPTOR = parseDescriptor("Ljava/lang/Double;"); + + public VarType type; + + public String descriptorString; + + private FieldDescriptor() { + } + + public static FieldDescriptor parseDescriptor(String descr) { + + FieldDescriptor fd = new FieldDescriptor(); + + fd.type = new VarType(descr); + fd.descriptorString = descr; + + return fd; + } + + public String getDescriptor() { + return type.toString(); + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof FieldDescriptor)) return false; + + FieldDescriptor fd = (FieldDescriptor)o; + return type.equals(fd.type); + } + + @Override + public int hashCode() { + return type.hashCode(); + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/MethodDescriptor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/MethodDescriptor.java new file mode 100644 index 000000000000..7dbc16c317f2 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/MethodDescriptor.java @@ -0,0 +1,102 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class MethodDescriptor { + + public VarType[] params; + + public VarType ret; + + + public static MethodDescriptor parseDescriptor(String mdescr) { + + MethodDescriptor md = new MethodDescriptor(); + + List<String> lst = new ArrayList<String>(); + String[] pars = mdescr.split("[()]"); + + String par = pars[1]; + + int indexFrom = -1, ind, index = 0; + int len = par.length(); + + for (; index < len; index++) { + + switch (par.charAt(index)) { + case '[': + if (indexFrom < 0) { + indexFrom = index; + } + break; + case 'L': + ind = par.indexOf(";", index); + lst.add(par.substring(indexFrom < 0 ? index : indexFrom, ind + 1)); + index = ind; + indexFrom = -1; + break; + default: + lst.add(par.substring(indexFrom < 0 ? index : indexFrom, index + 1)); + indexFrom = -1; + } + } + + lst.add(pars[2]); + + + md.params = new VarType[lst.size() - 1]; + + int i = 0; + for (; i < lst.size() - 1; i++) { + md.params[i] = new VarType(lst.get(i)); + } + md.ret = new VarType(lst.get(i)); + + return md; + } + + public String getDescriptor() { + String res = "("; + + for (int j = 0; j < params.length; j++) { + res += params[j].toString(); + } + + res += ")" + ret.toString(); + + return res; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof MethodDescriptor)) return false; + + MethodDescriptor md = (MethodDescriptor)o; + return ret.equals(md.ret) && Arrays.equals(params, md.params); + } + + @Override + public int hashCode() { + int result = ret.hashCode(); + result = 31 * result + params.length; + return result; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/VarType.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/VarType.java new file mode 100644 index 000000000000..a58898a1906d --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/VarType.java @@ -0,0 +1,422 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.util.InterpreterUtil; + +public class VarType { // TODO: optimize switch + + public static final int FALSEBOOLEAN = 1; + + public static final VarType VARTYPE_UNKNOWN = new VarType(CodeConstants.TYPE_UNKNOWN); + public static final VarType VARTYPE_INT = new VarType(CodeConstants.TYPE_INT); + public static final VarType VARTYPE_FLOAT = new VarType(CodeConstants.TYPE_FLOAT); + public static final VarType VARTYPE_LONG = new VarType(CodeConstants.TYPE_LONG); + public static final VarType VARTYPE_DOUBLE = new VarType(CodeConstants.TYPE_DOUBLE); + public static final VarType VARTYPE_BYTE = new VarType(CodeConstants.TYPE_BYTE); + public static final VarType VARTYPE_CHAR = new VarType(CodeConstants.TYPE_CHAR); + public static final VarType VARTYPE_SHORT = new VarType(CodeConstants.TYPE_SHORT); + public static final VarType VARTYPE_BOOLEAN = new VarType(CodeConstants.TYPE_BOOLEAN); + public static final VarType VARTYPE_BYTECHAR = new VarType(CodeConstants.TYPE_BYTECHAR); + public static final VarType VARTYPE_SHORTCHAR = new VarType(CodeConstants.TYPE_SHORTCHAR); + + public static final VarType VARTYPE_NULL = new VarType(CodeConstants.TYPE_NULL, 0, null); + public static final VarType VARTYPE_GROUP2EMPTY = new VarType(CodeConstants.TYPE_GROUP2EMPTY); + public static final VarType VARTYPE_STRING = new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/String"); + public static final VarType VARTYPE_CLASS = new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/Class"); + public static final VarType VARTYPE_OBJECT = new VarType(CodeConstants.TYPE_OBJECT, 0, "java/lang/Object"); + public static final VarType VARTYPE_VOID = new VarType(CodeConstants.TYPE_VOID); + + public int type; + + public int type_family; + + public int arraydim; + + public String value; + + public int stack_size; + + public int convinfo; + + public VarType(int type) { + this.type = type; + this.arraydim = 0; + + value = getChar(type); + setStackSize(type); + setFamily(); + } + + public VarType(int type, int arraydim) { + this(type); + this.arraydim = arraydim; + setFamily(); + } + + public VarType(int type, int arraydim, String value) { + this(type); + this.arraydim = arraydim; + this.value = value; + setFamily(); + } + + public VarType(String strtype) { + this(strtype, false); + } + + public VarType(String strtype, boolean cltype) { + parseTypeString(strtype, cltype); + setStackSize(type); + setFamily(); + } + + public void decArrayDim() { + if (arraydim > 0) { + arraydim--; + setFamily(); + } + else { + // throw new RuntimeException("array dimension equals 0!"); FIXME: investigate this case + } + } + + public String toString() { + String res = ""; + + for (int i = 0; i < arraydim; i++) { + res += "["; + } + + if (type == CodeConstants.TYPE_OBJECT) { + res += "L" + value + ";"; + } + else { + res += value; + } + + return res; + } + + public VarType copy() { + VarType v = new VarType(type, arraydim, value); + v.convinfo = convinfo; + return v; + } + + public boolean isFalseBoolean() { + return (convinfo & FALSEBOOLEAN) != 0; + } + + public boolean isSuperset(VarType val) { + + return this.equals(val) || this.isStrictSuperset(val); + } + + public boolean isStrictSuperset(VarType val) { + + int valtype = val.type; + + if (valtype == CodeConstants.TYPE_UNKNOWN && type != CodeConstants.TYPE_UNKNOWN) { + return true; + } + + if (val.arraydim > 0) { + return this.equals(VARTYPE_OBJECT); + } + else if (arraydim > 0) { + return (valtype == CodeConstants.TYPE_NULL); + } + + boolean res = false; + + switch (type) { + case CodeConstants.TYPE_INT: + res |= (valtype == CodeConstants.TYPE_SHORT || + valtype == CodeConstants.TYPE_CHAR); + case CodeConstants.TYPE_SHORT: + res |= (valtype == CodeConstants.TYPE_BYTE); + case CodeConstants.TYPE_CHAR: + res |= (valtype == CodeConstants.TYPE_SHORTCHAR); + case CodeConstants.TYPE_BYTE: + case CodeConstants.TYPE_SHORTCHAR: + res |= (valtype == CodeConstants.TYPE_BYTECHAR); + case CodeConstants.TYPE_BYTECHAR: + res |= (valtype == CodeConstants.TYPE_BOOLEAN); + break; + case CodeConstants.TYPE_OBJECT: + if (valtype == CodeConstants.TYPE_NULL) { + return true; + } + else if (this.equals(VARTYPE_OBJECT)) { + return valtype == CodeConstants.TYPE_OBJECT && + !val.equals(VARTYPE_OBJECT); + } + } + + return res; + } + + // type1 and type2 must not be null + public static VarType getCommonMinType(VarType type1, VarType type2) { + + if (type1.type == CodeConstants.TYPE_BOOLEAN && type2.type == CodeConstants.TYPE_BOOLEAN) { // special case booleans + return type1.isFalseBoolean() ? type2 : type1; + } + + if (type1.isSuperset(type2)) { + return type2; + } + else if (type2.isSuperset(type1)) { + return type1; + } + else if (type1.type_family == type2.type_family) { + switch (type1.type_family) { + case CodeConstants.TYPE_FAMILY_INTEGER: + if ((type1.type == CodeConstants.TYPE_CHAR && type2.type == CodeConstants.TYPE_SHORT) + || (type1.type == CodeConstants.TYPE_SHORT && type2.type == CodeConstants.TYPE_CHAR)) { + return VARTYPE_SHORTCHAR; + } + else { + return VARTYPE_BYTECHAR; + } + case CodeConstants.TYPE_FAMILY_OBJECT: + return VARTYPE_NULL; + } + } + + return null; + } + + // type1 and type2 must not be null + public static VarType getCommonSupertype(VarType type1, VarType type2) { + + if (type1.type == CodeConstants.TYPE_BOOLEAN && type2.type == CodeConstants.TYPE_BOOLEAN) { // special case booleans + return type1.isFalseBoolean() ? type1 : type2; + } + + if (type1.isSuperset(type2)) { + return type1; + } + else if (type2.isSuperset(type1)) { + return type2; + } + else if (type1.type_family == type2.type_family) { + switch (type1.type_family) { + case CodeConstants.TYPE_FAMILY_INTEGER: + if ((type1.type == CodeConstants.TYPE_SHORTCHAR && type2.type == CodeConstants.TYPE_BYTE) + || (type1.type == CodeConstants.TYPE_BYTE && type2.type == CodeConstants.TYPE_SHORTCHAR)) { + return VARTYPE_SHORT; + } + else { + return VARTYPE_INT; + } + case CodeConstants.TYPE_FAMILY_OBJECT: + return VARTYPE_OBJECT; + } + } + + return null; + } + + public static VarType getMinTypeInFamily(int family) { + switch (family) { + case CodeConstants.TYPE_FAMILY_BOOLEAN: + return VARTYPE_BOOLEAN; + case CodeConstants.TYPE_FAMILY_INTEGER: + return VARTYPE_BYTECHAR; + case CodeConstants.TYPE_FAMILY_OBJECT: + return VARTYPE_NULL; + case CodeConstants.TYPE_FAMILY_FLOAT: + return VARTYPE_FLOAT; + case CodeConstants.TYPE_FAMILY_LONG: + return VARTYPE_LONG; + case CodeConstants.TYPE_FAMILY_DOUBLE: + return VARTYPE_DOUBLE; + case CodeConstants.TYPE_FAMILY_UNKNOWN: + return VARTYPE_UNKNOWN; + default: + throw new RuntimeException("invalid type family!"); + } + } + + public boolean equals(Object o) { + + if (o == this) { + return true; + } + + if (o == null || !(o instanceof VarType)) { + return false; + } + + VarType vt = (VarType)o; + return type == vt.type && arraydim == vt.arraydim && InterpreterUtil.equalObjects(value, vt.value); + } + + private void parseTypeString(String strtype, boolean cltype) { + + for (int i = 0; i < strtype.length(); i++) { + switch (strtype.charAt(i)) { + case '[': + arraydim++; + break; + case 'L': + if (strtype.charAt(strtype.length() - 1) == ';') { + type = CodeConstants.TYPE_OBJECT; + value = strtype.substring(i + 1, strtype.length() - 1); + return; + } + default: + value = strtype.substring(i, strtype.length()); + if ((cltype && i == 0) || value.length() > 1) { + type = CodeConstants.TYPE_OBJECT; + } + else { + type = getType(value.charAt(0)); + } + return; + } + } + } + + private void setStackSize(int type) { + if (arraydim > 0) { + stack_size = 1; + } + else { + stack_size = (type == CodeConstants.TYPE_DOUBLE || + type == CodeConstants.TYPE_LONG) ? 2 : + ((type == CodeConstants.TYPE_VOID || + type == CodeConstants.TYPE_GROUP2EMPTY) ? 0 : 1); + } + } + + private static int getType(char c) { + switch (c) { + case 'B': + return CodeConstants.TYPE_BYTE; + case 'C': + return CodeConstants.TYPE_CHAR; + case 'D': + return CodeConstants.TYPE_DOUBLE; + case 'F': + return CodeConstants.TYPE_FLOAT; + case 'I': + return CodeConstants.TYPE_INT; + case 'J': + return CodeConstants.TYPE_LONG; + case 'S': + return CodeConstants.TYPE_SHORT; + case 'Z': + return CodeConstants.TYPE_BOOLEAN; + case 'V': + return CodeConstants.TYPE_VOID; + case 'G': + return CodeConstants.TYPE_GROUP2EMPTY; + case 'N': + return CodeConstants.TYPE_NOTINITIALIZED; + case 'A': + return CodeConstants.TYPE_ADDRESS; + case 'X': + return CodeConstants.TYPE_BYTECHAR; + case 'Y': + return CodeConstants.TYPE_SHORTCHAR; + case 'U': + return CodeConstants.TYPE_UNKNOWN; + default: + throw new RuntimeException("Invalid type"); + } + } + + private static String getChar(int type) { + switch (type) { + case CodeConstants.TYPE_BYTE: + return "B"; + case CodeConstants.TYPE_CHAR: + return "C"; + case CodeConstants.TYPE_DOUBLE: + return "D"; + case CodeConstants.TYPE_FLOAT: + return "F"; + case CodeConstants.TYPE_INT: + return "I"; + case CodeConstants.TYPE_LONG: + return "J"; + case CodeConstants.TYPE_SHORT: + return "S"; + case CodeConstants.TYPE_BOOLEAN: + return "Z"; + case CodeConstants.TYPE_VOID: + return "V"; + case CodeConstants.TYPE_GROUP2EMPTY: + return "G"; + case CodeConstants.TYPE_NOTINITIALIZED: + return "N"; + case CodeConstants.TYPE_ADDRESS: + return "A"; + case CodeConstants.TYPE_BYTECHAR: + return "X"; + case CodeConstants.TYPE_SHORTCHAR: + return "Y"; + case CodeConstants.TYPE_UNKNOWN: + return "U"; + case CodeConstants.TYPE_NULL: + case CodeConstants.TYPE_OBJECT: + return null; + default: + throw new RuntimeException("Invalid type"); + } + } + + public void setFamily() { + + if (arraydim > 0) { + this.type_family = CodeConstants.TYPE_FAMILY_OBJECT; + return; + } + + switch (type) { + case CodeConstants.TYPE_BYTE: + case CodeConstants.TYPE_BYTECHAR: + case CodeConstants.TYPE_SHORTCHAR: + case CodeConstants.TYPE_CHAR: + case CodeConstants.TYPE_SHORT: + case CodeConstants.TYPE_INT: + this.type_family = CodeConstants.TYPE_FAMILY_INTEGER; + break; + case CodeConstants.TYPE_DOUBLE: + this.type_family = CodeConstants.TYPE_FAMILY_DOUBLE; + break; + case CodeConstants.TYPE_FLOAT: + this.type_family = CodeConstants.TYPE_FAMILY_FLOAT; + break; + case CodeConstants.TYPE_LONG: + this.type_family = CodeConstants.TYPE_FAMILY_LONG; + break; + case CodeConstants.TYPE_BOOLEAN: + this.type_family = CodeConstants.TYPE_FAMILY_BOOLEAN; + break; + case CodeConstants.TYPE_NULL: + case CodeConstants.TYPE_OBJECT: + this.type_family = CodeConstants.TYPE_FAMILY_OBJECT; + break; + default: + this.type_family = CodeConstants.TYPE_FAMILY_UNKNOWN; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericClassDescriptor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericClassDescriptor.java new file mode 100644 index 000000000000..66fab96d35c3 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericClassDescriptor.java @@ -0,0 +1,30 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen.generics; + +import java.util.ArrayList; +import java.util.List; + +public class GenericClassDescriptor { + + public GenericType superclass; + + public List<GenericType> superinterfaces = new ArrayList<GenericType>(); + + public List<String> fparameters = new ArrayList<String>(); + + public List<List<GenericType>> fbounds = new ArrayList<List<GenericType>>(); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericFieldDescriptor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericFieldDescriptor.java new file mode 100644 index 000000000000..598d17bef2d0 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericFieldDescriptor.java @@ -0,0 +1,21 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen.generics; + +public class GenericFieldDescriptor { + + public GenericType type; +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericMain.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericMain.java new file mode 100644 index 000000000000..3082ecaf9ddd --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericMain.java @@ -0,0 +1,249 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen.generics; + +import org.jetbrains.java.decompiler.code.CodeConstants; +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerLogger; +import org.jetbrains.java.decompiler.struct.StructClass; + +import java.util.ArrayList; +import java.util.List; + +public class GenericMain { + + private static final String[] typeNames = { + "byte", + "char", + "double", + "float", + "int", + "long", + "short", + "boolean", + }; + + public static GenericClassDescriptor parseClassSignature(String signature) { + String original = signature; + try { + GenericClassDescriptor descriptor = new GenericClassDescriptor(); + + signature = parseFormalParameters(signature, descriptor.fparameters, descriptor.fbounds); + + String superCl = GenericType.getNextType(signature); + descriptor.superclass = new GenericType(superCl); + + signature = signature.substring(superCl.length()); + while (signature.length() > 0) { + String superIf = GenericType.getNextType(signature); + descriptor.superinterfaces.add(new GenericType(superIf)); + signature = signature.substring(superIf.length()); + } + + return descriptor; + } + catch (RuntimeException e) { + DecompilerContext.getLogger().writeMessage("Invalid signature: " + original, IFernflowerLogger.Severity.WARN); + return null; + } + } + + public static GenericFieldDescriptor parseFieldSignature(String signature) { + try { + GenericFieldDescriptor descriptor = new GenericFieldDescriptor(); + descriptor.type = new GenericType(signature); + return descriptor; + } + catch (RuntimeException e) { + DecompilerContext.getLogger().writeMessage("Invalid signature: " + signature, IFernflowerLogger.Severity.WARN); + return null; + } + } + + public static GenericMethodDescriptor parseMethodSignature(String signature) { + String original = signature; + try { + GenericMethodDescriptor descriptor = new GenericMethodDescriptor(); + + signature = parseFormalParameters(signature, descriptor.fparameters, descriptor.fbounds); + + int to = signature.indexOf(")"); + String pars = signature.substring(1, to); + signature = signature.substring(to + 1); + + while (pars.length() > 0) { + String par = GenericType.getNextType(pars); + descriptor.params.add(new GenericType(par)); + pars = pars.substring(par.length()); + } + + String par = GenericType.getNextType(signature); + descriptor.ret = new GenericType(par); + signature = signature.substring(par.length()); + + if (signature.length() > 0) { + String[] exceptions = signature.split("\\^"); + + for (int i = 1; i < exceptions.length; i++) { + descriptor.exceptions.add(new GenericType(exceptions[i])); + } + } + + return descriptor; + } + catch (RuntimeException e) { + DecompilerContext.getLogger().writeMessage("Invalid signature: " + original, IFernflowerLogger.Severity.WARN); + return null; + } + } + + private static String parseFormalParameters(String signature, List<String> parameters, List<List<GenericType>> bounds) { + if (signature.charAt(0) != '<') { + return signature; + } + + int counter = 1; + int index = 1; + + loop: + while (index < signature.length()) { + switch (signature.charAt(index)) { + case '<': + counter++; + break; + case '>': + counter--; + if (counter == 0) { + break loop; + } + } + + index++; + } + + String value = signature.substring(1, index); + signature = signature.substring(index + 1); + + while (value.length() > 0) { + int to = value.indexOf(":"); + + String param = value.substring(0, to); + value = value.substring(to + 1); + + List<GenericType> lstBounds = new ArrayList<GenericType>(); + + while (true) { + if (value.charAt(0) == ':') { + // empty superclass, skip + value = value.substring(1); + } + + String bound = GenericType.getNextType(value); + lstBounds.add(new GenericType(bound)); + value = value.substring(bound.length()); + + + if (value.length() == 0 || value.charAt(0) != ':') { + break; + } + else { + value = value.substring(1); + } + } + + parameters.add(param); + bounds.add(lstBounds); + } + + return signature; + } + + public static String getGenericCastTypeName(GenericType type) { + String s = getTypeName(type); + int dim = type.arraydim; + while (dim-- > 0) { + s += "[]"; + } + return s; + } + + private static String getTypeName(GenericType type) { + int tp = type.type; + if (tp <= CodeConstants.TYPE_BOOLEAN) { + return typeNames[tp]; + } + else if (tp == CodeConstants.TYPE_VOID) { + return "void"; + } + else if (tp == CodeConstants.TYPE_GENVAR) { + return type.value; + } + else if (tp == CodeConstants.TYPE_OBJECT) { + StringBuilder buffer = new StringBuilder(); + buffer.append(DecompilerContext.getImportCollector().getShortName(buildJavaClassName(type))); + + if (!type.getArguments().isEmpty()) { + buffer.append("<"); + for (int i = 0; i < type.getArguments().size(); i++) { + if (i > 0) { + buffer.append(", "); + } + int wildcard = type.getWildcards().get(i); + if (wildcard != GenericType.WILDCARD_NO) { + buffer.append("?"); + + switch (wildcard) { + case GenericType.WILDCARD_EXTENDS: + buffer.append(" extends "); + break; + case GenericType.WILDCARD_SUPER: + buffer.append(" super "); + } + } + + GenericType genPar = type.getArguments().get(i); + if (genPar != null) { + buffer.append(getGenericCastTypeName(genPar)); + } + } + buffer.append(">"); + } + + return buffer.toString(); + } + + throw new RuntimeException("Invalid type: " + type); + } + + private static String buildJavaClassName(GenericType type) { + String name = ""; + for (GenericType tp : type.getEnclosingClasses()) { + name += tp.value + "$"; + } + name += type.value; + + String res = name.replace('/', '.'); + + if (res.contains("$")) { + StructClass cl = DecompilerContext.getStructContext().getClass(name); + if (cl == null || !cl.isOwn()) { + res = res.replace('$', '.'); + } + } + + return res; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericMethodDescriptor.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericMethodDescriptor.java new file mode 100644 index 000000000000..7b4c9dc381f1 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericMethodDescriptor.java @@ -0,0 +1,32 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen.generics; + +import java.util.ArrayList; +import java.util.List; + +public class GenericMethodDescriptor { + + public List<String> fparameters = new ArrayList<String>(); + + public List<List<GenericType>> fbounds = new ArrayList<List<GenericType>>(); + + public List<GenericType> params = new ArrayList<GenericType>(); + + public GenericType ret; + + public List<GenericType> exceptions = new ArrayList<GenericType>(); +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericType.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericType.java new file mode 100644 index 000000000000..160a0ac46035 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/gen/generics/GenericType.java @@ -0,0 +1,268 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.gen.generics; + +import org.jetbrains.java.decompiler.code.CodeConstants; + +import java.util.ArrayList; +import java.util.List; + +public class GenericType { + + public static final int WILDCARD_EXTENDS = 1; + public static final int WILDCARD_SUPER = 2; + public static final int WILDCARD_UNBOUND = 3; + public static final int WILDCARD_NO = 4; + + public int type; + + public int arraydim; + + public String value; + + + private List<GenericType> enclosingClasses = new ArrayList<GenericType>(); + + private List<GenericType> arguments = new ArrayList<GenericType>(); + + private List<Integer> wildcards = new ArrayList<Integer>(); + + + public GenericType(int type, int arraydim, String value) { + this.type = type; + this.arraydim = arraydim; + this.value = value; + } + + + public GenericType(String strtype) { + + parseSignature(strtype); + } + + private void parseSignature(String sig) { + + int index = 0; + while (index < sig.length()) { + + switch (sig.charAt(index)) { + case '[': + arraydim++; + break; + case 'T': + type = CodeConstants.TYPE_GENVAR; + value = sig.substring(index + 1, sig.length() - 1); + return; + case 'L': + type = CodeConstants.TYPE_OBJECT; + sig = sig.substring(index + 1, sig.length() - 1); + + while (true) { + String cl = getNextClassSignature(sig); + + String name = cl; + String args = null; + + int argfrom = cl.indexOf("<"); + if (argfrom >= 0) { + name = cl.substring(0, argfrom); + args = cl.substring(argfrom + 1, cl.length() - 1); + } + + if (cl.length() < sig.length()) { + sig = sig.substring(cl.length() + 1); // skip '.' + GenericType type = new GenericType(CodeConstants.TYPE_OBJECT, 0, name); + parseArgumentsList(args, type); + enclosingClasses.add(type); + } + else { + value = name; + parseArgumentsList(args, this); + break; + } + } + + return; + default: + value = sig.substring(index, index + 1); + type = getType(value.charAt(0)); + } + + index++; + } + } + + private static String getNextClassSignature(String value) { + + int counter = 0; + int index = 0; + + loop: + while (index < value.length()) { + switch (value.charAt(index)) { + case '<': + counter++; + break; + case '>': + counter--; + break; + case '.': + if (counter == 0) { + break loop; + } + } + + index++; + } + + return value.substring(0, index); + } + + private static void parseArgumentsList(String value, GenericType type) { + + if (value == null) { + return; + } + + while (value.length() > 0) { + + String tstr = getNextType(value); + int len = tstr.length(); + int wildcard = WILDCARD_NO; + + switch (tstr.charAt(0)) { + case '*': + wildcard = WILDCARD_UNBOUND; + break; + case '+': + wildcard = WILDCARD_EXTENDS; + break; + case '-': + wildcard = WILDCARD_SUPER; + break; + } + + type.getWildcards().add(wildcard); + + if (wildcard != WILDCARD_NO) { + tstr = tstr.substring(1); + } + + type.getArguments().add(tstr.length() == 0 ? null : new GenericType(tstr)); + + value = value.substring(len); + } + } + + public static String getNextType(String value) { + + int counter = 0; + int index = 0; + + boolean contmode = false; + + loop: + while (index < value.length()) { + switch (value.charAt(index)) { + case '*': + if (!contmode) { + break loop; + } + break; + case 'L': + case 'T': + if (!contmode) { + contmode = true; + } + case '[': + case '+': + case '-': + break; + default: + if (!contmode) { + break loop; + } + break; + case '<': + counter++; + break; + case '>': + counter--; + break; + case ';': + if (counter == 0) { + break loop; + } + } + + index++; + } + + return value.substring(0, index + 1); + } + + private static int getType(char c) { + switch (c) { + case 'B': + return CodeConstants.TYPE_BYTE; + case 'C': + return CodeConstants.TYPE_CHAR; + case 'D': + return CodeConstants.TYPE_DOUBLE; + case 'F': + return CodeConstants.TYPE_FLOAT; + case 'I': + return CodeConstants.TYPE_INT; + case 'J': + return CodeConstants.TYPE_LONG; + case 'S': + return CodeConstants.TYPE_SHORT; + case 'Z': + return CodeConstants.TYPE_BOOLEAN; + case 'V': + return CodeConstants.TYPE_VOID; + case 'G': + return CodeConstants.TYPE_GROUP2EMPTY; + case 'N': + return CodeConstants.TYPE_NOTINITIALIZED; + case 'A': + return CodeConstants.TYPE_ADDRESS; + case 'X': + return CodeConstants.TYPE_BYTECHAR; + case 'Y': + return CodeConstants.TYPE_SHORTCHAR; + case 'U': + return CodeConstants.TYPE_UNKNOWN; + default: + throw new RuntimeException("Invalid type"); + } + } + + + public List<GenericType> getArguments() { + return arguments; + } + + + public List<GenericType> getEnclosingClasses() { + return enclosingClasses; + } + + + public List<Integer> getWildcards() { + return wildcards; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/lazy/LazyLoader.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/lazy/LazyLoader.java new file mode 100644 index 000000000000..70254d82977a --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/struct/lazy/LazyLoader.java @@ -0,0 +1,173 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.struct.lazy; + +import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider; +import org.jetbrains.java.decompiler.struct.StructMethod; +import org.jetbrains.java.decompiler.struct.attr.StructGeneralAttribute; +import org.jetbrains.java.decompiler.struct.consts.ConstantPool; +import org.jetbrains.java.decompiler.util.DataInputFullStream; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class LazyLoader { + + private final Map<String, Link> mapClassLinks = new HashMap<String, Link>(); + private final IBytecodeProvider provider; + + public LazyLoader(IBytecodeProvider provider) { + this.provider = provider; + } + + public void addClassLink(String classname, Link link) { + mapClassLinks.put(classname, link); + } + + public void removeClassLink(String classname) { + mapClassLinks.remove(classname); + } + + public Link getClassLink(String classname) { + return mapClassLinks.get(classname); + } + + public ConstantPool loadPool(String classname) { + try { + DataInputFullStream in = getClassStream(classname); + if (in == null) return null; + + try { + in.discard(8); + return new ConstantPool(in); + } + finally { + in.close(); + } + } + catch (IOException ex) { + throw new RuntimeException(ex); + } + } + + public byte[] loadBytecode(StructMethod mt, int codeFullLength) { + String className = mt.getClassStruct().qualifiedName; + + try { + DataInputFullStream in = getClassStream(className); + if (in == null) return null; + + try { + in.discard(8); + + ConstantPool pool = mt.getClassStruct().getPool(); + if (pool == null) { + pool = new ConstantPool(in); + } + else { + ConstantPool.skipPool(in); + } + + in.discard(6); + + // interfaces + in.discard(in.readUnsignedShort() * 2); + + // fields + int size = in.readUnsignedShort(); + for (int i = 0; i < size; i++) { + in.discard(6); + skipAttributes(in); + } + + // methods + size = in.readUnsignedShort(); + for (int i = 0; i < size; i++) { + in.discard(2); + + int nameIndex = in.readUnsignedShort(); + int descriptorIndex = in.readUnsignedShort(); + + String[] values = pool.getClassElement(ConstantPool.METHOD, className, nameIndex, descriptorIndex); + if (!mt.getName().equals(values[0]) || !mt.getDescriptor().equals(values[1])) { + skipAttributes(in); + continue; + } + + int attrSize = in.readUnsignedShort(); + for (int j = 0; j < attrSize; j++) { + int attrNameIndex = in.readUnsignedShort(); + String attrName = pool.getPrimitiveConstant(attrNameIndex).getString(); + if (!StructGeneralAttribute.ATTRIBUTE_CODE.equals(attrName)) { + in.discard(in.readInt()); + continue; + } + + in.discard(12); + byte[] code = new byte[codeFullLength]; + in.readFull(code); + return code; + } + + break; + } + } + finally { + in.close(); + } + + return null; + } + catch (IOException ex) { + throw new RuntimeException(ex); + } + } + + public DataInputFullStream getClassStream(String externalPath, String internalPath) throws IOException { + byte[] bytes = provider.getBytecode(externalPath, internalPath); + return new DataInputFullStream(bytes); + } + + public DataInputFullStream getClassStream(String qualifiedClassName) throws IOException { + Link link = mapClassLinks.get(qualifiedClassName); + return link == null ? null : getClassStream(link.externalPath, link.internalPath); + } + + public static void skipAttributes(DataInputFullStream in) throws IOException { + int length = in.readUnsignedShort(); + for (int i = 0; i < length; i++) { + in.discard(2); + in.discard(in.readInt()); + } + } + + + public static class Link { + public static final int CLASS = 1; + public static final int ENTRY = 2; + + public int type; + public String externalPath; + public String internalPath; + + public Link(int type, String externalPath, String internalPath) { + this.type = type; + this.externalPath = externalPath; + this.internalPath = internalPath; + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/DataInputFullStream.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/DataInputFullStream.java new file mode 100644 index 000000000000..011eddea5c92 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/DataInputFullStream.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; + +public class DataInputFullStream extends DataInputStream { + + public DataInputFullStream(byte[] bytes) { + super(new ByteArrayInputStream(bytes)); + } + + public int readFull(byte[] b) throws IOException { + int length = b.length; + byte[] temp = new byte[length]; + int pos = 0; + + int bytes_read; + while (true) { + bytes_read = read(temp, 0, length - pos); + if (bytes_read == -1) { + return -1; + } + + System.arraycopy(temp, 0, b, pos, bytes_read); + pos += bytes_read; + if (pos == length) { + break; + } + } + + return length; + } + + public void discard(int n) throws IOException { + if (super.skip(n) != n) { + throw new IOException("Skip failed"); + } + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastFixedSetFactory.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastFixedSetFactory.java new file mode 100644 index 000000000000..a26b77e95ad7 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastFixedSetFactory.java @@ -0,0 +1,360 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import java.util.*; + +public class FastFixedSetFactory<E> { + + private VBStyleCollection<int[], E> colValuesInternal = new VBStyleCollection<int[], E>(); + + private int dataLength; + + public FastFixedSetFactory(Collection<E> set) { + + dataLength = set.size() / 32 + 1; + + int index = 0; + int mask = 1; + + for (E element : set) { + + int block = index / 32; + + if (index % 32 == 0) { + mask = 1; + } + + colValuesInternal.putWithKey(new int[]{block, mask}, element); + + index++; + mask <<= 1; + } + } + + public FastFixedSet<E> spawnEmptySet() { + return new FastFixedSet<E>(this); + } + + private int getDataLength() { + return dataLength; + } + + private VBStyleCollection<int[], E> getInternalValuesCollection() { + return colValuesInternal; + } + + public static class FastFixedSet<E> implements Iterable<E> { + + private FastFixedSetFactory<E> factory; + + private VBStyleCollection<int[], E> colValuesInternal; + + private int[] data; + + + private FastFixedSet(FastFixedSetFactory<E> factory) { + this.factory = factory; + this.colValuesInternal = factory.getInternalValuesCollection(); + this.data = new int[factory.getDataLength()]; + } + + public FastFixedSet<E> getCopy() { + + FastFixedSet<E> copy = new FastFixedSet<E>(factory); + + int arrlength = data.length; + int[] cpdata = new int[arrlength]; + System.arraycopy(data, 0, cpdata, 0, arrlength); + copy.setData(cpdata); + + return copy; + } + + public void setAllElements() { + + int[] lastindex = colValuesInternal.get(colValuesInternal.size() - 1); + + for (int i = lastindex[0] - 1; i >= 0; i--) { + data[i] = 0xFFFFFFFF; + } + + data[lastindex[0]] = lastindex[1] | (lastindex[1] - 1); + } + + public void add(E element) { + int[] index = colValuesInternal.getWithKey(element); + data[index[0]] |= index[1]; + } + + public void addAll(Collection<E> set) { + for (E element : set) { + add(element); + } + } + + public void remove(E element) { + int[] index = colValuesInternal.getWithKey(element); + data[index[0]] &= ~index[1]; + } + + public void removeAll(Collection<E> set) { + for (E element : set) { + remove(element); + } + } + + public boolean contains(E element) { + int[] index = colValuesInternal.getWithKey(element); + return (data[index[0]] & index[1]) != 0; + } + + public boolean contains(FastFixedSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + if ((extdata[i] & ~intdata[i]) != 0) { + return false; + } + } + + return true; + } + + public void union(FastFixedSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + intdata[i] |= extdata[i]; + } + } + + public void intersection(FastFixedSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + intdata[i] &= extdata[i]; + } + } + + public void symdiff(FastFixedSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + intdata[i] ^= extdata[i]; + } + } + + public void complement(FastFixedSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + intdata[i] &= ~extdata[i]; + } + } + + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof FastFixedSet)) return false; + + int[] extdata = ((FastFixedSet)o).getData(); + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + if (intdata[i] != extdata[i]) { + return false; + } + } + + return true; + } + + public boolean isEmpty() { + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + if (intdata[i] != 0) { + return false; + } + } + + return true; + } + + public Iterator<E> iterator() { + return new FastFixedSetIterator<E>(this); + } + + public Set<E> toPlainSet() { + return toPlainCollection(new HashSet<E>()); + } + + public List<E> toPlainList() { + return toPlainCollection(new ArrayList<E>()); + } + + + private <T extends Collection<E>> T toPlainCollection(T cl) { + + int[] intdata = data; + for (int bindex = 0; bindex < intdata.length; bindex++) { + int block = intdata[bindex]; + if (block != 0) { + int index = bindex << 5; // * 32 + for (int i = 31; i >= 0; i--) { + if ((block & 1) != 0) { + cl.add(colValuesInternal.getKey(index)); + } + index++; + block >>>= 1; + } + } + } + + return cl; + } + + public String toBinary() { + + StringBuilder buffer = new StringBuilder(); + int[] intdata = data; + + for (int i = 0; i < intdata.length; i++) { + buffer.append(" ").append(Integer.toBinaryString(intdata[i])); + } + + return buffer.toString(); + } + + public String toString() { + + StringBuilder buffer = new StringBuilder("{"); + + int[] intdata = data; + boolean first = true; + + for (int i = colValuesInternal.size() - 1; i >= 0; i--) { + int[] index = colValuesInternal.get(i); + + if ((intdata[index[0]] & index[1]) != 0) { + if (first) { + first = false; + } + else { + buffer.append(","); + } + buffer.append(colValuesInternal.getKey(i)); + } + } + + buffer.append("}"); + + return buffer.toString(); + } + + private int[] getData() { + return data; + } + + private void setData(int[] data) { + this.data = data; + } + + public FastFixedSetFactory<E> getFactory() { + return factory; + } + } + + public static class FastFixedSetIterator<E> implements Iterator<E> { + + private VBStyleCollection<int[], E> colValuesInternal; + private int[] data; + private int size; + + private int pointer = -1; + private int next_pointer = -1; + + private FastFixedSetIterator(FastFixedSet<E> set) { + colValuesInternal = set.getFactory().getInternalValuesCollection(); + data = set.getData(); + size = colValuesInternal.size(); + } + + private int getNextIndex(int index) { + + index++; + int ret = index; + int bindex = index / 32; + int dindex = index % 32; + + while (bindex < data.length) { + int block = data[bindex]; + + if (block != 0) { + block >>>= dindex; + while (dindex < 32) { + if ((block & 1) != 0) { + return ret; + } + block >>>= 1; + dindex++; + ret++; + } + } + else { + ret += (32 - dindex); + } + + dindex = 0; + bindex++; + } + + return -1; + } + + public boolean hasNext() { + next_pointer = getNextIndex(pointer); + return (next_pointer >= 0); + } + + public E next() { + if (next_pointer >= 0) { + pointer = next_pointer; + } + else { + pointer = getNextIndex(pointer); + if (pointer == -1) { + pointer = size; + } + } + + next_pointer = -1; + return pointer < size ? colValuesInternal.getKey(pointer) : null; + } + + public void remove() { + int[] index = colValuesInternal.get(pointer); + data[index[0]] &= ~index[1]; + } + } +} + diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastSetFactory.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastSetFactory.java new file mode 100644 index 000000000000..e9cce03b827c --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastSetFactory.java @@ -0,0 +1,489 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class FastSetFactory<E> { + + private VBStyleCollection<int[], E> colValuesInternal = new VBStyleCollection<int[], E>(); + + private int lastBlock; + + private int lastMask; + + public FastSetFactory(Collection<E> set) { + + int block = -1; + int mask = -1; + int index = 0; + + for (E element : set) { + + block = index / 32; + + if (index % 32 == 0) { + mask = 1; + } + else { + mask <<= 1; + } + + colValuesInternal.putWithKey(new int[]{block, mask}, element); + + index++; + } + + lastBlock = block; + lastMask = mask; + } + + private int[] addElement(E element) { + + if (lastMask == -1 || lastMask == 0x80000000) { + lastMask = 1; + lastBlock++; + } + else { + lastMask <<= 1; + } + + int[] pointer = new int[]{lastBlock, lastMask}; + colValuesInternal.putWithKey(pointer, element); + + return pointer; + } + + public FastSet<E> spawnEmptySet() { + return new FastSet<E>(this); + } + + public int getLastBlock() { + return lastBlock; + } + + public int getLastMask() { + return lastMask; + } + + private VBStyleCollection<int[], E> getInternalValuesCollection() { + return colValuesInternal; + } + + + public static class FastSet<E> implements Iterable<E> { + + private FastSetFactory<E> factory; + + private VBStyleCollection<int[], E> colValuesInternal; + + private int[] data; + + private FastSet(FastSetFactory<E> factory) { + this.factory = factory; + this.colValuesInternal = factory.getInternalValuesCollection(); + this.data = new int[factory.getLastBlock() + 1]; + } + + public FastSet<E> getCopy() { + + FastSet<E> copy = new FastSet<E>(factory); + + int arrlength = data.length; + int[] cpdata = new int[arrlength]; + + System.arraycopy(data, 0, cpdata, 0, arrlength); + copy.setData(cpdata); + + return copy; + } + + private int[] ensureCapacity(int index) { + + int newlength = data.length; + if (newlength == 0) { + newlength = 1; + } + + while (newlength <= index) { + newlength *= 2; + } + + int[] newdata = new int[newlength]; + System.arraycopy(data, 0, newdata, 0, data.length); + + return data = newdata; + } + + public void add(E element) { + int[] index = colValuesInternal.getWithKey(element); + + if (index == null) { + index = factory.addElement(element); + } + + if (index[0] >= data.length) { + ensureCapacity(index[0]); + } + + data[index[0]] |= index[1]; + } + + public void setAllElements() { + + int lastblock = factory.getLastBlock(); + int lastmask = factory.getLastMask(); + + if (lastblock >= data.length) { + ensureCapacity(lastblock); + } + + for (int i = lastblock - 1; i >= 0; i--) { + data[i] = 0xFFFFFFFF; + } + + data[lastblock] = lastmask | (lastmask - 1); + } + + public void addAll(Set<E> set) { + for (E element : set) { + add(element); + } + } + + public void remove(E element) { + int[] index = colValuesInternal.getWithKey(element); + + if (index == null) { + index = factory.addElement(element); + } + + if (index[0] < data.length) { + data[index[0]] &= ~index[1]; + } + } + + public void removeAll(Set<E> set) { + for (E element : set) { + remove(element); + } + } + + public boolean contains(E element) { + int[] index = colValuesInternal.getWithKey(element); + + if (index == null) { + index = factory.addElement(element); + } + + return index[0] >= data.length ? false : ((data[index[0]] & index[1]) != 0); + } + + public boolean contains(FastSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + if ((extdata[i] & ~intdata[i]) != 0) { + return false; + } + } + + for (int i = extdata.length - 1; i >= minlength; i--) { + if (extdata[i] != 0) { + return false; + } + } + + return true; + } + + public void union(FastSet<E> set) { + + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + intdata[i] |= extdata[i]; + } + + boolean expanded = false; + for (int i = extdata.length - 1; i >= minlength; i--) { + if (extdata[i] != 0) { + if (!expanded) { + intdata = ensureCapacity(extdata.length - 1); + } + intdata[i] = extdata[i]; + } + } + } + + public void intersection(FastSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + intdata[i] &= extdata[i]; + } + + for (int i = intdata.length - 1; i >= minlength; i--) { + intdata[i] = 0; + } + } + + public void symdiff(FastSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + intdata[i] ^= extdata[i]; + } + + boolean expanded = false; + for (int i = extdata.length - 1; i >= minlength; i--) { + if (extdata[i] != 0) { + if (!expanded) { + intdata = ensureCapacity(extdata.length - 1); + } + intdata[i] = extdata[i]; + } + } + } + + public void complement(FastSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + intdata[i] &= ~extdata[i]; + } + } + + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof FastSet)) return false; + + int[] longdata = ((FastSet)o).getData(); + int[] shortdata = data; + + if (data.length > longdata.length) { + shortdata = longdata; + longdata = data; + } + + for (int i = shortdata.length - 1; i >= 0; i--) { + if (shortdata[i] != longdata[i]) { + return false; + } + } + + for (int i = longdata.length - 1; i >= shortdata.length; i--) { + if (longdata[i] != 0) { + return false; + } + } + + return true; + } + + public int getCardinality() { + + boolean found = false; + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + int block = intdata[i]; + if (block != 0) { + if (found) { + return 2; + } + else { + if ((block & (block - 1)) == 0) { + found = true; + } + else { + return 2; + } + } + } + } + + return found ? 1 : 0; + } + + public int size() { + + int size = 0; + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + size += Integer.bitCount(intdata[i]); + } + + return size; + } + + public boolean isEmpty() { + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + if (intdata[i] != 0) { + return false; + } + } + + return true; + } + + public Iterator<E> iterator() { + return new FastSetIterator<E>(this); + } + + public Set<E> toPlainSet() { + HashSet<E> set = new HashSet<E>(); + + int[] intdata = data; + + int size = data.length * 32; + if (size > colValuesInternal.size()) { + size = colValuesInternal.size(); + } + + for (int i = size - 1; i >= 0; i--) { + int[] index = colValuesInternal.get(i); + + if ((intdata[index[0]] & index[1]) != 0) { + set.add(colValuesInternal.getKey(i)); + } + } + + return set; + } + + public String toBinary() { + + StringBuilder buffer = new StringBuilder(); + int[] intdata = data; + + for (int i = 0; i < intdata.length; i++) { + buffer.append(" ").append(Integer.toBinaryString(intdata[i])); + } + + return buffer.toString(); + } + + private int[] getData() { + return data; + } + + private void setData(int[] data) { + this.data = data; + } + + public int[] getLoad() { + int[] intdata = data; + int notempty = 0; + + for (int i = 0; i < intdata.length; i++) { + if (intdata[i] != 0) { + notempty++; + } + } + + return new int[]{intdata.length, notempty}; + } + + public FastSetFactory<E> getFactory() { + return factory; + } + } + + public static class FastSetIterator<E> implements Iterator<E> { + + private VBStyleCollection<int[], E> colValuesInternal; + private int[] data; + private int size; + + private int pointer = -1; + private int next_pointer = -1; + + private FastSetIterator(FastSet<E> set) { + colValuesInternal = set.getFactory().getInternalValuesCollection(); + data = set.getData(); + + size = colValuesInternal.size(); + int datasize = data.length * 32; + + if (datasize < size) { + size = datasize; + } + } + + public boolean hasNext() { + + next_pointer = pointer; + + while (++next_pointer < size) { + int[] index = colValuesInternal.get(next_pointer); + if ((data[index[0]] & index[1]) != 0) { + return true; + } + } + + next_pointer = -1; + return false; + } + + public E next() { + if (next_pointer >= 0) { + pointer = next_pointer; + } + else { + while (++pointer < size) { + int[] index = colValuesInternal.get(pointer); + if ((data[index[0]] & index[1]) != 0) { + break; + } + } + } + + next_pointer = -1; + return pointer < size ? colValuesInternal.getKey(pointer) : null; + } + + public void remove() { + int[] index = colValuesInternal.get(pointer); + data[index[0]] &= ~index[1]; + + pointer--; + } + } +} + diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastSparseSetFactory.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastSparseSetFactory.java new file mode 100644 index 000000000000..bf01035616a4 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/FastSparseSetFactory.java @@ -0,0 +1,552 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +public class FastSparseSetFactory<E> { + + private VBStyleCollection<int[], E> colValuesInternal = new VBStyleCollection<int[], E>(); + + private int lastBlock; + + private int lastMask; + + public FastSparseSetFactory(Collection<E> set) { + + int block = -1; + int mask = -1; + int index = 0; + + for (E element : set) { + + block = index / 32; + + if (index % 32 == 0) { + mask = 1; + } + else { + mask <<= 1; + } + + colValuesInternal.putWithKey(new int[]{block, mask}, element); + + index++; + } + + lastBlock = block; + lastMask = mask; + } + + private int[] addElement(E element) { + + if (lastMask == -1 || lastMask == 0x80000000) { + lastMask = 1; + lastBlock++; + } + else { + lastMask <<= 1; + } + + int[] pointer = new int[]{lastBlock, lastMask}; + colValuesInternal.putWithKey(pointer, element); + + return pointer; + } + + public FastSparseSet<E> spawnEmptySet() { + return new FastSparseSet<E>(this); + } + + public int getLastBlock() { + return lastBlock; + } + + public int getLastMask() { + return lastMask; + } + + private VBStyleCollection<int[], E> getInternalValuesCollection() { + return colValuesInternal; + } + + + public static class FastSparseSet<E> implements Iterable<E> { + + private FastSparseSetFactory<E> factory; + + private VBStyleCollection<int[], E> colValuesInternal; + + private int[] data; + private int[] next; + + private FastSparseSet(FastSparseSetFactory<E> factory) { + this.factory = factory; + this.colValuesInternal = factory.getInternalValuesCollection(); + + int length = factory.getLastBlock() + 1; + this.data = new int[length]; + this.next = new int[length]; + } + + private FastSparseSet(FastSparseSetFactory<E> factory, int[] data, int[] next) { + this.factory = factory; + this.colValuesInternal = factory.getInternalValuesCollection(); + + this.data = data; + this.next = next; + } + + public FastSparseSet<E> getCopy() { + + int arrlength = data.length; + int[] cpdata = new int[arrlength]; + int[] cpnext = new int[arrlength]; + + System.arraycopy(data, 0, cpdata, 0, arrlength); + System.arraycopy(next, 0, cpnext, 0, arrlength); + + return new FastSparseSet<E>(factory, cpdata, cpnext); + } + + private int[] ensureCapacity(int index) { + + int newlength = data.length; + if (newlength == 0) { + newlength = 1; + } + + while (newlength <= index) { + newlength *= 2; + } + + int[] newdata = new int[newlength]; + System.arraycopy(data, 0, newdata, 0, data.length); + data = newdata; + + int[] newnext = new int[newlength]; + System.arraycopy(next, 0, newnext, 0, next.length); + next = newnext; + + return newdata; + } + + public void add(E element) { + int[] index = colValuesInternal.getWithKey(element); + + if (index == null) { + index = factory.addElement(element); + } + + int block = index[0]; + if (block >= data.length) { + ensureCapacity(block); + } + + data[block] |= index[1]; + + changeNext(next, block, next[block], block); + } + + public void setAllElements() { + + int lastblock = factory.getLastBlock(); + int lastmask = factory.getLastMask(); + + if (lastblock >= data.length) { + ensureCapacity(lastblock); + } + + for (int i = lastblock - 1; i >= 0; i--) { + data[i] = 0xFFFFFFFF; + next[i] = i + 1; + } + + data[lastblock] = lastmask | (lastmask - 1); + next[lastblock] = 0; + } + + public void addAll(Set<E> set) { + for (E element : set) { + add(element); + } + } + + public void remove(E element) { + int[] index = colValuesInternal.getWithKey(element); + + if (index == null) { + index = factory.addElement(element); + } + + int block = index[0]; + if (block < data.length) { + data[block] &= ~index[1]; + + if (data[block] == 0) { + changeNext(next, block, block, next[block]); + } + } + } + + public void removeAll(Set<E> set) { + for (E element : set) { + remove(element); + } + } + + public boolean contains(E element) { + int[] index = colValuesInternal.getWithKey(element); + + if (index == null) { + index = factory.addElement(element); + } + + return index[0] >= data.length ? false : ((data[index[0]] & index[1]) != 0); + } + + public boolean contains(FastSparseSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + if ((extdata[i] & ~intdata[i]) != 0) { + return false; + } + } + + for (int i = extdata.length - 1; i >= minlength; i--) { + if (extdata[i] != 0) { + return false; + } + } + + return true; + } + + private void setNext() { + + int link = 0; + for (int i = data.length - 1; i >= 0; i--) { + next[i] = link; + if (data[i] != 0) { + link = i; + } + } + } + + private static void changeNext(int[] arrnext, int key, int oldnext, int newnext) { + for (int i = key - 1; i >= 0; i--) { + if (arrnext[i] == oldnext) { + arrnext[i] = newnext; + } + else { + break; + } + } + } + + public void union(FastSparseSet<E> set) { + + int[] extdata = set.getData(); + int[] extnext = set.getNext(); + int[] intdata = data; + int intlength = intdata.length; + + int pointer = 0; + do { + if (pointer >= intlength) { + intdata = ensureCapacity(extdata.length - 1); + } + + boolean nextrec = (intdata[pointer] == 0); + intdata[pointer] |= extdata[pointer]; + + if (nextrec) { + changeNext(next, pointer, next[pointer], pointer); + } + + pointer = extnext[pointer]; + } + while (pointer != 0); + } + + public void intersection(FastSparseSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + intdata[i] &= extdata[i]; + } + + for (int i = intdata.length - 1; i >= minlength; i--) { + intdata[i] = 0; + } + + setNext(); + } + + public void symdiff(FastSparseSet<E> set) { + int[] extdata = set.getData(); + int[] intdata = data; + + int minlength = Math.min(extdata.length, intdata.length); + + for (int i = minlength - 1; i >= 0; i--) { + intdata[i] ^= extdata[i]; + } + + boolean expanded = false; + for (int i = extdata.length - 1; i >= minlength; i--) { + if (extdata[i] != 0) { + if (!expanded) { + intdata = ensureCapacity(extdata.length - 1); + } + intdata[i] = extdata[i]; + } + } + + setNext(); + } + + public void complement(FastSparseSet<E> set) { + + int[] extdata = set.getData(); + int[] intdata = data; + int extlength = extdata.length; + + int pointer = 0; + do { + if (pointer >= extlength) { + break; + } + + intdata[pointer] &= ~extdata[pointer]; + if (intdata[pointer] == 0) { + changeNext(next, pointer, pointer, next[pointer]); + } + + pointer = next[pointer]; + } + while (pointer != 0); + } + + + public boolean equals(Object o) { + if (o == this) return true; + if (o == null || !(o instanceof FastSparseSet)) return false; + + int[] longdata = ((FastSparseSet)o).getData(); + int[] shortdata = data; + + if (data.length > longdata.length) { + shortdata = longdata; + longdata = data; + } + + for (int i = shortdata.length - 1; i >= 0; i--) { + if (shortdata[i] != longdata[i]) { + return false; + } + } + + for (int i = longdata.length - 1; i >= shortdata.length; i--) { + if (longdata[i] != 0) { + return false; + } + } + + return true; + } + + public int getCardinality() { + + boolean found = false; + int[] intdata = data; + + for (int i = intdata.length - 1; i >= 0; i--) { + int block = intdata[i]; + if (block != 0) { + if (found) { + return 2; + } + else { + if ((block & (block - 1)) == 0) { + found = true; + } + else { + return 2; + } + } + } + } + + return found ? 1 : 0; + } + + public boolean isEmpty() { + return data.length == 0 || (next[0] == 0 && data[0] == 0); + } + + public Iterator<E> iterator() { + return new FastSparseSetIterator<E>(this); + } + + public Set<E> toPlainSet() { + HashSet<E> set = new HashSet<E>(); + + int[] intdata = data; + + int size = data.length * 32; + if (size > colValuesInternal.size()) { + size = colValuesInternal.size(); + } + + for (int i = size - 1; i >= 0; i--) { + int[] index = colValuesInternal.get(i); + + if ((intdata[index[0]] & index[1]) != 0) { + set.add(colValuesInternal.getKey(i)); + } + } + + return set; + } + + public String toString() { + return toPlainSet().toString(); + } + + public String toBinary() { + + StringBuilder buffer = new StringBuilder(); + int[] intdata = data; + + for (int i = 0; i < intdata.length; i++) { + buffer.append(" ").append(Integer.toBinaryString(intdata[i])); + } + + return buffer.toString(); + } + + private int[] getData() { + return data; + } + + private int[] getNext() { + return next; + } + + public int[] getLoad() { + int[] intdata = data; + int notempty = 0; + + for (int i = 0; i < intdata.length; i++) { + if (intdata[i] != 0) { + notempty++; + } + } + + return new int[]{intdata.length, notempty}; + } + + public FastSparseSetFactory<E> getFactory() { + return factory; + } + } + + public static class FastSparseSetIterator<E> implements Iterator<E> { + + private VBStyleCollection<int[], E> colValuesInternal; + private int[] data; + private int[] next; + private int size; + + private int pointer = -1; + private int next_pointer = -1; + + private FastSparseSetIterator(FastSparseSet<E> set) { + colValuesInternal = set.getFactory().getInternalValuesCollection(); + data = set.getData(); + next = set.getNext(); + size = colValuesInternal.size(); + } + + private int getNextIndex(int index) { + + index++; + int bindex = index >>> 5; + int dindex = index & 0x1F; + + while (bindex < data.length) { + int block = data[bindex]; + + if (block != 0) { + block >>>= dindex; + while (dindex < 32) { + if ((block & 1) != 0) { + return (bindex << 5) + dindex; + } + block >>>= 1; + dindex++; + } + } + + dindex = 0; + bindex = next[bindex]; + + if (bindex == 0) { + break; + } + } + + return -1; + } + + public boolean hasNext() { + next_pointer = getNextIndex(pointer); + return (next_pointer >= 0); + } + + public E next() { + if (next_pointer >= 0) { + pointer = next_pointer; + } + else { + pointer = getNextIndex(pointer); + if (pointer == -1) { + pointer = size; + } + } + + next_pointer = -1; + return pointer < size ? colValuesInternal.getKey(pointer) : null; + } + + public void remove() { + int[] index = colValuesInternal.get(pointer); + data[index[0]] &= ~index[1]; + } + } +} + diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/InterpreterUtil.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/InterpreterUtil.java new file mode 100644 index 000000000000..0047bb792c87 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/InterpreterUtil.java @@ -0,0 +1,175 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import org.jetbrains.java.decompiler.main.DecompilerContext; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; + +import java.io.*; +import java.nio.channels.FileChannel; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +public class InterpreterUtil { + public static final boolean IS_WINDOWS = System.getProperty("os.name", "").startsWith("Windows"); + + private static final int CHANNEL_WINDOW_SIZE = IS_WINDOWS ? 64 * 1024 * 1024 - (32 * 1024) : 64 * 1024 * 1024; // magic number for Windows + private static final int BUFFER_SIZE = 16* 1024; + + public static void copyFile(File in, File out) throws IOException { + FileInputStream inStream = new FileInputStream(in); + try { + FileOutputStream outStream = new FileOutputStream(out); + try { + FileChannel inChannel = inStream.getChannel(); + FileChannel outChannel = outStream.getChannel(); + long size = inChannel.size(), position = 0; + while (position < size) { + position += inChannel.transferTo(position, CHANNEL_WINDOW_SIZE, outChannel); + } + } + finally { + outStream.close(); + } + } + finally { + inStream.close(); + } + } + + public static void copyStream(InputStream in, OutputStream out) throws IOException { + byte[] buffer = new byte[BUFFER_SIZE]; + int len; + while ((len = in.read(buffer)) >= 0) { + out.write(buffer, 0, len); + } + } + + public static byte[] getBytes(ZipFile archive, ZipEntry entry) throws IOException { + return readAndClose(archive.getInputStream(entry), entry.getSize()); + } + + public static byte[] getBytes(File file) throws IOException { + return readAndClose(new FileInputStream(file), file.length()); + } + + private static byte[] readAndClose(InputStream stream, long length) throws IOException { + try { + byte[] bytes = new byte[(int)length]; + if (stream.read(bytes) != length) { + throw new IOException("premature end of stream"); + } + return bytes; + } + finally { + stream.close(); + } + } + + public static String getIndentString(int length) { + if (length == 0) return ""; + StringBuilder buf = new StringBuilder(); + appendIndent(buf, length); + return buf.toString(); + } + + public static void appendIndent(StringBuilder buffer, int length) { + if (length == 0) return; + String indent = (String)DecompilerContext.getProperty(IFernflowerPreferences.INDENT_STRING); + while (length-- > 0) { + buffer.append(indent); + } + } + + public static boolean equalSets(Collection<?> c1, Collection<?> c2) { + if (c1 == null) { + return c2 == null; + } + else if (c2 == null) { + return false; + } + + if (c1.size() != c2.size()) { + return false; + } + + HashSet<Object> set = new HashSet<Object>(c1); + set.removeAll(c2); + return (set.size() == 0); + } + + public static boolean equalObjects(Object first, Object second) { + return first == null ? second == null : first.equals(second); + } + + public static boolean equalObjectArrays(Object[] first, Object[] second) { + if (first == null || second == null) { + return equalObjects(first, second); + } + else { + if (first.length != second.length) { + return false; + } + + for (int i = 0; i < first.length; i++) { + if (!equalObjects(first[i], second[i])) { + return false; + } + } + } + + return true; + } + + public static boolean equalLists(List<?> first, List<?> second) { + if (first == null) { + return second == null; + } + else if (second == null) { + return false; + } + + if (first.size() == second.size()) { + for (int i = 0; i < first.size(); i++) { + if (!equalObjects(first.get(i), second.get(i))) { + return false; + } + } + return true; + } + + return false; + } + + public static boolean isPrintableUnicode(char c) { + int t = Character.getType(c); + return t != Character.UNASSIGNED && t != Character.LINE_SEPARATOR && t != Character.PARAGRAPH_SEPARATOR && + t != Character.CONTROL && t != Character.FORMAT && t != Character.PRIVATE_USE && t != Character.SURROGATE; + } + + public static String charToUnicodeLiteral(int value) { + String sTemp = Integer.toHexString(value); + sTemp = ("0000" + sTemp).substring(sTemp.length()); + return "\\u" + sTemp; + } + + public static String makeUniqueKey(String name, String descriptor) { + return name + " " + descriptor; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/ListStack.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/ListStack.java new file mode 100644 index 000000000000..19c2416c44de --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/ListStack.java @@ -0,0 +1,93 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import java.util.ArrayList; + +public class ListStack<T> extends ArrayList<T> { + + protected int pointer = 0; + + public ListStack() { + super(); + } + + public ListStack(ArrayList<T> list) { + super(list); + } + + public ListStack<T> clone() { + ListStack<T> newstack = new ListStack<T>(this); + newstack.pointer = this.pointer; + return newstack; + } + + public T push(T item) { + this.add(item); + pointer++; + return item; + } + + public T pop() { + pointer--; + T o = this.get(pointer); + this.remove(pointer); + return o; + } + + public T pop(int count) { + T o = null; + for (int i = count; i > 0; i--) { + o = this.pop(); + } + return o; + } + + public void remove() { + pointer--; + this.remove(pointer); + } + + public void removeMultiple(int count) { + while (count > 0) { + pointer--; + this.remove(pointer); + count--; + } + } + + public boolean empty() { + return (pointer == 0); + } + + public int getPointer() { + return pointer; + } + + public T getByOffset(int offset) { + return this.get(pointer + offset); + } + + public void insertByOffset(int offset, T item) { + this.add(pointer + offset, item); + pointer++; + } + + public void clear() { + super.clear(); + pointer = 0; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/SFormsFastMapDirect.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/SFormsFastMapDirect.java new file mode 100644 index 000000000000..996607a2bdbc --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/SFormsFastMapDirect.java @@ -0,0 +1,414 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent; +import org.jetbrains.java.decompiler.util.FastSparseSetFactory.FastSparseSet; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; + +public class SFormsFastMapDirect { + + private int size; + + @SuppressWarnings("unchecked") private FastSparseSet<Integer>[][] elements = new FastSparseSet[3][]; + + private int[][] next = new int[3][]; + + public SFormsFastMapDirect() { + this(true); + } + + private SFormsFastMapDirect(boolean initialize) { + if (initialize) { + for (int i = 2; i >= 0; i--) { + @SuppressWarnings("unchecked") FastSparseSet<Integer>[] empty = new FastSparseSet[0]; + elements[i] = empty; + next[i] = new int[0]; + } + } + } + + public SFormsFastMapDirect(SFormsFastMapDirect map) { + for (int i = 2; i >= 0; i--) { + FastSparseSet<Integer>[] arr = map.elements[i]; + int[] arrnext = map.next[i]; + + int length = arr.length; + @SuppressWarnings("unchecked") FastSparseSet<Integer>[] arrnew = new FastSparseSet[length]; + int[] arrnextnew = new int[length]; + + System.arraycopy(arr, 0, arrnew, 0, length); + System.arraycopy(arrnext, 0, arrnextnew, 0, length); + + elements[i] = arrnew; + next[i] = arrnextnew; + + size = map.size; + } + } + + public SFormsFastMapDirect getCopy() { + + SFormsFastMapDirect map = new SFormsFastMapDirect(false); + map.size = size; + + FastSparseSet[][] mapelements = map.elements; + int[][] mapnext = map.next; + + for (int i = 2; i >= 0; i--) { + FastSparseSet<Integer>[] arr = elements[i]; + int length = arr.length; + + if (length > 0) { + int[] arrnext = next[i]; + + @SuppressWarnings("unchecked") FastSparseSet<Integer>[] arrnew = new FastSparseSet[length]; + int[] arrnextnew = new int[length]; + + System.arraycopy(arrnext, 0, arrnextnew, 0, length); + + mapelements[i] = arrnew; + mapnext[i] = arrnextnew; + + int pointer = 0; + do { + FastSparseSet<Integer> set = arr[pointer]; + if (set != null) { + arrnew[pointer] = set.getCopy(); + } + + pointer = arrnext[pointer]; + } + while (pointer != 0); + } + else { + mapelements[i] = new FastSparseSet[0]; + mapnext[i] = new int[0]; + } + } + + return map; + } + + public int size() { + return size; + } + + public boolean isEmpty() { + return size == 0; + } + + public void put(int key, FastSparseSet<Integer> value) { + putInternal(key, value, false); + } + + public void remove(int key) { + putInternal(key, null, true); + } + + public void removeAllFields() { + FastSparseSet<Integer>[] arr = elements[2]; + int[] arrnext = next[2]; + + for (int i = arr.length - 1; i >= 0; i--) { + FastSparseSet<Integer> val = arr[i]; + if (val != null) { + arr[i] = null; + size--; + } + arrnext[i] = 0; + } + } + + public void putInternal(final int key, final FastSparseSet<Integer> value, boolean remove) { + + int index = 0; + int ikey = key; + if (ikey < 0) { + index = 2; + ikey = -ikey; + } + else if (ikey >= VarExprent.STACK_BASE) { + index = 1; + ikey -= VarExprent.STACK_BASE; + } + + FastSparseSet<Integer>[] arr = elements[index]; + if (ikey >= arr.length) { + if (remove) { + return; + } + else { + arr = ensureCapacity(index, ikey + 1, false); + } + } + + FastSparseSet<Integer> oldval = arr[ikey]; + arr[ikey] = value; + + int[] arrnext = next[index]; + + if (oldval == null && value != null) { + size++; + changeNext(arrnext, ikey, arrnext[ikey], ikey); + } + else if (oldval != null && value == null) { + size--; + changeNext(arrnext, ikey, ikey, arrnext[ikey]); + } + } + + private static void changeNext(int[] arrnext, int key, int oldnext, int newnext) { + for (int i = key - 1; i >= 0; i--) { + if (arrnext[i] == oldnext) { + arrnext[i] = newnext; + } + else { + break; + } + } + } + + public boolean containsKey(int key) { + return get(key) != null; + } + + public FastSparseSet<Integer> get(int key) { + + int index = 0; + if (key < 0) { + index = 2; + key = -key; + } + else if (key >= VarExprent.STACK_BASE) { + index = 1; + key -= VarExprent.STACK_BASE; + } + + FastSparseSet<Integer>[] arr = elements[index]; + + if (key < arr.length) { + return arr[key]; + } + return null; + } + + public void complement(SFormsFastMapDirect map) { + + for (int i = 2; i >= 0; i--) { + FastSparseSet<Integer>[] lstOwn = elements[i]; + + if (lstOwn.length == 0) { + continue; + } + + FastSparseSet<Integer>[] lstExtern = map.elements[i]; + int[] arrnext = next[i]; + + int pointer = 0; + do { + FastSparseSet<Integer> first = lstOwn[pointer]; + + if (first != null) { + if (pointer >= lstExtern.length) { + break; + } + FastSparseSet<Integer> second = lstExtern[pointer]; + + if (second != null) { + first.complement(second); + if (first.isEmpty()) { + lstOwn[pointer] = null; + size--; + changeNext(arrnext, pointer, pointer, arrnext[pointer]); + } + } + } + + pointer = arrnext[pointer]; + } + while (pointer != 0); + } + } + + public void intersection(SFormsFastMapDirect map) { + + for (int i = 2; i >= 0; i--) { + FastSparseSet<Integer>[] lstOwn = elements[i]; + + if (lstOwn.length == 0) { + continue; + } + + FastSparseSet<Integer>[] lstExtern = map.elements[i]; + int[] arrnext = next[i]; + + int pointer = 0; + do { + FastSparseSet<Integer> first = lstOwn[pointer]; + + if (first != null) { + FastSparseSet<Integer> second = null; + if (pointer < lstExtern.length) { + second = lstExtern[pointer]; + } + + if (second != null) { + first.intersection(second); + } + + if (second == null || first.isEmpty()) { + lstOwn[pointer] = null; + size--; + changeNext(arrnext, pointer, pointer, arrnext[pointer]); + } + } + + pointer = arrnext[pointer]; + } + while (pointer != 0); + } + } + + public void union(SFormsFastMapDirect map) { + + for (int i = 2; i >= 0; i--) { + FastSparseSet<Integer>[] lstExtern = map.elements[i]; + + if (lstExtern.length == 0) { + continue; + } + + FastSparseSet<Integer>[] lstOwn = elements[i]; + int[] arrnext = next[i]; + int[] arrnextExtern = map.next[i]; + + int pointer = 0; + do { + if (pointer >= lstOwn.length) { + lstOwn = ensureCapacity(i, lstExtern.length, true); + arrnext = next[i]; + } + + FastSparseSet<Integer> second = lstExtern[pointer]; + + if (second != null) { + FastSparseSet<Integer> first = lstOwn[pointer]; + + if (first == null) { + lstOwn[pointer] = second.getCopy(); + size++; + changeNext(arrnext, pointer, arrnext[pointer], pointer); + } + else { + first.union(second); + } + } + + pointer = arrnextExtern[pointer]; + } + while (pointer != 0); + } + } + + public String toString() { + + StringBuilder buffer = new StringBuilder("{"); + + List<Entry<Integer, FastSparseSet<Integer>>> lst = entryList(); + if (lst != null) { + boolean first = true; + for (Entry<Integer, FastSparseSet<Integer>> entry : lst) { + if (!first) { + buffer.append(", "); + } + else { + first = false; + } + + Set<Integer> set = entry.getValue().toPlainSet(); + buffer.append(entry.getKey()).append("={").append(set.toString()).append("}"); + } + } + + buffer.append("}"); + return buffer.toString(); + } + + public List<Entry<Integer, FastSparseSet<Integer>>> entryList() { + List<Entry<Integer, FastSparseSet<Integer>>> list = new ArrayList<Entry<Integer, FastSparseSet<Integer>>>(); + + for (int i = 2; i >= 0; i--) { + int ikey = 0; + for (final FastSparseSet<Integer> ent : elements[i]) { + if (ent != null) { + final int key = i == 0 ? ikey : (i == 1 ? ikey + VarExprent.STACK_BASE : -ikey); + + list.add(new Entry<Integer, FastSparseSet<Integer>>() { + + private Integer var = key; + private FastSparseSet<Integer> val = ent; + + public Integer getKey() { + return var; + } + + public FastSparseSet<Integer> getValue() { + return val; + } + + public FastSparseSet<Integer> setValue(FastSparseSet<Integer> newvalue) { + return null; + } + }); + } + + ikey++; + } + } + + return list; + } + + private FastSparseSet<Integer>[] ensureCapacity(int index, int size, boolean exact) { + + FastSparseSet<Integer>[] arr = elements[index]; + int[] arrnext = next[index]; + + int minsize = size; + if (!exact) { + minsize = 2 * arr.length / 3 + 1; + if (size > minsize) { + minsize = size; + } + } + + @SuppressWarnings("unchecked") FastSparseSet<Integer>[] arrnew = new FastSparseSet[minsize]; + System.arraycopy(arr, 0, arrnew, 0, arr.length); + + int[] arrnextnew = new int[minsize]; + System.arraycopy(arrnext, 0, arrnextnew, 0, arrnext.length); + + elements[index] = arrnew; + next[index] = arrnextnew; + + return arrnew; + } +} diff --git a/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/VBStyleCollection.java b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/VBStyleCollection.java new file mode 100644 index 000000000000..cdc176263cd2 --- /dev/null +++ b/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/util/VBStyleCollection.java @@ -0,0 +1,204 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; + +public class VBStyleCollection<E, K> extends ArrayList<E> { + + private HashMap<K, Integer> map = new HashMap<K, Integer>(); + + private ArrayList<K> lstKeys = new ArrayList<K>(); + + public VBStyleCollection() { + super(); + } + + public VBStyleCollection(int initialCapacity) { + super(initialCapacity); + lstKeys = new ArrayList<K>(initialCapacity); + map = new HashMap<K, Integer>(initialCapacity); + } + + public VBStyleCollection(Collection<E> c) { + super(c); + } + + public boolean add(E element) { + lstKeys.add(null); + super.add(element); + return true; + } + + public boolean remove(Object element) { // TODO: error on void remove(E element) + throw new RuntimeException("not implemented!"); + } + + public boolean addAll(Collection<? extends E> c) { + for (int i = c.size() - 1; i >= 0; i--) { + lstKeys.add(null); + } + return super.addAll(c); + } + + public void addAllWithKey(VBStyleCollection<E, K> c) { + for (int i = 0; i < c.size(); i++) { + addWithKey(c.get(i), c.getKey(i)); + } + } + + public void addAllWithKey(Collection<E> elements, Collection<K> keys) { + int index = super.size(); + + for (K key : keys) { + map.put(key, index++); + } + + super.addAll(elements); + lstKeys.addAll(keys); + } + + public void addWithKey(E element, K key) { + map.put(key, super.size()); + super.add(element); + lstKeys.add(key); + } + + // TODO: speed up the method + public E putWithKey(E element, K key) { + Integer index = map.get(key); + if (index == null) { + addWithKey(element, key); + } + else { + return super.set(index, element); + } + return null; + } + + public void add(int index, E element) { + addToListIndex(index, 1); + lstKeys.add(index, null); + super.add(index, element); + } + + public void addWithKeyAndIndex(int index, E element, K key) { + addToListIndex(index, 1); + map.put(key, new Integer(index)); + super.add(index, element); + lstKeys.add(index, key); + } + + public void removeWithKey(K key) { + int index = map.get(key).intValue(); + addToListIndex(index + 1, -1); + super.remove(index); + lstKeys.remove(index); + map.remove(key); + } + + public E remove(int index) { + addToListIndex(index + 1, -1); + K obj = lstKeys.get(index); + if (obj != null) { + map.remove(obj); + } + lstKeys.remove(index); + return super.remove(index); + } + + public E getWithKey(K key) { + Integer index = map.get(key); + if (index == null) { + return null; + } + return super.get(index.intValue()); + } + + public int getIndexByKey(K key) { + return map.get(key).intValue(); + } + + public E getLast() { + return super.get(super.size() - 1); + } + + public boolean containsKey(K key) { + return map.containsKey(key); + } + + public void clear() { + map.clear(); + lstKeys.clear(); + super.clear(); + } + + public VBStyleCollection<E, K> clone() { + VBStyleCollection<E, K> c = new VBStyleCollection<E, K>(); + c.addAll(new ArrayList<E>(this)); + c.setMap(new HashMap<K, Integer>(map)); + c.setLstKeys(new ArrayList<K>(lstKeys)); + return c; + } + + public void swap(int index1, int index2) { + + Collections.swap(this, index1, index2); + Collections.swap(lstKeys, index1, index2); + + K key = lstKeys.get(index1); + if (key != null) { + map.put(key, new Integer(index1)); + } + + key = lstKeys.get(index2); + if (key != null) { + map.put(key, new Integer(index2)); + } + } + + public HashMap<K, Integer> getMap() { + return map; + } + + public void setMap(HashMap<K, Integer> map) { + this.map = map; + } + + public K getKey(int index) { + return lstKeys.get(index); + } + + public ArrayList<K> getLstKeys() { + return lstKeys; + } + + public void setLstKeys(ArrayList<K> lstKeys) { + this.lstKeys = lstKeys; + } + + private void addToListIndex(int index, int diff) { + for (int i = lstKeys.size() - 1; i >= index; i--) { + K obj = lstKeys.get(i); + if (obj != null) { + map.put(obj, new Integer(i + diff)); + } + } + } +} diff --git a/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/BulkDecompilationTest.java b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/BulkDecompilationTest.java new file mode 100644 index 000000000000..1b5353b37a49 --- /dev/null +++ b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/BulkDecompilationTest.java @@ -0,0 +1,110 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler; + +import org.hamcrest.Matchers; +import org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler; +import org.jetbrains.java.decompiler.util.InterpreterUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.*; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class BulkDecompilationTest { + private DecompilerTestFixture fixture; + + @Before + public void setUp() throws IOException { + fixture = new DecompilerTestFixture(); + fixture.setUp(); + } + + @After + public void tearDown() { + fixture.tearDown(); + fixture = null; + } + + @Test + public void testDirectory() { + File classes = new File(fixture.getTempDir(), "classes"); + unpack(new File(fixture.getTestDataDir(), "bulk.jar"), classes); + + ConsoleDecompiler decompiler = fixture.getDecompiler(); + decompiler.addSpace(classes, true); + decompiler.decompileContext(); + + compareDirectories(new File(fixture.getTestDataDir(), "bulk"), fixture.getTargetDir()); + } + + @Test + public void testJar() { + ConsoleDecompiler decompiler = fixture.getDecompiler(); + decompiler.addSpace(new File(fixture.getTestDataDir(), "bulk.jar"), true); + decompiler.decompileContext(); + + File unpacked = new File(fixture.getTempDir(), "unpacked"); + unpack(new File(fixture.getTargetDir(), "bulk.jar"), unpacked); + + compareDirectories(new File(fixture.getTestDataDir(), "bulk"), unpacked); + } + + private static void unpack(File archive, File targetDir) { + try { + ZipFile zip = new ZipFile(archive); + try { + Enumeration<? extends ZipEntry> entries = zip.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory()) { + File file = new File(targetDir, entry.getName()); + assertTrue(file.getParentFile().mkdirs() || file.getParentFile().isDirectory()); + InputStream in = zip.getInputStream(entry); + OutputStream out = new FileOutputStream(file); + InterpreterUtil.copyStream(in, out); + out.close(); + in.close(); + } + } + } + finally { + zip.close(); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static void compareDirectories(File expected, File actual) { + String[] expectedList = expected.list(); + String[] actualList = actual.list(); + assertThat(actualList, Matchers.arrayContainingInAnyOrder(expectedList)); + for (String name : expectedList) { + File child = new File(expected, name); + if (child.isDirectory()) { + compareDirectories(child, new File(actual, name)); + } + } + } +} diff --git a/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/DecompilerTestFixture.java b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/DecompilerTestFixture.java new file mode 100644 index 000000000000..b82b65e2155b --- /dev/null +++ b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/DecompilerTestFixture.java @@ -0,0 +1,88 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler; + +import org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler; +import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences; + +import java.io.*; +import java.util.HashMap; + +import static org.junit.Assert.assertTrue; + +public class DecompilerTestFixture { + private File testDataDir; + private File tempDir; + private File targetDir; + private ConsoleDecompiler decompiler; + + public void setUp() throws IOException { + testDataDir = new File("testData"); + if (!isTestDataDir(testDataDir)) testDataDir = new File("community/plugins/java-decompiler/engine/testData"); + if (!isTestDataDir(testDataDir)) testDataDir = new File("plugins/java-decompiler/engine/testData"); + assertTrue("current dir: " + new File("").getAbsolutePath(), isTestDataDir(testDataDir)); + + //noinspection SSBasedInspection + tempDir = File.createTempFile("decompiler_test_", "_dir"); + assertTrue(tempDir.delete()); + + targetDir = new File(tempDir, "decompiled"); + assertTrue(targetDir.mkdirs()); + decompiler = new ConsoleDecompiler(this.targetDir, new HashMap<String, Object>() {{ + put(IFernflowerPreferences.LOG_LEVEL, "warn"); + put(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES, "1"); + put(IFernflowerPreferences.REMOVE_SYNTHETIC, "1"); + put(IFernflowerPreferences.REMOVE_BRIDGE, "1"); + put(IFernflowerPreferences.LITERALS_AS_IS, "1"); + }}); + } + + public void tearDown() { + if (tempDir != null) { + delete(tempDir); + } + } + + public File getTestDataDir() { + return testDataDir; + } + + public File getTempDir() { + return tempDir; + } + + public File getTargetDir() { + return targetDir; + } + + public ConsoleDecompiler getDecompiler() { + return decompiler; + } + + private static boolean isTestDataDir(File dir) { + return dir.isDirectory() && new File(dir, "classes").isDirectory() && new File(dir, "results").isDirectory(); + } + + private static void delete(File file) { + if (file.isDirectory()) { + File[] files = file.listFiles(); + if (files != null) { + for (File f : files) delete(f); + } + } + assertTrue(file.delete()); + } +} diff --git a/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/SingleClassesTest.java b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/SingleClassesTest.java new file mode 100644 index 000000000000..70aa605e8630 --- /dev/null +++ b/plugins/java-decompiler/engine/test/org/jetbrains/java/decompiler/SingleClassesTest.java @@ -0,0 +1,125 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.java.decompiler; + +import org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SingleClassesTest { + private DecompilerTestFixture fixture; + + @Before + public void setUp() throws IOException { + fixture = new DecompilerTestFixture(); + fixture.setUp(); + } + + @After + public void tearDown() { + fixture.tearDown(); + fixture = null; + } + + @Test public void testClassFields() { doTest("pkg/TestClassFields"); } + @Test public void testClassLambda() { doTest("pkg/TestClassLambda"); } + @Test public void testClassLoop() { doTest("pkg/TestClassLoop"); } + @Test public void testClassSwitch() { doTest("pkg/TestClassSwitch"); } + @Test public void testClassTypes() { doTest("pkg/TestClassTypes"); } + @Test public void testClassVar() { doTest("pkg/TestClassVar"); } + @Test public void testClassNestedInitializer() { doTest("pkg/TestClassNestedInitializer"); } + @Test public void testClassCast() { doTest("pkg/TestClassCast"); } + @Test public void testDeprecations() { doTest("pkg/TestDeprecations"); } + @Test public void testExtendsList() { doTest("pkg/TestExtendsList"); } + @Test public void testMethodParameters() { doTest("pkg/TestMethodParameters"); } + @Test public void testCodeConstructs() { doTest("pkg/TestCodeConstructs"); } + @Test public void testConstants() { doTest("pkg/TestConstants"); } + @Test public void testEnum() { doTest("pkg/TestEnum"); } + @Test public void testDebugSymbols() { doTest("pkg/TestDebugSymbols"); } + @Test public void testInvalidMethodSignature() { doTest("InvalidMethodSignature"); } + + private void doTest(String testFile) { + try { + File classFile = new File(fixture.getTestDataDir(), "/classes/" + testFile + ".class"); + assertTrue(classFile.isFile()); + String testName = classFile.getName().replace(".class", ""); + + ConsoleDecompiler decompiler = fixture.getDecompiler(); + for (File file : collectClasses(classFile)) { + decompiler.addSpace(file, true); + } + + decompiler.decompileContext(); + + File decompiledFile = new File(fixture.getTargetDir(), testName + ".java"); + assertTrue(decompiledFile.isFile()); + + File referenceFile = new File(fixture.getTestDataDir(), "results/" + testName + ".dec"); + assertTrue(referenceFile.isFile()); + + String decompiledContent = getContent(decompiledFile); + String referenceContent = getContent(referenceFile); + assertEquals(referenceContent, decompiledContent); + } + catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static List<File> collectClasses(File classFile) { + List<File> files = new ArrayList<File>(); + files.add(classFile); + + File parent = classFile.getParentFile(); + if (parent != null) { + final String pattern = classFile.getName().replace(".class", "") + "\\$.+\\.class"; + File[] inner = parent.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.matches(pattern); + } + }); + if (inner != null) Collections.addAll(files, inner); + } + + return files; + } + + private static String getContent(File file) throws IOException { + Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8"); + try { + char[] buff = new char[16 * 1024]; + StringBuilder content = new StringBuilder(); + int n; + while ((n = reader.read(buff)) > 0) { + content.append(buff, 0, n); + } + return content.toString(); + } + finally { + reader.close(); + } + } +} diff --git a/plugins/java-decompiler/engine/testData/bulk.jar b/plugins/java-decompiler/engine/testData/bulk.jar Binary files differnew file mode 100644 index 000000000000..80e0dcfd5781 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/bulk.jar diff --git a/plugins/java-decompiler/engine/testData/bulk/META-INF/MANIFEST.MF b/plugins/java-decompiler/engine/testData/bulk/META-INF/MANIFEST.MF new file mode 100644 index 000000000000..e69de29bb2d1 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/bulk/META-INF/MANIFEST.MF diff --git a/plugins/java-decompiler/engine/testData/bulk/pkg/Main.java b/plugins/java-decompiler/engine/testData/bulk/pkg/Main.java new file mode 100644 index 000000000000..e69de29bb2d1 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/bulk/pkg/Main.java diff --git a/plugins/java-decompiler/engine/testData/bulk/pkg/res/Loader.java b/plugins/java-decompiler/engine/testData/bulk/pkg/res/Loader.java new file mode 100644 index 000000000000..e69de29bb2d1 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/bulk/pkg/res/Loader.java diff --git a/plugins/java-decompiler/engine/testData/bulk/pkg/res/resource.txt b/plugins/java-decompiler/engine/testData/bulk/pkg/res/resource.txt new file mode 100644 index 000000000000..e69de29bb2d1 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/bulk/pkg/res/resource.txt diff --git a/plugins/java-decompiler/engine/testData/classes/InvalidMethodSignature.class b/plugins/java-decompiler/engine/testData/classes/InvalidMethodSignature.class Binary files differnew file mode 100644 index 000000000000..3b64eb80cda2 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/InvalidMethodSignature.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassCast.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassCast.class Binary files differnew file mode 100644 index 000000000000..5b71ce852454 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassCast.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassFields.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassFields.class Binary files differnew file mode 100644 index 000000000000..c1c0c6b9717c --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassFields.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassLambda.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassLambda.class Binary files differnew file mode 100644 index 000000000000..b506ea80c805 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassLambda.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassLoop.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassLoop.class Binary files differnew file mode 100644 index 000000000000..d363692ff02b --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassLoop.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassNestedInitializer$1.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassNestedInitializer$1.class Binary files differnew file mode 100644 index 000000000000..42b11df32210 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassNestedInitializer$1.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassNestedInitializer.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassNestedInitializer.class Binary files differnew file mode 100644 index 000000000000..1aa367010cbc --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassNestedInitializer.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassSwitch.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassSwitch.class Binary files differnew file mode 100644 index 000000000000..2fd6b5250df7 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassSwitch.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassTypes.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassTypes.class Binary files differnew file mode 100644 index 000000000000..45288caf7cd1 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassTypes.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestClassVar.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassVar.class Binary files differnew file mode 100644 index 000000000000..d66170c04214 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestClassVar.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestCodeConstructs.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestCodeConstructs.class Binary files differnew file mode 100644 index 000000000000..5727e89464dc --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestCodeConstructs.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestConstants$A.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestConstants$A.class Binary files differnew file mode 100644 index 000000000000..1d81f91d6fde --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestConstants$A.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestConstants.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestConstants.class Binary files differnew file mode 100644 index 000000000000..00c924aae6f8 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestConstants.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestDebugSymbols.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestDebugSymbols.class Binary files differnew file mode 100644 index 000000000000..102e09b778b1 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestDebugSymbols.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations$ByAnno.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations$ByAnno.class Binary files differnew file mode 100644 index 000000000000..72c86eadeb48 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations$ByAnno.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations$ByComment.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations$ByComment.class Binary files differnew file mode 100644 index 000000000000..e5576181f2d4 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations$ByComment.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations.class Binary files differnew file mode 100644 index 000000000000..f1bb2e34ab4e --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestDeprecations.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum$1.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum$1.class Binary files differnew file mode 100644 index 000000000000..163965a6acf0 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum$1.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum$2.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum$2.class Binary files differnew file mode 100644 index 000000000000..25c051bd8943 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum$2.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum.class Binary files differnew file mode 100644 index 000000000000..397ff04ee01e --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestEnum.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestExtendsList.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestExtendsList.class Binary files differnew file mode 100644 index 000000000000..98b5dbb3cfd4 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestExtendsList.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$1Local.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$1Local.class Binary files differnew file mode 100644 index 000000000000..6ba8aed255a3 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$1Local.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$C1.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$C1.class Binary files differnew file mode 100644 index 000000000000..843ebc4b8f0a --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$C1.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$C2.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$C2.class Binary files differnew file mode 100644 index 000000000000..fd52d14bd5fd --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters$C2.class diff --git a/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters.class b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters.class Binary files differnew file mode 100644 index 000000000000..e439d0c13edf --- /dev/null +++ b/plugins/java-decompiler/engine/testData/classes/pkg/TestMethodParameters.class diff --git a/plugins/java-decompiler/engine/testData/results/InvalidMethodSignature.dec b/plugins/java-decompiler/engine/testData/results/InvalidMethodSignature.dec new file mode 100644 index 000000000000..3b1bee4d20a9 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/InvalidMethodSignature.dec @@ -0,0 +1,26 @@ +package a.a.a.a.e.f; + +import a.a.a.a.a.k; +import a.a.a.a.c.c; +import a.a.a.a.c.j; +import a.a.a.a.e.bg; +import a.a.a.a.e.f.b; +import java.io.File; + +class i implements bg { + private final j a; + private final b b; + + i(b var1, j var2) { + this.b = var1; + this.a = var2; + } + + public void a(c var1, k var2, boolean var3) { + File var4 = this.a.b().a(var1); + b.a(this.b).add(var4); + } + + public void a(a.a.a.a.c.b var1) { + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassCast.dec b/plugins/java-decompiler/engine/testData/results/TestClassCast.dec new file mode 100644 index 000000000000..e09162ca0f5f --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassCast.dec @@ -0,0 +1,15 @@ +package pkg; + +import java.util.ArrayList; +import java.util.List; + +public class TestClassCast { + public void test(List var1) { + Object var2 = var1; + if(var1 != null) { + ((List)(var2 = new ArrayList(var1))).add("23"); + } + + System.out.println(((List)var2).size()); + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassFields.dec b/plugins/java-decompiler/engine/testData/results/TestClassFields.dec new file mode 100644 index 000000000000..749d828c2a71 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassFields.dec @@ -0,0 +1,10 @@ +package pkg; + +public class TestClassFields { + private static int[] sizes; + private static String[] names = new String[]{"name1", "name2"}; + + static { + sizes = new int[names.length]; + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassLambda.dec b/plugins/java-decompiler/engine/testData/results/TestClassLambda.dec new file mode 100644 index 000000000000..d0485d352461 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassLambda.dec @@ -0,0 +1,73 @@ +package pkg; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.OptionalInt; +import java.util.function.Consumer; +import java.util.function.IntBinaryOperator; +import java.util.function.Predicate; +import java.util.function.Supplier; + +public class TestClassLambda { + public int field = 0; + + public void testLambda() { + List var1 = Arrays.asList(new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7)}); + int var2 = (int)Math.random(); + var1.forEach((var2x) -> { + int var3 = 2 * var2x.intValue(); + System.out.println(var3 + var2 + this.field); + }); + } + + public void testLambda1() { + int var1 = (int)Math.random(); + Runnable var2 = () -> { + System.out.println("hello1" + var1); + }; + Runnable var3 = () -> { + System.out.println("hello2" + var1); + }; + } + + public void testLambda2() { + reduce((var0, var1) -> { + return Math.max(var0, var1); + }); + } + + public void testLambda3() { + reduce(Math::max); + } + + public void testLambda4() { + reduce(TestClassLambda::localMax); + } + + public void testLambda5() { + String var1 = "abcd"; + function(var1::toString); + } + + public void testLambda6() { + ArrayList var1 = new ArrayList(); + int var2 = var1.size() * 2; + int var3 = var1.size() * 5; + var1.removeIf((var2x) -> { + return var2 >= var2x.length() && var2x.length() <= var3; + }); + } + + public static OptionalInt reduce(IntBinaryOperator var0) { + return null; + } + + public static String function(Supplier<String> var0) { + return (String)var0.get(); + } + + public static int localMax(int var0, int var1) { + return 0; + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassLoop.dec b/plugins/java-decompiler/engine/testData/results/TestClassLoop.dec new file mode 100644 index 000000000000..74b8bac5d5e7 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassLoop.dec @@ -0,0 +1,43 @@ +package pkg; + +public class TestClassLoop { + public static void testSimpleInfinite() { + while(true) { + System.out.println(); + } + } + + public static void testFinally() { + boolean var0 = Math.random() > 0.0D; + + while(true) { + try { + if(!var0) { + return; + } + } finally { + System.out.println("1"); + } + } + } + + public static void testFinallyContinue() { + boolean var0 = Math.random() > 0.0D; + + while(true) { + while(true) { + try { + System.out.println("1"); + break; + } finally { + if(var0) { + System.out.println("3"); + continue; + } + } + } + + System.out.println("4"); + } + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassNestedInitializer.dec b/plugins/java-decompiler/engine/testData/results/TestClassNestedInitializer.dec new file mode 100644 index 000000000000..585b01a0261c --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassNestedInitializer.dec @@ -0,0 +1,14 @@ +package pkg; + +public class TestClassNestedInitializer { + public String secret; + + public void test() { + TestClassNestedInitializer var1 = new TestClassNestedInitializer() { + { + this.secret = "one"; + } + }; + System.out.println(var1.secret); + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassSwitch.dec b/plugins/java-decompiler/engine/testData/results/TestClassSwitch.dec new file mode 100644 index 000000000000..50efbe9b16f9 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassSwitch.dec @@ -0,0 +1,14 @@ +package pkg; + +public class TestClassSwitch { + public void testCaseOrder(int var1) { + switch(var1) { + case 5: + System.out.println(5); + default: + return; + case 13: + System.out.println(13); + } + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassTypes.dec b/plugins/java-decompiler/engine/testData/results/TestClassTypes.dec new file mode 100644 index 000000000000..7a50473fc3e7 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassTypes.dec @@ -0,0 +1,49 @@ +package pkg; + +import java.util.ArrayList; +import java.util.List; + +public class TestClassTypes { + public void testBoolean() { + byte var1 = 0; + long var2 = System.currentTimeMillis(); + if(var2 % 2L > 0L) { + var1 = 1; + } else if(var2 % 3L > 0L) { + var1 = 2; + } + + if(var1 == 1) { + System.out.println(); + } + + } + + public boolean testBit(int var1) { + return (var1 & 1) == 1; + } + + public void testSwitchConsts(int var1) { + switch(var1) { + case 88: + System.out.println("1"); + break; + case 656: + System.out.println("2"); + break; + case 65201: + case 65489: + System.out.println("3"); + } + + } + + public void testAssignmentType(List var1) { + Object var2 = var1; + if(var1 != null) { + ((List)(var2 = new ArrayList(var1))).add("23"); + } + + System.out.println(((List)var2).size()); + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestClassVar.dec b/plugins/java-decompiler/engine/testData/results/TestClassVar.dec new file mode 100644 index 000000000000..4cfd27f7854d --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestClassVar.dec @@ -0,0 +1,40 @@ +package pkg; + +public class TestClassVar { + private boolean field_boolean = Math.random() > 0.0D; + public int field_int = 0; + + public void testFieldSSAU() { + for(int var1 = 0; var1 < 10; ++var1) { + try { + System.out.println(); + } finally { + if(this.field_boolean) { + System.out.println(); + } + + } + } + + } + + public Long testFieldSSAU1() { + return new Long((long)(this.field_int++)); + } + + public void testComplexPropagation() { + int var1 = 0; + + while(var1 < 10) { + int var2; + for(var2 = var1; var1 < 10 && var1 == 0; ++var1) { + ; + } + + if(var2 != var1) { + System.out.println(); + } + } + + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestCodeConstructs.dec b/plugins/java-decompiler/engine/testData/results/TestCodeConstructs.dec new file mode 100644 index 000000000000..eb9de8daa07a --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestCodeConstructs.dec @@ -0,0 +1,13 @@ +package pkg; + +class TestCodeConstructs { + private int count = 0; + + void expressions() { + (new String()).hashCode(); + } + + Integer fieldIncrement() { + return new Integer(this.count++); + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestConstants.dec b/plugins/java-decompiler/engine/testData/results/TestConstants.dec new file mode 100644 index 000000000000..216da8e98468 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestConstants.dec @@ -0,0 +1,73 @@ +package pkg; + +import java.util.Date; + +public class TestConstants { + static final boolean T = true; + static final boolean F = false; + static final char C0 = '\n'; + static final char C1 = 'a'; + static final char C2 = 'Ȁ'; + static final byte BMin = -128; + static final byte BMax = 127; + static final short SMin = -32768; + static final short SMax = 32767; + static final int IMin = -2147483648; + static final int IMax = 2147483647; + static final long LMin = -9223372036854775808L; + static final long LMax = 9223372036854775807L; + static final float FNan = 0.0F / 0.0; + static final float FNeg = -1.0F / 0.0; + static final float FPos = 1.0F / 0.0; + static final float FMin = 1.4E-45F; + static final float FMax = 3.4028235E38F; + static final double DNan = 0.0D / 0.0; + static final double DNeg = -1.0D / 0.0; + static final double DPos = 1.0D / 0.0; + static final double DMin = 4.9E-324D; + static final double DMax = 1.7976931348623157E308D; + + @TestConstants.A(byte.class) + void m1() { + } + + @TestConstants.A(char.class) + void m2() { + } + + @TestConstants.A(double.class) + void m3() { + } + + @TestConstants.A(float.class) + void m4() { + } + + @TestConstants.A(int.class) + void m5() { + } + + @TestConstants.A(long.class) + void m6() { + } + + @TestConstants.A(short.class) + void m7() { + } + + @TestConstants.A(boolean.class) + void m8() { + } + + @TestConstants.A(void.class) + void m9() { + } + + @TestConstants.A(Date.class) + void m10() { + } + + @interface A { + Class<?> value(); + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestDebugSymbols.dec b/plugins/java-decompiler/engine/testData/results/TestDebugSymbols.dec new file mode 100644 index 000000000000..42ae7a8c5513 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestDebugSymbols.dec @@ -0,0 +1,11 @@ +package pkg; + +class TestDebugSymbols { + private int m() { + String text = "text"; + long prolonged = 42L; + float decimated = (float)prolonged / 10.0F; + double doubled = (double)(2.0F * decimated); + return (text + ":" + prolonged + ":" + decimated + ":" + doubled).length(); + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestDeprecations.dec b/plugins/java-decompiler/engine/testData/results/TestDeprecations.dec new file mode 100644 index 000000000000..237ac9c72348 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestDeprecations.dec @@ -0,0 +1,27 @@ +package pkg; + +public class TestDeprecations { + /** @deprecated */ + public int byComment; + /** @deprecated */ + @Deprecated + public int byAnno; + + /** @deprecated */ + public void byComment() { + } + + /** @deprecated */ + @Deprecated + public void byAnno() { + } + + /** @deprecated */ + @Deprecated + public static class ByAnno { + } + + /** @deprecated */ + public static class ByComment { + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestEnum.dec b/plugins/java-decompiler/engine/testData/results/TestEnum.dec new file mode 100644 index 000000000000..b32a3d9a4f66 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestEnum.dec @@ -0,0 +1,27 @@ +package pkg; + +public enum TestEnum { + E1, + E2 { + public void m() { + } + }, + E3("-"), + E4("+") { + public void m() { + } + }; + + private String s; + + public void m() { + } + + private TestEnum() { + this((String)"?"); + } + + private TestEnum(@Deprecated String var3) { + this.s = var3; + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestExtendsList.dec b/plugins/java-decompiler/engine/testData/results/TestExtendsList.dec new file mode 100644 index 000000000000..b4aacf6e126a --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestExtendsList.dec @@ -0,0 +1,11 @@ +package pkg; + +public class TestExtendsList { + static <T extends Comparable<? super T>> T m1(T var0) { + return null; + } + + static <T extends Object & Comparable<? super T>> T m2(T var0) { + return null; + } +} diff --git a/plugins/java-decompiler/engine/testData/results/TestMethodParameters.dec b/plugins/java-decompiler/engine/testData/results/TestMethodParameters.dec new file mode 100644 index 000000000000..e4c4724d7a7c --- /dev/null +++ b/plugins/java-decompiler/engine/testData/results/TestMethodParameters.dec @@ -0,0 +1,42 @@ +package pkg; + +public class TestMethodParameters { + TestMethodParameters(@Deprecated int var1) { + } + + void m1(@Deprecated int var1) { + } + + static void m2(@Deprecated int var0) { + } + + void local() { + class Local { + Local(@Deprecated int var2) { + } + + void m(@Deprecated int var1) { + } + } + + } + + static class C2 { + C2(@Deprecated int var1) { + } + + void m1(@Deprecated int var1) { + } + + static void m2(@Deprecated int var0) { + } + } + + class C1 { + C1(@Deprecated int var2) { + } + + void m(@Deprecated int var1) { + } + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassCast.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassCast.java new file mode 100644 index 000000000000..a831e54c98c1 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassCast.java @@ -0,0 +1,28 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +import java.util.*; + +public class TestClassCast { + public void test(List list) { + List a = list; + if (a != null) { + (a = new ArrayList(a)).add("23"); + } + System.out.println(a.size()); + } +}
\ No newline at end of file diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassFields.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassFields.java new file mode 100644 index 000000000000..a1f2facaf41c --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassFields.java @@ -0,0 +1,28 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestClassFields { + + private static int[] sizes; + private static String[] names; + + static { + + names = new String[]{"name1", "name2"}; + sizes = new int[names.length]; + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassLambda.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassLambda.java new file mode 100644 index 000000000000..589766e36506 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassLambda.java @@ -0,0 +1,77 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +import java.util.*; +import java.util.function.IntBinaryOperator; +import java.util.function.Supplier; + +public class TestClassLambda { + + public int field = 0; + + public void testLambda() { + List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + int b = (int)Math.random(); + + list.forEach(n -> { + int a = 2 * n; + System.out.println(a + b + field); + }); + } + + public void testLambda1() { + int a = (int)Math.random(); + Runnable r1 = () -> { System.out.println("hello1" + a); }; + Runnable r2 = () -> { System.out.println("hello2" + a); }; + } + + public void testLambda2() { + reduce((left, right) -> Math.max(left, right)); + } + + public void testLambda3() { // IDEA-127301 + reduce(Math::max); + } + + public void testLambda4() { + reduce(TestClassLambda::localMax); + } + + public void testLambda5() { + String x = "abcd"; + function(x::toString); + } + + public void testLambda6() { + List<String> list = new ArrayList<String>(); + int bottom = list.size() * 2; + int top = list.size() * 5; + list.removeIf(s -> (bottom >= s.length() && s.length() <= top)); + } + + public static OptionalInt reduce(IntBinaryOperator op) { + return null; + } + + public static String function(Supplier<String> supplier) { + return supplier.get(); + } + + public static int localMax(int first, int second) { + return 0; + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassLoop.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassLoop.java new file mode 100644 index 000000000000..0ecab7de08c3 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassLoop.java @@ -0,0 +1,61 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestClassLoop { + + public static void testSimpleInfinite() { + + while (true) { + System.out.println(); + } + } + + public static void testFinally() { + + boolean a = (Math.random() > 0); + + while (true) { + try { + if (!a) { + return; + } + } + finally { + System.out.println("1"); + } + } + } + + public static void testFinallyContinue() { + + boolean a = (Math.random() > 0); + + for (; ; ) { + try { + System.out.println("1"); + } + finally { + if (a) { + System.out.println("3"); + continue; + } + } + + System.out.println("4"); + } + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassNestedInitializer.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassNestedInitializer.java new file mode 100644 index 000000000000..ee8927aee89d --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassNestedInitializer.java @@ -0,0 +1,25 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestClassNestedInitializer { + public String secret; + + public void test() { + TestClassNestedInitializer obj = new TestClassNestedInitializer() { {secret = "one";} }; + System.out.println(obj.secret); + } +}
\ No newline at end of file diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassSwitch.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassSwitch.java new file mode 100644 index 000000000000..0c95d2530e3b --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassSwitch.java @@ -0,0 +1,30 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestClassSwitch { + + public void testCaseOrder(int a) { + + switch (a) { + case 13: + System.out.println(13); + return; + case 5: + System.out.println(5); + } + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassTypes.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassTypes.java new file mode 100644 index 000000000000..a745aebef600 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassTypes.java @@ -0,0 +1,69 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +import java.util.ArrayList; +import java.util.List; + +public class TestClassTypes { + + public void testBoolean() { + + byte var7 = 0; + long time = System.currentTimeMillis(); + + if (time % 2 > 0) { + var7 = 1; + } + else if (time % 3 > 0) { + var7 = 2; + } + + if (var7 == 1) { + System.out.println(); + } + } + + public boolean testBit(int var0) { + return (var0 & 1) == 1; + } + + public void testSwitchConsts(int a) { + + switch (a) { + case 88: + System.out.println("1"); + break; + case 656: + System.out.println("2"); + break; + case 65201: + case 65489: + System.out.println("3"); + } + } + + public void testAssignmentType(List list) { + + List a = list; + + if (a != null) { + (a = new ArrayList(a)).add("23"); + } + + System.out.println(a.size()); + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestClassVar.java b/plugins/java-decompiler/engine/testData/src/pkg/TestClassVar.java new file mode 100644 index 000000000000..09dcded92d66 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestClassVar.java @@ -0,0 +1,59 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + + +public class TestClassVar { + + private boolean field_boolean = (Math.random() > 0); + public int field_int = 0; + + public void testFieldSSAU() { + + for (int i = 0; i < 10; i++) { + + try { + System.out.println(); + } + finally { + if (field_boolean) { + System.out.println(); + } + } + } + } + + public Long testFieldSSAU1() { // IDEA-127466 + return new Long(field_int++); + } + + public void testComplexPropagation() { + + int a = 0; + + while (a < 10) { + + int b = a; + + for (; a < 10 && a == 0; a++) { + } + + if (b != a) { + System.out.println(); + } + } + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestCodeConstructs.java b/plugins/java-decompiler/engine/testData/src/pkg/TestCodeConstructs.java new file mode 100644 index 000000000000..fd903e4add33 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestCodeConstructs.java @@ -0,0 +1,27 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +class TestCodeConstructs { + void expressions() { + new String().hashCode(); + } + + private int count = 0; + Integer fieldIncrement() { + return new Integer(count++); + } +}
\ No newline at end of file diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestConstants.java b/plugins/java-decompiler/engine/testData/src/pkg/TestConstants.java new file mode 100644 index 000000000000..09b5419fc3e4 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestConstants.java @@ -0,0 +1,64 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestConstants { + static final boolean T = true; + static final boolean F = false; + + static final char C0 = '\n'; + static final char C1 = 'a'; + static final char C2 = 512; + + static final byte BMin = Byte.MIN_VALUE; + static final byte BMax = Byte.MAX_VALUE; + + static final short SMin = Short.MIN_VALUE; + static final short SMax = Short.MAX_VALUE; + + static final int IMin = Integer.MIN_VALUE; + static final int IMax = Integer.MAX_VALUE; + + static final long LMin = Long.MIN_VALUE; + static final long LMax = Long.MAX_VALUE; + + static final float FNan = Float.NaN; + static final float FNeg = Float.NEGATIVE_INFINITY; + static final float FPos = Float.POSITIVE_INFINITY; + static final float FMin = Float.MIN_VALUE; + static final float FMax = Float.MAX_VALUE; + + static final double DNan = Double.NaN; + static final double DNeg = Double.NEGATIVE_INFINITY; + static final double DPos = Double.POSITIVE_INFINITY; + static final double DMin = Double.MIN_VALUE; + static final double DMax = Double.MAX_VALUE; + + static @interface A { + Class<?> value(); + } + + @A(byte.class) void m1() { } + @A(char.class) void m2() { } + @A(double.class) void m3() { } + @A(float.class) void m4() { } + @A(int.class) void m5() { } + @A(long.class) void m6() { } + @A(short.class) void m7() { } + @A(boolean.class) void m8() { } + @A(void.class) void m9() { } + @A(java.util.Date.class) void m10() { } +}
\ No newline at end of file diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestDebugSymbols.java b/plugins/java-decompiler/engine/testData/src/pkg/TestDebugSymbols.java new file mode 100644 index 000000000000..167351031dc8 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestDebugSymbols.java @@ -0,0 +1,27 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +// need to be compiled with debug info +class TestDebugSymbols { + private int m() { + String text = "text"; + long prolonged = 42L; + float decimated = prolonged / 10.0f; + double doubled = 2 * decimated; + return (text + ":" + prolonged + ":" + decimated + ":" + doubled).length(); + } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestDeprecations.java b/plugins/java-decompiler/engine/testData/src/pkg/TestDeprecations.java new file mode 100644 index 000000000000..18ba0b5f10a6 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestDeprecations.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestDeprecations { + /** @deprecated */ + public int byComment; + + @Deprecated + public int byAnno; + + /** @deprecated */ + public void byComment() { } + + @Deprecated + public void byAnno() { } + + /** @deprecated */ + public static class ByComment { } + + @Deprecated + public static class ByAnno { } +}
\ No newline at end of file diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestEnum.java b/plugins/java-decompiler/engine/testData/src/pkg/TestEnum.java new file mode 100644 index 000000000000..43fab48355f2 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestEnum.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public enum TestEnum { + E1, + E2() { + @Override + public void m() { } + }, + E3("-"), + E4("+") { + @Override + public void m() { } + }; + + public void m() { } + + private String s; + + private TestEnum() { this("?"); } + private TestEnum(@Deprecated String s) { this.s = s; } +} diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestExtendsList.java b/plugins/java-decompiler/engine/testData/src/pkg/TestExtendsList.java new file mode 100644 index 000000000000..812f83689ba6 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestExtendsList.java @@ -0,0 +1,26 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestExtendsList { + static <T extends Comparable<? super T>> T m1(T t) { + return null; + } + + static <T extends Object & Comparable<? super T>> T m2(T t) { + return null; + } +}
\ No newline at end of file diff --git a/plugins/java-decompiler/engine/testData/src/pkg/TestMethodParameters.java b/plugins/java-decompiler/engine/testData/src/pkg/TestMethodParameters.java new file mode 100644 index 000000000000..b9739e9cfda4 --- /dev/null +++ b/plugins/java-decompiler/engine/testData/src/pkg/TestMethodParameters.java @@ -0,0 +1,40 @@ +/* + * Copyright 2000-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package pkg; + +public class TestMethodParameters { + TestMethodParameters(@Deprecated int p01) { } + void m1(@Deprecated int p02) { } + static void m2(@Deprecated int p03) { } + + class C1 { + C1(@Deprecated int p11) { } + void m(@Deprecated int p12) { } + } + + static class C2 { + C2(@Deprecated int p21) { } + void m1(@Deprecated int p22) { } + static void m2(@Deprecated int p23) { } + } + + void local() { + class Local { + Local(@Deprecated int p31) { } + void m(@Deprecated int p32) { } + } + } +}
\ No newline at end of file |