|
第一个程序是用来被跟踪的,第二个程序用来跟踪第一个程序,但是跟踪完后会导致第一个程序报段错误,不知道是什么原因?
- #include <stdio.h>
- int main(int argc, char **argv) {
- int i = 0;
- while(1) {
- printf("%d\n",i);
- i++;
- sleep(1);
- }
- }
复制代码
- #include <sys/ptrace.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <sys/syscall.h>
- #include <sys/user.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- const long long_size = sizeof(long);
- void getdata(pid_t child, long addr, char *str, int len) {
- char *laddr;
- int i,j;
- union u {
- long val;
- char chars[long_size];
- } data;
- i = 0;
- j = len / long_size;
- laddr = str;
- while(i < j) {
- data.val = ptrace(PTRACE_PEEKDATA, child, addr + i * 4, NULL);
- memcpy(laddr, data.chars, long_size);
- ++i;
- laddr += long_size;
- }
- j = len % long_size;
- if(j != 0) {
- data.val = ptrace(PTRACE_PEEKDATA, child, addr + i * 4, NULL);
- memcpy(laddr, data.chars, j);
- }
- }
- void putdata(pid_t child, long addr, char *str, int len) {
- char *laddr;
- int i,j;
- union u {
- long val;
- char chars[long_size];
- } data;
- i = 0;
- j = len /long_size;
- laddr = str;
- while(i < j) {
- memcpy(data.chars, laddr, long_size);
- ptrace(PTRACE_POKEDATA, child, addr + i * 4, data.val);
- ++i;
- laddr += long_size;
- }
- j = len % long_size;
- if(j != 0) {
- memcpy(data.chars, laddr, j);
- ptrace(PTRACE_POKEDATA, child, addr + i * 4, data.val);
- }
- }
- int main(int argc, char *argv[]) {
- pid_t traced_pid;
- struct user_regs_struct regs;
- long ins;
- char code[] = {0xcd, 0x80, 0xcc};//trap code,让程序挂断
- char backup[3];
- if(argc != 2) {
- printf("usage:%s <pid to be traced>", argv[0], argv[1]);
- exit(1);
- }
- traced_pid = atoi(argv[1]);
- ptrace(PTRACE_ATTACH, traced_pid, NULL, NULL);
- wait(NULL);
- ptrace(PTRACE_GETREGS, traced_pid, NULL, ®s);
- getdata(traced_pid, regs.eip, backup, 3);
- putdata(traced_pid, regs.eip, code, 3);
- ptrace(PTRACE_CONT, traced_pid, NULL, NULL);
- wait(NULL);
- printf("the process stopped, putting back the original instructions\n");
- printf("press <enter> to continue");
- getchar();
- putdata(traced_pid, regs.eip, backup, 3);
- ptrace(PTRACE_SETREGS, traced_pid, NULL, ®s);
- ptrace(PTRACE_DETACH, traced_pid, NULL, NULL);
- return 0;
- }
复制代码 |
|