blob: 10152f7adf28d181c951d5bf46b8a822043c45c8 [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>
34#include <unistd.h>
35
Christopher Ferrise2960912014-03-07 19:42:19 -080036#include <algorithm>
Christopher Ferris67aba682015-05-08 15:44:46 -070037#include <list>
Christopher Ferris2b4a63f2015-03-17 14:42:03 -070038#include <memory>
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -070039#include <ostream>
Christopher Ferris2c43cff2015-03-26 19:18:36 -070040#include <string>
Christopher Ferris17e91d42013-10-21 13:30:52 -070041#include <vector>
42
Dan Albert23f750b2015-04-30 12:52:21 -070043#include <backtrace/Backtrace.h>
44#include <backtrace/BacktraceMap.h>
45
Christopher Ferrisf5e568e2017-03-22 13:18:31 -070046#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080047#include <android-base/stringprintf.h>
Christopher Ferris82f3bbd2017-03-14 15:22:26 -070048#include <android-base/unique_fd.h>
Dan Albert23f750b2015-04-30 12:52:21 -070049#include <cutils/atomic.h>
50#include <cutils/threads.h>
51
52#include <gtest/gtest.h>
53
54// For the THREAD_SIGNAL definition.
55#include "BacktraceCurrent.h"
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -070056#include "backtrace_testlib.h"
Christopher Ferris17e91d42013-10-21 13:30:52 -070057#include "thread_utils.h"
58
59// Number of microseconds per milliseconds.
60#define US_PER_MSEC 1000
61
62// Number of nanoseconds in a second.
63#define NS_PER_SEC 1000000000ULL
64
65// Number of simultaneous dumping operations to perform.
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -080066#define NUM_THREADS 40
Christopher Ferris17e91d42013-10-21 13:30:52 -070067
68// Number of simultaneous threads running in our forked process.
69#define NUM_PTRACE_THREADS 5
70
Christopher Ferris46756822014-01-14 20:16:30 -080071struct thread_t {
Christopher Ferris17e91d42013-10-21 13:30:52 -070072 pid_t tid;
73 int32_t state;
74 pthread_t threadId;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -070075 void* data;
Christopher Ferris46756822014-01-14 20:16:30 -080076};
Christopher Ferris17e91d42013-10-21 13:30:52 -070077
Christopher Ferris46756822014-01-14 20:16:30 -080078struct dump_thread_t {
Christopher Ferris17e91d42013-10-21 13:30:52 -070079 thread_t thread;
Christopher Ferrisbe788d82017-11-27 14:50:38 -080080 BacktraceMap* map;
Christopher Ferris20303f82014-01-10 16:33:16 -080081 Backtrace* backtrace;
Christopher Ferris17e91d42013-10-21 13:30:52 -070082 int32_t* now;
83 int32_t done;
Christopher Ferris46756822014-01-14 20:16:30 -080084};
Christopher Ferris17e91d42013-10-21 13:30:52 -070085
Christopher Ferrisb9de87f2017-09-20 13:37:24 -070086typedef Backtrace* (*create_func_t)(pid_t, pid_t, BacktraceMap*);
87typedef BacktraceMap* (*map_create_func_t)(pid_t, bool);
88
89static void VerifyLevelDump(Backtrace* backtrace, create_func_t create_func = nullptr,
90 map_create_func_t map_func = nullptr);
91static void VerifyMaxDump(Backtrace* backtrace, create_func_t create_func = nullptr,
92 map_create_func_t map_func = nullptr);
93
Christopher Ferris82f3bbd2017-03-14 15:22:26 -070094static uint64_t NanoTime() {
Christopher Ferris17e91d42013-10-21 13:30:52 -070095 struct timespec t = { 0, 0 };
96 clock_gettime(CLOCK_MONOTONIC, &t);
97 return static_cast<uint64_t>(t.tv_sec * NS_PER_SEC + t.tv_nsec);
98}
99
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700100static std::string DumpFrames(Backtrace* backtrace) {
Christopher Ferris20303f82014-01-10 16:33:16 -0800101 if (backtrace->NumFrames() == 0) {
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700102 return " No frames to dump.\n";
Christopher Ferris20303f82014-01-10 16:33:16 -0800103 }
104
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700105 std::string frame;
Christopher Ferris20303f82014-01-10 16:33:16 -0800106 for (size_t i = 0; i < backtrace->NumFrames(); i++) {
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700107 frame += " " + backtrace->FormatFrameData(i) + '\n';
Christopher Ferris17e91d42013-10-21 13:30:52 -0700108 }
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700109 return frame;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700110}
111
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700112static void WaitForStop(pid_t pid) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700113 uint64_t start = NanoTime();
114
115 siginfo_t si;
116 while (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) < 0 && (errno == EINTR || errno == ESRCH)) {
117 if ((NanoTime() - start) > NS_PER_SEC) {
118 printf("The process did not get to a stopping point in 1 second.\n");
119 break;
120 }
121 usleep(US_PER_MSEC);
122 }
123}
124
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700125static void CreateRemoteProcess(pid_t* pid) {
126 if ((*pid = fork()) == 0) {
127 while (true)
128 ;
129 _exit(0);
130 }
131 ASSERT_NE(-1, *pid);
132
133 ASSERT_TRUE(ptrace(PTRACE_ATTACH, *pid, 0, 0) == 0);
134
135 // Wait for the process to get to a stopping point.
136 WaitForStop(*pid);
137}
138
139static void FinishRemoteProcess(pid_t pid) {
140 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
141
142 kill(pid, SIGKILL);
143 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
144}
145
146static bool ReadyLevelBacktrace(Backtrace* backtrace) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700147 // See if test_level_four is in the backtrace.
148 bool found = false;
Christopher Ferris46756822014-01-14 20:16:30 -0800149 for (Backtrace::const_iterator it = backtrace->begin(); it != backtrace->end(); ++it) {
150 if (it->func_name == "test_level_four") {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700151 found = true;
152 break;
153 }
154 }
155
156 return found;
157}
158
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700159static void VerifyLevelDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700160 ASSERT_GT(backtrace->NumFrames(), static_cast<size_t>(0))
161 << DumpFrames(backtrace);
162 ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
163 << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700164
165 // Look through the frames starting at the highest to find the
166 // frame we want.
167 size_t frame_num = 0;
Christopher Ferris20303f82014-01-10 16:33:16 -0800168 for (size_t i = backtrace->NumFrames()-1; i > 2; i--) {
Christopher Ferris46756822014-01-14 20:16:30 -0800169 if (backtrace->GetFrame(i)->func_name == "test_level_one") {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700170 frame_num = i;
171 break;
172 }
173 }
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700174 ASSERT_LT(static_cast<size_t>(0), frame_num) << DumpFrames(backtrace);
175 ASSERT_LE(static_cast<size_t>(3), frame_num) << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700176
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700177 ASSERT_EQ(backtrace->GetFrame(frame_num)->func_name, "test_level_one")
178 << DumpFrames(backtrace);
179 ASSERT_EQ(backtrace->GetFrame(frame_num-1)->func_name, "test_level_two")
180 << DumpFrames(backtrace);
181 ASSERT_EQ(backtrace->GetFrame(frame_num-2)->func_name, "test_level_three")
182 << DumpFrames(backtrace);
183 ASSERT_EQ(backtrace->GetFrame(frame_num-3)->func_name, "test_level_four")
184 << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700185}
186
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700187static void VerifyLevelBacktrace(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700188 std::unique_ptr<Backtrace> backtrace(
Christopher Ferris20303f82014-01-10 16:33:16 -0800189 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700190 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800191 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800192 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700193
Christopher Ferris20303f82014-01-10 16:33:16 -0800194 VerifyLevelDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700195}
196
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700197static bool ReadyMaxBacktrace(Backtrace* backtrace) {
Christopher Ferris20303f82014-01-10 16:33:16 -0800198 return (backtrace->NumFrames() == MAX_BACKTRACE_FRAMES);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700199}
200
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700201static void VerifyMaxDump(Backtrace* backtrace, create_func_t, map_create_func_t) {
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700202 ASSERT_EQ(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
203 << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700204 // Verify that the last frame is our recursive call.
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700205 ASSERT_EQ(backtrace->GetFrame(MAX_BACKTRACE_FRAMES-1)->func_name, "test_recursive_call")
206 << DumpFrames(backtrace);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700207}
208
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700209static void VerifyMaxBacktrace(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700210 std::unique_ptr<Backtrace> backtrace(
Christopher Ferris20303f82014-01-10 16:33:16 -0800211 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700212 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800213 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800214 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700215
Christopher Ferris20303f82014-01-10 16:33:16 -0800216 VerifyMaxDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700217}
218
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700219static void ThreadSetState(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700220 thread_t* thread = reinterpret_cast<thread_t*>(data);
221 android_atomic_acquire_store(1, &thread->state);
222 volatile int i = 0;
223 while (thread->state) {
224 i++;
225 }
226}
227
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700228static bool WaitForNonZero(int32_t* value, uint64_t seconds) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700229 uint64_t start = NanoTime();
230 do {
231 if (android_atomic_acquire_load(value)) {
232 return true;
233 }
234 } while ((NanoTime() - start) < seconds * NS_PER_SEC);
235 return false;
236}
237
Christopher Ferrisca09ce92015-03-31 17:28:22 -0700238TEST(libbacktrace, local_no_unwind_frames) {
239 // Verify that a local unwind does not include any frames within
240 // libunwind or libbacktrace.
241 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), getpid()));
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700242 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferrisca09ce92015-03-31 17:28:22 -0700243 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800244 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferrisca09ce92015-03-31 17:28:22 -0700245
246 ASSERT_TRUE(backtrace->NumFrames() != 0);
247 for (const auto& frame : *backtrace ) {
248 if (BacktraceMap::IsValid(frame.map)) {
249 const std::string name = basename(frame.map.name.c_str());
250 ASSERT_TRUE(name != "libunwind.so" && name != "libbacktrace.so")
251 << DumpFrames(backtrace.get());
252 }
253 break;
254 }
255}
256
Christopher Ferris17e91d42013-10-21 13:30:52 -0700257TEST(libbacktrace, local_trace) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700258 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelBacktrace, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700259}
260
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700261static void VerifyIgnoreFrames(Backtrace* bt_all, Backtrace* bt_ign1, Backtrace* bt_ign2,
262 const char* cur_proc) {
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700263 ASSERT_EQ(bt_all->NumFrames(), bt_ign1->NumFrames() + 1) << "All backtrace:\n"
264 << DumpFrames(bt_all)
265 << "Ignore 1 backtrace:\n"
266 << DumpFrames(bt_ign1);
267 ASSERT_EQ(bt_all->NumFrames(), bt_ign2->NumFrames() + 2) << "All backtrace:\n"
268 << DumpFrames(bt_all)
269 << "Ignore 2 backtrace:\n"
270 << DumpFrames(bt_ign2);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700271
272 // Check all of the frames are the same > the current frame.
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700273 bool check = (cur_proc == nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800274 for (size_t i = 0; i < bt_ign2->NumFrames(); i++) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700275 if (check) {
Christopher Ferris20303f82014-01-10 16:33:16 -0800276 EXPECT_EQ(bt_ign2->GetFrame(i)->pc, bt_ign1->GetFrame(i+1)->pc);
277 EXPECT_EQ(bt_ign2->GetFrame(i)->sp, bt_ign1->GetFrame(i+1)->sp);
278 EXPECT_EQ(bt_ign2->GetFrame(i)->stack_size, bt_ign1->GetFrame(i+1)->stack_size);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700279
Christopher Ferris20303f82014-01-10 16:33:16 -0800280 EXPECT_EQ(bt_ign2->GetFrame(i)->pc, bt_all->GetFrame(i+2)->pc);
281 EXPECT_EQ(bt_ign2->GetFrame(i)->sp, bt_all->GetFrame(i+2)->sp);
282 EXPECT_EQ(bt_ign2->GetFrame(i)->stack_size, bt_all->GetFrame(i+2)->stack_size);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700283 }
Christopher Ferris46756822014-01-14 20:16:30 -0800284 if (!check && bt_ign2->GetFrame(i)->func_name == cur_proc) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700285 check = true;
286 }
287 }
288}
289
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700290static void VerifyLevelIgnoreFrames(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700291 std::unique_ptr<Backtrace> all(
Christopher Ferris20303f82014-01-10 16:33:16 -0800292 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700293 ASSERT_TRUE(all.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800294 ASSERT_TRUE(all->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800295 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, all->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700296
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700297 std::unique_ptr<Backtrace> ign1(
Christopher Ferris20303f82014-01-10 16:33:16 -0800298 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700299 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800300 ASSERT_TRUE(ign1->Unwind(1));
Yabin Cuif8808282017-12-12 18:04:10 -0800301 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700302
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700303 std::unique_ptr<Backtrace> ign2(
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(ign2.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800306 ASSERT_TRUE(ign2->Unwind(2));
Yabin Cuif8808282017-12-12 18:04:10 -0800307 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700308
Christopher Ferris20303f82014-01-10 16:33:16 -0800309 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), "VerifyLevelIgnoreFrames");
Christopher Ferris17e91d42013-10-21 13:30:52 -0700310}
311
312TEST(libbacktrace, local_trace_ignore_frames) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700313 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelIgnoreFrames, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700314}
315
316TEST(libbacktrace, local_max_trace) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700317 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxBacktrace, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700318}
319
Christopher Ferris458cc662017-08-28 16:31:18 -0700320static void VerifyProcTest(pid_t pid, pid_t tid, bool (*ReadyFunc)(Backtrace*),
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700321 void (*VerifyFunc)(Backtrace*, create_func_t, map_create_func_t),
322 create_func_t create_func, map_create_func_t map_create_func) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700323 pid_t ptrace_tid;
324 if (tid < 0) {
325 ptrace_tid = pid;
326 } else {
327 ptrace_tid = tid;
328 }
329 uint64_t start = NanoTime();
330 bool verified = false;
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700331 std::string last_dump;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700332 do {
333 usleep(US_PER_MSEC);
334 if (ptrace(PTRACE_ATTACH, ptrace_tid, 0, 0) == 0) {
335 // Wait for the process to get to a stopping point.
336 WaitForStop(ptrace_tid);
337
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700338 std::unique_ptr<BacktraceMap> map;
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700339 map.reset(map_create_func(pid, false));
340 std::unique_ptr<Backtrace> backtrace(create_func(pid, tid, map.get()));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700341 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700342 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800343 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris20303f82014-01-10 16:33:16 -0800344 if (ReadyFunc(backtrace.get())) {
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700345 VerifyFunc(backtrace.get(), create_func, map_create_func);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700346 verified = true;
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700347 } else {
348 last_dump = DumpFrames(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700349 }
Christopher Ferris20303f82014-01-10 16:33:16 -0800350
Christopher Ferris17e91d42013-10-21 13:30:52 -0700351 ASSERT_TRUE(ptrace(PTRACE_DETACH, ptrace_tid, 0, 0) == 0);
352 }
353 // If 5 seconds have passed, then we are done.
354 } while (!verified && (NanoTime() - start) <= 5 * NS_PER_SEC);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700355 ASSERT_TRUE(verified) << "Last backtrace:\n" << last_dump;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700356}
357
358TEST(libbacktrace, ptrace_trace) {
359 pid_t pid;
360 if ((pid = fork()) == 0) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700361 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800362 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700363 }
Christopher Ferris458cc662017-08-28 16:31:18 -0700364 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, ReadyLevelBacktrace, VerifyLevelDump,
365 Backtrace::Create, BacktraceMap::Create);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800366
367 kill(pid, SIGKILL);
368 int status;
369 ASSERT_EQ(waitpid(pid, &status, 0), pid);
370}
371
Christopher Ferris17e91d42013-10-21 13:30:52 -0700372TEST(libbacktrace, ptrace_max_trace) {
373 pid_t pid;
374 if ((pid = fork()) == 0) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700375 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800376 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700377 }
Christopher Ferris458cc662017-08-28 16:31:18 -0700378 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, ReadyMaxBacktrace, VerifyMaxDump, Backtrace::Create,
379 BacktraceMap::Create);
380
381 kill(pid, SIGKILL);
382 int status;
383 ASSERT_EQ(waitpid(pid, &status, 0), pid);
384}
385
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700386static void VerifyProcessIgnoreFrames(Backtrace* bt_all, create_func_t create_func,
387 map_create_func_t map_create_func) {
388 std::unique_ptr<BacktraceMap> map(map_create_func(bt_all->Pid(), false));
389 std::unique_ptr<Backtrace> ign1(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700390 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800391 ASSERT_TRUE(ign1->Unwind(1));
Yabin Cuif8808282017-12-12 18:04:10 -0800392 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700393
Christopher Ferrisb9de87f2017-09-20 13:37:24 -0700394 std::unique_ptr<Backtrace> ign2(create_func(bt_all->Pid(), BACKTRACE_CURRENT_THREAD, map.get()));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700395 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800396 ASSERT_TRUE(ign2->Unwind(2));
Yabin Cuif8808282017-12-12 18:04:10 -0800397 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700398
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700399 VerifyIgnoreFrames(bt_all, ign1.get(), ign2.get(), nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700400}
401
402TEST(libbacktrace, ptrace_ignore_frames) {
403 pid_t pid;
404 if ((pid = fork()) == 0) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700405 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800406 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700407 }
Christopher Ferris458cc662017-08-28 16:31:18 -0700408 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, ReadyLevelBacktrace, VerifyProcessIgnoreFrames,
409 Backtrace::Create, BacktraceMap::Create);
410
411 kill(pid, SIGKILL);
412 int status;
413 ASSERT_EQ(waitpid(pid, &status, 0), pid);
414}
415
Christopher Ferris17e91d42013-10-21 13:30:52 -0700416// Create a process with multiple threads and dump all of the threads.
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700417static void* PtraceThreadLevelRun(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700418 EXPECT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
419 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700420}
421
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700422static void GetThreads(pid_t pid, std::vector<pid_t>* threads) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700423 // Get the list of tasks.
424 char task_path[128];
425 snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
426
James Hawkins588a2ca2016-02-18 14:52:46 -0800427 std::unique_ptr<DIR, decltype(&closedir)> tasks_dir(opendir(task_path), closedir);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700428 ASSERT_TRUE(tasks_dir != nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700429 struct dirent* entry;
James Hawkins588a2ca2016-02-18 14:52:46 -0800430 while ((entry = readdir(tasks_dir.get())) != nullptr) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700431 char* end;
432 pid_t tid = strtoul(entry->d_name, &end, 10);
433 if (*end == '\0') {
434 threads->push_back(tid);
435 }
436 }
Christopher Ferris17e91d42013-10-21 13:30:52 -0700437}
438
439TEST(libbacktrace, ptrace_threads) {
440 pid_t pid;
441 if ((pid = fork()) == 0) {
442 for (size_t i = 0; i < NUM_PTRACE_THREADS; i++) {
443 pthread_attr_t attr;
444 pthread_attr_init(&attr);
445 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
446
447 pthread_t thread;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700448 ASSERT_TRUE(pthread_create(&thread, &attr, PtraceThreadLevelRun, nullptr) == 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700449 }
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700450 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0);
Christopher Ferrise2960912014-03-07 19:42:19 -0800451 _exit(1);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700452 }
453
454 // Check to see that all of the threads are running before unwinding.
455 std::vector<pid_t> threads;
456 uint64_t start = NanoTime();
457 do {
458 usleep(US_PER_MSEC);
459 threads.clear();
460 GetThreads(pid, &threads);
461 } while ((threads.size() != NUM_PTRACE_THREADS + 1) &&
462 ((NanoTime() - start) <= 5 * NS_PER_SEC));
463 ASSERT_EQ(threads.size(), static_cast<size_t>(NUM_PTRACE_THREADS + 1));
464
465 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
466 WaitForStop(pid);
467 for (std::vector<int>::const_iterator it = threads.begin(); it != threads.end(); ++it) {
468 // Skip the current forked process, we only care about the threads.
469 if (pid == *it) {
470 continue;
471 }
Christopher Ferris458cc662017-08-28 16:31:18 -0700472 VerifyProcTest(pid, *it, ReadyLevelBacktrace, VerifyLevelDump, Backtrace::Create,
473 BacktraceMap::Create);
474 }
475
476 FinishRemoteProcess(pid);
477}
478
Christopher Ferris17e91d42013-10-21 13:30:52 -0700479void VerifyLevelThread(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700480 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
481 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800482 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800483 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700484
Christopher Ferris20303f82014-01-10 16:33:16 -0800485 VerifyLevelDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700486}
487
488TEST(libbacktrace, thread_current_level) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700489 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelThread, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700490}
491
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700492static void VerifyMaxThread(void*) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700493 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid()));
494 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800495 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800496 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700497
Christopher Ferris20303f82014-01-10 16:33:16 -0800498 VerifyMaxDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700499}
500
501TEST(libbacktrace, thread_current_max) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700502 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxThread, nullptr), 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700503}
504
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700505static void* ThreadLevelRun(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700506 thread_t* thread = reinterpret_cast<thread_t*>(data);
507
508 thread->tid = gettid();
509 EXPECT_NE(test_level_one(1, 2, 3, 4, ThreadSetState, data), 0);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700510 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700511}
512
513TEST(libbacktrace, thread_level_trace) {
514 pthread_attr_t attr;
515 pthread_attr_init(&attr);
516 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
517
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700518 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris17e91d42013-10-21 13:30:52 -0700519 pthread_t thread;
520 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadLevelRun, &thread_data) == 0);
521
522 // Wait up to 2 seconds for the tid to be set.
523 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
524
Christopher Ferrisaa63d9f2014-04-29 09:35:30 -0700525 // Make sure that the thread signal used is not visible when compiled for
526 // the target.
527#if !defined(__GLIBC__)
528 ASSERT_LT(THREAD_SIGNAL, SIGRTMIN);
529#endif
530
Christopher Ferris17e91d42013-10-21 13:30:52 -0700531 // Save the current signal action and make sure it is restored afterwards.
532 struct sigaction cur_action;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700533 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &cur_action) == 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700534
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700535 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
536 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800537 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800538 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700539
Christopher Ferris20303f82014-01-10 16:33:16 -0800540 VerifyLevelDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700541
542 // Tell the thread to exit its infinite loop.
543 android_atomic_acquire_store(0, &thread_data.state);
544
545 // Verify that the old action was restored.
546 struct sigaction new_action;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700547 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &new_action) == 0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700548 EXPECT_EQ(cur_action.sa_sigaction, new_action.sa_sigaction);
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -0800549 // The SA_RESTORER flag gets set behind our back, so a direct comparison
550 // doesn't work unless we mask the value off. Mips doesn't have this
551 // flag, so skip this on that platform.
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700552#if defined(SA_RESTORER)
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -0800553 cur_action.sa_flags &= ~SA_RESTORER;
554 new_action.sa_flags &= ~SA_RESTORER;
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700555#elif defined(__GLIBC__)
556 // Our host compiler doesn't appear to define this flag for some reason.
557 cur_action.sa_flags &= ~0x04000000;
558 new_action.sa_flags &= ~0x04000000;
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -0800559#endif
Christopher Ferris17e91d42013-10-21 13:30:52 -0700560 EXPECT_EQ(cur_action.sa_flags, new_action.sa_flags);
561}
562
563TEST(libbacktrace, thread_ignore_frames) {
564 pthread_attr_t attr;
565 pthread_attr_init(&attr);
566 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
567
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700568 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris17e91d42013-10-21 13:30:52 -0700569 pthread_t thread;
570 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadLevelRun, &thread_data) == 0);
571
572 // Wait up to 2 seconds for the tid to be set.
573 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
574
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700575 std::unique_ptr<Backtrace> all(Backtrace::Create(getpid(), thread_data.tid));
576 ASSERT_TRUE(all.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800577 ASSERT_TRUE(all->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800578 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, all->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700579
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700580 std::unique_ptr<Backtrace> ign1(Backtrace::Create(getpid(), thread_data.tid));
581 ASSERT_TRUE(ign1.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800582 ASSERT_TRUE(ign1->Unwind(1));
Yabin Cuif8808282017-12-12 18:04:10 -0800583 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign1->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700584
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700585 std::unique_ptr<Backtrace> ign2(Backtrace::Create(getpid(), thread_data.tid));
586 ASSERT_TRUE(ign2.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800587 ASSERT_TRUE(ign2->Unwind(2));
Yabin Cuif8808282017-12-12 18:04:10 -0800588 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, ign2->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700589
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700590 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700591
592 // Tell the thread to exit its infinite loop.
593 android_atomic_acquire_store(0, &thread_data.state);
594}
595
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700596static void* ThreadMaxRun(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700597 thread_t* thread = reinterpret_cast<thread_t*>(data);
598
599 thread->tid = gettid();
600 EXPECT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, ThreadSetState, data), 0);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700601 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700602}
603
604TEST(libbacktrace, thread_max_trace) {
605 pthread_attr_t attr;
606 pthread_attr_init(&attr);
607 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
608
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700609 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferris17e91d42013-10-21 13:30:52 -0700610 pthread_t thread;
611 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadMaxRun, &thread_data) == 0);
612
613 // Wait for the tid to be set.
614 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
615
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700616 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
617 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800618 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800619 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700620
Christopher Ferris20303f82014-01-10 16:33:16 -0800621 VerifyMaxDump(backtrace.get());
Christopher Ferris17e91d42013-10-21 13:30:52 -0700622
623 // Tell the thread to exit its infinite loop.
624 android_atomic_acquire_store(0, &thread_data.state);
625}
626
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700627static void* ThreadDump(void* data) {
Christopher Ferris17e91d42013-10-21 13:30:52 -0700628 dump_thread_t* dump = reinterpret_cast<dump_thread_t*>(data);
629 while (true) {
630 if (android_atomic_acquire_load(dump->now)) {
631 break;
632 }
633 }
634
Christopher Ferris17e91d42013-10-21 13:30:52 -0700635 // The status of the actual unwind will be checked elsewhere.
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800636 dump->backtrace = Backtrace::Create(getpid(), dump->thread.tid, dump->map);
Christopher Ferris20303f82014-01-10 16:33:16 -0800637 dump->backtrace->Unwind(0);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700638
639 android_atomic_acquire_store(1, &dump->done);
640
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700641 return nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700642}
643
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800644static void MultipleThreadDumpTest(bool share_map) {
645 // Dump NUM_THREADS simultaneously using the same map.
Christopher Ferris17e91d42013-10-21 13:30:52 -0700646 std::vector<thread_t> runners(NUM_THREADS);
647 std::vector<dump_thread_t> dumpers(NUM_THREADS);
648
649 pthread_attr_t attr;
650 pthread_attr_init(&attr);
651 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
652 for (size_t i = 0; i < NUM_THREADS; i++) {
653 // Launch the runners, they will spin in hard loops doing nothing.
654 runners[i].tid = 0;
655 runners[i].state = 0;
656 ASSERT_TRUE(pthread_create(&runners[i].threadId, &attr, ThreadMaxRun, &runners[i]) == 0);
657 }
658
659 // Wait for tids to be set.
660 for (std::vector<thread_t>::iterator it = runners.begin(); it != runners.end(); ++it) {
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -0800661 ASSERT_TRUE(WaitForNonZero(&it->state, 30));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700662 }
663
664 // Start all of the dumpers at once, they will spin until they are signalled
665 // to begin their dump run.
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800666 std::unique_ptr<BacktraceMap> map;
667 if (share_map) {
668 map.reset(BacktraceMap::Create(getpid()));
669 }
Christopher Ferris17e91d42013-10-21 13:30:52 -0700670 int32_t dump_now = 0;
671 for (size_t i = 0; i < NUM_THREADS; i++) {
672 dumpers[i].thread.tid = runners[i].tid;
673 dumpers[i].thread.state = 0;
674 dumpers[i].done = 0;
675 dumpers[i].now = &dump_now;
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800676 dumpers[i].map = map.get();
Christopher Ferris17e91d42013-10-21 13:30:52 -0700677
678 ASSERT_TRUE(pthread_create(&dumpers[i].thread.threadId, &attr, ThreadDump, &dumpers[i]) == 0);
679 }
680
681 // Start all of the dumpers going at once.
682 android_atomic_acquire_store(1, &dump_now);
683
684 for (size_t i = 0; i < NUM_THREADS; i++) {
Christopher Ferris3cdbfdc2014-11-08 15:57:11 -0800685 ASSERT_TRUE(WaitForNonZero(&dumpers[i].done, 30));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700686
687 // Tell the runner thread to exit its infinite loop.
688 android_atomic_acquire_store(0, &runners[i].state);
689
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700690 ASSERT_TRUE(dumpers[i].backtrace != nullptr);
Christopher Ferris20303f82014-01-10 16:33:16 -0800691 VerifyMaxDump(dumpers[i].backtrace);
692
693 delete dumpers[i].backtrace;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700694 dumpers[i].backtrace = nullptr;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700695 }
696}
697
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800698TEST(libbacktrace, thread_multiple_dump) {
699 MultipleThreadDumpTest(false);
700}
Christopher Ferrisa2efd3a2014-05-06 15:23:59 -0700701
Christopher Ferrisbe788d82017-11-27 14:50:38 -0800702TEST(libbacktrace, thread_multiple_dump_same_map) {
703 MultipleThreadDumpTest(true);
Christopher Ferrisa2efd3a2014-05-06 15:23:59 -0700704}
705
Christopher Ferrisdf290612014-01-22 19:21:07 -0800706// This test is for UnwindMaps that should share the same map cursor when
707// multiple maps are created for the current process at the same time.
708TEST(libbacktrace, simultaneous_maps) {
709 BacktraceMap* map1 = BacktraceMap::Create(getpid());
710 BacktraceMap* map2 = BacktraceMap::Create(getpid());
711 BacktraceMap* map3 = BacktraceMap::Create(getpid());
712
713 Backtrace* back1 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map1);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700714 ASSERT_TRUE(back1 != nullptr);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800715 EXPECT_TRUE(back1->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800716 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back1->GetError().error_code);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800717 delete back1;
718 delete map1;
719
720 Backtrace* back2 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map2);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700721 ASSERT_TRUE(back2 != nullptr);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800722 EXPECT_TRUE(back2->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800723 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back2->GetError().error_code);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800724 delete back2;
725 delete map2;
726
727 Backtrace* back3 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map3);
Christopher Ferris97e00bb2015-04-02 14:22:31 -0700728 ASSERT_TRUE(back3 != nullptr);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800729 EXPECT_TRUE(back3->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -0800730 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, back3->GetError().error_code);
Christopher Ferrisdf290612014-01-22 19:21:07 -0800731 delete back3;
732 delete map3;
733}
734
Christopher Ferris12385e32015-02-06 13:22:01 -0800735TEST(libbacktrace, fillin_erases) {
736 BacktraceMap* back_map = BacktraceMap::Create(getpid());
737
738 backtrace_map_t map;
739
740 map.start = 1;
741 map.end = 3;
742 map.flags = 1;
743 map.name = "Initialized";
744 back_map->FillIn(0, &map);
745 delete back_map;
746
747 ASSERT_FALSE(BacktraceMap::IsValid(map));
Christopher Ferris7937a362018-01-18 11:15:49 -0800748 ASSERT_EQ(static_cast<uint64_t>(0), map.start);
749 ASSERT_EQ(static_cast<uint64_t>(0), map.end);
Christopher Ferris12385e32015-02-06 13:22:01 -0800750 ASSERT_EQ(0, map.flags);
751 ASSERT_EQ("", map.name);
752}
753
Christopher Ferris17e91d42013-10-21 13:30:52 -0700754TEST(libbacktrace, format_test) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700755 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD));
756 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris17e91d42013-10-21 13:30:52 -0700757
Christopher Ferris20303f82014-01-10 16:33:16 -0800758 backtrace_frame_data_t frame;
Christopher Ferris46756822014-01-14 20:16:30 -0800759 frame.num = 1;
760 frame.pc = 2;
Christopher Ferris96722b02017-07-19 14:20:46 -0700761 frame.rel_pc = 2;
Christopher Ferris46756822014-01-14 20:16:30 -0800762 frame.sp = 0;
763 frame.stack_size = 0;
Christopher Ferris46756822014-01-14 20:16:30 -0800764 frame.func_offset = 0;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700765
Christopher Ferris46756822014-01-14 20:16:30 -0800766 // Check no map set.
Christopher Ferris20303f82014-01-10 16:33:16 -0800767 frame.num = 1;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700768#if defined(__LP64__)
Christopher Ferris46756822014-01-14 20:16:30 -0800769 EXPECT_EQ("#01 pc 0000000000000002 <unknown>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700770#else
Christopher Ferris46756822014-01-14 20:16:30 -0800771 EXPECT_EQ("#01 pc 00000002 <unknown>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700772#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800773 backtrace->FormatFrameData(&frame));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700774
Christopher Ferris46756822014-01-14 20:16:30 -0800775 // Check map name empty, but exists.
Christopher Ferrisda750a72015-11-30 13:36:08 -0800776 frame.pc = 0xb0020;
Christopher Ferris96722b02017-07-19 14:20:46 -0700777 frame.rel_pc = 0x20;
Christopher Ferrisda750a72015-11-30 13:36:08 -0800778 frame.map.start = 0xb0000;
779 frame.map.end = 0xbffff;
Christopher Ferris96722b02017-07-19 14:20:46 -0700780 frame.map.load_bias = 0;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700781#if defined(__LP64__)
Christopher Ferrisda750a72015-11-30 13:36:08 -0800782 EXPECT_EQ("#01 pc 0000000000000020 <anonymous:00000000000b0000>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700783#else
Christopher Ferrisda750a72015-11-30 13:36:08 -0800784 EXPECT_EQ("#01 pc 00000020 <anonymous:000b0000>",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700785#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800786 backtrace->FormatFrameData(&frame));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700787
Christopher Ferrisda750a72015-11-30 13:36:08 -0800788 // Check map name begins with a [.
789 frame.pc = 0xc0020;
790 frame.map.start = 0xc0000;
791 frame.map.end = 0xcffff;
Christopher Ferris96722b02017-07-19 14:20:46 -0700792 frame.map.load_bias = 0;
Christopher Ferrisda750a72015-11-30 13:36:08 -0800793 frame.map.name = "[anon:thread signal stack]";
794#if defined(__LP64__)
795 EXPECT_EQ("#01 pc 0000000000000020 [anon:thread signal stack:00000000000c0000]",
796#else
797 EXPECT_EQ("#01 pc 00000020 [anon:thread signal stack:000c0000]",
798#endif
799 backtrace->FormatFrameData(&frame));
Christopher Ferris46756822014-01-14 20:16:30 -0800800
801 // Check relative pc is set and map name is set.
802 frame.pc = 0x12345679;
Christopher Ferris96722b02017-07-19 14:20:46 -0700803 frame.rel_pc = 0x12345678;
Christopher Ferris12385e32015-02-06 13:22:01 -0800804 frame.map.name = "MapFake";
805 frame.map.start = 1;
806 frame.map.end = 1;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700807#if defined(__LP64__)
Christopher Ferris46756822014-01-14 20:16:30 -0800808 EXPECT_EQ("#01 pc 0000000012345678 MapFake",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700809#else
Christopher Ferris46756822014-01-14 20:16:30 -0800810 EXPECT_EQ("#01 pc 12345678 MapFake",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700811#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800812 backtrace->FormatFrameData(&frame));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700813
Christopher Ferris46756822014-01-14 20:16:30 -0800814 // Check func_name is set, but no func offset.
815 frame.func_name = "ProcFake";
816#if defined(__LP64__)
817 EXPECT_EQ("#01 pc 0000000012345678 MapFake (ProcFake)",
818#else
819 EXPECT_EQ("#01 pc 12345678 MapFake (ProcFake)",
820#endif
821 backtrace->FormatFrameData(&frame));
822
823 // Check func_name is set, and func offset is non-zero.
Christopher Ferris20303f82014-01-10 16:33:16 -0800824 frame.func_offset = 645;
Christopher Ferris17e91d42013-10-21 13:30:52 -0700825#if defined(__LP64__)
Christopher Ferris46756822014-01-14 20:16:30 -0800826 EXPECT_EQ("#01 pc 0000000012345678 MapFake (ProcFake+645)",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700827#else
Christopher Ferris46756822014-01-14 20:16:30 -0800828 EXPECT_EQ("#01 pc 12345678 MapFake (ProcFake+645)",
Christopher Ferris17e91d42013-10-21 13:30:52 -0700829#endif
Christopher Ferris46756822014-01-14 20:16:30 -0800830 backtrace->FormatFrameData(&frame));
Christopher Ferris2106f4b2015-05-01 15:02:03 -0700831
Christopher Ferris96722b02017-07-19 14:20:46 -0700832 // Check func_name is set, func offset is non-zero, and load_bias is non-zero.
833 frame.rel_pc = 0x123456dc;
Christopher Ferris2106f4b2015-05-01 15:02:03 -0700834 frame.func_offset = 645;
Christopher Ferris96722b02017-07-19 14:20:46 -0700835 frame.map.load_bias = 100;
Christopher Ferris2106f4b2015-05-01 15:02:03 -0700836#if defined(__LP64__)
837 EXPECT_EQ("#01 pc 00000000123456dc MapFake (ProcFake+645)",
838#else
839 EXPECT_EQ("#01 pc 123456dc MapFake (ProcFake+645)",
840#endif
841 backtrace->FormatFrameData(&frame));
Christopher Ferrise0ab2322015-08-20 11:16:54 -0700842
843 // Check a non-zero map offset.
844 frame.map.offset = 0x1000;
845#if defined(__LP64__)
846 EXPECT_EQ("#01 pc 00000000123456dc MapFake (offset 0x1000) (ProcFake+645)",
847#else
848 EXPECT_EQ("#01 pc 123456dc MapFake (offset 0x1000) (ProcFake+645)",
849#endif
850 backtrace->FormatFrameData(&frame));
Christopher Ferris17e91d42013-10-21 13:30:52 -0700851}
Christopher Ferrise2960912014-03-07 19:42:19 -0800852
853struct map_test_t {
Christopher Ferris7937a362018-01-18 11:15:49 -0800854 uint64_t start;
855 uint64_t end;
Christopher Ferrise2960912014-03-07 19:42:19 -0800856};
857
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700858static bool map_sort(map_test_t i, map_test_t j) { return i.start < j.start; }
Christopher Ferrise2960912014-03-07 19:42:19 -0800859
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800860static std::string GetTestMapsAsString(const std::vector<map_test_t>& maps) {
861 if (maps.size() == 0) {
862 return "No test map entries\n";
863 }
864 std::string map_txt;
865 for (auto map : maps) {
Christopher Ferris7937a362018-01-18 11:15:49 -0800866 map_txt += android::base::StringPrintf("%" PRIx64 "-%" PRIx64 "\n", map.start, map.end);
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800867 }
868 return map_txt;
869}
870
871static std::string GetMapsAsString(BacktraceMap* maps) {
872 if (maps->size() == 0) {
873 return "No map entries\n";
874 }
875 std::string map_txt;
876 for (const backtrace_map_t* map : *maps) {
877 map_txt += android::base::StringPrintf(
Christopher Ferris7937a362018-01-18 11:15:49 -0800878 "%" PRIx64 "-%" PRIx64 " flags: 0x%x offset: 0x%" PRIx64 " load_bias: 0x%" PRIx64,
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800879 map->start, map->end, map->flags, map->offset, map->load_bias);
880 if (!map->name.empty()) {
881 map_txt += ' ' + map->name;
882 }
883 map_txt += '\n';
884 }
885 return map_txt;
886}
887
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700888static void VerifyMap(pid_t pid) {
Christopher Ferrise2960912014-03-07 19:42:19 -0800889 char buffer[4096];
890 snprintf(buffer, sizeof(buffer), "/proc/%d/maps", pid);
891
892 FILE* map_file = fopen(buffer, "r");
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700893 ASSERT_TRUE(map_file != nullptr);
Christopher Ferrise2960912014-03-07 19:42:19 -0800894 std::vector<map_test_t> test_maps;
895 while (fgets(buffer, sizeof(buffer), map_file)) {
896 map_test_t map;
Christopher Ferris7937a362018-01-18 11:15:49 -0800897 ASSERT_EQ(2, sscanf(buffer, "%" SCNx64 "-%" SCNx64 " ", &map.start, &map.end));
Christopher Ferrise2960912014-03-07 19:42:19 -0800898 test_maps.push_back(map);
899 }
900 fclose(map_file);
901 std::sort(test_maps.begin(), test_maps.end(), map_sort);
902
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700903 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(pid));
Christopher Ferrise2960912014-03-07 19:42:19 -0800904
905 // Basic test that verifies that the map is in the expected order.
Christopher Ferrisb7de5f52017-12-01 21:37:37 -0800906 auto test_it = test_maps.begin();
907 for (auto it = map->begin(); it != map->end(); ++it) {
908 ASSERT_TRUE(test_it != test_maps.end()) << "Mismatch in number of maps, expected test maps:\n"
909 << GetTestMapsAsString(test_maps) << "Actual maps:\n"
910 << GetMapsAsString(map.get());
911 ASSERT_EQ(test_it->start, (*it)->start) << "Mismatch in map data, expected test maps:\n"
912 << GetTestMapsAsString(test_maps) << "Actual maps:\n"
913 << GetMapsAsString(map.get());
914 ASSERT_EQ(test_it->end, (*it)->end) << "Mismatch maps in map data, expected test maps:\n"
915 << GetTestMapsAsString(test_maps) << "Actual maps:\n"
916 << GetMapsAsString(map.get());
917 // Make sure the load bias get set to a value.
918 ASSERT_NE(static_cast<uint64_t>(-1), (*it)->load_bias) << "Found uninitialized load_bias\n"
919 << GetMapsAsString(map.get());
Christopher Ferrise2960912014-03-07 19:42:19 -0800920 ++test_it;
921 }
922 ASSERT_TRUE(test_it == test_maps.end());
923}
924
925TEST(libbacktrace, verify_map_remote) {
926 pid_t pid;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700927 CreateRemoteProcess(&pid);
Christopher Ferrise2960912014-03-07 19:42:19 -0800928
929 // The maps should match exactly since the forked process has been paused.
930 VerifyMap(pid);
931
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700932 FinishRemoteProcess(pid);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700933}
934
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700935static void InitMemory(uint8_t* memory, size_t bytes) {
Christopher Ferris944f4172015-05-06 16:36:34 -0700936 for (size_t i = 0; i < bytes; i++) {
937 memory[i] = i;
938 if (memory[i] == '\0') {
939 // Don't use '\0' in our data so we can verify that an overread doesn't
940 // occur by using a '\0' as the character after the read data.
941 memory[i] = 23;
942 }
943 }
944}
945
Christopher Ferris82f3bbd2017-03-14 15:22:26 -0700946static void* ThreadReadTest(void* data) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700947 thread_t* thread_data = reinterpret_cast<thread_t*>(data);
948
949 thread_data->tid = gettid();
950
951 // Create two map pages.
952 // Mark the second page as not-readable.
953 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
954 uint8_t* memory;
955 if (posix_memalign(reinterpret_cast<void**>(&memory), pagesize, 2 * pagesize) != 0) {
956 return reinterpret_cast<void*>(-1);
957 }
958
959 if (mprotect(&memory[pagesize], pagesize, PROT_NONE) != 0) {
960 return reinterpret_cast<void*>(-1);
961 }
962
963 // Set up a simple pattern in memory.
Christopher Ferris944f4172015-05-06 16:36:34 -0700964 InitMemory(memory, pagesize);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700965
966 thread_data->data = memory;
967
968 // Tell the caller it's okay to start reading memory.
969 android_atomic_acquire_store(1, &thread_data->state);
970
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700971 // Loop waiting for the caller to finish reading the memory.
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700972 while (thread_data->state) {
973 }
974
Christopher Ferris2c43cff2015-03-26 19:18:36 -0700975 // Re-enable read-write on the page so that we don't crash if we try
976 // and access data on this page when freeing the memory.
977 if (mprotect(&memory[pagesize], pagesize, PROT_READ | PROT_WRITE) != 0) {
978 return reinterpret_cast<void*>(-1);
979 }
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700980 free(memory);
981
982 android_atomic_acquire_store(1, &thread_data->state);
983
984 return nullptr;
985}
986
Christopher Ferris7937a362018-01-18 11:15:49 -0800987static void RunReadTest(Backtrace* backtrace, uint64_t read_addr) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700988 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
989
990 // Create a page of data to use to do quick compares.
991 uint8_t* expected = new uint8_t[pagesize];
Christopher Ferris944f4172015-05-06 16:36:34 -0700992 InitMemory(expected, pagesize);
993
Christopher Ferris2b4a63f2015-03-17 14:42:03 -0700994 uint8_t* data = new uint8_t[2*pagesize];
995 // Verify that we can only read one page worth of data.
996 size_t bytes_read = backtrace->Read(read_addr, data, 2 * pagesize);
997 ASSERT_EQ(pagesize, bytes_read);
998 ASSERT_TRUE(memcmp(data, expected, pagesize) == 0);
999
1000 // Verify unaligned reads.
1001 for (size_t i = 1; i < sizeof(word_t); i++) {
1002 bytes_read = backtrace->Read(read_addr + i, data, 2 * sizeof(word_t));
1003 ASSERT_EQ(2 * sizeof(word_t), bytes_read);
1004 ASSERT_TRUE(memcmp(data, &expected[i], 2 * sizeof(word_t)) == 0)
1005 << "Offset at " << i << " failed";
1006 }
Christopher Ferris944f4172015-05-06 16:36:34 -07001007
1008 // Verify small unaligned reads.
1009 for (size_t i = 1; i < sizeof(word_t); i++) {
1010 for (size_t j = 1; j < sizeof(word_t); j++) {
1011 // Set one byte past what we expect to read, to guarantee we don't overread.
1012 data[j] = '\0';
1013 bytes_read = backtrace->Read(read_addr + i, data, j);
1014 ASSERT_EQ(j, bytes_read);
1015 ASSERT_TRUE(memcmp(data, &expected[i], j) == 0)
1016 << "Offset at " << i << " length " << j << " miscompared";
1017 ASSERT_EQ('\0', data[j])
1018 << "Offset at " << i << " length " << j << " wrote too much data";
1019 }
1020 }
Pirama Arumuga Nainar837eff22015-07-09 10:50:04 -07001021 delete[] data;
1022 delete[] expected;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001023}
1024
1025TEST(libbacktrace, thread_read) {
1026 pthread_attr_t attr;
1027 pthread_attr_init(&attr);
1028 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1029 pthread_t thread;
1030 thread_t thread_data = { 0, 0, 0, nullptr };
1031 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadReadTest, &thread_data) == 0);
1032
1033 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10));
1034
1035 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
1036 ASSERT_TRUE(backtrace.get() != nullptr);
1037
Christopher Ferris7937a362018-01-18 11:15:49 -08001038 RunReadTest(backtrace.get(), reinterpret_cast<uint64_t>(thread_data.data));
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001039
1040 android_atomic_acquire_store(0, &thread_data.state);
1041
1042 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10));
1043}
1044
Christopher Ferris7937a362018-01-18 11:15:49 -08001045volatile uint64_t g_ready = 0;
1046volatile uint64_t g_addr = 0;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001047
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001048static void ForkedReadTest() {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001049 // Create two map pages.
1050 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
1051 uint8_t* memory;
1052 if (posix_memalign(reinterpret_cast<void**>(&memory), pagesize, 2 * pagesize) != 0) {
1053 perror("Failed to allocate memory\n");
1054 exit(1);
1055 }
1056
1057 // Mark the second page as not-readable.
1058 if (mprotect(&memory[pagesize], pagesize, PROT_NONE) != 0) {
1059 perror("Failed to mprotect memory\n");
1060 exit(1);
1061 }
1062
1063 // Set up a simple pattern in memory.
Christopher Ferris944f4172015-05-06 16:36:34 -07001064 InitMemory(memory, pagesize);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001065
Christopher Ferris7937a362018-01-18 11:15:49 -08001066 g_addr = reinterpret_cast<uint64_t>(memory);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001067 g_ready = 1;
1068
1069 while (1) {
1070 usleep(US_PER_MSEC);
1071 }
1072}
1073
1074TEST(libbacktrace, process_read) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001075 g_ready = 0;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001076 pid_t pid;
1077 if ((pid = fork()) == 0) {
1078 ForkedReadTest();
1079 exit(0);
1080 }
1081 ASSERT_NE(-1, pid);
1082
1083 bool test_executed = false;
1084 uint64_t start = NanoTime();
1085 while (1) {
1086 if (ptrace(PTRACE_ATTACH, pid, 0, 0) == 0) {
1087 WaitForStop(pid);
1088
1089 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
Christopher Ferris97e00bb2015-04-02 14:22:31 -07001090 ASSERT_TRUE(backtrace.get() != nullptr);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001091
Christopher Ferris7937a362018-01-18 11:15:49 -08001092 uint64_t read_addr;
1093 size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
1094 reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t));
1095 ASSERT_EQ(sizeof(uint64_t), bytes_read);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001096 if (read_addr) {
1097 // The forked process is ready to be read.
Christopher Ferris7937a362018-01-18 11:15:49 -08001098 bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
1099 reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t));
1100 ASSERT_EQ(sizeof(uint64_t), bytes_read);
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001101
1102 RunReadTest(backtrace.get(), read_addr);
1103
1104 test_executed = true;
1105 break;
1106 }
1107 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1108 }
1109 if ((NanoTime() - start) > 5 * NS_PER_SEC) {
1110 break;
1111 }
1112 usleep(US_PER_MSEC);
1113 }
1114 kill(pid, SIGKILL);
1115 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
1116
1117 ASSERT_TRUE(test_executed);
Christopher Ferrise2960912014-03-07 19:42:19 -08001118}
1119
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001120static void VerifyFunctionsFound(const std::vector<std::string>& found_functions) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001121 // We expect to find these functions in libbacktrace_test. If we don't
1122 // find them, that's a bug in the memory read handling code in libunwind.
1123 std::list<std::string> expected_functions;
1124 expected_functions.push_back("test_recursive_call");
1125 expected_functions.push_back("test_level_one");
1126 expected_functions.push_back("test_level_two");
1127 expected_functions.push_back("test_level_three");
1128 expected_functions.push_back("test_level_four");
1129 for (const auto& found_function : found_functions) {
1130 for (const auto& expected_function : expected_functions) {
1131 if (found_function == expected_function) {
1132 expected_functions.remove(found_function);
1133 break;
1134 }
1135 }
1136 }
1137 ASSERT_TRUE(expected_functions.empty()) << "Not all functions found in shared library.";
1138}
1139
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001140static const char* CopySharedLibrary() {
Christopher Ferris67aba682015-05-08 15:44:46 -07001141#if defined(__LP64__)
1142 const char* lib_name = "lib64";
1143#else
1144 const char* lib_name = "lib";
1145#endif
1146
1147#if defined(__BIONIC__)
1148 const char* tmp_so_name = "/data/local/tmp/libbacktrace_test.so";
1149 std::string cp_cmd = android::base::StringPrintf("cp /system/%s/libbacktrace_test.so %s",
1150 lib_name, tmp_so_name);
1151#else
1152 const char* tmp_so_name = "/tmp/libbacktrace_test.so";
1153 if (getenv("ANDROID_HOST_OUT") == NULL) {
1154 fprintf(stderr, "ANDROID_HOST_OUT not set, make sure you run lunch.");
1155 return nullptr;
1156 }
1157 std::string cp_cmd = android::base::StringPrintf("cp %s/%s/libbacktrace_test.so %s",
1158 getenv("ANDROID_HOST_OUT"), lib_name,
1159 tmp_so_name);
1160#endif
1161
1162 // Copy the shared so to a tempory directory.
1163 system(cp_cmd.c_str());
1164
1165 return tmp_so_name;
1166}
1167
1168TEST(libbacktrace, check_unreadable_elf_local) {
1169 const char* tmp_so_name = CopySharedLibrary();
1170 ASSERT_TRUE(tmp_so_name != nullptr);
1171
1172 struct stat buf;
1173 ASSERT_TRUE(stat(tmp_so_name, &buf) != -1);
Christopher Ferris7937a362018-01-18 11:15:49 -08001174 uint64_t map_size = buf.st_size;
Christopher Ferris67aba682015-05-08 15:44:46 -07001175
1176 int fd = open(tmp_so_name, O_RDONLY);
1177 ASSERT_TRUE(fd != -1);
1178
Christopher Ferris61c48ac2016-01-15 16:08:58 -08001179 void* map = mmap(NULL, map_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001180 ASSERT_TRUE(map != MAP_FAILED);
1181 close(fd);
1182 ASSERT_TRUE(unlink(tmp_so_name) != -1);
1183
1184 std::vector<std::string> found_functions;
1185 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS,
1186 BACKTRACE_CURRENT_THREAD));
1187 ASSERT_TRUE(backtrace.get() != nullptr);
1188
1189 // Needed before GetFunctionName will work.
1190 backtrace->Unwind(0);
1191
1192 // Loop through the entire map, and get every function we can find.
Christopher Ferris7937a362018-01-18 11:15:49 -08001193 map_size += reinterpret_cast<uint64_t>(map);
Christopher Ferris67aba682015-05-08 15:44:46 -07001194 std::string last_func;
Christopher Ferris7937a362018-01-18 11:15:49 -08001195 for (uint64_t read_addr = reinterpret_cast<uint64_t>(map); read_addr < map_size; read_addr += 4) {
1196 uint64_t offset;
Christopher Ferris67aba682015-05-08 15:44:46 -07001197 std::string func_name = backtrace->GetFunctionName(read_addr, &offset);
1198 if (!func_name.empty() && last_func != func_name) {
1199 found_functions.push_back(func_name);
1200 }
1201 last_func = func_name;
1202 }
1203
Christopher Ferris7937a362018-01-18 11:15:49 -08001204 ASSERT_TRUE(munmap(map, map_size - reinterpret_cast<uint64_t>(map)) == 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001205
1206 VerifyFunctionsFound(found_functions);
1207}
1208
1209TEST(libbacktrace, check_unreadable_elf_remote) {
1210 const char* tmp_so_name = CopySharedLibrary();
1211 ASSERT_TRUE(tmp_so_name != nullptr);
1212
1213 g_ready = 0;
1214
1215 struct stat buf;
1216 ASSERT_TRUE(stat(tmp_so_name, &buf) != -1);
Christopher Ferris7937a362018-01-18 11:15:49 -08001217 uint64_t map_size = buf.st_size;
Christopher Ferris67aba682015-05-08 15:44:46 -07001218
1219 pid_t pid;
1220 if ((pid = fork()) == 0) {
1221 int fd = open(tmp_so_name, O_RDONLY);
1222 if (fd == -1) {
1223 fprintf(stderr, "Failed to open file %s: %s\n", tmp_so_name, strerror(errno));
1224 unlink(tmp_so_name);
1225 exit(0);
1226 }
1227
Christopher Ferris61c48ac2016-01-15 16:08:58 -08001228 void* map = mmap(NULL, map_size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001229 if (map == MAP_FAILED) {
1230 fprintf(stderr, "Failed to map in memory: %s\n", strerror(errno));
1231 unlink(tmp_so_name);
1232 exit(0);
1233 }
1234 close(fd);
1235 if (unlink(tmp_so_name) == -1) {
1236 fprintf(stderr, "Failed to unlink: %s\n", strerror(errno));
1237 exit(0);
1238 }
1239
Christopher Ferris7937a362018-01-18 11:15:49 -08001240 g_addr = reinterpret_cast<uint64_t>(map);
Christopher Ferris67aba682015-05-08 15:44:46 -07001241 g_ready = 1;
1242 while (true) {
1243 usleep(US_PER_MSEC);
1244 }
1245 exit(0);
1246 }
1247 ASSERT_TRUE(pid > 0);
1248
1249 std::vector<std::string> found_functions;
1250 uint64_t start = NanoTime();
1251 while (true) {
1252 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1253
1254 // Wait for the process to get to a stopping point.
1255 WaitForStop(pid);
1256
1257 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
1258 ASSERT_TRUE(backtrace.get() != nullptr);
1259
Christopher Ferris7937a362018-01-18 11:15:49 -08001260 uint64_t read_addr;
1261 ASSERT_EQ(sizeof(uint64_t),
1262 backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
1263 reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t)));
Christopher Ferris67aba682015-05-08 15:44:46 -07001264 if (read_addr) {
Christopher Ferris7937a362018-01-18 11:15:49 -08001265 ASSERT_EQ(sizeof(uint64_t),
1266 backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
1267 reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t)));
Christopher Ferris67aba682015-05-08 15:44:46 -07001268
1269 // Needed before GetFunctionName will work.
1270 backtrace->Unwind(0);
1271
1272 // Loop through the entire map, and get every function we can find.
1273 map_size += read_addr;
1274 std::string last_func;
1275 for (; read_addr < map_size; read_addr += 4) {
Christopher Ferris7937a362018-01-18 11:15:49 -08001276 uint64_t offset;
Christopher Ferris67aba682015-05-08 15:44:46 -07001277 std::string func_name = backtrace->GetFunctionName(read_addr, &offset);
1278 if (!func_name.empty() && last_func != func_name) {
1279 found_functions.push_back(func_name);
1280 }
1281 last_func = func_name;
1282 }
1283 break;
1284 }
1285 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1286
1287 if ((NanoTime() - start) > 5 * NS_PER_SEC) {
1288 break;
1289 }
1290 usleep(US_PER_MSEC);
1291 }
1292
1293 kill(pid, SIGKILL);
1294 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
1295
1296 VerifyFunctionsFound(found_functions);
1297}
1298
Christopher Ferris7937a362018-01-18 11:15:49 -08001299static bool FindFuncFrameInBacktrace(Backtrace* backtrace, uint64_t test_func, size_t* frame_num) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001300 backtrace_map_t map;
1301 backtrace->FillInMap(test_func, &map);
1302 if (!BacktraceMap::IsValid(map)) {
1303 return false;
1304 }
1305
1306 // Loop through the frames, and find the one that is in the map.
1307 *frame_num = 0;
1308 for (Backtrace::const_iterator it = backtrace->begin(); it != backtrace->end(); ++it) {
1309 if (BacktraceMap::IsValid(it->map) && map.start == it->map.start &&
1310 it->pc >= test_func) {
1311 *frame_num = it->num;
1312 return true;
1313 }
1314 }
1315 return false;
1316}
1317
Christopher Ferris7937a362018-01-18 11:15:49 -08001318static void VerifyUnreadableElfFrame(Backtrace* backtrace, uint64_t test_func, size_t frame_num) {
Christopher Ferris67aba682015-05-08 15:44:46 -07001319 ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
1320 << DumpFrames(backtrace);
1321
1322 ASSERT_TRUE(frame_num != 0) << DumpFrames(backtrace);
1323 // Make sure that there is at least one more frame above the test func call.
1324 ASSERT_LT(frame_num, backtrace->NumFrames()) << DumpFrames(backtrace);
1325
Christopher Ferris7937a362018-01-18 11:15:49 -08001326 uint64_t diff = backtrace->GetFrame(frame_num)->pc - test_func;
Christopher Ferris67aba682015-05-08 15:44:46 -07001327 ASSERT_LT(diff, 200U) << DumpFrames(backtrace);
1328}
1329
Christopher Ferris7937a362018-01-18 11:15:49 -08001330static void VerifyUnreadableElfBacktrace(void* func) {
1331 uint64_t test_func = reinterpret_cast<uint64_t>(func);
Christopher Ferris67aba682015-05-08 15:44:46 -07001332 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS,
1333 BACKTRACE_CURRENT_THREAD));
1334 ASSERT_TRUE(backtrace.get() != nullptr);
1335 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -08001336 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris67aba682015-05-08 15:44:46 -07001337
1338 size_t frame_num;
1339 ASSERT_TRUE(FindFuncFrameInBacktrace(backtrace.get(), test_func, &frame_num));
1340
1341 VerifyUnreadableElfFrame(backtrace.get(), test_func, frame_num);
1342}
1343
Christopher Ferris7937a362018-01-18 11:15:49 -08001344typedef int (*test_func_t)(int, int, int, int, void (*)(void*), void*);
Christopher Ferris67aba682015-05-08 15:44:46 -07001345
1346TEST(libbacktrace, unwind_through_unreadable_elf_local) {
1347 const char* tmp_so_name = CopySharedLibrary();
1348 ASSERT_TRUE(tmp_so_name != nullptr);
1349 void* lib_handle = dlopen(tmp_so_name, RTLD_NOW);
1350 ASSERT_TRUE(lib_handle != nullptr);
1351 ASSERT_TRUE(unlink(tmp_so_name) != -1);
1352
1353 test_func_t test_func;
1354 test_func = reinterpret_cast<test_func_t>(dlsym(lib_handle, "test_level_one"));
1355 ASSERT_TRUE(test_func != nullptr);
1356
Christopher Ferris7937a362018-01-18 11:15:49 -08001357 ASSERT_NE(test_func(1, 2, 3, 4, VerifyUnreadableElfBacktrace, reinterpret_cast<void*>(test_func)),
1358 0);
Christopher Ferris67aba682015-05-08 15:44:46 -07001359
1360 ASSERT_TRUE(dlclose(lib_handle) == 0);
1361}
1362
1363TEST(libbacktrace, unwind_through_unreadable_elf_remote) {
1364 const char* tmp_so_name = CopySharedLibrary();
1365 ASSERT_TRUE(tmp_so_name != nullptr);
1366 void* lib_handle = dlopen(tmp_so_name, RTLD_NOW);
1367 ASSERT_TRUE(lib_handle != nullptr);
1368 ASSERT_TRUE(unlink(tmp_so_name) != -1);
1369
1370 test_func_t test_func;
1371 test_func = reinterpret_cast<test_func_t>(dlsym(lib_handle, "test_level_one"));
1372 ASSERT_TRUE(test_func != nullptr);
1373
1374 pid_t pid;
1375 if ((pid = fork()) == 0) {
1376 test_func(1, 2, 3, 4, 0, 0);
1377 exit(0);
1378 }
1379 ASSERT_TRUE(pid > 0);
1380 ASSERT_TRUE(dlclose(lib_handle) == 0);
1381
1382 uint64_t start = NanoTime();
1383 bool done = false;
1384 while (!done) {
1385 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1386
1387 // Wait for the process to get to a stopping point.
1388 WaitForStop(pid);
1389
1390 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
1391 ASSERT_TRUE(backtrace.get() != nullptr);
1392 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -08001393 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferris67aba682015-05-08 15:44:46 -07001394
1395 size_t frame_num;
Christopher Ferris7937a362018-01-18 11:15:49 -08001396 if (FindFuncFrameInBacktrace(backtrace.get(), reinterpret_cast<uint64_t>(test_func),
1397 &frame_num)) {
1398 VerifyUnreadableElfFrame(backtrace.get(), reinterpret_cast<uint64_t>(test_func), frame_num);
Christopher Ferris67aba682015-05-08 15:44:46 -07001399 done = true;
1400 }
1401
1402 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1403
1404 if ((NanoTime() - start) > 5 * NS_PER_SEC) {
1405 break;
1406 }
1407 usleep(US_PER_MSEC);
1408 }
1409
1410 kill(pid, SIGKILL);
1411 ASSERT_EQ(waitpid(pid, nullptr, 0), pid);
1412
1413 ASSERT_TRUE(done) << "Test function never found in unwind.";
1414}
1415
Christopher Ferris206a3b92016-03-09 14:35:54 -08001416TEST(libbacktrace, unwind_thread_doesnt_exist) {
1417 std::unique_ptr<Backtrace> backtrace(
1418 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, 99999999));
1419 ASSERT_TRUE(backtrace.get() != nullptr);
1420 ASSERT_FALSE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -08001421 ASSERT_EQ(BACKTRACE_UNWIND_ERROR_THREAD_DOESNT_EXIST, backtrace->GetError().error_code);
Christopher Ferris206a3b92016-03-09 14:35:54 -08001422}
1423
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001424TEST(libbacktrace, local_get_function_name_before_unwind) {
1425 std::unique_ptr<Backtrace> backtrace(
1426 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
1427 ASSERT_TRUE(backtrace.get() != nullptr);
1428
1429 // Verify that trying to get a function name before doing an unwind works.
Christopher Ferris7937a362018-01-18 11:15:49 -08001430 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
1431 uint64_t offset;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001432 ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
1433}
1434
1435TEST(libbacktrace, remote_get_function_name_before_unwind) {
1436 pid_t pid;
1437 CreateRemoteProcess(&pid);
1438
1439 // Now create an unwind object.
1440 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
1441
1442 // Verify that trying to get a function name before doing an unwind works.
Christopher Ferris7937a362018-01-18 11:15:49 -08001443 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
1444 uint64_t offset;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001445 ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
1446
1447 FinishRemoteProcess(pid);
1448}
1449
Christopher Ferris7937a362018-01-18 11:15:49 -08001450static void SetUcontextSp(uint64_t sp, ucontext_t* ucontext) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001451#if defined(__arm__)
1452 ucontext->uc_mcontext.arm_sp = sp;
1453#elif defined(__aarch64__)
1454 ucontext->uc_mcontext.sp = sp;
1455#elif defined(__i386__)
1456 ucontext->uc_mcontext.gregs[REG_ESP] = sp;
1457#elif defined(__x86_64__)
1458 ucontext->uc_mcontext.gregs[REG_RSP] = sp;
1459#else
1460 UNUSED(sp);
1461 UNUSED(ucontext);
1462 ASSERT_TRUE(false) << "Unsupported architecture";
1463#endif
1464}
1465
Christopher Ferris7937a362018-01-18 11:15:49 -08001466static void SetUcontextPc(uint64_t pc, ucontext_t* ucontext) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001467#if defined(__arm__)
1468 ucontext->uc_mcontext.arm_pc = pc;
1469#elif defined(__aarch64__)
1470 ucontext->uc_mcontext.pc = pc;
1471#elif defined(__i386__)
1472 ucontext->uc_mcontext.gregs[REG_EIP] = pc;
1473#elif defined(__x86_64__)
1474 ucontext->uc_mcontext.gregs[REG_RIP] = pc;
1475#else
1476 UNUSED(pc);
1477 UNUSED(ucontext);
1478 ASSERT_TRUE(false) << "Unsupported architecture";
1479#endif
1480}
1481
Christopher Ferris7937a362018-01-18 11:15:49 -08001482static void SetUcontextLr(uint64_t lr, ucontext_t* ucontext) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001483#if defined(__arm__)
1484 ucontext->uc_mcontext.arm_lr = lr;
1485#elif defined(__aarch64__)
1486 ucontext->uc_mcontext.regs[30] = lr;
1487#elif defined(__i386__)
1488 // The lr is on the stack.
1489 ASSERT_TRUE(lr != 0);
1490 ASSERT_TRUE(ucontext != nullptr);
1491#elif defined(__x86_64__)
1492 // The lr is on the stack.
1493 ASSERT_TRUE(lr != 0);
1494 ASSERT_TRUE(ucontext != nullptr);
1495#else
1496 UNUSED(lr);
1497 UNUSED(ucontext);
1498 ASSERT_TRUE(false) << "Unsupported architecture";
1499#endif
1500}
1501
1502static constexpr size_t DEVICE_MAP_SIZE = 1024;
1503
1504static void SetupDeviceMap(void** device_map) {
1505 // Make sure that anything in a device map will result in fails
1506 // to read.
1507 android::base::unique_fd device_fd(open("/dev/zero", O_RDONLY | O_CLOEXEC));
1508
1509 *device_map = mmap(nullptr, 1024, PROT_READ, MAP_PRIVATE, device_fd, 0);
1510 ASSERT_TRUE(*device_map != MAP_FAILED);
1511
1512 // Make sure the map is readable.
1513 ASSERT_EQ(0, reinterpret_cast<int*>(*device_map)[0]);
1514}
1515
1516static void UnwindFromDevice(Backtrace* backtrace, void* device_map) {
Christopher Ferris7937a362018-01-18 11:15:49 -08001517 uint64_t device_map_uint = reinterpret_cast<uint64_t>(device_map);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001518
1519 backtrace_map_t map;
1520 backtrace->FillInMap(device_map_uint, &map);
1521 // Verify the flag is set.
1522 ASSERT_EQ(PROT_DEVICE_MAP, map.flags & PROT_DEVICE_MAP);
1523
1524 // Quick sanity checks.
Christopher Ferris7937a362018-01-18 11:15:49 -08001525 uint64_t offset;
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001526 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset));
1527 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset, &map));
1528 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(0, &offset));
1529
Christopher Ferris7937a362018-01-18 11:15:49 -08001530 uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001531 // Now verify the device map flag actually causes the function name to be empty.
1532 backtrace->FillInMap(cur_func_offset, &map);
1533 ASSERT_TRUE((map.flags & PROT_DEVICE_MAP) == 0);
1534 ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset, &map));
1535 map.flags |= PROT_DEVICE_MAP;
1536 ASSERT_EQ(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset, &map));
1537
1538 ucontext_t ucontext;
1539
1540 // Create a context that has the pc in the device map, but the sp
1541 // in a non-device map.
1542 memset(&ucontext, 0, sizeof(ucontext));
Christopher Ferris7937a362018-01-18 11:15:49 -08001543 SetUcontextSp(reinterpret_cast<uint64_t>(&ucontext), &ucontext);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001544 SetUcontextPc(device_map_uint, &ucontext);
1545 SetUcontextLr(cur_func_offset, &ucontext);
1546
1547 ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
1548
1549 // The buffer should only be a single element.
1550 ASSERT_EQ(1U, backtrace->NumFrames());
1551 const backtrace_frame_data_t* frame = backtrace->GetFrame(0);
1552 ASSERT_EQ(device_map_uint, frame->pc);
Christopher Ferris7937a362018-01-18 11:15:49 -08001553 ASSERT_EQ(reinterpret_cast<uint64_t>(&ucontext), frame->sp);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001554
1555 // Check what happens when skipping the first frame.
1556 ASSERT_TRUE(backtrace->Unwind(1, &ucontext));
1557 ASSERT_EQ(0U, backtrace->NumFrames());
1558
1559 // Create a context that has the sp in the device map, but the pc
1560 // in a non-device map.
1561 memset(&ucontext, 0, sizeof(ucontext));
1562 SetUcontextSp(device_map_uint, &ucontext);
1563 SetUcontextPc(cur_func_offset, &ucontext);
1564 SetUcontextLr(cur_func_offset, &ucontext);
1565
1566 ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
1567
1568 // The buffer should only be a single element.
1569 ASSERT_EQ(1U, backtrace->NumFrames());
1570 frame = backtrace->GetFrame(0);
1571 ASSERT_EQ(cur_func_offset, frame->pc);
1572 ASSERT_EQ(device_map_uint, frame->sp);
1573
1574 // Check what happens when skipping the first frame.
1575 ASSERT_TRUE(backtrace->Unwind(1, &ucontext));
1576 ASSERT_EQ(0U, backtrace->NumFrames());
1577}
1578
1579TEST(libbacktrace, unwind_disallow_device_map_local) {
1580 void* device_map;
1581 SetupDeviceMap(&device_map);
1582
1583 // Now create an unwind object.
1584 std::unique_ptr<Backtrace> backtrace(
1585 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
1586 ASSERT_TRUE(backtrace);
1587
1588 UnwindFromDevice(backtrace.get(), device_map);
1589
1590 munmap(device_map, DEVICE_MAP_SIZE);
1591}
1592
Christopher Ferris086baf92017-10-17 14:12:52 -07001593TEST(libbacktrace, unwind_disallow_device_map_remote) {
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001594 void* device_map;
1595 SetupDeviceMap(&device_map);
1596
1597 // Fork a process to do a remote backtrace.
1598 pid_t pid;
1599 CreateRemoteProcess(&pid);
1600
1601 // Now create an unwind object.
Christopher Ferris086baf92017-10-17 14:12:52 -07001602 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001603
Christopher Ferris458cc662017-08-28 16:31:18 -07001604 UnwindFromDevice(backtrace.get(), device_map);
Christopher Ferrisf5e568e2017-03-22 13:18:31 -07001605
1606 FinishRemoteProcess(pid);
1607
1608 munmap(device_map, DEVICE_MAP_SIZE);
1609}
1610
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001611class ScopedSignalHandler {
1612 public:
1613 ScopedSignalHandler(int signal_number, void (*handler)(int)) : signal_number_(signal_number) {
1614 memset(&action_, 0, sizeof(action_));
1615 action_.sa_handler = handler;
1616 sigaction(signal_number_, &action_, &old_action_);
1617 }
1618
1619 ScopedSignalHandler(int signal_number, void (*action)(int, siginfo_t*, void*))
1620 : signal_number_(signal_number) {
1621 memset(&action_, 0, sizeof(action_));
1622 action_.sa_flags = SA_SIGINFO;
1623 action_.sa_sigaction = action;
1624 sigaction(signal_number_, &action_, &old_action_);
1625 }
1626
1627 ~ScopedSignalHandler() { sigaction(signal_number_, &old_action_, nullptr); }
1628
1629 private:
1630 struct sigaction action_;
1631 struct sigaction old_action_;
1632 const int signal_number_;
1633};
1634
1635static void SetValueAndLoop(void* data) {
1636 volatile int* value = reinterpret_cast<volatile int*>(data);
1637
1638 *value = 1;
1639 for (volatile int i = 0;; i++)
1640 ;
1641}
1642
Christopher Ferrisb9de87f2017-09-20 13:37:24 -07001643static void UnwindThroughSignal(bool use_action, create_func_t create_func,
1644 map_create_func_t map_create_func) {
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001645 volatile int value = 0;
1646 pid_t pid;
1647 if ((pid = fork()) == 0) {
1648 if (use_action) {
1649 ScopedSignalHandler ssh(SIGUSR1, test_signal_action);
1650
1651 test_level_one(1, 2, 3, 4, SetValueAndLoop, const_cast<int*>(&value));
1652 } else {
1653 ScopedSignalHandler ssh(SIGUSR1, test_signal_handler);
1654
1655 test_level_one(1, 2, 3, 4, SetValueAndLoop, const_cast<int*>(&value));
1656 }
1657 }
1658 ASSERT_NE(-1, pid);
1659
1660 int read_value = 0;
1661 uint64_t start = NanoTime();
1662 while (read_value == 0) {
1663 usleep(1000);
1664
1665 // Loop until the remote function gets into the final function.
1666 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1667
1668 WaitForStop(pid);
1669
Christopher Ferrisb9de87f2017-09-20 13:37:24 -07001670 std::unique_ptr<BacktraceMap> map(map_create_func(pid, false));
1671 std::unique_ptr<Backtrace> backtrace(create_func(pid, pid, map.get()));
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001672
Christopher Ferris7937a362018-01-18 11:15:49 -08001673 size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(const_cast<int*>(&value)),
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001674 reinterpret_cast<uint8_t*>(&read_value), sizeof(read_value));
1675 ASSERT_EQ(sizeof(read_value), bytes_read);
1676
1677 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1678
1679 ASSERT_TRUE(NanoTime() - start < 5 * NS_PER_SEC)
1680 << "Remote process did not execute far enough in 5 seconds.";
1681 }
1682
1683 // Now need to send a signal to the remote process.
1684 kill(pid, SIGUSR1);
1685
1686 // Wait for the process to get to the signal handler loop.
1687 Backtrace::const_iterator frame_iter;
1688 start = NanoTime();
Christopher Ferris458cc662017-08-28 16:31:18 -07001689 std::unique_ptr<BacktraceMap> map;
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001690 std::unique_ptr<Backtrace> backtrace;
1691 while (true) {
1692 usleep(1000);
1693
1694 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0);
1695
1696 WaitForStop(pid);
1697
Christopher Ferrisb9de87f2017-09-20 13:37:24 -07001698 map.reset(map_create_func(pid, false));
Christopher Ferris458cc662017-08-28 16:31:18 -07001699 ASSERT_TRUE(map.get() != nullptr);
Christopher Ferrisb9de87f2017-09-20 13:37:24 -07001700 backtrace.reset(create_func(pid, pid, map.get()));
Christopher Ferris5ea2c1f2017-03-23 14:55:01 -07001701 ASSERT_TRUE(backtrace->Unwind(0));
1702 bool found = false;
1703 for (frame_iter = backtrace->begin(); frame_iter != backtrace->end(); ++frame_iter) {
1704 if (frame_iter->func_name == "test_loop_forever") {
1705 ++frame_iter;
1706 found = true;
1707 break;
1708 }
1709 }
1710 if (found) {
1711 break;
1712 }
1713
1714 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0);
1715
1716 ASSERT_TRUE(NanoTime() - start < 5 * NS_PER_SEC)
1717 << "Remote process did not get in signal handler in 5 seconds." << std::endl
1718 << DumpFrames(backtrace.get());
1719 }
1720
1721 std::vector<std::string> names;
1722 // Loop through the frames, and save the function names.
1723 size_t frame = 0;
1724 for (; frame_iter != backtrace->end(); ++frame_iter) {
1725 if (frame_iter->func_name == "test_level_four") {
1726 frame = names.size() + 1;
1727 }
1728 names.push_back(frame_iter->func_name);
1729 }
1730 ASSERT_NE(0U, frame) << "Unable to find test_level_four in backtrace" << std::endl
1731 << DumpFrames(backtrace.get());
1732
1733 // The expected order of the frames:
1734 // test_loop_forever
1735 // test_signal_handler|test_signal_action
1736 // <OPTIONAL_FRAME> May or may not exist.
1737 // SetValueAndLoop (but the function name might be empty)
1738 // test_level_four
1739 // test_level_three
1740 // test_level_two
1741 // test_level_one
1742 ASSERT_LE(frame + 2, names.size()) << DumpFrames(backtrace.get());
1743 ASSERT_LE(2U, frame) << DumpFrames(backtrace.get());
1744 if (use_action) {
1745 ASSERT_EQ("test_signal_action", names[0]) << DumpFrames(backtrace.get());
1746 } else {
1747 ASSERT_EQ("test_signal_handler", names[0]) << DumpFrames(backtrace.get());
1748 }
1749 ASSERT_EQ("test_level_three", names[frame]) << DumpFrames(backtrace.get());
1750 ASSERT_EQ("test_level_two", names[frame + 1]) << DumpFrames(backtrace.get());
1751 ASSERT_EQ("test_level_one", names[frame + 2]) << DumpFrames(backtrace.get());
1752
1753 FinishRemoteProcess(pid);
1754}
1755
Christopher Ferris96722b02017-07-19 14:20:46 -07001756TEST(libbacktrace, unwind_remote_through_signal_using_handler) {
Christopher Ferris458cc662017-08-28 16:31:18 -07001757 UnwindThroughSignal(false, Backtrace::Create, BacktraceMap::Create);
1758}
1759
Christopher Ferris96722b02017-07-19 14:20:46 -07001760TEST(libbacktrace, unwind_remote_through_signal_using_action) {
Christopher Ferris458cc662017-08-28 16:31:18 -07001761 UnwindThroughSignal(true, Backtrace::Create, BacktraceMap::Create);
1762}
1763
Josh Gaocd546c12017-10-25 15:21:45 -07001764static void TestFrameSkipNumbering(create_func_t create_func, map_create_func_t map_create_func) {
1765 std::unique_ptr<BacktraceMap> map(map_create_func(getpid(), false));
1766 std::unique_ptr<Backtrace> backtrace(create_func(getpid(), gettid(), map.get()));
1767 backtrace->Unwind(1);
1768 ASSERT_NE(0U, backtrace->NumFrames());
1769 ASSERT_EQ(0U, backtrace->GetFrame(0)->num);
1770}
1771
1772TEST(libbacktrace, unwind_frame_skip_numbering) {
1773 TestFrameSkipNumbering(Backtrace::Create, BacktraceMap::Create);
1774}
1775
Christopher Ferrise2960912014-03-07 19:42:19 -08001776#if defined(ENABLE_PSS_TESTS)
1777#include "GetPss.h"
1778
Chih-Hung Hsieh67867db2016-05-18 15:53:15 -07001779#define MAX_LEAK_BYTES (32*1024UL)
Christopher Ferrise2960912014-03-07 19:42:19 -08001780
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001781static void CheckForLeak(pid_t pid, pid_t tid) {
Christopher Ferris086baf92017-10-17 14:12:52 -07001782 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(pid));
1783
Christopher Ferrise2960912014-03-07 19:42:19 -08001784 // Do a few runs to get the PSS stable.
1785 for (size_t i = 0; i < 100; i++) {
Christopher Ferris086baf92017-10-17 14:12:52 -07001786 Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001787 ASSERT_TRUE(backtrace != nullptr);
Christopher Ferrise2960912014-03-07 19:42:19 -08001788 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -08001789 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferrise2960912014-03-07 19:42:19 -08001790 delete backtrace;
1791 }
1792 size_t stable_pss = GetPssBytes();
Christopher Ferris2c43cff2015-03-26 19:18:36 -07001793 ASSERT_TRUE(stable_pss != 0);
Christopher Ferrise2960912014-03-07 19:42:19 -08001794
1795 // Loop enough that even a small leak should be detectable.
1796 for (size_t i = 0; i < 4096; i++) {
Christopher Ferris086baf92017-10-17 14:12:52 -07001797 Backtrace* backtrace = Backtrace::Create(pid, tid, map.get());
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001798 ASSERT_TRUE(backtrace != nullptr);
Christopher Ferrise2960912014-03-07 19:42:19 -08001799 ASSERT_TRUE(backtrace->Unwind(0));
Yabin Cuif8808282017-12-12 18:04:10 -08001800 ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
Christopher Ferrise2960912014-03-07 19:42:19 -08001801 delete backtrace;
1802 }
1803 size_t new_pss = GetPssBytes();
Christopher Ferris2c43cff2015-03-26 19:18:36 -07001804 ASSERT_TRUE(new_pss != 0);
Christopher Ferris5ccdfa62016-03-07 19:18:31 -08001805 if (new_pss > stable_pss) {
1806 ASSERT_LE(new_pss - stable_pss, MAX_LEAK_BYTES);
1807 }
Christopher Ferrise2960912014-03-07 19:42:19 -08001808}
1809
1810TEST(libbacktrace, check_for_leak_local) {
1811 CheckForLeak(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD);
1812}
1813
1814TEST(libbacktrace, check_for_leak_local_thread) {
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001815 thread_t thread_data = { 0, 0, 0, nullptr };
Christopher Ferrise2960912014-03-07 19:42:19 -08001816 pthread_t thread;
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001817 ASSERT_TRUE(pthread_create(&thread, nullptr, ThreadLevelRun, &thread_data) == 0);
Christopher Ferrise2960912014-03-07 19:42:19 -08001818
1819 // Wait up to 2 seconds for the tid to be set.
1820 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2));
1821
1822 CheckForLeak(BACKTRACE_CURRENT_PROCESS, thread_data.tid);
1823
1824 // Tell the thread to exit its infinite loop.
1825 android_atomic_acquire_store(0, &thread_data.state);
1826
Christopher Ferris2b4a63f2015-03-17 14:42:03 -07001827 ASSERT_TRUE(pthread_join(thread, nullptr) == 0);
Christopher Ferrise2960912014-03-07 19:42:19 -08001828}
1829
1830TEST(libbacktrace, check_for_leak_remote) {
1831 pid_t pid;
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001832 CreateRemoteProcess(&pid);
Christopher Ferrise2960912014-03-07 19:42:19 -08001833
1834 CheckForLeak(pid, BACKTRACE_CURRENT_THREAD);
1835
Christopher Ferris82f3bbd2017-03-14 15:22:26 -07001836 FinishRemoteProcess(pid);
Christopher Ferrise2960912014-03-07 19:42:19 -08001837}
1838#endif