|
| 1 | +package datadog.trace.agent.tooling.bytebuddy; |
| 2 | + |
| 3 | +import static datadog.trace.bootstrap.AgentClassLoading.LOCATING_CLASS; |
| 4 | + |
| 5 | +import datadog.trace.agent.tooling.Utils; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.InputStream; |
| 8 | +import java.lang.ref.WeakReference; |
| 9 | +import net.bytebuddy.dynamic.ClassFileLocator; |
| 10 | +import net.bytebuddy.utility.StreamDrainer; |
| 11 | + |
| 12 | +/** |
| 13 | + * Locate resources with the loading classloader. Because of a quirk with the way classes appended |
| 14 | + * to the bootstrap classpath work, we first check our bootstrap proxy. If the loading classloader |
| 15 | + * cannot find the desired resource, check up the classloader hierarchy until a resource is found. |
| 16 | + */ |
| 17 | +public final class DDClassFileLocator extends WeakReference<ClassLoader> |
| 18 | + implements ClassFileLocator { |
| 19 | + |
| 20 | + public DDClassFileLocator(final ClassLoader classLoader) { |
| 21 | + super(classLoader); |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public Resolution locate(final String className) throws IOException { |
| 26 | + String resourceName = className.replace('.', '/') + ".class"; |
| 27 | + |
| 28 | + // try bootstrap first |
| 29 | + Resolution resolution = loadClassResource(Utils.getBootstrapProxy(), resourceName); |
| 30 | + ClassLoader cl = get(); |
| 31 | + |
| 32 | + // now go up the classloader hierarchy |
| 33 | + if (null == resolution && null != cl) { |
| 34 | + LOCATING_CLASS.begin(); |
| 35 | + try { |
| 36 | + do { |
| 37 | + resolution = loadClassResource(cl, resourceName); |
| 38 | + cl = cl.getParent(); |
| 39 | + } while (null == resolution && null != cl); |
| 40 | + } finally { |
| 41 | + LOCATING_CLASS.end(); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return resolution != null ? resolution : new Resolution.Illegal(className); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + public void close() { |
| 50 | + // nothing to close |
| 51 | + } |
| 52 | + |
| 53 | + private static Resolution loadClassResource( |
| 54 | + final ClassLoader classLoader, final String resourceName) throws IOException { |
| 55 | + try (InputStream in = classLoader.getResourceAsStream(resourceName)) { |
| 56 | + if (null != in) { |
| 57 | + return new Resolution.Explicit(StreamDrainer.DEFAULT.drain(in)); |
| 58 | + } |
| 59 | + return null; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments