暂无描述

symbolizer.go 10KB

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