Go delve调试工具的简单应用

Delve是个啥

Delve is a debugger for the Go programming language. The goal of the project is to provide a simple, full featured debugging tool for Go. Delve should be easy to invoke and easy to use. Chances are if you’re using a debugger, things aren’t going your way. With that in mind, Delve should stay out of your way as much as possible.

  • Go语言的调试器
  • 目标:提供简单、功能齐全的Go调试工具
  • 容易调用、使用
  • 谁家好的代码天天需要调试呀,尽量少用

如何安装

安装latest,最新版
go install github.com/go-delve/delve/cmd/dlv@latest
如果它报这个错误,证明dlv不支持该平台

go install github.com/go-delve/delve/cmd/dlv@latest
D:\goworkspace\pkg\mod\github.com\go-delve\delve@v1.21.2\service\debugger\debugger.go:32:2: found packages native (dump_other.go) and your_windows_architecture_is_not_supported_by_delve (support_sentinel_windows.go) in D:\goworkspace\pkg\mod\github.com\go-delve\delve@v1.21.2\pkg\proc\native

如何使用

go version
go version go1.20 linux/arm64

dlv version
Delve Debugger
Version: 1.21.2
Build: $Id: 98f8ab2662d926245917ade2f2bb38277315c7fc $

你说啥?不会用?我也不会

