github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/qemu/debugger.go (about)

     1  package qemu
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/sirupsen/logrus"
     6  	"github.com/emc-advanced-dev/pkg/errors"
     7  	unikutil "github.com/solo-io/unik/pkg/util"
     8  	"net"
     9  	"path/filepath"
    10  )
    11  
    12  func startDebuggerListener(port int) error {
    13  	addr := fmt.Sprintf(":%v", port)
    14  	ln, err := net.Listen("tcp", addr)
    15  	if err != nil {
    16  		return errors.New("establishing tcp listener on "+addr, err)
    17  	}
    18  	logrus.Info("listening on " + addr)
    19  	go func() {
    20  		for {
    21  			conn, err := ln.Accept()
    22  			if err != nil {
    23  				logrus.WithError(err).Warnf("failed to accept debugger connection")
    24  				continue
    25  			}
    26  			go connectDebugger(conn)
    27  		}
    28  	}()
    29  	return nil
    30  }
    31  
    32  func connectDebugger(conn net.Conn) {
    33  	if debuggerTargetImageName == "" {
    34  		logrus.Error("no debug instance is currently running")
    35  		return
    36  	}
    37  	container := unikutil.NewContainer("rump-debugger-qemu").
    38  		WithNet("host").
    39  		WithVolume(filepath.Dir(getKernelPath(debuggerTargetImageName)), "/opt/prog/").
    40  		Interactive(true)
    41  
    42  	cmd := container.BuildCmd(
    43  		"/opt/gdb-7.11/gdb/gdb",
    44  		"-ex", "target remote 192.168.99.1:1234",
    45  		"/opt/prog/program.bin",
    46  	)
    47  	conn.Read([]byte("GET / HTTP/1.0\r\n\r\n"))
    48  	logrus.WithField("command", cmd.Args).Info("running debug command")
    49  	cmd.Stdin = conn
    50  	cmd.Stdout = conn
    51  	cmd.Stderr = conn
    52  	if err := cmd.Start(); err != nil {
    53  		logrus.WithError(err).Error("error starting debugger container")
    54  		return
    55  	}
    56  	defer func() {
    57  		//reset debugger target
    58  		debuggerTargetImageName = ""
    59  		container.Stop()
    60  	}()
    61  
    62  	for {
    63  		if _, err := conn.Write([]byte{0}); err != nil {
    64  			logrus.Debug("debugger disconnected: %v", err)
    65  			return
    66  		}
    67  	}
    68  }