Açıklama Yok

binutils.go 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Copyright 2014 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 binutils provides access to the GNU binutils.
  15. package binutils
  16. import (
  17. "debug/elf"
  18. "fmt"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "regexp"
  23. "strings"
  24. "github.com/google/pprof/internal/elfexec"
  25. "github.com/google/pprof/internal/plugin"
  26. )
  27. // A Binutils implements plugin.ObjTool by invoking the GNU binutils.
  28. // SetConfig must be called before any of the other methods.
  29. type Binutils struct {
  30. // Commands to invoke.
  31. llvmSymbolizer string
  32. addr2line string
  33. nm string
  34. objdump string
  35. // if fast, perform symbolization using nm (symbol names only),
  36. // instead of file-line detail from the slower addr2line.
  37. fast bool
  38. }
  39. // SetFastSymbolization sets a toggle that makes binutils use fast
  40. // symbolization (using nm), which is much faster than addr2line but
  41. // provides only symbol name information (no file/line).
  42. func (b *Binutils) SetFastSymbolization(fast bool) {
  43. b.fast = fast
  44. }
  45. // SetTools processes the contents of the tools option. It
  46. // expects a set of entries separated by commas; each entry is a pair
  47. // of the form t:path, where cmd will be used to look only for the
  48. // tool named t. If t is not specified, the path is searched for all
  49. // tools.
  50. func (b *Binutils) SetTools(config string) {
  51. // paths collect paths per tool; Key "" contains the default.
  52. paths := make(map[string][]string)
  53. for _, t := range strings.Split(config, ",") {
  54. name, path := "", t
  55. if ct := strings.SplitN(t, ":", 2); len(ct) == 2 {
  56. name, path = ct[0], ct[1]
  57. }
  58. paths[name] = append(paths[name], path)
  59. }
  60. defaultPath := paths[""]
  61. b.llvmSymbolizer = findExe("llvm-symbolizer", append(paths["llvm-symbolizer"], defaultPath...))
  62. b.addr2line = findExe("addr2line", append(paths["addr2line"], defaultPath...))
  63. b.nm = findExe("nm", append(paths["nm"], defaultPath...))
  64. b.objdump = findExe("objdump", append(paths["objdump"], defaultPath...))
  65. }
  66. // findExe looks for an executable command on a set of paths.
  67. // If it cannot find it, returns cmd.
  68. func findExe(cmd string, paths []string) string {
  69. for _, p := range paths {
  70. cp := filepath.Join(p, cmd)
  71. if c, err := exec.LookPath(cp); err == nil {
  72. return c
  73. }
  74. }
  75. return cmd
  76. }
  77. // Disasm returns the assembly instructions for the specified address range
  78. // of a binary.
  79. func (b *Binutils) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
  80. if b.addr2line == "" {
  81. // Update the command invocations if not initialized.
  82. b.SetTools("")
  83. }
  84. cmd := exec.Command(b.objdump, "-d", "-C", "--no-show-raw-insn", "-l",
  85. fmt.Sprintf("--start-address=%#x", start),
  86. fmt.Sprintf("--stop-address=%#x", end),
  87. file)
  88. out, err := cmd.Output()
  89. if err != nil {
  90. return nil, fmt.Errorf("%v: %v", cmd.Args, err)
  91. }
  92. return disassemble(out)
  93. }
  94. // Open satisfies the plugin.ObjTool interface.
  95. func (b *Binutils) Open(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
  96. if b.addr2line == "" {
  97. // Update the command invocations if not initialized.
  98. b.SetTools("")
  99. }
  100. // Make sure file is a supported executable.
  101. // The pprof driver uses Open to sniff the difference
  102. // between an executable and a profile.
  103. // For now, only ELF is supported.
  104. // Could read the first few bytes of the file and
  105. // use a table of prefixes if we need to support other
  106. // systems at some point.
  107. f, err := os.Open(name)
  108. if err != nil {
  109. // For testing, do not require file name to exist.
  110. if strings.Contains(b.addr2line, "testdata/") {
  111. return &fileAddr2Line{file: file{b: b, name: name}}, nil
  112. }
  113. return nil, err
  114. }
  115. defer f.Close()
  116. ef, err := elf.NewFile(f)
  117. if err != nil {
  118. return nil, fmt.Errorf("Parsing %s: %v", name, err)
  119. }
  120. var stextOffset *uint64
  121. var pageAligned = func(addr uint64) bool { return addr%4096 == 0 }
  122. if strings.Contains(name, "vmlinux") || !pageAligned(start) || !pageAligned(limit) || !pageAligned(offset) {
  123. // Reading all Symbols is expensive, and we only rarely need it so
  124. // we don't want to do it every time. But if _stext happens to be
  125. // page-aligned but isn't the same as Vaddr, we would symbolize
  126. // wrong. So if the name the addresses aren't page aligned, or if
  127. // the name is "vmlinux" we read _stext. We can be wrong if: (1)
  128. // someone passes a kernel path that doesn't contain "vmlinux" AND
  129. // (2) _stext is page-aligned AND (3) _stext is not at Vaddr
  130. symbols, err := ef.Symbols()
  131. if err != nil {
  132. return nil, err
  133. }
  134. for _, s := range symbols {
  135. if s.Name == "_stext" {
  136. // The kernel may use _stext as the mapping start address.
  137. stextOffset = &s.Value
  138. break
  139. }
  140. }
  141. }
  142. base, err := elfexec.GetBase(&ef.FileHeader, nil, stextOffset, start, limit, offset)
  143. if err != nil {
  144. return nil, fmt.Errorf("Could not identify base for %s: %v", name, err)
  145. }
  146. // Find build ID, while we have the file open.
  147. buildID := ""
  148. if id, err := elfexec.GetBuildID(f); err == nil {
  149. buildID = fmt.Sprintf("%x", id)
  150. }
  151. if b.fast {
  152. return &fileNM{file: file{b, name, base, buildID}}, nil
  153. }
  154. return &fileAddr2Line{file: file{b, name, base, buildID}}, nil
  155. }
  156. // file implements the binutils.ObjFile interface.
  157. type file struct {
  158. b *Binutils
  159. name string
  160. base uint64
  161. buildID string
  162. }
  163. func (f *file) Name() string {
  164. return f.name
  165. }
  166. func (f *file) Base() uint64 {
  167. return f.base
  168. }
  169. func (f *file) BuildID() string {
  170. return f.buildID
  171. }
  172. func (f *file) SourceLine(addr uint64) ([]plugin.Frame, error) {
  173. return []plugin.Frame{}, nil
  174. }
  175. func (f *file) Close() error {
  176. return nil
  177. }
  178. func (f *file) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
  179. // Get from nm a list of symbols sorted by address.
  180. cmd := exec.Command(f.b.nm, "-n", f.name)
  181. out, err := cmd.Output()
  182. if err != nil {
  183. return nil, fmt.Errorf("%v: %v", cmd.Args, err)
  184. }
  185. return findSymbols(out, f.name, r, addr)
  186. }
  187. // fileNM implements the binutils.ObjFile interface, using 'nm' to map
  188. // addresses to symbols (without file/line number information). It is
  189. // faster than fileAddr2Line.
  190. type fileNM struct {
  191. file
  192. addr2linernm *addr2LinerNM
  193. }
  194. func (f *fileNM) SourceLine(addr uint64) ([]plugin.Frame, error) {
  195. if f.addr2linernm == nil {
  196. addr2liner, err := newAddr2LinerNM(f.b.nm, f.name, f.base)
  197. if err != nil {
  198. return nil, err
  199. }
  200. f.addr2linernm = addr2liner
  201. }
  202. return f.addr2linernm.addrInfo(addr)
  203. }
  204. // fileAddr2Line implements the binutils.ObjFile interface, using
  205. // 'addr2line' to map addresses to symbols (with file/line number
  206. // information). It can be slow for large binaries with debug
  207. // information.
  208. type fileAddr2Line struct {
  209. file
  210. addr2liner *addr2Liner
  211. llvmSymbolizer *llvmSymbolizer
  212. }
  213. func (f *fileAddr2Line) SourceLine(addr uint64) ([]plugin.Frame, error) {
  214. if f.llvmSymbolizer != nil {
  215. return f.llvmSymbolizer.addrInfo(addr)
  216. }
  217. if f.addr2liner != nil {
  218. return f.addr2liner.addrInfo(addr)
  219. }
  220. if llvmSymbolizer, err := newLLVMSymbolizer(f.b.llvmSymbolizer, f.name, f.base); err == nil {
  221. f.llvmSymbolizer = llvmSymbolizer
  222. return f.llvmSymbolizer.addrInfo(addr)
  223. }
  224. if addr2liner, err := newAddr2Liner(f.b.addr2line, f.name, f.base); err == nil {
  225. f.addr2liner = addr2liner
  226. // When addr2line encounters some gcc compiled binaries, it
  227. // drops interesting parts of names in anonymous namespaces.
  228. // Fallback to NM for better function names.
  229. if nm, err := newAddr2LinerNM(f.b.nm, f.name, f.base); err == nil {
  230. f.addr2liner.nm = nm
  231. }
  232. return f.addr2liner.addrInfo(addr)
  233. }
  234. return nil, fmt.Errorf("could not find local addr2liner")
  235. }
  236. func (f *fileAddr2Line) Close() error {
  237. if f.addr2liner != nil {
  238. f.addr2liner.rw.close()
  239. f.addr2liner = nil
  240. }
  241. return nil
  242. }