java.lang.instrument.ClassDefinition Java Examples

The following examples show how to use java.lang.instrument.ClassDefinition. 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: InstrumentationImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #2
Source File: InstrumentationImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #3
Source File: InstrumentationImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #4
Source File: InstrumentationImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #5
Source File: MixinAgent.java    From Mixin with MIT License 6 votes vote down vote up
/**
 * Re-apply all mixins to the supplied list of target classes.
 * 
 * @param targets Target classes to re-transform
 * @return true if all targets were transformed, false if transformation
 *          failed
 */
private boolean reApplyMixins(List<String> targets) {
    IMixinService service = MixinService.getService();
    
    for (String target : targets) {
        String targetName = target.replace('/', '.');
        MixinAgent.logger.debug("Re-transforming target class {}", target);
        try {
            Class<?> targetClass = service.getClassProvider().findClass(targetName);
            byte[] targetBytecode = MixinAgent.classLoader.getOriginalTargetBytecode(targetName);
            if (targetBytecode == null) {
                MixinAgent.logger.error("Target class {} bytecode is not registered", targetName);
                return false;
            }
            targetBytecode = MixinAgent.this.classTransformer.transformClassBytes(null, targetName, targetBytecode);
            MixinAgent.instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode));
        } catch (Throwable th) {
            MixinAgent.logger.error("Error while re-transforming target class " + target, th);
            return false;
        }
    }
    return true;
}
 
Example #6
Source File: InstrumentationImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #7
Source File: Hotswaper.java    From Voovan with Apache License 2.0 6 votes vote down vote up
/**
 * 重新热加载Class
 * @param clazzDefines 有过变更的文件信息
 * @throws UnmodifiableClassException  不可修改的 Class 异常
 * @throws ClassNotFoundException Class未找到异常
 */
public static void reloadClass(Map<Class, byte[]> clazzDefines) throws UnmodifiableClassException, ClassNotFoundException {

    for(Map.Entry<Class, byte[]> clazzDefine : clazzDefines.entrySet()){
        Class clazz = clazzDefine.getKey();
        byte[] classBytes = clazzDefine.getValue();

        ClassDefinition classDefinition = new ClassDefinition(clazz, classBytes);
        try {
            Logger.info("[HOTSWAP] class:" + clazz + " will reload.");
            TEnv.instrumentation.redefineClasses(classDefinition);
        } catch (Exception e) {
            Logger.error("[HOTSWAP] class:" + clazz + " reload failed", e);
        }
    }
}
 
