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

The following examples show how to use org.apache.bcel.generic.GETSTATIC. 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
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    Instruction ins = location.getHandle().getInstruction();
    if (ins.getOpcode() != Const.GETSTATIC) {
        return null;
    }

    GETSTATIC getstatic = (GETSTATIC) ins;
    if (!className.equals(getstatic.getClassName(cpg)) || !fieldName.equals(getstatic.getName(cpg))
            || !fieldSig.equals(getstatic.getSignature(cpg))) {
        return null;
    }

    return new Stream(location, type.getClassName(), streamBaseClass).setIgnoreImplicitExceptions(true).setIsOpenOnCreation(
            true);
}
 
Example 2
/**
 * Does the given instruction refer to a likely assertion method?
 *
 * @param ins
 *            the instruction
 * @return true if the instruction likely refers to an assertion, false if
 *         not
 */

public boolean isAssertionInstruction(Instruction ins, ConstantPoolGen cpg) {

    if (ins instanceof InvokeInstruction) {
        return isAssertionCall((InvokeInstruction) ins);
    }
    if (ins instanceof GETSTATIC) {
        GETSTATIC getStatic = (GETSTATIC) ins;
        String className = getStatic.getClassName(cpg);
        String fieldName = getStatic.getFieldName(cpg);
        if ("java.util.logging.Level".equals(className) && "SEVERE".equals(fieldName)) {
            return true;
        }
        return "org.apache.log4j.Level".equals(className)
                && ("ERROR".equals(fieldName) || "FATAL".equals(fieldName));
    }
    return false;
}
 
