summaryrefslogtreecommitdiff
path: root/libunwindstack/tests/AndroidUnwinderTest.cpp
blob: 8017123b443973a3a791ddbb1cb935abfeebed3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <dlfcn.h>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include <gtest/gtest.h>

#include <atomic>
#include <string>
#include <thread>
#include <vector>

#include <android-base/strings.h>
#include <android-base/test_utils.h>
#include <android-base/threads.h>

#include <unwindstack/AndroidUnwinder.h>
#include <unwindstack/Error.h>
#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineRiscv64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsGetLocal.h>
#include <unwindstack/RegsRiscv64.h>
#include <unwindstack/RegsX86.h>
#include <unwindstack/RegsX86_64.h>
#include <unwindstack/UcontextArm.h>
#include <unwindstack/UcontextArm64.h>
#include <unwindstack/UcontextRiscv64.h>
#include <unwindstack/UcontextX86.h>
#include <unwindstack/UcontextX86_64.h>
#include <unwindstack/Unwinder.h>

#include "ForkTest.h"
#include "PidUtils.h"
#include "TestUtils.h"

namespace unwindstack {

static std::string GetBacktrace(AndroidUnwinder& unwinder, std::vector<FrameData>& frames) {
  std::string backtrace_str;
  for (auto& frame : frames) {
    backtrace_str += unwinder.FormatFrame(frame) + '\n';
  }
  return backtrace_str;
}

TEST(AndroidUnwinderDataTest, demangle_function_names) {
  AndroidUnwinderData data;

  // Add a few frames with and without demangled function names.
  data.frames.resize(4);
  data.frames[0].function_name = "no_demangle()";
  data.frames[1].function_name = "_Z4fakeb";
  data.frames[3].function_name = "_Z8demanglei";

  data.DemangleFunctionNames();
  EXPECT_EQ("no_demangle()", data.frames[0].function_name);
  EXPECT_EQ("fake(bool)", data.frames[1].function_name);
  EXPECT_EQ("", data.frames[2].function_name);
  EXPECT_EQ("demangle(int)", data.frames[3].function_name);

  // Make sure that this action is idempotent.
  data.DemangleFunctionNames();
  EXPECT_EQ("no_demangle()", data.frames[0].function_name);
  EXPECT_EQ("fake(bool)", data.frames[1].function_name);
  EXPECT_EQ("", data.frames[2].function_name);
  EXPECT_EQ("demangle(int)", data.frames[3].function_name);
}

TEST(AndroidUnwinderDataTest, get_error_string) {
  AndroidUnwinderData data;

  EXPECT_EQ("None", data.GetErrorString());
  data.error.code = ERROR_INVALID_ELF;
  EXPECT_EQ("Invalid Elf", data.GetErrorString());
  data.error.code = ERROR_MEMORY_INVALID;
  EXPECT_EQ("Memory Invalid", data.GetErrorString());
  data.error.address = 0x1000;
  EXPECT_EQ("Memory Invalid at address 0x1000", data.GetErrorString());
}

using AndroidUnwinderTest = ForkTest;

TEST_F(AndroidUnwinderTest, unwind_errors) {
  AndroidLocalUnwinder unwinder;

  AndroidUnwinderData data;
  void* ucontext = nullptr;
  EXPECT_FALSE(unwinder.Unwind(ucontext, data));
  EXPECT_EQ(ERROR_INVALID_PARAMETER, data.error.code);
  std::unique_ptr<Regs> regs;
  EXPECT_FALSE(unwinder.Unwind(regs.get(), data));
  EXPECT_EQ(ERROR_INVALID_PARAMETER, data.error.code);
  // Make sure that we are using a different arch from the
  // current arch.
  if (Regs::CurrentArch() == ARCH_ARM) {
    regs.reset(new RegsArm64);
  } else {
    regs.reset(new RegsArm);
  }
  EXPECT_FALSE(unwinder.Unwind(regs.get(), data));
  EXPECT_EQ(ERROR_BAD_ARCH, data.error.code);
}

TEST_F(AndroidUnwinderTest, create) {
  // Verify the local unwinder object is created.
  std::unique_ptr<AndroidUnwinder> unwinder(AndroidUnwinder::Create(getpid()));
  AndroidUnwinderData data;
  ASSERT_TRUE(unwinder->Unwind(data));

  ForkAndWaitForPidState([this, &unwinder]() {
    // Verify the remote unwinder object is created.
    unwinder.reset(AndroidUnwinder::Create(pid_));
    AndroidUnwinderData data;
    if (!unwinder->Unwind(data)) {
      printf("Failed to unwind %s\n", data.GetErrorString().c_str());
      return PID_RUN_FAIL;
    }
    return PID_RUN_PASS;
  });
}

TEST_F(AndroidUnwinderTest, initialize_fails) {
  AndroidLocalUnwinder unwinder;

  // Induce a failure in the initialize function by grabbing every
  // fd available.
  std::vector<android::base::unique_fd> fds;
  while (true) {
    auto fd = android::base::unique_fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY)));
    if (fd == -1) {
      break;
    }
    fds.emplace_back(std::move(fd));
  }

  ErrorData error;
  ASSERT_FALSE(unwinder.Initialize(error));

  // Make sure there is no crash when trying to unwind.
  AndroidUnwinderData data;
  ASSERT_FALSE(unwinder.Unwind(data));
}

