Java Code Examples for net.bytebuddy.implementation.bytecode.StackManipulation#Compound

The following examples show how to use net.bytebuddy.implementation.bytecode.StackManipulation#Compound . 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}
 */
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 3
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 4
Source File: UsingSwitchStackManipulation.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 List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>();

    stackManipulations.add(loadFieldIndexArg());

    final Label[] labels = new Label[props.size()];
    for (int i = 0, len = labels.length; i < len; ++i) {
        labels[i] = new Label();
    }
    final Label defaultLabel = new Label();
    stackManipulations.add(new TableSwitchStackManipulation(labels, defaultLabel));

    for (int i = 0, len = labels.length; i < len; ++i) {
        stackManipulations.add(new VisitLabelStackManipulation(labels[i]));
        stackManipulations.add(singlePropStackManipulationSupplier.supply(props.get(i)));
    }
    stackManipulations.add(new VisitLabelStackManipulation(defaultLabel));
    // and if no match, generate exception:
    stackManipulations.add(new GenerateIllegalPropertyCountExceptionStackManipulation(props.size()));

    final StackManipulation.Compound compound = new StackManipulation.Compound(stackManipulations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example 5
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 6
Source File: CreatorOptimizer.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private StackManipulation creatorInvokerStackManipulation(Constructor<?> ctor, Method factory) {
    final StackManipulation invokeManipulation =
            null == ctor ?
                invoke(new ForLoadedMethod(factory)) :
                new ConstructorCallStackManipulation.KnownConstructorOfExistingType(ctor);
    return new StackManipulation.Compound(
            invokeManipulation,
            MethodReturn.REFERENCE
    );
}
 
Example 7
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation prepare(MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic() && !methodDescription.isStatic()) {
        throw new IllegalStateException("Cannot invoke " + methodDescription + " from " + instrumentedMethod);
    }
    return new StackManipulation.Compound(methodDescription.isStatic()
            ? StackManipulation.Trivial.INSTANCE
            : MethodVariableAccess.loadThis(), MethodInvocation.invoke(methodDescription));
}
 
Example 8
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) {
    FieldDescription fieldDescription = instrumentedType.getDeclaredFields().filter(named(name)).getOnly();
    StackManipulation stackManipulation = assigner.assign(fieldDescription.getType(), fieldType.asGenericType(), typing);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + fieldDescription + " to " + fieldType);
    }
    return new Resolved.Simple(new StackManipulation.Compound(FieldAccess.forField(fieldDescription).read(),
            stackManipulation), fieldDescription.getType().asErasure());
}
 
Example 9
Source File: AbstractCreateLocalVarStackManipulation.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext) {

    final List<StackManipulation> operations = new ArrayList<StackManipulation>();

    operations.add(MethodVariableAccess.REFERENCE.loadFrom(beanArgIndex())); //load the bean
    operations.add(TypeCasting.to(beanClassDescription));

    operations.add(MethodVariableAccess.REFERENCE.storeAt(localVarIndexCalculator.calculate()));

    final StackManipulation.Compound compound = new StackManipulation.Compound(operations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example 10
Source File: FieldAccessor.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected StackManipulation resolve(Void unused,
                                    FieldDescription fieldDescription,
                                    TypeDescription instrumentedType,
                                    MethodDescription instrumentedMethod) {
    return new StackManipulation.Compound(stackManipulation, assigner.assign(typeDescription, fieldDescription.getType(), typing));
}
 
Example 11
Source File: CreatorOptimizer.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private StackManipulation creatorExceptionHandlerStackManipulation() {
    final TypeDescription typeDescription = new ForLoadedType(OptimizedValueInstantiator.class);
    final InDefinedShape methodDescription =
            typeDescription.getDeclaredMethods().filter(named("_handleInstantiationProblem")).getOnly();

    return new StackManipulation.Compound(
            REFERENCE.storeAt(2), //push exception to new local
            REFERENCE.loadFrom(0), //'this'
            REFERENCE.loadFrom(1), //Arg #1 ("ctxt")
            REFERENCE.loadFrom(2), //exception
            invoke(methodDescription),
            MethodReturn.REFERENCE
    );
}
 
Example 12
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Resolved doResolve(StackManipulation access, TypeDescription.Generic typeDescription, Assigner assigner, Assigner.Typing typing) {
    StackManipulation stackManipulation = assigner.assign(typeDescription, this.typeDescription.asGenericType(), typing);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + typeDescription + " to " + this.typeDescription);
    }
    return new Resolved.Simple(new StackManipulation.Compound(access, stackManipulation), this.typeDescription);
}
 
Example 13
Source File: FieldAccessor.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) {
    if (!instrumentedMethod.isMethod()) {
        throw new IllegalArgumentException(instrumentedMethod + " does not describe a field getter or setter");
    }
    FieldDescription fieldDescription = fieldLocation.resolve(instrumentedMethod);
    if (!fieldDescription.isStatic() && instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Cannot set instance field " + fieldDescription + " from " + instrumentedMethod);
    }
    StackManipulation implementation, initialization = fieldDescription.isStatic()
            ? StackManipulation.Trivial.INSTANCE
            : MethodVariableAccess.loadThis();
    if (!instrumentedMethod.getReturnType().represents(void.class)) {
        implementation = new StackManipulation.Compound(
                initialization,
                FieldAccess.forField(fieldDescription).read(),
                assigner.assign(fieldDescription.getType(), instrumentedMethod.getReturnType(), typing),
                MethodReturn.of(instrumentedMethod.getReturnType())
        );
    } else if (instrumentedMethod.getReturnType().represents(void.class) && instrumentedMethod.getParameters().size() == 1) {
        if (fieldDescription.isFinal() && instrumentedMethod.isMethod()) {
            throw new IllegalStateException("Cannot set final field " + fieldDescription + " from " + instrumentedMethod);
        }
        implementation = new StackManipulation.Compound(
                initialization,
                MethodVariableAccess.load(instrumentedMethod.getParameters().get(0)),
                assigner.assign(instrumentedMethod.getParameters().get(0).getType(), fieldDescription.getType(), typing),
                FieldAccess.forField(fieldDescription).write(),
                MethodReturn.VOID
        );
    } else {
        throw new IllegalArgumentException("Method " + instrumentedMethod + " is no bean accessor");
    }
    if (!implementation.isValid()) {
        throw new IllegalStateException("Cannot set or get value of " + instrumentedMethod + " using " + fieldDescription);
    }
    return new Size(implementation.apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example 14
Source File: DoParse.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a field. This will be all the
 * elements for a repeated field.
 *
 * @param info description of the field to set.
 * @param beforeReadField jump target for before reading a field, used once this field is
 *     completed being set.
 * @param locals the method local variables
 * @param fieldsByName the instance fields
 */
private StackManipulation setFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  if (info.isMapField()) {
    return setMapFieldValue(info, beforeReadField, locals, fieldsByName);
  } else {
    final StackManipulation setConcreteValue = invoke(info.setValueMethod());
    final StackManipulation setSingleValue;
    if (info.valueJavaType() == JavaType.MESSAGE) {
      setSingleValue =
          new StackManipulation.Compound(
              TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
    } else if (info.valueType() == Type.ENUM && !info.isRepeated()) {
      // For non-repeated enums, we treat unknown as the default value.
      setSingleValue =
          new StackManipulation.Compound(ParseSupport_mapUnknownEnumValue, setConcreteValue);
    } else {
      setSingleValue = setConcreteValue;
    }
    if (info.descriptor().isRepeated()) {
      return setRepeatedFieldValue(info, beforeReadField, locals, fieldsByName, setSingleValue);
    } else {
      // Set a singular value, e.g.,
      // builder.setFoo(readValue());
      return new StackManipulation.Compound(
          locals.load(LocalVariable.builder),
          locals.load(LocalVariable.parser),
          readValue(info, fieldsByName, locals),
          setSingleValue,
          Removal.SINGLE,
          new Goto(beforeReadField));
    }
  }
}
 
Example 15
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected Resolved doResolve(StackManipulation access, TypeDescription.Generic type, Assigner assigner, Assigner.Typing typing) {
    StackManipulation stackManipulation = assigner.assign(type, typeDescription.asGenericType(), typing);
    if (!stackManipulation.isValid()) {
        throw new IllegalStateException("Cannot assign " + type + " to " + typeDescription);
    }
    return new Resolved.Simple(new StackManipulation.Compound(access, stackManipulation), typeDescription);
}
 
Example 16
Source File: MethodInvocation.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation special(TypeDescription invocationTarget) {
    return new StackManipulation.Compound(invocation.special(invocationTarget), TypeCasting.to(targetType));
}
 
Example 17
Source File: DoParse.java    From curiostack with MIT License 4 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a map field.
 *
 * <p>Roughly equivalent to:
 *
 * <pre>{@code
 * ParseSupport.parseObjectStart(parser);
 * while (!ParseSupport.checkObjectEnd(parser.currentToken())) {
 *   builder.putFoo(readKey(), readValue());
 * }
 * }</pre>
 */
private StackManipulation setMapFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  final StackManipulation setConcreteValue = invoke(info.setValueMethod());
  final StackManipulation setMapEntry;
  if (info.valueJavaType() == JavaType.MESSAGE) {
    setMapEntry =
        new StackManipulation.Compound(
            TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
  } else {
    setMapEntry = setConcreteValue;
  }
  Label mapStart = new Label();
  Label afterSet = new Label();

  StackManipulation.Compound beforeReadKey =
      new StackManipulation.Compound(
          locals.load(LocalVariable.parser),
          ParseSupport_parseObjectStart,
          new SetJumpTargetLabel(mapStart),
          locals.load(LocalVariable.parser),
          Parser_currentToken,
          ParseSupport_checkObjectEnd,
          new IfTrue(beforeReadField));

  StackManipulation.Compound setValueAndPrepareForNext =
      new StackManipulation.Compound(
          setMapEntry,
          Removal.SINGLE,
          new SetJumpTargetLabel(afterSet),
          locals.load(LocalVariable.parser),
          Parser_nextToken,
          Removal.SINGLE,
          new Goto(mapStart));

  if (info.valueType() == Type.ENUM) {
    // We special-case enum since we may need to skip unknown values.
    final LocalVariable keyVar;
    switch (info.mapKeyField().valueJavaType()) {
      case INT:
        keyVar = LocalVariable.intMapKey;
        break;
      case LONG:
        keyVar = LocalVariable.longMapKey;
        break;
      case BOOLEAN:
        keyVar = LocalVariable.boolMapKey;
        break;
      case STRING:
        keyVar = LocalVariable.stringMapKey;
        break;
      default:
        throw new IllegalArgumentException("Invalid map key type");
    }

    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.store(keyVar),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        locals.store(LocalVariable.intvalue),
        locals.load(LocalVariable.intvalue),
        IntegerConstant.forValue(-1),
        new IfEqual(int.class, afterSet),
        locals.load(LocalVariable.builder),
        locals.load(keyVar),
        locals.load(LocalVariable.intvalue),
        setValueAndPrepareForNext);
  } else {
    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.builder),
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        setValueAndPrepareForNext);
  }
}
 
