Is it possible to ptrace the same process from a thread in that process? I found a discussion at [1] which seems to suggest a way which (may or may not work) seems to be bit involved to me as I am not intimately familiar with pthreads API. Has anybody tried this? Any code pointer would be great.
1 Answers
You most emphatically do not want to use POSIX threads (pthreads) for this. POSIX threads introduce a whole new set of application semantics which simply do not apply here.
The second paragraph explains how to do this the right way:
And for the first one I found a reasonable way to avoid the problem: the debugging thread can do a "vfork()" (or, if vfork() does something bad in libc, do the direct "clone(CLONE_VFORK|CLONE_MM)" thing) to have a new thread that is in a _different_ thread group, but is able to ptrace and also is "synchronized" with the VM, simply because it shares it with all the other threads it might want to debug
This mechanism is how user-space debuggers like gdb(1) and crash(8) work: they create either a closely-coupled child process using vfork(2) or use a similar Linux-specific clone(2) system call.
If fact, this is how every program except the primeval init(1) program is run: a current process forks, and one process [usually the child] then exec(2)' the desired program to overwrite its execution environment.

- 706
- 4
- 5
-
When you say "this mechanism" is commonly used, you really mean `clone()` without the `CLONE_VM` flag, right? So that is radically different from the approach outlined in your quote. Linus's quote also appears to be using `vfork()` and `CLONE_VFORK` wrongly, since according to the `vfork` man page, the new thread isn't able to ptrace -- the only thing it can legally do is call `exec` or `exit`. Probably `clone()` with `CLONE_VM` and not `CLONE_VFORK` would work as Linus described. – Ben Voigt Nov 13 '15 at 21:31