Arthas

Arthas mc内存动态编译原理

2021-05-09  本文已影响0人  晴天哥_王志

系列

开篇

动态编译

// 定义动态编译的输入对象
public class SourceJavaFileObject extends SimpleJavaFileObject {
    private String source; //源码字符串
    
    //返回源码字符串
    public SourceJavaFileObject(String name, String sourceStr){ 
            super(URI.create("String:///" + name + Kind.SOURCE.extension),Kind.SOURCE);
            this.source = sourceStr;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException{
        if(source == null) throw new IllegalArgumentException("source == null");
        else return source;
    }
}
// 定义动态编译的输出对象
public static class ClassJavaFileObject extends SimpleJavaFileObject {

    private ByteArrayOutputStream byteArrayOutputStream; //字节数组输出流
      // 编译完成后会回调OutputStream,回调成功后,
      // 我们就可以通过下面的getByteCode()方法获取编译后的字节码字节数组

    public ClassJavaFileObject(String name, Kind kind){
        super(URI.create("String:///" + name + kind.extension), kind);
        source = null;
    }

    @Override
    public OutputStream openOutputStream() throws IOException {
        byteArrayOutputStream = new ByteArrayOutputStream();

        return byteArrayOutputStream;
    }

    //将输出流中的字节码转换为字节数组
    public byte[] getCompiledBytes() {
        return byteArrayOutputStream.toByteArray();
    }
}
// 定义动态编译管理Manager对象
public static class MyJavaObjectManager extends ForwardingJavaFileManager<JavaFileManager>{

    private ClassFileObject classObject; //我们自定义的JavaFileObject

     //重写该方法,使其返回我们的ClassJavaFileObject
    @Override
    public JavaFileObject getJavaFileForOutput(Location location, String className, 
                                               JavaFileObject.Kind kind,
                                               FileObject sibling) throws IOException {

        classObject= new ClassJavaFileObject(className, kind);

        return classObject;
    }
}
// 串联整体源码动态编译过程
public class CompileFileToFile {

  public static void main(String[] args) {
    //获取系统Java编译器
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    // 获取源码文件的SourceJavaFileObject
    SourceJavaFileObject sourceFileObject = new SourceJavaFileObject("name",  "source code");

    // 执行源码编译
    Boolean result = compiler.getTask(null,new MyJavaObjectManager(), 
                null, null, null, Arrays.asList(sourceFileObject)).call(); 
}

编译任务getTask()这个方法一共有 6 个参数,它们分别是:

Arthas动态编译

public class MemoryCompilerCommand extends AnnotatedCommand {

    @Override
    public void process(final CommandProcess process) {
        RowAffect affect = new RowAffect();

        try {
            Instrumentation inst = process.session().getInstrumentation();

            // 定义ClassLoader对象
            ClassLoader classloader = null;
            if (hashCode == null) {
                classloader = ClassLoader.getSystemClassLoader();
            } else {
                classloader = ClassLoaderUtils.getClassLoader(inst, hashCode);
                if (classloader == null) {
                    process.end(-1, "Can not find classloader with hashCode: " + hashCode + ".");
                    return;
                }
            }

            // 定义DynamicCompiler的对象
            DynamicCompiler dynamicCompiler = new DynamicCompiler(classloader);

            Charset charset = Charset.defaultCharset();
            if (encoding != null) {
                charset = Charset.forName(encoding);
            }

            // 待编译的java源文件
            for (String sourceFile : sourcefiles) {
                // 将待编译的java文件编译成class源文件
                String sourceCode = FileUtils.readFileToString(new File(sourceFile), charset);
                String name = new File(sourceFile).getName();
                if (name.endsWith(".java")) {
                    name = name.substring(0, name.length() - ".java".length());
                }
                // 添加到动态编译器的待编译源文件中
                dynamicCompiler.addSource(name, sourceCode);
            }
            
            // 执行动态编译
            Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes();

            File outputDir = null;
            if (this.directory != null) {
                outputDir = new File(this.directory);
            } else {
                outputDir = new File("").getAbsoluteFile();
            }
            // 输出字节码到class文件中
            List<String> files = new ArrayList<String>();
            for (Entry<String, byte[]> entry : byteCodes.entrySet()) {
                File byteCodeFile = new File(outputDir, entry.getKey().replace('.', '/') + ".class");
                FileUtils.writeByteArrayToFile(byteCodeFile, entry.getValue());
                files.add(byteCodeFile.getAbsolutePath());
                affect.rCnt(1);
            }
        } catch (Throwable e) {
          // 省略相关代码
        }
    }
}
public class DynamicCompiler {
    // 定义动态编译器JavaCompiler
    private final JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    // 动态编译的自定义文件管理器,需要自定义
    private final StandardJavaFileManager standardFileManager;
    // 保存动态编译的options
    private final List<String> options = new ArrayList<String>();
    private final DynamicClassLoader dynamicClassLoader;
    // 保存待编译的源文件对应的JavaFileObject
    private final Collection<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>();

    public DynamicCompiler(ClassLoader classLoader) {
        // 动态编译的文件管理器
        standardFileManager = javaCompiler.getStandardFileManager(null, null, null);
        options.add("-Xlint:unchecked");
        // dynamicClassLoader负责保存编译后的字节码和class类对象
        dynamicClassLoader = new DynamicClassLoader(classLoader);
    }