Example 18
Source File: FieldAccess.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation read() {
    return new StackManipulation.Compound(defined.read(), TypeCasting.to(targetType));
}
 
Example 19
Source File: DoWrite.java    From curiostack with MIT License 4 votes vote down vote up
private StackManipulation printValue(
    Map<String, FieldDescription> fieldsByName, ProtoFieldInfo info) {
  boolean repeated = !info.isMapField() && info.isRepeated();
  switch (info.valueType()) {
    case INT32:
    case SINT32:
    case SFIXED32:
      return repeated
          ? SerializeSupport_printRepeatedSignedInt32
          : SerializeSupport_printSignedInt32;
    case INT64:
    case SINT64:
    case SFIXED64:
      return repeated
          ? SerializeSupport_printRepeatedSignedInt64
          : SerializeSupport_printSignedInt64;
    case BOOL:
      return repeated ? SerializeSupport_printRepeatedBool : SerializeSupport_printBool;
    case FLOAT:
      return repeated ? SerializeSupport_printRepeatedFloat : SerializeSupport_printFloat;
    case DOUBLE:
      return repeated ? SerializeSupport_printRepeatedDouble : SerializeSupport_printDouble;
    case UINT32:
    case FIXED32:
      return repeated
          ? SerializeSupport_printRepeatedUnsignedInt32
          : SerializeSupport_printUnsignedInt32;
    case UINT64:
    case FIXED64:
      return repeated
          ? SerializeSupport_printRepeatedUnsignedInt64
          : SerializeSupport_printUnsignedInt64;
    case STRING:
      return repeated ? SerializeSupport_printRepeatedString : SerializeSupport_printString;
    case BYTES:
      return repeated ? SerializeSupport_printRepeatedBytes : SerializeSupport_printBytes;
    case ENUM:
      // Special-case google.protobuf.NullValue (it's an Enum).
      if (info.valueField().descriptor().getEnumType().equals(NullValue.getDescriptor())) {
        return repeated ? SerializeSupport_printRepeatedNull : SerializeSupport_printNull;
      } else {
        if (printingEnumsAsInts) {
          return repeated
              ? SerializeSupport_printRepeatedUnsignedInt32
              : SerializeSupport_printUnsignedInt32;
        } else {
          return new StackManipulation.Compound(
              CodeGenUtil.getEnumDescriptor(info),
              repeated ? SerializeSupport_printRepeatedEnum : SerializeSupport_printEnum);
        }
      }
    case MESSAGE:
    case GROUP:
      return new StackManipulation.Compound(
          FieldAccess.forField(
                  fieldsByName.get(
                      CodeGenUtil.fieldNameForNestedMarshaller(
                          info.valueField().descriptor().getMessageType())))
              .read(),
          repeated ? SerializeSupport_printRepeatedMessage : SerializeSupport_printMessage);
    default:
      throw new IllegalStateException("Unknown field type.");
  }
}
 
Example 20
Source File: CopierImplementation.java    From unsafe with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static StackManipulation toStackManipulation(List<StackManipulation> stack) {
  return new StackManipulation.Compound(stack.toArray(new StackManipulation[stack.size()]));
}