Example #8
Source File: InstrumentationImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #9
Source File: InstrumentationImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #10
Source File: InstrumentationImpl.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #11
Source File: InstrumentationImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #12
Source File: InstrumentationRedefiner.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
public void redefineClasses(Map<Class<?>, byte[]> classes)
        throws ClassNotFoundException, UnmodifiableClassException {

    if (PluginManager.getInstance().getInstrumentation() == null) {
        throw new IllegalStateException(
                "Instrumentation agent is not properly installed!");
    }

    ClassDefinition[] definitions = new ClassDefinition[classes.size()];
    int i = 0;
    for (Map.Entry<Class<?>, byte[]> entry : classes.entrySet()) {
        definitions[i++] = new ClassDefinition(entry.getKey(),
                entry.getValue());
        URL classResource = getClassResource(entry.getKey());

        try (OutputStream fileWriter = new FileOutputStream(
                new File(classResource.toURI()))) {
            fileWriter.write(entry.getValue());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    PluginManager.getInstance().getInstrumentation()
            .redefineClasses(definitions);
}
 
Example #13
Source File: InstrumentationImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #14
Source File: PluginManager.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Redefine the supplied set of classes using the supplied bytecode.
 *
 * This method operates on a set in order to allow interdependent changes to more than one class at the same time
 * (a redefinition of class A can require a redefinition of class B).
 *
 * @param reloadMap class -> new bytecode
 * @see java.lang.instrument.Instrumentation#redefineClasses(java.lang.instrument.ClassDefinition...)
 */
public void hotswap(Map<Class<?>, byte[]> reloadMap) {
    if (instrumentation == null) {
        throw new IllegalStateException("Plugin manager is not correctly initialized - no instrumentation available.");
    }

    synchronized (reloadMap) {
        ClassDefinition[] definitions = new ClassDefinition[reloadMap.size()];
        String[] classNames = new String[reloadMap.size()];
        int i = 0;
        for (Map.Entry<Class<?>, byte[]> entry : reloadMap.entrySet()) {
            classNames[i] = entry.getKey().getName();
            definitions[i++] = new ClassDefinition(entry.getKey(), entry.getValue());
        }
        try {
            LOGGER.reload("Reloading classes {} (autoHotswap)", Arrays.toString(classNames));
            synchronized (hotswapLock) {
                instrumentation.redefineClasses(definitions);
            }
            LOGGER.debug("... reloaded classes {} (autoHotswap)", Arrays.toString(classNames));
        } catch (Exception e) {
            throw new IllegalStateException("Unable to redefine classes", e);
        }
        reloadMap.clear();
    }
}
 
Example #15
Source File: InstrumentationResource.java    From Recaf with MIT License 6 votes vote down vote up
/**
 * Saves changed by retransforming classes.
 *
 * @throws ClassNotFoundException
 * 		When the modified class couldn't be found.
 * @throws UnmodifiableClassException
 * 		When the modified class is not allowed to be modified.
 * @throws ClassFormatError
 * 		When the modified class is not valid.
 */
public void save() throws ClassNotFoundException, UnmodifiableClassException, ClassFormatError {
	// Classes to update
	Set<String> dirty = new HashSet<>(getDirtyClasses());
	if(dirty.isEmpty()) {
		Log.info("There are no classes to redefine.", dirty.size());
		return;
	}
	Log.info("Preparing to redefine {} classes", dirty.size());
	ClassDefinition[] definitions = new ClassDefinition[dirty.size()];
	int i = 0;
	for (String name : dirty) {
		String clsName = name.replace('/', '.');
		Class<?> cls = Class.forName(clsName, false, ClasspathUtil.scl);
		byte[] value = getClasses().get(name);
		if (value == null)
			throw new IllegalStateException("Failed to fetch code for class: " + name);
		definitions[i] = new ClassDefinition(cls, value);
		i++;
	}
	// Apply new definitions
	instrumentation.redefineClasses(definitions);
	// We don't want to continually re-apply changes that don't need to be updated
	getDirtyClasses().clear();
	Log.info("Successfully redefined {} classes", definitions.length);
}
 
Example #16
Source File: InstrumentationImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #17
Source File: InstrumentationImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #18
Source File: InstrumentationImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public void
redefineClasses(ClassDefinition...  definitions)
        throws  ClassNotFoundException {
    if (!isRedefineClassesSupported()) {
        throw new UnsupportedOperationException("redefineClasses is not supported in this environment");
    }
    if (definitions == null) {
        throw new NullPointerException("null passed as 'definitions' in redefineClasses");
    }
    for (int i = 0; i < definitions.length; ++i) {
        if (definitions[i] == null) {
            throw new NullPointerException("element of 'definitions' is null in redefineClasses");
        }
    }
    if (definitions.length == 0) {
        return; // short-circuit if there are no changes requested
    }

    redefineClasses0(mNativeAgent, definitions);
}
 
Example #19
Source File: RedefineMethodInBacktraceApp.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f.getAbsolutePath());
    InputStream redefineStream = new FileInputStream(f);

    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);

    ClassDefinition redefineParamBlock = new ClassDefinition(
            clazz, redefineBuffer);

    RedefineMethodInBacktraceAgent.getInstrumentation().redefineClasses(
            new ClassDefinition[] {redefineParamBlock});
}
 
Example #20
Source File: RedefineMethodWithAnnotationsApp.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f);
    InputStream redefineStream = new FileInputStream(f);

    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);

    ClassDefinition redefineParamBlock = new ClassDefinition(
            clazz, redefineBuffer);

    RedefineMethodWithAnnotationsAgent.getInstrumentation().redefineClasses(
            new ClassDefinition[] {redefineParamBlock});
}
 
Example #21
Source File: RedefineMethodWithAnnotationsApp.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f);
    InputStream redefineStream = new FileInputStream(f);

    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);

    ClassDefinition redefineParamBlock = new ClassDefinition(
            clazz, redefineBuffer);

    RedefineMethodWithAnnotationsAgent.getInstrumentation().redefineClasses(
            new ClassDefinition[] {redefineParamBlock});
}
 
Example #22
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulWithRedefinitionMatched() 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 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);
    verifyZeroInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isModifiableClass(REDEFINED);
    verify(instrumentation).redefineClasses(any(ClassDefinition.class));
    verify(instrumentation).isRedefineClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verify(typeMatcher).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(typeMatcher);
    verifyZeroInteractions(dispatcher);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #23
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulWithRedefinitionMatchedFallback() 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.isRedefineClassesSupported()).thenReturn(true);
    ResettableClassFileTransformer classFileTransformer = new AgentBuilder.Default(byteBuddy)
            .with(initializationStrategy)
            .with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
            .with(poolStrategy)
            .with(typeStrategy)
            .with(installationListener)
            .with(AgentBuilder.FallbackStrategy.Simple.ENABLED)
            .with(listener)
            .disableNativeMethodPrefix()
            .ignore(none())
            .type(typeMatcher).transform(transformer)
            .installOn(instrumentation);
    verifyZeroInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isModifiableClass(REDEFINED);
    verify(instrumentation).redefineClasses(any(ClassDefinition.class));
    verify(instrumentation).isRedefineClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verify(typeMatcher).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verify(typeMatcher).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);
    verifyNoMoreInteractions(installationListener);
}
 
