Java Code Examples for org.objectweb.asm.MethodVisitor#visitAnnotation()

The following examples show how to use org.objectweb.asm.MethodVisitor#visitAnnotation() . 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
Source File: EventSubclassTransformer.java    From patchwork-patcher with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Adds a public marker method that returns true.
 *
 * <p>It appears like so: <pre>
 * public boolean name() {
 *     return true;
 * }
 * </pre></p>
 *
 * @param name The name of the generated method
 */
private void visitMarkerMethod(String name) {
	MethodVisitor isCancelable = super.visitMethod(Opcodes.ACC_PUBLIC, name, BOOLEAN_DESCRIPTOR, null, null);

	if (isCancelable != null) {
		AnnotationVisitor override = isCancelable.visitAnnotation("Ljava/lang/Override;", true);

		if (override != null) {
			override.visitEnd();
		}

		isCancelable.visitInsn(Opcodes.ICONST_1);
		isCancelable.visitInsn(Opcodes.IRETURN);
		isCancelable.visitMaxs(2, 1);
		isCancelable.visitEnd();
	}
}
 
Example 2
Source File: DynamicEntityGenerator.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
private static void writeGetterForMapperBy(ClassWriter classWriter, FieldNode field, String className, String getter) {
    MethodVisitor methodVisitor;
    AnnotationVisitor annotationVisitor0;
    methodVisitor = classWriter.visitMethod(ACC_PUBLIC, getter, "()Ljava/util/Set;", "()" + getTypeSiganitureForOneToMany(field.getTypeDesc()), null);
    if (DynamicEntityType.MultiReference.equals(field.getEntityType())) {
        annotationVisitor0 = methodVisitor.visitAnnotation("Ljavax/persistence/ManyToMany;", true);
        annotationVisitor0.visit("mappedBy", field.getMappedBy());
        annotationVisitor0.visitEnd();
    } else {
        annotationVisitor0 = methodVisitor.visitAnnotation("Ljavax/persistence/OneToMany;", true);
        annotationVisitor0.visit("mappedBy", field.getMappedBy());
        if (DynamicEntityType.MultiSelection.equals(field.getEntityType())) {
            annotationVisitor0.visitEnum("fetch", "Ljavax/persistence/FetchType;", "EAGER");
            AnnotationVisitor annotationVisitor1 = annotationVisitor0.visitArray("cascade");
            annotationVisitor1.visitEnum(null, "Ljavax/persistence/CascadeType;", CascadeType.ALL.toString());
            annotationVisitor1.visitEnd();
        }
        annotationVisitor0.visitEnd();
    }
    {
        annotationVisitor0 = methodVisitor.visitAnnotation("Lcom/fasterxml/jackson/annotation/JsonIgnore;", true);
        annotationVisitor0.visitEnd();
    }

    // getter method body
    methodVisitor.visitVarInsn(ALOAD, 0);
    methodVisitor.visitFieldInsn(GETFIELD, className, field.getName(), "Ljava/util/Set;");
    methodVisitor.visitInsn(ARETURN);
    methodVisitor.visitMaxs(1, 1);
    methodVisitor.visitEnd();
}
 
Example 3
Source File: AddDefaultMethodsToInterfaceForFiber.java    From Concurnas with MIT License 4 votes vote down vote up
public MethodVisitor visitMethod(final int access, final String name, final String descriptor, final String signature, final String[] exceptions) {

		if (!Modifier.isStatic(access) &&  ((access & ACC_ABSTRACT ) != 0 && !descriptor.contains(Fiberizer.FIBER_SUFFIX)) ) {
			// replace with default method pointing to fiberized version
			{
				MethodVisitor methodVisitor = cv.visitMethod(access & ~ACC_ABSTRACT, name, descriptor, signature, null);
				//annotations indicating that this method is normally obligatory to implement! (i.e. normally not default)
				//@DefaultMethodRequiresImplementation
				
				{
					AnnotationVisitor annotationVisitor0 = methodVisitor.visitAnnotation("Lcom/concurnas/bootstrap/runtime/DefaultMethodRequiresImplementation;", true);
					annotationVisitor0.visitEnd();
				}
				methodVisitor.visitCode();
				
				methodVisitor.visitLabel(new Label());
				methodVisitor.visitVarInsn(ALOAD, 0);
				
				//load others
				int locVar=1;
				for(char c : ANFTransform.getPrimOrObj(descriptor)){//reload the stack from vars
					methodVisitor.visitVarInsn(ANFTransform.getLoadOp(c), locVar++);
					if(c == 'D' || c=='J'){
						locVar++;
					}
				}
				
				methodVisitor.visitMethodInsn(INVOKESTATIC, "com/concurnas/bootstrap/runtime/cps/Fiber", "getCurrentFiberWithCreate", "()Lcom/concurnas/bootstrap/runtime/cps/Fiber;", false);
				methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "com/concurnas/bootstrap/runtime/cps/Fiber", "begin", "()Lcom/concurnas/bootstrap/runtime/cps/Fiber;", false);
				
				methodVisitor.visitMethodInsn(INVOKEINTERFACE, this.name, name, descriptor.replace(")", Fiberizer.FIBER_SUFFIX), true);

				String dd = Type.getMethodType(descriptor).getReturnType().getDescriptor();
				methodVisitor.visitInsn(dd.startsWith("[")?ARETURN:ANFTransform.getReturnOp(descriptor.charAt(descriptor.length()-1)));//return
				
				methodVisitor.visitMaxs(2, 1);
				methodVisitor.visitEnd();
				return null;
			}
		}

		return cv.visitMethod(access, name, descriptor, signature, exceptions);
	}
 
Example 4
Source File: Utils.java    From click-debounce with MIT License 4 votes vote down vote up
static void addDebouncedAnno(MethodVisitor mv) {
  AnnotationVisitor annotationVisitor =
      mv.visitAnnotation("Lcom/smartdengg/clickdebounce/Debounced;", false);
  annotationVisitor.visitEnd();
}
 
