为什么Ptrace在Golang中完成两次后将在SYS_EXECVE上停止两次

时间:2018-10-14 08:50:15

标签: linux go ptrace

我正在尝试在Go中编写一个strace,但是我遇到了一个棘手的问题。为什么Ptrace完成后会在SYS_EXECVE上停止两次?

我的代码:

// main.go
package main

import (
    "fmt"
    "os"
    "os/exec"
    "syscall"
)

func main() {
    var regs syscall.PtraceRegs

    cmd := exec.Command(os.Args[1], os.Args[2:]...)
    cmd.Stderr = os.Stderr
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.SysProcAttr = &syscall.SysProcAttr{
        Ptrace: true,
    }

    cmd.Start()
    cmd.Wait()
    pid := cmd.Process.Pid
    fmt.Printf("Run %v [%d]\n", os.Args[1:], cmd.Process.Pid)
    err := syscall.PtraceSyscall(pid, 0)
    if err != nil {
        panic(err)
    }

    for {
        pid, err = syscall.Wait4(-1, nil, syscall.WALL, nil)
        if err != nil {
            break
        }
        if pid < 0 {
            continue
        }

        err = syscall.PtraceGetRegs(pid, &regs)
        if err != nil {
            continue
        }
        if regs.Orig_rax == syscall.SYS_EXECVE {
            fmt.Printf("%x : execve rax = %x, rsi = %x, rdi = %x, rdx = %x\n", regs.Rip, regs.Rax, regs.Rsi, regs.Rdi, regs.Rdx)
        }

        err = syscall.PtraceSyscall(pid, 0)
        if err != nil {
            panic(err)
        }
    }
    fmt.Println("[EXITED]")
}

和目标程序

// test.c
// gcc -o test test.c
#include<stdio.h>
#include<stdlib.h>

int main() {
    int x;
    puts("hello world");
    scanf("%d", &x);
    if (x == 0) {
        char *arg[] = {"ls", NULL};
        execve("/bin/ls", arg, NULL);
    }
    else {
        puts("bye");
    }
}

通常,当我运行go run main.go ./test时 输出应该类似于

Run [./test] [59525]
hello world
0
7f6ef3929e37 : execve rax = ffffffffffffffda, rsi = 7ffc856296e0, rdi = 564ee24fe896, rdx = 0
7f52da510090 : execve rax = 0, rsi = 0, rdi = 0, rdx = 0
main.go  test  test.c
[EXITED]

但是当我运行go run main.go ./test时,输出为

Run [./test] [59590]
hello world
0
7f0bda014e37 : execve rax = ffffffffffffffda, rsi = 7ffffc7e6080, rdi = 55c8f1c12896, rdx = 0
7f649e219090 : execve rax = 0, rsi = 0, rdi = 0, rdx = 0
7f649e219090 : execve rax = 0, rsi = 0, rdi = 0, rdx = 0
main.go  test  test.c
[EXITED]

为什么它在0x7f649e219090处停两次?

0 个答案:

没有答案