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 {
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 = true;
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         for (auto it = frames.begin(); it != frames.end(); it++) {
103           if (it == frames.begin() || std::prev(it)->map_name != it->map_name) {
104             LOG(ERROR) << " in " << it->map_name.c_str();
105           }
106           LOG(ERROR) << " pc " << std::setw(8) << std::setfill('0') << std::hex <<
107             it->rel_pc << " " << it->function_name.c_str();
108         }
109         LOG(FATAL);
110       }
111     }
112   }
113 }
114 
CollectImpl(unwindstack::Unwinder * unwinder)115 bool BacktraceCollector::CollectImpl(unwindstack::Unwinder* unwinder) {
116   std::unique_ptr<unwindstack::Regs> regs(unwindstack::Regs::CreateFromLocal());
117   RegsGetLocal(regs.get());
118   unwinder->SetRegs(regs.get());
119   unwinder->Unwind();
120 
121   num_frames_ = 0;
122   if (unwinder->NumFrames() > skip_count_) {
123     for (auto it = unwinder->frames().begin() + skip_count_; it != unwinder->frames().end(); ++it) {
124       CHECK_LT(num_frames_, max_depth_);
125       out_frames_[num_frames_++] = static_cast<uintptr_t>(it->pc);
126 
127       // Expected early end: Instrumentation breaks unwinding (b/138296821).
128       // Inexact compare because the unwinder does not give us exact return address,
129       // but rather it tries to guess the address of the preceding call instruction.
130       size_t exit_pc = reinterpret_cast<size_t>(GetQuickInstrumentationExitPc());
131       if (exit_pc - 4 <= it->pc && it->pc <= exit_pc) {
132         return true;
133       }
134 
135       if (kStrictUnwindChecks) {
136         if (it->function_name.empty()) {
137           return false;
138         }
139         if (it->function_name == "main" ||
140             it->function_name == "start_thread" ||
141             it->function_name == "__start_thread") {
142           return true;
143         }
144       }
145     }
146   }
147 
148   unwindstack::ErrorCode error = unwinder->LastErrorCode();
149   return error == unwindstack::ERROR_NONE || error == unwindstack::ERROR_MAX_FRAMES_EXCEEDED;
150 }
151 
152 #else
153 
154 #pragma clang diagnostic push
155 #pragma clang diagnostic warning "-W#warnings"
156 #warning "Backtrace collector is not implemented. GCStress cannot be used."
157 #pragma clang diagnostic pop
158 
159 // We only have an implementation for linux. On other plaforms just return nothing. This is not
160 // really correct but we only use this for hashing and gcstress so it's not too big a deal.
161 void BacktraceCollector::Collect() {
162   UNUSED(skip_count_);
163   UNUSED(out_frames_);
164   UNUSED(max_depth_);
165   num_frames_ = 0;
166 }
167 
168 #endif
169 
170 }  // namespace art
171