Skip to content

Instantly share code, notes, and snippets.

@jc-lab
Created September 10, 2020 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jc-lab/410ab3264be862541a3b9536ccff79f6 to your computer and use it in GitHub Desktop.
Save jc-lab/410ab3264be862541a3b9536ccff79f6 to your computer and use it in GitHub Desktop.
ptrace_test
#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/signal.h>
#include <sys/ptrace.h>
volatile int g_running = 1;
int main() {
setbuf(stdout, 0);
setbuf(stderr, 0);
printf("START APPLICATION (pid=%d)\n", ::getpid());
int forked = fork();
if (forked > 0) {
printf("[PARENT] I am parent (pid=%d, child=%d)\n", getpid(), forked);
long ptrace_res = ptrace(PTRACE_ATTACH, forked, 0, 0);
printf("[PARENT] PTRACE_ATTACH ptrace_res = %d\n", ptrace_res);
// ptrace_res = ptrace(PTRACE_SETOPTIONS, forked, NULL, PTRACE_O_TRACEEXIT);
// printf("[PARENT] PTRACE_SETOPTIONS ptrace_res = %d\n", ptrace_res);
pid_t signaled_pid;
int signaled_stat = 0;
// WNOHANG
while((signaled_pid = ::waitpid(-1, &signaled_stat, 0)) >= 0) {
char temp[128];
printf("[PARENT, %d] wait result : %d / %d\n", signaled_pid, signaled_stat);
struct stat st = { 0 };
sprintf(temp, "/proc/%d", signaled_pid);
if (stat(temp, &st) == -1 && errno == ENOENT) {
printf("CHILD IS DEAD!\n");
}
if(WIFEXITED(signaled_stat)) {
printf("[PARENT, %d] WIFEXITED exit_status=%d\n", signaled_pid, WEXITSTATUS(signaled_stat));
}
if (WIFSIGNALED(signaled_stat)) {
printf("[PARENT, %d] WIFSIGNALED signal=%d\n", signaled_pid, WTERMSIG(signaled_stat));
}
if (WIFSTOPPED(signaled_stat)) {
printf("[PARENT, %d] WIFSTOPPED signal=%d\n", signaled_pid, WSTOPSIG(signaled_stat));
if (WSTOPSIG(signaled_stat) == SIGSEGV) {
printf("CHILD IS SIGSEGV!!!\n");
while (1) {
if (stat(temp, &st) == -1 && errno == ENOENT) {
printf("CHILD IS DEAD!\n");
} else {
printf("CHILD IS ALIVE!\n");
}
usleep(1000000);
}
}
}
if (WIFCONTINUED(signaled_stat)) {
printf("[PARENT, %d] WIFCONTINUED\n", signaled_pid);
}
if (ptrace(PTRACE_CONT, forked, 0, WSTOPSIG(signaled_stat))) {
printf("stopper: ptrace(PTRACE_CONT, ...)");
break;
}
}
printf("** FINISH WAIT! / %d\n", signaled_pid);
// ptrace_res = ptrace(PT_KILL, forked, 0, 0);
// printf("[PARENT] PTRACE_O_TRACEEXIT ptrace_res = %d\n", ptrace_res);
while(g_running) {
usleep(1000000);
}
} else if (forked == 0) {
printf("[CHILD] TP-2\n");
usleep(1000000);
printf("[CHILD] TP-3\n");
printf("[CHILD] I am borned (pid=%d, ppid=%d)\n", getpid(), getppid());
*((int*)0x1234) = 0x12345678;
return 123;
} else {
printf("ERROR\n");
}
printf("APP EXIT forked=%d\n", forked);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment