net.bytebuddy.utility.JavaModule Java Examples

The following examples show how to use net.bytebuddy.utility.JavaModule. 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: AllowancesByteBuddyTransformer.java    From BlockHound with Apache License 2.0 6 votes vote down vote up
@Override
public DynamicType.Builder<?> transform(
        DynamicType.Builder<?> builder,
        TypeDescription typeDescription,
        ClassLoader classLoader,
        JavaModule module
) {
    Map<String, Boolean> methods = allowances.get(typeDescription.getName());

    if (methods == null) {
        return builder;
    }

    AsmVisitorWrapper advice = Advice
            .withCustomMapping()
            .bind(new AllowedArgument.Factory(methods))
            .to(AllowAdvice.class)
            .on(method -> methods.containsKey(method.getInternalName()));

    return builder.visit(advice);
}
 
Example #2
Source File: AgentBuilderListenerTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadEdgeAddingListenerDuplexCanRead() throws Exception {
    Instrumentation instrumentation = mock(Instrumentation.class);
    JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
    TypeDescription typeDescription = mock(TypeDescription.class);
    PackageDescription packageDescription = mock(PackageDescription.class);
    when(typeDescription.getPackage()).thenReturn(packageDescription);
    when(source.isNamed()).thenReturn(true);
    when(source.canRead(target)).thenReturn(true);
    when(source.isOpened(packageDescription, target)).thenReturn(true);
    when(target.canRead(source)).thenReturn(true);
    AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, true, Collections.singleton(target));
    listener.onTransformation(typeDescription, mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
    verify(source).isNamed();
    verify(source).canRead(target);
    verify(source).isOpened(packageDescription, target);
    verifyNoMoreInteractions(source);
    verify(target).canRead(source);
    verifyNoMoreInteractions(target);
}
 
Example #3
Source File: SkyWalkingAgent.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public DynamicType.Builder<?> transform(final DynamicType.Builder<?> builder,
                                        final TypeDescription typeDescription,
                                        final ClassLoader classLoader,
                                        final JavaModule module) {
    List<AbstractClassEnhancePluginDefine> pluginDefines = pluginFinder.find(typeDescription);
    if (pluginDefines.size() > 0) {
        DynamicType.Builder<?> newBuilder = builder;
        EnhanceContext context = new EnhanceContext();
        for (AbstractClassEnhancePluginDefine define : pluginDefines) {
            DynamicType.Builder<?> possibleNewBuilder = define.define(
                typeDescription, newBuilder, classLoader, context);
            if (possibleNewBuilder != null) {
                newBuilder = possibleNewBuilder;
            }
        }
        if (context.isEnhanced()) {
            logger.debug("Finish the prepare stage for {}.", typeDescription.getName());
        }

        return newBuilder;
    }

    logger.debug("Matched class {}, but ignore by finding mechanism.", typeDescription.getTypeName());
    return builder;
}
 
Example #4
Source File: AgentBuilderListenerTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadEdgeAddingListenerNamedCannotRead() throws Exception {
    Instrumentation instrumentation = mock(Instrumentation.class);
    JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
    when(source.isNamed()).thenReturn(true);
    when(source.canRead(target)).thenReturn(false);
    AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, false, Collections.singleton(target));
    listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
    verify(source).isNamed();
    verify(source).canRead(target);
    verify(source).modify(instrumentation,
            Collections.singleton(target),
            Collections.<String, Set<JavaModule>>emptyMap(),
            Collections.<String, Set<JavaModule>>emptyMap(),
            Collections.<Class<?>>emptySet(),
            Collections.<Class<?>, List<Class<?>>>emptyMap());
    verifyNoMoreInteractions(source);
    verifyZeroInteractions(target);
}
 
