Linux使用ptrace()模拟write()系统调用失败

时间:2014-07-11 19:38:41

标签: linux system-calls ptrace

我正在尝试模拟write()系统调用的失败。 我已经读过返回值-1(在EAX中)表示系统调用中的错误,并且errno给出了失败的确切原因。 我试图拦截系统调用write()在EAX寄存器中返回-1并将“errno”设置为某个错误值。 puts()内部使用write(),即系统调用号4。 如果我在孩子中做了perror(“错误:”),它应该显示与我想设置的“errno”相对应的错误。

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/reg.h>   /* For constants ORIG_EAX etc */
#include <stdio.h>
#include <sys/user.h>
#include <errno.h>
int main()
{   pid_t child;
    int status;
    long orig_eax,eax,params[3];
    int ret_val=-1,insyscall=0;
    struct user_regs_struct regs;
    child = fork();
    if(child == 0) {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);

        execl("/home/kashi/Documents/2nd_Sem/MyPrgms/ptrace/ramana/write", "write", NULL);
    //execl("/bin/ls","ls",NULL);
    }
    else {
      while(1)
      {
        wait(&status);
          if(WIFEXITED(status))
              break;

          orig_eax = ptrace(PTRACE_PEEKUSER,
                     child, 4 * ORIG_EAX, NULL);

      if(orig_eax == 4) 
          {
        ptrace( PTRACE_GETREGS, child, 0, &regs );
        printf("Write called with %ld, %ld %ld\n",regs.ebx, regs.ecx,regs.edx);

             if(insyscall == 0) 
             {
                /* Syscall entry */
                printf("In %d\n",insyscall);
                insyscall = 1;
             }
             else
             {
                /* Syscall exit */
        regs.orig_eax=-1;
        **errno=11;     //This errno should be set in the child process, how to do it?**

        ptrace( PTRACE_SETREGS, child, 0, &regs );
        eax = ptrace(PTRACE_PEEKUSER, child, 4 * ORIG_EAX, NULL);
                printf("Write returned with %ld\n", eax);
        insyscall = 0;
             }
          }   

        //printf("The child made a "
        //       "system call %ld\n", regs.orig_eax);
       ptrace(PTRACE_SYSCALL, child, NULL, NULL);
       }
    }
    return 0;
}

tracee程序(testwrite.c)是:

#include<stdio.h>
#include<unistd.h>
#include<sys/ptrace.h>
#include<signal.h>
#include<errno.h>

//int display(char *p);
int main()
{

    printf("Hi Kashi\n");
    perror("Error: ");
    return 0;
}

输出:

[kashi@localhost ramana]$ ./test.sh
In 0
Hi Kashi
Write returned with -1
In 0
**Error: : Success**
Write returned with -1

perror(“Error:”)显示对应于“errno”的文本消息。我无法在子进程中设置这个“错误”,我该怎么做?

0 个答案:

没有答案