..

Golang-语言源码级调试器 Delve

前言

Go 目前的调试器有如下几种:

  • GDB 最早期的调试工具,现在用的很少。
  • LLDB macOS 系统推荐的标准调试工具,单 Go 的一些专有特性支持的比较少。
  • Delve 专门为 Go 语言打造的调试工具,使用最为广泛。

本篇简单说明如何使用 Delve 工具来调试 Go 程序,使用的 delve 版本为 1.20.1。

delve 的汉语意思是:钻研、探索;用这个来命名一个debug工具还是非常的形象。

安装

已知以下说明适用于 Linux、macOS、Windows 和 FreeBSD。

克隆 git 存储库并构建:

$ git clone https://github.com/go-delve/delve
$ cd delve
$ go install github.com/go-delve/delve/cmd/dlv

或者,在 Go 版本 1.16 或更高版本上:

Install the latest release: $ go install github.com/go-delve/delve/cmd/dlv@latest

Install at tree head: $ go install github.com/go-delve/delve/cmd/dlv@master

安装在一个特定的版本或:

$ go install github.com/go-delve/delve/cmd/dlv@v1.7.3
$ go install github.com/go-delve/delve/cmd/dlv@v1.7.4-0.20211208103735-2f13672765fe

命令

Usage:
  dlv [command]

Available Commands:
  attach      附加到正在运行的进程并开始调试.
  connect     使用终端客户端连接到无头调试服务器.
  core        检查核心转储.
  dap         启动一个通过调试适配器协议(DAP)通信的无头TCP服务器.
  debug       编译并开始调试当前目录中的主包或指定的包.
  exec        执行预编译的二进制文件,并开始调试会话.
  help        Help about any command
  run         弃用的命令。使用'debug'代替.
  test        编译测试二进制文件并开始调试程序.
  trace       编译并开始跟踪程序.
  version     Prints version.

[操作] 示例代码

下面是检查操作的代码

.test/
├── go.mod
├── main.go
└── main_test.go
module debug_sample

go 1.18

main.go 执行以下处理:

package main

import (
	"fmt"
)

var abc string

func init() {
	abc = "wakuwaku bank"
}

func add(a, b int) int {
	fmt.Printf("func add %v\n", abc)
	return a + b
}

func sub(a, b int) int {
	fmt.Printf("func sub %v\n", abc)
	return a - b
}

func calculate(a, b int) (addValue, subValue int) {
	addValue = add(a, b)
	subValue = sub(a, b)
	return addValue, subValue
}

func sampleFunc1() {
	for i := 0; i < 10; i++ {
		a := i + 10
		b := i
		addValue, subValue := calculate(a, b)
		fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
	}
}

func main() {
	sampleFunc1()
}

main_test.go 执行以下处理:

package main

import "testing"

func Test_add(t *testing.T) {
	type args struct {
		a int
		b int
	}
	tests := []struct {
		name string
		args args
		want int
	}{{name: "Both positive values", args: args{10, 3}, want: 13}}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := add(tt.args.a, tt.args.b); got != tt.want {
				t.Errorf("add() = %v, want %v", got, tt.want)
			}
		})
	}
}

func Test_sub(t *testing.T) {
	type args struct {
		a int
		b int
	}
	tests := []struct {
		name string
		args args
		want int
	}{{name: "Both positive values", args: args{10, 3}, want: 7}}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := sub(tt.args.a, tt.args.b); got != tt.want {
				t.Errorf("sub() = %v, want %v", got, tt.want)
			}
		})
	}
}

[调试] dlv 调试

开始调试

$ dlv debug main.go
Type 'help' for list of commands.
(dlv) 

检查功能/代码( funcs list )

funcs main\..* 查看 main 文件 所有定义的方法

(dlv) funcs main\..*
main.add
main.calculate
main.init.0
main.main
main.sampleFunc1
main.sub
runtime.main.func1
runtime.main.func2

list 您可以在以下位置查看某个方法源代码

(dlv) list main.main
Showing /debug_sample/main.go:38 (PC: 0x1029dda10)
    33:                 addValue, subValue := calculate(a, b)
    34:                 fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
    35:         }
    36: }
    37: 
    38: func main() {
    39:         sampleFunc1()
    40: }
(dlv) list main.sampleFunc1:3
Showing /debug_sample/main.go:32 (PC: 0x1029dd8c0)
    27: }
    28: 
    29: func sampleFunc1() {
    30:         for i := 0; i < 10; i++ {
    31:                 a := i + 10
    32:                 b := i
    33:                 addValue, subValue := calculate(a, b)
    34:                 fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
    35:         }
    36: }
    37: 

设置/删除断点 ( break clear )

break 您可以使用以下命令设置断点

(dlv) break main.main
Breakpoint 1 set at 0x1029dda10 for main.main() ./main.go:38
(dlv) break main.sampleFunc1:3
Breakpoint 2 set at 0x1029dd8c0 for main.sampleFunc1() ./main.go:32

breakpoints 您可以检查中设置的断点。

(dlv) breakpoints
Breakpoint runtime-fatal-throw (enabled) at 0x10296c880 for runtime.throw() /Users/w/.gvm/gos/go1.18/src/runtime/panic.go:982 (0)
Breakpoint unrecovered-panic (enabled) at 0x10296cb90 for runtime.fatalpanic() /Users/w/.gvm/gos/go1.18/src/runtime/panic.go:1065 (0)
        print runtime.curg._panic.arg
Breakpoint 1 (enabled) at 0x1029dda10 for main.main() ./main.go:38 (0)
Breakpoint 2 (enabled) at 0x1029dd8c0 for main.sampleFunc1() ./main.go:32 (0)

clear 您可以使用 删除指定的断点。

(dlv) clear 1
Breakpoint 1 cleared at 0x1029dda10 for main.main() ./main.go:38
(dlv) breakpoints
Breakpoint runtime-fatal-throw (enabled) at 0x10296c880 for runtime.throw() /Users/w/.gvm/gos/go1.18/src/runtime/panic.go:982 (0)
Breakpoint unrecovered-panic (enabled) at 0x10296cb90 for runtime.fatalpanic() /Users/w/.gvm/gos/go1.18/src/runtime/panic.go:1065 (0)
        print runtime.curg._panic.arg
Breakpoint 2 (enabled) at 0x1029dd8c0 for main.sampleFunc1() ./main.go:32 (0)

clearall 删除所有断点。

(dlv) clearall
Breakpoint 1 cleared at 0x4986e6 for main.main() ./main.go:38
Breakpoint 5 cleared at 0x49858c for main.sampleFunc1() ./main.go:32

提前处理到断点( continue )

continue 让我们继续执行中设置的断点。

(dlv) continue
> main.sampleFunc1() ./main.go:32 (hits goroutine(1):1 total:1) (PC: 0x1029dd8c0)
    27: }
    28: 
    29: func sampleFunc1() {
    30:         for i := 0; i < 10; i++ {
    31:                 a := i + 10
=>  32:                 b := i
    33:                 addValue, subValue := calculate(a, b)
    34:                 fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
    35:         }
    36: }
    37: 

continue 或者,您可以继续执行以下命令。

next 向前迈出一行(跨过)。 step 前进一行。 stepout 退出当前功能。

检查并覆盖变量 ( locals set )

[root@cdh2 test]# dlv debug main.go  // 调试
Type 'help' for list of commands.

(dlv) break main.sampleFunc1:3  // 设置断点
Breakpoint 1 set at 0x49858c for main.sampleFunc1() ./main.go:32

(dlv) c  // 跳到断点
> main.sampleFunc1() ./main.go:32 (hits goroutine(1):1 total:1) (PC: 0x49858c)
    27:	}
    28:
    29:	func sampleFunc1() {
    30:		for i := 0; i < 10; i++ {
    31:			a := i + 10
=>  32:			b := i
    33:			addValue, subValue := calculate(a, b)
    34:			fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
    35:		}
    36:	}
    37:
    
(dlv) locals  // 打印局部变量
i = 0
a = 10

(dlv) vars main.abc
main.abc = "wakuwaku bank"

(dlv) print i
0
(dlv) print a
10

(dlv) set i = 2  // 重新给变量赋值
(dlv) print i
2

堆栈跟踪显示( stack frame )

首先,要检查操作,请继续添加功能。

(dlv) break main.add
Breakpoint 3 set at 0x1029dd610 for main.add() ./main.go:13
(dlv) c
> main.add() ./main.go:13 (hits goroutine(1):1 total:1) (PC: 0x1029dd610)
     8: 
     9: func init() {
    10:         abc = "wakuwaku bank"
    11: }
    12: 
