Java Examples for java.lang.instrument.Instrumentation

The following java examples will help you to understand the usage of java.lang.instrument.Instrumentation. These source code samples are taken from different open source projects.

Example 1
Project: apmrouter-master  File: Agent.java View source code
/**
	 * The helios jagent entry point
	 * @param agentArgs The agent bootstrap arguments
	 * @param inst The Instrumentation instance
	 * @param codahaleNode The configuration node for codahale
	 */
public static void heliosBoot(String agentArgs, Instrumentation inst, Node codahaleNode) {
    premain(agentArgs, inst);
    inst.addTransformer(new InitializerLoggingAgent(), true);
    //packageNames
    Node packageNode = XMLHelper.getChildNodeByName(codahaleNode, "packages", false);
    if (packageNode != null) {
        String ps = XMLHelper.getNodeTextValue(packageNode);
        for (String s : ps.split(",")) {
            if (s.trim().isEmpty())
                continue;
            packageNames.add(s.trim());
        }
    }
    String jarUrl = XMLHelper.getAttributeByName(codahaleNode, "jar", null);
    codahaleTransformer = new CodahaleClassTransformer(packageNames, jarUrl);
    if (XMLHelper.getChildNodeByName(codahaleNode, "annotations", false) != null) {
        codahaleTransformer = new CodahaleClassTransformer(packageNames, jarUrl);
        instrumentation.addTransformer(codahaleTransformer, instrumentation.isRetransformClassesSupported());
        info("CodahaleClassTransformer Installed");
    }
    try {
        //Class.forName("org.helios.apmrouter.codahale.metrics.Metrics", true, ClassLoader.getSystemClassLoader());
        Class.forName("org.helios.apmrouter.codahale.metrics.Metrics");
    } catch (Throwable t) {
        error("Failed to load metric registry", t);
    }
}
Example 2
Project: GroovyMX-master  File: AgentInstrumentation.java View source code
/**
	 * The agent bootstrap entry point
	 * @param agentArgs The agent initialization arguments
	 * @param inst The instrumentation instance
	 */
public static void premain(String agentArgs, Instrumentation inst) {
    if (inst == null) {
        System.err.println("Agent install failed. Instrumentation was null. Stack trace follows:");
        new Throwable().fillInStackTrace().printStackTrace(System.err);
        return;
    }
    System.out.println("Loading AgentInstrumentation MBean");
    AgentInstrumentation ai = new AgentInstrumentation(inst);
    try {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        if (server.isRegistered(AGENT_INSTR_ON)) {
            server.unregisterMBean(AGENT_INSTR_ON);
        }
        server.registerMBean(ai, AGENT_INSTR_ON);
        System.out.println("AgentInstrumentation MBean Loaded");
    } catch (Exception e) {
        System.err.println("Agent install failed. AgentInstrumentation MBean could not be registered. Stack trace follows:");
        e.printStackTrace(System.err);
    }
}
Example 3
Project: dcevm-master  File: InstrumentationRedefiner.java View source code
public void redefineClasses(Map<Class<?>, byte[]> classes) throws ClassNotFoundException, UnmodifiableClassException {
    Instrumentation instrumentation = InstrumentationAgent.INSTRUMENTATION;
    if (instrumentation == null) {
        throw new IllegalStateException("Instrumentation agent is not properly installed!");
    }
    ClassDefinition[] definitions = new ClassDefinition[classes.size()];
    int i = 0;
    for (Map.Entry<Class<?>, byte[]> entry : classes.entrySet()) {
        definitions[i++] = new ClassDefinition(entry.getKey(), entry.getValue());
    }
    instrumentation.redefineClasses(definitions);
}
Example 4
Project: gjit-master  File: AgentTest.java View source code
@Override
public void run() {
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e1) {
    }
    Instrumentation i = Agent.getInstrumentation();
    byte[] bytes;
    try {
        bytes = TestClassDump.dump();
        ClassDefinition[] def = new ClassDefinition[1];
        def[0] = new ClassDefinition(TestClass.class, bytes);
        i.redefineClasses(def);
        System.out.println("done");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 5
Project: greys-anatomy-master  File: ThreadTopCommand.java View source code
@Override
public RowAffect action(Session session, Instrumentation inst, Printer printer) throws Throwable {
    final ArrayList<ThreadInfoData> threadInfoDatas = new ArrayList<ThreadInfoData>();
    long totalCpuTime = threadMXBean.getCurrentThreadCpuTime();
    for (ThreadInfo tInfo : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), Integer.MAX_VALUE)) {
        final long tId = tInfo.getThreadId();
        final String tName = tInfo.getThreadName();
        final long cpuTime = threadMXBean.getThreadCpuTime(tId);
        final String tStateStr = tInfo.getThreadState().toString();
        final String tStackStr = isDetail ? stackToString(tInfo.getStackTrace()) : StringUtils.EMPTY;
        totalCpuTime += cpuTime;
        threadInfoDatas.add(new ThreadInfoData(tId, cpuTime, tName, tStateStr, tStackStr));
    }
    final int topFix = top == null ? threadInfoDatas.size() : Math.min(top, threadInfoDatas.size());
    Collections.sort(threadInfoDatas);
    final TTable tTable = new TTable(isDetail ? new TTable.ColumnDefine[] { new TTable.ColumnDefine(TTable.Align.LEFT), new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(), new TTable.ColumnDefine(20), new TTable.ColumnDefine() } : new TTable.ColumnDefine[] { new TTable.ColumnDefine(TTable.Align.LEFT), new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(), new TTable.ColumnDefine(50) }).addRow("ID", "CPU%", "USR%", "STATE", "THREAD_NAME", "THREAD_STACK").padding(1);
    final DecimalFormat df = new DecimalFormat("00.00");
    for (int index = 0; index < topFix; index++) {
        final ThreadInfoData data = threadInfoDatas.get(index);
        if (StringUtils.isNotBlank(tid)) {
            final String fixTid = StringUtils.replace(tid, "#", "");
            if (!StringUtils.equals("" + data.tId, fixTid)) {
                continue;
            }
        }
        final String cpuTimeRateStr = (totalCpuTime > 0 ? df.format(data.cpuTime * 100d / totalCpuTime) : "00.00") + "%";
        tTable.addRow("#" + data.tId, cpuTimeRateStr, data.tStateStr, data.tName, data.stackStr);
    }
    printer.println(tTable.rendering()).finish();
    return new RowAffect(topFix);
}
Example 6
Project: Lucee-master  File: ExternalAgent.java View source code
private static void setInstrumentation(Instrumentation inst) {
    if (inst != null) {
        try {
            System.out.println("start set instrumentation");
            System.out.println(Thread.currentThread().getContextClassLoader().getClass().getName());
            System.out.println(ClassLoader.getSystemClassLoader().getClass().getName());
            System.out.println(new ExternalAgent().getClass().getClassLoader().getClass().getName());
            instrumentation = inst;
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
Example 7
Project: proxyhotswap-master  File: InstrumentationRedefiner.java View source code
public void redefineClasses(Map<Class<?>, byte[]> classes) throws ClassNotFoundException, UnmodifiableClassException {
    Instrumentation instrumentation = JavaProxyHotswapAgent.INSTRUMENTATION;
    if (instrumentation == null) {
        throw new IllegalStateException("Instrumentation agent is not properly installed!");
    }
    ClassDefinition[] definitions = new ClassDefinition[classes.size()];
    int i = 0;
    for (Map.Entry<Class<?>, byte[]> entry : classes.entrySet()) {
        definitions[i++] = new ClassDefinition(entry.getKey(), entry.getValue());
    }
    instrumentation.redefineClasses(definitions);
}
Example 8
Project: railo-master  File: InstrumentationFactory.java View source code
public static synchronized Instrumentation getInstance() {
    if (doInit) {
        doInit = false;
        Class agent = ClassUtil.loadClass("railo.runtime.instrumentation.Agent", null);
        if (agent == null) {
            SystemOut.printDate("missing class railo.runtime.instrumentation.Agent");
            return null;
        }
        // if Agent was loaded at startup there is already a Instrumentation
        inst = getInstrumentation(agent);
        // try to load Agent
        if (inst == null) {
            SystemOut.printDate("class railo.runtime.instrumentation.Agent.getInstrumentation() is not returning an Instrumentation");
            try {
                String id = getPid();
                String path = getResourcFromLib().getAbsolutePath();
                Class vmClass = ClassUtil.loadClass("com.sun.tools.attach.VirtualMachine");
                Object vmObj = attach(vmClass, id);
                loadAgent(vmClass, vmObj, path);
                detach(vmClass, vmObj);
            } catch (Throwable t) {
                return null;
            }
            inst = getInstrumentation(agent);
        }
        if (inst != null)
            SystemOut.printDate("java.lang.instrument.Instrumentation is used to reload class files");
    }
    return inst;
}
Example 9
Project: AribaWeb-Framework-master  File: JVMTIClient.java View source code
// hotswap (ClassDefinition[] defns, Boolean[]succeeded)
public void hotswap(ClassDefinition[] changes, Boolean[] succeeded) {
    Instrumentation instrumentation = Agent.getInstrumentation();
    if (!instrumentation.isRedefineClassesSupported()) {
        //TODO - should we fail ?
        return;
    }
    // try to reload them all
    try {
        instrumentation.redefineClasses(changes);
        for (int i = 0; i < changes.length; i++) succeeded[i] = true;
    } catch (Exception e) {
        if (changes.length == 1) {
            succeeded[0] = false;
        } else {
            for (int i = 0; i < changes.length; i++) {
                ClassDefinition[] change = new ClassDefinition[] { changes[i] };
                try {
                    instrumentation.redefineClasses(change);
                    succeeded[i] = true;
                } catch (Exception e2) {
                    succeeded[i] = false;
                }
            }
        }
    }
}
Example 10
Project: java-agent-asm-javassist-sample-master  File: Agent.java View source code
public static void premain(String agentArgs, Instrumentation inst) {
    inst.addTransformer(new ClassFileTransformer() {

        @Override
        public byte[] transform(ClassLoader classLoader, String s, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {
            if ("other/Stuff".equals(s)) {
                // ASM Code
                ClassReader reader = new ClassReader(bytes);
                ClassWriter writer = new ClassWriter(reader, 0);
                ClassPrinter visitor = new ClassPrinter(writer);
                reader.accept(visitor, 0);
                return writer.toByteArray();
            // Javassist
            //                    try {
            //                        ClassPool cp = ClassPool.getDefault();
            //                        CtClass cc = cp.get("other.Stuff");
            //                        CtMethod m = cc.getDeclaredMethod("run");
            //                        m.addLocalVariable("elapsedTime", CtClass.longType);
            //                        m.insertBefore("elapsedTime = System.currentTimeMillis();");
            //                        m.insertAfter("{elapsedTime = System.currentTimeMillis() - elapsedTime;"
            //                                + "System.out.println(\"Method Executed in ms: \" + elapsedTime);}");
            //                        byte[] byteCode = cc.toBytecode();
            //                        cc.detach();
            //                        return byteCode;
            //                    } catch (Exception ex) {
            //                        ex.printStackTrace();
            //                    }
            }
            return null;
        }
    });
}
Example 11
Project: lombok-intellij-plugin-master  File: IdeaPatcher.java View source code
static void runAgent(String agentArgs, Instrumentation instrumentation, boolean injected) throws Exception {
    IdeaPatcherOptionsHolder optionsHolder = IdeaPatcherOptionsHolder.getInstance();
    optionsHolder.addAll(agentArgs);
    for (IdeaPatcherTransformer transformer : KNOWN_TRANSFORMERS) {
        if (transformer.supported()) {
            instrumentation.addTransformer(transformer, transformer.canRetransform());
        }
    }
}
Example 12
Project: murex-coding-dojo-master  File: Agent.java View source code
public static void premain(final String agentArgs, Instrumentation inst) {
    Agent.inst = inst;
    System.out.printf("premain called");
    inst.addTransformer(new ClassFileTransformer() {

        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            ClassPool cp = ClassPool.getDefault();
            try {
                if (className.equals("Application")) {
                    final CtClass ctClass = cp.get("Application");
                    final CtMethod ctMethod = ctClass.getDeclaredMethod("hello");
                    ctMethod.insertBefore("return \"Bye\";");
                    classfileBuffer = ctClass.toBytecode();
                    ctClass.detach();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return classfileBuffer;
        }
    });
}
Example 13
Project: skysail-server-ext-master  File: OsgiMonitorAgent.java View source code
public static void premain(String agentArgs, Instrumentation inst) {
    logger.info("\n[Agent Setup]\n");
    createCommandListenerThread();
    logger.info("Starting instrumentation for profiling...");
    Callbacks callbacks = defineCallbacks();
    transformer = new OsgiFrameworkTransformer(ClassPool.getDefault(), callbacks, agentLogger);
    if (inst.isRetransformClassesSupported()) {
        inst.addTransformer(transformer, true);
    } else {
        logger.warn("Retransformation is not supported be the current JVM...");
        logger.warn("No osgi monitoring will be performed by skysail.server.ext.osgi.monitor.");
    }
}
Example 14
Project: support-examples-master  File: TestAgent.java View source code
public static void premain(String arg, Instrumentation inst) throws Exception {
    System.out.println("TestAgent's classloader: " + TestAgent.class.getClassLoader());
    System.out.println("System classloader:      " + ClassLoader.getSystemClassLoader());
    System.out.println("Loaded class:  " + Class.forName("org.jboss.logmanager.LogManager").getName());
    System.out.println("j.u.l.manager: " + System.getProperty("java.util.logging.manager"));
    log = Logger.getLogger(TestAgent.class.getName());
    log.info("GSS IS HERE: " + arg);
    log.info("Installed logmanager: " + LogManager.getLogManager().getClass().getName());
}
Example 15
Project: byte-buddy-master  File: ClassFileLocatorAgentBasedTest.java View source code
@Test
@AgentAttachmentRule.Enforce(retransformsClasses = true)
public void testExtraction() throws Exception {
    assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
    ClassFileLocator classFileLocator = ClassFileLocator.AgentBased.fromInstalledAgent(getClass().getClassLoader());
    ClassFileLocator.Resolution resolution = classFileLocator.locate(Foo.class.getName());
    assertThat(resolution.isResolved(), is(true));
    assertThat(resolution.resolve(), notNullValue(byte[].class));
}
Example 16
Project: java-virtual-machine-master  File: ClassFileLocatorAgentBasedTest.java View source code
@Test
@AgentAttachmentRule.Enforce(retransformsClasses = true)
public void testExtraction() throws Exception {
    assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
    ClassFileLocator classFileLocator = ClassFileLocator.AgentBased.fromInstalledAgent(getClass().getClassLoader());
    ClassFileLocator.Resolution resolution = classFileLocator.locate(Foo.class.getName());
    assertThat(resolution.isResolved(), is(true));
    assertThat(resolution.resolve(), notNullValue(byte[].class));
}
Example 17
Project: jubula.core-master  File: RCAgent.java View source code
/**
     * Creates the arguments array for AutServer, <br>
     * saves the current ClassLoader, <br>
     * calls the main-method of the AUTServerLauncher, <br>
     * reactivates the saved ClassLoader.
     * @param agentArguments String agentArguments
     * @param instrumentation a java.lang.instrument.Instrumentation instance
     * @throws ClassNotFoundException 
     * @throws NoSuchMethodException 
     * @throws SecurityException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @throws IllegalArgumentException 
     *              If reflection calls fail.
     * @throws MalformedURLException 
     *              If any entry of the AUT Server classpath cannot be 
     *              parsed to a URL.
     */
public static void premain(String agentArguments, Instrumentation instrumentation) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, MalformedURLException {
    String autServerClassPath = //$NON-NLS-1$
    System.getenv("AUT_SERVER_CLASSPATH");
    // create AutServer arguments
    String[] args = new String[Constants.MIN_ARGS_REQUIRED];
    //$NON-NLS-1$
    args[Constants.ARG_SERVERPORT] = System.getenv("AUT_SERVER_PORT");
    // placeholder
    //$NON-NLS-1$
    args[Constants.ARG_AUTMAIN] = "AutMain";
    args[Constants.ARG_AUTSERVER_CLASSPATH] = autServerClassPath;
    //$NON-NLS-1$
    args[Constants.ARG_AUTSERVER_NAME] = System.getenv("AUT_SERVER_NAME");
    // Aut Agent arguments
    args[Constants.ARG_REG_HOST] = System.getenv(AutConfigConstants.AUT_AGENT_HOST);
    args[Constants.ARG_REG_PORT] = System.getenv(AutConfigConstants.AUT_AGENT_PORT);
    args[Constants.ARG_AUT_NAME] = System.getenv(AutConfigConstants.AUT_NAME);
    // true for agent is activated
    args[Constants.ARG_AGENT_SET] = CommandConstants.RC_COMMON_AGENT_ACTIVE;
    String[] fileNames = autServerClassPath.split(//$NON-NLS-1$
    System.getProperty("path.separator"));
    URL[] urls = new URL[fileNames.length];
    for (int i = 0; i < fileNames.length; i++) {
        urls[i] = new File(fileNames[i]).toURL();
    }
    final ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        ClassLoader autServerLauncherLoader = new URLClassLoader(urls);
        Class<?> autServerLauncherClass = autServerLauncherLoader.loadClass(CommandConstants.AUT_SERVER_LAUNCHER);
        Method mainMethod = //$NON-NLS-1$
        autServerLauncherClass.getMethod("main", String[].class);
        mainMethod.invoke(null, new Object[] { args });
    } finally {
        Thread.currentThread().setContextClassLoader(oldContextClassLoader);
    }
}
Example 18
Project: allocation-tracker-master  File: AllocationProfilingAgent.java View source code
public static void premain(String agentArgs, Instrumentation inst) {
    String prefix = agentArgs;
    if (prefix == null || prefix.length() == 0) {
        AgentLogger.log("Agent failed to start: Please provide a package prefix to filter.");
        return;
    }
    // accepts both . and / notation, but will convert dots to slashes
    prefix = prefix.replace(".", "/");
    if (!prefix.contains("/")) {
        AgentLogger.log("Agent failed to start: Please provide at least one package level prefix to filter.");
        return;
    }
    registerMBean();
    inst.addTransformer(new AllocationTrackerClassFileTransformer(prefix));
}
Example 19
Project: excalibur-master  File: Core.java View source code
private void initForClassDataSourcefinal(final Instrumentation inst) {
    ReflectManager.Factory.initInstance(new ClassDataSource() {

        @Override
        public Collection<Class<?>> allLoadedClasses() {
            final Class<?>[] classArray = inst.getAllLoadedClasses();
            return null == classArray ? new ArrayList<Class<?>>() : Arrays.asList(classArray);
        }
    });
}
Example 20
Project: HiTune-master  File: InstrumentAgent.java View source code
/**
     * premain function will be called before the main function.
     * @param agentArguments
     * @param instrumentation
     */
public static void premain(String agentArguments, Instrumentation instrumentation) {
    conf = new AgentConf(agentArguments);
    //new all instrument threads
    instrumentthreads = new InstrumentThreadFactory(conf);
    //start all instrument threads
    instrumentthreads.start();
    //A shutdown-hook to clean up all instrument threads
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            //long start = System.currentTimeMillis();
            instrumentthreads.Cleanup();
        //long end = System.currentTimeMillis();
        //System.out.println("ClosedTime: " + (end - start));
        }
    });
}
Example 21
Project: jacoco-coverage-master  File: ModifiedSystemClassRuntime.java View source code
/**
	 * Creates a new {@link ModifiedSystemClassRuntime} using the given class as
	 * the data container. The given class must not have been loaded before by
	 * the agent.
	 * 
	 * @param inst
	 *            instrumentation interface
	 * @param className
	 *            VM name of the class to use
	 * @param accessFieldName
	 *            name of the added runtime access field
	 * @return new runtime instance
	 * 
	 * @throws ClassNotFoundException
	 *             id the given class can not be found
	 */
public static IRuntime createFor(final Instrumentation inst, final String className, final String accessFieldName) throws ClassNotFoundException {
    final ClassFileTransformer transformer = new ClassFileTransformer() {

        public byte[] transform(final ClassLoader loader, final String name, final Class<?> classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] source) throws IllegalClassFormatException {
            if (name.equals(className)) {
                return instrument(source, accessFieldName);
            }
            return null;
        }
    };
    inst.addTransformer(transformer);
    final Class<?> clazz = Class.forName(className.replace('/', '.'));
    inst.removeTransformer(transformer);
    try {
        clazz.getField(accessFieldName);
    } catch (final NoSuchFieldException e) {
        throw new RuntimeException(format("Class %s could not be instrumented.", className), e);
    }
    return new ModifiedSystemClassRuntime(clazz, accessFieldName);
}
Example 22
Project: jacoco-master  File: ModifiedSystemClassRuntime.java View source code
/**
	 * Creates a new {@link ModifiedSystemClassRuntime} using the given class as
	 * the data container. The given class must not have been loaded before by
	 * the agent.
	 * 
	 * @param inst
	 *            instrumentation interface
	 * @param className
	 *            VM name of the class to use
	 * @param accessFieldName
	 *            name of the added runtime access field
	 * @return new runtime instance
	 * 
	 * @throws ClassNotFoundException
	 *             id the given class can not be found
	 */