TEST(AndroidLocalUnwinderTest, initialize_before) {
  AndroidLocalUnwinder unwinder;
  ErrorData error;
  ASSERT_TRUE(unwinder.Initialize(error));

  AndroidUnwinderData data;
  ASSERT_TRUE(unwinder.Unwind(data));
}

TEST(AndroidLocalUnwinderTest, suffix_ignore) {
  AndroidLocalUnwinder unwinder(std::vector<std::string>{}, std::vector<std::string>{"so"});
  AndroidUnwinderData data;
  // This should work as long as the first frame is in the test executable.
  ASSERT_TRUE(unwinder.Unwind(data));
  // Make sure the unwind doesn't include any .so frames.
  for (const auto& frame : data.frames) {
    ASSERT_TRUE(frame.map_info == nullptr ||
                !android::base::EndsWith(frame.map_info->name(), ".so"))
        << GetBacktrace(unwinder, data.frames);
  }
}

TEST_F(AndroidUnwinderTest, verify_all_unwind_functions) {
  // Do not reuse the unwinder object to verify initialization is done
  // correctly.
  AndroidUnwinderData data;
  {
    AndroidLocalUnwinder unwinder;
    ASSERT_TRUE(unwinder.Unwind(data));
  }
  {
    AndroidLocalUnwinder unwinder;
    ASSERT_TRUE(unwinder.Unwind(std::nullopt, data));
  }
  {
    AndroidLocalUnwinder unwinder;
    ASSERT_TRUE(unwinder.Unwind(getpid(), data));
  }

  std::unique_ptr<Regs> regs(Regs::CreateFromLocal());
  RegsGetLocal(regs.get());
  void* ucontext;
  switch (regs->Arch()) {
    case ARCH_ARM: {
      arm_ucontext_t* arm_ucontext =
          reinterpret_cast<arm_ucontext_t*>(malloc(sizeof(arm_ucontext_t)));
      ucontext = arm_ucontext;
      memcpy(&arm_ucontext->uc_mcontext.regs[0], regs->RawData(), ARM_REG_LAST * sizeof(uint32_t));
    } break;
    case ARCH_ARM64: {
      arm64_ucontext_t* arm64_ucontext =
          reinterpret_cast<arm64_ucontext_t*>(malloc(sizeof(arm64_ucontext_t)));
      ucontext = arm64_ucontext;
      memcpy(&arm64_ucontext->uc_mcontext.regs[0], regs->RawData(),
             ARM64_REG_LAST * sizeof(uint64_t));
    } break;
    case ARCH_X86: {
      x86_ucontext_t* x86_ucontext =
          reinterpret_cast<x86_ucontext_t*>(malloc(sizeof(x86_ucontext_t)));
      ucontext = x86_ucontext;
      RegsX86* regs_x86 = static_cast<RegsX86*>(regs.get());

      x86_ucontext->uc_mcontext.edi = (*regs_x86)[X86_REG_EDI];
      x86_ucontext->uc_mcontext.esi = (*regs_x86)[X86_REG_ESI];
      x86_ucontext->uc_mcontext.ebp = (*regs_x86)[X86_REG_EBP];
      x86_ucontext->uc_mcontext.esp = (*regs_x86)[X86_REG_ESP];
      x86_ucontext->uc_mcontext.ebx = (*regs_x86)[X86_REG_EBX];
      x86_ucontext->uc_mcontext.edx = (*regs_x86)[X86_REG_EDX];
      x86_ucontext->uc_mcontext.ecx = (*regs_x86)[X86_REG_ECX];
      x86_ucontext->uc_mcontext.eax = (*regs_x86)[X86_REG_EAX];
      x86_ucontext->uc_mcontext.eip = (*regs_x86)[X86_REG_EIP];
    } break;
    case ARCH_X86_64: {
      x86_64_ucontext_t* x86_64_ucontext =
          reinterpret_cast<x86_64_ucontext_t*>(malloc(sizeof(x86_64_ucontext_t)));
      ucontext = x86_64_ucontext;
      RegsX86_64* regs_x86_64 = static_cast<RegsX86_64*>(regs.get());

      memcpy(&x86_64_ucontext->uc_mcontext.r8, &(*regs_x86_64)[X86_64_REG_R8],
             8 * sizeof(uint64_t));

      x86_64_ucontext->uc_mcontext.rdi = (*regs_x86_64)[X86_64_REG_RDI];
      x86_64_ucontext->uc_mcontext.rsi = (*regs_x86_64)[X86_64_REG_RSI];
      x86_64_ucontext->uc_mcontext.rbp = (*regs_x86_64)[X86_64_REG_RBP];
      x86_64_ucontext->uc_mcontext.rbx = (*regs_x86_64)[X86_64_REG_RBX];
      x86_64_ucontext->uc_mcontext.rdx = (*regs_x86_64)[X86_64_REG_RDX];
      x86_64_ucontext->uc_mcontext.rax = (*regs_x86_64)[X86_64_REG_RAX];
      x86_64_ucontext->uc_mcontext.rcx = (*regs_x86_64)[X86_64_REG_RCX];
      x86_64_ucontext->uc_mcontext.rsp = (*regs_x86_64)[X86_64_REG_RSP];
      x86_64_ucontext->uc_mcontext.rip = (*regs_x86_64)[X86_64_REG_RIP];
    } break;
    case ARCH_RISCV64: {
      riscv64_ucontext_t* riscv64_ucontext =
          reinterpret_cast<riscv64_ucontext_t*>(malloc(sizeof(riscv64_ucontext_t)));
      ucontext = riscv64_ucontext;
      memcpy(&riscv64_ucontext->uc_mcontext.__gregs, regs->RawData(),
             RISCV64_REG_REAL_COUNT * sizeof(uint64_t));
    } break;
    default:
      ucontext = nullptr;
      break;
  }

  AndroidLocalUnwinder unwinder_with_ucontext;
  ASSERT_TRUE(ucontext != nullptr);
  ASSERT_TRUE(unwinder_with_ucontext.Unwind(ucontext, data));
  free(ucontext);

  AndroidLocalUnwinder unwinder_with_regs;
  AndroidUnwinderData reg_data;
  ASSERT_TRUE(unwinder_with_regs.Unwind(regs.get(), reg_data));
  ASSERT_EQ(data.frames.size(), reg_data.frames.size());
  // Make sure all of the frame data is exactly the same.
  for (size_t i = 0; i < data.frames.size(); i++) {
    SCOPED_TRACE("\nMismatch at Frame " + std::to_string(i) + "\nucontext trace:\n" +
                 GetBacktrace(unwinder_with_ucontext, data.frames) + "\nregs trace:\n" +
                 GetBacktrace(unwinder_with_regs, reg_data.frames));
    const auto& frame_context = data.frames[i];
    const auto& frame_reg = reg_data.frames[i];
    ASSERT_EQ(frame_context.num, frame_reg.num);
    ASSERT_EQ(frame_context.rel_pc, frame_reg.rel_pc);
    ASSERT_EQ(frame_context.pc, frame_reg.pc);
    ASSERT_EQ(frame_context.sp, frame_reg.sp);
    ASSERT_STREQ(frame_context.function_name.c_str(), frame_reg.function_name.c_str());
    ASSERT_EQ(frame_context.function_offset, frame_reg.function_offset);
    ASSERT_STREQ(frame_context.map_info->name().c_str(), frame_reg.map_info->name().c_str());
    ASSERT_EQ(frame_context.map_info->start(), frame_reg.map_info->start());
    ASSERT_EQ(frame_context.map_info->end(), frame_reg.map_info->end());
  }
}

