Example usage for org.objectweb.asm.commons GeneratorAdapter storeLocal

List of usage examples for org.objectweb.asm.commons GeneratorAdapter storeLocal

Introduction

In this page you can find the example usage for org.objectweb.asm.commons GeneratorAdapter storeLocal.

Prototype

public void storeLocal(final int local, final Type type) 

Source Link

Document

Generates the instruction to store the top stack value in the given local variable.

Usage

From source file:com.changingbits.Builder.java

License:Apache License

/** Build a {@link LongRangeMultiSet} implementation to
 *  lookup intervals for a given point./*from  w w w  . j  a v  a2  s  .com*/
 *
 *  @param useAsm If true, the tree will be compiled to
 *  java bytecodes using the {@code asm} library; typically
 *  this results in a faster (~3X) implementation. */
public LongRangeMultiSet getMultiSet(boolean useAsm, boolean useArrayImpl) {

    finish(useArrayImpl);

    if (useAsm) {
        StringBuilder sb = new StringBuilder();
        sb.append('\n');
        int count = 0;
        for (LongRange range : ranges) {
            sb.append("// range ");
            sb.append(count++);
            sb.append(": ");
            sb.append(range);
            sb.append('\n');
        }
        sb.append('\n');
        sb.append("int upto = 0;\n");
        buildJavaSource(root, 0, sb);
        String javaSource = sb.toString();
        //System.out.println("java: " + javaSource);

        ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
        classWriter.visit(Opcodes.V1_7,
                Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC,
                COMPILED_TREE_CLASS.replace('.', '/'), null, LONG_RANGE_MULTI_SET_TYPE.getInternalName(), null);
        classWriter.visitSource(javaSource, null);

        Method m = Method.getMethod("void <init> ()");
        GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, m, null,
                null, classWriter);
        constructor.loadThis();
        constructor.loadArgs();
        constructor.invokeConstructor(LONG_RANGE_MULTI_SET_TYPE, m);
        constructor.returnValue();
        constructor.endMethod();

        GeneratorAdapter gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, LOOKUP_METHOD,
                null, null, classWriter);
        //Label labelTop = new Label();
        //Label labelEnd = new Label();
        //gen.visitLabel(labelTop);
        int uptoLocal = gen.newLocal(Type.INT_TYPE);
        //System.out.println("uptoLocal=" + uptoLocal);
        // nocommit is this not needed!?
        //gen.visitLocalVariable("upto", "I", null, labelTop, labelEnd, uptoLocal);
        gen.push(0);
        gen.storeLocal(uptoLocal, Type.INT_TYPE);
        buildAsm(gen, root, uptoLocal);
        // Return upto:
        gen.loadLocal(uptoLocal, Type.INT_TYPE);
        gen.returnValue();
        //gen.visitLabel(labelEnd);
        gen.endMethod();
        classWriter.visitEnd();

        byte[] bytes = classWriter.toByteArray();

        // javap -c /x/tmp/my.class
        /*
        try {
          FileOutputStream fos = new FileOutputStream(new File("/x/tmp/my.class"));
          fos.write(bytes);
          fos.close();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
        */

        // nocommit allow changing the class loader
        Class<? extends LongRangeMultiSet> treeClass = new Loader(LongRangeMultiSet.class.getClassLoader())
                .define(COMPILED_TREE_CLASS, classWriter.toByteArray());
        try {
            return treeClass.getConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException
                | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

    } else if (useArrayImpl) {
        return new ArrayLongRangeMultiSet(root);
    } else {
        return new SimpleLongRangeMultiSet(root);
    }
}

From source file:de.enough.polish.postcompile.java5.Java5ClassVisitor.java

License:Open Source License

