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