暫無描述

symbolizer.go 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 symbolizer provides a routine to populate a profile with
  15. // symbol, file and line number information. It relies on the
  16. // addr2liner and demangle packages to do the actual work.
  17. package symbolizer
  18. import (
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. "net/url"
  23. "path/filepath"
  24. "strings"
  25. "github.com/google/pprof/internal/binutils"
  26. "github.com/google/pprof/internal/plugin"
  27. "github.com/google/pprof/internal/symbolz"
  28. "github.com/google/pprof/profile"
  29. "github.com/ianlancetaylor/demangle"
  30. )
  31. // Symbolizer implements the plugin.Symbolize interface.
  32. type Symbolizer struct {
  33. Obj plugin.ObjTool
  34. UI plugin.UI
  35. }
  36. // test taps for dependency injection
  37. var symbolzSymbolize = symbolz.Symbolize
  38. var localSymbolize = doLocalSymbolize
  39. // Symbolize attempts to symbolize profile p. First uses binutils on
  40. // local binaries; if the source is a URL it attempts to get any
  41. // missed entries using symbolz.
  42. func (s *Symbolizer) Symbolize(mode string, sources plugin.MappingSources, p *profile.Profile) error {
  43. remote, local, force, demanglerMode := true, true, false, ""
  44. for _, o := range strings.Split(strings.ToLower(mode), ":") {
  45. switch o {
  46. case "none", "no":
  47. return nil
  48. case "local", "fastlocal":
  49. remote, local = false, true
  50. case "remote":
  51. remote, local = true, false
  52. case "", "force":
  53. force = true
  54. default:
  55. switch d := strings.TrimPrefix(o, "demangle="); d {
  56. case "full", "none", "templates":
  57. demanglerMode = d
  58. force = true
  59. continue
  60. case "default":
  61. continue
  62. }
  63. s.UI.PrintErr("ignoring unrecognized symbolization option: " + mode)
  64. s.UI.PrintErr("expecting -symbolize=[local|fastlocal|remote|none][:force][:demangle=[none|full|templates|default]")
  65. }
  66. }
  67. var err error
  68. if local {
  69. // Symbolize locally using binutils.
  70. if err = localSymbolize(mode, p, s.Obj, s.UI); err != nil {
  71. s.UI.PrintErr("local symbolization: " + err.Error())
  72. }
  73. }
  74. if remote {
  75. if err = symbolzSymbolize(sources, postURL, p, s.UI); err != nil {
  76. return err // Ran out of options.
  77. }
  78. }
  79. Demangle(p, force, demanglerMode)
  80. return nil
  81. }
  82. // postURL issues a POST to a URL over HTTP.
  83. func postURL(source, post string) ([]byte, error) {
  84. resp, err := http.Post(source, "application/octet-stream", strings.NewReader(post))
  85. if err != nil {
  86. return nil, fmt.Errorf("http post %s: %v", source, err)
  87. }
  88. defer resp.Body.Close()
  89. if resp.StatusCode != http.StatusOK {
  90. return nil, statusCodeError(resp)
  91. }
  92. return ioutil.ReadAll(resp.Body)
  93. }
  94. func statusCodeError(resp *http.Response) error {
  95. if resp.Header.Get("X-Go-Pprof") != "" && strings.Contains(resp.Header.Get("Content-Type"), "text/plain") {
  96. // error is from pprof endpoint
  97. body, err := ioutil.ReadAll(resp.Body)
  98. if err == nil {
  99. return fmt.Errorf("server response: %s - %s", resp.Status, body)
  100. }
  101. }
  102. return fmt.Errorf("server response: %s", resp.Status)
  103. }
  104. // doLocalSymbolize adds symbol and line number information to all locations
  105. // in a profile. mode enables some options to control
  106. // symbolization.
  107. func doLocalSymbolize(mode string, prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI) error {
  108. force := false
  109. // Disable some mechanisms based on mode string.
  110. for _, o := range strings.Split(strings.ToLower(mode), ":") {
  111. switch {
  112. case o == "force":
  113. force = true
  114. case o == "fastlocal":
  115. if bu, ok := obj.(*binutils.Binutils); ok {
  116. bu.SetFastSymbolization(true)
  117. }
  118. default:
  119. }
  120. }
  121. mt, err := newMapping(prof, obj, ui, force)
  122. if err != nil {
  123. return err
  124. }
  125. defer mt.close()
  126. functions := make(map[profile.Function]*profile.Function)
  127. for _, l := range mt.prof.Location {
  128. m := l.Mapping
  129. segment := mt.segments[m]
  130. if segment == nil {
  131. // Nothing to do.
  132. continue
  133. }
  134. stack, err := segment.SourceLine(l.Address)
  135. if err != nil || len(stack) == 0 {
  136. // No answers from addr2line.
  137. continue
  138. }
  139. l.Line = make([]profile.Line, len(stack))
  140. for i, frame := range stack {
  141. if frame.Func != "" {
  142. m.HasFunctions = true
  143. }
  144. if frame.File != "" {
  145. m.HasFilenames = true
  146. }
  147. if frame.Line != 0 {
  148. m.HasLineNumbers = true
  149. }
  150. f := &profile.Function{
  151. Name: frame.Func,
  152. SystemName: frame.Func,
  153. Filename: frame.File,
  154. }
  155. if fp := functions[*f]; fp != nil {
  156. f = fp
  157. } else {
  158. functions[*f] = f
  159. f.ID = uint64(len(mt.prof.Function)) + 1
  160. mt.prof.Function = append(mt.prof.Function, f)
  161. }
  162. l.Line[i] = profile.Line{
  163. Function: f,
  164. Line: int64(frame.Line),
  165. }
  166. }
  167. if len(stack) > 0 {
  168. m.HasInlineFrames = true
  169. }
  170. }
  171. return nil
  172. }
  173. // Demangle updates the function names in a profile with demangled C++
  174. // names, simplified according to demanglerMode. If force is set,
  175. // overwrite any names that appear already demangled.
  176. func Demangle(prof *profile.Profile, force bool, demanglerMode string) {
  177. if force {
  178. // Remove the current demangled names to force demangling
  179. for _, f := range prof.Function {
  180. if f.Name != "" && f.SystemName != "" {
  181. f.Name = f.SystemName
  182. }
  183. }
  184. }
  185. var options []demangle.Option
  186. switch demanglerMode {
  187. case "": // demangled, simplified: no parameters, no templates, no return type
  188. options = []demangle.Option{demangle.NoParams, demangle.NoTemplateParams}
  189. case "templates": // demangled, simplified: no parameters, no return type
  190. options = []demangle.Option{demangle.NoParams}
  191. case "full":
  192. options = []demangle.Option{demangle.NoClones}
  193. case "none": // no demangling
  194. return
  195. }
  196. // Copy the options because they may be updated by the call.
  197. o := make([]demangle.Option, len(options))
  198. for _, fn := range prof.Function {
  199. if fn.Name != "" && fn.SystemName != fn.Name {
  200. continue // Already demangled.
  201. }
  202. copy(o, options)
  203. if demangled := demangle.Filter(fn.SystemName, o...); demangled != fn.SystemName {
  204. fn.Name = demangled
  205. continue
  206. }
  207. // Could not demangle. Apply heuristics in case the name is
  208. // already demangled.
  209. name := fn.SystemName
  210. if looksLikeDemangledCPlusPlus(name) {
  211. if demanglerMode == "" || demanglerMode == "templates" {
  212. name = removeMatching(name, '(', ')')
  213. }
  214. if demanglerMode == "" {
  215. name = removeMatching(name, '<', '>')
  216. }
  217. }
  218. fn.Name = name
  219. }
  220. }
  221. // looksLikeDemangledCPlusPlus is a heuristic to decide if a name is
  222. // the result of demangling C++. If so, further heuristics will be
  223. // applied to simplify the name.
  224. func looksLikeDemangledCPlusPlus(demangled string) bool {
  225. if strings.Contains(demangled, ".<") { // Skip java names of the form "class.<init>"
  226. return false
  227. }
  228. return strings.ContainsAny(demangled, "<>[]") || strings.Contains(demangled, "::")
  229. }
  230. // removeMatching removes nested instances of start..end from name.
  231. func removeMatching(name string, start, end byte) string {
  232. s := string(start) + string(end)
  233. var nesting, first, current int
  234. for index := strings.IndexAny(name[current:], s); index != -1; index = strings.IndexAny(name[current:], s) {
  235. switch current += index; name[current] {
  236. case start:
  237. nesting++
  238. if nesting == 1 {
  239. first = current
  240. }
  241. case end:
  242. nesting--
  243. switch {
  244. case nesting < 0:
  245. return name // Mismatch, abort
  246. case nesting == 0:
  247. name = name[:first] + name[current+1:]
  248. current = first - 1
  249. }
  250. }
  251. current++
  252. }
  253. return name
  254. }
  255. // newMapping creates a mappingTable for a profile.
  256. func newMapping(prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI, force bool) (*mappingTable, error) {
  257. mt := &mappingTable{
  258. prof: prof,
  259. segments: make(map[*profile.Mapping]plugin.ObjFile),
  260. }
  261. // Identify used mappings
  262. mappings := make(map[*profile.Mapping]bool)
  263. for _, l := range prof.Location {
  264. mappings[l.Mapping] = true
  265. }
  266. missingBinaries := false
  267. for midx, m := range prof.Mapping {
  268. if !mappings[m] {
  269. continue
  270. }
  271. // Do not attempt to re-symbolize a mapping that has already been symbolized.
  272. if !force && (m.HasFunctions || m.HasFilenames || m.HasLineNumbers) {
  273. continue
  274. }
  275. if m.File == "" {
  276. if midx == 0 {
  277. ui.PrintErr("Main binary filename not available.")
  278. continue
  279. }
  280. missingBinaries = true
  281. continue
  282. }
  283. // Skip well-known system mappings
  284. if m.Unsymbolizable() {
  285. continue
  286. }
  287. // Skip mappings pointing to a source URL
  288. if m.BuildID == "" {
  289. if u, err := url.Parse(m.File); err == nil && u.IsAbs() {
  290. continue
  291. }
  292. }
  293. name := filepath.Base(m.File)
  294. f, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)
  295. if err != nil {
  296. ui.PrintErr("Local symbolization failed for ", name, ": ", err)
  297. missingBinaries = true
  298. continue
  299. }
  300. if fid := f.BuildID(); m.BuildID != "" && fid != "" && fid != m.BuildID {
  301. ui.PrintErr("Local symbolization failed for ", name, ": build ID mismatch")
  302. f.Close()
  303. continue
  304. }
  305. mt.segments[m] = f
  306. }
  307. if missingBinaries {
  308. ui.PrintErr("Some binary filenames not available. Symbolization may be incomplete.\n" +
  309. "Try setting PPROF_BINARY_PATH to the search path for local binaries.")
  310. }
  311. return mt, nil
  312. }
  313. // mappingTable contains the mechanisms for symbolization of a
  314. // profile.
  315. type mappingTable struct {
  316. prof *profile.Profile
  317. segments map[*profile.Mapping]plugin.ObjFile
  318. }
  319. // Close releases any external processes being used for the mapping.
  320. func (mt *mappingTable) close() {
  321. for _, segment := range mt.segments {
  322. segment.Close()
  323. }
  324. }