generate-asm-lcov.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #!/usr/bin/python
  2. # Copyright (c) 2016, Google Inc.
  3. #
  4. # Permission to use, copy, modify, and/or distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  11. # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  13. # OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  14. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. import os
  16. import os.path
  17. import subprocess
  18. import sys
  19. # The LCOV output format for each source file is:
  20. #
  21. # SF:<filename>
  22. # DA:<line>,<execution count>
  23. # ...
  24. # end_of_record
  25. #
  26. # The <execution count> can either be 0 for an unexecuted instruction or a
  27. # value representing the number of executions. The DA line should be omitted
  28. # for lines not representing an instruction.
  29. SECTION_SEPERATOR = '-' * 80
  30. def is_asm(l):
  31. """Returns whether a line should be considered to be an instruction."""
  32. l = l.strip()
  33. # Empty lines
  34. if l == '':
  35. return False
  36. # Comments
  37. if l.startswith('#'):
  38. return False
  39. # Assembly Macros
  40. if l.startswith('.'):
  41. return False
  42. # Label
  43. if l.endswith(':'):
  44. return False
  45. return True
  46. def merge(callgrind_files, srcs):
  47. """Calls callgrind_annotate over the set of callgrind output
  48. |callgrind_files| using the sources |srcs| and merges the results
  49. together."""
  50. out = ''
  51. for file in callgrind_files:
  52. data = subprocess.check_output(['callgrind_annotate', file] + srcs)
  53. out += '%s\n%s\n' % (data, SECTION_SEPERATOR)
  54. return out
  55. def parse(filename, data, current):
  56. """Parses an annotated execution flow |data| from callgrind_annotate for
  57. source |filename| and updates the current execution counts from |current|."""
  58. with open(filename) as f:
  59. source = f.read().split('\n')
  60. out = current
  61. if out == None:
  62. out = [0 if is_asm(l) else None for l in source]
  63. # Lines are of the following formats:
  64. # -- line: Indicates that analysis continues from a different place.
  65. # Ir : Indicates the start of a file.
  66. # => : Indicates a call/jump in the control flow.
  67. # <Count> <Code>: Indicates that the line has been executed that many times.
  68. line = None
  69. for l in data:
  70. l = l.strip() + ' '
  71. if l.startswith('-- line'):
  72. line = int(l.split(' ')[2]) - 1
  73. elif l.strip() == 'Ir':
  74. line = 0
  75. elif line != None and l.strip() and '=>' not in l and 'unidentified lines' not in l:
  76. count = l.split(' ')[0].replace(',', '').replace('.', '0')
  77. instruction = l.split(' ', 1)[1].strip()
  78. if count != '0' or is_asm(instruction):
  79. if out[line] == None:
  80. out[line] = 0
  81. out[line] += int(count)
  82. line += 1
  83. return out
  84. def generate(data):
  85. """Parses the merged callgrind_annotate output |data| and generates execution
  86. counts for all annotated files."""
  87. out = {}
  88. data = [p.strip() for p in data.split(SECTION_SEPERATOR)]
  89. # Most sections are ignored, but a section with:
  90. # User-annotated source: <file>
  91. # precedes a listing of execution count for that <file>.
  92. for i in range(len(data)):
  93. if 'User-annotated source' in data[i] and i < len(data) - 1:
  94. filename = data[i].split(':', 1)[1].strip()
  95. res = data[i + 1]
  96. if filename not in out:
  97. out[filename] = None
  98. if 'No information' in res:
  99. res = []
  100. else:
  101. res = res.split('\n')
  102. out[filename] = parse(filename, res, out[filename])
  103. return out
  104. def output(data):
  105. """Takes a dictionary |data| of filenames and execution counts and generates
  106. a LCOV coverage output."""
  107. out = ''
  108. for filename, counts in data.iteritems():
  109. out += 'SF:%s\n' % (os.path.abspath(filename))
  110. for line, count in enumerate(counts):
  111. if count != None:
  112. out += 'DA:%d,%s\n' % (line + 1, count)
  113. out += 'end_of_record\n'
  114. return out
  115. if __name__ == '__main__':
  116. if len(sys.argv) != 3:
  117. print '%s <Callgrind Folder> <Build Folder>' % (__file__)
  118. sys.exit()
  119. cg_folder = sys.argv[1]
  120. build_folder = sys.argv[2]
  121. cg_files = []
  122. for (cwd, _, files) in os.walk(cg_folder):
  123. for f in files:
  124. if f.startswith('callgrind.out'):
  125. cg_files.append(os.path.abspath(os.path.join(cwd, f)))
  126. srcs = []
  127. for (cwd, _, files) in os.walk(build_folder):
  128. for f in files:
  129. fn = os.path.join(cwd, f)
  130. if fn.endswith('.S'):
  131. srcs.append(fn)
  132. annotated = merge(cg_files, srcs)
  133. lcov = generate(annotated)
  134. print output(lcov)