whatcanGOwrong

This commit is contained in:
2024-09-19 21:38:24 -04:00
commit d0ae4d841d
17908 changed files with 4096831 additions and 0 deletions
@@ -0,0 +1,803 @@
# Configuration and Command History
If `$XDG_CONFIG_HOME` is set, then configuration and command history files are located in `$XDG_CONFIG_HOME/dlv`. Otherwise, they are located in `$HOME/.config/dlv` on Linux and `$HOME/.dlv` on other systems.
The configuration file `config.yml` contains all the configurable options and their default values. The command history is stored in `.dbg_history`.
# Commands
## Running the program
Command | Description
--------|------------
[call](#call) | Resumes process, injecting a function call (EXPERIMENTAL!!!)
[continue](#continue) | Run until breakpoint or program termination.
[next](#next) | Step over to next source line.
[next-instruction](#next-instruction) | Single step a single cpu instruction, skipping function calls.
[rebuild](#rebuild) | Rebuild the target executable and restarts it. It does not work if the executable was not built by delve.
[restart](#restart) | Restart process.
[rev](#rev) | Reverses the execution of the target program for the command specified.
[rewind](#rewind) | Run backwards until breakpoint or start of recorded history.
[step](#step) | Single step through program.
[step-instruction](#step-instruction) | Single step a single cpu instruction.
[stepout](#stepout) | Step out of the current function.
## Manipulating breakpoints
Command | Description
--------|------------
[break](#break) | Sets a breakpoint.
[breakpoints](#breakpoints) | Print out info for active breakpoints.
[clear](#clear) | Deletes breakpoint.
[clearall](#clearall) | Deletes multiple breakpoints.
[condition](#condition) | Set breakpoint condition.
[on](#on) | Executes a command when a breakpoint is hit.
[toggle](#toggle) | Toggles on or off a breakpoint.
[trace](#trace) | Set tracepoint.
[watch](#watch) | Set watchpoint.
## Viewing program variables and memory
Command | Description
--------|------------
[args](#args) | Print function arguments.
[display](#display) | Print value of an expression every time the program stops.
[examinemem](#examinemem) | Examine raw memory at the given address.
[locals](#locals) | Print local variables.
[print](#print) | Evaluate an expression.
[regs](#regs) | Print contents of CPU registers.
[set](#set) | Changes the value of a variable.
[vars](#vars) | Print package variables.
[whatis](#whatis) | Prints type of an expression.
## Listing and switching between threads and goroutines
Command | Description
--------|------------
[goroutine](#goroutine) | Shows or changes current goroutine
[goroutines](#goroutines) | List program goroutines.
[thread](#thread) | Switch to the specified thread.
[threads](#threads) | Print out info for every traced thread.
## Viewing the call stack and selecting frames
Command | Description
--------|------------
[deferred](#deferred) | Executes command in the context of a deferred call.
[down](#down) | Move the current frame down.
[frame](#frame) | Set the current frame, or execute command on a different frame.
[stack](#stack) | Print stack trace.
[up](#up) | Move the current frame up.
## Other commands
Command | Description
--------|------------
[check](#check) | Creates a checkpoint at the current position.
[checkpoints](#checkpoints) | Print out info for existing checkpoints.
[clear-checkpoint](#clear-checkpoint) | Deletes checkpoint.
[config](#config) | Changes configuration parameters.
[disassemble](#disassemble) | Disassembler.
[dump](#dump) | Creates a core dump from the current process state
[edit](#edit) | Open where you are in $DELVE_EDITOR or $EDITOR
[exit](#exit) | Exit the debugger.
[funcs](#funcs) | Print list of functions.
[help](#help) | Prints the help message.
[libraries](#libraries) | List loaded dynamic libraries
[list](#list) | Show source code.
[packages](#packages) | Print list of packages.
[source](#source) | Executes a file containing a list of delve commands
[sources](#sources) | Print list of source files.
[target](#target) | Manages child process debugging.
[transcript](#transcript) | Appends command output to a file.
[types](#types) | Print list of types
## args
Print function arguments.
[goroutine <n>] [frame <m>] args [-v] [<regex>]
If regex is specified only function arguments with a name matching it will be returned. If -v is specified more information about each function argument will be shown.
## break
Sets a breakpoint.
break [name] [locspec] [if <condition>]
Locspec is a location specifier in the form of:
* *<address> Specifies the location of memory address address. address can be specified as a decimal, hexadecimal or octal number
* <filename>:<line> Specifies the 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.
* <line> Specifies the line in the current file
* +<offset> Specifies the line offset lines after the current one
* -<offset> Specifies the line offset lines before the current one
* <function>[:<line>] Specifies the line inside function.
The full syntax for function is <package>.(*<receiver type>).<function name> 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 <filename>:<line> syntax should be used to break in the correct init function at the correct location.
* /<regex>/ Specifies the location of all the functions matching regex
If locspec is omitted a breakpoint will be set on the current line.
If you would like to assign a name to the breakpoint you can do so with the form:
break mybpname main.go:4
Finally, you can assign a condition to the newly created breakpoint by using the 'if' postfix form, like so:
break main.go:55 if i == 5
Alternatively you can set a condition on a breakpoint after created by using the 'on' command.
See also: "help on", "help cond" and "help clear"
Aliases: b
## breakpoints
Print out info for active breakpoints.
breakpoints [-a]
Specifying -a prints all physical breakpoint, including internal breakpoints.
Aliases: bp
## call
Resumes process, injecting a function call (EXPERIMENTAL!!!)
call [-unsafe] <function call expression>
Current limitations:
- only pointers to stack-allocated objects can be passed as argument.
- only some automatic type conversions are supported.
- functions can only be called on running goroutines that are not
executing the runtime.
- the current goroutine needs to have at least 256 bytes of free space on
the stack.
- functions can only be called when the goroutine is stopped at a safe
point.
- calling a function will resume execution of all goroutines.
- only supported on linux's native backend.
## check
Creates a checkpoint at the current position.
checkpoint [note]
The "note" is arbitrary text that can be used to identify the checkpoint, if it is not specified it defaults to the current filename:line position.
Aliases: checkpoint
## checkpoints
Print out info for existing checkpoints.
## clear
Deletes breakpoint.
clear <breakpoint name or id>
## clear-checkpoint
Deletes checkpoint.
clear-checkpoint <id>
Aliases: clearcheck
## clearall
Deletes multiple breakpoints.
clearall [<locspec>]
If called with the locspec argument it will delete all the breakpoints matching the locspec. If locspec is omitted all breakpoints are deleted.
## condition
Set breakpoint condition.
condition <breakpoint name or id> <boolean expression>.
condition -hitcount <breakpoint name or id> <operator> <argument>.
condition -per-g-hitcount <breakpoint name or id> <operator> <argument>.
condition -clear <breakpoint name or id>.
Specifies that the breakpoint, tracepoint or watchpoint should break only if the boolean expression is true.
See [Documentation/cli/expr.md](//github.com/go-delve/delve/tree/master/Documentation/cli/expr.md) for a description of supported expressions.
With the -hitcount option a condition on the breakpoint hit count can be set, the following operators are supported
condition -hitcount bp > n
condition -hitcount bp >= n
condition -hitcount bp < n
condition -hitcount bp <= n
condition -hitcount bp == n
condition -hitcount bp != n
condition -hitcount bp % n
The -per-g-hitcount option works like -hitcount, but use per goroutine hitcount to compare with n.
With the -clear option a condition on the breakpoint can removed.
The '% n' form means we should stop at the breakpoint when the hitcount is a multiple of n.
Examples:
cond 2 i == 10 breakpoint 2 will stop when variable i equals 10
cond name runtime.curg.goid == 5 breakpoint 'name' will stop only on goroutine 5
cond -clear 2 the condition on breakpoint 2 will be removed
Aliases: cond
## config
Changes configuration parameters.
config -list
Show all configuration parameters.
config -save
Saves the configuration file to disk, overwriting the current configuration file.
config <parameter> <value>
Changes the value of a configuration parameter.
config substitute-path <from> <to>
config substitute-path <from>
config substitute-path -clear
Adds or removes a path substitution rule, if -clear is used all
substitute-path rules are removed. Without arguments shows the current list
of substitute-path rules.
See also [Documentation/cli/substitutepath.md](//github.com/go-delve/delve/tree/master/Documentation/cli/substitutepath.md) for how the rules are applied.
config alias <command> <alias>
config alias <alias>
Defines <alias> as an alias to <command> or removes an alias.
config debug-info-directories -add <path>
config debug-info-directories -rm <path>
config debug-info-directories -clear
Adds, removes or clears debug-info-directories.
## continue
Run until breakpoint or program termination.
continue [<locspec>]
Optional locspec argument allows you to continue until a specific location is reached. The program will halt if a breakpoint is hit before reaching the specified location.
For example:
continue main.main
continue encoding/json.Marshal
Aliases: c
## deferred
Executes command in the context of a deferred call.
deferred <n> <command>
Executes the specified command (print, args, locals) in the context of the n-th deferred call in the current frame.
## disassemble
Disassembler.
[goroutine <n>] [frame <m>] disassemble [-a <start> <end>] [-l <locspec>]
If no argument is specified the function being executed in the selected stack frame will be executed.
-a <start> <end> disassembles the specified address range
-l <locspec> disassembles the specified function
Aliases: disass
## display
Print value of an expression every time the program stops.
display -a [%format] <expression>
display -d <number>
The '-a' option adds an expression to the list of expression printed every time the program stops. The '-d' option removes the specified expression from the list.
If display is called without arguments it will print the value of all expression in the list.
## down
Move the current frame down.
down [<m>]
down [<m>] <command>
Move the current frame down by <m>. The second form runs the command on the given frame.
## dump
Creates a core dump from the current process state
dump <output file>
The core dump is always written in ELF, even on systems (windows, macOS) where this is not customary. For environments other than linux/amd64 threads and registers are dumped in a format that only Delve can read back.
## edit
Open where you are in $DELVE_EDITOR or $EDITOR
edit [locspec]
If locspec is omitted edit will open the current source file in the editor, otherwise it will open the specified location.
Aliases: ed
## examinemem
Examine raw memory at the given address.
Examine memory:
examinemem [-fmt <format>] [-count|-len <count>] [-size <size>] <address>
examinemem [-fmt <format>] [-count|-len <count>] [-size <size>] -x <expression>
Format represents the data format and the value is one of this list (default hex): bin(binary), oct(octal), dec(decimal), hex(hexadecimal).
Length is the number of bytes (default 1) and must be less than or equal to 1000.
Address is the memory location of the target to examine. Please note '-len' is deprecated by '-count and -size'.
Expression can be an integer expression or pointer value of the memory location to examine.
For example:
x -fmt hex -count 20 -size 1 0xc00008af38
x -fmt hex -count 20 -size 1 -x 0xc00008af38 + 8
x -fmt hex -count 20 -size 1 -x &myVar
x -fmt hex -count 20 -size 1 -x myPtrVar
Aliases: x
## exit
Exit the debugger.
exit [-c]
When connected to a headless instance started with the --accept-multiclient, pass -c to resume the execution of the target process before disconnecting.
Aliases: quit q
## frame
Set the current frame, or execute command on a different frame.
frame <m>
frame <m> <command>
The first form sets frame used by subsequent commands such as "print" or "set".
The second form runs the command on the given frame.
## funcs
Print list of functions.
funcs [<regex>]
If regex is specified only the functions matching it will be returned.
## goroutine
Shows or changes current goroutine
goroutine
goroutine <id>
goroutine <id> <command>
Called without arguments it will show information about the current goroutine.
Called with a single argument it will switch to the specified goroutine.
Called with more arguments it will execute a command on the specified goroutine.
Aliases: gr
## goroutines
List program goroutines.
goroutines [-u|-r|-g|-s] [-t [depth]] [-l] [-with loc expr] [-without loc expr] [-group argument] [-chan expr] [-exec command]
Print out info for every goroutine. The flag controls what information is shown along with each goroutine:
-u displays location of topmost stackframe in user code (default)
-r displays location of topmost stackframe (including frames inside private runtime functions)
-g displays location of go instruction that created the goroutine
-s displays location of the start function
-t displays goroutine's stacktrace (an optional depth value can be specified, default: 10)
-l displays goroutine's labels
If no flag is specified the default is -u, i.e. the first frame within the first 30 frames that is not executing a runtime private function.
FILTERING
If -with or -without are specified only goroutines that match the given condition are returned.
To only display goroutines where the specified location contains (or does not contain, for -without and -wo) expr as a substring, use:
goroutines -with (userloc|curloc|goloc|startloc) expr
goroutines -w (userloc|curloc|goloc|startloc) expr
goroutines -without (userloc|curloc|goloc|startloc) expr
goroutines -wo (userloc|curloc|goloc|startloc) expr
Where:
userloc: filter by the location of the topmost stackframe in user code
curloc: filter by the location of the topmost stackframe (including frames inside private runtime functions)
goloc: filter by the location of the go instruction that created the goroutine
startloc: filter by the location of the start function
To only display goroutines that have (or do not have) the specified label key and value, use:
goroutines -with label key=value
goroutines -without label key=value
To only display goroutines that have (or do not have) the specified label key, use:
goroutines -with label key
goroutines -without label key
To only display goroutines that are running (or are not running) on a OS thread, use:
goroutines -with running
goroutines -without running
To only display user (or runtime) goroutines, use:
goroutines -with user
goroutines -without user
CHANNELS
To only show goroutines waiting to send to or receive from a specific channel use:
goroutines -chan expr
Note that 'expr' must not contain spaces.
GROUPING
goroutines -group (userloc|curloc|goloc|startloc|running|user)
Where:
userloc: groups goroutines by the location of the topmost stackframe in user code
curloc: groups goroutines by the location of the topmost stackframe
goloc: groups goroutines by the location of the go instruction that created the goroutine
startloc: groups goroutines by the location of the start function
running: groups goroutines by whether they are running or not
user: groups goroutines by weather they are user or runtime goroutines
Groups goroutines by the given location, running status or user classification, up to 5 goroutines per group will be displayed as well as the total number of goroutines in the group.
goroutines -group label key
Groups goroutines by the value of the label with the specified key.
EXEC
goroutines -exec <command>
Runs the command on every goroutine.
Aliases: grs
## help
Prints the help message.
help [command]
Type "help" followed by the name of a command for more information about it.
Aliases: h
## libraries
List loaded dynamic libraries
## list
Show source code.
[goroutine <n>] [frame <m>] list [<locspec>]
Show source around current point or provided locspec.
For example:
frame 1 list 69
list testvariables.go:10000
list main.main:30
list 40
Aliases: ls l
## locals
Print local variables.
[goroutine <n>] [frame <m>] locals [-v] [<regex>]
The name of variables that are shadowed in the current scope will be shown in parenthesis.
If regex is specified only local variables with a name matching it will be returned. If -v is specified more information about each local variable will be shown.
## next
Step over to next source line.
next [count]
Optional [count] argument allows you to skip multiple lines.
Aliases: n
## next-instruction
Single step a single cpu instruction, skipping function calls.
Aliases: ni nexti
## on
Executes a command when a breakpoint is hit.
on <breakpoint name or id> <command>
on <breakpoint name or id> -edit
Supported commands: print, stack, goroutine, trace and cond.
To convert a breakpoint into a tracepoint use:
on <breakpoint name or id> trace
The command 'on <bp> cond <cond-arguments>' is equivalent to 'cond <bp> <cond-arguments>'.
The command 'on x -edit' can be used to edit the list of commands executed when the breakpoint is hit.
## packages
Print list of packages.
packages [<regex>]
If regex is specified only the packages matching it will be returned.
## print
Evaluate an expression.
[goroutine <n>] [frame <m>] print [%format] <expression>
See [Documentation/cli/expr.md](//github.com/go-delve/delve/tree/master/Documentation/cli/expr.md) for a description of supported expressions.
The optional format argument is a format specifier, like the ones used by the fmt package. For example "print %x v" will print v as an hexadecimal number.
Aliases: p
## rebuild
Rebuild the target executable and restarts it. It does not work if the executable was not built by delve.
## regs
Print contents of CPU registers.
regs [-a]
Argument -a shows more registers. Individual registers can also be displayed by 'print' and 'display'. See [Documentation/cli/expr.md](//github.com/go-delve/delve/tree/master/Documentation/cli/expr.md).
## restart
Restart process.
For recorded targets the command takes the following forms:
restart resets to the start of the recording
restart [checkpoint] resets the recording to the given checkpoint
restart -r [newargv...] [redirects...] re-records the target process
For live targets the command takes the following forms:
restart [newargv...] [redirects...] restarts the process
If newargv is omitted the process is restarted (or re-recorded) with the same argument vector.
If -noargs is specified instead, the argument vector is cleared.
A list of file redirections can be specified after the new argument list to override the redirections defined using the '--redirect' command line option. A syntax similar to Unix shells is used:
<input.txt redirects the standard input of the target process from input.txt
>output.txt redirects the standard output of the target process to output.txt
2>error.txt redirects the standard error of the target process to error.txt
Aliases: r
## rev
Reverses the execution of the target program for the command specified.
Currently, rev next, step, step-instruction and stepout commands are supported.
## rewind
Run backwards until breakpoint or start of recorded history.
Aliases: rw
## set
Changes the value of a variable.
[goroutine <n>] [frame <m>] set <variable> = <value>
See [Documentation/cli/expr.md](//github.com/go-delve/delve/tree/master/Documentation/cli/expr.md) for a description of supported expressions. Only numerical variables and pointers can be changed.
## source
Executes a file containing a list of delve commands
source <path>
If path ends with the .star extension it will be interpreted as a starlark script. See [Documentation/cli/starlark.md](//github.com/go-delve/delve/tree/master/Documentation/cli/starlark.md) for the syntax.
If path is a single '-' character an interactive starlark interpreter will start instead. Type 'exit' to exit.
## sources
Print list of source files.
sources [<regex>]
If regex is specified only the source files matching it will be returned.
## stack
Print stack trace.
[goroutine <n>] [frame <m>] stack [<depth>] [-full] [-offsets] [-defer] [-a <n>] [-adepth <depth>] [-mode <mode>]
-full every stackframe is decorated with the value of its local variables and arguments.
-offsets prints frame offset of each frame.
-defer prints deferred function call stack for each frame.
-a <n> prints stacktrace of n ancestors of the selected goroutine (target process must have tracebackancestors enabled)
-adepth <depth> configures depth of ancestor stacktrace
-mode <mode> specifies the stacktrace mode, possible values are:
normal - attempts to automatically switch between cgo frames and go frames
simple - disables automatic switch between cgo and go
fromg - starts from the registers stored in the runtime.g struct
Aliases: bt
## step
Single step through program.
Aliases: s
## step-instruction
Single step a single cpu instruction.
Aliases: si stepi
## stepout
Step out of the current function.
Aliases: so
## target
Manages child process debugging.
target follow-exec [-on [regex]] [-off]
Enables or disables follow exec mode. When follow exec mode Delve will automatically attach to new child processes executed by the target process. An optional regular expression can be passed to 'target follow-exec', only child processes with a command line matching the regular expression will be followed.
target list
List currently attached processes.
target switch [pid]
Switches to the specified process.
## thread
Switch to the specified thread.
thread <id>
Aliases: tr
## threads
Print out info for every traced thread.
## toggle
Toggles on or off a breakpoint.
toggle <breakpoint name or id>
## trace
Set tracepoint.
trace [name] [locspec]
A tracepoint is a breakpoint that does not stop the execution of the program, instead when the tracepoint is hit a notification is displayed. See [Documentation/cli/locspec.md](//github.com/go-delve/delve/tree/master/Documentation/cli/locspec.md) for the syntax of locspec. If locspec is omitted a tracepoint will be set on the current line.
See also: "help on", "help cond" and "help clear"
Aliases: t
## transcript
Appends command output to a file.
transcript [-t] [-x] <output file>
transcript -off
Output of Delve's command is appended to the specified output file. If '-t' is specified and the output file exists it is truncated. If '-x' is specified output to stdout is suppressed instead.
Using the -off option disables the transcript.
## types
Print list of types
types [<regex>]
If regex is specified only the types matching it will be returned.
## up
Move the current frame up.
up [<m>]
up [<m>] <command>
Move the current frame up by <m>. The second form runs the command on the given frame.
## vars
Print package variables.
vars [-v] [<regex>]
If regex is specified only package variables with a name matching it will be returned. If -v is specified more information about each package variable will be shown.
## watch
Set watchpoint.
watch [-r|-w|-rw] <expr>
-r stops when the memory location is read
-w stops when the memory location is written
-rw stops when the memory location is read or written
The memory location is specified with the same expression language used by 'print', for example:
watch v
watch -w *(*int)(0x1400007c018)
will watch the address of variable 'v' and writes to an int at addr '0x1400007c018'.
Note that writes that do not change the value of the watched memory address might not be reported.
See also: "help print".
## whatis
Prints type of an expression.
whatis <expression>
@@ -0,0 +1,144 @@
# 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:
```
<interface name>(<concrete type>) <value>
```
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.
## 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.
@@ -0,0 +1,90 @@
# 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.
@@ -0,0 +1,12 @@
# Location Specifiers
Several delve commands take a program location as an argument, the syntax accepted by this commands is:
* `*<address>` Specifies the location of memory address *address*. *address* can be specified as a decimal, hexadecimal or octal number
* `<filename>:<line>` 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.
* `<line>` Specifies the line *line* in the current file
* `+<offset>` Specifies the line *offset* lines after the current one
* `-<offset>` Specifies the line *offset* lines before the current one
* `<function>[:<line>]` Specifies the line *line* inside *function*. The full syntax for *function* is `<package>.(*<receiver type>).<function name>` 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 `<filename>:<line>` syntax should be used to break in the correct init function at the correct location.
* `/<regex>/` Specifies the location of all the functions matching *regex*
@@ -0,0 +1,341 @@
# 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
<!-- BEGIN MAPPING TABLE -->
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, 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)
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
<!-- END MAPPING TABLE -->
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.
# 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`.
## 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 <var_name> <next_field_name> <max_depth>
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 <arr> <pred>
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}
)
```
@@ -0,0 +1,66 @@
## 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.
### 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`.
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).
```
"substitutePath": [
{ "from": "/from/path", "to": "/to/path" }
]
```
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 /from/path /to/path
```
This command works similarly to the `config substitute-path` command described above.
### How are path substitution rules applied
Regardless of how they are specified the path substitution rules are an ordered list of `(from-path, to-path)` pairs. 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 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 path substitution code is SubstitutePath in pkg/locspec/locations.go.