net.bytebuddy.jar.asm.Opcodes Java Examples

The following examples show how to use net.bytebuddy.jar.asm.Opcodes. 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: IfEqual.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext) {
  final int opcode;
  Size size = new Size(-StackSize.of(variableType).getSize() * 2, 0);
  if (variableType == int.class || variableType == boolean.class) {
    opcode = Opcodes.IF_ICMPEQ;
  } else if (variableType == long.class) {
    methodVisitor.visitInsn(Opcodes.LCMP);
    opcode = Opcodes.IFEQ;
  } else if (variableType == float.class) {
    methodVisitor.visitInsn(Opcodes.FCMPG);
    opcode = Opcodes.IFEQ;
  } else if (variableType == double.class) {
    methodVisitor.visitInsn(Opcodes.DCMPG);
    opcode = Opcodes.IFEQ;
  } else {
    // Reference type comparison assumes the result of Object.equals is already on the stack.
    opcode = Opcodes.IFNE;
    // There is only a boolean on the stack, so we only consume one item, unlike the others that
    // consume both.
    size = new Size(-1, 0);
  }
  methodVisitor.visitJumpInsn(opcode, destination);
  return size;
}
 
Example #2
Source File: BridgeClassVisitor.java    From kanela with Apache License 2.0 6 votes vote down vote up
private void processBridge(java.lang.reflect.Method reflectMethod, Annotation annotation) {
    val bridge = (Bridge) annotation;
    val method = Method.getMethod(reflectMethod);
    val targetMethod = Method.getMethod(bridge.value());

    val mv = cv.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), method.getDescriptor(), null, null);
    mv.visitCode();
    int i = 0;
    mv.visitVarInsn(Opcodes.ALOAD, i++);

    for (Type argument : method.getArgumentTypes()) {
        mv.visitVarInsn(argument.getOpcode(Opcodes.ILOAD), i++);
    }

    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, type.getInternalName(), targetMethod.getName(), targetMethod.getDescriptor(), false);
    mv.visitInsn(method.getReturnType().getOpcode(Opcodes.IRETURN));
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example #3
Source File: AdviceExceptionHandler.java    From kanela with Apache License 2.0 6 votes vote down vote up
/**
 * Produces the following bytecode:
 *
 * <pre>
 * } catch(Throwable throwable) {
 *     kanela.agent.bootstrap.log.LoggerHandler.error("An error occurred while trying to apply an advisor", throwable)
 * }
 * </pre>
 */
private static StackManipulation getStackManipulation() {
    return new StackManipulation() {
        @Override
        public boolean isValid() {
            return true;
        }

        @Override
        public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
            val endCatchBlock = new Label();
            //message
            methodVisitor.visitLdcInsn("An error occurred while trying to apply an advisor");
            // logger, message, throwable => throwable, message, logger
            methodVisitor.visitInsn(Opcodes.SWAP);
            methodVisitor.visitMethodInsn(INVOKESTATIC, "kanela/agent/bootstrap/log/LoggerHandler", "error", "(Ljava/lang/String;Ljava/lang/Throwable;)V", false);
            methodVisitor.visitJumpInsn(GOTO, endCatchBlock);
            // ending catch block
            methodVisitor.visitLabel(endCatchBlock);
            return new StackManipulation.Size(-1, 1);
        }
    };
}
 
Example #4
Source File: ReturnHandlingMethodVisitor.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void visitInsn(int opcode) {
    if (!checkpointed && Opcodes.ARETURN == opcode) {
        changed.set(true);

        String callSite = String.format(
                "at %s.%s(%s:%d)",
                currentClassName.replace("/", "."), currentMethod, currentSource, currentLine
        );
        super.visitLdcInsn(callSite);

        super.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                "reactor/core/publisher/Hooks",
                "addReturnInfo",
                "(Lorg/reactivestreams/Publisher;Ljava/lang/String;)Lorg/reactivestreams/Publisher;",
                false
        );
        super.visitTypeInsn(Opcodes.CHECKCAST, returnType);
    }

    super.visitInsn(opcode);
}
 
