Need help on ptrace


(tree wang) #1

I’m trying to write a strace in Go, but I have a tricky problem.
My Code:

// 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]")
}

and the target program

// 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");
	}
}

Normally, when I run go run main.go ./test
the output should be something like

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]

BUT when I run go run main.go ./test, the output is

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]

Why does it stop at 0x7f649e219090 twice?

This problem has been bothering me for several days.
PLEASE HELP ME OUT!
THANKS!


Golang Function to debug external program
(Aaron Michaels) #2

I’m afraid this forum doesn’t have the userbase or experience to help you. You should try a more frequented site like stack overflow where people have experience. It’s just an unfortunate effect of trying to start a new community online. You find yourself in a catch 21 and anyone who wants to attack the community will find any ■■■■■ in the armor they can.

[Sorry for rant. So tired]