Без опису

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