    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 *  Unless required by applicable law or agreed to in writing, software
    012 *  distributed under the License is distributed on an "AS IS" BASIS,
    013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 *  See the License for the specific language governing permissions and
    015 *  limitations under the License.
    016 *
    017 */
    018package org.apache.bcel.util;
    019
    020import java.util.ArrayList;
    021import java.util.HashMap;
    022import java.util.Iterator;
    023import java.util.List;
    024import java.util.Locale;
    025import java.util.Map;
    026import java.util.regex.Matcher;
    027import java.util.regex.Pattern;
    028
    029import org.apache.bcel.Const;
    030import org.apache.bcel.generic.ClassGenException;
    031import org.apache.bcel.generic.InstructionHandle;
    032import org.apache.bcel.generic.InstructionList;
    033
    034/**
    035 * InstructionFinder is a tool to search for given instructions patterns, i.e.,
    036 * match sequences of instructions in an instruction list via regular
    037 * expressions. This can be used, e.g., in order to implement a peep hole
    038 * optimizer that looks for code patterns and replaces them with faster
    039 * equivalents.
    040 *
    041 * <p>
    042 * This class internally uses the java.util.regex
    043 * package to search for regular expressions.
    044 *
    045 * A typical application would look like this:
    046 *
    047 * <pre>
    048 *
    049 *
    050 *   InstructionFinder f   = new InstructionFinder(il);
    051 *   String            pat = &quot;IfInstruction ICONST_0 GOTO ICONST_1 NOP (IFEQ|IFNE)&quot;;
    052 *
    053 *   for (Iterator i = f.search(pat, constraint); i.hasNext(); ) {
    054 *   InstructionHandle[] match = (InstructionHandle[])i.next();
    055 *   ...
    056 *   il.delete(match[1], match[5]);
    057 *   ...
    058 *   }
    059 *
    060 *
    061 * </pre>
    062 *
    063 * @see org.apache.bcel.generic.Instruction
    064 * @see InstructionList
    065 */
    066public class InstructionFinder {
    067
    068    private static final int OFFSET = 32767; // char + OFFSET is outside of LATIN-1
    069    private static final int NO_OPCODES = 256; // Potential number, some are not used
    070    private static final Map<String, String> map = new HashMap<>();
    071    private final InstructionList il;
    072    private String il_string; // instruction list as string
    073    private InstructionHandle[] handles; // map instruction
    074
    075
    076    // list to array
    077    /**
    078     * @param il
    079     *          instruction list to search for given patterns
    080     */
    081    public InstructionFinder(final InstructionList il) {
    082        this.il = il;
    083        reread();
    084    }
    085
    086
    087    /**
    088     * Reread the instruction list, e.g., after you've altered the list upon a
    089     * match.
    090     */
    091    public final void reread() {
    092        final int size = il.getLength();
    093        final char[] buf = new char[size]; // Create a string with length equal to il length
    094        handles = il.getInstructionHandles();
    095        // Map opcodes to characters
    096        for (int i = 0; i < size; i++) {
    097            buf[i] = makeChar(handles[i].getInstruction().getOpcode());
    098        }
    099        il_string = new String(buf);
    100    }
    101
    102
    103    /**
    104     * Map symbolic instruction names like "getfield" to a single character.
    105     *
    106     * @param pattern
    107     *          instruction pattern in lower case
    108     * @return encoded string for a pattern such as "BranchInstruction".
    109     */
    110    private static String mapName( final String pattern ) {
    111        final String result = map.get(pattern);
    112        if (result != null) {
    113            return result;
    114        }
    115        for (short i = 0; i < NO_OPCODES; i++) {
    116            if (pattern.equals(Const.getOpcodeName(i))) {
    117                return "" + makeChar(i);
    118            }
    119        }
    120        throw new RuntimeException("Instruction unknown: " + pattern);
    121    }
    122
    123
    124    /**
    125     * Replace symbolic names of instructions with the appropiate character and
    126     * remove all white space from string. Meta characters such as +, * are
    127     * ignored.
    128     *
    129     * @param pattern
    130     *          The pattern to compile
    131     * @return translated regular expression string
    132     */
    133    private static String compilePattern( final String pattern ) {
    134        //Bug: BCEL-77 - Instructions are assumed to be english, to avoid odd Locale issues
    135        final String lower = pattern.toLowerCase(Locale.ENGLISH);
    136        final StringBuilder buf = new StringBuilder();
    137        final int size = pattern.length();
    138        for (int i = 0; i < size; i++) {
    139            char ch = lower.charAt(i);
    140            if (Character.isLetterOrDigit(ch)) {
    141                final StringBuilder name = new StringBuilder();
    142                while ((Character.isLetterOrDigit(ch) || ch == '_') && i < size) {
    143                    name.append(ch);
    144                    if (++i < size) {
    145                        ch = lower.charAt(i);
    146                    } else {
    147                        break;
    148                    }
    149                }
    150                i--;
    151                buf.append(mapName(name.toString()));
    152            } else if (!Character.isWhitespace(ch)) {
    153                buf.append(ch);
    154            }
    155        }
    156        return buf.toString();
    157    }
    158
    159
    160    /**
    161     * @return the matched piece of code as an array of instruction (handles)
    162     */
    163    private InstructionHandle[] getMatch( final int matched_from, final int match_length ) {
    164        final InstructionHandle[] match = new InstructionHandle[match_length];
    165        System.arraycopy(handles, matched_from, match, 0, match_length);
    166        return match;
    167    }
    168
    169
    170    /**
    171     * Search for the given pattern in the instruction list. You can search for
    172     * any valid opcode via its symbolic name, e.g. "istore". You can also use a
    173     * super class or an interface name to match a whole set of instructions, e.g.
    174     * "BranchInstruction" or "LoadInstruction". "istore" is also an alias for all
    175     * "istore_x" instructions. Additional aliases are "if" for "ifxx", "if_icmp"
    176     * for "if_icmpxx", "if_acmp" for "if_acmpxx".
    177     *
    178     * Consecutive instruction names must be separated by white space which will
    179     * be removed during the compilation of the pattern.
    180     *
    181     * For the rest the usual pattern matching rules for regular expressions
    182     * apply.
    183     * <P>
    184     * Example pattern:
    185     *
    186     * <pre>
    187     * search(&quot;BranchInstruction NOP ((IfInstruction|GOTO)+ ISTORE Instruction)*&quot;);
    188     * </pre>
    189     *
    190     * <p>
    191     * If you alter the instruction list upon a match such that other matching
    192     * areas are affected, you should call reread() to update the finder and call
    193     * search() again, because the matches are cached.
    194     *
    195     * @param pattern
    196     *          the instruction pattern to search for, where case is ignored
    197     * @param from
    198     *          where to start the search in the instruction list
    199     * @param constraint
    200     *          optional CodeConstraint to check the found code pattern for
    201     *          user-defined constraints
    202     * @return iterator of matches where e.nextElement() returns an array of
    203     *         instruction handles describing the matched area
    204     */
    205    public final Iterator<InstructionHandle[]> search( final String pattern, final InstructionHandle from, final CodeConstraint constraint ) {
    206        final String search = compilePattern(pattern);
    207        int start = -1;
    208        for (int i = 0; i < handles.length; i++) {
    209            if (handles[i] == from) {
    210                start = i; // Where to start search from (index)
    211                break;
    212            }
    213        }
    214        if (start == -1) {
    215            throw new ClassGenException("Instruction handle " + from
    216                    + " not found in instruction list.");
    217        }
    218        final Pattern regex = Pattern.compile(search);
    219        final List<InstructionHandle[]> matches = new ArrayList<>();
    220        final Matcher matcher = regex.matcher(il_string);
    221        while (start < il_string.length() && matcher.find(start)) {
    222            final int startExpr = matcher.start();
    223            final int endExpr = matcher.end();
    224            final int lenExpr = endExpr - startExpr;
    225            final InstructionHandle[] match = getMatch(startExpr, lenExpr);
    226            if ((constraint == null) || constraint.checkCode(match)) {
    227                matches.add(match);
    228            }
    229            start = endExpr;
    230        }
    231        return matches.iterator();
    232    }
    233
    234
    235    /**
    236     * Start search beginning from the start of the given instruction list.
    237     *
    238     * @param pattern
    239     *          the instruction pattern to search for, where case is ignored
    240     * @return iterator of matches where e.nextElement() returns an array of
    241     *         instruction handles describing the matched area
    242     */
    243    public final Iterator<InstructionHandle[]> search( final String pattern ) {
    244        return search(pattern, il.getStart(), null);
    245    }
    246
    247
    248    /**
    249     * Start search beginning from `from'.
    250     *
    251     * @param pattern
    252     *          the instruction pattern to search for, where case is ignored
    253     * @param from
    254     *          where to start the search in the instruction list
    255     * @return iterator of matches where e.nextElement() returns an array of
    256     *         instruction handles describing the matched area
    257     */
    258    public final Iterator<InstructionHandle[]> search( final String pattern, final InstructionHandle from ) {
    259        return search(pattern, from, null);
    260    }
    261
    262
    263    /**
    264     * Start search beginning from the start of the given instruction list. Check
    265     * found matches with the constraint object.
    266     *
    267     * @param pattern
    268     *          the instruction pattern to search for, case is ignored
    269     * @param constraint
    270     *          constraints to be checked on matching code
    271     * @return instruction handle or `null' if the match failed
    272     */
    273    public final Iterator<InstructionHandle[]> search( final String pattern, final CodeConstraint constraint ) {
    274        return search(pattern, il.getStart(), constraint);
    275    }
    276
    277
    278    /**
    279     * Convert opcode number to char.
    280     */
    281    private static char makeChar( final short opcode ) {
    282        return (char) (opcode + OFFSET);
    283    }
    284
    285
    286    /**
    287     * @return the inquired instruction list
    288     */
    289    public final InstructionList getInstructionList() {
    290        return il;
    291    }
    292
    293    /**
    294     * Code patterns found may be checked using an additional user-defined
    295     * constraint object whether they really match the needed criterion. I.e.,
    296     * check constraints that can not expressed with regular expressions.
    297     *
    298     */
    299    public interface CodeConstraint {
    300
    301        /**
    302         * @param match
    303         *          array of instructions matching the requested pattern
    304         * @return true if the matched area is really useful
    305         */
    306        boolean checkCode( InstructionHandle[] match );
    307    }
    308
    309    // Initialize pattern map
    310    static {
    311        map.put("arithmeticinstruction","(irem|lrem|iand|ior|ineg|isub|lneg|fneg|fmul|ldiv|fadd|lxor|frem|idiv|land|ixor|ishr|fsub|lshl|fdiv|iadd|lor|dmul|lsub|ishl|imul|lmul|lushr|dneg|iushr|lshr|ddiv|drem|dadd|ladd|dsub)");
    312        map.put("invokeinstruction", "(invokevirtual|invokeinterface|invokestatic|invokespecial|invokedynamic)");
    313        map.put("arrayinstruction", "(baload|aastore|saload|caload|fastore|lastore|iaload|castore|iastore|aaload|bastore|sastore|faload|laload|daload|dastore)");
    314        map.put("gotoinstruction", "(goto|goto_w)");
    315        map.put("conversioninstruction", "(d2l|l2d|i2s|d2i|l2i|i2b|l2f|d2f|f2i|i2d|i2l|f2d|i2c|f2l|i2f)");
    316        map.put("localvariableinstruction","(fstore|iinc|lload|dstore|dload|iload|aload|astore|istore|fload|lstore)");
    317        map.put("loadinstruction", "(fload|dload|lload|iload|aload)");
    318        map.put("fieldinstruction", "(getfield|putstatic|getstatic|putfield)");
    319        map.put("cpinstruction", "(ldc2_w|invokeinterface|invokedynamic|multianewarray|putstatic|instanceof|getstatic|checkcast|getfield|invokespecial|ldc_w|invokestatic|invokevirtual|putfield|ldc|new|anewarray)");
    320        map.put("stackinstruction", "(dup2|swap|dup2_x2|pop|pop2|dup|dup2_x1|dup_x2|dup_x1)");
    321        map.put("branchinstruction", "(ifle|if_acmpne|if_icmpeq|if_acmpeq|ifnonnull|goto_w|iflt|ifnull|if_icmpne|tableswitch|if_icmple|ifeq|if_icmplt|jsr_w|if_icmpgt|ifgt|jsr|goto|ifne|ifge|lookupswitch|if_icmpge)");
    322        map.put("returninstruction", "(lreturn|ireturn|freturn|dreturn|areturn|return)");
    323        map.put("storeinstruction", "(istore|fstore|dstore|astore|lstore)");
    324        map.put("select", "(tableswitch|lookupswitch)");
    325        map.put("ifinstruction", "(ifeq|ifgt|if_icmpne|if_icmpeq|ifge|ifnull|ifne|if_icmple|if_icmpge|if_acmpeq|if_icmplt|if_acmpne|ifnonnull|iflt|if_icmpgt|ifle)");
    326        map.put("jsrinstruction", "(jsr|jsr_w)");
    327        map.put("variablelengthinstruction", "(tableswitch|jsr|goto|lookupswitch)");
    328        map.put("unconditionalbranch", "(goto|jsr|jsr_w|athrow|goto_w)");
    329        map.put("constantpushinstruction", "(dconst|bipush|sipush|fconst|iconst|lconst)");
    330        map.put("typedinstruction", "(imul|lsub|aload|fload|lor|new|aaload|fcmpg|iand|iaload|lrem|idiv|d2l|isub|dcmpg|dastore|ret|f2d|f2i|drem|iinc|i2c|checkcast|frem|lreturn|astore|lushr|daload|dneg|fastore|istore|lshl|ldiv|lstore|areturn|ishr|ldc_w|invokeinterface|invokedynamic|aastore|lxor|ishl|l2d|i2f|return|faload|sipush|iushr|caload|instanceof|invokespecial|putfield|fmul|ireturn|laload|d2f|lneg|ixor|i2l|fdiv|lastore|multianewarray|i2b|getstatic|i2d|putstatic|fcmpl|saload|ladd|irem|dload|jsr_w|dconst|dcmpl|fsub|freturn|ldc|aconst_null|castore|lmul|ldc2_w|dadd|iconst|f2l|ddiv|dstore|land|jsr|anewarray|dmul|bipush|dsub|sastore|d2i|i2s|lshr|iadd|l2i|lload|bastore|fstore|fneg|iload|fadd|baload|fconst|ior|ineg|dreturn|l2f|lconst|getfield|invokevirtual|invokestatic|iastore)");
    331        map.put("popinstruction", "(fstore|dstore|pop|pop2|astore|putstatic|istore|lstore)");
    332        map.put("allocationinstruction", "(multianewarray|new|anewarray|newarray)");
    333        map.put("indexedinstruction", "(lload|lstore|fload|ldc2_w|invokeinterface|invokedynamic|multianewarray|astore|dload|putstatic|instanceof|getstatic|checkcast|getfield|invokespecial|dstore|istore|iinc|ldc_w|ret|fstore|invokestatic|iload|putfield|invokevirtual|ldc|new|aload|anewarray)");
    334        map.put("pushinstruction", "(dup|lload|dup2|bipush|fload|ldc2_w|sipush|lconst|fconst|dload|getstatic|ldc_w|aconst_null|dconst|iload|ldc|iconst|aload)");
    335        map.put("stackproducer", "(imul|lsub|aload|fload|lor|new|aaload|fcmpg|iand|iaload|lrem|idiv|d2l|isub|dcmpg|dup|f2d|f2i|drem|i2c|checkcast|frem|lushr|daload|dneg|lshl|ldiv|ishr|ldc_w|invokeinterface|invokedynamic|lxor|ishl|l2d|i2f|faload|sipush|iushr|caload|instanceof|invokespecial|fmul|laload|d2f|lneg|ixor|i2l|fdiv|getstatic|i2b|swap|i2d|dup2|fcmpl|saload|ladd|irem|dload|jsr_w|dconst|dcmpl|fsub|ldc|arraylength|aconst_null|tableswitch|lmul|ldc2_w|iconst|dadd|f2l|ddiv|land|jsr|anewarray|dmul|bipush|dsub|d2i|newarray|i2s|lshr|iadd|lload|l2i|fneg|iload|fadd|baload|fconst|lookupswitch|ior|ineg|lconst|l2f|getfield|invokevirtual|invokestatic)");
    336        map.put("stackconsumer", "(imul|lsub|lor|iflt|fcmpg|if_icmpgt|iand|ifeq|if_icmplt|lrem|ifnonnull|idiv|d2l|isub|dcmpg|dastore|if_icmpeq|f2d|f2i|drem|i2c|checkcast|frem|lreturn|astore|lushr|pop2|monitorexit|dneg|fastore|istore|lshl|ldiv|lstore|areturn|if_icmpge|ishr|monitorenter|invokeinterface|invokedynamic|aastore|lxor|ishl|l2d|i2f|return|iushr|instanceof|invokespecial|fmul|ireturn|d2f|lneg|ixor|pop|i2l|ifnull|fdiv|lastore|i2b|if_acmpeq|ifge|swap|i2d|putstatic|fcmpl|ladd|irem|dcmpl|fsub|freturn|ifgt|castore|lmul|dadd|f2l|ddiv|dstore|land|if_icmpne|if_acmpne|dmul|dsub|sastore|ifle|d2i|i2s|lshr|iadd|l2i|bastore|fstore|fneg|fadd|ior|ineg|ifne|dreturn|l2f|if_icmple|getfield|invokevirtual|invokestatic|iastore)");
    337        map.put("exceptionthrower","(irem|lrem|laload|putstatic|baload|dastore|areturn|getstatic|ldiv|anewarray|iastore|castore|idiv|saload|lastore|fastore|putfield|lreturn|caload|getfield|return|aastore|freturn|newarray|instanceof|multianewarray|athrow|faload|iaload|aaload|dreturn|monitorenter|checkcast|bastore|arraylength|new|invokevirtual|sastore|ldc_w|ireturn|invokespecial|monitorexit|invokeinterface|invokedynamic|ldc|invokestatic|daload)");
    338        map.put("loadclass", "(multianewarray|invokeinterface|invokedynamic|instanceof|invokespecial|putfield|checkcast|putstatic|invokevirtual|new|getstatic|invokestatic|getfield|anewarray)");
    339        map.put("instructiontargeter", "(ifle|if_acmpne|if_icmpeq|if_acmpeq|ifnonnull|goto_w|iflt|ifnull|if_icmpne|tableswitch|if_icmple|ifeq|if_icmplt|jsr_w|if_icmpgt|ifgt|jsr|goto|ifne|ifge|lookupswitch|if_icmpge)");
    340        // Some aliases
    341        map.put("if_icmp", "(if_icmpne|if_icmpeq|if_icmple|if_icmpge|if_icmplt|if_icmpgt)");
    342        map.put("if_acmp", "(if_acmpeq|if_acmpne)");
    343        map.put("if", "(ifeq|ifne|iflt|ifge|ifgt|ifle)");
    344        // Precompile some aliases first
    345        map.put("iconst", precompile(Const.ICONST_0, Const.ICONST_5, Const.ICONST_M1));
    346        map.put("lconst", new String(new char[] { '(', makeChar(Const.LCONST_0), '|', makeChar(Const.LCONST_1), ')' }));
    347        map.put("dconst", new String(new char[] { '(', makeChar(Const.DCONST_0), '|', makeChar(Const.DCONST_1), ')' }));
    348        map.put("fconst", new String(new char[] { '(', makeChar(Const.FCONST_0), '|', makeChar(Const.FCONST_1), '|', makeChar(Const.FCONST_2), ')' }));
    349        map.put("lload", precompile(Const.LLOAD_0, Const.LLOAD_3, Const.LLOAD));
    350        map.put("iload", precompile(Const.ILOAD_0, Const.ILOAD_3, Const.ILOAD));
    351        map.put("dload", precompile(Const.DLOAD_0, Const.DLOAD_3, Const.DLOAD));
    352        map.put("fload", precompile(Const.FLOAD_0, Const.FLOAD_3, Const.FLOAD));
    353        map.put("aload", precompile(Const.ALOAD_0, Const.ALOAD_3, Const.ALOAD));
    354        map.put("lstore", precompile(Const.LSTORE_0, Const.LSTORE_3, Const.LSTORE));
    355        map.put("istore", precompile(Const.ISTORE_0, Const.ISTORE_3, Const.ISTORE));
    356        map.put("dstore", precompile(Const.DSTORE_0, Const.DSTORE_3, Const.DSTORE));
    357        map.put("fstore", precompile(Const.FSTORE_0, Const.FSTORE_3, Const.FSTORE));
    358        map.put("astore", precompile(Const.ASTORE_0, Const.ASTORE_3, Const.ASTORE));
    359        // Compile strings
    360        for (final Map.Entry<String, String> entry : map.entrySet()) {
    361            final String key = entry.getKey();
    362            final String value = entry.getValue();
    363            final char ch = value.charAt(1); // Omit already precompiled patterns
    364            if (ch < OFFSET) {
    365                map.put(key, compilePattern(value)); // precompile all patterns
    366            }
    367        }
    368        // Add instruction alias to match anything
    369        final StringBuilder buf = new StringBuilder("(");
    370        for (short i = 0; i < NO_OPCODES; i++) {
    371            if (Const.getNoOfOperands(i) != Const.UNDEFINED) { // Not an invalid opcode
    372                buf.append(makeChar(i));
    373                if (i < NO_OPCODES - 1) {
    374                    buf.append('|');
    375                }
    376            }
    377        }
    378        buf.append(')');
    379        map.put("instruction", buf.toString());
    380    }
    381
    382
    383    private static String precompile( final short from, final short to, final short extra ) {
    384        final StringBuilder buf = new StringBuilder("(");
    385        for (short i = from; i <= to; i++) {
    386            buf.append(makeChar(i));
    387            buf.append('|');
    388        }
    389        buf.append(makeChar(extra));
    390        buf.append(")");
    391        return buf.toString();
    392    }
    393
    394
    395    /*
    396     * Internal debugging routines.
    397     */
    398//    private static final String pattern2string( String pattern ) {
    399//        return pattern2string(pattern, true);
    400//    }
    401
    402
    403//    private static final String pattern2string( String pattern, boolean make_string ) {
    404//        StringBuffer buf = new StringBuffer();
    405//        for (int i = 0; i < pattern.length(); i++) {
    406//            char ch = pattern.charAt(i);
    407//            if (ch >= OFFSET) {
    408//                if (make_string) {
    409//                    buf.append(Constants.getOpcodeName(ch - OFFSET));
    410//                } else {
    411//                    buf.append((ch - OFFSET));
    412//                }
    413//            } else {
    414//                buf.append(ch);
    415//            }
    416//        }
    417//        return buf.toString();
    418//    }
    419}