java.lang.instrument.Instrumentation#appendToBootstrapClassLoaderSearch ( )源码实例Demo

下面列出了java.lang.instrument.Instrumentation#appendToBootstrapClassLoaderSearch ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TencentKona-8   文件: BasicTest.java
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.");
    }
}
 
源代码2 项目: BlockHound   文件: InstrumentationUtils.java
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));
}
 
源代码3 项目: jdk8u_jdk   文件: BasicTest.java
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.");
    }
}
 
源代码4 项目: javan-warty-pig   文件: AgentBootstrap.java
/**
 * 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);
  }
}
 
源代码5 项目: jdk8u-dev-jdk   文件: BasicTest.java
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.");
    }
}
 
源代码6 项目: openjdk-jdk9   文件: BasicTest.java
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.");
    }
}
 
源代码7 项目: jdk8u-jdk   文件: BasicTest.java
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.");
    }
}
 
源代码8 项目: jdk8u-jdk   文件: BasicTest.java
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.");
    }
}
 
源代码9 项目: hottub   文件: BasicTest.java
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.");
    }
}
 
源代码10 项目: openjdk-8   文件: BasicTest.java
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.");
    }
}
 
源代码11 项目: bistoury   文件: AgentBootstrap2.java
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);
}
 
源代码12 项目: glowroot   文件: ClassLoaders.java
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);
}
 
源代码13 项目: apm-agent-java   文件: AgentMain.java
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();
    }
}
 
源代码14 项目: kanela   文件: BootstrapInjector.java
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);
}
 
源代码15 项目: uavstack   文件: Iagent.java
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();
        }
    }
 
源代码16 项目: uavstack   文件: MOFAgent.java
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();
        }
    }
 
源代码17 项目: glowroot   文件: AgentPremain.java
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();
    }
}
 
源代码18 项目: opencensus-java   文件: AgentMain.java
/**
 * 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.");
}
 
源代码19 项目: glowroot   文件: MainEntryPoint.java
@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);
}
 
源代码20 项目: arthas   文件: TestHelper.java
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));
    
}