Search in sources :

Example 1 with IllegalClassFormatException

use of java.lang.instrument.IllegalClassFormatException in project tomcat by apache.

the class WebappClassLoaderBase method findClassInternal.

/**
     * Find specified class in local repositories.
     *
     * @param name The binary name of the class to be loaded
     *
     * @return the loaded class, or null if the class isn't found
     */
protected Class<?> findClassInternal(String name) {
    checkStateForResourceLoading(name);
    if (name == null) {
        return null;
    }
    String path = binaryNameToPath(name, true);
    ResourceEntry entry = resourceEntries.get(path);
    WebResource resource = null;
    if (entry == null) {
        resource = resources.getClassLoaderResource(path);
        if (!resource.exists()) {
            return null;
        }
        entry = new ResourceEntry();
        entry.lastModified = resource.getLastModified();
        // Add the entry in the local resource repository
        synchronized (resourceEntries) {
            // Ensures that all the threads which may be in a race to load
            // a particular class all end up with the same ResourceEntry
            // instance
            ResourceEntry entry2 = resourceEntries.get(path);
            if (entry2 == null) {
                resourceEntries.put(path, entry);
            } else {
                entry = entry2;
            }
        }
    }
    Class<?> clazz = entry.loadedClass;
    if (clazz != null)
        return clazz;
    synchronized (getClassLoadingLock(name)) {
        clazz = entry.loadedClass;
        if (clazz != null)
            return clazz;
        if (resource == null) {
            resource = resources.getClassLoaderResource(path);
        }
        if (!resource.exists()) {
            return null;
        }
        byte[] binaryContent = resource.getContent();
        Manifest manifest = resource.getManifest();
        URL codeBase = resource.getCodeBase();
        Certificate[] certificates = resource.getCertificates();
        if (transformers.size() > 0) {
            // If the resource is a class just being loaded, decorate it
            // with any attached transformers
            String className = name.endsWith(CLASS_FILE_SUFFIX) ? name.substring(0, name.length() - CLASS_FILE_SUFFIX.length()) : name;
            String internalName = className.replace(".", "/");
            for (ClassFileTransformer transformer : this.transformers) {
                try {
                    byte[] transformed = transformer.transform(this, internalName, null, null, binaryContent);
                    if (transformed != null) {
                        binaryContent = transformed;
                    }
                } catch (IllegalClassFormatException e) {
                    log.error(sm.getString("webappClassLoader.transformError", name), e);
                    return null;
                }
            }
        }
        // Looking up the package
        String packageName = null;
        int pos = name.lastIndexOf('.');
        if (pos != -1)
            packageName = name.substring(0, pos);
        Package pkg = null;
        if (packageName != null) {
            pkg = getPackage(packageName);
            // Define the package (if null)
            if (pkg == null) {
                try {
                    if (manifest == null) {
                        definePackage(packageName, null, null, null, null, null, null, null);
                    } else {
                        definePackage(packageName, manifest, codeBase);
                    }
                } catch (IllegalArgumentException e) {
                // Ignore: normal error due to dual definition of package
                }
                pkg = getPackage(packageName);
            }
        }
        if (securityManager != null) {
            // Checking sealing
            if (pkg != null) {
                boolean sealCheck = true;
                if (pkg.isSealed()) {
                    sealCheck = pkg.isSealed(codeBase);
                } else {
                    sealCheck = (manifest == null) || !isPackageSealed(packageName, manifest);
                }
                if (!sealCheck)
                    throw new SecurityException("Sealing violation loading " + name + " : Package " + packageName + " is sealed.");
            }
        }
        try {
            clazz = defineClass(name, binaryContent, 0, binaryContent.length, new CodeSource(codeBase, certificates));
        } catch (UnsupportedClassVersionError ucve) {
            throw new UnsupportedClassVersionError(ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name));
        }
        entry.loadedClass = clazz;
    }
    return clazz;
}
Also used : ClassFileTransformer(java.lang.instrument.ClassFileTransformer) WebResource(org.apache.catalina.WebResource) Manifest(java.util.jar.Manifest) CodeSource(java.security.CodeSource) URL(java.net.URL) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) Certificate(java.security.cert.Certificate)

