使用Unsafe.defineClass在运行时定义多个类

时间:2016-09-27 16:17:53

标签: java instrumentation unsafe verifyerror jvm-bytecode

我正在使用REPL获取我的自定义编程语言。它在编译器之上实现,它用于生成输入的字节码,并使用Class<?>方法将其转换为sun.misc.Unsafe.defineClass(String, byte[], int, int, ClassLoader, ProtectionDomain)实例。相关代码看起来像这样(省略了异常处理等无关的部分):

void compileAndLoad(List<ICompilable> compilables)
{
    List<Class<?>> classes = ...;
    for (ICompilable c : compilables)
    {
        classes.add(compile(compilable));
    }
    for (Class<?> c : classes)
    {
        UNSAFE.ensureClassInitialized(c);
    }
}

// CLASS_LOADER = Enclosing.class.getClassLoader()
// PROTECTION_DOMAIN = Enclosing.class.getClassLoader()

Class<?> compile(ICompilable compilable)
{
    byte[] bytecode = genBytecode(compilable);
    String name = compilable.getFullName() // e.g. 'foo.bar.Baz'
    return UNSAFE.defineClass(name, bytes, 0, bytes.length, CLASS_LOADER, PROTECTION_DOMAIN);
}

假设输入需要编译和加载多个类。

> class A { interface B { }; func b() = new B { /* anonymous class */ } }

compilables列表包含内容

[ repl.Result_0, repl.Result_0$A, repl.Result_0$A$0, repl.Result_0$A$B ]

repl.Result_0$A类依赖于repl.Result_0$A$0(匿名)类和repl.Result_0$B类,并在字节码中引用它们的名称。使用Unsafe定义时,会出现以下错误:

java.lang.NoClassDefFoundError: repl/Result_0$A$B
    at sun.misc.Unsafe.defineClass(Native Method)
    at MyClass.compile(MyClass.java:42)
    // ... snip
Caused by: java.lang.ClassNotFoundException: repl.Result_0$A$B
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 9 more

我知道这可以通过重新排序列表并首先定义repl.Result_0$A$B来解决,但这不是一般解决方案,因为也可以引用B -> A

有没有办法使用Unsafe.defineClass定义和加载多个类,而不会导致未解析类的验证错误?

1 个答案:

答案 0 :(得分:2)

您的问题并非特定于Unsafe.defineClass,而是与程序逻辑有关。无论何时“推送”多个新类,无论是使用ClassLoader.defineClass还是Unsafe.defineClass,都必须避免使用前向引用,这会阻止在类依赖项中出现循环。 / p>

对于Unsafe.defineClass的实际预期用例,例如反射访问器,有明确的依赖方向,因此没有问题,但对于您的用例,它不是正确的工具。您必须定义一个类加载器,它允许JVM在需要时“”类,例如。

void compileAndLoad(List<ICompilable> compilables) {
    Map<String,byte[]> compiled = new HashMap<>(compilables.size());
    for(ICompilable c: compilables)
        compiled.put(c.getFullName(), genBytecode(c));
    ClassLoader l = new ClassLoader(CLASS_LOADER) {
        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            byte[] code = compiled.get(name);
            if(code == null) throw new ClassNotFoundException(name);
            return defineClass(name, code, 0, code.length);
        }
    };
    // the code below this line is questionable; it seems you are relying
    // on the side effects of a class initializer
    for(String name: compiled.keySet()) try {
        Class.forName(name, true, l);
    } catch (ClassNotFoundException ex) { throw new AssertionError(ex); }
}

请注意,代码使用Class.forName而非loadClass来强制执行原始代码的初始化。通常,代码不应该依赖于立即初始化,但是你没有将加载的类用于其他任何东西,所以它不清楚,有什么替代。通常的程序是将loadClass用于随后要使用的类并返回它;初始化(以及依赖项的加载和初始化)将在其实际使用中发生。

进一步注意,整个代码无需使用Unsafe ...

即可运行
相关问题