Example #5
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		MethodDescription instrumentedMethod
) {
	methodVisitor.visitVarInsn( Opcodes.ALOAD, 0 );
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKESPECIAL,
			managedCtClass.getSuperClass().asErasure().getInternalName(),
			EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + persistentField.getName(),
			Type.getMethodDescriptor( Type.getType( persistentField.getType().asErasure().getDescriptor() ) ),
			false
	);
	methodVisitor.visitInsn( Type.getType( persistentField.getType().asErasure().getDescriptor() ).getOpcode( Opcodes.IRETURN ) );
	return new Size( persistentField.getType().getStackSize().getSize(), instrumentedMethod.getStackSize() );
}
 
Example #6
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		MethodDescription instrumentedMethod
) {
	methodVisitor.visitVarInsn( Opcodes.ALOAD, 0 );
	methodVisitor.visitVarInsn( Type.getType( persistentField.getType().asErasure().getDescriptor() ).getOpcode( Opcodes.ILOAD ), 1 );
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKESPECIAL,
			managedCtClass.getSuperClass().asErasure().getInternalName(),
			EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + persistentField.getName(),
			Type.getMethodDescriptor( Type.getType( void.class ), Type.getType( persistentField.getType().asErasure().getDescriptor() ) ),
			false
	);
	methodVisitor.visitInsn( Opcodes.RETURN );
	return new Size( 1 + persistentField.getType().getStackSize().getSize(), instrumentedMethod.getStackSize() );
}
 
Example #7
Source File: FieldWriterAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldRead(MethodVisitor methodVisitor) {
	methodVisitor.visitFieldInsn(
			Opcodes.GETFIELD,
			persistentFieldAsDefined.getDeclaringType().asErasure().getInternalName(),
			persistentFieldAsDefined.getInternalName(),
			persistentFieldAsDefined.getDescriptor()
	);
}
 
Example #8
Source File: BridgeClassVisitor.java    From kanela with Apache License 2.0 5 votes vote down vote up
private void processFieldBridge(java.lang.reflect.Method reflectMethod, Annotation annotation) {
    val fieldBridge = (FieldBridge) annotation;
    val method = Method.getMethod(reflectMethod);

    val mv = cv.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), method.getDescriptor(), null, null);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, type.getInternalName(), fieldBridge.value(), method.getReturnType().getDescriptor());
    mv.visitInsn(Type.getType(type.getDescriptor()).getOpcode(Opcodes.IRETURN));
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example #9
Source File: BytecodeProviderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		MethodDescription instrumentedMethod) {
	int index = 0;
	for ( Method setter : setters ) {
		methodVisitor.visitVarInsn( Opcodes.ALOAD, 1 );
		methodVisitor.visitTypeInsn( Opcodes.CHECKCAST, Type.getInternalName( clazz ) );
		methodVisitor.visitVarInsn( Opcodes.ALOAD, 2 );
		methodVisitor.visitLdcInsn( index++ );
		methodVisitor.visitInsn( Opcodes.AALOAD );
		if ( setter.getParameterTypes()[0].isPrimitive() ) {
			PrimitiveUnboxingDelegate.forReferenceType( TypeDescription.Generic.OBJECT )
					.assignUnboxedTo(
							new TypeDescription.Generic.OfNonGenericType.ForLoadedType( setter.getParameterTypes()[0] ),
							ReferenceTypeAwareAssigner.INSTANCE,
							Assigner.Typing.DYNAMIC
					)
					.apply( methodVisitor, implementationContext );
		}
		else {
			methodVisitor.visitTypeInsn( Opcodes.CHECKCAST, Type.getInternalName( setter.getParameterTypes()[0] ) );
		}
		methodVisitor.visitMethodInsn(
				Opcodes.INVOKEVIRTUAL,
				Type.getInternalName( clazz ),
				setter.getName(),
				Type.getMethodDescriptor( setter ),
				false
		);
	}
	methodVisitor.visitInsn( Opcodes.RETURN );
	return new Size( 4, instrumentedMethod.getStackSize() );
}
 
