blob: a27106e8bce520f3e2ce8633545ef6dfcae30a27 [file] [log] [blame]
Austin Schuh745610d2015-09-06 18:19:50 -07001// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
2// Copyright (c) 2009, Google Inc.
3// All rights reserved.
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9// * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11// * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15// * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// ---
32// Author: Craig Silverstein
33//
34// This forks out to pprof to do the actual symbolizing. We might
35// be better off writing our own in C++.
36
37#include "config.h"
38#include "symbolize.h"
39#include <stdlib.h>
40#ifdef HAVE_UNISTD_H
41#include <unistd.h> // for write()
42#endif
43#ifdef HAVE_SYS_SOCKET_H
44#include <sys/socket.h> // for socketpair() -- needed by Symbolize
45#endif
46#ifdef HAVE_SYS_WAIT_H
47#include <sys/wait.h> // for wait() -- needed by Symbolize
48#endif
49#ifdef HAVE_POLL_H
50#include <poll.h>
51#endif
52#ifdef __MACH__
53#include <mach-o/dyld.h> // for GetProgramInvocationName()
54#include <limits.h> // for PATH_MAX
55#endif
56#if defined(__CYGWIN__) || defined(__CYGWIN32__)
57#include <io.h> // for get_osfhandle()
58#endif
59#include <string>
60#include "base/commandlineflags.h"
61#include "base/logging.h"
62#include "base/sysinfo.h"
63
64using std::string;
65using tcmalloc::DumpProcSelfMaps; // from sysinfo.h
66
67
68DEFINE_string(symbolize_pprof,
69 EnvToString("PPROF_PATH", "pprof"),
70 "Path to pprof to call for reporting function names.");
71
72// heap_profile_table_pprof may be referenced after destructors are
73// called (since that's when leak-checking is done), so we make
74// a more-permanent copy that won't ever get destroyed.
75static string* g_pprof_path = new string(FLAGS_symbolize_pprof);
76
77// Returns NULL if we're on an OS where we can't get the invocation name.
78// Using a static var is ok because we're not called from a thread.
79static const char* GetProgramInvocationName() {
80#if defined(HAVE_PROGRAM_INVOCATION_NAME)
81#ifdef __UCLIBC__
82 extern const char* program_invocation_name; // uclibc provides this
83#else
84 extern char* program_invocation_name; // gcc provides this
85#endif
86 return program_invocation_name;
87#elif defined(__MACH__)
88 // We don't want to allocate memory for this since we may be
89 // calculating it when memory is corrupted.
90 static char program_invocation_name[PATH_MAX];
91 if (program_invocation_name[0] == '\0') { // first time calculating
92 uint32_t length = sizeof(program_invocation_name);
93 if (_NSGetExecutablePath(program_invocation_name, &length))
94 return NULL;
95 }
96 return program_invocation_name;
97#else
98 return NULL; // figure out a way to get argv[0]
99#endif
100}
101
102// Prints an error message when you can't run Symbolize().
103static void PrintError(const char* reason) {
104 RAW_LOG(ERROR,
105 "*** WARNING: Cannot convert addresses to symbols in output below.\n"
106 "*** Reason: %s\n"
107 "*** If you cannot fix this, try running pprof directly.\n",
108 reason);
109}
110
111void SymbolTable::Add(const void* addr) {
112 symbolization_table_[addr] = "";
113}
114
115const char* SymbolTable::GetSymbol(const void* addr) {
116 return symbolization_table_[addr];
117}
118
119// Updates symbolization_table with the pointers to symbol names corresponding
120// to its keys. The symbol names are stored in out, which is allocated and
121// freed by the caller of this routine.
122// Note that the forking/etc is not thread-safe or re-entrant. That's
123// ok for the purpose we need -- reporting leaks detected by heap-checker
124// -- but be careful if you decide to use this routine for other purposes.
125// Returns number of symbols read on error. If can't symbolize, returns 0
126// and emits an error message about why.
127int SymbolTable::Symbolize() {
128#if !defined(HAVE_UNISTD_H) || !defined(HAVE_SYS_SOCKET_H) || !defined(HAVE_SYS_WAIT_H)
129 PrintError("Perftools does not know how to call a sub-process on this O/S");
130 return 0;
131#else
132 const char* argv0 = GetProgramInvocationName();
133 if (argv0 == NULL) { // can't call symbolize if we can't figure out our name
134 PrintError("Cannot figure out the name of this executable (argv0)");
135 return 0;
136 }
137 if (access(g_pprof_path->c_str(), R_OK) != 0) {
138 PrintError("Cannot find 'pprof' (is PPROF_PATH set correctly?)");
139 return 0;
140 }
141
142 // All this work is to do two-way communication. ugh.
143 int *child_in = NULL; // file descriptors
144 int *child_out = NULL; // for now, we don't worry about child_err
145 int child_fds[5][2]; // socketpair may be called up to five times below
146
147 // The client program may close its stdin and/or stdout and/or stderr
148 // thus allowing socketpair to reuse file descriptors 0, 1 or 2.
149 // In this case the communication between the forked processes may be broken
150 // if either the parent or the child tries to close or duplicate these
151 // descriptors. The loop below produces two pairs of file descriptors, each
152 // greater than 2 (stderr).
153 for (int i = 0; i < 5; i++) {
154 if (socketpair(AF_UNIX, SOCK_STREAM, 0, child_fds[i]) == -1) {
155 for (int j = 0; j < i; j++) {
156 close(child_fds[j][0]);
157 close(child_fds[j][1]);
158 PrintError("Cannot create a socket pair");
159 }
160 return 0;
161 } else {
162 if ((child_fds[i][0] > 2) && (child_fds[i][1] > 2)) {
163 if (child_in == NULL) {
164 child_in = child_fds[i];
165 } else {
166 child_out = child_fds[i];
167 for (int j = 0; j < i; j++) {
168 if (child_fds[j] == child_in) continue;
169 close(child_fds[j][0]);
170 close(child_fds[j][1]);
171 }
172 break;
173 }
174 }
175 }
176 }
177
178 switch (fork()) {
179 case -1: { // error
180 close(child_in[0]);
181 close(child_in[1]);
182 close(child_out[0]);
183 close(child_out[1]);
184 PrintError("Unknown error calling fork()");
185 return 0;
186 }
187 case 0: { // child
188 close(child_in[1]); // child uses the 0's, parent uses the 1's
189 close(child_out[1]); // child uses the 0's, parent uses the 1's
190 close(0);
191 close(1);
192 if (dup2(child_in[0], 0) == -1) _exit(1);
193 if (dup2(child_out[0], 1) == -1) _exit(2);
194 // Unset vars that might cause trouble when we fork
195 unsetenv("CPUPROFILE");
196 unsetenv("HEAPPROFILE");
197 unsetenv("HEAPCHECK");
198 unsetenv("PERFTOOLS_VERBOSE");
199 execlp(g_pprof_path->c_str(), g_pprof_path->c_str(),
200 "--symbols", argv0, NULL);
201 _exit(3); // if execvp fails, it's bad news for us
202 }
203 default: { // parent
204 close(child_in[0]); // child uses the 0's, parent uses the 1's
205 close(child_out[0]); // child uses the 0's, parent uses the 1's
206#ifdef HAVE_POLL_H
207 // Waiting for 1ms seems to give the OS time to notice any errors.
208 poll(0, 0, 1);
209 // For maximum safety, we check to make sure the execlp
210 // succeeded before trying to write. (Otherwise we'll get a
211 // SIGPIPE.) For systems without poll.h, we'll just skip this
212 // check, and trust that the user set PPROF_PATH correctly!
213 struct pollfd pfd = { child_in[1], POLLOUT, 0 };
214 if (!poll(&pfd, 1, 0) || !(pfd.revents & POLLOUT) ||
215 (pfd.revents & (POLLHUP|POLLERR))) {
216 PrintError("Cannot run 'pprof' (is PPROF_PATH set correctly?)");
217 return 0;
218 }
219#endif
220#if defined(__CYGWIN__) || defined(__CYGWIN32__)
221 // On cygwin, DumpProcSelfMaps() takes a HANDLE, not an fd. Convert.
222 const HANDLE symbols_handle = (HANDLE) get_osfhandle(child_in[1]);
223 DumpProcSelfMaps(symbols_handle);
224#else
225 DumpProcSelfMaps(child_in[1]); // what pprof expects on stdin
226#endif
227
228 // Allocate 24 bytes = ("0x" + 8 bytes + "\n" + overhead) for each
229 // address to feed to pprof.
230 const int kOutBufSize = 24 * symbolization_table_.size();
231 char *pprof_buffer = new char[kOutBufSize];
232 int written = 0;
233 for (SymbolMap::const_iterator iter = symbolization_table_.begin();
234 iter != symbolization_table_.end(); ++iter) {
235 written += snprintf(pprof_buffer + written, kOutBufSize - written,
236 // pprof expects format to be 0xXXXXXX
237 "0x%" PRIxPTR "\n", reinterpret_cast<uintptr_t>(iter->first));
238 }
239 write(child_in[1], pprof_buffer, strlen(pprof_buffer));
240 close(child_in[1]); // that's all we need to write
241
242 const int kSymbolBufferSize = kSymbolSize * symbolization_table_.size();
243 int total_bytes_read = 0;
244 delete[] symbol_buffer_;
245 symbol_buffer_ = new char[kSymbolBufferSize];
246 memset(symbol_buffer_, '\0', kSymbolBufferSize);
247 while (1) {
248 int bytes_read = read(child_out[1], symbol_buffer_ + total_bytes_read,
249 kSymbolBufferSize - total_bytes_read);
250 if (bytes_read < 0) {
251 close(child_out[1]);
252 PrintError("Cannot read data from pprof");
253 return 0;
254 } else if (bytes_read == 0) {
255 close(child_out[1]);
256 wait(NULL);
257 break;
258 } else {
259 total_bytes_read += bytes_read;
260 }
261 }
262 // We have successfully read the output of pprof into out. Make sure
263 // the last symbol is full (we can tell because it ends with a \n).
264 if (total_bytes_read == 0 || symbol_buffer_[total_bytes_read - 1] != '\n')
265 return 0;
266 // make the symbolization_table_ values point to the output vector
267 SymbolMap::iterator fill = symbolization_table_.begin();
268 int num_symbols = 0;
269 const char *current_name = symbol_buffer_;
270 for (int i = 0; i < total_bytes_read; i++) {
271 if (symbol_buffer_[i] == '\n') {
272 fill->second = current_name;
273 symbol_buffer_[i] = '\0';
274 current_name = symbol_buffer_ + i + 1;
275 fill++;
276 num_symbols++;
277 }
278 }
279 return num_symbols;
280 }
281 }
282 PrintError("Unkown error (should never occur!)");
283 return 0; // shouldn't be reachable
284#endif
285}