我是刚接触栈的人,而对C来说是相对陌生的。我尝试使用ptrace从另一个进程读取进程内存。 到目前为止,我设法从另一个过程中读取和更改数字。 但是用字符串我找不到办法。 这是我的代码:
int errno;
//the string we want to read is 8 bytes long
long len = 8;
const int buflen = (len / sizeof(long)) + 1;
void *buffer;
long *base;
char *data;
int i;
//the process pid i want to track
pid_t pid = 2984;
//the address that the string we want to read resides
void *addr = (unsigned long int*) 0x7ffe03f6e088 ;
buffer = calloc(buflen, sizeof(long));
if (NULL == buffer)
{
perror("Fault at allocation: ");
}
base = (long *) buffer;
ptrace(PTRACE_ATTACH, pid, NULL, NULL);
for (i = 0; i < buflen; i++) {
if(ptrace(PTRACE_PEEKDATA, pid , addr + (sizeof(long) * i),NULL) != -1)
{
*(base + i) = ptrace(PTRACE_PEEKDATA, pid , addr + (sizeof(long) * i),
NULL);
}else
{
fprintf(stderr, "Value of errno: %s\n", strerror(errno));
}
}
ptrace(PTRACE_DETACH, pid, NULL, NULL);
/* Pop a null at the end, since we're printing this string. */
*((char *) buffer + len) = '\0';
data = (char *)buffer;
printf("%p[\"%s\"]\n",addr, data);
free(buffer);
并输出:
errno的值:没有这样的过程
errno的值:没有这样的过程
0x7ffe03f6e088 [“”]
但是,进程ID是正确的,并且当addr指向数字时,类似的代码也可以工作。 请帮我。
[编辑]
贝娄是示踪过程的代码:
char *a = "lala";
pid_t child;
printf("Char length: %ld\n", strlen(a));
printf("Char value: %s\n", a);
//the address I use to read variable
printf("Char address: %p\n", &a);
//make the process sleep so I can halt it manually
sleep(3);