Example usage for org.objectweb.asm Opcodes NEW

List of usage examples for org.objectweb.asm Opcodes NEW

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes NEW.

Prototype

int NEW

To view the source code for org.objectweb.asm Opcodes NEW.

Click Source Link

Usage

From source file:org.evosuite.testcarver.instrument.Instrumenter.java

License:Open Source License

@SuppressWarnings("unchecked")
private void transformWrapperCalls(MethodNode mn) {
    Iterator<AbstractInsnNode> iterator = mn.instructions.iterator();
    List<Class<?>> wrapperClasses = getWrapperClasses();

    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn instanceof MethodInsnNode) {
            MethodInsnNode methodInsnNode = (MethodInsnNode) insn;
            if (methodInsnNode.name.equals("<init>")) {
                String ownerName = methodInsnNode.owner.replace('/', '.');
                for (Class<?> wrapperClass : wrapperClasses) {
                    if (wrapperClass.getName().equals(ownerName)) {
                        logger.debug("Replacing call " + methodInsnNode.name);
                        methodInsnNode.owner = "org/evosuite/testcarver/wrapper/" + methodInsnNode.owner;
                        break;
                    }//from   w ww  .j a  v a  2  s .  com
                }
            } else {
                String ownerName = methodInsnNode.owner.replace('/', '.');
                for (Class<?> wrapperClass : wrapperClasses) {
                    if (wrapperClass.getName().equals(ownerName)) {
                        if (methodInsnNode.getOpcode() == Opcodes.INVOKESTATIC) {
                            logger.debug("Replacing call " + methodInsnNode.name);
                            methodInsnNode.owner = PackageInfo.getEvoSuitePackageWithSlash()
                                    + "/testcarver/wrapper/" + methodInsnNode.owner;
                        }
                        Type[] parameterTypes = Type.getArgumentTypes(methodInsnNode.desc);
                        try {
                            Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
                            int pos = 0;
                            for (Type parameter : parameterTypes) {
                                switch (parameter.getSort()) {
                                case Type.OBJECT:
                                    parameterClasses[pos++] = Class.forName(parameter.getClassName());
                                    break;
                                case Type.BOOLEAN:
                                    parameterClasses[pos++] = boolean.class;
                                    break;
                                case Type.BYTE:
                                    parameterClasses[pos++] = byte.class;
                                    break;
                                case Type.CHAR:
                                    parameterClasses[pos++] = char.class;
                                    break;
                                case Type.DOUBLE:
                                    parameterClasses[pos++] = double.class;
                                    break;
                                case Type.FLOAT:
                                    parameterClasses[pos++] = float.class;
                                    break;
                                case Type.INT:
                                    parameterClasses[pos++] = int.class;
                                    break;
                                case Type.LONG:
                                    parameterClasses[pos++] = long.class;
                                    break;
                                case Type.SHORT:
                                    parameterClasses[pos++] = short.class;
                                    break;
                                }
                            }
                            Method method = wrapperClass.getMethod(methodInsnNode.name, parameterClasses);
                            if (Modifier.isFinal(method.getModifiers())) {
                                if (methodInsnNode.getOpcode() != Opcodes.INVOKESTATIC) {
                                    methodInsnNode.setOpcode(Opcodes.INVOKESTATIC);
                                    Type[] args = Type.getArgumentTypes(methodInsnNode.desc);
                                    Type returnType = Type.getReturnType(methodInsnNode.desc);
                                    Type[] newargs = new Type[args.length + 1];
                                    newargs[0] = Type.getObjectType(methodInsnNode.owner);
                                    for (int i = 0; i < args.length; i++)
                                        newargs[i + 1] = args[i];
                                    methodInsnNode.desc = Type.getMethodDescriptor(returnType, newargs);
                                    methodInsnNode.owner = PackageInfo.getEvoSuitePackageWithSlash()
                                            + "/testcarver/wrapper/" + methodInsnNode.owner;
                                } else {
                                    methodInsnNode.name += "_final";
                                }
                                logger.debug(
                                        "Method is final: " + methodInsnNode.owner + "." + methodInsnNode.name);
                            } else {
                                logger.debug("Method is not final: " + methodInsnNode.owner + "."
                                        + methodInsnNode.name);
                            }
                        } catch (Exception e) {
                            logger.warn("Error while instrumenting: " + e);
                        }

                        break;
                    }
                }
                //            } else if(methodInsnNode.name.equals("getTime")) {
                //               if(methodInsnNode.owner.equals("java/util/Calendar")) {
                //                  logger.debug("Replacing call "+methodInsnNode.name);
                //                  methodInsnNode.owner = "org/evosuite/testcarver/wrapper/java/util/Calendar";
                //                  methodInsnNode.name = "getTime";
                //                  methodInsnNode.desc = "(Ljava/util/Calendar;)Ljava/util/Date;";
                //                  methodInsnNode.setOpcode(Opcodes.INVOKESTATIC);
                //               }
                //            }
            }
        } else if (insn.getOpcode() == Opcodes.NEW || insn.getOpcode() == Opcodes.CHECKCAST) {
            TypeInsnNode typeInsnNode = (TypeInsnNode) insn;
            Type generatedType = Type.getType(typeInsnNode.desc);
            String name = generatedType.getInternalName().replace('/', '.');
            logger.debug("Checking for replacement of " + name);
            for (Class<?> wrapperClass : wrapperClasses) {
                if (wrapperClass.getName().equals(name)) {
                    logger.debug("Replacing new " + name);
                    typeInsnNode.desc = PackageInfo.getEvoSuitePackageWithSlash() + "/testcarver/wrapper/"
                            + generatedType.getInternalName();
                    break;
                }
            }

        }
    }
}

From source file:org.formulacompiler.compiler.internal.bytecode.TypeCompilerForPrecisionBigDecimals.java

License:Open Source License

final void buildStaticContext() {
    if (this.staticContextBuilt)
        return;//  w w  w  .j  av  a 2  s  .c  o m
    this.staticContextBuilt = true;

    final SectionCompiler root = engineCompiler().rootCompiler();
    final ClassWriter cw = root.cw();
    final FieldVisitor fv = cw.visitField(Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, RUNTIME_CONTEXT_NAME,
            RUNTIME_CONTEXT_TYPE.getDescriptor(), null, null);
    fv.visitEnd();

    final GeneratorAdapter mv = root.initializer();
    final MathContext mc = numericType().mathContext();
    if (mc == MathContext.DECIMAL32) {
        compilePredefinedMathContext(mv, "DECIMAL32");
    } else if (mc == MathContext.DECIMAL64) {
        compilePredefinedMathContext(mv, "DECIMAL64");
    } else if (mc == MathContext.DECIMAL128) {
        compilePredefinedMathContext(mv, "DECIMAL128");
    } else if (mc == MathContext.UNLIMITED) {
        compilePredefinedMathContext(mv, "UNLIMITED");
    } else {
        mv.visitTypeInsn(Opcodes.NEW, RUNTIME_CONTEXT_TYPE.getInternalName());
        mv.visitInsn(Opcodes.DUP);
        mv.push(mc.getPrecision());
        final Type modeType = Type.getType(RoundingMode.class);
        mv.getStatic(modeType, mc.getRoundingMode().name(), modeType);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, RUNTIME_CONTEXT_TYPE.getInternalName(), "<init>",
                "(ILjava/math/RoundingMode;)V");
    }
    mv.visitFieldInsn(Opcodes.PUTSTATIC, root.classInternalName(), RUNTIME_CONTEXT_NAME,
            RUNTIME_CONTEXT_DESCRIPTOR);
}

From source file:org.formulacompiler.compiler.internal.bytecode.TypeCompilerForScaledLongs.java

License:Open Source License

final void buildStaticContext() {
    if (this.staticContextBuilt)
        return;//from www  .j av a 2 s  . c  om
    this.staticContextBuilt = true;

    final SectionCompiler root = engineCompiler().rootCompiler();
    final ClassWriter cw = root.cw();
    final FieldVisitor fv = cw.visitField(Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, RUNTIME_CONTEXT_NAME,
            RUNTIME_CONTEXT_TYPE.getDescriptor(), null, null);
    fv.visitEnd();

    final GeneratorAdapter mv = root.initializer();
    mv.visitTypeInsn(Opcodes.NEW, RUNTIME_CONTEXT_TYPE.getInternalName());
    mv.visitInsn(Opcodes.DUP);
    mv.push(numericType().scale());
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, RUNTIME_CONTEXT_TYPE.getInternalName(), "<init>", "(I)V");
    mv.visitFieldInsn(Opcodes.PUTSTATIC, root.classInternalName(), RUNTIME_CONTEXT_NAME,
            RUNTIME_CONTEXT_DESCRIPTOR);
}

From source file:org.glassfish.pfl.tf.spi.Util.java

License:Open Source License

