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(std::move(Err), errs(), "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(*Ints, 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); |
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>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), |
250 | Addrs.get()); |
251 | break; |
252 | case Bitness32: |
253 | readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), |
254 | 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(0); |
264 | |
265 | return std::unique_ptr<RawCoverage>(new RawCoverage(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(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(&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(PointPtr); |
312 | } |
313 | } |
314 | |
315 | W.attributeObject(P.first, [&] { |
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(FunctionName, [&] { |
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(Point->Id) != WrittenIds.end()) |
327 | continue; |
328 | |
329 | // Output <point_id> : "<line>:<col>". |
330 | WrittenIds.insert(Point->Id); |
331 | W.attribute(Point->Id, |
332 | (utostr(Loc.Line) + ":" + utostr(Loc.Column))); |
333 | } |
334 | } |
335 | }); |
336 | } |
337 | }); |
338 | } |
339 | } |
340 | |
341 | static void operator<<(json::OStream &W, const SymbolizedCoverage &C) { |
342 | W.object([&] { |
343 | W.attributeArray("covered-points" , [&] { |
344 | for (const std::string &P : C.CoveredIds) { |
345 | W.value(P); |
346 | } |
347 | }); |
348 | W.attribute(Key: "binary-hash" , Contents: C.BinaryHash); |
349 | W.attributeObject("point-symbol-info" , [&] { 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>(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(InputFile); |
367 | failIfError(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>(Root); |
377 | failIf(B: !Top, E: "expecting mapping node: " + InputFile); |
378 | |
379 | for (auto &KVNode : *Top) { |
380 | auto Key = parseScalarString(KVNode.getKey()); |
381 | |
382 | if (Key == "covered-points" ) { |
383 | yaml::SequenceNode *Points = |
384 | dyn_cast<yaml::SequenceNode>(KVNode.getValue()); |
385 | failIf(!Points, "expected array: " + InputFile); |
386 | |
387 | for (auto I = Points->begin(), E = Points->end(); I != E; ++I) { |
388 | Coverage->CoveredIds.insert(parseScalarString(&*I)); |
389 | } |
390 | } else if (Key == "binary-hash" ) { |
391 | Coverage->BinaryHash = parseScalarString(KVNode.getValue()); |
392 | } else if (Key == "point-symbol-info" ) { |
393 | yaml::MappingNode *PointSymbolInfo = |
394 | dyn_cast<yaml::MappingNode>(KVNode.getValue()); |
395 | failIf(!PointSymbolInfo, "expected mapping node: " + InputFile); |
396 | |
397 | for (auto &FileKVNode : *PointSymbolInfo) { |
398 | auto Filename = parseScalarString(FileKVNode.getKey()); |
399 | |
400 | yaml::MappingNode *FileInfo = |
401 | dyn_cast<yaml::MappingNode>(FileKVNode.getValue()); |
402 | failIf(!FileInfo, "expected mapping node: " + InputFile); |
403 | |
404 | for (auto &FunctionKVNode : *FileInfo) { |
405 | auto FunctionName = parseScalarString(FunctionKVNode.getKey()); |
406 | |
407 | yaml::MappingNode *FunctionInfo = |
408 | dyn_cast<yaml::MappingNode>(FunctionKVNode.getValue()); |
409 | failIf(!FunctionInfo, "expected mapping node: " + InputFile); |
410 | |
411 | for (auto &PointKVNode : *FunctionInfo) { |
412 | auto PointId = parseScalarString(PointKVNode.getKey()); |
413 | auto Loc = parseScalarString(PointKVNode.getValue()); |
414 | |
415 | size_t ColonPos = Loc.find(':'); |
416 | failIf(ColonPos == std::string::npos, "expected ':': " + InputFile); |
417 | |
418 | auto LineStr = Loc.substr(0, ColonPos); |
419 | auto ColStr = Loc.substr(ColonPos + 1, Loc.size()); |
420 | |
421 | if (Points.find(PointId) == Points.end()) |
422 | Points.insert(std::make_pair(PointId, CoveragePoint(PointId))); |
423 | |
424 | DILineInfo LineInfo; |
425 | LineInfo.FileName = Filename; |
426 | LineInfo.FunctionName = FunctionName; |
427 | char *End; |
428 | LineInfo.Line = std::strtoul(LineStr.c_str(), &End, 10); |
429 | LineInfo.Column = std::strtoul(ColStr.c_str(), &End, 10); |
430 | |
431 | CoveragePoint *CoveragePoint = &Points.find(PointId)->second; |
432 | CoveragePoint->Locs.push_back(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(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(ClStripPathPrefix); |
454 | if (Pos == std::string::npos) |
455 | return Path; |
456 | return Path.substr(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::unique_ptr<symbolize::LLVMSymbolizer>( |
464 | new symbolize::LLVMSymbolizer(SymbolizerOptions)); |
465 | } |
466 | |
467 | static std::string normalizeFilename(const std::string &FileName) { |
468 | SmallString<256> S(FileName); |
469 | sys::path::remove_dots(path&: S, /* remove_dot_dot */ true); |
470 | return stripPathPrefix(Path: sys::path::convert_to_slash(path: std::string(S))); |
471 | } |
472 | |
473 | class Ignorelists { |
474 | public: |
475 | Ignorelists() |
476 | : DefaultIgnorelist(createDefaultIgnorelist()), |
477 | UserIgnorelist(createUserIgnorelist()) {} |
478 | |
479 | bool isIgnorelisted(const DILineInfo &I) { |
480 | if (DefaultIgnorelist && |
481 | DefaultIgnorelist->inSection("sancov" , "fun" , I.FunctionName)) |
482 | return true; |
483 | if (DefaultIgnorelist && |
484 | DefaultIgnorelist->inSection("sancov" , "src" , I.FileName)) |
485 | return true; |
486 | if (UserIgnorelist && |
487 | UserIgnorelist->inSection("sancov" , "fun" , I.FunctionName)) |
488 | return true; |
489 | if (UserIgnorelist && |
490 | UserIgnorelist->inSection("sancov" , "src" , I.FileName)) |
491 | return true; |
492 | return false; |
493 | } |
494 | |
495 | private: |
496 | static std::unique_ptr<SpecialCaseList> createDefaultIgnorelist() { |
497 | if (!ClUseDefaultIgnorelist) |
498 | return std::unique_ptr<SpecialCaseList>(); |
499 | std::unique_ptr<MemoryBuffer> MB = |
500 | MemoryBuffer::getMemBuffer(DefaultIgnorelistStr); |
501 | std::string Error; |
502 | auto Ignorelist = SpecialCaseList::create(MB.get(), Error); |
503 | failIfNotEmpty(E: Error); |
504 | return Ignorelist; |
505 | } |
506 | |
507 | static std::unique_ptr<SpecialCaseList> createUserIgnorelist() { |
508 | if (ClIgnorelist.empty()) |
509 | return std::unique_ptr<SpecialCaseList>(); |
510 | return SpecialCaseList::createOrDie({{ClIgnorelist}}, |
511 | *vfs::getRealFileSystem()); |
512 | } |
513 | std::unique_ptr<SpecialCaseList> DefaultIgnorelist; |
514 | std::unique_ptr<SpecialCaseList> UserIgnorelist; |
515 | }; |
516 | |
517 | static std::vector<CoveragePoint> |
518 | getCoveragePoints(const std::string &ObjectFile, |
519 | const std::set<uint64_t> &Addrs, |
520 | const std::set<uint64_t> &CoveredAddrs) { |
521 | std::vector<CoveragePoint> Result; |
522 | auto Symbolizer(createSymbolizer()); |
523 | Ignorelists Ig; |
524 | |
525 | std::set<std::string> CoveredFiles; |
526 | if (ClSkipDeadFiles) { |
527 | for (auto Addr : CoveredAddrs) { |
528 | // TODO: it would be neccessary to set proper section index here. |
529 | // object::SectionedAddress::UndefSection works for only absolute |
530 | // addresses. |
531 | object::SectionedAddress ModuleAddress = { |
532 | Addr, object::SectionedAddress::UndefSection}; |
533 | |
534 | auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, ModuleAddress); |
535 | failIfError(LineInfo); |
536 | CoveredFiles.insert(LineInfo->FileName); |
537 | auto InliningInfo = |
538 | Symbolizer->symbolizeInlinedCode(ObjectFile, ModuleAddress); |
539 | failIfError(InliningInfo); |
540 | for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { |
541 | auto FrameInfo = InliningInfo->getFrame(I); |
542 | CoveredFiles.insert(FrameInfo.FileName); |
543 | } |
544 | } |
545 | } |
546 | |
547 | for (auto Addr : Addrs) { |
548 | std::set<DILineInfo> Infos; // deduplicate debug info. |
549 | |
550 | // TODO: it would be neccessary to set proper section index here. |
551 | // object::SectionedAddress::UndefSection works for only absolute addresses. |
552 | object::SectionedAddress ModuleAddress = { |
553 | Addr, object::SectionedAddress::UndefSection}; |
554 | |
555 | auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, ModuleAddress); |
556 | failIfError(LineInfo); |
557 | if (ClSkipDeadFiles && |
558 | CoveredFiles.find(LineInfo->FileName) == CoveredFiles.end()) |
559 | continue; |
560 | LineInfo->FileName = normalizeFilename(LineInfo->FileName); |
561 | if (Ig.isIgnorelisted(*LineInfo)) |
562 | continue; |
563 | |
564 | auto Id = utohexstr(Addr, true); |
565 | auto Point = CoveragePoint(Id); |
566 | Infos.insert(*LineInfo); |
567 | Point.Locs.push_back(*LineInfo); |
568 | |
569 | auto InliningInfo = |
570 | Symbolizer->symbolizeInlinedCode(ObjectFile, ModuleAddress); |
571 | failIfError(InliningInfo); |
572 | for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { |
573 | auto FrameInfo = InliningInfo->getFrame(I); |
574 | if (ClSkipDeadFiles && |
575 | CoveredFiles.find(FrameInfo.FileName) == CoveredFiles.end()) |
576 | continue; |
577 | FrameInfo.FileName = normalizeFilename(FrameInfo.FileName); |
578 | if (Ig.isIgnorelisted(FrameInfo)) |
579 | continue; |
580 | if (Infos.find(FrameInfo) == Infos.end()) { |
581 | Infos.insert(FrameInfo); |
582 | Point.Locs.push_back(FrameInfo); |
583 | } |
584 | } |
585 | |
586 | Result.push_back(Point); |
587 | } |
588 | |
589 | return Result; |
590 | } |
591 | |
592 | static bool isCoveragePointSymbol(StringRef Name) { |
593 | return Name == "__sanitizer_cov" || Name == "__sanitizer_cov_with_check" || |
594 | Name == "__sanitizer_cov_trace_func_enter" || |
595 | Name == "__sanitizer_cov_trace_pc_guard" || |
596 | // Mac has '___' prefix |
597 | Name == "___sanitizer_cov" || Name == "___sanitizer_cov_with_check" || |
598 | Name == "___sanitizer_cov_trace_func_enter" || |
599 | Name == "___sanitizer_cov_trace_pc_guard" ; |
600 | } |
601 | |
602 | // Locate __sanitizer_cov* function addresses inside the stubs table on MachO. |
603 | static void findMachOIndirectCovFunctions(const object::MachOObjectFile &O, |
604 | std::set<uint64_t> *Result) { |
605 | MachO::dysymtab_command Dysymtab = O.getDysymtabLoadCommand(); |
606 | MachO::symtab_command Symtab = O.getSymtabLoadCommand(); |
607 | |
608 | for (const auto &Load : O.load_commands()) { |
609 | if (Load.C.cmd == MachO::LC_SEGMENT_64) { |
610 | MachO::segment_command_64 Seg = O.getSegment64LoadCommand(Load); |
611 | for (unsigned J = 0; J < Seg.nsects; ++J) { |
612 | MachO::section_64 Sec = O.getSection64(Load, J); |
613 | |
614 | uint32_t SectionType = Sec.flags & MachO::SECTION_TYPE; |
615 | if (SectionType == MachO::S_SYMBOL_STUBS) { |
616 | uint32_t Stride = Sec.reserved2; |
617 | uint32_t Cnt = Sec.size / Stride; |
618 | uint32_t N = Sec.reserved1; |
619 | for (uint32_t J = 0; J < Cnt && N + J < Dysymtab.nindirectsyms; J++) { |
620 | uint32_t IndirectSymbol = |
621 | O.getIndirectSymbolTableEntry(Dysymtab, N + J); |
622 | uint64_t Addr = Sec.addr + J * Stride; |
623 | if (IndirectSymbol < Symtab.nsyms) { |
624 | object::SymbolRef Symbol = *(O.getSymbolByIndex(IndirectSymbol)); |
625 | Expected<StringRef> Name = Symbol.getName(); |
626 | failIfError(Name); |
627 | if (isCoveragePointSymbol(Name.get())) { |
628 | Result->insert(Addr); |
629 | } |
630 | } |
631 | } |
632 | } |
633 | } |
634 | } |
635 | if (Load.C.cmd == MachO::LC_SEGMENT) { |
636 | errs() << "ERROR: 32 bit MachO binaries not supported\n" ; |
637 | } |
638 | } |
639 | } |
640 | |
641 | // Locate __sanitizer_cov* function addresses that are used for coverage |
642 | // reporting. |
643 | static std::set<uint64_t> |
644 | findSanitizerCovFunctions(const object::ObjectFile &O) { |
645 | std::set<uint64_t> Result; |
646 | |
647 | for (const object::SymbolRef &Symbol : O.symbols()) { |
648 | Expected<uint64_t> AddressOrErr = Symbol.getAddress(); |
649 | failIfError(AddressOrErr); |
650 | uint64_t Address = AddressOrErr.get(); |
651 | |
652 | Expected<StringRef> NameOrErr = Symbol.getName(); |
653 | failIfError(NameOrErr); |
654 | StringRef Name = NameOrErr.get(); |
655 | |
656 | Expected<uint32_t> FlagsOrErr = Symbol.getFlags(); |
657 | // TODO: Test this error. |
658 | failIfError(FlagsOrErr); |
659 | uint32_t Flags = FlagsOrErr.get(); |
660 | |
661 | if (!(Flags & object::BasicSymbolRef::SF_Undefined) && |
662 | isCoveragePointSymbol(Name)) { |
663 | Result.insert(Address); |
664 | } |
665 | } |
666 | |
667 | if (const auto *CO = dyn_cast<object::COFFObjectFile>(&O)) { |
668 | for (const object::ExportDirectoryEntryRef &Export : |
669 | CO->export_directories()) { |
670 | uint32_t RVA; |
671 | failIfError(Export.getExportRVA(RVA)); |
672 | |
673 | StringRef Name; |
674 | failIfError(Export.getSymbolName(Name)); |
675 | |
676 | if (isCoveragePointSymbol(Name)) |
677 | Result.insert(CO->getImageBase() + RVA); |
678 | } |
679 | } |
680 | |
681 | if (const auto *MO = dyn_cast<object::MachOObjectFile>(&O)) { |
682 | findMachOIndirectCovFunctions(*MO, &Result); |
683 | } |
684 | |
685 | return Result; |
686 | } |
687 | |
688 | // Ported from |
689 | // compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.h:GetPreviousInstructionPc |
690 | // GetPreviousInstructionPc. |
691 | static uint64_t getPreviousInstructionPc(uint64_t PC, Triple TheTriple) { |
692 | if (TheTriple.isARM()) |
693 | return (PC - 3) & (~1); |
694 | if (TheTriple.isMIPS() || TheTriple.isSPARC()) |
695 | return PC - 8; |
696 | if (TheTriple.isRISCV()) |
697 | return PC - 2; |
698 | if (TheTriple.isX86() || TheTriple.isSystemZ()) |
699 | return PC - 1; |
700 | return PC - 4; |
701 | } |
702 | |
703 | // Locate addresses of all coverage points in a file. Coverage point |
704 | // is defined as the 'address of instruction following __sanitizer_cov |
705 | // call - 1'. |
706 | static void getObjectCoveragePoints(const object::ObjectFile &O, |
707 | std::set<uint64_t> *Addrs) { |
708 | Triple TheTriple("unknown-unknown-unknown" ); |
709 | TheTriple.setArch(Kind: Triple::ArchType(O.getArch())); |
710 | auto TripleName = TheTriple.getTriple(); |
711 | |
712 | std::string Error; |
713 | const Target *TheTarget = TargetRegistry::lookupTarget(Triple: TripleName, Error); |
714 | failIfNotEmpty(E: Error); |
715 | |
716 | std::unique_ptr<const MCSubtargetInfo> STI( |
717 | TheTarget->createMCSubtargetInfo(TripleName, "" , "" )); |
718 | failIfEmpty(STI, "no subtarget info for target " + TripleName); |
719 | |
720 | std::unique_ptr<const MCRegisterInfo> MRI( |
721 | TheTarget->createMCRegInfo(TripleName)); |
722 | failIfEmpty(MRI, "no register info for target " + TripleName); |
723 | |
724 | MCTargetOptions MCOptions; |
725 | std::unique_ptr<const MCAsmInfo> AsmInfo( |
726 | TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); |
727 | failIfEmpty(AsmInfo, "no asm info for target " + TripleName); |
728 | |
729 | MCContext Ctx(TheTriple, AsmInfo.get(), MRI.get(), STI.get()); |
730 | std::unique_ptr<MCDisassembler> DisAsm( |
731 | TheTarget->createMCDisassembler(*STI, Ctx)); |
732 | failIfEmpty(DisAsm, "no disassembler info for target " + TripleName); |
733 | |
734 | std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); |
735 | failIfEmpty(MII, "no instruction info for target " + TripleName); |
736 | |
737 | std::unique_ptr<const MCInstrAnalysis> MIA( |
738 | TheTarget->createMCInstrAnalysis(MII.get())); |
739 | failIfEmpty(MIA, "no instruction analysis info for target " + TripleName); |
740 | |
741 | auto SanCovAddrs = findSanitizerCovFunctions(O); |
742 | if (SanCovAddrs.empty()) |
743 | fail(E: "__sanitizer_cov* functions not found" ); |
744 | |
745 | for (object::SectionRef Section : O.sections()) { |
746 | if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same. |
747 | continue; |
748 | uint64_t SectionAddr = Section.getAddress(); |
749 | uint64_t SectSize = Section.getSize(); |
750 | if (!SectSize) |
751 | continue; |
752 | |
753 | Expected<StringRef> BytesStr = Section.getContents(); |
754 | failIfError(BytesStr); |
755 | ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(*BytesStr); |
756 | |
757 | for (uint64_t Index = 0, Size = 0; Index < Section.getSize(); |
758 | Index += Size) { |
759 | MCInst Inst; |
760 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index); |
761 | uint64_t ThisAddr = SectionAddr + Index; |
762 | if (!DisAsm->getInstruction(Inst, Size, ThisBytes, ThisAddr, nulls())) { |
763 | if (Size == 0) |
764 | Size = std::min<uint64_t>( |
765 | ThisBytes.size(), |
766 | DisAsm->suggestBytesToSkip(ThisBytes, ThisAddr)); |
767 | continue; |
768 | } |
769 | uint64_t Addr = Index + SectionAddr; |
770 | // Sanitizer coverage uses the address of the next instruction - 1. |
771 | uint64_t CovPoint = getPreviousInstructionPc(Addr + Size, TheTriple); |
772 | uint64_t Target; |
773 | if (MIA->isCall(Inst) && |
774 | MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target) && |
775 | SanCovAddrs.find(Target) != SanCovAddrs.end()) |
776 | Addrs->insert(CovPoint); |
777 | } |
778 | } |
779 | } |
780 | |
781 | static void |
782 | visitObjectFiles(const object::Archive &A, |
783 | function_ref<void(const object::ObjectFile &)> Fn) { |
784 | Error Err = Error::success(); |
785 | for (auto &C : A.children(Err)) { |
786 | Expected<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary(); |
787 | failIfError(ChildOrErr); |
788 | if (auto *O = dyn_cast<object::ObjectFile>(&*ChildOrErr.get())) |
789 | Fn(*O); |
790 | else |
791 | failIfError(object::object_error::invalid_file_type); |
792 | } |
793 | failIfError(std::move(Err)); |
794 | } |
795 | |
796 | static void |
797 | visitObjectFiles(const std::string &FileName, |
798 | function_ref<void(const object::ObjectFile &)> Fn) { |
799 | Expected<object::OwningBinary<object::Binary>> BinaryOrErr = |
800 | object::createBinary(FileName); |
801 | if (!BinaryOrErr) |
802 | failIfError(BinaryOrErr); |
803 | |
804 | object::Binary &Binary = *BinaryOrErr.get().getBinary(); |
805 | if (object::Archive *A = dyn_cast<object::Archive>(&Binary)) |
806 | visitObjectFiles(*A, Fn); |
807 | else if (object::ObjectFile *O = dyn_cast<object::ObjectFile>(&Binary)) |
808 | Fn(*O); |
809 | else |
810 | failIfError(object::object_error::invalid_file_type); |
811 | } |
812 | |
813 | static std::set<uint64_t> |
814 | findSanitizerCovFunctions(const std::string &FileName) { |
815 | std::set<uint64_t> Result; |
816 | visitObjectFiles(FileName, [&](const object::ObjectFile &O) { |
817 | auto Addrs = findSanitizerCovFunctions(O); |
818 | Result.insert(Addrs.begin(), Addrs.end()); |
819 | }); |
820 | return Result; |
821 | } |
822 | |
823 | // Locate addresses of all coverage points in a file. Coverage point |
824 | // is defined as the 'address of instruction following __sanitizer_cov |
825 | // call - 1'. |
826 | static std::set<uint64_t> findCoveragePointAddrs(const std::string &FileName) { |
827 | std::set<uint64_t> Result; |
828 | visitObjectFiles(FileName, [&](const object::ObjectFile &O) { |
829 | getObjectCoveragePoints(O, &Result); |
830 | }); |
831 | return Result; |
832 | } |
833 | |
834 | static void printCovPoints(const std::string &ObjFile, raw_ostream &OS) { |
835 | for (uint64_t Addr : findCoveragePointAddrs(ObjFile)) { |
836 | OS << "0x" ; |
837 | OS.write_hex(Addr); |
838 | OS << "\n" ; |
839 | } |
840 | } |
841 | |
842 | static ErrorOr<bool> isCoverageFile(const std::string &FileName) { |
843 | auto ShortFileName = llvm::sys::path::filename(path: FileName); |
844 | if (!SancovFileRegex.match(String: ShortFileName)) |
845 | return false; |
846 | |
847 | ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = |
848 | MemoryBuffer::getFile(FileName); |
849 | if (!BufOrErr) { |
850 | errs() << "Warning: " << BufOrErr.getError().message() << "(" |
851 | << BufOrErr.getError().value() |
852 | << "), filename: " << llvm::sys::path::filename(path: FileName) << "\n" ; |
853 | return BufOrErr.getError(); |
854 | } |
855 | std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); |
856 | if (Buf->getBufferSize() < 8) { |
857 | return false; |
858 | } |
859 | const FileHeader * = |
860 | reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); |
861 | return Header->Magic == BinCoverageMagic; |
862 | } |
863 | |
864 | static bool isSymbolizedCoverageFile(const std::string &FileName) { |
865 | auto ShortFileName = llvm::sys::path::filename(path: FileName); |
866 | return SymcovFileRegex.match(String: ShortFileName); |
867 | } |
868 | |
869 | static std::unique_ptr<SymbolizedCoverage> |
870 | symbolize(const RawCoverage &Data, const std::string ObjectFile) { |
871 | auto Coverage = std::make_unique<SymbolizedCoverage>(); |
872 | |
873 | ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = |
874 | MemoryBuffer::getFile(ObjectFile); |
875 | failIfError(BufOrErr); |
876 | SHA1 Hasher; |
877 | Hasher.update((*BufOrErr)->getBuffer()); |
878 | Coverage->BinaryHash = toHex(Hasher.final()); |
879 | |
880 | Ignorelists Ig; |
881 | auto Symbolizer(createSymbolizer()); |
882 | |
883 | for (uint64_t Addr : *Data.Addrs) { |
884 | // TODO: it would be neccessary to set proper section index here. |
885 | // object::SectionedAddress::UndefSection works for only absolute addresses. |
886 | auto LineInfo = Symbolizer->symbolizeCode( |
887 | ObjectFile, {Addr, object::SectionedAddress::UndefSection}); |
888 | failIfError(LineInfo); |
889 | if (Ig.isIgnorelisted(*LineInfo)) |
890 | continue; |
891 | |
892 | Coverage->CoveredIds.insert(utohexstr(Addr, true)); |
893 | } |
894 | |
895 | std::set<uint64_t> AllAddrs = findCoveragePointAddrs(ObjectFile); |
896 | if (!std::includes(AllAddrs.begin(), AllAddrs.end(), Data.Addrs->begin(), |
897 | Data.Addrs->end())) { |
898 | fail(E: "Coverage points in binary and .sancov file do not match." ); |
899 | } |
900 | Coverage->Points = getCoveragePoints(ObjectFile, AllAddrs, *Data.Addrs); |
901 | return Coverage; |
902 | } |
903 | |
904 | struct FileFn { |
905 | bool operator<(const FileFn &RHS) const { |
906 | return std::tie(FileName, FunctionName) < |
907 | std::tie(RHS.FileName, RHS.FunctionName); |
908 | } |
909 | |
910 | std::string FileName; |
911 | std::string FunctionName; |
912 | }; |
913 | |
914 | static std::set<FileFn> |
915 | computeFunctions(const std::vector<CoveragePoint> &Points) { |
916 | std::set<FileFn> Fns; |
917 | for (const auto &Point : Points) { |
918 | for (const auto &Loc : Point.Locs) { |
919 | Fns.insert(FileFn{Loc.FileName, Loc.FunctionName}); |
920 | } |
921 | } |
922 | return Fns; |
923 | } |
924 | |
925 | static std::set<FileFn> |
926 | computeNotCoveredFunctions(const SymbolizedCoverage &Coverage) { |
927 | auto Fns = computeFunctions(Coverage.Points); |
928 | |
929 | for (const auto &Point : Coverage.Points) { |
930 | if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end()) |
931 | continue; |
932 | |
933 | for (const auto &Loc : Point.Locs) { |
934 | Fns.erase(FileFn{Loc.FileName, Loc.FunctionName}); |
935 | } |
936 | } |
937 | |
938 | return Fns; |
939 | } |
940 | |
941 | static std::set<FileFn> |
942 | computeCoveredFunctions(const SymbolizedCoverage &Coverage) { |
943 | auto AllFns = computeFunctions(Coverage.Points); |
944 | std::set<FileFn> Result; |
945 | |
946 | for (const auto &Point : Coverage.Points) { |
947 | if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end()) |
948 | continue; |
949 | |
950 | for (const auto &Loc : Point.Locs) { |
951 | Result.insert(FileFn{Loc.FileName, Loc.FunctionName}); |
952 | } |
953 | } |
954 | |
955 | return Result; |
956 | } |
957 | |
958 | typedef std::map<FileFn, std::pair<uint32_t, uint32_t>> FunctionLocs; |
959 | // finds first location in a file for each function. |
960 | static FunctionLocs resolveFunctions(const SymbolizedCoverage &Coverage, |
961 | const std::set<FileFn> &Fns) { |
962 | FunctionLocs Result; |
963 | for (const auto &Point : Coverage.Points) { |
964 | for (const auto &Loc : Point.Locs) { |
965 | FileFn Fn = FileFn{Loc.FileName, Loc.FunctionName}; |
966 | if (Fns.find(Fn) == Fns.end()) |
967 | continue; |
968 | |
969 | auto P = std::make_pair(Loc.Line, Loc.Column); |
970 | auto I = Result.find(Fn); |
971 | if (I == Result.end() || I->second > P) { |
972 | Result[Fn] = P; |
973 | } |
974 | } |
975 | } |
976 | return Result; |
977 | } |
978 | |
979 | static void printFunctionLocs(const FunctionLocs &FnLocs, raw_ostream &OS) { |
980 | for (const auto &P : FnLocs) { |
981 | OS << stripPathPrefix(P.first.FileName) << ":" << P.second.first << " " |
982 | << P.first.FunctionName << "\n" ; |
983 | } |
984 | } |
985 | CoverageStats computeStats(const SymbolizedCoverage &Coverage) { |
986 | CoverageStats Stats = {Coverage.Points.size(), Coverage.CoveredIds.size(), |
987 | computeFunctions(Coverage.Points).size(), |
988 | computeCoveredFunctions(Coverage).size()}; |
989 | return Stats; |
990 | } |
991 | |
992 | // Print list of covered functions. |
993 | // Line format: <file_name>:<line> <function_name> |
994 | static void printCoveredFunctions(const SymbolizedCoverage &CovData, |
995 | raw_ostream &OS) { |
996 | auto CoveredFns = computeCoveredFunctions(CovData); |
997 | printFunctionLocs(resolveFunctions(CovData, CoveredFns), OS); |
998 | } |
999 | |
1000 | // Print list of not covered functions. |
1001 | // Line format: <file_name>:<line> <function_name> |
1002 | static void printNotCoveredFunctions(const SymbolizedCoverage &CovData, |
1003 | raw_ostream &OS) { |
1004 | auto NotCoveredFns = computeNotCoveredFunctions(CovData); |
1005 | printFunctionLocs(resolveFunctions(CovData, NotCoveredFns), OS); |
1006 | } |
1007 | |
1008 | // Read list of files and merges their coverage info. |
1009 | static void readAndPrintRawCoverage(const std::vector<std::string> &FileNames, |
1010 | raw_ostream &OS) { |
1011 | std::vector<std::unique_ptr<RawCoverage>> Covs; |
1012 | for (const auto &FileName : FileNames) { |
1013 | auto Cov = RawCoverage::read(FileName); |
1014 | if (!Cov) |
1015 | continue; |
1016 | OS << *Cov.get(); |
1017 | } |
1018 | } |
1019 | |
1020 | static std::unique_ptr<SymbolizedCoverage> |
1021 | merge(const std::vector<std::unique_ptr<SymbolizedCoverage>> &Coverages) { |
1022 | if (Coverages.empty()) |
1023 | return nullptr; |
1024 | |
1025 | auto Result = std::make_unique<SymbolizedCoverage>(); |
1026 | |
1027 | for (size_t I = 0; I < Coverages.size(); ++I) { |
1028 | const SymbolizedCoverage &Coverage = *Coverages[I]; |
1029 | std::string Prefix; |
1030 | if (Coverages.size() > 1) { |
1031 | // prefix is not needed when there's only one file. |
1032 | Prefix = utostr(X: I); |
1033 | } |
1034 | |
1035 | for (const auto &Id : Coverage.CoveredIds) { |
1036 | Result->CoveredIds.insert(Prefix + Id); |
1037 | } |
1038 | |
1039 | for (const auto &CovPoint : Coverage.Points) { |
1040 | CoveragePoint NewPoint(CovPoint); |
1041 | NewPoint.Id = Prefix + CovPoint.Id; |
1042 | Result->Points.push_back(NewPoint); |
1043 | } |
1044 | } |
1045 | |
1046 | if (Coverages.size() == 1) { |
1047 | Result->BinaryHash = Coverages[0]->BinaryHash; |
1048 | } |
1049 | |
1050 | return Result; |
1051 | } |
1052 | |
1053 | static std::unique_ptr<SymbolizedCoverage> |
1054 | readSymbolizeAndMergeCmdArguments(std::vector<std::string> FileNames) { |
1055 | std::vector<std::unique_ptr<SymbolizedCoverage>> Coverages; |
1056 | |
1057 | { |
1058 | // Short name => file name. |
1059 | std::map<std::string, std::string> ObjFiles; |
1060 | std::string FirstObjFile; |
1061 | std::set<std::string> CovFiles; |
1062 | |
1063 | // Partition input values into coverage/object files. |
1064 | for (const auto &FileName : FileNames) { |
1065 | if (isSymbolizedCoverageFile(FileName)) { |
1066 | Coverages.push_back(SymbolizedCoverage::read(FileName)); |
1067 | } |
1068 | |
1069 | auto ErrorOrIsCoverage = isCoverageFile(FileName); |
1070 | if (!ErrorOrIsCoverage) |
1071 | continue; |
1072 | if (ErrorOrIsCoverage.get()) { |
1073 | CovFiles.insert(FileName); |
1074 | } else { |
1075 | auto ShortFileName = llvm::sys::path::filename(FileName); |
1076 | if (ObjFiles.find(std::string(ShortFileName)) != ObjFiles.end()) { |
1077 | fail("Duplicate binary file with a short name: " + ShortFileName); |
1078 | } |
1079 | |
1080 | ObjFiles[std::string(ShortFileName)] = FileName; |
1081 | if (FirstObjFile.empty()) |
1082 | FirstObjFile = FileName; |
1083 | } |
1084 | } |
1085 | |
1086 | SmallVector<StringRef, 2> Components; |
1087 | |
1088 | // Object file => list of corresponding coverage file names. |
1089 | std::map<std::string, std::vector<std::string>> CoverageByObjFile; |
1090 | for (const auto &FileName : CovFiles) { |
1091 | auto ShortFileName = llvm::sys::path::filename(FileName); |
1092 | auto Ok = SancovFileRegex.match(ShortFileName, &Components); |
1093 | if (!Ok) { |
1094 | fail("Can't match coverage file name against " |
1095 | "<module_name>.<pid>.sancov pattern: " + |
1096 | FileName); |
1097 | } |
1098 | |
1099 | auto Iter = ObjFiles.find(std::string(Components[1])); |
1100 | if (Iter == ObjFiles.end()) { |
1101 | fail("Object file for coverage not found: " + FileName); |
1102 | } |
1103 | |
1104 | CoverageByObjFile[Iter->second].push_back(FileName); |
1105 | }; |
1106 | |
1107 | for (const auto &Pair : ObjFiles) { |
1108 | auto FileName = Pair.second; |
1109 | if (CoverageByObjFile.find(FileName) == CoverageByObjFile.end()) |
1110 | errs() << "WARNING: No coverage file for " << FileName << "\n" ; |
1111 | } |
1112 | |
1113 | // Read raw coverage and symbolize it. |
1114 | for (const auto &Pair : CoverageByObjFile) { |
1115 | if (findSanitizerCovFunctions(Pair.first).empty()) { |
1116 | errs() |
1117 | << "WARNING: Ignoring " << Pair.first |
1118 | << " and its coverage because __sanitizer_cov* functions were not " |
1119 | "found.\n" ; |
1120 | continue; |
1121 | } |
1122 | |
1123 | for (const std::string &CoverageFile : Pair.second) { |
1124 | auto DataOrError = RawCoverage::read(CoverageFile); |
1125 | failIfError(DataOrError); |
1126 | Coverages.push_back(symbolize(*DataOrError.get(), Pair.first)); |
1127 | } |
1128 | } |
1129 | } |
1130 | |
1131 | return merge(Coverages); |
1132 | } |
1133 | |
1134 | } // namespace |
1135 | |
1136 | static void parseArgs(int Argc, char **Argv) { |
1137 | SancovOptTable Tbl; |
1138 | llvm::BumpPtrAllocator A; |
1139 | llvm::StringSaver Saver{A}; |
1140 | opt::InputArgList Args = |
1141 | Tbl.parseArgs(Argc, Argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) { |
1142 | llvm::errs() << Msg << '\n'; |
1143 | std::exit(status: 1); |
1144 | }); |
1145 | |
1146 | if (Args.hasArg(OPT_help)) { |
1147 | Tbl.printHelp( |
1148 | OS&: llvm::outs(), |
1149 | Usage: "sancov [options] <action> <binary files...> <.sancov files...> " |
1150 | "<.symcov files...>" , |
1151 | Title: "Sanitizer Coverage Processing Tool (sancov)\n\n" |
1152 | " This tool can extract various coverage-related information from: \n" |
1153 | " coverage-instrumented binary files, raw .sancov files and their " |
1154 | "symbolized .symcov version.\n" |
1155 | " Depending on chosen action the tool expects different input files:\n" |
1156 | " -print-coverage-pcs - coverage-instrumented binary files\n" |
1157 | " -print-coverage - .sancov files\n" |
1158 | " <other actions> - .sancov files & corresponding binary " |
1159 | "files, .symcov files\n" ); |
1160 | std::exit(status: 0); |
1161 | } |
1162 | |
1163 | if (Args.hasArg(OPT_version)) { |
1164 | cl::PrintVersionMessage(); |
1165 | std::exit(status: 0); |
1166 | } |
1167 | |
1168 | if (Args.hasMultipleArgs(Id: OPT_action_grp)) { |
1169 | fail(E: "Only one action option is allowed" ); |
1170 | } |
1171 | |
1172 | for (const opt::Arg *A : Args.filtered(OPT_INPUT)) { |
1173 | ClInputFiles.emplace_back(A->getValue()); |
1174 | } |
1175 | |
1176 | if (const llvm::opt::Arg *A = Args.getLastArg(OPT_action_grp)) { |
1177 | switch (A->getOption().getID()) { |
1178 | case OPT_print: |
1179 | Action = ActionType::PrintAction; |
1180 | break; |
1181 | case OPT_printCoveragePcs: |
1182 | Action = ActionType::PrintCovPointsAction; |
1183 | break; |
1184 | case OPT_coveredFunctions: |
1185 | Action = ActionType::CoveredFunctionsAction; |
1186 | break; |
1187 | case OPT_notCoveredFunctions: |
1188 | Action = ActionType::NotCoveredFunctionsAction; |
1189 | break; |
1190 | case OPT_printCoverageStats: |
1191 | Action = ActionType::StatsAction; |
1192 | break; |
1193 | case OPT_htmlReport: |
1194 | Action = ActionType::HtmlReportAction; |
1195 | break; |
1196 | case OPT_symbolize: |
1197 | Action = ActionType::SymbolizeAction; |
1198 | break; |
1199 | case OPT_merge: |
1200 | Action = ActionType::MergeAction; |
1201 | break; |
1202 | default: |
1203 | fail(E: "Invalid Action" ); |
1204 | } |
1205 | } |
1206 | |
1207 | ClDemangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true); |
1208 | ClSkipDeadFiles = Args.hasFlag(OPT_skipDeadFiles, OPT_no_skipDeadFiles, true); |
1209 | ClUseDefaultIgnorelist = |
1210 | Args.hasFlag(Pos: OPT_useDefaultIgnoreList, Neg: OPT_no_useDefaultIgnoreList, Default: true); |
1211 | |
1212 | ClStripPathPrefix = Args.getLastArgValue(Id: OPT_stripPathPrefix_EQ); |
1213 | ClIgnorelist = Args.getLastArgValue(Id: OPT_ignorelist_EQ); |
1214 | } |
1215 | |
1216 | int sancov_main(int Argc, char **Argv, const llvm::ToolContext &) { |
1217 | llvm::InitializeAllTargetInfos(); |
1218 | llvm::InitializeAllTargetMCs(); |
1219 | llvm::InitializeAllDisassemblers(); |
1220 | |
1221 | parseArgs(Argc, Argv); |
1222 | |
1223 | // -print doesn't need object files. |
1224 | if (Action == PrintAction) { |
1225 | readAndPrintRawCoverage(ClInputFiles, outs()); |
1226 | return 0; |
1227 | } |
1228 | if (Action == PrintCovPointsAction) { |
1229 | // -print-coverage-points doesn't need coverage files. |
1230 | for (const std::string &ObjFile : ClInputFiles) { |
1231 | printCovPoints(ObjFile, outs()); |
1232 | } |
1233 | return 0; |
1234 | } |
1235 | |
1236 | auto Coverage = readSymbolizeAndMergeCmdArguments(ClInputFiles); |
1237 | failIf(!Coverage, "No valid coverage files given." ); |
1238 | |
1239 | switch (Action) { |
1240 | case CoveredFunctionsAction: { |
1241 | printCoveredFunctions(*Coverage, outs()); |
1242 | return 0; |
1243 | } |
1244 | case NotCoveredFunctionsAction: { |
1245 | printNotCoveredFunctions(*Coverage, outs()); |
1246 | return 0; |
1247 | } |
1248 | case StatsAction: { |
1249 | outs() << computeStats(*Coverage); |
1250 | return 0; |
1251 | } |
1252 | case MergeAction: |
1253 | case SymbolizeAction: { // merge & symbolize are synonims. |
1254 | json::OStream W(outs(), 2); |
1255 | W << *Coverage; |
1256 | return 0; |
1257 | } |
1258 | case HtmlReportAction: |
1259 | errs() << "-html-report option is removed: " |
1260 | "use -symbolize & coverage-report-server.py instead\n" ; |
1261 | return 1; |
1262 | case PrintAction: |
1263 | case PrintCovPointsAction: |
1264 | llvm_unreachable("unsupported action" ); |
1265 | } |
1266 | |
1267 | return 0; |
1268 | } |
1269 | |