我编写了一个小程序,可以读写进程的内存,但我不明白为什么它不能工作。这是我的密码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/ptrace.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
int main()
{
pid_t pid=3169;
char mem_file_name[2048];
int mem_fd;
int offset=0;
char buf[1005128];
sprintf(mem_file_name, "/proc/%d/mem", pid);
mem_fd = open(mem_file_name, O_RDWR,S_IRWXU);
printf("1 %s\n",strerror(errno));
ptrace(PTRACE_ATTACH, pid, NULL, NULL);
printf("2 %s\n",strerror(errno));
waitpid(pid, NULL, 0);
printf("3 %s\n",strerror(errno));
lseek(mem_fd, offset, SEEK_SET);
printf("4 %s\n",strerror(errno));
read(mem_fd, buf, _SC_PAGE_SIZE);
printf("5 %s\n",strerror(errno));
ptrace(PTRACE_DETACH, pid, NULL, NULL);
printf("6 %s\n",strerror(errno));
printf("%s\n",buf );
}这就是我的输出:
1 Success
2 Success
3 Success
4 Success
5 Input/output error
6 Input/output error我用
gcc -Wall -Wextra main.c我在root许可下运行
sudo ./a.out在这个例子中,我只尝试从一个进程中读取,但是它不起作用。我的想法是抛出进程的内存,但我不知道为什么我不能阅读。
ps我知道有一些工具可以转储进程的内存,但是我想创建一个小程序来进行练习。
发布于 2018-11-05 11:20:51
您的代码有几处出错。
您的主要问题是试图从偏移量0读取,这是进程地址0x00000000,它没有映射到您的进程。
int offset=0;
...
lseek(mem_fd, offset, SEEK_SET);这就像从你的记忆中读到地址为零:
int offset=0;
char* p = 0x0;
printf("%d data",p[offset]);您只能通过进程中有效的映射地址的偏移量读取/proc/PID/mem内存。
例如,如果要通过该API读取buf变量的内存,可以通过查找其地址来读取它:
lseek(mem_fd, (off_t)buf, SEEK_SET); /* note that on 64 bit you need to use lseek64 and off64_t */
read(mem_fd, buf, _SC_PAGE_SIZE); /* this should work */备注:
getpid读取它,要么使用/proc/self/mem。https://stackoverflow.com/questions/53153058
复制相似问题