Example #5
Source File: ClassFileLocatorForClassLoaderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadTypesMultiple() throws Exception {
    Map<Class<?>, byte[]> binaryRepresentations = ClassFileLocator.ForClassLoader.read(Object.class, Foo.class);
    assertThat(binaryRepresentations.size(), is(2));
    JavaModule module = JavaModule.ofType(Object.class);
    InputStream objectStream = module == null
            ? Object.class.getResourceAsStream(Object.class.getSimpleName() + ".class")
            : module.getResourceAsStream(Object.class.getName().replace('.', '/') + ".class");
    try {
        assertThat(binaryRepresentations.get(Object.class), is(StreamDrainer.DEFAULT.drain(objectStream)));
    } finally {
        objectStream.close();
    }
    InputStream fooStream = getClass().getClassLoader().getResourceAsStream(Foo.class.getName().replace('.', '/') + ".class");
    try {
        assertThat(binaryRepresentations.get(Foo.class), is(StreamDrainer.DEFAULT.drain(fooStream)));
    } finally {
        fooStream.close();
    }
}
 
Example #6
Source File: AgentBuilderRawMatcherForLoadStateTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnloadedOnLoaded() throws Exception {
    assertThat(AgentBuilder.RawMatcher.ForLoadState.UNLOADED.matches(mock(TypeDescription.class),
            mock(ClassLoader.class),
            mock(JavaModule.class),
            Object.class,
            mock(ProtectionDomain.class)), is(false));
}
 
Example #7
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipRetransformationWithNonRedefinable() throws Exception {
    when(dynamicType.getBytes()).thenReturn(BAZ);
    when(resolution.resolve()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED));
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain()))
            .thenReturn(true);
    when(instrumentation.isModifiableClass(REDEFINED)).thenReturn(false);
    when(instrumentation.isRetransformClassesSupported()).thenReturn(true);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .type(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verifyNoMoreInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, true);
    verify(instrumentation).isModifiableClass(REDEFINED);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isRetransformClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verifyZeroInteractions(typeMatcher);
    verifyZeroInteractions(initializationStrategy);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #8
Source File: ResettableClassFileTransformer.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Iterator<AgentBuilder.Transformer> iterator(TypeDescription typeDescription,
                                                   ClassLoader classLoader,
                                                   JavaModule module,
                                                   Class<?> classBeingRedefined,
                                                   ProtectionDomain protectionDomain) {
    return classFileTransformer.iterator(typeDescription, classLoader, module, classBeingRedefined, protectionDomain);
}
 
Example #9
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedefinitionPatchPreviousDoesMatch() throws Exception {
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain())).thenReturn(true);
    when(instrumentation.isModifiableClass(REDEFINED)).thenReturn(true);
    when(instrumentation.isRedefineClassesSupported()).thenReturn(true);
    ResettableClassFileTransformer previous = mock(ResettableClassFileTransformer.class);
    when(previous.reset(instrumentation, AgentBuilder.RedefinitionStrategy.DISABLED)).thenReturn(true);
    when(previous.iterator(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain())).thenReturn(Collections.singleton(transformer).iterator());
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(typeMatcher).transform(transformer)
            .patchOn(instrumentation, previous);
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verifyNoMoreInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isRedefineClassesSupported();
    //verifyNoMoreInteractions(instrumentation);
    verify(typeMatcher).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(typeMatcher);
    verifyZeroInteractions(initializationStrategy);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
    verify(previous).reset(instrumentation, AgentBuilder.RedefinitionStrategy.DISABLED);
    verify(previous).iterator(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(previous);
}
 
