Java Code Examples for org.apache.bcel.generic.InstructionHandle

The following examples show how to use org.apache.bcel.generic.InstructionHandle. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Get the basic block in the subroutine for the given instruction. If
 * the block doesn't exist yet, it is created, and a work list item is
 * added which will populate it. Note that if start is an exception
 * thrower, the block returned will be its ETB.
 *
 * @param start
 *            the start instruction for the block
 * @return the basic block for the instruction
 */
public BasicBlock getBlock(InstructionHandle start) {
    BasicBlock block = blockMap.get(start);
    if (block == null) {
        block = allocateBasicBlock();
        blockMap.put(start, block);

        // Block is an exception handler?
        CodeExceptionGen exceptionGen = exceptionHandlerMap.getHandlerForStartInstruction(start);
        if (exceptionGen != null) {
            block.setExceptionGen(null, exceptionGen);
        }

        addItem(new WorkListItem(start, block));
    }
    return block;
}
 
Example 2
/**
 * @see org.apache.bcel.classfile.Visitor#visitCode
 */
public void visitCode(Code aCode)
{   
    for (Iterator iter = mVisitors.iterator(); iter.hasNext();) {
        IDeepVisitor visitor = (IDeepVisitor) iter.next();
        Visitor v = visitor.getClassFileVisitor();
        aCode.accept(v);
    }
    
    // perform a deep visit
    final byte[] code = aCode.getCode();
    final InstructionList list = new InstructionList(code);
    final Iterator it = list.iterator();
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        InstructionHandle instruction = (InstructionHandle) iter.next();
        visitInstructionHandle(instruction);
    }
}
 
Example 3
@Override
protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
                                           InstructionHandle handle) {
    assert invoke != null && cpg != null;

    String method = invoke.getMethodName(cpg);
    String sig    = invoke.getSignature(cpg);

    if(method.equals("registerReceiver")){
        if(sig.contains("Ljava/lang/String;")){
            if(sig.contains(";I)")){
                return new InjectionPoint(new int[]{2}, ANDROID_REGISTER_RECEIVER_TYPE);
            }else{
                return new InjectionPoint(new int[]{1}, ANDROID_REGISTER_RECEIVER_TYPE);
            }
        }
    }
    return InjectionPoint.NONE;
}
 
Example 4
@Override
    protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
                                               InstructionHandle handle) {
        assert invoke != null && cpg != null;

        String method = invoke.getMethodName(cpg);
        String sig    = invoke.getSignature(cpg);
//        System.out.println(invoke.getClassName(cpg));
        if(sig.contains("Ljava/lang/String;")) {
            if("loadUrl".equals(method)){
                if(sig.contains("Ljava/util/Map;")){
                    return new InjectionPoint(new int[]{1}, WEBVIEW_LOAD_DATA_URL_TYPE);
                }else{
                    return new InjectionPoint(new int[]{0}, WEBVIEW_LOAD_DATA_URL_TYPE);
                }
            }else if("loadData".equals(method)){
                return new InjectionPoint(new int[]{2}, WEBVIEW_LOAD_DATA_URL_TYPE);
            }else if("loadDataWithBaseURL".equals(method)){
                //BUG
                return new InjectionPoint(new int[]{4}, WEBVIEW_LOAD_DATA_URL_TYPE);
            }
        }
        return InjectionPoint.NONE;
    }
 
Example 5
Source Project: commons-bcel   Source File: Subroutines.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the leaving RET instruction. Must be invoked after all instructions are added.
 * Must not be invoked for top-level 'subroutine'.
 */
void setLeavingRET() {
    if (localVariable == UNSET) {
        throw new AssertionViolatedException(
            "setLeavingRET() called for top-level 'subroutine' or forgot to set local variable first.");
    }
    InstructionHandle ret = null;
    for (final InstructionHandle actual : instructions) {
        if (actual.getInstruction() instanceof RET) {
            if (ret != null) {
                throw new StructuralCodeConstraintException(
                    "Subroutine with more then one RET detected: '"+ret+"' and '"+actual+"'.");
            }
            ret = actual;
        }
    }
    if (ret == null) {
        throw new StructuralCodeConstraintException("Subroutine without a RET detected.");
    }
    if (((RET) ret.getInstruction()).getIndex() != localVariable) {
        throw new StructuralCodeConstraintException(
            "Subroutine uses '"+ret+"' which does not match the correct local variable '"+localVariable+"'.");
    }
    theRET = ret;
}
 
