1 package alt.jiapi.agent; 2 3 import java.lang.instrument.ClassFileTransformer ; 4 import java.lang.instrument.Instrumentation ; 5 import java.security.ProtectionDomain ; 6 import java.util.Properties ; 7 import java.util.StringTokenizer ; 8 9 import alt.jiapi.reflect.JiapiClass; 10 import alt.jiapi.InstrumentationDescriptor; 11 import alt.jiapi.InstrumentationContext; 12 import alt.jiapi.interceptor.*; 13 14 import java.lang.reflect.InvocationHandler ; 15 16 41 public class InstrumentationAgent implements ClassFileTransformer { 42 private String agentArgs; 43 private Instrumentation instrumentation; 44 private Transformer transformer; 45 46 public static void premain(String agentArgs, Instrumentation i) { 47 Properties p = new Properties (); 48 49 if (agentArgs != null) { 53 StringTokenizer st = new StringTokenizer (agentArgs, ","); 54 while(st.hasMoreTokens()) { 55 String nv = st.nextToken(); 56 57 StringTokenizer st2 = new StringTokenizer (nv, "="); 58 String n = st2.nextToken(); 59 String v = null; 60 if (st2.hasMoreTokens()) { 61 v = st2.nextToken(); 62 } 63 else { 64 v = ""; 65 } 66 67 p.setProperty(n, v); 68 } 69 } 70 71 try { 72 String tr = p.getProperty("transformer", 75 "alt.jiapi.agent.HotSpotTransformer"); 76 if (tr != null) { 77 Class c = Class.forName(tr); 78 79 Object o = c.newInstance(); 80 81 Transformer tf = (Transformer)o; 82 tf.init(p); 83 84 InstrumentationAgent jcft = 86 new InstrumentationAgent(agentArgs, i, tf); 87 88 i.addTransformer(jcft); 89 } 90 else { 91 System.out.println("Failed to create Transformer: Missing agent parameter 'transformer'"); 92 InstrumentationAgent jcft = 94 new InstrumentationAgent(agentArgs, i, null); 95 96 i.addTransformer(jcft); 97 } 98 } 99 catch(Exception e) { 100 System.out.println("Failed to create Transformer: " + e); 101 e.printStackTrace(); 102 } 103 } 104 105 106 public InstrumentationAgent(String agentArgs, Instrumentation i, Transformer transformer) { 107 this.agentArgs = agentArgs; 108 this.instrumentation = i; 109 this.transformer = transformer; 110 } 111 112 public byte[] transform(ClassLoader cl, String className, 113 Class <?> classBeingRedefined, 114 ProtectionDomain pd, 115 byte[] classFileBuffer) { 116 if (transformer == null) { 117 return null; 118 } 119 else { 120 byte[] tempBuffer = new byte[classFileBuffer.length]; 123 System.arraycopy(classFileBuffer, 0, tempBuffer, 0, 124 classFileBuffer.length); 125 126 try { 127 JiapiClass jc = JiapiClass.parseClass(tempBuffer); 128 129 if (transformer.transform(jc)) { 130 return jc.getByteCode(); 131 } 132 } 133 catch(Exception e) { 134 e.printStackTrace(); 135 } 136 137 return null; 138 } 139 } 140 } 141 | Popular Tags |