在macOS上使用GDB调试Go程序

时间:2018-09-27 09:55:57

标签: go gdb

一个简单的Go程序,例如main.go

package main

func main() {
    println("hello, world!")
}

然后使用

进行构建
go build -gcflags "-N -l" -o main main.go

使用GDB:

$ gdb main
GNU gdb (GDB) 8.2
(...)
Reading symbols from main...(no debugging symbols found)...done.
Loading Go Runtime support.
(gdb) source /usr/local/Cellar/go/1.11/libexec/src/runtime/runtime-gdb.py
Loading Go Runtime support.
(gdb) info files
Symbols from "/Users/changkun/Desktop/demo/main".
Local exec file:
        `/Users/changkun/Desktop/demo/main', file type mach-o-x86-64.
        Entry point: 0x1049e20
        0x0000000001001000 - 0x000000000104dfcf is .text
        0x000000000104dfe0 - 0x0000000001077344 is __TEXT.__rodata
        (...)
(gdb) b *0x1049e20
Breakpoint 1 at 0x1049e20
(gdb)

GDB输出中没有at,Go的版本为go version go1.11 darwin/amd64,并且:

$ ls -al /usr/local/bin | grep go
lrwxr-xr-x    1 changkun  admin        24 Aug 25 16:37 go -> ../Cellar/go/1.11/bin/go

======

Linux环境中的相同过程:

docker run -itd --name golang golang:1.11
docker exec -it golang bash

然后进入容器安装gdb

root@1326d3f1a957:/# gdb main
GNU gdb (Debian 7.12-6) 7.12.0.20161007-git
(...)
(gdb) info files
Symbols from "/main".
Local exec file:
        `/main', file type elf64-x86-64.
        Entry point: 0x44a2e0
        0x0000000000401000 - 0x000000000044ea8f is .text
        (...)
(gdb) b *0x44a2e0
Breakpoint 1 at 0x44a2e0: file /usr/local/go/src/runtime/rt0_linux_amd64.s, line 8.
(gdb)

Linux能够显示(gdb) b *0x44a2e0 Breakpoint 1 at 0x44a2e0: file /usr/local/go/src/runtime/rt0_linux_amd64.s, line 8.

我在macOS中错过了什么?如何在macOS上调试和跟踪程序?

1 个答案:

答案 0 :(得分:0)

在Go 1.11中,调试信息被压缩以减小二进制大小,并且Mac上的gdb无法理解压缩的DWARF。

解决方法是还要指定-ldflags=-compressdwarf=false,该功能完全符合其要求。

通常要这样做:

export GOFLAGS="-ldflags=-compressdwarf=false"

查看讨论内容:https://groups.google.com/forum/#!topic/golang-nuts/LlgN1qpbRE8