Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang debug using GDB?

Tags:

go

gdb

I got 2 questions about GDB + golang?

1) Go build GCC flags 

when I run "go build" , which gcc flags do the Go builder use to build a program? The build value is same as the "GOGCCFLAGS" set in the go envionment?

GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"

because I don't see any "-g" or "-g3" flags for adding code symbol. If yes, how could the symbol table be compiled ?

2) How to print a value in GDB I followed the tutorial here GDB debug go tutorial, but it seems the value is not what I set.

The value print 1, while actual is 1024

By the way, I noticed there is a post about it gdb debug go However, doesn't work for me either. the value is not what I set

like image 498
python Avatar asked Sep 02 '14 03:09

python


1 Answers

Golang now works well with GDB

Here is an example golang app gdbtest

- gdbtest/
  - main.go

Take the following example main.go

package main

import "fmt"

type MyStruct struct {
    x string
    i int
    f float64
}

func main() {
    x := "abc"
    i := 3
    fmt.Println(i)
    fmt.Println(x)

    ms := &MyStruct{
        x: "cba",
        i: 10,
        f: 11.10335,
    }
    fmt.Println(ms)
}

Save that to main.go. Then compile with the follwing gcflag flag.

go build -gcflags "-N"

Open gdb with your newly built golang app

gdb gdbtest
# or 
gdb <PROJECT_NAME>

You now have full control of gdb. For example, add a breakpoint with br <linenumber> command, then execute the app with run

(gdb) br 22
Breakpoint 1 at 0x2311: file /go/src/github.com/cevaris/gdbtest/main.go, line 22.
(gdb) run
Starting program: /go/src/github.com/cevaris/gdbtest/gdbtest
3
abc

Breakpoint 1, main.main () at /go/src/github.com/cevaris/gdbtest/main.go:22
22              fmt.Println(ms)
(gdb)

Now you can print all the local variables

(gdb) info locals
i = 3
ms = 0x20819e020
x = 0xdb1d0 "abc"

Even get access to the pointers

(gdb) p ms
$1 = (struct main.MyStruct *) 0x20819e020
(gdb) p *ms
$2 = {x = 0xdb870 "cba", i = 10, f = 11.103350000000001}
like image 170
cevaris Avatar answered Oct 11 '22 22:10

cevaris