Example #10
Source File: BytecodeProviderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		MethodDescription instrumentedMethod) {
	methodVisitor.visitLdcInsn( getters.length );
	methodVisitor.visitTypeInsn( Opcodes.ANEWARRAY, Type.getInternalName( Object.class ) );
	int index = 0;
	for ( Method getter : getters ) {
		methodVisitor.visitInsn( Opcodes.DUP );
		methodVisitor.visitLdcInsn( index++ );
		methodVisitor.visitVarInsn( Opcodes.ALOAD, 1 );
		methodVisitor.visitTypeInsn( Opcodes.CHECKCAST, Type.getInternalName( clazz ) );
		methodVisitor.visitMethodInsn(
				Opcodes.INVOKEVIRTUAL,
				Type.getInternalName( clazz ),
				getter.getName(),
				Type.getMethodDescriptor( getter ),
				false
		);
		if ( getter.getReturnType().isPrimitive() ) {
			PrimitiveBoxingDelegate.forPrimitive( new TypeDescription.ForLoadedType( getter.getReturnType() ) )
					.assignBoxedTo(
							TypeDescription.Generic.OBJECT,
							ReferenceTypeAwareAssigner.INSTANCE,
							Assigner.Typing.STATIC
					)
					.apply( methodVisitor, implementationContext );
		}
		methodVisitor.visitInsn( Opcodes.AASTORE );
	}
	methodVisitor.visitInsn( Opcodes.ARETURN );
	return new Size( 6, instrumentedMethod.getStackSize() );
}
 
Example #11
Source File: FieldWriterAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldWrite(MethodVisitor methodVisitor) {
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKESPECIAL,
			managedCtClass.getSuperClass().asErasure().getInternalName(),
			EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + persistentFieldAsDefined.getName(),
			Type.getMethodDescriptor( Type.getType( void.class ), Type.getType( persistentFieldAsDefined.getType().asErasure().getDescriptor() ) ),
			false
	);
}
 
Example #12
Source File: FieldWriterAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldRead(MethodVisitor methodVisitor) {
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKESPECIAL,
			managedCtClass.getSuperClass().asErasure().getInternalName(),
			EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + persistentFieldAsDefined.getName(),
			Type.getMethodDescriptor( Type.getType( persistentFieldAsDefined.getType().asErasure().getDescriptor() ) ),
			false
	);
}
 
Example #13
Source File: FieldWriterAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldWrite(MethodVisitor methodVisitor) {
	methodVisitor.visitFieldInsn(
			Opcodes.PUTFIELD,
			persistentFieldAsDefined.getDeclaringType().asErasure().getInternalName(),
			persistentFieldAsDefined.getInternalName(),
			persistentFieldAsDefined.getDescriptor()
	);
}
 
Example #14
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public MethodVisitor wrap(
		TypeDescription instrumentedType,
		MethodDescription instrumentedMethod,
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		TypePool typePool,
		int writerFlags,
		int readerFlags) {
	return new MethodVisitor( Opcodes.ASM5, methodVisitor ) {
		@Override
		public void visitFieldInsn(int opcode, String owner, String name, String desc) {
			if ( isEnhanced( owner, name, desc ) ) {
				switch ( opcode ) {
					case Opcodes.GETFIELD:
						methodVisitor.visitMethodInsn(
								Opcodes.INVOKEVIRTUAL,
								owner,
								EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + name,
								"()" + desc,
								false
						);
						return;
					case Opcodes.PUTFIELD:
						methodVisitor.visitMethodInsn(
								Opcodes.INVOKEVIRTUAL,
								owner,
								EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + name,
								"(" + desc + ")V",
								false
						);
						return;
				}
			}
			super.visitFieldInsn( opcode, owner, name, desc );
		}
	};
}
 
Example #15
Source File: ReturnHandlingMethodVisitor.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
ReturnHandlingMethodVisitor(
        MethodVisitor visitor,
        String returnType,
        String currentClassName,
        String currentMethod,
        String currentSource,
        AtomicBoolean changed
) {
    super(Opcodes.ASM7, visitor);
    this.changed = changed;
    this.currentClassName = currentClassName;
    this.currentMethod = currentMethod;
    this.returnType = returnType;
    this.currentSource = currentSource;
}
 
