judge-server icon indicating copy to clipboard operation
judge-server copied to clipboard

Whitelist builtin Java exceptions, rather than display any

Open Xyene opened this issue 1 year ago • 6 comments

Xyene avatar Mar 14 '23 01:03 Xyene

Overkill solution:

For Java 8, use ZipFile to list the contents of /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/rt.jar and filter anything ending with Exception|Error. Only a handful of builtin throwables don't follow this pattern (ThreadDeath is the only one I could quickly find).

For Java 9+ which moved classes to the JRT "filesystem", use something like the code below:

Main.java
import java.util.*;
import java.nio.file.*;
import java.net.*;

public class Main {
    private static void listFiles(Path dir) throws Exception {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path entry : stream) {
                if (Files.isDirectory(entry)) {
                    listFiles(entry);
                } else {
                    String demangledName = demangleClassName(entry);
                    if (demangledName.endsWith("Exception") || demangledName.endsWith("Error")) {
                        System.out.println(demangledName);
                    }
                }
            }
        }
    }

    private static String demangleClassName(Path filePath) {
        String fileName = filePath.toString();
        String withoutExtension = fileName.substring(0, fileName.lastIndexOf('.'));
        String withoutLeadingPackages = withoutExtension.replaceFirst("^/packages/.*?/.*?/", "");
        String demangledName = withoutLeadingPackages.replace('$', '.').replace('/', '.');
        return demangledName;
    }

    public static void main(String[] args) throws java.lang.Exception {
        FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
        Path rootPath = fs.getPath("/");
        listFiles(rootPath);
    }
}

Maybe this should just live as a cronjob...? Not sure.

Xyene avatar Jan 01 '24 00:01 Xyene

Should we try dynamically loading the classes and checking if they extend java.lang.Exception? :stuck_out_tongue:

kiritofeng avatar Jan 01 '24 00:01 kiritofeng

If we're doing that then we should definitely do it as a cronjob, otherwise doing it on startup would take too long.

Xyene avatar Jan 01 '24 00:01 Xyene

I'm in favour of doing it as a cronjob via Github Actions since this list will only change when Java updates, which is relatively infrequent (and not really worth the overhead on startup).

kiritofeng avatar Jan 01 '24 01:01 kiritofeng

If by cronjob then we ought to do only the Java 9+ thing, since exceptions are unlikely to be removed, but may be added.

Xyene avatar Jan 01 '24 01:01 Xyene

And I guess to make this more likely, we should only whitelist java.* exceptions.

Xyene avatar Jan 01 '24 18:01 Xyene