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.
 
 
 

459 lines
15 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. package dwarf
  15. // This file implements the mapping from PC to lines.
  16. // TODO: Find a way to test this properly.
  17. // http://www.dwarfstd.org/doc/DWARF4.pdf Section 6.2 page 108
  18. import (
  19. "fmt"
  20. "sort"
  21. "strings"
  22. )
  23. // PCToLine returns the file and line number corresponding to the PC value.
  24. // It returns an error if a correspondence cannot be found.
  25. func (d *Data) PCToLine(pc uint64) (file string, line uint64, err error) {
  26. c := d.pcToLineEntries
  27. if len(c) == 0 {
  28. return "", 0, fmt.Errorf("PCToLine: no line table")
  29. }
  30. i := sort.Search(len(c), func(i int) bool { return c[i].pc > pc }) - 1
  31. // c[i] is now the entry in pcToLineEntries with the largest pc that is not
  32. // larger than the query pc.
  33. // The search has failed if:
  34. // - All pcs in c were larger than the query pc (i == -1).
  35. // - c[i] marked the end of a sequence of instructions (c[i].file == 0).
  36. // - c[i] is the last element of c, and isn't the end of a sequence of
  37. // instructions, and the search pc is much larger than c[i].pc. In this
  38. // case, we don't know the range of the last instruction, but the search
  39. // pc is probably past it.
  40. if i == -1 || c[i].file == 0 || (i+1 == len(c) && pc-c[i].pc > 1024) {
  41. return "", 0, fmt.Errorf("no source line defined for PC %#x", pc)
  42. }
  43. if c[i].file >= uint64(len(d.sourceFiles)) {
  44. return "", 0, fmt.Errorf("invalid file number in DWARF data")
  45. }
  46. return d.sourceFiles[c[i].file], c[i].line, nil
  47. }
  48. // LineToBreakpointPCs returns the PCs that should be used as breakpoints
  49. // corresponding to the given file and line number.
  50. // It returns an empty slice if no PCs were found.
  51. func (d *Data) LineToBreakpointPCs(file string, line uint64) ([]uint64, error) {
  52. compDir := d.compilationDirectory()
  53. // Find the closest match in the executable for the specified file.
  54. // We choose the file with the largest number of path components matching
  55. // at the end of the name. If there is a tie, we prefer files that are
  56. // under the compilation directory. If there is still a tie, we choose
  57. // the file with the shortest name.
  58. // TODO: handle duplicate file names in the DWARF?
  59. var bestFile struct {
  60. fileNum uint64 // Index of the file in the DWARF data.
  61. components int // Number of matching path components.
  62. length int // Length of the filename.
  63. underComp bool // File is under the compilation directory.
  64. }
  65. for filenum, filename := range d.sourceFiles {
  66. c := matchingPathComponentSuffixSize(filename, file)
  67. underComp := strings.HasPrefix(filename, compDir)
  68. better := false
  69. if c != bestFile.components {
  70. better = c > bestFile.components
  71. } else if underComp != bestFile.underComp {
  72. better = underComp
  73. } else {
  74. better = len(filename) < bestFile.length
  75. }
  76. if better {
  77. bestFile.fileNum = uint64(filenum)
  78. bestFile.components = c
  79. bestFile.length = len(filename)
  80. bestFile.underComp = underComp
  81. }
  82. }
  83. if bestFile.components == 0 {
  84. return nil, fmt.Errorf("couldn't find file %q", file)
  85. }
  86. c := d.lineToPCEntries[bestFile.fileNum]
  87. // c contains all (pc, line) pairs for the appropriate file.
  88. start := sort.Search(len(c), func(i int) bool { return c[i].line >= line })
  89. end := sort.Search(len(c), func(i int) bool { return c[i].line > line })
  90. // c[i].line == line for all i in the range [start, end).
  91. pcs := make([]uint64, 0, end-start)
  92. for i := start; i < end; i++ {
  93. pcs = append(pcs, c[i].pc)
  94. }
  95. return pcs, nil
  96. }
  97. // compilationDirectory finds the first compilation unit entry in d and returns
  98. // the compilation directory contained in it.
  99. // If it fails, it returns the empty string.
  100. func (d *Data) compilationDirectory() string {
  101. r := d.Reader()
  102. for {
  103. entry, err := r.Next()
  104. if entry == nil || err != nil {
  105. return ""
  106. }
  107. if entry.Tag == TagCompileUnit {
  108. name, _ := entry.Val(AttrCompDir).(string)
  109. return name
  110. }
  111. }
  112. }
  113. // matchingPathComponentSuffixSize returns the largest n such that the last n
  114. // components of the paths p1 and p2 are equal.
  115. // e.g. matchingPathComponentSuffixSize("a/b/x/y.go", "b/a/x/y.go") returns 2.
  116. func matchingPathComponentSuffixSize(p1, p2 string) int {
  117. // TODO: deal with other path separators.
  118. c1 := strings.Split(p1, "/")
  119. c2 := strings.Split(p2, "/")
  120. min := len(c1)
  121. if len(c2) < min {
  122. min = len(c2)
  123. }
  124. var n int
  125. for n = 0; n < min; n++ {
  126. if c1[len(c1)-1-n] != c2[len(c2)-1-n] {
  127. break
  128. }
  129. }
  130. return n
  131. }
  132. // Standard opcodes. Figure 37, page 178.
  133. // If an opcode >= lineMachine.prologue.opcodeBase, it is a special
  134. // opcode rather than the opcode defined in this table.
  135. const (
  136. lineStdCopy = 0x01
  137. lineStdAdvancePC = 0x02
  138. lineStdAdvanceLine = 0x03
  139. lineStdSetFile = 0x04
  140. lineStdSetColumn = 0x05
  141. lineStdNegateStmt = 0x06
  142. lineStdSetBasicBlock = 0x07
  143. lineStdConstAddPC = 0x08
  144. lineStdFixedAdvancePC = 0x09
  145. lineStdSetPrologueEnd = 0x0a
  146. lineStdSetEpilogueBegin = 0x0b
  147. lineStdSetISA = 0x0c
  148. )
  149. // Extended opcodes. Figure 38, page 179.
  150. const (
  151. lineStartExtendedOpcode = 0x00 // Not defined as a named constant in the spec.
  152. lineExtEndSequence = 0x01
  153. lineExtSetAddress = 0x02
  154. lineExtDefineFile = 0x03
  155. lineExtSetDiscriminator = 0x04 // New in version 4.
  156. lineExtLoUser = 0x80
  157. lineExtHiUser = 0xff
  158. )
  159. // lineHeader holds the information stored in the header of the line table for a
  160. // single compilation unit.
  161. // Section 6.2.4, page 112.
  162. type lineHeader struct {
  163. unitLength int
  164. version int
  165. headerLength int
  166. minInstructionLength int
  167. maxOpsPerInstruction int
  168. defaultIsStmt bool
  169. lineBase int
  170. lineRange int
  171. opcodeBase byte
  172. stdOpcodeLengths []byte
  173. include []string // entry 0 is empty; means current directory
  174. file []lineFile // entry 0 is empty.
  175. }
  176. // lineFile represents a file name stored in the PC/line table, usually in the header.
  177. type lineFile struct {
  178. name string
  179. index int // index into include directories
  180. time int // implementation-defined time of last modification
  181. length int // length in bytes, 0 if not available.
  182. }
  183. // lineMachine holds the registers evaluated during executing of the PC/line mapping engine.
  184. // Section 6.2.2, page 109.
  185. type lineMachine struct {
  186. // The program-counter value corresponding to a machine instruction generated by the compiler.
  187. address uint64
  188. // An unsigned integer representing the index of an operation within a VLIW
  189. // instruction. The index of the first operation is 0. For non-VLIW
  190. // architectures, this register will always be 0.
  191. // The address and op_index registers, taken together, form an operation
  192. // pointer that can reference any individual operation with the instruction
  193. // stream.
  194. opIndex uint64
  195. // An unsigned integer indicating the identity of the source file corresponding to a machine instruction.
  196. file uint64
  197. // An unsigned integer indicating a source line number. Lines are numbered
  198. // beginning at 1. The compiler may emit the value 0 in cases where an
  199. // instruction cannot be attributed to any source line.
  200. line uint64
  201. // An unsigned integer indicating a column number within a source line.
  202. // Columns are numbered beginning at 1. The value 0 is reserved to indicate
  203. // that a statement begins at the “left edge” of the line.
  204. column uint64
  205. // A boolean indicating that the current instruction is a recommended
  206. // breakpoint location. A recommended breakpoint location is intended to
  207. // “represent” a line, a statement and/or a semantically distinct subpart of a
  208. // statement.
  209. isStmt bool
  210. // A boolean indicating that the current instruction is the beginning of a basic
  211. // block.
  212. basicBlock bool
  213. // A boolean indicating that the current address is that of the first byte after
  214. // the end of a sequence of target machine instructions. end_sequence
  215. // terminates a sequence of lines; therefore other information in the same
  216. // row is not meaningful.
  217. endSequence bool
  218. // A boolean indicating that the current address is one (of possibly many)
  219. // where execution should be suspended for an entry breakpoint of a
  220. // function.
  221. prologueEnd bool
  222. // A boolean indicating that the current address is one (of possibly many)
  223. // where execution should be suspended for an exit breakpoint of a function.
  224. epilogueBegin bool
  225. // An unsigned integer whose value encodes the applicable instruction set
  226. // architecture for the current instruction.
  227. // The encoding of instruction sets should be shared by all users of a given
  228. // architecture. It is recommended that this encoding be defined by the ABI
  229. // authoring committee for each architecture.
  230. isa uint64
  231. // An unsigned integer identifying the block to which the current instruction
  232. // belongs. Discriminator values are assigned arbitrarily by the DWARF
  233. // producer and serve to distinguish among multiple blocks that may all be
  234. // associated with the same source file, line, and column. Where only one
  235. // block exists for a given source position, the discriminator value should be
  236. // zero.
  237. discriminator uint64
  238. // The header for the current compilation unit.
  239. // Not an actual register, but stored here for cleanliness.
  240. header lineHeader
  241. }
  242. // parseHeader parses the header describing the compilation unit in the line
  243. // table starting at the specified offset.
  244. func (m *lineMachine) parseHeader(b *buf) error {
  245. m.header = lineHeader{}
  246. m.header.unitLength = int(b.uint32()) // Note: We are assuming 32-bit DWARF format.
  247. if m.header.unitLength > len(b.data) {
  248. return fmt.Errorf("DWARF: bad PC/line header length")
  249. }
  250. m.header.version = int(b.uint16())
  251. m.header.headerLength = int(b.uint32())
  252. m.header.minInstructionLength = int(b.uint8())
  253. if m.header.version >= 4 {
  254. m.header.maxOpsPerInstruction = int(b.uint8())
  255. } else {
  256. m.header.maxOpsPerInstruction = 1
  257. }
  258. m.header.defaultIsStmt = b.uint8() != 0
  259. m.header.lineBase = int(int8(b.uint8()))
  260. m.header.lineRange = int(b.uint8())
  261. m.header.opcodeBase = b.uint8()
  262. m.header.stdOpcodeLengths = make([]byte, m.header.opcodeBase-1)
  263. copy(m.header.stdOpcodeLengths, b.bytes(int(m.header.opcodeBase-1)))
  264. m.header.include = make([]string, 1) // First entry is empty; file index entries are 1-indexed.
  265. // Includes
  266. for {
  267. name := b.string()
  268. if name == "" {
  269. break
  270. }
  271. m.header.include = append(m.header.include, name)
  272. }
  273. // Files
  274. m.header.file = make([]lineFile, 1, 10) // entries are 1-indexed in line number program.
  275. for {
  276. name := b.string()
  277. if name == "" {
  278. break
  279. }
  280. index := b.uint()
  281. time := b.uint()
  282. length := b.uint()
  283. f := lineFile{
  284. name: name,
  285. index: int(index),
  286. time: int(time),
  287. length: int(length),
  288. }
  289. m.header.file = append(m.header.file, f)
  290. }
  291. return nil
  292. }
  293. // Special opcodes, page 117.
  294. // There are seven steps to processing special opcodes. We break them up here
  295. // because the caller needs to output a row between steps 2 and 4, and because
  296. // we need to perform just step 2 for the opcode DW_LNS_const_add_pc.
  297. func (m *lineMachine) specialOpcodeStep1(opcode byte) {
  298. adjustedOpcode := int(opcode - m.header.opcodeBase)
  299. lineAdvance := m.header.lineBase + (adjustedOpcode % m.header.lineRange)
  300. m.line += uint64(lineAdvance)
  301. }
  302. func (m *lineMachine) specialOpcodeStep2(opcode byte) {
  303. adjustedOpcode := int(opcode - m.header.opcodeBase)
  304. advance := adjustedOpcode / m.header.lineRange
  305. delta := (int(m.opIndex) + advance) / m.header.maxOpsPerInstruction
  306. m.address += uint64(m.header.minInstructionLength * delta)
  307. m.opIndex = (m.opIndex + uint64(advance)) % uint64(m.header.maxOpsPerInstruction)
  308. }
  309. func (m *lineMachine) specialOpcodeSteps4To7() {
  310. m.basicBlock = false
  311. m.prologueEnd = false
  312. m.epilogueBegin = false
  313. m.discriminator = 0
  314. }
  315. // evalCompilationUnit reads the next compilation unit and calls f at each output row.
  316. // Line machine execution continues while f returns true.
  317. func (m *lineMachine) evalCompilationUnit(b *buf, f func(m *lineMachine) (cont bool)) error {
  318. m.reset()
  319. for len(b.data) > 0 {
  320. op := b.uint8()
  321. if op >= m.header.opcodeBase {
  322. m.specialOpcodeStep1(op)
  323. m.specialOpcodeStep2(op)
  324. // Step 3 is to output a row, so we call f here.
  325. if !f(m) {
  326. return nil
  327. }
  328. m.specialOpcodeSteps4To7()
  329. continue
  330. }
  331. switch op {
  332. case lineStartExtendedOpcode:
  333. if len(b.data) == 0 {
  334. return fmt.Errorf("DWARF: short extended opcode (1)")
  335. }
  336. size := b.uint()
  337. if uint64(len(b.data)) < size {
  338. return fmt.Errorf("DWARF: short extended opcode (2)")
  339. }
  340. op = b.uint8()
  341. switch op {
  342. case lineExtEndSequence:
  343. m.endSequence = true
  344. if !f(m) {
  345. return nil
  346. }
  347. if len(b.data) == 0 {
  348. return nil
  349. }
  350. m.reset()
  351. case lineExtSetAddress:
  352. m.address = b.addr()
  353. m.opIndex = 0
  354. case lineExtDefineFile:
  355. return fmt.Errorf("DWARF: unimplemented define_file op")
  356. case lineExtSetDiscriminator:
  357. discriminator := b.uint()
  358. m.discriminator = discriminator
  359. default:
  360. return fmt.Errorf("DWARF: unknown extended opcode %#x", op)
  361. }
  362. case lineStdCopy:
  363. if !f(m) {
  364. return nil
  365. }
  366. m.discriminator = 0
  367. m.basicBlock = false
  368. m.prologueEnd = false
  369. m.epilogueBegin = false
  370. case lineStdAdvancePC:
  371. advance := b.uint()
  372. delta := (int(m.opIndex) + int(advance)) / m.header.maxOpsPerInstruction
  373. m.address += uint64(m.header.minInstructionLength * delta)
  374. m.opIndex = (m.opIndex + uint64(advance)) % uint64(m.header.maxOpsPerInstruction)
  375. m.basicBlock = false
  376. m.prologueEnd = false
  377. m.epilogueBegin = false
  378. m.discriminator = 0
  379. case lineStdAdvanceLine:
  380. advance := b.int()
  381. m.line = uint64(int64(m.line) + advance)
  382. case lineStdSetFile:
  383. index := b.uint()
  384. m.file = index
  385. case lineStdSetColumn:
  386. column := b.uint()
  387. m.column = column
  388. case lineStdNegateStmt:
  389. m.isStmt = !m.isStmt
  390. case lineStdSetBasicBlock:
  391. m.basicBlock = true
  392. case lineStdFixedAdvancePC:
  393. m.address += uint64(b.uint16())
  394. m.opIndex = 0
  395. case lineStdSetPrologueEnd:
  396. m.prologueEnd = true
  397. case lineStdSetEpilogueBegin:
  398. m.epilogueBegin = true
  399. case lineStdSetISA:
  400. m.isa = b.uint()
  401. case lineStdConstAddPC:
  402. // Update the the address and op_index registers.
  403. m.specialOpcodeStep2(255)
  404. default:
  405. panic("not reached")
  406. }
  407. }
  408. return fmt.Errorf("DWARF: unexpected end of line number information")
  409. }
  410. // reset sets the machine's registers to the initial state. Page 111.
  411. func (m *lineMachine) reset() {
  412. m.address = 0
  413. m.opIndex = 0
  414. m.file = 1
  415. m.line = 1
  416. m.column = 0
  417. m.isStmt = m.header.defaultIsStmt
  418. m.basicBlock = false
  419. m.endSequence = false
  420. m.prologueEnd = false
  421. m.epilogueBegin = false
  422. m.isa = 0
  423. m.discriminator = 0
  424. }