Example 6
/**
 * @see org.apache.bcel.classfile.Visitor#visitCode
 */
public void visitCode(Code aCode)
{   
    for (Iterator iter = mVisitors.iterator(); iter.hasNext();) {
        IDeepVisitor visitor = (IDeepVisitor) iter.next();
        Visitor v = visitor.getClassFileVisitor();
        aCode.accept(v);
    }
    
    // perform a deep visit
    final byte[] code = aCode.getCode();
    final InstructionList list = new InstructionList(code);
    final Iterator it = list.iterator();
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        InstructionHandle instruction = (InstructionHandle) iter.next();
        visitInstructionHandle(instruction);
    }
}
 
Example 7
public static boolean isThrower(BasicBlock target) {
    InstructionHandle ins = target.getFirstInstruction();
    int maxCount = 7;
    while (ins != null) {
        if (maxCount-- <= 0) {
            break;
        }
        Instruction i = ins.getInstruction();
        if (i instanceof ATHROW) {
            return true;
        }
        if (i instanceof InstructionTargeter || i instanceof ReturnInstruction) {
            return false;
        }
        ins = ins.getNext();
    }
    return false;
}
 
Example 8
Source Project: spotbugs   Source File: Stream.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean isStreamOpen(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, ResourceValueFrame frame) {
    if (isOpenOnCreation) {
        return false;
    }

    Instruction ins = handle.getInstruction();
    if (!(ins instanceof INVOKESPECIAL)) {
        return false;
    }

    // Does this instruction open the stream?
    INVOKESPECIAL inv = (INVOKESPECIAL) ins;

    return frame.isValid() && getInstanceValue(frame, inv, cpg).isInstance()
            && matchMethod(inv, cpg, this.getResourceClass(), Const.CONSTRUCTOR_NAME);
}
 
Example 9
Source Project: spotbugs   Source File: CFG.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public Location getPreviousLocation(Location loc) {
    InstructionHandle handle = loc.getHandle();

    BasicBlock basicBlock = loc.getBasicBlock();
    if (basicBlock.getFirstInstruction().equals(handle)) {
        BasicBlock prevBlock = basicBlock;

        while (true) {
            prevBlock = getPredecessorWithEdgeType(prevBlock, EdgeTypes.FALL_THROUGH_EDGE);
            if (prevBlock == null) {
                return loc;
            }

            handle = prevBlock.getLastInstruction();
            if (handle != null) {
                return new Location(handle, prevBlock);
            }
        }

    } else {
        handle = handle.getPrev();
        return new Location(handle, basicBlock);

    }

}
 
Example 10
private Type nullCheck(short opcode, Edge edge, InstructionHandle last, BasicBlock sourceBlock)
        throws DataflowAnalysisException {
    if (DEBUG_NULL_CHECK) {
        System.out.println("checking for nullcheck on edge " + edge);
    }
    Type type = null;
    if ((opcode == Const.IFNULL && edge.getType() == EdgeTypes.IFCMP_EDGE)
            || (opcode == Const.IFNONNULL && edge.getType() == EdgeTypes.FALL_THROUGH_EDGE)) {
        Location location = new Location(last, sourceBlock);
        TypeFrame typeFrame = typeDataflow.getFactAtLocation(location);
        if (typeFrame.isValid()) {
            type = typeFrame.getTopValue();
            if (DEBUG_NULL_CHECK) {
                System.out.println("ifnull comparison of " + type + " to null at " + last);
            }
        }
    }
    return type;
}
 
Example 11
public List<Edge> getDuplicates(CFG cfg, Edge edge) {
    InstructionHandle ih = edge.getSource().getLastInstruction();
    if (ih == null) {
        return Collections.emptyList();
    }
    BitSet duplicates = getDuplicates(ih.getPosition());
    if (duplicates.isEmpty()) {
        return Collections.emptyList();
    }
    List<Edge> result = new ArrayList<>();
    for (Iterator<Edge> edgeIterator = cfg.edgeIterator(); edgeIterator.hasNext();) {
        Edge next = edgeIterator.next();
        if (next.getType() != edge.getType()) {
            continue;
        }
        InstructionHandle lastInst = next.getSource().getLastInstruction();
        if (lastInst != null && lastInst.getPosition() >= 0 && duplicates.get(lastInst.getPosition())) {
            result.add(next);
        }
    }
    return result;
}
 