Example 2 with IllegalClassFormatException

use of java.lang.instrument.IllegalClassFormatException in project jetty.project by eclipse.

the class WebAppClassLoaderTest method testClassFileTranslations.

@Test
public void testClassFileTranslations() throws Exception {
    final List<Object> results = new ArrayList<Object>();
    _loader.addTransformer(new ClassFileTransformer() {

        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            results.add(loader);
            byte[] b = new byte[classfileBuffer.length];
            for (int i = 0; i < classfileBuffer.length; i++) b[i] = (byte) (classfileBuffer[i] ^ 0xff);
            return b;
        }
    });
    _loader.addTransformer(new ClassFileTransformer() {

        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            results.add(className);
            byte[] b = new byte[classfileBuffer.length];
            for (int i = 0; i < classfileBuffer.length; i++) b[i] = (byte) (classfileBuffer[i] ^ 0xff);
            return b;
        }
    });
    _context.setParentLoaderPriority(false);
    assertCanLoadClass("org.acme.webapp.ClassInJarA");
    assertCanLoadClass("org.acme.webapp.ClassInJarB");
    assertCanLoadClass("org.acme.other.ClassInClassesC");
    assertCanLoadClass("java.lang.String");
    assertCantLoadClass("org.eclipse.jetty.webapp.Configuration");
    assertThat("Classname Results", results, contains(_loader, "org.acme.webapp.ClassInJarA", _loader, "org.acme.webapp.ClassInJarB", _loader, "org.acme.other.ClassInClassesC"));
}
Also used : ProtectionDomain(java.security.ProtectionDomain) ClassFileTransformer(java.lang.instrument.ClassFileTransformer) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) Test(org.junit.Test)

Example 3 with IllegalClassFormatException

use of java.lang.instrument.IllegalClassFormatException in project jersey by jersey.

the class PerfTestAgent method premain.