Example #10
Source File: AgentBuilderListenerTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadEdgeAddingListenerNamedDuplexCannotRead() throws Exception {
    Instrumentation instrumentation = mock(Instrumentation.class);
    JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
    when(source.isNamed()).thenReturn(true);
    when(source.canRead(target)).thenReturn(false);
    when(target.canRead(source)).thenReturn(false);
    AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, true, Collections.singleton(target));
    listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
    verify(source).isNamed();
    verify(source).canRead(target);
    verify(source).modify(instrumentation,
            Collections.singleton(target),
            Collections.<String, Set<JavaModule>>emptyMap(),
            Collections.<String, Set<JavaModule>>emptyMap(),
            Collections.<Class<?>>emptySet(),
            Collections.<Class<?>, List<Class<?>>>emptyMap());
    verifyNoMoreInteractions(source);
    verify(target).canRead(source);
    verify(target).modify(instrumentation,
            Collections.singleton(source),
            Collections.<String, Set<JavaModule>>emptyMap(),
            Collections.<String, Set<JavaModule>>emptyMap(),
            Collections.<Class<?>>emptySet(),
            Collections.<Class<?>, List<Class<?>>>emptyMap());
    verifyNoMoreInteractions(target);
}
 
Example #11
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulWithoutExistingClassConjunction() throws Exception {
    when(dynamicType.getBytes()).thenReturn(BAZ);
    when(resolution.resolve()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED));
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), null, REDEFINED.getProtectionDomain()))
            .thenReturn(true);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(ElementMatchers.any()).and(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    assertThat(transform(classFileTransformer, JavaModule.ofType(REDEFINED), REDEFINED.getClassLoader(), REDEFINED.getName(), null, REDEFINED.getProtectionDomain(), QUX), is(BAZ));
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), false);
    verify(listener).onTransformation(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), false, dynamicType);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), false);
    verifyNoMoreInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verifyNoMoreInteractions(instrumentation);
    verify(initializationStrategy).dispatcher();
    verifyNoMoreInteractions(initializationStrategy);
    verify(dispatcher).apply(builder);
    verify(dispatcher).register(eq(dynamicType),
            eq(REDEFINED.getClassLoader()),
            eq(REDEFINED.getProtectionDomain()),
            eq(AgentBuilder.InjectionStrategy.UsingReflection.INSTANCE));
    verifyNoMoreInteractions(dispatcher);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #12
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testTransformerApplicationOrder() throws Exception {
    AgentBuilder.RawMatcher ignored = mock(AgentBuilder.RawMatcher.class);
    AgentBuilder.Transformer first = mock(AgentBuilder.Transformer.class), second = mock(AgentBuilder.Transformer.class);
    when(first.transform(builder, TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED)))
            .thenReturn((DynamicType.Builder) builder);
    when(second.transform(builder, TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED)))
            .thenReturn((DynamicType.Builder) builder);
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain()))
            .thenReturn(true);
    ClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(ignored)
            .type(typeMatcher).transform(first)
            .type(typeMatcher).transform(second)
            .installOn(instrumentation);
    assertThat(transform(classFileTransformer, JavaModule.ofType(REDEFINED), REDEFINED.getClassLoader(), REDEFINED.getName(), REDEFINED, REDEFINED.getProtectionDomain(), QUX), equalTo(new byte[]{4, 5, 6}));
    InOrder inOrder = inOrder(first, second);
    inOrder.verify(first).transform(builder, TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED));
    inOrder.verify(second).transform(builder, TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED));
    inOrder.verifyNoMoreInteractions();
}
 
Example #13
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetransformationConsiderationException() throws Exception {
    RuntimeException exception = new RuntimeException();
    when(instrumentation.isRetransformClassesSupported()).thenReturn(true);
    when(instrumentation.getAllLoadedClasses()).thenReturn(new Class<?>[]{REDEFINED});
    when(instrumentation.isModifiableClass(REDEFINED)).thenReturn(true);
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain()))
            .thenThrow(exception);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    verify(instrumentation).addTransformer(classFileTransformer, true);
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onError(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true, exception);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verifyNoMoreInteractions(listener);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #14
Source File: AgentBuilderDefaultApplicationSuperTypeLoadingTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
                                        TypeDescription typeDescription,
                                        ClassLoader classLoader,
                                        JavaModule module) {
    return builder
            .method(isDeclaredBy(typeDescription).and(named(FOO))).intercept(FixedValue.value(FOO))
            .method(isDeclaredBy(typeDescription).and(named(BAR))).intercept(FixedValue.value(BAR));
}
 