public void newWithSimpleConstructor(MethodVisitor mv, Class<?> cls) {
    info(2, "generating new for class " + cls);
    Type type = Type.getType(cls);
    mv.visitTypeInsn(Opcodes.NEW, type.getInternalName());
    mv.visitInsn(Opcodes.DUP);//from  w  w w  . jav a  2s  . com
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, type.getInternalName(), "<init>", "()V");
}

From source file:org.gradle.api.internal.model.DefaultObjectFactory.java

License:Apache License

private ClassGeneratingLoader loaderFor(Class<?> publicClass) {
    ////from ww  w.  jav  a  2s . c o  m
    // Generate implementation class
    //

    FormattingValidationProblemCollector problemCollector = new FormattingValidationProblemCollector(
            "Named implementation class", ModelType.of(publicClass));
    visitFields(publicClass, problemCollector);
    if (problemCollector.hasProblems()) {
        throw new GradleException(problemCollector.format());
    }

    AsmClassGenerator generator = new AsmClassGenerator(publicClass, "$Impl");
    Type implementationType = generator.getGeneratedType();
    ClassWriter visitor = generator.getVisitor();
    Type publicType = Type.getType(publicClass);

    Type superClass;
    String[] interfaces;
    if (publicClass.isInterface()) {
        superClass = OBJECT;
        interfaces = new String[] { publicType.getInternalName() };
    } else {
        superClass = publicType;
        interfaces = EMPTY_STRINGS;
    }

    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, implementationType.getInternalName(), null,
            superClass.getInternalName(), interfaces);

    //
    // Add name field
    //

    visitor.visitField(ACC_PRIVATE, NAME_FIELD, STRING.getDescriptor(), null, null);

    //
    // Add constructor
    //

    MethodVisitor methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING,
            null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID, false);
    // Set this.name = param1
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `getName()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "getName", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `toString()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "toString", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    generator.define();

    //
    // Generate factory class
    //

    generator = new AsmClassGenerator(publicClass, "$Factory");
    visitor = generator.getVisitor();
    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, generator.getGeneratedType().getInternalName(), null,
            Type.getType(ClassGeneratingLoader.class).getInternalName(), EMPTY_STRINGS);

    //
    // Add constructor
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
            Type.getType(ClassGeneratingLoader.class).getInternalName(), CONSTRUCTOR_NAME, RETURN_VOID, false);
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add factory method
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "load", Type.getMethodDescriptor(OBJECT, STRING), null,
            EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call return new <implClass>(param1)
    methodVisitor.visitTypeInsn(Opcodes.NEW, implementationType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, implementationType.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID_FROM_STRING, false);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    Class<Object> factoryClass = generator.define();
    try {
        return (ClassGeneratingLoader) (factoryClass.newInstance());
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.gradle.api.internal.model.NamedObjectInstantiator.java

License:Apache License

private ClassGeneratingLoader loaderFor(Class<?> publicClass) {
    ///* w w w . java2  s.  c o m*/
    // Generate implementation class
    //

    FormattingValidationProblemCollector problemCollector = new FormattingValidationProblemCollector(
            "Named implementation class", ModelType.of(publicClass));
    visitFields(publicClass, problemCollector);
    if (problemCollector.hasProblems()) {
        throw new GradleException(problemCollector.format());
    }

    AsmClassGenerator generator = new AsmClassGenerator(publicClass, "$Impl");
    Type implementationType = generator.getGeneratedType();
    ClassWriter visitor = generator.getVisitor();
    Type publicType = Type.getType(publicClass);

    Type superClass;
    String[] interfaces;
    if (publicClass.isInterface()) {
        superClass = OBJECT;
        interfaces = new String[] { publicType.getInternalName(), MANAGED.getInternalName() };
    } else {
        superClass = publicType;
        interfaces = INTERFACES_FOR_ABSTRACT_CLASS;
    }

    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, implementationType.getInternalName(), null,
            superClass.getInternalName(), interfaces);

    //
    // Add name field
    //

    visitor.visitField(ACC_PRIVATE, NAME_FIELD, STRING.getDescriptor(), null, null);

    //
    // Add constructor
    //

    MethodVisitor methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID_FROM_STRING,
            null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID, false);
    // Set this.name = param1
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `getName()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "getName", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add `toString()`
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "toString", RETURN_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // return this.name
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, implementationType.getInternalName(), NAME_FIELD,
            STRING.getDescriptor());
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    generator.define();

    //
    // Generate factory class
    //

    generator = new AsmClassGenerator(publicClass, "$Factory");
    visitor = generator.getVisitor();
    visitor.visit(V1_5, ACC_PUBLIC | ACC_SYNTHETIC, generator.getGeneratedType().getInternalName(), null,
            CLASS_GENERATING_LOADER.getInternalName(), EMPTY_STRINGS);

    //
    // Add constructor
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, CONSTRUCTOR_NAME, RETURN_VOID, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call this.super()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, CLASS_GENERATING_LOADER.getInternalName(),
            CONSTRUCTOR_NAME, RETURN_VOID, false);
    // Done
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    //
    // Add factory method
    //

    methodVisitor = visitor.visitMethod(ACC_PUBLIC, "load", RETURN_OBJECT_FROM_STRING, null, EMPTY_STRINGS);
    methodVisitor.visitCode();
    // Call return new <implClass>(param1)
    methodVisitor.visitTypeInsn(Opcodes.NEW, implementationType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, implementationType.getInternalName(), CONSTRUCTOR_NAME,
            RETURN_VOID_FROM_STRING, false);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    visitor.visitEnd();
    Class<Object> factoryClass = generator.define();
    try {
        return (ClassGeneratingLoader) factoryClass.getConstructor().newInstance();
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.gradle.initialization.ExceptionDecoratingClassGenerator.java

License:Apache License

private <T> Class<? extends T> doGenerate(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = StringUtils.substringBeforeLast(type.getName(), ".") + ".LocationAware"
            + type.getSimpleName();/*  w  ww  . j a  va2  s. c  o  m*/
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);

    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(),
            new String[] { Type.getType(LocationAwareException.class).getInternalName() });

    Type helperType = Type.getType(ExceptionHelper.class);
    Type throwableType = Type.getType(Throwable.class);
    Type scriptSourceType = Type.getType(ScriptSource.class);
    Type integerType = Type.getType(Integer.class);

    // GENERATE private ExceptionHelper helper;
    visitor.visitField(Opcodes.ACC_PRIVATE, "helper", helperType.getDescriptor(), null, null);

    // GENERATE <init>(<type> target, ScriptSource source, Integer lineNumber)

    String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE,
            new Type[] { superclassType, scriptSourceType, integerType });
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();

    boolean noArgsConstructor;
    try {
        type.getConstructor(type);
        noArgsConstructor = false;
    } catch (NoSuchMethodException e) {
        try {
            type.getConstructor();
            noArgsConstructor = true;
        } catch (NoSuchMethodException e1) {
            throw new IllegalArgumentException(String.format(
                    "Cannot create subtype for exception '%s'. It needs a zero-args or copy constructor.",
                    type.getName()));
        }
    }

    if (noArgsConstructor) {
        // GENERATE super()
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]));
        // END super()
    } else {
        // GENERATE super(target)
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { superclassType }));
        // END super(target)
    }

    // GENERATE helper = new ExceptionHelper(this, target, source, lineNumber)
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);

    methodVisitor.visitTypeInsn(Opcodes.NEW, helperType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, helperType.getInternalName(), "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE,
                    new Type[] { throwableType, throwableType, scriptSourceType, integerType }));

    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), "helper",
            helperType.getDescriptor());

    // END helper = new ExceptionHelper(target)

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // END <init>(<type> target, ScriptSource source, Integer lineNumber)

    for (Method method : ExceptionHelper.class.getDeclaredMethods()) {
        // GENERATE public <type> <method>() { return helper.<method>(); }
        methodDescriptor = Type.getMethodDescriptor(Type.getType(method.getReturnType()), new Type[0]);
        methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), methodDescriptor, null,
                new String[0]);
        methodVisitor.visitCode();

        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), "helper",
                helperType.getDescriptor());
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, helperType.getInternalName(), method.getName(),
                methodDescriptor);

        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
        // END public <type> <method>() { return helper.<method>(); }
    }

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    return (Class<T>) ReflectionUtil.invoke(type.getClassLoader(), "defineClass",
            new Object[] { typeName, bytecode, 0, bytecode.length });
}

From source file:org.greencheek.gc.memusage.agent.AddStaticAtomicLongInitializer.java

License:Apache License

@Override
public void visitCode() {
    super.visitCode();
    // build my static initializer by calling
    // visitFieldInsn(int opcode, String owner, String name, String desc)
    // or the/*  ww  w .ja v  a2  s.  c  o  m*/
    for (MethodInfo method : annotatedMeasurableMethods) {
        System.out.println("Adding static initialiser for: " + method.getAnnotatedClassName() + "."
                + method.getFieldName());
        mv.visitTypeInsn(Opcodes.NEW, "java/util/concurrent/atomic/AtomicLong");
        mv.visitInsn(Opcodes.DUP);
        mv.visitInsn(Opcodes.LCONST_0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/concurrent/atomic/AtomicLong", "<init>", "(J)V");
        mv.visitFieldInsn(Opcodes.PUTSTATIC, method.getAnnotatedClassName(), method.getFieldName(),
                "Ljava/util/concurrent/atomic/AtomicLong;");
    }
    System.out.println();
}

From source file:org.hua.ast.visitors.BytecodeGeneratorASTVisitor.java

/**
 * Assumes top of stack contains two strings
 *///from www .  j  a  v  a2s  .c  o  m
private void handleStringOperator(ASTNode node, Operator op) throws ASTVisitorException {
    if (op.equals(Operator.PLUS)) {
        mn.instructions.add(new TypeInsnNode(Opcodes.NEW, "java/lang/StringBuilder"));
        mn.instructions.add(new InsnNode(Opcodes.DUP));
        mn.instructions.add(
                new MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false));
        mn.instructions.add(new InsnNode(Opcodes.SWAP));
        mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false));
        mn.instructions.add(new InsnNode(Opcodes.SWAP));
        mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false));
        mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "toString",
                "()Ljava/lang/String;", false));
    } else if (op.isRelational()) {
        LabelNode trueLabelNode = new LabelNode();
        switch (op) {
        case EQUAL:
            mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/String", "equals",
                    "(Ljava/lang/Object;)Z", false));
            mn.instructions.add(new JumpInsnNode(Opcodes.IFNE, trueLabelNode));
            break;
        case NOT_EQUAL:
            mn.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/String", "equals",
                    "(Ljava/lang/Object;)Z", false));
            mn.instructions.add(new JumpInsnNode(Opcodes.IFEQ, trueLabelNode));
            break;
        default:
            ASTUtils.error(node, "Operator not supported on strings");
            break;
        }
        mn.instructions.add(new InsnNode(Opcodes.ICONST_0));
        LabelNode endLabelNode = new LabelNode();
        mn.instructions.add(new JumpInsnNode(Opcodes.GOTO, endLabelNode));
        mn.instructions.add(trueLabelNode);
        mn.instructions.add(new InsnNode(Opcodes.ICONST_1));
        mn.instructions.add(endLabelNode);
    } else {
        ASTUtils.error(node, "Operator not recognized");
    }
}

From source file:org.hua.ast.visitors.BytecodeGeneratorASTVisitor.java

@Override
public void visit(NewIdentifierExpression node) throws ASTVisitorException {
    if (node.getExpressions() != null) {
        node.getExpressions().accept(this);
    }/*from  w  w w . j  av a 2  s  .  c  o m*/
    mn.instructions.add(new TypeInsnNode(Opcodes.NEW, node.getIdentifier()));
    mn.instructions.add(new InsnNode(Opcodes.DUP));
    //@TODO: fix calling parameters
    if (node.getExpressions() != null) {
        if (node.getExpressions().getExpressions().isEmpty() && Registry.getInstance()
                .classExists(Type.getType("Lorg/hua/customclasses/" + node.getIdentifier() + ";"))) {
            System.out.println("222222222222222222222222222222222222222222 "
                    + ASTUtils.getSafeType(node).getInternalName());
            mn.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,
                    ASTUtils.getSafeType(node).getInternalName(), "<init>", "()V", false));
        } else //get parameter types and then give that as the signature
        if (Registry.getInstance()
                .classExists(Type.getType("Lorg/hua/customclasses/" + node.getIdentifier() + ";"))) {
            SymTable<SymTableEntry> existingClass = Registry.getInstance()
                    .getExistingClass(Type.getType("Lorg/hua/customclasses/" + node.getIdentifier() + ";"));
            SymTableEntry lookup = existingClass.lookup(node.getIdentifier());
            if (lookup != null) {
                Type[] types = lookup.getParametersTypes();
                mn.instructions.add(
                        new MethodInsnNode(Opcodes.INVOKEVIRTUAL, ASTUtils.getSafeType(node).getInternalName(),
                                node.getIdentifier(), Type.getMethodDescriptor(Type.VOID_TYPE, types), false));
            } else {
                ASTUtils.error(node, "Constructor not found");
            }
        } else {
            ASTUtils.error(node, "Problem with called constructor");
        }
    }
    LocalIndexPool pool = ASTUtils.getSafeLocalIndexPool(fd);
    int localIndex = pool.getLocalIndex();
    System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "
            + localIndex);
    mn.instructions.add(new VarInsnNode(Opcodes.ASTORE, localIndex));
}