Java Code Examples for net.bytebuddy.description.method.MethodDescription#getStackSize()

The following examples show how to use net.bytebuddy.description.method.MethodDescription#getStackSize() . 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: MethodCallProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    FieldList<?> fieldList = instrumentedType.getDeclaredFields();
    StackManipulation[] fieldLoading = new StackManipulation[fieldList.size()];
    int index = 0;
    for (FieldDescription fieldDescription : fieldList) {
        fieldLoading[index] = new StackManipulation.Compound(
                MethodVariableAccess.loadThis(),
                MethodVariableAccess.load(instrumentedMethod.getParameters().get(index)),
                FieldAccess.forField(fieldDescription).write()
        );
        index++;
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            MethodVariableAccess.loadThis(),
            MethodInvocation.invoke(ConstructorCall.INSTANCE.objectTypeDefaultConstructor),
            new StackManipulation.Compound(fieldLoading),
            MethodReturn.VOID
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 2
Source File: FieldAccessor.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    FieldDescription fieldDescription = fieldLocation.resolve(instrumentedMethod);
    if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot set instance field " + fieldDescription + " from " + instrumentedMethod);
    } else if (fieldDescription.isFinal() && instrumentedMethod.isMethod()) {
        throw new IllegalStateException("Cannot set final field " + fieldDescription + " from " + instrumentedMethod);
    }
    StackManipulation stackManipulation = resolve(initialized, fieldDescription, instrumentedType, instrumentedMethod);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Set value cannot be assigned to " + fieldDescription);
    }
    return new Size(new StackManipulation.Compound(
            instrumentedMethod.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            stackManipulation,
            FieldAccess.forField(fieldDescription).write(),
            terminationHandler.resolve(instrumentedMethod)
    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 3
Source File: CopierImplementation.java    From unsafe with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext,
    MethodDescription instrumentedMethod) {

  checkMethodSignature(instrumentedMethod);

  try {
    StackManipulation stack = buildStack();
    StackManipulation.Size finalStackSize = stack.apply(methodVisitor, implementationContext);

    return new Size(finalStackSize.getMaximalSize(),
        instrumentedMethod.getStackSize() + 2); // 2 stack slots for a single local variable

  } catch (NoSuchMethodException | NoSuchFieldException e) {
    throw new RuntimeException(e);
  }
}
 
Example 4
Source File: SimpleExceptionHandler.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext,
                  MethodDescription instrumentedMethod) {

    final Label startTryBlock = new Label();
    final Label endTryBlock = new Label();
    final Label startCatchBlock = new Label();

    final StackManipulation preTriggerAppender = preTrigger(startTryBlock, endTryBlock, startCatchBlock);
    final StackManipulation postTriggerAppender = postTrigger(endTryBlock, startCatchBlock);

    final StackManipulation delegate = new StackManipulation.Compound(
            preTriggerAppender, exceptionThrowingAppender, postTriggerAppender, exceptionHandlerAppender
    );

    final StackManipulation.Size operandStackSize = delegate.apply(methodVisitor, implementationContext);
    return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + newLocalVariablesCount);
}
 
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.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 6
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 7
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 8
Source File: AdviceDeadCodeTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitInsn(Opcodes.DUP_X1); // dead code
    methodVisitor.visitInsn(Opcodes.ARETURN);
    return new Size(1, instrumentedMethod.getStackSize());
}
 
