blob: 983847c4ce4fb38dd2f055d865d56cc6ebebc24d [file] [log] [blame]
Igor Murashkinec79ef22013-10-24 17:09:15 -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
17#define LOG_TAG "ProcessCallStack"
18// #define LOG_NDEBUG 0
19
Igor Murashkinec79ef22013-10-24 17:09:15 -070020#include <dirent.h>
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070021#include <errno.h>
22#include <stdio.h>
23#include <string.h>
Jaesoo Leeff39e9c2017-04-20 17:21:50 +090024#include <unistd.h>
James Hawkins588a2ca2016-02-18 14:52:46 -080025#include <memory>
Igor Murashkinec79ef22013-10-24 17:09:15 -070026
27#include <utils/Log.h>
28#include <utils/Errors.h>
29#include <utils/ProcessCallStack.h>
30#include <utils/Printer.h>
31
Igor Murashkin81f2c3d2013-10-30 16:01:54 -070032#include <limits.h>
33
Igor Murashkinec79ef22013-10-24 17:09:15 -070034namespace android {
35
36enum {
37 // Max sizes for various dynamically generated strings
38 MAX_TIME_STRING = 64,
39 MAX_PROC_PATH = 1024,
40
41 // Dump related prettiness constants
42 IGNORE_DEPTH_CURRENT_THREAD = 2,
43};
44
45static const char* CALL_STACK_PREFIX = " ";
46static const char* PATH_THREAD_NAME = "/proc/self/task/%d/comm";
47static const char* PATH_SELF_TASK = "/proc/self/task";
48
49static void dumpProcessHeader(Printer& printer, pid_t pid, const char* timeStr) {
50 if (timeStr == NULL) {
51 ALOGW("%s: timeStr was NULL", __FUNCTION__);
52 return;
53 }
54
55 char path[PATH_MAX];
56 char procNameBuf[MAX_PROC_PATH];
57 char* procName = NULL;
58 FILE* fp;
59
60 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
61 if ((fp = fopen(path, "r"))) {
62 procName = fgets(procNameBuf, sizeof(procNameBuf), fp);
63 fclose(fp);
64 }
65
66 if (!procName) {
67 procName = const_cast<char*>("<unknown>");
68 }
69
70 printer.printLine();
71 printer.printLine();
72 printer.printFormatLine("----- pid %d at %s -----", pid, timeStr);
73 printer.printFormatLine("Cmd line: %s", procName);
74}
75
76static void dumpProcessFooter(Printer& printer, pid_t pid) {
77 printer.printLine();
78 printer.printFormatLine("----- end %d -----", pid);
79 printer.printLine();
80}
81
82static String8 getThreadName(pid_t tid) {
83 char path[PATH_MAX];
84 char* procName = NULL;
85 char procNameBuf[MAX_PROC_PATH];
86 FILE* fp;
87
88 snprintf(path, sizeof(path), PATH_THREAD_NAME, tid);
89 if ((fp = fopen(path, "r"))) {
90 procName = fgets(procNameBuf, sizeof(procNameBuf), fp);
91 fclose(fp);
92 } else {
93 ALOGE("%s: Failed to open %s", __FUNCTION__, path);
94 }
95
Igor Murashkin63fbdb62014-08-19 11:48:52 -070096 if (procName == NULL) {
97 // Reading /proc/self/task/%d/comm failed due to a race
98 return String8::format("[err-unknown-tid-%d]", tid);
99 }
100
Igor Murashkinec79ef22013-10-24 17:09:15 -0700101 // Strip ending newline
102 strtok(procName, "\n");
103
104 return String8(procName);
105}
106
107static String8 getTimeString(struct tm tm) {
108 char timestr[MAX_TIME_STRING];
109 // i.e. '2013-10-22 14:42:05'
110 strftime(timestr, sizeof(timestr), "%F %T", &tm);
111
112 return String8(timestr);
113}
114
115/*
116 * Implementation of ProcessCallStack
117 */
118ProcessCallStack::ProcessCallStack() {
119}
120
121ProcessCallStack::ProcessCallStack(const ProcessCallStack& rhs) :
122 mThreadMap(rhs.mThreadMap),
123 mTimeUpdated(rhs.mTimeUpdated) {
124}
125
126ProcessCallStack::~ProcessCallStack() {
127}
128
129void ProcessCallStack::clear() {
130 mThreadMap.clear();
131 mTimeUpdated = tm();
132}
133
Christopher Ferris9b0e0742013-10-31 16:25:04 -0700134void ProcessCallStack::update() {
James Hawkins588a2ca2016-02-18 14:52:46 -0800135 std::unique_ptr<DIR, decltype(&closedir)> dp(opendir(PATH_SELF_TASK), closedir);
Igor Murashkinec79ef22013-10-24 17:09:15 -0700136 if (dp == NULL) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700137 ALOGE("%s: Failed to update the process's call stacks: %s",
138 __FUNCTION__, strerror(errno));
Igor Murashkinec79ef22013-10-24 17:09:15 -0700139 return;
140 }
141
142 pid_t selfPid = getpid();
143
144 clear();
145
146 // Get current time.
147 {
148 time_t t = time(NULL);
149 struct tm tm;
150 localtime_r(&t, &tm);
151
152 mTimeUpdated = tm;
153 }
154
155 /*
156 * Each tid is a directory inside of /proc/self/task
157 * - Read every file in directory => get every tid
158 */
Elliott Hughes9f206932016-09-28 13:29:54 -0700159 dirent* ep;
160 while ((ep = readdir(dp.get())) != NULL) {
Igor Murashkinec79ef22013-10-24 17:09:15 -0700161 pid_t tid = -1;
162 sscanf(ep->d_name, "%d", &tid);
163
164 if (tid < 0) {
165 // Ignore '.' and '..'
166 ALOGV("%s: Failed to read tid from %s/%s",
167 __FUNCTION__, PATH_SELF_TASK, ep->d_name);
168 continue;
169 }
170
171 ssize_t idx = mThreadMap.add(tid, ThreadInfo());
172 if (idx < 0) { // returns negative error value on error
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700173 ALOGE("%s: Failed to add new ThreadInfo: %s",
174 __FUNCTION__, strerror(-idx));
Igor Murashkinec79ef22013-10-24 17:09:15 -0700175 continue;
176 }
177
178 ThreadInfo& threadInfo = mThreadMap.editValueAt(static_cast<size_t>(idx));
179
180 /*
181 * Ignore CallStack::update and ProcessCallStack::update for current thread
182 * - Every other thread doesn't need this since we call update off-thread
183 */
184 int ignoreDepth = (selfPid == tid) ? IGNORE_DEPTH_CURRENT_THREAD : 0;
185
186 // Update thread's call stacks
Christopher Ferris9b0e0742013-10-31 16:25:04 -0700187 threadInfo.callStack.update(ignoreDepth, tid);
Igor Murashkinec79ef22013-10-24 17:09:15 -0700188
189 // Read/save thread name
190 threadInfo.threadName = getThreadName(tid);
191
192 ALOGV("%s: Got call stack for tid %d (size %zu)",
Christopher Ferris9b0e0742013-10-31 16:25:04 -0700193 __FUNCTION__, tid, threadInfo.callStack.size());
Igor Murashkinec79ef22013-10-24 17:09:15 -0700194 }
Igor Murashkinec79ef22013-10-24 17:09:15 -0700195}
196
197void ProcessCallStack::log(const char* logtag, android_LogPriority priority,
198 const char* prefix) const {
199 LogPrinter printer(logtag, priority, prefix, /*ignoreBlankLines*/false);
200 print(printer);
201}
202
203void ProcessCallStack::print(Printer& printer) const {
204 /*
205 * Print the header/footer with the regular printer.
206 * Print the callstack with an additional two spaces as the prefix for legibility.
207 */
208 PrefixPrinter csPrinter(printer, CALL_STACK_PREFIX);
209 printInternal(printer, csPrinter);
210}
211
212void ProcessCallStack::printInternal(Printer& printer, Printer& csPrinter) const {
213 dumpProcessHeader(printer, getpid(),
214 getTimeString(mTimeUpdated).string());
215
216 for (size_t i = 0; i < mThreadMap.size(); ++i) {
217 pid_t tid = mThreadMap.keyAt(i);
218 const ThreadInfo& threadInfo = mThreadMap.valueAt(i);
Igor Murashkinec79ef22013-10-24 17:09:15 -0700219 const String8& threadName = threadInfo.threadName;
220
221 printer.printLine("");
222 printer.printFormatLine("\"%s\" sysTid=%d", threadName.string(), tid);
223
Christopher Ferris9b0e0742013-10-31 16:25:04 -0700224 threadInfo.callStack.print(csPrinter);
Igor Murashkinec79ef22013-10-24 17:09:15 -0700225 }
226
227 dumpProcessFooter(printer, getpid());
228}
229
230void ProcessCallStack::dump(int fd, int indent, const char* prefix) const {
231
232 if (indent < 0) {
233 ALOGW("%s: Bad indent (%d)", __FUNCTION__, indent);
234 return;
235 }
236
237 FdPrinter printer(fd, static_cast<unsigned int>(indent), prefix);
238 print(printer);
239}
240
241String8 ProcessCallStack::toString(const char* prefix) const {
242
243 String8 dest;
244 String8Printer printer(&dest, prefix);
245 print(printer);
246
247 return dest;
248}
249
250size_t ProcessCallStack::size() const {
251 return mThreadMap.size();
252}
253
254}; //namespace android