1 /*
2 * Copyright (C) 2007 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 LOG_TAG "CallStack"
18
19 #include <utils/CallStack.h>
20
21 #include <memory>
22
23 #include <utils/Printer.h>
24 #include <utils/Errors.h>
25 #include <utils/Log.h>
26
27 #include <backtrace/Backtrace.h>
28
29 namespace android {
30
CallStack()31 CallStack::CallStack() {
32 }
33
CallStack(const char * logtag,int32_t ignoreDepth)34 CallStack::CallStack(const char* logtag, int32_t ignoreDepth) {
35 this->update(ignoreDepth+1);
36 this->log(logtag);
37 }
38
~CallStack()39 CallStack::~CallStack() {
40 }
41
update(int32_t ignoreDepth,pid_t tid)42 void CallStack::update(int32_t ignoreDepth, pid_t tid) {
43 mFrameLines.clear();
44
45 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
46 if (!backtrace->Unwind(ignoreDepth)) {
47 ALOGW("%s: Failed to unwind callstack.", __FUNCTION__);
48 }
49 for (size_t i = 0; i < backtrace->NumFrames(); i++) {
50 mFrameLines.push_back(String8(backtrace->FormatFrameData(i).c_str()));
51 }
52 }
53
log(const char * logtag,android_LogPriority priority,const char * prefix) const54 void CallStack::log(const char* logtag, android_LogPriority priority, const char* prefix) const {
55 LogPrinter printer(logtag, priority, prefix, /*ignoreBlankLines*/false);
56 print(printer);
57 }
58
dump(int fd,int indent,const char * prefix) const59 void CallStack::dump(int fd, int indent, const char* prefix) const {
60 FdPrinter printer(fd, indent, prefix);
61 print(printer);
62 }
63
toString(const char * prefix) const64 String8 CallStack::toString(const char* prefix) const {
65 String8 str;
66
67 String8Printer printer(&str, prefix);
68 print(printer);
69
70 return str;
71 }
72
print(Printer & printer) const73 void CallStack::print(Printer& printer) const {
74 for (size_t i = 0; i < mFrameLines.size(); i++) {
75 printer.printLine(mFrameLines[i]);
76 }
77 }
78
79 }; // namespace android
80