Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast the address to a type and print it in GDB for Golang

Tags:

go

gdb

This is the piece of code:

package main

import (
    "fmt"
)

type TestType struct {
    a int
    b int
}

func main() {
    var testType TestType = TestType{1, 2}
    fmt.Println(testType)
}

And this is the gdb debug output:

(gdb) r
Starting program: /home/bzhang/common/src/go/src/test/testBinary 

Breakpoint 1, main.main () at /home/bzhang/common/src/go/src/test/main.go:14
14              fmt.Println(testType)
(gdb) p testType
$1 = {a = 1, b = 2}
(gdb) p &testType
$2 = (main.TestType *) 0xc820059ee8
(gdb) p ('main.TestType'*) 0xc820059ee8
A syntax error in expression, near `) 0xc820059ee8'.
(gdb) p ('TestType'*) 0xc820059ee8     
A syntax error in expression, near `) 0xc820059ee8'.
(gdb) whatis testType
type = main.TestType
(gdb) 

Of course I know that I can print testType directly. But if it is a local variable, sometimes its value can not be printed out directly, and only its address is available. So I want to print its value with the indication of its type. But it seems not work correctly. Appreciate for your help!

like image 968
Aaron Avatar asked Nov 30 '16 07:11

Aaron


1 Answers

The delve tool is better than gdb. https://github.com/go-delve/delve

  1. install delve
go get -u github.com/go-delve/delve/cmd/dlv
  1. move path on main.go
cd $GOPATH/src/YOUPROJECT/main.go
  1. debug delve
$GOPATH/bin/delve debug main.go
  1. break point main
Type 'help' for list of commands.
(dlv) b main.main
Breakpoint 1 set at 0x4a7bbf for main.main() main.go:12
  1. run
(dlv) c
> main.main() main.go:12 (hits goroutine(1):1 total:1) (PC: 0x4a7bbf)
     7: type TestType struct {
     8:         a int
     9:         b int
    10: }
    11:
=>  12: func main() {
    13:         var testType TestType = TestType{1, 2}
    14:         fmt.Println(testType)
    15: }
  1. break point 14 line
(dlv) b 14
Breakpoint 2 set at 0x4a7bf0 for main.main() main.go:14
  1. continue
(dlv) c
> main.main() main.go:14 (hits goroutine(1):1 total:1) (PC: 0x4a7bf0)
     9:         b int
    10: }
    11:
    12: func main() {
    13:         var testType TestType = TestType{1, 2}
=>  14:         fmt.Println(testType)
    15: }
  1. show value
(dlv) locals
testType = main.TestType {a: 1, b: 2}

Finally, using goland, vscode is more convenient for debug.

like image 60
sh.seo Avatar answered Nov 15 '22 06:11

sh.seo