net.bytebuddy.implementation.bytecode.member.MethodVariableAccess Java Examples

The following examples show how to use net.bytebuddy.implementation.bytecode.member.MethodVariableAccess. 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: MethodCall.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    TypeDescription.Generic componentType;
    if (target.getType().represents(Object.class)) {
        componentType = TypeDescription.Generic.OBJECT;
    } else if (target.getType().isArray()) {
        componentType = target.getType().getComponentType();
    } else {
        throw new IllegalStateException("Cannot set method parameter array for non-array type: " + target);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(parameters.size());
    for (ParameterDescription parameter : parameters) {
        StackManipulation stackManipulation = new StackManipulation.Compound(
                MethodVariableAccess.load(parameter),
                assigner.assign(parameter.getType(), componentType, typing)
        );
        if (stackManipulation.isValid()) {
            stackManipulations.add(stackManipulation);
        } else {
            throw new IllegalStateException("Cannot assign " + parameter + " to " + componentType);
        }
    }
    return new StackManipulation.Compound(ArrayFactory.forType(componentType).withValues(stackManipulations));
}
 
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: FieldAccessor.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected StackManipulation resolve(FieldLocation.Prepared target,
                                    FieldDescription fieldDescription,
                                    TypeDescription instrumentedType,
                                    MethodDescription instrumentedMethod) {
    FieldDescription resolved = target.resolve(instrumentedMethod);
    if (!resolved.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot set instance field " + fieldDescription + " from " + instrumentedMethod);
    }
    return new StackManipulation.Compound(
            resolved.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            FieldAccess.forField(resolved).read(),
            assigner.assign(resolved.getType(), fieldDescription.getType(), typing)
    );
}
 
Example #4
Source File: PropertyMutatorCollector.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) {

    final boolean mustCast = (beanValueAccess == MethodVariableAccess.REFERENCE);

    final List<StackManipulation> operations = new ArrayList<StackManipulation>();
    operations.add(loadLocalVar()); // load local for cast bean
    operations.add(loadBeanValueArg());

    final AnnotatedMember member = prop.getMember();
    if (mustCast) {
        operations.add(TypeCasting.to(new ForLoadedType(getClassToCastBeanValueTo(member))));
    }

    operations.add(invocationOperation(member, beanClassDescription));
    operations.add(MethodReturn.VOID);

    final StackManipulation.Compound compound = new StackManipulation.Compound(operations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example #5
Source File: AdviceTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssigningEnterPostProcessorInline() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(PostProcessorInlineTest.class)
            .visit(Advice.withCustomMapping().with(new Advice.PostProcessor.Factory() {
                @Override
                public Advice.PostProcessor make(final MethodDescription.InDefinedShape advice, boolean exit) {
                    return new Advice.PostProcessor() {
                        @Override
                        public StackManipulation resolve(TypeDescription instrumentedType,
                                                         MethodDescription instrumentedMethod,
                                                         Assigner assigner,
                                                         Advice.ArgumentHandler argumentHandler) {
                            return new StackManipulation.Compound(
                                MethodVariableAccess.of(advice.getReturnType()).loadFrom(argumentHandler.enter()),
                                MethodVariableAccess.store(instrumentedMethod.getParameters().get(0))
                            );
                        }
                    };
                }
            }).to(PostProcessorInlineTest.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO, String.class).invoke(type.getDeclaredConstructor().newInstance(), BAR), is((Object) FOO));
}
 
Example #6
Source File: FixedValue.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) {
    if (instrumentedMethod.getParameters().size() <= index) {
        throw new IllegalStateException(instrumentedMethod + " does not define a parameter with index " + index);
    }
    ParameterDescription parameterDescription = instrumentedMethod.getParameters().get(index);
    StackManipulation stackManipulation = new StackManipulation.Compound(
            MethodVariableAccess.load(parameterDescription),
            assigner.assign(parameterDescription.getType(), instrumentedMethod.getReturnType(), typing),
            MethodReturn.of(instrumentedMethod.getReturnType())
    );
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + instrumentedMethod.getReturnType() + " to " + parameterDescription);
    }
    return new Size(stackManipulation.apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #7
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    if (implementationTarget.getInstrumentedType().isInterface()) {
        throw new IllegalStateException("Cannot implement meaningful equals method for " + implementationTarget.getInstrumentedType());
    }
    List<FieldDescription.InDefinedShape> fields = new ArrayList<FieldDescription.InDefinedShape>(implementationTarget.getInstrumentedType()
            .getDeclaredFields()
            .filter(not(isStatic().or(ignored))));
    Collections.sort(fields, comparator);
    return new Appender(implementationTarget.getInstrumentedType(), new StackManipulation.Compound(
            superClassCheck.resolve(implementationTarget.getInstrumentedType()),
            MethodVariableAccess.loadThis(),
            MethodVariableAccess.REFERENCE.loadFrom(1),
            ConditionalReturn.onIdentity().returningTrue(),
            typeCompatibilityCheck.resolve(implementationTarget.getInstrumentedType())
    ), fields, nonNullable);
}
 