Example 9
Source File: ToStringMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("toString method must not be static: " + instrumentedMethod);
    } else if (!instrumentedMethod.getReturnType().asErasure().isAssignableFrom(String.class)) {
        throw new IllegalStateException("toString method does not return String-compatible type: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(Math.max(0, fieldDescriptions.size() * 7 - 2) + 10);
    stackManipulations.add(TypeCreation.of(TypeDescription.ForLoadedType.of(StringBuilder.class)));
    stackManipulations.add(Duplication.SINGLE);
    stackManipulations.add(new TextConstant(prefix));
    stackManipulations.add(MethodInvocation.invoke(STRING_BUILDER_CONSTRUCTOR));
    stackManipulations.add(new TextConstant(start));
    stackManipulations.add(ValueConsumer.STRING);
    boolean first = true;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        if (first) {
            first = false;
        } else {
            stackManipulations.add(new TextConstant(separator));
            stackManipulations.add(ValueConsumer.STRING);
        }
        stackManipulations.add(new TextConstant(fieldDescription.getName() + definer));
        stackManipulations.add(ValueConsumer.STRING);
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        stackManipulations.add(ValueConsumer.of(fieldDescription.getType().asErasure()));
    }
    stackManipulations.add(new TextConstant(end));
    stackManipulations.add(ValueConsumer.STRING);
    stackManipulations.add(MethodInvocation.invoke(TO_STRING));
    stackManipulations.add(MethodReturn.REFERENCE);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 10
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    TargetHandler.Resolved targetHandler = this.targetHandler.resolve(instrumentedMethod);
    return new Size(new StackManipulation.Compound(terminationHandler.prepare(), toStackManipulation(instrumentedMethod,
            toInvokedMethod(instrumentedMethod, targetHandler),
            targetHandler)).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 11
Source File: DefaultMethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    StackManipulation defaultMethodInvocation = locateDefault(instrumentedMethod);
    if (!defaultMethodInvocation.isValid()) {
        throw new IllegalStateException("Cannot invoke default method on " + instrumentedMethod);
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            MethodVariableAccess.allArgumentsOf(instrumentedMethod).prependThisReference(),
            defaultMethodInvocation,
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 12
Source File: AdviceExchangedDuplicationTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    methodVisitor.visitLdcInsn(ignoredValue);
    methodVisitor.visitLdcInsn(value);
    methodVisitor.visitInsn(duplication);
    methodVisitor.visitInsn(Type.getType(valueType).getSize() == 2 ? Opcodes.POP2 : Opcodes.POP);
    methodVisitor.visitInsn(Type.getType(ignoredValueType).getSize() == 2 ? Opcodes.POP2 : Opcodes.POP);
    methodVisitor.visitInsn(Type.getType(valueType).getOpcode(Opcodes.IRETURN));
    return new Size(Type.getType(valueType).getSize() * 2 + Type.getType(ignoredValueType).getSize(), instrumentedMethod.getStackSize());
}
 
Example 13
Source File: StackAwareMethodVisitor.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new stack aware method visitor.
 *
 * @param methodVisitor      The method visitor to delegate operations to.
 * @param instrumentedMethod The method description for which this method visitor is applied.
 */
public StackAwareMethodVisitor(MethodVisitor methodVisitor, MethodDescription instrumentedMethod) {
    super(OpenedClassReader.ASM_API, methodVisitor);
    current = new ArrayList<StackSize>();
    sizes = new HashMap<Label, List<StackSize>>();
    freeIndex = instrumentedMethod.getStackSize();
}
 
Example 14
Source File: ByteCodeAppender.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext,
                  MethodDescription instrumentedMethod) {
    Size size = new Size(0, instrumentedMethod.getStackSize());
    for (ByteCodeAppender byteCodeAppender : byteCodeAppenders) {
        size = size.merge(byteCodeAppender.apply(methodVisitor, implementationContext, instrumentedMethod));
    }
    return size;
}
 
Example 15
Source File: AdviceDeadCodeTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitInsn(Opcodes.POP); // dead code
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    return new Size(1, instrumentedMethod.getStackSize());
}
 