=>  13: func add(a, b int) int {
    14:         fmt.Printf("func add %v\n", abc)
    15:         return a + b
    16: }
    17: 
    18: func sub(a, b int) int {

显示堆栈跟踪

(dlv) stack
0  0x00000000004982aa in main.add
   at ./main.go:13
1  0x00000000004984df in main.calculate
   at ./main.go:24
2  0x00000000004985a5 in main.sampleFunc1
   at ./main.go:33
3  0x00000000004986f7 in main.main
   at ./main.go:39
4  0x00000000004372d8 in runtime.main
   at /root/.go/src/runtime/proc.go:250
5  0x0000000000461661 in runtime.goexit
   at /root/.go/src/runtime/asm_amd64.s:1571

frame 您可以通过指定堆栈跟踪编号来检查代码和变量

(dlv) frame 2 ls
Goroutine 1 frame 2 at /debug_sample/main.go:33 (PC: 0x1029dd8d0)
    28: 
    29: func sampleFunc1() {
    30:         for i := 0; i < 10; i++ {
    31:                 a := i + 10
    32:                 b := i
=>  33:                 addValue, subValue := calculate(a, b)
    34:                 fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
    35:         }
    36: }
    37: 
    38: func main() {
(dlv) frame 2 locals
i = 2
a = 10
b = 2

指定条件 ( condition )

首先,进行for语句的处理

$ dlv debug main.go
Type 'help' for list of commands.
(dlv) b main.sampleFunc1:3
Breakpoint 1 set at 0x1050958c0 for main.sampleFunc1() ./main.go:32
(dlv) c
> main.sampleFunc1() ./main.go:32 (hits goroutine(1):1 total:1) (PC: 0x1050958c0)
    27: }
    28: 
    29: func sampleFunc1() {
    30:         for i := 0; i < 10; i++ {
    31:                 a := i + 10
=>  32:                 b := i
    33:                 addValue, subValue := calculate(a, b)
    34:                 fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
    35:         }
    36: }
    37: 
(dlv) locals
i = 0
a = 10

condition 您可以使用 设置断点条件。 i==5 让我们将其设置为停止时

(dlv) condition 1 i==5

(dlv) c
func add wakuwaku bank
func sub wakuwaku bank
addValue: 10 subValue: 10
func add wakuwaku bank
func sub wakuwaku bank
addValue: 12 subValue: 10
func add wakuwaku bank
func sub wakuwaku bank
addValue: 14 subValue: 10
func add wakuwaku bank
func sub wakuwaku bank
addValue: 16 subValue: 10
func add wakuwaku bank
func sub wakuwaku bank
addValue: 18 subValue: 10
> main.sampleFunc1() ./main.go:32 (hits goroutine(1):2 total:2) (PC: 0x1050958c0)
    27: }
    28: 
    29: func sampleFunc1() {
    30:         for i := 0; i < 10; i++ {
    31:                 a := i + 10
=>  32:                 b := i
    33:                 addValue, subValue := calculate(a, b)
    34:                 fmt.Printf("addValue: %v subValue: %v\n", addValue, subValue)
    35:         }
    36: }
    37: 
    
(dlv) locals
i = 5
a = 15

调试结束( exit )

exit 您可以使用 完成调试。

(dlv) exit

[debug] dlv测试(调试测试)

dlv test 您可以使用以下命令调试您的测试代码

$ dlv test
Type 'help' for list of commands.
(dlv) funcs test.Test*  // test.Test*  test 包含 Xxx_test.go 文件夹
debug_sample.Test_add
debug_sample.Test_add.func1
debug_sample.Test_sub
debug_sample.Test_sub.func1

(dlv) b test.Test_add
Breakpoint 1 set at 0x104891e90 for debug_sample.Test_add() ./main_test.go:5

(dlv) c
> debug_sample.Test_add() ./main_test.go:5 (hits goroutine(4):1 total:1) (PC: 0x104891e90)
     1: package main
     2: 
     3: import "testing"
     4: 
