1 | //===-- sancov.cpp --------------------------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // This file is a command-line tool for reading and analyzing sanitizer |
9 | // coverage. |
10 | //===----------------------------------------------------------------------===// |
11 | #include "llvm/ADT/STLExtras.h" |
12 | #include "llvm/ADT/StringExtras.h" |
13 | #include "llvm/ADT/Twine.h" |
14 | #include "llvm/DebugInfo/Symbolize/SymbolizableModule.h" |
15 | #include "llvm/DebugInfo/Symbolize/Symbolize.h" |
16 | #include "llvm/MC/MCAsmInfo.h" |
17 | #include "llvm/MC/MCContext.h" |
18 | #include "llvm/MC/MCDisassembler/MCDisassembler.h" |
19 | #include "llvm/MC/MCInst.h" |
20 | #include "llvm/MC/MCInstrAnalysis.h" |
21 | #include "llvm/MC/MCInstrInfo.h" |
22 | #include "llvm/MC/MCObjectFileInfo.h" |
23 | #include "llvm/MC/MCRegisterInfo.h" |
24 | #include "llvm/MC/MCSubtargetInfo.h" |
25 | #include "llvm/MC/MCTargetOptions.h" |
26 | #include "llvm/MC/TargetRegistry.h" |
27 | #include "llvm/Object/Archive.h" |
28 | #include "llvm/Object/Binary.h" |
29 | #include "llvm/Object/COFF.h" |
30 | #include "llvm/Object/MachO.h" |
31 | #include "llvm/Object/ObjectFile.h" |
32 | #include "llvm/Option/ArgList.h" |
33 | #include "llvm/Option/Option.h" |
34 | #include "llvm/Support/Casting.h" |
35 | #include "llvm/Support/CommandLine.h" |
36 | #include "llvm/Support/Errc.h" |
37 | #include "llvm/Support/ErrorOr.h" |
38 | #include "llvm/Support/FileSystem.h" |
39 | #include "llvm/Support/JSON.h" |
40 | #include "llvm/Support/LLVMDriver.h" |
41 | #include "llvm/Support/MD5.h" |
42 | #include "llvm/Support/MemoryBuffer.h" |
43 | #include "llvm/Support/Path.h" |
44 | #include "llvm/Support/Regex.h" |
45 | #include "llvm/Support/SHA1.h" |
46 | #include "llvm/Support/SourceMgr.h" |
47 | #include "llvm/Support/SpecialCaseList.h" |
48 | #include "llvm/Support/TargetSelect.h" |
49 | #include "llvm/Support/VirtualFileSystem.h" |
50 | #include "llvm/Support/YAMLParser.h" |
51 | #include "llvm/Support/raw_ostream.h" |
52 | |
53 | #include <set> |
54 | #include <vector> |
55 | |
56 | using namespace llvm; |
57 | |
58 | namespace { |
59 | |
60 | // Command-line option boilerplate. |
61 | namespace { |
62 | using namespace llvm::opt; |
63 | enum ID { |
64 | OPT_INVALID = 0, // This is not an option ID. |
65 | #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__), |
66 | #include "Opts.inc" |
67 | #undef OPTION |
68 | }; |
69 | |
70 | #define PREFIX(NAME, VALUE) \ |
71 | static constexpr StringLiteral NAME##_init[] = VALUE; \ |
72 | static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \ |
73 | std::size(NAME##_init) - 1); |
74 | #include "Opts.inc" |
75 | #undef PREFIX |
76 | |
77 | static constexpr opt::OptTable::Info InfoTable[] = { |
78 | #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__), |
79 | #include "Opts.inc" |
80 | #undef OPTION |
81 | }; |
82 | |
83 | class SancovOptTable : public opt::GenericOptTable { |
84 | public: |
85 | SancovOptTable() : GenericOptTable(InfoTable) {} |
86 | }; |
87 | } // namespace |
88 | |
89 | // --------- COMMAND LINE FLAGS --------- |
90 | |
91 | enum ActionType { |
92 | CoveredFunctionsAction, |
93 | HtmlReportAction, |
94 | MergeAction, |
95 | NotCoveredFunctionsAction, |
96 | PrintAction, |
97 | PrintCovPointsAction, |
98 | StatsAction, |
99 | SymbolizeAction |
100 | }; |
101 | |
102 | static ActionType Action; |
103 | static std::vector<std::string> ClInputFiles; |
104 | static bool ClDemangle; |
105 | static bool ClSkipDeadFiles; |
106 | static bool ClUseDefaultIgnorelist; |
107 | static std::string ClStripPathPrefix; |
108 | static std::string ClIgnorelist; |
109 | |
110 | static const char *const DefaultIgnorelistStr = "fun:__sanitizer_.*\n" |
111 | "src:/usr/include/.*\n" |
112 | "src:.*/libc\\+\\+/.*\n" ; |
113 | |
114 | // --------- FORMAT SPECIFICATION --------- |
115 | |
116 | struct { |
117 | uint32_t ; |
118 | uint32_t ; |
119 | }; |
120 | |
121 | static const uint32_t BinCoverageMagic = 0xC0BFFFFF; |
122 | static const uint32_t Bitness32 = 0xFFFFFF32; |
123 | static const uint32_t Bitness64 = 0xFFFFFF64; |
124 | |
125 | static const Regex SancovFileRegex("(.*)\\.[0-9]+\\.sancov" ); |
126 | static const Regex SymcovFileRegex(".*\\.symcov" ); |
127 | |
128 | // --------- MAIN DATASTRUCTURES ---------- |
129 | |
130 | // Contents of .sancov file: list of coverage point addresses that were |
131 | // executed. |
132 | struct RawCoverage { |
133 | explicit RawCoverage(std::unique_ptr<std::set<uint64_t>> Addrs) |
134 | : Addrs(std::move(Addrs)) {} |
135 | |
136 | // Read binary .sancov file. |
137 | static ErrorOr<std::unique_ptr<RawCoverage>> |
138 | read(const std::string &FileName); |
139 | |
140 | std::unique_ptr<std::set<uint64_t>> Addrs; |
141 | }; |
142 | |
143 | // Coverage point has an opaque Id and corresponds to multiple source locations. |
144 | struct CoveragePoint { |
145 | explicit CoveragePoint(const std::string &Id) : Id(Id) {} |
146 | |
147 | std::string Id; |
148 | SmallVector<DILineInfo, 1> Locs; |
149 | }; |
150 | |
151 | // Symcov file content: set of covered Ids plus information about all available |
152 | // coverage points. |
153 | struct SymbolizedCoverage { |
154 | // Read json .symcov file. |
155 | static std::unique_ptr<SymbolizedCoverage> read(const std::string &InputFile); |
156 | |
157 | std::set<std::string> CoveredIds; |
158 | std::string BinaryHash; |
159 | std::vector<CoveragePoint> Points; |
160 | }; |
161 | |
162 | struct CoverageStats { |
163 | size_t AllPoints; |
164 | size_t CovPoints; |
165 | size_t AllFns; |
166 | size_t CovFns; |
167 | }; |
168 | |
169 | // --------- ERROR HANDLING --------- |
170 | |
171 | static void fail(const llvm::Twine &E) { |
172 | errs() << "ERROR: " << E << "\n" ; |
173 | exit(status: 1); |
174 | } |
175 | |
176 | static void failIf(bool B, const llvm::Twine &E) { |
177 | if (B) |
178 | fail(E); |
179 | } |
180 | |
181 | static void failIfError(std::error_code Error) { |
182 | if (!Error) |
183 | return; |
184 | errs() << "ERROR: " << Error.message() << "(" << Error.value() << ")\n" ; |
185 | exit(status: 1); |
186 | } |
187 | |
188 | template <typename T> static void failIfError(const ErrorOr<T> &E) { |
189 | failIfError(E.getError()); |
190 | } |
191 | |
192 | static void failIfError(Error Err) { |
193 | if (Err) { |
194 | logAllUnhandledErrors(E: std::move(Err), OS&: errs(), ErrorBanner: "ERROR: " ); |
195 | exit(status: 1); |
196 | } |
197 | } |
198 | |
199 | template <typename T> static void failIfError(Expected<T> &E) { |
200 | failIfError(E.takeError()); |
201 | } |
202 | |
203 | static void failIfNotEmpty(const llvm::Twine &E) { |
204 | if (E.str().empty()) |
205 | return; |
206 | fail(E); |
207 | } |
208 | |
209 | template <typename T> |
210 | static void failIfEmpty(const std::unique_ptr<T> &Ptr, |
211 | const std::string &Message) { |
212 | if (Ptr.get()) |
213 | return; |
214 | fail(E: Message); |
215 | } |
216 | |
217 | // ----------- Coverage I/O ---------- |
218 | template <typename T> |
219 | static void readInts(const char *Start, const char *End, |
220 | std::set<uint64_t> *Ints) { |
221 | const T *S = reinterpret_cast<const T *>(Start); |
222 | const T *E = reinterpret_cast<const T *>(End); |
223 | std::copy(S, E, std::inserter(x&: *Ints, i: Ints->end())); |
224 | } |
225 | |
226 | ErrorOr<std::unique_ptr<RawCoverage>> |
227 | RawCoverage::read(const std::string &FileName) { |
228 | ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = |
229 | MemoryBuffer::getFile(Filename: FileName); |
230 | if (!BufOrErr) |
231 | return BufOrErr.getError(); |
232 | std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); |
233 | if (Buf->getBufferSize() < 8) { |
234 | errs() << "File too small (<8): " << Buf->getBufferSize() << '\n'; |
235 | return make_error_code(E: errc::illegal_byte_sequence); |
236 | } |
237 | const FileHeader * = |
238 | reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); |
239 | |
240 | if (Header->Magic != BinCoverageMagic) { |
241 | errs() << "Wrong magic: " << Header->Magic << '\n'; |
242 | return make_error_code(E: errc::illegal_byte_sequence); |
243 | } |
244 | |
245 | auto Addrs = std::make_unique<std::set<uint64_t>>(); |
246 | |
247 | switch (Header->Bitness) { |
248 | case Bitness64: |
249 | readInts<uint64_t>(Start: Buf->getBufferStart() + 8, End: Buf->getBufferEnd(), |
250 | Ints: Addrs.get()); |
251 | break; |
252 | case Bitness32: |
253 | readInts<uint32_t>(Start: Buf->getBufferStart() + 8, End: Buf->getBufferEnd(), |
254 | Ints: Addrs.get()); |
255 | break; |
256 | default: |
257 | errs() << "Unsupported bitness: " << Header->Bitness << '\n'; |
258 | return make_error_code(E: errc::illegal_byte_sequence); |
259 | } |
260 | |
261 | // Ignore slots that are zero, so a runtime implementation is not required |
262 | // to compactify the data. |
263 | Addrs->erase(x: 0); |
264 | |
265 | return std::make_unique<RawCoverage>(args: std::move(Addrs)); |
266 | } |
267 | |
268 | // Print coverage addresses. |
269 | raw_ostream &operator<<(raw_ostream &OS, const RawCoverage &CoverageData) { |
270 | for (auto Addr : *CoverageData.Addrs) { |
271 | OS << "0x" ; |
272 | OS.write_hex(N: Addr); |
273 | OS << "\n" ; |
274 | } |
275 | return OS; |
276 | } |
277 | |
278 | static raw_ostream &operator<<(raw_ostream &OS, const CoverageStats &Stats) { |
279 | OS << "all-edges: " << Stats.AllPoints << "\n" ; |
280 | OS << "cov-edges: " << Stats.CovPoints << "\n" ; |
281 | OS << "all-functions: " << Stats.AllFns << "\n" ; |
282 | OS << "cov-functions: " << Stats.CovFns << "\n" ; |
283 | return OS; |
284 | } |
285 | |
286 | // Output symbolized information for coverage points in JSON. |
287 | // Format: |
288 | // { |
289 | // '<file_name>' : { |
290 | // '<function_name>' : { |
291 | // '<point_id'> : '<line_number>:'<column_number'. |
292 | // .... |
293 | // } |
294 | // } |
295 | // } |
296 | static void operator<<(json::OStream &W, |
297 | const std::vector<CoveragePoint> &Points) { |
298 | // Group points by file. |
299 | std::map<std::string, std::vector<const CoveragePoint *>> PointsByFile; |
300 | for (const auto &Point : Points) { |
301 | for (const DILineInfo &Loc : Point.Locs) { |
302 | PointsByFile[Loc.FileName].push_back(x: &Point); |
303 | } |
304 | } |
305 | |
306 | for (const auto &P : PointsByFile) { |
307 | std::string FileName = P.first; |
308 | std::map<std::string, std::vector<const CoveragePoint *>> PointsByFn; |
309 | for (auto PointPtr : P.second) { |
310 | for (const DILineInfo &Loc : PointPtr->Locs) { |
311 | PointsByFn[Loc.FunctionName].push_back(x: PointPtr); |
312 | } |
313 | } |
314 | |
315 | W.attributeObject(Key: P.first, Contents: [&] { |
316 | // Group points by function. |
317 | for (const auto &P : PointsByFn) { |
318 | std::string FunctionName = P.first; |
319 | std::set<std::string> WrittenIds; |
320 | |
321 | W.attributeObject(Key: FunctionName, Contents: [&] { |
322 | for (const CoveragePoint *Point : P.second) { |
323 | for (const auto &Loc : Point->Locs) { |
324 | if (Loc.FileName != FileName || Loc.FunctionName != FunctionName) |
325 | continue; |
326 | if (WrittenIds.find(x: Point->Id) != WrittenIds.end()) |
327 | continue; |
328 | |
329 | // Output <point_id> : "<line>:<col>". |
330 | WrittenIds.insert(x: Point->Id); |
331 | W.attribute(Key: Point->Id, |
332 | Contents: (utostr(X: Loc.Line) + ":" + utostr(X: Loc.Column))); |
333 | } |
334 | } |
335 | }); |
336 | } |
337 | }); |
338 | } |
339 | } |
340 | |
341 | static void operator<<(json::OStream &W, const SymbolizedCoverage &C) { |
342 | W.object(Contents: [&] { |
343 | W.attributeArray(Key: "covered-points" , Contents: [&] { |
344 | for (const std::string &P : C.CoveredIds) { |
345 | W.value(V: P); |
346 | } |
347 | }); |
348 | W.attribute(Key: "binary-hash" , Contents: C.BinaryHash); |
349 | W.attributeObject(Key: "point-symbol-info" , Contents: [&] { W << C.Points; }); |
350 | }); |
351 | } |
352 | |
353 | static std::string parseScalarString(yaml::Node *N) { |
354 | SmallString<64> StringStorage; |
355 | yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(Val: N); |
356 | failIf(B: !S, E: "expected string" ); |
357 | return std::string(S->getValue(Storage&: StringStorage)); |
358 | } |
359 | |
360 | std::unique_ptr<SymbolizedCoverage> |
361 | SymbolizedCoverage::read(const std::string &InputFile) { |
362 | auto Coverage(std::make_unique<SymbolizedCoverage>()); |
363 | |
364 | std::map<std::string, CoveragePoint> Points; |
365 | ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = |
366 | MemoryBuffer::getFile(Filename: InputFile); |
367 | failIfError(E: BufOrErr); |
368 | |
369 | SourceMgr SM; |
370 | yaml::Stream S(**BufOrErr, SM); |
371 | |
372 | yaml::document_iterator DI = S.begin(); |
373 | failIf(B: DI == S.end(), E: "empty document: " + InputFile); |
374 | yaml::Node *Root = DI->getRoot(); |
375 | failIf(B: !Root, E: "expecting root node: " + InputFile); |
376 | yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Val: Root); |
377 | failIf(B: !Top, E: "expecting mapping node: " + InputFile); |
378 | |
379 | for (auto &KVNode : *Top) { |
380 | auto Key = parseScalarString(N: KVNode.getKey()); |
381 | |
382 | if (Key == "covered-points" ) { |
383 | yaml::SequenceNode *Points = |
384 | dyn_cast<yaml::SequenceNode>(Val: KVNode.getValue()); |
385 | failIf(B: !Points, E: "expected array: " + InputFile); |
386 | |
387 | for (auto I = Points->begin(), E = Points->end(); I != E; ++I) { |
388 | Coverage->CoveredIds.insert(x: parseScalarString(N: &*I)); |
389 | } |
390 | } else if (Key == "binary-hash" ) { |
391 | Coverage->BinaryHash = parseScalarString(N: KVNode.getValue()); |
392 | } else if (Key == "point-symbol-info" ) { |
393 | yaml::MappingNode *PointSymbolInfo = |
394 | dyn_cast<yaml::MappingNode>(Val: KVNode.getValue()); |
395 | failIf(B: !PointSymbolInfo, E: "expected mapping node: " + InputFile); |
396 | |
397 | for (auto &FileKVNode : *PointSymbolInfo) { |
398 | auto Filename = parseScalarString(N: FileKVNode.getKey()); |
399 | |
400 | yaml::MappingNode *FileInfo = |
401 | dyn_cast<yaml::MappingNode>(Val: FileKVNode.getValue()); |
402 | failIf(B: !FileInfo, E: "expected mapping node: " + InputFile); |
403 | |
404 | for (auto &FunctionKVNode : *FileInfo) { |
405 | auto FunctionName = parseScalarString(N: FunctionKVNode.getKey()); |
406 | |
407 | yaml::MappingNode *FunctionInfo = |
408 | dyn_cast<yaml::MappingNode>(Val: FunctionKVNode.getValue()); |
409 | failIf(B: !FunctionInfo, E: "expected mapping node: " + InputFile); |
410 | |
411 | for (auto &PointKVNode : *FunctionInfo) { |
412 | auto PointId = parseScalarString(N: PointKVNode.getKey()); |
413 | auto Loc = parseScalarString(N: PointKVNode.getValue()); |
414 | |
415 | size_t ColonPos = Loc.find(c: ':'); |
416 | failIf(B: ColonPos == std::string::npos, E: "expected ':': " + InputFile); |
417 | |
418 | auto LineStr = Loc.substr(pos: 0, n: ColonPos); |
419 | auto ColStr = Loc.substr(pos: ColonPos + 1, n: Loc.size()); |
420 | |
421 | if (Points.find(x: PointId) == Points.end()) |
422 | Points.insert(x: std::make_pair(x&: PointId, y: CoveragePoint(PointId))); |
423 | |
424 | DILineInfo LineInfo; |
425 | LineInfo.FileName = Filename; |
426 | LineInfo.FunctionName = FunctionName; |
427 | char *End; |
428 | LineInfo.Line = std::strtoul(nptr: LineStr.c_str(), endptr: &End, base: 10); |
429 | LineInfo.Column = std::strtoul(nptr: ColStr.c_str(), endptr: &End, base: 10); |
430 | |
431 | CoveragePoint *CoveragePoint = &Points.find(x: PointId)->second; |
432 | CoveragePoint->Locs.push_back(Elt: LineInfo); |
433 | } |
434 | } |
435 | } |
436 | } else { |
437 | errs() << "Ignoring unknown key: " << Key << "\n" ; |
438 | } |
439 | } |
440 | |
441 | for (auto &KV : Points) { |
442 | Coverage->Points.push_back(x: KV.second); |
443 | } |
444 | |
445 | return Coverage; |
446 | } |
447 | |
448 | // ---------- MAIN FUNCTIONALITY ---------- |
449 | |
450 | std::string stripPathPrefix(std::string Path) { |
451 | if (ClStripPathPrefix.empty()) |
452 | return Path; |
453 | size_t Pos = Path.find(str: ClStripPathPrefix); |
454 | if (Pos == std::string::npos) |
455 | return Path; |
456 | return Path.substr(pos: Pos + ClStripPathPrefix.size()); |
457 | } |
458 | |
459 | static std::unique_ptr<symbolize::LLVMSymbolizer> createSymbolizer() { |
460 | symbolize::LLVMSymbolizer::Options SymbolizerOptions; |
461 | SymbolizerOptions.Demangle = ClDemangle; |
462 | SymbolizerOptions.UseSymbolTable = true; |
463 | return std::make_unique<symbolize::LLVMSymbolizer>(args&: SymbolizerOptions); |
464 | } |
465 | |
466 | static std::string normalizeFilename(const std::string &FileName) { |
467 | SmallString<256> S(FileName); |
468 | sys::path::remove_dots(path&: S, /* remove_dot_dot */ true); |
469 | return stripPathPrefix(Path: sys::path::convert_to_slash(path: std::string(S))); |
470 | } |
471 | |
472 | class Ignorelists { |
473 | public: |
474 | Ignorelists() |
475 | : DefaultIgnorelist(createDefaultIgnorelist()), |
476 | UserIgnorelist(createUserIgnorelist()) {} |
477 | |
478 | bool isIgnorelisted(const DILineInfo &I) { |
479 | if (DefaultIgnorelist && |
480 | DefaultIgnorelist->inSection(Section: "sancov" , Prefix: "fun" , Query: I.FunctionName)) |
481 | return true; |
482 | if (DefaultIgnorelist && |
483 | DefaultIgnorelist->inSection(Section: "sancov" , Prefix: "src" , Query: I.FileName)) |
484 | return true; |
485 | if (UserIgnorelist && |
486 | UserIgnorelist->inSection(Section: "sancov" , Prefix: "fun" , Query: I.FunctionName)) |
487 | return true; |
488 | if (UserIgnorelist && |
489 | UserIgnorelist->inSection(Section: "sancov" , Prefix: "src" , Query: I.FileName)) |
490 | return true; |
491 | return false; |
492 | } |
493 | |
494 | private: |
495 | static std::unique_ptr<SpecialCaseList> createDefaultIgnorelist() { |
496 | if (!ClUseDefaultIgnorelist) |
497 | return std::unique_ptr<SpecialCaseList>(); |
498 | std::unique_ptr<MemoryBuffer> MB = |
499 | MemoryBuffer::getMemBuffer(InputData: DefaultIgnorelistStr); |
500 | std::string Error; |
501 | auto Ignorelist = SpecialCaseList::create(MB: MB.get(), Error); |
502 | failIfNotEmpty(E: Error); |
503 | return Ignorelist; |
504 | } |
505 | |
506 | static std::unique_ptr<SpecialCaseList> createUserIgnorelist() { |
507 | if (ClIgnorelist.empty()) |
508 | return std::unique_ptr<SpecialCaseList>(); |
509 | return SpecialCaseList::createOrDie(Paths: {{ClIgnorelist}}, |
510 | FS&: *vfs::getRealFileSystem()); |
511 | } |
512 | std::unique_ptr<SpecialCaseList> DefaultIgnorelist; |
513 | std::unique_ptr<SpecialCaseList> UserIgnorelist; |
514 | }; |
515 | |
516 | static std::vector<CoveragePoint> |
517 | getCoveragePoints(const std::string &ObjectFile, |
518 | const std::set<uint64_t> &Addrs, |
519 | const std::set<uint64_t> &CoveredAddrs) { |
520 | std::vector<CoveragePoint> Result; |
521 | auto Symbolizer(createSymbolizer()); |
522 | Ignorelists Ig; |
523 | |
524 | std::set<std::string> CoveredFiles; |
525 | if (ClSkipDeadFiles) { |
526 | for (auto Addr : CoveredAddrs) { |
527 | // TODO: it would be neccessary to set proper section index here. |
528 | // object::SectionedAddress::UndefSection works for only absolute |
529 | // addresses. |
530 | object::SectionedAddress ModuleAddress = { |
531 | .Address: Addr, .SectionIndex: object::SectionedAddress::UndefSection}; |
532 | |
533 | auto LineInfo = Symbolizer->symbolizeCode(ModuleName: ObjectFile, ModuleOffset: ModuleAddress); |
534 | failIfError(E&: LineInfo); |
535 | CoveredFiles.insert(x: LineInfo->FileName); |
536 | auto InliningInfo = |
537 | Symbolizer->symbolizeInlinedCode(ModuleName: ObjectFile, ModuleOffset: ModuleAddress); |
538 | failIfError(E&: InliningInfo); |
539 | for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { |
540 | auto FrameInfo = InliningInfo->getFrame(Index: I); |
541 | CoveredFiles.insert(x: FrameInfo.FileName); |
542 | } |
543 | } |
544 | } |
545 | |
546 | for (auto Addr : Addrs) { |
547 | std::set<DILineInfo> Infos; // deduplicate debug info. |
548 | |
549 | // TODO: it would be neccessary to set proper section index here. |
550 | // object::SectionedAddress::UndefSection works for only absolute addresses. |
551 | object::SectionedAddress ModuleAddress = { |
552 | .Address: Addr, .SectionIndex: object::SectionedAddress::UndefSection}; |
553 | |
554 | auto LineInfo = Symbolizer->symbolizeCode(ModuleName: ObjectFile, ModuleOffset: ModuleAddress); |
555 | failIfError(E&: LineInfo); |
556 | if (ClSkipDeadFiles && |
557 | CoveredFiles.find(x: LineInfo->FileName) == CoveredFiles.end()) |
558 | continue; |
559 | LineInfo->FileName = normalizeFilename(FileName: LineInfo->FileName); |
560 | if (Ig.isIgnorelisted(I: *LineInfo)) |
561 | continue; |
562 | |
563 | auto Id = utohexstr(X: Addr, LowerCase: true); |
564 | auto Point = CoveragePoint(Id); |
565 | Infos.insert(x: *LineInfo); |
566 | Point.Locs.push_back(Elt: *LineInfo); |
567 | |
568 | auto InliningInfo = |
569 | Symbolizer->symbolizeInlinedCode(ModuleName: ObjectFile, ModuleOffset: ModuleAddress); |
570 | failIfError(E&: InliningInfo); |
571 | for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { |
572 | auto FrameInfo = InliningInfo->getFrame(Index: I); |
573 | if (ClSkipDeadFiles && |
574 | CoveredFiles.find(x: FrameInfo.FileName) == CoveredFiles.end()) |
575 | continue; |
576 | FrameInfo.FileName = normalizeFilename(FileName: FrameInfo.FileName); |
577 | if (Ig.isIgnorelisted(I: FrameInfo)) |
578 | continue; |
579 | if (Infos.find(x: FrameInfo) == Infos.end()) { |
580 | Infos.insert(x: FrameInfo); |
581 | Point.Locs.push_back(Elt: FrameInfo); |
582 | } |
583 | } |
584 | |
585 | Result.push_back(x: Point); |
586 | } |
587 | |
588 | return Result; |
589 | } |
590 | |
591 | static bool isCoveragePointSymbol(StringRef Name) { |
592 | return Name == "__sanitizer_cov" || Name == "__sanitizer_cov_with_check" || |
593 | Name == "__sanitizer_cov_trace_func_enter" || |
594 | Name == "__sanitizer_cov_trace_pc_guard" || |
595 | // Mac has '___' prefix |
596 | Name == "___sanitizer_cov" || Name == "___sanitizer_cov_with_check" || |
597 | Name == "___sanitizer_cov_trace_func_enter" || |
598 | Name == "___sanitizer_cov_trace_pc_guard" ; |
599 | } |
600 | |
601 | // Locate __sanitizer_cov* function addresses inside the stubs table on MachO. |
602 | static void findMachOIndirectCovFunctions(const object::MachOObjectFile &O, |
603 | std::set<uint64_t> *Result) { |
604 | MachO::dysymtab_command Dysymtab = O.getDysymtabLoadCommand(); |
605 | MachO::symtab_command Symtab = O.getSymtabLoadCommand(); |
606 | |
607 | for (const auto &Load : O.load_commands()) { |
608 | if (Load.C.cmd == MachO::LC_SEGMENT_64) { |
609 | MachO::segment_command_64 Seg = O.getSegment64LoadCommand(L: Load); |
610 | for (unsigned J = 0; J < Seg.nsects; ++J) { |
611 | MachO::section_64 Sec = O.getSection64(L: Load, Index: J); |
612 | |
613 | uint32_t SectionType = Sec.flags & MachO::SECTION_TYPE; |
614 | if (SectionType == MachO::S_SYMBOL_STUBS) { |
615 | uint32_t Stride = Sec.reserved2; |
616 | uint32_t Cnt = Sec.size / Stride; |
617 | uint32_t N = Sec.reserved1; |
618 | for (uint32_t J = 0; J < Cnt && N + J < Dysymtab.nindirectsyms; J++) { |
619 | uint32_t IndirectSymbol = |
620 | O.getIndirectSymbolTableEntry(DLC: Dysymtab, Index: N + J); |
621 | uint64_t Addr = Sec.addr + J * Stride; |
622 | if (IndirectSymbol < Symtab.nsyms) { |
623 | object::SymbolRef Symbol = *(O.getSymbolByIndex(Index: IndirectSymbol)); |
624 | Expected<StringRef> Name = Symbol.getName(); |
625 | failIfError(E&: Name); |
626 | if (isCoveragePointSymbol(Name: Name.get())) { |
627 | Result->insert(x: Addr); |
628 | } |
629 | } |
630 | } |
631 | } |
632 | } |
633 | } |
634 | if (Load.C.cmd == MachO::LC_SEGMENT) { |
635 | errs() << "ERROR: 32 bit MachO binaries not supported\n" ; |
636 | } |
637 | } |
638 | } |
639 | |
640 | // Locate __sanitizer_cov* function addresses that are used for coverage |
641 | // reporting. |
642 | static std::set<uint64_t> |
643 | findSanitizerCovFunctions(const object::ObjectFile &O) { |
644 | std::set<uint64_t> Result; |
645 | |
646 | for (const object::SymbolRef &Symbol : O.symbols()) { |
647 | Expected<uint64_t> AddressOrErr = Symbol.getAddress(); |
648 | failIfError(E&: AddressOrErr); |
649 | uint64_t Address = AddressOrErr.get(); |
650 | |
651 | Expected<StringRef> NameOrErr = Symbol.getName(); |
652 | failIfError(E&: NameOrErr); |
653 | StringRef Name = NameOrErr.get(); |
654 | |
655 | Expected<uint32_t> FlagsOrErr = Symbol.getFlags(); |
656 | // TODO: Test this error. |
657 | failIfError(E&: FlagsOrErr); |
658 | uint32_t Flags = FlagsOrErr.get(); |
659 | |
660 | if (!(Flags & object::BasicSymbolRef::SF_Undefined) && |
661 | isCoveragePointSymbol(Name)) { |
662 | Result.insert(x: Address); |
663 | } |
664 | } |
665 | |
666 | if (const auto *CO = dyn_cast<object::COFFObjectFile>(Val: &O)) { |
667 | for (const object::ExportDirectoryEntryRef &Export : |
668 | CO->export_directories()) { |
669 | uint32_t RVA; |
670 | failIfError(Err: Export.getExportRVA(Result&: RVA)); |
671 | |
672 | StringRef Name; |
673 | failIfError(Err: Export.getSymbolName(Result&: Name)); |
674 | |
675 | if (isCoveragePointSymbol(Name)) |
676 | Result.insert(x: CO->getImageBase() + RVA); |
677 | } |
678 | } |
679 | |
680 | if (const auto *MO = dyn_cast<object::MachOObjectFile>(Val: &O)) { |
681 | findMachOIndirectCovFunctions(O: *MO, Result: &Result); |
682 | } |
683 | |
684 | return Result; |
685 | } |
686 | |
687 | // Ported from |
688 | // compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.h:GetPreviousInstructionPc |
689 | // GetPreviousInstructionPc. |
690 | static uint64_t getPreviousInstructionPc(uint64_t PC, Triple TheTriple) { |
691 | if (TheTriple.isARM()) |
692 | return (PC - 3) & (~1); |
693 | if (TheTriple.isMIPS() || TheTriple.isSPARC()) |
694 | return PC - 8; |
695 | if (TheTriple.isRISCV()) |
696 | return PC - 2; |
697 | if (TheTriple.isX86() || TheTriple.isSystemZ()) |
698 | return PC - 1; |
699 | return PC - 4; |
700 | } |
701 | |
702 | // Locate addresses of all coverage points in a file. Coverage point |
703 | // is defined as the 'address of instruction following __sanitizer_cov |
704 | // call - 1'. |
705 | static void getObjectCoveragePoints(const object::ObjectFile &O, |
706 | std::set<uint64_t> *Addrs) { |
707 | Triple TheTriple("unknown-unknown-unknown" ); |
708 | TheTriple.setArch(Kind: Triple::ArchType(O.getArch())); |
709 | auto TripleName = TheTriple.getTriple(); |
710 | |
711 | std::string Error; |
712 | const Target *TheTarget = TargetRegistry::lookupTarget(Triple: TripleName, Error); |
713 | failIfNotEmpty(E: Error); |
714 | |
715 | std::unique_ptr<const MCSubtargetInfo> STI( |
716 | TheTarget->createMCSubtargetInfo(TheTriple: TripleName, CPU: "" , Features: "" )); |
717 | failIfEmpty(Ptr: STI, Message: "no subtarget info for target " + TripleName); |
718 | |
719 | std::unique_ptr<const MCRegisterInfo> MRI( |
720 | TheTarget->createMCRegInfo(TT: TripleName)); |
721 | failIfEmpty(Ptr: MRI, Message: "no register info for target " + TripleName); |
722 | |
723 | MCTargetOptions MCOptions; |
724 | std::unique_ptr<const MCAsmInfo> AsmInfo( |
725 | TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple: TripleName, Options: MCOptions)); |
726 | failIfEmpty(Ptr: AsmInfo, Message: "no asm info for target " + TripleName); |
727 | |
728 | MCContext Ctx(TheTriple, AsmInfo.get(), MRI.get(), STI.get()); |
729 | std::unique_ptr<MCDisassembler> DisAsm( |
730 | TheTarget->createMCDisassembler(STI: *STI, Ctx)); |
731 | failIfEmpty(Ptr: DisAsm, Message: "no disassembler info for target " + TripleName); |
732 | |
733 | std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); |
734 | failIfEmpty(Ptr: MII, Message: "no instruction info for target " + TripleName); |
735 | |
736 | std::unique_ptr<const MCInstrAnalysis> MIA( |
737 | TheTarget->createMCInstrAnalysis(Info: MII.get())); |
738 | failIfEmpty(Ptr: MIA, Message: "no instruction analysis info for target " + TripleName); |
739 | |
740 | auto SanCovAddrs = findSanitizerCovFunctions(O); |
741 | if (SanCovAddrs.empty()) |
742 | fail(E: "__sanitizer_cov* functions not found" ); |
743 | |
744 | for (object::SectionRef Section : O.sections()) { |
745 | if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same. |
746 | continue; |
747 | uint64_t SectionAddr = Section.getAddress(); |
748 | uint64_t SectSize = Section.getSize(); |
749 | if (!SectSize) |
750 | continue; |
751 | |
752 | Expected<StringRef> BytesStr = Section.getContents(); |
753 | failIfError(E&: BytesStr); |
754 | ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(Input: *BytesStr); |
755 | |
756 | for (uint64_t Index = 0, Size = 0; Index < Section.getSize(); |
757 | Index += Size) { |
758 | MCInst Inst; |
759 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index); |
760 | uint64_t ThisAddr = SectionAddr + Index; |
761 | if (!DisAsm->getInstruction(Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: nulls())) { |
762 | if (Size == 0) |
763 | Size = std::min<uint64_t>( |
764 | a: ThisBytes.size(), |
765 | b: DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: ThisAddr)); |
766 | continue; |
767 | } |
768 | uint64_t Addr = Index + SectionAddr; |
769 | // Sanitizer coverage uses the address of the next instruction - 1. |
770 | uint64_t CovPoint = getPreviousInstructionPc(PC: Addr + Size, TheTriple); |
771 | uint64_t Target; |
772 | if (MIA->isCall(Inst) && |
773 | MIA->evaluateBranch(Inst, Addr: SectionAddr + Index, Size, Target) && |
774 | SanCovAddrs.find(x: Target) != SanCovAddrs.end()) |
775 | Addrs->insert(x: CovPoint); |
776 | } |
777 | } |
778 | } |
779 | |
780 | static void |
781 | visitObjectFiles(const object::Archive &A, |
782 | function_ref<void(const object::ObjectFile &)> Fn) { |
783 | Error Err = Error::success(); |
784 | for (auto &C : A.children(Err)) { |
785 | Expected<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary(); |
786 | failIfError(E&: ChildOrErr); |
787 | if (auto *O = dyn_cast<object::ObjectFile>(Val: &*ChildOrErr.get())) |
788 | Fn(*O); |
789 | else |
790 | failIfError(Error: object::object_error::invalid_file_type); |
791 | } |
792 | failIfError(Err: std::move(Err)); |
793 | } |
794 | |
795 | static void |
796 | visitObjectFiles(const std::string &FileName, |
797 | function_ref<void(const object::ObjectFile &)> Fn) { |
798 | Expected<object::OwningBinary<object::Binary>> BinaryOrErr = |
799 | object::createBinary(Path: FileName); |
800 | if (!BinaryOrErr) |
801 | failIfError(E&: BinaryOrErr); |
802 | |
803 | object::Binary &Binary = *BinaryOrErr.get().getBinary(); |
804 | if (object::Archive *A = dyn_cast<object::Archive>(Val: &Binary)) |
805 | visitObjectFiles(A: *A, Fn); |
806 | else if (object::ObjectFile *O = dyn_cast<object::ObjectFile>(Val: &Binary)) |
807 | Fn(*O); |
808 | else |
809 | failIfError(Error: object::object_error::invalid_file_type); |
810 | } |
811 | |
812 | static std::set<uint64_t> |
813 | findSanitizerCovFunctions(const std::string &FileName) { |
814 | std::set<uint64_t> Result; |
815 | visitObjectFiles(FileName, Fn: [&](const object::ObjectFile &O) { |
816 | auto Addrs = findSanitizerCovFunctions(O); |
817 | Result.insert(first: Addrs.begin(), last: Addrs.end()); |
818 | }); |
819 | return Result; |
820 | } |
821 | |
822 | // Locate addresses of all coverage points in a file. Coverage point |
823 | // is defined as the 'address of instruction following __sanitizer_cov |
824 | // call - 1'. |
825 | static std::set<uint64_t> findCoveragePointAddrs(const std::string &FileName) { |
826 | std::set<uint64_t> Result; |
827 | visitObjectFiles(FileName, Fn: [&](const object::ObjectFile &O) { |
828 | getObjectCoveragePoints(O, Addrs: &Result); |
829 | }); |
830 | return Result; |
831 | } |
832 | |
833 | static void printCovPoints(const std::string &ObjFile, raw_ostream &OS) { |
834 | for (uint64_t Addr : findCoveragePointAddrs(FileName: ObjFile)) { |
835 | OS << "0x" ; |
836 | OS.write_hex(N: Addr); |
837 | OS << "\n" ; |
838 | } |
839 | } |
840 | |
841 | static ErrorOr<bool> isCoverageFile(const std::string &FileName) { |
842 | auto ShortFileName = llvm::sys::path::filename(path: FileName); |
843 | if (!SancovFileRegex.match(String: ShortFileName)) |
844 | return false; |
845 | |
846 | ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = |
847 | MemoryBuffer::getFile(Filename: FileName); |
848 | if (!BufOrErr) { |
849 | errs() << "Warning: " << BufOrErr.getError().message() << "(" |
850 | << BufOrErr.getError().value() |
851 | << "), filename: " << llvm::sys::path::filename(path: FileName) << "\n" ; |
852 | return BufOrErr.getError(); |
853 | } |
854 | std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); |
855 | if (Buf->getBufferSize() < 8) { |
856 | return false; |
857 | } |
858 | const FileHeader * = |
859 | reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); |
860 | return Header->Magic == BinCoverageMagic; |
861 | } |
862 | |
863 | static bool isSymbolizedCoverageFile(const std::string &FileName) { |
864 | auto ShortFileName = llvm::sys::path::filename(path: FileName); |
865 | return SymcovFileRegex.match(String: ShortFileName); |
866 | } |
867 | |
868 | static std::unique_ptr<SymbolizedCoverage> |
869 | symbolize(const RawCoverage &Data, const std::string ObjectFile) { |
870 | auto Coverage = std::make_unique<SymbolizedCoverage>(); |
871 | |
872 | ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = |
873 | MemoryBuffer::getFile(Filename: ObjectFile); |
874 | failIfError(E: BufOrErr); |
875 | SHA1 Hasher; |
876 | Hasher.update(Str: (*BufOrErr)->getBuffer()); |
877 | Coverage->BinaryHash = toHex(Input: Hasher.final()); |
878 | |
879 | Ignorelists Ig; |
880 | auto Symbolizer(createSymbolizer()); |
881 | |
882 | for (uint64_t Addr : *Data.Addrs) { |
883 | // TODO: it would be neccessary to set proper section index here. |
884 | // object::SectionedAddress::UndefSection works for only absolute addresses. |
885 | auto LineInfo = Symbolizer->symbolizeCode( |
886 | ModuleName: ObjectFile, ModuleOffset: {.Address: Addr, .SectionIndex: object::SectionedAddress::UndefSection}); |
887 | failIfError(E&: LineInfo); |
888 | if (Ig.isIgnorelisted(I: *LineInfo)) |
889 | continue; |
890 | |
891 | Coverage->CoveredIds.insert(x: utohexstr(X: Addr, LowerCase: true)); |
892 | } |
893 | |
894 | std::set<uint64_t> AllAddrs = findCoveragePointAddrs(FileName: ObjectFile); |
895 | if (!std::includes(first1: AllAddrs.begin(), last1: AllAddrs.end(), first2: Data.Addrs->begin(), |
896 | last2: Data.Addrs->end())) { |
897 | fail(E: "Coverage points in binary and .sancov file do not match." ); |
898 | } |
899 | Coverage->Points = getCoveragePoints(ObjectFile, Addrs: AllAddrs, CoveredAddrs: *Data.Addrs); |
900 | return Coverage; |
901 | } |
902 | |
903 | struct FileFn { |
904 | bool operator<(const FileFn &RHS) const { |
905 | return std::tie(args: FileName, args: FunctionName) < |
906 | std::tie(args: RHS.FileName, args: RHS.FunctionName); |
907 | } |
908 | |
909 | std::string FileName; |
910 | std::string FunctionName; |
911 | }; |
912 | |
913 | static std::set<FileFn> |
914 | computeFunctions(const std::vector<CoveragePoint> &Points) { |
915 | std::set<FileFn> Fns; |
916 | for (const auto &Point : Points) { |
917 | for (const auto &Loc : Point.Locs) { |
918 | Fns.insert(x: FileFn{.FileName: Loc.FileName, .FunctionName: Loc.FunctionName}); |
919 | } |
920 | } |
921 | return Fns; |
922 | } |
923 | |
924 | static std::set<FileFn> |
925 | computeNotCoveredFunctions(const SymbolizedCoverage &Coverage) { |
926 | auto Fns = computeFunctions(Points: Coverage.Points); |
927 | |
928 | for (const auto &Point : Coverage.Points) { |
929 | if (Coverage.CoveredIds.find(x: Point.Id) == Coverage.CoveredIds.end()) |
930 | continue; |
931 | |
932 | for (const auto &Loc : Point.Locs) { |
933 | Fns.erase(x: FileFn{.FileName: Loc.FileName, .FunctionName: Loc.FunctionName}); |
934 | } |
935 | } |
936 | |
937 | return Fns; |
938 | } |
939 | |
940 | static std::set<FileFn> |
941 | computeCoveredFunctions(const SymbolizedCoverage &Coverage) { |
942 | auto AllFns = computeFunctions(Points: Coverage.Points); |
943 | std::set<FileFn> Result; |
944 | |
945 | for (const auto &Point : Coverage.Points) { |
946 | if (Coverage.CoveredIds.find(x: Point.Id) == Coverage.CoveredIds.end()) |
947 | continue; |
948 | |
949 | for (const auto &Loc : Point.Locs) { |
950 | Result.insert(x: FileFn{.FileName: Loc.FileName, .FunctionName: Loc.FunctionName}); |
951 | } |
952 | } |
953 | |
954 | return Result; |
955 | } |
956 | |
957 | typedef std::map<FileFn, std::pair<uint32_t, uint32_t>> FunctionLocs; |
958 | // finds first location in a file for each function. |
959 | static FunctionLocs resolveFunctions(const SymbolizedCoverage &Coverage, |
960 | const std::set<FileFn> &Fns) { |
961 | FunctionLocs Result; |
962 | for (const auto &Point : Coverage.Points) { |
963 | for (const auto &Loc : Point.Locs) { |
964 | FileFn Fn = FileFn{.FileName: Loc.FileName, .FunctionName: Loc.FunctionName}; |
965 | if (Fns.find(x: Fn) == Fns.end()) |
966 | continue; |
967 | |
968 | auto P = std::make_pair(x: Loc.Line, y: Loc.Column); |
969 | auto I = Result.find(x: Fn); |
970 | if (I == Result.end() || I->second > P) { |
971 | Result[Fn] = P; |
972 | } |
973 | } |
974 | } |
975 | return Result; |
976 | } |
977 | |
978 | static void printFunctionLocs(const FunctionLocs &FnLocs, raw_ostream &OS) { |
979 | for (const auto &P : FnLocs) { |
980 | OS << stripPathPrefix(Path: P.first.FileName) << ":" << P.second.first << " " |
981 | << P.first.FunctionName << "\n" ; |
982 | } |
983 | } |
984 | CoverageStats computeStats(const SymbolizedCoverage &Coverage) { |
985 | CoverageStats Stats = {.AllPoints: Coverage.Points.size(), .CovPoints: Coverage.CoveredIds.size(), |
986 | .AllFns: computeFunctions(Points: Coverage.Points).size(), |
987 | .CovFns: computeCoveredFunctions(Coverage).size()}; |
988 | return Stats; |
989 | } |
990 | |
991 | // Print list of covered functions. |
992 | // Line format: <file_name>:<line> <function_name> |
993 | static void printCoveredFunctions(const SymbolizedCoverage &CovData, |
994 | raw_ostream &OS) { |
995 | auto CoveredFns = computeCoveredFunctions(Coverage: CovData); |
996 | printFunctionLocs(FnLocs: resolveFunctions(Coverage: CovData, Fns: CoveredFns), OS); |
997 | } |
998 | |
999 | // Print list of not covered functions. |
1000 | // Line format: <file_name>:<line> <function_name> |
1001 | static void printNotCoveredFunctions(const SymbolizedCoverage &CovData, |
1002 | raw_ostream &OS) { |
1003 | auto NotCoveredFns = computeNotCoveredFunctions(Coverage: CovData); |
1004 | printFunctionLocs(FnLocs: resolveFunctions(Coverage: CovData, Fns: NotCoveredFns), OS); |
1005 | } |
1006 | |
1007 | // Read list of files and merges their coverage info. |
1008 | static void readAndPrintRawCoverage(const std::vector<std::string> &FileNames, |
1009 | raw_ostream &OS) { |
1010 | std::vector<std::unique_ptr<RawCoverage>> Covs; |
1011 | for (const auto &FileName : FileNames) { |
1012 | auto Cov = RawCoverage::read(FileName); |
1013 | if (!Cov) |
1014 | continue; |
1015 | OS << *Cov.get(); |
1016 | } |
1017 | } |
1018 | |
1019 | static std::unique_ptr<SymbolizedCoverage> |
1020 | merge(const std::vector<std::unique_ptr<SymbolizedCoverage>> &Coverages) { |
1021 | if (Coverages.empty()) |
1022 | return nullptr; |
1023 | |
1024 | auto Result = std::make_unique<SymbolizedCoverage>(); |
1025 | |
1026 | for (size_t I = 0; I < Coverages.size(); ++I) { |
1027 | const SymbolizedCoverage &Coverage = *Coverages[I]; |
1028 | std::string Prefix; |
1029 | if (Coverages.size() > 1) { |
1030 | // prefix is not needed when there's only one file. |
1031 | Prefix = utostr(X: I); |
1032 | } |
1033 | |
1034 | for (const auto &Id : Coverage.CoveredIds) { |
1035 | Result->CoveredIds.insert(x: Prefix + Id); |
1036 | } |
1037 | |
1038 | for (const auto &CovPoint : Coverage.Points) { |
1039 | CoveragePoint NewPoint(CovPoint); |
1040 | NewPoint.Id = Prefix + CovPoint.Id; |
1041 | Result->Points.push_back(x: NewPoint); |
1042 | } |
1043 | } |
1044 | |
1045 | if (Coverages.size() == 1) { |
1046 | Result->BinaryHash = Coverages[0]->BinaryHash; |
1047 | } |
1048 | |
1049 | return Result; |
1050 | } |
1051 | |
1052 | static std::unique_ptr<SymbolizedCoverage> |
1053 | readSymbolizeAndMergeCmdArguments(std::vector<std::string> FileNames) { |
1054 | std::vector<std::unique_ptr<SymbolizedCoverage>> Coverages; |
1055 | |
1056 | { |
1057 | // Short name => file name. |
1058 | std::map<std::string, std::string> ObjFiles; |
1059 | std::string FirstObjFile; |
1060 | std::set<std::string> CovFiles; |
1061 | |
1062 | // Partition input values into coverage/object files. |
1063 | for (const auto &FileName : FileNames) { |
1064 | if (isSymbolizedCoverageFile(FileName)) { |
1065 | Coverages.push_back(x: SymbolizedCoverage::read(InputFile: FileName)); |
1066 | } |
1067 | |
1068 | auto ErrorOrIsCoverage = isCoverageFile(FileName); |
1069 | if (!ErrorOrIsCoverage) |
1070 | continue; |
1071 | if (ErrorOrIsCoverage.get()) { |
1072 | CovFiles.insert(x: FileName); |
1073 | } else { |
1074 | auto ShortFileName = llvm::sys::path::filename(path: FileName); |
1075 | if (ObjFiles.find(x: std::string(ShortFileName)) != ObjFiles.end()) { |
1076 | fail(E: "Duplicate binary file with a short name: " + ShortFileName); |
1077 | } |
1078 | |
1079 | ObjFiles[std::string(ShortFileName)] = FileName; |
1080 | if (FirstObjFile.empty()) |
1081 | FirstObjFile = FileName; |
1082 | } |
1083 | } |
1084 | |
1085 | SmallVector<StringRef, 2> Components; |
1086 | |
1087 | // Object file => list of corresponding coverage file names. |
1088 | std::map<std::string, std::vector<std::string>> CoverageByObjFile; |
1089 | for (const auto &FileName : CovFiles) { |
1090 | auto ShortFileName = llvm::sys::path::filename(path: FileName); |
1091 | auto Ok = SancovFileRegex.match(String: ShortFileName, Matches: &Components); |
1092 | if (!Ok) { |
1093 | fail(E: "Can't match coverage file name against " |
1094 | "<module_name>.<pid>.sancov pattern: " + |
1095 | FileName); |
1096 | } |
1097 | |
1098 | auto Iter = ObjFiles.find(x: std::string(Components[1])); |
1099 | if (Iter == ObjFiles.end()) { |
1100 | fail(E: "Object file for coverage not found: " + FileName); |
1101 | } |
1102 | |
1103 | CoverageByObjFile[Iter->second].push_back(x: FileName); |
1104 | }; |
1105 | |
1106 | for (const auto &Pair : ObjFiles) { |
1107 | auto FileName = Pair.second; |
1108 | if (CoverageByObjFile.find(x: FileName) == CoverageByObjFile.end()) |
1109 | errs() << "WARNING: No coverage file for " << FileName << "\n" ; |
1110 | } |
1111 | |
1112 | // Read raw coverage and symbolize it. |
1113 | for (const auto &Pair : CoverageByObjFile) { |
1114 | if (findSanitizerCovFunctions(FileName: Pair.first).empty()) { |
1115 | errs() |
1116 | << "WARNING: Ignoring " << Pair.first |
1117 | << " and its coverage because __sanitizer_cov* functions were not " |
1118 | "found.\n" ; |
1119 | continue; |
1120 | } |
1121 | |
1122 | for (const std::string &CoverageFile : Pair.second) { |
1123 | auto DataOrError = RawCoverage::read(FileName: CoverageFile); |
1124 | failIfError(E: DataOrError); |
1125 | Coverages.push_back(x: symbolize(Data: *DataOrError.get(), ObjectFile: Pair.first)); |
1126 | } |
1127 | } |
1128 | } |
1129 | |
1130 | return merge(Coverages); |
1131 | } |
1132 | |
1133 | } // namespace |
1134 | |
1135 | static void parseArgs(int Argc, char **Argv) { |
1136 | SancovOptTable Tbl; |
1137 | llvm::BumpPtrAllocator A; |
1138 | llvm::StringSaver Saver{A}; |
1139 | opt::InputArgList Args = |
1140 | Tbl.parseArgs(Argc, Argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) { |
1141 | llvm::errs() << Msg << '\n'; |
1142 | std::exit(status: 1); |
1143 | }); |
1144 | |
1145 | if (Args.hasArg(Ids: OPT_help)) { |
1146 | Tbl.printHelp( |
1147 | OS&: llvm::outs(), |
1148 | Usage: "sancov [options] <action> <binary files...> <.sancov files...> " |
1149 | "<.symcov files...>" , |
1150 | Title: "Sanitizer Coverage Processing Tool (sancov)\n\n" |
1151 | " This tool can extract various coverage-related information from: \n" |
1152 | " coverage-instrumented binary files, raw .sancov files and their " |
1153 | "symbolized .symcov version.\n" |
1154 | " Depending on chosen action the tool expects different input files:\n" |
1155 | " -print-coverage-pcs - coverage-instrumented binary files\n" |
1156 | " -print-coverage - .sancov files\n" |
1157 | " <other actions> - .sancov files & corresponding binary " |
1158 | "files, .symcov files\n" ); |
1159 | std::exit(status: 0); |
1160 | } |
1161 | |
1162 | if (Args.hasArg(Ids: OPT_version)) { |
1163 | cl::PrintVersionMessage(); |
1164 | std::exit(status: 0); |
1165 | } |
1166 | |
1167 | if (Args.hasMultipleArgs(Id: OPT_action_grp)) { |
1168 | fail(E: "Only one action option is allowed" ); |
1169 | } |
1170 | |
1171 | for (const opt::Arg *A : Args.filtered(Ids: OPT_INPUT)) { |
1172 | ClInputFiles.emplace_back(args: A->getValue()); |
1173 | } |
1174 | |
1175 | if (const llvm::opt::Arg *A = Args.getLastArg(Ids: OPT_action_grp)) { |
1176 | switch (A->getOption().getID()) { |
1177 | case OPT_print: |
1178 | Action = ActionType::PrintAction; |
1179 | break; |
1180 | case OPT_printCoveragePcs: |
1181 | Action = ActionType::PrintCovPointsAction; |
1182 | break; |
1183 | case OPT_coveredFunctions: |
1184 | Action = ActionType::CoveredFunctionsAction; |
1185 | break; |
1186 | case OPT_notCoveredFunctions: |
1187 | Action = ActionType::NotCoveredFunctionsAction; |
1188 | break; |
1189 | case OPT_printCoverageStats: |
1190 | Action = ActionType::StatsAction; |
1191 | break; |
1192 | case OPT_htmlReport: |
1193 | Action = ActionType::HtmlReportAction; |
1194 | break; |
1195 | case OPT_symbolize: |
1196 | Action = ActionType::SymbolizeAction; |
1197 | break; |
1198 | case OPT_merge: |
1199 | Action = ActionType::MergeAction; |
1200 | break; |
1201 | default: |
1202 | fail(E: "Invalid Action" ); |
1203 | } |
1204 | } |
1205 | |
1206 | ClDemangle = Args.hasFlag(Pos: OPT_demangle, Neg: OPT_no_demangle, Default: true); |
1207 | ClSkipDeadFiles = Args.hasFlag(Pos: OPT_skipDeadFiles, Neg: OPT_no_skipDeadFiles, Default: true); |
1208 | ClUseDefaultIgnorelist = |
1209 | Args.hasFlag(Pos: OPT_useDefaultIgnoreList, Neg: OPT_no_useDefaultIgnoreList, Default: true); |
1210 | |
1211 | ClStripPathPrefix = Args.getLastArgValue(Id: OPT_stripPathPrefix_EQ); |
1212 | ClIgnorelist = Args.getLastArgValue(Id: OPT_ignorelist_EQ); |
1213 | } |
1214 | |
1215 | int sancov_main(int Argc, char **Argv, const llvm::ToolContext &) { |
1216 | llvm::InitializeAllTargetInfos(); |
1217 | llvm::InitializeAllTargetMCs(); |
1218 | llvm::InitializeAllDisassemblers(); |
1219 | |
1220 | parseArgs(Argc, Argv); |
1221 | |
1222 | // -print doesn't need object files. |
1223 | if (Action == PrintAction) { |
1224 | readAndPrintRawCoverage(FileNames: ClInputFiles, OS&: outs()); |
1225 | return 0; |
1226 | } |
1227 | if (Action == PrintCovPointsAction) { |
1228 | // -print-coverage-points doesn't need coverage files. |
1229 | for (const std::string &ObjFile : ClInputFiles) { |
1230 | printCovPoints(ObjFile, OS&: outs()); |
1231 | } |
1232 | return 0; |
1233 | } |
1234 | |
1235 | auto Coverage = readSymbolizeAndMergeCmdArguments(FileNames: ClInputFiles); |
1236 | failIf(B: !Coverage, E: "No valid coverage files given." ); |
1237 | |
1238 | switch (Action) { |
1239 | case CoveredFunctionsAction: { |
1240 | printCoveredFunctions(CovData: *Coverage, OS&: outs()); |
1241 | return 0; |
1242 | } |
1243 | case NotCoveredFunctionsAction: { |
1244 | printNotCoveredFunctions(CovData: *Coverage, OS&: outs()); |
1245 | return 0; |
1246 | } |
1247 | case StatsAction: { |
1248 | outs() << computeStats(Coverage: *Coverage); |
1249 | return 0; |
1250 | } |
1251 | case MergeAction: |
1252 | case SymbolizeAction: { // merge & symbolize are synonims. |
1253 | json::OStream W(outs(), 2); |
1254 | W << *Coverage; |
1255 | return 0; |
1256 | } |
1257 | case HtmlReportAction: |
1258 | errs() << "-html-report option is removed: " |
1259 | "use -symbolize & coverage-report-server.py instead\n" ; |
1260 | return 1; |
1261 | case PrintAction: |
1262 | case PrintCovPointsAction: |
1263 | llvm_unreachable("unsupported action" ); |
1264 | } |
1265 | |
1266 | return 0; |
1267 | } |
1268 | |