public void visitEnd() {
    if (this.isEnumClass) {
        if (this.name_values == null) {
            throw new BuildException("This is not an enum class: " + this.classDesc);
        }//from   w ww  .  ja  va2 s .  c  om

        // Generate new <clinit> method.
        int numValues = EnumManager.getInstance().getNumEnumValues(this.classDesc);
        Method m = Method.getMethod("void <clinit> ()");
        MethodVisitor mv = super.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
        GeneratorAdapter mg = new GeneratorAdapter(ACC_STATIC, m, mv);
        mg.push(numValues);
        mg.newArray(Type.INT_TYPE);

        if (numValues <= 3) {
            for (int i = 1; i < numValues; i++) {
                mg.dup();
                mg.push(i);
                mg.push(i);
                mg.arrayStore(Type.INT_TYPE);
            }
        } else {
            Label labelInitializeField = new Label();
            Label labelCheck = new Label();
            Label labelDone = new Label();

            mg.push(1);
            mg.storeLocal(0, Type.INT_TYPE);
            mg.goTo(labelCheck);

            mg.mark(labelInitializeField);
            mg.dup();
            mg.loadLocal(0, Type.INT_TYPE);
            mg.dup();
            mg.arrayStore(Type.INT_TYPE);
            mg.iinc(0, 1);

            mg.mark(labelCheck);
            mg.loadLocal(0, Type.INT_TYPE);
            mg.push(numValues);
            mg.ifICmp(GeneratorAdapter.LT, labelInitializeField);

            mg.mark(labelDone);
        }

        mg.putStatic(Type.getType(this.classDesc), this.name_values, Type.getType(int[].class));
        mg.returnValue();
        mg.endMethod();
    }

    // Called super implementation of this method to really close this class.
    super.visitEnd();
}

From source file:lucee.transformer.bytecode.statement.Return.java

License:Open Source License

public void _writeOut(BytecodeContext bc) throws BytecodeException {
    GeneratorAdapter adapter = bc.getAdapter();

    if (expr == null)
        ASMConstants.NULL(adapter);/*from  w  w w  .  j  av a  2  s  .co  m*/
    else
        expr.writeOut(bc, Expression.MODE_REF);

    // call finallies
    Stack<OnFinally> finallies = bc.getOnFinallyStack();
    int len = finallies.size();
    OnFinally onFinally;
    if (len > 0) {
        int rtn = adapter.newLocal(Types.OBJECT);
        adapter.storeLocal(rtn, Types.OBJECT);
        for (int i = len - 1; i >= 0; i--) {
            onFinally = finallies.get(i);
            if (!bc.insideFinally(onFinally))
                onFinally.writeOut(bc);
        }
        adapter.loadLocal(rtn, Types.OBJECT);
    }

    if (bc.getMethod().getReturnType().equals(Types.VOID)) {
        adapter.pop();
        adapter.visitInsn(Opcodes.RETURN);
    } else
        adapter.visitInsn(Opcodes.ARETURN);
}

From source file:org.evosuite.testcase.variable.VariableReferenceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override//  w ww.  j  a va  2 s.  com
public void storeBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals) {

    logger.debug("Storing variable in bytecode: " + getStPosition() + " of type "
            + org.objectweb.asm.Type.getType(type.getRawClass()));
    if (!locals.containsKey(getStPosition()))
        locals.put(getStPosition(), mg.newLocal(org.objectweb.asm.Type.getType(type.getRawClass())));
    mg.storeLocal(locals.get(getStPosition()), org.objectweb.asm.Type.getType(type.getRawClass()));
}

From source file:org.evosuite.testcase.VariableReferenceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override//from   w  ww.j ava2  s. c  o  m
public void storeBytecode(GeneratorAdapter mg, Map<Integer, Integer> locals) {

    logger.debug("Storing variable in bytecode: {} of type {}", getStPosition(),
            org.objectweb.asm.Type.getType(type.getRawClass()));
    if (!locals.containsKey(getStPosition()))
        locals.put(getStPosition(), mg.newLocal(org.objectweb.asm.Type.getType(type.getRawClass())));
    mg.storeLocal(locals.get(getStPosition()), org.objectweb.asm.Type.getType(type.getRawClass()));
}

