1 //===- TestingSupport.cpp - Convert objects files into test files --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Object/ObjectFile.h"
11 #include "llvm/ProfileData/InstrProf.h"
12 #include "llvm/Support/CommandLine.h"
13 #include "llvm/Support/LEB128.h"
14 #include "llvm/Support/raw_ostream.h"
16 #include <system_error>
19 using namespace object;
21 int convertForTestingMain(int argc, const char *argv[]) {
22 cl::opt<std::string> InputSourceFile(cl::Positional, cl::Required,
23 cl::desc("<Source file>"));
25 cl::opt<std::string> OutputFilename(
28 "File with the profile data obtained after an instrumented run"));
30 cl::ParseCommandLineOptions(argc, argv, "LLVM code coverage tool\n");
32 auto ObjErr = llvm::object::ObjectFile::createObjectFile(InputSourceFile);
35 raw_string_ostream OS(Buf);
36 logAllUnhandledErrors(ObjErr.takeError(), OS);
38 errs() << "error: " << Buf;
41 ObjectFile *OF = ObjErr.get().getBinary();
42 auto BytesInAddress = OF->getBytesInAddress();
43 if (BytesInAddress != 8) {
44 errs() << "error: 64 bit binary expected\n";
48 // Look for the sections that we are interested in.
49 int FoundSectionCount = 0;
50 SectionRef ProfileNames, CoverageMapping;
51 auto ObjFormat = OF->getTripleObjectFormat();
52 for (const auto &Section : OF->sections()) {
54 if (Section.getName(Name))
56 if (Name == llvm::getInstrProfSectionName(IPSK_name, ObjFormat,
57 /*AddSegmentInfo=*/false)) {
58 ProfileNames = Section;
59 } else if (Name == llvm::getInstrProfSectionName(
60 IPSK_covmap, ObjFormat, /*AddSegmentInfo=*/false)) {
61 CoverageMapping = Section;
66 if (FoundSectionCount != 2)
69 // Get the contents of the given sections.
70 uint64_t ProfileNamesAddress = ProfileNames.getAddress();
71 StringRef CoverageMappingData;
72 StringRef ProfileNamesData;
73 if (CoverageMapping.getContents(CoverageMappingData) ||
74 ProfileNames.getContents(ProfileNamesData))
78 if (auto Err = sys::fs::openFileForWrite(OutputFilename, FD)) {
79 errs() << "error: " << Err.message() << "\n";
83 raw_fd_ostream OS(FD, true);
84 OS << "llvmcovmtestdata";
85 encodeULEB128(ProfileNamesData.size(), OS);
86 encodeULEB128(ProfileNamesAddress, OS);
87 OS << ProfileNamesData;
88 // Coverage mapping data is expected to have an alignment of 8.
89 for (unsigned Pad = OffsetToAlignment(OS.tell(), 8); Pad; --Pad)
91 OS << CoverageMappingData;