Example 5
Source File: ModClassGenerator.java    From customstuff4 with GNU General Public License v3.0 4 votes vote down vote up
private static byte[] generateClassCode(ModInfo info)
{
    checkArgument(info.isValid(), "Invalid mod id");

    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "cs4mod/" + info.id, null, "java/lang/Object", new String[] {CS4_MOD});

    // Mod annotation
    AnnotationVisitor av = cw.visitAnnotation(String.format("L%s;", MOD), true);
    av.visit("modid", info.id);
    av.visit("name", info.name);
    av.visit("version", info.version);
    av.visit("dependencies", String.format("required-after:%s;%s", CustomStuff4.ID, info.dependencies));
    av.visitEnd();

    // Constructor
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mv.visitFieldInsn(GETSTATIC, "net/minecraftforge/common/MinecraftForge", "EVENT_BUS", desc(EVENT_BUS));
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEVIRTUAL, EVENT_BUS, "register", voidMethodDesc("java/lang/Object"), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(2, 1);
    mv.visitEnd();

    // PreInit
    mv = cw.visitMethod(ACC_PUBLIC, "preInit", voidMethodDesc(PRE_INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onPreInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // Init
    mv = cw.visitMethod(ACC_PUBLIC, "init", voidMethodDesc(INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // PostInit
    mv = cw.visitMethod(ACC_PUBLIC, "postInit", voidMethodDesc(POST_INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onPostInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterBlocks
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterBlocks", voidMethodDesc(REGISTER_BLOCKS_EVENT), voidMethodDesc(REGISTER_BLOCKS_SIGNATURE), null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterBlocks", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterItems
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterItems", voidMethodDesc(REGISTER_ITEMS_EVENT), voidMethodDesc(REGISTER_ITEMS_SIGNATURE), null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterItems", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterModels
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterModels", voidMethodDesc(REGISTER_MODELS_EVENT), null, null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterModels", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    return cw.toByteArray();
}
 
Example 6
Source File: AnnotatedMethodTest.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void generate(TraceClassVisitor cw) {

	
	MethodVisitor mv;
	AnnotationVisitor av0;

	cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, "soot/asm/backend/targets/AnnotatedMethod",
			null, "java/lang/Object", null);
	cw.visitSource("AnnotatedMethod.java", null);
	
	{
	mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
	mv.visitCode();
	mv.visitVarInsn(ALOAD, 0);
	mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
	mv.visitInsn(RETURN);
	mv.visitMaxs(0, 0);
	mv.visitEnd();
	}
	{
	mv = cw.visitMethod(ACC_PUBLIC, "doSth", "()V", null, null);
	{
	av0 = mv.visitAnnotation("Lsoot/asm/backend/targets/MyTestAnnotation;", true);
	av0.visit("iVal", new Integer(124));
	av0.visit("fVal", new Float("5132.0"));
	av0.visit("lVal", new Long(5123L));
	av0.visit("dVal", new Double("745.0"));
	av0.visit("zVal", Boolean.TRUE);
	av0.visit("bVal", new Byte((byte)1));
	av0.visit("sVal", new Short((short)123));
	av0.visit("strVal", "435243");
	av0.visit("rVal", Type.getType("Lsoot/asm/backend/targets/AnnotatedClass;"));
	av0.visit("iAVal", new int[] {123,234,345,456});
	{
	AnnotationVisitor av1 = av0.visitArray("sAVal");
	av1.visit(null, "A");
	av1.visit(null, "B");
	av1.visit(null, "C");
	av1.visitEnd();
	}
	av0.visitEnd();
	}
	mv.visitCode();
	mv.visitInsn(RETURN);
	mv.visitMaxs(0, 0);
	mv.visitEnd();
	}
	cw.visitEnd();


}
 
Example 7
Source File: ASMClassParser.java    From TickDynamic with MIT License 4 votes vote down vote up
protected void parseMethod(int access, String signature) throws Exception {
	String value = getCurrentToken();
	String methodName;
	String desc;
	String[] exceptionsArray = null;
	
	Map<String, Label> labels = new HashMap<String, Label>();
	
	int index = value.indexOf("(");
	methodName = value.substring(0, index);
	desc = value.substring(index);
	
	//System.out.println("Parsing method: " + methodName + " Desc: " + desc);
	
	value = nextToken();
	
	if(value.equals("throws")) {
		List<String> exceptions = new ArrayList<String>();
		while(true)
		{
			value = nextToken();
			if(value.equals("\n"))
				break;
			exceptions.add(value);
		}
		exceptionsArray = exceptions.toArray(new String[exceptions.size()]);
	} else if(!value.equals("\n"))
		throw new Exception(getCurrentTokenLine() + ": Error while parsing method: Expected \\n on method header, got: " + value);
	
	MethodVisitor method = cl.visitMethod(access, methodName, desc, signature, exceptionsArray); //TODO: Generics and exceptions
	
	//Read any annotations for the method
	while(true)
	{
		value = nextToken();
		if(value.startsWith("@"))
		{
			int valuesOffset = value.indexOf("(");
			String valuesToken = "";
			if(valuesOffset != -1)
			{
				valuesToken = value.substring(valuesOffset);
				valuesToken += getLine(); //There is whitespace inside the (), so we have to combine the tokens
			}
			desc = value.substring(1, valuesOffset);
			
			AnnotationVisitor av = method.visitAnnotation(desc, true);
			parseAnnotation(av, valuesToken);
			av.visitEnd();
		}
		else //End of method header if we reach anything else
		{
			currentToken--;
			break;
		}
	}

	//Parse method instructions
	boolean lineData = false;
	String insnSignature = null;
	while(true) {
		value = nextToken();
		
		if(value.equals("}"))
		{
			currentToken--; //Allow main loop to detect the class end
			break;
		}
		else if(value.startsWith("//"))
		{

			//Check for pre-method generics signature
			value = nextToken();
			if(value.equals("signature"))
				insnSignature = nextToken();
			else
				currentToken--;
			skipLine();
			continue;
		}
		if(!value.equals("\n"))
		{
			lineData = true;
			currentToken--;
			parseInstruction(method, labels, insnSignature);
			insnSignature = null; //Reset signature after known instruction
		}
		else
		{
			if(lineData == false)
				break; //End of method
			else
				lineData = false;
		}
	}
	
	method.visitEnd();
}
 
Example 8
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private static void visitAnnotation(MethodVisitor mv, String descriptor) {
    AnnotationVisitor av = mv.visitAnnotation(descriptor, true);
    checkNotNull(av);
    av.visitEnd();
}
 
Example 9
Source File: CommonMethodsBuilder.java    From OpenPeripheral with MIT License 4 votes vote down vote up
public void createScriptMethodWrapper(String methodName, int methodIndex, IMethodExecutor executor) {

		final String generatedMethodName = methodName.replaceAll("[^A-Za-z0-9_]", "_") + "$" + Integer.toString(methodIndex);

		final MethodVisitor wrap = writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, generatedMethodName, WRAP_TYPE.getDescriptor(), null, null);

		final Optional<String> returnSignal = executor.getReturnSignal();

		final AnnotationVisitor av = wrap.visitAnnotation(CALLBACK_TYPE.getDescriptor(), true);
		av.visit("value", methodName);
		// functions with return signal always return immediately
		av.visit("direct", executor.isAsynchronous() || returnSignal.isPresent());
		av.visit("doc", DocUtils.doc(executor.description()));
		av.visitEnd();
		// TODO: getter/setter

		av.visitEnd();

		wrap.visitCode();

		wrap.visitVarInsn(Opcodes.ALOAD, 0); // this
		wrap.visitInsn(Opcodes.DUP); // this, this
		wrap.visitFieldInsn(Opcodes.GETFIELD, clsName, TARGET_FIELD_NAME, targetType.getDescriptor()); // this, target

		Label skip = new Label();
		wrap.visitInsn(Opcodes.DUP); // this, target, target
		wrap.visitJumpInsn(Opcodes.IFNONNULL, skip); // this, target
		wrap.visitInsn(Opcodes.POP); // this
		wrap.visitMethodInsn(Opcodes.INVOKEINTERFACE, BASE_TYPE.getInternalName(), "invalidState", INVALID_STATE_TYPE.getDescriptor(), true); // result
		wrap.visitInsn(Opcodes.ARETURN);
		wrap.visitLabel(skip);

		wrap.visitFieldInsn(Opcodes.GETSTATIC, clsName, METHODS_FIELD_NAME, EXECUTORS_TYPE.getDescriptor()); // this, target, methods[]
		visitIntConst(wrap, methodIndex); // this, target, methods[], methodIndex
		wrap.visitInsn(Opcodes.AALOAD); // this, target, executor

		if (returnSignal.isPresent()) wrap.visitLdcInsn(returnSignal.get());
		wrap.visitVarInsn(Opcodes.ALOAD, 1); // this, target, executor, (returnSignal), context
		wrap.visitVarInsn(Opcodes.ALOAD, 2); // this, target, executor, (returnSignal), context, args

		if (returnSignal.isPresent()) {
			final String baseCallName = executor.isAsynchronous()? "callSignallingAsync" : "callSignallingSync";
			wrap.visitMethodInsn(Opcodes.INVOKEINTERFACE, SIGNALLING_BASE_TYPE.getInternalName(), baseCallName, SIGNALLING_CALLER_METHOD_TYPE.getDescriptor(), true);
		} else {
			wrap.visitMethodInsn(Opcodes.INVOKEINTERFACE, BASE_TYPE.getInternalName(), "call", CALLER_METHOD_TYPE.getDescriptor(), true);
		}
		wrap.visitInsn(Opcodes.ARETURN);

		wrap.visitMaxs(0, 0);

		wrap.visitEnd();
	}