From source file:org.jruby.javasupport.proxy.JavaProxyClassFactory.java

License:LGPL

private static void generateProxyMethod(Type selfType, Type superType, ClassVisitor cw,
        GeneratorAdapter clazzInit, MethodData md) {
    if (!md.generateProxyMethod()) {
        return;//w ww  .java2  s  .  co  m
    }

    org.objectweb.asm.commons.Method m = md.getMethod();
    Type[] ex = toType(md.getExceptions());

    String field_name = "__mth$" + md.getName() + md.scrambledSignature();

    // create static private method field
    FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, field_name,
            PROXY_METHOD_TYPE.getDescriptor(), null, null);
    fv.visitEnd();

    clazzInit.dup();
    clazzInit.push(m.getName());
    clazzInit.push(m.getDescriptor());
    clazzInit.push(md.isImplemented());
    clazzInit.invokeStatic(PROXY_HELPER_TYPE, PROXY_HELPER_GET_METHOD);
    clazzInit.putStatic(selfType, field_name, PROXY_METHOD_TYPE);

    org.objectweb.asm.commons.Method sm = new org.objectweb.asm.commons.Method("__super$" + m.getName(),
            m.getReturnType(), m.getArgumentTypes());

    //
    // construct the proxy method
    //
    GeneratorAdapter ga = new GeneratorAdapter(Opcodes.ACC_PUBLIC, m, null, ex, cw);

    ga.loadThis();
    ga.getField(selfType, INVOCATION_HANDLER_FIELD_NAME, INVOCATION_HANDLER_TYPE);

    // if the method is extending something, then we have
    // to test if the handler is initialized...

    if (md.isImplemented()) {
        ga.dup();
        Label ok = ga.newLabel();
        ga.ifNonNull(ok);

        ga.loadThis();
        ga.loadArgs();
        ga.invokeConstructor(superType, m);
        ga.returnValue();
        ga.mark(ok);
    }

    ga.loadThis();
    ga.getStatic(selfType, field_name, PROXY_METHOD_TYPE);

    if (m.getArgumentTypes().length == 0) {
        // load static empty array
        ga.getStatic(JAVA_PROXY_TYPE, "NO_ARGS", Type.getType(Object[].class));
    } else {
        // box arguments
        ga.loadArgArray();
    }

    Label before = ga.mark();

    ga.invokeInterface(INVOCATION_HANDLER_TYPE, INVOCATION_HANDLER_INVOKE_METHOD);

    Label after = ga.mark();

    ga.unbox(m.getReturnType());
    ga.returnValue();

    // this is a simple rethrow handler
    Label rethrow = ga.mark();
    ga.visitInsn(Opcodes.ATHROW);

    for (int i = 0; i < ex.length; i++) {
        ga.visitTryCatchBlock(before, after, rethrow, ex[i].getInternalName());
    }

    ga.visitTryCatchBlock(before, after, rethrow, "java/lang/Error");
    ga.visitTryCatchBlock(before, after, rethrow, "java/lang/RuntimeException");

    Type thr = Type.getType(Throwable.class);
    Label handler = ga.mark();
    Type udt = Type.getType(UndeclaredThrowableException.class);
    int loc = ga.newLocal(thr);
    ga.storeLocal(loc, thr);
    ga.newInstance(udt);
    ga.dup();
    ga.loadLocal(loc, thr);
    ga.invokeConstructor(udt, org.objectweb.asm.commons.Method.getMethod("void <init>(java.lang.Throwable)"));
    ga.throwException();

    ga.visitTryCatchBlock(before, after, handler, "java/lang/Throwable");

    ga.endMethod();

    //
    // construct the super-proxy method
    //
    if (md.isImplemented()) {

        GeneratorAdapter ga2 = new GeneratorAdapter(Opcodes.ACC_PUBLIC, sm, null, ex, cw);

        ga2.loadThis();
        ga2.loadArgs();
        ga2.invokeConstructor(superType, m);
        ga2.returnValue();
        ga2.endMethod();
    }
}