Go delve调试工具的简单应用

news2024/10/6 4:13:21

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.coloradmin.cn/o/1314437.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于单片机的智能导盲杖设计 (论文+源码)

1. 系统设计 应用STC89C52单片机微处理器进行研究一种智能手杖系统&#xff0c;需要同时实现超声波自动测距、语音自动报警、距离自动显示、电机震动报警、LED指示灯灯光明灭自动提醒等多种功能&#xff0c;在手机通信提醒模式下手机用户可拨打固定手机电话信号实现手机通信提…

Helplook VS Salesforce:哪个知识库更好?

对于组织来说&#xff0c;选择一个合适的平台来管理在线知识库可能是一个具有挑战性的任务。而Salesforce的知识管理功能可以帮助组织更好地管理和分享他们的知识&#xff0c;从而更好地为客户提供服务。这是一种将知识管理集成到CRM平台中的方法&#xff0c;可以简化知识共享和…

IS-IS原理与配置3

IS-IS原理与配置 • IS-IS&#xff08;Intermediate System to Intermediate System&#xff0c;中间系统到中间系统&#xff09;是ISO &#xff08;International Organization for Standardization&#xff0c;国际标准化组织&#xff09;为它的CLNP &#xff08;ConnectionL…

【深度学习目标检测】六、基于深度学习的路标识别(python,目标检测,yolov8)

YOLOv8是一种物体检测算法&#xff0c;是YOLO系列算法的最新版本。 YOLO&#xff08;You Only Look Once&#xff09;是一种实时物体检测算法&#xff0c;其优势在于快速且准确的检测结果。YOLOv8在之前的版本基础上进行了一系列改进和优化&#xff0c;提高了检测速度和准确性。…

uni-app微信小程序隐藏左上角返回按钮

官方文档链接&#xff1a;uni.setNavigationBarTitle(OBJECT) | uni-app官网 (dcloud.net.cn) 首先要明确的是页面间的跳转方式有几种、每一种默认的作用是什么。 uniapp五种跳转方式 第一&#xff1a;wx.navigatorTo 【新页面打开&#xff0c;默认会有返回按钮】第二&#x…

ClickHouse Kafka 引擎教程

如果您刚开始并且第一次设置 Kafka 和 ClickHouse 需要帮助怎么办&#xff1f;这篇文章也许会提供下帮助。 我们将通过一个端到端示例&#xff0c;使用 Kafka 引擎将数据从 Kafka 主题加载到 ClickHouse 表中。我们还将展示如何重置偏移量和重新加载数据&#xff0c;以及如何更…

「构」向云端 - 我与 2023 亚马逊云科技 re:Invent 大会

授权声明&#xff1a;本篇文章授权活动官方亚马逊云科技文章转发、改写权&#xff0c;包括不限于在 亚马逊云科技开发者社区, 知乎&#xff0c;自媒体平台&#xff0c;第三方开发者媒体等亚马逊云科技官方渠道 2023年亚马逊AWS re:Invent大会宣布一项Amazon Q的创新项目&#x…

微信小程序---使用npm包安装Vant组件库

在小程序项目中&#xff0c;安装Vant 组件库主要分为如下3步: 注意&#xff1a;如果你的文件中不存在pakage.json&#xff0c;请初始化一下包管理器 npm init -y 1.通过 npm 安装(建议指定版本为1.3.3&#xff09; 通过npm npm i vant/weapp1.3.3 -S --production 通过y…

十六、YARN和MapReduce配置

1、部署前提 &#xff08;1&#xff09;配置前提 已经配置好Hadoop集群。 配置内容&#xff1a; &#xff08;2&#xff09;部署说明 &#xff08;3&#xff09;集群规划 2、修改配置文件 MapReduce &#xff08;1&#xff09;修改mapred-env.sh配置文件 export JAVA_HOM…

基于BWA,Bowtie2,samtools、checkm等工具计算宏基因组学序列分析中Contigs与Genes在样品中的丰度,多种计算方式和脚本对比

