Geen omschrijving

binutils.go 12KB

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