Example #8
Source File: TypeProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    TypeDescription proxyType = implementationContext.register(new TypeProxy(proxiedType,
            implementationTarget,
            InvocationFactory.Default.DEFAULT_METHOD,
            true,
            serializableProxy));
    return new Compound(
            TypeCreation.of(proxyType),
            Duplication.SINGLE,
            MethodInvocation.invoke(proxyType.getDeclaredMethods().filter(isConstructor()).getOnly()),
            Duplication.SINGLE,
            MethodVariableAccess.loadThis(),
            FieldAccess.forField(proxyType.getDeclaredFields().filter((named(INSTANCE_FIELD))).getOnly()).write()
    ).apply(methodVisitor, implementationContext);
}
 
Example #9
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();
    List<StackManipulation> fieldLoadings = new ArrayList<StackManipulation>(fieldList.size());
    for (FieldDescription fieldDescription : fieldList) {
        fieldLoadings.add(new StackManipulation.Compound(MethodVariableAccess.loadThis(), FieldAccess.forField(fieldDescription).read()));
    }
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            new StackManipulation.Compound(fieldLoadings),
            MethodInvocation.invoke(accessorMethod),
            assigner.assign(accessorMethod.getReturnType(), instrumentedMethod.getReturnType(), Assigner.Typing.DYNAMIC),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #10
Source File: ByteBuddy.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) {
    if (instrumentedMethod.isMethod()) {
        return new Simple(
                MethodVariableAccess.loadThis(),
                FieldAccess.forField(instrumentedType.getDeclaredFields().filter(named(instrumentedMethod.getName())).getOnly()).read(),
                MethodReturn.of(instrumentedMethod.getReturnType())
        ).apply(methodVisitor, implementationContext, instrumentedMethod);
    } else {
        List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(instrumentedType.getRecordComponents().size() * 3 + 2);
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(MethodInvocation.invoke(new MethodDescription.Latent(JavaType.RECORD.getTypeStub(), new MethodDescription.Token(Opcodes.ACC_PUBLIC))));
        int offset = 1;
        for (RecordComponentDescription.InDefinedShape recordComponent : instrumentedType.getRecordComponents()) {
            stackManipulations.add(MethodVariableAccess.loadThis());
            stackManipulations.add(MethodVariableAccess.of(recordComponent.getType()).loadFrom(offset));
            stackManipulations.add(FieldAccess.forField(instrumentedType.getDeclaredFields()
                    .filter(named(recordComponent.getActualName()))
                    .getOnly()).write());
            offset += recordComponent.getType().getStackSize().getSize();
        }
        stackManipulations.add(MethodReturn.VOID);
        return new Simple(stackManipulations).apply(methodVisitor, implementationContext, instrumentedMethod);
    }
}
 
Example #11
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 #12
Source File: TypeProxy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    TypeDescription proxyType = implementationContext
            .register(new TypeProxy(proxiedType,
                    implementationTarget,
                    InvocationFactory.Default.SUPER_METHOD,
                    ignoreFinalizer,
                    serializableProxy));
    StackManipulation[] constructorValue = new StackManipulation[constructorParameters.size()];
    int index = 0;
    for (TypeDescription parameterType : constructorParameters) {
        constructorValue[index++] = DefaultValue.of(parameterType);
    }
    return new Compound(
            TypeCreation.of(proxyType),
            Duplication.SINGLE,
            new Compound(constructorValue),
            MethodInvocation.invoke(proxyType.getDeclaredMethods().filter(isConstructor().and(takesArguments(constructorParameters))).getOnly()),
            Duplication.SINGLE,
            MethodVariableAccess.loadThis(),
            FieldAccess.forField(proxyType.getDeclaredFields().filter((named(INSTANCE_FIELD))).getOnly()).write()
    ).apply(methodVisitor, implementationContext);
}
 
Example #13
Source File: InvocationHandlerAdapter.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Applies an implementation that delegates to a invocation handler.
 *
 * @param methodVisitor         The method visitor for writing the byte code to.
 * @param implementationContext The implementation context for the current implementation.
 * @param instrumentedMethod    The method that is instrumented.
 * @param preparingManipulation A stack manipulation that applies any preparation to the operand stack.
 * @param fieldDescription      The field that contains the value for the invocation handler.
 * @return The size of the applied assignment.
 */
protected ByteCodeAppender.Size apply(MethodVisitor methodVisitor,
                                      Context implementationContext,
                                      MethodDescription instrumentedMethod,
                                      StackManipulation preparingManipulation,
                                      FieldDescription fieldDescription) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("It is not possible to apply an invocation handler onto the static method " + instrumentedMethod);
    }
    MethodConstant.CanCache methodConstant = privileged
            ? MethodConstant.ofPrivileged(instrumentedMethod.asDefined())
            : MethodConstant.of(instrumentedMethod.asDefined());
    StackManipulation.Size stackSize = new StackManipulation.Compound(
            preparingManipulation,
            FieldAccess.forField(fieldDescription).read(),
            MethodVariableAccess.loadThis(),
            cached ? methodConstant.cached() : methodConstant,
            ArrayFactory.forType(TypeDescription.Generic.OBJECT).withValues(argumentValuesOf(instrumentedMethod)),
            MethodInvocation.invoke(INVOCATION_HANDLER_TYPE.getDeclaredMethods().getOnly()),
            assigner.assign(TypeDescription.Generic.OBJECT, instrumentedMethod.getReturnType(), Assigner.Typing.DYNAMIC),
            MethodReturn.of(instrumentedMethod.getReturnType())
    ).apply(methodVisitor, implementationContext);
    return new ByteCodeAppender.Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #14
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(MethodDescription invokedMethod, Assigner assigner, Assigner.Typing typing) {
    if (instrumentedMethod.isStatic() && !invokedMethod.isStatic() && !invokedMethod.isConstructor()) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " from " + instrumentedMethod);
    } else if (invokedMethod.isConstructor() && (!instrumentedMethod.isConstructor()
            || !instrumentedType.equals(invokedMethod.getDeclaringType().asErasure())
            && !instrumentedType.getSuperClass().asErasure().equals(invokedMethod.getDeclaringType().asErasure()))) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " from " + instrumentedMethod + " in " + instrumentedType);
    }
    return new StackManipulation.Compound(
            invokedMethod.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            invokedMethod.isConstructor()
                    ? Duplication.SINGLE
                    : StackManipulation.Trivial.INSTANCE
    );
}
 
Example #15
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot access non-static " + fieldDescription + " from " + instrumentedMethod);
    }
    StackManipulation stackManipulation = new StackManipulation.Compound(
            fieldDescription.isStatic()
                    ? StackManipulation.Trivial.INSTANCE
                    : MethodVariableAccess.loadThis(),
            FieldAccess.forField(fieldDescription).read(),
            assigner.assign(fieldDescription.getType(), target.getType(), typing)
    );
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + fieldDescription + " to " + target);
    }
    return stackManipulation;
}
 
