backtrace_test.cpp revision 428fad97a0c9c3def1489b16f0257a9cbcfd43f8
1/* 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 17#define _GNU_SOURCE 1 18#include <dirent.h> 19#include <errno.h> 20#include <inttypes.h> 21#include <pthread.h> 22#include <signal.h> 23#include <stdint.h> 24#include <stdio.h> 25#include <stdlib.h> 26#include <string.h> 27#include <sys/ptrace.h> 28#include <sys/types.h> 29#include <sys/wait.h> 30#include <time.h> 31#include <unistd.h> 32 33#include <algorithm> 34#include <memory> 35#include <string> 36#include <vector> 37 38#include <backtrace/Backtrace.h> 39#include <backtrace/BacktraceMap.h> 40 41#include <cutils/atomic.h> 42#include <cutils/threads.h> 43 44#include <gtest/gtest.h> 45 46// For the THREAD_SIGNAL definition. 47#include "BacktraceCurrent.h" 48#include "thread_utils.h" 49 50// Number of microseconds per milliseconds. 51#define US_PER_MSEC 1000 52 53// Number of nanoseconds in a second. 54#define NS_PER_SEC 1000000000ULL 55 56// Number of simultaneous dumping operations to perform. 57#define NUM_THREADS 40 58 59// Number of simultaneous threads running in our forked process. 60#define NUM_PTRACE_THREADS 5 61 62struct thread_t { 63 pid_t tid; 64 int32_t state; 65 pthread_t threadId; 66 void* data; 67}; 68 69struct dump_thread_t { 70 thread_t thread; 71 Backtrace* backtrace; 72 int32_t* now; 73 int32_t done; 74}; 75 76extern "C" { 77// Prototypes for functions in the test library. 78int test_level_one(int, int, int, int, void (*)(void*), void*); 79 80int test_recursive_call(int, void (*)(void*), void*); 81} 82 83uint64_t NanoTime() { 84 struct timespec t = { 0, 0 }; 85 clock_gettime(CLOCK_MONOTONIC, &t); 86 return static_cast<uint64_t>(t.tv_sec * NS_PER_SEC + t.tv_nsec); 87} 88 89std::string DumpFrames(Backtrace* backtrace) { 90 if (backtrace->NumFrames() == 0) { 91 return " No frames to dump.\n"; 92 } 93 94 std::string frame; 95 for (size_t i = 0; i < backtrace->NumFrames(); i++) { 96 frame += " " + backtrace->FormatFrameData(i) + '\n'; 97 } 98 return frame; 99} 100 101void WaitForStop(pid_t pid) { 102 uint64_t start = NanoTime(); 103 104 siginfo_t si; 105 while (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) < 0 && (errno == EINTR || errno == ESRCH)) { 106 if ((NanoTime() - start) > NS_PER_SEC) { 107 printf("The process did not get to a stopping point in 1 second.\n"); 108 break; 109 } 110 usleep(US_PER_MSEC); 111 } 112} 113 114bool ReadyLevelBacktrace(Backtrace* backtrace) { 115 // See if test_level_four is in the backtrace. 116 bool found = false; 117 for (Backtrace::const_iterator it = backtrace->begin(); it != backtrace->end(); ++it) { 118 if (it->func_name == "test_level_four") { 119 found = true; 120 break; 121 } 122 } 123 124 return found; 125} 126 127void VerifyLevelDump(Backtrace* backtrace) { 128 ASSERT_GT(backtrace->NumFrames(), static_cast<size_t>(0)) 129 << DumpFrames(backtrace); 130 ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES)) 131 << DumpFrames(backtrace); 132 133 // Look through the frames starting at the highest to find the 134 // frame we want. 135 size_t frame_num = 0; 136 for (size_t i = backtrace->NumFrames()-1; i > 2; i--) { 137 if (backtrace->GetFrame(i)->func_name == "test_level_one") { 138 frame_num = i; 139 break; 140 } 141 } 142 ASSERT_LT(static_cast<size_t>(0), frame_num) << DumpFrames(backtrace); 143 ASSERT_LE(static_cast<size_t>(3), frame_num) << DumpFrames(backtrace); 144 145 ASSERT_EQ(backtrace->GetFrame(frame_num)->func_name, "test_level_one") 146 << DumpFrames(backtrace); 147 ASSERT_EQ(backtrace->GetFrame(frame_num-1)->func_name, "test_level_two") 148 << DumpFrames(backtrace); 149 ASSERT_EQ(backtrace->GetFrame(frame_num-2)->func_name, "test_level_three") 150 << DumpFrames(backtrace); 151 ASSERT_EQ(backtrace->GetFrame(frame_num-3)->func_name, "test_level_four") 152 << DumpFrames(backtrace); 153} 154 155void VerifyLevelBacktrace(void*) { 156 std::unique_ptr<Backtrace> backtrace( 157 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD)); 158 ASSERT_TRUE(backtrace.get() != nullptr); 159 ASSERT_TRUE(backtrace->Unwind(0)); 160 161 VerifyLevelDump(backtrace.get()); 162} 163 164bool ReadyMaxBacktrace(Backtrace* backtrace) { 165 return (backtrace->NumFrames() == MAX_BACKTRACE_FRAMES); 166} 167 168void VerifyMaxDump(Backtrace* backtrace) { 169 ASSERT_EQ(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES)) 170 << DumpFrames(backtrace); 171 // Verify that the last frame is our recursive call. 172 ASSERT_EQ(backtrace->GetFrame(MAX_BACKTRACE_FRAMES-1)->func_name, "test_recursive_call") 173 << DumpFrames(backtrace); 174} 175 176void VerifyMaxBacktrace(void*) { 177 std::unique_ptr<Backtrace> backtrace( 178 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD)); 179 ASSERT_TRUE(backtrace.get() != nullptr); 180 ASSERT_TRUE(backtrace->Unwind(0)); 181 182 VerifyMaxDump(backtrace.get()); 183} 184 185void ThreadSetState(void* data) { 186 thread_t* thread = reinterpret_cast<thread_t*>(data); 187 android_atomic_acquire_store(1, &thread->state); 188 volatile int i = 0; 189 while (thread->state) { 190 i++; 191 } 192} 193 194void VerifyThreadTest(pid_t tid, void (*VerifyFunc)(Backtrace*)) { 195 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), tid)); 196 ASSERT_TRUE(backtrace.get() != nullptr); 197 ASSERT_TRUE(backtrace->Unwind(0)); 198 199 VerifyFunc(backtrace.get()); 200} 201 202bool WaitForNonZero(int32_t* value, uint64_t seconds) { 203 uint64_t start = NanoTime(); 204 do { 205 if (android_atomic_acquire_load(value)) { 206 return true; 207 } 208 } while ((NanoTime() - start) < seconds * NS_PER_SEC); 209 return false; 210} 211 212TEST(libbacktrace, local_no_unwind_frames) { 213 // Verify that a local unwind does not include any frames within 214 // libunwind or libbacktrace. 215 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), getpid())); 216 ASSERT_TRUE(backtrace.get() != nullptr); 217 ASSERT_TRUE(backtrace->Unwind(0)); 218 219 ASSERT_TRUE(backtrace->NumFrames() != 0); 220 for (const auto& frame : *backtrace ) { 221 if (BacktraceMap::IsValid(frame.map)) { 222 const std::string name = basename(frame.map.name.c_str()); 223 ASSERT_TRUE(name != "libunwind.so" && name != "libbacktrace.so") 224 << DumpFrames(backtrace.get()); 225 } 226 break; 227 } 228} 229 230TEST(libbacktrace, local_trace) { 231 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelBacktrace, nullptr), 0); 232} 233 234void VerifyIgnoreFrames( 235 Backtrace* bt_all, Backtrace* bt_ign1, 236 Backtrace* bt_ign2, const char* cur_proc) { 237 EXPECT_EQ(bt_all->NumFrames(), bt_ign1->NumFrames() + 1) 238 << "All backtrace:\n" << DumpFrames(bt_all) << "Ignore 1 backtrace:\n" << DumpFrames(bt_ign1); 239 EXPECT_EQ(bt_all->NumFrames(), bt_ign2->NumFrames() + 2) 240 << "All backtrace:\n" << DumpFrames(bt_all) << "Ignore 2 backtrace:\n" << DumpFrames(bt_ign2); 241 242 // Check all of the frames are the same > the current frame. 243 bool check = (cur_proc == nullptr); 244 for (size_t i = 0; i < bt_ign2->NumFrames(); i++) { 245 if (check) { 246 EXPECT_EQ(bt_ign2->GetFrame(i)->pc, bt_ign1->GetFrame(i+1)->pc); 247 EXPECT_EQ(bt_ign2->GetFrame(i)->sp, bt_ign1->GetFrame(i+1)->sp); 248 EXPECT_EQ(bt_ign2->GetFrame(i)->stack_size, bt_ign1->GetFrame(i+1)->stack_size); 249 250 EXPECT_EQ(bt_ign2->GetFrame(i)->pc, bt_all->GetFrame(i+2)->pc); 251 EXPECT_EQ(bt_ign2->GetFrame(i)->sp, bt_all->GetFrame(i+2)->sp); 252 EXPECT_EQ(bt_ign2->GetFrame(i)->stack_size, bt_all->GetFrame(i+2)->stack_size); 253 } 254 if (!check && bt_ign2->GetFrame(i)->func_name == cur_proc) { 255 check = true; 256 } 257 } 258} 259 260void VerifyLevelIgnoreFrames(void*) { 261 std::unique_ptr<Backtrace> all( 262 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD)); 263 ASSERT_TRUE(all.get() != nullptr); 264 ASSERT_TRUE(all->Unwind(0)); 265 266 std::unique_ptr<Backtrace> ign1( 267 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD)); 268 ASSERT_TRUE(ign1.get() != nullptr); 269 ASSERT_TRUE(ign1->Unwind(1)); 270 271 std::unique_ptr<Backtrace> ign2( 272 Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD)); 273 ASSERT_TRUE(ign2.get() != nullptr); 274 ASSERT_TRUE(ign2->Unwind(2)); 275 276 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), "VerifyLevelIgnoreFrames"); 277} 278 279TEST(libbacktrace, local_trace_ignore_frames) { 280 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelIgnoreFrames, nullptr), 0); 281} 282 283TEST(libbacktrace, local_max_trace) { 284 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxBacktrace, nullptr), 0); 285} 286 287void VerifyProcTest(pid_t pid, pid_t tid, bool share_map, 288 bool (*ReadyFunc)(Backtrace*), 289 void (*VerifyFunc)(Backtrace*)) { 290 pid_t ptrace_tid; 291 if (tid < 0) { 292 ptrace_tid = pid; 293 } else { 294 ptrace_tid = tid; 295 } 296 uint64_t start = NanoTime(); 297 bool verified = false; 298 std::string last_dump; 299 do { 300 usleep(US_PER_MSEC); 301 if (ptrace(PTRACE_ATTACH, ptrace_tid, 0, 0) == 0) { 302 // Wait for the process to get to a stopping point. 303 WaitForStop(ptrace_tid); 304 305 std::unique_ptr<BacktraceMap> map; 306 if (share_map) { 307 map.reset(BacktraceMap::Create(pid)); 308 } 309 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, tid, map.get())); 310 ASSERT_TRUE(backtrace.get() != nullptr); 311 ASSERT_TRUE(backtrace->Unwind(0)); 312 if (ReadyFunc(backtrace.get())) { 313 VerifyFunc(backtrace.get()); 314 verified = true; 315 } else { 316 last_dump = DumpFrames(backtrace.get()); 317 } 318 319 ASSERT_TRUE(ptrace(PTRACE_DETACH, ptrace_tid, 0, 0) == 0); 320 } 321 // If 5 seconds have passed, then we are done. 322 } while (!verified && (NanoTime() - start) <= 5 * NS_PER_SEC); 323 ASSERT_TRUE(verified) << "Last backtrace:\n" << last_dump; 324} 325 326TEST(libbacktrace, ptrace_trace) { 327 pid_t pid; 328 if ((pid = fork()) == 0) { 329 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0); 330 _exit(1); 331 } 332 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, false, ReadyLevelBacktrace, VerifyLevelDump); 333 334 kill(pid, SIGKILL); 335 int status; 336 ASSERT_EQ(waitpid(pid, &status, 0), pid); 337} 338 339TEST(libbacktrace, ptrace_trace_shared_map) { 340 pid_t pid; 341 if ((pid = fork()) == 0) { 342 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0); 343 _exit(1); 344 } 345 346 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, true, ReadyLevelBacktrace, VerifyLevelDump); 347 348 kill(pid, SIGKILL); 349 int status; 350 ASSERT_EQ(waitpid(pid, &status, 0), pid); 351} 352 353TEST(libbacktrace, ptrace_max_trace) { 354 pid_t pid; 355 if ((pid = fork()) == 0) { 356 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, nullptr, nullptr), 0); 357 _exit(1); 358 } 359 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, false, ReadyMaxBacktrace, VerifyMaxDump); 360 361 kill(pid, SIGKILL); 362 int status; 363 ASSERT_EQ(waitpid(pid, &status, 0), pid); 364} 365 366void VerifyProcessIgnoreFrames(Backtrace* bt_all) { 367 std::unique_ptr<Backtrace> ign1(Backtrace::Create(bt_all->Pid(), BACKTRACE_CURRENT_THREAD)); 368 ASSERT_TRUE(ign1.get() != nullptr); 369 ASSERT_TRUE(ign1->Unwind(1)); 370 371 std::unique_ptr<Backtrace> ign2(Backtrace::Create(bt_all->Pid(), BACKTRACE_CURRENT_THREAD)); 372 ASSERT_TRUE(ign2.get() != nullptr); 373 ASSERT_TRUE(ign2->Unwind(2)); 374 375 VerifyIgnoreFrames(bt_all, ign1.get(), ign2.get(), nullptr); 376} 377 378TEST(libbacktrace, ptrace_ignore_frames) { 379 pid_t pid; 380 if ((pid = fork()) == 0) { 381 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0); 382 _exit(1); 383 } 384 VerifyProcTest(pid, BACKTRACE_CURRENT_THREAD, false, ReadyLevelBacktrace, VerifyProcessIgnoreFrames); 385 386 kill(pid, SIGKILL); 387 int status; 388 ASSERT_EQ(waitpid(pid, &status, 0), pid); 389} 390 391// Create a process with multiple threads and dump all of the threads. 392void* PtraceThreadLevelRun(void*) { 393 EXPECT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0); 394 return nullptr; 395} 396 397void GetThreads(pid_t pid, std::vector<pid_t>* threads) { 398 // Get the list of tasks. 399 char task_path[128]; 400 snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid); 401 402 DIR* tasks_dir = opendir(task_path); 403 ASSERT_TRUE(tasks_dir != nullptr); 404 struct dirent* entry; 405 while ((entry = readdir(tasks_dir)) != nullptr) { 406 char* end; 407 pid_t tid = strtoul(entry->d_name, &end, 10); 408 if (*end == '\0') { 409 threads->push_back(tid); 410 } 411 } 412 closedir(tasks_dir); 413} 414 415TEST(libbacktrace, ptrace_threads) { 416 pid_t pid; 417 if ((pid = fork()) == 0) { 418 for (size_t i = 0; i < NUM_PTRACE_THREADS; i++) { 419 pthread_attr_t attr; 420 pthread_attr_init(&attr); 421 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 422 423 pthread_t thread; 424 ASSERT_TRUE(pthread_create(&thread, &attr, PtraceThreadLevelRun, nullptr) == 0); 425 } 426 ASSERT_NE(test_level_one(1, 2, 3, 4, nullptr, nullptr), 0); 427 _exit(1); 428 } 429 430 // Check to see that all of the threads are running before unwinding. 431 std::vector<pid_t> threads; 432 uint64_t start = NanoTime(); 433 do { 434 usleep(US_PER_MSEC); 435 threads.clear(); 436 GetThreads(pid, &threads); 437 } while ((threads.size() != NUM_PTRACE_THREADS + 1) && 438 ((NanoTime() - start) <= 5 * NS_PER_SEC)); 439 ASSERT_EQ(threads.size(), static_cast<size_t>(NUM_PTRACE_THREADS + 1)); 440 441 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0); 442 WaitForStop(pid); 443 for (std::vector<int>::const_iterator it = threads.begin(); it != threads.end(); ++it) { 444 // Skip the current forked process, we only care about the threads. 445 if (pid == *it) { 446 continue; 447 } 448 VerifyProcTest(pid, *it, false, ReadyLevelBacktrace, VerifyLevelDump); 449 } 450 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0); 451 452 kill(pid, SIGKILL); 453 int status; 454 ASSERT_EQ(waitpid(pid, &status, 0), pid); 455} 456 457void VerifyLevelThread(void*) { 458 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid())); 459 ASSERT_TRUE(backtrace.get() != nullptr); 460 ASSERT_TRUE(backtrace->Unwind(0)); 461 462 VerifyLevelDump(backtrace.get()); 463} 464 465TEST(libbacktrace, thread_current_level) { 466 ASSERT_NE(test_level_one(1, 2, 3, 4, VerifyLevelThread, nullptr), 0); 467} 468 469void VerifyMaxThread(void*) { 470 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), gettid())); 471 ASSERT_TRUE(backtrace.get() != nullptr); 472 ASSERT_TRUE(backtrace->Unwind(0)); 473 474 VerifyMaxDump(backtrace.get()); 475} 476 477TEST(libbacktrace, thread_current_max) { 478 ASSERT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, VerifyMaxThread, nullptr), 0); 479} 480 481void* ThreadLevelRun(void* data) { 482 thread_t* thread = reinterpret_cast<thread_t*>(data); 483 484 thread->tid = gettid(); 485 EXPECT_NE(test_level_one(1, 2, 3, 4, ThreadSetState, data), 0); 486 return nullptr; 487} 488 489TEST(libbacktrace, thread_level_trace) { 490 pthread_attr_t attr; 491 pthread_attr_init(&attr); 492 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 493 494 thread_t thread_data = { 0, 0, 0, nullptr }; 495 pthread_t thread; 496 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadLevelRun, &thread_data) == 0); 497 498 // Wait up to 2 seconds for the tid to be set. 499 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2)); 500 501 // Make sure that the thread signal used is not visible when compiled for 502 // the target. 503#if !defined(__GLIBC__) 504 ASSERT_LT(THREAD_SIGNAL, SIGRTMIN); 505#endif 506 507 // Save the current signal action and make sure it is restored afterwards. 508 struct sigaction cur_action; 509 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &cur_action) == 0); 510 511 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid)); 512 ASSERT_TRUE(backtrace.get() != nullptr); 513 ASSERT_TRUE(backtrace->Unwind(0)); 514 515 VerifyLevelDump(backtrace.get()); 516 517 // Tell the thread to exit its infinite loop. 518 android_atomic_acquire_store(0, &thread_data.state); 519 520 // Verify that the old action was restored. 521 struct sigaction new_action; 522 ASSERT_TRUE(sigaction(THREAD_SIGNAL, nullptr, &new_action) == 0); 523 EXPECT_EQ(cur_action.sa_sigaction, new_action.sa_sigaction); 524 // The SA_RESTORER flag gets set behind our back, so a direct comparison 525 // doesn't work unless we mask the value off. Mips doesn't have this 526 // flag, so skip this on that platform. 527#if defined(SA_RESTORER) 528 cur_action.sa_flags &= ~SA_RESTORER; 529 new_action.sa_flags &= ~SA_RESTORER; 530#elif defined(__GLIBC__) 531 // Our host compiler doesn't appear to define this flag for some reason. 532 cur_action.sa_flags &= ~0x04000000; 533 new_action.sa_flags &= ~0x04000000; 534#endif 535 EXPECT_EQ(cur_action.sa_flags, new_action.sa_flags); 536} 537 538TEST(libbacktrace, thread_ignore_frames) { 539 pthread_attr_t attr; 540 pthread_attr_init(&attr); 541 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 542 543 thread_t thread_data = { 0, 0, 0, nullptr }; 544 pthread_t thread; 545 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadLevelRun, &thread_data) == 0); 546 547 // Wait up to 2 seconds for the tid to be set. 548 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2)); 549 550 std::unique_ptr<Backtrace> all(Backtrace::Create(getpid(), thread_data.tid)); 551 ASSERT_TRUE(all.get() != nullptr); 552 ASSERT_TRUE(all->Unwind(0)); 553 554 std::unique_ptr<Backtrace> ign1(Backtrace::Create(getpid(), thread_data.tid)); 555 ASSERT_TRUE(ign1.get() != nullptr); 556 ASSERT_TRUE(ign1->Unwind(1)); 557 558 std::unique_ptr<Backtrace> ign2(Backtrace::Create(getpid(), thread_data.tid)); 559 ASSERT_TRUE(ign2.get() != nullptr); 560 ASSERT_TRUE(ign2->Unwind(2)); 561 562 VerifyIgnoreFrames(all.get(), ign1.get(), ign2.get(), nullptr); 563 564 // Tell the thread to exit its infinite loop. 565 android_atomic_acquire_store(0, &thread_data.state); 566} 567 568void* ThreadMaxRun(void* data) { 569 thread_t* thread = reinterpret_cast<thread_t*>(data); 570 571 thread->tid = gettid(); 572 EXPECT_NE(test_recursive_call(MAX_BACKTRACE_FRAMES+10, ThreadSetState, data), 0); 573 return nullptr; 574} 575 576TEST(libbacktrace, thread_max_trace) { 577 pthread_attr_t attr; 578 pthread_attr_init(&attr); 579 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 580 581 thread_t thread_data = { 0, 0, 0, nullptr }; 582 pthread_t thread; 583 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadMaxRun, &thread_data) == 0); 584 585 // Wait for the tid to be set. 586 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2)); 587 588 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid)); 589 ASSERT_TRUE(backtrace.get() != nullptr); 590 ASSERT_TRUE(backtrace->Unwind(0)); 591 592 VerifyMaxDump(backtrace.get()); 593 594 // Tell the thread to exit its infinite loop. 595 android_atomic_acquire_store(0, &thread_data.state); 596} 597 598void* ThreadDump(void* data) { 599 dump_thread_t* dump = reinterpret_cast<dump_thread_t*>(data); 600 while (true) { 601 if (android_atomic_acquire_load(dump->now)) { 602 break; 603 } 604 } 605 606 // The status of the actual unwind will be checked elsewhere. 607 dump->backtrace = Backtrace::Create(getpid(), dump->thread.tid); 608 dump->backtrace->Unwind(0); 609 610 android_atomic_acquire_store(1, &dump->done); 611 612 return nullptr; 613} 614 615TEST(libbacktrace, thread_multiple_dump) { 616 // Dump NUM_THREADS simultaneously. 617 std::vector<thread_t> runners(NUM_THREADS); 618 std::vector<dump_thread_t> dumpers(NUM_THREADS); 619 620 pthread_attr_t attr; 621 pthread_attr_init(&attr); 622 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 623 for (size_t i = 0; i < NUM_THREADS; i++) { 624 // Launch the runners, they will spin in hard loops doing nothing. 625 runners[i].tid = 0; 626 runners[i].state = 0; 627 ASSERT_TRUE(pthread_create(&runners[i].threadId, &attr, ThreadMaxRun, &runners[i]) == 0); 628 } 629 630 // Wait for tids to be set. 631 for (std::vector<thread_t>::iterator it = runners.begin(); it != runners.end(); ++it) { 632 ASSERT_TRUE(WaitForNonZero(&it->state, 30)); 633 } 634 635 // Start all of the dumpers at once, they will spin until they are signalled 636 // to begin their dump run. 637 int32_t dump_now = 0; 638 for (size_t i = 0; i < NUM_THREADS; i++) { 639 dumpers[i].thread.tid = runners[i].tid; 640 dumpers[i].thread.state = 0; 641 dumpers[i].done = 0; 642 dumpers[i].now = &dump_now; 643 644 ASSERT_TRUE(pthread_create(&dumpers[i].thread.threadId, &attr, ThreadDump, &dumpers[i]) == 0); 645 } 646 647 // Start all of the dumpers going at once. 648 android_atomic_acquire_store(1, &dump_now); 649 650 for (size_t i = 0; i < NUM_THREADS; i++) { 651 ASSERT_TRUE(WaitForNonZero(&dumpers[i].done, 30)); 652 653 // Tell the runner thread to exit its infinite loop. 654 android_atomic_acquire_store(0, &runners[i].state); 655 656 ASSERT_TRUE(dumpers[i].backtrace != nullptr); 657 VerifyMaxDump(dumpers[i].backtrace); 658 659 delete dumpers[i].backtrace; 660 dumpers[i].backtrace = nullptr; 661 } 662} 663 664TEST(libbacktrace, thread_multiple_dump_same_thread) { 665 pthread_attr_t attr; 666 pthread_attr_init(&attr); 667 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 668 thread_t runner; 669 runner.tid = 0; 670 runner.state = 0; 671 ASSERT_TRUE(pthread_create(&runner.threadId, &attr, ThreadMaxRun, &runner) == 0); 672 673 // Wait for tids to be set. 674 ASSERT_TRUE(WaitForNonZero(&runner.state, 30)); 675 676 // Start all of the dumpers at once, they will spin until they are signalled 677 // to begin their dump run. 678 int32_t dump_now = 0; 679 // Dump the same thread NUM_THREADS simultaneously. 680 std::vector<dump_thread_t> dumpers(NUM_THREADS); 681 for (size_t i = 0; i < NUM_THREADS; i++) { 682 dumpers[i].thread.tid = runner.tid; 683 dumpers[i].thread.state = 0; 684 dumpers[i].done = 0; 685 dumpers[i].now = &dump_now; 686 687 ASSERT_TRUE(pthread_create(&dumpers[i].thread.threadId, &attr, ThreadDump, &dumpers[i]) == 0); 688 } 689 690 // Start all of the dumpers going at once. 691 android_atomic_acquire_store(1, &dump_now); 692 693 for (size_t i = 0; i < NUM_THREADS; i++) { 694 ASSERT_TRUE(WaitForNonZero(&dumpers[i].done, 30)); 695 696 ASSERT_TRUE(dumpers[i].backtrace != nullptr); 697 VerifyMaxDump(dumpers[i].backtrace); 698 699 delete dumpers[i].backtrace; 700 dumpers[i].backtrace = nullptr; 701 } 702 703 // Tell the runner thread to exit its infinite loop. 704 android_atomic_acquire_store(0, &runner.state); 705} 706 707// This test is for UnwindMaps that should share the same map cursor when 708// multiple maps are created for the current process at the same time. 709TEST(libbacktrace, simultaneous_maps) { 710 BacktraceMap* map1 = BacktraceMap::Create(getpid()); 711 BacktraceMap* map2 = BacktraceMap::Create(getpid()); 712 BacktraceMap* map3 = BacktraceMap::Create(getpid()); 713 714 Backtrace* back1 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map1); 715 ASSERT_TRUE(back1 != nullptr); 716 EXPECT_TRUE(back1->Unwind(0)); 717 delete back1; 718 delete map1; 719 720 Backtrace* back2 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map2); 721 ASSERT_TRUE(back2 != nullptr); 722 EXPECT_TRUE(back2->Unwind(0)); 723 delete back2; 724 delete map2; 725 726 Backtrace* back3 = Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD, map3); 727 ASSERT_TRUE(back3 != nullptr); 728 EXPECT_TRUE(back3->Unwind(0)); 729 delete back3; 730 delete map3; 731} 732 733TEST(libbacktrace, fillin_erases) { 734 BacktraceMap* back_map = BacktraceMap::Create(getpid()); 735 736 backtrace_map_t map; 737 738 map.start = 1; 739 map.end = 3; 740 map.flags = 1; 741 map.name = "Initialized"; 742 back_map->FillIn(0, &map); 743 delete back_map; 744 745 ASSERT_FALSE(BacktraceMap::IsValid(map)); 746 ASSERT_EQ(static_cast<uintptr_t>(0), map.start); 747 ASSERT_EQ(static_cast<uintptr_t>(0), map.end); 748 ASSERT_EQ(0, map.flags); 749 ASSERT_EQ("", map.name); 750} 751 752TEST(libbacktrace, format_test) { 753 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), BACKTRACE_CURRENT_THREAD)); 754 ASSERT_TRUE(backtrace.get() != nullptr); 755 756 backtrace_frame_data_t frame; 757 frame.num = 1; 758 frame.pc = 2; 759 frame.sp = 0; 760 frame.stack_size = 0; 761 frame.func_offset = 0; 762 763 // Check no map set. 764 frame.num = 1; 765#if defined(__LP64__) 766 EXPECT_EQ("#01 pc 0000000000000002 <unknown>", 767#else 768 EXPECT_EQ("#01 pc 00000002 <unknown>", 769#endif 770 backtrace->FormatFrameData(&frame)); 771 772 // Check map name empty, but exists. 773 frame.map.start = 1; 774 frame.map.end = 1; 775 frame.map.load_base = 0; 776#if defined(__LP64__) 777 EXPECT_EQ("#01 pc 0000000000000001 <unknown>", 778#else 779 EXPECT_EQ("#01 pc 00000001 <unknown>", 780#endif 781 backtrace->FormatFrameData(&frame)); 782 783 784 // Check relative pc is set and map name is set. 785 frame.pc = 0x12345679; 786 frame.map.name = "MapFake"; 787 frame.map.start = 1; 788 frame.map.end = 1; 789#if defined(__LP64__) 790 EXPECT_EQ("#01 pc 0000000012345678 MapFake", 791#else 792 EXPECT_EQ("#01 pc 12345678 MapFake", 793#endif 794 backtrace->FormatFrameData(&frame)); 795 796 // Check func_name is set, but no func offset. 797 frame.func_name = "ProcFake"; 798#if defined(__LP64__) 799 EXPECT_EQ("#01 pc 0000000012345678 MapFake (ProcFake)", 800#else 801 EXPECT_EQ("#01 pc 12345678 MapFake (ProcFake)", 802#endif 803 backtrace->FormatFrameData(&frame)); 804 805 // Check func_name is set, and func offset is non-zero. 806 frame.func_offset = 645; 807#if defined(__LP64__) 808 EXPECT_EQ("#01 pc 0000000012345678 MapFake (ProcFake+645)", 809#else 810 EXPECT_EQ("#01 pc 12345678 MapFake (ProcFake+645)", 811#endif 812 backtrace->FormatFrameData(&frame)); 813 814 // Check func_name is set, func offset is non-zero, and load_base is non-zero. 815 frame.func_offset = 645; 816 frame.map.load_base = 100; 817#if defined(__LP64__) 818 EXPECT_EQ("#01 pc 00000000123456dc MapFake (ProcFake+645)", 819#else 820 EXPECT_EQ("#01 pc 123456dc MapFake (ProcFake+645)", 821#endif 822 backtrace->FormatFrameData(&frame)); 823} 824 825struct map_test_t { 826 uintptr_t start; 827 uintptr_t end; 828}; 829 830bool map_sort(map_test_t i, map_test_t j) { 831 return i.start < j.start; 832} 833 834void VerifyMap(pid_t pid) { 835 char buffer[4096]; 836 snprintf(buffer, sizeof(buffer), "/proc/%d/maps", pid); 837 838 FILE* map_file = fopen(buffer, "r"); 839 ASSERT_TRUE(map_file != nullptr); 840 std::vector<map_test_t> test_maps; 841 while (fgets(buffer, sizeof(buffer), map_file)) { 842 map_test_t map; 843 ASSERT_EQ(2, sscanf(buffer, "%" SCNxPTR "-%" SCNxPTR " ", &map.start, &map.end)); 844 test_maps.push_back(map); 845 } 846 fclose(map_file); 847 std::sort(test_maps.begin(), test_maps.end(), map_sort); 848 849 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(pid)); 850 851 // Basic test that verifies that the map is in the expected order. 852 std::vector<map_test_t>::const_iterator test_it = test_maps.begin(); 853 for (BacktraceMap::const_iterator it = map->begin(); it != map->end(); ++it) { 854 ASSERT_TRUE(test_it != test_maps.end()); 855 ASSERT_EQ(test_it->start, it->start); 856 ASSERT_EQ(test_it->end, it->end); 857 ++test_it; 858 } 859 ASSERT_TRUE(test_it == test_maps.end()); 860} 861 862TEST(libbacktrace, verify_map_remote) { 863 pid_t pid; 864 865 if ((pid = fork()) == 0) { 866 while (true) { 867 } 868 _exit(0); 869 } 870 ASSERT_LT(0, pid); 871 872 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0); 873 874 // Wait for the process to get to a stopping point. 875 WaitForStop(pid); 876 877 // The maps should match exactly since the forked process has been paused. 878 VerifyMap(pid); 879 880 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0); 881 882 kill(pid, SIGKILL); 883 ASSERT_EQ(waitpid(pid, nullptr, 0), pid); 884} 885 886void InitMemory(uint8_t* memory, size_t bytes) { 887 for (size_t i = 0; i < bytes; i++) { 888 memory[i] = i; 889 if (memory[i] == '\0') { 890 // Don't use '\0' in our data so we can verify that an overread doesn't 891 // occur by using a '\0' as the character after the read data. 892 memory[i] = 23; 893 } 894 } 895} 896 897void* ThreadReadTest(void* data) { 898 thread_t* thread_data = reinterpret_cast<thread_t*>(data); 899 900 thread_data->tid = gettid(); 901 902 // Create two map pages. 903 // Mark the second page as not-readable. 904 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE)); 905 uint8_t* memory; 906 if (posix_memalign(reinterpret_cast<void**>(&memory), pagesize, 2 * pagesize) != 0) { 907 return reinterpret_cast<void*>(-1); 908 } 909 910 if (mprotect(&memory[pagesize], pagesize, PROT_NONE) != 0) { 911 return reinterpret_cast<void*>(-1); 912 } 913 914 // Set up a simple pattern in memory. 915 InitMemory(memory, pagesize); 916 917 thread_data->data = memory; 918 919 // Tell the caller it's okay to start reading memory. 920 android_atomic_acquire_store(1, &thread_data->state); 921 922 // Loop waiting for the caller to finish reading the memory. 923 while (thread_data->state) { 924 } 925 926 // Re-enable read-write on the page so that we don't crash if we try 927 // and access data on this page when freeing the memory. 928 if (mprotect(&memory[pagesize], pagesize, PROT_READ | PROT_WRITE) != 0) { 929 return reinterpret_cast<void*>(-1); 930 } 931 free(memory); 932 933 android_atomic_acquire_store(1, &thread_data->state); 934 935 return nullptr; 936} 937 938void RunReadTest(Backtrace* backtrace, uintptr_t read_addr) { 939 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE)); 940 941 // Create a page of data to use to do quick compares. 942 uint8_t* expected = new uint8_t[pagesize]; 943 InitMemory(expected, pagesize); 944 945 uint8_t* data = new uint8_t[2*pagesize]; 946 // Verify that we can only read one page worth of data. 947 size_t bytes_read = backtrace->Read(read_addr, data, 2 * pagesize); 948 ASSERT_EQ(pagesize, bytes_read); 949 ASSERT_TRUE(memcmp(data, expected, pagesize) == 0); 950 951 // Verify unaligned reads. 952 for (size_t i = 1; i < sizeof(word_t); i++) { 953 bytes_read = backtrace->Read(read_addr + i, data, 2 * sizeof(word_t)); 954 ASSERT_EQ(2 * sizeof(word_t), bytes_read); 955 ASSERT_TRUE(memcmp(data, &expected[i], 2 * sizeof(word_t)) == 0) 956 << "Offset at " << i << " failed"; 957 } 958 959 // Verify small unaligned reads. 960 for (size_t i = 1; i < sizeof(word_t); i++) { 961 for (size_t j = 1; j < sizeof(word_t); j++) { 962 // Set one byte past what we expect to read, to guarantee we don't overread. 963 data[j] = '\0'; 964 bytes_read = backtrace->Read(read_addr + i, data, j); 965 ASSERT_EQ(j, bytes_read); 966 ASSERT_TRUE(memcmp(data, &expected[i], j) == 0) 967 << "Offset at " << i << " length " << j << " miscompared"; 968 ASSERT_EQ('\0', data[j]) 969 << "Offset at " << i << " length " << j << " wrote too much data"; 970 } 971 } 972 delete data; 973 delete expected; 974} 975 976TEST(libbacktrace, thread_read) { 977 pthread_attr_t attr; 978 pthread_attr_init(&attr); 979 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 980 pthread_t thread; 981 thread_t thread_data = { 0, 0, 0, nullptr }; 982 ASSERT_TRUE(pthread_create(&thread, &attr, ThreadReadTest, &thread_data) == 0); 983 984 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10)); 985 986 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid)); 987 ASSERT_TRUE(backtrace.get() != nullptr); 988 989 RunReadTest(backtrace.get(), reinterpret_cast<uintptr_t>(thread_data.data)); 990 991 android_atomic_acquire_store(0, &thread_data.state); 992 993 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10)); 994} 995 996volatile uintptr_t g_ready = 0; 997volatile uintptr_t g_addr = 0; 998 999void ForkedReadTest() { 1000 // Create two map pages. 1001 size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE)); 1002 uint8_t* memory; 1003 if (posix_memalign(reinterpret_cast<void**>(&memory), pagesize, 2 * pagesize) != 0) { 1004 perror("Failed to allocate memory\n"); 1005 exit(1); 1006 } 1007 1008 // Mark the second page as not-readable. 1009 if (mprotect(&memory[pagesize], pagesize, PROT_NONE) != 0) { 1010 perror("Failed to mprotect memory\n"); 1011 exit(1); 1012 } 1013 1014 // Set up a simple pattern in memory. 1015 InitMemory(memory, pagesize); 1016 1017 g_addr = reinterpret_cast<uintptr_t>(memory); 1018 g_ready = 1; 1019 1020 while (1) { 1021 usleep(US_PER_MSEC); 1022 } 1023} 1024 1025TEST(libbacktrace, process_read) { 1026 pid_t pid; 1027 if ((pid = fork()) == 0) { 1028 ForkedReadTest(); 1029 exit(0); 1030 } 1031 ASSERT_NE(-1, pid); 1032 1033 bool test_executed = false; 1034 uint64_t start = NanoTime(); 1035 while (1) { 1036 if (ptrace(PTRACE_ATTACH, pid, 0, 0) == 0) { 1037 WaitForStop(pid); 1038 1039 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid)); 1040 ASSERT_TRUE(backtrace.get() != nullptr); 1041 1042 uintptr_t read_addr; 1043 size_t bytes_read = backtrace->Read(reinterpret_cast<uintptr_t>(&g_ready), 1044 reinterpret_cast<uint8_t*>(&read_addr), 1045 sizeof(uintptr_t)); 1046 ASSERT_EQ(sizeof(uintptr_t), bytes_read); 1047 if (read_addr) { 1048 // The forked process is ready to be read. 1049 bytes_read = backtrace->Read(reinterpret_cast<uintptr_t>(&g_addr), 1050 reinterpret_cast<uint8_t*>(&read_addr), 1051 sizeof(uintptr_t)); 1052 ASSERT_EQ(sizeof(uintptr_t), bytes_read); 1053 1054 RunReadTest(backtrace.get(), read_addr); 1055 1056 test_executed = true; 1057 break; 1058 } 1059 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0); 1060 } 1061 if ((NanoTime() - start) > 5 * NS_PER_SEC) { 1062 break; 1063 } 1064 usleep(US_PER_MSEC); 1065 } 1066 kill(pid, SIGKILL); 1067 ASSERT_EQ(waitpid(pid, nullptr, 0), pid); 1068 1069 ASSERT_TRUE(test_executed); 1070} 1071 1072#if defined(ENABLE_PSS_TESTS) 1073#include "GetPss.h" 1074 1075#define MAX_LEAK_BYTES 32*1024UL 1076 1077void CheckForLeak(pid_t pid, pid_t tid) { 1078 // Do a few runs to get the PSS stable. 1079 for (size_t i = 0; i < 100; i++) { 1080 Backtrace* backtrace = Backtrace::Create(pid, tid); 1081 ASSERT_TRUE(backtrace != nullptr); 1082 ASSERT_TRUE(backtrace->Unwind(0)); 1083 delete backtrace; 1084 } 1085 size_t stable_pss = GetPssBytes(); 1086 ASSERT_TRUE(stable_pss != 0); 1087 1088 // Loop enough that even a small leak should be detectable. 1089 for (size_t i = 0; i < 4096; i++) { 1090 Backtrace* backtrace = Backtrace::Create(pid, tid); 1091 ASSERT_TRUE(backtrace != nullptr); 1092 ASSERT_TRUE(backtrace->Unwind(0)); 1093 delete backtrace; 1094 } 1095 size_t new_pss = GetPssBytes(); 1096 ASSERT_TRUE(new_pss != 0); 1097 size_t abs_diff = (new_pss > stable_pss) ? new_pss - stable_pss : stable_pss - new_pss; 1098 // As long as the new pss is within a certain amount, consider everything okay. 1099 ASSERT_LE(abs_diff, MAX_LEAK_BYTES); 1100} 1101 1102TEST(libbacktrace, check_for_leak_local) { 1103 CheckForLeak(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD); 1104} 1105 1106TEST(libbacktrace, check_for_leak_local_thread) { 1107 thread_t thread_data = { 0, 0, 0, nullptr }; 1108 pthread_t thread; 1109 ASSERT_TRUE(pthread_create(&thread, nullptr, ThreadLevelRun, &thread_data) == 0); 1110 1111 // Wait up to 2 seconds for the tid to be set. 1112 ASSERT_TRUE(WaitForNonZero(&thread_data.state, 2)); 1113 1114 CheckForLeak(BACKTRACE_CURRENT_PROCESS, thread_data.tid); 1115 1116 // Tell the thread to exit its infinite loop. 1117 android_atomic_acquire_store(0, &thread_data.state); 1118 1119 ASSERT_TRUE(pthread_join(thread, nullptr) == 0); 1120} 1121 1122TEST(libbacktrace, check_for_leak_remote) { 1123 pid_t pid; 1124 1125 if ((pid = fork()) == 0) { 1126 while (true) { 1127 } 1128 _exit(0); 1129 } 1130 ASSERT_LT(0, pid); 1131 1132 ASSERT_TRUE(ptrace(PTRACE_ATTACH, pid, 0, 0) == 0); 1133 1134 // Wait for the process to get to a stopping point. 1135 WaitForStop(pid); 1136 1137 CheckForLeak(pid, BACKTRACE_CURRENT_THREAD); 1138 1139 ASSERT_TRUE(ptrace(PTRACE_DETACH, pid, 0, 0) == 0); 1140 1141 kill(pid, SIGKILL); 1142 ASSERT_EQ(waitpid(pid, nullptr, 0), pid); 1143} 1144#endif 1145