You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

549 lines
14 KiB

  1. // Copyright 2018 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build linux
  15. package server
  16. import (
  17. "bytes"
  18. "fmt"
  19. "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/arch"
  20. "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/dwarf"
  21. )
  22. // typeAndAddress associates an address in the target with a DWARF type.
  23. type typeAndAddress struct {
  24. Type dwarf.Type
  25. Address uint64
  26. }
  27. // Routines to print a value using DWARF type descriptions.
  28. // TODO: Does this deserve its own package? It has no dependencies on Server.
  29. // A Printer pretty-prints values in the target address space.
  30. // It can be reused after each printing operation to avoid unnecessary
  31. // allocations. However, it is not safe for concurrent access.
  32. type Printer struct {
  33. err error // Sticky error value.
  34. server *Server
  35. dwarf *dwarf.Data
  36. arch *arch.Architecture
  37. printBuf bytes.Buffer // Accumulates the output.
  38. visited map[typeAndAddress]bool // Prevents looping on cyclic data.
  39. }
  40. // printf prints to printBuf.
  41. func (p *Printer) printf(format string, args ...interface{}) {
  42. fmt.Fprintf(&p.printBuf, format, args...)
  43. }
  44. // errorf prints the error to printBuf, then sets the sticky error for the
  45. // printer, if not already set.
  46. func (p *Printer) errorf(format string, args ...interface{}) {
  47. fmt.Fprintf(&p.printBuf, "<"+format+">", args...)
  48. if p.err != nil {
  49. return
  50. }
  51. p.err = fmt.Errorf(format, args...)
  52. }
  53. // NewPrinter returns a printer that can use the Server to access and print
  54. // values of the specified architecture described by the provided DWARF data.
  55. func NewPrinter(arch *arch.Architecture, dwarf *dwarf.Data, server *Server) *Printer {
  56. return &Printer{
  57. server: server,
  58. arch: arch,
  59. dwarf: dwarf,
  60. visited: make(map[typeAndAddress]bool),
  61. }
  62. }
  63. // reset resets the Printer. It must be called before starting a new
  64. // printing operation.
  65. func (p *Printer) reset() {
  66. p.err = nil
  67. p.printBuf.Reset()
  68. // Just wipe the map rather than reallocating. It's almost always tiny.
  69. for k := range p.visited {
  70. delete(p.visited, k)
  71. }
  72. }
  73. // Sprint returns the pretty-printed value of the item with the given name, such as "main.global".
  74. func (p *Printer) Sprint(name string) (string, error) {
  75. entry, err := p.dwarf.LookupEntry(name)
  76. if err != nil {
  77. return "", err
  78. }
  79. p.reset()
  80. switch entry.Tag {
  81. case dwarf.TagVariable: // TODO: What other entries have global location attributes?
  82. var a uint64
  83. iface := entry.Val(dwarf.AttrLocation)
  84. if iface != nil {
  85. a = p.decodeLocation(iface.([]byte))
  86. }
  87. p.printEntryValueAt(entry, a)
  88. default:
  89. p.errorf("unrecognized entry type %s", entry.Tag)
  90. }
  91. return p.printBuf.String(), p.err
  92. }
  93. // Figure 24 of DWARF v4.
  94. const (
  95. locationAddr = 0x03
  96. )
  97. // decodeLocation decodes the dwarf data describing an address.
  98. func (p *Printer) decodeLocation(data []byte) uint64 {
  99. switch data[0] {
  100. case locationAddr:
  101. return p.arch.Uintptr(data[1:])
  102. default:
  103. p.errorf("unimplemented location type %#x", data[0])
  104. }
  105. return 0
  106. }
  107. // SprintEntry returns the pretty-printed value of the item with the specified DWARF Entry and address.
  108. func (p *Printer) SprintEntry(entry *dwarf.Entry, a uint64) (string, error) {
  109. p.reset()
  110. p.printEntryValueAt(entry, a)
  111. return p.printBuf.String(), p.err
  112. }
  113. // printEntryValueAt pretty-prints the data at the specified address.
  114. // using the type information in the Entry.
  115. func (p *Printer) printEntryValueAt(entry *dwarf.Entry, a uint64) {
  116. if a == 0 {
  117. p.printf("<nil>")
  118. return
  119. }
  120. switch entry.Tag {
  121. case dwarf.TagVariable, dwarf.TagFormalParameter:
  122. // OK
  123. default:
  124. p.errorf("unrecognized entry type %s", entry.Tag)
  125. return
  126. }
  127. iface := entry.Val(dwarf.AttrType)
  128. if iface == nil {
  129. p.errorf("no type")
  130. return
  131. }
  132. typ, err := p.dwarf.Type(iface.(dwarf.Offset))
  133. if err != nil {
  134. p.errorf("type lookup: %v", err)
  135. return
  136. }
  137. p.printValueAt(typ, a)
  138. }
  139. // printValueAt pretty-prints the data at the specified address.
  140. // using the provided type information.
  141. func (p *Printer) printValueAt(typ dwarf.Type, a uint64) {
  142. if a != 0 {
  143. // Check if we are repeating the same type and address.
  144. ta := typeAndAddress{typ, a}
  145. if p.visited[ta] {
  146. p.printf("(%v %#x)", typ, a)
  147. return
  148. }
  149. p.visited[ta] = true
  150. }
  151. switch typ := typ.(type) {
  152. case *dwarf.BoolType:
  153. if typ.ByteSize != 1 {
  154. p.errorf("unrecognized bool size %d", typ.ByteSize)
  155. return
  156. }
  157. if b, err := p.server.peekUint8(a); err != nil {
  158. p.errorf("reading bool: %s", err)
  159. } else {
  160. p.printf("%t", b != 0)
  161. }
  162. case *dwarf.PtrType:
  163. if ptr, err := p.server.peekPtr(a); err != nil {
  164. p.errorf("reading pointer: %s", err)
  165. } else {
  166. p.printf("%#x", ptr)
  167. }
  168. case *dwarf.IntType:
  169. // Sad we can't tell a rune from an int32.
  170. if i, err := p.server.peekInt(a, typ.ByteSize); err != nil {
  171. p.errorf("reading integer: %s", err)
  172. } else {
  173. p.printf("%d", i)
  174. }
  175. case *dwarf.UintType:
  176. if u, err := p.server.peekUint(a, typ.ByteSize); err != nil {
  177. p.errorf("reading unsigned integer: %s", err)
  178. } else {
  179. p.printf("%d", u)
  180. }
  181. case *dwarf.FloatType:
  182. buf := make([]byte, typ.ByteSize)
  183. if err := p.server.peekBytes(a, buf); err != nil {
  184. p.errorf("reading float: %s", err)
  185. return
  186. }
  187. switch typ.ByteSize {
  188. case 4:
  189. p.printf("%g", p.arch.Float32(buf))
  190. case 8:
  191. p.printf("%g", p.arch.Float64(buf))
  192. default:
  193. p.errorf("unrecognized float size %d", typ.ByteSize)
  194. }
  195. case *dwarf.ComplexType:
  196. buf := make([]byte, typ.ByteSize)
  197. if err := p.server.peekBytes(a, buf); err != nil {
  198. p.errorf("reading complex: %s", err)
  199. return
  200. }
  201. switch typ.ByteSize {
  202. case 8:
  203. p.printf("%g", p.arch.Complex64(buf))
  204. case 16:
  205. p.printf("%g", p.arch.Complex128(buf))
  206. default:
  207. p.errorf("unrecognized complex size %d", typ.ByteSize)
  208. }
  209. case *dwarf.StructType:
  210. if typ.Kind != "struct" {
  211. // Could be "class" or "union".
  212. p.errorf("can't handle struct type %s", typ.Kind)
  213. return
  214. }
  215. p.printf("%s {", typ.String())
  216. for i, field := range typ.Field {
  217. if i != 0 {
  218. p.printf(", ")
  219. }
  220. p.printValueAt(field.Type, a+uint64(field.ByteOffset))
  221. }
  222. p.printf("}")
  223. case *dwarf.ArrayType:
  224. p.printArrayAt(typ, a)
  225. case *dwarf.InterfaceType:
  226. p.printInterfaceAt(typ, a)
  227. case *dwarf.MapType:
  228. p.printMapAt(typ, a)
  229. case *dwarf.ChanType:
  230. p.printChannelAt(typ, a)
  231. case *dwarf.SliceType:
  232. p.printSliceAt(typ, a)
  233. case *dwarf.StringType:
  234. p.printStringAt(typ, a)
  235. case *dwarf.TypedefType:
  236. p.printValueAt(typ.Type, a)
  237. case *dwarf.FuncType:
  238. p.printf("%v @%#x ", typ, a)
  239. case *dwarf.VoidType:
  240. p.printf("void")
  241. default:
  242. p.errorf("unimplemented type %v", typ)
  243. }
  244. }
  245. func (p *Printer) printArrayAt(typ *dwarf.ArrayType, a uint64) {
  246. elemType := typ.Type
  247. length := typ.Count
  248. stride, ok := p.arrayStride(typ)
  249. if !ok {
  250. p.errorf("can't determine element size")
  251. }
  252. p.printf("%s{", typ)
  253. n := length
  254. if n > 100 {
  255. n = 100 // TODO: Have a way to control this?
  256. }
  257. for i := int64(0); i < n; i++ {
  258. if i != 0 {
  259. p.printf(", ")
  260. }
  261. p.printValueAt(elemType, a)
  262. a += stride // TODO: Alignment and padding - not given by Type
  263. }
  264. if n < length {
  265. p.printf(", ...")
  266. }
  267. p.printf("}")
  268. }
  269. func (p *Printer) printInterfaceAt(t *dwarf.InterfaceType, a uint64) {
  270. // t embeds a TypedefType, which may point to another typedef.
  271. // The underlying type should be a struct.
  272. st, ok := followTypedefs(&t.TypedefType).(*dwarf.StructType)
  273. if !ok {
  274. p.errorf("bad interface type: not a struct")
  275. return
  276. }
  277. p.printf("(")
  278. tab, err := p.server.peekPtrStructField(st, a, "tab")
  279. if err != nil {
  280. p.errorf("reading interface type: %s", err)
  281. } else {
  282. f, err := getField(st, "tab")
  283. if err != nil {
  284. p.errorf("%s", err)
  285. } else {
  286. p.printTypeOfInterface(f.Type, tab)
  287. }
  288. }
  289. p.printf(", ")
  290. data, err := p.server.peekPtrStructField(st, a, "data")
  291. if err != nil {
  292. p.errorf("reading interface value: %s", err)
  293. } else if data == 0 {
  294. p.printf("<nil>")
  295. } else {
  296. p.printf("%#x", data)
  297. }
  298. p.printf(")")
  299. }
  300. // printTypeOfInterface prints the type of the given tab pointer.
  301. func (p *Printer) printTypeOfInterface(t dwarf.Type, a uint64) {
  302. if a == 0 {
  303. p.printf("<nil>")
  304. return
  305. }
  306. // t should be a pointer to a struct containing _type, which is a pointer to a
  307. // struct containing _string, which is the name of the type.
  308. // Depending on the compiler version, some of these types can be typedefs, and
  309. // _string may be a string or a *string.
  310. t1, ok := followTypedefs(t).(*dwarf.PtrType)
  311. if !ok {
  312. p.errorf("interface's tab is not a pointer")
  313. return
  314. }
  315. t2, ok := followTypedefs(t1.Type).(*dwarf.StructType)
  316. if !ok {
  317. p.errorf("interface's tab is not a pointer to struct")
  318. return
  319. }
  320. typeField, err := getField(t2, "_type")
  321. if err != nil {
  322. p.errorf("%s", err)
  323. return
  324. }
  325. t3, ok := followTypedefs(typeField.Type).(*dwarf.PtrType)
  326. if !ok {
  327. p.errorf("interface's _type is not a pointer")
  328. return
  329. }
  330. t4, ok := followTypedefs(t3.Type).(*dwarf.StructType)
  331. if !ok {
  332. p.errorf("interface's _type is not a pointer to struct")
  333. return
  334. }
  335. stringField, err := getField(t4, "_string")
  336. if err != nil {
  337. p.errorf("%s", err)
  338. return
  339. }
  340. if t5, ok := stringField.Type.(*dwarf.PtrType); ok {
  341. stringType, ok := t5.Type.(*dwarf.StringType)
  342. if !ok {
  343. p.errorf("interface _string is a pointer to %T, want string or *string", t5.Type)
  344. return
  345. }
  346. typeAddr, err := p.server.peekPtrStructField(t2, a, "_type")
  347. if err != nil {
  348. p.errorf("reading interface type: %s", err)
  349. return
  350. }
  351. stringAddr, err := p.server.peekPtrStructField(t4, typeAddr, "_string")
  352. if err != nil {
  353. p.errorf("reading interface type: %s", err)
  354. return
  355. }
  356. p.printStringAt(stringType, stringAddr)
  357. } else {
  358. stringType, ok := stringField.Type.(*dwarf.StringType)
  359. if !ok {
  360. p.errorf("interface _string is a %T, want string or *string", stringField.Type)
  361. return
  362. }
  363. typeAddr, err := p.server.peekPtrStructField(t2, a, "_type")
  364. if err != nil {
  365. p.errorf("reading interface type: %s", err)
  366. return
  367. }
  368. stringAddr := typeAddr + uint64(stringField.ByteOffset)
  369. p.printStringAt(stringType, stringAddr)
  370. }
  371. }
  372. // maxMapValuesToPrint values are printed for each map; any remaining values are
  373. // truncated to "...".
  374. const maxMapValuesToPrint = 8
  375. func (p *Printer) printMapAt(typ *dwarf.MapType, a uint64) {
  376. count := 0
  377. fn := func(keyAddr, valAddr uint64, keyType, valType dwarf.Type) (stop bool) {
  378. count++
  379. if count > maxMapValuesToPrint {
  380. return false
  381. }
  382. if count > 1 {
  383. p.printf(" ")
  384. }
  385. p.printValueAt(keyType, keyAddr)
  386. p.printf(":")
  387. p.printValueAt(valType, valAddr)
  388. return true
  389. }
  390. p.printf("map[")
  391. if err := p.server.peekMapValues(typ, a, fn); err != nil {
  392. p.errorf("reading map values: %s", err)
  393. }
  394. if count > maxMapValuesToPrint {
  395. p.printf(" ...")
  396. }
  397. p.printf("]")
  398. }
  399. func (p *Printer) printChannelAt(ct *dwarf.ChanType, a uint64) {
  400. p.printf("(chan %s ", ct.ElemType)
  401. defer p.printf(")")
  402. a, err := p.server.peekPtr(a)
  403. if err != nil {
  404. p.errorf("reading channel: %s", err)
  405. return
  406. }
  407. if a == 0 {
  408. p.printf("<nil>")
  409. return
  410. }
  411. p.printf("%#x", a)
  412. // ct is a typedef for a pointer to a struct.
  413. pt, ok := ct.TypedefType.Type.(*dwarf.PtrType)
  414. if !ok {
  415. p.errorf("bad channel type: not a pointer")
  416. return
  417. }
  418. st, ok := pt.Type.(*dwarf.StructType)
  419. if !ok {
  420. p.errorf("bad channel type: not a pointer to a struct")
  421. return
  422. }
  423. // Print the channel buffer's length (qcount) and capacity (dataqsiz),
  424. // if not 0/0.
  425. qcount, err := p.server.peekUintOrIntStructField(st, a, "qcount")
  426. if err != nil {
  427. p.errorf("reading channel: %s", err)
  428. return
  429. }
  430. dataqsiz, err := p.server.peekUintOrIntStructField(st, a, "dataqsiz")
  431. if err != nil {
  432. p.errorf("reading channel: %s", err)
  433. return
  434. }
  435. if qcount != 0 || dataqsiz != 0 {
  436. p.printf(" [%d/%d]", qcount, dataqsiz)
  437. }
  438. }
  439. func (p *Printer) printSliceAt(typ *dwarf.SliceType, a uint64) {
  440. // Slices look like a struct with fields array *elemtype, len uint32/64, cap uint32/64.
  441. // BUG: Slice header appears to have fields with ByteSize == 0
  442. ptr, err := p.server.peekPtrStructField(&typ.StructType, a, "array")
  443. if err != nil {
  444. p.errorf("reading slice: %s", err)
  445. return
  446. }
  447. length, err := p.server.peekUintOrIntStructField(&typ.StructType, a, "len")
  448. if err != nil {
  449. p.errorf("reading slice: %s", err)
  450. return
  451. }
  452. // Capacity is not used yet.
  453. _, err = p.server.peekUintOrIntStructField(&typ.StructType, a, "cap")
  454. if err != nil {
  455. p.errorf("reading slice: %s", err)
  456. return
  457. }
  458. elemType := typ.ElemType
  459. size, ok := p.sizeof(typ.ElemType)
  460. if !ok {
  461. p.errorf("can't determine element size")
  462. }
  463. p.printf("%s{", typ)
  464. for i := uint64(0); i < length; i++ {
  465. if i != 0 {
  466. p.printf(", ")
  467. }
  468. p.printValueAt(elemType, ptr)
  469. ptr += size // TODO: Alignment and padding - not given by Type
  470. }
  471. p.printf("}")
  472. }
  473. func (p *Printer) printStringAt(typ *dwarf.StringType, a uint64) {
  474. const maxStringSize = 100
  475. if s, err := p.server.peekString(typ, a, maxStringSize); err != nil {
  476. p.errorf("reading string: %s", err)
  477. } else {
  478. p.printf("%q", s)
  479. }
  480. }
  481. // sizeof returns the byte size of the type.
  482. func (p *Printer) sizeof(typ dwarf.Type) (uint64, bool) {
  483. size := typ.Size() // Will be -1 if ByteSize is not set.
  484. if size >= 0 {
  485. return uint64(size), true
  486. }
  487. switch typ.(type) {
  488. case *dwarf.PtrType:
  489. // This is the only one we know of, but more may arise.
  490. return uint64(p.arch.PointerSize), true
  491. }
  492. return 0, false
  493. }
  494. // arrayStride returns the stride of a dwarf.ArrayType in bytes.
  495. func (p *Printer) arrayStride(t *dwarf.ArrayType) (uint64, bool) {
  496. stride := t.StrideBitSize
  497. if stride > 0 {
  498. return uint64(stride / 8), true
  499. }
  500. return p.sizeof(t.Type)
  501. }
  502. // getField finds the *dwarf.StructField in a dwarf.StructType with name fieldName.
  503. func getField(t *dwarf.StructType, fieldName string) (*dwarf.StructField, error) {
  504. var r *dwarf.StructField
  505. for _, f := range t.Field {
  506. if f.Name == fieldName {
  507. if r != nil {
  508. return nil, fmt.Errorf("struct definition repeats field %s", fieldName)
  509. }
  510. r = f
  511. }
  512. }
  513. if r == nil {
  514. return nil, fmt.Errorf("struct field %s missing", fieldName)
  515. }
  516. return r, nil
  517. }