Ptrace one thread from another

While experimenting with a system call ptrace(), I am trying to track another thread of the same process. According to the man page, both the tracer and the trace are specific threads (not processes), so I see no reason why this should not work. So far I have tried the following:

  • use PTRACE_TRACEMEfrom child clone()d: the call succeeds but does not do what I want, perhaps because the parent thread to be monitored is not a thread calledclone()
  • use PTRACE_ATTACHor PTRACE_SEIZEfrom the parent thread: this always fails with EPERM, even if the process runs as root and withprctl(PR_SET_DUMPABLE, 1)

In all cases waitpid(-1, &status, __WALL)fails with ECHILD(same thing when passing child pid explicitly).

What to do to make it work?

If this is not possible at all, it is due to a bug or a bug in the kernel (I am using version 3.8.0). In the first case, could you tell me the correct bit of documentation?

+4
source share
1 answer

As @mic_e noted, this is a well-known fact about the kernel - not entirely a mistake, but not entirely correct. Pay attention to the kernel mailing list thread. To provide an excerpt from Linus Torvalds:

This "new" (last November) check is unlikely to go away. He solved so many problems (both security and stability), and given that

(a)

(b) , ,

, , , -, , , .

, , , - ptracing .

, , :

// this number is arbitrary - find a better one.
#define STACK_SIZE (1024 * 1024)

int main_thread(void *ptr) {
    // do work for main thread
}

int main(int argc, char *argv[]) {
    void *vstack = malloc(STACK_SIZE);
    pid_t v;
    if (clone(main_thread, vstack + STACK_SIZE, CLONE_PARENT_SETTID | CLONE_FILES | CLONE_FS | CLONE_IO, NULL, &v) == -1) { // you'll want to check these flags
        perror("failed to spawn child task");
        return 3;
    }
    long ptv = ptrace(PTRACE_SEIZE, v, NULL, NULL);
    if (ptv == -1) {
        perror("failed monitor sieze");
        return 1;
    }
    // do actual ptrace work
}
+1

Source: https://habr.com/ru/post/1544114/


All Articles