I'd like to write a mini-debugger with ptrace on OS X.
I want the parent process to make the child process run step by step.
This is what I tried, but the program gets stuck sometimes, it seems to be in an infinite loop or to be frozen.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/user.h>
#include <sys/types.h>
#include <sys/ptrace.h>
int main(void)
{
pid_t id = fork();
if (id < 0)
return 1;
else if (id == 0)
{
ptrace(PT_TRACE_ME, 0, 0, 0);
printf("Point 1\n");
kill(getpid(), SIGSTOP);
printf("Point 2\n");
exit(1);
}
else
{
while (1)
{
int status = 0;
pid_t retpid = waitpid(id, &status, WUNTRACED);
if (retpid < 0)
{
printf("Waitpid error\n");
exit(3);
}
if (WIFSTOPPED(status))
{
int ret = ptrace(PT_STEP, id, (caddr_t)1, 0);
if (ret < 0)
{
printf("Ptrace error\n");
exit(2);
}
}
else
{
printf("Program has terminated\n");
exit(0);
}
}
}
}
Compile with cc bug.c
, run with while true; do ./a.out; done
, wait 30 seconds and it will freeze.
When it freezes, the last lines are:
Point 1
Point 2
I can't figure out what I'm doing wrong.
Running on macOS Sierra 10.12.6 with Apple LLVM version 8.1.0 (clang-802.0.42)