-1

I want to trace only a part of C program for system calls. I am using ptrace() with PTRACE_TRACEME option to start getting traced. How to stop this process from getting traced after few lines of code. I am trying to use PTRACE_DETACH but it does not work?

The main .C file is:

#include<stdio.h>
#include<unistd.h>
#include<sys/ptrace.h>
#include<signal.h>

int display(char *p);
int main()
{
    puts("Before Display\n");   
    display("hello");
    puts("After Display\n");
    return 0;
}

int display(char *p)
{
    ptrace(PTRACE_TRACEME, 0, NULL, NULL);
    raise(SIGCONT);
    puts("interception");
    ptrace(PTRACE_DETACH, 0, NULL, NULL);
    return 0;
}

The code of parent process is:

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/reg.h>   /* For constants ORIG_EAX etc */
#include <stdio.h>
int main()
{   pid_t child;
    int status;
    long orig_eax;
    child = fork();
    if(child == 0) 
    {
        execl("/home/kashi/Documents/write", "write", NULL);
    }
    else {
      while(1)
      {
        wait(&status);
          if(WIFEXITED(status))
              break;
        orig_eax = ptrace(PTRACE_PEEKUSER,
                          child, 4 * ORIG_EAX,
                          NULL);
        printf("The child made a "
               "system call %ld\n", orig_eax);
       ptrace(PTRACE_SYSCALL, child, NULL, NULL);
       }
    }
    return 0;
}

1 Answers1

2

You cannot do it from the traced process.

PTRACE_TRACEME is the only request that makes sense in the traced process. PTRACE_DETACH and all the others must be used in the tracing process.

The tracee can communicate with the tracer and ask it politely to detach. There's no ptrace request specifically for that. The tracee can e.g. raise(SIGCONT), the tracer will observe it and issue PTRACE_DETACH.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243