ProcessCallStack.cpp 6.7 KB

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