Bez popisu

binutils.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. if !b.addr2lineFound {
  103. // On MacOS, brew installs addr2line under gaddr2line name, so search for
  104. // that if the tool is not found by its default name.
  105. b.addr2line, b.addr2lineFound = findExe("gaddr2line", append(paths["addr2line"], defaultPath...))
  106. }
  107. b.nm, b.nmFound = findExe("nm", append(paths["nm"], defaultPath...))
  108. b.objdump, b.objdumpFound = findExe("objdump", append(paths["objdump"], defaultPath...))
  109. }
  110. // findExe looks for an executable command on a set of paths.
  111. // If it cannot find it, returns cmd.
  112. func findExe(cmd string, paths []string) (string, bool) {
  113. for _, p := range paths {
  114. cp := filepath.Join(p, cmd)
  115. if c, err := exec.LookPath(cp); err == nil {
  116. return c, true
  117. }
  118. }
  119. return cmd, false
  120. }
  121. // Disasm returns the assembly instructions for the specified address range
  122. // of a binary.
  123. func (bu *Binutils) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
  124. b := bu.get()
  125. cmd := exec.Command(b.objdump, "-d", "-C", "--no-show-raw-insn", "-l",
  126. fmt.Sprintf("--start-address=%#x", start),
  127. fmt.Sprintf("--stop-address=%#x", end),
  128. file)
  129. out, err := cmd.Output()
  130. if err != nil {
  131. return nil, fmt.Errorf("%v: %v", cmd.Args, err)
  132. }
  133. return disassemble(out)
  134. }
  135. // Open satisfies the plugin.ObjTool interface.
  136. func (bu *Binutils) Open(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
  137. b := bu.get()
  138. // Make sure file is a supported executable.
  139. // The pprof driver uses Open to sniff the difference
  140. // between an executable and a profile.
  141. // For now, only ELF is supported.
  142. // Could read the first few bytes of the file and
  143. // use a table of prefixes if we need to support other
  144. // systems at some point.
  145. if _, err := os.Stat(name); err != nil {
  146. // For testing, do not require file name to exist.
  147. if strings.Contains(b.addr2line, "testdata/") {
  148. return &fileAddr2Line{file: file{b: b, name: name}}, nil
  149. }
  150. return nil, err
  151. }
  152. if f, err := b.openELF(name, start, limit, offset); err == nil {
  153. return f, nil
  154. }
  155. if f, err := b.openMachO(name, start, limit, offset); err == nil {
  156. return f, nil
  157. }
  158. return nil, fmt.Errorf("unrecognized binary: %s", name)
  159. }
  160. func (b *binrep) openMachO(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
  161. of, err := macho.Open(name)
  162. if err != nil {
  163. return nil, fmt.Errorf("error parsing %s: %v", name, err)
  164. }
  165. defer of.Close()
  166. // Subtract the load address of the __TEXT section. Usually 0 for shared
  167. // libraries or 0x100000000 for executables. You can check this value by
  168. // running `objdump -private-headers <file>`.
  169. textSegment := of.Segment("__TEXT")
  170. if textSegment == nil {
  171. return nil, fmt.Errorf("could not identify base for %s: no __TEXT segment", name)
  172. }
  173. if textSegment.Addr > start {
  174. return nil, fmt.Errorf("could not identify base for %s: __TEXT segment address (0x%x) > mapping start address (0x%x)",
  175. name, textSegment.Addr, start)
  176. }
  177. base := start - textSegment.Addr
  178. if b.fast || (!b.addr2lineFound && !b.llvmSymbolizerFound) {
  179. return &fileNM{file: file{b: b, name: name, base: base}}, nil
  180. }
  181. return &fileAddr2Line{file: file{b: b, name: name, base: base}}, nil
  182. }
  183. func (b *binrep) openELF(name string, start, limit, offset uint64) (plugin.ObjFile, error) {
  184. ef, err := elf.Open(name)
  185. if err != nil {
  186. return nil, fmt.Errorf("error parsing %s: %v", name, err)
  187. }
  188. defer ef.Close()
  189. var stextOffset *uint64
  190. var pageAligned = func(addr uint64) bool { return addr%4096 == 0 }
  191. if strings.Contains(name, "vmlinux") || !pageAligned(start) || !pageAligned(limit) || !pageAligned(offset) {
  192. // Reading all Symbols is expensive, and we only rarely need it so
  193. // we don't want to do it every time. But if _stext happens to be
  194. // page-aligned but isn't the same as Vaddr, we would symbolize
  195. // wrong. So if the name the addresses aren't page aligned, or if
  196. // the name is "vmlinux" we read _stext. We can be wrong if: (1)
  197. // someone passes a kernel path that doesn't contain "vmlinux" AND
  198. // (2) _stext is page-aligned AND (3) _stext is not at Vaddr
  199. symbols, err := ef.Symbols()
  200. if err != nil {
  201. return nil, err
  202. }
  203. for _, s := range symbols {
  204. if s.Name == "_stext" {
  205. // The kernel may use _stext as the mapping start address.
  206. stextOffset = &s.Value
  207. break
  208. }
  209. }
  210. }
  211. base, err := elfexec.GetBase(&ef.FileHeader, elfexec.FindTextProgHeader(ef), stextOffset, start, limit, offset)
  212. if err != nil {
  213. return nil, fmt.Errorf("could not identify base for %s: %v", name, err)
  214. }
  215. buildID := ""
  216. if f, err := os.Open(name); err == nil {
  217. if id, err := elfexec.GetBuildID(f); err == nil {
  218. buildID = fmt.Sprintf("%x", id)
  219. }
  220. }
  221. if b.fast || (!b.addr2lineFound && !b.llvmSymbolizerFound) {
  222. return &fileNM{file: file{b, name, base, buildID}}, nil
  223. }
  224. return &fileAddr2Line{file: file{b, name, base, buildID}}, nil
  225. }
  226. // file implements the binutils.ObjFile interface.
  227. type file struct {
  228. b *binrep
  229. name string
  230. base uint64
  231. buildID string
  232. }
  233. func (f *file) Name() string {
  234. return f.name
  235. }
  236. func (f *file) Base() uint64 {
  237. return f.base
  238. }
  239. func (f *file) BuildID() string {
  240. return f.buildID
  241. }
  242. func (f *file) SourceLine(addr uint64) ([]plugin.Frame, error) {
  243. return []plugin.Frame{}, nil
  244. }
  245. func (f *file) Close() error {
  246. return nil
  247. }
  248. func (f *file) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
  249. // Get from nm a list of symbols sorted by address.
  250. cmd := exec.Command(f.b.nm, "-n", f.name)
  251. out, err := cmd.Output()
  252. if err != nil {
  253. return nil, fmt.Errorf("%v: %v", cmd.Args, err)
  254. }
  255. return findSymbols(out, f.name, r, addr)
  256. }
  257. // fileNM implements the binutils.ObjFile interface, using 'nm' to map
  258. // addresses to symbols (without file/line number information). It is
  259. // faster than fileAddr2Line.
  260. type fileNM struct {
  261. file
  262. addr2linernm *addr2LinerNM
  263. }
  264. func (f *fileNM) SourceLine(addr uint64) ([]plugin.Frame, error) {
  265. if f.addr2linernm == nil {
  266. addr2liner, err := newAddr2LinerNM(f.b.nm, f.name, f.base)
  267. if err != nil {
  268. return nil, err
  269. }
  270. f.addr2linernm = addr2liner
  271. }
  272. return f.addr2linernm.addrInfo(addr)
  273. }
  274. // fileAddr2Line implements the binutils.ObjFile interface, using
  275. // llvm-symbolizer, if that's available, or addr2line to map addresses to
  276. // symbols (with file/line number information). It can be slow for large
  277. // binaries with debug information.
  278. type fileAddr2Line struct {
  279. once sync.Once
  280. file
  281. addr2liner *addr2Liner
  282. llvmSymbolizer *llvmSymbolizer
  283. }
  284. func (f *fileAddr2Line) SourceLine(addr uint64) ([]plugin.Frame, error) {
  285. f.once.Do(f.init)
  286. if f.llvmSymbolizer != nil {
  287. return f.llvmSymbolizer.addrInfo(addr)
  288. }
  289. if f.addr2liner != nil {
  290. return f.addr2liner.addrInfo(addr)
  291. }
  292. return nil, fmt.Errorf("could not find local addr2liner")
  293. }
  294. func (f *fileAddr2Line) init() {
  295. if llvmSymbolizer, err := newLLVMSymbolizer(f.b.llvmSymbolizer, f.name, f.base); err == nil {
  296. f.llvmSymbolizer = llvmSymbolizer
  297. return
  298. }
  299. if addr2liner, err := newAddr2Liner(f.b.addr2line, f.name, f.base); err == nil {
  300. f.addr2liner = addr2liner
  301. // When addr2line encounters some gcc compiled binaries, it
  302. // drops interesting parts of names in anonymous namespaces.
  303. // Fallback to NM for better function names.
  304. if nm, err := newAddr2LinerNM(f.b.nm, f.name, f.base); err == nil {
  305. f.addr2liner.nm = nm
  306. }
  307. }
  308. }
  309. func (f *fileAddr2Line) Close() error {
  310. if f.llvmSymbolizer != nil {
  311. f.llvmSymbolizer.rw.close()
  312. f.llvmSymbolizer = nil
  313. }
  314. if f.addr2liner != nil {
  315. f.addr2liner.rw.close()
  316. f.addr2liner = nil
  317. }
  318. return nil
  319. }