Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
GitHub Action edited this pageDec 26, 2024 ·22 revisions

The Go extension allows you to launch or attach to Go programs for debugging.You can inspect variables and stacks, set breakpoints, and do other debuggingactivities usingVS Code’s Debugging UI.

These debugging features are possible by usingDelve, the Go debugger.

Previously, the Go extension communicated with Delve through a custom debugadaptor program (legacy mode). SinceDelve's native debug adapter implementationis available, the Go extension is transitioning to deprecate the legacy debugadapter in favor of direct communication with Delve viaDAP.

📣We are happy to announce that the newdlv-dap mode of Delveintegration is enabled forlocaldebugging by default. Forremotedebugging it is the default inpre-release versions and is available with stable builds on demand with"debugAdapter": "dlv-dap" attribute inlaunch.json orsettings.json!

Many features and settings described in this document may be available only withthe newdlv-dap mode. For troubleshooting and configuring the legacy debugadapter, seethe legacy debug adapter documentation.

Get started

Open a file to debug (eitherpackage main source file or the test file) in theeditor, and select theRun and Debug button fromthe Run view.Alternatively, you can start debugging usingStart Debugging (F5) command fromthe Run menu orfromthe Command Palette(Linux/Windows: Ctrl+Shift+P, Mac: ⇧+⌘+P).

If you already have launch configurations for the project(.vscode/launch.json), the Run view will display the configuration list tochoose from.

When no configuration is configured yet (no.vscode/launch.json file), theextension will choose a default configuration based on the file open in theeditor.

❗ When you start debugging forthe first time or if thedlv executable on your system is too old to supportDAP, the Go extension may ask to install or update Delve. Follow theinstructions to install it, and then start the debugging session again.

Delve Install

To learn more about debugging in Go, watchGo: Writing and debugging fast, reliable, and efficient software.

Review theFeatures section for an overview ofthe Go Extension's debug UI and available features.

Stay up to date

Delve’s native DAP implementationis under active development. Take advantage of the most recent features and bugfixes by installing the latest version ofdlv using theGo:Install/Update Tools command from the Command Palette (Linux/Windows:Ctrl+Shift+P, Mac:Command+Shift+P). The command will showdlv inthe tool list.

Oncedlv is installed on your system, the extension will prompt you for updatewhenever installing a newer version is necessary. You can set thego.toolsManagement.autoUpdate setting so the extension can updatedlvautomatically for you.

If you need to installdlv manually outside of VS Code, follow the instructioninManually installingdlv. An exampleof a situation where manual installation might be needed is if you are buildinga dev container with the necessary tools preinstalled, or installingdlv builtfrom the tree head.

Switch to legacy debug adapter

Note: The extension still uses the legacy debug adapter for remote debugging.

If you need to use the legacy debug adapter for local debugging (legacy mode)by default, add the following in your VSCode settings.

"go.delveConfig": {"debugAdapter":"legacy",    }

Whenmode is set toremote you must explicitly setdebugAdapter todlv-dap to override the legacy adapter default.

If you want to switch tolegacy for only a subset of your launchconfigurations, you can usethedebugAdapter attribute to switch between"dlv-dap" and"legacy" mode.

If you chose to switch to legacy because of bugs or limitations in the new debugadapter,open an issueto help us improve.

Features

For general debugging features such as inspecting variables, settingbreakpoints, and other activities that aren't language-dependent, reviewVS Code debugging.

Configure

When you need more than the default debugging setup, you can create a launchconfiguration file for the project.

To create a configuration file:

  1. In thethe Run view,click "create a launch.json file"
  2. ChooseGo: Launch Package from the debug configuration drop-down menu. VSCode will create alaunch.json file in a .vscode folder in your workspace(project root folder) or in youruser settingsorworkspace settings.

Create a launch.json configuration file.

If you already have alaunch.json for your project, you can open it using theCommand PaletteOpen launch.json command.

To add a new configuration to an existinglaunch.json file:

  1. Open yourlaunch.json file using the Command PaletteOpen launch.jsoncommand.
  2. Click theAdd Configuration button to invoke the snippet IntelliSense.

There are many configuration attributes (seethe Launch.json attributes section). IntelliSense inVS Code’slaunch.json editor will help you navigate available options anddocumentation.

Launch

To launch and debug your project, selectRun >Start Debugging (F5).

The launch feature uses alaunch request type configuration in yourlaunch.json file. Itsprogram attribute needs to be the absolute path toeither the Go file, or folder containing the main package or test file. In thismode, the Go extension will start the debug session by building and launchingthe program. The launched program will be terminated when the debug sessionends.

  • Supported modes
    • debug: build and debug a main package
    • test: build and debug a test
    • exec: debug a precompiled binary
      • The binary must be built withgo build -gcflags=all="-N -l" to disableinlining and optimizations that can interfere with debugging.
    • auto: automatically choose betweendebug andtest depending on theopen file

⚠️ For"Remote Debugging", add theport attribute to thelaunch configuration. VS Code will connect to the external user-specifieddlv dap server athost:port and launch the target there.

For remote debugging, theprogram attribute must point to the absolute path tothe package or binary to debug in the remote host’s file system even whensubstitutePath is specified.

Attach

You can use this configuration to attach to a running process or a running debugsession.

  • Supported modes
    • local: attaches to a local process.
      • The binary must be built withgo build -gcflags=all="-N -l" to disableinlining and optimizations that can interfere with debugging.
    • remote: attaches to an in-progress debug session run by an externalserver.

You can debug an already running program using thelocal mode typeconfiguration. The Go extension will startdlv dap and configure it to attachto the specified process. Users can select the process to debug with one of thefollowing options:

  • Specifying the numeric process id (PID) with theprocessId attribute.
  • Specifying the target program name in theprocessId attribute. If there aremultiple processes matching the specified program name, the extension willshow the list of matching processes at the start of the debug session.
  • Specifying0 in theprocessId attribute and selecting the process from thedrop-down menu at the start of the debug session.

Attach to a running process

NOTE: For remote debugging, add theport attribute tothe launch configuration. VS Code will connect to the external user-specifieddlv dap server athost:port and attach to the target there.See"remote debugging" for more details).

You can connect to an already running remote debug session using theremotemode. Specify optionalhost and requiredport for the externaldlv --headless server that already took program or process id details ascommand-line arguments. See"Remote Debugging" for moredetails).

When you end an attach debug session, the debug UI allows you to choose to:

  • [DEFAULT] Disconnect: disconnect the client and:
    • local: leave the target process running (dlv terminates).
    • remote: let dlv decide if it can continue running (--accept-multiclientmode only); if so, the target will stay in halted or running state it was inat disconnect.
      • dlv debug/test/exec: terminate the target process if dlv terminates.
      • dlv attach: leave the target process running even if dlv terminates.
  • Stop: stop the attached server and the target process.

Terminate Debugging started with Attach

Debug actions

Once a debug session starts, the Debug toolbar will appear on the top of theeditor.

Debug Tool Bar

The available commands are:

  • Continue / Pause F5
  • Step Over (akanext in Delve) F10
  • Step Into (akastep in Delve) F11
  • Step Out (akastepout in Delve) Shift+F11 or ⇧F11
  • Restart (currently this is "Stop + Start") Ctrl+Shift+F5 or ⇧⌘F5
  • Stop (terminate the debugee. Available in Launch request) Shift+F5 or ⇧F5
  • Disconnect (detach from the debugee. Available only in Attach request)Shift+F5 or ⇧F5
  • Terminate (terminate the debugee. Available only in Attach request)Alt+Shift+F5 or ⌥⇧F5

Breakpoints

SeeVS Code’s Debug Documentation on Breakpointsto get familiar with VS Code’s UI. The Go debugger supports multiple ways toconfigure breakpoints.

  • Breakpoints: you can set breakpoints by clicking on the editor margin orusing F9 on the current line. If the breakpoints can’t be set by Delve, VSCode will show the failure reason and grey out the dot.

Invalid breakpoint

  • Conditional breakpoints: you can specify breakpoint conditions (similar toDelve’scondition command).
    • Expression condition: takes a boolean expression.
    • Hit count: supports comparison operators (>,>=,<,<=,==,!=)with an integer value.% n form means we should stop at the breakpointwhen the hitcount is a multiple ofn.

Conditional Breakpoint

  • Function Breakpoints: breakpoints can be set based on function names.Press the + button in the BREAKPOINTS section header and enter the location inthe form of<function>[:<line>]. This sets the breakpoint in thelineinside thefunction. The full syntax forfunction is<package>.(*<receiver type>).<function_name> as specified inDelve’s location spec.Function breakpoints are shown with a red triangle in the BREAKPOINTS section.

Function breakpoint

  • Logpoints: alogpoint isa variant of breakpoint that does not 'break', but instead logs a message toDEBUG CONSOLE and continues execution. Expressions within{} areinterpolated. For the list of acceptable expressions and syntax, seeDelve's documentation.

Data inspection

You can inspect variables in the VARIABLES section of the Run view or byhovering over their source in the editor. Variable values and expressionevaluation are relative to the selected stack frame in the CALL section.

By default, the VARIABLES section hides global variables, and shows only localvariables and function arguments. However, you can still inspect globalvariables from the DEBUG CONSOLE panel. If you prefer to have the VARIABLESsection show global variables, set theshowGlobalVariables attribute in thelaunch.json configuration, or set it in thego.delveConfig setting.

When you select a variable and right click from the VARIABLES section, thecontext menu will present shortcuts to features such as:

  • Set Value: you can set/modify simple string, numeric, pointer values. Usingcomposite literals, or memory allocation is not supported.
  • Copy Value: this copies the value in clipboard.
  • Copy as Expression: this is useful when you need to query from the REPL inthe DEBUG CONSOLE panel.
  • Add to Watch: this will automatically add the expression to the WATCHsection.

Shadowed variables will be marked with().

Shadowed Variables

⚠️ Delve debugger imposes variable loading limits to prevent loading too manyvariables at once and negatively impacting debugging latency. Thedlv-dap modeuses a different approach. It takes advantage of the interactive UI features toprovide on-demand loading of individual variables, paging of arrays, slices andmaps and increased string limits depending on the context. We continue toexplore additional interactive features to balance performance and usability ofvariable loading and look forward to your feedback.

You can inspect variables and evaluate expressions from the DEBUG CONSOLE paneltoo. Acceptable expressions are either

Debug Console

Variables and expressions accepted in DEBUG CONSOLE can be also registered inthe Run view’s WATCH section, so they can be evaluated automatically as youdebug. The "Add to Watch" feature from the VARIABLES section is convenient whenyou want to register interesting variables.

⚠️ Function call feature is highly EXPERIMENTAL due to the limitation in Goruntime. Registering function calls in the WATCH section can often beproblematic. Pause, stop, and disconnect will not work while a function call isrunning.

Hover over variables in editors during debugging shows the value of thevariable. For this feature, VS Code extracts the variable expression and makes arequest to the debugger to evaluate the expression. Delve evaluates theexpression relative to the highlighted stack frame chosen in the CALL STACK. Bydefault, that is the current top-most frame.

Hover over Variable in Source Code

⚠️ Limitation

  • VS Code heuristically determines the variable expression without fullunderstanding of the scope & the currently selected frame. Delve tries toevaluate the provided expression in the selected frame. As a result, hoverover variables outside the selected frame’s function may present incorrectinformation.

Call stack

You can inspect all goroutines and their stacks in the CALL STACK section. TheCALL STACK section UI allows switching between goroutines or selecting adifferent stack frame. As a different stack frame or different goroutine isselected, the scope shown in the VARIABLE section will be updated for the newlyselected stack frame, and the expressions in the WATCH section will beautomatically reevaluated relative to the newly selected stack frame.

Call Stack Section Overview

  1. Goroutine stacks are annotated with their internal goroutine IDs.
  2. The current goroutine is marked with*. If multiple goroutines stop (e.g.hit breakpoints) concurrently, Delve will pick one randomly. There also mightnot be a current goroutine (e.g. deadlock, pause or internal breakpoint hitby a system thread not running a goroutine).
  3. If you click a goroutine call stack from the CALL STACK section, thegoroutine isselected.
  4. You can select a frame of the selected goroutine. The VARIABLE and WATCHsections will be updated accordingly and the cursor in the editor will bemoved to the corresponding location in the source code.
  5. Runtime stack frames are deemphasized (greyed out or collapsed).
  6. Thread IDs are shown for scheduled goroutines.
  7. Stop reason. It’s possible that there are multiple reasons goroutines werestopped, but currently only one reason is presented.
  8. File name and line number of the frame.
  9. You can trigger a debug action with the selected goroutine. Note: Resuming orstopping only a single goroutine (Go Issue25578,31132) is currently notsupported, so the action will cause all the goroutines to get activated orpaused.
  10. Function name of the frame.

When the program stops due to exception, panic, or bad access error, the CALLSTACK shows the stop reason and the editor highlights the source location withmore details.

Panic

dlv command from DEBUG CONSOLE

DEBUG CONSOLE accepts commands that allow users to dynamically inspect/changedebug configuration, or inspect the list of source code compiled in the debuggedbinary. Usedlv help anddlv config -list from the DEBUG CONSOLE panel tosee the list of supported commands and dynamically adjustable settings.

Configuration

Launch.json attributes

There are many attributes that you can adjust in the launch and attach debugconfiguration. The following general attributes are mandatory for all launchconfigurations.

  • name: the name of your configuration as it appears in the drop-down in theRun view.
  • type: the debugging type VS Code uses to decide which debugging extensionshould be used. Always leave this set to"go".
  • request:launch orattach.

Here is the list of attributes specific to Go debugging.

PropertyLaunchAttach
argsCommand line arguments passed to the debugged program.
(Default:[])
n/a
asRoot(Experimental) Debug with elevated permissions (on Unix). It requiresintegrated orexternal console modes and is ignored in remote debugging.
(Default:false)
(Experimental) Debug with elevated permissions (on Unix). This requiresintegrated orexternal console modes and is ignored in remote debugging.
(Default:false)
backendBackend used by delve. Maps todlv's--backend flag.

Allowed Values:"default","native","lldb","rr"

same as Launch
buildFlagsBuild flags, to be passed to the Go compiler. Maps to dlv's--build-flags flag.
(Default:[])
n/a
console(Experimental) Where to launch the debugger and the debug target: internal console, integrated terminal, or external terminal. It is ignored in remote debugging.

Allowed Values:"internalConsole","integratedTerminal","externalTerminal"
(Default:internalConsole)

(Experimental) Where to launch the debugger: internal console, integrated terminal, or external terminal. This does not affect tty of the running program. It is ignored in remote debugging.

Allowed Values:"internalConsole","integratedTerminal","externalTerminal"
(Default:internalConsole)

coreFilePathPath to the core dump file to open. For use on 'core' mode only
(Default:"")
n/a
cwdWorkspace relative or absolute path to the working directory of the program being debugged if a non-empty value is specified. Theprogram folder is used as the working directory ifcwd is omitted or empty.
(Default:"")
Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
(Default:"${workspaceFolder}")
debugAdapterSelect which debug adapter to use with this launch configuration.

Allowed Values:"legacy","dlv-dap"
(Default:dlv-dap)

same as Launch
dlvFlagsExtra flags fordlv. Seedlv help for the full list of supported. Flags such as--log-output,--log,--log-dest,--api-version,--output,--backend already have corresponding properties in the debug configuration, and flags such as--listen and--headless are used internally. If they are specified indlvFlags, they may be ignored or cause an error.
same as Launch
envEnvironment variables passed to the launched debuggee program. Format as string key:value pairs. Merged withenvFile andgo.toolsEnvVars with precedenceenv >envFile >go.toolsEnvVars.
n/a
envFileAbsolute path to a file containing environment variable definitions, formatted as string key=value pairs. Multiple files can be specified by provided an array of absolute paths. Merged withenv andgo.toolsEnvVars with precedenceenv >envFile >go.toolsEnvVars.
n/a
hideSystemGoroutinesBoolean value to indicate whether system goroutines should be hidden from call stack view.
(Default:false)
same as Launch
hostWhen applied to remote-attach configurations, will look for "dlv ... --headless --listen=:" server started externally. In dlv-dap mode this will apply to all other configurations as well. The extension will try to connect to an external server started with "dlv dap --listen=:" to ask it to launch/attach to the target process.
(Default:"127.0.0.1")
When applied to remote-attach configurations, will look for "dlv ... --headless --listen=:" server started externally. In dlv-dap mode, this will apply to all other configurations as well. The extension will try to connect to an external server started with "dlv dap --listen=:" to ask it to launch/attach to the target process.
(Default:"127.0.0.1")
logDestdlv's--log-dest flag. Seedlv log for details. Number argument is not allowed. Supported only indlv-dap mode, and on Linux and Mac OS.
dlv's--log-dest flag. Seedlv log for details. Number argument is not allowed. Supported only indlv-dap mode and on Linux and Mac OS.
logOutputComma separated list of components that should produce debug output. Maps to dlv's--log-output flag. Checkdlv log for details.

Allowed Values:"debugger","gdbwire","lldbout","debuglineerr","rpc","dap"
(Default:"debugger")

same as Launch
modeOne ofauto,debug,test,exec,replay,core. Inauto mode, the extension will choose eitherdebug ortest depending on active editor window.

Allowed Values:"auto","debug","test","exec","replay","core"
(Default:auto)

Indicates local or remote debugging. Local is similar to thedlv attach command, remote - todlv connect

Allowed Values:"local","remote"
(Default:local)

outputOutput path for the binary of the debugee.
(Default:"debug")
n/a
portWhen applied to remote-attach configurations, will look for "dlv ... --headless --listen=:" server started externally. In dlv-dap mode this will apply to all other configurations as well. The extension will try to connect to an external server started with "dlv dap --listen=:" to ask it to launch/attach to the target process.
(Default:2345)
When applied to remote-attach configurations, will look for "dlv ... --headless --listen=:" server started externally. In dlv-dap mode, this will apply to all other configurations as well. The extension will try to connect to an external server started with "dlv dap --listen=:" to ask it to launch/attach to the target process.
(Default:2345)
processIdn/a

Option 1: Use process picker to select a process to attach, or Process ID as integer.

Allowed Values:"${command:pickProcess}","${command:pickGoProcess}"

Option 2: Attach to a process by name. If more than one process matches the name, use the process picker to select a process.

Option 3: The numeric ID of the process to be debugged. If 0, use the process picker to select a process.

(Default:0)

programPath to the program folder (or any go file within that folder) when indebug ortest mode, and to the pre-built binary file to debug inexec mode. If it is not an absolute path, the extension interprets it as a workspace relative path.
(Default:"${workspaceFolder}")
n/a
remotePathn/a(Deprecated)UsesubstitutePath instead.
The path to the source code on the remote machine, when the remote path is different from the local machine. If specified, becomes the first entry in substitutePath. Not supported withdlv-dap.
(Default:"")
showGlobalVariablesBoolean value to indicate whether global package variables should be shown in the variables pane or not.
(Default:false)
same as Launch
showLogShow log output from the delve debugger. Maps to dlv's--log flag.
(Default:false)
same as Launch
showRegistersBoolean value to indicate whether register variables should be shown in the variables pane or not.
(Default:false)
same as Launch
stackTraceDepthMaximum depth of stack trace collected from Delve.
(Default:50)
same as Launch
stopOnEntryAutomatically stop program after launch.
(Default:false)
Automatically stop program after attach.
(Default:false)
substitutePathAn array of mappings from a local path (editor) to the remote path (debugee). This setting is useful when working in a file system with symbolic links, running remote debugging, or debugging an executable compiled externally. The debug adapter will replace the local path with the remote path in all of the calls.


  • "from": The absolute local path to be replaced when passing paths to the debugger.
    (Default:"")
  • "to": The absolute remote path to be replaced when passing paths back to the client.
    (Default:"")

An array of mappings from a local path (editor) to the remote path (debugee). This setting is useful when working in a file system with symbolic links, running remote debugging, or debugging an executable compiled externally. The debug adapter will replace the local path with the remote path in all of the calls. Overridden byremotePath.


  • "from": The absolute local path to be replaced when passing paths to the debugger.
    (Default:"")
  • "to": The absolute remote path to be replaced when passing paths back to the client.
    (Default:"")

traceVarious levels of logging shown in the debug console & 'Go Debug' output channel. When using thelegacy debug adapter, the logs will also be written to a file if it is set to a value other thanerror.

Allowed Values:"verbose","trace","log","info","warn","error"
(Default:"error")

same as Launch
traceDirPathDirectory in which the record trace is located or to be created for a new output trace. For use on 'replay' mode only
(Default:"")
n/a

⚠️ Delve resolves relative paths fromdlv dap process's working directory, butfrom which directory the extension spawns thedlv dap process is animplementation detail. Thus, usethe VS Code variables substitutionto ensure consistent expansion of paths. VS Code will resolve the variablesinside strings inlaunch.json before passing the configuration to the Goextension anddlv dap. For example,${workspaceFolder} will be replaced withthe absolute path to the workspace root folder. When appropriate, the Goextension will resolve relative paths or home directory (~) before sending theconfiguration todlv dap.

Debug symlink directories

Since the debugger and go compiler use the actual filenames, extra configurationis required to debug symlinked directories. Use thesubstitutePath property totell thedebugAdapter how to properly translate the paths. For example, ifyour project lives in/path/to/actual/helloWorld, but the project is open invscode under the linked folder/link/to/helloWorld, you can add the followingto your config to set breakpoints in the files in/link/to/helloWorld:

{"name":"Launch with symlinks","type":"go","request":"launch","mode":"debug","program":"/path/to/actual/helloWorld","substitutePath": [        {"from":"/link/to/helloWorld","to":"/path/to/actual/helloWorld"        }    ]}

Settings

You can adjust the default value of the following configuration properties usinggo.delveConfig settings. These default values are useful when you choose torun a debug session without the launch configuration set inlaunch.json. Forexample, debug sessions started using theDebug Test code lenses use theadjusted values from these settings.

  • go.delveConfig
    • debugAdapter: Controls which debug adapter to use (default:legacy).Select ‘dlv-dap’.
    • showGlobalVariables: Show global variables in the Debug view (default:false).
    • substitutePath: Path mappings to apply to get from a path in the editor toa path in the compiled program (default:[]).

⚠️ Where is thedlvLoadConfig setting? Delve debugger imposes variable loadinglimits to avoid loading too many variables at once and negatively impactingdebugging latency. The legacy adapter supporteddlvLoadConfig to adjust theselimits for the duration of the session. The user therefore had to come up with aone-size-fits-all limit if the default behavior was not satisfactory.dlv-dapmode uses a different approach as described inthe Data Inspection section. If this setting is configuredanddlv-dap mode is used, the extension will show a warning prompt now. If thecurrent variable loading behavior and internal limits are not working for you,pleaseopen an issue and shareyour feedback.

dlvLoadConfig is invalid

Advanced topics

Go debug extension architecture overview

VS Code implements a generic, language-agnostic debugger UI based onDebug Adapter Protocol(DAP), an abstract protocol for communicating with debugger backend. Previously,the Go extension used an intermediary typescript program (legacy debug adapter)to launch Delve and adapt Delve to DAP. Withthe new, native DAP implementation in Delve,the intermediary program is no longer necessary, and efficient and tightintegration with Delve becomes possible.

vscode-go debug architecture

For information on debugging using the legacy debug adapter, please see the oldDebugging Documentation. Note that many new or enhanced featuresdiscussed in this document may not be available with the legacy debug adapter.

Handling STDIN

The Go extension anddlv started as a subprocess of the extension do not haveaccess totty. The Go extension captures and forwards STDOUT/STDERR of thedebug program to VS Code, so they can appear inDEBUG OUTPUT panel. But thisarrangement does not handle STDIN.

When the target program needs to read from STDIN or access terminals (tty),use the"console" launch option that controls where thedlv debugger and thetarget process run:

  • integratedTerminal for the terminal inside VS Code
  • externalTerminal for the terminal outside VS Code

The Go extension delegates interaction with terminals to VS Codeusing Debug Adapter Protocol'sRunInTerminal functionality.For configuring VS Code's terminal related behavior, see VS Code'sdocumentation.

Debug programs and tests as root

In order to run and debug a program or a package test running as root, thedebugger (dlv) must run with root privilege, too. You can start the debugsession with root privilege utilizing the"asRoot" AND"console" launchoptions. This is currently supported only on Linux and Mac.

WhenasRoot is true, the Go extension will use thesudo command to rundlv. Sincesudo may ask you to enter password, the debug session needsterminal access so set"console": "integratedTerminal" or"console": "externalTerminal" in the launch configuration.

Debug a program as root

For example, the following launch configuration will startmyprogram and debugit by runningsudo dlv dap command in the integrated terminal.

{"name":"Launch as Root","request":"launch","mode":"exec","asRoot":true,"program":"${workspaceRoot}/myprogram","console":"integratedTerminal",...}

TheasRoot setting can be used withauto/test/debug launch modes thatbuild the target binary to debug. That means thego command will beinvoked as root to compile the binary, too. This can cause issues:

  • by default,sudo does not preserve the user's current environment variables(see documentations about sudo's--preserve-env option). For example,PATHor library paths required for build may be different.
  • Go environment variable settings usually associated in the home directory aredifferent.
  • Module/build caches used during build as root may be different from the cachesused in your normal build. If they are the same, you may encounter permissionerrors due to cache data written to the caches as root.

Instead, you can arrange theexec launch mode to work with a pre-launchtask.

First, configure a debug build task to compile the target binary.

In.vscode/tasks.json:

{..."tasks": [        {"label":"go: build (debug)","type":"shell","command":"go","args": ["build","-gcflags=all=-N -l","-o","${fileDirname}/__debug_bin"            ],"options": {"cwd":"${fileDirname}"            },...        }    ]}

The-gcflags=all=-N -l flag tells thego build command to preserve the debuginformation. The-o flag causes the compiled binary to be placed in"${fileDirname}/__debug_bin". Extra build flags and environment variablesused for build should be configured here asargs oroptions'senvsettings.

It might be useful to add__debug_bin to your.gitignore to avoid debuggingbinaries getting checked-in into your repository.

Then, configure the launch config to run the task before starting debugging.

In.vscode/launch.json:

..."configurations": [        {"name":"Launch Package as root","type":"go","request":"launch","mode":"exec","asRoot":true,"console":"integratedTerminal","program":"${fileDirname}/__debug_bin","preLaunchTask":"go: build (debug)",        }    ]

Settings (args,cwd,env, ...) configured in the abovelaunch.json willonly apply whenrunning the compiled binary, not when building the binary.

Debug a package test as root

To debug package tests as root add the following launch and task configurations.

In.vscode/tasks.json:

..."tasks": [        {...        },        {"label":"go test (debug)","type":"shell","command":"go","args": ["test","-c","-o","${fileDirname}/__debug_bin"            ],"options": {"cwd":"${fileDirname}",            },...        }    ]

In.vscode/launch.json:

..."configurations": [        {...        },        {"name":"Debug Package Test as root","type":"go","request":"launch","mode":"exec","asRoot":true,"program":"${fileDirname}/__debug_bin","cwd":"${fileDirname}","console":"integratedTerminal","preLaunchTask":"go test (debug)"        }    ]

Manually installdlv

On rare occasions, you may want to installdlv by yourself instead of lettingthe extension handle its installation.

First, find where the Go extension finds tools. Likeother tools the extension uses, the Go extension searches thedlv executable from${GOPATH}/bin,${GOBIN} and${PATH} (orPath inWindows). So, installdlv in the directory. The easiest way to check the toolinstallation location the Go extension uses is currently by running theGo: Locate Configured Go Tools command from the command palette (⇧+⌘+P orCtrl+Shift+P).

If your Go version is 1.16 or newer:

GOBIN=<dir_to_install_dlv> go install github.com/go-delve/delve/cmd/dlv@latest

If your Go version is older than 1.16:

cd $(mktemp -d)GO111MODULE=on GOBIN=<dir_to_install_dlv> go get github.com/go-delve/delve/cmd/dlv@latest

You can choose to install a different version ofdlv by specifying a specificcommit hash, a branch name (e.g.master), or a released version instead oflatest. For more details about manual installation, seeDelve's documentation.

If you want to explicitly specify the location of the delve binary, use thego.alternateTools setting:

"go.alternateTools":{"dlv":"<absolute path to your dlv binary>"}

Remote debugging

If you are able to use theRemote Developmentextensions and VS Code’s universalremote development capabilities,that is the recommended way to debug Go programs remotely. Check outGetting startedsection andRemote tutorialsto learn more.

Remote debugging is the debug mode commonly used to work with a debugger andtarget running on a remote machine or a container. In spite of its name, it canalso be used on a local machine with server started in an external terminal(e.g. to support entering stdin into the server's terminal window).

With the introduction ofdlv dap users now have two options for remote (i.e.external) debugging.

Connect to headless delve with target specified at server start-up

In this mode the user must first manually start adlv --headlessserver listening athost:port while specifying the target program todebug/test/exec or a process to attach to on the command-line. Aremote attach configuration is then used to connect to the debuggerwith a running target.

Theheadless dlv servercan now be used with both"debugAdapter": "legacy" (default value) and"debugAdapter": "dlv-dap" (with Delve v1.7.3 or newer) as well as Delve'scommand-line interfaceviadlv connect. The--accept-multiclient flag makes this a multi-use serverthat persists onDisconnect from a client and allows repeated connections fromany of the aforementioned clients. A combination of--accept-multiclient --continue flags can be used to resume process executionon start-up. Please seedlv --help anddlv [command] --help for dlv'scommand-line options.

We encourage you to give the newly added"debugAdapter": "dlv-dap" support atry and tolet us know of any issues. Ifyou need to use thelegacy mode, please also see thelegacy remote debugging documentation.

For example, start external headless server:

dlv debug /path/to/program/ --headless --listen=:12345 # also add as needed: --accept-multiclient --continue

Connect to it with a remote attach configuration in yourlaunch.json:

{"name":"Connect to external session","type":"go","debugAdapter":"dlv-dap",// `legacy` by default"request":"attach","mode":"remote","port":12345,"host":"127.0.0.1",// can skip for localhost"substitutePath":[{"from":"${workspaceFolder}","to":"/path/to/remote/workspace"},      ...]}

Connect to delve dap with target specified at client start-up

In this mode the user must first manually start adlv dap serverlistening athost:port and then specify the target program vialaunch orattach client config with a"port" attribute.Instead of starting a new local server, the Go extension will tell VS Code toconnect to the server specified byhost:port attributes and then send arequest with the target to debug. This option provides the flexibility of easilyadapting local configurations to connect to external servers, but⚠️ must beused with care since anyone who can connect to the server can make it runarbitrary programs.

When usinglaunch mode, theprogram attribute must point to the absolutepath of the package or binary to debug in the remote host’s file system evenwhensubstitutePath is specified. When usingattach mode outside of localhost, you need to specify theprocessId in the config sincethe processId resolution feature cannot gather information aboutprocesses running remotely.

Start adlv dap server ready to accept a client request to launch or attach toa target process:

dlv dap --listen=:12345

Use the followinglaunch configuration to telldlv to execute a binaryprecompiled withgo build -gcflags=all="-N -l":

{"name":"Connect and launch","type":"go","debugAdapter":"dlv-dap",// the default"request":"launch","port":12345,"host":"127.0.0.1",// can skip for localhost"mode":"exec","program":"/absolute/path/to/remote/workspace/program/executable","substitutePath":[{"from":"${workspaceFolder}","to":"/path/to/remote/workspace"},      ...]}

Or have the binary compiled bydlv dap by modifying the above configuration touse:

"mode":"debug","program":"/absolute/path/to/remote/workspace/package",

⚠️ Limitations

  • Unlikedlv --headless above,dlv dap does not support--accept-multiclient or--continue flags, which means after a debugsession ends, thedlv dap process will always exit.
  • If you usedebug ortest modelaunch requests, Delve builds the targetbinary. Delve tries to build the target from the directory where thedlvprocess is running, so make sure to run thedlv command from the directoryyou would run thego build orgo test command.

Run debugee externally

Sometimes you might like to launch the program for debugging outside of VS Code(e.g. as a workaround of the missingconsole support to enter stdin via anexternal terminal or separate target's output from debug session logging). Thereare currently two options:

  • Compile and run the target program from the external terminal and usethe "attach" configuration.
  • Run the debug server from the external terminal with--listen=:<port> andhave VS Code connect to it usingport in your launch configuration (see"Remote Debugging" for more details)

Troubleshooting

The suggestions below are intended to help you troubleshoot any problems youencounter. If you are unable to resolve the issue, please take a look at thecurrent known debugging issuesorreport a new issue.

  1. Read documentation andFAQs. Also check theDelve FAQin case the problem is mentioned there.
  2. Check yourlaunch.json configuration. Often error messages appearing in theDEBUG CONSOLE panel reveal issues.
  3. Update Delve (dlv) to pick up most recent bug fixes. Followthe instruction.
  4. Check if you can reproduce the issue withdlv, the command line tool fromthe integrated terminal. If it's reproducible whenusingdlv, take a look at theDelve project issue tracker.
  5. Capturelogs and inspect them.
  6. Look at theexisting debugging issuesif similar issues were reported.
  7. If none of these solve your problem, pleaseopen a new issue.

FAQs

I need to view large strings. How can I do that ifdlvLoadConfig withmaxStringLen is deprecated?

The legacy adapter useddlvLoadConfig as one-time session-wide setting tooverride dlv's conservative default variable loading limits, intended to protecttool's performance. The new debug adapter is taking a different approach withon-demand loading of composite data and updated string limits, relaxed wheninteracting with individual strings. In particular, if the new default limit of512, applied to all string values in the variables pane, is not sufficient, youcan take advantage of a larger limit of 4096 with one of the following:

  • Hover over the variable in the source code
  • Copy as Expression to query the string via REPL in the DEBUG CONSOLE panel
  • Copy Value to clipboard

Pleaseopen an issue if thisis not sufficient for your use case or if you have any additional feedback.

Why does my debug session have aninvalid command error when I try to step?

When stepping through a program on a particular goroutine, the debugger willmake sure that the step is completed, even when interrupted by events on adifferent goroutine. If a breakpoint is hit on a different goroutine, the debugadapter will stop the program execution to allow you to inspect the state, eventhough the step request is still active.

If you attempt to make another step request you will get aninvalid commanderror.

Disablebreakpoints from the Breakpoints context menu

UseContinue to resume program execution.

If you do not want the step request to be interrupted, you can disable allbreakpoints from VS Code from the context menu in theBreakpoints view.

Disable breakpoints fromthe Breakpoints context menu

My program does not stop at breakpoints

Check the "BREAKPOINTS" section in the debug view and see if the breakpoints aregreyed outwhen your debug session is active. SettingstopOnEntry is a great way to pauseexecution at the start toverify breakpoints are set correctly. Orenable logging and see ifsetBreakpoints requestssucceeded with all the breakpointsverified.

This problem often occurs when the source location used in compiling thedebugged program and the workspace directory VS Code uses are different. Commonculprits are remote debugging where the program is built in the remote location,use of symbolic links, or use of-trimpath build flags. In this case,configure thesubstitutePath attribute in your launch configuration.

Trimpath tips

If you are using-trimpath to build your program, you need to add entries to substitutepath to let the debugger know how to map the package paths that are compiled in thebinary to the files that you are looking at in the editor.

Here are some tips for configuring substitutePath. This assumes that your program is using module mode, which is the default.

One rule that you will need will map your main module. The mapping will map"from" the file path to the directory containing the module,"to" the module path.

You will also need to create a similar mapping for all dependencies. These include modulesin the module cache, vendored modules, and the standard library.

"substitutePath": [// Main module.  {"from":"${workspaceFolder}","to":"moduleName",  },// Module cache paths.  {"from":"${env:HOME}/go/pkg/mod/github.com","to":"github.com",  },  {"from":"${env:HOME}/go/pkg/mod/golang.org","to":"golang.org",  },...// Standard library paths.// This rule should come last since the empty "to" will match every path.  {"from":"/path/to/local/goroot/pkg" ,"to":""} ],

Since rules are applied both from client to server and server to client,rules with an empty string will be applied toall paths that it sees, so evendependencies will be mapped to"/path/to/module".

We plan to make this easier in the future. Progress can be trackedin the issue trackergolang/vscode-go#1985.

Debug sessions started with the "debug test" CodeLens or the test UI does not use mylaunch.json configuration

The "debug test" CodeLens and thetest UI donot use thelaunch.json configuration(Issue 855). As a workaround,use thego.delveConfig setting and thego.testFlags setting. Please notethat these all apply to all debug sessions unless overwritten by a specificlaunch.json configuration.

Starting a debug session fails with

decoding dwarf section info at offset 0x0: too short orcould not open debug info error

These errors indicate that your binary was built with linker flags that strippedthe symbol table (-s) or the DWARF debug information (-w), making debuggingimpossible. If the binary is built while launching the session, make sure yourlaunch.json configuration does not contain"buildFlags": "--ldflags '-s -w'". If you usedebug test or Test Explorer,checkgo.buildFlags insettings.json. If the binary is built externally,check the command-line flags and do not usego run. Unlikego build,go run passes-s -w to the linker under the hood. If you try to attach tosuch a binary with a debugger, it will fail with one of the above errors (see GoIssue24833). Instead let dlv buildthe binary for you or usego build -gcflags=all="-N -l".

Report issues

When you are having issues indlv-dap mode, first check if the problems arereproducible after updatingdlv and using the most recent version ofdlv.It's possible that the problems are already fixed. You can also try to installdlv at tree head. Follow the instruction forupdatingdlv andupdating extension.

Please report issues inour issue tracker with thefollowing information.

  • go version
  • go version -m <path/to/dlv>
  • VS Code and VS Code Go version (e.g.code --version)
  • Instructions to reproduce the issue (code snippets, yourlaunch.json, screenshot)
  • DAP trace (Seethe instruction)

Collect logs

{"name":"Launch file","type":"go","trace":"verbose","showLog":true,"logOutput":"dap",    ...}

ThelogOutput andshowLog attributes inlaunch.json enable Delve-sidelogging (server-side) and DAP message tracing. Thetrace attribute controlsthe verbosity of Go extension's side logging (client-side).

The logging will appear in theGo Debug output channel (Command Palette ->"View: Toggle Output" -> Select "Go Debug" from the dropdown menu). By nature,debug logs may contain sensitive information. Please review the logs carefullybefore sharing debug logs.

Development

Code location

The core part of Delve DAP implementation is in theservice/dappackage. Follow Delve project'scontribution guidelineto send PRs.

Code for integration with the Go extension is mostly insrc/goDebugFactory.tsand tests are intest/integration/goDebug.test.ts.Please take a look at VS Code Go project'scontribution guideline to learn about how to prepare a changeand send it for review.

Testing

For simple launch cases, build thedlv binary, and configure"go.alternateTools" setting.

"go.alternateTools":{"dlv":<path_to_your_dlv>}

Go Debug outputchannel

If you are having issues with seeing logs and/orsuspect problems in the extension's integration, you can start the Delve DAPserver from a separate terminal and configure the extension to directly connectto it. Please remember to[file an issue](https://github.com/golang/vscode-go/issues/new) if you encounterany logging-related problems.
dlv dap --listen=:12345 --log --log-output=dap
{"name":"Launch file","type":"go","request":"launch","debugAdapter":"dlv-dap",    ..."port":12345}

✏️ Want to contribute to this wiki?

Updatethe source and send a PR.

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp