Java Code Examples for java.lang.instrument.Instrumentation#addTransformer()

The following examples show how to use java.lang.instrument.Instrumentation#addTransformer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScottAgent.java    From scott with MIT License 6 votes vote down vote up
public static void premain(String agentArgument, Instrumentation instrumentation) {
	instrumentation.addTransformer(new ClassFileTransformer() {
		@Override
		public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
			if (loader == null) {
				/*
				 * Leave the class alone, if it is being loaded by the Bootstrap classloader,
				 * as we don't want to do anything with JDK libs. See Issue #22.
				 */
				return classfileBuffer;
			} else {
				try {
					return new ScottClassTransformer().transform(classfileBuffer, ScottConfigurer.getConfiguration());
				} catch (Exception e) {
					System.err.println("Scott: test instrumentation failed for " + className + "!");
					e.printStackTrace();
					throw e;
				}
			}
		}
	});
}
 
Example 2
Source File: AbstractInstrumentationAgent.java    From tascalate-javaflow with Apache License 2.0 6 votes vote down vote up
protected void attach(String args, Instrumentation instrumentation) throws Exception {
    log.info("Installing agent...");
    
    // Collect classes before ever adding transformer!
    Set<String> ownPackages = new HashSet<String>(FIXED_OWN_PACKAGES);
    ownPackages.add(packageNameOf(getClass()) + '.');
    
    ClassFileTransformer transformer = createTransformer();
    instrumentation.addTransformer(transformer);
    if ("skip-retransform".equals(args)) {
        log.info("skip-retransform argument passed, skipping re-transforming classes");
    } else if (!instrumentation.isRetransformClassesSupported()) {
        log.info("JVM does not support re-transform, skipping re-transforming classes");
    } else {
        retransformClasses(instrumentation, ownPackages);
    }
    System.setProperty(transformer.getClass().getName(), "true");
    log.info("Agent was installed dynamically");
}
 
Example 3
Source File: Assembler.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void addTransformer(final String unitId, final ClassLoader classLoader, final ClassFileTransformer classFileTransformer) {
    final Instrumentation instrumentation = Agent.getInstrumentation();
    if (instrumentation != null) {
        instrumentation.addTransformer(classFileTransformer);

        if (unitId != null) {
            List<ClassFileTransformer> transformers = this.transformers.computeIfAbsent(unitId, k -> new ArrayList<>(1));
            transformers.add(classFileTransformer);
        }
    } else if (!logged.getAndSet(true)) {
        final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
        if (assembler != null) {
            assembler.logger.info("assembler.noAgent");
        } else {
            System.err.println("addTransformer: Assembler not initialized: JAVA AGENT NOT INSTALLED");
        }
    }
}
 
Example 4
Source File: SessionAgent.java    From HttpSessionReplacer with MIT License 6 votes vote down vote up
/**
 * Main entry point for the agent. It will parse arguments and add
 * {@link SessionSupportTransformer} to instrumentation. System property
 * com.amadeus.session.disabled can be used to deactivate the agent.
 *
 * @param agentArgs
 *          arguments passed on command line
 * @param inst
 *          the JVM instrumentation instance
 */
public static void premain(String agentArgs, Instrumentation inst) {
  if (agentActive) {
    throw new IllegalStateException("Agent started multiple times.");
  }
  agentActive = true;
  debugMode = Boolean.parseBoolean(System.getProperty(DEBUG_ACTIVE));
  readArguments(agentArgs);
  debug("Agent arguments: %s", agentArgs);

  boolean disabled = Boolean.parseBoolean(System.getProperty(SESSION_MANAGEMENT_DISABLED));
  interceptListener = Boolean.parseBoolean(System.getProperty(INTERCEPT_LISTENER_PROPERTY));

  if (!disabled) {
    debug("Code transformation is active");
    if (interceptListener) {
      debug("Will modify listeners to capture registered ones.");
    }

    inst.addTransformer(new SessionSupportTransformer(interceptListener));
  } else {
    debug("Agent is disabled.");
  }
}
 
Example 5
Source File: RO0Agent.java    From contrast-rO0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void setup(String args, Instrumentation inst) {
	properties = parseCommandLine(args);
	
	ClassFileTransformer xform = new RO0Transformer();
	inst.addTransformer(xform);
	readConfig(args);
}
 
Example 6
Source File: EvilInstrument.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void addTransformer(Instrumentation inst) {
    try {
        inst.addTransformer(new EvilTransformer());
    } catch(Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
}
 
Example 7
Source File: AgentTool.java    From vi with Apache License 2.0 5 votes vote down vote up
public static synchronized  void startUp(){
    if(!isLoaded){
        try {
            loadAgent();
            Instrumentation inst = instrumentation();
            inst.addTransformer(new CodeTransformer(), true);
            isLoaded = true;
        }catch (Throwable e){
            logger.warn("start agentTool failed",e);
        }
    }
}
 
Example 8
Source File: Premain.java    From jetty-alpn-agent with Apache License 2.0 5 votes vote down vote up
private static void configureClassFileTransformer(Instrumentation inst, URL artifactUrl) throws IOException {
    Map<String, byte[]> classes = new HashMap<>();
    try (JarInputStream jarIn = new JarInputStream(artifactUrl.openStream())) {
        byte[] buf = new byte[8192];
        while (true) {
            JarEntry e = jarIn.getNextJarEntry();
            if (e == null) {
                break;
            }

            String entryName = e.getName();
            if (!entryName.endsWith(".class")) {
                continue;
            }

            ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
            while (true) {
                int readBytes = jarIn.read(buf);
                if (readBytes < 0) {
                    break;
                }
                out.write(buf, 0, readBytes);
            }

            String className = entryName.substring(0, entryName.length() - 6);
            classes.put(className, out.toByteArray());
        }
    }
    inst.addTransformer(new ReplacingClassFileTransformer(classes));
}
 
Example 9
Source File: DummyAgent.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void premain(String agentArgs, Instrumentation inst) {
    inst.addTransformer(new DummyAgent(), false);
}
 
Example 10
Source File: Agent.java    From jandy with GNU General Public License v3.0 4 votes vote down vote up
public static void premain(String agentArgs, Instrumentation inst) {
  inst.addTransformer(new ProfilingClassFileTransformer());
}
 
Example 11
Source File: Agent.java    From krpc with Apache License 2.0 4 votes vote down vote up
public static void premain(String agentArgs, Instrumentation inst) {
    inst.addTransformer(new Transformer(agentArgs));
}
 
Example 12
Source File: DummyAgent.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void premain(String agentArgs, Instrumentation inst) {
    inst.addTransformer(new DummyAgent(), false);
}
 
Example 13
Source File: Agent.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
    Agent transformer = new Agent();
    instrumentation.addTransformer(transformer, true);

    redefine(agentArgs, instrumentation, Test.class);
}
 
Example 14
Source File: Agent.java    From callspy with Apache License 2.0 4 votes vote down vote up
public static void premain(String args, Instrumentation instrumentation){
  CallSpy transformer = new CallSpy();
  instrumentation.addTransformer(transformer);
}
 
Example 15
Source File: HelloWorldAgent.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static void agentmain(String args, Instrumentation inst) {
    inst.addTransformer(new HelloWorldAgent());
}
 
Example 16
Source File: PersistenceBootstrap.java    From tomee with Apache License 2.0 4 votes vote down vote up
public void addTransformer(final String unitId, final ClassLoader classLoader, final ClassFileTransformer classFileTransformer) {
    final Instrumentation instrumentation = Agent.getInstrumentation();
    if (instrumentation != null) {
        instrumentation.addTransformer(new Transformer(classFileTransformer));
    }
}
 
Example 17
Source File: Agent.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
    Agent transformer = new Agent();
    instrumentation.addTransformer(transformer, true);

    redefine(agentArgs, instrumentation, Test_class);
}
 
Example 18
Source File: AgentMain.java    From servicecomb-samples with Apache License 2.0 4 votes vote down vote up
public static void premain(String args, Instrumentation inst) {
  // to support web container, we can not just only inject spiJar to system classloader
  // in this sample, javaAgent jar equals ServiceComb plugin jar
  inst.addTransformer(
      new SCBClassFileTransformer(AgentMain.class.getProtectionDomain().getCodeSource().getLocation()));
}
 
Example 19
Source File: WdmAgent.java    From webdrivermanager with Apache License 2.0 4 votes vote down vote up
public static void premain(String args, Instrumentation instrumentation) {
    instrumentation.addTransformer(new DefineTransformer(), true);
}
 
Example 20
Source File: Enhancer.java    From bistoury with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 对象增强
 *
 * @param inst              inst
 * @param adviceId          通知ID
 * @param isTracing         可跟踪方法调用
 * @param skipJDKTrace      是否忽略对JDK内部方法的跟踪
 * @param classNameMatcher  类名匹配
 * @param methodNameMatcher 方法名匹配
 * @return 增强影响范围
 * @throws UnmodifiableClassException 增强失败
 */
public static synchronized EnhancerAffect enhance(
        final Instrumentation inst,
        final int adviceId,
        final boolean isTracing,
        final boolean skipJDKTrace,
        final Matcher classNameMatcher,
        final Matcher methodNameMatcher) throws UnmodifiableClassException {

    final EnhancerAffect affect = new EnhancerAffect();

    // 获取需要增强的类集合
    final Set<Class<?>> enhanceClassSet = GlobalOptions.isDisableSubClass
            ? SearchUtils.searchClass(inst, classNameMatcher)
            : SearchUtils.searchSubClass(inst, SearchUtils.searchClass(inst, classNameMatcher));

    // 过滤掉无法被增强的类
    filter(enhanceClassSet);

    // 构建增强器
    final Enhancer enhancer = new Enhancer(adviceId, isTracing, skipJDKTrace, enhanceClassSet, methodNameMatcher, affect);
    try {
        inst.addTransformer(enhancer, true);

        // 批量增强
        if (GlobalOptions.isBatchReTransform) {
            final int size = enhanceClassSet.size();
            final Class<?>[] classArray = new Class<?>[size];
            arraycopy(enhanceClassSet.toArray(), 0, classArray, 0, size);
            if (classArray.length > 0) {
                inst.retransformClasses(classArray);
                logger.info("Success to batch transform classes: " + Arrays.toString(classArray));
            }
        } else {
            // for each 增强
            for (Class<?> clazz : enhanceClassSet) {
                try {
                    inst.retransformClasses(clazz);
                    logger.info("Success to transform class: " + clazz);
                } catch (Throwable t) {
                    logger.warn("retransform {} failed.", clazz, t);
                    if (t instanceof UnmodifiableClassException) {
                        throw (UnmodifiableClassException) t;
                    } else if (t instanceof RuntimeException) {
                        throw (RuntimeException) t;
                    } else {
                        throw new RuntimeException(t);
                    }
                }
            }
        }
    } finally {
        inst.removeTransformer(enhancer);
    }

    return affect;
}