Guest User

Lookup native thread ID for Java thread from within Java

a guest
Dec 7th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. import java.lang.reflect.Field;
  2. import sun.misc.Unsafe;
  3.  
  4. public class NativeThreadIDLookup {
  5.     public static void main(String[] args) throws Exception {
  6.         for (int i = 0; i < 20; i++) {
  7.             Thread t = new Thread() {
  8.                 public void run() {
  9.                     while (true) {
  10.                         try {
  11.                             Thread.sleep(10000);
  12.                         } catch (InterruptedException ex) {
  13.                         }
  14.                     }
  15.                 };
  16.             };
  17.             t.setName("Target-" + i);
  18.             t.start();
  19.         }
  20.         Thread.sleep(500);
  21.         Thread[] ts = new Thread[Thread.activeCount() * 2];
  22.         Thread.enumerate(ts);
  23.         Field f = Thread.class.getDeclaredField("eetop");
  24.         f.setAccessible(true);
  25.         Field uf = Unsafe.class.getDeclaredField("theUnsafe");
  26.         uf.setAccessible(true);
  27.         Unsafe u = (Unsafe) uf.get(null);
  28.         for (int i = 5; i < ts.length; i++) {
  29.             if (ts[i] != null) {
  30.                 long pid = (Long) f.get(ts[i]);
  31.  
  32.                 // osthread pointer is 4 slots before stack size and one slot after a 0.
  33.                 // nid should be findable if you know at least one value :)
  34.  
  35.                 // Java 1.7.0_10 x64
  36.                 // int osthread = u.getInt(pid+4*41);
  37.                 // int nid = u.getInt(osthread+4*5);
  38.  
  39.                 // Java 1.7.0_40 x86
  40.                 // Java 1.7.0_72 x86
  41.                 // int osthread = u.getInt(pid+4*43);
  42.                 // int nid = u.getInt(osthread+4*7);
  43.  
  44.                 // Java 1.7.0_72 x64
  45.                 Object osthread = unpack(u, u.getInt(pid + 4 * 68));
  46.                 int nid = u.getInt(osthread, 4L * 11);
  47.  
  48.                 System.out.println(nid + "/0x" + Integer.toHexString(nid) + "\t" + Long.toHexString(pid) + "\t" + ts[i].getId() + "\t" + ts[i].getName());
  49.             }
  50.         }
  51.     }
  52.  
  53.     private static Object unpack(Unsafe u, int addr) throws Exception {
  54.         Unpacker uu = new Unpacker();
  55.         u.putInt(uu, u.objectFieldOffset(Unpacker.class.getDeclaredField("value")), addr);
  56.         return uu.value;
  57.     }
  58.  
  59.     private static class Unpacker {
  60.         public Object value;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment