]> granicus.if.org Git - llvm/commitdiff
Reland "[TextAPI] Introduce TBDv4"
authorCyndy Ishida <cyndy_ishida@apple.com>
Thu, 10 Oct 2019 04:24:44 +0000 (04:24 +0000)
committerCyndy Ishida <cyndy_ishida@apple.com>
Thu, 10 Oct 2019 04:24:44 +0000 (04:24 +0000)
Original Patch broke for compilations w/ gcc and exposed asan fail.
This reland repairs those bugs.

Differential Revision: https://reviews.llvm.org/D67529

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@374277 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/TextAPI/MachO/InterfaceFile.h
include/llvm/TextAPI/MachO/Symbol.h
include/llvm/TextAPI/MachO/Target.h
lib/TextAPI/MachO/Target.cpp
lib/TextAPI/MachO/TextStub.cpp
lib/TextAPI/MachO/TextStubCommon.cpp
unittests/TextAPI/CMakeLists.txt
unittests/TextAPI/TextStubV4Tests.cpp [new file with mode: 0644]

index 8bb6b5ff0666533165c46d1115705aefb36a785c..bd434e04b693a856046c3d8a4a101a4029d07388 100644 (file)
@@ -67,6 +67,9 @@ enum FileType : unsigned {
   /// Text-based stub file (.tbd) version 3.0
   TBD_V3  = 1U <<  2,
 
+  /// Text-based stub file (.tbd) version 4.0
+  TBD_V4  = 1U <<  3,
+
   All     = ~0U,
 
   LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/All),
index b6444fbd78ff7ce73d419c8d542e3de59806690c..1b1632c599c4af74d6b7423815cd3b58881e9927 100644 (file)
@@ -38,7 +38,10 @@ enum class SymbolFlags : uint8_t {
   /// Undefined
   Undefined        = 1U << 3,
 
-  LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/Undefined),
+  /// Rexported
+  Rexported        = 1U << 4,
+
+  LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/Rexported),
 };
 
 // clang-format on
@@ -50,7 +53,7 @@ enum class SymbolKind : uint8_t {
   ObjectiveCInstanceVariable,
 };
 
-using TargetList = SmallVector<Target, 20>;
+using TargetList = SmallVector<Target, 5>;
 class Symbol {
 public:
   Symbol(SymbolKind Kind, StringRef Name, TargetList Targets, SymbolFlags Flags)
@@ -81,6 +84,10 @@ public:
     return (Flags & SymbolFlags::Undefined) == SymbolFlags::Undefined;
   }
 
+  bool isReexported() const {
+    return (Flags & SymbolFlags::Rexported) == SymbolFlags::Rexported;
+  }
+
   using const_target_iterator = TargetList::const_iterator;
   using const_target_range = llvm::iterator_range<const_target_iterator>;
   const_target_range targets() const { return {Targets}; }
index 74e900d812f523e1c217802e332bbd20e0736d07..5fe44cb7d366f5a954ab4bb99c36513d17346a5e 100644 (file)
@@ -29,6 +29,8 @@ public:
   explicit Target(const llvm::Triple &Triple)
       : Arch(mapToArchitecture(Triple)), Platform(mapToPlatformKind(Triple)) {}
 
+  static llvm::Expected<Target> create(StringRef Target);
+
   operator std::string() const;
 
   Architecture Arch;
index 3052aa53ac233c6019157bf9938b01c0daf1d37f..aee8ef421425ff602ac201447801b38ffc6d536d 100644 (file)
 namespace llvm {
 namespace MachO {
 
+Expected<Target> Target::create(StringRef TargetValue) {
+  auto Result = TargetValue.split('-');
+  auto ArchitectureStr = Result.first;
+  auto Architecture = getArchitectureFromName(ArchitectureStr);
+  auto PlatformStr = Result.second;
+  PlatformKind Platform;
+  Platform = StringSwitch<PlatformKind>(PlatformStr)
+                 .Case("macos", PlatformKind::macOS)
+                 .Case("ios", PlatformKind::iOS)
+                 .Case("tvos", PlatformKind::tvOS)
+                 .Case("watchos", PlatformKind::watchOS)
+                 .Case("bridgeos", PlatformKind::bridgeOS)
+                 .Case("maccatalyst", PlatformKind::macCatalyst)
+                 .Case("ios-simulator", PlatformKind::iOSSimulator)
+                 .Case("tvos-simulator", PlatformKind::tvOSSimulator)
+                 .Case("watchos-simulator", PlatformKind::watchOSSimulator)
+                 .Default(PlatformKind::unknown);
+
+  if (Platform == PlatformKind::unknown) {
+    if (PlatformStr.startswith("<") && PlatformStr.endswith(">")) {
+      PlatformStr = PlatformStr.drop_front().drop_back();
+      unsigned long long RawValue;
+      if (!PlatformStr.getAsInteger(10, RawValue))
+        Platform = (PlatformKind)RawValue;
+    }
+  }
+
+  return Target{Architecture, Platform};
+}
+
 Target::operator std::string() const {
   return (getArchitectureName(Arch) + " (" + getPlatformName(Platform) + ")")
       .str();
@@ -42,4 +72,4 @@ ArchitectureSet mapToArchitectureSet(ArrayRef<Target> Targets) {
 }
 
 } // end namespace MachO.
-} // end namespace llvm.
\ No newline at end of file
+} // end namespace llvm.
index 78c9f54ba22dd5f1f34e8717fcd10d36a78b0b11..0584e43d5893fefe929fcd557f6de98c6749ce5a 100644 (file)
@@ -147,6 +147,58 @@ Each undefineds section is defined as following:
   objc-ivars: []       # Optional: List of Objective C Instance Variables
   weak-ref-symbols: [] # Optional: List of weak defined symbols
 */
+
+/*
+
+ YAML Format specification.
+
+--- !tapi-tbd
+tbd-version: 4                              # The tbd version for format
+targets: [ armv7-ios, x86_64-maccatalyst ]  # The list of applicable tapi supported target triples
+uuids:                                      # Optional: List of target and UUID pairs.
+  - target: armv7-ios
+    value: ...
+  - target: x86_64-maccatalyst
+    value: ...
+flags: []                        # Optional:
+install-name: /u/l/libfoo.dylib  #
+current-version: 1.2.3           # Optional: defaults to 1.0
+compatibility-version: 1.0       # Optional: defaults to 1.0
+swift-abi-version: 0             # Optional: defaults to 0
+parent-umbrella:                 # Optional:
+allowable-clients:
+  - targets: [ armv7-ios ]       # Optional:
+    clients: [ clientA ]
+exports:                         # List of export sections
+...
+re-exports:                      # List of reexport sections
+...
+undefineds:                      # List of undefineds sections
+...
+
+Each export and reexport  section is defined as following:
+
+- targets: [ arm64-macos ]                        # The list of target triples associated with symbols
+  symbols: [ _symA ]                              # Optional: List of symbols
+  objc-classes: []                                # Optional: List of Objective-C classes
+  objc-eh-types: []                               # Optional: List of Objective-C classes
+                                                  #           with EH
+  objc-ivars: []                                  # Optional: List of Objective C Instance
+                                                  #           Variables
+  weak-symbols: []                                # Optional: List of weak defined symbols
+  thread-local-symbols: []                        # Optional: List of thread local symbols
+- targets: [ arm64-macos, x86_64-maccatalyst ]    # Optional: Targets for applicable additional symbols
+  symbols: [ _symB ]                              # Optional: List of symbols
+
+Each undefineds section is defined as following:
+- targets: [ arm64-macos ]    # The list of target triples associated with symbols
+  symbols: [ _symC ]          # Optional: List of symbols
+  objc-classes: []            # Optional: List of Objective-C classes
+  objc-eh-types: []           # Optional: List of Objective-C classes
+                              #           with EH
+  objc-ivars: []              # Optional: List of Objective C Instance Variables
+  weak-symbols: []            # Optional: List of weak defined symbols
+*/
 // clang-format on
 
 using namespace llvm;
@@ -175,6 +227,38 @@ struct UndefinedSection {
   std::vector<FlowStringRef> WeakRefSymbols;
 };
 
+// Sections for direct target mapping in TBDv4
+struct SymbolSection {
+  TargetList Targets;
+  std::vector<FlowStringRef> Symbols;
+  std::vector<FlowStringRef> Classes;
+  std::vector<FlowStringRef> ClassEHs;
+  std::vector<FlowStringRef> Ivars;
+  std::vector<FlowStringRef> WeakSymbols;
+  std::vector<FlowStringRef> TlvSymbols;
+};
+
+struct MetadataSection {
+  enum Option { Clients, Libraries };
+  std::vector<Target> Targets;
+  std::vector<FlowStringRef> Values;
+};
+
+struct UmbrellaSection {
+  std::vector<Target> Targets;
+  std::string Umbrella;
+};
+
+// UUID's for TBDv4 are mapped to target not arch
+struct UUIDv4 {
+  Target TargetID;
+  std::string Value;
+
+  UUIDv4() = default;
+  UUIDv4(const Target &TargetID, const std::string &Value)
+      : TargetID(TargetID), Value(Value) {}
+};
+
 // clang-format off
 enum TBDFlags : unsigned {
   None                         = 0U,
@@ -189,6 +273,12 @@ enum TBDFlags : unsigned {
 LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(Architecture)
 LLVM_YAML_IS_SEQUENCE_VECTOR(ExportSection)
 LLVM_YAML_IS_SEQUENCE_VECTOR(UndefinedSection)
+// Specific to TBDv4
+LLVM_YAML_IS_SEQUENCE_VECTOR(SymbolSection)
+LLVM_YAML_IS_SEQUENCE_VECTOR(MetadataSection)
+LLVM_YAML_IS_SEQUENCE_VECTOR(UmbrellaSection)
+LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(Target)
+LLVM_YAML_IS_SEQUENCE_VECTOR(UUIDv4)
 
 namespace llvm {
 namespace yaml {
@@ -231,6 +321,49 @@ template <> struct MappingTraits<UndefinedSection> {
   }
 };
 
+template <> struct MappingTraits<SymbolSection> {
+  static void mapping(IO &IO, SymbolSection &Section) {
+    IO.mapRequired("targets", Section.Targets);
+    IO.mapOptional("symbols", Section.Symbols);
+    IO.mapOptional("objc-classes", Section.Classes);
+    IO.mapOptional("objc-eh-types", Section.ClassEHs);
+    IO.mapOptional("objc-ivars", Section.Ivars);
+    IO.mapOptional("weak-symbols", Section.WeakSymbols);
+    IO.mapOptional("thread-local-symbols", Section.TlvSymbols);
+  }
+};
+
+template <> struct MappingTraits<UmbrellaSection> {
+  static void mapping(IO &IO, UmbrellaSection &Section) {
+    IO.mapRequired("targets", Section.Targets);
+    IO.mapRequired("umbrella", Section.Umbrella);
+  }
+};
+
+template <> struct MappingTraits<UUIDv4> {
+  static void mapping(IO &IO, UUIDv4 &UUID) {
+    IO.mapRequired("target", UUID.TargetID);
+    IO.mapRequired("value", UUID.Value);
+  }
+};
+
+template <>
+struct MappingContextTraits<MetadataSection, MetadataSection::Option> {
+  static void mapping(IO &IO, MetadataSection &Section,
+                      MetadataSection::Option &OptionKind) {
+    IO.mapRequired("targets", Section.Targets);
+    switch (OptionKind) {
+    case MetadataSection::Option::Clients:
+      IO.mapRequired("clients", Section.Values);
+      return;
+    case MetadataSection::Option::Libraries:
+      IO.mapRequired("libraries", Section.Values);
+      return;
+    }
+    llvm_unreachable("unexpected option for metadata");
+  }
+};
+
 template <> struct ScalarBitSetTraits<TBDFlags> {
   static void bitset(IO &IO, TBDFlags &Flags) {
     IO.bitSetCase(Flags, "flat_namespace", TBDFlags::FlatNamespace);
@@ -240,6 +373,60 @@ template <> struct ScalarBitSetTraits<TBDFlags> {
   }
 };
 
+template <> struct ScalarTraits<Target> {
+  static void output(const Target &Value, void *, raw_ostream &OS) {
+    OS << Value.Arch << "-";
+    switch (Value.Platform) {
+    default:
+      OS << "unknown";
+      break;
+    case PlatformKind::macOS:
+      OS << "macos";
+      break;
+    case PlatformKind::iOS:
+      OS << "ios";
+      break;
+    case PlatformKind::tvOS:
+      OS << "tvos";
+      break;
+    case PlatformKind::watchOS:
+      OS << "watchos";
+      break;
+    case PlatformKind::bridgeOS:
+      OS << "bridgeos";
+      break;
+    case PlatformKind::macCatalyst:
+      OS << "maccatalyst";
+      break;
+    case PlatformKind::iOSSimulator:
+      OS << "ios-simulator";
+      break;
+    case PlatformKind::tvOSSimulator:
+      OS << "tvos-simulator";
+      break;
+    case PlatformKind::watchOSSimulator:
+      OS << "watchos-simulator";
+      break;
+    }
+  }
+
+  static StringRef input(StringRef Scalar, void *, Target &Value) {
+    auto Result = Target::create(Scalar);
+    if (!Result)
+      return toString(Result.takeError());
+
+    Value = *Result;
+    if (Value.Arch == AK_unknown)
+      return "unknown architecture";
+    if (Value.Platform == PlatformKind::unknown)
+      return "unknown platform";
+
+    return {};
+  }
+
+  static QuotingType mustQuote(StringRef) { return QuotingType::None; }
+};
+
 template <> struct MappingTraits<const InterfaceFile *> {
   struct NormalizedTBD {
     explicit NormalizedTBD(IO &IO) {}
@@ -555,71 +742,336 @@ template <> struct MappingTraits<const InterfaceFile *> {
     std::vector<UndefinedSection> Undefineds;
   };
 
+  static void setFileTypeForInput(TextAPIContext *Ctx, IO &IO) {
+    if (IO.mapTag("!tapi-tbd", false))
+      Ctx->FileKind = FileType::TBD_V4;
+    else if (IO.mapTag("!tapi-tbd-v3", false))
+      Ctx->FileKind = FileType::TBD_V3;
+    else if (IO.mapTag("!tapi-tbd-v2", false))
+      Ctx->FileKind = FileType::TBD_V2;
+    else if (IO.mapTag("!tapi-tbd-v1", false) ||
+             IO.mapTag("tag:yaml.org,2002:map", false))
+      Ctx->FileKind = FileType::TBD_V1;
+    else {
+      Ctx->FileKind = FileType::Invalid;
+      return;
+    }
+  }
+
   static void mapping(IO &IO, const InterfaceFile *&File) {
     auto *Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
     assert((!Ctx || !IO.outputting() ||
             (Ctx && Ctx->FileKind != FileType::Invalid)) &&
            "File type is not set in YAML context");
-    MappingNormalization<NormalizedTBD, const InterfaceFile *> Keys(IO, File);
 
-    // prope file type when reading.
     if (!IO.outputting()) {
-      if (IO.mapTag("!tapi-tbd-v3", false))
-        Ctx->FileKind = FileType::TBD_V3;
-      else if (IO.mapTag("!tapi-tbd-v2", false))
-        Ctx->FileKind = FileType::TBD_V2;
-      else if (IO.mapTag("!tapi-tbd-v1", false) ||
-               IO.mapTag("tag:yaml.org,2002:map", false))
-        Ctx->FileKind = FileType::TBD_V1;
-      else {
+      setFileTypeForInput(Ctx, IO);
+      switch (Ctx->FileKind) {
+      default:
+        break;
+      case FileType::TBD_V4:
+        mapKeysToValuesV4(IO, File);
+        return;
+      case FileType::Invalid:
         IO.setError("unsupported file type");
         return;
       }
-    }
-
-    // Set file type when writing.
-    if (IO.outputting()) {
+    } else {
+      // Set file type when writing.
       switch (Ctx->FileKind) {
       default:
         llvm_unreachable("unexpected file type");
-      case FileType::TBD_V1:
-        // Don't write the tag into the .tbd file for TBD v1.
+      case FileType::TBD_V4:
+        mapKeysToValuesV4(IO, File);
+        return;
+      case FileType::TBD_V3:
+        IO.mapTag("!tapi-tbd-v3", true);
         break;
       case FileType::TBD_V2:
         IO.mapTag("!tapi-tbd-v2", true);
         break;
-      case FileType::TBD_V3:
-        IO.mapTag("!tapi-tbd-v3", true);
+      case FileType::TBD_V1:
+        // Don't write the tag into the .tbd file for TBD v1
         break;
       }
     }
+    mapKeysToValues(Ctx->FileKind, IO, File);
+  }
+
+  using SectionList = std::vector<SymbolSection>;
+  struct NormalizedTBD_V4 {
+    explicit NormalizedTBD_V4(IO &IO) {}
+    NormalizedTBD_V4(IO &IO, const InterfaceFile *&File) {
+      auto Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
+      assert(Ctx);
+      TBDVersion = Ctx->FileKind >> 1;
+      Targets.insert(Targets.begin(), File->targets().begin(),
+                     File->targets().end());
+      for (const auto &IT : File->uuids())
+        UUIDs.emplace_back(IT.first, IT.second);
+      InstallName = File->getInstallName();
+      CurrentVersion = File->getCurrentVersion();
+      CompatibilityVersion = File->getCompatibilityVersion();
+      SwiftABIVersion = File->getSwiftABIVersion();
+
+      Flags = TBDFlags::None;
+      if (!File->isApplicationExtensionSafe())
+        Flags |= TBDFlags::NotApplicationExtensionSafe;
+
+      if (!File->isTwoLevelNamespace())
+        Flags |= TBDFlags::FlatNamespace;
+
+      if (File->isInstallAPI())
+        Flags |= TBDFlags::InstallAPI;
+
+      {
+        std::map<std::string, TargetList> valueToTargetList;
+        for (const auto &it : File->umbrellas())
+          valueToTargetList[it.second].emplace_back(it.first);
+
+        for (const auto &it : valueToTargetList) {
+          UmbrellaSection CurrentSection;
+          CurrentSection.Targets.insert(CurrentSection.Targets.begin(),
+                                        it.second.begin(), it.second.end());
+          CurrentSection.Umbrella = it.first;
+          ParentUmbrellas.emplace_back(std::move(CurrentSection));
+        }
+      }
+
+      assignTargetsToLibrary(File->allowableClients(), AllowableClients);
+      assignTargetsToLibrary(File->reexportedLibraries(), ReexportedLibraries);
+
+      auto handleSymbols =
+          [](SectionList &CurrentSections,
+             InterfaceFile::const_filtered_symbol_range Symbols,
+             std::function<bool(const Symbol *)> Pred) {
+            std::set<TargetList> TargetSet;
+            std::map<const Symbol *, TargetList> SymbolToTargetList;
+            for (const auto *Symbol : Symbols) {
+              if (!Pred(Symbol))
+                continue;
+              TargetList Targets(Symbol->targets());
+              SymbolToTargetList[Symbol] = Targets;
+              TargetSet.emplace(std::move(Targets));
+            }
+            for (const auto &TargetIDs : TargetSet) {
+              SymbolSection CurrentSection;
+              CurrentSection.Targets.insert(CurrentSection.Targets.begin(),
+                                            TargetIDs.begin(), TargetIDs.end());
+
+              for (const auto &IT : SymbolToTargetList) {
+                if (IT.second != TargetIDs)
+                  continue;
+
+                const auto *Symbol = IT.first;
+                switch (Symbol->getKind()) {
+                case SymbolKind::GlobalSymbol:
+                  if (Symbol->isWeakDefined())
+                    CurrentSection.WeakSymbols.emplace_back(Symbol->getName());
+                  else if (Symbol->isThreadLocalValue())
+                    CurrentSection.TlvSymbols.emplace_back(Symbol->getName());
+                  else
+                    CurrentSection.Symbols.emplace_back(Symbol->getName());
+                  break;
+                case SymbolKind::ObjectiveCClass:
+                  CurrentSection.Classes.emplace_back(Symbol->getName());
+                  break;
+                case SymbolKind::ObjectiveCClassEHType:
+                  CurrentSection.ClassEHs.emplace_back(Symbol->getName());
+                  break;
+                case SymbolKind::ObjectiveCInstanceVariable:
+                  CurrentSection.Ivars.emplace_back(Symbol->getName());
+                  break;
+                }
+              }
+              sort(CurrentSection.Symbols);
+              sort(CurrentSection.Classes);
+              sort(CurrentSection.ClassEHs);
+              sort(CurrentSection.Ivars);
+              sort(CurrentSection.WeakSymbols);
+              sort(CurrentSection.TlvSymbols);
+              CurrentSections.emplace_back(std::move(CurrentSection));
+            }
+          };
+
+      handleSymbols(Exports, File->exports(), [](const Symbol *Symbol) {
+        return !Symbol->isReexported();
+      });
+      handleSymbols(Reexports, File->exports(), [](const Symbol *Symbol) {
+        return Symbol->isReexported();
+      });
+      handleSymbols(Undefineds, File->undefineds(),
+                    [](const Symbol *Symbol) { return true; });
+    }
+
+    const InterfaceFile *denormalize(IO &IO) {
+      auto Ctx = reinterpret_cast<TextAPIContext *>(IO.getContext());
+      assert(Ctx);
 
+      auto *File = new InterfaceFile;
+      File->setPath(Ctx->Path);
+      File->setFileType(Ctx->FileKind);
+      for (auto &id : UUIDs)
+        File->addUUID(id.TargetID, id.Value);
+      File->addTargets(Targets);
+      File->setInstallName(InstallName);
+      File->setCurrentVersion(CurrentVersion);
+      File->setCompatibilityVersion(CompatibilityVersion);
+      File->setSwiftABIVersion(SwiftABIVersion);
+      for (const auto &CurrentSection : ParentUmbrellas)
+        for (const auto &target : CurrentSection.Targets)
+          File->addParentUmbrella(target, CurrentSection.Umbrella);
+      File->setTwoLevelNamespace(!(Flags & TBDFlags::FlatNamespace));
+      File->setApplicationExtensionSafe(
+          !(Flags & TBDFlags::NotApplicationExtensionSafe));
+      File->setInstallAPI(Flags & TBDFlags::InstallAPI);
+
+      for (const auto &CurrentSection : AllowableClients) {
+        for (const auto &lib : CurrentSection.Values)
+          for (const auto &Target : CurrentSection.Targets)
+            File->addAllowableClient(lib, Target);
+      }
+
+      for (const auto &CurrentSection : ReexportedLibraries) {
+        for (const auto &Lib : CurrentSection.Values)
+          for (const auto &Target : CurrentSection.Targets)
+            File->addReexportedLibrary(Lib, Target);
+      }
+
+      auto handleSymbols = [File](const SectionList &CurrentSections,
+                                  SymbolFlags Flag = SymbolFlags::None) {
+        for (const auto &CurrentSection : CurrentSections) {
+          for (auto &sym : CurrentSection.Symbols)
+            File->addSymbol(SymbolKind::GlobalSymbol, sym,
+                            CurrentSection.Targets, Flag);
+
+          for (auto &sym : CurrentSection.Classes)
+            File->addSymbol(SymbolKind::ObjectiveCClass, sym,
+                            CurrentSection.Targets);
+
+          for (auto &sym : CurrentSection.ClassEHs)
+            File->addSymbol(SymbolKind::ObjectiveCClassEHType, sym,
+                            CurrentSection.Targets);
+
+          for (auto &sym : CurrentSection.Ivars)
+            File->addSymbol(SymbolKind::ObjectiveCInstanceVariable, sym,
+                            CurrentSection.Targets);
+
+          for (auto &sym : CurrentSection.WeakSymbols)
+            File->addSymbol(SymbolKind::GlobalSymbol, sym,
+                            CurrentSection.Targets);
+          for (auto &sym : CurrentSection.TlvSymbols)
+            File->addSymbol(SymbolKind::GlobalSymbol, sym,
+                            CurrentSection.Targets,
+                            SymbolFlags::ThreadLocalValue);
+        }
+      };
+
+      handleSymbols(Exports);
+      handleSymbols(Reexports, SymbolFlags::Rexported);
+      handleSymbols(Undefineds, SymbolFlags::Undefined);
+
+      return File;
+    }
+
+    unsigned TBDVersion;
+    std::vector<UUIDv4> UUIDs;
+    TargetList Targets;
+    StringRef InstallName;
+    PackedVersion CurrentVersion;
+    PackedVersion CompatibilityVersion;
+    SwiftVersion SwiftABIVersion{0};
+    std::vector<MetadataSection> AllowableClients;
+    std::vector<MetadataSection> ReexportedLibraries;
+    TBDFlags Flags{TBDFlags::None};
+    std::vector<UmbrellaSection> ParentUmbrellas;
+    SectionList Exports;
+    SectionList Reexports;
+    SectionList Undefineds;
+
+  private:
+    void assignTargetsToLibrary(const std::vector<InterfaceFileRef> &Libraries,
+                                std::vector<MetadataSection> &Section) {
+      std::set<TargetList> targetSet;
+      std::map<const InterfaceFileRef *, TargetList> valueToTargetList;
+      for (const auto &library : Libraries) {
+        TargetList targets(library.targets());
+        valueToTargetList[&library] = targets;
+        targetSet.emplace(std::move(targets));
+      }
+
+      for (const auto &targets : targetSet) {
+        MetadataSection CurrentSection;
+        CurrentSection.Targets.insert(CurrentSection.Targets.begin(),
+                                      targets.begin(), targets.end());
+
+        for (const auto &it : valueToTargetList) {
+          if (it.second != targets)
+            continue;
+
+          CurrentSection.Values.emplace_back(it.first->getInstallName());
+        }
+        llvm::sort(CurrentSection.Values);
+        Section.emplace_back(std::move(CurrentSection));
+      }
+    }
+  };
+
+  static void mapKeysToValues(FileType FileKind, IO &IO,
+                              const InterfaceFile *&File) {
+    MappingNormalization<NormalizedTBD, const InterfaceFile *> Keys(IO, File);
     IO.mapRequired("archs", Keys->Architectures);
-    if (Ctx->FileKind != FileType::TBD_V1)
+    if (FileKind != FileType::TBD_V1)
       IO.mapOptional("uuids", Keys->UUIDs);
     IO.mapRequired("platform", Keys->Platforms);
-    if (Ctx->FileKind != FileType::TBD_V1)
+    if (FileKind != FileType::TBD_V1)
       IO.mapOptional("flags", Keys->Flags, TBDFlags::None);
     IO.mapRequired("install-name", Keys->InstallName);
     IO.mapOptional("current-version", Keys->CurrentVersion,
                    PackedVersion(1, 0, 0));
     IO.mapOptional("compatibility-version", Keys->CompatibilityVersion,
                    PackedVersion(1, 0, 0));
-    if (Ctx->FileKind != FileType::TBD_V3)
+    if (FileKind != FileType::TBD_V3)
       IO.mapOptional("swift-version", Keys->SwiftABIVersion, SwiftVersion(0));
     else
       IO.mapOptional("swift-abi-version", Keys->SwiftABIVersion,
                      SwiftVersion(0));
     IO.mapOptional("objc-constraint", Keys->ObjCConstraint,
-                   (Ctx->FileKind == FileType::TBD_V1)
+                   (FileKind == FileType::TBD_V1)
                        ? ObjCConstraintType::None
                        : ObjCConstraintType::Retain_Release);
-    if (Ctx->FileKind != FileType::TBD_V1)
+    if (FileKind != FileType::TBD_V1)
       IO.mapOptional("parent-umbrella", Keys->ParentUmbrella, StringRef());
     IO.mapOptional("exports", Keys->Exports);
-    if (Ctx->FileKind != FileType::TBD_V1)
+    if (FileKind != FileType::TBD_V1)
       IO.mapOptional("undefineds", Keys->Undefineds);
   }
+
+  static void mapKeysToValuesV4(IO &IO, const InterfaceFile *&File) {
+    MappingNormalization<NormalizedTBD_V4, const InterfaceFile *> Keys(IO,
+                                                                       File);
+    IO.mapTag("!tapi-tbd", true);
+    IO.mapRequired("tbd-version", Keys->TBDVersion);
+    IO.mapRequired("targets", Keys->Targets);
+    IO.mapOptional("uuids", Keys->UUIDs);
+    IO.mapOptional("flags", Keys->Flags, TBDFlags::None);
+    IO.mapRequired("install-name", Keys->InstallName);
+    IO.mapOptional("current-version", Keys->CurrentVersion,
+                   PackedVersion(1, 0, 0));
+    IO.mapOptional("compatibility-version", Keys->CompatibilityVersion,
+                   PackedVersion(1, 0, 0));
+    IO.mapOptional("swift-abi-version", Keys->SwiftABIVersion, SwiftVersion(0));
+    IO.mapOptional("parent-umbrella", Keys->ParentUmbrellas);
+    auto OptionKind = MetadataSection::Option::Clients;
+    IO.mapOptionalWithContext("allowable-clients", Keys->AllowableClients,
+                              OptionKind);
+    OptionKind = MetadataSection::Option::Libraries;
+    IO.mapOptionalWithContext("reexported-libraries", Keys->ReexportedLibraries,
+                              OptionKind);
+    IO.mapOptional("exports", Keys->Exports);
+    IO.mapOptional("reexports", Keys->Reexports);
+    IO.mapOptional("undefineds", Keys->Undefineds);
+  }
 };
 
 template <>
index cfd9ac8d0cf6f56a053d04995747aa8864017749..183c5d5a93b03ce2293ba58acfa7616d7a3cb9e5 100644 (file)
@@ -172,14 +172,25 @@ void ScalarTraits<SwiftVersion>::output(const SwiftVersion &Value, void *,
     break;
   }
 }
-StringRef ScalarTraits<SwiftVersion>::input(StringRef Scalar, void *,
+StringRef ScalarTraits<SwiftVersion>::input(StringRef Scalar, void *IO,
                                             SwiftVersion &Value) {
-  Value = StringSwitch<SwiftVersion>(Scalar)
-              .Case("1.0", 1)
-              .Case("1.1", 2)
-              .Case("2.0", 3)
-              .Case("3.0", 4)
-              .Default(0);
+  const auto *Ctx = reinterpret_cast<TextAPIContext *>(IO);
+  assert((!Ctx || Ctx->FileKind != FileType::Invalid) &&
+         "File type is not set in context");
+
+  if (Ctx->FileKind == FileType::TBD_V4) {
+    if (Scalar.getAsInteger(10, Value))
+      return "invalid Swift ABI version.";
+    return {};
+  } else {
+    Value = StringSwitch<SwiftVersion>(Scalar)
+                .Case("1.0", 1)
+                .Case("1.1", 2)
+                .Case("2.0", 3)
+                .Case("3.0", 4)
+                .Default(0);
+  }
+
   if (Value != SwiftVersion(0))
     return {};
 
index 7f49df43ac3d4ac0a4b0b2fa8a966bcd9808474a..775ec2f1d1e886967f3cb31bc1392bda670ace0d 100644 (file)
@@ -7,6 +7,7 @@ add_llvm_unittest(TextAPITests
   TextStubV1Tests.cpp
   TextStubV2Tests.cpp
   TextStubV3Tests.cpp
+  TextStubV4Tests.cpp
 )
 
 target_link_libraries(TextAPITests PRIVATE LLVMTestingSupport)
diff --git a/unittests/TextAPI/TextStubV4Tests.cpp b/unittests/TextAPI/TextStubV4Tests.cpp
new file mode 100644 (file)
index 0000000..dc50e51
--- /dev/null
@@ -0,0 +1,564 @@
+//===-- TextStubV4Tests.cpp - TBD V4 File Test ----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===-----------------------------------------------------------------------===/
+#include "llvm/TextAPI/MachO/InterfaceFile.h"
+#include "llvm/TextAPI/MachO/TextAPIReader.h"
+#include "llvm/TextAPI/MachO/TextAPIWriter.h"
+#include "gtest/gtest.h"
+#include <string>
+#include <vector>
+
+using namespace llvm;
+using namespace llvm::MachO;
+
+struct ExampleSymbol {
+  SymbolKind Kind;
+  std::string Name;
+  bool WeakDefined;
+  bool ThreadLocalValue;
+};
+using ExampleSymbolSeq = std::vector<ExampleSymbol>;
+using UUIDs = std::vector<std::pair<Target, std::string>>;
+
+inline bool operator<(const ExampleSymbol &LHS, const ExampleSymbol &RHS) {
+  return std::tie(LHS.Kind, LHS.Name) < std::tie(RHS.Kind, RHS.Name);
+}
+
+inline bool operator==(const ExampleSymbol &LHS, const ExampleSymbol &RHS) {
+  return std::tie(LHS.Kind, LHS.Name, LHS.WeakDefined, LHS.ThreadLocalValue) ==
+         std::tie(RHS.Kind, RHS.Name, RHS.WeakDefined, RHS.ThreadLocalValue);
+}
+
+static ExampleSymbol TBDv4ExportedSymbols[] = {
+    {SymbolKind::GlobalSymbol, "_symA", false, false},
+    {SymbolKind::GlobalSymbol, "_symAB", false, false},
+    {SymbolKind::GlobalSymbol, "_symB", false, false},
+};
+
+static ExampleSymbol TBDv4ReexportedSymbols[] = {
+    {SymbolKind::GlobalSymbol, "_symC", false, false},
+};
+
+static ExampleSymbol TBDv4UndefinedSymbols[] = {
+    {SymbolKind::GlobalSymbol, "_symD", false, false},
+};
+
+namespace TBDv4 {
+
+TEST(TBDv4, ReadFile) {
+  static const char tbd_v4_file[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets:  [ i386-macos, x86_64-macos, x86_64-ios ]\n"
+      "uuids:\n"
+      "  - target: i386-macos\n"
+      "    value: 00000000-0000-0000-0000-000000000000\n"
+      "  - target: x86_64-macos\n"
+      "    value: 11111111-1111-1111-1111-111111111111\n"
+      "  - target: x86_64-ios\n"
+      "    value: 11111111-1111-1111-1111-111111111111\n"
+      "flags: [ flat_namespace, installapi ]\n"
+      "install-name: Umbrella.framework/Umbrella\n"
+      "current-version: 1.2.3\n"
+      "compatibility-version: 1.2\n"
+      "swift-abi-version: 5\n"
+      "parent-umbrella:\n"
+      "  - targets: [ i386-macos, x86_64-macos, x86_64-ios ]\n"
+      "    umbrella: System\n"
+      "allowable-clients:\n"
+      "  - targets: [ i386-macos, x86_64-macos, x86_64-ios ]\n"
+      "    clients: [ ClientA ]\n"
+      "reexported-libraries:\n"
+      "  - targets: [ i386-macos ]\n"
+      "    libraries: [ /System/Library/Frameworks/A.framework/A ]\n"
+      "exports:\n"
+      "  - targets: [ i386-macos ]\n"
+      "    symbols: [ _symA ]\n"
+      "    objc-classes: []\n"
+      "    objc-eh-types: []\n"
+      "    objc-ivars: []\n"
+      "    weak-symbols: []\n"
+      "    thread-local-symbols: []\n"
+      "  - targets: [ x86_64-ios ]\n"
+      "    symbols: [_symB]\n"
+      "  - targets: [ x86_64-macos, x86_64-ios ]\n"
+      "    symbols: [_symAB]\n"
+      "reexports:\n"
+      "  - targets: [ i386-macos ]\n"
+      "    symbols: [_symC]\n"
+      "    objc-classes: []\n"
+      "    objc-eh-types: []\n"
+      "    objc-ivars: []\n"
+      "    weak-symbols: []\n"
+      "    thread-local-symbols: []\n"
+      "undefineds:\n"
+      "  - targets: [ i386-macos ]\n"
+      "    symbols: [ _symD ]\n"
+      "    objc-classes: []\n"
+      "    objc-eh-types: []\n"
+      "    objc-ivars: []\n"
+      "    weak-symbols: []\n"
+      "    thread-local-symbols: []\n"
+      "...\n";
+
+  auto Result = TextAPIReader::get(MemoryBufferRef(tbd_v4_file, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  PlatformSet Platforms;
+  Platforms.insert(PlatformKind::macOS);
+  Platforms.insert(PlatformKind::iOS);
+  auto Archs = AK_i386 | AK_x86_64;
+  TargetList Targets = {
+      Target(AK_i386, PlatformKind::macOS),
+      Target(AK_x86_64, PlatformKind::macOS),
+      Target(AK_x86_64, PlatformKind::iOS),
+  };
+  UUIDs uuids = {{Targets[0], "00000000-0000-0000-0000-000000000000"},
+                 {Targets[1], "11111111-1111-1111-1111-111111111111"},
+                 {Targets[2], "11111111-1111-1111-1111-111111111111"}};
+  EXPECT_EQ(Archs, File->getArchitectures());
+  EXPECT_EQ(uuids, File->uuids());
+  EXPECT_EQ(Platforms.size(), File->getPlatforms().size());
+  for (auto Platform : File->getPlatforms())
+    EXPECT_EQ(Platforms.count(Platform), 1U);
+  EXPECT_EQ(std::string("Umbrella.framework/Umbrella"), File->getInstallName());
+  EXPECT_EQ(PackedVersion(1, 2, 3), File->getCurrentVersion());
+  EXPECT_EQ(PackedVersion(1, 2, 0), File->getCompatibilityVersion());
+  EXPECT_EQ(5U, File->getSwiftABIVersion());
+  EXPECT_FALSE(File->isTwoLevelNamespace());
+  EXPECT_TRUE(File->isApplicationExtensionSafe());
+  EXPECT_TRUE(File->isInstallAPI());
+  InterfaceFileRef client("ClientA", Targets);
+  InterfaceFileRef reexport("/System/Library/Frameworks/A.framework/A",
+                            {Targets[0]});
+  EXPECT_EQ(1U, File->allowableClients().size());
+  EXPECT_EQ(client, File->allowableClients().front());
+  EXPECT_EQ(1U, File->reexportedLibraries().size());
+  EXPECT_EQ(reexport, File->reexportedLibraries().front());
+
+  ExampleSymbolSeq Exports, Reexports, Undefineds;
+  ExampleSymbol temp;
+  for (const auto *Sym : File->symbols()) {
+    temp = ExampleSymbol{Sym->getKind(), Sym->getName(), Sym->isWeakDefined(),
+                         Sym->isThreadLocalValue()};
+    EXPECT_FALSE(Sym->isWeakReferenced());
+    if (Sym->isUndefined())
+      Undefineds.emplace_back(std::move(temp));
+    else
+      Sym->isReexported() ? Reexports.emplace_back(std::move(temp))
+                          : Exports.emplace_back(std::move(temp));
+  }
+  llvm::sort(Exports.begin(), Exports.end());
+  llvm::sort(Reexports.begin(), Reexports.end());
+  llvm::sort(Undefineds.begin(), Undefineds.end());
+
+  EXPECT_EQ(sizeof(TBDv4ExportedSymbols) / sizeof(ExampleSymbol),
+            Exports.size());
+  EXPECT_EQ(sizeof(TBDv4ReexportedSymbols) / sizeof(ExampleSymbol),
+            Reexports.size());
+  EXPECT_EQ(sizeof(TBDv4UndefinedSymbols) / sizeof(ExampleSymbol),
+            Undefineds.size());
+  EXPECT_TRUE(std::equal(Exports.begin(), Exports.end(),
+                         std::begin(TBDv4ExportedSymbols)));
+  EXPECT_TRUE(std::equal(Reexports.begin(), Reexports.end(),
+                         std::begin(TBDv4ReexportedSymbols)));
+  EXPECT_TRUE(std::equal(Undefineds.begin(), Undefineds.end(),
+                         std::begin(TBDv4UndefinedSymbols)));
+}
+
+TEST(TBDv4, WriteFile) {
+  static const char tbd_v4_file[] =
+      "--- !tapi-tbd\n"
+      "tbd-version:     4\n"
+      "targets:         [ i386-macos, x86_64-ios-simulator ]\n"
+      "uuids:\n"
+      "  - target:          i386-macos\n"
+      "    value:           00000000-0000-0000-0000-000000000000\n"
+      "  - target:          x86_64-ios-simulator\n"
+      "    value:           11111111-1111-1111-1111-111111111111\n"
+      "flags:           [ installapi ]\n"
+      "install-name:    'Umbrella.framework/Umbrella'\n"
+      "current-version: 1.2.3\n"
+      "compatibility-version: 0\n"
+      "swift-abi-version: 5\n"
+      "parent-umbrella:\n"
+      "  - targets:         [ i386-macos, x86_64-ios-simulator ]\n"
+      "    umbrella:        System\n"
+      "allowable-clients:\n"
+      "  - targets:         [ i386-macos ]\n"
+      "    clients:         [ ClientA ]\n"
+      "exports:\n"
+      "  - targets:         [ i386-macos ]\n"
+      "    symbols:         [ _symA ]\n"
+      "    objc-classes:    [ Class1 ]\n"
+      "    weak-symbols:    [ _symC ]\n"
+      "  - targets:         [ x86_64-ios-simulator ]\n"
+      "    symbols:         [ _symB ]\n"
+      "...\n";
+
+  InterfaceFile File;
+  TargetList Targets = {
+      Target(AK_i386, PlatformKind::macOS),
+      Target(AK_x86_64, PlatformKind::iOSSimulator),
+  };
+  UUIDs uuids = {{Targets[0], "00000000-0000-0000-0000-000000000000"},
+                 {Targets[1], "11111111-1111-1111-1111-111111111111"}};
+  File.setInstallName("Umbrella.framework/Umbrella");
+  File.setFileType(FileType::TBD_V4);
+  File.addTargets(Targets);
+  File.addUUID(uuids[0].first, uuids[0].second);
+  File.addUUID(uuids[1].first, uuids[1].second);
+  File.setCurrentVersion(PackedVersion(1, 2, 3));
+  File.setTwoLevelNamespace();
+  File.setInstallAPI(true);
+  File.setApplicationExtensionSafe(true);
+  File.setSwiftABIVersion(5);
+  File.addAllowableClient("ClientA", Targets[0]);
+  File.addParentUmbrella(Targets[0], "System");
+  File.addParentUmbrella(Targets[1], "System");
+  File.addSymbol(SymbolKind::GlobalSymbol, "_symA", {Targets[0]});
+  File.addSymbol(SymbolKind::GlobalSymbol, "_symB", {Targets[1]});
+  File.addSymbol(SymbolKind::GlobalSymbol, "_symC", {Targets[0]},
+                 SymbolFlags::WeakDefined);
+  File.addSymbol(SymbolKind::ObjectiveCClass, "Class1", {Targets[0]});
+
+  SmallString<4096> Buffer;
+  raw_svector_ostream OS(Buffer);
+  auto Result = TextAPIWriter::writeToStream(OS, File);
+  EXPECT_FALSE(Result);
+  EXPECT_STREQ(tbd_v4_file, Buffer.c_str());
+}
+
+TEST(TBDv4, MultipleTargets) {
+  static const char tbd_multiple_targets[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets: [ i386-maccatalyst, x86_64-tvos, arm64-ios ]\n"
+      "install-name: Test.dylib\n"
+      "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_multiple_targets, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  PlatformSet Platforms;
+  Platforms.insert(PlatformKind::macCatalyst);
+  Platforms.insert(PlatformKind::tvOS);
+  Platforms.insert(PlatformKind::iOS);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(AK_x86_64 | AK_arm64 | AK_i386, File->getArchitectures());
+  EXPECT_EQ(Platforms.size(), File->getPlatforms().size());
+  for (auto Platform : File->getPlatforms())
+    EXPECT_EQ(Platforms.count(Platform), 1U);
+}
+
+TEST(TBDv4, MultipleTargetsSameArch) {
+  static const char tbd_targets_same_arch[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets: [ x86_64-maccatalyst, x86_64-tvos ]\n"
+      "install-name: Test.dylib\n"
+      "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_targets_same_arch, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  PlatformSet Platforms;
+  Platforms.insert(PlatformKind::tvOS);
+  Platforms.insert(PlatformKind::macCatalyst);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
+  EXPECT_EQ(Platforms.size(), File->getPlatforms().size());
+  for (auto Platform : File->getPlatforms())
+    EXPECT_EQ(Platforms.count(Platform), 1U);
+}
+
+TEST(TBDv4, MultipleTargetsSamePlatform) {
+  static const char tbd_multiple_targets_same_platform[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets: [ arm64-ios, armv7k-ios ]\n"
+      "install-name: Test.dylib\n"
+      "...\n";
+
+  auto Result = TextAPIReader::get(
+      MemoryBufferRef(tbd_multiple_targets_same_platform, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(AK_arm64 | AK_armv7k, File->getArchitectures());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::iOS, *File->getPlatforms().begin());
+}
+
+TEST(TBDv4, Target_maccatalyst) {
+  static const char tbd_target_maccatalyst[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets: [  x86_64-maccatalyst ]\n"
+      "install-name: Test.dylib\n"
+      "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_target_maccatalyst, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::macCatalyst, *File->getPlatforms().begin());
+}
+
+TEST(TBDv4, Target_x86_ios) {
+  static const char tbd_target_x86_ios[] = "--- !tapi-tbd\n"
+                                           "tbd-version: 4\n"
+                                           "targets: [  x86_64-ios ]\n"
+                                           "install-name: Test.dylib\n"
+                                           "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_target_x86_ios, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::iOS, *File->getPlatforms().begin());
+}
+
+TEST(TBDv4, Target_arm_bridgeOS) {
+  static const char tbd_platform_bridgeos[] = "--- !tapi-tbd\n"
+                                              "tbd-version: 4\n"
+                                              "targets: [  armv7k-bridgeos ]\n"
+                                              "install-name: Test.dylib\n"
+                                              "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_platform_bridgeos, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::bridgeOS, *File->getPlatforms().begin());
+  EXPECT_EQ(ArchitectureSet(AK_armv7k), File->getArchitectures());
+}
+
+TEST(TBDv4, Target_x86_macos) {
+  static const char tbd_x86_macos[] = "--- !tapi-tbd\n"
+                                      "tbd-version: 4\n"
+                                      "targets: [  x86_64-macos ]\n"
+                                      "install-name: Test.dylib\n"
+                                      "...\n";
+
+  auto Result = TextAPIReader::get(MemoryBufferRef(tbd_x86_macos, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::macOS, *File->getPlatforms().begin());
+}
+
+TEST(TBDv4, Target_x86_ios_simulator) {
+  static const char tbd_x86_ios_sim[] = "--- !tapi-tbd\n"
+                                        "tbd-version: 4\n"
+                                        "targets: [  x86_64-ios-simulator  ]\n"
+                                        "install-name: Test.dylib\n"
+                                        "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_x86_ios_sim, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::iOSSimulator, *File->getPlatforms().begin());
+}
+
+TEST(TBDv4, Target_x86_tvos_simulator) {
+  static const char tbd_x86_tvos_sim[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets: [  x86_64-tvos-simulator  ]\n"
+      "install-name: Test.dylib\n"
+      "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_x86_tvos_sim, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(ArchitectureSet(AK_x86_64), File->getArchitectures());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::tvOSSimulator, *File->getPlatforms().begin());
+}
+
+TEST(TBDv4, Target_i386_watchos_simulator) {
+  static const char tbd_i386_watchos_sim[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets: [  i386-watchos-simulator  ]\n"
+      "install-name: Test.dylib\n"
+      "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_i386_watchos_sim, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(ArchitectureSet(AK_i386), File->getArchitectures());
+  EXPECT_EQ(File->getPlatforms().size(), 1U);
+  EXPECT_EQ(PlatformKind::watchOSSimulator, *File->getPlatforms().begin());
+}
+
+TEST(TBDv4, Swift_1) {
+  static const char tbd_swift_1[] = "--- !tapi-tbd\n"
+                                    "tbd-version: 4\n"
+                                    "targets: [  x86_64-macos ]\n"
+                                    "install-name: Test.dylib\n"
+                                    "swift-abi-version: 1\n"
+                                    "...\n";
+
+  auto Result = TextAPIReader::get(MemoryBufferRef(tbd_swift_1, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(1U, File->getSwiftABIVersion());
+}
+
+TEST(TBDv4, Swift_2) {
+  static const char tbd_v1_swift_2[] = "--- !tapi-tbd\n"
+                                       "tbd-version: 4\n"
+                                       "targets: [  x86_64-macos ]\n"
+                                       "install-name: Test.dylib\n"
+                                       "swift-abi-version: 2\n"
+                                       "...\n";
+
+  auto Result = TextAPIReader::get(MemoryBufferRef(tbd_v1_swift_2, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(2U, File->getSwiftABIVersion());
+}
+
+TEST(TBDv4, Swift_5) {
+  static const char tbd_swift_5[] = "--- !tapi-tbd\n"
+                                    "tbd-version: 4\n"
+                                    "targets: [  x86_64-macos ]\n"
+                                    "install-name: Test.dylib\n"
+                                    "swift-abi-version: 5\n"
+                                    "...\n";
+
+  auto Result = TextAPIReader::get(MemoryBufferRef(tbd_swift_5, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(5U, File->getSwiftABIVersion());
+}
+
+TEST(TBDv4, Swift_99) {
+  static const char tbd_swift_99[] = "--- !tapi-tbd\n"
+                                     "tbd-version: 4\n"
+                                     "targets: [  x86_64-macos ]\n"
+                                     "install-name: Test.dylib\n"
+                                     "swift-abi-version: 99\n"
+                                     "...\n";
+
+  auto Result = TextAPIReader::get(MemoryBufferRef(tbd_swift_99, "Test.tbd"));
+  EXPECT_TRUE(!!Result);
+  auto File = std::move(Result.get());
+  EXPECT_EQ(FileType::TBD_V4, File->getFileType());
+  EXPECT_EQ(99U, File->getSwiftABIVersion());
+}
+
+TEST(TBDv4, InvalidArchitecture) {
+  static const char tbd_file_unknown_architecture[] =
+      "--- !tapi-tbd\n"
+      "tbd-version: 4\n"
+      "targets: [ foo-macos ]\n"
+      "install-name: Test.dylib\n"
+      "...\n";
+
+  auto Result = TextAPIReader::get(
+      MemoryBufferRef(tbd_file_unknown_architecture, "Test.tbd"));
+  EXPECT_FALSE(!!Result);
+  auto errorMessage = toString(Result.takeError());
+  EXPECT_EQ("malformed file\nTest.tbd:3:12: error: unknown "
+            "architecture\ntargets: [ foo-macos ]\n"
+            "           ^~~~~~~~~~\n",
+            errorMessage);
+}
+
+TEST(TBDv4, InvalidPlatform) {
+  static const char tbd_file_invalid_platform[] = "--- !tapi-tbd\n"
+                                                  "tbd-version: 4\n"
+                                                  "targets: [ x86_64-maos ]\n"
+                                                  "install-name: Test.dylib\n"
+                                                  "...\n";
+
+  auto Result = TextAPIReader::get(
+      MemoryBufferRef(tbd_file_invalid_platform, "Test.tbd"));
+  EXPECT_FALSE(!!Result);
+  auto errorMessage = toString(Result.takeError());
+  EXPECT_EQ("malformed file\nTest.tbd:3:12: error: unknown platform\ntargets: "
+            "[ x86_64-maos ]\n"
+            "           ^~~~~~~~~~~~\n",
+            errorMessage);
+}
+
+TEST(TBDv4, MalformedFile1) {
+  static const char malformed_file1[] = "--- !tapi-tbd\n"
+                                        "tbd-version: 4\n"
+                                        "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(malformed_file1, "Test.tbd"));
+  EXPECT_FALSE(!!Result);
+  auto errorMessage = toString(Result.takeError());
+  ASSERT_EQ("malformed file\nTest.tbd:2:1: error: missing required key "
+            "'targets'\ntbd-version: 4\n^\n",
+            errorMessage);
+}
+
+TEST(TBDv4, MalformedFile2) {
+  static const char malformed_file2[] = "--- !tapi-tbd\n"
+                                        "tbd-version: 4\n"
+                                        "targets: [ x86_64-macos ]\n"
+                                        "install-name: Test.dylib\n"
+                                        "foobar: \"unsupported key\"\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(malformed_file2, "Test.tbd"));
+  EXPECT_FALSE(!!Result);
+  auto errorMessage = toString(Result.takeError());
+  ASSERT_EQ(
+      "malformed file\nTest.tbd:5:9: error: unknown key 'foobar'\nfoobar: "
+      "\"unsupported key\"\n        ^~~~~~~~~~~~~~~~~\n",
+      errorMessage);
+}
+
+TEST(TBDv4, MalformedFile3) {
+  static const char tbd_v1_swift_1_1[] = "--- !tapi-tbd\n"
+                                         "tbd-version: 4\n"
+                                         "targets: [  x86_64-macos ]\n"
+                                         "install-name: Test.dylib\n"
+                                         "swift-abi-version: 1.1\n"
+                                         "...\n";
+
+  auto Result =
+      TextAPIReader::get(MemoryBufferRef(tbd_v1_swift_1_1, "Test.tbd"));
+  EXPECT_FALSE(!!Result);
+  auto errorMessage = toString(Result.takeError());
+  EXPECT_EQ("malformed file\nTest.tbd:5:20: error: invalid Swift ABI "
+            "version.\nswift-abi-version: 1.1\n                   ^~~\n",
+            errorMessage);
+}
+
+} // end namespace TBDv4