net.bytebuddy.jar.asm.MethodVisitor Java Examples

The following examples show how to use net.bytebuddy.jar.asm.MethodVisitor. 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: 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 #2
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 #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: AbstractDelegatingAppender.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 List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>();
    //contains the initial bytecode needed for all cases
    stackManipulations.add(createLocalVar());

    // Ok; minor optimization, 3 or fewer fields, just do IFs; over that, use switch
    switch (propsSize) {
        case 1:
            stackManipulations.add(single());
            break;
        case 2:
        case 3:
            stackManipulations.add(usingIf());
            break;
        default:
            stackManipulations.add(usingSwitch());
    }

    final StackManipulation.Compound compound = new StackManipulation.Compound(stackManipulations);
    final StackManipulation.Size operandStackSize = compound.apply(methodVisitor, implementationContext);
    return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);
}
 
Example #5
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 #6
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 #7
Source File: GenerateIllegalPropertyCountExceptionStackManipulation.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 MethodDescription.InDefinedShape messageConstructor =
            new ForLoadedType(IllegalArgumentException.class)
                    .getDeclaredMethods()
                    .filter(isConstructor())
                    .filter(takesArguments(1))
                    .filter(takesArgument(0, String.class))
                    .getOnly();

    final StackManipulation.Compound delegate = new StackManipulation.Compound(
            new ConstructorCallStackManipulation.KnownInDefinedShapeOfExistingType(
                    messageConstructor,
                    new TextConstant("Invalid field index (valid; 0 <= n < "+propertyCount+"): ")
            ),
            Throw.INSTANCE
    );

    return delegate.apply(methodVisitor, implementationContext);
}
 
Example #8
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 #9
Source File: SimpleExceptionHandler.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
private StackManipulation preTrigger(final Label startTryBlock,
                                     final Label endTryBlock,
                                     final Label startCatchBlock) {
    return new StackManipulation() {
        @Override
        public boolean isValid() {
            return true;
        }

        @Override
        public Size apply(MethodVisitor mv, Implementation.Context ic) {
            final String name = exceptionType.getName();
            mv.visitTryCatchBlock(startTryBlock, endTryBlock, startCatchBlock, name.replace(".", "/"));
            mv.visitLabel(startTryBlock);
            return new Size(0,0);
        }
    };
}
 
Example #10
Source File: SimpleExceptionHandler.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
private StackManipulation postTrigger(final Label endTryBlock, final Label startCatchBlock) {
    return new StackManipulation() {
        @Override
        public boolean isValid() {
            return true;
        }

        @Override
        public Size apply(MethodVisitor mv, Implementation.Context ic) {
            mv.visitLabel(endTryBlock);
            // and then do catch block
            mv.visitLabel(startCatchBlock);

            //although this StackManipulation does not alter the stack on it's own
            //however when an exception is caught
            //the exception will be on the top of the stack (being placed there by the JVM)
            //we need to increment the stack size
            return new Size(1, 0);
        }
    };
}
 
Example #11
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 #12
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 #13
Source File: MethodVariableStore.java    From unsafe with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
  switch (variableIndex) {
    case 0:
      methodVisitor.visitInsn(storeOpcode + storeOpcodeShortcutOffset);
      break;
    case 1:
      methodVisitor.visitInsn(storeOpcode + storeOpcodeShortcutOffset + 1);
      break;
    case 2:
      methodVisitor.visitInsn(storeOpcode + storeOpcodeShortcutOffset + 2);
      break;
    case 3:
      methodVisitor.visitInsn(storeOpcode + storeOpcodeShortcutOffset + 3);
      break;
    default:
      methodVisitor.visitVarInsn(storeOpcode, variableIndex);
      break;
  }
  return size;
}
 