Example #16
Source File: FieldReaderAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldWrite(MethodVisitor methodVisitor) {
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKESPECIAL,
			managedCtClass.getSuperClass().asErasure().getInternalName(),
			EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + persistentFieldAsDefined.getName(),
			Type.getMethodDescriptor( Type.getType( void.class ), Type.getType( persistentFieldAsDefined.getType().asErasure().getDescriptor() ) ),
			false
	);
}
 
Example #17
Source File: FieldReaderAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldRead(MethodVisitor methodVisitor) {
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKESPECIAL,
			managedCtClass.getSuperClass().asErasure().getInternalName(),
			EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + persistentFieldAsDefined.getName(),
			Type.getMethodDescriptor( Type.getType( persistentFieldAsDefined.getType().asErasure().getDescriptor() ) ),
			false
	);
}
 
Example #18
Source File: FieldReaderAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldWrite(MethodVisitor methodVisitor) {
	methodVisitor.visitFieldInsn(
			Opcodes.PUTFIELD,
			persistentFieldAsDefined.getDeclaringType().asErasure().getInternalName(),
			persistentFieldAsDefined.getInternalName(),
			persistentFieldAsDefined.getDescriptor()
	);
}
 
Example #19
Source File: FieldReaderAppender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void fieldRead(MethodVisitor methodVisitor) {
	methodVisitor.visitFieldInsn(
			Opcodes.GETFIELD,
			persistentFieldAsDefined.getDeclaringType().asErasure().getInternalName(),
			persistentFieldAsDefined.getInternalName(),
			persistentFieldAsDefined.getDescriptor()
	);
}
 
Example #20
Source File: CallSiteInfoAddingMethodVisitor.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
CallSiteInfoAddingMethodVisitor(
        MethodVisitor visitor,
        String currentClassName,
        String currentMethod,
        String currentSource,
        AtomicBoolean changed
) {
    super(Opcodes.ASM7, visitor);
    this.currentMethod = currentMethod;
    this.currentClassName = currentClassName;
    this.currentSource = currentSource;
    this.changed = changed;
}
 
Example #21
Source File: CallSiteInfoAddingMethodVisitor.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) {
    super.visitMethodInsn(opcode, owner, name, descriptor, isInterface);
    if (isCorePublisher(owner)) {
        if ("checkpoint".equals(name)) {
            return;
        }
        String returnType = Type.getReturnType(descriptor).getInternalName();
        if (!returnType.startsWith("reactor/core/publisher/")) {
            return;
        }

        changed.set(true);

        String callSite = String.format(
                "\t%s.%s\n\t%s.%s(%s:%d)\n",
                owner.replace("/", "."), name,
                currentClassName.replace("/", "."), currentMethod, currentSource, currentLine
        );
        super.visitLdcInsn(callSite);
        super.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                "reactor/core/publisher/Hooks",
                "addCallSiteInfo",
                ADD_CALLSITE_INFO_METHOD,
                false
        );
        super.visitTypeInsn(Opcodes.CHECKCAST, returnType);
    }
}
 
Example #22
Source File: FrontendClassVisitor.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new {@link ClassVisitor} that will be used for visiting a
 * specific class.
 *
 * @param className
 *            the class to visit
 * @param endPoint
 *            the end-point object that will be updated during the visit
 * @param themeScope
 *            whether we are visiting from Theme
 */
