Geen omschrijving

symbolizer.go 9.7KB

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