Created
April 29, 2017 12:21
-
-
Save Garciat/745545a62584dd079055d10841c8777c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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