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

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

源代码1 项目: scott   文件: ScottAgent.java
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;
				}
			}
		}
	});
}
 
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");
}
 
源代码3 项目: tomee   文件: Assembler.java
@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");
        }
    }
}
 
源代码4 项目: HttpSessionReplacer   文件: SessionAgent.java
/**
 * 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.");
  }
}
 
源代码5 项目: vi   文件: AgentTool.java
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);
        }
    }
}
 
源代码6 项目: jetty-alpn-agent   文件: Premain.java
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));
}
 
源代码7 项目: openjdk-jdk8u   文件: EvilInstrument.java
private void addTransformer(Instrumentation inst) {
    try {
        inst.addTransformer(new EvilTransformer());
    } catch(Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
}
 
源代码8 项目: contrast-rO0   文件: RO0Agent.java
private static void setup(String args, Instrumentation inst) {
	properties = parseCommandLine(args);
	
	ClassFileTransformer xform = new RO0Transformer();
	inst.addTransformer(xform);
	readConfig(args);
}
 
源代码9 项目: jandy   文件: Agent.java
public static void premain(String agentArgs, Instrumentation inst) {
  inst.addTransformer(new ProfilingClassFileTransformer());
}
 
源代码10 项目: bistoury   文件: Enhancer.java
/**
 * 对象增强
 *
 * @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;
}
 
源代码11 项目: webdrivermanager   文件: WdmAgent.java
public static void premain(String args, Instrumentation instrumentation) {
    instrumentation.addTransformer(new DefineTransformer(), true);
}
 
源代码12 项目: servicecomb-samples   文件: AgentMain.java
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()));
}
 
源代码13 项目: openjdk-jdk9   文件: Agent.java
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
    Agent transformer = new Agent();
    instrumentation.addTransformer(transformer, true);

    redefine(agentArgs, instrumentation, Test_class);
}
 
源代码14 项目: tomee   文件: PersistenceBootstrap.java
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));
    }
}
 
源代码15 项目: netbeans   文件: HelloWorldAgent.java
public static void agentmain(String args, Instrumentation inst) {
    inst.addTransformer(new HelloWorldAgent());
}
 
源代码16 项目: callspy   文件: Agent.java
public static void premain(String args, Instrumentation instrumentation){
  CallSpy transformer = new CallSpy();
  instrumentation.addTransformer(transformer);
}
 
源代码17 项目: openjdk-jdk9   文件: Agent.java
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
    Agent transformer = new Agent();
    instrumentation.addTransformer(transformer, true);

    redefine(agentArgs, instrumentation, Test.class);
}
 
源代码18 项目: jdk8u-jdk   文件: DummyAgent.java
public static void premain(String agentArgs, Instrumentation inst) {
    inst.addTransformer(new DummyAgent(), false);
}
 
源代码19 项目: krpc   文件: Agent.java
public static void premain(String agentArgs, Instrumentation inst) {
    inst.addTransformer(new Transformer(agentArgs));
}
 
源代码20 项目: hottub   文件: DummyAgent.java
public static void premain(String agentArgs, Instrumentation inst) {
    inst.addTransformer(new DummyAgent(), false);
}