简体   繁体   中英

How can I debug Go file in VS Code with root privileges?

How can I force Delve in VS Code to use root privileges?

I'm trying to debug go file that involves gopacket/pcap:

hndl, err := pcapgo.NewEthernetHandle(ifname)
// err == "couldn't open packet socket: operation not permitted"

Launching same program using sudo doesn't trigger error.

I've tried several methods:

  1. Launch sudo code. It warns that it is not recommended. Plus there are issues to use dlv in this mode as environment variables are messed up.
  2. Using this guide https://fatdragon.me/blog/2020/06/debug-golang-vs-code-linux-root . However "go.alternateTools" seems to know nothing about "dlv": Property dlv is not allowed. Probably something is missing in guide.
  3. Search for .vscode/launch.json config property that allows to sudo. VSC allows to do such for Python , but not for Go.

Is there any trivial way to launch debugger with root privileges?

Environment:

  • Ubuntu 18.04
  • VSCode 1.48.0
  • Go 1.13.4
  • Delve 1.4.0

Update May 2022

Debugging programs and tests as root in the documentation of the VSCode Go addon has been updated accordingly with task and launch configuration examples to not only debug programs but also tests as root.

Old

Debugging Go programs and tests that require root privileges using VSCode has been sore for a long time. As of VSCode version 1.65.0 I noticed a new experimental launch option "asRoot": "true" that needs to be combined with "console": "integratedTerminal" .

For instance, in your launch.json :

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Test/dbg pkg as root",
            "type": "go",
            "request": "launch",
            "mode": "test",
            "program": "${fileDirname}",
            "console": "integratedTerminal",
            "asRoot": true,
        },
    ]
}

When launching this configuration by pressing F5, a new debug terminal session opens (or might get reused) and the following command executed:

/usr/bin/env GOPATH=/home/foobar/go /usr/bin/sudo /home/foobar/go/bin/dlv dap --check-go-version=false --client-addr=:41945

This now automatically inserts the sudo command before dlv itself, so this needs to be launched into an internal or external interactive terminal (and thus does not work in the internal console). After authenticating to sudo, VSCode switches back to the debug console view and you are good to go.

This now avoids having to fiddle around with remapping the dlv command in your workspace to a wrapper shell script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM