blob: 7b66070a1827bca2f7934fea470ee56d052e6a8d [file] [log] [blame]
Steven Valdezab14a4a2016-02-29 16:58:26 -05001#!/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.
15import os
16import os.path
17import subprocess
18import sys
19
20# The LCOV output format for each source file is:
21#
22# SF:<filename>
23# DA:<line>,<execution count>
24# ...
25# end_of_record
26#
27# The <execution count> can either be 0 for an unexecuted instruction or a
28# value representing the number of executions. The DA line should be omitted
29# for lines not representing an instruction.
30
31SECTION_SEPERATOR = '-' * 80
32
33def is_asm(l):
34 """Returns whether a line should be considered to be an instruction."""
35 l = l.strip()
36 # Empty lines
37 if l == '':
38 return False
39 # Comments
40 if l.startswith('#'):
41 return False
42 # Assembly Macros
43 if l.startswith('.'):
44 return False
45 # Label
46 if l.endswith(':'):
47 return False
48 return True
49
50def merge(callgrind_files, srcs):
51 """Calls callgrind_annotate over the set of callgrind output
52 |callgrind_files| using the sources |srcs| and merges the results
53 together."""
54 out = ''
55 for file in callgrind_files:
56 data = subprocess.check_output(['callgrind_annotate', file] + srcs)
57 out += '%s\n%s\n' % (data, SECTION_SEPERATOR)
58 return out
59
60def parse(filename, data, current):
61 """Parses an annotated execution flow |data| from callgrind_annotate for
62 source |filename| and updates the current execution counts from |current|."""
63 with open(filename) as f:
64 source = f.read().split('\n')
65
66 out = current
67 if out == None:
68 out = [0 if is_asm(l) else None for l in source]
69
70 # Lines are of the following formats:
71 # -- line: Indicates that analysis continues from a different place.
72 # => : Indicates a call/jump in the control flow.
73 # <Count> <Code>: Indicates that the line has been executed that many times.
74 line = None
75 for l in data:
76 l = l.strip() + ' '
77 if l.startswith('-- line'):
78 line = int(l.split(' ')[2]) - 1
79 elif line != None and '=>' not in l:
80 count = l.split(' ')[0].replace(',', '').replace('.', '0')
81 instruction = l.split(' ', 1)[1].strip()
82 if count != '0' or is_asm(instruction):
83 if out[line] == None:
84 out[line] = 0
85 out[line] += int(count)
86 line += 1
87
88 return out
89
90
91def generate(data):
92 """Parses the merged callgrind_annotate output |data| and generates execution
93 counts for all annotated files."""
94 out = {}
95 data = [p.strip() for p in data.split(SECTION_SEPERATOR)]
96
97
98 # Most sections are ignored, but a section with:
99 # User-annotated source: <file>
100 # precedes a listing of execution count for that <file>.
101 for i in range(len(data)):
102 if 'User-annotated source' in data[i] and i < len(data) - 1:
103 filename = data[i].split(':', 1)[1].strip()
104 res = data[i + 1]
105 if filename not in out:
106 out[filename] = None
107 if 'No information' in res:
108 res = []
109 else:
110 res = res.split('\n')
111 out[filename] = parse(filename, res, out[filename])
112 return out
113
114def output(data):
115 """Takes a dictionary |data| of filenames and execution counts and generates
116 a LCOV coverage output."""
117 out = ''
118 for filename, counts in data.iteritems():
119 out += 'SF:%s\n' % (os.path.abspath(filename))
120 for line, count in enumerate(counts):
121 if count != None:
122 out += 'DA:%d,%s\n' % (line + 1, count)
123 out += 'end_of_record\n'
124 return out
125
126if __name__ == '__main__':
127 if len(sys.argv) != 3:
128 print '%s <Callgrind Folder> <Build Folder>' % (__file__)
129 sys.exit()
130
131 cg_folder = sys.argv[1]
132 build_folder = sys.argv[2]
133
134 cg_files = []
135 for (cwd, _, files) in os.walk(cg_folder):
136 for f in files:
137 if f.startswith('callgrind.out'):
138 cg_files.append(os.path.abspath(os.path.join(cwd, f)))
139
140 srcs = []
141 for (cwd, _, files) in os.walk(build_folder):
142 for f in files:
143 fn = os.path.join(cwd, f)
144 if fn.endswith('.S'):
145 srcs.append(fn)
146
147 annotated = merge(cg_files, srcs)
148 lcov = generate(annotated)
149 print output(lcov)