1 //===- llvm-ifs.cpp -------------------------------------------------------===//
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/ADT/StringRef.h"
10 #include "llvm/ADT/StringSwitch.h"
11 #include "llvm/ADT/Triple.h"
12 #include "llvm/ObjectYAML/yaml2obj.h"
13 #include "llvm/Support/CommandLine.h"
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/Error.h"
17 #include "llvm/Support/FileOutputBuffer.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/VersionTuple.h"
21 #include "llvm/Support/WithColor.h"
22 #include "llvm/Support/YAMLTraits.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/TextAPI/MachO/InterfaceFile.h"
25 #include "llvm/TextAPI/MachO/TextAPIReader.h"
26 #include "llvm/TextAPI/MachO/TextAPIWriter.h"
31 using namespace llvm::yaml
;
32 using namespace llvm::MachO
;
34 #define DEBUG_TYPE "llvm-ifs"
37 const VersionTuple
IFSVersionCurrent(1, 2);
40 static cl::opt
<std::string
> Action("action", cl::desc("<llvm-ifs action>"),
41 cl::value_desc("write-ifs | write-bin"),
42 cl::init("write-ifs"));
44 static cl::opt
<std::string
> ForceFormat("force-format",
45 cl::desc("<force object format>"),
46 cl::value_desc("ELF | TBD"),
49 static cl::list
<std::string
> InputFilenames(cl::Positional
,
50 cl::desc("<input ifs files>"),
53 static cl::opt
<std::string
> OutputFilename("o", cl::desc("<output file>"),
54 cl::value_desc("path"));
56 enum class IFSSymbolType
{
60 // Type information is 4 bits, so 16 is safely out of range.
64 std::string
getTypeName(IFSSymbolType Type
) {
66 case IFSSymbolType::NoType
:
68 case IFSSymbolType::Func
:
70 case IFSSymbolType::Object
:
72 case IFSSymbolType::Unknown
:
75 llvm_unreachable("Unexpected ifs symbol type.");
79 IFSSymbol(std::string SymbolName
) : Name(SymbolName
) {}
84 Optional
<std::string
> Warning
;
85 bool operator<(const IFSSymbol
&RHS
) const { return Name
< RHS
.Name
; }
90 /// YAML traits for IFSSymbolType.
91 template <> struct ScalarEnumerationTraits
<IFSSymbolType
> {
92 static void enumeration(IO
&IO
, IFSSymbolType
&SymbolType
) {
93 IO
.enumCase(SymbolType
, "NoType", IFSSymbolType::NoType
);
94 IO
.enumCase(SymbolType
, "Func", IFSSymbolType::Func
);
95 IO
.enumCase(SymbolType
, "Object", IFSSymbolType::Object
);
96 IO
.enumCase(SymbolType
, "Unknown", IFSSymbolType::Unknown
);
97 // Treat other symbol types as noise, and map to Unknown.
98 if (!IO
.outputting() && IO
.matchEnumFallback())
99 SymbolType
= IFSSymbolType::Unknown
;
103 template <> struct ScalarTraits
<VersionTuple
> {
104 static void output(const VersionTuple
&Value
, void *,
105 llvm::raw_ostream
&Out
) {
106 Out
<< Value
.getAsString();
109 static StringRef
input(StringRef Scalar
, void *, VersionTuple
&Value
) {
110 if (Value
.tryParse(Scalar
))
111 return StringRef("Can't parse version: invalid version format.");
113 if (Value
> IFSVersionCurrent
)
114 return StringRef("Unsupported IFS version.");
116 // Returning empty StringRef indicates successful parse.
120 // Don't place quotation marks around version value.
121 static QuotingType
mustQuote(StringRef
) { return QuotingType::None
; }
124 /// YAML traits for IFSSymbol.
125 template <> struct MappingTraits
<IFSSymbol
> {
126 static void mapping(IO
&IO
, IFSSymbol
&Symbol
) {
127 IO
.mapRequired("Type", Symbol
.Type
);
128 // The need for symbol size depends on the symbol type.
129 if (Symbol
.Type
== IFSSymbolType::NoType
)
130 IO
.mapOptional("Size", Symbol
.Size
, (uint64_t)0);
131 else if (Symbol
.Type
== IFSSymbolType::Func
)
134 IO
.mapRequired("Size", Symbol
.Size
);
135 IO
.mapOptional("Weak", Symbol
.Weak
, false);
136 IO
.mapOptional("Warning", Symbol
.Warning
);
139 // Compacts symbol information into a single line.
140 static const bool flow
= true;
143 /// YAML traits for set of IFSSymbols.
144 template <> struct CustomMappingTraits
<std::set
<IFSSymbol
>> {
145 static void inputOne(IO
&IO
, StringRef Key
, std::set
<IFSSymbol
> &Set
) {
146 std::string Name
= Key
.str();
148 IO
.mapRequired(Name
.c_str(), Sym
);
152 static void output(IO
&IO
, std::set
<IFSSymbol
> &Set
) {
153 for (auto &Sym
: Set
)
154 IO
.mapRequired(Sym
.Name
.c_str(), const_cast<IFSSymbol
&>(Sym
));
157 } // End yaml namespace
158 } // End llvm namespace
160 // A cumulative representation of ELF stubs.
161 // Both textual and binary stubs will read into and write from this object.
163 // TODO: Add support for symbol versioning.
165 VersionTuple IfsVersion
;
167 std::string ObjectFileFormat
;
168 Optional
<std::string
> SOName
;
169 std::vector
<std::string
> NeededLibs
;
170 std::set
<IFSSymbol
> Symbols
;
173 IFSStub(const IFSStub
&Stub
)
174 : IfsVersion(Stub
.IfsVersion
), Triple(Stub
.Triple
),
175 ObjectFileFormat(Stub
.ObjectFileFormat
), SOName(Stub
.SOName
),
176 NeededLibs(Stub
.NeededLibs
), Symbols(Stub
.Symbols
) {}
177 IFSStub(IFSStub
&&Stub
)
178 : IfsVersion(std::move(Stub
.IfsVersion
)), Triple(std::move(Stub
.Triple
)),
179 ObjectFileFormat(std::move(Stub
.ObjectFileFormat
)),
180 SOName(std::move(Stub
.SOName
)), NeededLibs(std::move(Stub
.NeededLibs
)),
181 Symbols(std::move(Stub
.Symbols
)) {}
186 /// YAML traits for IFSStub objects.
187 template <> struct MappingTraits
<IFSStub
> {
188 static void mapping(IO
&IO
, IFSStub
&Stub
) {
189 if (!IO
.mapTag("!experimental-ifs-v1", true))
190 IO
.setError("Not a .ifs YAML file.");
191 IO
.mapRequired("IfsVersion", Stub
.IfsVersion
);
192 IO
.mapOptional("Triple", Stub
.Triple
);
193 IO
.mapOptional("ObjectFileFormat", Stub
.ObjectFileFormat
);
194 IO
.mapOptional("SOName", Stub
.SOName
);
195 IO
.mapOptional("NeededLibs", Stub
.NeededLibs
);
196 IO
.mapRequired("Symbols", Stub
.Symbols
);
199 } // End yaml namespace
200 } // End llvm namespace
202 static Expected
<std::unique_ptr
<IFSStub
>> readInputFile(StringRef FilePath
) {
204 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrError
=
205 MemoryBuffer::getFileOrSTDIN(FilePath
);
207 return createStringError(BufOrError
.getError(), "Could not open `%s`",
210 std::unique_ptr
<MemoryBuffer
> FileReadBuffer
= std::move(*BufOrError
);
211 yaml::Input
YamlIn(FileReadBuffer
->getBuffer());
212 std::unique_ptr
<IFSStub
> Stub(new IFSStub());
215 if (std::error_code Err
= YamlIn
.error())
216 return createStringError(Err
, "Failed reading Interface Stub File.");
218 return std::move(Stub
);
221 int writeTbdStub(const llvm::Triple
&T
, const std::set
<IFSSymbol
> &Symbols
,
222 const StringRef Format
, raw_ostream
&Out
) {
224 [](const llvm::Triple
&T
) -> llvm::Expected
<llvm::MachO::Architecture
> {
225 switch (T
.getArch()) {
227 return createStringError(errc::not_supported
, "Invalid Architecture.");
228 case llvm::Triple::ArchType::x86
:
230 case llvm::Triple::ArchType::x86_64
:
232 case llvm::Triple::ArchType::arm
:
234 case llvm::Triple::ArchType::aarch64
:
242 Architecture Arch
= ArchOrError
.get();
245 File
.setFileType(FileType::TBD_V3
);
246 File
.setArchitectures(Arch
);
247 File
.setPlatform(PlatformKind::macOS
);
249 for (const auto &Symbol
: Symbols
) {
250 auto Name
= Symbol
.Name
;
251 auto Kind
= SymbolKind::GlobalSymbol
;
252 switch (Symbol
.Type
) {
254 case IFSSymbolType::NoType
:
255 Kind
= SymbolKind::GlobalSymbol
;
257 case IFSSymbolType::Object
:
258 Kind
= SymbolKind::GlobalSymbol
;
260 case IFSSymbolType::Func
:
261 Kind
= SymbolKind::GlobalSymbol
;
265 File
.addSymbol(Kind
, Name
, Arch
, SymbolFlags::WeakDefined
);
267 File
.addSymbol(Kind
, Name
, Arch
);
270 SmallString
<4096> Buffer
;
271 raw_svector_ostream
OS(Buffer
);
272 if (Error Result
= TextAPIWriter::writeToStream(OS
, File
))
278 int writeElfStub(const llvm::Triple
&T
, const std::set
<IFSSymbol
> &Symbols
,
279 const StringRef Format
, raw_ostream
&Out
) {
280 SmallString
<0> Storage
;
282 raw_svector_ostream
OS(Storage
);
285 OS
<< "FileHeader:\n";
286 OS
<< " Class: ELFCLASS";
287 OS
<< (T
.isArch64Bit() ? "64" : "32");
289 OS
<< " Data: ELFDATA2";
290 OS
<< (T
.isLittleEndian() ? "LSB" : "MSB");
292 OS
<< " Type: ET_DYN\n";
294 << llvm::StringSwitch
<llvm::StringRef
>(T
.getArchName())
295 .Case("x86_64", "EM_X86_64")
296 .Case("i386", "EM_386")
297 .Case("i686", "EM_386")
298 .Case("aarch64", "EM_AARCH64")
299 .Case("amdgcn", "EM_AMDGPU")
300 .Case("r600", "EM_AMDGPU")
301 .Case("arm", "EM_ARM")
302 .Case("thumb", "EM_ARM")
303 .Case("avr", "EM_AVR")
304 .Case("mips", "EM_MIPS")
305 .Case("mipsel", "EM_MIPS")
306 .Case("mips64", "EM_MIPS")
307 .Case("mips64el", "EM_MIPS")
308 .Case("msp430", "EM_MSP430")
309 .Case("ppc", "EM_PPC")
310 .Case("ppc64", "EM_PPC64")
311 .Case("ppc64le", "EM_PPC64")
312 .Case("x86", T
.isOSIAMCU() ? "EM_IAMCU" : "EM_386")
313 .Case("x86_64", "EM_X86_64")
316 << "\n - Name: .text"
317 << "\n Type: SHT_PROGBITS"
318 << "\n - Name: .data"
319 << "\n Type: SHT_PROGBITS"
320 << "\n - Name: .rodata"
321 << "\n Type: SHT_PROGBITS"
323 for (const auto &Symbol
: Symbols
) {
324 OS
<< " - Name: " << Symbol
.Name
<< "\n"
326 switch (Symbol
.Type
) {
328 case IFSSymbolType::NoType
:
331 case IFSSymbolType::Object
:
334 case IFSSymbolType::Func
:
338 OS
<< "\n Section: .text"
339 << "\n Binding: STB_" << (Symbol
.Weak
? "WEAK" : "GLOBAL")
344 std::string YamlStr
= OS
.str();
346 // Only or debugging. Not an offical format.
348 if (ForceFormat
== "ELFOBJYAML") {
354 yaml::Input
YIn(YamlStr
);
355 if (Error E
= convertYAML(YIn
, Out
)) {
356 logAllUnhandledErrors(std::move(E
), WithColor::error(errs(), "llvm-ifs"));
363 int writeIfso(const IFSStub
&Stub
, bool IsWriteIfs
, raw_ostream
&Out
) {
365 yaml::Output
YamlOut(Out
, NULL
, /*WrapColumn =*/0);
366 YamlOut
<< const_cast<IFSStub
&>(Stub
);
370 std::string ObjectFileFormat
=
371 ForceFormat
.empty() ? Stub
.ObjectFileFormat
: ForceFormat
;
373 if (ObjectFileFormat
== "ELF" || ForceFormat
== "ELFOBJYAML")
374 return writeElfStub(llvm::Triple(Stub
.Triple
), Stub
.Symbols
,
375 Stub
.ObjectFileFormat
, Out
);
376 if (ObjectFileFormat
== "TBD")
377 return writeTbdStub(llvm::Triple(Stub
.Triple
), Stub
.Symbols
,
378 Stub
.ObjectFileFormat
, Out
);
381 << "Invalid ObjectFileFormat: Only ELF and TBD are supported.\n";
385 // New Interface Stubs Yaml Format:
386 // --- !experimental-ifs-v1
388 // Triple: <llvm triple>
389 // ObjectFileFormat: <ELF | others not yet supported>
391 // _ZSymbolName: { Type: <type> }
394 int main(int argc
, char *argv
[]) {
396 cl::ParseCommandLineOptions(argc
, argv
);
398 if (InputFilenames
.empty())
399 InputFilenames
.push_back("-");
402 std::map
<std::string
, IFSSymbol
> SymbolMap
;
404 std::string PreviousInputFilePath
= "";
405 for (const std::string
&InputFilePath
: InputFilenames
) {
406 Expected
<std::unique_ptr
<IFSStub
>> StubOrErr
= readInputFile(InputFilePath
);
408 WithColor::error() << StubOrErr
.takeError() << "\n";
411 std::unique_ptr
<IFSStub
> TargetStub
= std::move(StubOrErr
.get());
413 if (Stub
.Triple
.empty()) {
414 PreviousInputFilePath
= InputFilePath
;
415 Stub
.IfsVersion
= TargetStub
->IfsVersion
;
416 Stub
.Triple
= TargetStub
->Triple
;
417 Stub
.ObjectFileFormat
= TargetStub
->ObjectFileFormat
;
418 Stub
.SOName
= TargetStub
->SOName
;
419 Stub
.NeededLibs
= TargetStub
->NeededLibs
;
421 if (Stub
.IfsVersion
!= TargetStub
->IfsVersion
) {
422 if (Stub
.IfsVersion
.getMajor() != IFSVersionCurrent
.getMajor()) {
424 << "Interface Stub: IfsVersion Mismatch."
425 << "\nFilenames: " << PreviousInputFilePath
<< " "
426 << InputFilePath
<< "\nIfsVersion Values: " << Stub
.IfsVersion
427 << " " << TargetStub
->IfsVersion
<< "\n";
430 if (TargetStub
->IfsVersion
> Stub
.IfsVersion
)
431 Stub
.IfsVersion
= TargetStub
->IfsVersion
;
433 if (Stub
.ObjectFileFormat
!= TargetStub
->ObjectFileFormat
) {
434 WithColor::error() << "Interface Stub: ObjectFileFormat Mismatch."
435 << "\nFilenames: " << PreviousInputFilePath
<< " "
436 << InputFilePath
<< "\nObjectFileFormat Values: "
437 << Stub
.ObjectFileFormat
<< " "
438 << TargetStub
->ObjectFileFormat
<< "\n";
441 if (Stub
.Triple
!= TargetStub
->Triple
) {
442 WithColor::error() << "Interface Stub: Triple Mismatch."
443 << "\nFilenames: " << PreviousInputFilePath
<< " "
445 << "\nTriple Values: " << Stub
.Triple
<< " "
446 << TargetStub
->Triple
<< "\n";
449 if (Stub
.SOName
!= TargetStub
->SOName
) {
450 WithColor::error() << "Interface Stub: SOName Mismatch."
451 << "\nFilenames: " << PreviousInputFilePath
<< " "
453 << "\nSOName Values: " << Stub
.SOName
<< " "
454 << TargetStub
->SOName
<< "\n";
457 if (Stub
.NeededLibs
!= TargetStub
->NeededLibs
) {
458 WithColor::error() << "Interface Stub: NeededLibs Mismatch."
459 << "\nFilenames: " << PreviousInputFilePath
<< " "
460 << InputFilePath
<< "\n";
465 for (auto Symbol
: TargetStub
->Symbols
) {
466 auto SI
= SymbolMap
.find(Symbol
.Name
);
467 if (SI
== SymbolMap
.end()) {
469 std::pair
<std::string
, IFSSymbol
>(Symbol
.Name
, Symbol
));
473 assert(Symbol
.Name
== SI
->second
.Name
&& "Symbol Names Must Match.");
476 if (Symbol
.Type
!= SI
->second
.Type
) {
477 WithColor::error() << "Interface Stub: Type Mismatch for "
478 << Symbol
.Name
<< ".\nFilename: " << InputFilePath
479 << "\nType Values: " << getTypeName(SI
->second
.Type
)
480 << " " << getTypeName(Symbol
.Type
) << "\n";
484 if (Symbol
.Size
!= SI
->second
.Size
) {
485 WithColor::error() << "Interface Stub: Size Mismatch for "
486 << Symbol
.Name
<< ".\nFilename: " << InputFilePath
487 << "\nSize Values: " << SI
->second
.Size
<< " "
488 << Symbol
.Size
<< "\n";
492 if (Symbol
.Weak
!= SI
->second
.Weak
) {
493 // TODO: Add conflict resolution for Weak vs non-Weak.
494 WithColor::error() << "Interface Stub: Weak Mismatch for "
495 << Symbol
.Name
<< ".\nFilename: " << InputFilePath
496 << "\nWeak Values: " << SI
->second
.Weak
<< " "
497 << Symbol
.Weak
<< "\n";
501 // TODO: Not checking Warning. Will be dropped.
504 PreviousInputFilePath
= InputFilePath
;
507 if (Stub
.IfsVersion
!= IFSVersionCurrent
)
508 if (Stub
.IfsVersion
.getMajor() != IFSVersionCurrent
.getMajor()) {
509 WithColor::error() << "Interface Stub: Bad IfsVersion: "
510 << Stub
.IfsVersion
<< ", llvm-ifs supported version: "
511 << IFSVersionCurrent
<< ".\n";
515 for (auto &Entry
: SymbolMap
)
516 Stub
.Symbols
.insert(Entry
.second
);
518 std::error_code SysErr
;
520 // Open file for writing.
521 raw_fd_ostream
Out(OutputFilename
, SysErr
);
523 WithColor::error() << "Couldn't open " << OutputFilename
524 << " for writing.\n";
528 return writeIfso(Stub
, (Action
== "write-ifs"), Out
);