Java Code Examples for net.bytebuddy.agent.ByteBuddyAgent#install()

The following examples show how to use net.bytebuddy.agent.ByteBuddyAgent#install() . 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: AgentAttachmentRule.java    From garmadon with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
    Enforce enforce = method.getAnnotation(Enforce.class);
    if (enforce != null) {
        if (!available) {
            return new NoOpStatement("The executing JVM does not support runtime attachment");
        }
        Instrumentation instrumentation = ByteBuddyAgent.install(ByteBuddyAgent.AttachmentProvider.DEFAULT);
        if (enforce.redefinesClasses() && !instrumentation.isRedefineClassesSupported()) {
            return new NoOpStatement("The executing JVM does not support class redefinition");
        } else if (enforce.retransformsClasses() && !instrumentation.isRetransformClassesSupported()) {
            return new NoOpStatement("The executing JVM does not support class retransformation");
        } else if (enforce.nativeMethodPrefix() && !instrumentation.isNativeMethodPrefixSupported()) {
            return new NoOpStatement("The executing JVM does not support class native method prefixes");
        }
    }
    return base;
}
 
Example 2
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce(redefinesClasses = true)
public void testTutorialGettingStartedClassReloading() throws Exception {
    ByteBuddyAgent.install();
    FooReloading foo = new FooReloading();
    try {
        new ByteBuddy()
                .redefine(BarReloading.class)
                .name(FooReloading.class.getName())
                .make()
                .load(FooReloading.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
        assertThat(foo.m(), is("bar"));
    } finally {
        ClassReloadingStrategy.fromInstalledAgent().reset(FooReloading.class); // Assure repeatability.
    }
    assertThat(foo.m(), is("foo"));
}
 
Example 3
Source File: AgentAttachmentRule.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
public Statement apply(Statement base, FrameworkMethod method, Object target) {
    Enforce enforce = method.getAnnotation(Enforce.class);
    if (enforce != null) {
        if (!available) {
            return new NoOpStatement("The executing JVM does not support runtime attachment");
        }
        Instrumentation instrumentation = ByteBuddyAgent.install(ByteBuddyAgent.AttachmentProvider.DEFAULT);
        if (enforce.redefinesClasses() && !instrumentation.isRedefineClassesSupported()) {
            return new NoOpStatement("The executing JVM does not support class redefinition");
        } else if (enforce.retransformsClasses() && !instrumentation.isRetransformClassesSupported()) {
            return new NoOpStatement("The executing JVM does not support class retransformation");
        } else if (enforce.nativeMethodPrefix() && !instrumentation.isNativeMethodPrefixSupported()) {
            return new NoOpStatement("The executing JVM does not support class native method prefixes");
        }
    }
    return base;
}
 
Example 4
Source File: AgentAttachmentRule.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
public Statement apply(Statement base, FrameworkMethod method, Object target) {
    Enforce enforce = method.getAnnotation(Enforce.class);
    if (enforce != null) {
        if (!available) {
            return new NoOpStatement("The executing JVM does not support runtime attachment");
        }
        Instrumentation instrumentation = ByteBuddyAgent.install(ByteBuddyAgent.AttachmentProvider.DEFAULT);
        if (enforce.redefinesClasses() && !instrumentation.isRedefineClassesSupported()) {
            return new NoOpStatement("The executing JVM does not support class redefinition");
        } else if (enforce.retransformsClasses() && !instrumentation.isRetransformClassesSupported()) {
            return new NoOpStatement("The executing JVM does not support class retransformation");
        } else if (enforce.nativeMethodPrefix() && !instrumentation.isNativeMethodPrefixSupported()) {
            return new NoOpStatement("The executing JVM does not support class native method prefixes");
        }
    }
    return base;
}
 
Example 5
Source File: ReactorDebugAgent.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
public static synchronized void init() {
	if (System.getProperty(INSTALLED_PROPERTY) != null) {
		return;
	}

	if (instrumentation != null) {
		return;
	}
	instrumentation = ByteBuddyAgent.install();

	instrument(instrumentation);
}
 
Example 6
Source File: ClassReloadingStrategyTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@JavaVersionRule.Enforce(value = 8, atMost = 8, j9 = false)
@AgentAttachmentRule.Enforce(retransformsClasses = true)
public void testAnonymousType() throws Exception {
    ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
            ClassFileLocator.ForClassLoader.readToNames(Class.forName(LAMBDA_SAMPLE_FACTORY)),
            ByteArrayClassLoader.PersistenceHandler.MANIFEST);
    Instrumentation instrumentation = ByteBuddyAgent.install();
    Class<?> factory = classLoader.loadClass(LAMBDA_SAMPLE_FACTORY);
    @SuppressWarnings("unchecked")
    Callable<String> instance = (Callable<String>) factory.getDeclaredMethod("nonCapturing").invoke(factory.getDeclaredConstructor().newInstance());
    // Anonymous types can only be reset to their original format, if a retransformation is applied.
    ClassReloadingStrategy classReloadingStrategy = new ClassReloadingStrategy(instrumentation,
            ClassReloadingStrategy.Strategy.RETRANSFORMATION).preregistered(instance.getClass());
    ClassFileLocator classFileLocator = ClassFileLocator.AgentBased.of(instrumentation, instance.getClass());
    try {
        assertThat(instance.call(), is(FOO));
        new ByteBuddy()
                .redefine(instance.getClass(), classFileLocator)
                .method(named("call"))
                .intercept(FixedValue.value(BAR))
                .make()
                .load(instance.getClass().getClassLoader(), classReloadingStrategy);
        assertThat(instance.call(), is(BAR));
    } finally {
        classReloadingStrategy.reset(classFileLocator, instance.getClass());
        assertThat(instance.call(), is(FOO));
    }
}
 
Example 7
Source File: ClassLoadingStrategyForBootstrapInjectionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce
public void testBootstrapInjection() throws Exception {
    ClassLoadingStrategy<ClassLoader> bootstrapStrategy = new ClassLoadingStrategy.ForBootstrapInjection(ByteBuddyAgent.install(), file);
    String name = FOO + RandomString.make();
    DynamicType dynamicType = new ByteBuddy().subclass(Object.class).name(name).make();
    Map<TypeDescription, Class<?>> loaded = bootstrapStrategy.load(ClassLoadingStrategy.BOOTSTRAP_LOADER, Collections.singletonMap(dynamicType.getTypeDescription(), dynamicType.getBytes()));
    assertThat(loaded.size(), is(1));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getName(), is(name));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getClassLoader(), nullValue(ClassLoader.class));
}
 
Example 8
Source File: ClassLoadingStrategyForBootstrapInjectionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@AgentAttachmentRule.Enforce
@ClassReflectionInjectionAvailableRule.Enforce
public void testClassLoaderInjection() throws Exception {
    ClassLoadingStrategy<ClassLoader> bootstrapStrategy = new ClassLoadingStrategy.ForBootstrapInjection(ByteBuddyAgent.install(), file);
    String name = BAR + RandomString.make();
    ClassLoader classLoader = new URLClassLoader(new URL[0], null);
    DynamicType dynamicType = new ByteBuddy().subclass(Object.class).name(name).make();
    Map<TypeDescription, Class<?>> loaded = bootstrapStrategy.load(classLoader, Collections.singletonMap(dynamicType.getTypeDescription(), dynamicType.getBytes()));
    assertThat(loaded.size(), is(1));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getName(), is(name));
    assertThat(loaded.get(dynamicType.getTypeDescription()).getClassLoader(), is(classLoader));
}
 
Example 9
Source File: ByteBuddyUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
    ByteBuddyAgent.install();
    new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
    Foo f = new Foo();
    assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
}
 
Example 10
Source File: BlockHound.java    From BlockHound with Apache License 2.0 4 votes vote down vote up
/**
 * Installs the agent and runs the instrumentation, but only if BlockHound wasn't installed yet (it is global).
 */
