Add signal handling to the register object.

- Add the StepIfSignalHandler function to the Regs object that checks
  if the code is in a signal handler.
- Add tests for new code, also add a test that unwinds through a signal
  handler.
- Slight modification to Elf to fail if a bad machine type is encountered.
  Add tests for this.

Bug: 23762183

Test: Ran unit tests.
Change-Id: Idafa1105d00b91a9343d7464ac9ed1cb95830963
diff --git a/libunwindstack/tests/ElfTest.cpp b/libunwindstack/tests/ElfTest.cpp
index 72ceb85..ed1be3b 100644
--- a/libunwindstack/tests/ElfTest.cpp
+++ b/libunwindstack/tests/ElfTest.cpp
@@ -26,6 +26,7 @@
 #include <unwindstack/MapInfo.h>
 
 #include "ElfTestUtils.h"
+#include "LogFake.h"
 #include "MemoryFake.h"
 
 #if !defined(PT_ARM_EXIDX)
@@ -131,6 +132,32 @@
   ASSERT_FALSE(elf.Step(0, nullptr, nullptr));
 }
 
+TEST_F(ElfTest, elf32_invalid_machine) {
+  Elf elf(memory_);
+
+  InitElf32(EM_PPC);
+
+  ResetLogs();
+  ASSERT_FALSE(elf.Init());
+
+  ASSERT_EQ("", GetFakeLogBuf());
+  ASSERT_EQ("4 unwind 32 bit elf that is neither arm nor x86: e_machine = 20\n\n",
+            GetFakeLogPrint());
+}
+
+TEST_F(ElfTest, elf64_invalid_machine) {
+  Elf elf(memory_);
+
+  InitElf64(EM_PPC64);
+
+  ResetLogs();
+  ASSERT_FALSE(elf.Init());
+
+  ASSERT_EQ("", GetFakeLogBuf());
+  ASSERT_EQ("4 unwind 64 bit elf that is neither aarch64 nor x86_64: e_machine = 21\n\n",
+            GetFakeLogPrint());
+}
+
 TEST_F(ElfTest, elf_arm) {
   Elf elf(memory_);
 
diff --git a/libunwindstack/tests/RegsFake.h b/libunwindstack/tests/RegsFake.h
index e796c9b..f998da7 100644
--- a/libunwindstack/tests/RegsFake.h
+++ b/libunwindstack/tests/RegsFake.h
@@ -33,6 +33,7 @@
 
   uint64_t GetAdjustedPc(uint64_t, Elf*) override { return 0; }
   void SetFromRaw() override {}
+  bool StepIfSignalHandler(Memory*) override { return false; }
   bool GetReturnAddressFromDefault(Memory*, uint64_t*) { return false; }
 };
 
diff --git a/libunwindstack/tests/RegsTest.cpp b/libunwindstack/tests/RegsTest.cpp
index 3613689..9622166 100644
--- a/libunwindstack/tests/RegsTest.cpp
+++ b/libunwindstack/tests/RegsTest.cpp
@@ -23,6 +23,8 @@
 #include <unwindstack/MapInfo.h>
 #include <unwindstack/Regs.h>
 
+#include "Machine.h"
+
 #include "MemoryFake.h"
 
 namespace unwindstack {
@@ -60,6 +62,7 @@
 
   uint64_t GetAdjustedPc(uint64_t, Elf*) override { return 0; }
   void SetFromRaw() override {}
+  bool StepIfSignalHandler(Memory*) override { return false; }
 };
 
 class RegsTest : public ::testing::Test {
@@ -72,7 +75,10 @@
   }
 
   template <typename AddressType>
-  void regs_return_address_register();
+  void RegsReturnAddressRegister();
+
+  void ArmStepIfSignalHandlerNonRt(uint32_t pc_data);
+  void ArmStepIfSignalHandlerRt(uint32_t pc_data);
 
   ElfInterfaceFake* elf_interface_;
   MemoryFake* memory_;
@@ -126,7 +132,7 @@
 }
 
 template <typename AddressType>
-void RegsTest::regs_return_address_register() {
+void RegsTest::RegsReturnAddressRegister() {
   RegsTestImpl<AddressType> regs(20, 10, Regs::Location(Regs::LOCATION_REGISTER, 5));
 
   regs[5] = 0x12345;
@@ -136,11 +142,11 @@
 }
 
 TEST_F(RegsTest, regs32_return_address_register) {
-  regs_return_address_register<uint32_t>();
+  RegsReturnAddressRegister<uint32_t>();
 }
 
 TEST_F(RegsTest, regs64_return_address_register) {
-  regs_return_address_register<uint64_t>();
+  RegsReturnAddressRegister<uint64_t>();
 }
 
 TEST_F(RegsTest, regs32_return_address_sp_offset) {
@@ -285,4 +291,160 @@
   EXPECT_EQ(0x4900000000U, x86_64.pc());
 }
 
+void RegsTest::ArmStepIfSignalHandlerNonRt(uint32_t pc_data) {
+  uint64_t addr = 0x1000;
+  RegsArm regs;
+  regs[ARM_REG_PC] = 0x5000;
+  regs[ARM_REG_SP] = addr;
+  regs.SetFromRaw();
+
+  memory_->SetData32(0x5000, pc_data);
+
+  for (uint64_t index = 0; index <= 30; index++) {
+    memory_->SetData32(addr + index * 4, index * 0x10);
+  }
+
+  ASSERT_TRUE(regs.StepIfSignalHandler(memory_));
+  EXPECT_EQ(0x100U, regs[ARM_REG_SP]);
+  EXPECT_EQ(0x120U, regs[ARM_REG_PC]);
+  EXPECT_EQ(0x100U, regs.sp());
+  EXPECT_EQ(0x120U, regs.pc());
+}
+
+TEST_F(RegsTest, arm_step_if_signal_handler_non_rt) {
+  // Form 1
+  ArmStepIfSignalHandlerNonRt(0xe3a07077);
+
+  // Form 2
+  ArmStepIfSignalHandlerNonRt(0xef900077);
+
+  // Form 3
+  ArmStepIfSignalHandlerNonRt(0xdf002777);
+}
+
+void RegsTest::ArmStepIfSignalHandlerRt(uint32_t pc_data) {
+  uint64_t addr = 0x1000;
+  RegsArm regs;
+  regs[ARM_REG_PC] = 0x5000;
+  regs[ARM_REG_SP] = addr;
+  regs.SetFromRaw();
+
+  memory_->SetData32(0x5000, pc_data);
+
+  for (uint64_t index = 0; index <= 100; index++) {
+    memory_->SetData32(addr + index * 4, index * 0x10);
+  }
+
+  ASSERT_TRUE(regs.StepIfSignalHandler(memory_));
+  EXPECT_EQ(0x350U, regs[ARM_REG_SP]);
+  EXPECT_EQ(0x370U, regs[ARM_REG_PC]);
+  EXPECT_EQ(0x350U, regs.sp());
+  EXPECT_EQ(0x370U, regs.pc());
+}
+
+TEST_F(RegsTest, arm_step_if_signal_handler_rt) {
+  // Form 1
+  ArmStepIfSignalHandlerRt(0xe3a070ad);
+
+  // Form 2
+  ArmStepIfSignalHandlerRt(0xef9000ad);
+
+  // Form 3
+  ArmStepIfSignalHandlerRt(0xdf0027ad);
+}
+
+TEST_F(RegsTest, arm64_step_if_signal_handler) {
+  uint64_t addr = 0x1000;
+  RegsArm64 regs;
+  regs[ARM64_REG_PC] = 0x8000;
+  regs[ARM64_REG_SP] = addr;
+  regs.SetFromRaw();
+
+  memory_->SetData64(0x8000, 0xd4000001d2801168ULL);
+
+  for (uint64_t index = 0; index <= 100; index++) {
+    memory_->SetData64(addr + index * 8, index * 0x10);
+  }
+
+  ASSERT_TRUE(regs.StepIfSignalHandler(memory_));
+  EXPECT_EQ(0x460U, regs[ARM64_REG_SP]);
+  EXPECT_EQ(0x470U, regs[ARM64_REG_PC]);
+  EXPECT_EQ(0x460U, regs.sp());
+  EXPECT_EQ(0x470U, regs.pc());
+}
+
+TEST_F(RegsTest, x86_step_if_signal_handler_no_siginfo) {
+  uint64_t addr = 0xa00;
+  RegsX86 regs;
+  regs[X86_REG_EIP] = 0x4100;
+  regs[X86_REG_ESP] = addr;
+  regs.SetFromRaw();
+
+  memory_->SetData64(0x4100, 0x80cd00000077b858ULL);
+  for (uint64_t index = 0; index <= 25; index++) {
+    memory_->SetData32(addr + index * 4, index * 0x10);
+  }
+
+  ASSERT_TRUE(regs.StepIfSignalHandler(memory_));
+  EXPECT_EQ(0x70U, regs[X86_REG_EBP]);
+  EXPECT_EQ(0x80U, regs[X86_REG_ESP]);
+  EXPECT_EQ(0x90U, regs[X86_REG_EBX]);
+  EXPECT_EQ(0xa0U, regs[X86_REG_EDX]);
+  EXPECT_EQ(0xb0U, regs[X86_REG_ECX]);
+  EXPECT_EQ(0xc0U, regs[X86_REG_EAX]);
+  EXPECT_EQ(0xf0U, regs[X86_REG_EIP]);
+  EXPECT_EQ(0x80U, regs.sp());
+  EXPECT_EQ(0xf0U, regs.pc());
+}
+
+TEST_F(RegsTest, x86_step_if_signal_handler_siginfo) {
+  uint64_t addr = 0xa00;
+  RegsX86 regs;
+  regs[X86_REG_EIP] = 0x4100;
+  regs[X86_REG_ESP] = addr;
+  regs.SetFromRaw();
+
+  memory_->SetData64(0x4100, 0x0080cd000000adb8ULL);
+  addr += 8;
+  // Pointer to ucontext data.
+  memory_->SetData32(addr, 0x8100);
+
+  addr = 0x8100;
+  for (uint64_t index = 0; index <= 30; index++) {
+    memory_->SetData32(addr + index * 4, index * 0x10);
+  }
+
+  ASSERT_TRUE(regs.StepIfSignalHandler(memory_));
+  EXPECT_EQ(0xb0U, regs[X86_REG_EBP]);
+  EXPECT_EQ(0xc0U, regs[X86_REG_ESP]);
+  EXPECT_EQ(0xd0U, regs[X86_REG_EBX]);
+  EXPECT_EQ(0xe0U, regs[X86_REG_EDX]);
+  EXPECT_EQ(0xf0U, regs[X86_REG_ECX]);
+  EXPECT_EQ(0x100U, regs[X86_REG_EAX]);
+  EXPECT_EQ(0x130U, regs[X86_REG_EIP]);
+  EXPECT_EQ(0xc0U, regs.sp());
+  EXPECT_EQ(0x130U, regs.pc());
+}
+
+TEST_F(RegsTest, x86_64_step_if_signal_handler) {
+  uint64_t addr = 0x500;
+  RegsX86_64 regs;
+  regs[X86_64_REG_RIP] = 0x7000;
+  regs[X86_64_REG_RSP] = addr;
+  regs.SetFromRaw();
+
+  memory_->SetData64(0x7000, 0x0f0000000fc0c748);
+  memory_->SetData16(0x7008, 0x0f05);
+
+  for (uint64_t index = 0; index <= 30; index++) {
+    memory_->SetData64(addr + index * 8, index * 0x10);
+  }
+
+  ASSERT_TRUE(regs.StepIfSignalHandler(memory_));
+  EXPECT_EQ(0x140U, regs[X86_64_REG_RSP]);
+  EXPECT_EQ(0x150U, regs[X86_64_REG_RIP]);
+  EXPECT_EQ(0x140U, regs.sp());
+  EXPECT_EQ(0x150U, regs.pc());
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/UnwindTest.cpp b/libunwindstack/tests/UnwindTest.cpp
index 72065c9..3c69e2a 100644
--- a/libunwindstack/tests/UnwindTest.cpp
+++ b/libunwindstack/tests/UnwindTest.cpp
@@ -30,6 +30,7 @@
 #include <sstream>
 #include <string>
 #include <thread>
+#include <vector>
 
 #include <unwindstack/Elf.h>
 #include <unwindstack/MapInfo.h>
@@ -42,16 +43,41 @@
 
 static std::atomic_bool g_ready(false);
 static volatile bool g_ready_for_remote = false;
+static volatile bool g_signal_ready_for_remote = false;
 static std::atomic_bool g_finish(false);
 static std::atomic_uintptr_t g_ucontext;
 
-static void Signal(int, siginfo_t*, void* sigcontext) {
+static std::vector<const char*> kFunctionOrder{"InnerFunction", "MiddleFunction", "OuterFunction"};
+
+static std::vector<const char*> kFunctionSignalOrder{"SignalInnerFunction", "SignalMiddleFunction",
+                                                     "SignalOuterFunction", "InnerFunction",
+                                                     "MiddleFunction",      "OuterFunction"};
+
+static void SignalHandler(int, siginfo_t*, void* sigcontext) {
   g_ucontext = reinterpret_cast<uintptr_t>(sigcontext);
   while (!g_finish.load()) {
   }
 }
 
-static std::string ErrorMsg(const char** function_names, size_t index,
+extern "C" void SignalInnerFunction() {
+  g_signal_ready_for_remote = true;
+  while (!g_finish.load()) {
+  }
+}
+
+extern "C" void SignalMiddleFunction() {
+  SignalInnerFunction();
+}
+
+extern "C" void SignalOuterFunction() {
+  SignalMiddleFunction();
+}
+
+static void SignalCallerHandler(int, siginfo_t*, void*) {
+  SignalOuterFunction();
+}
+
+static std::string ErrorMsg(const std::vector<const char*>& function_names, size_t index,
                             std::stringstream& unwind_stream) {
   return std::string(
              "Unwind completed without finding all frames\n"
@@ -59,10 +85,8 @@
          function_names[index] + "\n" + "Unwind data:\n" + unwind_stream.str();
 }
 
-static void VerifyUnwind(pid_t pid, Memory* memory, Maps* maps, Regs* regs) {
-  const char* function_names[] = {
-      "InnerFunction", "MiddleFunction", "OuterFunction",
-  };
+static void VerifyUnwind(pid_t pid, Memory* memory, Maps* maps, Regs* regs,
+                         std::vector<const char*>& function_names) {
   size_t function_name_index = 0;
 
   std::stringstream unwind_stream;
@@ -91,8 +115,7 @@
     uint64_t func_offset;
     if (elf->GetFunctionName(adjusted_rel_pc, &name, &func_offset)) {
       if (name == function_names[function_name_index]) {
-        function_name_index++;
-        if (function_name_index == sizeof(function_names) / sizeof(const char*)) {
+        if (++function_name_index == function_names.size()) {
           return;
         }
       }
@@ -116,7 +139,7 @@
     RegsGetLocal(regs.get());
     MemoryLocal memory;
 
-    VerifyUnwind(getpid(), &memory, &maps, regs.get());
+    VerifyUnwind(getpid(), &memory, &maps, regs.get(), kFunctionOrder);
   } else {
     g_ready_for_remote = true;
     g_ready = true;
@@ -137,6 +160,37 @@
   OuterFunction(true);
 }
 
+void WaitForRemote(pid_t pid, uint64_t addr, bool leave_attached, bool* completed) {
+  *completed = false;
+  // Need to sleep before attempting first ptrace. Without this, on the
+  // host it becomes impossible to attach and ptrace set errno to EPERM.
+  usleep(1000);
+  for (size_t i = 0; i < 100; i++) {
+    ASSERT_EQ(0, ptrace(PTRACE_ATTACH, pid, 0, 0));
+    for (size_t j = 0; j < 100; j++) {
+      siginfo_t si;
+      if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
+        MemoryRemote memory(pid);
+        // Read the remote value to see if we are ready.
+        bool value;
+        if (memory.Read(addr, &value, sizeof(value)) && value) {
+          *completed = true;
+          break;
+        }
+      }
+      usleep(1000);
+    }
+    if (leave_attached && *completed) {
+      break;
+    }
+    ASSERT_EQ(0, ptrace(PTRACE_DETACH, pid, 0, 0));
+    if (*completed) {
+      break;
+    }
+    usleep(1000);
+  }
+}
+
 TEST(UnwindTest, remote) {
   pid_t pid;
   if ((pid = fork()) == 0) {
@@ -145,31 +199,9 @@
   }
   ASSERT_NE(-1, pid);
 
-  bool ready = false;
-  uint64_t addr = reinterpret_cast<uint64_t>(&g_ready_for_remote);
-  for (size_t i = 0; i < 100; i++) {
-    ASSERT_EQ(0, ptrace(PTRACE_ATTACH, pid, 0, 0));
-    for (size_t j = 0; j < 100; j++) {
-      siginfo_t si;
-      if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
-        // Check to see if process is ready to be unwound.
-        MemoryRemote memory(pid);
-        // Read the remote value to see if we are ready.
-        bool value;
-        if (memory.Read(addr, &value, sizeof(value)) && value) {
-          ready = true;
-          break;
-        }
-      }
-      usleep(1000);
-    }
-    if (ready) {
-      break;
-    }
-    ASSERT_EQ(0, ptrace(PTRACE_DETACH, pid, 0, 0));
-    usleep(1000);
-  }
-  ASSERT_TRUE(read) << "Timed out waiting for remote process to be ready.";
+  bool completed;
+  WaitForRemote(pid, reinterpret_cast<uint64_t>(&g_ready_for_remote), true, &completed);
+  ASSERT_TRUE(completed) << "Timed out waiting for remote process to be ready.";
 
   RemoteMaps maps(pid);
   ASSERT_TRUE(maps.Parse());
@@ -178,7 +210,7 @@
   std::unique_ptr<Regs> regs(Regs::RemoteGet(pid, &machine_type));
   ASSERT_TRUE(regs.get() != nullptr);
 
-  VerifyUnwind(pid, &memory, &maps, regs.get());
+  VerifyUnwind(pid, &memory, &maps, regs.get(), kFunctionOrder);
 
   ASSERT_EQ(0, ptrace(PTRACE_DETACH, pid, 0, 0));
 
@@ -195,7 +227,7 @@
 
   struct sigaction act, oldact;
   memset(&act, 0, sizeof(act));
-  act.sa_sigaction = Signal;
+  act.sa_sigaction = SignalHandler;
   act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
   ASSERT_EQ(0, sigaction(SIGUSR1, &act, &oldact));
   // Wait for the tid to get set.
@@ -207,8 +239,7 @@
   }
   ASSERT_NE(0, tid.load());
   // Portable tgkill method.
-  ASSERT_EQ(0, syscall(__NR_tgkill, getpid(), tid.load(), SIGUSR1)) << "Failed because "
-                                                                    << strerror(errno);
+  ASSERT_EQ(0, syscall(__NR_tgkill, getpid(), tid.load(), SIGUSR1)) << "Error: " << strerror(errno);
 
   // Wait for context data.
   void* ucontext;
@@ -226,7 +257,7 @@
   std::unique_ptr<Regs> regs(Regs::CreateFromUcontext(Regs::GetMachineType(), ucontext));
   MemoryLocal memory;
 
-  VerifyUnwind(tid.load(), &memory, &maps, regs.get());
+  VerifyUnwind(tid.load(), &memory, &maps, regs.get(), kFunctionOrder);
 
   ASSERT_EQ(0, sigaction(SIGUSR1, &oldact, nullptr));
 
@@ -234,4 +265,52 @@
   thread.join();
 }
 
+static void RemoteThroughSignal(unsigned int sa_flags) {
+  g_ready = false;
+  g_signal_ready_for_remote = false;
+  g_finish = false;
+
+  pid_t pid;
+  if ((pid = fork()) == 0) {
+    struct sigaction act, oldact;
+    memset(&act, 0, sizeof(act));
+    act.sa_sigaction = SignalCallerHandler;
+    act.sa_flags = SA_RESTART | SA_ONSTACK | sa_flags;
+    ASSERT_EQ(0, sigaction(SIGUSR1, &act, &oldact));
+
+    OuterFunction(false);
+    exit(0);
+  }
+  ASSERT_NE(-1, pid);
+
+  bool completed;
+  WaitForRemote(pid, reinterpret_cast<uint64_t>(&g_ready_for_remote), false, &completed);
+  ASSERT_TRUE(completed) << "Timed out waiting for remote process to be ready.";
+  ASSERT_EQ(0, kill(pid, SIGUSR1));
+  WaitForRemote(pid, reinterpret_cast<uint64_t>(&g_signal_ready_for_remote), true, &completed);
+  ASSERT_TRUE(completed) << "Timed out waiting for remote process to be in signal handler.";
+
+  RemoteMaps maps(pid);
+  ASSERT_TRUE(maps.Parse());
+  MemoryRemote memory(pid);
+  uint32_t machine_type;
+  std::unique_ptr<Regs> regs(Regs::RemoteGet(pid, &machine_type));
+  ASSERT_TRUE(regs.get() != nullptr);
+
+  VerifyUnwind(pid, &memory, &maps, regs.get(), kFunctionSignalOrder);
+
+  ASSERT_EQ(0, ptrace(PTRACE_DETACH, pid, 0, 0));
+
+  kill(pid, SIGKILL);
+  ASSERT_EQ(pid, wait(nullptr));
+}
+
+TEST(UnwindTest, remote_through_signal) {
+  RemoteThroughSignal(0);
+}
+
+TEST(UnwindTest, remote_through_signal_sa_siginfo) {
+  RemoteThroughSignal(SA_SIGINFO);
+}
+
 }  // namespace unwindstack