Move GetAuxvData from Host to relevant process plugins

Summary:
GetAuxvData was causing dependencies from host to target and linux
process modules. It also does not fit netbsd use case, as there we can
only read the auxiliary vector with ptrace, which is better done in the
process plugin, with the other ptrace calls.

I resolve these issues by moving the freebsd and linux versions into the
relevant process plugins. In case of linux, this required adding an
interface in NativeProcessProtocol. The empty definitions on other
platforms can simply be removed.

To get the code compiling I had to add ProcessGdbRemote -> ProcessLinux
dependency, which was not caught before because we depended on it
transitively.

Reviewers: zturner, emaste

Subscribers: srhines, mgorny, lldb-commits

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

llvm-svn: 298066
diff --git a/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp b/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp
index 1f02385..f95599b8 100644
--- a/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp
+++ b/lldb/source/Plugins/Process/FreeBSD/ProcessFreeBSD.cpp
@@ -10,6 +10,12 @@
 
 // C Includes
 #include <errno.h>
+#include <pthread.h>
+#include <pthread_np.h>
+#include <stdlib.h>
+#include <sys/sysctl.h>
+#include <sys/types.h>
+#include <sys/user.h>
 
 // C++ Includes
 #include <mutex>
@@ -904,15 +910,18 @@
 const DataBufferSP ProcessFreeBSD::GetAuxvData() {
   // If we're the local platform, we can ask the host for auxv data.
   PlatformSP platform_sp = GetTarget().GetPlatform();
-  if (platform_sp && platform_sp->IsHost())
-    return lldb_private::Host::GetAuxvData(this);
+  assert(platform_sp && platform_sp->IsHost());
 
-  // Somewhat unexpected - the process is not running locally or we don't have a
-  // platform.
-  assert(
-      false &&
-      "no platform or not the host - how did we get here with ProcessFreeBSD?");
-  return DataBufferSP();
+  int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, process->GetID()};
+  size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
+  DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
+
+  if (::sysctl(mib, 4, buf_ap->GetBytes(), &auxv_size, NULL, 0) != 0) {
+    perror("sysctl failed on auxv");
+    buf_sp.reset();
+  }
+
+  return buf_sp;
 }
 
 struct EmulatorBaton {
diff --git a/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h b/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h
index 685a2ca..d6411f0 100644
--- a/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h
+++ b/lldb/source/Plugins/Process/Linux/NativeProcessLinux.h
@@ -18,6 +18,7 @@
 #include "lldb/Host/Debug.h"
 #include "lldb/Host/FileSpec.h"
 #include "lldb/Host/HostThread.h"
+#include "lldb/Host/linux/Support.h"
 #include "lldb/Target/MemoryRegionInfo.h"
 #include "lldb/lldb-types.h"
 
@@ -98,6 +99,11 @@
 
   NativeThreadLinuxSP GetThreadByID(lldb::tid_t id);
 
+  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
+  GetAuxvData() const override {
+    return getProcFile(GetID(), "auxv");
+  }
+
   // ---------------------------------------------------------------------
   // Interface used by NativeRegisterContext-derived classes.
   // ---------------------------------------------------------------------
diff --git a/lldb/source/Plugins/Process/gdb-remote/CMakeLists.txt b/lldb/source/Plugins/Process/gdb-remote/CMakeLists.txt
index fecbb8f..da9087f 100644
--- a/lldb/source/Plugins/Process/gdb-remote/CMakeLists.txt
+++ b/lldb/source/Plugins/Process/gdb-remote/CMakeLists.txt
@@ -2,6 +2,15 @@
   include_directories(${LIBXML2_INCLUDE_DIR})
 endif()
 
+set(LLDB_PLUGINS
+  lldbPluginProcessUtility
+  lldbPluginPlatformMacOSX
+)
+
+if(CMAKE_SYSTEM_NAME MATCHES "Linux|Android")
+  list(APPEND LLDB_PLUGINS lldbPluginProcessLinux)
+endif()
+
 add_lldb_library(lldbPluginProcessGDBRemote PLUGIN
   GDBRemoteClientBase.cpp
   GDBRemoteCommunication.cpp
@@ -24,8 +33,7 @@
     lldbSymbol
     lldbTarget
     lldbUtility
-    lldbPluginProcessUtility
-    lldbPluginPlatformMacOSX
+    ${LLDB_PLUGINS}
   LINK_COMPONENTS
     Support
   )
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp
index f0aea5d..7a64254 100644
--- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.cpp
@@ -81,7 +81,6 @@
       m_continue_tid(LLDB_INVALID_THREAD_ID), m_debugged_process_mutex(),
       m_debugged_process_sp(), m_stdio_communication("process.stdio"),
       m_inferior_prev_state(StateType::eStateInvalid),
-      m_active_auxv_buffer_sp(), m_saved_registers_mutex(),
       m_saved_registers_map(), m_next_saved_registers_id(1),
       m_handshake_completed(false) {
   RegisterPacketHandlers();
@@ -2694,7 +2693,7 @@
                                  "qXfer:auxv:read:: packet missing length");
 
   // Grab the auxv data if we need it.
-  if (!m_active_auxv_buffer_sp) {
+  if (!m_active_auxv_buffer_up) {
     // Make sure we have a valid process.
     if (!m_debugged_process_sp ||
         (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
@@ -2706,55 +2705,45 @@
     }
 
     // Grab the auxv data.
-    m_active_auxv_buffer_sp = Host::GetAuxvData(m_debugged_process_sp->GetID());
-    if (!m_active_auxv_buffer_sp ||
-        m_active_auxv_buffer_sp->GetByteSize() == 0) {
-      // Hmm, no auxv data, call that an error.
-      if (log)
-        log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data "
-                    "retrieved",
-                    __FUNCTION__);
-      m_active_auxv_buffer_sp.reset();
-      return SendErrorResponse(0x11);
+    auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
+    if (!buffer_or_error) {
+      std::error_code ec = buffer_or_error.getError();
+      LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
+      return SendErrorResponse(ec.value());
     }
+    m_active_auxv_buffer_up = std::move(*buffer_or_error);
   }
 
-  // FIXME find out if/how I lock the stream here.
-
   StreamGDBRemote response;
   bool done_with_buffer = false;
 
-  if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize()) {
+  llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
+  if (auxv_offset >= buffer.size()) {
     // We have nothing left to send.  Mark the buffer as complete.
     response.PutChar('l');
     done_with_buffer = true;
   } else {
     // Figure out how many bytes are available starting at the given offset.
-    const uint64_t bytes_remaining =
-        m_active_auxv_buffer_sp->GetByteSize() - auxv_offset;
-
-    // Figure out how many bytes we're going to read.
-    const uint64_t bytes_to_read =
-        (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
+    buffer = buffer.drop_front(auxv_offset);
 
     // Mark the response type according to whether we're reading the remainder
     // of the auxv data.
-    if (bytes_to_read >= bytes_remaining) {
+    if (auxv_length >= buffer.size()) {
       // There will be nothing left to read after this
       response.PutChar('l');
       done_with_buffer = true;
     } else {
       // There will still be bytes to read after this request.
       response.PutChar('m');
+      buffer = buffer.take_front(auxv_length);
     }
 
     // Now write the data in encoded binary form.
-    response.PutEscapedBytes(m_active_auxv_buffer_sp->GetBytes() + auxv_offset,
-                             bytes_to_read);
+    response.PutEscapedBytes(buffer.data(), buffer.size());
   }
 
   if (done_with_buffer)
-    m_active_auxv_buffer_sp.reset();
+    m_active_auxv_buffer_up.reset();
 
   return SendPacketNoLock(response.GetString());
 #else
@@ -3216,20 +3205,10 @@
 }
 
 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
-  Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | GDBR_LOG_PROCESS));
-  if (log)
-    log->Printf("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
+  Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
 
-// Clear any auxv cached data.
-// *BSD impls should be able to do this too.
-#if defined(__linux__)
-  if (log)
-    log->Printf("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer "
-                "(previously %s)",
-                __FUNCTION__,
-                m_active_auxv_buffer_sp ? "was set" : "was not set");
-  m_active_auxv_buffer_sp.reset();
-#endif
+  LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
+  m_active_auxv_buffer_up.reset();
 }
 
 FileSpec
diff --git a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h
index e255b4c..a47927e 100644
--- a/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h
+++ b/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h
@@ -117,7 +117,7 @@
   MainLoop::ReadHandleUP m_stdio_handle_up;
 
   lldb::StateType m_inferior_prev_state;
-  lldb::DataBufferSP m_active_auxv_buffer_sp;
+  std::unique_ptr<llvm::MemoryBuffer> m_active_auxv_buffer_up;
   std::mutex m_saved_registers_mutex;
   std::unordered_map<uint32_t, lldb::DataBufferSP> m_saved_registers_map;
   uint32_t m_next_saved_registers_id;