説明なし

symbolizer.go 8.7KB

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