1 /*
2 * Copyright (C) 2018 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 #include "backtrace_helper.h"
18
19 #if defined(__linux__)
20
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <iomanip>
24
25 #include "unwindstack/Regs.h"
26 #include "unwindstack/RegsGetLocal.h"
27 #include "unwindstack/Memory.h"
28 #include "unwindstack/Unwinder.h"
29
30 #include "base/bit_utils.h"
31 #include "entrypoints/runtime_asm_entrypoints.h"
32 #include "thread-inl.h"
33
34 #else
35
36 // For UNUSED
37 #include "base/macros.h"
38
39 #endif
40
41 namespace art HIDDEN {
42
43 // We only really support libunwindstack on linux which is unfortunate but since this is only for
44 // gcstress this isn't a huge deal.
45 #if defined(__linux__)
46
47 // Strict integrity check of the backtrace:
48 // All methods must have a name, all the way to "main".
49 static constexpr bool kStrictUnwindChecks = false;
50
51 struct UnwindHelper : public TLSData {
52 static constexpr const char* kTlsKey = "UnwindHelper::kTlsKey";
53
UnwindHelperart::UnwindHelper54 explicit UnwindHelper(size_t max_depth)
55 : arch_(unwindstack::Regs::CurrentArch()),
56 memory_(unwindstack::Memory::CreateProcessMemoryThreadCached(getpid())),
57 jit_(unwindstack::CreateJitDebug(arch_, memory_)),
58 dex_(unwindstack::CreateDexFiles(arch_, memory_)),
59 unwinder_(max_depth, &maps_, memory_) {
60 CHECK(maps_.Parse());
61 unwinder_.SetArch(arch_);
62 unwinder_.SetJitDebug(jit_.get());
63 unwinder_.SetDexFiles(dex_.get());
64 unwinder_.SetResolveNames(kStrictUnwindChecks);
65 unwindstack::Elf::SetCachingEnabled(true);
66 }
67
68 // Reparse process mmaps to detect newly loaded libraries.
Reparseart::UnwindHelper69 bool Reparse(bool* any_changed) { return maps_.Reparse(any_changed); }
70
Getart::UnwindHelper71 static UnwindHelper* Get(Thread* self, size_t max_depth) {
72 UnwindHelper* tls = reinterpret_cast<UnwindHelper*>(self->GetCustomTLS(kTlsKey));
73 if (tls == nullptr) {
74 tls = new UnwindHelper(max_depth);
75 self->SetCustomTLS(kTlsKey, tls);
76 }
77 return tls;
78 }
79
Unwinderart::UnwindHelper80 unwindstack::Unwinder* Unwinder() { return &unwinder_; }
81
82 private:
83 unwindstack::LocalUpdatableMaps maps_;
84 unwindstack::ArchEnum arch_;
85 std::shared_ptr<unwindstack::Memory> memory_;
86 std::unique_ptr<unwindstack::JitDebug> jit_;
87 std::unique_ptr<unwindstack::DexFiles> dex_;
88 unwindstack::Unwinder unwinder_;
89 };
90
Collect()91 void BacktraceCollector::Collect() {
92 unwindstack::Unwinder* unwinder = UnwindHelper::Get(Thread::Current(), max_depth_)->Unwinder();
93 if (!CollectImpl(unwinder)) {
94 // Reparse process mmaps to detect newly loaded libraries and retry,
95 // but only if any maps changed (we don't want to hide racy failures).
96 bool any_changed;
97 UnwindHelper::Get(Thread::Current(), max_depth_)->Reparse(&any_changed);
98 if (!any_changed || !CollectImpl(unwinder)) {
99 if (kStrictUnwindChecks) {
100 std::vector<unwindstack::FrameData>& frames = unwinder->frames();
101 LOG(ERROR) << "Failed to unwind stack (error " << unwinder->LastErrorCodeString() << "):";
102 std::string prev_name;
103 for (auto& frame : frames) {
104 if (frame.map_info != nullptr) {
105 std::string full_name = frame.map_info->GetFullName();
106 if (prev_name != full_name) {
107 LOG(ERROR) << " in " << full_name;
108 }
109 prev_name = full_name;
110 } else {
111 prev_name = "";
112 }
113 LOG(ERROR) << " pc " << std::setw(8) << std::setfill('0') << std::hex <<
114 frame.rel_pc << " " << frame.function_name.c_str();
115 }
116 LOG(FATAL);
117 }
118 }
119 }
120 }
121
CollectImpl(unwindstack::Unwinder * unwinder)122 bool BacktraceCollector::CollectImpl(unwindstack::Unwinder* unwinder) {
123 std::unique_ptr<unwindstack::Regs> regs(unwindstack::Regs::CreateFromLocal());
124 RegsGetLocal(regs.get());
125 unwinder->SetRegs(regs.get());
126 unwinder->Unwind();
127
128 num_frames_ = 0;
129 if (unwinder->NumFrames() > skip_count_) {
130 for (auto it = unwinder->frames().begin() + skip_count_; it != unwinder->frames().end(); ++it) {
131 CHECK_LT(num_frames_, max_depth_);
132 out_frames_[num_frames_++] = static_cast<uintptr_t>(it->pc);
133
134 if (kStrictUnwindChecks) {
135 if (it->function_name.empty()) {
136 return false;
137 }
138 if (it->function_name == "main" ||
139 it->function_name == "start_thread" ||
140 it->function_name == "__start_thread") {
141 return true;
142 }
143 }
144 }
145 }
146
147 unwindstack::ErrorCode error = unwinder->LastErrorCode();
148 return error == unwindstack::ERROR_NONE || error == unwindstack::ERROR_MAX_FRAMES_EXCEEDED;
149 }
150
151 #else
152
153 #pragma clang diagnostic push
154 #pragma clang diagnostic warning "-W#warnings"
155 #warning "Backtrace collector is not implemented. GCStress cannot be used."
156 #pragma clang diagnostic pop
157
158 // We only have an implementation for linux. On other plaforms just return nothing. This is not
159 // really correct but we only use this for hashing and gcstress so it's not too big a deal.
160 void BacktraceCollector::Collect() {
161 UNUSED(skip_count_);
162 UNUSED(out_frames_);
163 UNUSED(max_depth_);
164 num_frames_ = 0;
165 }
166
167 #endif
168
169 } // namespace art
170