linux: Identify requesting threads

When a crashing process is in a different PID namespace than the
handler, the crasher doesn't have a way of knowing its own thread ID in
the handler's namespace and the kernel lacks mechanisms to perform this
translation before Linux 4.1 (where the information is present in
/proc/<pid>/status:NSPid).

This patch gives the handler a way of identifying the requesting thread
by sending a stack address along with the crash dump request, which
the handler can search for in each of the process' threads.

This information is useful both for attaching exception information
to the right thread and to allow the handler to send signals to the
correct thread when using a shared socket connection.

Bug: crashpad:284, crashpad:286
Change-Id: I4fa366c8fb17f932b056265cf71a4af160ba342f
Reviewed-on: https://chromium-review.googlesource.com/c/crashpad/crashpad/+/1558828
Commit-Queue: Joshua Peraza <jperaza@chromium.org>
Reviewed-by: Mark Mentovai <mark@chromium.org>
diff --git a/handler/linux/crash_report_exception_handler.cc b/handler/linux/crash_report_exception_handler.cc
index 910b288..5401baf 100644
--- a/handler/linux/crash_report_exception_handler.cc
+++ b/handler/linux/crash_report_exception_handler.cc
@@ -43,9 +43,12 @@
 
 CrashReportExceptionHandler::~CrashReportExceptionHandler() = default;
 
-bool CrashReportExceptionHandler::HandleException(pid_t client_process_id,
-                                                  const ClientInformation& info,
-                                                  UUID* local_report_id) {
+bool CrashReportExceptionHandler::HandleException(
+    pid_t client_process_id,
+    const ClientInformation& info,
+    VMAddress requesting_thread_stack_address,
+    pid_t* requesting_thread_id,
+    UUID* local_report_id) {
   Metrics::ExceptionEncountered();
 
   DirectPtraceConnection connection;
@@ -55,7 +58,11 @@
     return false;
   }
 
-  return HandleExceptionWithConnection(&connection, info, local_report_id);
+  return HandleExceptionWithConnection(&connection,
+                                       info,
+                                       requesting_thread_stack_address,
+                                       requesting_thread_id,
+                                       local_report_id);
 }
 
 bool CrashReportExceptionHandler::HandleExceptionWithBroker(
@@ -72,12 +79,15 @@
     return false;
   }
 
-  return HandleExceptionWithConnection(&client, info, local_report_id);
+  return HandleExceptionWithConnection(
+      &client, info, 0, nullptr, local_report_id);
 }
 
 bool CrashReportExceptionHandler::HandleExceptionWithConnection(
     PtraceConnection* connection,
     const ClientInformation& info,
+    VMAddress requesting_thread_stack_address,
+    pid_t* requesting_thread_id,
     UUID* local_report_id) {
   ProcessSnapshotLinux process_snapshot;
   if (!process_snapshot.Initialize(connection)) {
@@ -85,6 +95,11 @@
     return false;
   }
 
+  if (requesting_thread_id && requesting_thread_stack_address) {
+    *requesting_thread_id = process_snapshot.FindThreadWithStackAddress(
+        requesting_thread_stack_address);
+  }
+
   if (!process_snapshot.InitializeException(
           info.exception_information_address)) {
     Metrics::ExceptionCaptureResult(
diff --git a/handler/linux/crash_report_exception_handler.h b/handler/linux/crash_report_exception_handler.h
index 9951d84..1805165 100644
--- a/handler/linux/crash_report_exception_handler.h
+++ b/handler/linux/crash_report_exception_handler.h
@@ -66,6 +66,8 @@
 
   bool HandleException(pid_t client_process_id,
                        const ClientInformation& info,
+                       VMAddress requesting_thread_stack_address = 0,
+                       pid_t* requesting_thread_id = nullptr,
                        UUID* local_report_id = nullptr) override;
 
   bool HandleExceptionWithBroker(pid_t client_process_id,
@@ -76,6 +78,8 @@
  private:
   bool HandleExceptionWithConnection(PtraceConnection* connection,
                                      const ClientInformation& info,
+                                     VMAddress requesting_thread_stack_address,
+                                     pid_t* requesting_thread_id,
                                      UUID* local_report_id = nullptr);
 
   CrashReportDatabase* database_;  // weak
diff --git a/handler/linux/exception_handler_server.cc b/handler/linux/exception_handler_server.cc
index 12e7363..c284212 100644
--- a/handler/linux/exception_handler_server.cc
+++ b/handler/linux/exception_handler_server.cc
@@ -414,8 +414,10 @@
 
   switch (client_msg->type) {
     case ClientToServerMessage::kCrashDumpRequest:
-      return HandleCrashDumpRequest(
-          msg, client_msg->client_info, event->fd.get());
+      return HandleCrashDumpRequest(msg,
+                                    client_msg->client_info,
+                                    client_msg->requesting_thread_stack_address,
+                                    event->fd.get());
   }
 
   DCHECK(false);
@@ -426,6 +428,7 @@
 bool ExceptionHandlerServer::HandleCrashDumpRequest(
     const msghdr& msg,
     const ClientInformation& client_info,
+    VMAddress requesting_thread_stack_address,
     int client_sock) {
   cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
   if (cmsg == nullptr) {
@@ -460,7 +463,8 @@
                                  ServerToClientMessage::kTypeCrashDumpFailed);
 
     case PtraceStrategyDecider::Strategy::kDirectPtrace:
-      delegate_->HandleException(client_process_id, client_info);
+      delegate_->HandleException(
+          client_process_id, client_info, requesting_thread_stack_address);
       break;
 
     case PtraceStrategyDecider::Strategy::kUseBroker:
diff --git a/handler/linux/exception_handler_server.h b/handler/linux/exception_handler_server.h
index 239aeea..6f13fdc 100644
--- a/handler/linux/exception_handler_server.h
+++ b/handler/linux/exception_handler_server.h
@@ -73,11 +73,19 @@
     //!
     //! \param[in] client_process_id The process ID of the crashing client.
     //! \param[in] info Information on the client.
+    //! \param[in] requesting_thread_stack_address Any address within the stack
+    //!     range for the the thread that sent the crash dump request. Optional.
+    //!     If unspecified or 0, \a requesting_thread_id will be -1.
+    //! \param[out] requesting_thread_id The thread ID of the thread which
+    //!     requested the crash dump if not `nullptr`. Set to -1 if the thread
+    //!     ID could not be determined. Optional.
     //! \param[out] local_report_id The unique identifier for the report created
     //!     in the local report database. Optional.
     //! \return `true` on success. `false` on failure with a message logged.
     virtual bool HandleException(pid_t client_process_id,
                                  const ClientInformation& info,
+                                 VMAddress requesting_thread_stack_address = 0,
+                                 pid_t* requesting_thread_id = nullptr,
                                  UUID* local_report_id = nullptr) = 0;
 
     //! \brief Called on the receipt of a crash dump request from a client for a
@@ -141,6 +149,7 @@
   bool ReceiveClientMessage(Event* event);
   bool HandleCrashDumpRequest(const msghdr& msg,
                               const ClientInformation& client_info,
+                              VMAddress requesting_thread_stack_address,
                               int client_sock);
 
   std::unordered_map<int, std::unique_ptr<Event>> clients_;
diff --git a/handler/linux/exception_handler_server_test.cc b/handler/linux/exception_handler_server_test.cc
index 083a4ea..7d15cbb 100644
--- a/handler/linux/exception_handler_server_test.cc
+++ b/handler/linux/exception_handler_server_test.cc
@@ -19,6 +19,7 @@
 
 #include "base/logging.h"
 #include "gtest/gtest.h"
+#include "snapshot/linux/process_snapshot_linux.h"
 #include "test/errors.h"
 #include "test/multiprocess.h"
 #include "util/linux/direct_ptrace_connection.h"
@@ -103,6 +104,8 @@
 
   bool HandleException(pid_t client_process_id,
                        const ClientInformation& info,
+                       VMAddress requesting_thread_stack_address,
+                       pid_t* requesting_thread_id = nullptr,
                        UUID* local_report_id = nullptr) override {
     DirectPtraceConnection connection;
     bool connected = connection.Initialize(client_process_id);
@@ -111,7 +114,24 @@
     last_exception_address_ = info.exception_information_address;
     last_client_ = client_process_id;
     sem_.Signal();
-    return connected;
+    if (!connected) {
+      return false;
+    }
+
+    if (requesting_thread_id) {
+      if (requesting_thread_stack_address) {
+        ProcessSnapshotLinux process_snapshot;
+        if (!process_snapshot.Initialize(&connection)) {
+          ADD_FAILURE();
+          return false;
+        }
+        *requesting_thread_id = process_snapshot.FindThreadWithStackAddress(
+            requesting_thread_stack_address);
+      } else {
+        *requesting_thread_id = -1;
+      }
+    }
+    return true;
   }
 
   bool HandleExceptionWithBroker(pid_t client_process_id,
diff --git a/snapshot/linux/process_snapshot_linux.cc b/snapshot/linux/process_snapshot_linux.cc
index 4141b2f..3442e4a 100644
--- a/snapshot/linux/process_snapshot_linux.cc
+++ b/snapshot/linux/process_snapshot_linux.cc
@@ -49,6 +49,20 @@
   return true;
 }
 
+pid_t ProcessSnapshotLinux::FindThreadWithStackAddress(
+    VMAddress stack_address) {
+  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
+
+  for (const auto& thread : process_reader_.Threads()) {
+    if (stack_address >= thread.stack_region_address &&
+        stack_address <
+            thread.stack_region_address + thread.stack_region_size) {
+      return thread.tid;
+    }
+  }
+  return -1;
+}
+
 bool ProcessSnapshotLinux::InitializeException(
     LinuxVMAddress exception_info_address) {
   INITIALIZATION_STATE_DCHECK_VALID(initialized_);
diff --git a/snapshot/linux/process_snapshot_linux.h b/snapshot/linux/process_snapshot_linux.h
index 84bd226..c96384d 100644
--- a/snapshot/linux/process_snapshot_linux.h
+++ b/snapshot/linux/process_snapshot_linux.h
@@ -58,6 +58,13 @@
   //!     an appropriate message logged.
   bool Initialize(PtraceConnection* connection);
 
+  //! \brief Finds the thread whose stack contains \a stack_address.
+  //!
+  //! \param[in] stack_address A stack address to search for.
+  //! \return The thread ID of the thread whose stack contains \a stack_address
+  //!     or -1 if no matching thread is found.
+  pid_t FindThreadWithStackAddress(VMAddress stack_address);
+
   //! \brief Initializes the object's exception.
   //!
   //! \param[in] exception_info The address of an ExceptionInformation in the
diff --git a/util/linux/exception_handler_client.cc b/util/linux/exception_handler_client.cc
index 6333351..e4548d6 100644
--- a/util/linux/exception_handler_client.cc
+++ b/util/linux/exception_handler_client.cc
@@ -25,6 +25,7 @@
 #include "build/build_config.h"
 #include "util/file/file_io.h"
 #include "util/linux/ptrace_broker.h"
+#include "util/misc/from_pointer_cast.h"
 #include "util/posix/signals.h"
 
 namespace crashpad {
@@ -35,7 +36,9 @@
 ExceptionHandlerClient::~ExceptionHandlerClient() = default;
 
 int ExceptionHandlerClient::RequestCrashDump(const ClientInformation& info) {
-  int status = SendCrashDumpRequest(info);
+  VMAddress sp = FromPointerCast<VMAddress>(&sp);
+
+  int status = SendCrashDumpRequest(info, sp);
   if (status != 0) {
     return status;
   }
@@ -61,10 +64,11 @@
   can_set_ptracer_ = can_set_ptracer;
 }
 
-int ExceptionHandlerClient::SendCrashDumpRequest(
-    const ClientInformation& info) {
+int ExceptionHandlerClient::SendCrashDumpRequest(const ClientInformation& info,
+                                                 VMAddress stack_pointer) {
   ClientToServerMessage message;
   message.type = ClientToServerMessage::kCrashDumpRequest;
+  message.requesting_thread_stack_address = stack_pointer;
   message.client_info = info;
 
   iovec iov;
diff --git a/util/linux/exception_handler_client.h b/util/linux/exception_handler_client.h
index a60b065..25a8a44 100644
--- a/util/linux/exception_handler_client.h
+++ b/util/linux/exception_handler_client.h
@@ -53,7 +53,8 @@
   void SetCanSetPtracer(bool can_set_ptracer);
 
  private:
-  int SendCrashDumpRequest(const ClientInformation& info);
+  int SendCrashDumpRequest(const ClientInformation& info,
+                           VMAddress stack_pointer);
   int WaitForCrashDumpComplete();
 
   int server_sock_;
diff --git a/util/linux/exception_handler_protocol.h b/util/linux/exception_handler_protocol.h
index 4ba1b5d..0ab3ffd 100644
--- a/util/linux/exception_handler_protocol.h
+++ b/util/linux/exception_handler_protocol.h
@@ -57,6 +57,9 @@
   //! \brief Indicates what message version is being used.
   int32_t version;
 
+  //! \brief A stack address of the thread sending the message.
+  VMAddress requesting_thread_stack_address;
+
   enum Type : uint32_t {
     //! \brief Used to request a crash dump for the sending client.
     kCrashDumpRequest