public static IRuntime createFor(final Instrumentation inst, final String className, final String accessFieldName) throws ClassNotFoundException {
    final ClassFileTransformer transformer = new ClassFileTransformer() {

        public byte[] transform(final ClassLoader loader, final String name, final Class<?> classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] source) throws IllegalClassFormatException {
            if (name.equals(className)) {
                return instrument(source, accessFieldName);
            }
            return null;
        }
    };
    inst.addTransformer(transformer);
    final Class<?> clazz = Class.forName(className.replace('/', '.'));
    inst.removeTransformer(transformer);
    try {
        clazz.getField(accessFieldName);
    } catch (final NoSuchFieldException e) {
        throw new RuntimeException(format("Class %s could not be instrumented.", className), e);
    }
    return new ModifiedSystemClassRuntime(clazz, accessFieldName);
}
Example 23
Project: JDBC-Performance-Logger-master  File: Agent.java View source code
private static void installAgent(final String agentArgs, final Instrumentation inst) {
    System.out.print(PREFIX + " Loading...");
    // final ByteBuddy byteBuddy = new ByteBuddy().with(Implementation.Context.Disabled.Factory.INSTANCE);
    //
    new AgentBuilder.Default().with(new AgentBuilder.Listener.Adapter() {

        @Override
        public void onError(final String typeName, final ClassLoader classLoader, final Throwable throwable) {
            System.err.println(PREFIX + " ERROR " + typeName);
            throwable.printStackTrace(System.err);
        }
    }).type(// .with(AgentBuilder.TypeStrategy.Default.REBASE)//
    ElementMatchers.isSubTypeOf(Driver.class).and(//
    ElementMatchers.noneOf(WrappingDriver.class))).transform(new AgentBuilder.Transformer() {

        @Override
        public Builder<?> transform(final Builder<?> builder, final TypeDescription typeDescription, final ClassLoader classLoader) {
            System.out.println(PREFIX + " Transforming " + typeDescription + " for interception");
            return //
            builder.method(//
            named("connect")).intercept(MethodDelegation.to(new DriverInterceptor()).filter(//
            ElementMatchers.isMethod().and(named("connect"))));
        }
    }).installOn(//
    inst);
    // TODO: intercept javax.sql.DataSource, javax.sql.PooledConnection.getConnection()...
    loaded = true;
    System.out.println("OK");
}
Example 24
Project: jdk7u-jdk-master  File: RedefineAgent.java View source code
// test transform and redefine for an attached agent
public static void testRedefine(Instrumentation inst) throws Exception {
    Class[] classes = inst.getAllLoadedClasses();
    for (Class k : classes) {
        if (k.getName().equals(targetName)) {
            throw new Exception("RedefineAgent Test error: class " + targetName + " has already been loaded.");
        }
    }
    inst.addTransformer(new RedefineAgent());
    ClassLoader.getSystemClassLoader().loadClass(targetName);
    classes = inst.getAllLoadedClasses();
    Class targetClass = null;
    for (Class k : classes) {
        if (k.getName().equals(targetName)) {
            targetClass = k;
            break;
        }
    }
    if (targetClass == null) {
        throw new Exception("RedefineAgent Test error: class " + targetName + " not loaded.");
    }
    if (classfilebytes == null) {
        throw new Exception("RedefineAgent Error(6439234): no transform call for class " + targetName);
    }
    ClassDefinition cd = new ClassDefinition(targetClass, classfilebytes);
    inst.redefineClasses(cd);
    System.out.println("RedefineAgent did redefine.");
    if (gotRedefineTransform) {
        System.out.println("RedefineAgent got redefine transform.");
    } else {
        throw new Exception("RedefineAgent Error(6439234): no transform call for redefine " + targetName);
    }
}
Example 25
Project: ManagedRuntimeInitiative-master  File: InstrumentationImpl.java View source code
// Attempt to load and start an agent
private void loadClassAndStartAgent(String classname, String methodname, String optionsString) throws Throwable {
    ClassLoader mainAppLoader = ClassLoader.getSystemClassLoader();
    Class<?> javaAgentClass = mainAppLoader.loadClass(classname);
    Method m = null;
    NoSuchMethodException firstExc = null;
    boolean twoArgAgent = false;
    try {
        m = javaAgentClass.getMethod(methodname, new Class[] { String.class, java.lang.instrument.Instrumentation.class });
        twoArgAgent = true;
    } catch (NoSuchMethodException x) {
        firstExc = x;
    }
    // check for the 1-arg method
    if (m == null) {
        try {
            m = javaAgentClass.getMethod(methodname, new Class[] { String.class });
        } catch (NoSuchMethodException x) {
            throw firstExc;
        }
    }
    // the premain method should not be required to be public,
    // make it accessible so we can call it
    setAccessible(m, true);
    // invoke the 1 or 2-arg method
    if (twoArgAgent) {
        m.invoke(null, new Object[] { optionsString, this });
    } else {
        m.invoke(null, new Object[] { optionsString });
    }
    // don't let others access a non-public premain method
    setAccessible(m, false);
}
Example 26
Project: monitoring-master  File: JavassistEngineTest.java View source code
private InstrumentEngine newJavassistEngine() {
    Instrumentation instrumentation = mock(Instrumentation.class);
    ObjectBinderFactory objectBinderFactory = mock(ObjectBinderFactory.class);
    Provider<ApiMetaDataService> apiMetaDataService = Providers.of(mock(ApiMetaDataService.class));
    InterceptorRegistryBinder binder = new TestInterceptorRegistryBinder();
    return new JavassistEngine(instrumentation, objectBinderFactory, binder, apiMetaDataService, null);
}
Example 27
Project: openjdk-master  File: InstrumentationImpl.java View source code
// Attempt to load and start an agent
private void loadClassAndStartAgent(String classname, String methodname, String optionsString) throws Throwable {
    ClassLoader mainAppLoader = ClassLoader.getSystemClassLoader();
    Class<?> javaAgentClass = mainAppLoader.loadClass(classname);
    Method m = null;
    NoSuchMethodException firstExc = null;
    boolean twoArgAgent = false;
    try {
        m = javaAgentClass.getDeclaredMethod(methodname, new Class<?>[] { String.class, java.lang.instrument.Instrumentation.class });
        twoArgAgent = true;
    } catch (NoSuchMethodException x) {
        firstExc = x;
    }
    if (m == null) {
        // now try the declared 1-arg method
        try {
            m = javaAgentClass.getDeclaredMethod(methodname, new Class<?>[] { String.class });
        } catch (NoSuchMethodException x) {
        }
    }
    if (m == null) {
        // now try the inherited 2-arg method
        try {
            m = javaAgentClass.getMethod(methodname, new Class<?>[] { String.class, java.lang.instrument.Instrumentation.class });
            twoArgAgent = true;
        } catch (NoSuchMethodException x) {
        }
    }
    if (m == null) {
        // finally try the inherited 1-arg method
        try {
            m = javaAgentClass.getMethod(methodname, new Class<?>[] { String.class });
        } catch (NoSuchMethodException x) {
            throw firstExc;
        }
    }
    // the premain method should not be required to be public,
    // make it accessible so we can call it
    // Note: The spec says the following:
    //     The agent class must implement a public static premain method...
    setAccessible(m, true);
    // invoke the 1 or 2-arg method
    if (twoArgAgent) {
        m.invoke(null, new Object[] { optionsString, this });
    } else {
        m.invoke(null, new Object[] { optionsString });
    }
}
Example 28
Project: openjdk8-jdk-master  File: RedefineAgent.java View source code
// test transform and redefine for an attached agent
public static void testRedefine(Instrumentation inst) throws Exception {
    Class[] classes = inst.getAllLoadedClasses();
    for (Class k : classes) {
        if (k.getName().equals(targetName)) {
            throw new Exception("RedefineAgent Test error: class " + targetName + " has already been loaded.");
        }
    }
    inst.addTransformer(new RedefineAgent());
    ClassLoader.getSystemClassLoader().loadClass(targetName);
    classes = inst.getAllLoadedClasses();
    Class targetClass = null;
    for (Class k : classes) {
        if (k.getName().equals(targetName)) {
            targetClass = k;
            break;
        }
    }
    if (targetClass == null) {
        throw new Exception("RedefineAgent Test error: class " + targetName + " not loaded.");
    }
    if (classfilebytes == null) {
        throw new Exception("RedefineAgent Error(6439234): no transform call for class " + targetName);
    }
    ClassDefinition cd = new ClassDefinition(targetClass, classfilebytes);
    inst.redefineClasses(cd);
    System.out.println("RedefineAgent did redefine.");
    if (gotRedefineTransform) {
        System.out.println("RedefineAgent got redefine transform.");
    } else {
        throw new Exception("RedefineAgent Error(6439234): no transform call for redefine " + targetName);
    }
}
Example 29
Project: org.intrace-master  File: AgentInit.java View source code
/**
   * Common init function.
   *
   * @param agentArgs
   * @param inst
   */
