快速读取进程内存

快速读取进程内存(摘自《Debug Hacks》,略做修改)


Linux下使用ptrace调用可以监视和控制其他进程,并能够改变进程的寄存器值和内核映像。ptrace提供了PTRACE_PEEKDATA来实现进程内存读取,这是原语级的操作,在x86_64下一次仅读取8字节。因此在读取量较大时,需要反复调用ptrace。/proc/<PID>/mem接口提供了read调用,只需一次就可以读取任意大小内存,可谓价格便宜量又足。

以下示例代码摘自《Debug Hacks》,使用了/proc/<PID>/mem接口:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <errno.h>

int main(int argc, char *argv[])
{
	if (argc < 5) {
		fprintf(stdout, "usage: dumpmem pid start_addr length filaname\n");
		return -1;
	}

	/*get argvs*/
	off_t start_addr;
	int len;
	pid_t pid;
	pid = atoi(argv[1]);
	sscanf(argv[2], "%x", &start_addr);
	sscanf(argv[3], "%x", &len);
	
	/*attach the memory of pid*/
	int ptrace_ret;
	ptrace_ret = ptrace(PTRACE_ATTACH, pid, NULL, NULL);
	if (ptrace_ret == -1) {
		fprintf(stderr, "ptrace attach failed.\n");
		perror("ptrace");
		return -1;
	}
	if (waitpid(pid, NULL, 0) == -1) {
		fprintf(stderr, "waitpid failed.\n");
		perror("waitpid");
		ptrace(PTRACE_DETACH, pid, NULL, NULL);
		return -1;
	}
	
	/*open /proc/<pid>/mem to attach the memory*/
	int fd;
	char path[256] = {0};
	sprintf(path, "/proc/%d/mem", pid);
	fd = open(path, O_RDONLY);
	if (fd == -1) {
		fprintf(stderr, "open file failed.\n");
		perror("open");
		ptrace(PTRACE_DETACH, pid, NULL, NULL);
		return -1;
	}
	
	/*seek the file pointer*/
	off_t off;
	off = lseek(fd, start_addr, SEEK_SET);
	if (off == (off_t)-1) {
		fprintf(stderr, "lseek failed.\n");
		perror("lseek");
		ptrace(PTRACE_DETACH, pid, NULL, NULL);
		close(fd);
		return -1;
	}
	
	/*read mem*/
	unsigned char *buf = (unsigned char *)malloc(len);
	if (buf == NULL) {
		fprintf(stderr, "malloc failed.\n");
		perror("malloc");
		ptrace(PTRACE_DETACH, pid, NULL, NULL);
		close(fd);
		return -1;
	}
	int rd_sz;
	rd_sz = read(fd, buf, len);
	if (rd_sz < len) {
		fprintf(stderr, "read failed.\n");
		perror("read");
		ptrace(PTRACE_DETACH, pid, NULL, NULL);
		free(buf);
		close(fd);
		return -1;
	}
	
	/*now show mem*/
	int i = 0;
	FILE *fp = fopen(argv[4], "wb+");
	if (fp == NULL) {
		fprintf(stderr, "fopen failed.\n");
		perror("fopen");
		ptrace(PTRACE_DETACH, pid, NULL, NULL);
		free(buf);
		close(fd);
		return -1;
	}
	fwrite(buf, 1, len, fp);
	fclose(fp);
	
	ptrace(PTRACE_DETACH, pid, NULL, NULL);
	free(buf);
	close(fd);
	return 0;
}

需要注意的是,读取可能因权限问题而失败。读取前可参考/proc/<PID>/maps内存映射,选取带有r标识的可读部分(如代码段,数据段或堆内存)。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值