Upstream macCatalyst support in debugserver and the macOS dynamic loader
plugin.

Unfortunately the test is currently XFAILed because of missing changes
to the clang driver.

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

llvm-svn: 370931
diff --git a/lldb/source/Core/Module.cpp b/lldb/source/Core/Module.cpp
index c0dea3e..491ce93 100644
--- a/lldb/source/Core/Module.cpp
+++ b/lldb/source/Core/Module.cpp
@@ -1634,6 +1634,26 @@
   return m_source_mappings.RemapPath(path, new_path);
 }
 
+bool Module::MergeArchitecture(const ArchSpec &arch_spec) {
+  if (!arch_spec.IsValid())
+    return false;
+  LLDB_LOG(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_MODULES),
+           "module has arch %s, merging/replacing with arch %s",
+           m_arch.GetTriple().getTriple().c_str(),
+           arch_spec.GetTriple().getTriple().c_str());
+  if (!m_arch.IsCompatibleMatch(arch_spec)) {
+    // The new architecture is different, we just need to replace it.
+    return SetArchitecture(arch_spec);
+  }
+
+  // Merge bits from arch_spec into "merged_arch" and set our architecture.
+  ArchSpec merged_arch(m_arch);
+  merged_arch.MergeFrom(arch_spec);
+  // SetArchitecture() is a no-op if m_arch is already valid.
+  m_arch = ArchSpec();
+  return SetArchitecture(merged_arch);
+}
+
 llvm::VersionTuple Module::GetVersion() {
   if (ObjectFile *obj_file = GetObjectFile())
     return obj_file->GetVersion();
diff --git a/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm b/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
index 506c722..3f3f301 100644
--- a/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
+++ b/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm
@@ -71,23 +71,32 @@
   return false;
 }
 
+static void ParseOSVersion(llvm::VersionTuple &version, NSString *Key) {
+  @autoreleasepool {
+    NSDictionary *version_info =
+      [NSDictionary dictionaryWithContentsOfFile:
+       @"/System/Library/CoreServices/SystemVersion.plist"];
+    NSString *version_value = [version_info objectForKey: Key];
+    const char *version_str = [version_value UTF8String];
+    version.tryParse(version_str);
+  }
+}
+
 llvm::VersionTuple HostInfoMacOSX::GetOSVersion() {
   static llvm::VersionTuple g_version;
-
-  if (g_version.empty()) {
-    @autoreleasepool {
-      NSDictionary *version_info = [NSDictionary
-          dictionaryWithContentsOfFile:
-              @"/System/Library/CoreServices/SystemVersion.plist"];
-      NSString *version_value = [version_info objectForKey:@"ProductVersion"];
-      const char *version_str = [version_value UTF8String];
-      g_version.tryParse(version_str);
-    }
-  }
-
+  if (g_version.empty())
+    ParseOSVersion(g_version, @"ProductVersion");
   return g_version;
 }
 
+llvm::VersionTuple HostInfoMacOSX::GetMacCatalystVersion() {
+  static llvm::VersionTuple g_version;
+  if (g_version.empty())
+    ParseOSVersion(g_version, @"iOSSupportVersion");
+  return g_version;
+}
+
+
 FileSpec HostInfoMacOSX::GetProgramFileSpec() {
   static FileSpec g_program_filespec;
   if (!g_program_filespec) {
diff --git a/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp b/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
index 61afe51..9ec4ae0 100644
--- a/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
+++ b/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp
@@ -100,6 +100,18 @@
   const ModuleList &target_images = target.GetImages();
   ModuleSpec module_spec(image_info.file_spec);
   module_spec.GetUUID() = image_info.uuid;
+
+  // macCatalyst support: Request matching os/environment.
+  {
+    auto &target_triple = target.GetArchitecture().GetTriple();
+    if (target_triple.getOS() == llvm::Triple::IOS &&
+        target_triple.getEnvironment() == llvm::Triple::MacABI) {
+      // Request the macCatalyst variant of frameworks that have both
+      // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
+      module_spec.GetArchitecture() = ArchSpec(target_triple);
+    }
+  }
+
   ModuleSP module_sp(target_images.FindFirstModule(module_spec));
 
   if (module_sp && !module_spec.GetUUID().IsValid() &&
@@ -384,6 +396,10 @@
         image_infos[i].os_type = llvm::Triple::WatchOS;
       // NEED_BRIDGEOS_TRIPLE else if (os_name == "bridgeos")
       // NEED_BRIDGEOS_TRIPLE   image_infos[i].os_type = llvm::Triple::BridgeOS;
+      else if (os_name == "maccatalyst") {
+        image_infos[i].os_type = llvm::Triple::IOS;
+        image_infos[i].os_env = llvm::Triple::MacABI;
+      }
     }
     if (image->HasKey("min_version_os_sdk")) {
       image_infos[i].min_version_os_sdk =
@@ -654,6 +670,20 @@
         target_images.AppendIfNeeded(image_module_sp);
         loaded_module_list.AppendIfNeeded(image_module_sp);
       }
+
+      // macCataylst support:
+      // Update the module's platform with the DYLD info.
+      ArchSpec dyld_spec = image_infos[idx].GetArchitecture();
+      if (dyld_spec.GetTriple().getOS() == llvm::Triple::IOS &&
+          dyld_spec.GetTriple().getEnvironment() == llvm::Triple::MacABI) {
+        image_module_sp->MergeArchitecture(dyld_spec);
+        const auto &target_triple = target.GetArchitecture().GetTriple();
+        // If dyld reports the process as being loaded as MACCATALYST,
+        // force-update the target's architecture to MACCATALYST.
+        if (!(target_triple.getOS() == llvm::Triple::IOS &&
+              target_triple.getEnvironment() == llvm::Triple::MacABI))
+          target.SetArchitecture(dyld_spec);
+      }
     }
   }
 
@@ -711,6 +741,20 @@
   }
 }
 
+lldb_private::ArchSpec DynamicLoaderDarwin::ImageInfo::GetArchitecture() const {
+  // Update the module's platform with the DYLD info.
+  lldb_private::ArchSpec arch_spec(lldb_private::eArchTypeMachO, header.cputype,
+                                   header.cpusubtype);
+  if (os_type == llvm::Triple::IOS && os_env == llvm::Triple::MacABI) {
+    llvm::Triple triple(llvm::Twine("x86_64-apple-ios") + min_version_os_sdk +
+                        "-macabi");
+    ArchSpec maccatalyst_spec(triple);
+    if (arch_spec.IsCompatibleMatch(maccatalyst_spec))
+      arch_spec.MergeFrom(maccatalyst_spec);
+  }
+  return arch_spec;
+}
+
 const DynamicLoaderDarwin::Segment *
 DynamicLoaderDarwin::ImageInfo::FindSegment(ConstString name) const {
   const size_t num_segments = segments.size();
diff --git a/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h b/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h
index aac0a5d..f2c78d4 100644
--- a/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h
+++ b/lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.h
@@ -95,25 +95,34 @@
   };
 
   struct ImageInfo {
-    lldb::addr_t address;  // Address of mach header for this dylib
-    lldb::addr_t slide;    // The amount to slide all segments by if there is a
-                           // global slide.
-    lldb::addr_t mod_date; // Modification date for this dylib
-    lldb_private::FileSpec file_spec; // Resolved path for this dylib
-    lldb_private::UUID
-        uuid; // UUID for this dylib if it has one, else all zeros
-    llvm::MachO::mach_header header; // The mach header for this image
-    std::vector<Segment> segments;   // All segment vmaddr and vmsize pairs for
-                                   // this executable (from memory of inferior)
-    uint32_t load_stop_id; // The process stop ID that the sections for this
-                           // image were loaded
-    llvm::Triple::OSType os_type;   // LC_VERSION_MIN_... load command os type
-    std::string min_version_os_sdk; // LC_VERSION_MIN_... sdk value
+    /// Address of mach header for this dylib.
+    lldb::addr_t address = LLDB_INVALID_ADDRESS;
+    /// The amount to slide all segments by if there is a global
+    /// slide.
+    lldb::addr_t slide = 0;
+    /// Modification date for this dylib.
+    lldb::addr_t mod_date = 0;
+    /// Resolved path for this dylib.
+    lldb_private::FileSpec file_spec;
+    /// UUID for this dylib if it has one, else all zeros.
+    lldb_private::UUID uuid;
+    /// The mach header for this image.
+    llvm::MachO::mach_header header;
+    /// All segment vmaddr and vmsize pairs for this executable (from
+    /// memory of inferior).
+    std::vector<Segment> segments;
+    /// The process stop ID that the sections for this image were
+    /// loaded.
+    uint32_t load_stop_id = 0;
+    /// LC_VERSION_MIN_... load command os type.
+    llvm::Triple::OSType os_type = llvm::Triple::OSType::UnknownOS;
+    /// LC_VERSION_MIN_... load command os environment.
+    llvm::Triple::EnvironmentType os_env =
+        llvm::Triple::EnvironmentType::UnknownEnvironment;
+    /// LC_VERSION_MIN_... SDK.
+    std::string min_version_os_sdk;
 
-    ImageInfo()
-        : address(LLDB_INVALID_ADDRESS), slide(0), mod_date(0), file_spec(),
-          uuid(), header(), segments(), load_stop_id(0),
-          os_type(llvm::Triple::OSType::UnknownOS), min_version_os_sdk() {}
+    ImageInfo() = default;
 
     void Clear(bool load_cmd_data_only) {
       if (!load_cmd_data_only) {
@@ -127,6 +136,7 @@
       segments.clear();
       load_stop_id = 0;
       os_type = llvm::Triple::OSType::UnknownOS;
+      os_env = llvm::Triple::EnvironmentType::UnknownEnvironment;
       min_version_os_sdk.clear();
     }
 
@@ -135,7 +145,8 @@
              mod_date == rhs.mod_date && file_spec == rhs.file_spec &&
              uuid == rhs.uuid &&
              memcmp(&header, &rhs.header, sizeof(header)) == 0 &&
-             segments == rhs.segments && os_type == rhs.os_type;
+             segments == rhs.segments && os_type == rhs.os_type &&
+             os_env == rhs.os_env;
     }
 
     bool UUIDValid() const { return uuid.IsValid(); }
@@ -150,10 +161,7 @@
       return 0;
     }
 
-    lldb_private::ArchSpec GetArchitecture() const {
-      return lldb_private::ArchSpec(lldb_private::eArchTypeMachO,
-                                    header.cputype, header.cpusubtype);
-    }
+    lldb_private::ArchSpec GetArchitecture() const;
 
     const Segment *FindSegment(lldb_private::ConstString name) const;
 
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
index b00ecd7..40a88fb 100644
--- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp
@@ -931,6 +931,11 @@
   return m_os_version;
 }
 
+llvm::VersionTuple GDBRemoteCommunicationClient::GetMacCatalystVersion() {
+  GetHostInfo();
+  return m_maccatalyst_version;
+}
+
 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
   if (GetHostInfo()) {
     if (!m_os_build.empty()) {
@@ -1133,6 +1138,7 @@
         uint32_t sub = 0;
         std::string arch_name;
         std::string os_name;
+        std::string environment;
         std::string vendor_name;
         std::string triple;
         std::string distribution_id;
@@ -1172,7 +1178,11 @@
             extractor.GetHexByteString(m_os_kernel);
             ++num_keys_decoded;
           } else if (name.equals("ostype")) {
-            os_name = value;
+            if (value.equals("maccatalyst")) {
+              os_name = "ios";
+              environment = "macabi";
+            } else
+              os_name = value;
             ++num_keys_decoded;
           } else if (name.equals("vendor")) {
             vendor_name = value;
@@ -1196,6 +1206,9 @@
           {
             if (!m_os_version.tryParse(value))
               ++num_keys_decoded;
+          } else if (name.equals("maccatalyst_version")) {
+            if (!m_maccatalyst_version.tryParse(value))
+              ++num_keys_decoded;
           } else if (name.equals("watchpoint_exceptions_received")) {
             m_watchpoints_trigger_after_instruction =
                 llvm::StringSwitch<LazyBool>(value)
@@ -1233,6 +1246,8 @@
                     llvm::StringRef(vendor_name));
               if (!os_name.empty())
                 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
+              if (!environment.empty())
+                m_host_arch.GetTriple().setEnvironmentName(environment);
             }
           } else {
             std::string triple;
@@ -1985,6 +2000,7 @@
       uint32_t sub = 0;
       std::string arch_name;
       std::string os_name;
+      std::string environment;
       std::string vendor_name;
       std::string triple;
       std::string elf_abi;
@@ -2005,7 +2021,11 @@
           extractor.GetHexByteString(triple);
           ++num_keys_decoded;
         } else if (name.equals("ostype")) {
-          os_name = value;
+          if (value.equals("maccatalyst")) {
+            os_name = "ios";
+            environment = "macabi";
+          } else
+            os_name = value;
           ++num_keys_decoded;
         } else if (name.equals("vendor")) {
           vendor_name = value;
@@ -2046,6 +2066,8 @@
       } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
                  !vendor_name.empty()) {
         llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
+        if (!environment.empty())
+            triple.setEnvironmentName(environment);
 
         assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
         assert(triple.getObjectFormat() != llvm::Triple::Wasm);
@@ -2077,8 +2099,10 @@
         }
         m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
         m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
+        m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
         m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
         m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
+        m_host_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment));
       }
       return true;
     }
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h
index de85c9f..daee680 100644
--- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.h
@@ -248,6 +248,8 @@
 
   llvm::VersionTuple GetOSVersion();
 
+  llvm::VersionTuple GetMacCatalystVersion();
+
   bool GetOSBuildString(std::string &s);
 
   bool GetOSKernelDescription(std::string &s);
@@ -548,6 +550,7 @@
   ArchSpec m_host_arch;
   ArchSpec m_process_arch;
   llvm::VersionTuple m_os_version;
+  llvm::VersionTuple m_maccatalyst_version;
   std::string m_os_build;
   std::string m_os_kernel;
   std::string m_hostname;
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
index 7c84bf4..d0ae519 100644
--- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerCommon.cpp
@@ -260,6 +260,15 @@
     response.PutChar(';');
   }
 
+#if defined(__APPLE__)
+  llvm::VersionTuple maccatalyst_version = HostInfo::GetMacCatalystVersion();
+  if (!maccatalyst_version.empty()) {
+    response.Format("maccatalyst_version:{0}",
+                    maccatalyst_version.getAsString());
+    response.PutChar(';');
+  }
+#endif
+
   std::string s;
   if (HostInfo::GetOSBuildString(s)) {
     response.PutCString("os_build:");
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
index 69bcd8a..fee7b3f 100644
--- a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
@@ -4320,6 +4320,10 @@
   return m_gdb_comm.GetOSVersion();
 }
 
+llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
+  return m_gdb_comm.GetMacCatalystVersion();
+}
+
 namespace {
 
 typedef std::vector<std::string> stringVec;
diff --git a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
index 1411469..84004c1 100644
--- a/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
+++ b/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.h
@@ -199,6 +199,7 @@
                            const llvm::Triple &triple) override;
 
   llvm::VersionTuple GetHostOSVersion() override;
+  llvm::VersionTuple GetHostMacCatalystVersion() override;
 
   llvm::Error LoadModules() override;