Example #24
Source File: RedefineMethodWithAnnotationsApp.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f);
    InputStream redefineStream = new FileInputStream(f);

    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);

    ClassDefinition redefineParamBlock = new ClassDefinition(
            clazz, redefineBuffer);

    RedefineMethodWithAnnotationsAgent.getInstrumentation().redefineClasses(
            new ClassDefinition[] {redefineParamBlock});
}
 
Example #25
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulWithRedefinitionMatchedAndReset() 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 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);
    when(instrumentation.removeTransformer(classFileTransformer)).thenReturn(true);
    assertThat(classFileTransformer.reset(instrumentation, AgentBuilder.RedefinitionStrategy.REDEFINITION), is(true));
    verifyZeroInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verify(instrumentation).removeTransformer(classFileTransformer);
    verify(instrumentation, times(2)).getAllLoadedClasses();
    verify(instrumentation, times(2)).isModifiableClass(REDEFINED);
    verify(instrumentation, times(2)).redefineClasses(any(ClassDefinition.class));
    verify(instrumentation, times(2)).isRedefineClassesSupported();
    verifyNoMoreInteractions(instrumentation);
    verify(typeMatcher, times(2)).matches(TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED), REDEFINED, REDEFINED.getProtectionDomain());
    verifyNoMoreInteractions(typeMatcher);
    verifyZeroInteractions(dispatcher);
    verify(installationListener).onBeforeInstall(instrumentation, classFileTransformer);
    verify(installationListener).onInstall(instrumentation, classFileTransformer);
    verify(installationListener).onReset(instrumentation, classFileTransformer);
    verifyNoMoreInteractions(installationListener);
}
 
Example #26
Source File: ClassReloader.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void reloadClasses(Collection<byte[]> classDatas) throws Exception, Error
{
	if (_inst == null)
		throw new NullPointerException("Instrumentation not initialized");
	int i = 0, n = classDatas.size();
	ClassDefinition[] clsDefs = new ClassDefinition[n];
	for (byte[] classData : classDatas)
		clsDefs[i++] = new ClassDefinition(Class.forName(getClassPathFromData(classData)), classData);
	_inst.redefineClasses(clsDefs);
}
 
Example #27
Source File: AgentBuilderDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedefinitionPatchPreviousDoesNotMatch() 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.<AgentBuilder.Transformer>emptySet().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);
    verifyZeroInteractions(listener);
    verify(instrumentation).addTransformer(classFileTransformer, false);
    verify(instrumentation).getAllLoadedClasses();
    verify(instrumentation).isModifiableClass(REDEFINED);
    verify(instrumentation).redefineClasses(any(ClassDefinition.class));
    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 #28
Source File: RedefineMethodInBacktraceApp.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f.getAbsolutePath());
    InputStream redefineStream = new FileInputStream(f);

    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);

    ClassDefinition redefineParamBlock = new ClassDefinition(
            clazz, redefineBuffer);

    RedefineMethodInBacktraceAgent.getInstrumentation().redefineClasses(
            new ClassDefinition[] {redefineParamBlock});
}
 
Example #29
Source File: RedefineMethodWithAnnotationsApp.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f);
    InputStream redefineStream = new FileInputStream(f);

    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);

    ClassDefinition redefineParamBlock = new ClassDefinition(
            clazz, redefineBuffer);

    RedefineMethodWithAnnotationsAgent.getInstrumentation().redefineClasses(
            new ClassDefinition[] {redefineParamBlock});
}
 
Example #30
Source File: RedefineMethodInBacktraceApp.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void doRedefine(Class<?> clazz) throws Exception {
    // Load the second version of this class.
    File f = new File(clazz.getName() + ".class");
    System.out.println("Reading test class from " + f.getAbsolutePath());
    InputStream redefineStream = new FileInputStream(f);

    byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);

    ClassDefinition redefineParamBlock = new ClassDefinition(
            clazz, redefineBuffer);

    RedefineMethodInBacktraceAgent.getInstrumentation().redefineClasses(
            new ClassDefinition[] {redefineParamBlock});
}