public static void initialize(String agentArgs, Instrumentation inst) {
    System.out.println("## Loaded InTrace Agent.");
    if (agentArgs == null) {
        agentArgs = "";
    }
    // Setup the trace instrumentation handler
    AgentHelper.setInstrumentationHandler(TraceHandler.INSTANCE);
    // Parse startup args
    AgentSettings args = new AgentSettings(agentArgs);
    AgentHelper.getResponses(null, agentArgs);
    // Construct Transformer
    ClassTransformer t = new ClassTransformer(inst, args);
    inst.addTransformer(t, inst.isRetransformClassesSupported());
    // Ensure loaded classes are traced
    t.instrumentKlasses(t.getLoadedClassesForModification());
    // Start Server thread
    new AgentServer(t, args.getServerPort()).start();
    // Store server port
    waitForServerPort();
    args.setActualServerPort(serverPort);
    // Wait for callback connection
    if (args.getCallbackPort() > -1) {
        System.out.println("## Establishing Callback Connection...");
        doCallbackConnection(args.getCallbackPort(), t);
    }
    // Wait for startup
    if (args.isWaitStart()) {
        try {
            System.out.println("## Program Paused");
            AgentServer.waitForStartSignal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    // Setup shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            AgentHelper.gracefulShutdown();
        }
    });
}
Example 30
Project: pinpoint-master  File: JavassistEngineTest.java View source code
private InstrumentEngine newJavassistEngine() {
    Instrumentation instrumentation = mock(Instrumentation.class);
    ObjectBinderFactory objectBinderFactory = mock(ObjectBinderFactory.class);
    Provider<ApiMetaDataService> apiMetaDataService = Providers.of(mock(ApiMetaDataService.class));
    InterceptorRegistryBinder binder = new TestInterceptorRegistryBinder();
    return new JavassistEngine(instrumentation, objectBinderFactory, binder, apiMetaDataService, null);
}
Example 31
Project: rife-master  File: ContinuationsAgent.java View source code
public static void premain(String agentArguments, Instrumentation instrumentation) {
    if (null == agentArguments)
        throw new IllegalArgumentException("expecting the fully qualified class name of a ContinuationConfigInstrument class");
    ContinuationConfigInstrument config = null;
    try {
        Class config_class = Class.forName(agentArguments);
        config = (ContinuationConfigInstrument) config_class.newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Unexpected error while creating an instance of the instrumentation configuration with class name '" + agentArguments + "'", e);
    }
    System.getProperties().setProperty(AGENT_ACTIVE_PROPERTY, Boolean.TRUE.toString());
    instrumentation.addTransformer(new InitialTransformer());
    instrumentation.addTransformer(new ContinuationsTransformer(config));
    instrumentation.addTransformer(new FinalTransformer());
}
Example 32
Project: scout-master  File: JavaModule.java View source code
@Override
public Dispatcher run() {
    try {
        Class<?> module = Class.forName("java.lang.reflect.Module");
        return new Dispatcher.Enabled(Class.class.getMethod("getModule"), module.getMethod("getClassLoader"), module.getMethod("isNamed"), module.getMethod("getName"), module.getMethod("getResourceAsStream", String.class), module.getMethod("canRead", module), Instrumentation.class.getMethod("redefineModule", module, Set.class, Map.class, Map.class, Set.class, Map.class));
    } catch (Exception ignored) {
        return Dispatcher.Disabled.INSTANCE;
    }
}
Example 33
Project: scouter-master  File: JavaModule.java View source code
@Override
public Dispatcher run() {
    try {
        Class<?> module = Class.forName("java.lang.reflect.Module");
        return new Dispatcher.Enabled(Class.class.getMethod("getModule"), module.getMethod("getClassLoader"), module.getMethod("isNamed"), module.getMethod("getName"), module.getMethod("getResourceAsStream", String.class), module.getMethod("canRead", module), Instrumentation.class.getMethod("redefineModule", module, Set.class, Map.class, Map.class, Set.class, Map.class));
    } catch (Exception ignored) {
        return Dispatcher.Disabled.INSTANCE;
    }
}
Example 34
Project: Scribengin-master  File: PremainBootstrap.java View source code
public static void premain(String pluginPath, Instrumentation inst) throws Exception {
    ClassLoader oldClassloader = Thread.currentThread().getContextClassLoader();
    try {
        Properties props = new Properties();
        props.load(new FileInputStream(pluginPath + "/agent.properties"));
        String pluginClassName = props.getProperty("plugin.class");
        boolean newClassloader = "true".equalsIgnoreCase(props.getProperty("plugin.classloader.isolate"));
        ClassLoader cl = null;
        if (newClassloader) {
            File pluginDir = new File(pluginPath);
            List<URL> jars = new ArrayList<URL>();
            for (File sel : pluginDir.listFiles()) {
                String name = sel.getName();
                if (name.endsWith(".jar")) {
                    URL url = new URL("file:" + sel.getCanonicalPath());
                    jars.add(url);
                    System.out.println("add jar: " + url);
                }
            }
            URL[] jarPaths = new URL[jars.size()];
            jarPaths = jars.toArray(jarPaths);
            cl = new URLClassLoader(jarPaths, Thread.currentThread().getContextClassLoader());
        } else {
            cl = Thread.currentThread().getContextClassLoader();
        }
        Thread.currentThread().setContextClassLoader(cl);
        Class<BootstrapAgentPlugin> pluginClass = (Class<BootstrapAgentPlugin>) cl.loadClass(pluginClassName);
        BootstrapAgentPlugin plugin = pluginClass.newInstance();
        props.remove("plugin.class");
        props.remove("plugin.classloader.isolate");
        plugin.run(props, inst);
    } finally {
        Thread.currentThread().setContextClassLoader(oldClassloader);
    }
}
Example 35
Project: unitprofiler-master  File: ProfilingExprEditor.java View source code
@Override
public void edit(NewExpr newExpression) throws CannotCompileException {
    logger.warn(" >>> NewExpr: {}, line {}, {}", new Object[] { newExpression.getEnclosingClass().getName(), newExpression.getLineNumber(), newExpression.getSignature() });
    try {
        CtConstructor constructor = newExpression.getConstructor();
        CtClass ctClass = constructor.getDeclaringClass();
        MethodDescriptor methodDescriptor = new MethodDescriptor(newExpression);
        if (classTransformer.isAlreadyInstrumented(methodDescriptor)) {
            return;
        }
        classTransformer.addInstrumentation(methodDescriptor);
        if (ctClass.isFrozen()) {
            logger.warn("'{}' is 'frozen'", ctClass.getName());
            return;
        }
        instrument(constructor, ctClass, methodDescriptor);
        Transformation transformation = classTransformer.getTransformation(ctClass.getName());
        if (transformation != null) {
            java.lang.instrument.Instrumentation javainstrumentation = classTransformer.getInstrumentation();
            ProfilingClassFileTransformer localTransformer = new ProfilingClassFileTransformer(javainstrumentation);
            javainstrumentation.addTransformer(localTransformer, true);
            Class<?> cls1 = Class.forName(ctClass.getName());
            ClassDefinition classDefinition = new ClassDefinition(cls1, ctClass.toBytecode());
            javainstrumentation.redefineClasses(classDefinition);
            javainstrumentation.removeTransformer(localTransformer);
        }
    } catch (Exception e1) {
        logger.error(e1.getMessage(), e1);
    }
}
Example 36
Project: Log4jJMXSupportAgentDelegate-master  File: Log4jJmxSupportAgentDelegate.java View source code
/**
	 * This method is called by the general agent {@code com.hapiware.agent.Agent} and
	 * is done before the main method call right after the JVM initialisation. 
	 * <p>
	 * <b>Notice</b> the difference between this method and 
	 * the {@code public static void premain(String, Instrumentation} method described in
	 * {@code java.lang.instrument} package. 
	 *
	 * @param includePatterns
	 * 		A list of patterns to include classes for instrumentation.
	 * 
	 * @param excludePatterns
	 * 		A list patterns to set classes not to be instrumented.
	 * 
	 * @param config
	 * 		Not used.
	 * 
	 * @param instrumentation
	 * 		See {@link java.lang.instrument.Instrumentation}
	 * 
	 * @throws IllegalArgumentException
	 * 		If there is something wrong with the configuration file.
	 *
	 * @see java.lang.instrument
	 */
public static void premain(Pattern[] includePatterns, Pattern[] excludePatterns, Object config, Instrumentation instrumentation) {
    try {
        instrumentation.addTransformer(new Log4jJmxSupportTransformer(includePatterns, excludePatterns));
    } catch (Exception e) {
        System.err.println("Couldn't start the Log4jJmxSupport agent delegate due to an exception. " + e.getMessage());
        e.printStackTrace();
    }
}
Example 37
Project: openjpa-master  File: ClassRedefiner.java View source code
/**
     * For each element in <code>classes</code>, this method will redefine
     * all the element's methods such that field accesses are intercepted
     * in-line. If {@link #canRedefineClasses()} returns <code>false</code>,
     * this method is a no-op.
     */
public static void redefineClasses(OpenJPAConfiguration conf, final Map<Class<?>, byte[]> classes) {
    Log log = conf.getLog(OpenJPAConfiguration.LOG_ENHANCE);
    if (classes == null || classes.size() == 0 || !canRedefineClasses(log))
        return;
    Instrumentation inst = null;
    ClassFileTransformer t = null;
    try {
        inst = InstrumentationFactory.getInstrumentation(log);
        Class<?>[] array = classes.keySet().toArray(new Class[classes.size()]);
        if (JavaVersions.VERSION >= 6) {
            log.trace(_loc.get("retransform-types", classes.keySet()));
            t = new ClassFileTransformer() {

                public byte[] transform(ClassLoader loader, String clsName, Class<?> classBeingRedefined, ProtectionDomain pd, byte[] classfileBuffer) {
                    return classes.get(classBeingRedefined);
                }
            };
            // these are Java 6 methods, and we don't have a Java 6 build
            // module yet. The cost of reflection here is negligible
            // compared to the redefinition / enhancement costs in total,
            // so this should not be a big problem.
            Method meth = inst.getClass().getMethod("addTransformer", new Class[] { ClassFileTransformer.class, boolean.class });
            meth.invoke(inst, new Object[] { t, true });
            meth = inst.getClass().getMethod("retransformClasses", new Class[] { array.getClass() });
            meth.invoke(inst, new Object[] { array });
        } else {
            log.trace(_loc.get("redefine-types", classes.keySet()));
            // in a Java 5 context, we can use class redefinition instead
            ClassDefinition[] defs = new ClassDefinition[array.length];
            for (int i = 0; i < defs.length; i++) defs[i] = new ClassDefinition(array[i], classes.get(array[i]));
            inst.redefineClasses(defs);
        }
    } catch (Exception e) {
        throw new InternalException(e);
    } finally {
        if (inst != null && t != null)
            inst.removeTransformer(t);
    }
}
Example 38
Project: AIM-master  File: JmsMessageSizeProbe.java View source code
/**
	 * Before part for JMS onMessage method.
	 */