Example #16
Source File: AdviceTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssigningEnterPostProcessorDelegate() throws Exception {
    Class<?> type = new ByteBuddy()
            .redefine(PostProcessorDelegateTest.class)
            .visit(Advice.withCustomMapping().with(new Advice.PostProcessor.Factory() {
                @Override
                public Advice.PostProcessor make(final MethodDescription.InDefinedShape advice, boolean exit) {
                    return new Advice.PostProcessor() {
                        @Override
                        public StackManipulation resolve(TypeDescription instrumentedType,
                                                         MethodDescription instrumentedMethod,
                                                         Assigner assigner,
                                                         Advice.ArgumentHandler argumentHandler) {
                            return new StackManipulation.Compound(
                                    MethodVariableAccess.of(advice.getReturnType()).loadFrom(argumentHandler.enter()),
                                    MethodVariableAccess.store(instrumentedMethod.getParameters().get(0))
                            );
                        }
                    };
                }
            }).to(PostProcessorDelegateTest.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO, String.class).invoke(type.getDeclaredConstructor().newInstance(), BAR), is((Object) FOO));
}
 
Example #17
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Override
public StackManipulation resolve(TypeDescription instrumentedType) {
    return new StackManipulation.Compound(
            MethodVariableAccess.REFERENCE.loadFrom(1),
            ConditionalReturn.onNullValue(),
            MethodVariableAccess.REFERENCE.loadFrom(0),
            MethodInvocation.invoke(GET_CLASS),
            MethodVariableAccess.REFERENCE.loadFrom(1),
            MethodInvocation.invoke(GET_CLASS),
            ConditionalReturn.onNonIdentity()
    );
}
 
Example #18
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Override
protected StackManipulation resolve(TypeDescription instrumentedType) {
    TypeDefinition superClass = instrumentedType.getSuperClass();
    if (superClass == null) {
        throw new IllegalStateException(instrumentedType + " does not declare a super class");
    }
    return new StackManipulation.Compound(MethodVariableAccess.loadThis(),
            MethodVariableAccess.REFERENCE.loadFrom(1),
            MethodInvocation.invoke(EQUALS).special(superClass.asErasure()),
            ConditionalReturn.onZeroInteger());
}
 
Example #19
Source File: EqualsMethod.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("Hash code method must not be static: " + instrumentedMethod);
    } else if (instrumentedMethod.getParameters().size() != 1 || instrumentedMethod.getParameters().getOnly().getType().isPrimitive()) {
        throw new IllegalStateException();
    } else if (!instrumentedMethod.getReturnType().represents(boolean.class)) {
        throw new IllegalStateException("Hash code method does not return primitive boolean: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(3 + fieldDescriptions.size() * 8);
    stackManipulations.add(baseline);
    int padding = 0;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        stackManipulations.add(MethodVariableAccess.REFERENCE.loadFrom(1));
        stackManipulations.add(TypeCasting.to(instrumentedType));
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        NullValueGuard nullValueGuard = fieldDescription.getType().isPrimitive() || fieldDescription.getType().isArray() || nonNullable.matches(fieldDescription)
                ? NullValueGuard.NoOp.INSTANCE
                : new NullValueGuard.UsingJump(instrumentedMethod);
        stackManipulations.add(nullValueGuard.before());
        stackManipulations.add(ValueComparator.of(fieldDescription.getType()));
        stackManipulations.add(nullValueGuard.after());
        padding = Math.max(padding, nullValueGuard.getRequiredVariablePadding());
    }
    stackManipulations.add(IntegerConstant.forValue(true));
    stackManipulations.add(MethodReturn.INTEGER);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize() + padding);
}
 
