java.lang.instrument.IllegalClassFormatException Java Examples

The following examples show how to use java.lang.instrument.IllegalClassFormatException. 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: RedefineAnnotations.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override public byte[] transform(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    if (className.contains("TypeAnnotatedTestClass")) {
        try {
            // Here we remove and re-add the dummy fields. This shuffles the constant pool
            return asm(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
        } catch (Throwable e) {
            // The retransform native code that called this method does not propagate
            // exceptions. Instead of getting an uninformative generic error, catch
            // problems here and print it, then exit.
            e.printStackTrace();
            System.exit(1);
        }
    }
    return null;
}
 
Example #2
Source File: HelloWorldAgent.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] transform(
    ClassLoader loader, String className, Class<?> classBeingRedefined,
    ProtectionDomain protectionDomain, byte[] arr
) throws IllegalClassFormatException {
    byte[] ret = arr;
    for (int i = 0; i < arr.length - 4; i++) {
        if (arr[i] == 'H' && arr[i + 1] == 'e' && arr[i + 2] == 'l' && 
            arr[i + 3] == 'o'
        ) {
            ret = ret.clone();
            ret[i] = 'A';
            ret[i + 1] = 'h';
            ret[i + 2] = 'o';
            ret[i + 3] = 'j';
        }
    }
    return ret;
}
 
Example #3
Source File: HelloWorldAgent.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] transform(
    ClassLoader loader, String className, Class<?> classBeingRedefined,
    ProtectionDomain protectionDomain, byte[] arr
) throws IllegalClassFormatException {
    byte[] ret = arr;
    for (int i = 0; i < arr.length - 4; i++) {
        if (arr[i] == 'H' && arr[i + 1] == 'e' && arr[i + 2] == 'l' && 
            arr[i + 3] == 'o'
        ) {
            ret = ret.clone();
            ret[i] = 'A';
            ret[i + 1] = 'h';
            ret[i + 2] = 'o';
            ret[i + 3] = 'j';
        }
    }
    return ret;
}
 
Example #4
Source File: WeavingTransformer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Apply transformation on a given class byte definition.
 * The method will always return a non-null byte array (if no transformation has taken place
 * the array content will be identical to the original one).
 * @param className the full qualified name of the class in dot format (i.e. some.package.SomeClass)
 * @param internalName class name internal name in / format (i.e. some/package/SomeClass)
 * @param bytes class byte definition
 * @param pd protection domain to be used (can be null)
 * @return (possibly transformed) class byte definition
 */
public byte[] transformIfNecessary(String className, String internalName, byte[] bytes, @Nullable ProtectionDomain pd) {
	byte[] result = bytes;
	for (ClassFileTransformer cft : this.transformers) {
		try {
			byte[] transformed = cft.transform(this.classLoader, internalName, null, pd, result);
			if (transformed != null) {
				result = transformed;
			}
		}
		catch (IllegalClassFormatException ex) {
			throw new IllegalStateException("Class file transformation failed", ex);
		}
	}
	return result;
}
 
Example #5
Source File: NbInstrumentation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static byte[] patchByteCode(ClassLoader l, String className, ProtectionDomain pd, byte[] arr) throws IllegalClassFormatException {
    if (ACTIVE == null) {
        return arr;
    }
    if (Boolean.TRUE.equals(IN.get())) {
        return arr;
    }
    try {
        IN.set(Boolean.TRUE);
        for (NbInstrumentation inst : ACTIVE) {
            for (ClassFileTransformer t : inst.transformers) {
                arr = t.transform(l, className, null, pd, arr);
            }
        }
    } finally {
        IN.set(null);
    }
    return arr;
}
 