@ProbeBeforePart(requiredMethodName = "onMessage(javax.jms.Message")
public void onMessageBeforePart() {
    try {
        if (((Message) __parameter[1]).propertyExists(JmsCommunicationProbe.MSG_CORRELATION_VARIABLE)) {
            _JmsMessageSizeProbe_instrumentationObject = System.getProperties().get(J_INSTRUMENTATION_KEY);
            _JmsMessageSizeProbe_record = new JmsMessageSizeRecord();
            _JmsMessageSizeProbe_record.setTimeStamp(_GenericProbe_startTime);
            _JmsMessageSizeProbe_record.setCallId(_GenericProbe_callId);
            _JmsMessageSizeProbe_instrumentation = (Instrumentation) _JmsMessageSizeProbe_instrumentationObject;
            _JmsMessageSizeProbe_record.setSize(_JmsMessageSizeProbe_instrumentation.getObjectSize(__parameter[1]));
            _JmsMessageSizeProbe_record.setBodySize(_JmsMessageSizeProbe_instrumentation.getObjectSize(((TextMessage) __parameter[1]).getText()));
            _JmsMessageSizeProbe_correlationValue = ((Message) __parameter[1]).getStringProperty(JmsCommunicationProbe.MSG_CORRELATION_VARIABLE);
            _JmsMessageSizeProbe_record.setMessageCorrelationHash(_JmsMessageSizeProbe_correlationValue);
            _GenericProbe_collector.newRecord(_JmsMessageSizeProbe_record);
        }
    } catch (Exception e) {
        _JmsMessageSizeProbe_record = null;
    }
}
Example 39
Project: Deadlock-Preventer-master  File: PreMain.java View source code
public static void premain(String agentArguments, Instrumentation instrumentation) {
    Analyzer.instance().activate();
    Transformer transformer = new Transformer();
    instrumentation.addTransformer(transformer, true);
    InputStream stream = PreMain.class.getResourceAsStream("config.ini");
    if (stream != null) {
        ArrayList<String> classesToInstrument = new ArrayList<String>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        try {
            String line = reader.readLine();
            while (line != null) {
                line = line.trim();
                if (!line.startsWith("##")) {
                    String arguments[] = line.split(" ");
                    if (arguments.length < 4) {
                        System.out.println("invalid arguments in config.ini: " + line);
                        System.out.println("usage: mode classname methodname signature [unscoped]");
                        System.out.println(" where 'mode' is one of: L U L(n) U(n)");
                        System.out.println(" 'unscoped' indicates that the object is not used for locking a scope, but for signaling");
                    } else {
                        String mode = arguments[0];
                        String className = arguments[1];
                        String methodName = arguments[2];
                        String signature = arguments[3];
                        int modeInt = parseMode(mode);
                        boolean unscoped = arguments.length > 4 && arguments[4].equals("unscoped");
                        transformer.register(modeInt, className, methodName, signature, unscoped);
                        if (!classesToInstrument.contains(className))
                            classesToInstrument.add(className);
                    }
                }
                line = reader.readLine();
            }
        } catch (IOException e) {
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
        for (String classToInstrument : classesToInstrument) {
            try {
                Class<?> cls = Class.forName(classToInstrument.replace('/', '.'));
                instrumentation.retransformClasses(cls);
            } catch (RuntimeException e) {
            } catch (ClassNotFoundException e) {
            } catch (UnmodifiableClassException e) {
                e.printStackTrace();
            }
        }
    }
    Analyzer.instance().enable();
}
Example 40
Project: Diorite-master  File: AddClinitClassFileTransformer.java View source code
@Nullable
@Override
public byte[] transform(Controller controller, Instrumentation instr, Module module, @Nullable ClassLoader loader, String className, @Nullable Class<?> clazz, ProtectionDomain pd, byte[] bytecode) throws IllegalClassFormatException {
    // skip basic java classes
    if (loader == null) {
        return null;
    }
    ClassReader cr = new ClassReader(bytecode);
    ClassWriter cw = new ClassWriter(0);
    ClinitClassVisitor classVisitor = new ClinitClassVisitor(cw);
    cr.accept(classVisitor, 0);
    if (!classVisitor.added) {
        return null;
    }
    return cw.toByteArray();
}
Example 41
Project: EasyMPermission-master  File: AgentLauncher.java View source code
public static void runAgents(String agentArgs, Instrumentation instrumentation, boolean injected, Class<?> launchingContext) throws Throwable {
    for (AgentInfo info : AGENTS) {
        try {
            Class<?> agentClass = Class.forName(info.className());
            AgentLaunchable agent = (AgentLaunchable) agentClass.newInstance();
            agent.runAgent(agentArgs, instrumentation, injected, launchingContext);
        } catch (Throwable t) {
            info.problem(t, instrumentation);
        }
    }
}
Example 42
Project: evosuite-master  File: Agent.java View source code
/**
	 * @param args
	 */
public static void premain(final String agentArgs, final Instrumentation inst) {
    Configuration.INSTANCE.initLogger();
    LOG.debug("starting agent with with args={}", agentArgs);
    try {
        try {
            if (!Capturer.isCapturing()) {
                Capturer.startCapture(agentArgs);
            }
        } catch (CapturerException e) {
            LOG.error(e.getMessage(), e);
            throw new Error(e);
        }
        final Transformer trans = new Transformer(agentArgs.split("\\s+"));
        // install our class transformer which performs the instrumentation
        inst.addTransformer(trans);
    } catch (Throwable t) {
        LOG.error("an errorr occurred while executing agent (premain)", t);
    }
}
Example 43
Project: glowroot-master  File: CentralGlowrootAgentInit.java View source code
@Override
public void init(final File glowrootDir, final File agentDir, @Nullable final String collectorAddress, @Nullable final Collector customCollector, final Map<String, String> properties, @Nullable final Instrumentation instrumentation, final String glowrootVersion, boolean offline) throws Exception {
    agentDirLockingCloseable = AgentDirLocking.lockAgentDir(agentDir);
    Ticker ticker = Tickers.getTicker();
    Clock clock = Clock.systemClock();
    // need to perform jrebel workaround prior to loading any jackson classes
    JRebelWorkaround.performWorkaroundIfNeeded();
    final PluginCache pluginCache = PluginCache.create(glowrootDir, false);
    final ConfigService configService = ConfigService.create(agentDir, pluginCache.pluginDescriptors());
    final CollectorProxy collectorProxy = new CollectorProxy();
    CollectorLogbackAppender collectorLogbackAppender = new CollectorLogbackAppender(collectorProxy);
    collectorLogbackAppender.setName(CollectorLogbackAppender.class.getName());
    collectorLogbackAppender.setContext((Context) LoggerFactory.getILoggerFactory());
    collectorLogbackAppender.start();
    attachAppender(collectorLogbackAppender);
    // need to delay creation of the scheduled executor until instrumentation is set up
    Supplier<ScheduledExecutorService> backgroundExecutorSupplier = createBackgroundExecutorSupplier();
    final AgentModule agentModule = new AgentModule(clock, ticker, pluginCache, configService, backgroundExecutorSupplier, collectorProxy, instrumentation, agentDir);
    final ScheduledExecutorService backgroundExecutor = backgroundExecutorSupplier.get();
    final AgentConfigUpdater agentConfigUpdater = new ConfigUpdateService(configService, pluginCache);
    NettyWorkaround.run(instrumentation, new NettyInit() {

        @Override
        public void execute(boolean newThread) throws Exception {
            Collector collector;
            if (customCollector == null) {
                centralCollector = new CentralCollector(properties, checkNotNull(collectorAddress), agentModule.getLiveJvmService(), agentModule.getLiveWeavingService(), agentModule.getLiveTraceRepository(), agentConfigUpdater);
                collector = centralCollector;
            } else {
                collector = customCollector;
            }
            collectorProxy.setInstance(collector);
            collector.init(glowrootDir, agentDir, EnvironmentCreator.create(glowrootVersion), configService.getAgentConfig(), agentConfigUpdater);
        }
    });
    this.agentModule = agentModule;
    this.backgroundExecutor = backgroundExecutor;
}
Example 44
Project: gpu-garbage-collection-master  File: AgentX.java View source code
public static void premain(final String args, final Instrumentation instrumentation) {
    System.out.println("Running premain with args: " + args);
    System.out.println("Adding class transformer");
    instrumentation.addTransformer(new AgentX());
    final Object[] array = new Object[10];
    final Object object = new Object();
    long arraySize = instrumentation.getObjectSize(array);
    long objectSize = instrumentation.getObjectSize(object);
    // Conservatively assume sizeof(Object) > 0 and sizeof(array) >= array.length
    System.out.println("Array size ok: " + (arraySize >= array.length));
    System.out.println("Object size ok: " + (objectSize > 0));
    System.out.println("AgentX in initiated classes? " + findClass(instrumentation.getInitiatedClasses(AgentX.class.getClassLoader()), AgentX.class));
    System.out.println("AgentX in all classes? " + findClass(instrumentation.getAllLoadedClasses(), AgentX.class));
}
Example 45
Project: HeraJVM-master  File: AgentX.java View source code
public static void premain(final String args, final Instrumentation instrumentation) {
    System.out.println("Running premain with args: " + args);
    System.out.println("Adding class transformer");
    instrumentation.addTransformer(new AgentX());
    final Object[] array = new Object[10];
    final Object object = new Object();
    long arraySize = instrumentation.getObjectSize(array);
    long objectSize = instrumentation.getObjectSize(object);
    // Conservatively assume sizeof(Object) > 0 and sizeof(array) >= array.length
    System.out.println("Array size ok: " + (arraySize >= array.length));
    System.out.println("Object size ok: " + (objectSize > 0));
    System.out.println("AgentX in initiated classes? " + findClass(instrumentation.getInitiatedClasses(AgentX.class.getClassLoader()), AgentX.class));
    System.out.println("AgentX in all classes? " + findClass(instrumentation.getAllLoadedClasses(), AgentX.class));
}
Example 46
Project: instrumentj-master  File: Main.java View source code
/**
     *
     * @param args
     * @param instrumentation
     */
public static void agentmain(final String args, final Instrumentation instrumentation) throws Exception {
    profilerController = new ProfilerControllerImpl(instrumentation);
    StaticProfilerInterface.initialize(profilerController);
    profilerController.initialize();
    final Binding binding = new Binding();
    binding.setProperty("profiler", StaticProfilerInterface.INSTANCE.getProfiler());
    shellServer = new ShellServer(7000, binding);
    shell.execute(shellServer);
}
Example 47
Project: intellij-coverage-master  File: CoveragePremain.java View source code
public static void premain(String argsString, Instrumentation instrumentation) throws Exception {
    final File lib = new File(getArchivePath()).getParentFile();
    final URL[] urls = new URL[3];
    urls[0] = fileToURL(new File(lib, "coverage-instrumenter.jar"));
    urls[1] = fileToURL(new File(lib, "asm-all.jar"));
    urls[2] = fileToURL(new File(lib, "trove4j.jar"));
    final Class instrumentator = Class.forName("com.intellij.rt.coverage.instrumentation.Instrumentator", true, new URLClassLoader(urls) {

        protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
            synchronized (this) {
                Class result = findLoadedClass(name);
                if (result == null) {
                    try {
                        result = findClass(name);
                    } catch (ClassNotFoundException e) {
                    }
                }
                if (result != null && resolve) {
                    resolveClass(result);
                }
                if (result != null) {
                    return result;
                }
            }
            return getParent().loadClass(name);
        }
    });
    final Method premainMethod = instrumentator.getDeclaredMethod("premain", new Class[] { String.class, Instrumentation.class });
    premainMethod.invoke(null, new Object[] { argsString, instrumentation });
}
Example 48
Project: jephyr-master  File: Main.java View source code
public static void premain(String agentArgs, Instrumentation inst) throws IOException {
    Properties props = parseArgs(agentArgs);
    Pattern includes = getPattern(props.getProperty("includes"));
    Pattern excludes = getPattern(props.getProperty("excludes"));
    Predicate<String> classNamePredicate =  t -> (includes == null || includes.matcher(t).find()) && (excludes == null || !excludes.matcher(t).find());
    Function<String, String> mapper = parseMapper(props.getProperty("mapping"));
    inst.addTransformer(new RemappingClassFileTransformer(classNamePredicate, mapper));
}
Example 49
Project: JikesRVM-master  File: AgentX.java View source code
public static void premain(final String args, final Instrumentation instrumentation) {
    System.out.println("Running premain with args: " + args);
    System.out.println("Adding class transformer");
    instrumentation.addTransformer(new AgentX());
    final Object[] array = new Object[10];
    final Object object = new Object();
    long arraySize = instrumentation.getObjectSize(array);
    long objectSize = instrumentation.getObjectSize(object);
    // Conservatively assume sizeof(Object) > 0 and sizeof(array) >= array.length
    System.out.println("Array size ok: " + (arraySize >= array.length));
    System.out.println("Object size ok: " + (objectSize > 0));
    System.out.println("AgentX in initiated classes? " + findClass(instrumentation.getInitiatedClasses(AgentX.class.getClassLoader()), AgentX.class));
    System.out.println("AgentX in all classes? " + findClass(instrumentation.getAllLoadedClasses(), AgentX.class));
}
Example 50
Project: jmxtrans2-master  File: JmxTransAgent.java View source code
public static void premain(String configFile, Instrumentation inst) throws IOException {
    AppInfo.load(JmxTransAgent.class).print(System.out);
    if (configFile == null || configFile.isEmpty()) {
        String msg = "JmxTransAgent configurationFile must be defined";
        logger.error(msg);
        throw new IllegalStateException(msg);
    }
    try {
        new JmxTransBuilder(false, Collections.<Resource>singletonList(new StandardResource(configFile))).build().start();
        logger.info("JmxTransAgent started with configuration '" + configFile + "'");
    } catch (Exception e) {
        String msg = "Exception loading JmxTransExporter from '" + configFile + "'";
        logger.error(msg, e);
        throw new IllegalStateException(msg, e);
    }
}
Example 51
Project: lombok-master  File: AgentLauncher.java View source code
public static void runAgents(String agentArgs, Instrumentation instrumentation, boolean injected, Class<?> launchingContext) throws Throwable {
    for (AgentInfo info : AGENTS) {
        try {
            Class<?> agentClass = Class.forName(info.className());
            AgentLaunchable agent = (AgentLaunchable) agentClass.newInstance();
            agent.runAgent(agentArgs, instrumentation, injected, launchingContext);
        } catch (Throwable t) {
            info.problem(t, instrumentation);
        }
    }
}
Example 52
Project: lombok-pg-master  File: LombokPGAgent.java View source code
private static void runMoreAgents(final String agentArgs, final Instrumentation instrumentation, final boolean injected) throws Throwable {
    AgentInfo info = new LombokPGEclipsePatcherInfo();
    try {
        Class<?> agentClass = Class.forName(info.className());
        Agent agent = (Agent) agentClass.newInstance();
        agent.runAgent(agentArgs, instrumentation, injected);
    } catch (final Throwable t) {
        info.problem(t, instrumentation);
    }
}
Example 53
Project: perftrace-master  File: PerftraceInstrument.java View source code
/**
	 * 
	 * ç›®å‰?使用的javassist,修改了方法签å??,增加了新的方法,因此在目å‰?的版本里 The retransformation must not
	 * add, remove or rename fields or methods, change the signatures of
	 * methods, or change inheritance.
	 * 
	 * @param agentArgs
	 * @param inst
	 * 
	 * 
	 */
