Nessuna descrizione

binutils.go 14KB

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