下面列出了java.lang.instrument.Instrumentation#getAllLoadedClasses ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static Class<?> findLibClass(Instrumentation inst, final String libClass) {
if (libClass == null || "".equals(libClass)) {
ps.println("can not find lib class, [" + libClass + "]");
throw new IllegalStateException("can not find lib class, [" + libClass + "]");
}
Class[] allLoadedClasses = inst.getAllLoadedClasses();
for (Class clazz : allLoadedClasses) {
if (libClass.equals(clazz.getName())) {
return clazz;
}
}
ps.println("can not find lib class, [" + libClass + "]");
ps.println("begin print all loaded classes");
for (Class allLoadedClass : allLoadedClasses) {
ps.println("[" + allLoadedClass.getName() + "]");
}
ps.println("end print all loaded classes");
throw new IllegalStateException("can not find lib class, [" + libClass + "]");
}
/**
*
* @param jvmInfo
* @param inst
* @return
*/
public static void getAllLoadedClass(JvmInfo jvmInfo, Instrumentation inst) {
for (Class classz : inst.getAllLoadedClasses()) {
try {
jvmInfo.getClassFileList().add(classz.getName());
jvmInfo.getJarPathMap().put(classz.getResource("/").toString(),"");
}
catch (Exception e) {
jvmInfo.getErrorList().add("getAllLoadedClass:\t" + e.toString());
}
}
}
private static void transformClass(String className, Instrumentation instrumentation) {
Class<?> targetCls = null;
ClassLoader targetClassLoader = null;
// see if we can get the class using forName
try {
targetCls = Class.forName(className);
targetClassLoader = targetCls.getClassLoader();
transform(targetCls, targetClassLoader, instrumentation);
return;
} catch (Exception ex) {
LOGGER.error("Class [{}] not found with Class.forName");
}
// otherwise iterate all loaded classes and find what we want
for(Class<?> clazz: instrumentation.getAllLoadedClasses()) {
if(clazz.getName().equals(className)) {
targetCls = clazz;
targetClassLoader = targetCls.getClassLoader();
transform(targetCls, targetClassLoader, instrumentation);
return;
}
}
throw new RuntimeException("Failed to find class [" + className + "]");
}
public static void premain(String agentArgs, Instrumentation inst) throws ClassNotFoundException {
preloadClasses();
inst.addTransformer(new SnoopInstructionTransformer(), true);
if (inst.isRetransformClassesSupported()) {
for (Class clazz : inst.getAllLoadedClasses()) {
try {
String cname = clazz.getName().replace(".","/");
if (shouldExclude(cname) == false) {
if (inst.isModifiableClass(clazz)) {
inst.retransformClasses(clazz);
} else {
println("[WARNING] Could not instrument " + clazz);
}
}
} catch (Exception e){
if (verbose) {
println("[WARNING] Could not instrument " + clazz);
e.printStackTrace();
}
}
}
}
}
public static void agentmain(String args, Instrumentation inst){
INST=inst;
System.out.println("agentmain----agentArgs:"+args);
Class clazz=null;
for (Class allLoadedClass : inst.getAllLoadedClasses()) {
if(allLoadedClass.getName().equals(args)){
clazz=allLoadedClass;break;
}
}
System.out.println("agentmain----,clazz:"+clazz);
if(clazz!=null){
try {
Method initMethod=clazz.getDeclaredMethod("init", new Class[]{Instrumentation.class});
initMethod.setAccessible(true);
Object result = initMethod.invoke(null, inst);
System.out.println("agentmain------,initSuccess");
if(inst.isRetransformClassesSupported() && result!=null){
ClassFileTransformer classFileTransformer=(ClassFileTransformer)result;
inst.addTransformer(classFileTransformer,true);
System.out.println("agentmain------,hookClassFileTransformer success");
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public static void premain(String args, Instrumentation instrumentation) {
if (!instrumentation.isRetransformClassesSupported()) {
System.out.println("Class retransformation is not supported.");
return;
}
System.out.println("Calling lambda to ensure that lambda forms were created");
Agent.lambda.run();
System.out.println("Registering class file transformer");
instrumentation.addTransformer(new Agent());
for (Class c : instrumentation.getAllLoadedClasses()) {
if (c.getName().contains("LambdaForm") &&
instrumentation.isModifiableClass(c)) {
System.out.format("We've found a modifiable lambda form: %s%n", c.getName());
try {
instrumentation.retransformClasses(c);
} catch (UnmodifiableClassException e) {
throw new AssertionError("Modification of modifiable class " +
"caused UnmodifiableClassException", e);
}
}
}
}
/**
* JVM hook to dynamically load javaagent at runtime.
*
* The agent class may have an agentmain method for use when the agent is
* started after VM startup.
*
* @param args arguments supplied to the agent
* @param instrumentation {@link Instrumentation} object passed by JVM
* @throws Exception thrown when agent is unable to start
*/
public static void agentmain(String args, Instrumentation instrumentation) throws Exception {
setupInstrumentation(instrumentation);
for (Class<?> clazz : instrumentation.getAllLoadedClasses()) {
if (instrumentation.isModifiableClass(clazz) &&
!AsyncAwaitClassFileTransformer.skipClassByName(clazz.getName())) {
try {
instrumentation.retransformClasses(clazz);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
System.setProperty(AsyncAwaitInstrumentationAgent.class.getName(), "true");
System.setProperty("org.apache.commons.javaflow.instrumentation.JavaFlowInstrumentationAgent", "true");
}
private static void reloadClasses(Instrumentation inst) {
for (Class<?> loadedClass : inst.getAllLoadedClasses()) {
if (Transformer.needsTransform(loadedClass.getName())) {
try {
inst.retransformClasses(loadedClass);
} catch (Throwable e) {
log.log(Level.WARNING, "Failed instrumenting " + loadedClass.getName() + ". Shared secret extraction might fail.", e);
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
return;
}
throw new IllegalStateException(e);
}
}
}
}
private static Class<?> findOneAppLibClass(Instrumentation instrumentation) {
Class[] allLoadedClasses = instrumentation.getAllLoadedClasses();
final String libClass = System.getProperty("bistoury.app.lib.class");
if (Strings.isNullOrEmpty(libClass)) {
System.err.println("can not find lib class, [" + libClass + "]");
throw new IllegalStateException("can not find lib class, [" + libClass + "]");
}
for (Class clazz : allLoadedClasses) {
if (libClass.equals(clazz.getName())) {
return clazz;
}
}
System.err.println("can not find lib class, [" + libClass + "]");
throw new IllegalStateException("can not find lib class, [" + libClass + "]");
}
public static Set<Class<?>> searchClass(Instrumentation inst, String searchName, int limit) {
if (StringUtils.isBlank(searchName)) {
return Collections.emptySet();
}
final Set<Class<?>> matches = new HashSet<>();
for (Class<?> clazz : inst.getAllLoadedClasses()) {
if (searchName.equals(clazz.getName())) {
matches.add(clazz);
}
if (matches.size() >= limit) {
break;
}
}
return matches;
}
public static void premain(@SuppressWarnings("unused") String agentArgs,
Instrumentation instrumentation) {
try {
Class<?>[] allPriorLoadedClasses;
if (PRE_CHECK_LOADED_CLASSES) {
allPriorLoadedClasses = instrumentation.getAllLoadedClasses();
} else {
allPriorLoadedClasses = new Class<?>[0];
}
CodeSource codeSource = AgentPremain.class.getProtectionDomain().getCodeSource();
// suppress warnings is used instead of annotating this method with @Nullable
// just to avoid dependencies on other classes (in this case the @Nullable annotation)
@SuppressWarnings("argument.type.incompatible")
File glowrootJarFile = getGlowrootJarFile(codeSource);
Class<?> mainEntryPointClass;
if (glowrootJarFile != null) {
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(glowrootJarFile));
}
mainEntryPointClass = Class.forName("org.glowroot.agent.MainEntryPoint", true,
AgentPremain.class.getClassLoader());
Method premainMethod = mainEntryPointClass.getMethod("premain", Instrumentation.class,
Class[].class, File.class);
premainMethod.invoke(null, instrumentation, allPriorLoadedClasses, glowrootJarFile);
} catch (Throwable t) {
// log error but don't re-throw which would prevent monitored app from starting
System.err.println("Glowroot failed to start: " + t.getMessage());
t.printStackTrace();
}
}
/**
* 搜索目标类的子类
*
* @param inst inst
* @param classSet 当前类集合
* @return 匹配的子类集合
*/
public static Set<Class<?>> searchSubClass(Instrumentation inst, Set<Class<?>> classSet) {
final Set<Class<?>> matches = new HashSet<Class<?>>();
for (Class<?> clazz : inst.getAllLoadedClasses()) {
for (Class<?> superClass : classSet) {
if (superClass.isAssignableFrom(clazz)) {
matches.add(clazz);
break;
}
}
}
return matches;
}
public static Set<ClassLoader> getAllClassLoader(Instrumentation inst) {
Set<ClassLoader> classLoaderSet = new HashSet<ClassLoader>();
for (Class<?> clazz : inst.getAllLoadedClasses()) {
ClassLoader classLoader = clazz.getClassLoader();
if (classLoader != null) {
classLoaderSet.add(classLoader);
}
}
return classLoaderSet;
}
public static ClassLoader getClassLoader(Instrumentation inst, String hashCode) {
if (hashCode == null || hashCode.isEmpty()) {
return null;
}
for (Class<?> clazz : inst.getAllLoadedClasses()) {
ClassLoader classLoader = clazz.getClassLoader();
if (classLoader != null) {
if (Integer.toHexString(classLoader.hashCode()).equals(hashCode)) {
return classLoader;
}
}
}
return null;
}
public static List<String> loadedClasses() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
List<String> rtn = new ArrayList<>();
Instrumentation inst = instrumentation();
Class[] classes = inst.getAllLoadedClasses();
for(Class c:classes){
rtn.add(c.getName());
}
return rtn;
}
public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
if (inst.isRedefineClassesSupported() && inst.isRetransformClassesSupported()) {
inst.addTransformer(new Redefiner(), true);
Class<?>[] allClasses = inst.getAllLoadedClasses();
for (int i = 0; i < allClasses.length; i++) {
Class<?> c = allClasses[i];
if (c == Intrinsic.class) {
inst.retransformClasses(new Class<?>[]{c});
}
}
}
}
public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
if (inst.isRedefineClassesSupported() && inst.isRetransformClassesSupported()) {
inst.addTransformer(new FooTransformer(), true);
Class<?>[] allClasses = inst.getAllLoadedClasses();
for (int i = 0; i < allClasses.length; i++) {
Class<?> c = allClasses[i];
if (c == Foo.class) {
inst.retransformClasses(new Class<?>[]{c});
}
}
}
}
public static void main(String[] args) throws Exception {
Instrumentation inst = Agent.inst;
if (inst == null)
throw new RuntimeException("Agent not loaded");
// check boot class path has been extended
Class<?> helper = Class.forName("AgentHelper");
if (helper.getClassLoader() != null)
throw new RuntimeException("AgentHelper not loaded by boot loader");
// check Instrumentation object can be used
Class<?>[] classes = inst.getAllLoadedClasses();
System.out.println(classes.length + " classes loaded");
}
public static boolean completeClassName(Completion completion) {
List<CliToken> tokens = completion.lineTokens();
String lastToken = tokens.get(tokens.size() - 1).value();
if (StringUtils.isBlank(lastToken)) {
lastToken = "";
}
if (lastToken.startsWith("-")) {
return false;
}
Instrumentation instrumentation = completion.session().getInstrumentation();
Class<?>[] allLoadedClasses = instrumentation.getAllLoadedClasses();
Set<String> result = new HashSet<String>();
for(Class<?> clazz : allLoadedClasses) {
String name = clazz.getName();
if (name.startsWith("[")) {
continue;
}
if(name.startsWith(lastToken)) {
int index = name.indexOf('.', lastToken.length());
if(index > 0) {
result.add(name.substring(0, index + 1));
}else {
result.add(name);
}
}
}
if(result.size() == 1 && result.iterator().next().endsWith(".")) {
completion.complete(result.iterator().next().substring(lastToken.length()), false);
}else {
CompletionUtils.complete(completion, result);
}
return true;
}
protected void retransformClasses(Instrumentation instrumentation, Set<String> ownPackages) {
log.info("Re-transforming existing classes...");
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
for (Class<?> clazz : instrumentation.getAllLoadedClasses()) {
String className = clazz.getName();
if (instrumentation.isModifiableClass(clazz)) {
if (isClassLoaderParent(systemClassLoader, clazz.getClassLoader())) {
if (log.isTraceEnabled()) {
log.trace("Skip re-transforming boot or extension/platform class: " + className);
}
continue;
}
boolean isOwnClass = false;
for (String ownPackage : ownPackages) {
if (className.startsWith(ownPackage)) {
isOwnClass = true;
break;
}
}
if (isOwnClass) {
if (log.isDebugEnabled()) {
log.debug("Skip re-transforming class (agent class): " + className);
}
continue;
}
if (log.isDebugEnabled()) {
log.debug("Re-transforming class: " + className);
}
try {
instrumentation.retransformClasses(clazz);
} catch (Throwable e) {
log.error("Error re-transofrming class "+ className, e);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Non-modifiable class (re-transforming skipped): " + className);
}
}
}
log.info("Existing classes was re-transormed");
}