public static void agentmain(String agentArgs, Instrumentation inst) {
    action(agentArgs, inst, true);
/*
		 * * The retransformation may change method bodies, the constant pool
		 * and attributes. The retransformation must not add, remove or rename
		 * fields or methods, change the signatures of methods, or change
		 * inheritance. These restrictions maybe be lifted in future versions.
		 * The class file bytes are not checked, verified and installed until
		 * after the transformations have been applied, if the resultant bytes
		 * are in error this method will throw an exception.*
		 */
// try {
// if( inst.isRetransformClassesSupported())
// {
// logger.info("agent main redefine class");
// for (Class<?> cls : inst.getAllLoadedClasses()) {
// if(cls.getName().contains("Business"))
// inst.retransformClasses(cls);
// }
// }
// } catch (UnmodifiableClassException e) {
// logger.error("e", e);
// }
}
Example 54
Project: telemetry-master  File: TelemetryAgent.java View source code
public static void premain(String agentArgs, Instrumentation inst) {
    if (!agentArgs.isEmpty()) {
        try {
            TelemetryConfiguration config = loadConfiguration(agentArgs);
            SpanHelper.setSampler(config.getSampler());
            Annotations.setServiceAnnotations(config.getAnnotations());
            if (config.isEnabled()) {
                LogConfiguration log = config.getSinks().getLog();
                if (log.isEnabled()) {
                    SpanSinkRegistry.register(new LoggingSpanSink(log.getFile()));
                }
                final TelemetryTransformer transformer = new TelemetryTransformer();
                if (config.getInstruments().contains("inbound-http")) {
                    transformer.addHandler(new HttpServletClassHandler());
                }
                if (config.getInstruments().contains("outbound-http")) {
                    transformer.addHandler(new ApacheHttpClientClassHandler());
                }
                if (config.getInstruments().contains("database")) {
                    transformer.addHandler(new JdbcDriverClassHandler());
                }
                if (config.getInstruments().contains("metrics")) {
                    transformer.addHandler(new MetricsRegistryHandler());
                }
                if (config.getInstruments().contains("executors")) {
                    transformer.addHandler(new EnvironmentExecutorClassHandler());
                }
                inst.addTransformer(transformer);
            }
        } catch (IOException e) {
            System.err.println("Failed to load telemetry agent configuration: " + e.toString());
            System.err.println("Application will continue uninstrumented.");
            e.printStackTrace(System.err);
        }
    } else {
        System.err.println("No agent configuration path was specified. Application will not be traced by telemetry.");
        System.err.println("To trace an application, specify the path to telemetry.yml as an argument to the agent.");
    }
}
Example 55
Project: activejdbc-master  File: JavaAgent.java View source code
@Override
public synchronized byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    try {
        CtClass clazz = modelFinder.getClazz(className.replace('/', '.'));
        if (modelFinder.isModel(clazz)) {
            if (!loaders.contains(loader) && loader instanceof URLClassLoader) {
                scanLoader(loader);
                loaders.add(loader);
                List<CtClass> models = modelFinder.getModels();
                for (CtClass ctClass : models) {
                    modelFound.invoke(null, ctClass.getName());
                }
            }
            byte[] bytecode = modelInstrumentation.instrument(clazz);
            Instrumentation.log("Instrumented model: " + clazz.getName());
            return bytecode;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new InstrumentationException(e);
    }
}
Example 56
Project: appmon4j-master  File: Appmon4JAgent.java View source code
/**
  * @see java.lang.instrument.ClassFileTransformer#transform(ClassLoader, String,
  *      Class, java.security.ProtectionDomain, byte[])
  * /
  public byte[] transform(final ClassLoader loader, final String className, final Class<?> classBeingRedefined,
                          final ProtectionDomain protectionDomain, final byte[] classfileBuffer)
                   throws IllegalClassFormatException {
    byte[] instrumentedBytecode = classfileBuffer;

    throw new RuntimeException("not yet used");
    //return instrumentedBytecode;
  }
  */
/**
   * The premain method to be implemented by java agents to provide an entry point for the instrumentation.
   *
   * @param agentArgs arguments passed to the agent.
   * @param instrumentation the Instrumentation.
   */
public static void premain(final String agentArgs, final Instrumentation instrumentation) {
    System.out.println("Initialiting Appmon4jAgent");
    Appmon4JAgentConfiguration configuration = null;
    try {
        configuration = Appmon4JAgentConfiguration.load(agentArgs);
    } catch (Exception e) {
        System.err.println("failed to load appmon4j agent configuration from " + agentArgs + ".");
        e.printStackTrace();
    }
    if (configuration != null) {
        new Appmon4JAgent(configuration, instrumentation);
    } else {
        System.err.println("appmon4j Agent: Unable to start up. No valid configuration found. Will do nothing. ");
    }
}
Example 57
Project: coldswap-master  File: ClassListener.java View source code
@Override
public void fileModified(int i, String root, String className) {
    if ((!"".equals(className)) && (null != className))
        if (filter.accept(new File(className))) {
            Map<String, Class<?>> loaded = ClassInstrumenter.getInstance().getLoadedClasses();
            byte[] bytes = ByteCodeClassLoader.loadClassBytes(root + sep + className);
            // first eight bytes for versioning
            if (bytes.length < 8) {
                return;
            }
            ClassNode classNode = new ClassNode(Opcodes.ASM5);
            ClassReader classReader = new ClassReader(bytes);
            classReader.accept(classNode, 0);
            String clsName = classNode.name.replace('/', '.').replace(".class", "");
            logger.info("Class " + clsName + " has been modified on the disk");
            if ((!"".equals(clsName)) && (null != clsName)) {
                Class<?> clazz = loaded.get(clsName);
                if (clazz == null) {
                    logger.info(clsName + " is new class file!");
                    try {
                        Class<?> cla = Class.forName(clsName);
                        // run reference replacer
                        bytes = refManager.runReferenceReplacer(bytes);
                        ClassDefinition def = new ClassDefinition(cla, bytes);
                        Instrumentation inst = ClassInstrumenter.getInstance().getInstrumenter();
                        inst.redefineClasses(def);
                    } catch (ClassNotFoundException e) {
                    } catch (UnmodifiableClassException e) {
                        logger.warning(toString());
                    }
                    return;
                }
                ClassRedefiner redefiner = new ClassRedefiner(clsName, root + sep + className, maxNumberOfMethods);
                try {
                    redefiner.redefineClass(clazz);
                } catch (UnmodifiableClassException e) {
                    logger.severe(e.toString());
                } catch (ClassNotFoundException e) {
                    logger.severe(e.toString());
                }
            }
        }
}
Example 58
Project: coroutines-master  File: CoroutinesAgent.java View source code
/**
     * Java agent premain.
     * @param agentArgs args passed in to agent
     * @param inst instrumentation for agent
     * @throws NullPointerException if {@code inst} is {@code null}
     * @throws IllegalArgumentException if {@code agentArgs} is present but not in the format {@code markerType,debugMode}, or if the passed
     * in arguments were not parseable (debugMode must be a boolean and markerType must be a member of {@link MarkerType})
     */
public static void premain(String agentArgs, Instrumentation inst) {
    // How do agent args work? http://stackoverflow.com/questions/23287228/how-do-i-pass-arguments-to-a-java-instrumentation-agent
    // e.g. java -javaagent:/path/to/agent.jar=argumentstring
    MarkerType markerType = MarkerType.NONE;
    boolean debugMode = false;
    if (agentArgs != null && !agentArgs.isEmpty()) {
        String[] splitArgs = agentArgs.split(",");
        if (splitArgs.length != 2) {
            throw new IllegalArgumentException("Expected argument format is: markerType,debugMode");
        }
        try {
            markerType = MarkerType.valueOf(splitArgs[0]);
        } catch (IllegalArgumentException iae) {
            throw new IllegalArgumentException("Unable to parse marker type -- must be one of the following: " + Arrays.toString(MarkerType.values()), iae);
        }
        if (splitArgs[1].equalsIgnoreCase("true")) {
            debugMode = true;
        } else if (splitArgs[1].equalsIgnoreCase("false")) {
            debugMode = false;
        } else {
            throw new IllegalArgumentException("Unable to parse debug mode -- must be true or false");
        }
    }
    inst.addTransformer(new CoroutinesClassFileTransformer(markerType, debugMode));
}
Example 59
Project: Empire-master  File: Instrumentor.java View source code
/**
	 * Return all the classes loaded into the JVM which extend from the provided class
	 * @param theClass the class
	 * @param <T> the base class type
	 * @return all the classes extending from the parameter. An empty collection will be returned if this java agent is not installed
	 */
public static <T> Collection<Class<? extends T>> instancesOf(Class<T> theClass) {
    Instrumentation aInst = instrumentation();
    if (aInst == null) {
        return Sets.newHashSet();
    }
    Set<Class<? extends T>> aClasses = Sets.newHashSet();
    for (Class<?> aCls : aInst.getAllLoadedClasses()) {
        if (theClass.isAssignableFrom(aCls)) {
            aClasses.add((Class<T>) aCls);
        }
    }
    return aClasses;
}
Example 60
Project: errai-master  File: ClientLocalClassHidingAgent.java View source code
public static void premain(String agentArgs, Instrumentation inst) {
    Map<String, String> options = parseOptionsWithDefaults(agentArgs);
    boolean debug = Boolean.parseBoolean(options.get("debugAgent"));
    Pattern hideClassesPattern = Pattern.compile(options.get("classPattern"));
    inst.addTransformer(new ClientLocalClassHider(hideClassesPattern, debug));
    inst.addTransformer(new GwtLinkerClassHider(debug));
}
Example 61
Project: intellij-community-master  File: ResetAgent.java View source code
public static void premain(String options, Instrumentation inst) {
    // Handle duplicate agents
    if (initialized) {
        return;
    }
    initialized = true;
    inst.addTransformer(new ClassFileTransformer() {

        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            if (classBeingRedefined != null) {
                try {
                    Field callSiteArrayField = classBeingRedefined.getDeclaredField("$callSiteArray");
                    callSiteArrayField.setAccessible(true);
                    callSiteArrayField.set(null, null);
                } catch (Throwable ignored) {
                }
            }
            return removeTimestampField(classfileBuffer);
        }
    });
}
Example 62
Project: jane-master  File: ClassReloader.java View source code
public static void reloadClasses(List<byte[]> classDatas) throws Exception, Error {
    if (_inst == null)
        throw new NullPointerException("Instrumentation not initialized");
    int i = 0, n = classDatas.size();
    ClassDefinition[] clsDefs = new ClassDefinition[n];
    for (byte[] classData : classDatas) clsDefs[i++] = new ClassDefinition(Class.forName(getClassPathFromData(classData)), classData);
    _inst.redefineClasses(clsDefs);
}
Example 63
Project: jolokia-master  File: JvmAgent.java View source code
private static void startAgent(final JvmAgentConfig pConfig, final boolean pLazy, final Instrumentation instrumentation) {
    // start the JolokiaServer in a new daemon thread
    Thread jolokiaStartThread = new Thread("JolokiaStart") {

        public void run() {
            try {
                // block until the server supporting early detection is initialized
                awaitServerInitialization(pConfig, instrumentation);
                server = new JolokiaServer(pConfig, pLazy);
                server.start();
                setStateMarker();
                System.out.println("Jolokia: Agent started with URL " + server.getUrl());
            } catch (RuntimeException exp) {
                System.err.println("Could not start Jolokia agent: " + exp);
            } catch (IOException exp) {
                System.err.println("Could not start Jolokia agent: " + exp);
            }
        }
    };
    jolokiaStartThread.setDaemon(true);
    jolokiaStartThread.start();
}
Example 64
Project: MPS-master  File: MemoryAnalyzer.java View source code
private static Instrumentation getInstrumentation() {
    try {
        Class<?> agentClass = Class.forName(AGENT_CLASS_NAME, true, ClassLoader.getSystemClassLoader());
        if (agentClass == null) {
            return null;
        }
        Method getter = getInstrumentationGetter(agentClass);
        return (Instrumentation) getter.invoke(null);
    } catch (ClassNotFoundException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }
    return null;
}
Example 65
Project: mut4j-master  File: AgentPremain.java View source code
/**
	 * JavaAgent premain entry point as specified in the MANIFEST.MF file. See
	 * {@link http
	 * ://java.sun.com/javase/6/docs/api/java/lang/instrument/package-
	 * summary.html} for details.
	 * 
	 * @param agentArgument
	 *            string provided after "=" up to first space
	 * @param instrumentation
	 *            instrumentation environment provided by the JVM
	 */
