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;
}
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"));
}
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;
}
});
}
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);
}
}
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);
}
}
Aggregations