=>   5: func Test_add(t *testing.T) {
     6:         type args struct {
     7:                 a int
     8:                 b int
     9:         }
    10:         tests := []struct { 

[debug] dlv Attach(调试运行进程)

更正操作检查代码

对其进行修改以保持作为 Web 服务器运行,如下所示。

package main

import (
	"fmt"
	"net/http"
)

var abc string

func init() {
	abc = "wakuwaku bank"
}

func add(a, b int) int {
	fmt.Printf("func add %v\n", abc)
	return a + b
}

func sub(a, b int) int {
	fmt.Printf("func sub %v\n", abc)
	return a - b
}

func calculate(a, b int) (addValue, subValue int) {
	addValue = add(a, b)
	subValue = sub(a, b)
	return addValue, subValue
}

func sampleFunc1(w http.ResponseWriter, r *http.Request) {
	for i := 0; i < 10; i++ {
		a := i * 2
		b := i
		addValue, subValue := calculate(a, b)
		fmt.Fprintf(w, "addValue: %v subValue: %v\n", addValue, subValue)
	}
}

func main() {
	http.HandleFunc("/sample_func_1", sampleFunc1)
	http.ListenAndServe(":80", nil)
}

启动。

$ go build     
$ ./test

调试运行进程

检查进程 ID。

$ ps -ef | grep "test"
root     254882  56889  0 15:24 pts/2    00:00:00 ./test
root     257090  18100  0 15:25 pts/0    00:00:00 grep --color=auto test

调试

# dlv attach 254882
Type 'help' for list of commands.
(dlv)

设置断点并等待进程被调用。

(dlv) b main.sampleFunc1
Breakpoint 1 set at 0x1010e8470 for main.sampleFunc1() ./main.go:30

(dlv) c

尝试在另一个控制台中向端点发出请求。

$ curl http://localhost/sample_func_1

处理在设置的断点处停止,如下所示。

(dlv) c
> main.sampleFunc1() ./main.go:30 (hits goroutine(21):1 total:1) (PC: 0x1010e8470)
Warning: debugging optimized function
    25:         addValue = add(a, b)
    26:         subValue = sub(a, b)
    27:         return addValue, subValue
    28: }
    29: 
=>  30: func sampleFunc1(w http.ResponseWriter, r *http.Request) {
    31:         for i := 0; i < 10; i++ {
    32:                 a := i * 2
    33:                 b := i
    34:                 addValue, subValue := calculate(a, b)
    35:                 fmt.Fprintf(w, "addValue: %v subValue: %v\n", addValue, subValue)

命令说明

以下是一些最常用的命令。

断点相关

命令别名解释
breakb设置断点
breakpointsbp显示活动断点
clear删除断点
clearall删除所有断点
conditioncond设置断点条件

继续

命令别名解释
continuec继续到“下一个断点”或“程序结束”或“指定点”。(例如 c main.add:1 )
nextn向前迈出一行(跨过)。
steps前进一行。
stepoutso退出当前功能。
restart恢复该过程。
exitq退出调试器。

其他的

命令别名解释
funcs检查功能列表。(例如 funcs main..* )
listl显示代码。(例如 l 10 l main.main:3 )
locals检查局部变量。
vars检查包变量。
printp评估一个表达式。
set覆盖变量。
stackbt显示堆栈跟踪。

您还可以通过在调试过程中执行来查看如何使用其他命令 help

(dlv) help
The following commands are available:

Running the program:
    call ------------------------ Resumes process, injecting a function call (EXPERIMENTAL!!!)
    continue (alias: c) --------- Run until breakpoint or program termination.
    next (alias: n) ------------- Step over to next source line.
    rebuild --------------------- Rebuild the target executable and restarts it. It does not work if the executable was not built by delve.
    restart (alias: r) ---------- Restart process.
    step (alias: s) ------------- Single step through program.
    step-instruction (alias: si)  Single step a single cpu instruction.
    stepout (alias: so) --------- Step out of the current function.

Manipulating breakpoints:
    break (alias: b) ------- Sets a breakpoint.
    breakpoints (alias: bp)  Print out info for active breakpoints.
    clear ------------------ Deletes breakpoint.
    clearall --------------- Deletes multiple breakpoints.
    condition (alias: cond)  Set breakpoint condition.
    on --------------------- Executes a command when a breakpoint is hit.
    toggle ----------------- Toggles on or off a breakpoint.
    trace (alias: t) ------- Set tracepoint.
    watch ------------------ Set watchpoint.

Viewing program variables and memory:
    args ----------------- Print function arguments.
    display -------------- Print value of an expression every time the program stops.
    examinemem (alias: x)  Examine raw memory at the given address.
    locals --------------- Print local variables.
    print (alias: p) ----- Evaluate an expression.
    regs ----------------- Print contents of CPU registers.
    set ------------------ Changes the value of a variable.
    vars ----------------- Print package variables.
    whatis --------------- Prints type of an expression.

Listing and switching between threads and goroutines:
    goroutine (alias: gr) -- Shows or changes current goroutine
    goroutines (alias: grs)  List program goroutines.
    thread (alias: tr) ----- Switch to the specified thread.
    threads ---------------- Print out info for every traced thread.

Viewing the call stack and selecting frames:
    deferred --------- Executes command in the context of a deferred call.
    down ------------- Move the current frame down.
    frame ------------ Set the current frame, or execute command on a different frame.
    stack (alias: bt)  Print stack trace.
    up --------------- Move the current frame up.

Other commands:
    config --------------------- Changes configuration parameters.
    disassemble (alias: disass)  Disassembler.
    dump ----------------------- Creates a core dump from the current process state
    edit (alias: ed) ----------- Open where you are in $DELVE_EDITOR or $EDITOR
    exit (alias: quit | q) ----- Exit the debugger.
    funcs ---------------------- Print list of functions.
    help (alias: h) ------------ Prints the help message.
    libraries ------------------ List loaded dynamic libraries
    list (alias: ls | l) ------- Show source code.
    source --------------------- Executes a file containing a list of delve commands
    sources -------------------- Print list of source files.
    transcript ----------------- Appends command output to a file.
    types ---------------------- Print list of types

Type help followed by a command for full documentation.

参考

go-delve/delve:Delve 是 Go 编程语言的调试器