Example #15
Source File: AgentBuilderDescriptionStrategyTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDescriptionPoolOnly() throws Exception {
    when(typePool.describe(Object.class.getName())).thenReturn(new TypePool.Resolution.Simple(typeDescription));
    assertThat(AgentBuilder.DescriptionStrategy.Default.POOL_ONLY.apply(Object.class.getName(),
            Object.class,
            typePool,
            mock(AgentBuilder.CircularityLock.class),
            Object.class.getClassLoader(),
            JavaModule.ofType(Object.class)), is(typeDescription));
}
 
Example #16
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipRedefinitionWithIgnoredTypeChainedDisjunction() throws Exception {
    when(dynamicType.getBytes()).thenReturn(BAZ);
    when(resolution.resolve()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED));
    @SuppressWarnings("unchecked")
    ElementMatcher<? super TypeDescription> ignoredTypes = mock(ElementMatcher.class);
    when(ignoredTypes.matches(TypeDescription.ForLoadedType.of(REDEFINED))).thenReturn(true);
    when(instrumentation.isModifiableClass(REDEFINED)).thenReturn(true);
    when(instrumentation.isRedefineClassesSupported()).thenReturn(true);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none()).or(ignoredTypes)
            .type(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verifyNoMoreInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verify(instrumentation).isModifiableClass(REDEFINED);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isRedefineClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verifyZeroInteractions(typeMatcher);
    verifyZeroInteractions(initializationStrategy);
    verify(ignoredTypes).matches(TypeDescription.ForLoadedType.of(REDEFINED));
    verifyNoMoreInteractions(ignoredTypes);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #17
Source File: ClassFileLocator.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a class file locator for a Java module where the module is referenced weakly. If the module is not named, the module's class loader
 * is represented instead. Module's of the boot layer are not referenced weakly.
 *
 * @param module The Java module to represent.
 * @return A suitable class file locator.
 */
public static ClassFileLocator of(JavaModule module) {
    if (module.isNamed()) {
        return module.getClassLoader() == null || module.getClassLoader() == ClassLoader.getSystemClassLoader() || module.getClassLoader() == ClassLoader.getSystemClassLoader().getParent()
                ? new ForModule(module)
                : new WeaklyReferenced(module.unwrap());
    } else {
        return ForClassLoader.WeaklyReferenced.of(module.getClassLoader());
    }
}
 
Example #18
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@JavaVersionRule.Enforce(9)
public void testExecutingTransformerDoesNotRecurseWithModules() throws Exception {
    final AgentBuilder.Default.ExecutingTransformer executingTransformer = new AgentBuilder.Default.ExecutingTransformer(byteBuddy,
            listener,
            poolStrategy,
            typeStrategy,
            locationStrategy,
            mock(AgentBuilder.Default.NativeMethodStrategy.class),
            initializationStrategy,
            mock(AgentBuilder.InjectionStrategy.class),
            AgentBuilder.LambdaInstrumentationStrategy.DISABLED,
            AgentBuilder.DescriptionStrategy.Default.HYBRID,
            mock(AgentBuilder.FallbackStrategy.class),
            mock(AgentBuilder.ClassFileBufferStrategy.class),
            mock(AgentBuilder.InstallationListener.class),
            mock(AgentBuilder.RawMatcher.class),
            Collections.<AgentBuilder.Default.Transformation>emptyList(),
            new AgentBuilder.CircularityLock.Default());
    final ClassLoader classLoader = mock(ClassLoader.class);
    final ProtectionDomain protectionDomain = mock(ProtectionDomain.class);
    doAnswer(new Answer() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertThat(executingTransformer.transform(JavaModule.ofType(Object.class).unwrap(),
                    classLoader,
                    FOO,
                    Object.class,
                    protectionDomain,
                    new byte[0]), nullValue(byte[].class));
            return null;
        }
    }).when(listener).onComplete(FOO, classLoader, JavaModule.ofType(Object.class), true);
    assertThat(executingTransformer.transform(JavaModule.ofType(Object.class).unwrap(),
            classLoader,
            FOO,
            Object.class,
            protectionDomain,
            new byte[0]), nullValue(byte[].class));
    verify(listener).onComplete(FOO, classLoader, JavaModule.ofType(Object.class), true);
}
 