    public Map<String, Class<?>> build() {

        JavaFileManager fileManager = new DynamicJavaFileManager(standardFileManager, dynamicClassLoader);
        DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>();
        // 定义
        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, collector, options, null,
                        compilationUnits);

        try {
            // 执行动态编译
            if (!compilationUnits.isEmpty()) {
                boolean result = task.call();
            }
            // 返回动态编译的结果
            return dynamicClassLoader.getClasses();
        } catch (Throwable e) {
        } finally {
        }

    }

    public Map<String, byte[]> buildByteCodes() {

        JavaFileManager fileManager = new DynamicJavaFileManager(standardFileManager, dynamicClassLoader);

        DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>();
        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, collector, options, null,
                        compilationUnits);

        try {
            // 返回编译的字节码
            return dynamicClassLoader.getByteCodes();
        } catch (ClassFormatError e) {
        } finally {
        }
    }

    public void addSource(String className, String source) {
        // 添加待编译的源码字节流
        addSource(new StringSource(className, source));
    }

    public void addSource(JavaFileObject javaFileObject) {
        compilationUnits.add(javaFileObject);
    }
}
public class StringSource extends SimpleJavaFileObject {
    private final String contents;

    public StringSource(String className, String contents) {
        super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
        this.contents = contents;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
        return contents;
    }

}
public class MemoryByteCode extends SimpleJavaFileObject {
    private static final char PKG_SEPARATOR = '.';
    private static final char DIR_SEPARATOR = '/';
    private static final String CLASS_FILE_SUFFIX = ".class";

    private ByteArrayOutputStream byteArrayOutputStream;

    public MemoryByteCode(String className) {
        super(URI.create("byte:///" + className.replace(PKG_SEPARATOR, DIR_SEPARATOR)
                + Kind.CLASS.extension), Kind.CLASS);
    }

    public MemoryByteCode(String className, ByteArrayOutputStream byteArrayOutputStream)
            throws URISyntaxException {
        this(className);
        this.byteArrayOutputStream = byteArrayOutputStream;
    }

    @Override
    public OutputStream openOutputStream() throws IOException {
        if (byteArrayOutputStream == null) {
            byteArrayOutputStream = new ByteArrayOutputStream();
        }
        return byteArrayOutputStream;
    }

    public byte[] getByteCode() {
        return byteArrayOutputStream.toByteArray();
    }

    public String getClassName() {
        String className = getName();
        className = className.replace(DIR_SEPARATOR, PKG_SEPARATOR);
        className = className.substring(1, className.indexOf(CLASS_FILE_SUFFIX));
        return className;
    }
}
public class DynamicJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> {
    private static final String[] superLocationNames = { StandardLocation.PLATFORM_CLASS_PATH.name(),
            /** JPMS StandardLocation.SYSTEM_MODULES **/
            "SYSTEM_MODULES" };
    private final PackageInternalsFinder finder;

    private final DynamicClassLoader classLoader;
    private final List<MemoryByteCode> byteCodes = new ArrayList<MemoryByteCode>();

    public DynamicJavaFileManager(JavaFileManager fileManager, DynamicClassLoader classLoader) {
        super(fileManager);
        this.classLoader = classLoader;

        finder = new PackageInternalsFinder(classLoader);
    }

    @Override
    public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className,
                    JavaFileObject.Kind kind, FileObject sibling) throws IOException {

        for (MemoryByteCode byteCode : byteCodes) {
            if (byteCode.getClassName().equals(className)) {
                return byteCode;
            }
        }

        MemoryByteCode innerClass = new MemoryByteCode(className);
        byteCodes.add(innerClass);
        classLoader.registerCompiledSource(innerClass);

        return innerClass;
    }
}
public class DynamicClassLoader extends ClassLoader {
    private final Map<String, MemoryByteCode> byteCodes = new HashMap<String, MemoryByteCode>();

    public DynamicClassLoader(ClassLoader classLoader) {
        super(classLoader);
    }

    public void registerCompiledSource(MemoryByteCode byteCode) {
        byteCodes.put(byteCode.getClassName(), byteCode);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        MemoryByteCode byteCode = byteCodes.get(name);
        if (byteCode == null) {
            return super.findClass(name);
        }
        // 通过父类的defineClass来加载类
        return super.defineClass(name, byteCode.getByteCode(), 0, byteCode.getByteCode().length);
    }

    public Map<String, Class<?>> getClasses() throws ClassNotFoundException {
        Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
        for (MemoryByteCode byteCode : byteCodes.values()) {
            classes.put(byteCode.getClassName(), findClass(byteCode.getClassName()));
        }
        return classes;
    }

    public Map<String, byte[]> getByteCodes() {
        Map<String, byte[]> result = new HashMap<String, byte[]>(byteCodes.size());
        for (Entry<String, MemoryByteCode> entry : byteCodes.entrySet()) {
            result.put(entry.getKey(), entry.getValue().getByteCode());
        }
        return result;
    }
}

参考文章

上一篇下一篇

猜你喜欢

热点阅读