Example 12
/**
 * @param handle instruction handle which loads the object for further GETFIELD/PUTFIELD operation
 * @return true if this object is known to be non-null
 */
private boolean isSafeFieldSource(InstructionHandle handle) {
    while (handle != null && handle.getInstruction().getOpcode() == Const.DUP) {
        // Some compilers generate DUP for field increment code like
        // ALOAD_0 / DUP / GETFIELD x / ICONST_1 / IADD / PUTFIELD x
        handle = handle.getPrev();
    }
    if (handle == null) {
        return false;
    }
    Instruction inst = handle.getInstruction();
    if (inst.getOpcode() == Const.ALOAD_0) {
        return true;
    }
    return inst instanceof GETFIELD && ((GETFIELD) inst).getFieldName(cpg).startsWith("this$");
}
 
Example 13
/**
 * @param methodGen method
 * @param start instruction to scan
 * @return instruction which consumes value which was on top of stack before start instruction
 * or null if cannot be determined
 */
private InstructionHandle getConsumer(MethodGen methodGen, InstructionHandle start) {
    int depth = 1;
    InstructionHandle cur = start;
    while (cur != null) {
        Instruction inst = cur.getInstruction();
        depth -= inst.consumeStack(methodGen.getConstantPool());
        if (depth <= 0) {
            return cur;
        }
        depth += inst.produceStack(methodGen.getConstantPool());
        if (inst instanceof BranchInstruction) {
            if (inst instanceof GotoInstruction) {
                cur = ((GotoInstruction) inst).getTarget();
                continue;
            }
            if (!(inst instanceof IfInstruction)) {
                return null;
            }
        }
        cur = cur.getNext();
    }
    return null;
}
 
Example 14
public void addAccess(MethodDescriptor method, InstructionHandle handle, boolean isLocked) {
    if (!interesting) {
        return;
    }
    if (!SYNC_ACCESS && isLocked) {
        return;
    }

    if (!servletField && !isLocked && syncAccessList.size() == 0 && unsyncAccessList.size() > 6) {
        interesting = false;
        syncAccessList = null;
        unsyncAccessList = null;
        return;
    }
    FieldAccess fa = new FieldAccess(method, handle.getPosition());
    if (isLocked) {
        syncAccessList = Util.addTo(syncAccessList, fa);
    } else {
        unsyncAccessList = Util.addTo(unsyncAccessList, fa);
    }
}
 
Example 15
@Override
public void transfer(BasicBlock basicBlock, @CheckForNull InstructionHandle end, BlockType start, BlockType result)
        throws DataflowAnalysisException {
    result.copyFrom(start);

    if (start.isValid() && basicBlock.isExceptionHandler()) {
        CodeExceptionGen exceptionGen = basicBlock.getExceptionGen();
        ObjectType catchType = exceptionGen.getCatchType();
        if (catchType == null) {
            // Probably a finally block, or a synchronized block
            // exception-compensation catch block.
            result.pushFinally();
        } else {
            // Catch type was explicitly specified:
            // this is probably a programmer-written catch block
            result.pushCatch();
        }
    }
}
 
Example 16
Source Project: commons-bcel   Source File: TestReturn01Creator.java    License: Apache License 2.0 6 votes vote down vote up
private void createMethod_1() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS,
          new String[] {  }, "foo", TEST_PACKAGE+".TestReturn01", il, _cp);

  final InstructionHandle ih_0 = il.append(_factory.createNew("java.lang.Object"));
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(InstructionConst.DUP);
  il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
  il.append(InstructionConst.NOP);
  final InstructionHandle ih_8 = il.append(InstructionFactory.createReturn(Type.OBJECT));
  Assert.assertNotNull(ih_8); // TODO why is this not used
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example 17
@Override
public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, StateSet fact)
        throws DataflowAnalysisException {
    Collection<ObligationPolicyDatabaseAction> actionList = actionCache.getActions(basicBlock, handle);
    if (actionList.isEmpty()) {
        return;
    }
    if (DEBUG) {
        System.out.println("Applying actions at " + handle + " to " + fact);
    }
    for (ObligationPolicyDatabaseAction action : actionList) {
        if (DEBUG) {
            System.out.print("  " + action + "...");
        }
        action.apply(fact, basicBlock.getLabel());
        if (DEBUG) {
            System.out.println(fact);
        }
    }
}
 
