4
0

profile_symbolize.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #!/usr/bin/env python3
  2. # Names the LYNX.exe frames of a message-thread profile (LYNX_PROFILE_MAIN, src/platform/CrashGuard.cpp; round 190kz).
  3. #
  4. # The profiler writes LYNX.exe's own frames as raw addresses ("-- raw" section of each window: "S|T <rva> <weight>")
  5. # because loading the ~750 MB LYNX.pdb inside the measured process took longer than a measurement run. This script
  6. # names them afterwards with llvm-symbolizer and the PDB next to the exe (inlined functions included), and prints, for
  7. # the windows chosen, the functions by self weight and by total (self + callees) weight, as shares of all samples.
  8. #
  9. # usage: profile_symbolize.py <profile.txt> <LYNX.exe> [--from S] [--to S] [--top N] [--symbolizer PATH]
  10. # llvm-symbolizer: PATH, $LLVM_SYMBOLIZER, or llvm-symbolizer on the PATH (LLVM 18 reads PDBs on Linux)
  11. import argparse
  12. import os
  13. import re
  14. import shutil
  15. import struct
  16. import subprocess
  17. import sys
  18. from collections import defaultdict
  19. def image_base(exe):
  20. with open(exe, "rb") as f:
  21. head = f.read(4096)
  22. pe = struct.unpack_from("<I", head, 0x3C)[0]
  23. magic = struct.unpack_from("<H", head, pe + 24)[0]
  24. return struct.unpack_from("<Q", head, pe + 24 + 24)[0] if magic == 0x20B else struct.unpack_from("<I", head, pe + 24 + 28)[0]
  25. def symbolize(symbolizer, exe, base, rvas):
  26. """rva -> list of function names, innermost (inlined) first"""
  27. names = {}
  28. if not rvas:
  29. return names
  30. order = sorted(rvas)
  31. text = "\n".join("0x%x" % (base + r) for r in order) + "\n"
  32. out = subprocess.run([symbolizer, "--obj=" + exe, "--functions=short", "--inlining", "--demangle"],
  33. input=text, capture_output=True, text=True, check=False).stdout
  34. # LLVM style: per address, pairs of lines (function, file:line:col), innermost first; a blank line after each address
  35. blocks = out.split("\n\n")
  36. for rva, block in zip(order, blocks):
  37. lines = [l for l in block.split("\n") if l.strip()]
  38. funcs = [lines[i] for i in range(0, len(lines), 2)]
  39. names[rva] = [f if f != "??" else "LYNX.exe+0x%x" % rva for f in funcs] or ["LYNX.exe+0x%x" % rva]
  40. return names
  41. def main():
  42. ap = argparse.ArgumentParser()
  43. ap.add_argument("profile")
  44. ap.add_argument("exe")
  45. ap.add_argument("--from", dest="t0", type=float, default=0.0)
  46. ap.add_argument("--to", dest="t1", type=float, default=1e18)
  47. ap.add_argument("--top", type=int, default=45)
  48. ap.add_argument("--symbolizer", default=os.environ.get("LLVM_SYMBOLIZER") or shutil.which("llvm-symbolizer") or "llvm-symbolizer")
  49. a = ap.parse_args()
  50. windows = 0
  51. samples = 0
  52. cpu = []
  53. self_raw = defaultdict(int)
  54. total_raw = defaultdict(int)
  55. other_self = defaultdict(float) # non-LYNX self lines, in % of their window, weighted back to samples
  56. other_total = defaultdict(float)
  57. section = None
  58. take = False
  59. wsamples = 0
  60. for line in open(a.profile, encoding="utf-8", errors="replace"):
  61. line = line.rstrip("\n")
  62. m = re.match(r"=== window ([\d.]+)-([\d.]+) s: (\d+) ticks, message thread CPU ([\d.]+) %", line)
  63. if m:
  64. take = a.t0 <= float(m.group(1)) and float(m.group(2)) <= a.t1
  65. section = None
  66. if take:
  67. windows += 1
  68. cpu.append(float(m.group(4)))
  69. continue
  70. if not take:
  71. continue
  72. if line.startswith("-- raw"):
  73. section = "raw"
  74. wsamples = int(re.search(r"of (\d+)", line).group(1))
  75. samples += wsamples
  76. continue
  77. if line.startswith("-- self"):
  78. section = "self"
  79. continue
  80. if line.startswith("-- total"):
  81. section = "total"
  82. continue
  83. if line.startswith("--"):
  84. section = None
  85. continue
  86. if section == "raw":
  87. kind, rva, w = line.split()
  88. (self_raw if kind == "S" else total_raw)[int(rva, 16)] += int(w)
  89. elif section in ("self", "total"):
  90. m = re.match(r"\s*([\d.]+) %\s+(.*)", line)
  91. if m and not m.group(2).startswith("LYNX.exe+0x"):
  92. (other_self if section == "self" else other_total)[m.group(2)] += float(m.group(1))
  93. if windows == 0:
  94. sys.exit("no window in the range")
  95. base = image_base(a.exe)
  96. # caller frames are return addresses: the call is the instruction before (rva - 1), else the inlined function of the
  97. # next statement would be named
  98. names = symbolize(a.symbolizer, a.exe, base, set(self_raw) | {r - 1 for r in total_raw})
  99. self_fn = defaultdict(int)
  100. total_fn = defaultdict(int)
  101. for r, w in self_raw.items():
  102. self_fn[names.get(r, ["?"])[0]] += w
  103. for r, w in total_raw.items():
  104. for f in dict.fromkeys(names.get(r - 1, ["?"])):
  105. total_fn[f] += w
  106. pct = lambda w: 100.0 * w / max(1, samples)
  107. print("%d windows, message thread CPU %.1f %% (mean of the windows), %d weight units" % (windows, sum(cpu) / len(cpu), samples))
  108. print("-- self (LYNX.exe functions, inlined callees named; shares of all samples)")
  109. for f, w in sorted(self_fn.items(), key=lambda kv: -kv[1])[: a.top]:
  110. print("%6.1f %% %s" % (pct(w), f))
  111. print("-- self, other modules (mean %% of the windows' samples)")
  112. for f, v in sorted(other_self.items(), key=lambda kv: -kv[1])[:15]:
  113. print("%6.1f %% %s" % (v / windows, f))
  114. print("-- total (self + callees; LYNX.exe functions)")
  115. for f, w in sorted(total_fn.items(), key=lambda kv: -kv[1])[: a.top + 25]:
  116. print("%6.1f %% %s" % (pct(w), f))
  117. if __name__ == "__main__":
  118. main()