Skip to content

Commit

Permalink
testsuite: Add test for sun.misc.Unsafe
Browse files Browse the repository at this point in the history
  • Loading branch information
kiritofeng committed Dec 22, 2023
1 parent 6003c3c commit 0ec2343
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
46 changes: 46 additions & 0 deletions testsuite/helloworld/tests/java_unsafe/HelloWorld.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import sun.misc.Unsafe;

class OffHeapArray {
private final static int BYTE = 1;
private long size;
private long address;

public OffHeapArray(long size) throws NoSuchFieldException, IllegalAccessException {
this.size = size;
address = getUnsafe().allocateMemory(size * BYTE);
}

private Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe) f.get(null);
}

public void set(long i, byte value) throws NoSuchFieldException, IllegalAccessException {
getUnsafe().putByte(address + i * BYTE, value);
}

public int get(long idx) throws NoSuchFieldException, IllegalAccessException {
return getUnsafe().getByte(address + idx * BYTE);
}

public long size() {
return size;
}

public void freeMemory() throws NoSuchFieldException, IllegalAccessException {
getUnsafe().freeMemory(address);
}
}

public class HelloWorld {
public static void main(String[] args) throws Exception {
OffHeapArray bigarray = new OffHeapArray(64*8*1024*1024);
for (int i = 0; i < 131072; i++) bigarray.set(i * 4096 + 16, (byte) 1);
System.out.println("Hello, World!");
}
}
// Source: https://dmoj.ca/src/5961758
6 changes: 6 additions & 0 deletions testsuite/helloworld/tests/java_unsafe/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
language: JAVA8
time: 5
memory: 65535
source: HelloWorld.java
expect: IR
feedback: ca.dmoj.java.UnsafeDisallowedException

0 comments on commit 0ec2343

Please sign in to comment.