Example 18
@Override
protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
        InstructionHandle handle) {
    assert invoke != null && cpg != null;

    //1. Verify if the class used has a known sink
    String fullMethodName = getFullMethodName(invoke, cpg);
    //This will skip the most common lookup
    if ("java/lang/Object.<init>()V".equals(fullMethodName)) {
        return InjectionPoint.NONE;
    }

    InjectionPoint injectionPoint = injectionMap.get(fullMethodName);
    if (injectionPoint != null) {
        return injectionPoint;
    }

    try {
        //2. Verify if the super classes match a known sink
        JavaClass classDef = Repository.lookupClass(invoke.getClassName(cpg));
        for (JavaClass superClass : classDef.getSuperClasses()) {
            if ("java.lang.Object".equals(superClass.getClassName())) {
                continue;
            }
            String superClassFullMethodName = superClass.getClassName().replace('.','/')
                    + "." + invoke.getMethodName(cpg) + invoke.getSignature(cpg);
            injectionPoint = injectionMap.get(superClassFullMethodName);
            if (injectionPoint != null) {
                return injectionPoint;
            }
        }
    } catch (ClassNotFoundException e) {
        AnalysisContext.reportMissingClass(e);
    }
    return InjectionPoint.NONE;
}
 
Example 19
private void addExceptionHandler(CodeExceptionGen exceptionHandler) {
    InstructionHandle handlerPC = exceptionHandler.getHandlerPC();
    CodeExceptionGen existing = startInstructionToHandlerMap.get(handlerPC);
    if (existing != null) {
        exceptionHandler = merge(this.merger, existing, exceptionHandler);
    }
    startInstructionToHandlerMap.put(handlerPC, exceptionHandler);
}
 
Example 20
/**
 * Add an instruction to the subroutine. We keep track of which
 * instructions are part of which subroutines. No instruction may be
 * part of more than one subroutine.
 *
 * @param handle
 *            the instruction to be added to the subroutine
 */
public void addInstruction(InstructionHandle handle) throws CFGBuilderException {
    int position = handle.getPosition();
    if (usedInstructionSet.get(position)) {
        throw new CFGBuilderException("Instruction " + handle + " visited in multiple subroutines");
    }
    instructionSet.set(position);
    usedInstructionSet.set(position);
}
 
Example 21
Source Project: commons-bcel   Source File: HandleTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that branch handles can be added an instruction list, without
 * corrupting the list.
 */
static void branchHandles() {
    for (int i = 0; i < MAXI; i++) {
        final InstructionList list = new InstructionList();
        final InstructionHandle start = list.append(new NOP());
        try {
            for (int j = 0; j < MAXJ; j++) {
                list.append(new GOTO(start));
            }
            final InstructionHandle[] instructionHandles = list.getInstructionHandles();
            for (int j = 0; j < instructionHandles.length; j++) {
                final InstructionHandle handle = instructionHandles[j];
                if (j > 0) {
                    checkLinkage(handle, j);
                    if (start != ((GOTO) handle.getInstruction()).getTarget()) {
                        final AssertionFailedError error = new AssertionFailedError(
                                "unexpected instruction at index " + j);
                        exception = error;
                        throw error;
                    }
                }
            }
            if (exception != null) {
                return;
            }
        } catch (final NullPointerException e) {
            System.out.println("NPE at i=" + i);
            exception = e;
            throw e;
        }
        list.dispose(); // this initializes caching of unused instruction handles
    }
}
 
Example 22
Source Project: commons-bcel   Source File: ControlFlowGraph.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the InstructionContext of a given instruction.
 */
public InstructionContext contextOf(final InstructionHandle inst) {
    final InstructionContext ic = instructionContexts.get(inst);
    if (ic == null) {
        throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!");
    }
    return ic;
}
 
Example 23
Source Project: spotbugs   Source File: Opcode.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after,
        BindingSet bindingSet) throws DataflowAnalysisException {

    if (handle.getInstruction().getOpcode() == opcode) {
        return new MatchResult(this, bindingSet);
    } else {
        return null;
    }

}
 
