下面列出了java.lang.instrument.Instrumentation#appendToBootstrapClassLoaderSearch ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
static void injectBootstrapClasses(Instrumentation instrumentation, String... classNames) throws IOException {
File tempJarFile = File.createTempFile("BlockHound", ".jar");
tempJarFile.deleteOnExit();
ClassLoader classLoader = BlockHound.class.getClassLoader();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(tempJarFile))) {
for (String className : classNames) {
String classFile = className.replace(".", "/") + ".class";
try (InputStream inputStream = classLoader.getResourceAsStream(classFile)) {
ZipEntry entry = new ZipEntry(classFile);
zipOutputStream.putNextEntry(entry);
ClassReader cr = new ClassReader(inputStream);
ClassWriter cw = new ClassWriter(cr, 0);
cr.accept(new MakePublicClassVisitor(cw), 0);
zipOutputStream.write(cw.toByteArray());
}
zipOutputStream.closeEntry();
}
}
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(tempJarFile));
}
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
/**
* Entry point for the agent. This concept was taken from
* <a href="https://github.com/google/allocation-instrumenter/blob/2de61ea4225ab0d75580b7341f39deb688f572c3/src/main/java/com/google/monitoring/runtime/instrumentation/Bootstrap.java.in">
* Google's Allocation Instrumenter
* </a>. It also adds this JAR in the bootstrap classpath
*/
public static void premain(String agentArgs, Instrumentation inst) {
try {
// Add JAR to bootstrap loader
java.net.URL url = ClassLoader.getSystemResource("jwp/agent");
JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
inst.appendToBootstrapClassLoaderSearch(jarFile);
// Invoke Agent::premain w/ runtime lookup
Class.forName("jwp.agent.Agent").
getDeclaredMethod("premain", String.class, Instrumentation.class).
invoke(null, agentArgs, inst);
} catch (Exception e) {
System.err.println("Unable to start agent: " + e);
throw new RuntimeException(e);
}
}
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
public static void main(String args[]) throws IOException {
JarFile bootclasses = new JarFile("BootSupport.jar");
JarFile agentclasses = new JarFile("AgentSupport.jar");
Instrumentation ins = Agent.getInstrumentation();
// Test 1: Add BootSupport.jar to boot class path and check that
// BootSupport is loaded by the bootstrap class loader
ins.appendToBootstrapClassLoaderSearch(bootclasses);
checkLoadedByLoader("BootSupport", null);
// Test 2: Add AgentSupport.jar to the system class path and check that
// AgentSupport is loaded by the system class loader.
try {
ins.appendToSystemClassLoaderSearch(agentclasses);
checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
} catch (UnsupportedOperationException x) {
System.out.println("System class loader does not support adding to class path");
}
// throw exception if a test failed
if (failures > 0) {
throw new RuntimeException(failures + " test(s) failed.");
}
}
private static ClassLoader getClassLoader(Instrumentation inst, List<File> spyJarFiles, File agentJarFile, final String libClass) throws Throwable {
// 将Spy添加到BootstrapClassLoader
for (File spyJarFile : spyJarFiles) {
inst.appendToBootstrapClassLoaderSearch(new JarFile(spyJarFile));
}
// 构造自定义的类加载器,尽量减少bistoury对现有工程的侵蚀
return loadOrDefineClassLoader(inst, agentJarFile, spyJarFiles, libClass);
}
static void defineClassesInBootstrapClassLoader(Collection<LazyDefinedClass> lazyDefinedClasses,
Instrumentation instrumentation, File generatedJarFile) throws IOException {
Closer closer = Closer.create();
try {
FileOutputStream out = closer.register(new FileOutputStream(generatedJarFile));
JarOutputStream jarOut = closer.register(new JarOutputStream(out));
generate(lazyDefinedClasses, jarOut);
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(generatedJarFile));
// appendToBootstrapClassLoaderSearch() line above does not add to the bootstrap resource
// search path, only to the bootstrap class search path (this is different from
// appendToSystemClassLoaderSearch() which adds to both the system resource search path and
// the system class search path)
//
// adding the generated jar file to the bootstrap resource search path is probably needed
// more generally, but it is at least needed to support jboss 4.2.0 - 4.2.3 because
// org.jboss.mx.loading.LoadMgr3.beginLoadTask() checks that the class loader has the class
// as a resource before loading it, so without adding the generated jar file to the
// bootstrap resource search path, jboss ends up throwing ClassNotFoundException for the
// glowroot generated classes that have been added to the bootstrap class loader search path
// (see issue #101 for more info on this particular jboss issue)
appendToBootstrapResourcePath(generatedJarFile);
}
public synchronized static void init(String agentArguments, Instrumentation instrumentation, boolean premain) {
if (Boolean.getBoolean("ElasticApm.attached")) {
// agent is already attached; don't attach twice
// don't fail as this is a valid case
// for example, Spring Boot restarts the application in dev mode
return;
}
String javaVersion = System.getProperty("java.version");
String javaVmName = System.getProperty("java.vm.name");
if (!isJavaVersionSupported(javaVersion, javaVmName)) {
// Gracefully abort agent startup is better than unexpected failure down the road when we known a given JVM
// version is not supported. Agent might trigger known JVM bugs causing JVM crashes, notably on early Java 8
// versions (but fixed in later versions), given those versions are obsolete and agent can't have workarounds
// for JVM internals, there is no other option but to use an up-to-date JVM instead.
System.err.println(String.format("Failed to start agent - JVM version not supported: %s", javaVersion));
return;
}
try {
// workaround for classloader deadlock https://bugs.openjdk.java.net/browse/JDK-8194653
FileSystems.getDefault();
final File agentJarFile = getAgentJarFile();
try (JarFile jarFile = new JarFile(agentJarFile)) {
instrumentation.appendToBootstrapClassLoaderSearch(jarFile);
}
// invoking via reflection to make sure the class is not loaded by the system classloader,
// but only from the bootstrap classloader
Class.forName("co.elastic.apm.agent.bci.ElasticApmAgent", true, null)
.getMethod("initialize", String.class, Instrumentation.class, File.class, boolean.class)
.invoke(null, agentArguments, instrumentation, agentJarFile, premain);
System.setProperty("ElasticApm.attached", Boolean.TRUE.toString());
} catch (Exception e) {
System.err.println("Failed to start agent");
e.printStackTrace();
}
}
public static void injectJar(Instrumentation instrumentation, String jarName) {
val jarFile = Jar.getEmbeddedJar(jarName + ".jar")
.onFailure(error -> Logger.error(error::getMessage, error))
.get();
instrumentation.appendToBootstrapClassLoaderSearch(jarFile);
}
public static void premain(String agentArgs, Instrumentation inst) {
String jarPath = "D:/creditRepository/ce-datamonitorsystem/com.creditease.uav.ttl/target/com.creditease.uav.ttl-2.1.0-agent.jar";
inst.addTransformer(new TtlTransformer());
try {
inst.appendToBootstrapClassLoaderSearch(new JarFile(jarPath));
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void installUAVjdk(Instrumentation inst, String extJdkLib) {
URL[] jdkJars = JarUtil.loadJars(extJdkLib);
try {
for (URL temp : jdkJars) {
inst.appendToBootstrapClassLoaderSearch(new JarFile(temp.getFile()));
}
}
catch (IOException e) {
// ignore
e.printStackTrace();
}
}
public static void premain(@SuppressWarnings("unused") String agentArgs,
Instrumentation instrumentation) {
try {
Class<?>[] allPriorLoadedClasses;
if (PRE_CHECK_LOADED_CLASSES) {
allPriorLoadedClasses = instrumentation.getAllLoadedClasses();
} else {
allPriorLoadedClasses = new Class<?>[0];
}
CodeSource codeSource = AgentPremain.class.getProtectionDomain().getCodeSource();
// suppress warnings is used instead of annotating this method with @Nullable
// just to avoid dependencies on other classes (in this case the @Nullable annotation)
@SuppressWarnings("argument.type.incompatible")
File glowrootJarFile = getGlowrootJarFile(codeSource);
Class<?> mainEntryPointClass;
if (glowrootJarFile != null) {
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(glowrootJarFile));
}
mainEntryPointClass = Class.forName("org.glowroot.agent.MainEntryPoint", true,
AgentPremain.class.getClassLoader());
Method premainMethod = mainEntryPointClass.getMethod("premain", Instrumentation.class,
Class[].class, File.class);
premainMethod.invoke(null, instrumentation, allPriorLoadedClasses, glowrootJarFile);
} catch (Throwable t) {
// log error but don't re-throw which would prevent monitored app from starting
System.err.println("Glowroot failed to start: " + t.getMessage());
t.printStackTrace();
}
}
/**
* Initializes the OpenCensus Agent for Java.
*
* @param agentArgs agent options, passed as a single string by the JVM
* @param instrumentation the {@link Instrumentation} object provided by the JVM for instrumenting
* Java programming language code
* @throws Exception if initialization of the agent fails
* @see java.lang.instrument
* @since 0.6
*/
public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception {
checkNotNull(instrumentation, "instrumentation");
logger.fine("Initializing.");
// The classes in bootstrap.jar, such as ContextManger and ContextStrategy, will be referenced
// from classes loaded by the bootstrap classloader. Thus, these classes have to be loaded by
// the bootstrap classloader, too.
instrumentation.appendToBootstrapClassLoaderSearch(
new JarFile(Resources.getResourceAsTempFile("bootstrap.jar")));
checkLoadedByBootstrapClassloader(ContextTrampoline.class);
checkLoadedByBootstrapClassloader(ContextStrategy.class);
Settings settings = Settings.load();
AgentBuilder agentBuilder =
new AgentBuilder.Default()
.disableClassFormatChanges()
.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
.with(new AgentBuilderListener())
.ignore(none());
for (Instrumenter instrumenter : ServiceLoader.load(Instrumenter.class)) {
agentBuilder = instrumenter.instrument(agentBuilder, settings);
}
agentBuilder.installOn(instrumentation);
logger.fine("Initialized.");
}
@EnsuresNonNull("startupLogger")
public static void initLogging(List<File> confDirs, File logDir,
@Nullable File loggingLogstashJarFile, @Nullable Instrumentation instrumentation)
throws IOException {
if (loggingLogstashJarFile != null && instrumentation != null) {
instrumentation
.appendToBootstrapClassLoaderSearch(new JarFile(loggingLogstashJarFile));
}
if (JavaVersion.isJava6() && "IBM J9 VM".equals(System.getProperty("java.vm.name"))
&& instrumentation != null) {
instrumentation.addTransformer(new IbmJ9Java6HackClassFileTransformer2());
}
for (File confDir : confDirs) {
File logbackXmlOverride = new File(confDir, "glowroot.logback.xml");
if (logbackXmlOverride.exists()) {
System.setProperty("glowroot.logback.configurationFile",
logbackXmlOverride.getAbsolutePath());
break;
}
}
String priorProperty = System.getProperty("glowroot.log.dir");
System.setProperty("glowroot.log.dir", logDir.getPath());
ClassLoader priorLoader = Thread.currentThread().getContextClassLoader();
// setting the context class loader to only load from bootstrap class loader (by specifying
// null parent class loader), otherwise logback will pick up and use a SAX parser on the
// system classpath because SAXParserFactory.newInstance() checks the thread context class
// loader for resource named META-INF/services/javax.xml.parsers.SAXParserFactory
// (see the xerces dependency in glowroot-agent-integration-tests for testing this)
Thread.currentThread().setContextClassLoader(new ClassLoader(null) {
// overriding getResourceAsStream() is needed for JDK 6 since it still manages to
// fallback and find the resource on the system class path otherwise
@Override
public @Nullable InputStream getResourceAsStream(String name) {
if (name.equals("META-INF/services/javax.xml.parsers.SAXParserFactory")) {
return new ByteArrayInputStream(new byte[0]);
}
return null;
}
});
try {
startupLogger = LoggerFactory.getLogger("org.glowroot");
} finally {
Thread.currentThread().setContextClassLoader(priorLoader);
if (priorProperty == null) {
System.clearProperty("glowroot.log.dir");
} else {
System.setProperty("glowroot.log.dir", priorProperty);
}
System.clearProperty("glowroot.logback.configurationFile");
// don't remove transformer in case the class is retransformed later
}
// TODO report checker framework issue that occurs without checkNotNull
checkNotNull(startupLogger);
}
public static void appendSpyJar(Instrumentation instrumentation) throws IOException {
// find spy target/classes directory
String file = TestHelper.class.getProtectionDomain().getCodeSource().getLocation().getFile();
File spyClassDir = new File(file, "../../../spy/target/classes").getAbsoluteFile();
File destJarFile = new File(file, "../../../spy/target/test-spy.jar").getAbsoluteFile();
ZipUtil.pack(spyClassDir, destJarFile);
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(destJarFile));
}