public void install() {
    if (!INITIALIZED.compareAndSet(false, true)) {
        return;
    }

    Consumer<BlockingMethod> originalOnBlockingMethod = onBlockingMethod;
    try {
        Instrumentation instrumentation = ByteBuddyAgent.install();
        InstrumentationUtils.injectBootstrapClasses(
                instrumentation,
                BLOCK_HOUND_RUNTIME_TYPE.getInternalName(),
                "reactor/blockhound/BlockHoundRuntime$State"
        );

        // Since BlockHoundRuntime is injected into the bootstrap classloader,
        // we use raw Object[] here instead of `BlockingMethod` to avoid classloading issues
        BlockHoundRuntime.blockingMethodConsumer = args -> {
            String className = (String) args[0];
            String methodName = (String) args[1];
            int modifiers = (Integer) args[2];
            onBlockingMethod.accept(new BlockingMethod(className, methodName, modifiers));
        };

        onBlockingMethod = m -> {
            Thread currentThread = Thread.currentThread();
            if (currentThread instanceof TestThread) {
                ((TestThread) currentThread).blockingCallDetected = true;
            }
        };
        BlockHoundRuntime.dynamicThreadPredicate = t -> false;
        BlockHoundRuntime.threadPredicate = TestThread.class::isInstance;

        instrument(instrumentation);
    }
    catch (Throwable e) {
        throw new RuntimeException(e);
    }

    testInstrumentation();

    // Eagerly trigger the classloading of `dynamicThreadPredicate` (since classloading is blocking)
    dynamicThreadPredicate.test(Thread.currentThread());
    BlockHoundRuntime.dynamicThreadPredicate = dynamicThreadPredicate;

    // Eagerly trigger the classloading of `threadPredicate` (since classloading is blocking)
    threadPredicate.test(Thread.currentThread());
    BlockHoundRuntime.threadPredicate = threadPredicate;

    onBlockingMethod = originalOnBlockingMethod;

    // Re-evaluate the current thread's state after assigning user-provided predicates
    BlockHoundRuntime.STATE.remove();
}
 
Example 11
Source File: EnhancerTest.java    From arthas with Apache License 2.0 4 votes vote down vote up
@Test
    public void test() throws Throwable {
        Instrumentation instrumentation = ByteBuddyAgent.install();

        TestHelper.appendSpyJar(instrumentation);

        ArthasBootstrap.getInstance(instrumentation, "");

        AdviceListener listener = Mockito.mock(AdviceListener.class);

        EqualsMatcher<String> methodNameMatcher = new EqualsMatcher<String>("print");
        EqualsMatcher<String> classNameMatcher = new EqualsMatcher<String>(MathGame.class.getName());

        Enhancer enhancer = new Enhancer(listener, true, false, classNameMatcher, methodNameMatcher);

        ClassLoader inClassLoader = MathGame.class.getClassLoader();
        String className = MathGame.class.getName();
        Class<?> classBeingRedefined = MathGame.class;

        ClassNode classNode = AsmUtils.loadClass(MathGame.class);

        byte[] classfileBuffer = AsmUtils.toBytes(classNode);

        byte[] result = enhancer.transform(inClassLoader, className, classBeingRedefined, null, classfileBuffer);

        ClassNode resultClassNode1 = AsmUtils.toClassNode(result);

//        FileUtils.writeByteArrayToFile(new File("/tmp/MathGame1.class"), result);

        result = enhancer.transform(inClassLoader, className, classBeingRedefined, null, result);

        ClassNode resultClassNode2 = AsmUtils.toClassNode(result);

//        FileUtils.writeByteArrayToFile(new File("/tmp/MathGame2.class"), result);

        MethodNode resultMethodNode1 = AsmUtils.findMethods(resultClassNode1.methods, "print").get(0);
        MethodNode resultMethodNode2 = AsmUtils.findMethods(resultClassNode2.methods, "print").get(0);

        Assertions
                .assertThat(AsmUtils
                        .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atEnter").size())
                .isEqualTo(AsmUtils.findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atEnter")
                        .size());

        Assertions.assertThat(AsmUtils
                .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atExceptionExit").size())
                .isEqualTo(AsmUtils
                        .findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atExceptionExit")
                        .size());

        Assertions.assertThat(AsmUtils
                .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atBeforeInvoke").size())
                .isEqualTo(AsmUtils
                        .findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atBeforeInvoke")
                        .size());
        Assertions.assertThat(AsmUtils
                .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atInvokeException").size())
                .isEqualTo(AsmUtils
                        .findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atInvokeException")
                        .size());

        String string = Decompiler.decompile(result);

        System.err.println(string);
    }