combinerefs.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. #! /usr/bin/env python3
  2. """
  3. combinerefs path
  4. A helper for analyzing PYTHONDUMPREFS output.
  5. When the PYTHONDUMPREFS envar is set in a debug build, at Python shutdown
  6. time Py_FinalizeEx() prints the list of all live objects twice: first it
  7. prints the repr() of each object while the interpreter is still fully intact.
  8. After cleaning up everything it can, it prints all remaining live objects
  9. again, but the second time just prints their addresses, refcounts, and type
  10. names (because the interpreter has been torn down, calling repr methods at
  11. this point can get into infinite loops or blow up).
  12. Save all this output into a file, then run this script passing the path to
  13. that file. The script finds both output chunks, combines them, then prints
  14. a line of output for each object still alive at the end:
  15. address refcnt typename repr
  16. address is the address of the object, in whatever format the platform C
  17. produces for a %p format code.
  18. refcnt is of the form
  19. "[" ref "]"
  20. when the object's refcount is the same in both PYTHONDUMPREFS output blocks,
  21. or
  22. "[" ref_before "->" ref_after "]"
  23. if the refcount changed.
  24. typename is object->ob_type->tp_name, extracted from the second PYTHONDUMPREFS
  25. output block.
  26. repr is repr(object), extracted from the first PYTHONDUMPREFS output block.
  27. CAUTION: If object is a container type, it may not actually contain all the
  28. objects shown in the repr: the repr was captured from the first output block,
  29. and some of the containees may have been released since then. For example,
  30. it's common for the line showing the dict of interned strings to display
  31. strings that no longer exist at the end of Py_FinalizeEx; this can be recognized
  32. (albeit painfully) because such containees don't have a line of their own.
  33. The objects are listed in allocation order, with most-recently allocated
  34. printed first, and the first object allocated printed last.
  35. Simple examples:
  36. 00857060 [14] str '__len__'
  37. The str object '__len__' is alive at shutdown time, and both PYTHONDUMPREFS
  38. output blocks said there were 14 references to it. This is probably due to
  39. C modules that intern the string "__len__" and keep a reference to it in a
  40. file static.
  41. 00857038 [46->5] tuple ()
  42. 46-5 = 41 references to the empty tuple were removed by the cleanup actions
  43. between the times PYTHONDUMPREFS produced output.
  44. 00858028 [1025->1456] str '<dummy key>'
  45. The string '<dummy key>', which is used in dictobject.c to overwrite a real
  46. key that gets deleted, grew several hundred references during cleanup. It
  47. suggests that stuff did get removed from dicts by cleanup, but that the dicts
  48. themselves are staying alive for some reason. """
  49. import re
  50. import sys
  51. # Generate lines from fileiter. If whilematch is true, continue reading
  52. # while the regexp object pat matches line. If whilematch is false, lines
  53. # are read so long as pat doesn't match them. In any case, the first line
  54. # that doesn't match pat (when whilematch is true), or that does match pat
  55. # (when whilematch is false), is lost, and fileiter will resume at the line
  56. # following it.
  57. def read(fileiter, pat, whilematch):
  58. for line in fileiter:
  59. if bool(pat.match(line)) == whilematch:
  60. yield line
  61. else:
  62. break
  63. def combine(fname):
  64. f = open(fname)
  65. fi = iter(f)
  66. for line in read(fi, re.compile(r'^Remaining objects:$'), False):
  67. pass
  68. crack = re.compile(r'([a-zA-Z\d]+) \[(\d+)\] (.*)')
  69. addr2rc = {}
  70. addr2guts = {}
  71. before = 0
  72. for line in read(fi, re.compile(r'^Remaining object addresses:$'), False):
  73. m = crack.match(line)
  74. if m:
  75. addr, addr2rc[addr], addr2guts[addr] = m.groups()
  76. before += 1
  77. else:
  78. print('??? skipped:', line)
  79. after = 0
  80. for line in read(fi, crack, True):
  81. after += 1
  82. m = crack.match(line)
  83. assert m
  84. addr, rc, guts = m.groups() # guts is type name here
  85. if addr not in addr2rc:
  86. print('??? new object created while tearing down:', line.rstrip())
  87. continue
  88. print(addr, end=' ')
  89. if rc == addr2rc[addr]:
  90. print('[%s]' % rc, end=' ')
  91. else:
  92. print('[%s->%s]' % (addr2rc[addr], rc), end=' ')
  93. print(guts, addr2guts[addr])
  94. f.close()
  95. print("%d objects before, %d after" % (before, after))
  96. if __name__ == '__main__':
  97. combine(sys.argv[1])