public static void premain(String agentArgs, Instrumentation instrumentation) {
    final String handlerClassName = (agentArgs != null && !agentArgs.isEmpty()) ? agentArgs.substring(0, agentArgs.lastIndexOf('.')) : HANDLER_CLASS_NAME;
    final String handlerMethodName = (agentArgs != null && !agentArgs.isEmpty()) ? agentArgs.substring(agentArgs.lastIndexOf('.') + 1) : HANDLER_METHOD_NAME;
    instrumentation.addTransformer(new ClassFileTransformer() {

        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {
            if (handlerClassName.replaceAll("\\.", "/").equals(className)) {
                try {
                    ClassPool cp = ClassPool.getDefault();
                    cp.appendSystemPath();
                    CtClass cc = cp.makeClass(new java.io.ByteArrayInputStream(bytes));
                    final CtField ctxField = CtField.make("public static final agent.metrics.Timer.Context agentTimerCtx;", cc);
                    final CtField registryField = CtField.make("public static final agent.metrics.MetricRegistry agentREG = new agent.metrics.MetricRegistry();", cc);
                    final CtField reporterField = CtField.make("public static final agent.metrics.JmxReporter agentReporter = agent.metrics.JmxReporter.forRegistry(agentREG).build();", cc);
                    final CtField timerField = CtField.make("public static final agent.metrics.Timer agentTimer = " + "agentREG.timer(agent.metrics.MetricRegistry.name(\"" + handlerClassName + "\", new String[] {\"" + handlerMethodName + "\"}));", cc);
                    cc.addField(registryField);
                    cc.addField(reporterField);
                    cc.addField(timerField);
                    cc.makeClassInitializer().insertAfter("agentReporter.start();");
                    CtMethod m = cc.getDeclaredMethod(handlerMethodName);
                    m.addLocalVariable("agentCtx", ctxField.getType());
                    m.insertBefore("agentCtx = agentTimer.time();");
                    m.insertAfter("agentCtx.stop();", true);
                    byte[] byteCode = cc.toBytecode();
                    cc.detach();
                    System.out.printf("Jersey Perf Agent Instrumentation Done! (instrumented method: %s)\n", m.getLongName());
                    return byteCode;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
    });
}
Also used : ProtectionDomain(java.security.ProtectionDomain) ClassFileTransformer(java.lang.instrument.ClassFileTransformer) ClassPool(javassist.ClassPool) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtClass(javassist.CtClass) CtField(javassist.CtField) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtMethod(javassist.CtMethod)

Example 4 with IllegalClassFormatException

use of java.lang.instrument.IllegalClassFormatException in project pinpoint by naver.

the class DefaultTranslator method customTransformer.

private byte[] customTransformer(String jvmClassName) {
    logger.info("Modify find classname:{}, loader:{}", jvmClassName, loader);
    MatchableClassFileTransformer transformer = transformerMap.get(jvmClassName);
    if (transformer == null) {
        return null;
    }
    logger.info("Modify jvmClassName:{},  modifier{}, loader:{}", jvmClassName, transformer, loader);
    final Thread thread = Thread.currentThread();
    final ClassLoader beforeClassLoader = thread.getContextClassLoader();
    thread.setContextClassLoader(loader);
    try {
        String javaClassName = JavaAssistUtils.jvmNameToJavaName(jvmClassName);
        byte[] transformBytes = transformer.transform(loader, javaClassName, null, null, null);
        return transformBytes;
    } catch (IllegalClassFormatException e) {
        throw new RuntimeException(jvmClassName + " transform fail", e);
    } finally {
        thread.setContextClassLoader(beforeClassLoader);
    }
}
Also used : MatchableClassFileTransformer(com.navercorp.pinpoint.profiler.plugin.MatchableClassFileTransformer) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException)

Example 5 with IllegalClassFormatException

use of java.lang.instrument.IllegalClassFormatException in project powermock by powermock.

the class PowerMockClassTransformer method transform.

public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (loader == null || shouldIgnore(className)) {
        return null;
    }
    try {
        String normalizedClassName = className.replace("/", ".");
        if (classesToTransform != null && classesToTransform.contains(normalizedClassName)) {
            ByteArrayInputStream is = new ByteArrayInputStream(classfileBuffer);
            CtClass ctClass = null;
            try {
                ctClass = ClassPool.getDefault().makeClass(is);
            } finally {
                is.close();
            }
            if (ctClass.isInterface()) {
                ctClass = INTERFACE_MOCK_TRANSFORMER.transform(ctClass);
            } else {
                ctClass = CLASS_MOCK_TRANSFORMER.transform(ctClass);
            }
            /*
                 * ClassPool may cause huge memory consumption if the number of CtClass
                 * objects becomes amazingly large (this rarely happens since Javassist
                 * tries to reduce memory consumption in various ways). To avoid this
                 * problem, you can explicitly remove an unnecessary CtClass object from
                 * the ClassPool. If you call detach() on a CtClass object, then that
                 * CtClass object is removed from the ClassPool.
                 */
            ctClass.detach();
            javaAgentClassRegister.registerClass(loader, normalizedClassName);
            return ctClass.toBytecode();
        }
        return null;
    } catch (Exception e) {
        throw new RuntimeException("Failed to redefine class " + className, e);
    }
}
Also used : CtClass(javassist.CtClass) ByteArrayInputStream(java.io.ByteArrayInputStream) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException)

Aggregations

IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)11 ClassFileTransformer (java.lang.instrument.ClassFileTransformer)7 ProtectionDomain (java.security.ProtectionDomain)4 MatchableClassFileTransformer (com.navercorp.pinpoint.profiler.plugin.MatchableClassFileTransformer)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 URLClassLoader (java.net.URLClassLoader)2 CtClass (javassist.CtClass)2 Test (org.junit.Test)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 String (java.lang.String)1 Field (java.lang.reflect.Field)1 URL (java.net.URL)1 CodeSource (java.security.CodeSource)1 Certificate (java.security.cert.Certificate)1 ArrayList (java.util.ArrayList)1 Manifest (java.util.jar.Manifest)1 ClassPool (javassist.ClassPool)1 CtField (javassist.CtField)1 CtMethod (javassist.CtMethod)1