@Override public boolean matches(TypeDescription targetInterface) { if (ElementMatchers.declaresMethod(named(targetMethod.getName()) .and(returns(targetMethod.getReturnType().asErasure())) .and(takesArguments(targetMethod.getParameters().asTypeList().asErasures()))) .matches(targetInterface)) { return true; } else { for (TypeDescription typeDescription : targetInterface.getInterfaces().asErasures()) { if (matches(typeDescription)) { return true; } } } return false; } }
public InlineBytecodeGenerator(Instrumentation instrumentation, WeakConcurrentMap<Object, MockMethodInterceptor> mocks) { preload(); this.instrumentation = instrumentation; byteBuddy = new ByteBuddy() .with(TypeValidation.DISABLED) .with(Implementation.Context.Disabled.Factory.INSTANCE) .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE); mocked = new WeakConcurrentSet<Class<?>>(WeakConcurrentSet.Cleaner.INLINE); subclassEngine = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(withDefaultConfiguration() .withBinders(of(MockMethodAdvice.Identifier.class, identifier)) .to(MockMethodAdvice.ForReadObject.class), isAbstract().or(isNative()).or(isToString())), false); mockTransformer = new AsmVisitorWrapper.ForDeclaredMethods() .method(isVirtual() .and(not(isBridge().or(isHashCode()).or(isEquals()).or(isDefaultFinalizer()))) .and(not(isDeclaredBy(nameStartsWith("java.")).<MethodDescription>and(isPackagePrivate()))), Advice.withCustomMapping() .bind(MockMethodAdvice.Identifier.class, identifier)
Class<? extends T> proxied = builder.method(ElementMatchers.isDeclaredBy( Introspectior.getTypeDescription(RLiveObject.class)) .and(ElementMatchers.isGetter().or(ElementMatchers.isSetter()) .or(ElementMatchers.named("isPhantom")) .or(ElementMatchers.named("delete")))) .intercept(MethodDelegation.withDefaultConfiguration() .withBinders(FieldProxy.Binder .install(LiveObjectInterceptor.Getter.class, .implement(RLiveObject.class) .method(ElementMatchers.isAnnotatedWith(RFieldAccessor.class) .and(ElementMatchers.named("get") .or(ElementMatchers.named("set")))) .intercept(MethodDelegation.to(FieldAccessorInterceptor.class)) .method(ElementMatchers.isDeclaredBy(RObject.class) .or(ElementMatchers.isDeclaredBy(RObjectAsync.class))) .intercept(MethodDelegation.to(RObjectInterceptor.class)) .implement(RObject.class) .or(ElementMatchers.isDeclaredBy(RExpirableAsync.class))) .or(ElementMatchers.isDeclaredBy(ConcurrentMap.class)) .or(ElementMatchers.isDeclaredBy(RMapAsync.class)) .or(ElementMatchers.isDeclaredBy(RMap.class))) .and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RLiveObject.class))) .and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RExpirable.class))) .and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RExpirableAsync.class)))
/** * {@inheritDoc} */ public DynamicType make(String auxiliaryTypeName, ClassFileVersion classFileVersion, MethodAccessorFactory methodAccessorFactory) { LinkedHashMap<String, TypeDescription> parameterFields = extractFields(sourceMethod); DynamicType.Builder<?> builder = new ByteBuddy(classFileVersion) .with(TypeValidation.DISABLED) .subclass(forwardingType, ConstructorStrategy.Default.NO_CONSTRUCTORS) .name(auxiliaryTypeName) .modifiers(DEFAULT_TYPE_MODIFIER) .implement(serializableProxy ? new Class<?>[]{Serializable.class} : new Class<?>[0]) .method(ElementMatchers.<MethodDescription>isAbstract().and(isDeclaredBy(forwardingType))) .intercept(new MethodCall(sourceMethod, assigner)) .defineConstructor().withParameters(parameterFields.values()) .intercept(ConstructorCall.INSTANCE); for (Map.Entry<String, TypeDescription> field : parameterFields.entrySet()) { builder = builder.defineField(field.getKey(), field.getValue(), Visibility.PRIVATE); } return builder.make(); }
public Factory run() { try { return new Factory.ForJava9CapableVm(new ByteBuddy() .with(TypeValidation.DISABLED) .subclass(ExecutingTransformer.class) .name(ExecutingTransformer.class.getName() + "$ByteBuddy$ModuleSupport") .method(named("transform").and(takesArgument(0, JavaType.MODULE.load()))) .intercept(MethodCall.invoke(ExecutingTransformer.class.getDeclaredMethod("transform", Object.class, ClassLoader.class, ProtectionDomain.class, byte[].class)).onSuper().withAllArguments()) .make() .load(ExecutingTransformer.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER_PERSISTENT.with(ExecutingTransformer.class.getProtectionDomain()))
/** * Only matches the {@link Object#toString()} method, also if it was overridden. * * @param <T> The type of the matched object. * @return A matcher that only matches the {@link Object#toString()} method. */ public static <T extends MethodDescription> ElementMatcher.Junction<T> isHashCode() { return named("hashCode").and(takesArguments(0)).and(returns(int.class)); }
public <T> Class<? extends T> createStageClass( Class<T> stageClass ) { return new ByteBuddy() .subclass( stageClass, ConstructorStrategy.Default.IMITATE_SUPER_CLASS_OPENING ) .implement( StageInterceptorInternal.class ) .defineField( INTERCEPTOR_FIELD_NAME, StepInterceptor.class ) .method( named(SETTER_NAME) ) .intercept( MethodDelegation.withDefaultConfiguration() .withBinders( FieldProxy.Binder.install( StepInterceptorGetterSetter.class )) .to(new StepInterceptorSetter() )) .method( not( named( SETTER_NAME ) .or(ElementMatchers.isDeclaredBy(Object.class)))) .intercept( MethodDelegation.withDefaultConfiguration() .withBinders(FieldProxy.Binder.install( StepInterceptorGetterSetter.class )) .to( new ByteBuddyMethodInterceptor() )) .make() .load( getClassLoader( stageClass ), getClassLoadingStrategy( stageClass ) ) .getLoaded(); }
/** * Creates a matcher where only overridable or declared methods are matched unless those are ignored. Methods that * are declared by the target type are only matched if they are not ignored. Declared methods that are not found on the * target type are always matched. * * @param ignoredMethods A method matcher that matches any ignored method. * @param originalType The original type of the instrumentation before adding any user methods. * @return A latent method matcher that identifies any method to instrument for a rebasement or redefinition. */ protected static LatentMatcher<MethodDescription> of(LatentMatcher<? super MethodDescription> ignoredMethods, TypeDescription originalType) { ElementMatcher.Junction<MethodDescription> predefinedMethodSignatures = none(); for (MethodDescription methodDescription : originalType.getDeclaredMethods()) { ElementMatcher.Junction<MethodDescription> signature = methodDescription.isConstructor() ? isConstructor() : ElementMatchers.<MethodDescription>named(methodDescription.getName()); signature = signature.and(returns(methodDescription.getReturnType().asErasure())); signature = signature.and(takesArguments(methodDescription.getParameters().asTypeList().asErasures())); predefinedMethodSignatures = predefinedMethodSignatures.or(signature); } return new InliningImplementationMatcher(ignoredMethods, predefinedMethodSignatures); }
private static synchronized void agent(final boolean shouldRedefine, final Instrumentation instrumentation) { BufferAlignmentAgent.instrumentation = instrumentation; // all Int methods, and all String method other than // XXXStringWithoutLengthXXX or getStringXXX(int, int) final Junction<MethodDescription> intVerifierMatcher = nameContains("Int") .or(nameMatches(".*String[^W].*").and(not(ElementMatchers.takesArguments(int.class, int.class)))); alignmentTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED)) .with(LISTENER) .disableClassFormatChanges() .with(shouldRedefine ? AgentBuilder.RedefinitionStrategy.RETRANSFORMATION : AgentBuilder.RedefinitionStrategy.DISABLED) .type(isSubTypeOf(DirectBuffer.class).and(not(isInterface()))) .transform((builder, typeDescription, classLoader, module) -> builder .visit(to(LongVerifier.class).on(nameContains("Long"))) .visit(to(DoubleVerifier.class).on(nameContains("Double"))) .visit(to(IntVerifier.class).on(intVerifierMatcher)) .visit(to(FloatVerifier.class).on(nameContains("Float"))) .visit(to(ShortVerifier.class).on(nameContains("Short"))) .visit(to(CharVerifier.class).on(nameContains("Char")))) .installOn(instrumentation); }
static Object create(final Object bean, DecoratorExecutor executor) { try { Object proxy = new ByteBuddy() .subclass(bean.getClass()) .implement(EnhancedProxy.class) .defineField("bean", bean.getClass(), Modifier.PRIVATE) .defineField("executor", DecoratorExecutor.class, Modifier.PRIVATE) .method(isEquals()) .intercept(to(EqualsInterceptor.class)) .method(isAnnotatedWith(nameStartsWith("cucumber.api"))) .intercept(to(CucumberInterceptor.class)) .method(not(isEquals().or(isClone()).or(isAnnotatedWith(nameStartsWith("cucumber.api"))))) .intercept(toField("bean")) .make() .load(bean.getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .newInstance(); ReflectionUtils.injectValue(proxy, "bean", bean); ReflectionUtils.injectValue(proxy, "executor", executor); return proxy; } catch (Exception e) { throw new JpaUnitException("Failed to create proxy for " + bean, e); } } }
private static AgentBuilder createAgentBuilder(AutoEvictingCachingBinaryLocator binaryLocator) { final ByteBuddy byteBuddy = new ByteBuddy() .with(TypeValidation.of(corePlugin.isDebugInstrumentation())) .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE); return new AgentBuilder.Default(byteBuddy) .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION) .with(getListener()) .with(binaryLocator) .ignore(any(), timed("classloader", "reflection", isReflectionClassLoader())) .or(any(), timed("classloader", "groovy-call-site", classLoaderWithName("org.codehaus.groovy.runtime.callsite.CallSiteClassLoader"))) .or(any(), new IsIgnoredClassLoaderElementMatcher()) .or(timed("type", "global-exclude", nameStartsWith("org.aspectj.") .or(nameStartsWith("org.groovy.")) .or(nameStartsWith("com.p6spy.")) .or(nameStartsWith("net.bytebuddy.")) .or(nameStartsWith("org.slf4j.").and(not(nameStartsWith("org.slf4j.impl.")))) .or(nameContains("javassist")) .or(nameContains(".asm.")) .or(nameStartsWith("org.stagemonitor") .and(not(nameContains("Test") .or(nameContains("benchmark")) .or(nameStartsWith("org.stagemonitor.demo"))))) )) .disableClassFormatChanges(); }
/** * {@inheritDoc} */ public Compiled compile(TypeDescription instrumentedType) { MethodList<?> targets = new MethodList.Explicit<MethodDescription>(CompoundList.<MethodDescription>of( instrumentedType.getDeclaredMethods().filter(isStatic().or(isPrivate())), methodGraphCompiler.compile(instrumentedType).listNodes().asMethodList()) ).filter(named(name).and(takesArguments(0)).and(not(returns(isPrimitive().or(isArray()))))); if (targets.size() != 1) { throw new IllegalStateException(instrumentedType + " does not define method without arguments with name " + name + ": " + targets); } else if (!targets.getOnly().getReturnType().asErasure().isVisibleTo(instrumentedType)) { throw new IllegalStateException(targets.getOnly() + " is not visible to " + instrumentedType); } else { MethodList<?> candidates = methodGraphCompiler.compile(targets.getOnly().getReturnType(), instrumentedType) .listNodes() .asMethodList() .filter(matcher); List<MethodDelegationBinder.Record> records = new ArrayList<MethodDelegationBinder.Record>(candidates.size()); MethodDelegationBinder methodDelegationBinder = TargetMethodAnnotationDrivenBinder.of(parameterBinders); for (MethodDescription candidate : candidates) { records.add(methodDelegationBinder.compile(candidate)); } return new Compiled.ForMethodReturn(targets.get(0), records); } }
MethodList<?> candidates; if (opcode == Opcodes.INVOKESPECIAL && internalName.equals(MethodDescription.CONSTRUCTOR_INTERNAL_NAME)) { candidates = resolution.resolve().getDeclaredMethods().filter(strict ? ElementMatchers.<MethodDescription>isConstructor().and(hasDescriptor(descriptor)) : ElementMatchers.<MethodDescription>failSafe(isConstructor().and(hasDescriptor(descriptor)))); } else if (opcode == Opcodes.INVOKESTATIC || opcode == Opcodes.INVOKESPECIAL) { candidates = resolution.resolve().getDeclaredMethods().filter(strict ? ElementMatchers.<MethodDescription>named(internalName).and(hasDescriptor(descriptor)) : ElementMatchers.<MethodDescription>failSafe(named(internalName).and(hasDescriptor(descriptor)))); } else { // Invokevirtual and invokeinterface can represent a private, non-static method from Java 11. candidates = resolution.resolve().getDeclaredMethods().filter(strict ? ElementMatchers.<MethodDescription>isPrivate().and(not(isStatic())).and(named(internalName).and(hasDescriptor(descriptor))) : ElementMatchers.<MethodDescription>failSafe(isPrivate().<MethodDescription>and(not(isStatic())).and(named(internalName).and(hasDescriptor(descriptor))))); if (candidates.isEmpty()) { candidates = methodGraphCompiler.compile(resolution.resolve(), instrumentedType).listNodes().asMethodList().filter(strict ? ElementMatchers.<MethodDescription>named(internalName).and(hasDescriptor(descriptor)) : ElementMatchers.<MethodDescription>failSafe(named(internalName).and(hasDescriptor(descriptor)))); if (binding.isBound()) { stackSizeBuffer = Math.max(stackSizeBuffer, binding.make( candidates.getOnly().isStatic() || candidates.getOnly().isConstructor() ? candidates.getOnly().getParameters().asTypeList() : new TypeList.Generic.Explicit(CompoundList.of(resolution.resolve(), candidates.getOnly().getParameters().asTypeList())), candidates.getOnly().isConstructor()
private <E extends EntityContext<?, ?>> E createEntityMappingContext(Class<? extends E> entityContextImplType, Class<? extends PropertyContext<?, ?>> propertyContextImplType) { // ByteBuddyState#resolveClassLoadingStrategy static method is an Hibernate ORM internal, // please remove its use here as soon the issue HHH-13014 has been closed. // url https://hibernate.atlassian.net/browse/HHH-13014. Class<? extends E> entityContextType = new ByteBuddy() .subclass( entityContextImplType ) .method( filterEntityMethod().or( filterPropertyMethod() ) ) .intercept( to( new EntityOrPropertyMethodInterceptor( entityContextImplType, propertyContextImplType ) ) ) .make().load( entityContextImplType.getClassLoader(), resolveClassLoadingStrategy( entityContextImplType ) ).getLoaded(); try { return entityContextType.getConstructor( ConfigurationContext.class ).newInstance( this ); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw log.cannotCreateEntityContextProxy( entityContextType, e ); } }
String lambdaClassName = targetType.getName() + LAMBDA_TYPE_INFIX + LAMBDA_NAME_COUNTER.incrementAndGet(); DynamicType.Builder<?> builder = byteBuddy .subclass(factoryMethod.getReturnType(), ConstructorStrategy.Default.NO_CONSTRUCTORS) .modifiers(TypeManifestation.FINAL, Visibility.PUBLIC) .implement(markerInterfaces) .name(lambdaClassName) .defineConstructor(Visibility.PUBLIC) .withParameters(factoryMethod.getParameterTypes()) .intercept(ConstructorImplementation.INSTANCE) .method(named(lambdaMethodName) .and(takesArguments(lambdaMethod.getParameterTypes())) .and(returns(lambdaMethod.getReturnType()))) .intercept(new LambdaMethodImplementation(targetMethod, specializedLambdaMethod)); int index = 0; for (TypeDescription capturedType : factoryMethod.getParameterTypes()) { targetMethod, JavaConstant.MethodType.ofLoaded(specializedLambdaMethodType))); } else if (factoryMethod.getReturnType().isAssignableTo(Serializable.class)) { builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE) .withParameters(ObjectInputStream.class) .throwing(NotSerializableException.class) .intercept(ExceptionMethod.throwing(NotSerializableException.class, "Non-serializable lambda")) .defineMethod("writeObject", void.class, Visibility.PRIVATE) .withParameters(ObjectOutputStream.class) .throwing(NotSerializableException.class)
TypeDescription instrumentedType = instrumentedMethod.getDeclaringType().asErasure(); MethodDescription enumConstructor = instrumentedType.getDeclaredMethods() .filter(isConstructor().and(takesArguments(String.class, int.class))) .getOnly(); int ordinal = 0; List<FieldDescription> enumerationFields = new ArrayList<FieldDescription>(values.size()); for (String value : values) { FieldDescription fieldDescription = instrumentedType.getDeclaredFields().filter(named(value)).getOnly(); stackManipulation = new StackManipulation.Compound(stackManipulation, TypeCreation.of(instrumentedType), ArrayFactory.forType(instrumentedType.asGenericType()).withValues(fieldGetters), FieldAccess.forField(instrumentedType.getDeclaredFields().filter(named(ENUM_VALUES)).getOnly()).write() ); return new Size(stackManipulation.apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
/** * Matches any Java bean getter method. * * @param <T> The type of the matched object. * @return A matcher that matches any getter method. */ public static <T extends MethodDescription> ElementMatcher.Junction<T> isGetter() { return takesArguments(0).and(not(returns(TypeDescription.VOID))).and(nameStartsWith("get").or(nameStartsWith("is").and(returnsGeneric(anyOf(boolean.class, Boolean.class))))); }
/** * {@inheritDoc} */ public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) { TypeDescription proxyType = implementationContext.register(new TypeProxy(proxiedType, implementationTarget, InvocationFactory.Default.SUPER_METHOD, ignoreFinalizer, serializableProxy)); return new Compound( MethodInvocation.invoke(proxyType.getDeclaredMethods().filter(named(REFLECTION_METHOD).and(takesArguments(0))).getOnly()), Duplication.SINGLE, MethodVariableAccess.loadThis(), FieldAccess.forField(proxyType.getDeclaredFields().filter((named(INSTANCE_FIELD))).getOnly()).write() ).apply(methodVisitor, implementationContext); } }
ElementMatcher<? super MethodDescription> relevanceMatcher = (ElementMatcher<? super MethodDescription>) not(anyOf(implementations.keySet())) .and(returns(isVisibleTo(instrumentedType))) .and(hasParameters(whereNone(hasType(not(isVisibleTo(instrumentedType)))))) .and(ignoredMethods.resolve(instrumentedType)); List<MethodDescription> methods = new ArrayList<MethodDescription>(); for (MethodGraph.Node node : methodGraph.listNodes()) { && methodDescription.isPublic() && !(methodDescription.isAbstract() || methodDescription.isFinal()) && methodDescription.getDeclaringType().isPackagePrivate()) { instrumentedType.getDeclaredMethods().filter(not(isVirtual()).and(relevanceMatcher)), new MethodDescription.Latent.TypeInitializer(instrumentedType))) { for (Entry entry : entries) {
DynamicType.Builder<T> builder = byteBuddy.subclass(features.mockedType) .name(name) .ignoreAlso(isGroovyMethod()) .annotateType(features.stripAnnotations ? new Annotation[0] : features.mockedType.getAnnotations()) .implement(new ArrayList<Type>(features.interfaces)) .method(matcher) .intercept(dispatcher) .transform(withModifiers(SynchronizationState.PLAIN)) .attribute(features.stripAnnotations ? MethodAttributeAppender.NoOp.INSTANCE : INCLUDING_RECEIVER) .method(isHashCode()) .intercept(hashCode) .method(isEquals()) .intercept(equals) .serialVersionUid(42L) .defineField("mockitoInterceptor", MockMethodInterceptor.class, PRIVATE) .implement(MockAccess.class) builder = builder.ignoreAlso(isPackagePrivate() .or(returns(isPackagePrivate())) .or(hasParameters(whereAny(hasType(isPackagePrivate()))))); return builder.make()