Example #14
Source File: ReactorDebugClassVisitor.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String currentMethod, String descriptor, String signature, String[] exceptions) {
	MethodVisitor visitor = super.visitMethod(access, currentMethod, descriptor, signature, exceptions);

	if (currentClassName.contains("CGLIB$$")) {
		return visitor;
	}

	String returnType = Type.getReturnType(descriptor).getInternalName();
	switch (returnType) {
		// Handle every core publisher type.
		// Note that classes like `GroupedFlux` or `ConnectableFlux` are not included,
		// because they don't have a type-preserving "checkpoint" method
		case "reactor/core/publisher/Flux":
		case "reactor/core/publisher/Mono":
		case "reactor/core/publisher/ParallelFlux":
			visitor = new ReturnHandlingMethodVisitor(visitor, returnType, currentClassName, currentMethod, currentSource,
					changed);
	}

	return new CallSiteInfoAddingMethodVisitor(visitor, currentClassName, currentMethod, currentSource, changed);
}
 
Example #15
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 #16
Source File: PropertyAccessorCollector.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(loadLocalVar()); // load local for cast bean

    final AnnotatedMember member = prop.getMember();

    operations.add(invocationOperation(member, beanClassDescription));
    operations.add(methodReturn);

    final StackManipulation.Compound compound = new StackManipulation.Compound(operations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example #17
Source File: MixinClassVisitor.java    From kanela with Apache License 2.0 5 votes vote down vote up
@Override
public void visitEnd() {
    Try.run(() -> {
        // By default, ClassReader will try to use the System ClassLoader to load the classes but we need to make sure
        // that all classes are loaded with Kanela's Instrumentation ClassLoader (which some times might be the
        // System ClassLoader and some others will be an Attach ClassLoader).
        val classLoader = InstrumentationClassPath.last()
                .map(InstrumentationClassPath::getClassLoader)
                .getOrElse(() -> Thread.currentThread().getContextClassLoader());

        val mixinClassFileName = mixin.getMixinClass().getName().replace('.', '/') + ".class";

        try (val classStream = classLoader.getResourceAsStream(mixinClassFileName)) {
            val cr = new ClassReader(classStream);
            val cn = new ClassNode();
            cr.accept(cn, ClassReader.EXPAND_FRAMES);

            cn.fields.forEach(fieldNode -> fieldNode.accept(this));
            cn.methods.stream().filter(isConstructor()).forEach(mn -> {
                String[] exceptions = new String[mn.exceptions.size()];
                MethodVisitor mv = cv.visitMethod(mn.access, mn.name, mn.desc, mn.signature, exceptions);
                mn.accept(new MethodRemapper(mv, new SimpleRemapper(cn.name, type.getInternalName())));
            });
        }
        super.visitEnd();
    });
}
 
Example #18
Source File: MixinClassVisitor.java    From kanela with Apache License 2.0 5 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    if (name.equals(ConstructorDescriptor) && mixin.getInitializerMethod().isDefined()) {
        val mv = super.visitMethod(access, name, desc, signature, exceptions);
        return new MixinInitializer(mv, access, name, desc, type, mixin);
    }
    return super.visitMethod(access, name, desc, signature, exceptions);
}
 
Example #19
Source File: SetSerializedFieldName.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public Size apply(
    MethodVisitor methodVisitor,
    Context implementationContext,
    MethodDescription instrumentedMethod) {
  Map<String, FieldDescription> fieldsByName = CodeGenUtil.fieldsByName(implementationContext);
  StackManipulation.Size operandStackSize =
      new StackManipulation.Compound(
              new TextConstant(unserializedFieldValue),
              SerializeSupport_serializeString,
              FieldAccess.forField(fieldsByName.get(fieldName)).write())
          .apply(methodVisitor, implementationContext);
  return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #20
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 #21
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 #22
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 #23
Source File: ConstructorCallStackManipulation.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
@Override
public StackManipulation.Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    final TypeDescription typeDescription = determineTypeDescription(implementationContext);

    final List<StackManipulation> stackManipulations = new ArrayList<>();
    stackManipulations.add(TypeCreation.of(typeDescription)); //new
    stackManipulations.add(Duplication.of(typeDescription)); //dup
    stackManipulations.addAll(constructorArgumentLoadingOperations); //load any needed variables
    stackManipulations.add(invoke(determineConstructor(typeDescription))); //invokespecial

    final StackManipulation.Compound delegate = new StackManipulation.Compound(stackManipulations);
    return delegate.apply(methodVisitor, implementationContext);
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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
	);
}