Example 3
Source Project: commons-bcel   Source File: Pass3aVerifier.java    License: Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitGETSTATIC(final GETSTATIC o) {
    try {
    final String field_name = o.getFieldName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
            f = field;
            break;
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    if (! (f.isStatic())) {
        constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 4
@Override
public void visitGETSTATIC(GETSTATIC obj) {
    // Scala uses some classes to represent null instances of objects
    // If we find one of them, we will handle it as a Java Null
    if (obj.getLoadClassType(getCPG()).getSignature().equals("Lscala/collection/immutable/Nil$;")) {

        if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) {
            getFrame().pushValue(new Taint(Taint.State.NULL).setDebugInfo("NULL"));
        } else {
            getFrame().pushValue(new Taint(Taint.State.NULL));
        }
    } else {
        super.visitGETSTATIC(obj);
    }
}
 
Example 5
Source Project: spotbugs   Source File: LazyInit.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean prescreen(Method method, ClassContext classContext) {
    if (Const.STATIC_INITIALIZER_NAME.equals(method.getName())) {
        return false;
    }

    Code code = method.getCode();
    if (code.getCode().length > 5000) {
        return false;
    }

    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return false;
    }

    // The pattern requires a get/put pair accessing the same field.
    boolean hasGetStatic = bytecodeSet.get(Const.GETSTATIC);
    boolean hasPutStatic = bytecodeSet.get(Const.PUTSTATIC);
    if (!hasGetStatic || !hasPutStatic) {
        return false;
    }

    // If the method is synchronized, then we'll assume that
    // things are properly synchronized
    if (method.isSynchronized()) {
        return false;
    }

    reported.clear();
    return true;
}
 
Example 6
@Override
public void visitGETSTATIC(GETSTATIC obj) {
    Type type = obj.getType(getCPG());
    XField xf = XFactory.createXField(obj, cpg);
    if (xf.isFinal()) {
        FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary();
        Item summary = fieldSummary.getSummary(xf);
        if (summary.isNull()) {
            pushValue(TypeFrame.getNullType());
            return;
        }

        String slashedClassName = ClassName.fromFieldSignature(type.getSignature());
        if (slashedClassName != null) {
            String dottedClassName = ClassName.toDottedClassName(slashedClassName);
            if (DEFAULT_SUSPICIOUS_SET.contains(dottedClassName)) {
                type = new FinalConstant(dottedClassName, xf);
                consumeStack(obj);
                pushValue(type);
                return;
            }
        }

    }
    if (STRING_SIGNATURE.equals(type.getSignature())) {
        handleLoad(obj);
    } else {
        super.visitGETSTATIC(obj);
    }
}
 
Example 7
private boolean isSafeValue(Location location, ConstantPoolGen cpg) throws CFGBuilderException {
    Instruction prevIns = location.getHandle().getInstruction();
    if (prevIns instanceof LDC || prevIns instanceof GETSTATIC) {
        return true;
    }
    if (prevIns instanceof InvokeInstruction) {
        String methodName = ((InvokeInstruction) prevIns).getMethodName(cpg);
        if (methodName.startsWith("to") && methodName.endsWith("String") && methodName.length() > 8) {
            return true;
        }
    }
    if (prevIns instanceof AALOAD) {
        CFG cfg = classContext.getCFG(method);

        Location prev = getPreviousLocation(cfg, location, true);
        if (prev != null) {
            Location prev2 = getPreviousLocation(cfg, prev, true);
            if (prev2 != null && prev2.getHandle().getInstruction() instanceof GETSTATIC) {
                GETSTATIC getStatic = (GETSTATIC) prev2.getHandle().getInstruction();
                if ("[Ljava/lang/String;".equals(getStatic.getSignature(cpg))) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 8
@Override
public void visitGETSTATIC(GETSTATIC obj) {
    ConstantPoolGen cpg = getCPG();

    String fieldName = obj.getName(cpg);
    String fieldSig = obj.getSignature(cpg);
    ValueNumberFrame frame = getFrame();

    if (RLE_DEBUG) {
        System.out.println("GETSTATIC of " + fieldName + " : " + fieldSig);
    }
    // Is this an access of a Class object?
    if (fieldName.startsWith("class$") && "Ljava/lang/Class;".equals(fieldSig)) {
        String className = fieldName.substring("class$".length()).replace('$', '.');
        if (RLE_DEBUG) {
            System.out.println("[found load of class object " + className + "]");
        }
        ValueNumber value = factory.getClassObjectValue(className);
        frame.pushValue(value);
        return;
    }

    XField xfield = Hierarchy.findXField(obj, getCPG());
    if (xfield != null) {
        if (xfield.isVolatile()) {
            getFrame().killAllLoads();
        }
        if (doRedundantLoadElimination()) {
            loadStaticField(xfield, obj);
            return;
        }

    }

    handleNormalInstruction(obj);
}
 
Example 9
/**
 * Is the given instruction a read of a field?
 *
 * @param ins
 *            the Instruction to check
 * @param cpg
 *            ConstantPoolGen of the method containing the instruction
 * @return the Field if the instruction is a read of a field, null otherwise
 */
public static FieldAnnotation isRead(Instruction ins, ConstantPoolGen cpg) {
    if (ins instanceof GETFIELD || ins instanceof GETSTATIC) {
        FieldInstruction fins = (FieldInstruction) ins;
        String className = fins.getClassName(cpg);
        return new FieldAnnotation(className, fins.getName(cpg), fins.getSignature(cpg), fins instanceof GETSTATIC);
    } else {
        return null;
    }
}
 
Example 10
/**
 * @param aInstruction
 * @param aPoolGen
 */
public GETSTATICReference(
    GETSTATIC aInstruction,
    ConstantPoolGen aPoolGen)
{
    super(aInstruction, aPoolGen);
}
 
Example 11
/**
 * @param aInstruction
 * @param aPoolGen
 */
public GETSTATICReference(
    GETSTATIC aInstruction,
    ConstantPoolGen aPoolGen)
{
    super(aInstruction, aPoolGen);
}
 
Example 12
public InstructionList createPrintln(final ConstantPoolGen cp, final Instruction instruction) {
    final InstructionList il = new InstructionList();

    final int out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;");
    final int println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V");
    il.append(new GETSTATIC(out));
    il.append(instruction);
    il.append(new INVOKEVIRTUAL(println));

    return il;
}
 
Example 13
@Override
public void visitGETSTATIC(GETSTATIC obj) {
    if (getNumWordsProduced(obj) != 1) {
        super.visitGETSTATIC(obj);
        return;
    }

    if (checkForKnownValue(obj)) {
        return;
    }
    XField field = XFactory.createXField(obj, cpg);
    if (field.isFinal()) {
        Item summary = AnalysisContext.currentAnalysisContext().getFieldSummary().getSummary(field);
        if (summary.isNull()) {
            produce(IsNullValue.nullValue());
            return;
        }
    }
    if ("java.util.logging.Level".equals(field.getClassName()) && "SEVERE".equals(field.getName())
            || "org.apache.log4j.Level".equals(field.getClassName())
                    && ("ERROR".equals(field.getName()) || "FATAL".equals(field.getName()))) {
        getFrame().toExceptionValues();
    }

    if (field.getName().startsWith("class$")) {
        produce(IsNullValue.nonNullValue());
        return;
    }
    NullnessAnnotation annotation = AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase()
            .getResolvedAnnotation(field, false);
    if (annotation == NullnessAnnotation.NONNULL) {
        modelNormalInstruction(obj, getNumWordsConsumed(obj), 0);
        produce(IsNullValue.nonNullValue());
    } else if (annotation == NullnessAnnotation.CHECK_FOR_NULL) {
        modelNormalInstruction(obj, getNumWordsConsumed(obj), 0);
        produce(IsNullValue.nullOnSimplePathValue().markInformationAsComingFromFieldValue(field));
    } else {

        super.visitGETSTATIC(obj);
    }
}
 
Example 14
/**
 * Return whether or not the given instruction can throw exceptions.
 *
 * @param handle
 *            the instruction
 * @return true if the instruction can throw an exception, false otherwise
 * @throws CFGBuilderException
 */
private boolean isPEI(InstructionHandle handle) throws CFGBuilderException {
    Instruction ins = handle.getInstruction();

    if (!(ins instanceof ExceptionThrower)) {
        return false;
    }

    if (ins instanceof NEW) {
        return false;
    }
    // if (ins instanceof ATHROW) return false;
    if (ins instanceof GETSTATIC) {
        return false;
    }
    if (ins instanceof PUTSTATIC) {
        return false;
    }
    if (ins instanceof ReturnInstruction) {
        return false;
    }
    if (ins instanceof INSTANCEOF) {
        return false;
    }
    if (ins instanceof MONITOREXIT) {
        return false;
    }
    if (ins instanceof LDC) {
        return false;
    }
    if (ins instanceof GETFIELD && !methodGen.isStatic()) {
        // Assume that GETFIELD on this object is not PEI
        return !isSafeFieldSource(handle.getPrev());
    }
    if (ins instanceof PUTFIELD && !methodGen.isStatic()) {
        // Assume that PUTFIELD on this object is not PEI
        int depth = ins.consumeStack(cpg);
        for (InstructionHandle prev = handle.getPrev(); prev != null; prev = prev.getPrev()) {
            Instruction prevInst = prev.getInstruction();
            if (prevInst instanceof BranchInstruction) {
                if (prevInst instanceof GotoInstruction) {
                    // Currently we support only jumps to the PUTFIELD itself
                    // This will cover simple cases like this.a = flag ? foo : bar
                    if (((BranchInstruction) prevInst).getTarget() == handle) {
                        depth = ins.consumeStack(cpg);
                    } else {
                        return true;
                    }
                } else if (!(prevInst instanceof IfInstruction)) {
                    // As IF instructions may fall through then the stack depth remains unchanged
                    // Actually we should not go here for normal Java bytecode: switch or jsr should not appear in this context
                    return true;
                }
            }
            depth = depth - prevInst.produceStack(cpg) + prevInst.consumeStack(cpg);
            if (depth < 1) {
                throw new CFGBuilderException("Invalid stack at " + prev + " when checking " + handle);
            }
            if (depth == 1) {
                InstructionHandle prevPrev = prev.getPrev();
                if (prevPrev != null && prevPrev.getInstruction() instanceof BranchInstruction) {
                    continue;
                }
                return !isSafeFieldSource(prevPrev);
            }
        }
    }
    return true;
}
 
Example 15
/** @see org.apache.bcel.generic.Visitor */
public void visitGETSTATIC(GETSTATIC aGETSTATIC)
{
    addFieldReference(
        new GETSTATICReference(aGETSTATIC, mCurrentPoolGen));
}
 
Example 16
/** @see org.apache.bcel.generic.Visitor */
public void visitGETSTATIC(GETSTATIC aGETSTATIC)
{
    addFieldReference(
        new GETSTATICReference(aGETSTATIC, mCurrentPoolGen));
}
 
Example 17
Source Project: commons-bcel   Source File: helloify.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Patch a method.
 */
private static Method helloifyMethod(Method m) {
    final Code code = m.getCode();
    final int flags = m.getAccessFlags();
    final String name = m.getName();

    // Sanity check
    if (m.isNative() || m.isAbstract() || (code == null)) {
        return m;
    }

    // Create instruction list to be inserted at method start.
    final String mesg = "Hello from " + Utility.methodSignatureToString(m.getSignature(),
            name,
            Utility.accessToString(flags));
    final InstructionList patch = new InstructionList();
    patch.append(new GETSTATIC(out));
    patch.append(new PUSH(cp, mesg));
    patch.append(new INVOKEVIRTUAL(println));

    final MethodGen mg = new MethodGen(m, class_name, cp);
    final InstructionList il = mg.getInstructionList();
    final InstructionHandle[] ihs = il.getInstructionHandles();

    if (name.equals("<init>")) { // First let the super or other constructor be called
        for (int j = 1; j < ihs.length; j++) {
            if (ihs[j].getInstruction() instanceof INVOKESPECIAL) {
                il.append(ihs[j], patch); // Should check: method name == "<init>"
                break;
            }
        }
    } else {
        il.insert(ihs[0], patch);
    }

    // Stack size must be at least 2, since the println method takes 2 argument.
    if (code.getMaxStack() < 2) {
        mg.setMaxStack(2);
    }

    m = mg.getMethod();

    il.dispose(); // Reuse instruction handles

    return m;
}
 
Example 18
Source Project: commons-bcel   Source File: ProxyCreator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Create JavaClass object for a simple proxy for an java.awt.event.ActionListener
 * that just prints the passed arguments, load and use it via the class loader
 * mechanism.
 */
public static void main(final String[] argv) throws Exception {
    final ClassLoader loader = ProxyCreator.class.getClassLoader();

    // instanceof won't work here ...
    // TODO this is broken; cannot ever be true now that ClassLoader has been dropped
    if (loader.getClass().toString().equals("class org.apache.bcel.util.ClassLoader")) {
        // Real class name will be set by the class loader
        final ClassGen cg = new ClassGen("foo", "java.lang.Object", "", Constants.ACC_PUBLIC,
                new String[]{"java.awt.event.ActionListener"});

        // That's important, otherwise newInstance() won't work
        cg.addEmptyConstructor(Constants.ACC_PUBLIC);

        final InstructionList il = new InstructionList();
        final ConstantPoolGen cp = cg.getConstantPool();
        final InstructionFactory factory = new InstructionFactory(cg);

        final int out = cp.addFieldref("java.lang.System", "out",
                "Ljava/io/PrintStream;");
        final int println = cp.addMethodref("java.io.PrintStream", "println",
                "(Ljava/lang/Object;)V");
        final MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, Type.VOID,
                new Type[]{
                        new ObjectType("java.awt.event.ActionEvent")
                }, null, "actionPerformed", "foo", il, cp);

        // System.out.println("actionPerformed:" + event);
        il.append(new GETSTATIC(out));
        il.append(factory.createNew("java.lang.StringBuffer"));
        il.append(InstructionConstants.DUP);
        il.append(new PUSH(cp, "actionPerformed:"));
        il.append(factory.createInvoke("java.lang.StringBuffer", "<init>", Type.VOID,
                new Type[]{Type.STRING}, Constants.INVOKESPECIAL));

        il.append(new ALOAD(1));
        il.append(factory.createAppend(Type.OBJECT));
        il.append(new INVOKEVIRTUAL(println));
        il.append(InstructionConstants.RETURN);

        mg.stripAttributes(true);
        mg.setMaxStack();
        mg.setMaxLocals();
        cg.addMethod(mg.getMethod());

        final byte[] bytes = cg.getJavaClass().getBytes();

        System.out.println("Uncompressed class: " + bytes.length);

        final String s = Utility.encode(bytes, true);
        System.out.println("Encoded class: " + s.length());

        System.out.print("Creating proxy ... ");
        final ActionListener a = (ActionListener) createProxy("foo.bar.", s);
        System.out.println("Done. Now calling actionPerformed()");

        a.actionPerformed(new ActionEvent(a, ActionEvent.ACTION_PERFORMED, "hello"));
    } else {
        System.err.println("Call me with java org.apache.bcel.util.JavaWrapper ProxyCreator");
    }
}