暂无描述

binutils.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. "debug/macho"
  19. "fmt"
  20. "os"
  21. "os/exec"
  22. "path/filepath"
  23. "regexp"
  24. "strings"
  25. "sync"
  26. "github.com/google/pprof/internal/elfexec"
  27. "github.com/google/pprof/internal/plugin"
  28. )
  29. // A Binutils implements plugin.ObjTool by invoking the GNU binutils.
  30. type Binutils struct {
  31. mu sync.Mutex
  32. rep *binrep
  33. }
  34. // binrep is an immutable representation for Binutils. It is atomically
  35. // replaced on every mutation to provide thread-safe access.
  36. type binrep struct {
  37. // Commands to invoke.
  38. llvmSymbolizer string
  39. llvmSymbolizerFound bool
  40. addr2line string
  41. addr2lineFound bool
  42. nm string
  43. nmFound bool
  44. objdump string
  45. objdumpFound bool
  46. // if fast, perform symbolization using nm (symbol names only),
  47. // instead of file-line detail from the slower addr2line.
  48. fast bool
  49. }
  50. // get returns the current representation for bu, initializing it if necessary.
  51. func (bu *Binutils) get() *binrep {
  52. bu.mu.Lock()
  53. r := bu.rep
  54. if r == nil {
  55. r = &binrep{}
  56. initTools(r, "")
  57. bu.rep = r
  58. }
  59. bu.mu.Unlock()
  60. return r
  61. }
  62. // update modifies the rep for bu via the supplied function.
  63. func (bu *Binutils) update(fn func(r *binrep)) {
  64. r := &binrep{}
  65. bu.mu.Lock()
  66. defer bu.mu.Unlock()
  67. if bu.rep == nil {
  68. initTools(r, "")
  69. } else {
  70. *r = *bu.rep
  71. }
  72. fn(r)
  73. bu.rep = r
  74. }
  75. // SetFastSymbolization sets a toggle that makes binutils use fast
  76. // symbolization (using nm), which is much faster than addr2line but
  77. // provides only symbol name information (no file/line).
  78. func (bu *Binutils) SetFastSymbolization(fast bool) {
  79. bu.update(func(r *binrep) { r.fast = fast })
  80. }
  81. // SetTools processes the contents of the tools option. It
  82. // expects a set of entries separated by commas; each entry is a pair
  83. // of the form t:path, where cmd will be used to look only for the
  84. // tool named t. If t is not specified, the path is searched for all
  85. // tools.
  86. func (bu *Binutils) SetTools(config string) {
  87. bu.update(func(r *binrep) { initTools(r, config) })
  88. }
  89. func initTools(b *binrep, config string) {
  90. // paths collect paths per tool; Key "" contains the default.
  91. paths := make(map[string][]string)
  92. for _, t := range strings.Split(config, ",") {
  93. name, path := "", t
  94. if ct := strings.SplitN(t, ":", 2); len(ct) == 2 {
  95. name, path = ct[0], ct[1]
  96. }
  97. paths[name] = append(paths[name], path)
  98. }
  99. defaultPath := paths[""]
  100. b.llvmSymbolizer, b.llvmSymbolizerFound = findExe("llvm-symbolizer", append(paths["llvm-symbolizer"], defaultPath...))
  101. b.addr2line, b.addr2lineFound = findExe("addr2line", append(paths["addr2line"], defaultPath...))
  102. b.nm, b.nmFound = findExe("nm", append(paths["nm"], defaultPath...))
  103. b.objdump, b.objdumpFound = findExe("objdump", append(paths["objdump"], defaultPath...))
  104. }
  105. // findExe looks for an executable command on a set of paths.
  106. // If it cannot find it, returns cmd.
  107. func findExe(cmd string, paths []string) (string, bool) {
  108. for _, p := range paths {
  109. cp := filepath.Join(p, cmd)
  110. if c, err := exec.LookPath(cp); err == nil {
  111. return c, true
  112. }
  113. }
  114. return cmd, false
  115. }
  116. // Disasm returns the assembly instructions for the specified address range
  117. // of a binary.
  118. func (bu *Binutils) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
  119. b := bu.get()
  120. cmd := exec.Command(b.objdump, "-d", "-C", "--no-show-raw-insn", "-l",
  121. fmt.Sprintf("--start-address=%#x", start),
  122. fmt.Sprintf("--stop-address=%#x", end),
  123. file)
  124. out, err := cmd.Output()
  125. if err != nil {
  126. return nil, fmt.Errorf("%v: %v", cmd.Args, err)
  127. }
  128. return disassemble(out)
  129. }
  130. // Open satisfies the plugin.ObjTool interface.
  131. func (bu *Binutils) Open(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
  132. b := bu.get()
  133. // Make sure file is a supported executable.
  134. // The pprof driver uses Open to sniff the difference
  135. // between an executable and a profile.
  136. // For now, only ELF is supported.
  137. // Could read the first few bytes of the file and
  138. // use a table of prefixes if we need to support other
  139. // systems at some point.
  140. if _, err := os.Stat(name); err != nil {
  141. // For testing, do not require file name to exist.
  142. if strings.Contains(b.addr2line, "testdata/") {
  143. return &fileAddr2Line{file: file{b: b, name: name}}, nil
  144. }
  145. return nil, err
  146. }
  147. if f, err := b.openELF(name, start, limit, offset); err == nil {
  148. return f, nil
  149. }
  150. if f, err := b.openMachO(name, start, limit, offset); err == nil {
  151. return f, nil
  152. }
  153. return nil, fmt.Errorf("unrecognized binary: %s", name)
  154. }
  155. func (b *binrep) openMachO(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
  156. of, err := macho.Open(name)
  157. if err != nil {
  158. return nil, fmt.Errorf("error parsing %s: %v", name, err)
  159. }
  160. defer of.Close()
  161. // Subtract the load address of the __TEXT section. Usually 0 for shared
  162. // libraries or 0x100000000 for executables. You can check this value by
  163. // running `objdump -private-headers <file>`.
  164. textSegment := of.Segment("__TEXT")
  165. if textSegment == nil {
  166. return nil, fmt.Errorf("could not identify base for %s: no __TEXT segment", name)
  167. }
  168. if textSegment.Addr > start {
  169. return nil, fmt.Errorf("could not identify base for %s: __TEXT segment address (0x%x) > mapping start address (0x%x)",
  170. name, textSegment.Addr, start)
  171. }
  172. base := start - textSegment.Addr
  173. if b.fast || (!b.addr2lineFound && !b.llvmSymbolizerFound) {
  174. return &fileNM{file: file{b: b, name: name, base: base}}, nil
  175. }
  176. return &fileAddr2Line{file: file{b: b, name: name, base: base}}, nil
  177. }
  178. func (b *binrep) openELF(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
  179. ef, err := elf.Open(name)
  180. if err != nil {
  181. return nil, fmt.Errorf("error parsing %s: %v", name, err)
  182. }
  183. defer ef.Close()
  184. var stextOffset *uint64
  185. var pageAligned = func(addr uint64) bool { return addr%4096 == 0 }
  186. if strings.Contains(name, "vmlinux") || !pageAligned(start) || !pageAligned(limit) || !pageAligned(offset) {
  187. // Reading all Symbols is expensive, and we only rarely need it so
  188. // we don't want to do it every time. But if _stext happens to be
  189. // page-aligned but isn't the same as Vaddr, we would symbolize
  190. // wrong. So if the name the addresses aren't page aligned, or if
  191. // the name is "vmlinux" we read _stext. We can be wrong if: (1)
  192. // someone passes a kernel path that doesn't contain "vmlinux" AND
  193. // (2) _stext is page-aligned AND (3) _stext is not at Vaddr
  194. symbols, err := ef.Symbols()
  195. if err != nil {
  196. return nil, err
  197. }
  198. for _, s := range symbols {
  199. if s.Name == "_stext" {
  200. // The kernel may use _stext as the mapping start address.
  201. stextOffset = &s.Value
  202. break
  203. }
  204. }
  205. }
  206. base, err := elfexec.GetBase(&ef.FileHeader, elfexec.FindTextProgHeader(ef), stextOffset, start, limit, offset)
  207. if err != nil {
  208. return nil, fmt.Errorf("could not identify base for %s: %v", name, err)
  209. }
  210. buildID := ""
  211. if f, err := os.Open(name); err == nil {
  212. if id, err := elfexec.GetBuildID(f); err == nil {
  213. buildID = fmt.Sprintf("%x", id)
  214. }
  215. }
  216. if b.fast || (!b.addr2lineFound && !b.llvmSymbolizerFound) {
  217. return &fileNM{file: file{b, name, base, buildID}}, nil
  218. }
  219. return &fileAddr2Line{file: file{b, name, base, buildID}}, nil
  220. }
  221. // file implements the binutils.ObjFile interface.
  222. type file struct {
  223. b *binrep
  224. name string
  225. base uint64
  226. buildID string
  227. }
  228. func (f *file) Name() string {
  229. return f.name
  230. }
  231. func (f *file) Base() uint64 {
  232. return f.base
  233. }
  234. func (f *file) BuildID() string {
  235. return f.buildID
  236. }
  237. func (f *file) SourceLine(addr uint64) ([]plugin.Frame, error) {
  238. return []plugin.Frame{}, nil
  239. }
  240. func (f *file) Close() error {
  241. return nil
  242. }
  243. func (f *file) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
  244. // Get from nm a list of symbols sorted by address.
  245. cmd := exec.Command(f.b.nm, "-n", f.name)
  246. out, err := cmd.Output()
  247. if err != nil {
  248. return nil, fmt.Errorf("%v: %v", cmd.Args, err)
  249. }
  250. return findSymbols(out, f.name, r, addr)
  251. }
  252. // fileNM implements the binutils.ObjFile interface, using 'nm' to map
  253. // addresses to symbols (without file/line number information). It is
  254. // faster than fileAddr2Line.
  255. type fileNM struct {
  256. file
  257. addr2linernm *addr2LinerNM
  258. }
  259. func (f *fileNM) SourceLine(addr uint64) ([]plugin.Frame, error) {
  260. if f.addr2linernm == nil {
  261. addr2liner, err := newAddr2LinerNM(f.b.nm, f.name, f.base)
  262. if err != nil {
  263. return nil, err
  264. }
  265. f.addr2linernm = addr2liner
  266. }
  267. return f.addr2linernm.addrInfo(addr)
  268. }
  269. // fileAddr2Line implements the binutils.ObjFile interface, using
  270. // 'addr2line' to map addresses to symbols (with file/line number
  271. // information). It can be slow for large binaries with debug
  272. // information.
  273. type fileAddr2Line struct {
  274. once sync.Once
  275. file
  276. addr2liner *addr2Liner
  277. llvmSymbolizer *llvmSymbolizer
  278. }
  279. func (f *fileAddr2Line) SourceLine(addr uint64) ([]plugin.Frame, error) {
  280. f.once.Do(f.init)
  281. if f.llvmSymbolizer != nil {
  282. return f.llvmSymbolizer.addrInfo(addr)
  283. }
  284. if f.addr2liner != nil {
  285. return f.addr2liner.addrInfo(addr)
  286. }
  287. return nil, fmt.Errorf("could not find local addr2liner")
  288. }
  289. func (f *fileAddr2Line) init() {
  290. if llvmSymbolizer, err := newLLVMSymbolizer(f.b.llvmSymbolizer, f.name, f.base); err == nil {
  291. f.llvmSymbolizer = llvmSymbolizer
  292. return
  293. }
  294. if addr2liner, err := newAddr2Liner(f.b.addr2line, f.name, f.base); err == nil {
  295. f.addr2liner = addr2liner
  296. // When addr2line encounters some gcc compiled binaries, it
  297. // drops interesting parts of names in anonymous namespaces.
  298. // Fallback to NM for better function names.
  299. if nm, err := newAddr2LinerNM(f.b.nm, f.name, f.base); err == nil {
  300. f.addr2liner.nm = nm
  301. }
  302. }
  303. }
  304. func (f *fileAddr2Line) Close() error {
  305. if f.llvmSymbolizer != nil {
  306. f.llvmSymbolizer.rw.close()
  307. f.llvmSymbolizer = nil
  308. }
  309. if f.addr2liner != nil {
  310. f.addr2liner.rw.close()
  311. f.addr2liner = nil
  312. }
  313. return nil
  314. }