TextStub.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. //===- TextStub.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. //
  9. // Implements the text stub file reader/writer.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TextAPIContext.h"
  13. #include "TextStubCommon.h"
  14. #include "llvm/ADT/BitmaskEnum.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Support/Allocator.h"
  18. #include "llvm/Support/SourceMgr.h"
  19. #include "llvm/Support/YAMLTraits.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include "llvm/TextAPI/Architecture.h"
  22. #include "llvm/TextAPI/ArchitectureSet.h"
  23. #include "llvm/TextAPI/InterfaceFile.h"
  24. #include "llvm/TextAPI/PackedVersion.h"
  25. #include "llvm/TextAPI/TextAPIReader.h"
  26. #include "llvm/TextAPI/TextAPIWriter.h"
  27. #include <algorithm>
  28. #include <set>
  29. // clang-format off
  30. /*
  31. YAML Format specification.
  32. The TBD v1 format only support two level address libraries and is per
  33. definition application extension safe.
  34. --- # the tag !tapi-tbd-v1 is optional and
  35. # shouldn't be emitted to support older linker.
  36. archs: [ armv7, armv7s, arm64 ] # the list of architecture slices that are
  37. # supported by this file.
  38. platform: ios # Specifies the platform (macosx, ios, etc)
  39. install-name: /u/l/libfoo.dylib #
  40. current-version: 1.2.3 # Optional: defaults to 1.0
  41. compatibility-version: 1.0 # Optional: defaults to 1.0
  42. swift-version: 0 # Optional: defaults to 0
  43. objc-constraint: none # Optional: defaults to none
  44. exports: # List of export sections
  45. ...
  46. Each export section is defined as following:
  47. - archs: [ arm64 ] # the list of architecture slices
  48. allowed-clients: [ client ] # Optional: List of clients
  49. re-exports: [ ] # Optional: List of re-exports
  50. symbols: [ _sym ] # Optional: List of symbols
  51. objc-classes: [] # Optional: List of Objective-C classes
  52. objc-ivars: [] # Optional: List of Objective C Instance
  53. # Variables
  54. weak-def-symbols: [] # Optional: List of weak defined symbols
  55. thread-local-symbols: [] # Optional: List of thread local symbols
  56. */
  57. /*
  58. YAML Format specification.
  59. --- !tapi-tbd-v2
  60. archs: [ armv7, armv7s, arm64 ] # the list of architecture slices that are
  61. # supported by this file.
  62. uuids: [ armv7:... ] # Optional: List of architecture and UUID pairs.
  63. platform: ios # Specifies the platform (macosx, ios, etc)
  64. flags: [] # Optional:
  65. install-name: /u/l/libfoo.dylib #
  66. current-version: 1.2.3 # Optional: defaults to 1.0
  67. compatibility-version: 1.0 # Optional: defaults to 1.0
  68. swift-version: 0 # Optional: defaults to 0
  69. objc-constraint: retain_release # Optional: defaults to retain_release
  70. parent-umbrella: # Optional:
  71. exports: # List of export sections
  72. ...
  73. undefineds: # List of undefineds sections
  74. ...
  75. Each export section is defined as following:
  76. - archs: [ arm64 ] # the list of architecture slices
  77. allowed-clients: [ client ] # Optional: List of clients
  78. re-exports: [ ] # Optional: List of re-exports
  79. symbols: [ _sym ] # Optional: List of symbols
  80. objc-classes: [] # Optional: List of Objective-C classes
  81. objc-ivars: [] # Optional: List of Objective C Instance
  82. # Variables
  83. weak-def-symbols: [] # Optional: List of weak defined symbols
  84. thread-local-symbols: [] # Optional: List of thread local symbols
  85. Each undefineds section is defined as following:
  86. - archs: [ arm64 ] # the list of architecture slices
  87. symbols: [ _sym ] # Optional: List of symbols
  88. objc-classes: [] # Optional: List of Objective-C classes
  89. objc-ivars: [] # Optional: List of Objective C Instance Variables
  90. weak-ref-symbols: [] # Optional: List of weak defined symbols
  91. */
  92. /*
  93. YAML Format specification.
  94. --- !tapi-tbd-v3
  95. archs: [ armv7, armv7s, arm64 ] # the list of architecture slices that are
  96. # supported by this file.
  97. uuids: [ armv7:... ] # Optional: List of architecture and UUID pairs.
  98. platform: ios # Specifies the platform (macosx, ios, etc)
  99. flags: [] # Optional:
  100. install-name: /u/l/libfoo.dylib #
  101. current-version: 1.2.3 # Optional: defaults to 1.0
  102. compatibility-version: 1.0 # Optional: defaults to 1.0
  103. swift-abi-version: 0 # Optional: defaults to 0
  104. objc-constraint: retain_release # Optional: defaults to retain_release
  105. parent-umbrella: # Optional:
  106. exports: # List of export sections
  107. ...
  108. undefineds: # List of undefineds sections
  109. ...
  110. Each export section is defined as following:
  111. - archs: [ arm64 ] # the list of architecture slices
  112. allowed-clients: [ client ] # Optional: List of clients
  113. re-exports: [ ] # Optional: List of re-exports
  114. symbols: [ _sym ] # Optional: List of symbols
  115. objc-classes: [] # Optional: List of Objective-C classes
  116. objc-eh-types: [] # Optional: List of Objective-C classes
  117. # with EH
  118. objc-ivars: [] # Optional: List of Objective C Instance
  119. # Variables
  120. weak-def-symbols: [] # Optional: List of weak defined symbols
  121. thread-local-symbols: [] # Optional: List of thread local symbols
  122. Each undefineds section is defined as following:
  123. - archs: [ arm64 ] # the list of architecture slices
  124. symbols: [ _sym ] # Optional: List of symbols
  125. objc-classes: [] # Optional: List of Objective-C classes
  126. objc-eh-types: [] # Optional: List of Objective-C classes
  127. # with EH
  128. objc-ivars: [] # Optional: List of Objective C Instance Variables
  129. weak-ref-symbols: [] # Optional: List of weak defined symbols
  130. */
  131. /*
  132. YAML Format specification.
  133. --- !tapi-tbd
  134. tbd-version: 4 # The tbd version for format
  135. targets: [ armv7-ios, x86_64-maccatalyst ] # The list of applicable tapi supported target triples
  136. uuids: # Optional: List of target and UUID pairs.
  137. - target: armv7-ios
  138. value: ...
  139. - target: x86_64-maccatalyst
  140. value: ...
  141. flags: [] # Optional:
  142. install-name: /u/l/libfoo.dylib #
  143. current-version: 1.2.3 # Optional: defaults to 1.0
  144. compatibility-version: 1.0 # Optional: defaults to 1.0
  145. swift-abi-version: 0 # Optional: defaults to 0
  146. parent-umbrella: # Optional:
  147. allowable-clients:
  148. - targets: [ armv7-ios ] # Optional:
  149. clients: [ clientA ]
  150. exports: # List of export sections
  151. ...
  152. re-exports: # List of reexport sections
  153. ...
  154. undefineds: # List of undefineds sections
  155. ...
  156. Each export and reexport section is defined as following:
  157. - targets: [ arm64-macos ] # The list of target triples associated with symbols
  158. symbols: [ _symA ] # Optional: List of symbols
  159. objc-classes: [] # Optional: List of Objective-C classes
  160. objc-eh-types: [] # Optional: List of Objective-C classes
  161. # with EH
  162. objc-ivars: [] # Optional: List of Objective C Instance
  163. # Variables
  164. weak-symbols: [] # Optional: List of weak defined symbols
  165. thread-local-symbols: [] # Optional: List of thread local symbols
  166. - targets: [ arm64-macos, x86_64-maccatalyst ] # Optional: Targets for applicable additional symbols
  167. symbols: [ _symB ] # Optional: List of symbols
  168. Each undefineds section is defined as following:
  169. - targets: [ arm64-macos ] # The list of target triples associated with symbols
  170. symbols: [ _symC ] # Optional: List of symbols
  171. objc-classes: [] # Optional: List of Objective-C classes
  172. objc-eh-types: [] # Optional: List of Objective-C classes
  173. # with EH
  174. objc-ivars: [] # Optional: List of Objective C Instance Variables
  175. weak-symbols: [] # Optional: List of weak defined symbols
  176. */
  177. // clang-format on
  178. using namespace llvm;
  179. using namespace llvm::yaml;
  180. using namespace llvm::MachO;
  181. namespace {
  182. struct ExportSection {
  183. std::vector<Architecture> Architectures;
  184. std::vector<FlowStringRef> AllowableClients;
  185. std::vector<FlowStringRef> ReexportedLibraries;
  186. std::vector<FlowStringRef> Symbols;
  187. std::vector<FlowStringRef> Classes;
  188. std::vector<FlowStringRef> ClassEHs;
  189. std::vector<FlowStringRef> IVars;
  190. std::vector<FlowStringRef> WeakDefSymbols;
  191. std::vector<FlowStringRef> TLVSymbols;
  192. };
  193. struct UndefinedSection {
  194. std::vector<Architecture> Architectures;
  195. std::vector<FlowStringRef> Symbols;
  196. std::vector<FlowStringRef> Classes;
  197. std::vector<FlowStringRef> ClassEHs;
  198. std::vector<FlowStringRef> IVars;
  199. std::vector<FlowStringRef> WeakRefSymbols;
  200. };
  201. // Sections for direct target mapping in TBDv4
  202. struct SymbolSection {
  203. TargetList Targets;
  204. std::vector<FlowStringRef> Symbols;
  205. std::vector<FlowStringRef> Classes;
  206. std::vector<FlowStringRef> ClassEHs;
  207. std::vector<FlowStringRef> Ivars;
  208. std::vector<FlowStringRef> WeakSymbols;
  209. std::vector<FlowStringRef> TlvSymbols;
  210. };
  211. struct MetadataSection {
  212. enum Option { Clients, Libraries };
  213. std::vector<Target> Targets;
  214. std::vector<FlowStringRef> Values;
  215. };
  216. struct UmbrellaSection {
  217. std::vector<Target> Targets;
  218. std::string Umbrella;
  219. };
  220. // UUID's for TBDv4 are mapped to target not arch
  221. struct UUIDv4 {
  222. Target TargetID;
  223. std::string Value;
  224. UUIDv4() = default;
  225. UUIDv4(const Target &TargetID, const std::string &Value)
  226. : TargetID(TargetID), Value(Value) {}
  227. };
  228. // clang-format off
  229. enum TBDFlags : unsigned {
  230. None = 0U,
  231. FlatNamespace = 1U << 0,
  232. NotApplicationExtensionSafe = 1U << 1,
  233. InstallAPI = 1U << 2,
  234. LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/InstallAPI),
  235. };
  236. // clang-format on
  237. } // end anonymous namespace.
  238. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(Architecture)
  239. LLVM_YAML_IS_SEQUENCE_VECTOR(ExportSection)
  240. LLVM_YAML_IS_SEQUENCE_VECTOR(UndefinedSection)
  241. // Specific to TBDv4
  242. LLVM_YAML_IS_SEQUENCE_VECTOR(SymbolSection)
  243. LLVM_YAML_IS_SEQUENCE_VECTOR(MetadataSection)
  244. LLVM_YAML_IS_SEQUENCE_VECTOR(UmbrellaSection)
  245. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(Target)
  246. LLVM_YAML_IS_SEQUENCE_VECTOR(UUIDv4)
  247. namespace llvm {
  248. namespace yaml {
  249. template <> struct MappingTraits<ExportSection> {
  250. static void mapping(IO &IO, ExportSection &Section) {
  251. const auto *Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
  252. assert((!Ctx || (Ctx && Ctx->FileKind != FileType::Invalid)) &&
  253. "File type is not set in YAML context");
  254. IO.mapRequired("archs", Section.Architectures);
  255. if (Ctx->FileKind == FileType::TBD_V1)
  256. IO.mapOptional("allowed-clients", Section.AllowableClients);
  257. else
  258. IO.mapOptional("allowable-clients", Section.AllowableClients);
  259. IO.mapOptional("re-exports", Section.ReexportedLibraries);
  260. IO.mapOptional("symbols", Section.Symbols);
  261. IO.mapOptional("objc-classes", Section.Classes);
  262. if (Ctx->FileKind == FileType::TBD_V3)
  263. IO.mapOptional("objc-eh-types", Section.ClassEHs);
  264. IO.mapOptional("objc-ivars", Section.IVars);
  265. IO.mapOptional("weak-def-symbols", Section.WeakDefSymbols);
  266. IO.mapOptional("thread-local-symbols", Section.TLVSymbols);
  267. }
  268. };
  269. template <> struct MappingTraits<UndefinedSection> {
  270. static void mapping(IO &IO, UndefinedSection &Section) {
  271. const auto *Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
  272. assert((!Ctx || (Ctx && Ctx->FileKind != FileType::Invalid)) &&
  273. "File type is not set in YAML context");
  274. IO.mapRequired("archs", Section.Architectures);
  275. IO.mapOptional("symbols", Section.Symbols);
  276. IO.mapOptional("objc-classes", Section.Classes);
  277. if (Ctx->FileKind == FileType::TBD_V3)
  278. IO.mapOptional("objc-eh-types", Section.ClassEHs);
  279. IO.mapOptional("objc-ivars", Section.IVars);
  280. IO.mapOptional("weak-ref-symbols", Section.WeakRefSymbols);
  281. }
  282. };
  283. template <> struct MappingTraits<SymbolSection> {
  284. static void mapping(IO &IO, SymbolSection &Section) {
  285. IO.mapRequired("targets", Section.Targets);
  286. IO.mapOptional("symbols", Section.Symbols);
  287. IO.mapOptional("objc-classes", Section.Classes);
  288. IO.mapOptional("objc-eh-types", Section.ClassEHs);
  289. IO.mapOptional("objc-ivars", Section.Ivars);
  290. IO.mapOptional("weak-symbols", Section.WeakSymbols);
  291. IO.mapOptional("thread-local-symbols", Section.TlvSymbols);
  292. }
  293. };
  294. template <> struct MappingTraits<UmbrellaSection> {
  295. static void mapping(IO &IO, UmbrellaSection &Section) {
  296. IO.mapRequired("targets", Section.Targets);
  297. IO.mapRequired("umbrella", Section.Umbrella);
  298. }
  299. };
  300. template <> struct MappingTraits<UUIDv4> {
  301. static void mapping(IO &IO, UUIDv4 &UUID) {
  302. IO.mapRequired("target", UUID.TargetID);
  303. IO.mapRequired("value", UUID.Value);
  304. }
  305. };
  306. template <>
  307. struct MappingContextTraits<MetadataSection, MetadataSection::Option> {
  308. static void mapping(IO &IO, MetadataSection &Section,
  309. MetadataSection::Option &OptionKind) {
  310. IO.mapRequired("targets", Section.Targets);
  311. switch (OptionKind) {
  312. case MetadataSection::Option::Clients:
  313. IO.mapRequired("clients", Section.Values);
  314. return;
  315. case MetadataSection::Option::Libraries:
  316. IO.mapRequired("libraries", Section.Values);
  317. return;
  318. }
  319. llvm_unreachable("unexpected option for metadata");
  320. }
  321. };
  322. template <> struct ScalarBitSetTraits<TBDFlags> {
  323. static void bitset(IO &IO, TBDFlags &Flags) {
  324. IO.bitSetCase(Flags, "flat_namespace", TBDFlags::FlatNamespace);
  325. IO.bitSetCase(Flags, "not_app_extension_safe",
  326. TBDFlags::NotApplicationExtensionSafe);
  327. IO.bitSetCase(Flags, "installapi", TBDFlags::InstallAPI);
  328. }
  329. };
  330. template <> struct ScalarTraits<Target> {
  331. static void output(const Target &Value, void *, raw_ostream &OS) {
  332. OS << Value.Arch << "-";
  333. switch (Value.Platform) {
  334. default:
  335. OS << "unknown";
  336. break;
  337. case PLATFORM_MACOS:
  338. OS << "macos";
  339. break;
  340. case PLATFORM_IOS:
  341. OS << "ios";
  342. break;
  343. case PLATFORM_TVOS:
  344. OS << "tvos";
  345. break;
  346. case PLATFORM_WATCHOS:
  347. OS << "watchos";
  348. break;
  349. case PLATFORM_BRIDGEOS:
  350. OS << "bridgeos";
  351. break;
  352. case PLATFORM_MACCATALYST:
  353. OS << "maccatalyst";
  354. break;
  355. case PLATFORM_IOSSIMULATOR:
  356. OS << "ios-simulator";
  357. break;
  358. case PLATFORM_TVOSSIMULATOR:
  359. OS << "tvos-simulator";
  360. break;
  361. case PLATFORM_WATCHOSSIMULATOR:
  362. OS << "watchos-simulator";
  363. break;
  364. case PLATFORM_DRIVERKIT:
  365. OS << "driverkit";
  366. break;
  367. }
  368. }
  369. static StringRef input(StringRef Scalar, void *, Target &Value) {
  370. auto Result = Target::create(Scalar);
  371. if (!Result) {
  372. consumeError(Result.takeError());
  373. return "unparsable target";
  374. }
  375. Value = *Result;
  376. if (Value.Arch == AK_unknown)
  377. return "unknown architecture";
  378. if (Value.Platform == PLATFORM_UNKNOWN)
  379. return "unknown platform";
  380. return {};
  381. }
  382. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  383. };
  384. template <> struct MappingTraits<const InterfaceFile *> {
  385. struct NormalizedTBD {
  386. explicit NormalizedTBD(IO &IO) {}
  387. NormalizedTBD(IO &IO, const InterfaceFile *&File) {
  388. Architectures = File->getArchitectures();
  389. UUIDs = File->uuids();
  390. Platforms = File->getPlatforms();
  391. InstallName = File->getInstallName();
  392. CurrentVersion = PackedVersion(File->getCurrentVersion());
  393. CompatibilityVersion = PackedVersion(File->getCompatibilityVersion());
  394. SwiftABIVersion = File->getSwiftABIVersion();
  395. ObjCConstraint = File->getObjCConstraint();
  396. Flags = TBDFlags::None;
  397. if (!File->isApplicationExtensionSafe())
  398. Flags |= TBDFlags::NotApplicationExtensionSafe;
  399. if (!File->isTwoLevelNamespace())
  400. Flags |= TBDFlags::FlatNamespace;
  401. if (File->isInstallAPI())
  402. Flags |= TBDFlags::InstallAPI;
  403. if (!File->umbrellas().empty())
  404. ParentUmbrella = File->umbrellas().begin()->second;
  405. std::set<ArchitectureSet> ArchSet;
  406. for (const auto &Library : File->allowableClients())
  407. ArchSet.insert(Library.getArchitectures());
  408. for (const auto &Library : File->reexportedLibraries())
  409. ArchSet.insert(Library.getArchitectures());
  410. std::map<const Symbol *, ArchitectureSet> SymbolToArchSet;
  411. for (const auto *Symbol : File->exports()) {
  412. auto Architectures = Symbol->getArchitectures();
  413. SymbolToArchSet[Symbol] = Architectures;
  414. ArchSet.insert(Architectures);
  415. }
  416. for (auto Architectures : ArchSet) {
  417. ExportSection Section;
  418. Section.Architectures = Architectures;
  419. for (const auto &Library : File->allowableClients())
  420. if (Library.getArchitectures() == Architectures)
  421. Section.AllowableClients.emplace_back(Library.getInstallName());
  422. for (const auto &Library : File->reexportedLibraries())
  423. if (Library.getArchitectures() == Architectures)
  424. Section.ReexportedLibraries.emplace_back(Library.getInstallName());
  425. for (const auto &SymArch : SymbolToArchSet) {
  426. if (SymArch.second != Architectures)
  427. continue;
  428. const auto *Symbol = SymArch.first;
  429. switch (Symbol->getKind()) {
  430. case SymbolKind::GlobalSymbol:
  431. if (Symbol->isWeakDefined())
  432. Section.WeakDefSymbols.emplace_back(Symbol->getName());
  433. else if (Symbol->isThreadLocalValue())
  434. Section.TLVSymbols.emplace_back(Symbol->getName());
  435. else
  436. Section.Symbols.emplace_back(Symbol->getName());
  437. break;
  438. case SymbolKind::ObjectiveCClass:
  439. if (File->getFileType() != FileType::TBD_V3)
  440. Section.Classes.emplace_back(
  441. copyString("_" + Symbol->getName().str()));
  442. else
  443. Section.Classes.emplace_back(Symbol->getName());
  444. break;
  445. case SymbolKind::ObjectiveCClassEHType:
  446. if (File->getFileType() != FileType::TBD_V3)
  447. Section.Symbols.emplace_back(
  448. copyString("_OBJC_EHTYPE_$_" + Symbol->getName().str()));
  449. else
  450. Section.ClassEHs.emplace_back(Symbol->getName());
  451. break;
  452. case SymbolKind::ObjectiveCInstanceVariable:
  453. if (File->getFileType() != FileType::TBD_V3)
  454. Section.IVars.emplace_back(
  455. copyString("_" + Symbol->getName().str()));
  456. else
  457. Section.IVars.emplace_back(Symbol->getName());
  458. break;
  459. }
  460. }
  461. llvm::sort(Section.Symbols);
  462. llvm::sort(Section.Classes);
  463. llvm::sort(Section.ClassEHs);
  464. llvm::sort(Section.IVars);
  465. llvm::sort(Section.WeakDefSymbols);
  466. llvm::sort(Section.TLVSymbols);
  467. Exports.emplace_back(std::move(Section));
  468. }
  469. ArchSet.clear();
  470. SymbolToArchSet.clear();
  471. for (const auto *Symbol : File->undefineds()) {
  472. auto Architectures = Symbol->getArchitectures();
  473. SymbolToArchSet[Symbol] = Architectures;
  474. ArchSet.insert(Architectures);
  475. }
  476. for (auto Architectures : ArchSet) {
  477. UndefinedSection Section;
  478. Section.Architectures = Architectures;
  479. for (const auto &SymArch : SymbolToArchSet) {
  480. if (SymArch.second != Architectures)
  481. continue;
  482. const auto *Symbol = SymArch.first;
  483. switch (Symbol->getKind()) {
  484. case SymbolKind::GlobalSymbol:
  485. if (Symbol->isWeakReferenced())
  486. Section.WeakRefSymbols.emplace_back(Symbol->getName());
  487. else
  488. Section.Symbols.emplace_back(Symbol->getName());
  489. break;
  490. case SymbolKind::ObjectiveCClass:
  491. if (File->getFileType() != FileType::TBD_V3)
  492. Section.Classes.emplace_back(
  493. copyString("_" + Symbol->getName().str()));
  494. else
  495. Section.Classes.emplace_back(Symbol->getName());
  496. break;
  497. case SymbolKind::ObjectiveCClassEHType:
  498. if (File->getFileType() != FileType::TBD_V3)
  499. Section.Symbols.emplace_back(
  500. copyString("_OBJC_EHTYPE_$_" + Symbol->getName().str()));
  501. else
  502. Section.ClassEHs.emplace_back(Symbol->getName());
  503. break;
  504. case SymbolKind::ObjectiveCInstanceVariable:
  505. if (File->getFileType() != FileType::TBD_V3)
  506. Section.IVars.emplace_back(
  507. copyString("_" + Symbol->getName().str()));
  508. else
  509. Section.IVars.emplace_back(Symbol->getName());
  510. break;
  511. }
  512. }
  513. llvm::sort(Section.Symbols);
  514. llvm::sort(Section.Classes);
  515. llvm::sort(Section.ClassEHs);
  516. llvm::sort(Section.IVars);
  517. llvm::sort(Section.WeakRefSymbols);
  518. Undefineds.emplace_back(std::move(Section));
  519. }
  520. }
  521. // TBD v1 - TBD v3 files only support one platform and several
  522. // architectures. It is possible to have more than one platform for TBD v3
  523. // files, but the architectures don't apply to all
  524. // platforms, specifically to filter out the i386 slice from
  525. // platform macCatalyst.
  526. TargetList synthesizeTargets(ArchitectureSet Architectures,
  527. const PlatformSet &Platforms) {
  528. TargetList Targets;
  529. for (auto Platform : Platforms) {
  530. Platform = mapToPlatformType(Platform, Architectures.hasX86());
  531. for (const auto &&Architecture : Architectures) {
  532. if ((Architecture == AK_i386) && (Platform == PLATFORM_MACCATALYST))
  533. continue;
  534. Targets.emplace_back(Architecture, Platform);
  535. }
  536. }
  537. return Targets;
  538. }
  539. const InterfaceFile *denormalize(IO &IO) {
  540. auto Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
  541. assert(Ctx);
  542. auto *File = new InterfaceFile;
  543. File->setPath(Ctx->Path);
  544. File->setFileType(Ctx->FileKind);
  545. File->addTargets(synthesizeTargets(Architectures, Platforms));
  546. for (auto &ID : UUIDs)
  547. File->addUUID(ID.first, ID.second);
  548. File->setInstallName(InstallName);
  549. File->setCurrentVersion(CurrentVersion);
  550. File->setCompatibilityVersion(CompatibilityVersion);
  551. File->setSwiftABIVersion(SwiftABIVersion);
  552. File->setObjCConstraint(ObjCConstraint);
  553. for (const auto &Target : File->targets())
  554. File->addParentUmbrella(Target, ParentUmbrella);
  555. if (Ctx->FileKind == FileType::TBD_V1) {
  556. File->setTwoLevelNamespace();
  557. File->setApplicationExtensionSafe();
  558. } else {
  559. File->setTwoLevelNamespace(!(Flags & TBDFlags::FlatNamespace));
  560. File->setApplicationExtensionSafe(
  561. !(Flags & TBDFlags::NotApplicationExtensionSafe));
  562. File->setInstallAPI(Flags & TBDFlags::InstallAPI);
  563. }
  564. for (const auto &Section : Exports) {
  565. const auto Targets =
  566. synthesizeTargets(Section.Architectures, Platforms);
  567. for (const auto &Lib : Section.AllowableClients)
  568. for (const auto &Target : Targets)
  569. File->addAllowableClient(Lib, Target);
  570. for (const auto &Lib : Section.ReexportedLibraries)
  571. for (const auto &Target : Targets)
  572. File->addReexportedLibrary(Lib, Target);
  573. for (const auto &Symbol : Section.Symbols) {
  574. if (Ctx->FileKind != FileType::TBD_V3 &&
  575. Symbol.value.startswith("_OBJC_EHTYPE_$_"))
  576. File->addSymbol(SymbolKind::ObjectiveCClassEHType,
  577. Symbol.value.drop_front(15), Targets);
  578. else
  579. File->addSymbol(SymbolKind::GlobalSymbol, Symbol, Targets);
  580. }
  581. for (auto &Symbol : Section.Classes) {
  582. auto Name = Symbol.value;
  583. if (Ctx->FileKind != FileType::TBD_V3)
  584. Name = Name.drop_front();
  585. File->addSymbol(SymbolKind::ObjectiveCClass, Name, Targets);
  586. }
  587. for (auto &Symbol : Section.ClassEHs)
  588. File->addSymbol(SymbolKind::ObjectiveCClassEHType, Symbol, Targets);
  589. for (auto &Symbol : Section.IVars) {
  590. auto Name = Symbol.value;
  591. if (Ctx->FileKind != FileType::TBD_V3)
  592. Name = Name.drop_front();
  593. File->addSymbol(SymbolKind::ObjectiveCInstanceVariable, Name,
  594. Targets);
  595. }
  596. for (auto &Symbol : Section.WeakDefSymbols)
  597. File->addSymbol(SymbolKind::GlobalSymbol, Symbol, Targets,
  598. SymbolFlags::WeakDefined);
  599. for (auto &Symbol : Section.TLVSymbols)
  600. File->addSymbol(SymbolKind::GlobalSymbol, Symbol, Targets,
  601. SymbolFlags::ThreadLocalValue);
  602. }
  603. for (const auto &Section : Undefineds) {
  604. const auto Targets =
  605. synthesizeTargets(Section.Architectures, Platforms);
  606. for (auto &Symbol : Section.Symbols) {
  607. if (Ctx->FileKind != FileType::TBD_V3 &&
  608. Symbol.value.startswith("_OBJC_EHTYPE_$_"))
  609. File->addSymbol(SymbolKind::ObjectiveCClassEHType,
  610. Symbol.value.drop_front(15), Targets,
  611. SymbolFlags::Undefined);
  612. else
  613. File->addSymbol(SymbolKind::GlobalSymbol, Symbol, Targets,
  614. SymbolFlags::Undefined);
  615. }
  616. for (auto &Symbol : Section.Classes) {
  617. auto Name = Symbol.value;
  618. if (Ctx->FileKind != FileType::TBD_V3)
  619. Name = Name.drop_front();
  620. File->addSymbol(SymbolKind::ObjectiveCClass, Name, Targets,
  621. SymbolFlags::Undefined);
  622. }
  623. for (auto &Symbol : Section.ClassEHs)
  624. File->addSymbol(SymbolKind::ObjectiveCClassEHType, Symbol, Targets,
  625. SymbolFlags::Undefined);
  626. for (auto &Symbol : Section.IVars) {
  627. auto Name = Symbol.value;
  628. if (Ctx->FileKind != FileType::TBD_V3)
  629. Name = Name.drop_front();
  630. File->addSymbol(SymbolKind::ObjectiveCInstanceVariable, Name, Targets,
  631. SymbolFlags::Undefined);
  632. }
  633. for (auto &Symbol : Section.WeakRefSymbols)
  634. File->addSymbol(SymbolKind::GlobalSymbol, Symbol, Targets,
  635. SymbolFlags::Undefined | SymbolFlags::WeakReferenced);
  636. }
  637. return File;
  638. }
  639. llvm::BumpPtrAllocator Allocator;
  640. StringRef copyString(StringRef String) {
  641. if (String.empty())
  642. return {};
  643. void *Ptr = Allocator.Allocate(String.size(), 1);
  644. memcpy(Ptr, String.data(), String.size());
  645. return StringRef(reinterpret_cast<const char *>(Ptr), String.size());
  646. }
  647. std::vector<Architecture> Architectures;
  648. std::vector<UUID> UUIDs;
  649. PlatformSet Platforms;
  650. StringRef InstallName;
  651. PackedVersion CurrentVersion;
  652. PackedVersion CompatibilityVersion;
  653. SwiftVersion SwiftABIVersion{0};
  654. ObjCConstraintType ObjCConstraint{ObjCConstraintType::None};
  655. TBDFlags Flags{TBDFlags::None};
  656. StringRef ParentUmbrella;
  657. std::vector<ExportSection> Exports;
  658. std::vector<UndefinedSection> Undefineds;
  659. };
  660. static void setFileTypeForInput(TextAPIContext *Ctx, IO &IO) {
  661. if (IO.mapTag("!tapi-tbd", false))
  662. Ctx->FileKind = FileType::TBD_V4;
  663. else if (IO.mapTag("!tapi-tbd-v3", false))
  664. Ctx->FileKind = FileType::TBD_V3;
  665. else if (IO.mapTag("!tapi-tbd-v2", false))
  666. Ctx->FileKind = FileType::TBD_V2;
  667. else if (IO.mapTag("!tapi-tbd-v1", false) ||
  668. IO.mapTag("tag:yaml.org,2002:map", false))
  669. Ctx->FileKind = FileType::TBD_V1;
  670. else {
  671. Ctx->FileKind = FileType::Invalid;
  672. return;
  673. }
  674. }
  675. static void mapping(IO &IO, const InterfaceFile *&File) {
  676. auto *Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
  677. assert((!Ctx || !IO.outputting() ||
  678. (Ctx && Ctx->FileKind != FileType::Invalid)) &&
  679. "File type is not set in YAML context");
  680. if (!IO.outputting()) {
  681. setFileTypeForInput(Ctx, IO);
  682. switch (Ctx->FileKind) {
  683. default:
  684. break;
  685. case FileType::TBD_V4:
  686. mapKeysToValuesV4(IO, File);
  687. return;
  688. case FileType::Invalid:
  689. IO.setError("unsupported file type");
  690. return;
  691. }
  692. } else {
  693. // Set file type when writing.
  694. switch (Ctx->FileKind) {
  695. default:
  696. llvm_unreachable("unexpected file type");
  697. case FileType::TBD_V4:
  698. mapKeysToValuesV4(IO, File);
  699. return;
  700. case FileType::TBD_V3:
  701. IO.mapTag("!tapi-tbd-v3", true);
  702. break;
  703. case FileType::TBD_V2:
  704. IO.mapTag("!tapi-tbd-v2", true);
  705. break;
  706. case FileType::TBD_V1:
  707. // Don't write the tag into the .tbd file for TBD v1
  708. break;
  709. }
  710. }
  711. mapKeysToValues(Ctx->FileKind, IO, File);
  712. }
  713. using SectionList = std::vector<SymbolSection>;
  714. struct NormalizedTBD_V4 {
  715. explicit NormalizedTBD_V4(IO &IO) {}
  716. NormalizedTBD_V4(IO &IO, const InterfaceFile *&File) {
  717. auto Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
  718. assert(Ctx);
  719. TBDVersion = Ctx->FileKind >> 1;
  720. Targets.insert(Targets.begin(), File->targets().begin(),
  721. File->targets().end());
  722. for (const auto &IT : File->uuids())
  723. UUIDs.emplace_back(IT.first, IT.second);
  724. InstallName = File->getInstallName();
  725. CurrentVersion = File->getCurrentVersion();
  726. CompatibilityVersion = File->getCompatibilityVersion();
  727. SwiftABIVersion = File->getSwiftABIVersion();
  728. Flags = TBDFlags::None;
  729. if (!File->isApplicationExtensionSafe())
  730. Flags |= TBDFlags::NotApplicationExtensionSafe;
  731. if (!File->isTwoLevelNamespace())
  732. Flags |= TBDFlags::FlatNamespace;
  733. if (File->isInstallAPI())
  734. Flags |= TBDFlags::InstallAPI;
  735. {
  736. std::map<std::string, TargetList> valueToTargetList;
  737. for (const auto &it : File->umbrellas())
  738. valueToTargetList[it.second].emplace_back(it.first);
  739. for (const auto &it : valueToTargetList) {
  740. UmbrellaSection CurrentSection;
  741. CurrentSection.Targets.insert(CurrentSection.Targets.begin(),
  742. it.second.begin(), it.second.end());
  743. CurrentSection.Umbrella = it.first;
  744. ParentUmbrellas.emplace_back(std::move(CurrentSection));
  745. }
  746. }
  747. assignTargetsToLibrary(File->allowableClients(), AllowableClients);
  748. assignTargetsToLibrary(File->reexportedLibraries(), ReexportedLibraries);
  749. auto handleSymbols =
  750. [](SectionList &CurrentSections,
  751. InterfaceFile::const_filtered_symbol_range Symbols,
  752. std::function<bool(const Symbol *)> Pred) {
  753. std::set<TargetList> TargetSet;
  754. std::map<const Symbol *, TargetList> SymbolToTargetList;
  755. for (const auto *Symbol : Symbols) {
  756. if (!Pred(Symbol))
  757. continue;
  758. TargetList Targets(Symbol->targets());
  759. SymbolToTargetList[Symbol] = Targets;
  760. TargetSet.emplace(std::move(Targets));
  761. }
  762. for (const auto &TargetIDs : TargetSet) {
  763. SymbolSection CurrentSection;
  764. CurrentSection.Targets.insert(CurrentSection.Targets.begin(),
  765. TargetIDs.begin(), TargetIDs.end());
  766. for (const auto &IT : SymbolToTargetList) {
  767. if (IT.second != TargetIDs)
  768. continue;
  769. const auto *Symbol = IT.first;
  770. switch (Symbol->getKind()) {
  771. case SymbolKind::GlobalSymbol:
  772. if (Symbol->isWeakDefined())
  773. CurrentSection.WeakSymbols.emplace_back(Symbol->getName());
  774. else if (Symbol->isThreadLocalValue())
  775. CurrentSection.TlvSymbols.emplace_back(Symbol->getName());
  776. else
  777. CurrentSection.Symbols.emplace_back(Symbol->getName());
  778. break;
  779. case SymbolKind::ObjectiveCClass:
  780. CurrentSection.Classes.emplace_back(Symbol->getName());
  781. break;
  782. case SymbolKind::ObjectiveCClassEHType:
  783. CurrentSection.ClassEHs.emplace_back(Symbol->getName());
  784. break;
  785. case SymbolKind::ObjectiveCInstanceVariable:
  786. CurrentSection.Ivars.emplace_back(Symbol->getName());
  787. break;
  788. }
  789. }
  790. sort(CurrentSection.Symbols);
  791. sort(CurrentSection.Classes);
  792. sort(CurrentSection.ClassEHs);
  793. sort(CurrentSection.Ivars);
  794. sort(CurrentSection.WeakSymbols);
  795. sort(CurrentSection.TlvSymbols);
  796. CurrentSections.emplace_back(std::move(CurrentSection));
  797. }
  798. };
  799. handleSymbols(Exports, File->exports(), [](const Symbol *Symbol) {
  800. return !Symbol->isReexported();
  801. });
  802. handleSymbols(Reexports, File->exports(), [](const Symbol *Symbol) {
  803. return Symbol->isReexported();
  804. });
  805. handleSymbols(Undefineds, File->undefineds(),
  806. [](const Symbol *Symbol) { return true; });
  807. }
  808. const InterfaceFile *denormalize(IO &IO) {
  809. auto Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
  810. assert(Ctx);
  811. auto *File = new InterfaceFile;
  812. File->setPath(Ctx->Path);
  813. File->setFileType(Ctx->FileKind);
  814. for (auto &id : UUIDs)
  815. File->addUUID(id.TargetID, id.Value);
  816. File->addTargets(Targets);
  817. File->setInstallName(InstallName);
  818. File->setCurrentVersion(CurrentVersion);
  819. File->setCompatibilityVersion(CompatibilityVersion);
  820. File->setSwiftABIVersion(SwiftABIVersion);
  821. for (const auto &CurrentSection : ParentUmbrellas)
  822. for (const auto &target : CurrentSection.Targets)
  823. File->addParentUmbrella(target, CurrentSection.Umbrella);
  824. File->setTwoLevelNamespace(!(Flags & TBDFlags::FlatNamespace));
  825. File->setApplicationExtensionSafe(
  826. !(Flags & TBDFlags::NotApplicationExtensionSafe));
  827. File->setInstallAPI(Flags & TBDFlags::InstallAPI);
  828. for (const auto &CurrentSection : AllowableClients) {
  829. for (const auto &lib : CurrentSection.Values)
  830. for (const auto &Target : CurrentSection.Targets)
  831. File->addAllowableClient(lib, Target);
  832. }
  833. for (const auto &CurrentSection : ReexportedLibraries) {
  834. for (const auto &Lib : CurrentSection.Values)
  835. for (const auto &Target : CurrentSection.Targets)
  836. File->addReexportedLibrary(Lib, Target);
  837. }
  838. auto handleSymbols = [File](const SectionList &CurrentSections,
  839. SymbolFlags Flag = SymbolFlags::None) {
  840. for (const auto &CurrentSection : CurrentSections) {
  841. for (auto &sym : CurrentSection.Symbols)
  842. File->addSymbol(SymbolKind::GlobalSymbol, sym,
  843. CurrentSection.Targets, Flag);
  844. for (auto &sym : CurrentSection.Classes)
  845. File->addSymbol(SymbolKind::ObjectiveCClass, sym,
  846. CurrentSection.Targets);
  847. for (auto &sym : CurrentSection.ClassEHs)
  848. File->addSymbol(SymbolKind::ObjectiveCClassEHType, sym,
  849. CurrentSection.Targets);
  850. for (auto &sym : CurrentSection.Ivars)
  851. File->addSymbol(SymbolKind::ObjectiveCInstanceVariable, sym,
  852. CurrentSection.Targets);
  853. for (auto &sym : CurrentSection.WeakSymbols)
  854. File->addSymbol(SymbolKind::GlobalSymbol, sym,
  855. CurrentSection.Targets, SymbolFlags::WeakDefined);
  856. for (auto &sym : CurrentSection.TlvSymbols)
  857. File->addSymbol(SymbolKind::GlobalSymbol, sym,
  858. CurrentSection.Targets,
  859. SymbolFlags::ThreadLocalValue);
  860. }
  861. };
  862. handleSymbols(Exports);
  863. handleSymbols(Reexports, SymbolFlags::Rexported);
  864. handleSymbols(Undefineds, SymbolFlags::Undefined);
  865. return File;
  866. }
  867. unsigned TBDVersion;
  868. std::vector<UUIDv4> UUIDs;
  869. TargetList Targets;
  870. StringRef InstallName;
  871. PackedVersion CurrentVersion;
  872. PackedVersion CompatibilityVersion;
  873. SwiftVersion SwiftABIVersion{0};
  874. std::vector<MetadataSection> AllowableClients;
  875. std::vector<MetadataSection> ReexportedLibraries;
  876. TBDFlags Flags{TBDFlags::None};
  877. std::vector<UmbrellaSection> ParentUmbrellas;
  878. SectionList Exports;
  879. SectionList Reexports;
  880. SectionList Undefineds;
  881. private:
  882. void assignTargetsToLibrary(const std::vector<InterfaceFileRef> &Libraries,
  883. std::vector<MetadataSection> &Section) {
  884. std::set<TargetList> targetSet;
  885. std::map<const InterfaceFileRef *, TargetList> valueToTargetList;
  886. for (const auto &library : Libraries) {
  887. TargetList targets(library.targets());
  888. valueToTargetList[&library] = targets;
  889. targetSet.emplace(std::move(targets));
  890. }
  891. for (const auto &targets : targetSet) {
  892. MetadataSection CurrentSection;
  893. CurrentSection.Targets.insert(CurrentSection.Targets.begin(),
  894. targets.begin(), targets.end());
  895. for (const auto &it : valueToTargetList) {
  896. if (it.second != targets)
  897. continue;
  898. CurrentSection.Values.emplace_back(it.first->getInstallName());
  899. }
  900. llvm::sort(CurrentSection.Values);
  901. Section.emplace_back(std::move(CurrentSection));
  902. }
  903. }
  904. };
  905. static void mapKeysToValues(FileType FileKind, IO &IO,
  906. const InterfaceFile *&File) {
  907. MappingNormalization<NormalizedTBD, const InterfaceFile *> Keys(IO, File);
  908. IO.mapRequired("archs", Keys->Architectures);
  909. if (FileKind != FileType::TBD_V1)
  910. IO.mapOptional("uuids", Keys->UUIDs);
  911. IO.mapRequired("platform", Keys->Platforms);
  912. if (FileKind != FileType::TBD_V1)
  913. IO.mapOptional("flags", Keys->Flags, TBDFlags::None);
  914. IO.mapRequired("install-name", Keys->InstallName);
  915. IO.mapOptional("current-version", Keys->CurrentVersion,
  916. PackedVersion(1, 0, 0));
  917. IO.mapOptional("compatibility-version", Keys->CompatibilityVersion,
  918. PackedVersion(1, 0, 0));
  919. if (FileKind != FileType::TBD_V3)
  920. IO.mapOptional("swift-version", Keys->SwiftABIVersion, SwiftVersion(0));
  921. else
  922. IO.mapOptional("swift-abi-version", Keys->SwiftABIVersion,
  923. SwiftVersion(0));
  924. IO.mapOptional("objc-constraint", Keys->ObjCConstraint,
  925. (FileKind == FileType::TBD_V1)
  926. ? ObjCConstraintType::None
  927. : ObjCConstraintType::Retain_Release);
  928. if (FileKind != FileType::TBD_V1)
  929. IO.mapOptional("parent-umbrella", Keys->ParentUmbrella, StringRef());
  930. IO.mapOptional("exports", Keys->Exports);
  931. if (FileKind != FileType::TBD_V1)
  932. IO.mapOptional("undefineds", Keys->Undefineds);
  933. }
  934. static void mapKeysToValuesV4(IO &IO, const InterfaceFile *&File) {
  935. MappingNormalization<NormalizedTBD_V4, const InterfaceFile *> Keys(IO,
  936. File);
  937. IO.mapTag("!tapi-tbd", true);
  938. IO.mapRequired("tbd-version", Keys->TBDVersion);
  939. IO.mapRequired("targets", Keys->Targets);
  940. IO.mapOptional("uuids", Keys->UUIDs);
  941. IO.mapOptional("flags", Keys->Flags, TBDFlags::None);
  942. IO.mapRequired("install-name", Keys->InstallName);
  943. IO.mapOptional("current-version", Keys->CurrentVersion,
  944. PackedVersion(1, 0, 0));
  945. IO.mapOptional("compatibility-version", Keys->CompatibilityVersion,
  946. PackedVersion(1, 0, 0));
  947. IO.mapOptional("swift-abi-version", Keys->SwiftABIVersion, SwiftVersion(0));
  948. IO.mapOptional("parent-umbrella", Keys->ParentUmbrellas);
  949. auto OptionKind = MetadataSection::Option::Clients;
  950. IO.mapOptionalWithContext("allowable-clients", Keys->AllowableClients,
  951. OptionKind);
  952. OptionKind = MetadataSection::Option::Libraries;
  953. IO.mapOptionalWithContext("reexported-libraries", Keys->ReexportedLibraries,
  954. OptionKind);
  955. IO.mapOptional("exports", Keys->Exports);
  956. IO.mapOptional("reexports", Keys->Reexports);
  957. IO.mapOptional("undefineds", Keys->Undefineds);
  958. }
  959. };
  960. template <>
  961. struct DocumentListTraits<std::vector<const MachO::InterfaceFile *>> {
  962. static size_t size(IO &IO, std::vector<const MachO::InterfaceFile *> &Seq) {
  963. return Seq.size();
  964. }
  965. static const InterfaceFile *&
  966. element(IO &IO, std::vector<const InterfaceFile *> &Seq, size_t Index) {
  967. if (Index >= Seq.size())
  968. Seq.resize(Index + 1);
  969. return Seq[Index];
  970. }
  971. };
  972. } // end namespace yaml.
  973. } // namespace llvm
  974. static void DiagHandler(const SMDiagnostic &Diag, void *Context) {
  975. auto *File = static_cast<TextAPIContext *>(Context);
  976. SmallString<1024> Message;
  977. raw_svector_ostream S(Message);
  978. SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), File->Path,
  979. Diag.getLineNo(), Diag.getColumnNo(), Diag.getKind(),
  980. Diag.getMessage(), Diag.getLineContents(),
  981. Diag.getRanges(), Diag.getFixIts());
  982. NewDiag.print(nullptr, S);
  983. File->ErrorMessage = ("malformed file\n" + Message).str();
  984. }
  985. Expected<std::unique_ptr<InterfaceFile>>
  986. TextAPIReader::get(MemoryBufferRef InputBuffer) {
  987. TextAPIContext Ctx;
  988. Ctx.Path = std::string(InputBuffer.getBufferIdentifier());
  989. yaml::Input YAMLIn(InputBuffer.getBuffer(), &Ctx, DiagHandler, &Ctx);
  990. // Fill vector with interface file objects created by parsing the YAML file.
  991. std::vector<const InterfaceFile *> Files;
  992. YAMLIn >> Files;
  993. // YAMLIn dynamically allocates for Interface file and in case of error,
  994. // memory leak will occur unless wrapped around unique_ptr
  995. auto File = std::unique_ptr<InterfaceFile>(
  996. const_cast<InterfaceFile *>(Files.front()));
  997. for (const InterfaceFile *FI : llvm::drop_begin(Files))
  998. File->addDocument(
  999. std::shared_ptr<InterfaceFile>(const_cast<InterfaceFile *>(FI)));
  1000. if (YAMLIn.error())
  1001. return make_error<StringError>(Ctx.ErrorMessage, YAMLIn.error());
  1002. return std::move(File);
  1003. }
  1004. Error TextAPIWriter::writeToStream(raw_ostream &OS, const InterfaceFile &File) {
  1005. TextAPIContext Ctx;
  1006. Ctx.Path = std::string(File.getPath());
  1007. Ctx.FileKind = File.getFileType();
  1008. llvm::yaml::Output YAMLOut(OS, &Ctx, /*WrapColumn=*/80);
  1009. std::vector<const InterfaceFile *> Files;
  1010. Files.emplace_back(&File);
  1011. for (auto Document : File.documents())
  1012. Files.emplace_back(Document.get());
  1013. // Stream out yaml.
  1014. YAMLOut << Files;
  1015. return Error::success();
  1016. }