Example 16
Source File: ExceptionMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            constructionDelegate.make(),
            Throw.INSTANCE
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 17
Source File: SuperMethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
    StackManipulation superMethodCall = implementationTarget
            .invokeDominant(instrumentedMethod.asSignatureToken())
            .withCheckedCompatibilityTo(instrumentedMethod.asTypeToken());
    if (!superMethodCall.isValid()) {
        throw new IllegalStateException("Cannot call super (or default) method for " + instrumentedMethod);
    }
    StackManipulation.Size size = new StackManipulation.Compound(
            MethodVariableAccess.allArgumentsOf(instrumentedMethod).prependThisReference(),
            superMethodCall,
            terminationHandler.of(instrumentedMethod)
    ).apply(methodVisitor, implementationContext);
    return new Size(size.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 18
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (!instrumentedMethod.getReturnType().represents(void.class)) {
        throw new IllegalStateException("Instrumented method " + instrumentedMethod + " does not return void for field setting method call");
    }
    return new Size(MethodReturn.VOID.apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 19
Source File: AdviceDeadCodeTest.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitInsn(Opcodes.POP); // dead code
    methodVisitor.visitInsn(Opcodes.RETURN);
    return new Size(1, instrumentedMethod.getStackSize());
}
 
Example 20
Source File: InlineDirtyCheckingHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Size apply(
		MethodVisitor methodVisitor,
		Context implementationContext,
		MethodDescription instrumentedMethod) {
	// if (arg != field) {
	methodVisitor.visitVarInsn( Type.getType( persistentField.getType().asErasure().getDescriptor() ).getOpcode( Opcodes.ILOAD ), 1 );
	methodVisitor.visitVarInsn( Opcodes.ALOAD, 0 );
	if ( persistentField.getDeclaringType().asErasure().equals( managedCtClass ) ) {
		methodVisitor.visitFieldInsn(
				Opcodes.GETFIELD,
				persistentField.getDeclaringType().asErasure().getInternalName(),
				persistentField.getName(),
				persistentField.getDescriptor()
		);
	}
	else {
		methodVisitor.visitMethodInsn(
				Opcodes.INVOKEVIRTUAL,
				persistentField.getDeclaringType().asErasure().getInternalName(),
				EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + persistentField.getName(),
				Type.getMethodDescriptor( Type.getType( persistentField.getDescriptor() ) ),
				false
		);
	}
	int branchCode;
	if ( persistentField.getType().isPrimitive() ) {
		if ( persistentField.getType().represents( long.class ) ) {
			methodVisitor.visitInsn( Opcodes.LCMP );
		}
		else if ( persistentField.getType().represents( float.class ) ) {
			methodVisitor.visitInsn( Opcodes.FCMPL );
		}
		else if ( persistentField.getType().represents( double.class ) ) {
			methodVisitor.visitInsn( Opcodes.DCMPL );
		}
		else {
			methodVisitor.visitInsn( Opcodes.ISUB );
		}
		branchCode = Opcodes.IFEQ;
	}
	else {
		methodVisitor.visitMethodInsn(
				Opcodes.INVOKESTATIC,
				Type.getInternalName( Objects.class ),
				"deepEquals",
				Type.getMethodDescriptor( Type.getType( boolean.class ), Type.getType( Object.class ), Type.getType( Object.class ) ),
				false
		);
		branchCode = Opcodes.IFNE;
	}
	Label skip = new Label();
	methodVisitor.visitJumpInsn( branchCode, skip );
	// this.$$_hibernate_trackChange(fieldName)
	methodVisitor.visitVarInsn( Opcodes.ALOAD, 0 );
	methodVisitor.visitLdcInsn( persistentField.getName() );
	methodVisitor.visitMethodInsn(
			Opcodes.INVOKEVIRTUAL,
			managedCtClass.getInternalName(),
			EnhancerConstants.TRACKER_CHANGER_NAME,
			Type.getMethodDescriptor( Type.getType( void.class ), Type.getType( String.class ) ),
			false
	);
	// }
	methodVisitor.visitLabel( skip );
	if ( implementationContext.getClassFileVersion().isAtLeast( ClassFileVersion.JAVA_V6 ) ) {
		methodVisitor.visitFrame( Opcodes.F_SAME, 0, null, 0, null );
	}
	return new Size( 1 + 2 * persistentField.getType().asErasure().getStackSize().getSize(), instrumentedMethod.getStackSize() );
}