blob: 8183494b87725127cb0bcea419b746976829cc86 [file] [log] [blame]
Austin Schuh745610d2015-09-06 18:19:50 -07001// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
2// Copyright (c) 2006, 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#include <config.h>
32#if (defined(_WIN32) || defined(__MINGW32__)) && !defined(__CYGWIN__) && !defined(__CYGWIN32)
33# define PLATFORM_WINDOWS 1
34#endif
35
36#include <ctype.h> // for isspace()
37#include <stdlib.h> // for getenv()
38#include <stdio.h> // for snprintf(), sscanf()
39#include <string.h> // for memmove(), memchr(), etc.
40#include <fcntl.h> // for open()
41#include <errno.h> // for errno
42#ifdef HAVE_UNISTD_H
43#include <unistd.h> // for read()
44#endif
45#if defined __MACH__ // Mac OS X, almost certainly
46#include <mach-o/dyld.h> // for iterating over dll's in ProcMapsIter
47#include <mach-o/loader.h> // for iterating over dll's in ProcMapsIter
48#include <sys/types.h>
49#include <sys/sysctl.h> // how we figure out numcpu's on OS X
50#elif defined __FreeBSD__
51#include <sys/sysctl.h>
52#elif defined __sun__ // Solaris
53#include <procfs.h> // for, e.g., prmap_t
54#elif defined(PLATFORM_WINDOWS)
55#include <process.h> // for getpid() (actually, _getpid())
56#include <shlwapi.h> // for SHGetValueA()
57#include <tlhelp32.h> // for Module32First()
58#endif
59#include "base/sysinfo.h"
60#include "base/commandlineflags.h"
61#include "base/dynamic_annotations.h" // for RunningOnValgrind
62#include "base/logging.h"
63#include "base/cycleclock.h"
64
65#ifdef PLATFORM_WINDOWS
66#ifdef MODULEENTRY32
67// In a change from the usual W-A pattern, there is no A variant of
68// MODULEENTRY32. Tlhelp32.h #defines the W variant, but not the A.
69// In unicode mode, tlhelp32.h #defines MODULEENTRY32 to be
70// MODULEENTRY32W. These #undefs are the only way I see to get back
71// access to the original, ascii struct (and related functions).
72#undef MODULEENTRY32
73#undef Module32First
74#undef Module32Next
75#undef PMODULEENTRY32
76#undef LPMODULEENTRY32
77#endif /* MODULEENTRY32 */
78// MinGW doesn't seem to define this, perhaps some windowsen don't either.
79#ifndef TH32CS_SNAPMODULE32
80#define TH32CS_SNAPMODULE32 0
81#endif /* TH32CS_SNAPMODULE32 */
82#endif /* PLATFORM_WINDOWS */
83
84// Re-run fn until it doesn't cause EINTR.
85#define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR)
86
87// open/read/close can set errno, which may be illegal at this
88// time, so prefer making the syscalls directly if we can.
89#ifdef HAVE_SYS_SYSCALL_H
90# include <sys/syscall.h>
91#endif
92#ifdef SYS_open // solaris 11, at least sometimes, only defines SYS_openat
93# define safeopen(filename, mode) syscall(SYS_open, filename, mode)
94#else
95# define safeopen(filename, mode) open(filename, mode)
96#endif
97#ifdef SYS_read
98# define saferead(fd, buffer, size) syscall(SYS_read, fd, buffer, size)
99#else
100# define saferead(fd, buffer, size) read(fd, buffer, size)
101#endif
102#ifdef SYS_close
103# define safeclose(fd) syscall(SYS_close, fd)
104#else
105# define safeclose(fd) close(fd)
106#endif
107
108// ----------------------------------------------------------------------
109// GetenvBeforeMain()
110// GetUniquePathFromEnv()
111// Some non-trivial getenv-related functions.
112// ----------------------------------------------------------------------
113
114// It's not safe to call getenv() in the malloc hooks, because they
115// might be called extremely early, before libc is done setting up
116// correctly. In particular, the thread library may not be done
117// setting up errno. So instead, we use the built-in __environ array
118// if it exists, and otherwise read /proc/self/environ directly, using
119// system calls to read the file, and thus avoid setting errno.
120// /proc/self/environ has a limit of how much data it exports (around
121// 8K), so it's not an ideal solution.
122const char* GetenvBeforeMain(const char* name) {
123#if defined(HAVE___ENVIRON) // if we have it, it's declared in unistd.h
124 if (__environ) { // can exist but be NULL, if statically linked
125 const int namelen = strlen(name);
126 for (char** p = __environ; *p; p++) {
127 if (strlen(*p) < namelen) {
128 continue;
129 }
130 if (!memcmp(*p, name, namelen) && (*p)[namelen] == '=') // it's a match
131 return *p + namelen+1; // point after =
132 }
133 return NULL;
134 }
135#endif
136#if defined(PLATFORM_WINDOWS)
137 // TODO(mbelshe) - repeated calls to this function will overwrite the
138 // contents of the static buffer.
139 static char envvar_buf[1024]; // enough to hold any envvar we care about
140 if (!GetEnvironmentVariableA(name, envvar_buf, sizeof(envvar_buf)-1))
141 return NULL;
142 return envvar_buf;
143#endif
144 // static is ok because this function should only be called before
145 // main(), when we're single-threaded.
146 static char envbuf[16<<10];
147 if (*envbuf == '\0') { // haven't read the environ yet
148 int fd = safeopen("/proc/self/environ", O_RDONLY);
149 // The -2 below guarantees the last two bytes of the buffer will be \0\0
150 if (fd == -1 || // unable to open the file, fall back onto libc
151 saferead(fd, envbuf, sizeof(envbuf) - 2) < 0) { // error reading file
152 RAW_VLOG(1, "Unable to open /proc/self/environ, falling back "
153 "on getenv(\"%s\"), which may not work", name);
154 if (fd != -1) safeclose(fd);
155 return getenv(name);
156 }
157 safeclose(fd);
158 }
159 const int namelen = strlen(name);
160 const char* p = envbuf;
161 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
162 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
Brian Silverman660d6092015-11-26 18:41:59 -0500163 const char* endp = (const char*)memchr(p, '\0', sizeof(envbuf) - (p - envbuf));
Austin Schuh745610d2015-09-06 18:19:50 -0700164 if (endp == NULL) // this entry isn't NUL terminated
165 return NULL;
166 else if (!memcmp(p, name, namelen) && p[namelen] == '=') // it's a match
167 return p + namelen+1; // point after =
168 p = endp + 1;
169 }
170 return NULL; // env var never found
171}
172
173extern "C" {
174 const char* TCMallocGetenvSafe(const char* name) {
175 return GetenvBeforeMain(name);
176 }
177}
178
179// This takes as an argument an environment-variable name (like
180// CPUPROFILE) whose value is supposed to be a file-path, and sets
181// path to that path, and returns true. If the env var doesn't exist,
182// or is the empty string, leave path unchanged and returns false.
183// The reason this is non-trivial is that this function handles munged
184// pathnames. Here's why:
185//
186// If we're a child process of the 'main' process, we can't just use
187// getenv("CPUPROFILE") -- the parent process will be using that path.
188// Instead we append our pid to the pathname. How do we tell if we're a
189// child process? Ideally we'd set an environment variable that all
190// our children would inherit. But -- and this is seemingly a bug in
191// gcc -- if you do a setenv() in a shared libarary in a global
192// constructor, the environment setting is lost by the time main() is
193// called. The only safe thing we can do in such a situation is to
194// modify the existing envvar. So we do a hack: in the parent, we set
195// the high bit of the 1st char of CPUPROFILE. In the child, we
196// notice the high bit is set and append the pid(). This works
197// assuming cpuprofile filenames don't normally have the high bit set
198// in their first character! If that assumption is violated, we'll
199// still get a profile, but one with an unexpected name.
200// TODO(csilvers): set an envvar instead when we can do it reliably.
201bool GetUniquePathFromEnv(const char* env_name, char* path) {
202 char* envval = getenv(env_name);
203 if (envval == NULL || *envval == '\0')
204 return false;
205 if (envval[0] & 128) { // high bit is set
206 snprintf(path, PATH_MAX, "%c%s_%u", // add pid and clear high bit
207 envval[0] & 127, envval+1, (unsigned int)(getpid()));
208 } else {
209 snprintf(path, PATH_MAX, "%s", envval);
210 envval[0] |= 128; // set high bit for kids to see
211 }
212 return true;
213}
214
215// ----------------------------------------------------------------------
216// CyclesPerSecond()
217// NumCPUs()
218// It's important this not call malloc! -- they may be called at
219// global-construct time, before we've set up all our proper malloc
220// hooks and such.
221// ----------------------------------------------------------------------
222
223static double cpuinfo_cycles_per_second = 1.0; // 0.0 might be dangerous
224static int cpuinfo_num_cpus = 1; // Conservative guess
225
226void SleepForMilliseconds(int milliseconds) {
227#ifdef PLATFORM_WINDOWS
228 _sleep(milliseconds); // Windows's _sleep takes milliseconds argument
229#else
230 // Sleep for a few milliseconds
231 struct timespec sleep_time;
232 sleep_time.tv_sec = milliseconds / 1000;
233 sleep_time.tv_nsec = (milliseconds % 1000) * 1000000;
234 while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR)
235 ; // Ignore signals and wait for the full interval to elapse.
236#endif
237}
238
239// Helper function estimates cycles/sec by observing cycles elapsed during
240// sleep(). Using small sleep time decreases accuracy significantly.
241static int64 EstimateCyclesPerSecond(const int estimate_time_ms) {
242 assert(estimate_time_ms > 0);
243 if (estimate_time_ms <= 0)
244 return 1;
245 double multiplier = 1000.0 / (double)estimate_time_ms; // scale by this much
246
247 const int64 start_ticks = CycleClock::Now();
248 SleepForMilliseconds(estimate_time_ms);
249 const int64 guess = int64(multiplier * (CycleClock::Now() - start_ticks));
250 return guess;
251}
252
253// ReadIntFromFile is only called on linux and cygwin platforms.
254#if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
255// Helper function for reading an int from a file. Returns true if successful
256// and the memory location pointed to by value is set to the value read.
257static bool ReadIntFromFile(const char *file, int *value) {
258 bool ret = false;
259 int fd = open(file, O_RDONLY);
260 if (fd != -1) {
261 char line[1024];
262 char* err;
263 memset(line, '\0', sizeof(line));
264 read(fd, line, sizeof(line) - 1);
265 const int temp_value = strtol(line, &err, 10);
266 if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
267 *value = temp_value;
268 ret = true;
269 }
270 close(fd);
271 }
272 return ret;
273}
274#endif
275
276// WARNING: logging calls back to InitializeSystemInfo() so it must
277// not invoke any logging code. Also, InitializeSystemInfo() can be
278// called before main() -- in fact it *must* be since already_called
279// isn't protected -- before malloc hooks are properly set up, so
280// we make an effort not to call any routines which might allocate
281// memory.
282
283static void InitializeSystemInfo() {
284 static bool already_called = false; // safe if we run before threads
285 if (already_called) return;
286 already_called = true;
287
288 bool saw_mhz = false;
289
290 if (RunningOnValgrind()) {
291 // Valgrind may slow the progress of time artificially (--scale-time=N
292 // option). We thus can't rely on CPU Mhz info stored in /sys or /proc
293 // files. Thus, actually measure the cps.
294 cpuinfo_cycles_per_second = EstimateCyclesPerSecond(100);
295 saw_mhz = true;
296 }
297
298#if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
299 char line[1024];
300 char* err;
301 int freq;
302
303 // If the kernel is exporting the tsc frequency use that. There are issues
304 // where cpuinfo_max_freq cannot be relied on because the BIOS may be
305 // exporintg an invalid p-state (on x86) or p-states may be used to put the
306 // processor in a new mode (turbo mode). Essentially, those frequencies
307 // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as
308 // well.
309 if (!saw_mhz &&
310 ReadIntFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) {
311 // The value is in kHz (as the file name suggests). For example, on a
312 // 2GHz warpstation, the file contains the value "2000000".
313 cpuinfo_cycles_per_second = freq * 1000.0;
314 saw_mhz = true;
315 }
316
317 // If CPU scaling is in effect, we want to use the *maximum* frequency,
318 // not whatever CPU speed some random processor happens to be using now.
319 if (!saw_mhz &&
320 ReadIntFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
321 &freq)) {
322 // The value is in kHz. For example, on a 2GHz machine, the file
323 // contains the value "2000000".
324 cpuinfo_cycles_per_second = freq * 1000.0;
325 saw_mhz = true;
326 }
327
328 // Read /proc/cpuinfo for other values, and if there is no cpuinfo_max_freq.
329 const char* pname = "/proc/cpuinfo";
330 int fd = open(pname, O_RDONLY);
331 if (fd == -1) {
332 perror(pname);
333 if (!saw_mhz) {
334 cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000);
335 }
336 return; // TODO: use generic tester instead?
337 }
338
339 double bogo_clock = 1.0;
340 bool saw_bogo = false;
341 int num_cpus = 0;
342 line[0] = line[1] = '\0';
343 int chars_read = 0;
344 do { // we'll exit when the last read didn't read anything
345 // Move the next line to the beginning of the buffer
346 const int oldlinelen = strlen(line);
347 if (sizeof(line) == oldlinelen + 1) // oldlinelen took up entire line
348 line[0] = '\0';
349 else // still other lines left to save
350 memmove(line, line + oldlinelen+1, sizeof(line) - (oldlinelen+1));
351 // Terminate the new line, reading more if we can't find the newline
352 char* newline = strchr(line, '\n');
353 if (newline == NULL) {
354 const int linelen = strlen(line);
355 const int bytes_to_read = sizeof(line)-1 - linelen;
356 assert(bytes_to_read > 0); // because the memmove recovered >=1 bytes
357 chars_read = read(fd, line + linelen, bytes_to_read);
358 line[linelen + chars_read] = '\0';
359 newline = strchr(line, '\n');
360 }
361 if (newline != NULL)
362 *newline = '\0';
363
364#if defined(__powerpc__) || defined(__ppc__)
365 // PowerPC cpus report the frequency in "clock" line
366 if (strncasecmp(line, "clock", sizeof("clock")-1) == 0) {
367 const char* freqstr = strchr(line, ':');
368 if (freqstr) {
369 // PowerPC frequencies are only reported as MHz (check 'show_cpuinfo'
370 // function at arch/powerpc/kernel/setup-common.c)
371 char *endp = strstr(line, "MHz");
372 if (endp) {
373 *endp = 0;
374 cpuinfo_cycles_per_second = strtod(freqstr+1, &err) * 1000000.0;
375 if (freqstr[1] != '\0' && *err == '\0' && cpuinfo_cycles_per_second > 0)
376 saw_mhz = true;
377 }
378 }
379#else
380 // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only
381 // accept postive values. Some environments (virtual machines) report zero,
382 // which would cause infinite looping in WallTime_Init.
383 if (!saw_mhz && strncasecmp(line, "cpu MHz", sizeof("cpu MHz")-1) == 0) {
384 const char* freqstr = strchr(line, ':');
385 if (freqstr) {
386 cpuinfo_cycles_per_second = strtod(freqstr+1, &err) * 1000000.0;
387 if (freqstr[1] != '\0' && *err == '\0' && cpuinfo_cycles_per_second > 0)
388 saw_mhz = true;
389 }
390 } else if (strncasecmp(line, "bogomips", sizeof("bogomips")-1) == 0) {
391 const char* freqstr = strchr(line, ':');
392 if (freqstr) {
393 bogo_clock = strtod(freqstr+1, &err) * 1000000.0;
394 if (freqstr[1] != '\0' && *err == '\0' && bogo_clock > 0)
395 saw_bogo = true;
396 }
397#endif
398 } else if (strncasecmp(line, "processor", sizeof("processor")-1) == 0) {
399 num_cpus++; // count up every time we see an "processor :" entry
400 }
401 } while (chars_read > 0);
402 close(fd);
403
404 if (!saw_mhz) {
405 if (saw_bogo) {
406 // If we didn't find anything better, we'll use bogomips, but
407 // we're not happy about it.
408 cpuinfo_cycles_per_second = bogo_clock;
409 } else {
410 // If we don't even have bogomips, we'll use the slow estimation.
411 cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000);
412 }
413 }
414 if (cpuinfo_cycles_per_second == 0.0) {
415 cpuinfo_cycles_per_second = 1.0; // maybe unnecessary, but safe
416 }
417 if (num_cpus > 0) {
418 cpuinfo_num_cpus = num_cpus;
419 }
420
421#elif defined __FreeBSD__
422 // For this sysctl to work, the machine must be configured without
423 // SMP, APIC, or APM support. hz should be 64-bit in freebsd 7.0
424 // and later. Before that, it's a 32-bit quantity (and gives the
425 // wrong answer on machines faster than 2^32 Hz). See
426 // http://lists.freebsd.org/pipermail/freebsd-i386/2004-November/001846.html
427 // But also compare FreeBSD 7.0:
428 // http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG70#L223
429 // 231 error = sysctl_handle_quad(oidp, &freq, 0, req);
430 // To FreeBSD 6.3 (it's the same in 6-STABLE):
431 // http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG6#L131
432 // 139 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
433#if __FreeBSD__ >= 7
434 uint64_t hz = 0;
435#else
436 unsigned int hz = 0;
437#endif
438 size_t sz = sizeof(hz);
439 const char *sysctl_path = "machdep.tsc_freq";
440 if ( sysctlbyname(sysctl_path, &hz, &sz, NULL, 0) != 0 ) {
441 fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n",
442 sysctl_path, strerror(errno));
443 cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000);
444 } else {
445 cpuinfo_cycles_per_second = hz;
446 }
447 // TODO(csilvers): also figure out cpuinfo_num_cpus
448
449#elif defined(PLATFORM_WINDOWS)
450# pragma comment(lib, "shlwapi.lib") // for SHGetValue()
451 // In NT, read MHz from the registry. If we fail to do so or we're in win9x
452 // then make a crude estimate.
453 OSVERSIONINFO os;
454 os.dwOSVersionInfoSize = sizeof(os);
455 DWORD data, data_size = sizeof(data);
456 if (GetVersionEx(&os) &&
457 os.dwPlatformId == VER_PLATFORM_WIN32_NT &&
458 SUCCEEDED(SHGetValueA(HKEY_LOCAL_MACHINE,
459 "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
460 "~MHz", NULL, &data, &data_size)))
461 cpuinfo_cycles_per_second = (int64)data * (int64)(1000 * 1000); // was mhz
462 else
463 cpuinfo_cycles_per_second = EstimateCyclesPerSecond(500); // TODO <500?
464
465 // Get the number of processors.
466 SYSTEM_INFO info;
467 GetSystemInfo(&info);
468 cpuinfo_num_cpus = info.dwNumberOfProcessors;
469
470#elif defined(__MACH__) && defined(__APPLE__)
471 // returning "mach time units" per second. the current number of elapsed
472 // mach time units can be found by calling uint64 mach_absolute_time();
473 // while not as precise as actual CPU cycles, it is accurate in the face
474 // of CPU frequency scaling and multi-cpu/core machines.
475 // Our mac users have these types of machines, and accuracy
476 // (i.e. correctness) trumps precision.
477 // See cycleclock.h: CycleClock::Now(), which returns number of mach time
478 // units on Mac OS X.
479 mach_timebase_info_data_t timebase_info;
480 mach_timebase_info(&timebase_info);
481 double mach_time_units_per_nanosecond =
482 static_cast<double>(timebase_info.denom) /
483 static_cast<double>(timebase_info.numer);
484 cpuinfo_cycles_per_second = mach_time_units_per_nanosecond * 1e9;
485
486 int num_cpus = 0;
487 size_t size = sizeof(num_cpus);
488 int numcpus_name[] = { CTL_HW, HW_NCPU };
489 if (::sysctl(numcpus_name, arraysize(numcpus_name), &num_cpus, &size, 0, 0)
490 == 0
491 && (size == sizeof(num_cpus)))
492 cpuinfo_num_cpus = num_cpus;
493
494#else
495 // Generic cycles per second counter
496 cpuinfo_cycles_per_second = EstimateCyclesPerSecond(1000);
497#endif
498}
499
500double CyclesPerSecond(void) {
501 InitializeSystemInfo();
502 return cpuinfo_cycles_per_second;
503}
504
505int NumCPUs(void) {
506 InitializeSystemInfo();
507 return cpuinfo_num_cpus;
508}
509
510// ----------------------------------------------------------------------
511// HasPosixThreads()
512// Return true if we're running POSIX (e.g., NPTL on Linux)
513// threads, as opposed to a non-POSIX thread library. The thing
514// that we care about is whether a thread's pid is the same as
515// the thread that spawned it. If so, this function returns
516// true.
517// ----------------------------------------------------------------------
518bool HasPosixThreads() {
519#if defined(__linux__)
520#ifndef _CS_GNU_LIBPTHREAD_VERSION
521#define _CS_GNU_LIBPTHREAD_VERSION 3
522#endif
523 char buf[32];
524 // We assume that, if confstr() doesn't know about this name, then
525 // the same glibc is providing LinuxThreads.
526 if (confstr(_CS_GNU_LIBPTHREAD_VERSION, buf, sizeof(buf)) == 0)
527 return false;
528 return strncmp(buf, "NPTL", 4) == 0;
529#elif defined(PLATFORM_WINDOWS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
530 return false;
531#else // other OS
532 return true; // Assume that everything else has Posix
533#endif // else OS_LINUX
534}
535
536// ----------------------------------------------------------------------
537
538#if defined __linux__ || defined __FreeBSD__ || defined __sun__ || defined __CYGWIN__ || defined __CYGWIN32__
539static void ConstructFilename(const char* spec, pid_t pid,
540 char* buf, int buf_size) {
541 CHECK_LT(snprintf(buf, buf_size,
542 spec,
543 static_cast<int>(pid ? pid : getpid())), buf_size);
544}
545#endif
546
547// A templatized helper function instantiated for Mach (OS X) only.
548// It can handle finding info for both 32 bits and 64 bits.
549// Returns true if it successfully handled the hdr, false else.
550#ifdef __MACH__ // Mac OS X, almost certainly
551template<uint32_t kMagic, uint32_t kLCSegment,
552 typename MachHeader, typename SegmentCommand>
553static bool NextExtMachHelper(const mach_header* hdr,
554 int current_image, int current_load_cmd,
555 uint64 *start, uint64 *end, char **flags,
556 uint64 *offset, int64 *inode, char **filename,
557 uint64 *file_mapping, uint64 *file_pages,
558 uint64 *anon_mapping, uint64 *anon_pages,
559 dev_t *dev) {
560 static char kDefaultPerms[5] = "r-xp";
561 if (hdr->magic != kMagic)
562 return false;
563 const char* lc = (const char *)hdr + sizeof(MachHeader);
564 // TODO(csilvers): make this not-quadradic (increment and hold state)
565 for (int j = 0; j < current_load_cmd; j++) // advance to *our* load_cmd
566 lc += ((const load_command *)lc)->cmdsize;
567 if (((const load_command *)lc)->cmd == kLCSegment) {
568 const intptr_t dlloff = _dyld_get_image_vmaddr_slide(current_image);
569 const SegmentCommand* sc = (const SegmentCommand *)lc;
570 if (start) *start = sc->vmaddr + dlloff;
571 if (end) *end = sc->vmaddr + sc->vmsize + dlloff;
572 if (flags) *flags = kDefaultPerms; // can we do better?
573 if (offset) *offset = sc->fileoff;
574 if (inode) *inode = 0;
575 if (filename)
576 *filename = const_cast<char*>(_dyld_get_image_name(current_image));
577 if (file_mapping) *file_mapping = 0;
578 if (file_pages) *file_pages = 0; // could we use sc->filesize?
579 if (anon_mapping) *anon_mapping = 0;
580 if (anon_pages) *anon_pages = 0;
581 if (dev) *dev = 0;
582 return true;
583 }
584
585 return false;
586}
587#endif
588
589// Finds |c| in |text|, and assign '\0' at the found position.
590// The original character at the modified position should be |c|.
591// A pointer to the modified position is stored in |endptr|.
592// |endptr| should not be NULL.
593static bool ExtractUntilChar(char *text, int c, char **endptr) {
594 CHECK_NE(text, NULL);
595 CHECK_NE(endptr, NULL);
596 char *found;
597 found = strchr(text, c);
598 if (found == NULL) {
599 *endptr = NULL;
600 return false;
601 }
602
603 *endptr = found;
604 *found = '\0';
605 return true;
606}
607
608// Increments |*text_pointer| while it points a whitespace character.
609// It is to follow sscanf's whilespace handling.
610static void SkipWhileWhitespace(char **text_pointer, int c) {
611 if (isspace(c)) {
612 while (isspace(**text_pointer) && isspace(*((*text_pointer) + 1))) {
613 ++(*text_pointer);
614 }
615 }
616}
617
618template<class T>
619static T StringToInteger(char *text, char **endptr, int base) {
620 assert(false);
621 return T();
622}
623
624template<>
625int StringToInteger<int>(char *text, char **endptr, int base) {
626 return strtol(text, endptr, base);
627}
628
629template<>
630int64 StringToInteger<int64>(char *text, char **endptr, int base) {
631 return strtoll(text, endptr, base);
632}
633
634template<>
635uint64 StringToInteger<uint64>(char *text, char **endptr, int base) {
636 return strtoull(text, endptr, base);
637}
638
639template<typename T>
640static T StringToIntegerUntilChar(
641 char *text, int base, int c, char **endptr_result) {
642 CHECK_NE(endptr_result, NULL);
643 *endptr_result = NULL;
644
645 char *endptr_extract;
646 if (!ExtractUntilChar(text, c, &endptr_extract))
647 return 0;
648
649 T result;
650 char *endptr_strto;
651 result = StringToInteger<T>(text, &endptr_strto, base);
652 *endptr_extract = c;
653
654 if (endptr_extract != endptr_strto)
655 return 0;
656
657 *endptr_result = endptr_extract;
658 SkipWhileWhitespace(endptr_result, c);
659
660 return result;
661}
662
663static char *CopyStringUntilChar(
664 char *text, unsigned out_len, int c, char *out) {
665 char *endptr;
666 if (!ExtractUntilChar(text, c, &endptr))
667 return NULL;
668
669 strncpy(out, text, out_len);
670 out[out_len-1] = '\0';
671 *endptr = c;
672
673 SkipWhileWhitespace(&endptr, c);
674 return endptr;
675}
676
677template<typename T>
678static bool StringToIntegerUntilCharWithCheck(
679 T *outptr, char *text, int base, int c, char **endptr) {
680 *outptr = StringToIntegerUntilChar<T>(*endptr, base, c, endptr);
681 if (*endptr == NULL || **endptr == '\0') return false;
682 ++(*endptr);
683 return true;
684}
685
686static bool ParseProcMapsLine(char *text, uint64 *start, uint64 *end,
687 char *flags, uint64 *offset,
688 int *major, int *minor, int64 *inode,
689 unsigned *filename_offset) {
690#if defined(__linux__)
691 /*
692 * It's similar to:
693 * sscanf(text, "%"SCNx64"-%"SCNx64" %4s %"SCNx64" %x:%x %"SCNd64" %n",
694 * start, end, flags, offset, major, minor, inode, filename_offset)
695 */
696 char *endptr = text;
697 if (endptr == NULL || *endptr == '\0') return false;
698
699 if (!StringToIntegerUntilCharWithCheck(start, endptr, 16, '-', &endptr))
700 return false;
701
702 if (!StringToIntegerUntilCharWithCheck(end, endptr, 16, ' ', &endptr))
703 return false;
704
705 endptr = CopyStringUntilChar(endptr, 5, ' ', flags);
706 if (endptr == NULL || *endptr == '\0') return false;
707 ++endptr;
708
709 if (!StringToIntegerUntilCharWithCheck(offset, endptr, 16, ' ', &endptr))
710 return false;
711
712 if (!StringToIntegerUntilCharWithCheck(major, endptr, 16, ':', &endptr))
713 return false;
714
715 if (!StringToIntegerUntilCharWithCheck(minor, endptr, 16, ' ', &endptr))
716 return false;
717
718 if (!StringToIntegerUntilCharWithCheck(inode, endptr, 10, ' ', &endptr))
719 return false;
720
721 *filename_offset = (endptr - text);
722 return true;
723#else
724 return false;
725#endif
726}
727
728ProcMapsIterator::ProcMapsIterator(pid_t pid) {
729 Init(pid, NULL, false);
730}
731
732ProcMapsIterator::ProcMapsIterator(pid_t pid, Buffer *buffer) {
733 Init(pid, buffer, false);
734}
735
736ProcMapsIterator::ProcMapsIterator(pid_t pid, Buffer *buffer,
737 bool use_maps_backing) {
738 Init(pid, buffer, use_maps_backing);
739}
740
741void ProcMapsIterator::Init(pid_t pid, Buffer *buffer,
742 bool use_maps_backing) {
743 pid_ = pid;
744 using_maps_backing_ = use_maps_backing;
745 dynamic_buffer_ = NULL;
746 if (!buffer) {
747 // If the user didn't pass in any buffer storage, allocate it
748 // now. This is the normal case; the signal handler passes in a
749 // static buffer.
750 buffer = dynamic_buffer_ = new Buffer;
751 } else {
752 dynamic_buffer_ = NULL;
753 }
754
755 ibuf_ = buffer->buf_;
756
757 stext_ = etext_ = nextline_ = ibuf_;
758 ebuf_ = ibuf_ + Buffer::kBufSize - 1;
759 nextline_ = ibuf_;
760
761#if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
762 if (use_maps_backing) { // don't bother with clever "self" stuff in this case
763 ConstructFilename("/proc/%d/maps_backing", pid, ibuf_, Buffer::kBufSize);
764 } else if (pid == 0) {
765 // We have to kludge a bit to deal with the args ConstructFilename
766 // expects. The 1 is never used -- it's only impt. that it's not 0.
767 ConstructFilename("/proc/self/maps", 1, ibuf_, Buffer::kBufSize);
768 } else {
769 ConstructFilename("/proc/%d/maps", pid, ibuf_, Buffer::kBufSize);
770 }
771 // No error logging since this can be called from the crash dump
772 // handler at awkward moments. Users should call Valid() before
773 // using.
774 NO_INTR(fd_ = open(ibuf_, O_RDONLY));
775#elif defined(__FreeBSD__)
776 // We don't support maps_backing on freebsd
777 if (pid == 0) {
778 ConstructFilename("/proc/curproc/map", 1, ibuf_, Buffer::kBufSize);
779 } else {
780 ConstructFilename("/proc/%d/map", pid, ibuf_, Buffer::kBufSize);
781 }
782 NO_INTR(fd_ = open(ibuf_, O_RDONLY));
783#elif defined(__sun__)
784 if (pid == 0) {
785 ConstructFilename("/proc/self/map", 1, ibuf_, Buffer::kBufSize);
786 } else {
787 ConstructFilename("/proc/%d/map", pid, ibuf_, Buffer::kBufSize);
788 }
789 NO_INTR(fd_ = open(ibuf_, O_RDONLY));
790#elif defined(__MACH__)
791 current_image_ = _dyld_image_count(); // count down from the top
792 current_load_cmd_ = -1;
793#elif defined(PLATFORM_WINDOWS)
794 snapshot_ = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE |
795 TH32CS_SNAPMODULE32,
796 GetCurrentProcessId());
797 memset(&module_, 0, sizeof(module_));
798#else
799 fd_ = -1; // so Valid() is always false
800#endif
801
802}
803
804ProcMapsIterator::~ProcMapsIterator() {
805#if defined(PLATFORM_WINDOWS)
806 if (snapshot_ != INVALID_HANDLE_VALUE) CloseHandle(snapshot_);
807#elif defined(__MACH__)
808 // no cleanup necessary!
809#else
810 if (fd_ >= 0) NO_INTR(close(fd_));
811#endif
812 delete dynamic_buffer_;
813}
814
815bool ProcMapsIterator::Valid() const {
816#if defined(PLATFORM_WINDOWS)
817 return snapshot_ != INVALID_HANDLE_VALUE;
818#elif defined(__MACH__)
819 return 1;
820#else
821 return fd_ != -1;
822#endif
823}
824
825bool ProcMapsIterator::Next(uint64 *start, uint64 *end, char **flags,
826 uint64 *offset, int64 *inode, char **filename) {
827 return NextExt(start, end, flags, offset, inode, filename, NULL, NULL,
828 NULL, NULL, NULL);
829}
830
831// This has too many arguments. It should really be building
832// a map object and returning it. The problem is that this is called
833// when the memory allocator state is undefined, hence the arguments.
834bool ProcMapsIterator::NextExt(uint64 *start, uint64 *end, char **flags,
835 uint64 *offset, int64 *inode, char **filename,
836 uint64 *file_mapping, uint64 *file_pages,
837 uint64 *anon_mapping, uint64 *anon_pages,
838 dev_t *dev) {
839
840#if defined(__linux__) || defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
841 do {
842 // Advance to the start of the next line
843 stext_ = nextline_;
844
845 // See if we have a complete line in the buffer already
846 nextline_ = static_cast<char *>(memchr (stext_, '\n', etext_ - stext_));
847 if (!nextline_) {
848 // Shift/fill the buffer so we do have a line
849 int count = etext_ - stext_;
850
851 // Move the current text to the start of the buffer
852 memmove(ibuf_, stext_, count);
853 stext_ = ibuf_;
854 etext_ = ibuf_ + count;
855
856 int nread = 0; // fill up buffer with text
857 while (etext_ < ebuf_) {
858 NO_INTR(nread = read(fd_, etext_, ebuf_ - etext_));
859 if (nread > 0)
860 etext_ += nread;
861 else
862 break;
863 }
864
865 // Zero out remaining characters in buffer at EOF to avoid returning
866 // garbage from subsequent calls.
867 if (etext_ != ebuf_ && nread == 0) {
868 memset(etext_, 0, ebuf_ - etext_);
869 }
870 *etext_ = '\n'; // sentinel; safe because ibuf extends 1 char beyond ebuf
871 nextline_ = static_cast<char *>(memchr (stext_, '\n', etext_ + 1 - stext_));
872 }
873 *nextline_ = 0; // turn newline into nul
874 nextline_ += ((nextline_ < etext_)? 1 : 0); // skip nul if not end of text
875 // stext_ now points at a nul-terminated line
876 uint64 tmpstart, tmpend, tmpoffset;
877 int64 tmpinode;
878 int major, minor;
879 unsigned filename_offset = 0;
880#if defined(__linux__)
881 // for now, assume all linuxes have the same format
882 if (!ParseProcMapsLine(
883 stext_,
884 start ? start : &tmpstart,
885 end ? end : &tmpend,
886 flags_,
887 offset ? offset : &tmpoffset,
888 &major, &minor,
889 inode ? inode : &tmpinode, &filename_offset)) continue;
890#elif defined(__CYGWIN__) || defined(__CYGWIN32__)
891 // cygwin is like linux, except the third field is the "entry point"
892 // rather than the offset (see format_process_maps at
893 // http://cygwin.com/cgi-bin/cvsweb.cgi/src/winsup/cygwin/fhandler_process.cc?rev=1.89&content-type=text/x-cvsweb-markup&cvsroot=src
894 // Offset is always be 0 on cygwin: cygwin implements an mmap
895 // by loading the whole file and then calling NtMapViewOfSection.
896 // Cygwin also seems to set its flags kinda randomly; use windows default.
897 char tmpflags[5];
898 if (offset)
899 *offset = 0;
900 strcpy(flags_, "r-xp");
901 if (sscanf(stext_, "%llx-%llx %4s %llx %x:%x %lld %n",
902 start ? start : &tmpstart,
903 end ? end : &tmpend,
904 tmpflags,
905 &tmpoffset,
906 &major, &minor,
907 inode ? inode : &tmpinode, &filename_offset) != 7) continue;
908#elif defined(__FreeBSD__)
909 // For the format, see http://www.freebsd.org/cgi/cvsweb.cgi/src/sys/fs/procfs/procfs_map.c?rev=1.31&content-type=text/x-cvsweb-markup
910 tmpstart = tmpend = tmpoffset = 0;
911 tmpinode = 0;
912 major = minor = 0; // can't get this info in freebsd
913 if (inode)
914 *inode = 0; // nor this
915 if (offset)
916 *offset = 0; // seems like this should be in there, but maybe not
917 // start end resident privateresident obj(?) prot refcnt shadowcnt
918 // flags copy_on_write needs_copy type filename:
919 // 0x8048000 0x804a000 2 0 0xc104ce70 r-x 1 0 0x0 COW NC vnode /bin/cat
920 if (sscanf(stext_, "0x%" SCNx64 " 0x%" SCNx64 " %*d %*d %*p %3s %*d %*d 0x%*x %*s %*s %*s %n",
921 start ? start : &tmpstart,
922 end ? end : &tmpend,
923 flags_,
924 &filename_offset) != 3) continue;
925#endif
926
927 // Depending on the Linux kernel being used, there may or may not be a space
928 // after the inode if there is no filename. sscanf will in such situations
929 // nondeterministically either fill in filename_offset or not (the results
930 // differ on multiple calls in the same run even with identical arguments).
931 // We don't want to wander off somewhere beyond the end of the string.
932 size_t stext_length = strlen(stext_);
933 if (filename_offset == 0 || filename_offset > stext_length)
934 filename_offset = stext_length;
935
936 // We found an entry
937 if (flags) *flags = flags_;
938 if (filename) *filename = stext_ + filename_offset;
939 if (dev) *dev = minor | (major << 8);
940
941 if (using_maps_backing_) {
942 // Extract and parse physical page backing info.
943 char *backing_ptr = stext_ + filename_offset +
944 strlen(stext_+filename_offset);
945
946 // find the second '('
947 int paren_count = 0;
948 while (--backing_ptr > stext_) {
949 if (*backing_ptr == '(') {
950 ++paren_count;
951 if (paren_count >= 2) {
952 uint64 tmp_file_mapping;
953 uint64 tmp_file_pages;
954 uint64 tmp_anon_mapping;
955 uint64 tmp_anon_pages;
956
957 sscanf(backing_ptr+1, "F %" SCNx64 " %" SCNd64 ") (A %" SCNx64 " %" SCNd64 ")",
958 file_mapping ? file_mapping : &tmp_file_mapping,
959 file_pages ? file_pages : &tmp_file_pages,
960 anon_mapping ? anon_mapping : &tmp_anon_mapping,
961 anon_pages ? anon_pages : &tmp_anon_pages);
962 // null terminate the file name (there is a space
963 // before the first (.
964 backing_ptr[-1] = 0;
965 break;
966 }
967 }
968 }
969 }
970
971 return true;
972 } while (etext_ > ibuf_);
973#elif defined(__sun__)
974 // This is based on MA_READ == 4, MA_WRITE == 2, MA_EXEC == 1
975 static char kPerms[8][4] = { "---", "--x", "-w-", "-wx",
976 "r--", "r-x", "rw-", "rwx" };
977 COMPILE_ASSERT(MA_READ == 4, solaris_ma_read_must_equal_4);
978 COMPILE_ASSERT(MA_WRITE == 2, solaris_ma_write_must_equal_2);
979 COMPILE_ASSERT(MA_EXEC == 1, solaris_ma_exec_must_equal_1);
980 Buffer object_path;
981 int nread = 0; // fill up buffer with text
982 NO_INTR(nread = read(fd_, ibuf_, sizeof(prmap_t)));
983 if (nread == sizeof(prmap_t)) {
984 long inode_from_mapname = 0;
985 prmap_t* mapinfo = reinterpret_cast<prmap_t*>(ibuf_);
986 // Best-effort attempt to get the inode from the filename. I think the
987 // two middle ints are major and minor device numbers, but I'm not sure.
988 sscanf(mapinfo->pr_mapname, "ufs.%*d.%*d.%ld", &inode_from_mapname);
989
990 if (pid_ == 0) {
991 CHECK_LT(snprintf(object_path.buf_, Buffer::kBufSize,
992 "/proc/self/path/%s", mapinfo->pr_mapname),
993 Buffer::kBufSize);
994 } else {
995 CHECK_LT(snprintf(object_path.buf_, Buffer::kBufSize,
996 "/proc/%d/path/%s",
997 static_cast<int>(pid_), mapinfo->pr_mapname),
998 Buffer::kBufSize);
999 }
1000 ssize_t len = readlink(object_path.buf_, current_filename_, PATH_MAX);
1001 CHECK_LT(len, PATH_MAX);
1002 if (len < 0)
1003 len = 0;
1004 current_filename_[len] = '\0';
1005
1006 if (start) *start = mapinfo->pr_vaddr;
1007 if (end) *end = mapinfo->pr_vaddr + mapinfo->pr_size;
1008 if (flags) *flags = kPerms[mapinfo->pr_mflags & 7];
1009 if (offset) *offset = mapinfo->pr_offset;
1010 if (inode) *inode = inode_from_mapname;
1011 if (filename) *filename = current_filename_;
1012 if (file_mapping) *file_mapping = 0;
1013 if (file_pages) *file_pages = 0;
1014 if (anon_mapping) *anon_mapping = 0;
1015 if (anon_pages) *anon_pages = 0;
1016 if (dev) *dev = 0;
1017 return true;
1018 }
1019#elif defined(__MACH__)
1020 // We return a separate entry for each segment in the DLL. (TODO(csilvers):
1021 // can we do better?) A DLL ("image") has load-commands, some of which
1022 // talk about segment boundaries.
1023 // cf image_for_address from http://svn.digium.com/view/asterisk/team/oej/minivoicemail/dlfcn.c?revision=53912
1024 for (; current_image_ >= 0; current_image_--) {
1025 const mach_header* hdr = _dyld_get_image_header(current_image_);
1026 if (!hdr) continue;
1027 if (current_load_cmd_ < 0) // set up for this image
1028 current_load_cmd_ = hdr->ncmds; // again, go from the top down
1029
1030 // We start with the next load command (we've already looked at this one).
1031 for (current_load_cmd_--; current_load_cmd_ >= 0; current_load_cmd_--) {
1032#ifdef MH_MAGIC_64
1033 if (NextExtMachHelper<MH_MAGIC_64, LC_SEGMENT_64,
1034 struct mach_header_64, struct segment_command_64>(
1035 hdr, current_image_, current_load_cmd_,
1036 start, end, flags, offset, inode, filename,
1037 file_mapping, file_pages, anon_mapping,
1038 anon_pages, dev)) {
1039 return true;
1040 }
1041#endif
1042 if (NextExtMachHelper<MH_MAGIC, LC_SEGMENT,
1043 struct mach_header, struct segment_command>(
1044 hdr, current_image_, current_load_cmd_,
1045 start, end, flags, offset, inode, filename,
1046 file_mapping, file_pages, anon_mapping,
1047 anon_pages, dev)) {
1048 return true;
1049 }
1050 }
1051 // If we get here, no more load_cmd's in this image talk about
1052 // segments. Go on to the next image.
1053 }
1054#elif defined(PLATFORM_WINDOWS)
1055 static char kDefaultPerms[5] = "r-xp";
1056 BOOL ok;
1057 if (module_.dwSize == 0) { // only possible before first call
1058 module_.dwSize = sizeof(module_);
1059 ok = Module32First(snapshot_, &module_);
1060 } else {
1061 ok = Module32Next(snapshot_, &module_);
1062 }
1063 if (ok) {
1064 uint64 base_addr = reinterpret_cast<DWORD_PTR>(module_.modBaseAddr);
1065 if (start) *start = base_addr;
1066 if (end) *end = base_addr + module_.modBaseSize;
1067 if (flags) *flags = kDefaultPerms;
1068 if (offset) *offset = 0;
1069 if (inode) *inode = 0;
1070 if (filename) *filename = module_.szExePath;
1071 if (file_mapping) *file_mapping = 0;
1072 if (file_pages) *file_pages = 0;
1073 if (anon_mapping) *anon_mapping = 0;
1074 if (anon_pages) *anon_pages = 0;
1075 if (dev) *dev = 0;
1076 return true;
1077 }
1078#endif
1079
1080 // We didn't find anything
1081 return false;
1082}
1083
1084int ProcMapsIterator::FormatLine(char* buffer, int bufsize,
1085 uint64 start, uint64 end, const char *flags,
1086 uint64 offset, int64 inode,
1087 const char *filename, dev_t dev) {
1088 // We assume 'flags' looks like 'rwxp' or 'rwx'.
1089 char r = (flags && flags[0] == 'r') ? 'r' : '-';
1090 char w = (flags && flags[0] && flags[1] == 'w') ? 'w' : '-';
1091 char x = (flags && flags[0] && flags[1] && flags[2] == 'x') ? 'x' : '-';
1092 // p always seems set on linux, so we set the default to 'p', not '-'
1093 char p = (flags && flags[0] && flags[1] && flags[2] && flags[3] != 'p')
1094 ? '-' : 'p';
1095
1096 const int rc = snprintf(buffer, bufsize,
1097 "%08" PRIx64 "-%08" PRIx64 " %c%c%c%c %08" PRIx64 " %02x:%02x %-11" PRId64 " %s\n",
1098 start, end, r,w,x,p, offset,
1099 static_cast<int>(dev/256), static_cast<int>(dev%256),
1100 inode, filename);
1101 return (rc < 0 || rc >= bufsize) ? 0 : rc;
1102}
1103
1104namespace tcmalloc {
1105
1106// Helper to add the list of mapped shared libraries to a profile.
1107// Fill formatted "/proc/self/maps" contents into buffer 'buf' of size 'size'
1108// and return the actual size occupied in 'buf'. We fill wrote_all to true
1109// if we successfully wrote all proc lines to buf, false else.
1110// We do not provision for 0-terminating 'buf'.
1111int FillProcSelfMaps(char buf[], int size, bool* wrote_all) {
1112 ProcMapsIterator::Buffer iterbuf;
1113 ProcMapsIterator it(0, &iterbuf); // 0 means "current pid"
1114
1115 uint64 start, end, offset;
1116 int64 inode;
1117 char *flags, *filename;
1118 int bytes_written = 0;
1119 *wrote_all = true;
1120 while (it.Next(&start, &end, &flags, &offset, &inode, &filename)) {
1121 const int line_length = it.FormatLine(buf + bytes_written,
1122 size - bytes_written,
1123 start, end, flags, offset,
1124 inode, filename, 0);
1125 if (line_length == 0)
1126 *wrote_all = false; // failed to write this line out
1127 else
1128 bytes_written += line_length;
1129
1130 }
1131 return bytes_written;
1132}
1133
1134// Dump the same data as FillProcSelfMaps reads to fd.
1135// It seems easier to repeat parts of FillProcSelfMaps here than to
1136// reuse it via a call.
1137void DumpProcSelfMaps(RawFD fd) {
1138 ProcMapsIterator::Buffer iterbuf;
1139 ProcMapsIterator it(0, &iterbuf); // 0 means "current pid"
1140
1141 uint64 start, end, offset;
1142 int64 inode;
1143 char *flags, *filename;
1144 ProcMapsIterator::Buffer linebuf;
1145 while (it.Next(&start, &end, &flags, &offset, &inode, &filename)) {
1146 int written = it.FormatLine(linebuf.buf_, sizeof(linebuf.buf_),
1147 start, end, flags, offset, inode, filename,
1148 0);
1149 RawWrite(fd, linebuf.buf_, written);
1150 }
1151}
1152
1153} // namespace tcmalloc