计算contigs和genes相对丰度可以提供有关微生物群落结构和功能的信息。以下是计算这两个指标的意义&#xff1a; 1. Contigs的相对丰度&#xff1a;contigs是利用基因组测序技术获得的碎片序列&#xff0c;通过计算contigs的相对丰度可以了解微生物群落中不同菌种的相对丰度。…

2023.12.14每日一题

2023.12.14 题目来源我的题解二维前缀和二维差分 题目来源 力扣每日一题&#xff1b;题序&#xff1a;2132 我的题解 哈哈哈哈&#xff01;&#xff01;&#xff01;我不会&#xff0c;借鉴一下官方题解 二维前缀和二维差分 求二维前缀和&#xff0c;用于判断快速判断右下角…

GPT-4V被超越?SEED-Bench多模态大模型测评基准更新

&#x1f4d6; 技术报告 SEED-Bench-1&#xff1a;https://arxiv.org/abs/2307.16125 SEED-Bench-2&#xff1a;https://arxiv.org/abs/2311.17092 &#x1f917; 测评数据 SEED-Bench-1&#xff1a;https://huggingface.co/datasets/AILab-CVC/SEED-Bench SEED-Bench-2&…

Tomcat-安装部署(源码包安装)

一、简介 Tomcat 是由 Apache 开发的一个 Servlet 容器&#xff0c;实现了对 Servlet 和 JSP 的支持&#xff0c;并提供了作为Web服务器的一些特有功能&#xff0c;如Tomcat管理和控制平台、安全域管理和Tomcat阀等。 简单来说&#xff0c;Tomcat是一个WEB应用程序的托管平台…

【期末复习向】长江后浪推前浪之ChatGPT概述

参考文章&#xff1a;GPT系列模型技术路径演进-CSDN博客 这篇文章讲了之前称霸NLP领域的预训练模型bert&#xff0c;它是基于预训练理念&#xff0c;采用完形填空和下一句预测任务2个预训练任务完成特征的提取。当时很多的特定领域的NLP任务&#xff08;如情感分类&#xff0c…

jenkins-Generic Webhook Trigger指定分支构建

文章目录 1 需求分析1.1 关键词 : 2、webhooks 是什么&#xff1f;3、配置步骤3.1 github 里需要的仓库配置&#xff1a;3.2 jenkins 的主要配置3.3 option filter配置用于匹配目标分支 实现指定分支构建 1 需求分析 一个项目一般会开多个分支进行开发&#xff0c;测试&#x…

Redis设计与实现之跳跃表

目录 一、跳跃表 1、跳跃表的实现 2、跳跃表的应用 3、跳跃表的时间复杂度是什么&#xff1f; 二、跳跃表有哪些应用场景&#xff1f; 三、跳跃表和其他数据结构&#xff08;如数组、链表等&#xff09;相比有什么优点和缺点&#xff1f; 四、Redis的跳跃表支持并发操作吗…

使用React实现随机颜色选择器,JS如何生成随机颜色

背景 在标签功能中&#xff0c;由于有「背景色」属性&#xff0c;每次新增标签时都为选择哪种颜色犯难。因此&#xff0c;我们思考如何通过JS代码生成随机颜色&#xff0c;提取一个通用的随机颜色生成工具&#xff0c;并基于React框架封装随机颜色选择器组件。 实际效果 原理…

智能插座是什么

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

Python:如何将MCD12Q1\MOD11A2\MOD13A2原始数据集批量输出为TIFF文件(镶嵌/重投影/)?

博客已同步微信公众号&#xff1a;GIS茄子&#xff1b;若博客出现纰漏或有更多问题交流欢迎关注GIS茄子&#xff0c;或者邮箱联系(推荐-见主页). 00 前言 之前一段时间一直使用ENVI IDL处理遥感数据&#xff0c;但是确实对于一些比较新鲜的东西IDL并没有python那么好的及时性&…

【STM32独立看门狗(IWDG) 】

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、看门狗是什么&#xff1f;1.简介2. 主要功能3.独立看门狗如何工作4.寄存器写保护5.看门狗 看门时间 二、使用步骤1.开启时钟2.初始化看门狗3.开启看门狗4.喂…