FrontendClassVisitor(String className, EndPointData endPoint,
        boolean themeScope) { // NOSONAR
    super(Opcodes.ASM7);
    this.className = className;
    this.endPoint = endPoint;

    // Visitor for each method in the class.
    methodVisitor = new FrontendMethodVisitor();
    // Visitor for each annotation in the class.
    routeVisitor = new RepeatedAnnotationVisitor() {
        @Override
        public void visit(String name, Object value) {
            if (LAYOUT.equals(name)) {
                endPoint.layout = ((Type) value).getClassName();
                children.add(endPoint.layout);
            }
            if (VALUE.equals(name)) {
                endPoint.route = value.toString();
            }
        }
    };
    // Visitor for @Theme annotations in classes annotated with @Route
    themeRouteVisitor = new RepeatedAnnotationVisitor() {
        @Override
        public void visit(String name, Object value) {
            if (VALUE.equals(name)) {
                endPoint.theme.name = ((Type) value).getClassName();
                children.add(endPoint.theme.name);
            } else if (VARIANT.equals(name)) {
                endPoint.theme.variant = value.toString();
            }
        }
    };
    // Visitor for @Theme annotations in classes extending RouterLayout
    themeLayoutVisitor = new RepeatedAnnotationVisitor() {
        @Override
        public void visit(String name, Object value) {
            if (VALUE.equals(name) && endPoint.theme.name == null) {
                themeRouteVisitor.visit(name, value);
            } else if (VARIANT.equals(name)
                    && endPoint.theme.variant.isEmpty()) {
                themeRouteVisitor.visit(name, value);
            }
        }
    };
    // Visitor for @JsModule annotations
    jsModuleVisitor = new RepeatedAnnotationVisitor() {
        @Override
        public void visit(String name, Object value) {
            if (themeScope) {
                endPoint.themeModules.add(value.toString());
            } else {
                endPoint.modules.add(value.toString());
            }
        }
    };
    // Visitor for @JavaScript annotations
    jScriptVisitor = new RepeatedAnnotationVisitor() {
        @Override
        public void visit(String name, Object value) {
            endPoint.scripts.add(value.toString());
        }
    };
    // Visitor all other annotations
    annotationVisitor = new RepeatedAnnotationVisitor() {
        @Override
        public void visit(String name, Object value) {
            if (value != null && !value.getClass().isPrimitive()
                    && !value.getClass().equals(String.class)) {
                addSignatureToClasses(children, value.toString());
            }
        }
    };
}
 
Example #23
Source File: IfRefsEqual.java    From curiostack with MIT License 4 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext) {
  methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, destination);
  return new Size(-StackSize.SINGLE.getSize() * 2, 0);
}
 
Example #24
Source File: FrontendClassVisitor.java    From flow with Apache License 2.0 4 votes vote down vote up
public FrontendMethodVisitor() {
    super(Opcodes.ASM7);
}
 
Example #25
Source File: RepeatedAnnotationVisitor.java    From flow with Apache License 2.0 4 votes vote down vote up
RepeatedAnnotationVisitor() {
    super(Opcodes.ASM7);
}
 
Example #26
Source File: AnalyzedClass.java    From kanela with Apache License 2.0 4 votes vote down vote up
private static Map<String, Set<String>> extractMethods(ClassNode classNode) {
    return List.ofAll(classNode.methods)
            .filter(methodNode -> (methodNode.access & Opcodes.ACC_SYNTHETIC) == 0)
            .toJavaMap(methodNode -> Tuple.of(methodNode.name, Array.of(Type.getArgumentTypes(methodNode.desc)).map(AnalyzedClass::getType).toJavaSet()));
}
 
Example #27
Source File: AnalyzedClass.java    From kanela with Apache License 2.0 4 votes vote down vote up
private static Map<String, Object> extractFieldsAndValues(ClassRefiner refiner, ClassNode classNode, ClassLoader loader) {
    return List.ofAll(classNode.fields)
            .filter(fieldNode -> (fieldNode.access & Opcodes.ACC_SYNTHETIC) == 0)
            .toJavaMap(fieldNode -> Tuple.of(fieldNode.name, extractFieldValue(refiner, fieldNode.name, loader)));
}
 
Example #28
Source File: ReactorDebugClassVisitor.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
ReactorDebugClassVisitor(ClassVisitor classVisitor, AtomicBoolean changed) {
	super(Opcodes.ASM7, classVisitor);
	this.changed = changed;
}
 
Example #29
Source File: IfNotNull.java    From curiostack with MIT License 4 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext) {
  methodVisitor.visitJumpInsn(Opcodes.IFNONNULL, destination);
  return StackSize.SINGLE.toDecreasingSize();
}
 
Example #30
Source File: Goto.java    From curiostack with MIT License 4 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor, Context implementationContext) {
  methodVisitor.visitJumpInsn(Opcodes.GOTO, destination);
  return new Size(0, 0);
}