2

Is is possible (in a C or C++ program, running under Linux on a 64-bit-Intel architecture) for thread A to read the value of thread B's program counter register, without requiring any special instrumentation of to thread B's code?

(I realize that's an odd thing to want to do; the desire only comes up because I'm curious if thread A could use that to detect if thread B had become stuck in a failed system call, as described here)

Community
  • 1
  • 1
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234

1 Answers1

3

On Linux, field 30 of /proc/self/task/%d/stat, where %d needs to be filled in with the kernel tid of the thread in question, contains the last-observed instruction pointer value for the thread. See http://man7.org/linux/man-pages/man5/proc.5.html and note that it's documented under /proc/[pid]/stat but the version in the task directory under the current process is the one you want for targeting a thread.

The hard part may be getting the kernel tid for the thread. The easiest way to do this is to call syscall(SYS_gettid) from the thread and have it store its kernel tid somewhere.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • For a given process, checking all the TIDs listed in the task directory would suffice if the goal is to find **any** stuck thread - "TID X seems stuck at PC value Y". The TID value really doesn't matter. But that's not going to avoid false positives if the PC value is for a "normal" place for that thread to block. – Andrew Henle May 06 '15 at 23:16
  • Yes. OP may have an XY problem going on here, in that the desired mechanism is not really a good approach to the problem. But I still thought it was worth answering since there is a solution for the requested mechanism. – R.. GitHub STOP HELPING ICE May 06 '15 at 23:38
  • R.. agreed that I probably do have an XY problem... what I'd really like is for a kernel "oops" to crash my process cleanly, rather than forcing my other thread to jump through hoops to determine whether the main thread has been paralyzed for ever and if it should therefore crash the process itself to allow the process to be restarted. But it seems unlikely that a facility exists to control that behavior. :( – Jeremy Friesner May 06 '15 at 23:43
  • BTW you can also get the stack pointer as field 29. This might be some extra information to help you figure out what's going on. Stack pointer and instruction pointer might even be sufficient to do a backtrace on the target thread with the appropriate unwind library code. – R.. GitHub STOP HELPING ICE May 06 '15 at 23:47