Нема описа

symbolizer.go 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. if resp.StatusCode != http.StatusOK {
  89. return nil, fmt.Errorf("server response: %s", resp.Status)
  90. }
  91. defer resp.Body.Close()
  92. return ioutil.ReadAll(resp.Body)
  93. }
  94. // doLocalSymbolize adds symbol and line number information to all locations
  95. // in a profile. mode enables some options to control
  96. // symbolization.
  97. func doLocalSymbolize(mode string, prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI) error {
  98. force := false
  99. // Disable some mechanisms based on mode string.
  100. for _, o := range strings.Split(strings.ToLower(mode), ":") {
  101. switch {
  102. case o == "force":
  103. force = true
  104. case o == "fastlocal":
  105. if bu, ok := obj.(*binutils.Binutils); ok {
  106. bu.SetFastSymbolization(true)
  107. }
  108. default:
  109. }
  110. }
  111. mt, err := newMapping(prof, obj, ui, force)
  112. if err != nil {
  113. return err
  114. }
  115. defer mt.close()
  116. functions := make(map[profile.Function]*profile.Function)
  117. for _, l := range mt.prof.Location {
  118. m := l.Mapping
  119. segment := mt.segments[m]
  120. if segment == nil {
  121. // Nothing to do.
  122. continue
  123. }
  124. stack, err := segment.SourceLine(l.Address)
  125. if err != nil || len(stack) == 0 {
  126. // No answers from addr2line.
  127. continue
  128. }
  129. l.Line = make([]profile.Line, len(stack))
  130. for i, frame := range stack {
  131. if frame.Func != "" {
  132. m.HasFunctions = true
  133. }
  134. if frame.File != "" {
  135. m.HasFilenames = true
  136. }
  137. if frame.Line != 0 {
  138. m.HasLineNumbers = true
  139. }
  140. f := &profile.Function{
  141. Name: frame.Func,
  142. SystemName: frame.Func,
  143. Filename: frame.File,
  144. }
  145. if fp := functions[*f]; fp != nil {
  146. f = fp
  147. } else {
  148. functions[*f] = f
  149. f.ID = uint64(len(mt.prof.Function)) + 1
  150. mt.prof.Function = append(mt.prof.Function, f)
  151. }
  152. l.Line[i] = profile.Line{
  153. Function: f,
  154. Line: int64(frame.Line),
  155. }
  156. }
  157. if len(stack) > 0 {
  158. m.HasInlineFrames = true
  159. }
  160. }
  161. return nil
  162. }
  163. // Demangle updates the function names in a profile with demangled C++
  164. // names, simplified according to demanglerMode. If force is set,
  165. // overwrite any names that appear already demangled.
  166. func Demangle(prof *profile.Profile, force bool, demanglerMode string) {
  167. if force {
  168. // Remove the current demangled names to force demangling
  169. for _, f := range prof.Function {
  170. if f.Name != "" && f.SystemName != "" {
  171. f.Name = f.SystemName
  172. }
  173. }
  174. }
  175. var options []demangle.Option
  176. switch demanglerMode {
  177. case "": // demangled, simplified: no parameters, no templates, no return type
  178. options = []demangle.Option{demangle.NoParams, demangle.NoTemplateParams}
  179. case "templates": // demangled, simplified: no parameters, no return type
  180. options = []demangle.Option{demangle.NoParams}
  181. case "full":
  182. options = []demangle.Option{demangle.NoClones}
  183. case "none": // no demangling
  184. return
  185. }
  186. // Copy the options because they may be updated by the call.
  187. o := make([]demangle.Option, len(options))
  188. for _, fn := range prof.Function {
  189. if fn.Name != "" && fn.SystemName != fn.Name {
  190. continue // Already demangled.
  191. }
  192. copy(o, options)
  193. if demangled := demangle.Filter(fn.SystemName, o...); demangled != fn.SystemName {
  194. fn.Name = demangled
  195. continue
  196. }
  197. // Could not demangle. Apply heuristics in case the name is
  198. // already demangled.
  199. name := fn.SystemName
  200. if looksLikeDemangledCPlusPlus(name) {
  201. if demanglerMode == "" || demanglerMode == "templates" {
  202. name = removeMatching(name, '(', ')')
  203. }
  204. if demanglerMode == "" {
  205. name = removeMatching(name, '<', '>')
  206. }
  207. }
  208. fn.Name = name
  209. }
  210. }
  211. // looksLikeDemangledCPlusPlus is a heuristic to decide if a name is
  212. // the result of demangling C++. If so, further heuristics will be
  213. // applied to simplify the name.
  214. func looksLikeDemangledCPlusPlus(demangled string) bool {
  215. if strings.Contains(demangled, ".<") { // Skip java names of the form "class.<init>"
  216. return false
  217. }
  218. return strings.ContainsAny(demangled, "<>[]") || strings.Contains(demangled, "::")
  219. }
  220. // removeMatching removes nested instances of start..end from name.
  221. func removeMatching(name string, start, end byte) string {
  222. s := string(start) + string(end)
  223. var nesting, first, current int
  224. for index := strings.IndexAny(name[current:], s); index != -1; index = strings.IndexAny(name[current:], s) {
  225. switch current += index; name[current] {
  226. case start:
  227. nesting++
  228. if nesting == 1 {
  229. first = current
  230. }
  231. case end:
  232. nesting--
  233. switch {
  234. case nesting < 0:
  235. return name // Mismatch, abort
  236. case nesting == 0:
  237. name = name[:first] + name[current+1:]
  238. current = first - 1
  239. }
  240. }
  241. current++
  242. }
  243. return name
  244. }
  245. // newMapping creates a mappingTable for a profile.
  246. func newMapping(prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI, force bool) (*mappingTable, error) {
  247. mt := &mappingTable{
  248. prof: prof,
  249. segments: make(map[*profile.Mapping]plugin.ObjFile),
  250. }
  251. // Identify used mappings
  252. mappings := make(map[*profile.Mapping]bool)
  253. for _, l := range prof.Location {
  254. mappings[l.Mapping] = true
  255. }
  256. missingBinaries := false
  257. for midx, m := range prof.Mapping {
  258. if !mappings[m] {
  259. continue
  260. }
  261. // Do not attempt to re-symbolize a mapping that has already been symbolized.
  262. if !force && (m.HasFunctions || m.HasFilenames || m.HasLineNumbers) {
  263. continue
  264. }
  265. if m.File == "" {
  266. if midx == 0 {
  267. ui.PrintErr("Main binary filename not available.")
  268. continue
  269. }
  270. missingBinaries = true
  271. continue
  272. }
  273. // Skip well-known system mappings
  274. if m.Unsymbolizable() {
  275. continue
  276. }
  277. // Skip mappings pointing to a source URL
  278. if m.BuildID == "" {
  279. if u, err := url.Parse(m.File); err == nil && u.IsAbs() {
  280. continue
  281. }
  282. }
  283. name := filepath.Base(m.File)
  284. f, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)
  285. if err != nil {
  286. ui.PrintErr("Local symbolization failed for ", name, ": ", err)
  287. missingBinaries = true
  288. continue
  289. }
  290. if fid := f.BuildID(); m.BuildID != "" && fid != "" && fid != m.BuildID {
  291. ui.PrintErr("Local symbolization failed for ", name, ": build ID mismatch")
  292. f.Close()
  293. continue
  294. }
  295. mt.segments[m] = f
  296. }
  297. if missingBinaries {
  298. ui.PrintErr("Some binary filenames not available. Symbolization may be incomplete.\n" +
  299. "Try setting PPROF_BINARY_PATH to the search path for local binaries.")
  300. }
  301. return mt, nil
  302. }
  303. // mappingTable contains the mechanisms for symbolization of a
  304. // profile.
  305. type mappingTable struct {
  306. prof *profile.Profile
  307. segments map[*profile.Mapping]plugin.ObjFile
  308. }
  309. // Close releases any external processes being used for the mapping.
  310. func (mt *mappingTable) close() {
  311. for _, segment := range mt.segments {
  312. segment.Close()
  313. }
  314. }