Example #6
Source File: RedefineAnnotations.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override public byte[] transform(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    if (className.contains("TypeAnnotatedTestClass")) {
        try {
            // Here we remove and re-add the dummy fields. This shuffles the constant pool
            return asm(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
        } catch (Throwable e) {
            // The retransform native code that called this method does not propagate
            // exceptions. Instead of getting an uninformative generic error, catch
            // problems here and print it, then exit.
            e.printStackTrace();
            System.exit(1);
        }
    }
    return null;
}
 
Example #7
Source File: WeavingTransformer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Apply transformation on a given class byte definition.
 * The method will always return a non-null byte array (if no transformation has taken place
 * the array content will be identical to the original one).
 * @param className the full qualified name of the class in dot format (i.e. some.package.SomeClass)
 * @param internalName class name internal name in / format (i.e. some/package/SomeClass)
 * @param bytes class byte definition
 * @param pd protection domain to be used (can be null)
 * @return (possibly transformed) class byte definition
 */
public byte[] transformIfNecessary(String className, String internalName, byte[] bytes, ProtectionDomain pd) {
	byte[] result = bytes;
	for (ClassFileTransformer cft : this.transformers) {
		try {
			byte[] transformed = cft.transform(this.classLoader, internalName, null, pd, result);
			if (transformed != null) {
				result = transformed;
			}
		}
		catch (IllegalClassFormatException ex) {
			throw new IllegalStateException("Class file transformation failed", ex);
		}
	}
	return result;
}
 
Example #8
Source File: TestInstrumentation.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public byte[] transform(
        ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException {
    // Check if this class should be instrumented.
    if (!instrClassesTarget.contains(className)) {
        return null;
    }

    boolean isRedefinition = classBeingRedefined != null;
    log("instrument class(" + className + ") " + (isRedefinition ? "redef" : "load"));

    ClassReader reader = new ClassReader(bytes);
    ClassWriter writer = new ClassWriter(
            reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    CallbackClassVisitor classVisitor = new CallbackClassVisitor(writer);
    reader.accept(classVisitor, 0);
    instrClassesDone.add(className);
    return writer.toByteArray();
}
 
Example #9
Source File: KeyTransformer.java    From atlassian-agent with GNU General Public License v3.0 6 votes vote down vote up
private byte[] handleKeySpec() throws IllegalClassFormatException {
    try {
        ClassPool cp = ClassPool.getDefault();
        cp.importPackage("java.util.Arrays");
        cp.importPackage("javax.xml.bind.DatatypeConverter");

        int mod = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
        CtClass cc = cp.get(CN_KEY_SPEC.replace('/', '.'));
        CtClass cb = cp.get("byte[]");
        CtField cfOld = new CtField(cb, "__h_ok", cc);
        CtField cfNew = new CtField(cb, "__h_nk", cc);
        cfOld.setModifiers(mod);
        cfNew.setModifiers(mod);
        cc.addField(cfOld, "DatatypeConverter.parseBase64Binary(\"MIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAIvfweZvmGo5otwawI3no7Udanxal3hX2haw962KL/nHQrnC4FG2PvUFf34OecSK1KtHDPQoSQ+DHrfdf6vKUJphw0Kn3gXm4LS8VK/LrY7on/wh2iUobS2XlhuIqEc5mLAUu9Hd+1qxsQkQ50d0lzKrnDqPsM0WA9htkdJJw2nS\");");
        cc.addField(cfNew, "DatatypeConverter.parseBase64Binary(\"MIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAO0DidNibJHhtgxAnM9NszURYU25CVLAlwFdOWhiUkjrjOY459ObRZDVd35hQmN/cCLkDox7y2InJE6PDWfbx9BsgPmPvH75yKgPs3B8pClQVkgIpJp08R59hoZabYuvm7mxCyDGTl2lbrOi0a3j4vM5OoCWKQjIEZ28OpjTyCr3\");");
        CtConstructor cm = cc.getConstructor("([B)V");
        cm.insertBeforeBody("if(Arrays.equals($1,__h_ok)){$1=__h_nk;System.out.println(\"============================== agent working ==============================\");}");

        return cc.toBytecode();
    } catch (Exception e) {
        throw new IllegalClassFormatException(e.getMessage());
    }
}
 
Example #10
Source File: TestInstrumentation.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public byte[] transform(
        ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException {
    // Check if this class should be instrumented.
    if (!instrClassesTarget.contains(className)) {
        return null;
    }

    boolean isRedefinition = classBeingRedefined != null;
    log("instrument class(" + className + ") " + (isRedefinition ? "redef" : "load"));

    ClassReader reader = new ClassReader(bytes);
    ClassWriter writer = new ClassWriter(
            reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    CallbackClassVisitor classVisitor = new CallbackClassVisitor(writer);
    reader.accept(classVisitor, 0);
    instrClassesDone.add(className);
    return writer.toByteArray();
}
 
Example #11
Source File: EnhancingClassTransformerImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public byte[] transform(
		ClassLoader loader,
		String className,
		Class<?> classBeingRedefined,
		ProtectionDomain protectionDomain,
		byte[] classfileBuffer) throws IllegalClassFormatException {

	// The first design had the enhancer as a class variable. That approach had some goods and bads.
	// We don't had to create an enhancer for each class, but on the other end it would stay in memory forever.
	// It also assumed that all calls come from the same class loader, which is fair, but this makes it more robust.

	try {
		Enhancer enhancer = Environment.getBytecodeProvider().getEnhancer( new EnhancementContextWrapper( enhancementContext, loader ) );
		return enhancer.enhance( className, classfileBuffer );
	}
	catch (final Exception e) {
		throw new IllegalClassFormatException( "Error performing enhancement of " + className ) {
			@Override
			public synchronized Throwable getCause() {
				return e;
			}
		};
	}
}
 
Example #12
Source File: JavaClassFile.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
public JavaClassFile(ClassReader reader) throws IllegalClassFormatException {
    int magic = reader.readInt32();
    //第一位必须是 cafe babe
    if (magic != 0xCAFEBABE){
        throw new IllegalClassFormatException("is not a Java .class file");
    }
    this.minorVersion = reader.readUint16();
    this.majorVersion = JavaVersion.valueOf(reader.readUint16());
    this.constantPool = readConstantPool(reader);
    this.accessFlags = readAccessFlags(reader);
    this.thisClassIndex = reader.readUint16();
    this.superClassIndex = reader.readUint16();
    this.interfacesIndex = reader.readUint16s();
    this.fields = readMembers(reader);
    this.methods = readMembers(reader);
    this.attributes = readAttributes(reader);
    reader.close();
}
 
Example #13
Source File: WeavingTransformer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Apply transformation on a given class byte definition.
 * The method will always return a non-null byte array (if no transformation has taken place
 * the array content will be identical to the original one).
 * @param className the full qualified name of the class in dot format (i.e. some.package.SomeClass)
 * @param internalName class name internal name in / format (i.e. some/package/SomeClass)
 * @param bytes class byte definition
 * @param pd protection domain to be used (can be null)
 * @return (possibly transformed) class byte definition
 */
public byte[] transformIfNecessary(String className, String internalName, byte[] bytes, @Nullable ProtectionDomain pd) {
	byte[] result = bytes;
	for (ClassFileTransformer cft : this.transformers) {
		try {
			byte[] transformed = cft.transform(this.classLoader, internalName, null, pd, result);
			if (transformed != null) {
				result = transformed;
			}
		}
		catch (IllegalClassFormatException ex) {
			throw new IllegalStateException("Class file transformation failed", ex);
		}
	}
	return result;
}
 
Example #14
Source File: RedefineAnnotations.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override public byte[] transform(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    if (className.contains("TypeAnnotatedTestClass")) {
        try {
            // Here we remove and re-add the dummy fields. This shuffles the constant pool
            return asm(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
        } catch (Throwable e) {
            // The retransform native code that called this method does not propagate
            // exceptions. Instead of getting an uninformative generic error, catch
            // problems here and print it, then exit.
            e.printStackTrace();
            System.exit(1);
        }
    }
    return null;
}
 
Example #15
Source File: RedefineAnnotations.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override public byte[] transform(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    if (className.contains("TypeAnnotatedTestClass")) {
        try {
            // Here we remove and re-add the dummy fields. This shuffles the constant pool
            return asm(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
        } catch (Throwable e) {
            // The retransform native code that called this method does not propagate
            // exceptions. Instead of getting an uninformative generic error, catch
            // problems here and print it, then exit.
            e.printStackTrace();
            System.exit(1);
        }
    }
    return null;
}
 
Example #16
Source File: MonitorClassFileTransformer.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] transform(final String className,
                           final Class<?> classBeingRedefined,
                           final ProtectionDomain protectionDomain,
                           final byte[] classBytes) throws IllegalClassFormatException {
    if (!Objects.equal(className, monitorClassName)) {
        return null;
    }
    LOG.info("monitor class: {}", className);
    Lock lock = classFileBuffer.getLock();
    lock.lock();
    try {
        final ClassReader classReader = new ClassReader(classFileBuffer.getClassBuffer(classBeingRedefined, classBytes));
        final ClassWriter classWriter = new ClassWriter(computeFlag(classReader));
        final ClassVisitor classVisitor = new MonitorClassVisitor(new CheckClassAdapter(classWriter), methodName, methodDesc);
        classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
        byte[] bytes = classWriter.toByteArray();
        classFileBuffer.setClassBuffer(classBeingRedefined, bytes);
        return bytes;
    } finally {
        lock.unlock();
    }
}
 
Example #17
Source File: ExampleTransformer.java    From java-svc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
		ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
	if (probes.containsKey(className)) {
		try {
			ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
			TimingVisitor visitor = new TimingVisitor(classWriter, probes.get(className));
			ClassReader reader = new ClassReader(classfileBuffer);
			reader.accept(visitor, 0);
			return classWriter.toByteArray();
		} catch (Throwable t) {
			Logger.getLogger(getClass().getName()).log(Level.SEVERE,
					"Failed to instrument " + probes.get(className), t);
			return classfileBuffer;
		}
	} else {
		// Use the byte code as is...
		return null;
	}
}
 
Example #18
Source File: ExampleTransformerTests.java    From java-svc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
void testTransform() throws IOException, IllegalClassFormatException {
	List<TransformDescriptor> probes = ExampleAgent.readProbes(null);
	ExampleTransformer transformer = new ExampleTransformer(probes);
	byte[] originalClass = TestUtils.getByteCode(TestProgram.class);
	byte[] transformedClass = transformer.transform(TestProgram.class.getClassLoader(),
			Type.getInternalName(TestProgram.class), TestProgram.class, null, originalClass);
	assertNotNull(transformedClass);
	assertNotEquals(originalClass, transformedClass);

	
	StringWriter writer = new StringWriter();
	TraceClassVisitor visitor = new TraceClassVisitor(new PrintWriter(writer));
	CheckClassAdapter checkAdapter = new CheckClassAdapter(visitor);
	ClassReader reader = new ClassReader(transformedClass);
	reader.accept(checkAdapter, 0);
	String decompiledTransformedClass = writer.getBuffer().toString();
	// System.out.println(decompiledTransformedClass);
	assertNotNull(decompiledTransformedClass);
}
 
Example #19
Source File: ConfigurableClassLoader.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private byte[] doTransform(final String resourceName, final byte[] inBytes) {
    if (transformers.isEmpty()) {
        return inBytes;
    }
    byte[] bytes = inBytes;
    for (final ClassFileTransformer transformer : transformers) {
        try {
            bytes = transformer.transform(this, resourceName, null, null, bytes);
        } catch (final IllegalClassFormatException e) {
            log.error(e.getMessage() + ", will ignore the transformers", e);
            break;
        }
    }
    return bytes;
}
 
Example #20
Source File: DummyAgent.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String className,
                        Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
                        byte[] classfileBuffer) throws IllegalClassFormatException {

    /* The Daemon Thread bug is timing dependent and you want the transform method
     * to return ASAP - so just return the buffer will be fine
     */
    return classfileBuffer;
}
 
Example #21
Source File: RedefineIntrinsicTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (Intrinsic.class.equals(classBeingRedefined)) {
        String cf = new String(classfileBuffer);
        int i = cf.indexOf("intrinsic");
        Assert.assertTrue("cannot find \"intrinsic\" constant in " + Intrinsic.class.getSimpleName() + "'s class file", i > 0);
        System.arraycopy("redefined".getBytes(), 0, classfileBuffer, i, "redefined".length());
    }
    return classfileBuffer;
}
 
Example #22
Source File: ColaTransformer.java    From COLA with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String classFile, Class<?> classBeingRedefined,
                        ProtectionDomain protectionDomain, byte[] classFileBuffer)
    throws IllegalClassFormatException {
    try {
        // Lambda has no class file, no need to transform, just return.
        if (classFile == null){
            return EMPTY_BYTE_ARRAY;
        }

        final String className = toClassName(classFile);
        if(!className.equals(args.getClassName())){
            return classFileBuffer;
        }

        byte[] cacheByteCode = cacheMap.get(args.getKey());
        if(cacheByteCode != null){
            return cacheByteCode;
        }
        cacheByteCode = doTransform(loader, className, classFileBuffer).toBytecode();
        cacheMap.put(args.getKey(), cacheByteCode);
        return cacheByteCode;
    } catch (Throwable t) {
        t.printStackTrace();
        String msg = "Fail to transform class " + classFile + ", cause: " + t.toString();
        throw new IllegalStateException(msg, t);
    }
}
 
Example #23
Source File: RedefineAnnotations.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public byte[] asm(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    ClassWriter cw = new ClassWriter(0);
    ClassVisitor cv = new ReAddDummyFieldsClassVisitor(ASM5, cw) { };
    ClassReader cr = new ClassReader(classfileBuffer);
    cr.accept(cv, 0);
    return cw.toByteArray();
}
 
Example #24
Source File: KeyTransformer.java    From atlassian-agent with GNU General Public License v3.0 5 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (className == null) {
        return classfileBuffer;
    }

    if (className.equals(CN_KEY_SPEC)) {
        return handleKeySpec();
    }

    return classfileBuffer;
}
 
Example #25
Source File: ClassDumpTransformer.java    From arthas with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                        ProtectionDomain protectionDomain, byte[] classfileBuffer)
        throws IllegalClassFormatException {
    if (classesToEnhance.contains(classBeingRedefined)) {
        dumpClassIfNecessary(classBeingRedefined, classfileBuffer);
    }
    return null;
}
 