public static void premain(String agentArgument, Instrumentation instrumentation) {
    // We cannot do sanity checks for slf4j here as the jars loaded
    // by the application are not visible here.
    LogTransformer.Builder builder = new LogTransformer.Builder();
    builder = builder.addEntryExit(true);
    if (agentArgument != null) {
        Properties args = parseArguments(agentArgument, ",");
        if (args.containsKey(AgentOptions.VERBOSE)) {
            builder = builder.verbose(true);
        }
        if (args.containsKey(AgentOptions.TIME)) {
            printStartStopTimes();
        }
        if (args.containsKey(AgentOptions.IGNORE)) {
            String ignore = args.getProperty(AgentOptions.IGNORE);
            builder = builder.ignore(ignore.split(":"));
        }
        if (args.containsKey(AgentOptions.LEVEL)) {
            builder = builder.level(args.getProperty(AgentOptions.LEVEL));
        }
    }
    instrumentation.addTransformer(builder.build());
}
Example 66
Project: Prendamigo-master  File: AgentPremain.java View source code
/**
	 * JavaAgent premain entry point as specified in the MANIFEST.MF file. See
	 * {@link http
	 * ://java.sun.com/javase/6/docs/api/java/lang/instrument/package-
	 * summary.html} for details.
	 * 
	 * @param agentArgument
	 *            string provided after "=" up to first space
	 * @param instrumentation
	 *            instrumentation environment provided by the JVM
	 */
public static void premain(String agentArgument, Instrumentation instrumentation) {
    // We cannot do sanity checks for slf4j here as the jars loaded
    // by the application are not visible here.
    LogTransformer.Builder builder = new LogTransformer.Builder();
    builder = builder.addEntryExit(true);
    if (agentArgument != null) {
        Properties args = parseArguments(agentArgument, ",");
        if (args.containsKey(AgentOptions.VERBOSE)) {
            builder = builder.verbose(true);
        }
        if (args.containsKey(AgentOptions.TIME)) {
            printStartStopTimes();
        }
        if (args.containsKey(AgentOptions.IGNORE)) {
            String ignore = args.getProperty(AgentOptions.IGNORE);
            builder = builder.ignore(ignore.split(":"));
        }
        if (args.containsKey(AgentOptions.LEVEL)) {
            builder = builder.level(args.getProperty(AgentOptions.LEVEL));
        }
    }
    instrumentation.addTransformer(builder.build());
}
Example 67
Project: sky-walking-master  File: SkyWalkingAgent.java View source code
/**
     * Main entrance.
     * Use byte-buddy transform to enhance all classes, which define in plugins.
     *
     * @param agentArgs
     * @param instrumentation
     * @throws PluginException
     */
public static void premain(String agentArgs, Instrumentation instrumentation) throws PluginException {
    SnifferConfigInitializer.initialize();
    final PluginFinder pluginFinder = new PluginFinder(new PluginBootstrap().loadPlugins());
    ServiceManager.INSTANCE.boot();
    new AgentBuilder.Default().type(enhanceClassMatcher(pluginFinder).and(not(isInterface()))).transform(new AgentBuilder.Transformer() {

        public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader) {
            List<AbstractClassEnhancePluginDefine> pluginDefines = pluginFinder.find(typeDescription.getTypeName());
            for (AbstractClassEnhancePluginDefine pluginDefine : pluginDefines) {
                DynamicType.Builder<?> newBuilder = pluginDefine.define(typeDescription.getTypeName(), builder);
                if (newBuilder != null) {
                    return newBuilder;
                }
            }
            logger.warn("Matched class {}, but enhancement fail.", typeDescription.getTypeName());
            return builder;
        }
    }).with(new AgentBuilder.Listener() {

        @Override
        public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, DynamicType dynamicType) {
        }

        @Override
        public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
        }

        @Override
        public void onError(String typeName, ClassLoader classLoader, JavaModule module, Throwable throwable) {
            logger.error("Failed to enhance class " + typeName, throwable);
        }

        @Override
        public void onComplete(String typeName, ClassLoader classLoader, JavaModule module) {
        }
    }).installOn(instrumentation);
}
Example 68
Project: spudplayer-master  File: AgentPremain.java View source code
/**
	 * JavaAgent premain entry point as specified in the MANIFEST.MF file. See
	 * {@link http
	 * ://java.sun.com/javase/6/docs/api/java/lang/instrument/package-
	 * summary.html} for details.
	 * 
	 * @param agentArgument
	 *            string provided after "=" up to first space
	 * @param instrumentation
	 *            instrumentation environment provided by the JVM
	 */
public static void premain(String agentArgument, Instrumentation instrumentation) {
    // We cannot do sanity checks for slf4j here as the jars loaded
    // by the application are not visible here.
    LogTransformer.Builder builder = new LogTransformer.Builder();
    builder = builder.addEntryExit(true);
    if (agentArgument != null) {
        Properties args = parseArguments(agentArgument, ",");
        if (args.containsKey(AgentOptions.VERBOSE)) {
            builder = builder.verbose(true);
        }
        if (args.containsKey(AgentOptions.TIME)) {
            printStartStopTimes();
        }
        if (args.containsKey(AgentOptions.IGNORE)) {
            String ignore = args.getProperty(AgentOptions.IGNORE);
            builder = builder.ignore(ignore.split(":"));
        }
        if (args.containsKey(AgentOptions.LEVEL)) {
            builder = builder.level(args.getProperty(AgentOptions.LEVEL));
        }
    }
    instrumentation.addTransformer(builder.build());
}
Example 69
Project: TridentCommons-master  File: Instrument.java View source code
public static Instrumentation get() {
    if (instrumentation == null) {
        try {
            attachAgentToJVM(getCurrentPID(), Instrument.class);
        } catch (IOExceptionAttachNotSupportedException | AgentLoadException | AgentInitializationException |  e) {
            e.printStackTrace();
        }
    }
    return instrumentation;
}
Example 70
Project: tyrion-master  File: LockProfilingAgent.java View source code
/**
     * JVM hook to statically load the javaagent at startup.
     * <p/>
     * After the Java Virtual Machine (JVM) has initialized, the premain method
     * will be called. Then the real application main method will be called.
     *
     * @param args The agent's arguments
     * @param inst The instrumentation class that will be used
     * @throws Exception
     */
public static void premain(String args, Instrumentation inst) throws Exception {
    Configuration configuration = new Configuration(args);
    Configuration.ParameterValue outputFileParameter = configuration.outputFile();
    if (outputFileParameter.isDefaultValue()) {
        SimpleLogger.warn("No output file was provided, agent is disabled");
    } else {
        SimpleLogger.info("Tyrion agent starting with arguments '%s'", configuration);
        final String outputFile = outputFileParameter.getValue();
        clearOutputFile(outputFile);
        scheduleLocksWrite(outputFile);
        configureLockInterceptor(configuration);
        instrumentLocks(inst);
    }
}
Example 71
Project: zorka-master  File: OnlineReconfUnitTest.java View source code
@Test
public void testCheckInstrumentationInterface() {
    Method isModifiable = null, retransformMethod = null;
    for (Method m : Instrumentation.class.getDeclaredMethods()) {
        if ("isModifiableClass".equals(m.getName())) {
            isModifiable = m;
        }
        if ("retransformClasses".equals(m.getName())) {
            retransformMethod = m;
        }
    }
    assertNotNull("isModifiableMethod should exist", isModifiable);
    assertNotNull("retransformMethod should exist", retransformMethod);
}
Example 72
Project: fakereplace-master  File: Agent.java View source code
public static void premain(java.lang.String s, java.lang.instrument.Instrumentation i) {
    AgentOptions.setup(s);
    inst = i;
    final Set<Extension> extension = getIntegrationInfo(ClassLoader.getSystemClassLoader());
    //initialise the unmodified file index
    UnmodifiedFileIndex.loadIndex();
    //first we need to instrument the class loaders
    final Set<Class> cls = new HashSet<Class>();
    for (Class c : inst.getAllLoadedClasses()) {
        if (ClassLoader.class.isAssignableFrom(c)) {
            cls.add(c);
        }
    }
    final ClassLoaderTransformer classLoaderTransformer = new ClassLoaderTransformer();
    final MainTransformer mainTransformer = new MainTransformer(extension);
    Agent.mainTransformer = mainTransformer;
    inst.addTransformer(mainTransformer, true);
    mainTransformer.addTransformer(classLoaderTransformer);
    try {
        inst.retransformClasses(cls.toArray(EMPTY_CL_ARRAY));
    } catch (UnmodifiableClassException e) {
        e.printStackTrace();
    }
    mainTransformer.addTransformer(new AnnotationTransformer());
    mainTransformer.addTransformer(new FieldReplacementTransformer());
    mainTransformer.addTransformer(new MethodReplacementTransformer());
    mainTransformer.addTransformer(new Transformer(extension));
    mainTransformer.setRetransformationStarted(false);
    mainTransformer.setLogClassRetransformation(true);
    //start the server
    String portString = AgentOptions.getOption(AgentOption.SERVER);
    if (portString == null || !portString.equals("-1")) {
        if (portString == null) {
            portString = "6555";
        }
        Thread thread = new Thread(new FakereplaceServer(Integer.parseInt(portString)));
        thread.setDaemon(true);
        thread.setName("Fakereplace Thread");
        thread.start();
    } else {
        System.out.println("Fakereplace is running.");
    }
}
Example 73
Project: HotswapAgent-master  File: InitHandler.java View source code
/**
     * Support for autowiring of agent services - resolve instance by class.
     *
     * @param classLoader application classloader
     * @param pluginClass used only for debugging messages
     * @param type        requested type
     * @return resolved instance or null (error is logged)
     */