TEST(AndroidLocalUnwinderTest, unwind_current_thread) {
  AndroidLocalUnwinder unwinder;
  AndroidUnwinderData data;
  ASSERT_TRUE(unwinder.Unwind(data));
  // Verify that the libunwindstack.so does not appear in the first frame.
  ASSERT_TRUE(data.frames[0].map_info == nullptr ||
              !android::base::EndsWith(data.frames[0].map_info->name(), "/libunwindstack.so"))
      << "libunwindstack.so not removed properly\n"
      << GetBacktrace(unwinder, data.frames);
}

TEST(AndroidLocalUnwinderTest, unwind_current_thread_show_all_frames) {
  AndroidLocalUnwinder unwinder;
  AndroidUnwinderData data(true);
  ASSERT_TRUE(unwinder.Unwind(data));
  // Verify that the libunwindstack.so does appear in the first frame.
  ASSERT_TRUE(data.frames[0].map_info != nullptr &&
              android::base::EndsWith(data.frames[0].map_info->name(), "/libunwindstack.so"))
      << "libunwindstack.so was removed improperly\n"
      << GetBacktrace(unwinder, data.frames);
}

__attribute__((__noinline__)) extern "C" void ThreadBusyWait(std::atomic<pid_t>* tid,
                                                             volatile bool* keep_running) {
  *tid = android::base::GetThreadId();
  while (*keep_running) {
  }
}

TEST(AndroidLocalUnwinderTest, unwind_different_thread) {
  std::atomic<pid_t> tid;
  volatile bool keep_running = true;
  std::thread thread([&tid, &keep_running] {
    ThreadBusyWait(&tid, &keep_running);
    return nullptr;
  });

  while (tid == 0) {
  }

  AndroidLocalUnwinder unwinder;
  AndroidUnwinderData data;
  ASSERT_TRUE(unwinder.Unwind(tid, data));
  // Verify that we are unwinding the thread.

  // It's possible that ThreadBusyWait is not the lowest called function.
  // This can happen when running hwasan or if you run fast enough, you
  // can catch the code still in the atomic operator= function, but after
  // the tid is set. We really only care that the unwind sees you are in
  // ThreadBusyWait, so look for it specifically.
  size_t i = 0;
  for (; i < data.frames.size(); i++) {
    if (data.frames[i].function_name == "ThreadBusyWait") {
      break;
    }
  }
  ASSERT_NE(i, data.frames.size()) << "Cannot find ThreadBusyWait in backtrace\n"
                                   << GetBacktrace(unwinder, data.frames);
  ASSERT_NE(i + 1, data.frames.size())
      << "ThreadBusyWait function is the last frame of the unwind.\n"
      << GetBacktrace(unwinder, data.frames);

  // Allow the thread to terminate normally.
  keep_running = false;
  thread.join();
}

class AndroidRemoteUnwinderTest : public ForkTest {
 protected:
  void Verify(std::function<PidRunEnum(const FrameData& frame)> verify_func) {
    ForkAndWaitForPidState([this, &verify_func]() {
      AndroidRemoteUnwinder unwinder(pid_);
      AndroidUnwinderData data;
      if (!unwinder.Unwind(data)) {
        printf("Failed to unwind %s\n", data.GetErrorString().c_str());
        return PID_RUN_FAIL;
      }
      const auto& frame = data.frames[0];
      return verify_func(frame);
    });
  }
};

TEST_F(AndroidRemoteUnwinderTest, initialize_before) {
  ASSERT_NO_FATAL_FAILURE(Fork());

  AndroidRemoteUnwinder unwinder(pid_);
  ErrorData error;
  ASSERT_TRUE(unwinder.Initialize(error));

  AndroidUnwinderData data;
  ASSERT_TRUE(unwinder.Unwind(data));
}

TEST_F(AndroidRemoteUnwinderTest, skip_libraries) {
  void* test_lib = GetTestLibHandle();
  ASSERT_TRUE(test_lib != nullptr);
  void (*wait_func)() = reinterpret_cast<void (*)()>(dlsym(test_lib, "WaitForever"));
  ASSERT_TRUE(wait_func != nullptr);

  SetForkFunc([wait_func]() { wait_func(); });
  Verify([this](const FrameData& frame) {
    // Make sure that the frame is in the dlopen'd library before proceeding.
    if (frame.map_info == nullptr ||
        !android::base::EndsWith(frame.map_info->name(), "/libunwindstack_local.so")) {
      return PID_RUN_KEEP_GOING;
    }

    // Do an unwind removing the libunwindstack_local.so library.
    AndroidRemoteUnwinder unwinder(pid_, std::vector<std::string>{"libunwindstack_local.so"});
    AndroidUnwinderData data;
    if (!unwinder.Unwind(data)) {
      printf("Failed to unwind %s\n", data.GetErrorString().c_str());
      return PID_RUN_FAIL;
    }

    // Verify that library is properly ignored.
    if (android::base::EndsWith(data.frames[0].map_info->name(), "/libunwindstack_local.so")) {
      printf("Failed to strip libunwindstack_local.so\n%s\n",
             GetBacktrace(unwinder, data.frames).c_str());
      return PID_RUN_FAIL;
    }
    return PID_RUN_PASS;
  });
}

TEST_F(AndroidRemoteUnwinderTest, suffix_ignore) {
  Verify([this](const FrameData& frame) {
    // Wait until the forked process is no longer in libc.so.
    if (frame.map_info != nullptr && android::base::EndsWith(frame.map_info->name(), ".so")) {
      return PID_RUN_KEEP_GOING;
    }

    AndroidRemoteUnwinder unwinder(pid_, std::vector<std::string>{},
                                   std::vector<std::string>{"so"});
    AndroidUnwinderData data;
    if (!unwinder.Unwind(data)) {
      printf("Failed to unwind %s\n", data.GetErrorString().c_str());

      AndroidRemoteUnwinder normal_unwinder(pid_);
      if (normal_unwinder.Unwind(data)) {
        printf("Full unwind %s\n", GetBacktrace(normal_unwinder, data.frames).c_str());
      }
      return PID_RUN_FAIL;
    }

    // Make sure the unwind doesn't include any .so frames.
    for (const auto& frame : data.frames) {
      if (frame.map_info != nullptr && android::base::EndsWith(frame.map_info->name(), ".so")) {
        printf("Found unexpected .so frame\n%s\n", GetBacktrace(unwinder, data.frames).c_str());
        return PID_RUN_FAIL;
      }
    }
    return PID_RUN_PASS;
  });
}

TEST_F(AndroidRemoteUnwinderTest, remote_get_arch_ptrace_fails) {
  AndroidRemoteUnwinder unwinder(getpid());
  AndroidUnwinderData data;
  ASSERT_FALSE(unwinder.Unwind(data));
  EXPECT_EQ("Ptrace Call Failed", data.GetErrorString());
}

TEST_F(AndroidRemoteUnwinderTest, remote_get_ptrace_fails) {
  AndroidRemoteUnwinder unwinder(getpid(), Regs::CurrentArch());
  AndroidUnwinderData data;
  ASSERT_FALSE(unwinder.Unwind(data));
  EXPECT_EQ("Ptrace Call Failed", data.GetErrorString());
}

}  // namespace unwindstack