llvm-ifs.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. //===- llvm-ifs.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. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/ADT/StringSwitch.h"
  10. #include "llvm/ADT/Triple.h"
  11. #include "llvm/ObjectYAML/yaml2obj.h"
  12. #include "llvm/Support/CommandLine.h"
  13. #include "llvm/Support/Debug.h"
  14. #include "llvm/Support/Errc.h"
  15. #include "llvm/Support/Error.h"
  16. #include "llvm/Support/FileOutputBuffer.h"
  17. #include "llvm/Support/MemoryBuffer.h"
  18. #include "llvm/Support/Path.h"
  19. #include "llvm/Support/VersionTuple.h"
  20. #include "llvm/Support/WithColor.h"
  21. #include "llvm/Support/YAMLTraits.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include "llvm/TextAPI/MachO/InterfaceFile.h"
  24. #include "llvm/TextAPI/MachO/TextAPIReader.h"
  25. #include "llvm/TextAPI/MachO/TextAPIWriter.h"
  26. #include <set>
  27. #include <string>
  28. #include <vector>
  29. using namespace llvm;
  30. using namespace llvm::yaml;
  31. using namespace llvm::MachO;
  32. #define DEBUG_TYPE "llvm-ifs"
  33. namespace {
  34. const VersionTuple IFSVersionCurrent(2, 0);
  35. } // end anonymous namespace
  36. static cl::opt<std::string> Action("action", cl::desc("<llvm-ifs action>"),
  37. cl::value_desc("write-ifs | write-bin"),
  38. cl::init("write-ifs"));
  39. static cl::opt<std::string> ForceFormat("force-format",
  40. cl::desc("<force object format>"),
  41. cl::value_desc("ELF | TBD"),
  42. cl::init(""));
  43. static cl::list<std::string> InputFilenames(cl::Positional,
  44. cl::desc("<input ifs files>"),
  45. cl::ZeroOrMore);
  46. static cl::opt<std::string> OutputFilename("o", cl::desc("<output file>"),
  47. cl::value_desc("path"));
  48. enum class IFSSymbolType {
  49. NoType = 0,
  50. Object,
  51. Func,
  52. // Type information is 4 bits, so 16 is safely out of range.
  53. Unknown = 16,
  54. };
  55. static std::string getTypeName(IFSSymbolType Type) {
  56. switch (Type) {
  57. case IFSSymbolType::NoType:
  58. return "NoType";
  59. case IFSSymbolType::Func:
  60. return "Func";
  61. case IFSSymbolType::Object:
  62. return "Object";
  63. case IFSSymbolType::Unknown:
  64. return "Unknown";
  65. }
  66. llvm_unreachable("Unexpected ifs symbol type.");
  67. }
  68. struct IFSSymbol {
  69. IFSSymbol() = default;
  70. IFSSymbol(std::string SymbolName) : Name(SymbolName) {}
  71. std::string Name;
  72. uint64_t Size;
  73. IFSSymbolType Type;
  74. bool Weak;
  75. Optional<std::string> Warning;
  76. bool operator<(const IFSSymbol &RHS) const { return Name < RHS.Name; }
  77. };
  78. LLVM_YAML_IS_SEQUENCE_VECTOR(IFSSymbol)
  79. namespace llvm {
  80. namespace yaml {
  81. /// YAML traits for IFSSymbolType.
  82. template <> struct ScalarEnumerationTraits<IFSSymbolType> {
  83. static void enumeration(IO &IO, IFSSymbolType &SymbolType) {
  84. IO.enumCase(SymbolType, "NoType", IFSSymbolType::NoType);
  85. IO.enumCase(SymbolType, "Func", IFSSymbolType::Func);
  86. IO.enumCase(SymbolType, "Object", IFSSymbolType::Object);
  87. IO.enumCase(SymbolType, "Unknown", IFSSymbolType::Unknown);
  88. // Treat other symbol types as noise, and map to Unknown.
  89. if (!IO.outputting() && IO.matchEnumFallback())
  90. SymbolType = IFSSymbolType::Unknown;
  91. }
  92. };
  93. /// YAML traits for IFSSymbol.
  94. template <> struct MappingTraits<IFSSymbol> {
  95. static void mapping(IO &IO, IFSSymbol &Symbol) {
  96. IO.mapRequired("Name", Symbol.Name);
  97. IO.mapRequired("Type", Symbol.Type);
  98. // The need for symbol size depends on the symbol type.
  99. if (Symbol.Type == IFSSymbolType::NoType)
  100. IO.mapOptional("Size", Symbol.Size, (uint64_t)0);
  101. else if (Symbol.Type == IFSSymbolType::Func)
  102. Symbol.Size = 0;
  103. else
  104. IO.mapRequired("Size", Symbol.Size);
  105. IO.mapOptional("Weak", Symbol.Weak, false);
  106. IO.mapOptional("Warning", Symbol.Warning);
  107. }
  108. // Compacts symbol information into a single line.
  109. static const bool flow = true;
  110. };
  111. } // namespace yaml
  112. } // namespace llvm
  113. // A cumulative representation of ELF stubs.
  114. // Both textual and binary stubs will read into and write from this object.
  115. class IFSStub {
  116. // TODO: Add support for symbol versioning.
  117. public:
  118. VersionTuple IfsVersion;
  119. std::string Triple;
  120. std::string ObjectFileFormat;
  121. Optional<std::string> SOName;
  122. std::vector<std::string> NeededLibs;
  123. std::vector<IFSSymbol> Symbols;
  124. IFSStub() = default;
  125. IFSStub(const IFSStub &Stub)
  126. : IfsVersion(Stub.IfsVersion), Triple(Stub.Triple),
  127. ObjectFileFormat(Stub.ObjectFileFormat), SOName(Stub.SOName),
  128. NeededLibs(Stub.NeededLibs), Symbols(Stub.Symbols) {}
  129. IFSStub(IFSStub &&Stub)
  130. : IfsVersion(std::move(Stub.IfsVersion)), Triple(std::move(Stub.Triple)),
  131. ObjectFileFormat(std::move(Stub.ObjectFileFormat)),
  132. SOName(std::move(Stub.SOName)), NeededLibs(std::move(Stub.NeededLibs)),
  133. Symbols(std::move(Stub.Symbols)) {}
  134. };
  135. namespace llvm {
  136. namespace yaml {
  137. /// YAML traits for IFSStub objects.
  138. template <> struct MappingTraits<IFSStub> {
  139. static void mapping(IO &IO, IFSStub &Stub) {
  140. if (!IO.mapTag("!experimental-ifs-v2", true))
  141. IO.setError("Not a .ifs YAML file.");
  142. auto OldContext = IO.getContext();
  143. IO.setContext(&Stub);
  144. IO.mapRequired("IfsVersion", Stub.IfsVersion);
  145. IO.mapOptional("Triple", Stub.Triple);
  146. IO.mapOptional("ObjectFileFormat", Stub.ObjectFileFormat);
  147. IO.mapOptional("SOName", Stub.SOName);
  148. IO.mapOptional("NeededLibs", Stub.NeededLibs);
  149. IO.mapRequired("Symbols", Stub.Symbols);
  150. IO.setContext(&OldContext);
  151. }
  152. };
  153. } // namespace yaml
  154. } // namespace llvm
  155. static Expected<std::unique_ptr<IFSStub>> readInputFile(StringRef FilePath) {
  156. // Read in file.
  157. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
  158. MemoryBuffer::getFileOrSTDIN(FilePath);
  159. if (!BufOrError)
  160. return createStringError(BufOrError.getError(), "Could not open `%s`",
  161. FilePath.data());
  162. std::unique_ptr<MemoryBuffer> FileReadBuffer = std::move(*BufOrError);
  163. yaml::Input YamlIn(FileReadBuffer->getBuffer());
  164. std::unique_ptr<IFSStub> Stub(new IFSStub());
  165. YamlIn >> *Stub;
  166. if (std::error_code Err = YamlIn.error())
  167. return createStringError(Err, "Failed reading Interface Stub File.");
  168. if (Stub->IfsVersion > IFSVersionCurrent)
  169. return make_error<StringError>(
  170. "IFS version " + Stub->IfsVersion.getAsString() + " is unsupported.",
  171. std::make_error_code(std::errc::invalid_argument));
  172. return std::move(Stub);
  173. }
  174. static int writeTbdStub(const Triple &T, const std::vector<IFSSymbol> &Symbols,
  175. const StringRef Format, raw_ostream &Out) {
  176. auto PlatformKindOrError =
  177. [](const llvm::Triple &T) -> llvm::Expected<llvm::MachO::PlatformKind> {
  178. if (T.isMacOSX())
  179. return llvm::MachO::PlatformKind::macOS;
  180. if (T.isTvOS())
  181. return llvm::MachO::PlatformKind::tvOS;
  182. if (T.isWatchOS())
  183. return llvm::MachO::PlatformKind::watchOS;
  184. // Note: put isiOS last because tvOS and watchOS are also iOS according
  185. // to the Triple.
  186. if (T.isiOS())
  187. return llvm::MachO::PlatformKind::iOS;
  188. // TODO: Add an option for ForceTriple, but keep ForceFormat for now.
  189. if (ForceFormat == "TBD")
  190. return llvm::MachO::PlatformKind::macOS;
  191. return createStringError(errc::not_supported, "Invalid Platform.\n");
  192. }(T);
  193. if (!PlatformKindOrError)
  194. return -1;
  195. PlatformKind Plat = PlatformKindOrError.get();
  196. TargetList Targets({Target(llvm::MachO::mapToArchitecture(T), Plat)});
  197. InterfaceFile File;
  198. File.setFileType(FileType::TBD_V3); // Only supporting v3 for now.
  199. File.addTargets(Targets);
  200. for (const auto &Symbol : Symbols) {
  201. auto Name = Symbol.Name;
  202. auto Kind = SymbolKind::GlobalSymbol;
  203. switch (Symbol.Type) {
  204. default:
  205. case IFSSymbolType::NoType:
  206. Kind = SymbolKind::GlobalSymbol;
  207. break;
  208. case IFSSymbolType::Object:
  209. Kind = SymbolKind::GlobalSymbol;
  210. break;
  211. case IFSSymbolType::Func:
  212. Kind = SymbolKind::GlobalSymbol;
  213. break;
  214. }
  215. if (Symbol.Weak)
  216. File.addSymbol(Kind, Name, Targets, SymbolFlags::WeakDefined);
  217. else
  218. File.addSymbol(Kind, Name, Targets);
  219. }
  220. SmallString<4096> Buffer;
  221. raw_svector_ostream OS(Buffer);
  222. if (Error Result = TextAPIWriter::writeToStream(OS, File))
  223. return -1;
  224. Out << OS.str();
  225. return 0;
  226. }
  227. static int writeElfStub(const Triple &T, const std::vector<IFSSymbol> &Symbols,
  228. const StringRef Format, raw_ostream &Out) {
  229. SmallString<0> Storage;
  230. Storage.clear();
  231. raw_svector_ostream OS(Storage);
  232. OS << "--- !ELF\n";
  233. OS << "FileHeader:\n";
  234. OS << " Class: ELFCLASS";
  235. OS << (T.isArch64Bit() ? "64" : "32");
  236. OS << "\n";
  237. OS << " Data: ELFDATA2";
  238. OS << (T.isLittleEndian() ? "LSB" : "MSB");
  239. OS << "\n";
  240. OS << " Type: ET_DYN\n";
  241. OS << " Machine: "
  242. << llvm::StringSwitch<llvm::StringRef>(T.getArchName())
  243. .Case("x86_64", "EM_X86_64")
  244. .Case("i386", "EM_386")
  245. .Case("i686", "EM_386")
  246. .Case("aarch64", "EM_AARCH64")
  247. .Case("amdgcn", "EM_AMDGPU")
  248. .Case("r600", "EM_AMDGPU")
  249. .Case("arm", "EM_ARM")
  250. .Case("thumb", "EM_ARM")
  251. .Case("avr", "EM_AVR")
  252. .Case("mips", "EM_MIPS")
  253. .Case("mipsel", "EM_MIPS")
  254. .Case("mips64", "EM_MIPS")
  255. .Case("mips64el", "EM_MIPS")
  256. .Case("msp430", "EM_MSP430")
  257. .Case("ppc", "EM_PPC")
  258. .Case("ppc64", "EM_PPC64")
  259. .Case("ppc64le", "EM_PPC64")
  260. .Case("x86", T.isOSIAMCU() ? "EM_IAMCU" : "EM_386")
  261. .Case("x86_64", "EM_X86_64")
  262. .Default("EM_NONE")
  263. << "\nSections:"
  264. << "\n - Name: .text"
  265. << "\n Type: SHT_PROGBITS"
  266. << "\n - Name: .data"
  267. << "\n Type: SHT_PROGBITS"
  268. << "\n - Name: .rodata"
  269. << "\n Type: SHT_PROGBITS"
  270. << "\nSymbols:\n";
  271. for (const auto &Symbol : Symbols) {
  272. OS << " - Name: " << Symbol.Name << "\n"
  273. << " Type: STT_";
  274. switch (Symbol.Type) {
  275. default:
  276. case IFSSymbolType::NoType:
  277. OS << "NOTYPE";
  278. break;
  279. case IFSSymbolType::Object:
  280. OS << "OBJECT";
  281. break;
  282. case IFSSymbolType::Func:
  283. OS << "FUNC";
  284. break;
  285. }
  286. OS << "\n Section: .text"
  287. << "\n Binding: STB_" << (Symbol.Weak ? "WEAK" : "GLOBAL")
  288. << "\n";
  289. }
  290. OS << "...\n";
  291. std::string YamlStr = std::string(OS.str());
  292. // Only or debugging. Not an offical format.
  293. LLVM_DEBUG({
  294. if (ForceFormat == "ELFOBJYAML") {
  295. Out << YamlStr;
  296. return 0;
  297. }
  298. });
  299. yaml::Input YIn(YamlStr);
  300. auto ErrHandler = [](const Twine &Msg) {
  301. WithColor::error(errs(), "llvm-ifs") << Msg << "\n";
  302. };
  303. return convertYAML(YIn, Out, ErrHandler) ? 0 : 1;
  304. }
  305. static int writeIfso(const IFSStub &Stub, bool IsWriteIfs, raw_ostream &Out) {
  306. if (IsWriteIfs) {
  307. yaml::Output YamlOut(Out, NULL, /*WrapColumn =*/0);
  308. YamlOut << const_cast<IFSStub &>(Stub);
  309. return 0;
  310. }
  311. std::string ObjectFileFormat =
  312. ForceFormat.empty() ? Stub.ObjectFileFormat : ForceFormat;
  313. if (ObjectFileFormat == "ELF" || ForceFormat == "ELFOBJYAML")
  314. return writeElfStub(llvm::Triple(Stub.Triple), Stub.Symbols,
  315. Stub.ObjectFileFormat, Out);
  316. if (ObjectFileFormat == "TBD")
  317. return writeTbdStub(llvm::Triple(Stub.Triple), Stub.Symbols,
  318. Stub.ObjectFileFormat, Out);
  319. WithColor::error()
  320. << "Invalid ObjectFileFormat: Only ELF and TBD are supported.\n";
  321. return -1;
  322. }
  323. // TODO: Drop ObjectFileFormat, it can be subsumed from the triple.
  324. // New Interface Stubs Yaml Format:
  325. // --- !experimental-ifs-v2
  326. // IfsVersion: 2.0
  327. // Triple: <llvm triple>
  328. // ObjectFileFormat: <ELF | others not yet supported>
  329. // Symbols:
  330. // _ZSymbolName: { Type: <type> }
  331. // ...
  332. int main(int argc, char *argv[]) {
  333. // Parse arguments.
  334. cl::ParseCommandLineOptions(argc, argv);
  335. if (InputFilenames.empty())
  336. InputFilenames.push_back("-");
  337. IFSStub Stub;
  338. std::map<std::string, IFSSymbol> SymbolMap;
  339. std::string PreviousInputFilePath;
  340. for (const std::string &InputFilePath : InputFilenames) {
  341. Expected<std::unique_ptr<IFSStub>> StubOrErr = readInputFile(InputFilePath);
  342. if (!StubOrErr) {
  343. WithColor::error() << StubOrErr.takeError() << "\n";
  344. return -1;
  345. }
  346. std::unique_ptr<IFSStub> TargetStub = std::move(StubOrErr.get());
  347. if (Stub.Triple.empty()) {
  348. PreviousInputFilePath = InputFilePath;
  349. Stub.IfsVersion = TargetStub->IfsVersion;
  350. Stub.Triple = TargetStub->Triple;
  351. Stub.ObjectFileFormat = TargetStub->ObjectFileFormat;
  352. Stub.SOName = TargetStub->SOName;
  353. Stub.NeededLibs = TargetStub->NeededLibs;
  354. } else {
  355. Stub.ObjectFileFormat = !Stub.ObjectFileFormat.empty()
  356. ? Stub.ObjectFileFormat
  357. : TargetStub->ObjectFileFormat;
  358. if (Stub.IfsVersion != TargetStub->IfsVersion) {
  359. if (Stub.IfsVersion.getMajor() != IFSVersionCurrent.getMajor()) {
  360. WithColor::error()
  361. << "Interface Stub: IfsVersion Mismatch."
  362. << "\nFilenames: " << PreviousInputFilePath << " "
  363. << InputFilePath << "\nIfsVersion Values: " << Stub.IfsVersion
  364. << " " << TargetStub->IfsVersion << "\n";
  365. return -1;
  366. }
  367. if (TargetStub->IfsVersion > Stub.IfsVersion)
  368. Stub.IfsVersion = TargetStub->IfsVersion;
  369. }
  370. if (Stub.ObjectFileFormat != TargetStub->ObjectFileFormat &&
  371. !TargetStub->ObjectFileFormat.empty()) {
  372. WithColor::error() << "Interface Stub: ObjectFileFormat Mismatch."
  373. << "\nFilenames: " << PreviousInputFilePath << " "
  374. << InputFilePath << "\nObjectFileFormat Values: "
  375. << Stub.ObjectFileFormat << " "
  376. << TargetStub->ObjectFileFormat << "\n";
  377. return -1;
  378. }
  379. if (Stub.Triple != TargetStub->Triple && !TargetStub->Triple.empty()) {
  380. WithColor::error() << "Interface Stub: Triple Mismatch."
  381. << "\nFilenames: " << PreviousInputFilePath << " "
  382. << InputFilePath
  383. << "\nTriple Values: " << Stub.Triple << " "
  384. << TargetStub->Triple << "\n";
  385. return -1;
  386. }
  387. if (Stub.SOName != TargetStub->SOName) {
  388. WithColor::error() << "Interface Stub: SOName Mismatch."
  389. << "\nFilenames: " << PreviousInputFilePath << " "
  390. << InputFilePath
  391. << "\nSOName Values: " << Stub.SOName << " "
  392. << TargetStub->SOName << "\n";
  393. return -1;
  394. }
  395. if (Stub.NeededLibs != TargetStub->NeededLibs) {
  396. WithColor::error() << "Interface Stub: NeededLibs Mismatch."
  397. << "\nFilenames: " << PreviousInputFilePath << " "
  398. << InputFilePath << "\n";
  399. return -1;
  400. }
  401. }
  402. for (auto Symbol : TargetStub->Symbols) {
  403. auto SI = SymbolMap.find(Symbol.Name);
  404. if (SI == SymbolMap.end()) {
  405. SymbolMap.insert(
  406. std::pair<std::string, IFSSymbol>(Symbol.Name, Symbol));
  407. continue;
  408. }
  409. assert(Symbol.Name == SI->second.Name && "Symbol Names Must Match.");
  410. // Check conflicts:
  411. if (Symbol.Type != SI->second.Type) {
  412. WithColor::error() << "Interface Stub: Type Mismatch for "
  413. << Symbol.Name << ".\nFilename: " << InputFilePath
  414. << "\nType Values: " << getTypeName(SI->second.Type)
  415. << " " << getTypeName(Symbol.Type) << "\n";
  416. return -1;
  417. }
  418. if (Symbol.Size != SI->second.Size) {
  419. WithColor::error() << "Interface Stub: Size Mismatch for "
  420. << Symbol.Name << ".\nFilename: " << InputFilePath
  421. << "\nSize Values: " << SI->second.Size << " "
  422. << Symbol.Size << "\n";
  423. return -1;
  424. }
  425. if (Symbol.Weak != SI->second.Weak) {
  426. Symbol.Weak = false;
  427. continue;
  428. }
  429. // TODO: Not checking Warning. Will be dropped.
  430. }
  431. PreviousInputFilePath = InputFilePath;
  432. }
  433. if (Stub.IfsVersion != IFSVersionCurrent)
  434. if (Stub.IfsVersion.getMajor() != IFSVersionCurrent.getMajor()) {
  435. WithColor::error() << "Interface Stub: Bad IfsVersion: "
  436. << Stub.IfsVersion << ", llvm-ifs supported version: "
  437. << IFSVersionCurrent << ".\n";
  438. return -1;
  439. }
  440. for (auto &Entry : SymbolMap)
  441. Stub.Symbols.push_back(Entry.second);
  442. std::error_code SysErr;
  443. // Open file for writing.
  444. raw_fd_ostream Out(OutputFilename, SysErr);
  445. if (SysErr) {
  446. WithColor::error() << "Couldn't open " << OutputFilename
  447. << " for writing.\n";
  448. return -1;
  449. }
  450. return writeIfso(Stub, (Action == "write-ifs"), Out);
  451. }