Example #19
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetransformationPatchPreviousDoesMatch() throws Exception {
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain())).thenReturn(true);
    when(instrumentation.isModifiableClass(REDEFINED)).thenReturn(true);
    when(instrumentation.isRetransformClassesSupported()).thenReturn(true);
    ResettableClassFileTransformer previous = mock(ResettableClassFileTransformer.class);
    when(previous.reset(instrumentation, AgentBuilder.RedefinitionStrategy.DISABLED)).thenReturn(true);
    when(previous.iterator(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain())).thenReturn(Collections.singleton(transformer).iterator());
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(typeMatcher).transform(transformer)
            .patchOn(instrumentation, previous);
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verifyNoMoreInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, true);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isRetransformClassesSupported();
    //verifyNoMoreInteractions(instrumentation);
    verify(typeMatcher).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(typeMatcher);
    verifyZeroInteractions(initializationStrategy);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
    verify(previous).reset(instrumentation, AgentBuilder.RedefinitionStrategy.DISABLED);
    verify(previous).iterator(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(previous);
}
 
Example #20
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkipRedefinitionWithNonMatched() throws Exception {
    when(dynamicType.getBytes()).thenReturn(BAZ);
    when(resolution.resolve()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED));
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain()))
            .thenReturn(false);
    when(instrumentation.isModifiableClass(REDEFINED)).thenReturn(true);
    when(instrumentation.isRedefineClassesSupported()).thenReturn(true);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    verify(listener).onDiscovery(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onIgnored(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verify(listener).onComplete(REDEFINED.getName(), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), true);
    verifyNoMoreInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verify(instrumentation).isModifiableClass(REDEFINED);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isRedefineClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verify(typeMatcher).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(typeMatcher);
    verifyZeroInteractions(initializationStrategy);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #21
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulWithRetransformationMatchedFallbackAndReset() throws Exception {
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain()))
            .thenThrow(new RuntimeException());
    when(typeMatcher.matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), null, REDEFINED.getProtectionDomain()))
            .thenReturn(true);
    when(resolution.resolve()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED));
    when(instrumentation.isModifiableClass(REDEFINED)).thenReturn(true);
    when(instrumentation.isRetransformClassesSupported()).thenReturn(true);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(AgentBuilder.FallbackStrategy.Simple.ENABLED)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    when(instrumentation.removeTransformer(classFileTransformer)).thenReturn(true);
    assertThat(classFileTransformer.reset(instrumentation, AgentBuilder.RedefinitionStrategy.RETRANSFORMATION), is(true));
    verifyZeroInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, true);
    verify(instrumentation).removeTransformer(classFileTransformer);
    verify(instrumentation, times(2)).getAllLoadedClasses();
    verify(instrumentation, times(2)).isModifiableClass(REDEFINED);
    verify(instrumentation, times(2)).retransformClasses(REDEFINED);
    verify(instrumentation, times(2)).isRetransformClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verify(typeMatcher, times(2)).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verify(typeMatcher, times(2)).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), null, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(typeMatcher);
    verifyZeroInteractions(initializationStrategy);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verify(installationListener).onReset(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #22
Source File: BufferAlignmentAgent.java    From agrona with Apache License 2.0 5 votes vote down vote up
public void onDiscovery(
    final String typeName,
    final ClassLoader classLoader,
    final JavaModule module,
    final boolean loaded)
{
}
 
Example #23
Source File: EventLogAgent.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void onComplete(
    final String typeName,
    final ClassLoader classLoader,
    final JavaModule module,
    final boolean loaded)
{
}
 
Example #24
Source File: EventLogAgent.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void onError(
    final String typeName,
    final ClassLoader classLoader,
    final JavaModule module,
    final boolean loaded,
    final Throwable throwable)
{
    System.err.println("ERROR " + typeName);
    throwable.printStackTrace(System.err);
}
 
Example #25
Source File: EventLogAgent.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void onIgnored(
    final TypeDescription typeDescription,
    final ClassLoader classLoader,
    final JavaModule module,
    final boolean loaded)
{
}
 
Example #26
Source File: EventLogAgent.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void onTransformation(
    final TypeDescription typeDescription,
    final ClassLoader classLoader,
    final JavaModule module,
    final boolean loaded,
    final DynamicType dynamicType)
{
}
 
Example #27
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testExecutingTransformerDoesNotRecurse() throws Exception {
    final AgentBuilder.Default.ExecutingTransformer executingTransformer = new AgentBuilder.Default.ExecutingTransformer(byteBuddy,
            listener,
            poolStrategy,
            typeStrategy,
            locationStrategy,
            mock(AgentBuilder.Default.NativeMethodStrategy.class),
            initializationStrategy,
            mock(AgentBuilder.InjectionStrategy.class),
            AgentBuilder.LambdaInstrumentationStrategy.DISABLED,
            AgentBuilder.DescriptionStrategy.Default.HYBRID,
            mock(AgentBuilder.FallbackStrategy.class),
            mock(AgentBuilder.ClassFileBufferStrategy.class),
            mock(AgentBuilder.InstallationListener.class),
            mock(AgentBuilder.RawMatcher.class),
            Collections.<AgentBuilder.Default.Transformation>emptyList(),
            new AgentBuilder.Default.CircularityLock.Default());
    final ClassLoader classLoader = mock(ClassLoader.class);
    final ProtectionDomain protectionDomain = mock(ProtectionDomain.class);
    doAnswer(new Answer() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            assertThat(executingTransformer.transform(classLoader,
                    FOO,
                    Object.class,
                    protectionDomain,
                    new byte[0]), nullValue(byte[].class));
            return null;
        }
    }).when(listener).onComplete(FOO, classLoader, JavaModule.UNSUPPORTED, true);
    assertThat(executingTransformer.transform(classLoader,
            FOO,
            Object.class,
            protectionDomain,
            new byte[0]), nullValue(byte[].class));
    verify(listener).onComplete(FOO, classLoader, JavaModule.UNSUPPORTED, true);
}
 
Example #28
Source File: AgentBuilderRawMatcherTrivialTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchesNot() throws Exception {
    assertThat(AgentBuilder.RawMatcher.Trivial.NON_MATCHING.matches(mock(TypeDescription.class),
            mock(ClassLoader.class),
            mock(JavaModule.class),
            Void.class,
            mock(ProtectionDomain.class)), is(false));
}
 
Example #29
Source File: SkyWalkingAgent.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void onError(final String typeName,
                    final ClassLoader classLoader,
                    final JavaModule module,
                    final boolean loaded,
                    final Throwable throwable) {
    logger.error("Enhance class " + typeName + " error.", throwable);
}
 
Example #30
Source File: SkyWalkingAgent.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void onTransformation(final TypeDescription typeDescription,
                             final ClassLoader classLoader,
                             final JavaModule module,
                             final boolean loaded,
                             final DynamicType dynamicType) {
    if (logger.isDebugEnable()) {
        logger.debug("On Transformation class {}.", typeDescription.getName());
    }

    InstrumentDebuggingClass.INSTANCE.log(dynamicType);
}