Created
February 7, 2019 18:08
-
-
Save knightsc/a51951469f603d9cac645219ec0032ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/errno.h> | |
#include <sys/types.h> | |
#include <sys/ptrace.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/wait.h> | |
#include <mach/mach.h> | |
/* | |
Need entitlements added to binary | |
<?xml version="1.0" encoding="UTF-8"?> | |
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
<plist version="1.0"> | |
<dict> | |
<key>com.apple.security.cs.debugger</key> | |
<true/> | |
</dict> | |
</plist> | |
*/ | |
static void setup_inferior(const char *path, char *const argv[]) | |
{ | |
int result; | |
ptrace(PT_TRACE_ME, 0, 0, 0); | |
execv(path, argv); | |
} | |
static void attach_to_inferior(pid_t pid) | |
{ | |
while(1) { | |
int status; | |
waitpid(pid, &status, 0); | |
if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP) { | |
printf("Inferior stopped on SIGTRAP - continuing...\n"); | |
task_t task; | |
kern_return_t kr; | |
kr = task_for_pid(mach_task_self(), pid, &task); | |
if (kr != KERN_SUCCESS) { | |
mach_error("task_for_pid:", kr); | |
} | |
else { | |
printf("Got task port\n"); | |
} | |
ptrace(PT_CONTINUE, pid, (caddr_t)1, 0); | |
} | |
else if (WIFEXITED(status)) { | |
printf("Inferior exited - debugger terminating...\n"); | |
exit(0); | |
} | |
} | |
} | |
void dbg_inferior_exec(const char *path, char *const argv[]) | |
{ | |
pid_t result; | |
do { | |
result = fork(); | |
switch (result) { | |
case 0: // inferior | |
setup_inferior(path, argv); | |
break; | |
case -1: // error | |
break; | |
default: // debugger | |
attach_to_inferior(result); | |
break; | |
} | |
} while (result == -1 && errno == EAGAIN); | |
} | |
int main() | |
{ | |
char *argv[1] = { 0 }; | |
dbg_inferior_exec("./hello", argv); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment