下面列出了java.lang.instrument.Instrumentation#addTransformer ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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");
}
@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");
}
}
}
/**
* 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.");
}
}
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);
}
}
}
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));
}
private void addTransformer(Instrumentation inst) {
try {
inst.addTransformer(new EvilTransformer());
} catch(Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
private static void setup(String args, Instrumentation inst) {
properties = parseCommandLine(args);
ClassFileTransformer xform = new RO0Transformer();
inst.addTransformer(xform);
readConfig(args);
}
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new ProfilingClassFileTransformer());
}
/**
* 对象增强
*
* @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;
}
public static void premain(String args, Instrumentation instrumentation) {
instrumentation.addTransformer(new DefineTransformer(), true);
}
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()));
}
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
Agent transformer = new Agent();
instrumentation.addTransformer(transformer, true);
redefine(agentArgs, instrumentation, Test_class);
}
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));
}
}
public static void agentmain(String args, Instrumentation inst) {
inst.addTransformer(new HelloWorldAgent());
}
public static void premain(String args, Instrumentation instrumentation){
CallSpy transformer = new CallSpy();
instrumentation.addTransformer(transformer);
}
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
Agent transformer = new Agent();
instrumentation.addTransformer(transformer, true);
redefine(agentArgs, instrumentation, Test.class);
}
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new DummyAgent(), false);
}
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new Transformer(agentArgs));
}
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new DummyAgent(), false);
}