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