ptrace:跟踪一个指定的进程
2.getpid、gettid和pthread_self的区别:
pthread_self属于POSIX线程库的函数,Linux下POSIX的pthread线程库是用进程来实现的,pthread_create是通过系统调用
clone创建一个子进程作为线程的。下面是这两个函数的声明:
#include <sys/types.h> #include <unistd.h> pid_t getpid(void); #include <sys/types.h> pid_t gettid(void); #include <pthread.h> pthread_t pthread_self(void);可以很容易发现pthread_self获取的是pthread_t(占用8Byte),而其他两个函数返回的都是pid_t(占用4Byte),上面我
3.ptrace函数:
#include <sys/ptrace.h> long ptrace(enum __ptrace_request request, pid_t pid, void *addr, void *data);这个函数比较复杂,具体的一些介绍,大家可以看这个:
man ptrace
ptrace用法
4.通过ptrace获取指定pthread线程的寄存器信息:
这个是被跟踪的进程的程序:
#include <stdio.h> #include <unistd.h> //for sleep #include <stdlib.h> //for exit #include <pthread.h>//for pthread #include <errno.h> //for errno #include <sys/syscall.h> //for gettid #define gettid() syscall(__NR_gettid) void *func(void *para) { printf("Hello world.\n"); printf("child process tid: %u\n", gettid()); sleep(-1); // 该进程一直sleep,等待 return NULL; } int main() { pthread_t tid; int ret = pthread_create(&tid, NULL, func, NULL); if(ret != 0) { exit(errno); } printf("parent process pid: %u\n", getpid()); pthread_join(tid, NULL); return 0; }输出为(注意不要结束此进程,不然没办法跟踪):
[biz@localhost test]$ g++ main.cpp -lpthread [biz@localhost test]$ ./a.out parent process pid: 14396 child process tid: 14397 sleep ...
#include <sys/ptrace.h> #include <stdlib.h> // for atoi #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <sys/user.h> /* For user_regs_struct */ int main(int argc, char *argv[]) { pid_t traced_process; struct user_regs_struct regs; long ins; if(argc != 2) { printf("Usage: %s <pid to be traced> ", argv[0], argv[1]); exit(1); } traced_process = atoi(argv[1]); ptrace(PTRACE_ATTACH, traced_process, NULL, NULL); wait(NULL); ptrace(PTRACE_GETREGS, traced_process, NULL, ®s); ins = ptrace(PTRACE_PEEKTEXT, traced_process, regs.rip, NULL); printf("EIP: %lx Instruction executed: %lx \n", regs.rip, ins); ptrace(PTRACE_DETACH, traced_process, NULL, NULL); return 0; }
[biz@localhost test]$ g++ attach.cpp -o attach [biz@localhost test]$ ./attach 14397 EIP: 33d98ab91d Instruction executed: e8c28948243c8b48