@SuppressWarnings("unchecked")
protected Object resolveType(ClassLoader classLoader, Class pluginClass, Class type) {
    if (type.isAssignableFrom(PluginManager.class)) {
        return pluginManager;
    } else if (type.isAssignableFrom(Watcher.class)) {
        return pluginManager.getWatcher();
    } else if (type.isAssignableFrom(Scheduler.class)) {
        return pluginManager.getScheduler();
    } else if (type.isAssignableFrom(HotswapTransformer.class)) {
        return pluginManager.getHotswapTransformer();
    } else if (type.isAssignableFrom(PluginConfiguration.class)) {
        return pluginManager.getPluginConfiguration(classLoader);
    } else if (type.isAssignableFrom(ClassLoader.class)) {
        return classLoader;
    } else if (type.isAssignableFrom(Instrumentation.class)) {
        return pluginManager.getInstrumentation();
    } else {
        LOGGER.error("Unable process @Init on plugin '{}'." + " Type '" + type + "' is not recognized for @Init annotation.", pluginClass);
        return null;
    }
}
Example 74
Project: Agrona-master  File: BufferAlignmentAgent.java View source code
private static synchronized void agent(final boolean shouldRedefine, final Instrumentation instrumentation) {
    BufferAlignmentAgent.instrumentation = instrumentation;
    // all Int methods, and all String method other than
    // XXXStringWithoutLengthXXX or getStringXXX(int, int)
    final Junction<MethodDescription> intVerifierMatcher = nameContains("Int").or(nameMatches(".*String[^W].*").and(not(ElementMatchers.takesArguments(int.class, int.class))));
    alignmentTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED)).with(LISTENER).disableClassFormatChanges().with(shouldRedefine ? AgentBuilder.RedefinitionStrategy.RETRANSFORMATION : AgentBuilder.RedefinitionStrategy.DISABLED).type(isSubTypeOf(DirectBuffer.class).and(not(isInterface()))).transform(( builder,  typeDescription,  classLoader,  module) -> builder.visit(to(LongVerifier.class).on(nameContains("Long"))).visit(to(DoubleVerifier.class).on(nameContains("Double"))).visit(to(IntVerifier.class).on(intVerifierMatcher)).visit(to(FloatVerifier.class).on(nameContains("Float"))).visit(to(ShortVerifier.class).on(nameContains("Short"))).visit(to(CharVerifier.class).on(nameContains("Char")))).installOn(instrumentation);
}
Example 75
Project: btrace2-master  File: Main.java View source code
private static void setupBootstrap(String args, Instrumentation inst) throws IOException {
    String blPath = null;
    String bootlibKey = "bootstrap=";
    int blStart = args.indexOf(bootlibKey);
    if (blStart > -1) {
        int blEnd = args.indexOf(",", blStart);
        if (blEnd > -1) {
            blPath = args.substring(blStart + bootlibKey.length(), blEnd).trim();
        }
    }
    if (blPath == null) {
        ClassLoader cl = Main.class.getClassLoader();
        if (cl == null) {
            cl = ClassLoader.getSystemClassLoader();
        }
        URL blPathURL = cl.getResource(Main.class.getName().replace('.', '/') + ".class");
        blPath = blPathURL.toString().replace("jar:file:", "");
        // NOI18N
        blPath = blPath.substring(0, blPath.indexOf(".jar!") + 4).replace("btrace-agent", "btrace-boot");
    }
    inst.appendToBootstrapClassLoaderSearch(new JarFile(blPath));
}
Example 76
Project: crash-master  File: Agent.java View source code
public static void agentmain(final String agentArgs, final Instrumentation inst) throws Exception {
    log.log(Level.INFO, "CRaSH agent loaded");
    //
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                CommandDescriptor<Instance<Agent>> c = CommandFactory.DEFAULT.create(Agent.class);
                InvocationMatcher<Instance<Agent>> matcher = c.matcher();
                InvocationMatch<Instance<Agent>> match = matcher.parse(agentArgs);
                match.invoke(Util.wrap(new Agent(inst)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    //
    t.start();
    log.log(Level.INFO, "Spawned CRaSH thread " + t.getId() + " for further processing");
}
Example 77
Project: glassfish-main-master  File: AppClientContainerAgent.java View source code
public static void premain(String agentArgsText, Instrumentation inst) {
    try {
        final long now = System.currentTimeMillis();
        /*
             * The agent prepares the ACC but does not launch the client.
             */
        AppClientFacade.prepareACC(optionsValue(agentArgsText), inst);
        logger.fine("AppClientContainerAgent finished after " + (System.currentTimeMillis() - now) + " ms");
    } catch (UserError ue) {
        ue.displayAndExit();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Example 78
Project: glassfish-master  File: AppClientContainerAgent.java View source code
public static void premain(String agentArgsText, Instrumentation inst) {
    try {
        final long now = System.currentTimeMillis();
        /*
             * The agent prepares the ACC but does not launch the client.
             */
        AppClientFacade.prepareACC(optionsValue(agentArgsText), inst);
        logger.fine("AppClientContainerAgent finished after " + (System.currentTimeMillis() - now) + " ms");
    } catch (UserError ue) {
        ue.displayAndExit();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Example 79
Project: highway-to-urhell-master  File: TransformerService.java View source code
private void transformOneClass(Instrumentation inst, String className) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {
        inst.retransformClasses(classLoader.loadClass(className));
    } catch (ClassNotFoundException e) {
        System.err.println("Error while transform Class" + className + " msg " + e);
    } catch (UnmodifiableClassException e) {
        System.err.println("Error while transform Class" + className + " msg " + e);
    }
}
Example 80
Project: java-callgraph-master  File: Instrumenter.java View source code
public static void premain(String argument, Instrumentation instrumentation) {
    if (argument == null) {
        err("Missing configuration argument");
        return;
    }
    err("Argument is: " + argument);
    String[] tokens = argument.split(";");
    if (tokens.length < 1) {
        err("Missing delimiter ;");
        return;
    }
    for (String token : tokens) {
        String[] args = token.split("=");
        if (args.length < 2) {
            err("Missing argument delimiter =:" + token);
            return;
        }
        String argtype = args[0];
        if (!argtype.equals("incl") && !argtype.equals("excl")) {
            err("Wrong argument: " + argtype);
            return;
        }
        String[] patterns = args[1].split(",");
        for (String pattern : patterns) {
            Pattern p = null;
            err("Compiling " + argtype + " pattern:" + pattern + "$");
            try {
                p = Pattern.compile(pattern + "$");
            } catch (PatternSyntaxException pse) {
                err("pattern: " + pattern + " not valid, ignoring");
            }
            if (argtype.equals("incl"))
                pkgIncl.add(p);
            else
                pkgExcl.add(p);
        }
    }
    instrumentation.addTransformer(new Instrumenter());
}
Example 81
Project: jcarder-master  File: JavaAgent.java View source code
private void init(Instrumentation instrumentation) throws Exception {
    handleProperties();
    initLogger();
    mLogger.info("Starting " + BuildInformation.getShortInfo() + " agent");
    logJvmInfo();
    EventListener listener = EventListener.create(mLogger, mOutputDir);
    ClassTransformer classTransformer = new ClassTransformer(mLogger, mOutputDir, mConfig);
    instrumentation.addTransformer(classTransformer);
    StaticEventListener.setListener(listener);
    mLogger.info("JCarder agent initialized\n");
}
Example 82
Project: jersey-master  File: PerfTestAgent.java View source code
@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;
}
Example 83
Project: jokre-master  File: Main.java View source code
public static void premain(String args, Instrumentation inst) throws Exception {
    // guard against the agent being loaded twice
    synchronized (Main.class) {
        if (firstTime) {
            firstTime = false;
        } else {
            throw new Exception("org.jboss.jokre.agent.Main : attempting to load Jokre agent more than once");
        }
    }
    if (args != null) {
        // args are supplied separated by ',' characters
        String[] argsArray = args.split(",");
        // listener flag which implies use of a retransformer
        for (String arg : argsArray) {
            if (arg.startsWith(BOOT_PREFIX)) {
                bootJarPaths.add(arg.substring(BOOT_PREFIX.length(), arg.length()));
            } else if (arg.startsWith(SYS_PREFIX)) {
                sysJarPaths.add(arg.substring(SYS_PREFIX.length(), arg.length()));
            } else {
                System.err.println("org.jboss.jokre.agent.Main:\n" + "  illegal agent argument : " + arg + "\n" + "  valid arguments are boot:<path-to-jar> or sys:<path-to-jar>");
            }
        }
    }
    for (String bootJarPath : bootJarPaths) {
        try {
            JarFile jarfile = new JarFile(new File(bootJarPath));
            inst.appendToBootstrapClassLoaderSearch(jarfile);
        } catch (IOException ioe) {
            System.err.println("org.jboss.jokre.agent.Main: unable to open boot jar file : " + bootJarPath);
            throw ioe;
        }
    }
    for (String sysJarPath : sysJarPaths) {
        try {
            JarFile jarfile = new JarFile(new File(sysJarPath));
            inst.appendToSystemClassLoaderSearch(jarfile);
        } catch (IOException ioe) {
            System.err.println("org.jboss.jokre.agent.Main: unable to open system jar file : " + sysJarPath);
            throw ioe;
        }
    }
    // install a transformer to do call site transformations
    boolean isRetransform = inst.isRetransformClassesSupported();
    if (!isRetransform) {
        throw new Exception("org.jboss.jokre.agent.Main : JVM does not support retransformation");
    }
    ClassFileTransformer transformer;
    ClassLoader loader = ClassLoader.getSystemClassLoader();
    Class transformerClazz;
    // create the Jokre agent via reflection in case we want to put the Jokre lib into the bootstrap classpath
    //transformer = new Jokre(inst);
    transformerClazz = loader.loadClass("org.jboss.jokre.agent.Jokre");
    Constructor constructor = transformerClazz.getConstructor(Instrumentation.class);
    transformer = (ClassFileTransformer) constructor.newInstance(new Object[] { inst });
    inst.addTransformer(transformer, true);
}
Example 84
Project: linux-jvm-processio-master  File: ProcessIOAgent.java View source code
// Required method for instrumentation agent.
public static void premain(String arglist, Instrumentation inst) {
    if (!foundPID) {
        log.error("Unabled to Determine pid for current jvm process to agent has no effect");
    } else {
        String beanName = null;
        String domainName = null;
        long frequencyOfScheduler = DEFAULT_SCHEDULING_FREQUENCY;
        if (arglist != null && arglist.trim().length() > 0) {
            Matcher m = FREQUENCY_OPTION.matcher(arglist);
            if (m.matches()) {
                try {
                    frequencyOfScheduler = Long.parseLong(m.group(1));
                } catch (NumberFormatException e) {
                }
            }
            m = JMX_BEAN_NAME.matcher(arglist);
            // got a bean name
            if (m.matches()) {
                beanName = m.group(1);
            }
            m = JMX_DOMAIN_NAME.matcher(arglist);
            if (m.matches())
                domainName = m.group(1);
            if (beanName == null || beanName.trim().length() == 0)
                beanName = ProcessIOUsagePersistenceViaJmx.DEFAULT_JMX_BEAN_NAME;
            if (domainName == null || domainName.trim().length() == 0)
                domainName = ProcessIOUsagePersistenceViaJmx.DEFAULT_JMX_DOMAIN_NAME;
            persistence = new ProcessIOUsagePersistenceViaJmx(calculator, domainName, beanName);
        } else {
            persistence = new ProcessIOUsagePersistenceViaJmx(calculator);
        }
        scheduler = new ScheduledExecutorServiceProcessIOScheduler(processIOReader, persistence);
        scheduler.start(frequencyOfScheduler);
        log.info("ProcessIOAgent Running, io will be obtain every {}ms", frequencyOfScheduler);
    }
}
Example 85
Project: liverepl-master  File: Agent.java View source code
public static void agentmain(String agentArgs, Instrumentation inst) {
    TRC.fine("Started Attach agent");
    StringTokenizer stok = new StringTokenizer(agentArgs, "\n");
    if (stok.countTokens() != 4) {
        throw new RuntimeException("Invalid parameters: " + agentArgs);
    }
    int port = Integer.parseInt(stok.nextToken());
    TRC.fine("Port: " + port);
    String clojurePath = stok.nextToken();
    String serverPath = stok.nextToken();
    String classLoaderId = stok.nextToken();
    if ("L".equals(classLoaderId)) {
        printClassLoaderInfo(port);
        return;
    }
    boolean clojureLoaded = isClojureLoaded();
    TRC.fine("Clojure is " + (clojureLoaded ? "" : "not ") + "loaded");
    List<URL> urls;
    if (clojureLoaded) {
        urls = getJarUrls(serverPath);
    } else {
        urls = getJarUrls(clojurePath, serverPath);
    }
    ClassLoader old = pushClassLoader(urls, classLoaderId);
    try {
        if (!clojureLoaded) {
            // if clojure wasn't loaded before, print current status
            TRC.fine("Clojure is " + (isClojureLoaded() ? "" : "not ") + "loaded");
        }
        startRepl(port, inst);
    } finally {
        popClassLoader(old);
    }
}
Example 86
Project: Payara-master  File: AppClientContainerAgent.java View source code
public static void premain(String agentArgsText, Instrumentation inst) {
    try {
        final long now = System.currentTimeMillis();
        /*
             * The agent prepares the ACC but does not launch the client.
             */
        AppClientFacade.prepareACC(optionsValue(agentArgsText), inst);
        logger.fine("AppClientContainerAgent finished after " + (System.currentTimeMillis() - now) + " ms");
    } catch (UserError ue) {
        ue.displayAndExit();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Example 87
Project: performance-master  File: BufferAlignmentAgent.java View source code
private static synchronized void agent(final boolean shouldRedefine, final Instrumentation instrumentation) {
    BufferAlignmentAgent.instrumentation = instrumentation;
    // all Int methods, and all String method other than
    // XXXStringWithoutLengthXXX or getStringXXX(int, int)
    final Junction<MethodDescription> intVerifierMatcher = nameContains("Int").or(nameMatches(".*String[^W].*").and(not(ElementMatchers.takesArguments(int.class, int.class))));
    alignmentTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED)).with(LISTENER).disableClassFormatChanges().with(shouldRedefine ? AgentBuilder.RedefinitionStrategy.RETRANSFORMATION : AgentBuilder.RedefinitionStrategy.DISABLED).type(isSubTypeOf(DirectBuffer.class).and(not(isInterface()))).transform(( builder,  typeDescription,  classLoader,  module) -> builder.visit(to(LongVerifier.class).on(nameContains("Long"))).visit(to(DoubleVerifier.class).on(nameContains("Double"))).visit(to(IntVerifier.class).on(intVerifierMatcher)).visit(to(FloatVerifier.class).on(nameContains("Float"))).visit(to(ShortVerifier.class).on(nameContains("Short"))).visit(to(CharVerifier.class).on(nameContains("Char")))).installOn(instrumentation);
}
Example 88
Project: revoc-master  File: RevocAgent.java View source code
private static void retransform(Instrumentation instrumentation, String[] packages) throws UnmodifiableClassException {
    List<Class> classesToInstrument = new ArrayList<Class>();
    for (Class clazz : instrumentation.getAllLoadedClasses()) {
        if (RevocClassTransformer.shouldFilter(clazz.getClassLoader(), clazz.getName().replace('.', '/'), packages)) {
            classesToInstrument.add(clazz);
        }
    }
    log.info(String.format("Instrumenting %s classes", classesToInstrument.size()));
    instrumentation.addTransformer(new RevocClassTransformer(packages), true);
    instrumentation.retransformClasses(classesToInstrument.toArray(new Class[classesToInstrument.size()]));
}
Example 89
Project: slf4j-master  File: AgentPremain.java View source code
/**
     * JavaAgent premain entry point as specified in the MANIFEST.MF file. See
     * <a href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html">http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html</a> for details.
     *
     * @param agentArgument
     *            string provided after "=" up to first space
     * @param instrumentation
     *            instrumentation environment provided by the JVM
     */
public static void premain(String agentArgument, Instrumentation instrumentation) {
    // We cannot do sanity checks for slf4j here as the jars loaded
    // by the application are not visible here.
    LogTransformer.Builder builder = new LogTransformer.Builder();
    builder = builder.addEntryExit(true);
    if (agentArgument != null) {
        Properties args = parseArguments(agentArgument, ",");
        if (args.containsKey(AgentOptions.VERBOSE)) {
            builder = builder.verbose(true);
        }
        if (args.containsKey(AgentOptions.TIME)) {
            printStartStopTimes();
        }
        if (args.containsKey(AgentOptions.IGNORE)) {
            String ignore = args.getProperty(AgentOptions.IGNORE);
            builder = builder.ignore(ignore.split(":"));
        }
        if (args.containsKey(AgentOptions.LEVEL)) {
            builder = builder.level(args.getProperty(AgentOptions.LEVEL));
        }
    }
    instrumentation.addTransformer(builder.build());
}
Example 90
Project: spectator-master  File: Agent.java View source code
/** Entry point for the agent. */
public static void premain(String arg, Instrumentation instrumentation) throws Exception {
    // Setup logging
    Config config = loadConfig(arg);
    createDependencyProperties(config);
    // Setup Registry
    AtlasRegistry registry = new AtlasRegistry(Clock.SYSTEM, new AgentAtlasConfig(config));
    // Add to global registry for http stats and GC logger
    Spectator.globalRegistry().add(registry);
    // Enable GC logger
    GcLogger gcLogger = new GcLogger();
    if (config.getBoolean("collection.gc")) {
        gcLogger.start(null);
    }
    // Enable JVM data collection
    if (config.getBoolean("collection.jvm")) {
        Jmx.registerStandardMXBeans(registry);
    }
    // Enable JMX query collection
    if (config.getBoolean("collection.jmx")) {
        for (Config cfg : config.getConfigList("jmx.mappings")) {
            registry.register(new JmxMeter(registry, JmxConfig.from(cfg)));
        }
    }
    // Start collection for the registry
    registry.start();
    // Shutdown registry
    Runtime.getRuntime().addShutdownHook(new Thread(registry::stop, "spectator-agent-shutdown"));
}
Example 91
Project: Static-master  File: Instrumenter.java View source code
public static void premain(String argument, Instrumentation instrumentation) {
    if (argument == null) {
        err("Missing configuration argument");
        return;
    }
    err("Argument is: " + argument);
    String[] tokens = argument.split(";");
    if (tokens.length < 1) {
        err("Missing delimiter ;");
        return;
    }
    for (String token : tokens) {
        String[] args = token.split("=");
        if (args.length < 2) {
            err("Missing argument delimiter =:" + token);
            return;
        }
        String argtype = args[0];
        if (!argtype.equals("incl") && !argtype.equals("excl")) {
            err("Wrong argument: " + argtype);
            return;
        }
        String[] patterns = args[1].split(",");
        for (String pattern : patterns) {
            Pattern p = null;
            err("Compiling " + argtype + " pattern:" + pattern + "$");
            try {
                p = Pattern.compile(pattern + "$");
            } catch (PatternSyntaxException pse) {
                err("pattern: " + pattern + " not valid, ignoring");
            }
            if (argtype.equals("incl"))
                pkgIncl.add(p);
            else
                pkgExcl.add(p);
        }
    }
    instrumentation.addTransformer(new Instrumenter());
}
Example 92
Project: statsd-jvm-profiler-master  File: Agent.java View source code
/**
     * Start the profiler
     *
     * @param args Profiler arguments
     * @param instrumentation Instrumentation agent
     */
public static void premain(final String args, final Instrumentation instrumentation) {
    Arguments arguments = Arguments.parseArgs(args);
    Reporter reporter = instantiate(arguments.reporter, Reporter.CONSTRUCTOR_PARAM_TYPES, arguments);
    Collection<Profiler> profilers = new ArrayList<>();
    for (Class<? extends Profiler> profiler : arguments.profilers) {
        profilers.add(instantiate(profiler, Profiler.CONSTRUCTOR_PARAM_TYPES, reporter, arguments));
    }
    scheduleProfilers(profilers, arguments);
    registerShutdownHook(profilers);
}
Example 93
Project: tamiflex-master  File: Agent.java View source code
public static void premain(String agentArgs, Instrumentation inst) throws IOException, ClassNotFoundException, UnmodifiableClassException, URISyntaxException, InterruptedException {
    if (!inst.isRetransformClassesSupported()) {
        throw new RuntimeException("retransformation not supported");
    }
    if (agentArgs == null)
        agentArgs = "";
    if (agentArgs.equals(""))
        usage();
    appendRtJarToBootClassPath(inst);
    String outPath = agentArgs;
    if (outPath == null || outPath.isEmpty()) {
        System.err.println("No outpath given!");
        usage();
    }
    File outDir = new File(outPath);
    if (outDir.exists()) {
        if (!outDir.isDirectory()) {
            System.err.println(outDir + "is not a directory");
            usage();
        }
    } else {
        boolean res = outDir.mkdirs();
        if (!res) {
            System.err.println("Cannot create directory " + outDir);
            usage();
        }
    }
    final File logFile = new File(outDir, "refl.log");
    ReflLogger.setLogFile(logFile);
    instrumentClassesForLogging(inst);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            ShutdownStatus.hasShutDown = true;
            ReflLogger.closeLogger();
        }
    });
}
Example 94
Project: classlib6-master  File: InstrumentationImpl.java View source code
// Attempt to load and start an agent
private void loadClassAndStartAgent(String classname, String methodname, String optionsString) throws Throwable {
    ClassLoader mainAppLoader = ClassLoader.getSystemClassLoader();
    Class<?> javaAgentClass = mainAppLoader.loadClass(classname);
    Method m = null;
    NoSuchMethodException firstExc = null;
    boolean twoArgAgent = false;
    try {
        m = javaAgentClass.getMethod(methodname, new Class[] { String.class, java.lang.instrument.Instrumentation.class });
        twoArgAgent = true;
    } catch (NoSuchMethodException x) {
        firstExc = x;
    }
    // check for the 1-arg method
    if (m == null) {
        try {
            m = javaAgentClass.getMethod(methodname, new Class[] { String.class });
        } catch (NoSuchMethodException x) {
            throw firstExc;
        }
    }
    // the premain method should not be required to be public,
    // make it accessible so we can call it
    setAccessible(m, true);
    // invoke the 1 or 2-arg method
    if (twoArgAgent) {
        m.invoke(null, new Object[] { optionsString, this });
    } else {
        m.invoke(null, new Object[] { optionsString });
    }
    // don't let others access a non-public premain method
    setAccessible(m, false);
}
Example 95
Project: h-store-master  File: ClassEnhancer.java View source code
/**
     * Enhances classes as specified by a JVM -javaagent argument.
     *
     * @see java.lang.instrument.Instrumentation
     */
public static void premain(String args, Instrumentation inst) {
    if (!args.startsWith(AGENT_PREFIX)) {
        throw new IllegalArgumentException("Unknown javaagent args: " + args + " Args must start with: \"" + AGENT_PREFIX + '"');
    }
    args = args.substring(AGENT_PREFIX.length());
    Set<String> packageNames = null;
    boolean verbose = false;
    if (args.length() > 0) {
        packageNames = new HashSet<String>();
        StringTokenizer tokens = new StringTokenizer(args, ",");
        while (tokens.hasMoreTokens()) {
            String token = tokens.nextToken();
            if (token.startsWith("-")) {
                if (token.equals("-v")) {
                    verbose = true;
                } else {
                    throw new IllegalArgumentException("Unknown javaagent arg: " + token);
                }
            } else {
                packageNames.add(token);
            }
        }
    }
    ClassEnhancer enhancer = new ClassEnhancer(packageNames);
    enhancer.setVerbose(verbose);
    inst.addTransformer(enhancer);
}
Example 96
Project: ikvm-openjdk-master  File: InstrumentationImpl.java View source code
// Attempt to load and start an agent
private void loadClassAndStartAgent(String classname, String methodname, String optionsString) throws Throwable {
    ClassLoader mainAppLoader = ClassLoader.getSystemClassLoader();
    Class<?> javaAgentClass = mainAppLoader.loadClass(classname);
    Method m = null;
    NoSuchMethodException firstExc = null;
    boolean twoArgAgent = false;
    try {
        m = javaAgentClass.getMethod(methodname, new Class[] { String.class, java.lang.instrument.Instrumentation.class });
        twoArgAgent = true;
    } catch (NoSuchMethodException x) {
        firstExc = x;
    }
    // check for the 1-arg method
    if (m == null) {
        try {
            m = javaAgentClass.getMethod(methodname, new Class[] { String.class });
        } catch (NoSuchMethodException x) {
            throw firstExc;
        }
    }
    // the premain method should not be required to be public,
    // make it accessible so we can call it
    setAccessible(m, true);
    // invoke the 1 or 2-arg method
    if (twoArgAgent) {
        m.invoke(null, new Object[] { optionsString, this });
    } else {
        m.invoke(null, new Object[] { optionsString });
    }
    // don't let others access a non-public premain method
    setAccessible(m, false);
}
Example 97
Project: Java-Agent-Timemachine-master  File: TimeMachineAgentDelegate.java View source code
/**
	 * This method is called by the general agent {@code com.hapiware.agent.Agent} and
	 * is done before the main method call right after the JVM initialisation. 
	 * <p>
	 * <b>Notice</b> the difference between this method and 
	 * the {@code public static void premain(String, Instrumentation} method described in
	 * {@code java.lang.instrument} package. 
	 *
	 * @param includePatterns
	 * 		A list of patterns to include classes for instrumentation.
	 * 
	 * @param excludePatterns
	 * 		A list patterns to set classes not to be instrumented.
	 * 
	 * @param config
	 * 		{@code String} to set time shift for {@link TimeMachineTransformer}.
	 * 
	 * @param instrumentation
	 * 		See {@link java.lang.instrument.Instrumentation}
	 * 
	 * @throws IllegalArgumentException
	 * 		If there is something wrong with the configuration file.
	 *
	 * @see java.lang.instrument
	 */
public static void premain(Pattern[] includePatterns, Pattern[] excludePatterns, Object config, Instrumentation instrumentation) {
    try {
        if (config != null) {
            instrumentation.addTransformer(new TimeMachineTransformer(includePatterns, excludePatterns, parseTime((String) config)));
        } else {
            String ex = "Time shift configuration is missing.";
            throw new IllegalArgumentException(ex);
        }
    } catch (Exception e) {
        System.err.println("Couldn't start the TimeMachine agent delegate due to an exception. " + e.getMessage());
        e.printStackTrace();
    }
}
Example 98
Project: Aeron-master  File: EventLogAgent.java View source code
private static void agent(final boolean shouldRedefine, final Instrumentation instrumentation) {
    if (EventConfiguration.ENABLED_EVENT_CODES == 0) {
        return;
    }
    /*
         * Intercept based on enabled events:
         *  SenderProxy
         *  ReceiverProxy
         *  ClientProxy
         *  DriverConductor (onClientCommand)
         *  SendChannelEndpoint
         *  ReceiveChannelEndpoint
         */
    EventLogAgent.instrumentation = instrumentation;
    logTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED)).with(LISTENER).disableClassFormatChanges().with(shouldRedefine ? AgentBuilder.RedefinitionStrategy.RETRANSFORMATION : AgentBuilder.RedefinitionStrategy.DISABLED).type(nameEndsWith("DriverConductor")).transform(( builder,  typeDescription,  classLoader,  javaModule) -> builder.visit(to(CleanupInterceptor.DriverConductorInterceptor.CleanupImage.class).on(named("cleanupImage"))).visit(to(CleanupInterceptor.DriverConductorInterceptor.CleanupPublication.class).on(named("cleanupPublication"))).visit(to(CleanupInterceptor.DriverConductorInterceptor.CleanupSubscriptionLink.class).on(named("cleanupSubscriptionLink")))).type(nameEndsWith("DriverAdapter")).transform(( builder,  typeDescription,  classLoader,  javaModule) -> builder.visit(to(CmdInterceptor.class).on(named("onMessage")))).type(nameEndsWith("ClientProxy")).transform(( builder,  typeDescription,  classLoader,  javaModule) -> builder.visit(to(CmdInterceptor.class).on(named("transmit")))).type(nameEndsWith("SenderProxy")).transform(( builder,  typeDescription,  classLoader,  javaModule) -> builder.visit(to(ChannelEndpointInterceptor.SenderProxyInterceptor.RegisterSendChannelEndpoint.class).on(named("registerSendChannelEndpoint"))).visit(to(ChannelEndpointInterceptor.SenderProxyInterceptor.CloseSendChannelEndpoint.class).on(named("closeSendChannelEndpoint")))).type(nameEndsWith("ReceiverProxy")).transform(( builder,  typeDescription,  classLoader,  javaModule) -> builder.visit(to(ChannelEndpointInterceptor.ReceiverProxyInterceptor.RegisterReceiveChannelEndpoint.class).on(named("registerReceiveChannelEndpoint"))).visit(to(ChannelEndpointInterceptor.ReceiverProxyInterceptor.CloseReceiveChannelEndpoint.class).on(named("closeReceiveChannelEndpoint")))).type(inheritsAnnotation(EventLog.class)).transform(( builder,  typeDescription,  classLoader,  javaModule) -> builder.visit(to(ChannelEndpointInterceptor.SendChannelEndpointInterceptor.Presend.class).on(named("presend"))).visit(to(ChannelEndpointInterceptor.ReceiveChannelEndpointInterceptor.SendTo.class).on(named("sendTo"))).visit(to(ChannelEndpointInterceptor.SendChannelEndpointInterceptor.OnStatusMessage.class).on(named("onStatusMessage"))).visit(to(ChannelEndpointInterceptor.SendChannelEndpointInterceptor.OnNakMessage.class).on(named("onNakMessage"))).visit(to(ChannelEndpointInterceptor.SendChannelEndpointInterceptor.OnRttMeasurement.class).on(named("onRttMeasurement"))).visit(to(ChannelEndpointInterceptor.ReceiveChannelEndpointInterceptor.OnDataPacket.class).on(named("onDataPacket"))).visit(to(ChannelEndpointInterceptor.ReceiveChannelEndpointInterceptor.OnSetupMessage.class).on(named("onSetupMessage"))).visit(to(ChannelEndpointInterceptor.ReceiveChannelEndpointInterceptor.OnRttMeasurement.class).on(named("onRttMeasurement")))).installOn(instrumentation);
    EVENT_LOG_READER_THREAD.setName("event log reader");
    EVENT_LOG_READER_THREAD.setDaemon(true);
    EVENT_LOG_READER_THREAD.start();
}
Example 99
Project: analytica-agent-master  File: AnalyticaSpyAgent.java View source code
private static void addTransformer(final String agentArgs, final Instrumentation inst, final boolean canRetransform) {
    if (instrumentation == null) {
        instrumentation = inst;
        System.out.println("AnalyticaAgent prepare at " + new Date());
        transformer = new AnalyticaSpyTransformer(agentArgs);
        //code jdk1.6+ inst.addTransformer(transformer, canRetransform);
        // code jdk1.5 : inst.addTransformer(transformer);
        inst.addTransformer(transformer, canRetransform);
        System.out.println("AnalyticaAgent Start at " + new Date());
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                AnalyticaSpyAgent.stopAgent();
            }
        });
        reloadAll();
    }
}
Example 100
Project: android-gradle-plugin-master  File: ApiLookupTest.java View source code
public void testIsValidPackage() {
    assertTrue(mDb.isValidJavaPackage("java/lang/Integer"));
    assertTrue(mDb.isValidJavaPackage("javax/crypto/Cipher"));
    assertTrue(mDb.isValidJavaPackage("java/awt/font/NumericShaper"));
    assertFalse(mDb.isValidJavaPackage("javax/swing/JButton"));
    assertFalse(mDb.isValidJavaPackage("java/rmi/Naming"));
    assertFalse(mDb.isValidJavaPackage("java/lang/instrument/Instrumentation"));
}
Example 101
Project: android-platform-tools-base-master  File: ApiLookupTest.java View source code
public void testIsValidPackage() {
    assertTrue(mDb.isValidJavaPackage("java/lang/Integer"));
    assertTrue(mDb.isValidJavaPackage("javax/crypto/Cipher"));
    assertTrue(mDb.isValidJavaPackage("java/awt/font/NumericShaper"));
    assertFalse(mDb.isValidJavaPackage("javax/swing/JButton"));
    assertFalse(mDb.isValidJavaPackage("java/rmi/Naming"));
    assertFalse(mDb.isValidJavaPackage("java/lang/instrument/Instrumentation"));
}