Example usage for org.objectweb.asm ClassVisitor visitSource

List of usage examples for org.objectweb.asm ClassVisitor visitSource

Introduction

In this page you can find the example usage for org.objectweb.asm ClassVisitor visitSource.

Prototype

public void visitSource(final String source, final String debug) 

Source Link

Document

Visits the source of the class.

Usage

From source file:com.facebook.presto.byteCode.ClassDefinition.java

License:Apache License

public void visit(ClassVisitor visitor) {
    // Generic signature if super class or any interface is generic
    String signature = null;/*from   w  w  w .  jav a2 s . c o  m*/
    if (superClass.isGeneric() || any(interfaces, ParameterizedType.isGenericType())) {
        signature = genericClassSignature(superClass, interfaces);
    }

    String[] interfaces = new String[this.interfaces.size()];
    for (int i = 0; i < interfaces.length; i++) {
        interfaces[i] = this.interfaces.get(i).getClassName();
    }
    visitor.visit(V1_7, toAccessModifier(access) | ACC_SUPER, type.getClassName(), signature,
            superClass.getClassName(), interfaces);

    // visit source
    if (source != null) {
        visitor.visitSource(source, debug);
    }

    // visit annotations
    for (AnnotationDefinition annotation : annotations) {
        annotation.visitClassAnnotation(visitor);
    }

    // visit fields
    for (FieldDefinition field : fields) {
        field.visit(visitor);
    }

    // visit clinit method
    classInitializer.visit(visitor, true);

    // visit methods
    for (MethodDefinition method : methods) {
        method.visit(visitor);
    }

    // done
    visitor.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.ComputationClassGenerator.java

License:Apache License

public void accept(TransformationContext context) {
    ClassVisitor cv = context.writer();

    // extends Object implements Computation<ValueType>
    SignatureWriter sign = new SignatureWriter();
    SignatureVisitor supsign = sign.visitSuperclass();
    supsign.visitClassType(OBJECT_NAME);
    supsign.visitEnd();//from   w w w  .  ja va 2s  .  c  om
    SignatureVisitor iface = sign.visitInterface();
    iface.visitClassType(COMPUTATION_NAME);
    SignatureVisitor argsign = iface.visitTypeArgument('=');
    new SignatureReader(info.valueSignature).acceptType(argsign);
    argsign.visitEnd();

    cv.visit(Opcodes.V1_6, Opcodes.ACC_FINAL, info.computationClassName, sign.toString(), OBJECT_NAME,
            new String[] { COMPUTATION_NAME });

    cv.visitSource(info.ownerSource, null);
    cv.visitInnerClass(info.stateClassName, info.owner, info.stateSimpleName, 0);
    cv.visitInnerClass(info.computationClassName, info.owner, info.computationSimpleName, 0);

    cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "state", stateDesc, null, null);

    generateConstructor(cv);
    generateExecute(cv);

    cv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.ContinuationClassGenerator.java

License:Apache License

public void accept(TransformationContext context) {
    ClassVisitor cv = context.writer();

    cv.visit(Opcodes.V1_6, Opcodes.ACC_FINAL, info.continuationClassName, signature, OBJECT_NAME,
            new String[] { CONTINUATION_NAME });

    cv.visitSource(info.ownerSource, null);
    cv.visitInnerClass(info.stateClassName, info.owner, info.stateSimpleName, 0);
    cv.visitInnerClass(info.continuationClassName, info.owner, info.continuationSimpleName, 0);

    cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "state", stateDesc, null, null);

    cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "index", "I", null, null);

    generateConstructor(cv);/*w ww  . j  av  a 2  s.c o m*/
    generateExecute(cv, true);
    generateExecute(cv, false);

    cv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.StateClassGenerator.java

License:Apache License

public void accept(TransformationContext context) {
    ClassVisitor cv = context.writer();

    final String name = info.stateClassName;

    cv.visit(Opcodes.V1_6, Opcodes.ACC_FINAL /*| Opcodes.ACC_SYNTHETIC*/, name, null, OBJECT_NAME, null);

    cv.visitSource(info.ownerSource, null);
    cv.visitOuterClass(info.owner, null, null);

    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, CONTINUATION_FIELD, CONTINUATION_DESC,
            'L' + CONTINUATION_NAME + '<' + info.valueSignature + ">;", null);

    // Local variables state
    List<String> names = info.tracker.getFieldNames();
    List<Type> types = info.tracker.getFieldTypes();
    for (int i = 0; i < names.size(); ++i) {
        cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, names.get(i), types.get(i).getDescriptor(), null, null);
    }//from  www  .j  av a  2  s. co  m

    // Return value variable
    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, "result", OBJECT_DESC, null, null);
    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, "exception", THROWABLE_DESC, null, null);

    // Generate constructor
    MethodVisitor mv = cv.visitMethod(0, CTOR_NAME, DEFAULT_CTOR_DESC, null, null);
    mv.visitCode();
    Label start = new Label();
    Label end = new Label();
    mv.visitLabel(start);
    mv.visitLineNumber(0, start);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, OBJECT_NAME, CTOR_NAME, DEFAULT_CTOR_DESC);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitLabel(end);

    mv.visitLocalVariable("this", 'L' + name + ';', null, start, end, 0);

    mv.visitMaxs(1, 1);
    mv.visitEnd();

    cv.visitEnd();
}

From source file:com.googlecode.ddom.weaver.asm.ClassVisitorTee.java

License:Apache License

public void visitSource(String source, String debug) {
    for (ClassVisitor visitor : visitors) {
        visitor.visitSource(source, debug);
    }//from  ww w .j  av a 2s  . c  o m
}

From source file:com.mulberry.athena.asm.ASMTest.java

License:Open Source License

@Test
public void generateClass() throws Exception {
    ClassWriter classWriter = new ClassWriter(0);
    ClassVisitor cv = new TraceClassVisitor(classWriter, new PrintWriter(System.out));
    //FieldVisitor fv;
    MethodVisitor mv;//from w  ww  .  j av  a2  s  .  c o  m
    //AnnotationVisitor av0;

    cv.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "Testing", null, "java/lang/Object", null);
    cv.visitSource("Testing.java", null);
    {
        mv = cv.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(1, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
        mv.visitInsn(RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "LTesting;", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cv.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(3, l0);
        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        mv.visitLdcInsn("Works!");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(4, l1);
        mv.visitInsn(RETURN);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("args", "[Ljava/lang/String;", null, l0, l2, 0);
        mv.visitMaxs(2, 1);
        mv.visitEnd();
    }
    cv.visitEnd();

    Class<?> clazz = new DynamicClassLoader().defineClass("Testing", classWriter.toByteArray());
    java.lang.reflect.Method method = clazz.getMethod("main", String[].class);
    final String[] arguments = new String[] { "hello", "world" };
    method.invoke(clazz, (Object) arguments);
}

From source file:jaspex.stm.ExternalAccessHelper.java

License:Open Source License

public static byte[] generateClass(Type extAccessType) throws java.io.IOException {
    // Obter tipo original
    Type originalType = Type.fromCommon(extAccessType.commonName().replace(EXTERNALACCESS_CLASS_PREFIX, ""));

    Class<?> javaClass = null;
    try {//from w  w  w.  j  a v a 2 s  .  com
        javaClass = Class.forName(originalType.commonName());
    } catch (ClassNotFoundException e) {
        throw new Error(e);
    }

    Log.trace(color("[ ExternalAccessHelper ]", "31") + " Generating wrapper for {}", originalType);

    // Criar classe
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = cw;

    List<InfoField> fieldList = InfoClass.fromType(originalType).fields();

    // Adicionar inicializao de offsets usados pela unsafetrans ao clinit da classe
    // Nota: Visitor tem que estar *depois* do FieldTransactifierClassVisitor
    cv = new GenericMethodVisitorAdapter(cv, ChangeClinitMethodVisitor.class, originalType, extAccessType,
            fieldList);

    // Visitor que cria os campos offset e o staticfieldbase
    cv = new FieldTransactifierClassVisitor(cv, false);

    cv.visit(V1_6, ACC_PUBLIC | ACC_FINAL, extAccessType.asmName(), null, Type.OBJECT.asmName(), null);
    cv.visitSource(color("JaSPEx Generated External Access Class", "31"), null);

    // Visitar campos, para serem apanhados pelos visitors
    Iterator<InfoField> it = fieldList.iterator();
    while (it.hasNext()) {
        InfoField f = it.next();

        // Alguns campos (como o java.lang.System.security) no so visveis por reflection,
        // e portanto no geramos entradas para eles (hopefully nunca sero necessrias)
        try {
            Transaction.getFieldOffset(javaClass, f.name());
        } catch (SecurityException e) {
            it.remove();
            continue;
        }

        cv.visitField(f.access(), f.name(), f.desc().bytecodeName(), null, null);
    }

    cv.visitEnd();

    byte[] newClass = cw.toByteArray();

    if (Options.WRITECLASS) {
        try {
            new java.io.File("output" + java.io.File.separatorChar).mkdir();
            java.io.FileOutputStream fos = new java.io.FileOutputStream(
                    "output" + java.io.File.separatorChar + extAccessType.commonName() + ".class");
            fos.write(newClass);
            fos.close();
        } catch (java.io.FileNotFoundException e) {
            throw new Error(e);
        } catch (java.io.IOException e) {
            throw new Error(e);
        }
    }

    return newClass;
}

From source file:jpcsp.Allegrex.compiler.CompilerContext.java

License:Open Source License

public void startClass(ClassVisitor cv) {
    if (RuntimeContext.enableLineNumbers) {
        cv.visitSource(getCodeBlock().getClassName() + ".java", null);
    }//  w w w . ja v a 2 s .co m
}

From source file:kilim.analysis.ClassWeaver.java

License:Open Source License

private void accept(final ClassVisitor cv) {
    ClassFlow cf = classFlow;/*from   w ww. jav a2 s  .c  o m*/
    // visits header
    String[] interfaces = toStringArray(cf.interfaces);
    cv.visit(cf.version, cf.access, cf.name, cf.signature, cf.superName, interfaces);
    // visits source
    if (cf.sourceFile != null || cf.sourceDebug != null) {
        cv.visitSource(cf.sourceFile, cf.sourceDebug);
    }
    // visits outer class
    if (cf.outerClass != null) {
        cv.visitOuterClass(cf.outerClass, cf.outerMethod, cf.outerMethodDesc);
    }
    // visits attributes and annotations
    int i, n;
    AnnotationNode an;
    n = cf.visibleAnnotations == null ? 0 : cf.visibleAnnotations.size();
    for (i = 0; i < n; ++i) {
        an = (AnnotationNode) cf.visibleAnnotations.get(i);
        an.accept(cv.visitAnnotation(an.desc, true));
    }
    n = cf.invisibleAnnotations == null ? 0 : cf.invisibleAnnotations.size();
    for (i = 0; i < n; ++i) {
        an = (AnnotationNode) cf.invisibleAnnotations.get(i);
        an.accept(cv.visitAnnotation(an.desc, false));
    }

    n = cf.attrs == null ? 0 : cf.attrs.size();
    for (i = 0; i < n; ++i) {
        cv.visitAttribute((Attribute) cf.attrs.get(i));
    }
    // visits inner classes
    for (i = 0; i < cf.innerClasses.size(); ++i) {
        ((InnerClassNode) cf.innerClasses.get(i)).accept(cv);
    }
    // visits fields
    for (i = 0; i < cf.fields.size(); ++i) {
        ((FieldNode) cf.fields.get(i)).accept(cv);
    }
    /*
     * Mark this class as "processed" by adding a dummy field, so that
     * we don't weave an already woven file
     */
    cv.visitField(ACC_PUBLIC | ACC_STATIC | ACC_FINAL, WOVEN_FIELD, "Z", "Z", Boolean.TRUE);
    // visits methods
    for (i = 0; i < cf.methods.size(); ++i) {
        MethodFlow m = (MethodFlow) cf.methods.get(i);
        if (needsWeaving(m)) {
            MethodWeaver mw = new MethodWeaver(this, m);
            mw.accept(cv);
            mw.makeNotWovenMethod(cv, m);
        } else {
            m.accept(cv);
        }
    }
    // visits end
    cv.visitEnd();
}

From source file:org.adjective.stout.writer.ByteCodeWriter.java

License:Apache License

public byte[] write(ClassDescriptor cls) {
    begin(cls);// ww w  .j av a 2  s .c  o m
    ClassWriter writer = createClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = writer;
    if (_trace) {
        cv = new TraceClassVisitor(cv, new PrintWriter(System.err));
    }
    if (_check) {
        cv = new CheckClassAdapter(cv);
    }

    String signature = null; // @TODO
    cv.visit(Opcodes.V1_5, getModifierCode(cls.getModifiers(), cls.getSort()), cls.getInternalName(), signature,
            getInternalName(cls.getSuperClass()), getInterfaceNames(cls));

    if (cls.getSourceFile() != null) {
        cv.visitSource(cls.getSourceFile(), "");
    }

    UnresolvedType outer = cls.getOuterClass();
    if (outer != null) {
        cv.visitOuterClass(outer.getInternalName(), null, null);
    }

    for (AnnotationDescriptor annotation : cls.getAnnotations()) {
        writeAnnotation(cv, annotation);
    }

    for (ClassDescriptor inner : cls.getInnerClasses()) {
        String name = inner.getInternalName();
        String simpleName = name.substring(name.lastIndexOf('/') + 1);
        cv.visitInnerClass(name, cls.getInternalName(), simpleName,
                getModifierCode(inner.getModifiers(), inner.getSort()));
    }

    for (FieldDescriptor field : cls.getFields()) {
        writeField(cv, field);
    }

    for (MethodDescriptor method : cls.getMethods()) {
        writeMethod(cv, cls, method);
    }

    cv.visitEnd();

    end(cls);
    return writer.toByteArray();
}