1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #if (defined(_WIN32) || defined(__MINGW32__)) && !defined(__CYGWIN__) && !defined(__CYGWIN32)
32 # define PLATFORM_WINDOWS 1
35 #include <ctype.h> // for isspace()
36 #include <stdlib.h> // for getenv()
37 #include <stdio.h> // for snprintf(), sscanf()
38 #include <string.h> // for memmove(), memchr(), etc.
39 #include <fcntl.h> // for open()
40 #include <errno.h> // for errno
42 #include <unistd.h> // for read()
44 #if defined __MACH__ // Mac OS X, almost certainly
45 #include <mach-o/dyld.h> // for iterating over dll's in ProcMapsIter
46 #include <mach-o/loader.h> // for iterating over dll's in ProcMapsIter
47 #include <sys/types.h>
48 #include <sys/sysctl.h> // how we figure out numcpu's on OS X
49 #elif defined __FreeBSD__
50 #include <sys/sysctl.h>
51 #elif defined __sun__ // Solaris
52 #include <procfs.h> // for, e.g., prmap_t
53 #elif defined(PLATFORM_WINDOWS)
54 #include <process.h> // for getpid() (actually, _getpid())
55 #include <shlwapi.h> // for SHGetValueA()
56 #include <tlhelp32.h> // for Module32First()
58 #include "base/sysinfo.h"
59 #include "base/commandlineflags.h"
60 #include "base/dynamic_annotations.h" // for RunningOnValgrind
61 #include "base/logging.h"
62 #include "base/cycleclock.h"
64 #ifdef PLATFORM_WINDOWS
66 // In a change from the usual W-A pattern, there is no A variant of
67 // MODULEENTRY32. Tlhelp32.h #defines the W variant, but not the A.
68 // In unicode mode, tlhelp32.h #defines MODULEENTRY32 to be
69 // MODULEENTRY32W. These #undefs are the only way I see to get back
70 // access to the original, ascii struct (and related functions).
75 #undef LPMODULEENTRY32
76 #endif /* MODULEENTRY32 */
77 // MinGW doesn't seem to define this, perhaps some windowsen don't either.
78 #ifndef TH32CS_SNAPMODULE32
79 #define TH32CS_SNAPMODULE32 0
80 #endif /* TH32CS_SNAPMODULE32 */
81 #endif /* PLATFORM_WINDOWS */
83 // Re-run fn until it doesn't cause EINTR.
84 #define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR)
86 // open/read/close can set errno, which may be illegal at this
87 // time, so prefer making the syscalls directly if we can.
88 #ifdef HAVE_SYS_SYSCALL_H
89 # include <sys/syscall.h>
91 #ifdef SYS_open // solaris 11, at least sometimes, only defines SYS_openat
92 # define safeopen(filename, mode) syscall(SYS_open, filename, mode)
94 # define safeopen(filename, mode) open(filename, mode)
97 # define saferead(fd, buffer, size) syscall(SYS_read, fd, buffer, size)
99 # define saferead(fd, buffer, size) read(fd, buffer, size)
102 # define safeclose(fd) syscall(SYS_close, fd)
104 # define safeclose(fd) close(fd)
107 // ----------------------------------------------------------------------
108 // GetenvBeforeMain()
109 // GetUniquePathFromEnv()
110 // Some non-trivial getenv-related functions.
111 // ----------------------------------------------------------------------
113 // It's not safe to call getenv() in the malloc hooks, because they
114 // might be called extremely early, before libc is done setting up
115 // correctly. In particular, the thread library may not be done
116 // setting up errno. So instead, we use the built-in __environ array
117 // if it exists, and otherwise read /proc/self/environ directly, using
118 // system calls to read the file, and thus avoid setting errno.
119 // /proc/self/environ has a limit of how much data it exports (around
120 // 8K), so it's not an ideal solution.
121 const char* GetenvBeforeMain(const char* name
) {
122 #if defined(HAVE___ENVIRON) // if we have it, it's declared in unistd.h
123 if (__environ
) { // can exist but be NULL, if statically linked
124 const int namelen
= strlen(name
);
125 for (char** p
= __environ
; *p
; p
++) {
126 if (!memcmp(*p
, name
, namelen
) && (*p
)[namelen
] == '=') // it's a match
127 return *p
+ namelen
+1; // point after =
132 #if defined(PLATFORM_WINDOWS)
133 // TODO(mbelshe) - repeated calls to this function will overwrite the
134 // contents of the static buffer.
135 static char envvar_buf
[1024]; // enough to hold any envvar we care about
136 if (!GetEnvironmentVariableA(name
, envvar_buf
, sizeof(envvar_buf
)-1))
140 // static is ok because this function should only be called before
141 // main(), when we're single-threaded.
142 static char envbuf
[16<<10];
143 if (*envbuf
== '\0') { // haven't read the environ yet
144 int fd
= safeopen("/proc/self/environ", O_RDONLY
);
145 // The -2 below guarantees the last two bytes of the buffer will be \0\0
146 if (fd
== -1 || // unable to open the file, fall back onto libc
147 saferead(fd
, envbuf
, sizeof(envbuf
) - 2) < 0) { // error reading file
148 RAW_VLOG(1, "Unable to open /proc/self/environ, falling back "
149 "on getenv(\"%s\"), which may not work", name
);
150 if (fd
!= -1) safeclose(fd
);
155 const int namelen
= strlen(name
);
156 const char* p
= envbuf
;
157 while (*p
!= '\0') { // will happen at the \0\0 that terminates the buffer
158 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
159 const char* endp
= (char*)memchr(p
, '\0', sizeof(envbuf
) - (p
- envbuf
));
160 if (endp
== NULL
) // this entry isn't NUL terminated
162 else if (!memcmp(p
, name
, namelen
) && p
[namelen
] == '=') // it's a match
163 return p
+ namelen
+1; // point after =
166 return NULL
; // env var never found
169 // This takes as an argument an environment-variable name (like
170 // CPUPROFILE) whose value is supposed to be a file-path, and sets
171 // path to that path, and returns true. If the env var doesn't exist,
172 // or is the empty string, leave path unchanged and returns false.
173 // The reason this is non-trivial is that this function handles munged
174 // pathnames. Here's why:
176 // If we're a child process of the 'main' process, we can't just use
177 // getenv("CPUPROFILE") -- the parent process will be using that path.
178 // Instead we append our pid to the pathname. How do we tell if we're a
179 // child process? Ideally we'd set an environment variable that all
180 // our children would inherit. But -- and this is seemingly a bug in
181 // gcc -- if you do a setenv() in a shared libarary in a global
182 // constructor, the environment setting is lost by the time main() is
183 // called. The only safe thing we can do in such a situation is to
184 // modify the existing envvar. So we do a hack: in the parent, we set
185 // the high bit of the 1st char of CPUPROFILE. In the child, we
186 // notice the high bit is set and append the pid(). This works
187 // assuming cpuprofile filenames don't normally have the high bit set
188 // in their first character! If that assumption is violated, we'll
189 // still get a profile, but one with an unexpected name.
190 // TODO(csilvers): set an envvar instead when we can do it reliably.
192 // In Chromium this hack is intentionally disabled, because the path is not
193 // re-initialized upon fork.
194 bool GetUniquePathFromEnv(const char* env_name
, char* path
) {
195 char* envval
= getenv(env_name
);
196 if (envval
== NULL
|| *envval
== '\0')
198 if (envval
[0] & 128) { // high bit is set
199 snprintf(path
, PATH_MAX
, "%c%s_%u", // add pid and clear high bit
200 envval
[0] & 127, envval
+1, (unsigned int)(getpid()));
202 snprintf(path
, PATH_MAX
, "%s", envval
);
204 envval
[0] |= 128; // set high bit for kids to see
210 // ----------------------------------------------------------------------
213 // It's important this not call malloc! -- they may be called at
214 // global-construct time, before we've set up all our proper malloc
216 // ----------------------------------------------------------------------
218 static double cpuinfo_cycles_per_second
= 1.0; // 0.0 might be dangerous
219 static int cpuinfo_num_cpus
= 1; // Conservative guess
221 void SleepForMilliseconds(int milliseconds
) {
222 #ifdef PLATFORM_WINDOWS
223 _sleep(milliseconds
); // Windows's _sleep takes milliseconds argument
225 // Sleep for a few milliseconds
226 struct timespec sleep_time
;
227 sleep_time
.tv_sec
= milliseconds
/ 1000;
228 sleep_time
.tv_nsec
= (milliseconds
% 1000) * 1000000;
229 while (nanosleep(&sleep_time
, &sleep_time
) != 0 && errno
== EINTR
)
230 ; // Ignore signals and wait for the full interval to elapse.
234 // Helper function estimates cycles/sec by observing cycles elapsed during
235 // sleep(). Using small sleep time decreases accuracy significantly.
236 static int64
EstimateCyclesPerSecond(const int estimate_time_ms
) {
237 assert(estimate_time_ms
> 0);
238 if (estimate_time_ms
<= 0)
240 double multiplier
= 1000.0 / (double)estimate_time_ms
; // scale by this much
242 const int64 start_ticks
= CycleClock::Now();
243 SleepForMilliseconds(estimate_time_ms
);
244 const int64 guess
= int64(multiplier
* (CycleClock::Now() - start_ticks
));
248 // ReadIntFromFile is only called on linux and cygwin platforms.
249 #if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
250 // Helper function for reading an int from a file. Returns true if successful
251 // and the memory location pointed to by value is set to the value read.
252 static bool ReadIntFromFile(const char *file
, int *value
) {
254 int fd
= open(file
, O_RDONLY
);
258 memset(line
, '\0', sizeof(line
));
259 read(fd
, line
, sizeof(line
) - 1);
260 const int temp_value
= strtol(line
, &err
, 10);
261 if (line
[0] != '\0' && (*err
== '\n' || *err
== '\0')) {
271 // WARNING: logging calls back to InitializeSystemInfo() so it must
272 // not invoke any logging code. Also, InitializeSystemInfo() can be
273 // called before main() -- in fact it *must* be since already_called
274 // isn't protected -- before malloc hooks are properly set up, so
275 // we make an effort not to call any routines which might allocate
278 static void InitializeSystemInfo() {
279 static bool already_called
= false; // safe if we run before threads
280 if (already_called
) return;
281 already_called
= true;
283 bool saw_mhz
= false;
285 if (RunningOnValgrind()) {
286 // Valgrind may slow the progress of time artificially (--scale-time=N
287 // option). We thus can't rely on CPU Mhz info stored in /sys or /proc
288 // files. Thus, actually measure the cps.
289 cpuinfo_cycles_per_second
= EstimateCyclesPerSecond(100);
293 #if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
298 // If the kernel is exporting the tsc frequency use that. There are issues
299 // where cpuinfo_max_freq cannot be relied on because the BIOS may be
300 // exporintg an invalid p-state (on x86) or p-states may be used to put the
301 // processor in a new mode (turbo mode). Essentially, those frequencies
302 // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as
305 ReadIntFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq
)) {
306 // The value is in kHz (as the file name suggests). For example, on a
307 // 2GHz warpstation, the file contains the value "2000000".
308 cpuinfo_cycles_per_second
= freq
* 1000.0;
312 // If CPU scaling is in effect, we want to use the *maximum* frequency,
313 // not whatever CPU speed some random processor happens to be using now.
315 ReadIntFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
317 // The value is in kHz. For example, on a 2GHz machine, the file
318 // contains the value "2000000".
319 cpuinfo_cycles_per_second
= freq
* 1000.0;
323 // Read /proc/cpuinfo for other values, and if there is no cpuinfo_max_freq.
324 const char* pname
= "/proc/cpuinfo";
325 int fd
= open(pname
, O_RDONLY
);
329 cpuinfo_cycles_per_second
= EstimateCyclesPerSecond(1000);
331 return; // TODO: use generic tester instead?
334 double bogo_clock
= 1.0;
335 bool saw_bogo
= false;
337 line
[0] = line
[1] = '\0';
339 do { // we'll exit when the last read didn't read anything
340 // Move the next line to the beginning of the buffer
341 const int oldlinelen
= strlen(line
);
342 if (sizeof(line
) == oldlinelen
+ 1) // oldlinelen took up entire line
344 else // still other lines left to save
345 memmove(line
, line
+ oldlinelen
+1, sizeof(line
) - (oldlinelen
+1));
346 // Terminate the new line, reading more if we can't find the newline
347 char* newline
= strchr(line
, '\n');
348 if (newline
== NULL
) {
349 const int linelen
= strlen(line
);
350 const int bytes_to_read
= sizeof(line
)-1 - linelen
;
351 assert(bytes_to_read
> 0); // because the memmove recovered >=1 bytes
352 chars_read
= read(fd
, line
+ linelen
, bytes_to_read
);
353 line
[linelen
+ chars_read
] = '\0';
354 newline
= strchr(line
, '\n');
359 // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only
360 // accept postive values. Some environments (virtual machines) report zero,
361 // which would cause infinite looping in WallTime_Init.
362 if (!saw_mhz
&& strncasecmp(line
, "cpu MHz", sizeof("cpu MHz")-1) == 0) {
363 const char* freqstr
= strchr(line
, ':');
365 cpuinfo_cycles_per_second
= strtod(freqstr
+1, &err
) * 1000000.0;
366 if (freqstr
[1] != '\0' && *err
== '\0' && cpuinfo_cycles_per_second
> 0)
369 } else if (strncasecmp(line
, "bogomips", sizeof("bogomips")-1) == 0) {
370 const char* freqstr
= strchr(line
, ':');
372 bogo_clock
= strtod(freqstr
+1, &err
) * 1000000.0;
373 if (freqstr
[1] != '\0' && *err
== '\0' && bogo_clock
> 0)
376 } else if (strncasecmp(line
, "processor", sizeof("processor")-1) == 0) {
377 num_cpus
++; // count up every time we see an "processor :" entry
379 } while (chars_read
> 0);
384 // If we didn't find anything better, we'll use bogomips, but
385 // we're not happy about it.
386 cpuinfo_cycles_per_second
= bogo_clock
;
388 // If we don't even have bogomips, we'll use the slow estimation.
389 cpuinfo_cycles_per_second
= EstimateCyclesPerSecond(1000);
392 if (cpuinfo_cycles_per_second
== 0.0) {
393 cpuinfo_cycles_per_second
= 1.0; // maybe unnecessary, but safe
396 cpuinfo_num_cpus
= num_cpus
;
399 #elif defined __FreeBSD__
400 // For this sysctl to work, the machine must be configured without
401 // SMP, APIC, or APM support. hz should be 64-bit in freebsd 7.0
402 // and later. Before that, it's a 32-bit quantity (and gives the
403 // wrong answer on machines faster than 2^32 Hz). See
404 // http://lists.freebsd.org/pipermail/freebsd-i386/2004-November/001846.html
405 // But also compare FreeBSD 7.0:
406 // http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG70#L223
407 // 231 error = sysctl_handle_quad(oidp, &freq, 0, req);
408 // To FreeBSD 6.3 (it's the same in 6-STABLE):
409 // http://fxr.watson.org/fxr/source/i386/i386/tsc.c?v=RELENG6#L131
410 // 139 error = sysctl_handle_int(oidp, &freq, sizeof(freq), req);
416 size_t sz
= sizeof(hz
);
417 const char *sysctl_path
= "machdep.tsc_freq";
418 if ( sysctlbyname(sysctl_path
, &hz
, &sz
, NULL
, 0) != 0 ) {
419 fprintf(stderr
, "Unable to determine clock rate from sysctl: %s: %s\n",
420 sysctl_path
, strerror(errno
));
421 cpuinfo_cycles_per_second
= EstimateCyclesPerSecond(1000);
423 cpuinfo_cycles_per_second
= hz
;
425 // TODO(csilvers): also figure out cpuinfo_num_cpus
427 #elif defined(PLATFORM_WINDOWS)
428 # pragma comment(lib, "shlwapi.lib") // for SHGetValue()
429 // In NT, read MHz from the registry. If we fail to do so or we're in win9x
430 // then make a crude estimate.
432 os
.dwOSVersionInfoSize
= sizeof(os
);
433 DWORD data
, data_size
= sizeof(data
);
434 if (GetVersionEx(&os
) &&
435 os
.dwPlatformId
== VER_PLATFORM_WIN32_NT
&&
436 SUCCEEDED(SHGetValueA(HKEY_LOCAL_MACHINE
,
437 "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
438 "~MHz", NULL
, &data
, &data_size
)))
439 cpuinfo_cycles_per_second
= (int64
)data
* (int64
)(1000 * 1000); // was mhz
441 cpuinfo_cycles_per_second
= EstimateCyclesPerSecond(500); // TODO <500?
443 // Get the number of processors.
445 GetSystemInfo(&info
);
446 cpuinfo_num_cpus
= info
.dwNumberOfProcessors
;
448 #elif defined(__MACH__) && defined(__APPLE__)
449 // returning "mach time units" per second. the current number of elapsed
450 // mach time units can be found by calling uint64 mach_absolute_time();
451 // while not as precise as actual CPU cycles, it is accurate in the face
452 // of CPU frequency scaling and multi-cpu/core machines.
453 // Our mac users have these types of machines, and accuracy
454 // (i.e. correctness) trumps precision.
455 // See cycleclock.h: CycleClock::Now(), which returns number of mach time
456 // units on Mac OS X.
457 mach_timebase_info_data_t timebase_info
;
458 mach_timebase_info(&timebase_info
);
459 double mach_time_units_per_nanosecond
=
460 static_cast<double>(timebase_info
.denom
) /
461 static_cast<double>(timebase_info
.numer
);
462 cpuinfo_cycles_per_second
= mach_time_units_per_nanosecond
* 1e9
;
465 size_t size
= sizeof(num_cpus
);
466 int numcpus_name
[] = { CTL_HW
, HW_NCPU
};
467 if (::sysctl(numcpus_name
, arraysize(numcpus_name
), &num_cpus
, &size
, 0, 0)
469 && (size
== sizeof(num_cpus
)))
470 cpuinfo_num_cpus
= num_cpus
;
473 // Generic cycles per second counter
474 cpuinfo_cycles_per_second
= EstimateCyclesPerSecond(1000);
478 double CyclesPerSecond(void) {
479 InitializeSystemInfo();
480 return cpuinfo_cycles_per_second
;
484 InitializeSystemInfo();
485 return cpuinfo_num_cpus
;
488 // ----------------------------------------------------------------------
490 // Return true if we're running POSIX (e.g., NPTL on Linux)
491 // threads, as opposed to a non-POSIX thread libary. The thing
492 // that we care about is whether a thread's pid is the same as
493 // the thread that spawned it. If so, this function returns
495 // ----------------------------------------------------------------------
496 bool HasPosixThreads() {
497 #if defined(__linux__)
498 #ifndef _CS_GNU_LIBPTHREAD_VERSION
499 #define _CS_GNU_LIBPTHREAD_VERSION 3
502 // We assume that, if confstr() doesn't know about this name, then
503 // the same glibc is providing LinuxThreads.
504 if (confstr(_CS_GNU_LIBPTHREAD_VERSION
, buf
, sizeof(buf
)) == 0)
506 return strncmp(buf
, "NPTL", 4) == 0;
507 #elif defined(PLATFORM_WINDOWS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
510 return true; // Assume that everything else has Posix
511 #endif // else OS_LINUX
514 // ----------------------------------------------------------------------
516 #if defined __linux__ || defined __FreeBSD__ || defined __sun__ || defined __CYGWIN__ || defined __CYGWIN32__
517 static void ConstructFilename(const char* spec
, pid_t pid
,
518 char* buf
, int buf_size
) {
519 CHECK_LT(snprintf(buf
, buf_size
,
521 static_cast<int>(pid
? pid
: getpid())), buf_size
);
525 // A templatized helper function instantiated for Mach (OS X) only.
526 // It can handle finding info for both 32 bits and 64 bits.
527 // Returns true if it successfully handled the hdr, false else.
528 #ifdef __MACH__ // Mac OS X, almost certainly
529 template<uint32_t kMagic
, uint32_t kLCSegment
,
530 typename MachHeader
, typename SegmentCommand
>
531 static bool NextExtMachHelper(const mach_header
* hdr
,
532 int current_image
, int current_load_cmd
,
533 uint64
*start
, uint64
*end
, char **flags
,
534 uint64
*offset
, int64
*inode
, char **filename
,
535 uint64
*file_mapping
, uint64
*file_pages
,
536 uint64
*anon_mapping
, uint64
*anon_pages
,
538 static char kDefaultPerms
[5] = "r-xp";
539 if (hdr
->magic
!= kMagic
)
541 const char* lc
= (const char *)hdr
+ sizeof(MachHeader
);
542 // TODO(csilvers): make this not-quadradic (increment and hold state)
543 for (int j
= 0; j
< current_load_cmd
; j
++) // advance to *our* load_cmd
544 lc
+= ((const load_command
*)lc
)->cmdsize
;
545 if (((const load_command
*)lc
)->cmd
== kLCSegment
) {
546 const intptr_t dlloff
= _dyld_get_image_vmaddr_slide(current_image
);
547 const SegmentCommand
* sc
= (const SegmentCommand
*)lc
;
548 if (start
) *start
= sc
->vmaddr
+ dlloff
;
549 if (end
) *end
= sc
->vmaddr
+ sc
->vmsize
+ dlloff
;
550 if (flags
) *flags
= kDefaultPerms
; // can we do better?
551 if (offset
) *offset
= sc
->fileoff
;
552 if (inode
) *inode
= 0;
554 *filename
= const_cast<char*>(_dyld_get_image_name(current_image
));
555 if (file_mapping
) *file_mapping
= 0;
556 if (file_pages
) *file_pages
= 0; // could we use sc->filesize?
557 if (anon_mapping
) *anon_mapping
= 0;
558 if (anon_pages
) *anon_pages
= 0;
567 // Finds |c| in |text|, and assign '\0' at the found position.
568 // The original character at the modified position should be |c|.
569 // A pointer to the modified position is stored in |endptr|.
570 // |endptr| should not be NULL.
571 static bool ExtractUntilChar(char *text
, int c
, char **endptr
) {
572 CHECK_NE(text
, NULL
);
573 CHECK_NE(endptr
, NULL
);
575 found
= strchr(text
, c
);
586 // Increments |*text_pointer| while it points a whitespace character.
587 // It is to follow sscanf's whilespace handling.
588 static void SkipWhileWhitespace(char **text_pointer
, int c
) {
590 while (isspace(**text_pointer
) && isspace(*((*text_pointer
) + 1))) {
597 static T
StringToInteger(char *text
, char **endptr
, int base
) {
603 int StringToInteger
<int>(char *text
, char **endptr
, int base
) {
604 return strtol(text
, endptr
, base
);
608 int64 StringToInteger
<int64
>(char *text
, char **endptr
, int base
) {
609 return strtoll(text
, endptr
, base
);
613 uint64 StringToInteger
<uint64
>(char *text
, char **endptr
, int base
) {
614 return strtoull(text
, endptr
, base
);
618 static T
StringToIntegerUntilChar(
619 char *text
, int base
, int c
, char **endptr_result
) {
620 CHECK_NE(endptr_result
, NULL
);
621 *endptr_result
= NULL
;
623 char *endptr_extract
;
624 if (!ExtractUntilChar(text
, c
, &endptr_extract
))
629 result
= StringToInteger
<T
>(text
, &endptr_strto
, base
);
632 if (endptr_extract
!= endptr_strto
)
635 *endptr_result
= endptr_extract
;
636 SkipWhileWhitespace(endptr_result
, c
);
641 static char *CopyStringUntilChar(
642 char *text
, unsigned out_len
, int c
, char *out
) {
644 if (!ExtractUntilChar(text
, c
, &endptr
))
647 strncpy(out
, text
, out_len
);
648 out
[out_len
-1] = '\0';
651 SkipWhileWhitespace(&endptr
, c
);
656 static bool StringToIntegerUntilCharWithCheck(
657 T
*outptr
, char *text
, int base
, int c
, char **endptr
) {
658 *outptr
= StringToIntegerUntilChar
<T
>(*endptr
, base
, c
, endptr
);
659 if (*endptr
== NULL
|| **endptr
== '\0') return false;
664 static bool ParseProcMapsLine(char *text
, uint64
*start
, uint64
*end
,
665 char *flags
, uint64
*offset
,
666 int *major
, int *minor
, int64
*inode
,
667 unsigned *filename_offset
) {
668 #if defined(__linux__)
671 * sscanf(text, "%"SCNx64"-%"SCNx64" %4s %"SCNx64" %x:%x %"SCNd64" %n",
672 * start, end, flags, offset, major, minor, inode, filename_offset)
675 if (endptr
== NULL
|| *endptr
== '\0') return false;
677 if (!StringToIntegerUntilCharWithCheck(start
, endptr
, 16, '-', &endptr
))
680 if (!StringToIntegerUntilCharWithCheck(end
, endptr
, 16, ' ', &endptr
))
683 endptr
= CopyStringUntilChar(endptr
, 5, ' ', flags
);
684 if (endptr
== NULL
|| *endptr
== '\0') return false;
687 if (!StringToIntegerUntilCharWithCheck(offset
, endptr
, 16, ' ', &endptr
))
690 if (!StringToIntegerUntilCharWithCheck(major
, endptr
, 16, ':', &endptr
))
693 if (!StringToIntegerUntilCharWithCheck(minor
, endptr
, 16, ' ', &endptr
))
696 if (!StringToIntegerUntilCharWithCheck(inode
, endptr
, 10, ' ', &endptr
))
699 *filename_offset
= (endptr
- text
);
706 ProcMapsIterator::ProcMapsIterator(pid_t pid
) {
707 Init(pid
, NULL
, false);
710 ProcMapsIterator::ProcMapsIterator(pid_t pid
, Buffer
*buffer
) {
711 Init(pid
, buffer
, false);
714 ProcMapsIterator::ProcMapsIterator(pid_t pid
, Buffer
*buffer
,
715 bool use_maps_backing
) {
716 Init(pid
, buffer
, use_maps_backing
);
719 void ProcMapsIterator::Init(pid_t pid
, Buffer
*buffer
,
720 bool use_maps_backing
) {
722 using_maps_backing_
= use_maps_backing
;
723 dynamic_buffer_
= NULL
;
725 // If the user didn't pass in any buffer storage, allocate it
726 // now. This is the normal case; the signal handler passes in a
728 buffer
= dynamic_buffer_
= new Buffer
;
730 dynamic_buffer_
= NULL
;
733 ibuf_
= buffer
->buf_
;
735 stext_
= etext_
= nextline_
= ibuf_
;
736 ebuf_
= ibuf_
+ Buffer::kBufSize
- 1;
739 #if defined(__linux__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
740 if (use_maps_backing
) { // don't bother with clever "self" stuff in this case
741 ConstructFilename("/proc/%d/maps_backing", pid
, ibuf_
, Buffer::kBufSize
);
742 } else if (pid
== 0) {
743 // We have to kludge a bit to deal with the args ConstructFilename
744 // expects. The 1 is never used -- it's only impt. that it's not 0.
745 ConstructFilename("/proc/self/maps", 1, ibuf_
, Buffer::kBufSize
);
747 ConstructFilename("/proc/%d/maps", pid
, ibuf_
, Buffer::kBufSize
);
749 // No error logging since this can be called from the crash dump
750 // handler at awkward moments. Users should call Valid() before
752 NO_INTR(fd_
= open(ibuf_
, O_RDONLY
));
753 #elif defined(__FreeBSD__)
754 // We don't support maps_backing on freebsd
756 ConstructFilename("/proc/curproc/map", 1, ibuf_
, Buffer::kBufSize
);
758 ConstructFilename("/proc/%d/map", pid
, ibuf_
, Buffer::kBufSize
);
760 NO_INTR(fd_
= open(ibuf_
, O_RDONLY
));
761 #elif defined(__sun__)
763 ConstructFilename("/proc/self/map", 1, ibuf_
, Buffer::kBufSize
);
765 ConstructFilename("/proc/%d/map", pid
, ibuf_
, Buffer::kBufSize
);
767 NO_INTR(fd_
= open(ibuf_
, O_RDONLY
));
768 #elif defined(__MACH__)
769 current_image_
= _dyld_image_count(); // count down from the top
770 current_load_cmd_
= -1;
771 #elif defined(PLATFORM_WINDOWS)
772 snapshot_
= CreateToolhelp32Snapshot(TH32CS_SNAPMODULE
|
774 GetCurrentProcessId());
775 memset(&module_
, 0, sizeof(module_
));
777 fd_
= -1; // so Valid() is always false
782 ProcMapsIterator::~ProcMapsIterator() {
783 #if defined(PLATFORM_WINDOWS)
784 if (snapshot_
!= INVALID_HANDLE_VALUE
) CloseHandle(snapshot_
);
785 #elif defined(__MACH__)
786 // no cleanup necessary!
788 if (fd_
>= 0) NO_INTR(close(fd_
));
790 delete dynamic_buffer_
;
793 bool ProcMapsIterator::Valid() const {
794 #if defined(PLATFORM_WINDOWS)
795 return snapshot_
!= INVALID_HANDLE_VALUE
;
796 #elif defined(__MACH__)
803 bool ProcMapsIterator::Next(uint64
*start
, uint64
*end
, char **flags
,
804 uint64
*offset
, int64
*inode
, char **filename
) {
805 return NextExt(start
, end
, flags
, offset
, inode
, filename
, NULL
, NULL
,
809 // This has too many arguments. It should really be building
810 // a map object and returning it. The problem is that this is called
811 // when the memory allocator state is undefined, hence the arguments.
812 bool ProcMapsIterator::NextExt(uint64
*start
, uint64
*end
, char **flags
,
813 uint64
*offset
, int64
*inode
, char **filename
,
814 uint64
*file_mapping
, uint64
*file_pages
,
815 uint64
*anon_mapping
, uint64
*anon_pages
,
818 #if defined(__linux__) || defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__CYGWIN32__)
820 // Advance to the start of the next line
823 // See if we have a complete line in the buffer already
824 nextline_
= static_cast<char *>(memchr (stext_
, '\n', etext_
- stext_
));
826 // Shift/fill the buffer so we do have a line
827 int count
= etext_
- stext_
;
829 // Move the current text to the start of the buffer
830 memmove(ibuf_
, stext_
, count
);
832 etext_
= ibuf_
+ count
;
834 int nread
= 0; // fill up buffer with text
835 while (etext_
< ebuf_
) {
836 NO_INTR(nread
= read(fd_
, etext_
, ebuf_
- etext_
));
843 // Zero out remaining characters in buffer at EOF to avoid returning
844 // garbage from subsequent calls.
845 if (etext_
!= ebuf_
&& nread
== 0) {
846 memset(etext_
, 0, ebuf_
- etext_
);
848 *etext_
= '\n'; // sentinel; safe because ibuf extends 1 char beyond ebuf
849 nextline_
= static_cast<char *>(memchr (stext_
, '\n', etext_
+ 1 - stext_
));
851 *nextline_
= 0; // turn newline into nul
852 nextline_
+= ((nextline_
< etext_
)? 1 : 0); // skip nul if not end of text
853 // stext_ now points at a nul-terminated line
854 uint64 tmpstart
, tmpend
, tmpoffset
;
857 unsigned filename_offset
= 0;
858 #if defined(__linux__)
859 // for now, assume all linuxes have the same format
860 if (!ParseProcMapsLine(
862 start
? start
: &tmpstart
,
865 offset
? offset
: &tmpoffset
,
867 inode
? inode
: &tmpinode
, &filename_offset
)) continue;
868 #elif defined(__CYGWIN__) || defined(__CYGWIN32__)
869 // cygwin is like linux, except the third field is the "entry point"
870 // rather than the offset (see format_process_maps at
871 // http://cygwin.com/cgi-bin/cvsweb.cgi/src/winsup/cygwin/fhandler_process.cc?rev=1.89&content-type=text/x-cvsweb-markup&cvsroot=src
872 // Offset is always be 0 on cygwin: cygwin implements an mmap
873 // by loading the whole file and then calling NtMapViewOfSection.
874 // Cygwin also seems to set its flags kinda randomly; use windows default.
878 strcpy(flags_
, "r-xp");
879 if (sscanf(stext_
, "%llx-%llx %4s %llx %x:%x %lld %n",
880 start
? start
: &tmpstart
,
885 inode
? inode
: &tmpinode
, &filename_offset
) != 7) continue;
886 #elif defined(__FreeBSD__)
887 // 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
888 tmpstart
= tmpend
= tmpoffset
= 0;
890 major
= minor
= 0; // can't get this info in freebsd
892 *inode
= 0; // nor this
894 *offset
= 0; // seems like this should be in there, but maybe not
895 // start end resident privateresident obj(?) prot refcnt shadowcnt
896 // flags copy_on_write needs_copy type filename:
897 // 0x8048000 0x804a000 2 0 0xc104ce70 r-x 1 0 0x0 COW NC vnode /bin/cat
898 if (sscanf(stext_
, "0x%"SCNx64
" 0x%"SCNx64
" %*d %*d %*p %3s %*d %*d 0x%*x %*s %*s %*s %n",
899 start
? start
: &tmpstart
,
902 &filename_offset
) != 3) continue;
905 // Depending on the Linux kernel being used, there may or may not be a space
906 // after the inode if there is no filename. sscanf will in such situations
907 // nondeterministically either fill in filename_offset or not (the results
908 // differ on multiple calls in the same run even with identical arguments).
909 // We don't want to wander off somewhere beyond the end of the string.
910 size_t stext_length
= strlen(stext_
);
911 if (filename_offset
== 0 || filename_offset
> stext_length
)
912 filename_offset
= stext_length
;
915 if (flags
) *flags
= flags_
;
916 if (filename
) *filename
= stext_
+ filename_offset
;
917 if (dev
) *dev
= minor
| (major
<< 8);
919 if (using_maps_backing_
) {
920 // Extract and parse physical page backing info.
921 char *backing_ptr
= stext_
+ filename_offset
+
922 strlen(stext_
+filename_offset
);
924 // find the second '('
926 while (--backing_ptr
> stext_
) {
927 if (*backing_ptr
== '(') {
929 if (paren_count
>= 2) {
930 uint64 tmp_file_mapping
;
931 uint64 tmp_file_pages
;
932 uint64 tmp_anon_mapping
;
933 uint64 tmp_anon_pages
;
935 sscanf(backing_ptr
+1, "F %"SCNx64
" %"SCNd64
") (A %"SCNx64
" %"SCNd64
")",
936 file_mapping
? file_mapping
: &tmp_file_mapping
,
937 file_pages
? file_pages
: &tmp_file_pages
,
938 anon_mapping
? anon_mapping
: &tmp_anon_mapping
,
939 anon_pages
? anon_pages
: &tmp_anon_pages
);
940 // null terminate the file name (there is a space
941 // before the first (.
950 } while (etext_
> ibuf_
);
951 #elif defined(__sun__)
952 // This is based on MA_READ == 4, MA_WRITE == 2, MA_EXEC == 1
953 static char kPerms
[8][4] = { "---", "--x", "-w-", "-wx",
954 "r--", "r-x", "rw-", "rwx" };
955 COMPILE_ASSERT(MA_READ
== 4, solaris_ma_read_must_equal_4
);
956 COMPILE_ASSERT(MA_WRITE
== 2, solaris_ma_write_must_equal_2
);
957 COMPILE_ASSERT(MA_EXEC
== 1, solaris_ma_exec_must_equal_1
);
959 int nread
= 0; // fill up buffer with text
960 NO_INTR(nread
= read(fd_
, ibuf_
, sizeof(prmap_t
)));
961 if (nread
== sizeof(prmap_t
)) {
962 long inode_from_mapname
= 0;
963 prmap_t
* mapinfo
= reinterpret_cast<prmap_t
*>(ibuf_
);
964 // Best-effort attempt to get the inode from the filename. I think the
965 // two middle ints are major and minor device numbers, but I'm not sure.
966 sscanf(mapinfo
->pr_mapname
, "ufs.%*d.%*d.%ld", &inode_from_mapname
);
969 CHECK_LT(snprintf(object_path
.buf_
, Buffer::kBufSize
,
970 "/proc/self/path/%s", mapinfo
->pr_mapname
),
973 CHECK_LT(snprintf(object_path
.buf_
, Buffer::kBufSize
,
975 static_cast<int>(pid_
), mapinfo
->pr_mapname
),
978 ssize_t len
= readlink(object_path
.buf_
, current_filename_
, PATH_MAX
);
979 CHECK_LT(len
, PATH_MAX
);
982 current_filename_
[len
] = '\0';
984 if (start
) *start
= mapinfo
->pr_vaddr
;
985 if (end
) *end
= mapinfo
->pr_vaddr
+ mapinfo
->pr_size
;
986 if (flags
) *flags
= kPerms
[mapinfo
->pr_mflags
& 7];
987 if (offset
) *offset
= mapinfo
->pr_offset
;
988 if (inode
) *inode
= inode_from_mapname
;
989 if (filename
) *filename
= current_filename_
;
990 if (file_mapping
) *file_mapping
= 0;
991 if (file_pages
) *file_pages
= 0;
992 if (anon_mapping
) *anon_mapping
= 0;
993 if (anon_pages
) *anon_pages
= 0;
997 #elif defined(__MACH__)
998 // We return a separate entry for each segment in the DLL. (TODO(csilvers):
999 // can we do better?) A DLL ("image") has load-commands, some of which
1000 // talk about segment boundaries.
1001 // cf image_for_address from http://svn.digium.com/view/asterisk/team/oej/minivoicemail/dlfcn.c?revision=53912
1002 for (; current_image_
>= 0; current_image_
--) {
1003 const mach_header
* hdr
= _dyld_get_image_header(current_image_
);
1005 if (current_load_cmd_
< 0) // set up for this image
1006 current_load_cmd_
= hdr
->ncmds
; // again, go from the top down
1008 // We start with the next load command (we've already looked at this one).
1009 for (current_load_cmd_
--; current_load_cmd_
>= 0; current_load_cmd_
--) {
1011 if (NextExtMachHelper
<MH_MAGIC_64
, LC_SEGMENT_64
,
1012 struct mach_header_64
, struct segment_command_64
>(
1013 hdr
, current_image_
, current_load_cmd_
,
1014 start
, end
, flags
, offset
, inode
, filename
,
1015 file_mapping
, file_pages
, anon_mapping
,
1020 if (NextExtMachHelper
<MH_MAGIC
, LC_SEGMENT
,
1021 struct mach_header
, struct segment_command
>(
1022 hdr
, current_image_
, current_load_cmd_
,
1023 start
, end
, flags
, offset
, inode
, filename
,
1024 file_mapping
, file_pages
, anon_mapping
,
1029 // If we get here, no more load_cmd's in this image talk about
1030 // segments. Go on to the next image.
1032 #elif defined(PLATFORM_WINDOWS)
1033 static char kDefaultPerms
[5] = "r-xp";
1035 if (module_
.dwSize
== 0) { // only possible before first call
1036 module_
.dwSize
= sizeof(module_
);
1037 ok
= Module32First(snapshot_
, &module_
);
1039 ok
= Module32Next(snapshot_
, &module_
);
1042 uint64 base_addr
= reinterpret_cast<DWORD_PTR
>(module_
.modBaseAddr
);
1043 if (start
) *start
= base_addr
;
1044 if (end
) *end
= base_addr
+ module_
.modBaseSize
;
1045 if (flags
) *flags
= kDefaultPerms
;
1046 if (offset
) *offset
= 0;
1047 if (inode
) *inode
= 0;
1048 if (filename
) *filename
= module_
.szExePath
;
1049 if (file_mapping
) *file_mapping
= 0;
1050 if (file_pages
) *file_pages
= 0;
1051 if (anon_mapping
) *anon_mapping
= 0;
1052 if (anon_pages
) *anon_pages
= 0;
1058 // We didn't find anything
1062 int ProcMapsIterator::FormatLine(char* buffer
, int bufsize
,
1063 uint64 start
, uint64 end
, const char *flags
,
1064 uint64 offset
, int64 inode
,
1065 const char *filename
, dev_t dev
) {
1066 // We assume 'flags' looks like 'rwxp' or 'rwx'.
1067 char r
= (flags
&& flags
[0] == 'r') ? 'r' : '-';
1068 char w
= (flags
&& flags
[0] && flags
[1] == 'w') ? 'w' : '-';
1069 char x
= (flags
&& flags
[0] && flags
[1] && flags
[2] == 'x') ? 'x' : '-';
1070 // p always seems set on linux, so we set the default to 'p', not '-'
1071 char p
= (flags
&& flags
[0] && flags
[1] && flags
[2] && flags
[3] != 'p')
1074 const int rc
= snprintf(buffer
, bufsize
,
1075 "%08"PRIx64
"-%08"PRIx64
" %c%c%c%c %08"PRIx64
" %02x:%02x %-11"PRId64
" %s\n",
1076 start
, end
, r
,w
,x
,p
, offset
,
1077 static_cast<int>(dev
/256), static_cast<int>(dev
%256),
1079 return (rc
< 0 || rc
>= bufsize
) ? 0 : rc
;
1082 namespace tcmalloc
{
1084 // Helper to add the list of mapped shared libraries to a profile.
1085 // Fill formatted "/proc/self/maps" contents into buffer 'buf' of size 'size'
1086 // and return the actual size occupied in 'buf'. We fill wrote_all to true
1087 // if we successfully wrote all proc lines to buf, false else.
1088 // We do not provision for 0-terminating 'buf'.
1089 int FillProcSelfMaps(char buf
[], int size
, bool* wrote_all
) {
1090 ProcMapsIterator::Buffer iterbuf
;
1091 ProcMapsIterator
it(0, &iterbuf
); // 0 means "current pid"
1093 uint64 start
, end
, offset
;
1095 char *flags
, *filename
;
1096 int bytes_written
= 0;
1098 while (it
.Next(&start
, &end
, &flags
, &offset
, &inode
, &filename
)) {
1099 const int line_length
= it
.FormatLine(buf
+ bytes_written
,
1100 size
- bytes_written
,
1101 start
, end
, flags
, offset
,
1102 inode
, filename
, 0);
1103 if (line_length
== 0)
1104 *wrote_all
= false; // failed to write this line out
1106 bytes_written
+= line_length
;
1109 return bytes_written
;
1112 // Dump the same data as FillProcSelfMaps reads to fd.
1113 // It seems easier to repeat parts of FillProcSelfMaps here than to
1114 // reuse it via a call.
1115 void DumpProcSelfMaps(RawFD fd
) {
1116 ProcMapsIterator::Buffer iterbuf
;
1117 ProcMapsIterator
it(0, &iterbuf
); // 0 means "current pid"
1119 uint64 start
, end
, offset
;
1121 char *flags
, *filename
;
1122 ProcMapsIterator::Buffer linebuf
;
1123 while (it
.Next(&start
, &end
, &flags
, &offset
, &inode
, &filename
)) {
1124 int written
= it
.FormatLine(linebuf
.buf_
, sizeof(linebuf
.buf_
),
1125 start
, end
, flags
, offset
, inode
, filename
,
1127 RawWrite(fd
, linebuf
.buf_
, written
);
1131 } // namespace tcmalloc