Example #20
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 #21
Source File: HashCodeMethod.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("Hash code method must not be static: " + instrumentedMethod);
    } else if (!instrumentedMethod.getReturnType().represents(int.class)) {
        throw new IllegalStateException("Hash code method does not return primitive integer: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(2 + fieldDescriptions.size() * 8);
    stackManipulations.add(initialValue);
    int padding = 0;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        stackManipulations.add(IntegerConstant.forValue(multiplier));
        stackManipulations.add(Multiplication.INTEGER);
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        NullValueGuard nullValueGuard = fieldDescription.getType().isPrimitive() || fieldDescription.getType().isArray() || nonNullable.matches(fieldDescription)
                ? NullValueGuard.NoOp.INSTANCE
                : new NullValueGuard.UsingJump(instrumentedMethod);
        stackManipulations.add(nullValueGuard.before());
        stackManipulations.add(ValueTransformer.of(fieldDescription.getType()));
        stackManipulations.add(Addition.INTEGER);
        stackManipulations.add(nullValueGuard.after());
        padding = Math.max(padding, nullValueGuard.getRequiredVariablePadding());
    }
    stackManipulations.add(MethodReturn.INTEGER);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize() + padding);
}
 
Example #22
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Resolved resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Assigner.Typing typing) {
    ParameterList<?> parameters = instrumentedMethod.getParameters();
    if (index >= parameters.size()) {
        throw new IllegalStateException("No parameter " + index + " for " + instrumentedMethod);
    }
    return doResolve(MethodVariableAccess.load(parameters.get(index)), parameters.get(index).getType(), assigner, typing);
}
 
Example #23
Source File: HashCodeMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation resolve(TypeDescription instrumentedType) {
    TypeDefinition superClass = instrumentedType.getSuperClass();
    if (superClass == null) {
        throw new IllegalStateException(instrumentedType + " does not declare a super class");
    }
    return new StackManipulation.Compound(MethodVariableAccess.loadThis(), MethodInvocation.invoke(HASH_CODE).special(superClass.asErasure()));
}
 
Example #24
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 #25
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(MethodDescription invokedMethod, Assigner assigner, Assigner.Typing typing) {
    StackManipulation stackManipulation = assigner.assign(parameterDescription.getType(), invokedMethod.getDeclaringType().asGenericType(), typing);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " on " + parameterDescription.getType());
    }
    return new StackManipulation.Compound(MethodVariableAccess.load(parameterDescription), stackManipulation);
}
 
Example #26
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(MethodDescription invokedMethod, Assigner assigner, Assigner.Typing typing) {
    if (!invokedMethod.isInvokableOn(fieldDescription.getType().asErasure())) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " on " + fieldDescription);
    }
    StackManipulation stackManipulation = assigner.assign(fieldDescription.getType(), invokedMethod.getDeclaringType().asGenericType(), typing);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot invoke " + invokedMethod + " on " + fieldDescription);
    }
    return new StackManipulation.Compound(invokedMethod.isStatic() || fieldDescription.isStatic()
            ? StackManipulation.Trivial.INSTANCE
            : MethodVariableAccess.loadThis(),
            FieldAccess.forField(fieldDescription).read(), stackManipulation);
}
 
Example #27
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 #28
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    StackManipulation stackManipulation = new StackManipulation.Compound(
            MethodVariableAccess.load(parameterDescription),
            IntegerConstant.forValue(index),
            ArrayAccess.of(parameterDescription.getType().getComponentType()).load(),
            assigner.assign(parameterDescription.getType().getComponentType(), target.getType(), typing)
    );
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + parameterDescription.getType().getComponentType() + " to " + target);
    }
    return stackManipulation;
}
 
Example #29
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation toStackManipulation(ParameterDescription target, Assigner assigner, Assigner.Typing typing) {
    ParameterDescription parameterDescription = instrumentedMethod.getParameters().get(index);
    StackManipulation stackManipulation = new StackManipulation.Compound(
            MethodVariableAccess.load(parameterDescription),
            assigner.assign(parameterDescription.getType(), target.getType(), typing));
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + parameterDescription + " to " + target + " for " + instrumentedMethod);
    }
    return stackManipulation;
}
 
Example #30
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Resolved resolve(TypeDescription instrumentedType, MethodDescription instrumentedMethod, Assigner assigner, Assigner.Typing typing) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot get this instance from static method: " + instrumentedMethod);
    } else if (!instrumentedType.isAssignableTo(typeDescription)) {
        throw new IllegalStateException(instrumentedType + " is not assignable to " + instrumentedType);
    }
    return new Resolved.Simple(MethodVariableAccess.loadThis(), typeDescription);
}