blob: aab6db9de5862d576f432cc26f29ef94016a22ec [file] [log] [blame]
Christopher Ferris17e91d42013-10-21 13:30:52 -07001/*
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 Ferrisca09ce92015-03-31 17:28:22 -070017#define _GNU_SOURCE 1
Christopher Ferris17e91d42013-10-21 13:30:52 -070018#include <dirent.h>
Christopher Ferris67aba682015-05-08 15:44:46 -070019#include <dlfcn.h>
Christopher Ferris17e91d42013-10-21 13:30:52 -070020#include <errno.h>
Christopher Ferris67aba682015-05-08 15:44:46 -070021#include <fcntl.h>
Christopher Ferrise2960912014-03-07 19:42:19 -080022#include <inttypes.h>
Christopher Ferris17e91d42013-10-21 13:30:52 -070023#include <pthread.h>
24#include <signal.h>
Christopher Ferrise2960912014-03-07 19:42:19 -080025#include <stdint.h>
Christopher Ferris17e91d42013-10-21 13:30:52 -070026#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <sys/ptrace.h>
Christopher Ferris67aba682015-05-08 15:44:46 -070030#include <sys/stat.h>
Christopher Ferris17e91d42013-10-21 13:30:52 -070031#include <sys/types.h>
32#include <sys/wait.h>
33#include <time.h>
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -080034#include <ucontext.h>
Christopher Ferris17e91d42013-10-21 13:30:52 -070035#include <unistd.h>
36
Christopher Ferrise2960912014-03-07 19:42:19 -080037#include <algorithm>
Christopher Ferris67aba682015-05-08 15:44:46 -070038#include <list>
Christopher Ferris2b4a63f2015-03-17 14:42:03 -070039#include <memory>
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -070040#include <ostream>
Christopher Ferris2c43cff2015-03-26 19:18:36 -070041#include <string>
Christopher Ferris17e91d42013-10-21 13:30:52 -070042#include <vector>
43
Dan Albert23f750b2015-04-30 12:52:21 -070044#include <backtrace/Backtrace.h>
45#include <backtrace/BacktraceMap.h>
46
Christopher Ferrisf5e568e2017-03-22 13:18:31 -070047#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080048#include <android-base/stringprintf.h>
Christopher Ferris82f3bbd2017-03-14 15:22:26 -070049#include <android-base/unique_fd.h>
Dan Albert23f750b2015-04-30 12:52:21 -070050#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 Ferris5ea2c1f2017-03-23 14:55:01 -070057#include "backtrace_testlib.h"
Christopher Ferris17e91d42013-10-21 13:30:52 -070058#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 Ferris3cdbfdc2014-11-08 15:57:11 -080067#define NUM_THREADS 40
Christopher Ferris17e91d42013-10-21 13:30:52 -070068
69// Number of simultaneous threads running in our forked process.
70#define NUM_PTRACE_THREADS 5
71
Christopher Ferris46756822014-01-14 20:16:30 -080072struct thread_t {
Christopher Ferris17e91d42013-10-21 13:30:52 -070073 pid_t tid;
74 int32_t state;
75 pthread_t threadId;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -070076 void* data;
Christopher Ferris46756822014-01-14 20:16:30 -080077};
Christopher Ferris17e91d42013-10-21 13:30:52 -070078
Christopher Ferris46756822014-01-14 20:16:30 -080079struct dump_thread_t {
Christopher Ferris17e91d42013-10-21 13:30:52 -070080 thread_t thread;
Christopher Ferrisbe788d82017-11-27 14:50:38 -080081 BacktraceMap* map;
Christopher Ferris20303f82014-01-10 16:33:16 -080082 Backtrace* backtrace;
Christopher Ferris17e91d42013-10-21 13:30:52 -070083 int32_t* now;
84 int32_t done;
Christopher Ferris46756822014-01-14 20:16:30 -080085};
Christopher Ferris17e91d42013-10-21 13:30:52 -070086
Christopher Ferrisb9de87f2017-09-20 13:37:24 -070087typedef 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 Ferris82f3bbd2017-03-14 15:22:26 -070095static uint64_t NanoTime() {
Christopher Ferris17e91d42013-10-21 13:30:52 -070096 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 Ferris82f3bbd2017-03-14 15:22:26 -0700101static std::string DumpFrames(Backtrace* backtrace) {
Christopher Ferris20303f82014-01-10 16:33:16 -0800102 if (backtrace->NumFrames() == 0) {
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700103 return " No frames to dump.\n";
Christopher Ferris20303f82014-01-10 16:33:16 -0800104 }
105
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700106 std::string frame;
Christopher Ferris20303f82014-01-10 16:33:16 -0800107 for (size_t i = 0; i < backtrace->NumFrames(); i++) {
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700108 frame += " " + backtrace->FormatFrameData(i) + '\n';
Christopher Ferris17e91d42013-10-21 13:30:52 -0700109 }
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700110 return frame;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700111}
112
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700113static void WaitForStop(pid_t pid) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700114 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 Ferris82f3bbd2017-03-14 15:22:26 -0700126static 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 Ferrisc8bec5a2017-12-11 17:44:33 -0800147#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 Ferris82f3bbd2017-03-14 15:22:26 -0700158static bool ReadyLevelBacktrace(Backtrace* backtrace) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700159 // See if test_level_four is in the backtrace.
160 bool found = false;
Christopher Ferris46756822014-01-14 20:16:30 -0800161 for (Backtrace::const_iterator it = backtrace->begin(); it != backtrace->end(); ++it) {
162 if (it->func_name == "test_level_four") {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700163 found = true;
164 break;
165 }
166 }
167
168 return found;
169}
170
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700171static void VerifyLevelDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700172 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 Ferris17e91d42013-10-21 13:30:52 -0700176
177 // Look through the frames starting at the highest to find the
178 // frame we want.
179 size_t frame_num = 0;
Christopher Ferris20303f82014-01-10 16:33:16 -0800180 for (size_t i = backtrace->NumFrames()-1; i > 2; i--) {
Christopher Ferris46756822014-01-14 20:16:30 -0800181 if (backtrace->GetFrame(i)->func_name == "test_level_one") {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700182 frame_num = i;
183 break;
184 }
185 }
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700186 ASSERT_LT(static_cast<size_t>(0), frame_num) << DumpFrames(backtrace);
187 ASSERT_LE(static_cast<size_t>(3), frame_num) << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700188
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700189 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 Ferris17e91d42013-10-21 13:30:52 -0700197}
198
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700199static void VerifyLevelBacktrace(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700200 std::unique_ptr<Backtrace> backtrace(
Christopher Ferris20303f82014-01-10 16:33:16 -0800201 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700202 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800203 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800204 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700205
Christopher Ferris20303f82014-01-10 16:33:16 -0800206 VerifyLevelDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700207}
208
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700209static bool ReadyMaxBacktrace(Backtrace* backtrace) {
Christopher Ferris20303f82014-01-10 16:33:16 -0800210 return (backtrace->NumFrames() == MAX_BACKTRACE_FRAMES);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700211}
212
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700213static void VerifyMaxDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700214 ASSERT_EQ(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
215 << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700216 // Verify that the last frame is our recursive call.
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700217 ASSERT_EQ(backtrace->GetFrame(MAX_BACKTRACE_FRAMES-1)->func_name, "test_recursive_call")
218 << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700219}
220
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700221static void VerifyMaxBacktrace(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700222 std::unique_ptr<Backtrace> backtrace(
Christopher Ferris20303f82014-01-10 16:33:16 -0800223 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700224 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800225 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800226 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700227
Christopher Ferris20303f82014-01-10 16:33:16 -0800228 VerifyMaxDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700229}
230
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700231static void ThreadSetState(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700232 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 Ferris82f3bbd2017-03-14 15:22:26 -0700240static bool WaitForNonZero(int32_t* value, uint64_t seconds) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700241 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 Ferrisca09ce92015-03-31 17:28:22 -0700250TEST(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 Ferris97e00bb2015-04-02 14:22:31 -0700254 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferrisca09ce92015-03-31 17:28:22 -0700255 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800256 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferrisca09ce92015-03-31 17:28:22 -0700257
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 Ferris17e91d42013-10-21 13:30:52 -0700269TEST(libbacktrace, local_trace) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700270 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelBacktrace, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700271}
272
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700273static void VerifyIgnoreFrames(Backtrace* bt_all, Backtrace* bt_ign1, Backtrace* bt_ign2,
274 const char* cur_proc) {
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700275 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 Ferris17e91d42013-10-21 13:30:52 -0700283
284 // Check all of the frames are the same > the current frame.
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700285 bool check = (cur_proc == nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800286 for (size_t i = 0; i < bt_ign2->NumFrames(); i++) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700287 if (check) {
Christopher Ferris20303f82014-01-10 16:33:16 -0800288 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 Ferris17e91d42013-10-21 13:30:52 -0700291
Christopher Ferris20303f82014-01-10 16:33:16 -0800292 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 Ferris17e91d42013-10-21 13:30:52 -0700295 }
Christopher Ferris46756822014-01-14 20:16:30 -0800296 if (!check && bt_ign2->GetFrame(i)->func_name == cur_proc) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700297 check = true;
298 }
299 }
300}
301
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700302static void VerifyLevelIgnoreFrames(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700303 std::unique_ptr<Backtrace> all(
Christopher Ferris20303f82014-01-10 16:33:16 -0800304 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700305 ASSERT_TRUE(all.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800306 ASSERT_TRUE(all->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800307 VERIFY_NO_ERROR(all->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700308
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700309 std::unique_ptr<Backtrace> ign1(
Christopher Ferris20303f82014-01-10 16:33:16 -0800310 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700311 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800312 ASSERT_TRUE(ign1->Unwind(1));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800313 VERIFY_NO_ERROR(ign1->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700314
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700315 std::unique_ptr<Backtrace> ign2(
Christopher Ferris20303f82014-01-10 16:33:16 -0800316 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700317 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800318 ASSERT_TRUE(ign2->Unwind(2));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800319 VERIFY_NO_ERROR(ign2->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700320
Christopher Ferris20303f82014-01-10 16:33:16 -0800321 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), "VerifyLevelIgnoreFrames");
Christopher Ferris17e91d42013-10-21 13:30:52 -0700322}
323
324TEST(libbacktrace, local_trace_ignore_frames) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700325 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelIgnoreFrames, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700326}
327
328TEST(libbacktrace, local_max_trace) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700329 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxBacktrace, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700330}
331
Christopher Ferris458cc662017-08-28 16:31:18 -0700332static void VerifyProcTest(pid_t pid, pid_t tid, bool (*ReadyFunc)(Backtrace*),
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700333 void (*VerifyFunc)(Backtrace*, create_func_t, map_create_func_t),
334 create_func_t create_func, map_create_func_t map_create_func) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700335 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 Ferris97e00bb2015-04-02 14:22:31 -0700343 std::string last_dump;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700344 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 Ferris2b4a63f2015-03-17 14:42:03 -0700350 std::unique_ptr<BacktraceMap> map;
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700351 map.reset(map_create_func(pid, false));
352 std::unique_ptr<Backtrace> backtrace(create_func(pid, tid, map.get()));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700353 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700354 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferris20303f82014-01-10 16:33:16 -0800355 if (ReadyFunc(backtrace.get())) {
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700356 VerifyFunc(backtrace.get(), create_func, map_create_func);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700357 verified = true;
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700358 } else {
359 last_dump = DumpFrames(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700360 }
Christopher Ferris20303f82014-01-10 16:33:16 -0800361
Christopher Ferris17e91d42013-10-21 13:30:52 -0700362 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 Ferris97e00bb2015-04-02 14:22:31 -0700366 ASSERT_TRUE(verified) << "Last backtrace:\n" << last_dump;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700367}
368
369TEST(libbacktrace, ptrace_trace) {
370 pid_t pid;
371 if ((pid = fork()) == 0) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700372 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800373 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700374 }
Christopher Ferris458cc662017-08-28 16:31:18 -0700375 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, ReadyLevelBacktrace, VerifyLevelDump,
376 Backtrace::Create, BacktraceMap::Create);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800377
378 kill(pid, SIGKILL);
379 int status;
380 ASSERT_EQ(waitpid(pid, &status, 0), pid);
381}
382
Christopher Ferris17e91d42013-10-21 13:30:52 -0700383TEST(libbacktrace, ptrace_max_trace) {
384 pid_t pid;
385 if ((pid = fork()) == 0) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700386 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800387 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700388 }
Christopher Ferris458cc662017-08-28 16:31:18 -0700389 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 Ferrisb9de87f2017-09-20 13:37:24 -0700397static 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 Ferris2b4a63f2015-03-17 14:42:03 -0700401 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800402 ASSERT_TRUE(ign1->Unwind(1));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800403 VERIFY_NO_ERROR(ign1->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700404
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700405 std::unique_ptr<Backtrace> ign2(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700406 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800407 ASSERT_TRUE(ign2->Unwind(2));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800408 VERIFY_NO_ERROR(ign2->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700409
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700410 VerifyIgnoreFrames(bt_all, ign1.get(), ign2.get(), nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700411}
412
413TEST(libbacktrace, ptrace_ignore_frames) {
414 pid_t pid;
415 if ((pid = fork()) == 0) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700416 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800417 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700418 }
Christopher Ferris458cc662017-08-28 16:31:18 -0700419 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 Ferris17e91d42013-10-21 13:30:52 -0700427// Create a process with multiple threads and dump all of the threads.
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700428static void* PtraceThreadLevelRun(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700429 EXPECT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
430 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700431}
432
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700433static void GetThreads(pid_t pid, std::vector<pid_t>* threads) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700434 // Get the list of tasks.
435 char task_path[128];
436 snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
437
James Hawkins588a2ca2016-02-18 14:52:46 -0800438 std::unique_ptr<DIR, decltype(&closedir)> tasks_dir(opendir(task_path), closedir);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700439 ASSERT_TRUE(tasks_dir != nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700440 struct dirent* entry;
James Hawkins588a2ca2016-02-18 14:52:46 -0800441 while ((entry = readdir(tasks_dir.get())) != nullptr) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700442 char* end;
443 pid_t tid = strtoul(entry->d_name, &end, 10);
444 if (*end == '\0') {
445 threads->push_back(tid);
446 }
447 }
Christopher Ferris17e91d42013-10-21 13:30:52 -0700448}
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 Ferris2b4a63f2015-03-17 14:42:03 -0700459 ASSERT_TRUE(pthread_create(&thread, &attr, PtraceThreadLevelRun, nullptr) == 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700460 }
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700461 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800462 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700463 }
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 Ferris458cc662017-08-28 16:31:18 -0700483 VerifyProcTest(pid, *it, ReadyLevelBacktrace, VerifyLevelDump, Backtrace::Create,
484 BacktraceMap::Create);
485 }
486
487 FinishRemoteProcess(pid);
488}
489
Christopher Ferris17e91d42013-10-21 13:30:52 -0700490void VerifyLevelThread(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700491 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
492 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800493 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800494 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700495
Christopher Ferris20303f82014-01-10 16:33:16 -0800496 VerifyLevelDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700497}
498
499TEST(libbacktrace, thread_current_level) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700500 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelThread, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700501}
502
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700503static void VerifyMaxThread(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700504 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
505 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800506 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800507 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700508
Christopher Ferris20303f82014-01-10 16:33:16 -0800509 VerifyMaxDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700510}
511
512TEST(libbacktrace, thread_current_max) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700513 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxThread, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700514}
515
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700516static void* ThreadLevelRun(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700517 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 Ferris2b4a63f2015-03-17 14:42:03 -0700521 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700522}
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 Ferris2b4a63f2015-03-17 14:42:03 -0700529 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris17e91d42013-10-21 13:30:52 -0700530 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 Ferrisaa63d9f2014-04-29 09:35:30 -0700536 // 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 Ferris17e91d42013-10-21 13:30:52 -0700542 // Save the current signal action and make sure it is restored afterwards.
543 struct sigaction cur_action;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700544 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &cur_action) == 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700545
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700546 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
547 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800548 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800549 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700550
Christopher Ferris20303f82014-01-10 16:33:16 -0800551 VerifyLevelDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700552
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 Ferris2b4a63f2015-03-17 14:42:03 -0700558 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &new_action) == 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700559 EXPECT_EQ(cur_action.sa_sigaction, new_action.sa_sigaction);
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -0800560 // 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 Ferris2c43cff2015-03-26 19:18:36 -0700563#if defined(SA_RESTORER)
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -0800564 cur_action.sa_flags &= ~SA_RESTORER;
565 new_action.sa_flags &= ~SA_RESTORER;
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700566#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 Ferris3cdbfdc2014-11-08 15:57:11 -0800570#endif
Christopher Ferris17e91d42013-10-21 13:30:52 -0700571 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 Ferris2b4a63f2015-03-17 14:42:03 -0700579 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris17e91d42013-10-21 13:30:52 -0700580 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 Ferris2b4a63f2015-03-17 14:42:03 -0700586 std::unique_ptr<Backtrace> all(Backtrace::Create(getpid(), thread_data.tid));
587 ASSERT_TRUE(all.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800588 ASSERT_TRUE(all->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800589 VERIFY_NO_ERROR(all->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700590
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700591 std::unique_ptr<Backtrace> ign1(Backtrace::Create(getpid(), thread_data.tid));
592 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800593 ASSERT_TRUE(ign1->Unwind(1));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800594 VERIFY_NO_ERROR(ign1->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700595
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700596 std::unique_ptr<Backtrace> ign2(Backtrace::Create(getpid(), thread_data.tid));
597 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800598 ASSERT_TRUE(ign2->Unwind(2));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800599 VERIFY_NO_ERROR(ign2->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700600
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700601 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700602
603 // Tell the thread to exit its infinite loop.
604 android_atomic_acquire_store(0, &thread_data.state);
605}
606
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700607static void* ThreadMaxRun(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700608 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 Ferris2b4a63f2015-03-17 14:42:03 -0700612 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700613}
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 Ferris2b4a63f2015-03-17 14:42:03 -0700620 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris17e91d42013-10-21 13:30:52 -0700621 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 Ferris2b4a63f2015-03-17 14:42:03 -0700627 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
628 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800629 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800630 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_EXCEED_MAX_FRAMES_LIMIT, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700631
Christopher Ferris20303f82014-01-10 16:33:16 -0800632 VerifyMaxDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700633
634 // Tell the thread to exit its infinite loop.
635 android_atomic_acquire_store(0, &thread_data.state);
636}
637
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700638static void* ThreadDump(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700639 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 Ferris17e91d42013-10-21 13:30:52 -0700646 // The status of the actual unwind will be checked elsewhere.
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800647 dump->backtrace = Backtrace::Create(getpid(), dump->thread.tid, dump->map);
Christopher Ferris20303f82014-01-10 16:33:16 -0800648 dump->backtrace->Unwind(0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700649
650 android_atomic_acquire_store(1, &dump->done);
651
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700652 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700653}
654
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800655static void MultipleThreadDumpTest(bool share_map) {
656 // Dump NUM_THREADS simultaneously using the same map.
Christopher Ferris17e91d42013-10-21 13:30:52 -0700657 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 Ferris3cdbfdc2014-11-08 15:57:11 -0800672 ASSERT_TRUE(WaitForNonZero(&it->state, 30));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700673 }
674
675 // Start all of the dumpers at once, they will spin until they are signalled
676 // to begin their dump run.
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800677 std::unique_ptr<BacktraceMap> map;
678 if (share_map) {
679 map.reset(BacktraceMap::Create(getpid()));
680 }
Christopher Ferris17e91d42013-10-21 13:30:52 -0700681 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 Ferrisbe788d82017-11-27 14:50:38 -0800687 dumpers[i].map = map.get();
Christopher Ferris17e91d42013-10-21 13:30:52 -0700688
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 Ferris3cdbfdc2014-11-08 15:57:11 -0800696 ASSERT_TRUE(WaitForNonZero(&dumpers[i].done, 30));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700697
698 // Tell the runner thread to exit its infinite loop.
699 android_atomic_acquire_store(0, &runners[i].state);
700
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700701 ASSERT_TRUE(dumpers[i].backtrace != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800702 VerifyMaxDump(dumpers[i].backtrace);
703
704 delete dumpers[i].backtrace;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700705 dumpers[i].backtrace = nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700706 }
707}
708
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800709TEST(libbacktrace, thread_multiple_dump) {
710 MultipleThreadDumpTest(false);
711}
Christopher Ferrisa2efd3a2014-05-06 15:23:59 -0700712
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800713TEST(libbacktrace, thread_multiple_dump_same_map) {
714 MultipleThreadDumpTest(true);
Christopher Ferrisa2efd3a2014-05-06 15:23:59 -0700715}
716
Christopher Ferrisdf290612014-01-22 19:21:07 -0800717// 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 Ferris97e00bb2015-04-02 14:22:31 -0700725 ASSERT_TRUE(back1 != nullptr);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800726 EXPECT_TRUE(back1->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800727 VERIFY_NO_ERROR(back1->GetError().error_code);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800728 delete back1;
729 delete map1;
730
731 Backtrace* back2 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map2);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700732 ASSERT_TRUE(back2 != nullptr);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800733 EXPECT_TRUE(back2->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800734 VERIFY_NO_ERROR(back2->GetError().error_code);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800735 delete back2;
736 delete map2;
737
738 Backtrace* back3 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map3);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700739 ASSERT_TRUE(back3 != nullptr);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800740 EXPECT_TRUE(back3->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -0800741 VERIFY_NO_ERROR(back3->GetError().error_code);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800742 delete back3;
743 delete map3;
744}
745
Christopher Ferris12385e32015-02-06 13:22:01 -0800746TEST(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 Ferris7937a362018-01-18 11:15:49 -0800759 ASSERT_EQ(static_cast<uint64_t>(0), map.start);
760 ASSERT_EQ(static_cast<uint64_t>(0), map.end);
Christopher Ferris12385e32015-02-06 13:22:01 -0800761 ASSERT_EQ(0, map.flags);
762 ASSERT_EQ("", map.name);
763}
764
Christopher Ferris17e91d42013-10-21 13:30:52 -0700765TEST(libbacktrace, format_test) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700766 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD));
767 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700768
Christopher Ferris20303f82014-01-10 16:33:16 -0800769 backtrace_frame_data_t frame;
Christopher Ferris46756822014-01-14 20:16:30 -0800770 frame.num = 1;
771 frame.pc = 2;
Christopher Ferris96722b02017-07-19 14:20:46 -0700772 frame.rel_pc = 2;
Christopher Ferris46756822014-01-14 20:16:30 -0800773 frame.sp = 0;
774 frame.stack_size = 0;
Christopher Ferris46756822014-01-14 20:16:30 -0800775 frame.func_offset = 0;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700776
Christopher Ferris46756822014-01-14 20:16:30 -0800777 // Check no map set.
Christopher Ferris20303f82014-01-10 16:33:16 -0800778 frame.num = 1;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700779#if defined(__LP64__)
Christopher Ferris46756822014-01-14 20:16:30 -0800780 EXPECT_EQ("#01 pc 0000000000000002 <unknown>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700781#else
Christopher Ferris46756822014-01-14 20:16:30 -0800782 EXPECT_EQ("#01 pc 00000002 <unknown>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700783#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800784 backtrace->FormatFrameData(&frame));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700785
Christopher Ferris46756822014-01-14 20:16:30 -0800786 // Check map name empty, but exists.
Christopher Ferrisda750a72015-11-30 13:36:08 -0800787 frame.pc = 0xb0020;
Christopher Ferris96722b02017-07-19 14:20:46 -0700788 frame.rel_pc = 0x20;
Christopher Ferrisda750a72015-11-30 13:36:08 -0800789 frame.map.start = 0xb0000;
790 frame.map.end = 0xbffff;
Christopher Ferris96722b02017-07-19 14:20:46 -0700791 frame.map.load_bias = 0;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700792#if defined(__LP64__)
Christopher Ferrisda750a72015-11-30 13:36:08 -0800793 EXPECT_EQ("#01 pc 0000000000000020 <anonymous:00000000000b0000>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700794#else
Christopher Ferrisda750a72015-11-30 13:36:08 -0800795 EXPECT_EQ("#01 pc 00000020 <anonymous:000b0000>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700796#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800797 backtrace->FormatFrameData(&frame));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700798
Christopher Ferrisda750a72015-11-30 13:36:08 -0800799 // Check map name begins with a [.
800 frame.pc = 0xc0020;
801 frame.map.start = 0xc0000;
802 frame.map.end = 0xcffff;
Christopher Ferris96722b02017-07-19 14:20:46 -0700803 frame.map.load_bias = 0;
Christopher Ferrisda750a72015-11-30 13:36:08 -0800804 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 Ferris46756822014-01-14 20:16:30 -0800811
812 // Check relative pc is set and map name is set.
813 frame.pc = 0x12345679;
Christopher Ferris96722b02017-07-19 14:20:46 -0700814 frame.rel_pc = 0x12345678;
Christopher Ferris12385e32015-02-06 13:22:01 -0800815 frame.map.name = "MapFake";
816 frame.map.start = 1;
817 frame.map.end = 1;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700818#if defined(__LP64__)
Christopher Ferris46756822014-01-14 20:16:30 -0800819 EXPECT_EQ("#01 pc 0000000012345678 MapFake",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700820#else
Christopher Ferris46756822014-01-14 20:16:30 -0800821 EXPECT_EQ("#01 pc 12345678 MapFake",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700822#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800823 backtrace->FormatFrameData(&frame));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700824
Christopher Ferris46756822014-01-14 20:16:30 -0800825 // 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 Ferris20303f82014-01-10 16:33:16 -0800835 frame.func_offset = 645;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700836#if defined(__LP64__)
Christopher Ferris46756822014-01-14 20:16:30 -0800837 EXPECT_EQ("#01 pc 0000000012345678 MapFake (ProcFake+645)",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700838#else
Christopher Ferris46756822014-01-14 20:16:30 -0800839 EXPECT_EQ("#01 pc 12345678 MapFake (ProcFake+645)",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700840#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800841 backtrace->FormatFrameData(&frame));
Christopher Ferris2106f4b2015-05-01 15:02:03 -0700842
Christopher Ferris96722b02017-07-19 14:20:46 -0700843 // Check func_name is set, func offset is non-zero, and load_bias is non-zero.
844 frame.rel_pc = 0x123456dc;
Christopher Ferris2106f4b2015-05-01 15:02:03 -0700845 frame.func_offset = 645;
Christopher Ferris96722b02017-07-19 14:20:46 -0700846 frame.map.load_bias = 100;
Christopher Ferris2106f4b2015-05-01 15:02:03 -0700847#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 Ferrise0ab2322015-08-20 11:16:54 -0700853
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 Ferris17e91d42013-10-21 13:30:52 -0700862}
Christopher Ferrise2960912014-03-07 19:42:19 -0800863
864struct map_test_t {
Christopher Ferris7937a362018-01-18 11:15:49 -0800865 uint64_t start;
866 uint64_t end;
Christopher Ferrise2960912014-03-07 19:42:19 -0800867};
868
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700869static bool map_sort(map_test_t i, map_test_t j) { return i.start < j.start; }
Christopher Ferrise2960912014-03-07 19:42:19 -0800870
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800871static 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 Ferris7937a362018-01-18 11:15:49 -0800877 map_txt += android::base::StringPrintf("%" PRIx64 "-%" PRIx64 "\n", map.start, map.end);
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800878 }
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 Ferris7937a362018-01-18 11:15:49 -0800889 "%" PRIx64 "-%" PRIx64 " flags: 0x%x offset: 0x%" PRIx64 " load_bias: 0x%" PRIx64,
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800890 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 Ferris82f3bbd2017-03-14 15:22:26 -0700899static void VerifyMap(pid_t pid) {
Christopher Ferrise2960912014-03-07 19:42:19 -0800900 char buffer[4096];
901 snprintf(buffer, sizeof(buffer), "/proc/%d/maps", pid);
902
903 FILE* map_file = fopen(buffer, "r");
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700904 ASSERT_TRUE(map_file != nullptr);
Christopher Ferrise2960912014-03-07 19:42:19 -0800905 std::vector<map_test_t> test_maps;
906 while (fgets(buffer, sizeof(buffer), map_file)) {
907 map_test_t map;
Christopher Ferris7937a362018-01-18 11:15:49 -0800908 ASSERT_EQ(2, sscanf(buffer, "%" SCNx64 "-%" SCNx64 " ", &map.start, &map.end));
Christopher Ferrise2960912014-03-07 19:42:19 -0800909 test_maps.push_back(map);
910 }
911 fclose(map_file);
912 std::sort(test_maps.begin(), test_maps.end(), map_sort);
913
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700914 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(pid));
Christopher Ferrise2960912014-03-07 19:42:19 -0800915
916 // Basic test that verifies that the map is in the expected order.
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800917 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 Ferrise2960912014-03-07 19:42:19 -0800931 ++test_it;
932 }
933 ASSERT_TRUE(test_it == test_maps.end());
934}
935
936TEST(libbacktrace, verify_map_remote) {
937 pid_t pid;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700938 CreateRemoteProcess(&pid);
Christopher Ferrise2960912014-03-07 19:42:19 -0800939
940 // The maps should match exactly since the forked process has been paused.
941 VerifyMap(pid);
942
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700943 FinishRemoteProcess(pid);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700944}
945
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700946static void InitMemory(uint8_t* memory, size_t bytes) {
Christopher Ferris944f4172015-05-06 16:36:34 -0700947 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 Ferris82f3bbd2017-03-14 15:22:26 -0700957static void* ThreadReadTest(void* data) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700958 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 Ferris944f4172015-05-06 16:36:34 -0700975 InitMemory(memory, pagesize);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700976
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 Ferris2c43cff2015-03-26 19:18:36 -0700982 // Loop waiting for the caller to finish reading the memory.
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700983 while (thread_data->state) {
984 }
985
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700986 // 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 Ferris2b4a63f2015-03-17 14:42:03 -0700991 free(memory);
992
993 android_atomic_acquire_store(1, &thread_data->state);
994
995 return nullptr;
996}
997
Christopher Ferris7937a362018-01-18 11:15:49 -0800998static void RunReadTest(Backtrace* backtrace, uint64_t read_addr) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700999 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 Ferris944f4172015-05-06 16:36:34 -07001003 InitMemory(expected, pagesize);
1004
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001005 uint8_t* data = new uint8_t[2 * pagesize];
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001006 // 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 Ferris944f4172015-05-06 16:36:34 -07001018
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 Nainar837eff22015-07-09 10:50:04 -07001032 delete[] data;
1033 delete[] expected;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001034}
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 Ferris7937a362018-01-18 11:15:49 -08001049 RunReadTest(backtrace.get(), reinterpret_cast<uint64_t>(thread_data.data));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001050
1051 android_atomic_acquire_store(0, &thread_data.state);
1052
1053 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10));
1054}
1055
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001056// The code requires these variables are the same size.
Christopher Ferris7937a362018-01-18 11:15:49 -08001057volatile uint64_t g_ready = 0;
1058volatile uint64_t g_addr = 0;
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001059static_assert(sizeof(g_ready) == sizeof(g_addr), "g_ready/g_addr must be same size");
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001060
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001061static void ForkedReadTest() {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001062 // 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 Ferris944f4172015-05-06 16:36:34 -07001077 InitMemory(memory, pagesize);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001078
Christopher Ferris7937a362018-01-18 11:15:49 -08001079 g_addr = reinterpret_cast<uint64_t>(memory);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001080 g_ready = 1;
1081
1082 while (1) {
1083 usleep(US_PER_MSEC);
1084 }
1085}
1086
1087TEST(libbacktrace, process_read) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001088 g_ready = 0;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001089 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 Ferris97e00bb2015-04-02 14:22:31 -07001103 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001104
Christopher Ferris7937a362018-01-18 11:15:49 -08001105 uint64_t read_addr;
1106 size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001107 reinterpret_cast<uint8_t*>(&read_addr), sizeof(g_ready));
1108 ASSERT_EQ(sizeof(g_ready), bytes_read);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001109 if (read_addr) {
1110 // The forked process is ready to be read.
Christopher Ferris7937a362018-01-18 11:15:49 -08001111 bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001112 reinterpret_cast<uint8_t*>(&read_addr), sizeof(g_addr));
1113 ASSERT_EQ(sizeof(g_addr), bytes_read);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001114
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 Ferrise2960912014-03-07 19:42:19 -08001131}
1132
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001133static void VerifyFunctionsFound(const std::vector<std::string>& found_functions) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001134 // 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 Ferris82f3bbd2017-03-14 15:22:26 -07001153static const char* CopySharedLibrary() {
Christopher Ferris67aba682015-05-08 15:44:46 -07001154#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 Ferris7937a362018-01-18 11:15:49 -08001187 uint64_t map_size = buf.st_size;
Christopher Ferris67aba682015-05-08 15:44:46 -07001188
1189 int fd = open(tmp_so_name, O_RDONLY);
1190 ASSERT_TRUE(fd != -1);
1191
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001192 void* map = mmap(nullptr, map_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001193 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 Ferris7937a362018-01-18 11:15:49 -08001206 map_size += reinterpret_cast<uint64_t>(map);
Christopher Ferris67aba682015-05-08 15:44:46 -07001207 std::string last_func;
Christopher Ferris7937a362018-01-18 11:15:49 -08001208 for (uint64_t read_addr = reinterpret_cast<uint64_t>(map); read_addr < map_size; read_addr += 4) {
1209 uint64_t offset;
Christopher Ferris67aba682015-05-08 15:44:46 -07001210 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 Ferris7937a362018-01-18 11:15:49 -08001217 ASSERT_TRUE(munmap(map, map_size - reinterpret_cast<uint64_t>(map)) == 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001218
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 Ferris7937a362018-01-18 11:15:49 -08001230 uint64_t map_size = buf.st_size;
Christopher Ferris67aba682015-05-08 15:44:46 -07001231
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 Ferrisc8bec5a2017-12-11 17:44:33 -08001241 void* map = mmap(nullptr, map_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001242 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 Ferris7937a362018-01-18 11:15:49 -08001253 g_addr = reinterpret_cast<uint64_t>(map);
Christopher Ferris67aba682015-05-08 15:44:46 -07001254 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 Ferris7937a362018-01-18 11:15:49 -08001273 uint64_t read_addr;
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001274 ASSERT_EQ(sizeof(g_ready),
Christopher Ferris7937a362018-01-18 11:15:49 -08001275 backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001276 reinterpret_cast<uint8_t*>(&read_addr), sizeof(g_ready)));
Christopher Ferris67aba682015-05-08 15:44:46 -07001277 if (read_addr) {
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001278 ASSERT_EQ(sizeof(g_addr),
Christopher Ferris7937a362018-01-18 11:15:49 -08001279 backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
1280 reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t)));
Christopher Ferris67aba682015-05-08 15:44:46 -07001281
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 Ferris7937a362018-01-18 11:15:49 -08001289 uint64_t offset;
Christopher Ferris67aba682015-05-08 15:44:46 -07001290 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 Ferris7937a362018-01-18 11:15:49 -08001312static bool FindFuncFrameInBacktrace(Backtrace* backtrace, uint64_t test_func, size_t* frame_num) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001313 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 Ferris7937a362018-01-18 11:15:49 -08001331static void VerifyUnreadableElfFrame(Backtrace* backtrace, uint64_t test_func, size_t frame_num) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001332 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 Ferris7937a362018-01-18 11:15:49 -08001339 uint64_t diff = backtrace->GetFrame(frame_num)->pc - test_func;
Christopher Ferris67aba682015-05-08 15:44:46 -07001340 ASSERT_LT(diff, 200U) << DumpFrames(backtrace);
1341}
1342
Christopher Ferris7937a362018-01-18 11:15:49 -08001343static void VerifyUnreadableElfBacktrace(void* func) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001344 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 Ferrisc8bec5a2017-12-11 17:44:33 -08001348 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris67aba682015-05-08 15:44:46 -07001349
1350 size_t frame_num;
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001351 uint64_t test_func = reinterpret_cast<uint64_t>(func);
1352 ASSERT_TRUE(FindFuncFrameInBacktrace(backtrace.get(), test_func, &frame_num))
1353 << DumpFrames(backtrace.get());
Christopher Ferris67aba682015-05-08 15:44:46 -07001354
1355 VerifyUnreadableElfFrame(backtrace.get(), test_func, frame_num);
1356}
1357
Christopher Ferris7937a362018-01-18 11:15:49 -08001358typedef int (*test_func_t)(int, int, int, int, void (*)(void*), void*);
Christopher Ferris67aba682015-05-08 15:44:46 -07001359
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 Ferris7937a362018-01-18 11:15:49 -08001371 ASSERT_NE(test_func(1, 2, 3, 4, VerifyUnreadableElfBacktrace, reinterpret_cast<void*>(test_func)),
1372 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001373
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 Ferrisc8bec5a2017-12-11 17:44:33 -08001407 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferris67aba682015-05-08 15:44:46 -07001408
1409 size_t frame_num;
Christopher Ferris7937a362018-01-18 11:15:49 -08001410 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 Ferris67aba682015-05-08 15:44:46 -07001413 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 Ferris206a3b92016-03-09 14:35:54 -08001430TEST(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 Cuif8808282017-12-12 18:04:10 -08001435 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST, backtrace->GetError().error_code);
Christopher Ferris206a3b92016-03-09 14:35:54 -08001436}
1437
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001438TEST(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 Ferris7937a362018-01-18 11:15:49 -08001444 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
1445 uint64_t offset;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001446 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 Ferris7937a362018-01-18 11:15:49 -08001457 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
1458 uint64_t offset;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001459 ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
1460
1461 FinishRemoteProcess(pid);
1462}
1463
Christopher Ferris7937a362018-01-18 11:15:49 -08001464static void SetUcontextSp(uint64_t sp, ucontext_t* ucontext) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001465#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 Ferris7937a362018-01-18 11:15:49 -08001480static void SetUcontextPc(uint64_t pc, ucontext_t* ucontext) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001481#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 Ferris7937a362018-01-18 11:15:49 -08001496static void SetUcontextLr(uint64_t lr, ucontext_t* ucontext) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001497#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 Ferris7937a362018-01-18 11:15:49 -08001531 uint64_t device_map_uint = reinterpret_cast<uint64_t>(device_map);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001532
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 Ferris7937a362018-01-18 11:15:49 -08001539 uint64_t offset;
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001540 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 Ferris7937a362018-01-18 11:15:49 -08001544 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001545 // 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 Ferris7937a362018-01-18 11:15:49 -08001557 SetUcontextSp(reinterpret_cast<uint64_t>(&ucontext), &ucontext);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001558 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 Ferris7937a362018-01-18 11:15:49 -08001567 ASSERT_EQ(reinterpret_cast<uint64_t>(&ucontext), frame->sp);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001568
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 Ferris086baf92017-10-17 14:12:52 -07001607TEST(libbacktrace, unwind_disallow_device_map_remote) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001608 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 Ferris086baf92017-10-17 14:12:52 -07001616 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001617
Christopher Ferris458cc662017-08-28 16:31:18 -07001618 UnwindFromDevice(backtrace.get(), device_map);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001619
1620 FinishRemoteProcess(pid);
1621
1622 munmap(device_map, DEVICE_MAP_SIZE);
1623}
1624
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001625class 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 Ferrisb9de87f2017-09-20 13:37:24 -07001657static void UnwindThroughSignal(bool use_action, create_func_t create_func,
1658 map_create_func_t map_create_func) {
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001659 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 Ferrisb9de87f2017-09-20 13:37:24 -07001684 std::unique_ptr<BacktraceMap> map(map_create_func(pid, false));
1685 std::unique_ptr<Backtrace> backtrace(create_func(pid, pid, map.get()));
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001686
Christopher Ferris7937a362018-01-18 11:15:49 -08001687 size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(const_cast<int*>(&value)),
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001688 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 Ferris458cc662017-08-28 16:31:18 -07001703 std::unique_ptr<BacktraceMap> map;
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001704 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 Ferrisb9de87f2017-09-20 13:37:24 -07001712 map.reset(map_create_func(pid, false));
Christopher Ferris458cc662017-08-28 16:31:18 -07001713 ASSERT_TRUE(map.get() != nullptr);
Christopher Ferrisb9de87f2017-09-20 13:37:24 -07001714 backtrace.reset(create_func(pid, pid, map.get()));
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001715 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 Ferris96722b02017-07-19 14:20:46 -07001770TEST(libbacktrace, unwind_remote_through_signal_using_handler) {
Christopher Ferris458cc662017-08-28 16:31:18 -07001771 UnwindThroughSignal(false, Backtrace::Create, BacktraceMap::Create);
1772}
1773
Christopher Ferris96722b02017-07-19 14:20:46 -07001774TEST(libbacktrace, unwind_remote_through_signal_using_action) {
Christopher Ferris458cc662017-08-28 16:31:18 -07001775 UnwindThroughSignal(true, Backtrace::Create, BacktraceMap::Create);
1776}
1777
Josh Gaocd546c12017-10-25 15:21:45 -07001778static 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 Ferrise2960912014-03-07 19:42:19 -08001790#if defined(ENABLE_PSS_TESTS)
1791#include "GetPss.h"
1792
Chih-Hung Hsieh67867db2016-05-18 15:53:15 -07001793#define MAX_LEAK_BYTES (32*1024UL)
Christopher Ferrise2960912014-03-07 19:42:19 -08001794
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001795static void CheckForLeak(pid_t pid, pid_t tid) {
Christopher Ferris086baf92017-10-17 14:12:52 -07001796 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(pid));
1797
Christopher Ferrise2960912014-03-07 19:42:19 -08001798 // Do a few runs to get the PSS stable.
1799 for (size_t i = 0; i < 100; i++) {
Christopher Ferris086baf92017-10-17 14:12:52 -07001800 Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001801 ASSERT_TRUE(backtrace != nullptr);
Christopher Ferrise2960912014-03-07 19:42:19 -08001802 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001803 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferrise2960912014-03-07 19:42:19 -08001804 delete backtrace;
1805 }
1806 size_t stable_pss = GetPssBytes();
Christopher Ferris2c43cff2015-03-26 19:18:36 -07001807 ASSERT_TRUE(stable_pss != 0);
Christopher Ferrise2960912014-03-07 19:42:19 -08001808
1809 // Loop enough that even a small leak should be detectable.
1810 for (size_t i = 0; i < 4096; i++) {
Christopher Ferris086baf92017-10-17 14:12:52 -07001811 Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001812 ASSERT_TRUE(backtrace != nullptr);
Christopher Ferrise2960912014-03-07 19:42:19 -08001813 ASSERT_TRUE(backtrace->Unwind(0));
Christopher Ferrisc8bec5a2017-12-11 17:44:33 -08001814 VERIFY_NO_ERROR(backtrace->GetError().error_code);
Christopher Ferrise2960912014-03-07 19:42:19 -08001815 delete backtrace;
1816 }
1817 size_t new_pss = GetPssBytes();
Christopher Ferris2c43cff2015-03-26 19:18:36 -07001818 ASSERT_TRUE(new_pss != 0);
Christopher Ferris5ccdfa62016-03-07 19:18:31 -08001819 if (new_pss > stable_pss) {
1820 ASSERT_LE(new_pss - stable_pss, MAX_LEAK_BYTES);
1821 }
Christopher Ferrise2960912014-03-07 19:42:19 -08001822}
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 Ferris2b4a63f2015-03-17 14:42:03 -07001829 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferrise2960912014-03-07 19:42:19 -08001830 pthread_t thread;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001831 ASSERT_TRUE(pthread_create(&thread, nullptr, ThreadLevelRun, &thread_data) == 0);
Christopher Ferrise2960912014-03-07 19:42:19 -08001832
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 Ferris2b4a63f2015-03-17 14:42:03 -07001841 ASSERT_TRUE(pthread_join(thread, nullptr) == 0);
Christopher Ferrise2960912014-03-07 19:42:19 -08001842}
1843
1844TEST(libbacktrace, check_for_leak_remote) {
1845 pid_t pid;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001846 CreateRemoteProcess(&pid);
Christopher Ferrise2960912014-03-07 19:42:19 -08001847
1848 CheckForLeak(pid, BACKTRACE_CURRENT_THREAD);
1849
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001850 FinishRemoteProcess(pid);
Christopher Ferrise2960912014-03-07 19:42:19 -08001851}
1852#endif