Skip to content

Instantly share code, notes, and snippets.

@Garciat
Created April 29, 2017 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Garciat/745545a62584dd079055d10841c8777c to your computer and use it in GitHub Desktop.
Save Garciat/745545a62584dd079055d10841c8777c to your computer and use it in GitHub Desktop.
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class Program {
private static final Unsafe UNSAFE;
static {
Unsafe it = null;
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
it = (Unsafe) field.get(null);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
UNSAFE = it;
}
}
public static void main(String[] args) throws Exception {
byte[] data = {'h', 'e', 'l', 'l', 'o'};
Pointer ptr = new Pointer(toAddress(data) + Unsafe.ARRAY_BYTE_BASE_OFFSET);
Pointer pos = CLibrary.INSTANCE.memchr(ptr, 'e', 5);
System.out.println((char) pos.getByte(0));
}
static long toAddress(Object obj) {
Object[] array = new Object[] {obj};
long baseOffset = UNSAFE.arrayBaseOffset(Object[].class);
long address = UNSAFE.getLong(array, baseOffset);
return address << 3; // compressed Oops
}
}
interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary ("c", CLibrary.class);
Pointer memchr(Pointer s, int c, long n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment