# Delve > The following editor plugins for delve are available: --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/EditorIntegration.md ## Editor plugins The following editor plugins for delve are available: **Atom** * [Go Debugger for Atom](https://github.com/lloiser/go-debug) **Emacs** * [Emacs plugin](https://github.com/benma/go-dlv.el/) * [dap-mode](https://github.com/emacs-lsp/dap-mode#go-1) * [dape](https://github.com/svaante/dape?tab=readme-ov-file#go---dlv) **Goland** * [JetBrains Goland](https://www.jetbrains.com/go) **IntelliJ IDEA** * [Golang Plugin for IntelliJ IDEA](https://plugins.jetbrains.com/plugin/9568-go) **LiteIDE** * [LiteIDE](https://github.com/visualfc/liteide) **Vim** * [vim-go](https://github.com/fatih/vim-go) (both Vim and Neovim) * [vim-delve](https://github.com/sebdah/vim-delve) (both Vim and Neovim) * [vim-godebug](https://github.com/jodosha/vim-godebug) (only Neovim) * [vimspector](https://github.com/puremourning/vimspector/) **VisualStudio Code** * [Go for Visual Studio Code](https://github.com/golang/vscode-go) **Sublime** * [Go Debugger for Sublime](https://github.com/dishmaev/GoDebug) ## Alternative UIs The following alternative UIs for delve are available: * [Gdlv](https://github.com/aarzilli/gdlv) * [Debugger](https://github.com/emad-elsaid/debugger) --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/KnownBugs.md # Known Bugs - When Delve is compiled with versions of go prior to 1.7.0 it is not possible to set a breakpoint on a function in a remote package using the `Receiver.MethodName` syntax. See [Issue #528](https://github.com/go-delve/delve/issues/528). - When running Delve on binaries compiled with a version of go prior to 1.9.0 `locals` will print all local variables, including ones that are out of scope, the shadowed flag will be applied arbitrarily. If there are multiple variables defined with the same name in the current function `print` will not be able to select the correct one for the current line. - `reverse step` will not reverse step into functions called by deferred calls. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/api/ClientHowto.md # How to write a Delve client, an informal guide ## Spawning the backend The `dlv` binary built by our `Makefile` contains both the backend and a simple command line client. If you are writing your own client you will probably want to run only the backend, you can do this by specifying the `--headless` option, for example: ``` $ dlv --headless debug ``` The rest of the command line remains unchanged. You can use `debug`, `exec`, `test`, etc... along with `--headless` and they will work. If this project is part of a larger IDE integration then you probably have your own build system and do not wish to offload this task to Delve, in that case it's perfectly fine to always use the `dlv exec` command but do remember that: 1. Delve may not have all the information necessary to properly debug optimized binaries, so it is recommended to disable them via: `-gcflags='all=-N -l`. 2. your users *do want* to debug their tests so you should also provide some way to build the test executable (equivalent to `go test -c --gcflags='all=-N -l'`) and pass it to Delve. It would also be nice for your users if you provided a way to attach to a running process, like `dlv attach` does. Command line arguments that should be handed to the inferior process should be specified on dlv's command line after a "--" argument: ``` dlv exec --headless ./somebinary -- these arguments are for the inferior process ``` Specifying a static port number, like in the [README](//github.com/go-delve/delve/tree/master/Documentation/README.md) example, can be done using `--listen=127.0.0.1:portnumber`. This will, however, cause problems if you actually spawn multiple instances of the debugger. It's probably better to let Delve pick a random unused port number on its own. To do this do not specify any `--listen` option and read one line of output from dlv's stdout. If the first line emitted by dlv starts with "API server listening at: " then dlv started correctly and the rest of the line specifies the address that Delve is listening at. The `--log-dest` option can be used to redirect the "API server listening at:" message to a file or to a file descriptor. If the flag is not specified, the message will be output to stdout while other log messages are output to stderr. ## Controlling the backend Once you have a running headless instance you can connect to it and start sending commands. Delve's protocol is built on top of the [JSON-RPC 1.0 specification](https://www.jsonrpc.org/specification_v1). The methods of a `service/rpc2.RPCServer` are exposed through this connection, to find out which requests you can send see the documentation of RPCServer on [Go Reference](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer). ### Example Let's say you are trying to create a breakpoint. By looking at [Go Reference](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer) you'll find that there is a `CreateBreakpoint` method in `RPCServer`. This method, like all other methods of RPCServer that you can call through the API, has two arguments: `args` and `out`: `args` contains all the input arguments of `CreateBreakpoint`, while `out` is what `CreateBreakpoint` will return to you. The call that you could want to make, in pseudo-code, would be: ``` RPCServer.CreateBreakpoint(CreateBreakpointIn{ File: "/User/you/some/file.go", Line: 16 }) ``` To actually send this request on the JSON-RPC connection you just have to convert the CreateBreakpointIn object to json and then wrap everything into a JSON-RPC envelope: ``` {"method":"RPCServer.CreateBreakpoint","params":[{"Breakpoint":{"file":"/User/you/some/file.go","line":16}}],"id":27} ``` Delve will respond by sending a response packet that will look like this: ``` {"id":27, "result": {"Breakpoint": {"id":3, "name":"", "addr":4538829, "file":"/User/you/some/file.go", "line":16, "functionName":"main.main", "Cond":"", "continue":false, "goroutine":false, "stacktrace":0, "LoadArgs":null, "LoadLocals":null, "hitCount":{}, "totalHitCount":0}}, "error":null} ``` ## Selecting the API version Delve currently supports two version of its API, APIv1 and APIv2. By default a headless instance of `dlv` will serve APIv1 for backward-compatibility with older clients, however new clients should use APIv2 as new features will only be made available through version 2. The preferred method of switching to APIv2 is to send the `RPCServer.SetApiVersion` command right after connecting to the backend. Alternatively the `--api-version=2` command line option can be used when spawning the backend. ## Diagnostics Just like any other program, both Delve and your client have bugs. To help with determining where the problem is you should log the exchange of messages between Delve and your client somehow. If you don't want to do this yourself you can also pass the options `--log --log-output=rpc` to Delve. In fact the `--log-output` has many useful values and you should expose it to users, if possible, so that we can diagnose problems that are hard to reproduce. ## Using RPCServer.Command `Command` is probably the most important API entry point. It lets your client stop (`Name == "halt"`) and resume (`Name == "continue"`) execution of the inferior process. The return value of `Command` is a `DebuggerState` object. If you lose the DebuggerState object returned by your last call to `Command` you can ask for a new copy with `RPCServer.State`. ### Dealing with simultaneous breakpoints Since Go is a programming language with a big emphasis on concurrency and parallelism it's possible that multiple goroutines will stop at a breakpoint simultaneously. This may at first seem incredibly unlikely but you must understand that between the time a breakpoint is triggered and the point where the debugger finishes stopping all threads of the inferior process thousands of CPU instructions have to be executed, which make simultaneous breakpoint triggering not that unlikely. You should signal to your user *all* the breakpoints that occur after executing a command, not just the first one. To do this iterate through the `Threads` array in `DebuggerState` and note all the threads that have a non nil `Breakpoint` member. ### Special continue commands In addition to "halt" and vanilla "continue" `Command` offers a few extra flavours of continue that automatically set interesting temporary breakpoints: "next" will continue until the next line of the program, "stepout" will continue until the function returns, "step" is just like "next" but it will step into function calls (but skip all calls to unexported runtime functions). All of "next", "step" and "stepout" operate on the selected goroutine. The selected goroutine is described by the `SelectedGoroutine` field of `DebuggerState`. Every time `Command` returns the selected goroutine will be reset to the goroutine that triggered the breakpoint. If multiple breakpoints are triggered simultaneously the selected goroutine will be chosen randomly between the goroutines that are stopped at a breakpoint. If a breakpoint is hit by a thread that is executing on the system stack *there will be no selected goroutine*. If the "halt" command is called *there may not be a selected goroutine*. The selected goroutine can be changed using the "switchGoroutine" command. If "switchGoroutine" is used to switch to a goroutine that's currently parked SelectedGoroutine and CurrentThread will be mismatched. Always prefer SelectedGoroutine over CurrentThread, you should ignore CurrentThread entirely unless SelectedGoroutine is nil. ### Special continue commands and asynchronous breakpoints Because of the way go internals work it is not possible for a debugger to resume a single goroutine. Therefore it's possible that after executing a next/step/stepout a goroutine other than the goroutine the next/step/stepout was executed on will hit a breakpoint. If this happens Delve will return a DebuggerState with NextInProgress set to true. When this happens your client has two options: * You can signal that a different breakpoint was hit and then automatically attempt to complete the next/step/stepout by calling `RPCServer.Command` with `Name == "continue"` * You can abort the next/step/stepout operation using `RPCServer.CancelNext`. It is important to note that while NextInProgress is true it is not possible to call next/step/stepout again without using CancelNext first. There can not be multiple next/step/stepout operations in progress at any time. ### RPCServer.Command and stale executable files It's possible (albeit unfortunate) that your user will decide to change the source of the program being executed in the debugger, while the debugger is running. Because of this it would be advisable that your client check that the executable is not stale every time `Command` returns and notify the user that the executable being run is stale and line numbers may nor align properly anymore. You can do this bookkeeping yourself, but Delve can also help you with the `LastModified` call that returns the LastModified time of the executable file when Delve started it. ## Using RPCServer.CreateBreakpoint The only two fields you probably want to fill of the Breakpoint argument of CreateBreakpoint are File and Line. The file name should be the absolute path to the file as the compiler saw it. For example if the compiler saw this path: ``` /Users/you/go/src/something/something.go ``` But `/Users/you/go/src/something` is a symbolic link to `/Users/you/projects/golang/something` the path *must* be specified as `/Users/you/go/src/something/something.go` and `/Users/you/projects/golang/something/something.go` will not be recognized as valid. If you want to let your users specify a breakpoint on a function selected from a list of all functions you should specify the name of the function in the FunctionName field of Breakpoint. If you want to support the [same language as dlv's break and trace commands](//github.com/go-delve/delve/tree/master/Documentation/cli/locspec.md) you should call RPCServer.FindLocation and then use the returned slice of Location objects to create Breakpoints to pass to CreateBreakpoint: just fill each Breakpoint.Addr with the contents of the corresponding Location.PC. ## Looking into variables There are several API entry points to evaluate variables in Delve: * RPCServer.ListPackageVars returns all global variables in all packages * PRCServer.ListLocalVars returns all local variables of a stack frame * RPCServer.ListFunctionArgs returns all function arguments of a stack frame * RPCServer.Eval evaluates an expression on a given stack frame All those API calls take a LoadConfig argument. The LoadConfig specifies how much of the variable's value should actually be loaded. Because of LoadConfig a variable could be loaded incompletely, you should always notify the user of this: * For strings, arrays, slices *and structs* the load is incomplete if: `Variable.Len > len(Variable.Children)`. This can happen to structs even if LoadConfig.MaxStructFields is -1 when MaxVariableRecurse is reached. * For maps the load is incomplete if: `Variable.Len > len(Variable.Children) / 2` * For interfaces the load is incomplete if the only children has the onlyAddr attribute set to true. ### Loading more of a Variable You can also give the user an option to continue loading an incompletely loaded variable. To load a struct that wasn't loaded automatically evaluate the expression returned by: ``` fmt.Sprintf("*(*%q)(%#x)", v.Type, v.Addr) ``` where v is the variable that was truncated. To load more elements from an array, slice or string: ``` fmt.Sprintf("(*(*%q)(%#x))[%d:]", v.Type, v.Addr, len(v.Children)) ``` To load more elements from a map: ``` fmt.Sprintf("(*(*%q)(%#x))[%d:]", v.Type, v.Addr, len(v.Children)/2) ``` All the evaluation API calls except ListPackageVars also take a EvalScope argument, this specifies which stack frame you are interested in. If you are interested in the topmost stack frame of the current goroutine (or thread) use: `EvalScope{ GoroutineID: -1, Frame: 0 }`. More information on the expression language interpreted by RPCServer.Eval can be found [here](//github.com/go-delve/delve/tree/master/Documentation/cli/expr.md). ### Variable shadowing Let's assume you are debugging a piece of code that looks like this: ``` for i := 0; i < N; i++ { for i := 0; i < M; i++ { f(i) // <-- debugger is stopped here } } ``` The response to a ListLocalVars request will list two variables named `i`, because at that point in the code two variables named `i` exist and are in scope. Only one (the innermost one), however, is visible to the user. The other one is *shadowed*. Delve will tell you which variable is shadowed through the `Flags` field of the `Variable` object. If `Flags` has the `VariableShadowed` bit set then the variable in question is shadowed. Users of your client should be able to distinguish between shadowed and non-shadowed variables. ## Gracefully ending the debug session To ensure that Delve cleans up after itself by deleting the `debug` or `debug.test` binary it creates and killing any processes spawned by the program being debugged, the `Detach` command needs to be called. In case you are disconnecting a running program, ensure to halt the program before trying to detach. ## Testing the Client A set of [example programs is available](https://github.com/aarzilli/delve_client_testing) to test corner cases in handling breakpoints and displaying data structures. Follow the instructions in the README.txt file. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/backend_test_health.md Tests skipped by each supported backend: * 386 skipped = 11 * 1 broken * 3 broken - cgo stacktraces * 6 not implemented * 1 not working due to optimizations * arm64 skipped = 1 * 1 broken - global variable symbolication * darwin skipped = 5 * 4 follow exec not implemented on macOS * 1 waitfor implementation is delegated to debugserver * darwin/arm64 skipped = 1 * 1 broken - cgo stacktraces * darwin/lldb skipped = 1 * 1 upstream issue * freebsd skipped = 15 * 2 flaky * 4 follow exec not implemented on freebsd * 7 not implemented * 2 not working on freebsd * linux/386 skipped = 2 * 2 not working on linux/386 * linux/386/pie skipped = 1 * 1 broken * linux/loong64 skipped = 1 * 1 not working on linux/loong64 * linux/ppc64le skipped = 3 * 1 broken - cgo stacktraces * 2 not working on linux/ppc64le when -gcflags=-N -l is passed * linux/ppc64le/native skipped = 1 * 1 broken in linux ppc64le * linux/ppc64le/native/pie skipped = 3 * 3 broken - pie mode * linux/riscv64 skipped = 1 * 1 not working on linux/riscv64 * loong64 skipped = 7 * 1 broken - global variable symbolication * 6 not implemented * pie skipped = 2 * 2 upstream issue - https://github.com/golang/go/issues/29322 * ppc64le skipped = 14 * 6 broken * 1 broken - global variable symbolication * 7 not implemented * riscv64 skipped = 6 * 1 broken - global variable symbolication * 5 not implemented * windows skipped = 9 * 1 broken * 2 not working on windows * 6 see https://github.com/go-delve/delve/issues/2768 * windows/arm64 skipped = 3 * 2 broken - cgo stacktraces * 1 flaky --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/cli/cond.md # Breakpoint conditions Breakpoints have two conditions: * The normal condition, which is specified using the command `cond ` (or by setting the Cond field when amending a breakpoint via the API), is any [expression](expr.md) which evaluates to true or false. * The hitcount condition, which is specified `cond -hitcount ` (or by setting the HitCond field when amending a breakpoint via the API), is a constraint on the number of times the breakpoint has been hit. When a breakpoint location is encountered during the execution of the program, the debugger will: * Evaluate the normal condition * Stop if there is an error while evaluating the normal condition * If the normal condition evaluates to true the hit count is incremented * Evaluate the hitcount condition * If the hitcount condition is also satisfied stop the execution at the breakpoint --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/cli/expr.md # Expressions Delve can evaluate a subset of go expression language, specifically the following features are supported: - All (binary and unary) on basic types except <-, ++ and -- - Comparison operators on any type - Type casts between numeric types - Type casts of integer constants into any pointer type and vice versa - Type casts between string, []byte and []rune - Struct member access (i.e. `somevar.memberfield`) - Slicing and indexing operators on arrays, slices and strings - Map access - Pointer dereference - Calls to builtin functions: `cap`, `len`, `complex`, `imag` and `real` - Type assertion on interface variables (i.e. `somevar.(concretetype)`) # Nesting limit When delve evaluates a memory address it will automatically return the value of nested struct members, array and slice items and dereference pointers. However to limit the size of the output evaluation will be limited to two levels deep. Beyond two levels only the address of the item will be returned, for example: ``` (dlv) print c1 main.cstruct { pb: *struct main.bstruct { a: (*main.astruct)(0xc82000a430), }, sa: []*main.astruct len: 3, cap: 3, [ *(*main.astruct)(0xc82000a440), *(*main.astruct)(0xc82000a450), *(*main.astruct)(0xc82000a460), ], } ``` To see the contents of the first item of the slice `c1.sa` there are two possibilities: 1. Execute `print c1.sa[0]` 2. Use the address directly, executing: `print *(*main.astruct)(0xc82000a440)` # Elements limit For arrays, slices, strings and maps delve will only return a maximum of 64 elements at a time: ``` (dlv) print ba []int len: 200, cap: 200, [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...+136 more] ``` To see more values use the slice operator: ``` (dlv) print ba[64:] []int len: 136, cap: 136, [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...+72 more] ``` For this purpose delve allows use of the slice operator on maps, `m[64:]` will return the key/value pairs of map `m` that follow the first 64 key/value pairs (note that delve iterates over maps using a fixed ordering). These limits can be configured with `max-string-len` and `max-array-values`. See [config](https://github.com/go-delve/delve/tree/master/Documentation/cli#config) for usage. # Interfaces Interfaces will be printed using the following syntax: ``` () ``` For example: ``` (dlv) p iface1 (dlv) p iface1 interface {}(*struct main.astruct) *{A: 1, B: 2} (dlv) p iface2 interface {}(*struct string) *"test" (dlv) p err1 error(*struct main.astruct) *{A: 1, B: 2} ``` To use the contents of an interface variable use a type assertion: ``` (dlv) p iface1.(*main.astruct).B 2 ``` Or just use the special `.(data)` type assertion: ``` (dlv) p iface1.(data).B 2 ``` If the contents of the interface variable are a struct or a pointer to struct the fields can also be accessed directly: ``` (dlv) p iface1.B 2 ``` # Specifying package paths Packages with the same name can be disambiguated by using the full package path. For example, if the application imports two packages, `some/package` and `some/other/package`, both defining a variable `A`, the two variables can be accessed using this syntax: ``` (dlv) p "some/package".A (dlv) p "some/other/package".A ``` # Pointers in Cgo Char pointers are always treated as NUL terminated strings, both indexing and the slice operator can be applied to them. Other C pointers can also be used similarly to Go slices, with indexing and the slice operator. In both of these cases it is up to the user to respect array bounds. # Special Features ## Special Variables Delve defines two special variables: * `runtime.curg` evaluates to the 'g' struct for the current goroutine, in particular `runtime.curg.goid` is the goroutine id of the current goroutine. * `runtime.frameoff` is the offset of the frame's base address from the bottom of the stack. * `delve.bphitcount[X]` is the total hitcount for breakpoint X, which can be either an ID or the breakpoint name as a string. ## Access to variables from previous frames Variables from previous frames (i.e. stack frames other than the top of the stack) can be referred using the following notation `runtime.frame(n).name` which is the variable called 'name' on the n-th frame from the top of the stack. ## CPU Registers The name of a CPU register, in all uppercase letters, will resolve to the value of that CPU register in the current frame. For example on AMD64 the expression `RAX` will evaluate to the value of the RAX register. Register names are shadowed by both local and global variables, so if a local variable called "RAX" exists, the `RAX` expression will evaluate to it instead of the CPU register. Register names can optionally be prefixed by any number of underscore characters, so `RAX`, `_RAX`, `__RAX`, etc... can all be used to refer to the same RAX register and, in absence of shadowing from other variables, will all evaluate to the same value. Registers of 64bits or less are returned as uint64 variables. Larger registers are returned as strings of hexadecimal digits. Because many architectures have SIMD registers that can be used by the application in different ways the following syntax is also available: * `REGNAME.intN` returns the register REGNAME as an array of intN elements. * `REGNAME.uintN` returns the register REGNAME as an array of uintN elements. * `REGNAME.floatN` returns the register REGNAME as an array of floatN elements. In all cases N must be a power of 2. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/cli/getting_started.md # Getting Started Delve aims to be a very simple and powerful tool, but can be confusing if you're not used to using a source level debugger in a compiled language. This document will provide all the information you need to get started debugging your Go programs. ## Debugging 'main' packages The first CLI subcommand we will explore is `debug`. This subcommand can be run without arguments if you're in the same directory as your `main` package, otherwise it optionally accepts a package path. For example given this project layout: ``` github.com/me/foo ├── cmd │   └── foo │   └── main.go └── pkg └── baz ├── bar.go └── bar_test.go ``` If you are in the directory `github.com/me/foo/cmd/foo` you can simply run `dlv debug` from the command line. From anywhere else, say the project root, you can simply provide the package: `dlv debug github.com/me/foo/cmd/foo`. To pass flags to your program separate them with `--`: `dlv debug github.com/me/foo/cmd/foo -- -arg1 value`. Invoking that command will cause Delve to compile the program in a way most suitable for debugging, then it will execute and attach to the program and begin a debug session. Now, when the debug session has first started you are at the very beginning of the program's initialization. To get to someplace more useful you're going to want to set a breakpoint or two and continue execution to that point. For example, to continue execution to your program's `main` function: ``` $ dlv debug github.com/me/foo/cmd/foo Type 'help' for list of commands. (dlv) break main.main Breakpoint 1 set at 0x49ecf3 for main.main() ./test.go:5 (dlv) continue > main.main() ./test.go:5 (hits goroutine(1):1 total:1) (PC: 0x49ecf3) 1: package main 2: 3: import "fmt" 4: => 5: func main() { 6: fmt.Println("delve test") 7: } (dlv) ``` ## Debugging tests Given the same directory structure as above you can debug your code by executing your test suite. For this you can use the `dlv test` subcommand, which takes the same optional package path as `dlv debug`, and will also build the current package if not given any argument. ``` $ dlv test github.com/me/foo/pkg/baz Type 'help' for list of commands. (dlv) funcs test.Test* /home/me/go/src/github.com/me/foo/pkg/baz/test.TestHi (dlv) break TestHi Breakpoint 1 set at 0x536513 for /home/me/go/src/github.com/me/foo/pkg/baz/test.TestHi() ./test_test.go:5 (dlv) continue > /home/me/go/src/github.com/me/foo/pkg/baz/test.TestHi() ./bar_test.go:5 (hits goroutine(5):1 total:1) (PC: 0x536513) 1: package baz 2: 3: import "testing" 4: => 5: func TestHi(t *testing.T) { 6: t.Fatal("implement me!") 7: } (dlv) ``` As you can see, we began debugging the test binary, found our test function via the `funcs` command which takes a regexp to filter the list of functions, set a breakpoint and then continued execution until we hit that breakpoint. For more information on subcommands you can use, type `dlv help`, and once in a debug session you can see all of the commands available to you by typing `help` at any time. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/cli/locspec.md # Location Specifiers Several delve commands take a program location as an argument, the syntax accepted by this commands is: * `*
` Specifies the location of memory address *address*. *address* can be specified as a decimal, hexadecimal or octal number * `:` Specifies the line *line* in *filename*. *filename* can be the partial path to a file or even just the base name as long as the expression remains unambiguous. * `` Specifies the line *line* in the current file * `+` Specifies the line *offset* lines after the current one * `-` Specifies the line *offset* lines before the current one * `[:]` Specifies the line *line* inside *function*. The full syntax for *function* is `.(*).` however the only required element is the function name, everything else can be omitted as long as the expression remains unambiguous. For setting a breakpoint on an init function (ex: main.init), the `:` syntax should be used to break in the correct init function at the correct location. * `//` Specifies the location of all the functions matching *regex* --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/cli/starlark.md # Introduction Passing a file with the .star extension to the `source` command will cause delve to interpret it as a starlark script. Starlark is a dialect of python, a [specification of its syntax can be found here](https://github.com/google/starlark-go/blob/master/doc/spec.md). In addition to the normal starlark built-ins delve defines [a number of global functions](#Starlark-built-ins) that can be used to interact with the debugger. After the file has been evaluated delve will bind any function starting with `command_` to a command-line command: for example `command_goroutines_wait_reason` will be bound to `goroutines_wait_reason`. Then if a function named `main` exists it will be executed. Global functions with a name that begins with a capital letter will be available to other scripts. # Starlark built-ins Function | API Call ---------|--------- amend_breakpoint(Breakpoint) | Equivalent to API call [AmendBreakpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.AmendBreakpoint) ancestors(GoroutineID, NumAncestors, Depth) | Equivalent to API call [Ancestors](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Ancestors) attached_to_existing_process() | Equivalent to API call [AttachedToExistingProcess](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.AttachedToExistingProcess) build_id() | Equivalent to API call [BuildID](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.BuildID) cancel_next() | Equivalent to API call [CancelNext](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.CancelNext) checkpoint(Where) | Equivalent to API call [Checkpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Checkpoint) clear_breakpoint(Id, Name) | Equivalent to API call [ClearBreakpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ClearBreakpoint) clear_checkpoint(ID) | Equivalent to API call [ClearCheckpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ClearCheckpoint) raw_command(Name, ThreadID, GoroutineID, ReturnInfoLoadConfig, Expr, WithEvents, UnsafeCall) | Equivalent to API call [Command](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Command) create_breakpoint(Breakpoint, LocExpr, SubstitutePathRules, Suspended) | Equivalent to API call [CreateBreakpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.CreateBreakpoint) create_ebpf_tracepoint(FunctionName) | Equivalent to API call [CreateEBPFTracepoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.CreateEBPFTracepoint) create_watchpoint(Scope, Expr, Type) | Equivalent to API call [CreateWatchpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.CreateWatchpoint) debug_info_directories(Set, List) | Equivalent to API call [DebugInfoDirectories](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.DebugInfoDirectories) detach(Kill) | Equivalent to API call [Detach](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Detach) disassemble(Scope, StartPC, EndPC, Flavour) | Equivalent to API call [Disassemble](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Disassemble) dump_cancel() | Equivalent to API call [DumpCancel](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.DumpCancel) dump_start(Destination) | Equivalent to API call [DumpStart](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.DumpStart) dump_wait(Wait) | Equivalent to API call [DumpWait](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.DumpWait) eval(Scope, Expr, Cfg) | Equivalent to API call [Eval](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Eval) examine_memory(Address, Length) | Equivalent to API call [ExamineMemory](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ExamineMemory) find_location(Scope, Loc, IncludeNonExecutableLines, SubstitutePathRules) | Equivalent to API call [FindLocation](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.FindLocation) follow_exec(Enable, Regex) | Equivalent to API call [FollowExec](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.FollowExec) follow_exec_enabled() | Equivalent to API call [FollowExecEnabled](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.FollowExecEnabled) function_return_locations(FnName) | Equivalent to API call [FunctionReturnLocations](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.FunctionReturnLocations) get_breakpoint(Id, Name) | Equivalent to API call [GetBreakpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.GetBreakpoint) get_buffered_tracepoints() | Equivalent to API call [GetBufferedTracepoints](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.GetBufferedTracepoints) get_thread(Id) | Equivalent to API call [GetThread](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.GetThread) guess_substitute_path(Args) | Equivalent to API call [GuessSubstitutePath](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.GuessSubstitutePath) is_multiclient() | Equivalent to API call [IsMulticlient](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.IsMulticlient) last_modified() | Equivalent to API call [LastModified](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.LastModified) breakpoints(All) | Equivalent to API call [ListBreakpoints](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListBreakpoints) checkpoints() | Equivalent to API call [ListCheckpoints](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListCheckpoints) dynamic_libraries() | Equivalent to API call [ListDynamicLibraries](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListDynamicLibraries) function_args(Scope, Cfg) | Equivalent to API call [ListFunctionArgs](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListFunctionArgs) functions(Filter, FollowCalls) | Equivalent to API call [ListFunctions](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListFunctions) goroutines(Start, Count, Filters, GoroutineGroupingOptions, EvalScope) | Equivalent to API call [ListGoroutines](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListGoroutines) local_vars(Scope, Cfg) | Equivalent to API call [ListLocalVars](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListLocalVars) package_vars(Filter, Cfg) | Equivalent to API call [ListPackageVars](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListPackageVars) packages_build_info(IncludeFiles, Filter) | Equivalent to API call [ListPackagesBuildInfo](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListPackagesBuildInfo) registers(ThreadID, IncludeFp, Scope) | Equivalent to API call [ListRegisters](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListRegisters) sources(Filter) | Equivalent to API call [ListSources](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListSources) targets() | Equivalent to API call [ListTargets](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListTargets) threads() | Equivalent to API call [ListThreads](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListThreads) types(Filter) | Equivalent to API call [ListTypes](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ListTypes) process_pid() | Equivalent to API call [ProcessPid](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ProcessPid) recorded() | Equivalent to API call [Recorded](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Recorded) restart(Position, ResetArgs, NewArgs, Rerecord, Rebuild, NewRedirects) | Equivalent to API call [Restart](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Restart) set_expr(Scope, Symbol, Value) | Equivalent to API call [Set](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Set) stacktrace(Id, Depth, Full, Defers, Opts, Cfg) | Equivalent to API call [Stacktrace](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Stacktrace) state(NonBlocking) | Equivalent to API call [State](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.State) toggle_breakpoint(Id, Name) | Equivalent to API call [ToggleBreakpoint](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.ToggleBreakpoint) dlv_command(command) | Executes the specified command as if typed at the dlv_prompt read_file(path) | Reads the file as a string write_file(path, contents) | Writes string to a file cur_scope() | Returns the current evaluation scope default_load_config() | Returns the current default load configuration In addition to these built-ins, the [time](https://pkg.go.dev/go.starlark.net/lib/time#pkg-variables) library from the starlark-go project is also available to scripts. ## Should I use raw_command or dlv_command? There are two ways to resume the execution of the target program: raw_command("continue") dlv_command("continue") The first one maps to the API call [Command](https://pkg.go.dev/github.com/go-delve/delve/service/rpc2#RPCServer.Command). As such all the caveats explained in the [Client HowTo](../api/ClientHowto.md). The latter is equivalent to typing `continue` to the `(dlv)` command line and should do what you expect. In general `dlv_command("continue")` should be preferred, unless the behavior you wish to produces diverges significantly from that of the command line's `continue`. # Creating new commands Any global function with a name starting with `command_` will be made available as a command line command. If the function has a single argument named `args` all arguments passed on the command line will be passed to the function as a single string. Otherwise arguments passed on the command line are interpreted as starlark expressions. See the [expression arguments](#expression-arguments) example. If the command function has a doc string it will be used as a help message. ## Using custom commands with the `on` prefix All custom starlark commands can be used with the `on` command (see `help on`) to execute when a breakpoint is hit: ```python def command_my_trace(args): """Custom trace command that executes when a breakpoint is hit.""" print("Tracing:", args) ``` You can use this command like this: ``` (dlv) break main.go:10 (dlv) on 1 my_trace ``` # Working with variables Variables of the target program can be accessed using `local_vars`, `function_args` or the `eval` functions. Each variable will be returned as a [Variable](https://pkg.go.dev/github.com/go-delve/delve/service/api#Variable) struct, with one special field: `Value`. As a convenience a special global object exists, called `tgt`: evaluating `tgt.varname` is equivalent to evaluating `eval(None, "varname").Variable.Value`. ## Variable.Value The `Value` field will return the value of the target variable converted to a starlark value: * integers, floating point numbers and strings are represented by equivalent starlark values * structs are represented as starlark dictionaries * slices and arrays are represented by starlark lists * maps are represented by starlark dicts * pointers and interfaces are represented by a one-element starlark list containing the value they point to For example, given this variable in the target program: ```go type astruct struct { A int B int } s2 := []astruct{{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}, {15, 16}} ``` The following is possible: ``` >>> s2 = eval(None, "s2").Variable >>> s2.Value[0] # access of a slice item by index main.astruct {A: 1, B: 2} >>> a = s2.Value[1] >>> a.Value.A # access to a struct field 3 >>> a.Value.A + 10 # arithmetic on the value of s2[1].X 13 >>> a.Value["B"] # access to a struct field, using dictionary syntax 4 ``` For more examples see the [linked list example](#Print-all-elements-of-a-linked-list) below. # Examples ## Listing goroutines and making custom commands Create a `goroutine_start_line` command that prints the starting line of each goroutine, sets `gsl` as an alias: ```python def command_goroutine_start_line(args): gs = goroutines().Goroutines for g in gs: line = read_file(g.StartLoc.File).splitlines()[g.StartLoc.Line-1].strip() print(g.ID, "\t", g.StartLoc.File + ":" + str(g.StartLoc.Line), "\t", line) def main(): dlv_command("config alias goroutine_start_line gsl") ``` Use it like this: ``` (dlv) source goroutine_start_line.star (dlv) goroutine_start_line 1 /usr/local/go/src/runtime/proc.go:110 func main() { 2 /usr/local/go/src/runtime/proc.go:242 func forcegchelper() { 17 /usr/local/go/src/runtime/mgcsweep.go:64 func bgsweep(c chan int) { 18 /usr/local/go/src/runtime/mfinal.go:161 func runfinq() { (dlv) gsl 1 /usr/local/go/src/runtime/proc.go:110 func main() { 2 /usr/local/go/src/runtime/proc.go:242 func forcegchelper() { 17 /usr/local/go/src/runtime/mgcsweep.go:64 func bgsweep(c chan int) { 18 /usr/local/go/src/runtime/mfinal.go:161 func runfinq() { ``` ## Expression arguments After evaluating this script: ```python def command_echo(args): print(args) def command_echo_expr(a, b, c): print("a", a, "b", b, "c", c) ``` The first command, `echo`, takes its arguments as a single string, while for `echo_expr` it will be possible to pass starlark expression as arguments: ``` (dlv) echo 2+2, 2-1, 2*3 "2+2, 2-1, 2*3" (dlv) echo_expr 2+2, 2-1, 2*3 a 4 b 1 c 6 ``` ## Creating breakpoints Set a breakpoint on all private methods of package `main`: ```python def main(): for f in functions().Funcs: v = f.split('.') if len(v) != 2: continue if v[0] != "main": continue if v[1][0] >= 'a' and v[1][0] <= 'z': create_breakpoint({ "FunctionName": f, "Line": -1 }) # see documentation of RPCServer.CreateBreakpoint ``` ## Switching goroutines Create a command, `switch_to_main_goroutine`, that searches for a goroutine running a function in the main package and switches to it: ```python def command_switch_to_main_goroutine(args): for g in goroutines().Goroutines: if g.currentLoc.function != None and g.currentLoc.function.name.startswith("main."): print("switching to:", g.id) raw_command("switchGoroutine", GoroutineID=g.id) break ``` ## Listing goroutines Create a command, "goexcl", that lists all goroutines excluding the ones stopped on a specified function. ```python def command_goexcl(args): """Prints all goroutines not stopped in the function passed as argument.""" excluded = 0 start = 0 while start >= 0: gr = goroutines(start, 10) start = gr.Nextg for g in gr.Goroutines: fn = g.UserCurrentLoc.Function if fn == None: print("Goroutine", g.ID, "User:", g.UserCurrentLoc.File, g.UserCurrentLoc.Line) elif fn.Name_ != args: print("Goroutine", g.ID, "User:", g.UserCurrentLoc.File, g.UserCurrentLoc.Line, fn.Name_) else: excluded = excluded + 1 print("Excluded", excluded, "goroutines") ``` Usage: ``` (dlv) goexcl main.somefunc ``` prints all goroutines that are not stopped inside `main.somefunc`. ## Repeatedly executing the target until a breakpoint is hit. Repeatedly call continue and restart until the target hits a breakpoint. ```python def command_flaky(args): "Repeatedly runs program until a breakpoint is hit" while True: if dlv_command("continue") == None: break dlv_command("restart") ``` ## Print all elements of a linked list ```python def command_linked_list(args): """Prints the contents of a linked list. linked_list Prints up to max_depth elements of the linked list variable 'var_name' using 'next_field_name' as the name of the link field. """ var_name, next_field_name, max_depth = args.split(" ") max_depth = int(max_depth) next_name = var_name v = eval(None, var_name).Variable.Value for i in range(0, max_depth): print(str(i)+":",v) if v[0] == None: break v = v[next_field_name] ``` ## Find an array element matching a predicate ```python def command_find_array(arr, pred): """Calls pred for each element of the array or slice 'arr' returns the index of the first element for which pred returns true. find_arr Example use (find the first element of slice 's2' with field A equal to 5): find_arr "s2", lambda x: x.A == 5 """ arrv = eval(None, arr).Variable for i in range(0, arrv.Len): v = arrv.Value[i] if pred(v): print("found", i) return print("not found") ``` ## Rerunning a program until it fails or hits a breakpoint ```python def command_flaky(args): "Continues and restarts the target program repeatedly (re-recording it on the rr backend), until a breakpoint is hit" count = 1 while True: if dlv_command("continue") == None: break print("restarting", count, "...") count = count+1 restart(Rerecord=True) ``` ## Passing a struct as an argument Struct literals can be passed to built-ins as Starlark dictionaries. For example, the following snippet passes in an [api.EvalScope](https://pkg.go.dev/github.com/go-delve/delve/service/api#EvalScope) and [api.LoadConfig](https://pkg.go.dev/github.com/go-delve/delve/service/api#LoadConfig) to the `eval` built-in. `None` can be passed for optional arguments, and trailing optional arguments can be elided completely. ```python var = eval( {"GoroutineID": 42, "Frame": 5}, "myVar", {"FollowPointers":True, "MaxVariableRecurse":2, "MaxStringLen":100, "MaxArrayValues":10, "MaxStructFields":100} ) ``` ## Chain breakpoints Chain a number of breakpoints such that breakpoint n+1 is only hit after breakpoint n is hit: ```python def command_breakchain(*args): v = args.split(" ") bp = get_breakpoint(int(v[0]), "").Breakpoint bp.HitCond = "== 1" amend_breakpoint(bp) for i in range(1, len(v)): bp = get_breakpoint(int(v[i]), "").Breakpoint if i != len(v)-1: bp.HitCond = "== 1" bp.Cond = "delve.bphitcount[" + v[i-1] + "] > 0" amend_breakpoint(bp) ``` To be used as `chain 1 2 3` where `1`, `2`, and `3` are IDs of breakpoints to chain together. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/cli/substitutepath.md ## Path substitution configuration Normally Delve finds the path to the source code that was used to produce an executable by looking at the debug symbols of the executable. However, under [some circumstances](../faq.md#substpath), the paths that end up inside the executable will be different from the paths to the source code on the machine that is running the debugger. If that is the case Delve will need extra configuration to convert the paths stored inside the executable to paths in your local filesystem. This configuration is done by specifying a list of path substitution rules. The path substitution code is SubstitutePath in pkg/locspec/locations.go. ### Where are path substitution rules specified #### Delve command line client The command line client reads the path substitution rules from Delve's YAML configuration file located at `$XDG_CONFIG_HOME/dlv/config.yml` or `.dlv/config.yml` inside the home directory on Windows. The `substitute-path` entry should look like this: ``` substitute-path: - {from: "/compiler/machine/directory", to: "/debugger/machine/directory"} - {from: "", to: "/mapping/for/relative/paths"} ``` If you are starting a headless instance of Delve and connecting to it through `dlv connect` the configuration file that is used is the one that runs `dlv connect`. When Delve needs to convert a path P found inside the executable file into a path in the local filesystem it will scan through the list of rules looking for the first one where P starts with the from-path and replace from-path with to-path. Empty paths in both from-path and to-path are special, they represent relative paths: - `(from="" to="/home/user/project/src")` converts all relative paths in the executable to absolute paths in `/home/user/project/src` - `(from="/build/dir" to="")` converts all paths in the executable that start with `/build/dir` into relative paths. The rules can also be modified while Delve is running by using the [config substitute-path command](./README.md#config): ``` (dlv) config substitute-path /from/path /to/path ``` Double quotes can be used to specify paths that contain spaces, or to specify empty paths: ``` (dlv) config substitute-path "/path containing spaces/" /path-without-spaces/ (dlv) config substitute-path /make/this/path/relative "" ``` #### DAP server If you connect to Delve using the DAP protocol then the substitute path rules are specified using the substitutePath option in [launch.json](https://github.com/golang/vscode-go/blob/master/docs/debugging.md#launchjson-attributes). **Note that `from` and `to` have reversed meaning here.** ``` "substitutePath": [ { "from": "/debugger/machine/directory", "to": "/compiler/machine/directory" } ] ``` When Delve needs to convert a path P found in the local filesystem into a path inside the executable file it will scan through the list of rules looking for the first one where P starts with from-path and replace from-path with to-path. Empty paths in both from-path and to-path are special, they represent relative paths: - `(from="/home/user/project/src" to="")` converts all relative paths in the executable to absolute paths in `/home/user/project/src` - `(from="" to="/build/dir")` converts all paths in the executable that start with `/build/dir` into relative paths. The [debug console](https://github.com/golang/vscode-go/blob/master/docs/debugging.md#dlv-command-from-debug-console) can also be used to modify the path substitution list: ``` dlv config substitutePath /debugger/machine/directory /compiler/machine/directory ``` --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/faq.md ## Frequently Asked Questions * [I'm getting an error while compiling Delve / unsupported architectures and OSs](#unsupportedplatforms) * [How do I use Delve with Docker?](#docker) * [How can I use Delve to debug a CLI application?](#ttydebug) * [How can I use Delve for remote debugging?](#remote) * [Can not set breakpoints or see source listing in a complicated debugging environment](#substpath) * [Using Delve to debug the Go runtime](#runtime) ### I'm getting an error while compiling Delve / unsupported architectures and OSs The most likely cause of this is that you are running an unsupported Operating System or architecture. Currently Delve supports (GOOS / GOARCH): * linux / amd64 (86x64) * linux / arm64 (AARCH64) * linux / 386 * windows / amd64 * windows / arm64 * darwin (macOS) / amd64 There is no planned ETA for support of other architectures or operating systems. Bugs tracking requested support are: - [32bit ARM support](https://github.com/go-delve/delve/issues/328) - [PowerPC support](https://github.com/go-delve/delve/issues/1564) - [OpenBSD](https://github.com/go-delve/delve/issues/1477) See also: [backend test health](backend_test_health.md). ### How do I use Delve with Docker? When running the container you should pass the `--security-opt=seccomp:unconfined` option to Docker. You can start a headless instance of Delve inside the container like this: ``` dlv exec --headless --listen :4040 /path/to/executable ``` And then connect to it from outside the container: ``` dlv connect :4040 ``` The program will not start executing until you connect to Delve and send the `continue` command. If you want the program to start immediately you can do that by passing the `--continue` and `--accept-multiclient` options to Delve: ``` dlv exec --headless --continue --listen :4040 --accept-multiclient /path/to/executable ``` Note that the connection to Delve is unauthenticated and will allow arbitrary remote code execution: *do not do this in production*. ### How can I use Delve to debug a CLI application? There are three good ways to go about this 1. Run your CLI application in a separate terminal and then attach to it via `dlv attach`. 1. Run Delve in headless mode via `dlv debug --headless` and then connect to it from another terminal. This will place the process in the foreground and allow it to access the terminal TTY. 1. Assign the process its own TTY. This can be done on UNIX systems via the `--tty` flag for the `dlv debug` and `dlv exec` commands. For the best experience, you should create your own PTY and assign it as the TTY. This can be done via [ptyme](https://github.com/derekparker/ptyme). ### How can I use Delve for remote debugging? It is best not to use remote debugging on a public network. If you have to do this, we recommend using ssh tunnels or a vpn connection. ##### ```Example ``` Remote server: ``` dlv exec --headless --listen localhost:4040 /path/to/executable ``` Local client: 1. connect to the server and start a local port forward ``` ssh -NL 4040:localhost:4040 user@remote.ip ``` 2. connect local port ``` dlv connect :4040 ``` ### Can not set breakpoints or see source listing in a complicated debugging environment This problem manifests when one or more of these things happen: * Can not see source code when the program stops at a breakpoint * Setting a breakpoint using full path, or through an IDE, does not work While doing one of the following things: * **The program is built and run inside a container** and Delve (or an IDE) is remotely connecting to it * Generally, every time the build environment (VM, container, computer...) differs from the environment where Delve's front-end (dlv or a IDE) runs * Using `-trimpath` or `-gcflags=-trimpath` * Using a build system other than `go build` (eg. bazel) * Using symlinks in your source tree If you are affected by this problem then the `list main.main` command (in the command line interface) will have this result: ``` (dlv) list main.main Showing /path/to/the/mainfile.go:42 (PC: 0x47dfca) Command failed: open /path/to/the/mainfile.go: no such file or directory (dlv) ``` This is not a bug. The Go compiler embeds the paths of source files into the executable so that debuggers, including Delve, can use them. Doing any of the things listed above will prevent this feature from working seamlessly. The substitute-path feature can be used to solve this problem, see `help config` or the `substitutePath` option in launch.json. The `sources` command could also be useful in troubleshooting this problem, it shows the list of file paths that has been embedded by the compiler into the executable. For more information on path substitution see [path substitution](cli/substitutepath.md). If you still think this is a bug in Delve and not a configuration problem, open an [issue](https://github.com/go-delve/delve/issues), filling the issue template and including the logs produced by delve with the options `--log --log-output=rpc,dap`. ### Using Delve to debug the Go runtime It's possible to use Delve to debug the Go runtime, however there are some caveats to keep in mind * The `runtime` package is always compiled with optimizations and inlining, all of the caveats that apply to debugging optimized binaries apply to the runtime package. In particular some variables could be unavailable or have stale values and it could expose some bugs with the compiler assigning line numbers to instructions. * Next, step and stepout try to follow the current goroutine, if you debug one of the functions in the runtime that modify the curg pointer they will get confused. The 'step-instruction' command should be used instead. * When executing a stacktrace from g0 Delve will return the top frame and then immediately switch to the goroutine stack. If you want to see the g0 stacktrace use `stack -mode simple`. * The step command only steps into private runtime functions if it is already inside a runtime function. To step inside a private runtime function inserted into user code by the compiler set a breakpoint and then use `runtime.curg.goid == ` as condition. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/installation/freebsd/install.md See [general install instructions](../README.md). --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/installation/linux/install.md See [general install instructions](../README.md). --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/installation/osx/install.md ## Homebrew You can install Delve via HomeBrew with the following command: ```shell $ brew install delve ``` ## Other installation methods See [general install instructions](../README.md). --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/installation/windows/install.md See [general install instructions](../README.md). --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/internal/portnotes.md # Notes on porting Delve to other architectures ## Continuous Integration requirements Code that isn't tested doesn't work, we like to run CI on all supported platforms. Currently our CI is done on an [instance of TeamCity cloud provided by JetBrains](https://delve.teamcity.com/), with the exception of the FreeBSD port, which is tested by Cirrus-CI. TeamCity settings are in `.teamcity/settings.kts` which in turn runs one of `_scripts/test_linux.sh`, `_scripts/test_mac.sh` or `_scripts/test_windows.ps1`. All test scripts eventually end up calling into our main test program `_scripts/make.go`, which makes the appropriate `go test` calls. If you plan to port Delve to a new platform you should first figure out how we are going to add your port to our CI, there are three possible solutions: 1. the platform can be run on existing agents we have on TeamCity (linux/amd64, linux/arm64, windows/amd64, darwin/amd64, darwin/arm64) through Docker or similar solutions. 2. there is a free CI service that integrates with GitHub that we can use 3. you provide the hardware to be added to TeamCity to test it Exception to this requirement can be discussed in special cases. ## General code organization An introduction to the architecture of Delve can be found in the 2018 Gophercon Iceland talk: [slides](https://speakerdeck.com/aarzilli/internal-architecture-of-delve), [video](https://www.youtube.com/watch?v=IKnTr7Zms1k). ### Packages you shouldn't worry about * `cmd/dlv/...` implements the command line program * `pkg/terminal/...` implements the command line user interface * `service/...` with the exception of `service/test`, implements our API as well as DAP * `pkg/dwarf/...` with the exception of `pkg/dwarf/regnum`, implements DWARF features not covered by the standard library * anything else in `pkg` that isn't inside `pkg/proc` ### pkg/proc `pkg/proc` is the symbolic layer of Delve, its job is to bridge the distance between the API and low level Operating System and CPU features. Almost all features of Delve are implemented here, **except for the interaction with the OS/CPU**, which is provided by one of three backends: `pkg/proc/native`, `pkg/proc/core` or `pkg/proc/gdbserial`. This package also contains the main test suite for Delve's backends in `pkg/proc/proc_test.go`. The tests for reading variables, however, are inside `service/test` for historical reasons. When porting Delve to a new CPU a new instance of the `proc.Arch` structure should be filled, see `pkg/proc/arch.go` and `pkg/proc/amd64_arch.go` as an example. To do this you will have to: - provide a disassembler for the port architecture - provide a mapping between DWARF register numbers and hardware registers in `pkg/dwarf/regnum` (see `pkg/dwarf/regnum/amd64.go` as an example). This mapping *is not arbitrary* it needs to be described in some standard document which should be linked to in the documentation of `pkg/dwarf/regnum`, for example the mapping for amd64 is described by the System V ABI AMD64 Architecture Processor Supplement v. 1.0 on page 61 figure 3.36. - if you don't know what `proc.Arch.fixFrameUnwindContext` or `porc.Arch.switchStack` should do *leave them empty* - the `proc.Arch.prologues` field needs to be filled by looking at the relevant parts of the Go linker (`cmd/link`), the code is somewhere inside `$GOROOT/src/cmd/internal/obj`, usually the function is called `stacksplit`. If your target OS uses an executable file format other than ELF, Mach-O or PE you will also have to change `pkg/proc/bininfo.go` . **See also** the note on [build tags](#buildtags). ### pkg/proc/gdbserial This implements GDB remote serial protocol, it is used as the main backend on macOS as well as connecting to [rr](https://rr-project.org/). Unless you are making a macOS port you shouldn't worry about this. ### pkg/proc/core This implements code for reading core files. You don't need to support this for the port platform, see the note on [skippable features](#skippable). If you decide to do it anyway see the note on [build tags](#buildtags). ### pkg/proc/native This is the interface between Delve and the OS/CPU, you will definitely want to work on this and it will be the bulk of the port job. The tests for this code however are not in this directory, they are in `pkg/proc` and `service/test`. ## General port process 1. Edit `pkg/proc/native/support_sentinel.go` to disable it in the port platform 2. Fill `proc.Arch` struct for target architecture if it isn't supported already 3. Go in `pkg/proc` * run `go test -v` * fix compiler errors * repeat until compilation succeeds * fix test failures * repeat until almost all tests pass (see note on [skippable tests and features](#skippable)) 5. Go in `service/test` * run `go test -v` * fix compiler errors * repeat until compilation succeeds * fix test failures * repeat until almost all tests pass (see note on [skippable tests and features](#skippable)) 6. Go to the root directory of the project * run `go run _scripts/make.go test` * fix compiler errors * repeat until compilation succeeds * fix test failures * repeat until almost all tests pass (see note on [skippable tests and features](#skippable)) ## Miscellaneous ### Uses of build tags, runtime.GOOS and runtime.GOARCH Delve has the ability to read cross-platform core files: you can read a core file of any supported platform with Delve running on any other supported platform. For example, a core file produced by linux/arm64 can be read using Delve running under windows/amd64. This feature has far reaching consequences, for example the stack unwinding code in `pkg/proc/stack.go` could be asked to unwind a stack for an architecture different from the one its running under. What this means in practice is that, in general, using build tags (like `_amd64.go`) or checking `runtime.GOOS` and `runtime.GOARCH` is forbidden throughout Delve's source tree, with two important exceptions: * `pkg/proc/native` is allowed to check runtime.GOOS/runtime.GOARCH as well as using build tags * test files are allowed to check runtime.GOOS/runtime.GOARCH as well as using build tags Other exceptions can be considered, but in general code outside of `pkg/proc/native` should: * use `proc.BinaryInfo.GOOS` instead of `runtime.GOOS` * use `proc.BinaryInfo.Arch.Name` instead of `runtime.GOARCH` * use `proc.BinaryInfo.Arch.PtrSize()` instead of determining the pointer size with `unsafe.Sizeof` * use `uint64` wherever an address-sized integer is needed, instead of `uintptr` * use `amd64_filename.go` instead of the build tag version, `filename_amd64.go` ### Features and tests that can be skipped by a port Delve offers many features, however not all of them are necessary for a useful port of Delve. The following features are optional to implement for a port: - Reading core files (i.e. `pkg/proc/core`) - Writing core files (i.e. `pkg/proc/native/dump_*.go`) - Watchpoints (`(*nativeThread).writeHardwareBreakpoint` etc) - Supporting CGO calls (`proc.Arch.switchStack`) - eBPF (`pkg/proc/internal/ebpf`) - Working with Position Independent Executables (PIE), unless the default buildmode for the port platform is PIE - Function call injection (`pkg/proc/fncall.go` -- it is probably not supported on the port architecture anyway) For all these features it is acceptable (and possibly advisable) to either leave the implementation empty or to write a stub that always returns an "not implemented" error. Tests relative to these features can be skipped, `proc_test.go` has a `skipOn` utility function that can be called to skip a specific test on some architectures. Other tests should pass reliably, it is acceptable to skip some of them as long as most of them will pass. The following tests should not be skipped even if you will be tempted to: * `proc.TestNextConcurrent` * `proc.TestNextConcurrentVariant2` * `proc.TestBreakpointCounts` (enable `proc.TestBreakpointCountsWithDetection` if you have problems with this) * `proc.TestStepConcurrentDirect` * `proc.TestStepConcurrentPtr` ### Porting to Big Endian architectures Delve was initially written for amd64 and assumed 64bit and little endianness everywhere. The assumption on pointer size has been removed throughout the codebase, the assumption about endianness hasn't. Both `pkg/dwarf/loclist` and `pkg/dwarf/frame` incorrectly assume little endian encoding. Other parts of the code might do the same. ### Porting to ARM32, MIPS and Software Single Stepping When resuming a thread stopped at a breakpoint Delve will: 1. remove the breakpoint temporarily 2. make the thread execute a single instruction 3. write the breakpoint back Step 2 is implemented using the hardware single step feature that many CPUs have and that is exposed via PTRACE_SINGLESTEP or similar features. ARM32 and MIPS do not have a hardware single step implemented, this means that it has to be implemented in software. The linux kernel used to have a software implementation of PTRACE_SINGLESTEP but those have been removed because they were too burdensome to maintain and delegated the feature to userspace debuggers entirely. A software singlestep implementation would work like this: 1. decode the current instruction 2. figure out all the possible places where the PC registers could be after executing the current instruction 3. set a breakpoint on all of them 4. resume the thread normally 5. clear all breakpoints created on step 3 Delve does not currently have any infrastructure to help implement this, which means that porting to architectures without hardware singlestep is even more complicated. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv.md ## dlv Delve is a debugger for the Go programming language. ### Synopsis Delve is a source level debugger for Go programs. Delve enables you to interact with your program by controlling the execution of the process, evaluating variables, and providing information of thread / goroutine state, CPU register state and more. The goal of this tool is to provide a simple yet powerful interface for debugging Go programs. Pass flags to the program you are debugging using `--`, for example: `dlv exec ./hello -- server --config conf/config.toml` ### Options ``` -h, --help help for dlv ``` ### SEE ALSO * [dlv attach](dlv_attach.md) - Attach to running process and begin debugging. * [dlv connect](dlv_connect.md) - Connect to a headless debug server with a terminal client. * [dlv core](dlv_core.md) - Examine a core dump. * [dlv dap](dlv_dap.md) - Starts a headless TCP server communicating via Debug Adaptor Protocol (DAP). * [dlv debug](dlv_debug.md) - Compile and begin debugging main package in current directory, or the package specified. * [dlv exec](dlv_exec.md) - Execute a precompiled binary, and begin a debug session. * [dlv replay](dlv_replay.md) - Replays a rr trace. * [dlv test](dlv_test.md) - Compile test binary and begin debugging program. * [dlv trace](dlv_trace.md) - Compile and begin tracing program. * [dlv version](dlv_version.md) - Prints version. * [dlv log](dlv_log.md) - Help about logging flags * [dlv backend](dlv_backend.md) - Help about the `--backend` flag --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_attach.md ## dlv attach Attach to running process and begin debugging. ### Synopsis Attach to an already running process and begin debugging it. This command will cause Delve to take control of an already running process, and begin a new debug session. When exiting the debug session you will have the option to let the process continue or kill it. ``` dlv attach pid [executable] [flags] ``` ### Options ``` --continue Continue the debugged process on start. -h, --help help for attach --waitfor string Wait for a process with a name beginning with this prefix --waitfor-duration float Total time to wait for a process --waitfor-interval float Interval between checks of the process list, in millisecond (default 1) ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_backend.md ## dlv backend Help about the --backend flag. ### Synopsis The --backend flag specifies which backend should be used, possible values are: default Uses lldb on macOS, native everywhere else. native Native backend. lldb Uses lldb-server or debugserver. rr Uses mozilla rr (https://github.com/mozilla/rr). Some backends can be configured using environment variables: * DELVE_DEBUGSERVER_PATH specifies the path of the debugserver executable for the lldb backend * DELVE_RR_RECORD_FLAGS specifies additional flags used when calling 'rr record' * DELVE_RR_REPLAY_FLAGS specifies additional flags used when calling 'rr replay' ### Options ``` -h, --help help for backend ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_connect.md ## dlv connect Connect to a headless debug server with a terminal client. ### Synopsis Connect to a running headless debug server with a terminal client. Prefix with 'unix:' to use a unix domain socket. ``` dlv connect addr [flags] ``` ### Options ``` -h, --help help for connect ``` ### Options inherited from parent commands ``` --backend string Backend selection (see 'dlv help backend'). (default "default") --init string Init file, executed by the terminal client. --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_core.md ## dlv core Examine a core dump. ### Synopsis Examine a core dump (only supports linux and windows core dumps). The core command will open the specified core file and the associated executable and let you examine the state of the process when the core dump was taken. Currently supports linux/amd64 and linux/arm64 core files, windows/amd64 minidumps and core files generated by Delve's 'dump' command. ``` dlv core [flags] ``` ### Options ``` -h, --help help for core ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_dap.md ## dlv dap Starts a headless TCP server communicating via Debug Adaptor Protocol (DAP). ### Synopsis Starts a headless TCP server communicating via Debug Adaptor Protocol (DAP). The server is always headless and requires a DAP client like VS Code to connect and request a binary to be launched or a process to be attached to. The following modes can be specified via the client's launch config: - launch + exec (executes precompiled binary, like 'dlv exec') - launch + debug (builds and launches, like 'dlv debug') - launch + test (builds and tests, like 'dlv test') - launch + replay (replays an rr trace, like 'dlv replay') - launch + core (replays a core dump file, like 'dlv core') - attach + local (attaches to a running process, like 'dlv attach') Program and output binary paths will be interpreted relative to dlv's working directory. This server does not accept multiple client connections (--accept-multiclient). Use 'dlv [command] --headless' instead and a DAP client with attach + remote config. While --continue is not supported, stopOnEntry launch/attach attribute can be used to control if execution is resumed at the start of the debug session. The --client-addr flag is a special flag that makes the server initiate a debug session by dialing in to the host:port where a DAP client is waiting. This server process will exit when the debug session ends. ``` dlv dap [flags] ``` ### Options ``` --client-addr string Address where the DAP client is waiting for the DAP server to dial in. Prefix with 'unix:' to use a unix domain socket. -h, --help help for dap ``` ### Options inherited from parent commands ``` --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_debug.md ## dlv debug Compile and begin debugging main package in current directory, or the package specified. ### Synopsis Compiles your program with optimizations disabled, starts and attaches to it. By default, with no arguments, Delve will compile the 'main' package in the current directory, and begin to debug it. Alternatively you can specify a package name and Delve will compile that package instead, and begin a new debug session. ``` dlv debug [package] [flags] ``` ### Options ``` --continue Continue the debugged process on start. -h, --help help for debug --output string Output path for the binary. --rr-cleanup Delete directory containing debug recording on detach. (default true) --tty string TTY to use for the target program ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_exec.md ## dlv exec Execute a precompiled binary, and begin a debug session. ### Synopsis Execute a precompiled binary and begin a debug session. This command will cause Delve to exec the binary and immediately attach to it to begin a new debug session. Please note that if the binary was not compiled with optimizations disabled, it may be difficult to properly debug it. Please consider compiling debugging binaries with -gcflags="all=-N -l" on Go 1.10 or later, -gcflags="-N -l" on earlier versions of Go. ``` dlv exec [flags] ``` ### Options ``` --continue Continue the debugged process on start. -h, --help help for exec --rr-cleanup Delete directory containing debug recording on detach. (default true) --tty string TTY to use for the target program ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_log.md ## dlv log Help about logging flags. ### Synopsis Logging can be enabled by specifying the --log flag and using the --log-output flag to select which components should produce logs. The argument of --log-output must be a comma separated list of component names selected from this list: debugger Log debugger commands gdbwire Log connection to gdbserial backend lldbout Copy output from debugserver/lldb to standard output debuglineerr Log recoverable errors reading .debug_line rpc Log all RPC messages dap Log all DAP messages fncall Log function call protocol minidump Log minidump loading stack Log stacktracer Additionally --log-dest can be used to specify where the logs should be written. If the argument is a number it will be interpreted as a file descriptor, otherwise as a file path. This option will also redirect the "server listening at" message in headless and dap modes. ### Options ``` -h, --help help for log ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_redirect.md ## dlv redirect Help about file redirection. ### Synopsis The standard file descriptors of the target process can be controlled using the '-r' and '--tty' arguments. The --tty argument allows redirecting all standard descriptors to a terminal, specified as an argument to --tty. The syntax for '-r' argument is: -r [source:]destination Where source is one of 'stdin', 'stdout' or 'stderr' and destination is the path to a file. If the source is omitted stdin is used implicitly. File redirects can also be changed using the 'restart' command. ### Options ``` -h, --help help for redirect ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_replay.md ## dlv replay Replays a rr trace. ### Synopsis Replays a rr trace. The replay command will open a trace generated by mozilla rr. Mozilla rr must be installed: https://github.com/mozilla/rr ``` dlv replay [trace directory] [flags] ``` ### Options ``` -h, --help help for replay -p, --onprocess int Pass onprocess pid to rr. ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_run.md ## dlv run Deprecated command. Use 'debug' instead. ``` dlv run [flags] ``` ### Options ``` -h, --help help for run ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. New clients should use v2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 1) --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_test.md ## dlv test Compile test binary and begin debugging program. ### Synopsis Compiles a test binary with optimizations disabled and begins a new debug session. The test command allows you to begin a new debug session in the context of your unit tests. By default Delve will debug the tests in the current directory. Alternatively you can specify a package name, and Delve will debug the tests in that package instead. Double-dashes `--` can be used to pass arguments to the test program: dlv test [package] -- -test.run TestSomething -test.v -other-argument See also: 'go help testflag'. ``` dlv test [package] [flags] ``` ### Options ``` -h, --help help for test --output string Output path for the binary. ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_trace.md ## dlv trace Compile and begin tracing program. ### Synopsis Trace program execution. The trace sub command will set a tracepoint on every function matching the provided regular expression and output information when tracepoint is hit. This is useful if you do not want to begin an entire debug session, but merely want to know what functions your process is executing. The output of the trace sub command is printed to stderr, so if you would like to only see the output of the trace operations you can redirect stdout. ``` dlv trace [package] regexp [flags] ``` ### Options ``` --ebpf Trace using eBPF (experimental). -e, --exec string Binary file to exec and trace. --follow-calls int Trace all children of the function to the required depth. Trace also supports defer functions and cases where functions are dynamically returned and passed as parameters. -h, --help help for trace --output string Output path for the binary. -p, --pid int Pid to attach to. -s, --stack int Show stack trace with given depth. (Ignored with --ebpf) -t, --test Trace a test binary. --timestamp Show timestamp in the output ``` ### Options inherited from parent commands ``` --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language. --- # Source: https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_version.md ## dlv version Prints version. ``` dlv version [flags] ``` ### Options ``` -h, --help help for version ``` ### Options inherited from parent commands ``` --accept-multiclient Allows a headless server to accept multiple client connections via JSON-RPC or DAP. --allow-non-terminal-interactive Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr --api-version int Selects JSON-RPC API version when headless. The only valid value is 2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 2) --backend string Backend selection (see 'dlv help backend'). (default "default") --build-flags string Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v" --check-go-version Exits if the version of Go in use is not compatible (too old or too new) with the version of Delve. (default true) --disable-aslr Disables address space randomization --headless Run debug server only, in headless mode. Server will accept both JSON-RPC or DAP client connections. --init string Init file, executed by the terminal client. -l, --listen string Debugging server listen address. Prefix with 'unix:' to use a unix domain socket. (default "127.0.0.1:0") --log Enable debugging server logging. --log-dest string Writes logs to the specified file or file descriptor (see 'dlv help log'). --log-output string Comma separated list of components that should produce debug output (see 'dlv help log') --only-same-user Only connections from the same user that started this instance of Delve are allowed to connect. (default true) -r, --redirect stringArray Specifies redirect rules for target process (see 'dlv help redirect') --wd string Working directory for running the program. ``` ### SEE ALSO * [dlv](dlv.md) - Delve is a debugger for the Go programming language.