Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.Field;
- import sun.misc.Unsafe;
- public class NativeThreadIDLookup {
- public static void main(String[] args) throws Exception {
- for (int i = 0; i < 20; i++) {
- Thread t = new Thread() {
- public void run() {
- while (true) {
- try {
- Thread.sleep(10000);
- } catch (InterruptedException ex) {
- }
- }
- };
- };
- t.setName("Target-" + i);
- t.start();
- }
- Thread.sleep(500);
- Thread[] ts = new Thread[Thread.activeCount() * 2];
- Thread.enumerate(ts);
- Field f = Thread.class.getDeclaredField("eetop");
- f.setAccessible(true);
- Field uf = Unsafe.class.getDeclaredField("theUnsafe");
- uf.setAccessible(true);
- Unsafe u = (Unsafe) uf.get(null);
- for (int i = 5; i < ts.length; i++) {
- if (ts[i] != null) {
- long pid = (Long) f.get(ts[i]);
- // osthread pointer is 4 slots before stack size and one slot after a 0.
- // nid should be findable if you know at least one value :)
- // Java 1.7.0_10 x64
- // int osthread = u.getInt(pid+4*41);
- // int nid = u.getInt(osthread+4*5);
- // Java 1.7.0_40 x86
- // Java 1.7.0_72 x86
- // int osthread = u.getInt(pid+4*43);
- // int nid = u.getInt(osthread+4*7);
- // Java 1.7.0_72 x64
- Object osthread = unpack(u, u.getInt(pid + 4 * 68));
- int nid = u.getInt(osthread, 4L * 11);
- System.out.println(nid + "/0x" + Integer.toHexString(nid) + "\t" + Long.toHexString(pid) + "\t" + ts[i].getId() + "\t" + ts[i].getName());
- }
- }
- }
- private static Object unpack(Unsafe u, int addr) throws Exception {
- Unpacker uu = new Unpacker();
- u.putInt(uu, u.objectFieldOffset(Unpacker.class.getDeclaredField("value")), addr);
- return uu.value;
- }
- private static class Unpacker {
- public Object value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment