[go: nahoru, domu]

blob: aab6db9de5862d576f432cc26f29ef94016a22ec [file] [log] [blame]
Christopher Ferris20bc65f2013-10-29 20:56:521/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Christopher Ferrisba413b62015-04-02 02:59:5317#define _GNU_SOURCE 1
Christopher Ferris20bc65f2013-10-29 20:56:5218#include <dirent.h>
Christopher Ferris386a23e2015-05-13 18:47:2419#include <dlfcn.h>
Christopher Ferris20bc65f2013-10-29 20:56:5220#include <errno.h>
Christopher Ferris386a23e2015-05-13 18:47:2421#include <fcntl.h>
Christopher Ferrisf994e562014-04-04 03:19:3922#include <inttypes.h>
Christopher Ferris20bc65f2013-10-29 20:56:5223#include <pthread.h>
24#include <signal.h>
Christopher Ferrisf994e562014-04-04 03:19:3925#include <stdint.h>
Christopher Ferris20bc65f2013-10-29 20:56:5226#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <sys/ptrace.h>
Christopher Ferris386a23e2015-05-13 18:47:2430#include <sys/stat.h>
Christopher Ferris20bc65f2013-10-29 20:56:5231#include <sys/types.h>
32#include <sys/wait.h>
33#include <time.h>
Christopher Ferris703a27f2018-01-30 15:44:3634#include <ucontext.h>
Christopher Ferris20bc65f2013-10-29 20:56:5235#include <unistd.h>
36
Christopher Ferrisf994e562014-04-04 03:19:3937#include <algorithm>
Christopher Ferris386a23e2015-05-13 18:47:2438#include <list>
Christopher Ferrisb487b312015-03-18 10:57:3839#include <memory>
Christopher Ferrise622fb82017-03-24 17:31:0540#include <ostream>
Christopher Ferriscc629982015-03-31 23:01:2841#include <string>
Christopher Ferris20bc65f2013-10-29 20:56:5242#include <vector>
43
Dan Albert66f3dc72015-05-01 01:31:4544#include <backtrace/Backtrace.h>
45#include <backtrace/BacktraceMap.h>
46
Christopher Ferris96e504b2017-03-23 01:18:3847#include <android-base/macros.h>
Elliott Hughes35a19fc2015-12-07 23:59:4448#include <android-base/stringprintf.h>
Christopher Ferris25dc7302017-03-22 17:41:0149#include <android-base/unique_fd.h>
Dan Albert66f3dc72015-05-01 01:31:4550#include <cutils/atomic.h>
51#include <cutils/threads.h>
52
53#include <gtest/gtest.h>
54
55// For the THREAD_SIGNAL definition.
56#include "BacktraceCurrent.h"
Christopher Ferrise622fb82017-03-24 17:31:0557#include "backtrace_testlib.h"
Christopher Ferris20bc65f2013-10-29 20:56:5258#include "thread_utils.h"
59
60// Number of microseconds per milliseconds.
61#define US_PER_MSEC 1000
62
63// Number of nanoseconds in a second.
64#define NS_PER_SEC 1000000000ULL
65
66// Number of simultaneous dumping operations to perform.
Christopher Ferris4f07bf92014-11-14 19:39:0467#define NUM_THREADS 40
Christopher Ferris20bc65f2013-10-29 20:56:5268
69// Number of simultaneous threads running in our forked process.
70#define NUM_PTRACE_THREADS 5
71
Christopher Ferrisabf39bb2014-01-17 19:56:0472struct thread_t {
Christopher Ferris20bc65f2013-10-29 20:56:5273 pid_t tid;
74 int32_t state;
75 pthread_t threadId;
Christopher Ferrisb487b312015-03-18 10:57:3876 void* data;
Christopher Ferrisabf39bb2014-01-17 19:56:0477};
Christopher Ferris20bc65f2013-10-29 20:56:5278
Christopher Ferrisabf39bb2014-01-17 19:56:0479struct dump_thread_t {
Christopher Ferris20bc65f2013-10-29 20:56:5280 thread_t thread;
Christopher Ferris219eb8d2017-11-29 03:07:0881 BacktraceMap* map;
Christopher Ferris737b6a12014-01-14 02:12:0482 Backtrace* backtrace;
Christopher Ferris20bc65f2013-10-29 20:56:5283 int32_t* now;
84 int32_t done;
Christopher Ferrisabf39bb2014-01-17 19:56:0485};
Christopher Ferris20bc65f2013-10-29 20:56:5286
Christopher Ferris73a04f12017-09-25 19:24:0787typedef Backtrace* (*create_func_t)(pid_t, pid_t, BacktraceMap*);
88typedef BacktraceMap* (*map_create_func_t)(pid_t, bool);
89
90static void VerifyLevelDump(Backtrace* backtrace, create_func_t create_func = nullptr,
91 map_create_func_t map_func = nullptr);
92static void VerifyMaxDump(Backtrace* backtrace, create_func_t create_func = nullptr,
93 map_create_func_t map_func = nullptr);
94
Christopher Ferris25dc7302017-03-22 17:41:0195static uint64_t NanoTime() {
Christopher Ferris20bc65f2013-10-29 20:56:5296 struct timespec t = { 0, 0 };
97 clock_gettime(CLOCK_MONOTONIC, &t);
98 return static_cast<uint64_t>(t.tv_sec * NS_PER_SEC + t.tv_nsec);
99}
100
Christopher Ferris25dc7302017-03-22 17:41:01101static std::string DumpFrames(Backtrace* backtrace) {
Christopher Ferris737b6a12014-01-14 02:12:04102 if (backtrace->NumFrames() == 0) {
Christopher Ferris04f818f2015-04-03 14:52:56103 return " No frames to dump.\n";
Christopher Ferris737b6a12014-01-14 02:12:04104 }
105
Christopher Ferriscc629982015-03-31 23:01:28106 std::string frame;
Christopher Ferris737b6a12014-01-14 02:12:04107 for (size_t i = 0; i < backtrace->NumFrames(); i++) {
Christopher Ferriscc629982015-03-31 23:01:28108 frame += " " + backtrace->FormatFrameData(i) + '\n';
Christopher Ferris20bc65f2013-10-29 20:56:52109 }
Christopher Ferriscc629982015-03-31 23:01:28110 return frame;
Christopher Ferris20bc65f2013-10-29 20:56:52111}
112
Christopher Ferris25dc7302017-03-22 17:41:01113static void WaitForStop(pid_t pid) {
Christopher Ferris20bc65f2013-10-29 20:56:52114 uint64_t start = NanoTime();
115
116 siginfo_t si;
117 while (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) < 0 && (errno == EINTR || errno == ESRCH)) {
118 if ((NanoTime() - start) > NS_PER_SEC) {
119 printf("The process did not get to a stopping point in 1 second.\n");
120 break;
121 }
122 usleep(US_PER_MSEC);
123 }
124}
125
Christopher Ferris25dc7302017-03-22 17:41:01126static void CreateRemoteProcess(pid_t* pid) {
127 if ((*pid = fork()) == 0) {
128 while (true)
129 ;
130 _exit(0);
131 }
132 ASSERT_NE(-1, *pid);
133
134 ASSERT_TRUE(ptrace(PTRACE_ATTACH, *pid, 0, 0) == 0);
135
136 // Wait for the process to get to a stopping point.
137 WaitForStop(*pid);
138}
139
140static void FinishRemoteProcess(pid_t pid) {
141 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
142
143 kill(pid, SIGKILL);
144 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
145}
146
Christopher Ferris703a27f2018-01-30 15:44:36147#if !defined(__ANDROID__) || defined(__arm__)
148// On host and arm target we aren't guaranteed that we will terminate cleanly.
149#define VERIFY_NO_ERROR(error_code) \
150 ASSERT_TRUE(error_code == BACKTRACE_UNWIND_NO_ERROR || \
151 error_code == BACKTRACE_UNWIND_ERROR_UNWIND_INFO || \
152 error_code == BACKTRACE_UNWIND_ERROR_MAP_MISSING) \
153 << "Unknown error code " << std::to_string(error_code);
154#else
155#define VERIFY_NO_ERROR(error_code) ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, error_code);
156#endif
157
Christopher Ferris25dc7302017-03-22 17:41:01158static bool ReadyLevelBacktrace(Backtrace* backtrace) {
Christopher Ferris20bc65f2013-10-29 20:56:52159 // See if test_level_four is in the backtrace.
160 bool found = false;
Christopher Ferrisabf39bb2014-01-17 19:56:04161 for (Backtrace::const_iterator it = backtrace->begin(); it != backtrace->end(); ++it) {
162 if (it->func_name == "test_level_four") {
Christopher Ferris20bc65f2013-10-29 20:56:52163 found = true;
164 break;
165 }
166 }
167
168 return found;
169}
170
Christopher Ferris73a04f12017-09-25 19:24:07171static void VerifyLevelDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
Christopher Ferris04f818f2015-04-03 14:52:56172 ASSERT_GT(backtrace->NumFrames(), static_cast<size_t>(0))
173 << DumpFrames(backtrace);
174 ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
175 << DumpFrames(backtrace);
Christopher Ferris20bc65f2013-10-29 20:56:52176
177 // Look through the frames starting at the highest to find the
178 // frame we want.
179 size_t frame_num = 0;
Christopher Ferris737b6a12014-01-14 02:12:04180 for (size_t i = backtrace->NumFrames()-1; i > 2; i--) {
Christopher Ferrisabf39bb2014-01-17 19:56:04181 if (backtrace->GetFrame(i)->func_name == "test_level_one") {
Christopher Ferris20bc65f2013-10-29 20:56:52182 frame_num = i;
183 break;
184 }
185 }
Christopher Ferriscc629982015-03-31 23:01:28186 ASSERT_LT(static_cast<size_t>(0), frame_num) << DumpFrames(backtrace);
187 ASSERT_LE(static_cast<size_t>(3), frame_num) << DumpFrames(backtrace);
Christopher Ferris20bc65f2013-10-29 20:56:52188
Christopher Ferris04f818f2015-04-03 14:52:56189 ASSERT_EQ(backtrace->GetFrame(frame_num)->func_name, "test_level_one")
190 << DumpFrames(backtrace);
191 ASSERT_EQ(backtrace->GetFrame(frame_num-1)->func_name, "test_level_two")
192 << DumpFrames(backtrace);
193 ASSERT_EQ(backtrace->GetFrame(frame_num-2)->func_name, "test_level_three")
194 << DumpFrames(backtrace);
195 ASSERT_EQ(backtrace->GetFrame(frame_num-3)->func_name, "test_level_four")
196 << DumpFrames(backtrace);
Christopher Ferris20bc65f2013-10-29 20:56:52197}
198
Christopher Ferris25dc7302017-03-22 17:41:01199static void VerifyLevelBacktrace(void*) {
Christopher Ferrisb487b312015-03-18 10:57:38200 std::unique_ptr<Backtrace> backtrace(
Christopher Ferris737b6a12014-01-14 02:12:04201 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferrisb487b312015-03-18 10:57:38202 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04203 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36204 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52205
Christopher Ferris737b6a12014-01-14 02:12:04206 VerifyLevelDump(backtrace.get());
Christopher Ferris20bc65f2013-10-29 20:56:52207}
208
Christopher Ferris25dc7302017-03-22 17:41:01209static bool ReadyMaxBacktrace(Backtrace* backtrace) {
Christopher Ferris737b6a12014-01-14 02:12:04210 return (backtrace->NumFrames() == MAX_BACKTRACE_FRAMES);
Christopher Ferris20bc65f2013-10-29 20:56:52211}
212
Christopher Ferris73a04f12017-09-25 19:24:07213static void VerifyMaxDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
Christopher Ferris04f818f2015-04-03 14:52:56214 ASSERT_EQ(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
215 << DumpFrames(backtrace);
Christopher Ferris20bc65f2013-10-29 20:56:52216 // Verify that the last frame is our recursive call.
Christopher Ferris04f818f2015-04-03 14:52:56217 ASSERT_EQ(backtrace->GetFrame(MAX_BACKTRACE_FRAMES-1)->func_name, "test_recursive_call")
218 << DumpFrames(backtrace);
Christopher Ferris20bc65f2013-10-29 20:56:52219}
220
Christopher Ferris25dc7302017-03-22 17:41:01221static void VerifyMaxBacktrace(void*) {
Christopher Ferrisb487b312015-03-18 10:57:38222 std::unique_ptr<Backtrace> backtrace(
Christopher Ferris737b6a12014-01-14 02:12:04223 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferrisb487b312015-03-18 10:57:38224 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04225 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36226 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT, backtrace->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52227
Christopher Ferris737b6a12014-01-14 02:12:04228 VerifyMaxDump(backtrace.get());
Christopher Ferris20bc65f2013-10-29 20:56:52229}
230
Christopher Ferris25dc7302017-03-22 17:41:01231static void ThreadSetState(void* data) {
Christopher Ferris20bc65f2013-10-29 20:56:52232 thread_t* thread = reinterpret_cast<thread_t*>(data);
233 android_atomic_acquire_store(1, &thread->state);
234 volatile int i = 0;
235 while (thread->state) {
236 i++;
237 }
238}
239
Christopher Ferris25dc7302017-03-22 17:41:01240static bool WaitForNonZero(int32_t* value, uint64_t seconds) {
Christopher Ferris20bc65f2013-10-29 20:56:52241 uint64_t start = NanoTime();
242 do {
243 if (android_atomic_acquire_load(value)) {
244 return true;
245 }
246 } while ((NanoTime() - start) < seconds * NS_PER_SEC);
247 return false;
248}
249
Christopher Ferrisba413b62015-04-02 02:59:53250TEST(libbacktrace, local_no_unwind_frames) {
251 // Verify that a local unwind does not include any frames within
252 // libunwind or libbacktrace.
253 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), getpid()));
Christopher Ferris04f818f2015-04-03 14:52:56254 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferrisba413b62015-04-02 02:59:53255 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36256 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferrisba413b62015-04-02 02:59:53257
258 ASSERT_TRUE(backtrace->NumFrames() != 0);
259 for (const auto& frame : *backtrace ) {
260 if (BacktraceMap::IsValid(frame.map)) {
261 const std::string name = basename(frame.map.name.c_str());
262 ASSERT_TRUE(name != "libunwind.so" && name != "libbacktrace.so")
263 << DumpFrames(backtrace.get());
264 }
265 break;
266 }
267}
268
Christopher Ferris20bc65f2013-10-29 20:56:52269TEST(libbacktrace, local_trace) {
Christopher Ferrisb487b312015-03-18 10:57:38270 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelBacktrace, nullptr), 0);
Christopher Ferris20bc65f2013-10-29 20:56:52271}
272
Christopher Ferris25dc7302017-03-22 17:41:01273static void VerifyIgnoreFrames(Backtrace* bt_all, Backtrace* bt_ign1, Backtrace* bt_ign2,
274 const char* cur_proc) {
Christopher Ferris73a04f12017-09-25 19:24:07275 ASSERT_EQ(bt_all->NumFrames(), bt_ign1->NumFrames() + 1) << "All backtrace:\n"
276 << DumpFrames(bt_all)
277 << "Ignore 1 backtrace:\n"
278 << DumpFrames(bt_ign1);
279 ASSERT_EQ(bt_all->NumFrames(), bt_ign2->NumFrames() + 2) << "All backtrace:\n"
280 << DumpFrames(bt_all)
281 << "Ignore 2 backtrace:\n"
282 << DumpFrames(bt_ign2);
Christopher Ferris20bc65f2013-10-29 20:56:52283
284 // Check all of the frames are the same > the current frame.
Christopher Ferrisb487b312015-03-18 10:57:38285 bool check = (cur_proc == nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04286 for (size_t i = 0; i < bt_ign2->NumFrames(); i++) {
Christopher Ferris20bc65f2013-10-29 20:56:52287 if (check) {
Christopher Ferris737b6a12014-01-14 02:12:04288 EXPECT_EQ(bt_ign2->GetFrame(i)->pc, bt_ign1->GetFrame(i+1)->pc);
289 EXPECT_EQ(bt_ign2->GetFrame(i)->sp, bt_ign1->GetFrame(i+1)->sp);
290 EXPECT_EQ(bt_ign2->GetFrame(i)->stack_size, bt_ign1->GetFrame(i+1)->stack_size);
Christopher Ferris20bc65f2013-10-29 20:56:52291
Christopher Ferris737b6a12014-01-14 02:12:04292 EXPECT_EQ(bt_ign2->GetFrame(i)->pc, bt_all->GetFrame(i+2)->pc);
293 EXPECT_EQ(bt_ign2->GetFrame(i)->sp, bt_all->GetFrame(i+2)->sp);
294 EXPECT_EQ(bt_ign2->GetFrame(i)->stack_size, bt_all->GetFrame(i+2)->stack_size);
Christopher Ferris20bc65f2013-10-29 20:56:52295 }
Christopher Ferrisabf39bb2014-01-17 19:56:04296 if (!check && bt_ign2->GetFrame(i)->func_name == cur_proc) {
Christopher Ferris20bc65f2013-10-29 20:56:52297 check = true;
298 }
299 }
300}
301
Christopher Ferris25dc7302017-03-22 17:41:01302static void VerifyLevelIgnoreFrames(void*) {
Christopher Ferrisb487b312015-03-18 10:57:38303 std::unique_ptr<Backtrace> all(
Christopher Ferris737b6a12014-01-14 02:12:04304 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferrisb487b312015-03-18 10:57:38305 ASSERT_TRUE(all.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04306 ASSERT_TRUE(all->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36307 VERIFY_NO_ERROR(all->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52308
Christopher Ferrisb487b312015-03-18 10:57:38309 std::unique_ptr<Backtrace> ign1(
Christopher Ferris737b6a12014-01-14 02:12:04310 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferrisb487b312015-03-18 10:57:38311 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04312 ASSERT_TRUE(ign1->Unwind(1));
Christopher Ferris703a27f2018-01-30 15:44:36313 VERIFY_NO_ERROR(ign1->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52314
Christopher Ferrisb487b312015-03-18 10:57:38315 std::unique_ptr<Backtrace> ign2(
Christopher Ferris737b6a12014-01-14 02:12:04316 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferrisb487b312015-03-18 10:57:38317 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04318 ASSERT_TRUE(ign2->Unwind(2));
Christopher Ferris703a27f2018-01-30 15:44:36319 VERIFY_NO_ERROR(ign2->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52320
Christopher Ferris737b6a12014-01-14 02:12:04321 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), "VerifyLevelIgnoreFrames");
Christopher Ferris20bc65f2013-10-29 20:56:52322}
323
324TEST(libbacktrace, local_trace_ignore_frames) {
Christopher Ferrisb487b312015-03-18 10:57:38325 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelIgnoreFrames, nullptr), 0);
Christopher Ferris20bc65f2013-10-29 20:56:52326}
327
328TEST(libbacktrace, local_max_trace) {
Christopher Ferrisb487b312015-03-18 10:57:38329 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxBacktrace, nullptr), 0);
Christopher Ferris20bc65f2013-10-29 20:56:52330}
331
Christopher Ferris55d10c62017-08-29 17:38:31332static void VerifyProcTest(pid_t pid, pid_t tid, bool (*ReadyFunc)(Backtrace*),
Christopher Ferris73a04f12017-09-25 19:24:07333 void (*VerifyFunc)(Backtrace*, create_func_t, map_create_func_t),
334 create_func_t create_func, map_create_func_t map_create_func) {
Christopher Ferris20bc65f2013-10-29 20:56:52335 pid_t ptrace_tid;
336 if (tid < 0) {
337 ptrace_tid = pid;
338 } else {
339 ptrace_tid = tid;
340 }
341 uint64_t start = NanoTime();
342 bool verified = false;
Christopher Ferris04f818f2015-04-03 14:52:56343 std::string last_dump;
Christopher Ferris20bc65f2013-10-29 20:56:52344 do {
345 usleep(US_PER_MSEC);
346 if (ptrace(PTRACE_ATTACH, ptrace_tid, 0, 0) == 0) {
347 // Wait for the process to get to a stopping point.
348 WaitForStop(ptrace_tid);
349
Christopher Ferrisb487b312015-03-18 10:57:38350 std::unique_ptr<BacktraceMap> map;
Christopher Ferris73a04f12017-09-25 19:24:07351 map.reset(map_create_func(pid, false));
352 std::unique_ptr<Backtrace> backtrace(create_func(pid, tid, map.get()));
Christopher Ferrisb487b312015-03-18 10:57:38353 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris04f818f2015-04-03 14:52:56354 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris737b6a12014-01-14 02:12:04355 if (ReadyFunc(backtrace.get())) {
Christopher Ferris73a04f12017-09-25 19:24:07356 VerifyFunc(backtrace.get(), create_func, map_create_func);
Christopher Ferris20bc65f2013-10-29 20:56:52357 verified = true;
Christopher Ferris04f818f2015-04-03 14:52:56358 } else {
359 last_dump = DumpFrames(backtrace.get());
Christopher Ferris20bc65f2013-10-29 20:56:52360 }
Christopher Ferris737b6a12014-01-14 02:12:04361
Christopher Ferris20bc65f2013-10-29 20:56:52362 ASSERT_TRUE(ptrace(PTRACE_DETACH, ptrace_tid, 0, 0) == 0);
363 }
364 // If 5 seconds have passed, then we are done.
365 } while (!verified && (NanoTime() - start) <= 5 * NS_PER_SEC);
Christopher Ferris04f818f2015-04-03 14:52:56366 ASSERT_TRUE(verified) << "Last backtrace:\n" << last_dump;
Christopher Ferris20bc65f2013-10-29 20:56:52367}
368
369TEST(libbacktrace, ptrace_trace) {
370 pid_t pid;
371 if ((pid = fork()) == 0) {
Christopher Ferrisb487b312015-03-18 10:57:38372 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrisf994e562014-04-04 03:19:39373 _exit(1);
Christopher Ferris20bc65f2013-10-29 20:56:52374 }
Christopher Ferris55d10c62017-08-29 17:38:31375 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, ReadyLevelBacktrace, VerifyLevelDump,
376 Backtrace::Create, BacktraceMap::Create);
Christopher Ferris18e41fe2014-01-29 12:19:59377
378 kill(pid, SIGKILL);
379 int status;
380 ASSERT_EQ(waitpid(pid, &status, 0), pid);
381}
382
Christopher Ferris20bc65f2013-10-29 20:56:52383TEST(libbacktrace, ptrace_max_trace) {
384 pid_t pid;
385 if ((pid = fork()) == 0) {
Christopher Ferrisb487b312015-03-18 10:57:38386 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, nullptr, nullptr), 0);
Christopher Ferrisf994e562014-04-04 03:19:39387 _exit(1);
Christopher Ferris20bc65f2013-10-29 20:56:52388 }
Christopher Ferris55d10c62017-08-29 17:38:31389 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, ReadyMaxBacktrace, VerifyMaxDump, Backtrace::Create,
390 BacktraceMap::Create);
391
392 kill(pid, SIGKILL);
393 int status;
394 ASSERT_EQ(waitpid(pid, &status, 0), pid);
395}
396
Christopher Ferris73a04f12017-09-25 19:24:07397static void VerifyProcessIgnoreFrames(Backtrace* bt_all, create_func_t create_func,
398 map_create_func_t map_create_func) {
399 std::unique_ptr<BacktraceMap> map(map_create_func(bt_all->Pid(), false));
400 std::unique_ptr<Backtrace> ign1(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
Christopher Ferrisb487b312015-03-18 10:57:38401 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04402 ASSERT_TRUE(ign1->Unwind(1));
Christopher Ferris703a27f2018-01-30 15:44:36403 VERIFY_NO_ERROR(ign1->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52404
Christopher Ferris73a04f12017-09-25 19:24:07405 std::unique_ptr<Backtrace> ign2(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
Christopher Ferrisb487b312015-03-18 10:57:38406 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04407 ASSERT_TRUE(ign2->Unwind(2));
Christopher Ferris703a27f2018-01-30 15:44:36408 VERIFY_NO_ERROR(ign2->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52409
Christopher Ferrisb487b312015-03-18 10:57:38410 VerifyIgnoreFrames(bt_all, ign1.get(), ign2.get(), nullptr);
Christopher Ferris20bc65f2013-10-29 20:56:52411}
412
413TEST(libbacktrace, ptrace_ignore_frames) {
414 pid_t pid;
415 if ((pid = fork()) == 0) {
Christopher Ferrisb487b312015-03-18 10:57:38416 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrisf994e562014-04-04 03:19:39417 _exit(1);
Christopher Ferris20bc65f2013-10-29 20:56:52418 }
Christopher Ferris55d10c62017-08-29 17:38:31419 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, ReadyLevelBacktrace, VerifyProcessIgnoreFrames,
420 Backtrace::Create, BacktraceMap::Create);
421
422 kill(pid, SIGKILL);
423 int status;
424 ASSERT_EQ(waitpid(pid, &status, 0), pid);
425}
426
Christopher Ferris20bc65f2013-10-29 20:56:52427// Create a process with multiple threads and dump all of the threads.
Christopher Ferris25dc7302017-03-22 17:41:01428static void* PtraceThreadLevelRun(void*) {
Christopher Ferrisb487b312015-03-18 10:57:38429 EXPECT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
430 return nullptr;
Christopher Ferris20bc65f2013-10-29 20:56:52431}
432
Christopher Ferris25dc7302017-03-22 17:41:01433static void GetThreads(pid_t pid, std::vector<pid_t>* threads) {
Christopher Ferris20bc65f2013-10-29 20:56:52434 // Get the list of tasks.
435 char task_path[128];
436 snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
437
James Hawkins85c96812016-02-19 19:10:30438 std::unique_ptr<DIR, decltype(&closedir)> tasks_dir(opendir(task_path), closedir);
Christopher Ferrisb487b312015-03-18 10:57:38439 ASSERT_TRUE(tasks_dir != nullptr);
Christopher Ferris20bc65f2013-10-29 20:56:52440 struct dirent* entry;
James Hawkins85c96812016-02-19 19:10:30441 while ((entry = readdir(tasks_dir.get())) != nullptr) {
Christopher Ferris20bc65f2013-10-29 20:56:52442 char* end;
443 pid_t tid = strtoul(entry->d_name, &end, 10);
444 if (*end == '\0') {
445 threads->push_back(tid);
446 }
447 }
Christopher Ferris20bc65f2013-10-29 20:56:52448}
449
450TEST(libbacktrace, ptrace_threads) {
451 pid_t pid;
452 if ((pid = fork()) == 0) {
453 for (size_t i = 0; i < NUM_PTRACE_THREADS; i++) {
454 pthread_attr_t attr;
455 pthread_attr_init(&attr);
456 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
457
458 pthread_t thread;
Christopher Ferrisb487b312015-03-18 10:57:38459 ASSERT_TRUE(pthread_create(&thread, &attr, PtraceThreadLevelRun, nullptr) == 0);
Christopher Ferris20bc65f2013-10-29 20:56:52460 }
Christopher Ferrisb487b312015-03-18 10:57:38461 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrisf994e562014-04-04 03:19:39462 _exit(1);
Christopher Ferris20bc65f2013-10-29 20:56:52463 }
464
465 // Check to see that all of the threads are running before unwinding.
466 std::vector<pid_t> threads;
467 uint64_t start = NanoTime();
468 do {
469 usleep(US_PER_MSEC);
470 threads.clear();
471 GetThreads(pid, &threads);
472 } while ((threads.size() != NUM_PTRACE_THREADS + 1) &&
473 ((NanoTime() - start) <= 5 * NS_PER_SEC));
474 ASSERT_EQ(threads.size(), static_cast<size_t>(NUM_PTRACE_THREADS + 1));
475
476 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
477 WaitForStop(pid);
478 for (std::vector<int>::const_iterator it = threads.begin(); it != threads.end(); ++it) {
479 // Skip the current forked process, we only care about the threads.
480 if (pid == *it) {
481 continue;
482 }
Christopher Ferris55d10c62017-08-29 17:38:31483 VerifyProcTest(pid, *it, ReadyLevelBacktrace, VerifyLevelDump, Backtrace::Create,
484 BacktraceMap::Create);
485 }
486
487 FinishRemoteProcess(pid);
488}
489
Christopher Ferris20bc65f2013-10-29 20:56:52490void VerifyLevelThread(void*) {
Christopher Ferrisb487b312015-03-18 10:57:38491 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
492 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04493 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36494 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52495
Christopher Ferris737b6a12014-01-14 02:12:04496 VerifyLevelDump(backtrace.get());
Christopher Ferris20bc65f2013-10-29 20:56:52497}
498
499TEST(libbacktrace, thread_current_level) {
Christopher Ferrisb487b312015-03-18 10:57:38500 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelThread, nullptr), 0);
Christopher Ferris20bc65f2013-10-29 20:56:52501}
502
Christopher Ferris25dc7302017-03-22 17:41:01503static void VerifyMaxThread(void*) {
Christopher Ferrisb487b312015-03-18 10:57:38504 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
505 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04506 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36507 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT, backtrace->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52508
Christopher Ferris737b6a12014-01-14 02:12:04509 VerifyMaxDump(backtrace.get());
Christopher Ferris20bc65f2013-10-29 20:56:52510}
511
512TEST(libbacktrace, thread_current_max) {
Christopher Ferrisb487b312015-03-18 10:57:38513 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxThread, nullptr), 0);
Christopher Ferris20bc65f2013-10-29 20:56:52514}
515
Christopher Ferris25dc7302017-03-22 17:41:01516static void* ThreadLevelRun(void* data) {
Christopher Ferris20bc65f2013-10-29 20:56:52517 thread_t* thread = reinterpret_cast<thread_t*>(data);
518
519 thread->tid = gettid();
520 EXPECT_NE(test_level_one(1, 2, 3, 4, ThreadSetState, data), 0);
Christopher Ferrisb487b312015-03-18 10:57:38521 return nullptr;
Christopher Ferris20bc65f2013-10-29 20:56:52522}
523
524TEST(libbacktrace, thread_level_trace) {
525 pthread_attr_t attr;
526 pthread_attr_init(&attr);
527 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
528
Christopher Ferrisb487b312015-03-18 10:57:38529 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris20bc65f2013-10-29 20:56:52530 pthread_t thread;
531 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadLevelRun, &thread_data) == 0);
532
533 // Wait up to 2 seconds for the tid to be set.
534 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
535
Christopher Ferris3f212cf2014-05-01 00:24:30536 // Make sure that the thread signal used is not visible when compiled for
537 // the target.
538#if !defined(__GLIBC__)
539 ASSERT_LT(THREAD_SIGNAL, SIGRTMIN);
540#endif
541
Christopher Ferris20bc65f2013-10-29 20:56:52542 // Save the current signal action and make sure it is restored afterwards.
543 struct sigaction cur_action;
Christopher Ferrisb487b312015-03-18 10:57:38544 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &cur_action) == 0);
Christopher Ferris20bc65f2013-10-29 20:56:52545
Christopher Ferrisb487b312015-03-18 10:57:38546 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
547 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04548 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36549 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52550
Christopher Ferris737b6a12014-01-14 02:12:04551 VerifyLevelDump(backtrace.get());
Christopher Ferris20bc65f2013-10-29 20:56:52552
553 // Tell the thread to exit its infinite loop.
554 android_atomic_acquire_store(0, &thread_data.state);
555
556 // Verify that the old action was restored.
557 struct sigaction new_action;
Christopher Ferrisb487b312015-03-18 10:57:38558 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &new_action) == 0);
Christopher Ferris20bc65f2013-10-29 20:56:52559 EXPECT_EQ(cur_action.sa_sigaction, new_action.sa_sigaction);
Christopher Ferris4f07bf92014-11-14 19:39:04560 // The SA_RESTORER flag gets set behind our back, so a direct comparison
561 // doesn't work unless we mask the value off. Mips doesn't have this
562 // flag, so skip this on that platform.
Christopher Ferriscc629982015-03-31 23:01:28563#if defined(SA_RESTORER)
Christopher Ferris4f07bf92014-11-14 19:39:04564 cur_action.sa_flags &= ~SA_RESTORER;
565 new_action.sa_flags &= ~SA_RESTORER;
Christopher Ferriscc629982015-03-31 23:01:28566#elif defined(__GLIBC__)
567 // Our host compiler doesn't appear to define this flag for some reason.
568 cur_action.sa_flags &= ~0x04000000;
569 new_action.sa_flags &= ~0x04000000;
Christopher Ferris4f07bf92014-11-14 19:39:04570#endif
Christopher Ferris20bc65f2013-10-29 20:56:52571 EXPECT_EQ(cur_action.sa_flags, new_action.sa_flags);
572}
573
574TEST(libbacktrace, thread_ignore_frames) {
575 pthread_attr_t attr;
576 pthread_attr_init(&attr);
577 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
578
Christopher Ferrisb487b312015-03-18 10:57:38579 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris20bc65f2013-10-29 20:56:52580 pthread_t thread;
581 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadLevelRun, &thread_data) == 0);
582
583 // Wait up to 2 seconds for the tid to be set.
584 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
585
Christopher Ferrisb487b312015-03-18 10:57:38586 std::unique_ptr<Backtrace> all(Backtrace::Create(getpid(), thread_data.tid));
587 ASSERT_TRUE(all.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04588 ASSERT_TRUE(all->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36589 VERIFY_NO_ERROR(all->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52590
Christopher Ferrisb487b312015-03-18 10:57:38591 std::unique_ptr<Backtrace> ign1(Backtrace::Create(getpid(), thread_data.tid));
592 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04593 ASSERT_TRUE(ign1->Unwind(1));
Christopher Ferris703a27f2018-01-30 15:44:36594 VERIFY_NO_ERROR(ign1->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52595
Christopher Ferrisb487b312015-03-18 10:57:38596 std::unique_ptr<Backtrace> ign2(Backtrace::Create(getpid(), thread_data.tid));
597 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04598 ASSERT_TRUE(ign2->Unwind(2));
Christopher Ferris703a27f2018-01-30 15:44:36599 VERIFY_NO_ERROR(ign2->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52600
Christopher Ferrisb487b312015-03-18 10:57:38601 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), nullptr);
Christopher Ferris20bc65f2013-10-29 20:56:52602
603 // Tell the thread to exit its infinite loop.
604 android_atomic_acquire_store(0, &thread_data.state);
605}
606
Christopher Ferris25dc7302017-03-22 17:41:01607static void* ThreadMaxRun(void* data) {
Christopher Ferris20bc65f2013-10-29 20:56:52608 thread_t* thread = reinterpret_cast<thread_t*>(data);
609
610 thread->tid = gettid();
611 EXPECT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, ThreadSetState, data), 0);
Christopher Ferrisb487b312015-03-18 10:57:38612 return nullptr;
Christopher Ferris20bc65f2013-10-29 20:56:52613}
614
615TEST(libbacktrace, thread_max_trace) {
616 pthread_attr_t attr;
617 pthread_attr_init(&attr);
618 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
619
Christopher Ferrisb487b312015-03-18 10:57:38620 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris20bc65f2013-10-29 20:56:52621 pthread_t thread;
622 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadMaxRun, &thread_data) == 0);
623
624 // Wait for the tid to be set.
625 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
626
Christopher Ferrisb487b312015-03-18 10:57:38627 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
628 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04629 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36630 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT, backtrace->GetError().error_code);
Christopher Ferris20bc65f2013-10-29 20:56:52631
Christopher Ferris737b6a12014-01-14 02:12:04632 VerifyMaxDump(backtrace.get());
Christopher Ferris20bc65f2013-10-29 20:56:52633
634 // Tell the thread to exit its infinite loop.
635 android_atomic_acquire_store(0, &thread_data.state);
636}
637
Christopher Ferris25dc7302017-03-22 17:41:01638static void* ThreadDump(void* data) {
Christopher Ferris20bc65f2013-10-29 20:56:52639 dump_thread_t* dump = reinterpret_cast<dump_thread_t*>(data);
640 while (true) {
641 if (android_atomic_acquire_load(dump->now)) {
642 break;
643 }
644 }
645
Christopher Ferris20bc65f2013-10-29 20:56:52646 // The status of the actual unwind will be checked elsewhere.
Christopher Ferris219eb8d2017-11-29 03:07:08647 dump->backtrace = Backtrace::Create(getpid(), dump->thread.tid, dump->map);
Christopher Ferris737b6a12014-01-14 02:12:04648 dump->backtrace->Unwind(0);
Christopher Ferris20bc65f2013-10-29 20:56:52649
650 android_atomic_acquire_store(1, &dump->done);
651
Christopher Ferrisb487b312015-03-18 10:57:38652 return nullptr;
Christopher Ferris20bc65f2013-10-29 20:56:52653}
654
Christopher Ferris219eb8d2017-11-29 03:07:08655static void MultipleThreadDumpTest(bool share_map) {
656 // Dump NUM_THREADS simultaneously using the same map.
Christopher Ferris20bc65f2013-10-29 20:56:52657 std::vector<thread_t> runners(NUM_THREADS);
658 std::vector<dump_thread_t> dumpers(NUM_THREADS);
659
660 pthread_attr_t attr;
661 pthread_attr_init(&attr);
662 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
663 for (size_t i = 0; i < NUM_THREADS; i++) {
664 // Launch the runners, they will spin in hard loops doing nothing.
665 runners[i].tid = 0;
666 runners[i].state = 0;
667 ASSERT_TRUE(pthread_create(&runners[i].threadId, &attr, ThreadMaxRun, &runners[i]) == 0);
668 }
669
670 // Wait for tids to be set.
671 for (std::vector<thread_t>::iterator it = runners.begin(); it != runners.end(); ++it) {
Christopher Ferris4f07bf92014-11-14 19:39:04672 ASSERT_TRUE(WaitForNonZero(&it->state, 30));
Christopher Ferris20bc65f2013-10-29 20:56:52673 }
674
675 // Start all of the dumpers at once, they will spin until they are signalled
676 // to begin their dump run.
Christopher Ferris219eb8d2017-11-29 03:07:08677 std::unique_ptr<BacktraceMap> map;
678 if (share_map) {
679 map.reset(BacktraceMap::Create(getpid()));
680 }
Christopher Ferris20bc65f2013-10-29 20:56:52681 int32_t dump_now = 0;
682 for (size_t i = 0; i < NUM_THREADS; i++) {
683 dumpers[i].thread.tid = runners[i].tid;
684 dumpers[i].thread.state = 0;
685 dumpers[i].done = 0;
686 dumpers[i].now = &dump_now;
Christopher Ferris219eb8d2017-11-29 03:07:08687 dumpers[i].map = map.get();
Christopher Ferris20bc65f2013-10-29 20:56:52688
689 ASSERT_TRUE(pthread_create(&dumpers[i].thread.threadId, &attr, ThreadDump, &dumpers[i]) == 0);
690 }
691
692 // Start all of the dumpers going at once.
693 android_atomic_acquire_store(1, &dump_now);
694
695 for (size_t i = 0; i < NUM_THREADS; i++) {
Christopher Ferris4f07bf92014-11-14 19:39:04696 ASSERT_TRUE(WaitForNonZero(&dumpers[i].done, 30));
Christopher Ferris20bc65f2013-10-29 20:56:52697
698 // Tell the runner thread to exit its infinite loop.
699 android_atomic_acquire_store(0, &runners[i].state);
700
Christopher Ferrisb487b312015-03-18 10:57:38701 ASSERT_TRUE(dumpers[i].backtrace != nullptr);
Christopher Ferris737b6a12014-01-14 02:12:04702 VerifyMaxDump(dumpers[i].backtrace);
703
704 delete dumpers[i].backtrace;
Christopher Ferrisb487b312015-03-18 10:57:38705 dumpers[i].backtrace = nullptr;
Christopher Ferris20bc65f2013-10-29 20:56:52706 }
707}
708
Christopher Ferris219eb8d2017-11-29 03:07:08709TEST(libbacktrace, thread_multiple_dump) {
710 MultipleThreadDumpTest(false);
711}
Christopher Ferrise73a2462014-05-09 16:45:35712
Christopher Ferris219eb8d2017-11-29 03:07:08713TEST(libbacktrace, thread_multiple_dump_same_map) {
714 MultipleThreadDumpTest(true);
Christopher Ferrise73a2462014-05-09 16:45:35715}
716
Christopher Ferris18e41fe2014-01-29 12:19:59717// This test is for UnwindMaps that should share the same map cursor when
718// multiple maps are created for the current process at the same time.
719TEST(libbacktrace, simultaneous_maps) {
720 BacktraceMap* map1 = BacktraceMap::Create(getpid());
721 BacktraceMap* map2 = BacktraceMap::Create(getpid());
722 BacktraceMap* map3 = BacktraceMap::Create(getpid());
723
724 Backtrace* back1 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map1);
Christopher Ferris04f818f2015-04-03 14:52:56725 ASSERT_TRUE(back1 != nullptr);
Christopher Ferris18e41fe2014-01-29 12:19:59726 EXPECT_TRUE(back1->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36727 VERIFY_NO_ERROR(back1->GetError().error_code);
Christopher Ferris18e41fe2014-01-29 12:19:59728 delete back1;
729 delete map1;
730
731 Backtrace* back2 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map2);
Christopher Ferris04f818f2015-04-03 14:52:56732 ASSERT_TRUE(back2 != nullptr);
Christopher Ferris18e41fe2014-01-29 12:19:59733 EXPECT_TRUE(back2->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36734 VERIFY_NO_ERROR(back2->GetError().error_code);
Christopher Ferris18e41fe2014-01-29 12:19:59735 delete back2;
736 delete map2;
737
738 Backtrace* back3 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map3);
Christopher Ferris04f818f2015-04-03 14:52:56739 ASSERT_TRUE(back3 != nullptr);
Christopher Ferris18e41fe2014-01-29 12:19:59740 EXPECT_TRUE(back3->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:36741 VERIFY_NO_ERROR(back3->GetError().error_code);
Christopher Ferris18e41fe2014-01-29 12:19:59742 delete back3;
743 delete map3;
744}
745
Christopher Ferris8df2ce72015-02-09 04:13:37746TEST(libbacktrace, fillin_erases) {
747 BacktraceMap* back_map = BacktraceMap::Create(getpid());
748
749 backtrace_map_t map;
750
751 map.start = 1;
752 map.end = 3;
753 map.flags = 1;
754 map.name = "Initialized";
755 back_map->FillIn(0, &map);
756 delete back_map;
757
758 ASSERT_FALSE(BacktraceMap::IsValid(map));
Christopher Ferris103f4572018-01-19 23:38:38759 ASSERT_EQ(static_cast<uint64_t>(0), map.start);
760 ASSERT_EQ(static_cast<uint64_t>(0), map.end);
Christopher Ferris8df2ce72015-02-09 04:13:37761 ASSERT_EQ(0, map.flags);
762 ASSERT_EQ("", map.name);
763}
764
Christopher Ferris20bc65f2013-10-29 20:56:52765TEST(libbacktrace, format_test) {
Christopher Ferrisb487b312015-03-18 10:57:38766 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD));
767 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20bc65f2013-10-29 20:56:52768
Christopher Ferris737b6a12014-01-14 02:12:04769 backtrace_frame_data_t frame;
Christopher Ferrisabf39bb2014-01-17 19:56:04770 frame.num = 1;
771 frame.pc = 2;
Christopher Ferris9dccd512017-07-20 04:08:49772 frame.rel_pc = 2;
Christopher Ferrisabf39bb2014-01-17 19:56:04773 frame.sp = 0;
774 frame.stack_size = 0;
Christopher Ferrisabf39bb2014-01-17 19:56:04775 frame.func_offset = 0;
Christopher Ferris20bc65f2013-10-29 20:56:52776
Christopher Ferrisabf39bb2014-01-17 19:56:04777 // Check no map set.
Christopher Ferris737b6a12014-01-14 02:12:04778 frame.num = 1;
Christopher Ferris20bc65f2013-10-29 20:56:52779#if defined(__LP64__)
Christopher Ferrisabf39bb2014-01-17 19:56:04780 EXPECT_EQ("#01 pc 0000000000000002 <unknown>",
Christopher Ferris20bc65f2013-10-29 20:56:52781#else
Christopher Ferrisabf39bb2014-01-17 19:56:04782 EXPECT_EQ("#01 pc 00000002 <unknown>",
Christopher Ferris20bc65f2013-10-29 20:56:52783#endif
Christopher Ferrisabf39bb2014-01-17 19:56:04784 backtrace->FormatFrameData(&frame));
Christopher Ferris20bc65f2013-10-29 20:56:52785
Christopher Ferrisabf39bb2014-01-17 19:56:04786 // Check map name empty, but exists.
Christopher Ferrisd63bd3d2015-12-01 00:42:38787 frame.pc = 0xb0020;
Christopher Ferris9dccd512017-07-20 04:08:49788 frame.rel_pc = 0x20;
Christopher Ferrisd63bd3d2015-12-01 00:42:38789 frame.map.start = 0xb0000;
790 frame.map.end = 0xbffff;
Christopher Ferris9dccd512017-07-20 04:08:49791 frame.map.load_bias = 0;
Christopher Ferris20bc65f2013-10-29 20:56:52792#if defined(__LP64__)
Christopher Ferrisd63bd3d2015-12-01 00:42:38793 EXPECT_EQ("#01 pc 0000000000000020 <anonymous:00000000000b0000>",
Christopher Ferris20bc65f2013-10-29 20:56:52794#else
Christopher Ferrisd63bd3d2015-12-01 00:42:38795 EXPECT_EQ("#01 pc 00000020 <anonymous:000b0000>",
Christopher Ferris20bc65f2013-10-29 20:56:52796#endif
Christopher Ferrisabf39bb2014-01-17 19:56:04797 backtrace->FormatFrameData(&frame));
Christopher Ferris20bc65f2013-10-29 20:56:52798
Christopher Ferrisd63bd3d2015-12-01 00:42:38799 // Check map name begins with a [.
800 frame.pc = 0xc0020;
801 frame.map.start = 0xc0000;
802 frame.map.end = 0xcffff;
Christopher Ferris9dccd512017-07-20 04:08:49803 frame.map.load_bias = 0;
Christopher Ferrisd63bd3d2015-12-01 00:42:38804 frame.map.name = "[anon:thread signal stack]";
805#if defined(__LP64__)
806 EXPECT_EQ("#01 pc 0000000000000020 [anon:thread signal stack:00000000000c0000]",
807#else
808 EXPECT_EQ("#01 pc 00000020 [anon:thread signal stack:000c0000]",
809#endif
810 backtrace->FormatFrameData(&frame));
Christopher Ferrisabf39bb2014-01-17 19:56:04811
812 // Check relative pc is set and map name is set.
813 frame.pc = 0x12345679;
Christopher Ferris9dccd512017-07-20 04:08:49814 frame.rel_pc = 0x12345678;
Christopher Ferris8df2ce72015-02-09 04:13:37815 frame.map.name = "MapFake";
816 frame.map.start = 1;
817 frame.map.end = 1;
Christopher Ferris20bc65f2013-10-29 20:56:52818#if defined(__LP64__)
Christopher Ferrisabf39bb2014-01-17 19:56:04819 EXPECT_EQ("#01 pc 0000000012345678 MapFake",
Christopher Ferris20bc65f2013-10-29 20:56:52820#else
Christopher Ferrisabf39bb2014-01-17 19:56:04821 EXPECT_EQ("#01 pc 12345678 MapFake",
Christopher Ferris20bc65f2013-10-29 20:56:52822#endif
Christopher Ferrisabf39bb2014-01-17 19:56:04823 backtrace->FormatFrameData(&frame));
Christopher Ferris20bc65f2013-10-29 20:56:52824
Christopher Ferrisabf39bb2014-01-17 19:56:04825 // Check func_name is set, but no func offset.
826 frame.func_name = "ProcFake";
827#if defined(__LP64__)
828 EXPECT_EQ("#01 pc 0000000012345678 MapFake (ProcFake)",
829#else
830 EXPECT_EQ("#01 pc 12345678 MapFake (ProcFake)",
831#endif
832 backtrace->FormatFrameData(&frame));
833
834 // Check func_name is set, and func offset is non-zero.
Christopher Ferris737b6a12014-01-14 02:12:04835 frame.func_offset = 645;
Christopher Ferris20bc65f2013-10-29 20:56:52836#if defined(__LP64__)
Christopher Ferrisabf39bb2014-01-17 19:56:04837 EXPECT_EQ("#01 pc 0000000012345678 MapFake (ProcFake+645)",
Christopher Ferris20bc65f2013-10-29 20:56:52838#else
Christopher Ferrisabf39bb2014-01-17 19:56:04839 EXPECT_EQ("#01 pc 12345678 MapFake (ProcFake+645)",
Christopher Ferris20bc65f2013-10-29 20:56:52840#endif
Christopher Ferrisabf39bb2014-01-17 19:56:04841 backtrace->FormatFrameData(&frame));
Christopher Ferrisc53388d2015-05-02 00:46:19842
Christopher Ferris9dccd512017-07-20 04:08:49843 // Check func_name is set, func offset is non-zero, and load_bias is non-zero.
844 frame.rel_pc = 0x123456dc;
Christopher Ferrisc53388d2015-05-02 00:46:19845 frame.func_offset = 645;
Christopher Ferris9dccd512017-07-20 04:08:49846 frame.map.load_bias = 100;
Christopher Ferrisc53388d2015-05-02 00:46:19847#if defined(__LP64__)
848 EXPECT_EQ("#01 pc 00000000123456dc MapFake (ProcFake+645)",
849#else
850 EXPECT_EQ("#01 pc 123456dc MapFake (ProcFake+645)",
851#endif
852 backtrace->FormatFrameData(&frame));
Christopher Ferris136db2a2015-08-20 22:01:38853
854 // Check a non-zero map offset.
855 frame.map.offset = 0x1000;
856#if defined(__LP64__)
857 EXPECT_EQ("#01 pc 00000000123456dc MapFake (offset 0x1000) (ProcFake+645)",
858#else
859 EXPECT_EQ("#01 pc 123456dc MapFake (offset 0x1000) (ProcFake+645)",
860#endif
861 backtrace->FormatFrameData(&frame));
Christopher Ferris20bc65f2013-10-29 20:56:52862}
Christopher Ferrisf994e562014-04-04 03:19:39863
864struct map_test_t {
Christopher Ferris103f4572018-01-19 23:38:38865 uint64_t start;
866 uint64_t end;
Christopher Ferrisf994e562014-04-04 03:19:39867};
868
Christopher Ferris25dc7302017-03-22 17:41:01869static bool map_sort(map_test_t i, map_test_t j) { return i.start < j.start; }
Christopher Ferrisf994e562014-04-04 03:19:39870
Christopher Ferris4102ba02017-12-05 23:43:27871static std::string GetTestMapsAsString(const std::vector<map_test_t>& maps) {
872 if (maps.size() == 0) {
873 return "No test map entries\n";
874 }
875 std::string map_txt;
876 for (auto map : maps) {
Christopher Ferris103f4572018-01-19 23:38:38877 map_txt += android::base::StringPrintf("%" PRIx64 "-%" PRIx64 "\n", map.start, map.end);
Christopher Ferris4102ba02017-12-05 23:43:27878 }
879 return map_txt;
880}
881
882static std::string GetMapsAsString(BacktraceMap* maps) {
883 if (maps->size() == 0) {
884 return "No map entries\n";
885 }
886 std::string map_txt;
887 for (const backtrace_map_t* map : *maps) {
888 map_txt += android::base::StringPrintf(
Christopher Ferris103f4572018-01-19 23:38:38889 "%" PRIx64 "-%" PRIx64 " flags: 0x%x offset: 0x%" PRIx64 " load_bias: 0x%" PRIx64,
Christopher Ferris4102ba02017-12-05 23:43:27890 map->start, map->end, map->flags, map->offset, map->load_bias);
891 if (!map->name.empty()) {
892 map_txt += ' ' + map->name;
893 }
894 map_txt += '\n';
895 }
896 return map_txt;
897}
898
Christopher Ferris25dc7302017-03-22 17:41:01899static void VerifyMap(pid_t pid) {
Christopher Ferrisf994e562014-04-04 03:19:39900 char buffer[4096];
901 snprintf(buffer, sizeof(buffer), "/proc/%d/maps", pid);
902
903 FILE* map_file = fopen(buffer, "r");
Christopher Ferrisb487b312015-03-18 10:57:38904 ASSERT_TRUE(map_file != nullptr);
Christopher Ferrisf994e562014-04-04 03:19:39905 std::vector<map_test_t> test_maps;
906 while (fgets(buffer, sizeof(buffer), map_file)) {
907 map_test_t map;
Christopher Ferris103f4572018-01-19 23:38:38908 ASSERT_EQ(2, sscanf(buffer, "%" SCNx64 "-%" SCNx64 " ", &map.start, &map.end));
Christopher Ferrisf994e562014-04-04 03:19:39909 test_maps.push_back(map);
910 }
911 fclose(map_file);
912 std::sort(test_maps.begin(), test_maps.end(), map_sort);
913
Christopher Ferrisb487b312015-03-18 10:57:38914 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(pid));
Christopher Ferrisf994e562014-04-04 03:19:39915
916 // Basic test that verifies that the map is in the expected order.
Christopher Ferris4102ba02017-12-05 23:43:27917 auto test_it = test_maps.begin();
918 for (auto it = map->begin(); it != map->end(); ++it) {
919 ASSERT_TRUE(test_it != test_maps.end()) << "Mismatch in number of maps, expected test maps:\n"
920 << GetTestMapsAsString(test_maps) << "Actual maps:\n"
921 << GetMapsAsString(map.get());
922 ASSERT_EQ(test_it->start, (*it)->start) << "Mismatch in map data, expected test maps:\n"
923 << GetTestMapsAsString(test_maps) << "Actual maps:\n"
924 << GetMapsAsString(map.get());
925 ASSERT_EQ(test_it->end, (*it)->end) << "Mismatch maps in map data, expected test maps:\n"
926 << GetTestMapsAsString(test_maps) << "Actual maps:\n"
927 << GetMapsAsString(map.get());
928 // Make sure the load bias get set to a value.
929 ASSERT_NE(static_cast<uint64_t>(-1), (*it)->load_bias) << "Found uninitialized load_bias\n"
930 << GetMapsAsString(map.get());
Christopher Ferrisf994e562014-04-04 03:19:39931 ++test_it;
932 }
933 ASSERT_TRUE(test_it == test_maps.end());
934}
935
936TEST(libbacktrace, verify_map_remote) {
937 pid_t pid;
Christopher Ferris25dc7302017-03-22 17:41:01938 CreateRemoteProcess(&pid);
Christopher Ferrisf994e562014-04-04 03:19:39939
940 // The maps should match exactly since the forked process has been paused.
941 VerifyMap(pid);
942
Christopher Ferris25dc7302017-03-22 17:41:01943 FinishRemoteProcess(pid);
Christopher Ferrisb487b312015-03-18 10:57:38944}
945
Christopher Ferris25dc7302017-03-22 17:41:01946static void InitMemory(uint8_t* memory, size_t bytes) {
Christopher Ferris3e601aa2015-05-07 08:18:21947 for (size_t i = 0; i < bytes; i++) {
948 memory[i] = i;
949 if (memory[i] == '\0') {
950 // Don't use '\0' in our data so we can verify that an overread doesn't
951 // occur by using a '\0' as the character after the read data.
952 memory[i] = 23;
953 }
954 }
955}
956
Christopher Ferris25dc7302017-03-22 17:41:01957static void* ThreadReadTest(void* data) {
Christopher Ferrisb487b312015-03-18 10:57:38958 thread_t* thread_data = reinterpret_cast<thread_t*>(data);
959
960 thread_data->tid = gettid();
961
962 // Create two map pages.
963 // Mark the second page as not-readable.
964 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
965 uint8_t* memory;
966 if (posix_memalign(reinterpret_cast<void**>(&memory), pagesize, 2 * pagesize) != 0) {
967 return reinterpret_cast<void*>(-1);
968 }
969
970 if (mprotect(&memory[pagesize], pagesize, PROT_NONE) != 0) {
971 return reinterpret_cast<void*>(-1);
972 }
973
974 // Set up a simple pattern in memory.
Christopher Ferris3e601aa2015-05-07 08:18:21975 InitMemory(memory, pagesize);
Christopher Ferrisb487b312015-03-18 10:57:38976
977 thread_data->data = memory;
978
979 // Tell the caller it's okay to start reading memory.
980 android_atomic_acquire_store(1, &thread_data->state);
981
Christopher Ferriscc629982015-03-31 23:01:28982 // Loop waiting for the caller to finish reading the memory.
Christopher Ferrisb487b312015-03-18 10:57:38983 while (thread_data->state) {
984 }
985
Christopher Ferriscc629982015-03-31 23:01:28986 // Re-enable read-write on the page so that we don't crash if we try
987 // and access data on this page when freeing the memory.
988 if (mprotect(&memory[pagesize], pagesize, PROT_READ | PROT_WRITE) != 0) {
989 return reinterpret_cast<void*>(-1);
990 }
Christopher Ferrisb487b312015-03-18 10:57:38991 free(memory);
992
993 android_atomic_acquire_store(1, &thread_data->state);
994
995 return nullptr;
996}
997
Christopher Ferris103f4572018-01-19 23:38:38998static void RunReadTest(Backtrace* backtrace, uint64_t read_addr) {
Christopher Ferrisb487b312015-03-18 10:57:38999 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
1000
1001 // Create a page of data to use to do quick compares.
1002 uint8_t* expected = new uint8_t[pagesize];
Christopher Ferris3e601aa2015-05-07 08:18:211003 InitMemory(expected, pagesize);
1004
Christopher Ferris703a27f2018-01-30 15:44:361005 uint8_t* data = new uint8_t[2 * pagesize];
Christopher Ferrisb487b312015-03-18 10:57:381006 // Verify that we can only read one page worth of data.
1007 size_t bytes_read = backtrace->Read(read_addr, data, 2 * pagesize);
1008 ASSERT_EQ(pagesize, bytes_read);
1009 ASSERT_TRUE(memcmp(data, expected, pagesize) == 0);
1010
1011 // Verify unaligned reads.
1012 for (size_t i = 1; i < sizeof(word_t); i++) {
1013 bytes_read = backtrace->Read(read_addr + i, data, 2 * sizeof(word_t));
1014 ASSERT_EQ(2 * sizeof(word_t), bytes_read);
1015 ASSERT_TRUE(memcmp(data, &expected[i], 2 * sizeof(word_t)) == 0)
1016 << "Offset at " << i << " failed";
1017 }
Christopher Ferris3e601aa2015-05-07 08:18:211018
1019 // Verify small unaligned reads.
1020 for (size_t i = 1; i < sizeof(word_t); i++) {
1021 for (size_t j = 1; j < sizeof(word_t); j++) {
1022 // Set one byte past what we expect to read, to guarantee we don't overread.
1023 data[j] = '\0';
1024 bytes_read = backtrace->Read(read_addr + i, data, j);
1025 ASSERT_EQ(j, bytes_read);
1026 ASSERT_TRUE(memcmp(data, &expected[i], j) == 0)
1027 << "Offset at " << i << " length " << j << " miscompared";
1028 ASSERT_EQ('\0', data[j])
1029 << "Offset at " << i << " length " << j << " wrote too much data";
1030 }
1031 }
Pirama Arumuga Nainara69a7fd2015-07-09 23:18:141032 delete[] data;
1033 delete[] expected;
Christopher Ferrisb487b312015-03-18 10:57:381034}
1035
1036TEST(libbacktrace, thread_read) {
1037 pthread_attr_t attr;
1038 pthread_attr_init(&attr);
1039 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1040 pthread_t thread;
1041 thread_t thread_data = { 0, 0, 0, nullptr };
1042 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadReadTest, &thread_data) == 0);
1043
1044 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10));
1045
1046 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
1047 ASSERT_TRUE(backtrace.get() != nullptr);
1048
Christopher Ferris103f4572018-01-19 23:38:381049 RunReadTest(backtrace.get(), reinterpret_cast<uint64_t>(thread_data.data));
Christopher Ferrisb487b312015-03-18 10:57:381050
1051 android_atomic_acquire_store(0, &thread_data.state);
1052
1053 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10));
1054}
1055
Christopher Ferris703a27f2018-01-30 15:44:361056// The code requires these variables are the same size.
Christopher Ferris103f4572018-01-19 23:38:381057volatile uint64_t g_ready = 0;
1058volatile uint64_t g_addr = 0;
Christopher Ferris703a27f2018-01-30 15:44:361059static_assert(sizeof(g_ready) == sizeof(g_addr), "g_ready/g_addr must be same size");
Christopher Ferrisb487b312015-03-18 10:57:381060
Christopher Ferris25dc7302017-03-22 17:41:011061static void ForkedReadTest() {
Christopher Ferrisb487b312015-03-18 10:57:381062 // Create two map pages.
1063 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
1064 uint8_t* memory;
1065 if (posix_memalign(reinterpret_cast<void**>(&memory), pagesize, 2 * pagesize) != 0) {
1066 perror("Failed to allocate memory\n");
1067 exit(1);
1068 }
1069
1070 // Mark the second page as not-readable.
1071 if (mprotect(&memory[pagesize], pagesize, PROT_NONE) != 0) {
1072 perror("Failed to mprotect memory\n");
1073 exit(1);
1074 }
1075
1076 // Set up a simple pattern in memory.
Christopher Ferris3e601aa2015-05-07 08:18:211077 InitMemory(memory, pagesize);
Christopher Ferrisb487b312015-03-18 10:57:381078
Christopher Ferris103f4572018-01-19 23:38:381079 g_addr = reinterpret_cast<uint64_t>(memory);
Christopher Ferrisb487b312015-03-18 10:57:381080 g_ready = 1;
1081
1082 while (1) {
1083 usleep(US_PER_MSEC);
1084 }
1085}
1086
1087TEST(libbacktrace, process_read) {
Christopher Ferris386a23e2015-05-13 18:47:241088 g_ready = 0;
Christopher Ferrisb487b312015-03-18 10:57:381089 pid_t pid;
1090 if ((pid = fork()) == 0) {
1091 ForkedReadTest();
1092 exit(0);
1093 }
1094 ASSERT_NE(-1, pid);
1095
1096 bool test_executed = false;
1097 uint64_t start = NanoTime();
1098 while (1) {
1099 if (ptrace(PTRACE_ATTACH, pid, 0, 0) == 0) {
1100 WaitForStop(pid);
1101
1102 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
Christopher Ferris04f818f2015-04-03 14:52:561103 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferrisb487b312015-03-18 10:57:381104
Christopher Ferris103f4572018-01-19 23:38:381105 uint64_t read_addr;
1106 size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
Christopher Ferris703a27f2018-01-30 15:44:361107 reinterpret_cast<uint8_t*>(&read_addr), sizeof(g_ready));
1108 ASSERT_EQ(sizeof(g_ready), bytes_read);
Christopher Ferrisb487b312015-03-18 10:57:381109 if (read_addr) {
1110 // The forked process is ready to be read.
Christopher Ferris103f4572018-01-19 23:38:381111 bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
Christopher Ferris703a27f2018-01-30 15:44:361112 reinterpret_cast<uint8_t*>(&read_addr), sizeof(g_addr));
1113 ASSERT_EQ(sizeof(g_addr), bytes_read);
Christopher Ferrisb487b312015-03-18 10:57:381114
1115 RunReadTest(backtrace.get(), read_addr);
1116
1117 test_executed = true;
1118 break;
1119 }
1120 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1121 }
1122 if ((NanoTime() - start) > 5 * NS_PER_SEC) {
1123 break;
1124 }
1125 usleep(US_PER_MSEC);
1126 }
1127 kill(pid, SIGKILL);
1128 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
1129
1130 ASSERT_TRUE(test_executed);
Christopher Ferrisf994e562014-04-04 03:19:391131}
1132
Christopher Ferris25dc7302017-03-22 17:41:011133static void VerifyFunctionsFound(const std::vector<std::string>& found_functions) {
Christopher Ferris386a23e2015-05-13 18:47:241134 // We expect to find these functions in libbacktrace_test. If we don't
1135 // find them, that's a bug in the memory read handling code in libunwind.
1136 std::list<std::string> expected_functions;
1137 expected_functions.push_back("test_recursive_call");
1138 expected_functions.push_back("test_level_one");
1139 expected_functions.push_back("test_level_two");
1140 expected_functions.push_back("test_level_three");
1141 expected_functions.push_back("test_level_four");
1142 for (const auto& found_function : found_functions) {
1143 for (const auto& expected_function : expected_functions) {
1144 if (found_function == expected_function) {
1145 expected_functions.remove(found_function);
1146 break;
1147 }
1148 }
1149 }
1150 ASSERT_TRUE(expected_functions.empty()) << "Not all functions found in shared library.";
1151}
1152
Christopher Ferris25dc7302017-03-22 17:41:011153static const char* CopySharedLibrary() {
Christopher Ferris386a23e2015-05-13 18:47:241154#if defined(__LP64__)
1155 const char* lib_name = "lib64";
1156#else
1157 const char* lib_name = "lib";
1158#endif
1159
1160#if defined(__BIONIC__)
1161 const char* tmp_so_name = "/data/local/tmp/libbacktrace_test.so";
1162 std::string cp_cmd = android::base::StringPrintf("cp /system/%s/libbacktrace_test.so %s",
1163 lib_name, tmp_so_name);
1164#else
1165 const char* tmp_so_name = "/tmp/libbacktrace_test.so";
1166 if (getenv("ANDROID_HOST_OUT") == NULL) {
1167 fprintf(stderr, "ANDROID_HOST_OUT not set, make sure you run lunch.");
1168 return nullptr;
1169 }
1170 std::string cp_cmd = android::base::StringPrintf("cp %s/%s/libbacktrace_test.so %s",
1171 getenv("ANDROID_HOST_OUT"), lib_name,
1172 tmp_so_name);
1173#endif
1174
1175 // Copy the shared so to a tempory directory.
1176 system(cp_cmd.c_str());
1177
1178 return tmp_so_name;
1179}
1180
1181TEST(libbacktrace, check_unreadable_elf_local) {
1182 const char* tmp_so_name = CopySharedLibrary();
1183 ASSERT_TRUE(tmp_so_name != nullptr);
1184
1185 struct stat buf;
1186 ASSERT_TRUE(stat(tmp_so_name, &buf) != -1);
Christopher Ferris103f4572018-01-19 23:38:381187 uint64_t map_size = buf.st_size;
Christopher Ferris386a23e2015-05-13 18:47:241188
1189 int fd = open(tmp_so_name, O_RDONLY);
1190 ASSERT_TRUE(fd != -1);
1191
Christopher Ferris703a27f2018-01-30 15:44:361192 void* map = mmap(nullptr, map_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
Christopher Ferris386a23e2015-05-13 18:47:241193 ASSERT_TRUE(map != MAP_FAILED);
1194 close(fd);
1195 ASSERT_TRUE(unlink(tmp_so_name) != -1);
1196
1197 std::vector<std::string> found_functions;
1198 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS,
1199 BACKTRACE_CURRENT_THREAD));
1200 ASSERT_TRUE(backtrace.get() != nullptr);
1201
1202 // Needed before GetFunctionName will work.
1203 backtrace->Unwind(0);
1204
1205 // Loop through the entire map, and get every function we can find.
Christopher Ferris103f4572018-01-19 23:38:381206 map_size += reinterpret_cast<uint64_t>(map);
Christopher Ferris386a23e2015-05-13 18:47:241207 std::string last_func;
Christopher Ferris103f4572018-01-19 23:38:381208 for (uint64_t read_addr = reinterpret_cast<uint64_t>(map); read_addr < map_size; read_addr += 4) {
1209 uint64_t offset;
Christopher Ferris386a23e2015-05-13 18:47:241210 std::string func_name = backtrace->GetFunctionName(read_addr, &offset);
1211 if (!func_name.empty() && last_func != func_name) {
1212 found_functions.push_back(func_name);
1213 }
1214 last_func = func_name;
1215 }
1216
Christopher Ferris103f4572018-01-19 23:38:381217 ASSERT_TRUE(munmap(map, map_size - reinterpret_cast<uint64_t>(map)) == 0);
Christopher Ferris386a23e2015-05-13 18:47:241218
1219 VerifyFunctionsFound(found_functions);
1220}
1221
1222TEST(libbacktrace, check_unreadable_elf_remote) {
1223 const char* tmp_so_name = CopySharedLibrary();
1224 ASSERT_TRUE(tmp_so_name != nullptr);
1225
1226 g_ready = 0;
1227
1228 struct stat buf;
1229 ASSERT_TRUE(stat(tmp_so_name, &buf) != -1);
Christopher Ferris103f4572018-01-19 23:38:381230 uint64_t map_size = buf.st_size;
Christopher Ferris386a23e2015-05-13 18:47:241231
1232 pid_t pid;
1233 if ((pid = fork()) == 0) {
1234 int fd = open(tmp_so_name, O_RDONLY);
1235 if (fd == -1) {
1236 fprintf(stderr, "Failed to open file %s: %s\n", tmp_so_name, strerror(errno));
1237 unlink(tmp_so_name);
1238 exit(0);
1239 }
1240
Christopher Ferris703a27f2018-01-30 15:44:361241 void* map = mmap(nullptr, map_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
Christopher Ferris386a23e2015-05-13 18:47:241242 if (map == MAP_FAILED) {
1243 fprintf(stderr, "Failed to map in memory: %s\n", strerror(errno));
1244 unlink(tmp_so_name);
1245 exit(0);
1246 }
1247 close(fd);
1248 if (unlink(tmp_so_name) == -1) {
1249 fprintf(stderr, "Failed to unlink: %s\n", strerror(errno));
1250 exit(0);
1251 }
1252
Christopher Ferris103f4572018-01-19 23:38:381253 g_addr = reinterpret_cast<uint64_t>(map);
Christopher Ferris386a23e2015-05-13 18:47:241254 g_ready = 1;
1255 while (true) {
1256 usleep(US_PER_MSEC);
1257 }
1258 exit(0);
1259 }
1260 ASSERT_TRUE(pid > 0);
1261
1262 std::vector<std::string> found_functions;
1263 uint64_t start = NanoTime();
1264 while (true) {
1265 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1266
1267 // Wait for the process to get to a stopping point.
1268 WaitForStop(pid);
1269
1270 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
1271 ASSERT_TRUE(backtrace.get() != nullptr);
1272
Christopher Ferris103f4572018-01-19 23:38:381273 uint64_t read_addr;
Christopher Ferris703a27f2018-01-30 15:44:361274 ASSERT_EQ(sizeof(g_ready),
Christopher Ferris103f4572018-01-19 23:38:381275 backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
Christopher Ferris703a27f2018-01-30 15:44:361276 reinterpret_cast<uint8_t*>(&read_addr), sizeof(g_ready)));
Christopher Ferris386a23e2015-05-13 18:47:241277 if (read_addr) {
Christopher Ferris703a27f2018-01-30 15:44:361278 ASSERT_EQ(sizeof(g_addr),
Christopher Ferris103f4572018-01-19 23:38:381279 backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
1280 reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t)));
Christopher Ferris386a23e2015-05-13 18:47:241281
1282 // Needed before GetFunctionName will work.
1283 backtrace->Unwind(0);
1284
1285 // Loop through the entire map, and get every function we can find.
1286 map_size += read_addr;
1287 std::string last_func;
1288 for (; read_addr < map_size; read_addr += 4) {
Christopher Ferris103f4572018-01-19 23:38:381289 uint64_t offset;
Christopher Ferris386a23e2015-05-13 18:47:241290 std::string func_name = backtrace->GetFunctionName(read_addr, &offset);
1291 if (!func_name.empty() && last_func != func_name) {
1292 found_functions.push_back(func_name);
1293 }
1294 last_func = func_name;
1295 }
1296 break;
1297 }
1298 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1299
1300 if ((NanoTime() - start) > 5 * NS_PER_SEC) {
1301 break;
1302 }
1303 usleep(US_PER_MSEC);
1304 }
1305
1306 kill(pid, SIGKILL);
1307 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
1308
1309 VerifyFunctionsFound(found_functions);
1310}
1311
Christopher Ferris103f4572018-01-19 23:38:381312static bool FindFuncFrameInBacktrace(Backtrace* backtrace, uint64_t test_func, size_t* frame_num) {
Christopher Ferris386a23e2015-05-13 18:47:241313 backtrace_map_t map;
1314 backtrace->FillInMap(test_func, &map);
1315 if (!BacktraceMap::IsValid(map)) {
1316 return false;
1317 }
1318
1319 // Loop through the frames, and find the one that is in the map.
1320 *frame_num = 0;
1321 for (Backtrace::const_iterator it = backtrace->begin(); it != backtrace->end(); ++it) {
1322 if (BacktraceMap::IsValid(it->map) && map.start == it->map.start &&
1323 it->pc >= test_func) {
1324 *frame_num = it->num;
1325 return true;
1326 }
1327 }
1328 return false;
1329}
1330
Christopher Ferris103f4572018-01-19 23:38:381331static void VerifyUnreadableElfFrame(Backtrace* backtrace, uint64_t test_func, size_t frame_num) {
Christopher Ferris386a23e2015-05-13 18:47:241332 ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
1333 << DumpFrames(backtrace);
1334
1335 ASSERT_TRUE(frame_num != 0) << DumpFrames(backtrace);
1336 // Make sure that there is at least one more frame above the test func call.
1337 ASSERT_LT(frame_num, backtrace->NumFrames()) << DumpFrames(backtrace);
1338
Christopher Ferris103f4572018-01-19 23:38:381339 uint64_t diff = backtrace->GetFrame(frame_num)->pc - test_func;
Christopher Ferris386a23e2015-05-13 18:47:241340 ASSERT_LT(diff, 200U) << DumpFrames(backtrace);
1341}
1342
Christopher Ferris103f4572018-01-19 23:38:381343static void VerifyUnreadableElfBacktrace(void* func) {
Christopher Ferris386a23e2015-05-13 18:47:241344 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS,
1345 BACKTRACE_CURRENT_THREAD));
1346 ASSERT_TRUE(backtrace.get() != nullptr);
1347 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:361348 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris386a23e2015-05-13 18:47:241349
1350 size_t frame_num;
Christopher Ferris703a27f2018-01-30 15:44:361351 uint64_t test_func = reinterpret_cast<uint64_t>(func);
1352 ASSERT_TRUE(FindFuncFrameInBacktrace(backtrace.get(), test_func, &frame_num))
1353 << DumpFrames(backtrace.get());
Christopher Ferris386a23e2015-05-13 18:47:241354
1355 VerifyUnreadableElfFrame(backtrace.get(), test_func, frame_num);
1356}
1357
Christopher Ferris103f4572018-01-19 23:38:381358typedef int (*test_func_t)(int, int, int, int, void (*)(void*), void*);
Christopher Ferris386a23e2015-05-13 18:47:241359
1360TEST(libbacktrace, unwind_through_unreadable_elf_local) {
1361 const char* tmp_so_name = CopySharedLibrary();
1362 ASSERT_TRUE(tmp_so_name != nullptr);
1363 void* lib_handle = dlopen(tmp_so_name, RTLD_NOW);
1364 ASSERT_TRUE(lib_handle != nullptr);
1365 ASSERT_TRUE(unlink(tmp_so_name) != -1);
1366
1367 test_func_t test_func;
1368 test_func = reinterpret_cast<test_func_t>(dlsym(lib_handle, "test_level_one"));
1369 ASSERT_TRUE(test_func != nullptr);
1370
Christopher Ferris103f4572018-01-19 23:38:381371 ASSERT_NE(test_func(1, 2, 3, 4, VerifyUnreadableElfBacktrace, reinterpret_cast<void*>(test_func)),
1372 0);
Christopher Ferris386a23e2015-05-13 18:47:241373
1374 ASSERT_TRUE(dlclose(lib_handle) == 0);
1375}
1376
1377TEST(libbacktrace, unwind_through_unreadable_elf_remote) {
1378 const char* tmp_so_name = CopySharedLibrary();
1379 ASSERT_TRUE(tmp_so_name != nullptr);
1380 void* lib_handle = dlopen(tmp_so_name, RTLD_NOW);
1381 ASSERT_TRUE(lib_handle != nullptr);
1382 ASSERT_TRUE(unlink(tmp_so_name) != -1);
1383
1384 test_func_t test_func;
1385 test_func = reinterpret_cast<test_func_t>(dlsym(lib_handle, "test_level_one"));
1386 ASSERT_TRUE(test_func != nullptr);
1387
1388 pid_t pid;
1389 if ((pid = fork()) == 0) {
1390 test_func(1, 2, 3, 4, 0, 0);
1391 exit(0);
1392 }
1393 ASSERT_TRUE(pid > 0);
1394 ASSERT_TRUE(dlclose(lib_handle) == 0);
1395
1396 uint64_t start = NanoTime();
1397 bool done = false;
1398 while (!done) {
1399 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1400
1401 // Wait for the process to get to a stopping point.
1402 WaitForStop(pid);
1403
1404 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
1405 ASSERT_TRUE(backtrace.get() != nullptr);
1406 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:361407 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris386a23e2015-05-13 18:47:241408
1409 size_t frame_num;
Christopher Ferris103f4572018-01-19 23:38:381410 if (FindFuncFrameInBacktrace(backtrace.get(), reinterpret_cast<uint64_t>(test_func),
1411 &frame_num)) {
1412 VerifyUnreadableElfFrame(backtrace.get(), reinterpret_cast<uint64_t>(test_func), frame_num);
Christopher Ferris386a23e2015-05-13 18:47:241413 done = true;
1414 }
1415
1416 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1417
1418 if ((NanoTime() - start) > 5 * NS_PER_SEC) {
1419 break;
1420 }
1421 usleep(US_PER_MSEC);
1422 }
1423
1424 kill(pid, SIGKILL);
1425 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
1426
1427 ASSERT_TRUE(done) << "Test function never found in unwind.";
1428}
1429
Christopher Ferris5297f492016-03-10 22:32:051430TEST(libbacktrace, unwind_thread_doesnt_exist) {
1431 std::unique_ptr<Backtrace> backtrace(
1432 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, 99999999));
1433 ASSERT_TRUE(backtrace.get() != nullptr);
1434 ASSERT_FALSE(backtrace->Unwind(0));
Yabin Cuicc1ac012017-12-16 20:43:541435 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST, backtrace->GetError().error_code);
Christopher Ferris5297f492016-03-10 22:32:051436}
1437
Christopher Ferris25dc7302017-03-22 17:41:011438TEST(libbacktrace, local_get_function_name_before_unwind) {
1439 std::unique_ptr<Backtrace> backtrace(
1440 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
1441 ASSERT_TRUE(backtrace.get() != nullptr);
1442
1443 // Verify that trying to get a function name before doing an unwind works.
Christopher Ferris103f4572018-01-19 23:38:381444 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
1445 uint64_t offset;
Christopher Ferris25dc7302017-03-22 17:41:011446 ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
1447}
1448
1449TEST(libbacktrace, remote_get_function_name_before_unwind) {
1450 pid_t pid;
1451 CreateRemoteProcess(&pid);
1452
1453 // Now create an unwind object.
1454 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
1455
1456 // Verify that trying to get a function name before doing an unwind works.
Christopher Ferris103f4572018-01-19 23:38:381457 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
1458 uint64_t offset;
Christopher Ferris25dc7302017-03-22 17:41:011459 ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
1460
1461 FinishRemoteProcess(pid);
1462}
1463
Christopher Ferris103f4572018-01-19 23:38:381464static void SetUcontextSp(uint64_t sp, ucontext_t* ucontext) {
Christopher Ferris96e504b2017-03-23 01:18:381465#if defined(__arm__)
1466 ucontext->uc_mcontext.arm_sp = sp;
1467#elif defined(__aarch64__)
1468 ucontext->uc_mcontext.sp = sp;
1469#elif defined(__i386__)
1470 ucontext->uc_mcontext.gregs[REG_ESP] = sp;
1471#elif defined(__x86_64__)
1472 ucontext->uc_mcontext.gregs[REG_RSP] = sp;
1473#else
1474 UNUSED(sp);
1475 UNUSED(ucontext);
1476 ASSERT_TRUE(false) << "Unsupported architecture";
1477#endif
1478}
1479
Christopher Ferris103f4572018-01-19 23:38:381480static void SetUcontextPc(uint64_t pc, ucontext_t* ucontext) {
Christopher Ferris96e504b2017-03-23 01:18:381481#if defined(__arm__)
1482 ucontext->uc_mcontext.arm_pc = pc;
1483#elif defined(__aarch64__)
1484 ucontext->uc_mcontext.pc = pc;
1485#elif defined(__i386__)
1486 ucontext->uc_mcontext.gregs[REG_EIP] = pc;
1487#elif defined(__x86_64__)
1488 ucontext->uc_mcontext.gregs[REG_RIP] = pc;
1489#else
1490 UNUSED(pc);
1491 UNUSED(ucontext);
1492 ASSERT_TRUE(false) << "Unsupported architecture";
1493#endif
1494}
1495
Christopher Ferris103f4572018-01-19 23:38:381496static void SetUcontextLr(uint64_t lr, ucontext_t* ucontext) {
Christopher Ferris96e504b2017-03-23 01:18:381497#if defined(__arm__)
1498 ucontext->uc_mcontext.arm_lr = lr;
1499#elif defined(__aarch64__)
1500 ucontext->uc_mcontext.regs[30] = lr;
1501#elif defined(__i386__)
1502 // The lr is on the stack.
1503 ASSERT_TRUE(lr != 0);
1504 ASSERT_TRUE(ucontext != nullptr);
1505#elif defined(__x86_64__)
1506 // The lr is on the stack.
1507 ASSERT_TRUE(lr != 0);
1508 ASSERT_TRUE(ucontext != nullptr);
1509#else
1510 UNUSED(lr);
1511 UNUSED(ucontext);
1512 ASSERT_TRUE(false) << "Unsupported architecture";
1513#endif
1514}
1515
1516static constexpr size_t DEVICE_MAP_SIZE = 1024;
1517
1518static void SetupDeviceMap(void** device_map) {
1519 // Make sure that anything in a device map will result in fails
1520 // to read.
1521 android::base::unique_fd device_fd(open("/dev/zero", O_RDONLY | O_CLOEXEC));
1522
1523 *device_map = mmap(nullptr, 1024, PROT_READ, MAP_PRIVATE, device_fd, 0);
1524 ASSERT_TRUE(*device_map != MAP_FAILED);
1525
1526 // Make sure the map is readable.
1527 ASSERT_EQ(0, reinterpret_cast<int*>(*device_map)[0]);
1528}
1529
1530static void UnwindFromDevice(Backtrace* backtrace, void* device_map) {
Christopher Ferris103f4572018-01-19 23:38:381531 uint64_t device_map_uint = reinterpret_cast<uint64_t>(device_map);
Christopher Ferris96e504b2017-03-23 01:18:381532
1533 backtrace_map_t map;
1534 backtrace->FillInMap(device_map_uint, &map);
1535 // Verify the flag is set.
1536 ASSERT_EQ(PROT_DEVICE_MAP, map.flags & PROT_DEVICE_MAP);
1537
1538 // Quick sanity checks.
Christopher Ferris103f4572018-01-19 23:38:381539 uint64_t offset;
Christopher Ferris96e504b2017-03-23 01:18:381540 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset));
1541 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset, &map));
1542 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(0, &offset));
1543
Christopher Ferris103f4572018-01-19 23:38:381544 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
Christopher Ferris96e504b2017-03-23 01:18:381545 // Now verify the device map flag actually causes the function name to be empty.
1546 backtrace->FillInMap(cur_func_offset, &map);
1547 ASSERT_TRUE((map.flags & PROT_DEVICE_MAP) == 0);
1548 ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset, &map));
1549 map.flags |= PROT_DEVICE_MAP;
1550 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset, &map));
1551
1552 ucontext_t ucontext;
1553
1554 // Create a context that has the pc in the device map, but the sp
1555 // in a non-device map.
1556 memset(&ucontext, 0, sizeof(ucontext));
Christopher Ferris103f4572018-01-19 23:38:381557 SetUcontextSp(reinterpret_cast<uint64_t>(&ucontext), &ucontext);
Christopher Ferris96e504b2017-03-23 01:18:381558 SetUcontextPc(device_map_uint, &ucontext);
1559 SetUcontextLr(cur_func_offset, &ucontext);
1560
1561 ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
1562
1563 // The buffer should only be a single element.
1564 ASSERT_EQ(1U, backtrace->NumFrames());
1565 const backtrace_frame_data_t* frame = backtrace->GetFrame(0);
1566 ASSERT_EQ(device_map_uint, frame->pc);
Christopher Ferris103f4572018-01-19 23:38:381567 ASSERT_EQ(reinterpret_cast<uint64_t>(&ucontext), frame->sp);
Christopher Ferris96e504b2017-03-23 01:18:381568
1569 // Check what happens when skipping the first frame.
1570 ASSERT_TRUE(backtrace->Unwind(1, &ucontext));
1571 ASSERT_EQ(0U, backtrace->NumFrames());
1572
1573 // Create a context that has the sp in the device map, but the pc
1574 // in a non-device map.
1575 memset(&ucontext, 0, sizeof(ucontext));
1576 SetUcontextSp(device_map_uint, &ucontext);
1577 SetUcontextPc(cur_func_offset, &ucontext);
1578 SetUcontextLr(cur_func_offset, &ucontext);
1579
1580 ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
1581
1582 // The buffer should only be a single element.
1583 ASSERT_EQ(1U, backtrace->NumFrames());
1584 frame = backtrace->GetFrame(0);
1585 ASSERT_EQ(cur_func_offset, frame->pc);
1586 ASSERT_EQ(device_map_uint, frame->sp);
1587
1588 // Check what happens when skipping the first frame.
1589 ASSERT_TRUE(backtrace->Unwind(1, &ucontext));
1590 ASSERT_EQ(0U, backtrace->NumFrames());
1591}
1592
1593TEST(libbacktrace, unwind_disallow_device_map_local) {
1594 void* device_map;
1595 SetupDeviceMap(&device_map);
1596
1597 // Now create an unwind object.
1598 std::unique_ptr<Backtrace> backtrace(
1599 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
1600 ASSERT_TRUE(backtrace);
1601
1602 UnwindFromDevice(backtrace.get(), device_map);
1603
1604 munmap(device_map, DEVICE_MAP_SIZE);
1605}
1606
Christopher Ferrisb0d1e7e2017-10-31 00:48:511607TEST(libbacktrace, unwind_disallow_device_map_remote) {
Christopher Ferris96e504b2017-03-23 01:18:381608 void* device_map;
1609 SetupDeviceMap(&device_map);
1610
1611 // Fork a process to do a remote backtrace.
1612 pid_t pid;
1613 CreateRemoteProcess(&pid);
1614
1615 // Now create an unwind object.
Christopher Ferrisb0d1e7e2017-10-31 00:48:511616 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
Christopher Ferris96e504b2017-03-23 01:18:381617
Christopher Ferris55d10c62017-08-29 17:38:311618 UnwindFromDevice(backtrace.get(), device_map);
Christopher Ferris96e504b2017-03-23 01:18:381619
1620 FinishRemoteProcess(pid);
1621
1622 munmap(device_map, DEVICE_MAP_SIZE);
1623}
1624
Christopher Ferrise622fb82017-03-24 17:31:051625class ScopedSignalHandler {
1626 public:
1627 ScopedSignalHandler(int signal_number, void (*handler)(int)) : signal_number_(signal_number) {
1628 memset(&action_, 0, sizeof(action_));
1629 action_.sa_handler = handler;
1630 sigaction(signal_number_, &action_, &old_action_);
1631 }
1632
1633 ScopedSignalHandler(int signal_number, void (*action)(int, siginfo_t*, void*))
1634 : signal_number_(signal_number) {
1635 memset(&action_, 0, sizeof(action_));
1636 action_.sa_flags = SA_SIGINFO;
1637 action_.sa_sigaction = action;
1638 sigaction(signal_number_, &action_, &old_action_);
1639 }
1640
1641 ~ScopedSignalHandler() { sigaction(signal_number_, &old_action_, nullptr); }
1642
1643 private:
1644 struct sigaction action_;
1645 struct sigaction old_action_;
1646 const int signal_number_;
1647};
1648
1649static void SetValueAndLoop(void* data) {
1650 volatile int* value = reinterpret_cast<volatile int*>(data);
1651
1652 *value = 1;
1653 for (volatile int i = 0;; i++)
1654 ;
1655}
1656
Christopher Ferris73a04f12017-09-25 19:24:071657static void UnwindThroughSignal(bool use_action, create_func_t create_func,
1658 map_create_func_t map_create_func) {
Christopher Ferrise622fb82017-03-24 17:31:051659 volatile int value = 0;
1660 pid_t pid;
1661 if ((pid = fork()) == 0) {
1662 if (use_action) {
1663 ScopedSignalHandler ssh(SIGUSR1, test_signal_action);
1664
1665 test_level_one(1, 2, 3, 4, SetValueAndLoop, const_cast<int*>(&value));
1666 } else {
1667 ScopedSignalHandler ssh(SIGUSR1, test_signal_handler);
1668
1669 test_level_one(1, 2, 3, 4, SetValueAndLoop, const_cast<int*>(&value));
1670 }
1671 }
1672 ASSERT_NE(-1, pid);
1673
1674 int read_value = 0;
1675 uint64_t start = NanoTime();
1676 while (read_value == 0) {
1677 usleep(1000);
1678
1679 // Loop until the remote function gets into the final function.
1680 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1681
1682 WaitForStop(pid);
1683
Christopher Ferris73a04f12017-09-25 19:24:071684 std::unique_ptr<BacktraceMap> map(map_create_func(pid, false));
1685 std::unique_ptr<Backtrace> backtrace(create_func(pid, pid, map.get()));
Christopher Ferrise622fb82017-03-24 17:31:051686
Christopher Ferris103f4572018-01-19 23:38:381687 size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(const_cast<int*>(&value)),
Christopher Ferrise622fb82017-03-24 17:31:051688 reinterpret_cast<uint8_t*>(&read_value), sizeof(read_value));
1689 ASSERT_EQ(sizeof(read_value), bytes_read);
1690
1691 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1692
1693 ASSERT_TRUE(NanoTime() - start < 5 * NS_PER_SEC)
1694 << "Remote process did not execute far enough in 5 seconds.";
1695 }
1696
1697 // Now need to send a signal to the remote process.
1698 kill(pid, SIGUSR1);
1699
1700 // Wait for the process to get to the signal handler loop.
1701 Backtrace::const_iterator frame_iter;
1702 start = NanoTime();
Christopher Ferris55d10c62017-08-29 17:38:311703 std::unique_ptr<BacktraceMap> map;
Christopher Ferrise622fb82017-03-24 17:31:051704 std::unique_ptr<Backtrace> backtrace;
1705 while (true) {
1706 usleep(1000);
1707
1708 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1709
1710 WaitForStop(pid);
1711
Christopher Ferris73a04f12017-09-25 19:24:071712 map.reset(map_create_func(pid, false));
Christopher Ferris55d10c62017-08-29 17:38:311713 ASSERT_TRUE(map.get() != nullptr);
Christopher Ferris73a04f12017-09-25 19:24:071714 backtrace.reset(create_func(pid, pid, map.get()));
Christopher Ferrise622fb82017-03-24 17:31:051715 ASSERT_TRUE(backtrace->Unwind(0));
1716 bool found = false;
1717 for (frame_iter = backtrace->begin(); frame_iter != backtrace->end(); ++frame_iter) {
1718 if (frame_iter->func_name == "test_loop_forever") {
1719 ++frame_iter;
1720 found = true;
1721 break;
1722 }
1723 }
1724 if (found) {
1725 break;
1726 }
1727
1728 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1729
1730 ASSERT_TRUE(NanoTime() - start < 5 * NS_PER_SEC)
1731 << "Remote process did not get in signal handler in 5 seconds." << std::endl
1732 << DumpFrames(backtrace.get());
1733 }
1734
1735 std::vector<std::string> names;
1736 // Loop through the frames, and save the function names.
1737 size_t frame = 0;
1738 for (; frame_iter != backtrace->end(); ++frame_iter) {
1739 if (frame_iter->func_name == "test_level_four") {
1740 frame = names.size() + 1;
1741 }
1742 names.push_back(frame_iter->func_name);
1743 }
1744 ASSERT_NE(0U, frame) << "Unable to find test_level_four in backtrace" << std::endl
1745 << DumpFrames(backtrace.get());
1746
1747 // The expected order of the frames:
1748 // test_loop_forever
1749 // test_signal_handler|test_signal_action
1750 // <OPTIONAL_FRAME> May or may not exist.
1751 // SetValueAndLoop (but the function name might be empty)
1752 // test_level_four
1753 // test_level_three
1754 // test_level_two
1755 // test_level_one
1756 ASSERT_LE(frame + 2, names.size()) << DumpFrames(backtrace.get());
1757 ASSERT_LE(2U, frame) << DumpFrames(backtrace.get());
1758 if (use_action) {
1759 ASSERT_EQ("test_signal_action", names[0]) << DumpFrames(backtrace.get());
1760 } else {
1761 ASSERT_EQ("test_signal_handler", names[0]) << DumpFrames(backtrace.get());
1762 }
1763 ASSERT_EQ("test_level_three", names[frame]) << DumpFrames(backtrace.get());
1764 ASSERT_EQ("test_level_two", names[frame + 1]) << DumpFrames(backtrace.get());
1765 ASSERT_EQ("test_level_one", names[frame + 2]) << DumpFrames(backtrace.get());
1766
1767 FinishRemoteProcess(pid);
1768}
1769
Christopher Ferris9dccd512017-07-20 04:08:491770TEST(libbacktrace, unwind_remote_through_signal_using_handler) {
Christopher Ferris55d10c62017-08-29 17:38:311771 UnwindThroughSignal(false, Backtrace::Create, BacktraceMap::Create);
1772}
1773
Christopher Ferris9dccd512017-07-20 04:08:491774TEST(libbacktrace, unwind_remote_through_signal_using_action) {
Christopher Ferris55d10c62017-08-29 17:38:311775 UnwindThroughSignal(true, Backtrace::Create, BacktraceMap::Create);
1776}
1777
Josh Gaoc4c75932017-10-27 00:17:541778static void TestFrameSkipNumbering(create_func_t create_func, map_create_func_t map_create_func) {
1779 std::unique_ptr<BacktraceMap> map(map_create_func(getpid(), false));
1780 std::unique_ptr<Backtrace> backtrace(create_func(getpid(), gettid(), map.get()));
1781 backtrace->Unwind(1);
1782 ASSERT_NE(0U, backtrace->NumFrames());
1783 ASSERT_EQ(0U, backtrace->GetFrame(0)->num);
1784}
1785
1786TEST(libbacktrace, unwind_frame_skip_numbering) {
1787 TestFrameSkipNumbering(Backtrace::Create, BacktraceMap::Create);
1788}
1789
Christopher Ferrisf994e562014-04-04 03:19:391790#if defined(ENABLE_PSS_TESTS)
1791#include "GetPss.h"
1792
Chih-Hung Hsieh29690dc2016-05-19 00:25:511793#define MAX_LEAK_BYTES (32*1024UL)
Christopher Ferrisf994e562014-04-04 03:19:391794
Christopher Ferris25dc7302017-03-22 17:41:011795static void CheckForLeak(pid_t pid, pid_t tid) {
Christopher Ferrisb0d1e7e2017-10-31 00:48:511796 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(pid));
1797
Christopher Ferrisf994e562014-04-04 03:19:391798 // Do a few runs to get the PSS stable.
1799 for (size_t i = 0; i < 100; i++) {
Christopher Ferrisb0d1e7e2017-10-31 00:48:511800 Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
Christopher Ferrisb487b312015-03-18 10:57:381801 ASSERT_TRUE(backtrace != nullptr);
Christopher Ferrisf994e562014-04-04 03:19:391802 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:361803 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferrisf994e562014-04-04 03:19:391804 delete backtrace;
1805 }
1806 size_t stable_pss = GetPssBytes();
Christopher Ferriscc629982015-03-31 23:01:281807 ASSERT_TRUE(stable_pss != 0);
Christopher Ferrisf994e562014-04-04 03:19:391808
1809 // Loop enough that even a small leak should be detectable.
1810 for (size_t i = 0; i < 4096; i++) {
Christopher Ferrisb0d1e7e2017-10-31 00:48:511811 Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
Christopher Ferrisb487b312015-03-18 10:57:381812 ASSERT_TRUE(backtrace != nullptr);
Christopher Ferrisf994e562014-04-04 03:19:391813 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris703a27f2018-01-30 15:44:361814 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferrisf994e562014-04-04 03:19:391815 delete backtrace;
1816 }
1817 size_t new_pss = GetPssBytes();
Christopher Ferriscc629982015-03-31 23:01:281818 ASSERT_TRUE(new_pss != 0);
Christopher Ferrisf48f6b62016-03-08 19:45:131819 if (new_pss > stable_pss) {
1820 ASSERT_LE(new_pss - stable_pss, MAX_LEAK_BYTES);
1821 }
Christopher Ferrisf994e562014-04-04 03:19:391822}
1823
1824TEST(libbacktrace, check_for_leak_local) {
1825 CheckForLeak(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD);
1826}
1827
1828TEST(libbacktrace, check_for_leak_local_thread) {
Christopher Ferrisb487b312015-03-18 10:57:381829 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferrisf994e562014-04-04 03:19:391830 pthread_t thread;
Christopher Ferrisb487b312015-03-18 10:57:381831 ASSERT_TRUE(pthread_create(&thread, nullptr, ThreadLevelRun, &thread_data) == 0);
Christopher Ferrisf994e562014-04-04 03:19:391832
1833 // Wait up to 2 seconds for the tid to be set.
1834 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
1835
1836 CheckForLeak(BACKTRACE_CURRENT_PROCESS, thread_data.tid);
1837
1838 // Tell the thread to exit its infinite loop.
1839 android_atomic_acquire_store(0, &thread_data.state);
1840
Christopher Ferrisb487b312015-03-18 10:57:381841 ASSERT_TRUE(pthread_join(thread, nullptr) == 0);
Christopher Ferrisf994e562014-04-04 03:19:391842}
1843
1844TEST(libbacktrace, check_for_leak_remote) {
1845 pid_t pid;
Christopher Ferris25dc7302017-03-22 17:41:011846 CreateRemoteProcess(&pid);
Christopher Ferrisf994e562014-04-04 03:19:391847
1848 CheckForLeak(pid, BACKTRACE_CURRENT_THREAD);
1849
Christopher Ferris25dc7302017-03-22 17:41:011850 FinishRemoteProcess(pid);
Christopher Ferrisf994e562014-04-04 03:19:391851}
1852#endif