|
19 | 19 | from coverage import Coverage |
20 | 20 |
|
21 | 21 |
|
| 22 | +def lcov_field(text: str) -> str: |
| 23 | + """Make `text` safe to write as a field in a single LCOV record. |
| 24 | +
|
| 25 | + LCOV records are newline-delimited and the format has no escaping, so a |
| 26 | + value carrying a newline (a legal character in a POSIX file name) would |
| 27 | + spill into fabricated records. Replace any control characters, which can't |
| 28 | + appear in a valid one-line field, and leave printable text untouched. |
| 29 | + """ |
| 30 | + if text.isprintable(): |
| 31 | + return text |
| 32 | + return "".join(ch if ch.isprintable() else "?" for ch in text) |
| 33 | + |
| 34 | + |
22 | 35 | def line_hash(line: str) -> str: |
23 | 36 | """Produce a hash of a source line for use in the LCOV file.""" |
24 | 37 | # The LCOV file format optionally allows each line to be MD5ed as a |
@@ -97,8 +110,9 @@ def lcov_functions( |
97 | 110 | hit = int(analysis.numbers.n_executed > 0) |
98 | 111 | functions_hit += hit |
99 | 112 |
|
100 | | - outfile.write(f"FN:{first_line},{last_line},{region.name}\n") |
101 | | - outfile.write(f"FNDA:{hit},{region.name}\n") |
| 113 | + name = lcov_field(region.name) |
| 114 | + outfile.write(f"FN:{first_line},{last_line},{name}\n") |
| 115 | + outfile.write(f"FNDA:{hit},{name}\n") |
102 | 116 |
|
103 | 117 | outfile.write(f"FNF:{functions_found}\n") |
104 | 118 | outfile.write(f"FNH:{functions_hit}\n") |
@@ -145,7 +159,7 @@ def lcov_arcs( |
145 | 159 | destinations.sort(key=lambda d: (d[0] < 0, d)) |
146 | 160 |
|
147 | 161 | for dst, hit in destinations: |
148 | | - branch = fr.arc_description(line, dst) |
| 162 | + branch = lcov_field(fr.arc_description(line, dst)) |
149 | 163 | outfile.write(f"BRDA:{line},0,{branch},{hit}\n") |
150 | 164 |
|
151 | 165 | # Summary of the branch coverage. |
@@ -207,7 +221,7 @@ def lcov_file( |
207 | 221 | if self.config.skip_empty: |
208 | 222 | return |
209 | 223 |
|
210 | | - outfile.write(f"SF:{rel_fname}\n") |
| 224 | + outfile.write(f"SF:{lcov_field(rel_fname)}\n") |
211 | 225 |
|
212 | 226 | lines = sorted(analysis.statements) |
213 | 227 | if self.config.lcov_line_checksums: |
|
0 commit comments