不会用就看看help吧。dlv --help

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`

Usage:
  dlv [command]

Available Commands:
  attach      Attach to running process and begin debugging.
  connect     Connect to a headless debug server with a terminal client.
  core        Examine a core dump.
  dap         Starts a headless TCP server communicating via Debug Adaptor Protocol (DAP).
  debug       Compile and begin debugging main package in current directory, or the package specified.
  exec        Execute a precompiled binary, and begin a debug session.
  help        Help about any command
  test        Compile test binary and begin debugging program.
  trace       Compile and begin tracing program.
  version     Prints version.

Additional help topics:
  dlv backend  Help about the --backend flag.
  dlv log      Help about logging flags.
  dlv redirect Help about file redirection.

Use "dlv [command] --help" for more information about a command.

汇总一下

命令名作用
attachAttach to running process and begin debugging (白话:跟某个进程建立联系,跟某个进程搞搞暧昧呗)
connectConnect to a headless debug server with a terminal client.(白话:作为一个客户端,连接到一个(无头?不可描述的)调试服务)
coreExamine a core dump. (白话:检查核心转储)
dapStarts a headless TCP server communicating via Debug Adaptor Protocol (DAP). (白话:启一个服务,让客户端连接调试)
debugCompile and begin debugging main package in current directory, or the package specified. (白话:编译并开始调试在当前目录的main包,或者其他给定的包)
execExecute a precompiled binary, and begin a debug session. (白话:执行一个预编译好的二进制文件,并开启一个调试会话)
helpHelp about any command (它会帮你哦,别的可以不会,这个必须会)
testCompile test binary and begin debugging program. (编译测试二进制、并开始调试程序)
traceCompile and begin tracing program. (追踪模式)
versionPrints version. (版本信息啦)

总结一下,上述命令中,如下5个用的多一点儿:

  • attach
  • debug
  • exec
  • core
  • help

其他的看看帮助命令就好
使用dlv help 子命令可查看子命令的帮助文档哈

另外还有如下不常用的命令,暂不做介绍

Additional help topics:
  dlv backend  Help about the --backend flag.
  dlv log      Help about logging flags.
  dlv redirect Help about file redirection.

子命令的具体用法

搞一个先决条件,创建一个main.go文件,写一段简单的代码进去。
就以如下代码为例,main函数中写了一个简易版的httpServer,80端口开放,访问 “http://localhost:80/” 路径,则执行一次斐波那契数列的函数。

package main

import "net/http"

func main() {
        http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
            fib(3)
        })
        if err := http.ListenAndServe(":80", nil); err != nil {
                panic(err)
        }
}

func fib(n int) int {
    if n < 2 {
        return 1
    }
    return fib(n-1) + fib(n-2)
}

下面对调试命令进行梳理

1. attach

dlv help attach

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.

Usage:
  dlv attach pid [executable] [flags]

Flags:
      --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)

Global Flags:
      --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")
      --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. (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)

该命令主要部分: dlv attach pid,该pid是一个Go程序的pid

  1. go build ./main.go

  2. 生成了 main 可执行文件

  3. 使用nohub ./main 或者 setsid ./main 启动 main 文件,此时该文件加载进内存后对应一个进程ID。

  4. 这里使用ps -ef | grep main 找到程序的pid

  5. 使用dlv attach PID 进行调试
    在这里插入图片描述

  6. 输入help 看一下帮助命令

root@Ophelia:~/test# dlv attach 1680
Type 'help' for list of commands.
(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.
    packages ------------------- Print list of packages.
    source --------------------- Executes a file containing a list of delve commands
    sources -------------------- Print list of source files.
    target --------------------- Manages child process debugging.
    transcript ----------------- Appends command output to a file.
    types ---------------------- Print list of types

Type help followed by a command for full documentation.
(dlv)

可以看见子命令非常之多

如下汇总一下子命令

执行程序

序号子命令别名描述
01callResumes process, injecting a function call (EXPERIMENTAL!!!) (实验性的功能,注入一个函数调用,重新执行)
02continuecRun until breakpoint or program termination. (执行到断点或程序中止)
03nextnStep over to next source line. (步过下一行,下一行若是函数,则调用并返回)
04rebuildRebuild the target executable and restarts it. It does not work if the executable was not built by delve. (重新编译目标执行文件并启动他, 若该程序不是由delve编译的,则无法执行)
05restartrRestart process. (重启进程)
06stepsSingle step through program. (单步调试,整个程序)
07step-instructionsiSingle step a single cpu instruction. (单步执行cpu指令)
08stepoutosStep out of the current function. (步出当前函数)

操纵断点

序号子命令别名描述
01breakbSets a breakpoint. (设置一个断点)
02breakpointsbpPrint out info for active breakpoints. (打印正在使用的断点)
03clearDeletes brekpoint. (根据断点编号,删除断点)
04clearallDeletes multiple breakpoints.(删除多个断点)
05conditioncondSet breakpoint condition. (设置断点条件)
06onExecutes a command when a breakpoint is hit. (当断点命中时候,执行一个命令)
07toggleToggles on or off a breakpoint. (切换断点的状态,启用或关闭)
08tracetSet tracepoint. (设置追踪点)
09watchSet watchpoint. (设置内存观测点,看门狗的功能)

查看程序变量和内存

序号子命令别名描述
01argsPrint function arguments. (打印函数参数)
02displayPrint value of an expression every time the program stops. (打印表达式的值,在下一行或者下一个断点)
03examinememxExamine raw memory at the given address.(检查给定地址的原始内存)
04localsPrint local variables. (打印局部变量)
05printpEvaluate an expression. (计算并打印表达式结果)
06regsPrint contents of CPU registers.(打印CPU 寄存器的内容)
07setChanges the value of a variable. (给变量设置值)
08varsPrint package variables. (打印包级别变量)
09whatisPrints type of an expression. (打印表达式类型)

进程、协程

序号子命令别名描述
01goroutinegrShows or changes current goroutine. (显示或切换当前协程)
02goroutinesgrsList program goroutines. (列出当前程序所有的协程)
03threadtrSwitch to the specified thread. (切换到指定的线程)
04threadsPrint out info for every traced thread.(打印所有线程的追踪信息)

调用栈、栈帧

序号子命令别名描述
01deferredExecutes command in the context of a deferred call. (在defer调用的上下文中执行一个命令)
01downMove the current frame down. (向下移动栈帧)
03frameSet the current frame, or execute command on a different frame. (设置当前栈帧、或在其他栈帧执行命令)
04stackbtPrint stack trace. (打印栈追踪信息)
05upMove the current frame up. (向上移动当前栈帧)

其他命令

序号子命令别名描述
01configChanges configuration parameters. (修改配置参数)
02disassembledisassDisassembler. (反汇编)
03dumpCreates a core dump from the current process state. (创建核心转储)
04edited
05exitquit、qExit the debugger. (退出调试器)
06funcsPrint list of functions.(打印所有函数)
07helphPrints the help message. (打印帮助信息)
08librariesList loaded dynamic libraries. (列出动态链接库)
09listls 、lShow source code. (打印源码)
10packagesPrint list of packages.(打印包列表)
11sourceExecutes a file containing a list of delve commands. (执行一个包含delve命令列表的文件)
12sourcesPrint list of source files. (打印源码路径列表)
13targetManages child process debugging. (管理子进程调试)
14transcriptappends command output to a file. (追加命令输出到一个文件)
15typesPrint list of types.(打印类型列表)

以上高亮的子命令用的多一些
打一套组合拳(啊打!)
设置断点的方式

break 包名.函数名
b 包名.函数名
break 文件名:行号
b 文件名行号
b main.main
b main.fib
c
n

其他终端: curl http://localhost:80
在这里插入图片描述

描述过于诡异

bp,查看一下断点
在这里插入图片描述clear 1,删除一个断点,并再次查看断点
在这里插入图片描述c,此时断住不动了,怎么办,怎么办?
curl http://localhost:80 当然是在其他终端输入这个啦
在这里插入图片描述此时你会发现,其他终端中卡住了
此时你需要在当前终端一直

c
c
...

c下去,直到把fib函数执行完,再次断住
此时另一个终端中有结果了哦

curl http://localhost:80
StatusCode        : 200
StatusDescription : OK
Content           : {}
RawContent        : HTTP/1.1 200 OK
                    Content-Length: 0
                    Date: Fri, 15 Dec 2023 15:44:06 GMT
Headers           : {[Content-Length, 0], [Date, Fri, 15 Dec 2023 15:44:06 GMT]}
RawContentLength  : 0

其他命令自行探索

2. debug

dlv debug ./main.go
命令参考 attach

3. exec

dlv exec ./main
命令参考 attach

Reference
https://github.com/go-delve/delve

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/248869.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

机器学习练习题

例1: 解&#xff1a; 最大似然估计&#xff1a; P &#xff08;男&#xff09; 8 / 20 0.4 &#xff0c; P &#xff08;女&#xff09; 12 / 20 0.6 P&#xff08;男&#xff09; 8/200.4&#xff0c;P&#xff08;女&#xff09; 12/20 0.6 P&#xff08;男&#xff0…

three.js模拟太阳系

地球的旋转轨迹目前设置为了圆形&#xff0c;效果&#xff1a; <template><div><el-container><el-main><div class"box-card-left"><div id"threejs" style"border: 1px solid red"></div><div c…

服务器被攻击宕机的一些小建议

现在网络攻击屡有发生&#xff0c;任何网站服务器都面临这样的危险&#xff0c;服务器被攻击造成的崩溃宕机是损失是我们无法估量的。网络攻击我们无法预测&#xff0c;但做好防御措施是必须的&#xff0c;建议所有的网站都要做好防范措施&#xff0c;准备相应的防护预案&#…

RT-DETR 目标过线计数

使用 Ultralytics RT-DETR 进行目标计数 🚀 实际应用场景 物流水产养殖使用 Ultralytics RT-DETR 进行传送带包裹计数使用 Ultralytics RT-DETR 在海中进行鱼类计数请使用最新代码(2023年12月8日后),旧版本不支持! 示例 “目标计数示例” 目标计数 from ultralytics

高并发如何实现单用户信息查询接口

高并发如何实现单用户信息查询接口 故事情节 产品&#xff1a;小李&#xff0c;有个单用户信息查询的功能&#xff0c;需要你实现一下小李&#xff1a;这还不简单&#xff0c;两分钟我给你实现两分钟过去…小李&#xff1a;欧克了&#xff0c;部署上线了运维&#xff1a;哪个…

git checkout进行更改分支

git clone https://gitee.com/yaleguo1/minit-learning-demo.git下载代码。 cd minit-learning-demo/进入目录里边。 ls -l看一下当前分支的内容。 git checkout geek_chapter02更改分支到geek_chapter02。 ls -l看一下目录里边的内容。

Python 自动化之收发邮件(二)

发邮件之Windows进程监控 文章目录 发邮件之Windows进程监控前言一、基本内容二、基本结构三、库模块四、函数模块1.进程监控2.邮件发送 五、程序运行模块1.获取时间2.用户输入3.进程监控3.1进程启动发邮件3.2进程停止发邮件 总结 前言 上一篇简单写了一下如何进行邮件的收发操…

NXP应用随记(四):eMios阅读随记-整体功能概述

目录 1、eMios IP介绍 2、时钟结构 3、通道类型 4、功能介绍 5、中断与DMA 6、EMIOS -通道分配建议(针对S32K312) 1、eMios IP介绍 Emios是什么&#xff1f;eMIOS提供了独立的通道(UCs)&#xff0c;您可以配置这些通道来为不同的功能生成或测量时间事件。 每个eMIOS实例最…

智能插座是什么

智能插座 电工电气百科 文章目录 智能插座前言一、智能插座是什么二、智能插座的类别三、智能插座的原理总结 前言 智能插座的应用广泛&#xff0c;可以用于智能家居系统中的电器控制&#xff0c;也可以应用在办公室、商业场所和工业控制中&#xff0c;方便快捷地实现电器的远…

锁--07_2---- index merge(索引合并)引起的死锁

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 案例分析生产背景死锁日志表结构执行计划 EXPLAN为什么会用 index_merge&#xff08;索引合并&#xff09;为什么用了 index_merge就死锁了解决方案注&#xff1a;M…

算法训练营Day14

#Java #二叉树层次遍历 #反转二叉树 开源学习资料 二叉树的层次遍历&#xff1a;力扣题目链接 二叉树的层次遍历很好理解&#xff1a; 就是从根结点一层一层地往下遍历&#xff08;同一层&#xff0c;从左到右&#xff09;&#xff1a; 迭代的方式很好理解&#xff1a;就是…

Netty常见的设计模式

简介 设计模式在软件开发中起着至关重要的作用&#xff0c;它们是解决常见问题的经过验证的解决方案。而Netty作为一个优秀的网络应用程序框架&#xff0c;同样也采用了许多设计模式来提供高性能和可扩展性。在本文中&#xff0c;我们将探讨Netty中使用的一些关键设计模式&…

TS系列-keyof的妙用

案例1 1、如果&#xff0c;有一个接口&#xff0c;某个变量的类型&#xff0c;是这个接口的 key &#xff1f; keyof 后面可以跟 一个对象类型或者一个接口类型keyof 是把后面 对象或者接口 的 键 都提取出来&#xff0c;组成一个联合类型 interface IStudentAttr {name: stri…

【LeetCode刷题笔记(6-1)】【Python】【三数之和】【哈希表】【中等】

文章目录 三数之和题目描述示例示例1示例2示例3 提示解决方案1&#xff1a;【三层遍历查找】解决方案2&#xff1a;【哈希表】【两层遍历】 结束语 三数之和 三数之和 题目描述 给你一个整数数组 nums &#xff0c;判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i ! …

nodejs微信小程序+python+PHP血液中心管理平台的设计与实现-计算机毕业设计推荐

在二十一世纪的今天&#xff0c;我国献血总量已经不容小觑&#xff0c;在全国人民的不懈努力下&#xff0c;贫血、缺血的病人已经有了足够的血液保障。与此同时&#xff0c;采血工作和血液入库、出库等工作也日愈繁重。为进一步提高采血工作和血液中心的工作效率&#xff0c;开…

【算法与数据结构】376、LeetCode摆动序列

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;本题难点在于要考虑到不同序列的情况&#xff0c;具体来说要考虑一下几种特殊情况&#xff1a; 1、上…

提前预警,时刻守护:迅软DLP的数据安全先锋

许多数据泄密事件的发生&#xff0c;往往都是由于没有在案发事前做好安全保护&#xff0c;使得重要信息被随意攻击、盗取、泄密。比起在危机发生后亡羊补牢&#xff0c;更重要的是应该在案发之前未雨绸缪。迅软DLP作为迅软股份研发的“重磅选手”&#xff0c;可为政企单位在一切…

物联网智能仓库解决方案

物联网智能仓库解决方案是一种基于物联网技术的仓库管理系统&#xff0c;通过自动化设备、智能化管理系统和大数据分析等技术&#xff0c;实现仓库的智能化运营和管理。 物联网智能仓库解决方案包括&#xff1a; 仓库设备自动化&#xff1a;通过自动化设备和技术&#xff0c;实…

OpenHarmony关于修改系统横屏导致启动视频显示不全问题解决

前言 OpenHarmony源码版本&#xff1a;4.0release 开发板&#xff1a;DAYU / rk3568 前段时间写的设置OpenHarmony启动视频&#xff0c;在竖屏状态下是正常的&#xff0c;但是横屏状态下显示不全。 链接直达&#xff1a;OpenHarmony 设备启动Logo和启动视频替换指南-CSDN博…

docker小白第四天

docker小白第一天 什么是镜像 1、是一种轻量级、可执行的独立软件包&#xff0c;它包含运行某个软件所需的所有内容&#xff0c;我们把应用程序和配置依赖打包好形成一个可交付的运行环境(包括代码、运行时需要的库、环境变量和配置文件等)&#xff0c;这个打包好的运行环境就…
最新文章