blob: cc5cb7485eca155b5dbb0cb4e8891617e538db8e [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// All functions here are thread-hostile due to file caching unless
32// commented otherwise.
33
34#ifndef _SYSINFO_H_
35#define _SYSINFO_H_
36
37#include <config.h>
38
39#include <time.h>
40#if (defined(_WIN32) || defined(__MINGW32__)) && (!defined(__CYGWIN__) && !defined(__CYGWIN32__))
41#include <windows.h> // for DWORD
42#include <tlhelp32.h> // for CreateToolhelp32Snapshot
43#endif
44#ifdef HAVE_UNISTD_H
45#include <unistd.h> // for pid_t
46#endif
47#include <stddef.h> // for size_t
48#include <limits.h> // for PATH_MAX
49#include "base/basictypes.h"
50#include "base/logging.h" // for RawFD
51
52// This getenv function is safe to call before the C runtime is initialized.
53// On Windows, it utilizes GetEnvironmentVariable() and on unix it uses
54// /proc/self/environ instead calling getenv(). It's intended to be used in
55// routines that run before main(), when the state required for getenv() may
56// not be set up yet. In particular, errno isn't set up until relatively late
57// (after the pthreads library has a chance to make it threadsafe), and
58// getenv() doesn't work until then.
59// On some platforms, this call will utilize the same, static buffer for
60// repeated GetenvBeforeMain() calls. Callers should not expect pointers from
61// this routine to be long lived.
62// Note that on unix, /proc only has the environment at the time the
63// application was started, so this routine ignores setenv() calls/etc. Also
64// note it only reads the first 16K of the environment.
65extern const char* GetenvBeforeMain(const char* name);
66
67// This takes as an argument an environment-variable name (like
68// CPUPROFILE) whose value is supposed to be a file-path, and sets
69// path to that path, and returns true. Non-trivial for surprising
70// reasons, as documented in sysinfo.cc. path must have space PATH_MAX.
71extern bool GetUniquePathFromEnv(const char* env_name, char* path);
72
73extern int NumCPUs();
74
75void SleepForMilliseconds(int milliseconds);
76
77// processor cycles per second of each processor. Thread-safe.
78extern double CyclesPerSecond(void);
79
80
81// Return true if we're running POSIX (e.g., NPTL on Linux) threads,
82// as opposed to a non-POSIX thread library. The thing that we care
83// about is whether a thread's pid is the same as the thread that
84// spawned it. If so, this function returns true.
85// Thread-safe.
86// Note: We consider false negatives to be OK.
87bool HasPosixThreads();
88
89#ifndef SWIG // SWIG doesn't like struct Buffer and variable arguments.
90
91// A ProcMapsIterator abstracts access to /proc/maps for a given
92// process. Needs to be stack-allocatable and avoid using stdio/malloc
93// so it can be used in the google stack dumper, heap-profiler, etc.
94//
95// On Windows and Mac OS X, this iterator iterates *only* over DLLs
96// mapped into this process space. For Linux, FreeBSD, and Solaris,
97// it iterates over *all* mapped memory regions, including anonymous
98// mmaps. For other O/Ss, it is unlikely to work at all, and Valid()
99// will always return false. Also note: this routine only works on
100// FreeBSD if procfs is mounted: make sure this is in your /etc/fstab:
101// proc /proc procfs rw 0 0
102class ProcMapsIterator {
103 public:
104 struct Buffer {
105#ifdef __FreeBSD__
106 // FreeBSD requires us to read all of the maps file at once, so
107 // we have to make a buffer that's "always" big enough
108 static const size_t kBufSize = 102400;
109#else // a one-line buffer is good enough
110 static const size_t kBufSize = PATH_MAX + 1024;
111#endif
112 char buf_[kBufSize];
113 };
114
115
116 // Create a new iterator for the specified pid. pid can be 0 for "self".
117 explicit ProcMapsIterator(pid_t pid);
118
119 // Create an iterator with specified storage (for use in signal
120 // handler). "buffer" should point to a ProcMapsIterator::Buffer
121 // buffer can be NULL in which case a bufer will be allocated.
122 ProcMapsIterator(pid_t pid, Buffer *buffer);
123
124 // Iterate through maps_backing instead of maps if use_maps_backing
125 // is true. Otherwise the same as above. buffer can be NULL and
126 // it will allocate a buffer itself.
127 ProcMapsIterator(pid_t pid, Buffer *buffer,
128 bool use_maps_backing);
129
130 // Returns true if the iterator successfully initialized;
131 bool Valid() const;
132
133 // Returns a pointer to the most recently parsed line. Only valid
134 // after Next() returns true, and until the iterator is destroyed or
135 // Next() is called again. This may give strange results on non-Linux
136 // systems. Prefer FormatLine() if that may be a concern.
137 const char *CurrentLine() const { return stext_; }
138
139 // Writes the "canonical" form of the /proc/xxx/maps info for a single
140 // line to the passed-in buffer. Returns the number of bytes written,
141 // or 0 if it was not able to write the complete line. (To guarantee
142 // success, buffer should have size at least Buffer::kBufSize.)
143 // Takes as arguments values set via a call to Next(). The
144 // "canonical" form of the line (taken from linux's /proc/xxx/maps):
145 // <start_addr(hex)>-<end_addr(hex)> <perms(rwxp)> <offset(hex)> +
146 // <major_dev(hex)>:<minor_dev(hex)> <inode> <filename> Note: the
147 // eg
148 // 08048000-0804c000 r-xp 00000000 03:01 3793678 /bin/cat
149 // If you don't have the dev_t (dev), feel free to pass in 0.
150 // (Next() doesn't return a dev_t, though NextExt does.)
151 //
152 // Note: if filename and flags were obtained via a call to Next(),
153 // then the output of this function is only valid if Next() returned
154 // true, and only until the iterator is destroyed or Next() is
155 // called again. (Since filename, at least, points into CurrentLine.)
156 static int FormatLine(char* buffer, int bufsize,
157 uint64 start, uint64 end, const char *flags,
158 uint64 offset, int64 inode, const char *filename,
159 dev_t dev);
160
161 // Find the next entry in /proc/maps; return true if found or false
162 // if at the end of the file.
163 //
164 // Any of the result pointers can be NULL if you're not interested
165 // in those values.
166 //
167 // If "flags" and "filename" are passed, they end up pointing to
168 // storage within the ProcMapsIterator that is valid only until the
169 // iterator is destroyed or Next() is called again. The caller may
170 // modify the contents of these strings (up as far as the first NUL,
171 // and only until the subsequent call to Next()) if desired.
172
173 // The offsets are all uint64 in order to handle the case of a
174 // 32-bit process running on a 64-bit kernel
175 //
176 // IMPORTANT NOTE: see top-of-class notes for details about what
177 // mapped regions Next() iterates over, depending on O/S.
178 // TODO(csilvers): make flags and filename const.
179 bool Next(uint64 *start, uint64 *end, char **flags,
180 uint64 *offset, int64 *inode, char **filename);
181
182 bool NextExt(uint64 *start, uint64 *end, char **flags,
183 uint64 *offset, int64 *inode, char **filename,
184 uint64 *file_mapping, uint64 *file_pages,
185 uint64 *anon_mapping, uint64 *anon_pages,
186 dev_t *dev);
187
188 ~ProcMapsIterator();
189
190 private:
191 void Init(pid_t pid, Buffer *buffer, bool use_maps_backing);
192
193 char *ibuf_; // input buffer
194 char *stext_; // start of text
195 char *etext_; // end of text
196 char *nextline_; // start of next line
197 char *ebuf_; // end of buffer (1 char for a nul)
198#if (defined(_WIN32) || defined(__MINGW32__)) && (!defined(__CYGWIN__) && !defined(__CYGWIN32__))
199 HANDLE snapshot_; // filehandle on dll info
200 // In a change from the usual W-A pattern, there is no A variant of
201 // MODULEENTRY32. Tlhelp32.h #defines the W variant, but not the A.
202 // We want the original A variants, and this #undef is the only
203 // way I see to get them. Redefining it when we're done prevents us
204 // from affecting other .cc files.
205# ifdef MODULEENTRY32 // Alias of W
206# undef MODULEENTRY32
207 MODULEENTRY32 module_; // info about current dll (and dll iterator)
208# define MODULEENTRY32 MODULEENTRY32W
209# else // It's the ascii, the one we want.
210 MODULEENTRY32 module_; // info about current dll (and dll iterator)
211# endif
212#elif defined(__MACH__)
213 int current_image_; // dll's are called "images" in macos parlance
214 int current_load_cmd_; // the segment of this dll we're examining
215#elif defined(__sun__) // Solaris
216 int fd_;
217 char current_filename_[PATH_MAX];
218#else
219 int fd_; // filehandle on /proc/*/maps
220#endif
221 pid_t pid_;
222 char flags_[10];
223 Buffer* dynamic_buffer_; // dynamically-allocated Buffer
224 bool using_maps_backing_; // true if we are looking at maps_backing instead of maps.
225};
226
227#endif /* #ifndef SWIG */
228
229// Helper routines
230
231namespace tcmalloc {
232int FillProcSelfMaps(char buf[], int size, bool* wrote_all);
233void DumpProcSelfMaps(RawFD fd);
234}
235
236#endif /* #ifndef _SYSINFO_H_ */