Example #26
Source File: Enhancer.java    From arthas with Apache License 2.0 5 votes vote down vote up
/**
 * 重置指定的Class
 *
 * @param inst             inst
 * @param classNameMatcher 类名匹配
 * @return 增强影响范围
 * @throws UnmodifiableClassException
 */
public static synchronized EnhancerAffect reset(final Instrumentation inst, final Matcher classNameMatcher)
        throws UnmodifiableClassException {

    final EnhancerAffect affect = new EnhancerAffect();
    final Set<Class<?>> enhanceClassSet = new HashSet<Class<?>>();

    for (Class<?> classInCache : classBytesCache.keySet()) {
        if (classNameMatcher.matching(classInCache.getName())) {
            enhanceClassSet.add(classInCache);
        }
    }

    final ClassFileTransformer resetClassFileTransformer = new ClassFileTransformer() {
        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            return null;
        }
    };

    try {
        enhance(inst, resetClassFileTransformer, enhanceClassSet);
        logger.info("Success to reset classes: " + enhanceClassSet);
    } finally {
        for (Class<?> resetClass : enhanceClassSet) {
            classBytesCache.remove(resetClass);
            affect.cCnt(1);
        }
    }

    return affect;
}
 
Example #27
Source File: AgentUtils.java    From arthas with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

    if (this.classLoader == loader && className.equals(this.className)) {
        return classBuffer;
    }

    return null;

}
 
Example #28
Source File: DummyAgent.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public byte[] transform(ClassLoader loader, String className,
                        Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
                        byte[] classfileBuffer) throws IllegalClassFormatException {

    /* The Daemon Thread bug is timing dependent and you want the transform method
     * to return ASAP - so just return the buffer will be fine
     */
    return classfileBuffer;
}
 
Example #29
Source File: RedefineAnnotations.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public byte[] asm(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    ClassWriter cw = new ClassWriter(0);
    ClassVisitor cv = new ReAddDummyFieldsClassVisitor(ASM5, cw) { };
    ClassReader cr = new ClassReader(classfileBuffer);
    cr.accept(cv, 0);
    return cw.toByteArray();
}
 
Example #30
Source File: RedefineLeak.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined,
    ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

    transformCount++;
    if (transformCount % 1000 == 0) System.out.println("transformCount:" + transformCount);
    return null;
}