Example 24
Source Project: commons-bcel   Source File: TestReturn01Creator.java    License: Apache License 2.0 5 votes vote down vote up
private void createMethod_0() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {  },
          "<init>", TEST_PACKAGE+".TestReturn01", il, _cp);

  final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
  final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
  Assert.assertNotNull(ih_4); // TODO why is this not used
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example 25
Source Project: spotbugs   Source File: LazyInit.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean potentialInitialization(InstructionHandle nextHandle) {
    if (nextHandle == null) {
        return true;
    }
    Instruction instruction = nextHandle.getInstruction();
    return !(instruction instanceof ReturnInstruction
            || instruction instanceof IfInstruction);
}
 
Example 26
Source Project: spotbugs   Source File: Monitorenter.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after,
        BindingSet bindingSet) throws DataflowAnalysisException {

    // Instruction must be MONITORENTER.
    Instruction ins = handle.getInstruction();
    if (!(ins instanceof MONITORENTER)) {
        return null;
    }

    // Ensure the object being locked matches any previous
    // instructions which bound our variable name to a value.
    Variable lock = new LocalVariable(before.getTopValue());
    return addOrCheckDefinition(lock, bindingSet);
}
 
Example 27
Source Project: commons-bcel   Source File: ASTLetExpr.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fifth pass, produce Java byte code.
 */
@Override
public void byte_code(final InstructionList il, final MethodGen method, final ConstantPoolGen cp) {
  final int size = idents.length;
  final LocalVariableGen[] l = new LocalVariableGen[size];

  for(int i=0; i < size; i++) {
    final String           ident = idents[i].getName();
    final Variable         entry = (Variable)env.get(ident);
    final Type             t     = BasicType.getType((byte)idents[i].getType());
    final LocalVariableGen lg    = method.addLocalVariable(ident, t, null, null);
    final int              slot  = lg.getIndex();

    entry.setLocalVariable(lg);
    InstructionHandle start = il.getEnd();
    exprs[i].byte_code(il, method, cp);
    start = (start == null)? il.getStart() : start.getNext();
    lg.setStart(start);
    il.append(new ISTORE(slot));     ASTFunDecl.pop();
    l[i] = lg;
  }

  body.byte_code(il, method, cp);
  final InstructionHandle end = il.getEnd();
  for(int i=0; i < size; i++) {
      l[i].setEnd(end);
  }
}
 
Example 28
Source Project: commons-bcel   Source File: HandleTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that instruction handles can be added an instruction list, without
 * corrupting the list.
 */
static void handles() {
    for (int i = 0; i < MAXI; i++) {
        final InstructionList list = new InstructionList();
        try {
            for (int j = 0; j < MAXJ; j++) {
                list.append(new ILOAD(j));
            }
            final InstructionHandle[] instructionHandles = list.getInstructionHandles();
            for (int j = 0; j < instructionHandles.length; j++) {
                final InstructionHandle handle = instructionHandles[j];
                checkLinkage(handle, j);
                if (j != ((ILOAD) handle.getInstruction()).getIndex()) {
                    final AssertionFailedError error = new AssertionFailedError("unexpected instruction at index " + j);
                    exception = error;
                    throw error;
                }
            }
            if (exception != null) {
                return;
            }
        } catch (final NullPointerException e) {
            System.out.println("NPE at i=" + i);
            exception = e;
            throw e;
        }
        list.dispose(); // this initializes caching of unused instruction handles
    }
}
 
Example 29
Source Project: commons-bcel   Source File: Subroutines.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public InstructionHandle getLeavingRET() {
    if (this == getTopLevel()) {
        throw new AssertionViolatedException("getLeavingRET() called on top level pseudo-subroutine.");
    }
    return theRET;
}
 
Example 30
@Override
public Lock isResourceCreation(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg)
        throws DataflowAnalysisException {

    InvokeInstruction inv = toInvokeInstruction(handle.getInstruction());
    if (inv == null) {
        return null;
    }

    String className = inv.getClassName(cpg);
    String methodName = inv.getName(cpg);
    String methodSig = inv.getSignature(cpg);

    try {
        if ("lock".equals(methodName) && "()V".equals(methodSig)
                && Hierarchy.isSubtype(className, "java.util.concurrent.locks.Lock")) {

            Location location = new Location(handle, basicBlock);
            ValueNumberFrame frame = vnaDataflow.getFactAtLocation(location);
            ValueNumber lockValue = frame.getTopValue();
            if (DEBUG) {
                System.out.println("Lock value is " + lockValue.getNumber() + ", frame=" + frame.toString());
            }
            if (DEBUG) {
                ++numAcquires;
            }
            return new Lock(location, className, lockValue);
        }
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }
    return null;
}