1 //===- TestingSupport.cpp - Convert objects files into test files --------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Object/ObjectFile.h"
10 #include "llvm/ProfileData/InstrProf.h"
11 #include "llvm/Support/CommandLine.h"
12 #include "llvm/Support/LEB128.h"
13 #include "llvm/Support/raw_ostream.h"
15 #include <system_error>
18 using namespace object
;
20 int convertForTestingMain(int argc
, const char *argv
[]) {
21 cl::opt
<std::string
> InputSourceFile(cl::Positional
, cl::Required
,
22 cl::desc("<Source file>"));
24 cl::opt
<std::string
> OutputFilename(
27 "File with the profile data obtained after an instrumented run"));
29 cl::ParseCommandLineOptions(argc
, argv
, "LLVM code coverage tool\n");
31 auto ObjErr
= llvm::object::ObjectFile::createObjectFile(InputSourceFile
);
34 raw_string_ostream
OS(Buf
);
35 logAllUnhandledErrors(ObjErr
.takeError(), OS
);
37 errs() << "error: " << Buf
;
40 ObjectFile
*OF
= ObjErr
.get().getBinary();
41 auto BytesInAddress
= OF
->getBytesInAddress();
42 if (BytesInAddress
!= 8) {
43 errs() << "error: 64 bit binary expected\n";
47 // Look for the sections that we are interested in.
48 int FoundSectionCount
= 0;
49 SectionRef ProfileNames
, CoverageMapping
;
50 auto ObjFormat
= OF
->getTripleObjectFormat();
51 for (const auto &Section
: OF
->sections()) {
53 if (Section
.getName(Name
))
55 if (Name
== llvm::getInstrProfSectionName(IPSK_name
, ObjFormat
,
56 /*AddSegmentInfo=*/false)) {
57 ProfileNames
= Section
;
58 } else if (Name
== llvm::getInstrProfSectionName(
59 IPSK_covmap
, ObjFormat
, /*AddSegmentInfo=*/false)) {
60 CoverageMapping
= Section
;
65 if (FoundSectionCount
!= 2)
68 // Get the contents of the given sections.
69 uint64_t ProfileNamesAddress
= ProfileNames
.getAddress();
70 StringRef CoverageMappingData
;
71 StringRef ProfileNamesData
;
72 if (Expected
<StringRef
> E
= CoverageMapping
.getContents())
73 CoverageMappingData
= *E
;
75 consumeError(E
.takeError());
78 if (Expected
<StringRef
> E
= ProfileNames
.getContents())
79 ProfileNamesData
= *E
;
81 consumeError(E
.takeError());
86 if (auto Err
= sys::fs::openFileForWrite(OutputFilename
, FD
)) {
87 errs() << "error: " << Err
.message() << "\n";
91 raw_fd_ostream
OS(FD
, true);
92 OS
<< "llvmcovmtestdata";
93 encodeULEB128(ProfileNamesData
.size(), OS
);
94 encodeULEB128(ProfileNamesAddress
, OS
);
95 OS
<< ProfileNamesData
;
96 // Coverage mapping data is expected to have an alignment of 8.
97 for (unsigned Pad
= OffsetToAlignment(OS
.tell(), 8); Pad
; --Pad
)
99 OS
<< CoverageMappingData
;