1

我想将一个应用程序沙箱化,最终用户可以在其中将 Java 代码提交到编译和执行它的服务器(一种基于 Web 的 IDE,作为教育游戏的一部分)。大多数方面都可以通过使用标准安全管理器或使用 ASM 或类似工具根据白名单验证使用的 API 来轻松处理。

一个悬而未决的问题是如何处理无限循环。由于线程有自己的堆栈,StackOverFlowErrors 似乎是线程本地的。我做了一个小秒杀并想出了这个:

public class TryToSurviveAStackOverflow {

public static void main(String[] args) throws Exception {

    final Runnable infiniteLoop = new Runnable() {
        @Override public void run() {
            run();
        }
    };

    Runnable sandboxed = new Runnable() {
            @Override public void run() {
                try {
                    Thread.sleep(10000); // some time to connect VisualVM to monitor this
                    infiniteLoop.run();
                }
                catch (StackOverflowError x) {
                    System.err.println("Thread crashed with stack overflow");
                } catch (InterruptedException e) {
                    System.err.println("Thread interruped");
                }
            }
        };

        Thread thread = new Thread(sandboxed,"infinite loop");
        thread.start();
        thread.join();
        System.out.println(thread.getState());

        System.out.println("I am still alive");

}

}

这似乎有效,但这有多安全?特别是,不安全线程使用的堆栈空间会发生什么变化?我可以看到线程的状态设置为 TERMINATED。

任何帮助/指针都非常感谢!

干杯,延斯

4

0 回答 0