Reputation: 1041
I'm just testing read and write memory via ptrace()
call, but when I run the code shown below, I got an error like this.
Processkey() : 0x80481240
readmem pid 3950
Original opcode : 0x4641682b
writemem pid 3950
readmem pid 3950
PEEKDATA error: No such file or directory
As you can see, readmem()
works fine, but afterwards, readmem()
prints an error.
long readmem(int pid, unsigned long addr)
{
long ret=0;
printf("readmem pid %d\n", pid);
ret = ptrace(PTRACE_PEEKDATA, pid, (void *)(addr), 0);
if(ret<0)
{
error("PEEKDATA error");
}
return ret;
}
void writemem(int pid, unsigned long addr, long data)
{
long ret=0;
printf("writemem pid %d\n", pid);
ret = ptrace(PTRACE_POKEDATA, pid, (void *)addr, (void *)data);
if(ret<0)
{
error("POKEDATA error");
}
}
void detach(int pid)
{
long ret=0;
ret = ptrace(PTRACE_DETACH, pid, NULL, NULL);
if(ret<0)
{
error("detach() error");
}
}
void attach(int pid)
{
long ret=0;
ret = ptrace(PTRACE_ATTACH, pid, NULL, NULL);
if(ret<0)
{
error("ptrace() error");
}
ret = waitpid(pid, NULL, WUNTRACED);
if(ret<0)
{
error("waitpid ()");
}
}
int main(int argc, char **argv)
{
long ret = 0;
pid_t pid = 0;
REGS *regs;
unsigned long processkey_addr = 0;
int stat_value = 0;
long op = 0;
pid = atoi(argv[1]);
processkey_addr = 0x80481240;
printf("Processkey() : 0x%lx\n", processkey_addr);
attach(pid);
op = readmem(pid, processkey_addr);
printf("Original opcode : 0x%lx\n", op);
writemem(pid, processkey_addr, 0x41424344);
printf("Changed opcode : 0x%lx\n", readmem(pid, processkey_addr));
detach(pid);
}
But — and this made me crazy — when I tested code without the functions (just wrote the code inline in main()
), this whole code worked fine!
Does anyone know why this happens...?
Upvotes: 1
Views: 1849
Reputation: 399813
It seems a bit odd, but there's at least one actual error in your code. From the manual page:
On error, all requests return -1, and errno is set appropriately. Since the value returned by a successful PTRACE_PEEK* request may be -1, the caller must check errno after such requests to determine whether or not an error occurred.
It seems your code does not check errno
, it just assumes an error occured if the return value is -1.
Upvotes: 3