blob: 14f0db5e2909314a7d95ef50093a06a061073463 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000028// Platform specific code for Linux goes here. For the POSIX comaptible parts
29// the implementation is in platform-posix.cc.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000030
31#include <pthread.h>
32#include <semaphore.h>
33#include <signal.h>
lrn@chromium.org5d00b602011-01-05 09:51:43 +000034#include <sys/prctl.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include <sys/time.h>
36#include <sys/resource.h>
lrn@chromium.org303ada72010-10-27 09:33:13 +000037#include <sys/syscall.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000038#include <sys/types.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000039#include <stdlib.h>
40
41// Ubuntu Dapper requires memory pages to be marked as
42// executable. Otherwise, OS raises an exception when executing code
43// in that page.
44#include <sys/types.h> // mmap & munmap
ager@chromium.org236ad962008-09-25 09:45:57 +000045#include <sys/mman.h> // mmap & munmap
46#include <sys/stat.h> // open
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000047#include <fcntl.h> // open
48#include <unistd.h> // sysconf
49#ifdef __GLIBC__
ager@chromium.org236ad962008-09-25 09:45:57 +000050#include <execinfo.h> // backtrace, backtrace_symbols
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000051#endif // def __GLIBC__
ager@chromium.org236ad962008-09-25 09:45:57 +000052#include <strings.h> // index
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000053#include <errno.h>
54#include <stdarg.h>
55
56#undef MAP_TYPE
57
58#include "v8.h"
59
60#include "platform.h"
ager@chromium.orga1645e22009-09-09 19:27:10 +000061#include "v8threads.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000062#include "vm-state-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063
64
kasperl@chromium.org71affb52009-05-26 05:44:31 +000065namespace v8 {
66namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067
68// 0 is never a valid thread id on Linux since tids and pids share a
69// name space and pid 0 is reserved (see man 2 kill).
70static const pthread_t kNoThread = (pthread_t) 0;
71
72
73double ceiling(double x) {
74 return ceil(x);
75}
76
77
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000078static Mutex* limit_mutex = NULL;
79
80
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081void OS::Setup() {
82 // Seed the random number generator.
ager@chromium.org9258b6b2008-09-11 09:11:10 +000083 // Convert the current time to a 64-bit integer first, before converting it
84 // to an unsigned. Going directly can cause an overflow and the seed to be
85 // set to all ones. The seed will be identical for different instances that
86 // call this setup code within the same millisecond.
87 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
88 srandom(static_cast<unsigned int>(seed));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000089 limit_mutex = CreateMutex();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000090}
91
92
ager@chromium.orgc4c92722009-11-18 14:12:51 +000093uint64_t OS::CpuFeaturesImpliedByPlatform() {
94#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
95 // Here gcc is telling us that we are on an ARM and gcc is assuming that we
96 // have VFP3 instructions. If gcc can assume it then so can we.
97 return 1u << VFP3;
ager@chromium.org5c838252010-02-19 08:53:10 +000098#elif CAN_USE_ARMV7_INSTRUCTIONS
99 return 1u << ARMv7;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000100#else
101 return 0; // Linux runs on anything.
102#endif
103}
104
105
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000106#ifdef __arm__
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000107static bool CPUInfoContainsString(const char * search_string) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000108 const char* file_name = "/proc/cpuinfo";
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000109 // This is written as a straight shot one pass parser
110 // and not using STL string and ifstream because,
111 // on Linux, it's reading from a (non-mmap-able)
112 // character special device.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000113 FILE* f = NULL;
114 const char* what = search_string;
115
116 if (NULL == (f = fopen(file_name, "r")))
117 return false;
118
119 int k;
120 while (EOF != (k = fgetc(f))) {
121 if (k == *what) {
122 ++what;
123 while ((*what != '\0') && (*what == fgetc(f))) {
124 ++what;
125 }
126 if (*what == '\0') {
127 fclose(f);
128 return true;
129 } else {
130 what = search_string;
131 }
132 }
133 }
134 fclose(f);
135
136 // Did not find string in the proc file.
137 return false;
138}
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000139
140bool OS::ArmCpuHasFeature(CpuFeature feature) {
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000141 const char* search_string = NULL;
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000142 // Simple detection of VFP at runtime for Linux.
143 // It is based on /proc/cpuinfo, which reveals hardware configuration
144 // to user-space applications. According to ARM (mid 2009), no similar
145 // facility is universally available on the ARM architectures,
146 // so it's up to individual OSes to provide such.
147 switch (feature) {
148 case VFP3:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000149 search_string = "vfpv3";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000150 break;
151 case ARMv7:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000152 search_string = "ARMv7";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000153 break;
154 default:
155 UNREACHABLE();
156 }
157
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000158 if (CPUInfoContainsString(search_string)) {
159 return true;
160 }
161
162 if (feature == VFP3) {
163 // Some old kernels will report vfp not vfpv3. Here we make a last attempt
164 // to detect vfpv3 by checking for vfp *and* neon, since neon is only
165 // available on architectures with vfpv3.
166 // Checking neon on its own is not enough as it is possible to have neon
167 // without vfp.
168 if (CPUInfoContainsString("vfp") && CPUInfoContainsString("neon")) {
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000169 return true;
170 }
171 }
172
173 return false;
174}
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000175#endif // def __arm__
176
177
ager@chromium.org236ad962008-09-25 09:45:57 +0000178int OS::ActivationFrameAlignment() {
ager@chromium.orge2902be2009-06-08 12:21:35 +0000179#ifdef V8_TARGET_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000180 // On EABI ARM targets this is required for fp correctness in the
181 // runtime system.
ager@chromium.org3a6061e2009-03-12 14:24:36 +0000182 return 8;
ager@chromium.org5c838252010-02-19 08:53:10 +0000183#elif V8_TARGET_ARCH_MIPS
184 return 8;
185#endif
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000186 // With gcc 4.4 the tree vectorization optimizer can generate code
ager@chromium.orge2902be2009-06-08 12:21:35 +0000187 // that requires 16 byte alignment such as movdqa on x86.
188 return 16;
ager@chromium.org236ad962008-09-25 09:45:57 +0000189}
190
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000191
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000192void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
ricow@chromium.org30ce4112010-05-31 10:38:25 +0000193#if defined(V8_TARGET_ARCH_ARM) && defined(__arm__)
194 // Only use on ARM hardware.
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000195 MemoryBarrier();
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000196#else
197 __asm__ __volatile__("" : : : "memory");
198 // An x86 store acts as a release barrier.
199#endif
200 *ptr = value;
201}
202
203
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000204const char* OS::LocalTimezone(double time) {
205 if (isnan(time)) return "";
206 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
207 struct tm* t = localtime(&tv);
208 if (NULL == t) return "";
209 return t->tm_zone;
210}
211
212
213double OS::LocalTimeOffset() {
214 time_t tv = time(NULL);
215 struct tm* t = localtime(&tv);
216 // tm_gmtoff includes any daylight savings offset, so subtract it.
217 return static_cast<double>(t->tm_gmtoff * msPerSecond -
218 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
219}
220
221
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000222// We keep the lowest and highest addresses mapped as a quick way of
223// determining that pointers are outside the heap (used mostly in assertions
224// and verification). The estimate is conservative, ie, not all addresses in
225// 'allocated' space are actually allocated to our heap. The range is
226// [lowest, highest), inclusive on the low and and exclusive on the high end.
227static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
228static void* highest_ever_allocated = reinterpret_cast<void*>(0);
229
230
231static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000232 ASSERT(limit_mutex != NULL);
233 ScopedLock lock(limit_mutex);
234
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000235 lowest_ever_allocated = Min(lowest_ever_allocated, address);
236 highest_ever_allocated =
237 Max(highest_ever_allocated,
238 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
239}
240
241
242bool OS::IsOutsideAllocatedSpace(void* address) {
243 return address < lowest_ever_allocated || address >= highest_ever_allocated;
244}
245
246
247size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000248 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000249}
250
251
kasper.lund7276f142008-07-30 08:49:36 +0000252void* OS::Allocate(const size_t requested,
253 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000254 bool is_executable) {
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000255 // TODO(805): Port randomization of allocated executable memory to Linux.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000256 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000257 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000258 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000259 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000260 LOG(i::Isolate::Current(),
261 StringEvent("OS::Allocate", "mmap failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000262 return NULL;
263 }
264 *allocated = msize;
265 UpdateAllocatedSpaceLimits(mbase, msize);
266 return mbase;
267}
268
269
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000270void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000271 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000272 int result = munmap(address, size);
273 USE(result);
274 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000275}
276
277
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000278#ifdef ENABLE_HEAP_PROTECTION
279
280void OS::Protect(void* address, size_t size) {
281 // TODO(1240712): mprotect has a return value which is ignored here.
282 mprotect(address, size, PROT_READ);
283}
284
285
286void OS::Unprotect(void* address, size_t size, bool is_executable) {
287 // TODO(1240712): mprotect has a return value which is ignored here.
288 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
289 mprotect(address, size, prot);
290}
291
292#endif
293
294
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000295void OS::Sleep(int milliseconds) {
296 unsigned int ms = static_cast<unsigned int>(milliseconds);
297 usleep(1000 * ms);
298}
299
300
301void OS::Abort() {
302 // Redirect to std abort to signal abnormal program termination.
303 abort();
304}
305
306
kasper.lund7276f142008-07-30 08:49:36 +0000307void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000308// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
309// which is the architecture of generated code).
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000310#if (defined(__arm__) || defined(__thumb__))
311# if defined(CAN_USE_ARMV5_INSTRUCTIONS)
kasper.lund7276f142008-07-30 08:49:36 +0000312 asm("bkpt 0");
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000313# endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000314#elif defined(__mips__)
315 asm("break");
kasper.lund7276f142008-07-30 08:49:36 +0000316#else
317 asm("int $3");
318#endif
319}
320
321
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000322class PosixMemoryMappedFile : public OS::MemoryMappedFile {
323 public:
324 PosixMemoryMappedFile(FILE* file, void* memory, int size)
325 : file_(file), memory_(memory), size_(size) { }
326 virtual ~PosixMemoryMappedFile();
327 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000328 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000329 private:
330 FILE* file_;
331 void* memory_;
332 int size_;
333};
334
335
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000336OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000337 FILE* file = fopen(name, "r+");
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000338 if (file == NULL) return NULL;
339
340 fseek(file, 0, SEEK_END);
341 int size = ftell(file);
342
343 void* memory =
344 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
345 return new PosixMemoryMappedFile(file, memory, size);
346}
347
348
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000349OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
350 void* initial) {
351 FILE* file = fopen(name, "w+");
352 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000353 int result = fwrite(initial, size, 1, file);
354 if (result < 1) {
355 fclose(file);
356 return NULL;
357 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000358 void* memory =
359 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
360 return new PosixMemoryMappedFile(file, memory, size);
361}
362
363
364PosixMemoryMappedFile::~PosixMemoryMappedFile() {
365 if (memory_) munmap(memory_, size_);
366 fclose(file_);
367}
368
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000369
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000370void OS::LogSharedLibraryAddresses() {
371#ifdef ENABLE_LOGGING_AND_PROFILING
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000372 // This function assumes that the layout of the file is as follows:
373 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
374 // If we encounter an unexpected situation we abort scanning further entries.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000375 FILE* fp = fopen("/proc/self/maps", "r");
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000376 if (fp == NULL) return;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000377
378 // Allocate enough room to be able to store a full file name.
379 const int kLibNameLen = FILENAME_MAX + 1;
380 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
381
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000382 i::Isolate* isolate = ISOLATE;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000383 // This loop will terminate once the scanning hits an EOF.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000384 while (true) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000385 uintptr_t start, end;
386 char attr_r, attr_w, attr_x, attr_p;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000387 // Parse the addresses and permission bits at the beginning of the line.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000388 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
389 if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000390
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000391 int c;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000392 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
393 // Found a read-only executable entry. Skip characters until we reach
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000394 // the beginning of the filename or the end of the line.
395 do {
396 c = getc(fp);
397 } while ((c != EOF) && (c != '\n') && (c != '/'));
398 if (c == EOF) break; // EOF: Was unexpected, just exit.
399
400 // Process the filename if found.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000401 if (c == '/') {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000402 ungetc(c, fp); // Push the '/' back into the stream to be read below.
403
404 // Read to the end of the line. Exit if the read fails.
405 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
406
407 // Drop the newline character read by fgets. We do not need to check
408 // for a zero-length string because we know that we at least read the
409 // '/' character.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000410 lib_name[strlen(lib_name) - 1] = '\0';
411 } else {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000412 // No library name found, just record the raw address range.
413 snprintf(lib_name, kLibNameLen,
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000414 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
415 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000416 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000417 } else {
418 // Entry not describing executable data. Skip to end of line to setup
419 // reading the next entry.
420 do {
421 c = getc(fp);
422 } while ((c != EOF) && (c != '\n'));
423 if (c == EOF) break;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000424 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000425 }
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000426 free(lib_name);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000427 fclose(fp);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000428#endif
429}
430
431
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000432static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
433
434
435void OS::SignalCodeMovingGC() {
436#ifdef ENABLE_LOGGING_AND_PROFILING
437 // Support for ll_prof.py.
438 //
439 // The Linux profiler built into the kernel logs all mmap's with
440 // PROT_EXEC so that analysis tools can properly attribute ticks. We
441 // do a mmap with a name known by ll_prof.py and immediately munmap
442 // it. This injects a GC marker into the stream of events generated
443 // by the kernel and allows us to synchronize V8 code log and the
444 // kernel log.
445 int size = sysconf(_SC_PAGESIZE);
446 FILE* f = fopen(kGCFakeMmap, "w+");
447 void* addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE,
448 fileno(f), 0);
449 ASSERT(addr != MAP_FAILED);
450 munmap(addr, size);
451 fclose(f);
452#endif
453}
454
455
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000456int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000457 // backtrace is a glibc extension.
458#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000459 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000460 ScopedVector<void*> addresses(frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000462 int frames_count = backtrace(addresses.start(), frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000463
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000464 char** symbols = backtrace_symbols(addresses.start(), frames_count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465 if (symbols == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000466 return kStackWalkError;
467 }
468
469 for (int i = 0; i < frames_count; i++) {
470 frames[i].address = addresses[i];
471 // Format a text representation of the frame based on the information
472 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000473 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
474 "%s",
475 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000476 // Make sure line termination is in place.
477 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
478 }
479
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480 free(symbols);
481
482 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000483#else // ndef __GLIBC__
484 return 0;
485#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000486}
487
488
489// Constants used for mmap.
490static const int kMmapFd = -1;
491static const int kMmapFdOffset = 0;
492
493
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000494VirtualMemory::VirtualMemory(size_t size) {
495 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000496 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
497 kMmapFd, kMmapFdOffset);
498 size_ = size;
499}
500
501
502VirtualMemory::~VirtualMemory() {
503 if (IsReserved()) {
504 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
505 }
506}
507
508
509bool VirtualMemory::IsReserved() {
510 return address_ != MAP_FAILED;
511}
512
513
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000514bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
515 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000516 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000517 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
518 kMmapFd, kMmapFdOffset)) {
519 return false;
520 }
521
522 UpdateAllocatedSpaceLimits(address, size);
523 return true;
524}
525
526
527bool VirtualMemory::Uncommit(void* address, size_t size) {
528 return mmap(address, size, PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000529 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000530 kMmapFd, kMmapFdOffset) != MAP_FAILED;
531}
532
533
534class ThreadHandle::PlatformData : public Malloced {
535 public:
536 explicit PlatformData(ThreadHandle::Kind kind) {
537 Initialize(kind);
538 }
539
540 void Initialize(ThreadHandle::Kind kind) {
541 switch (kind) {
542 case ThreadHandle::SELF: thread_ = pthread_self(); break;
543 case ThreadHandle::INVALID: thread_ = kNoThread; break;
544 }
545 }
ager@chromium.org41826e72009-03-30 13:30:57 +0000546
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000547 pthread_t thread_; // Thread handle for pthread.
548};
549
550
551ThreadHandle::ThreadHandle(Kind kind) {
552 data_ = new PlatformData(kind);
553}
554
555
556void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
557 data_->Initialize(kind);
558}
559
560
561ThreadHandle::~ThreadHandle() {
562 delete data_;
563}
564
565
566bool ThreadHandle::IsSelf() const {
567 return pthread_equal(data_->thread_, pthread_self());
568}
569
570
571bool ThreadHandle::IsValid() const {
572 return data_->thread_ != kNoThread;
573}
574
575
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000576Thread::Thread(Isolate* isolate, const Options& options)
577 : ThreadHandle(ThreadHandle::INVALID),
578 isolate_(isolate),
579 stack_size_(options.stack_size) {
580 set_name(options.name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000581}
582
583
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000584Thread::Thread(Isolate* isolate, const char* name)
585 : ThreadHandle(ThreadHandle::INVALID),
586 isolate_(isolate),
587 stack_size_(0) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000588 set_name(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589}
590
591
592Thread::~Thread() {
593}
594
595
596static void* ThreadEntry(void* arg) {
597 Thread* thread = reinterpret_cast<Thread*>(arg);
598 // This is also initialized by the first argument to pthread_create() but we
599 // don't know which thread will run first (the original thread or the new
600 // one) so we initialize it here too.
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000601 prctl(PR_SET_NAME,
602 reinterpret_cast<unsigned long>(thread->name()), // NOLINT
603 0, 0, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604 thread->thread_handle_data()->thread_ = pthread_self();
605 ASSERT(thread->IsValid());
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000606 Thread::SetThreadLocal(Isolate::isolate_key(), thread->isolate());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607 thread->Run();
608 return NULL;
609}
610
611
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000612void Thread::set_name(const char* name) {
613 strncpy(name_, name, sizeof(name_));
614 name_[sizeof(name_) - 1] = '\0';
615}
616
617
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000618void Thread::Start() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000619 pthread_attr_t* attr_ptr = NULL;
620 pthread_attr_t attr;
621 if (stack_size_ > 0) {
622 pthread_attr_init(&attr);
623 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
624 attr_ptr = &attr;
625 }
626 pthread_create(&thread_handle_data()->thread_, attr_ptr, ThreadEntry, this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000627 ASSERT(IsValid());
628}
629
630
631void Thread::Join() {
632 pthread_join(thread_handle_data()->thread_, NULL);
633}
634
635
636Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
637 pthread_key_t key;
638 int result = pthread_key_create(&key, NULL);
639 USE(result);
640 ASSERT(result == 0);
641 return static_cast<LocalStorageKey>(key);
642}
643
644
645void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
646 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
647 int result = pthread_key_delete(pthread_key);
648 USE(result);
649 ASSERT(result == 0);
650}
651
652
653void* Thread::GetThreadLocal(LocalStorageKey key) {
654 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
655 return pthread_getspecific(pthread_key);
656}
657
658
659void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
660 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
661 pthread_setspecific(pthread_key, value);
662}
663
664
665void Thread::YieldCPU() {
666 sched_yield();
667}
668
669
670class LinuxMutex : public Mutex {
671 public:
672
673 LinuxMutex() {
674 pthread_mutexattr_t attrs;
675 int result = pthread_mutexattr_init(&attrs);
676 ASSERT(result == 0);
677 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
678 ASSERT(result == 0);
679 result = pthread_mutex_init(&mutex_, &attrs);
680 ASSERT(result == 0);
681 }
682
683 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
684
685 virtual int Lock() {
686 int result = pthread_mutex_lock(&mutex_);
687 return result;
688 }
689
690 virtual int Unlock() {
691 int result = pthread_mutex_unlock(&mutex_);
692 return result;
693 }
694
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000695 virtual bool TryLock() {
696 int result = pthread_mutex_trylock(&mutex_);
697 // Return false if the lock is busy and locking failed.
698 if (result == EBUSY) {
699 return false;
700 }
701 ASSERT(result == 0); // Verify no other errors.
702 return true;
703 }
704
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000705 private:
706 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
707};
708
709
710Mutex* OS::CreateMutex() {
711 return new LinuxMutex();
712}
713
714
715class LinuxSemaphore : public Semaphore {
716 public:
717 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
718 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
719
kasper.lund7276f142008-07-30 08:49:36 +0000720 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000721 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000722 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000723 private:
724 sem_t sem_;
725};
726
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000727
kasper.lund7276f142008-07-30 08:49:36 +0000728void LinuxSemaphore::Wait() {
729 while (true) {
730 int result = sem_wait(&sem_);
731 if (result == 0) return; // Successfully got semaphore.
732 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
733 }
734}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000735
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000736
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000737#ifndef TIMEVAL_TO_TIMESPEC
738#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
739 (ts)->tv_sec = (tv)->tv_sec; \
740 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
741} while (false)
742#endif
743
744
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000745bool LinuxSemaphore::Wait(int timeout) {
746 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000747
748 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000749 struct timeval delta;
750 delta.tv_usec = timeout % kOneSecondMicros;
751 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000752
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000753 struct timeval current_time;
754 // Get the current time.
755 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000756 return false;
757 }
758
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000759 // Calculate time for end of timeout.
760 struct timeval end_time;
761 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000762
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000763 struct timespec ts;
764 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000765 // Wait for semaphore signalled or timeout.
766 while (true) {
767 int result = sem_timedwait(&sem_, &ts);
768 if (result == 0) return true; // Successfully got semaphore.
769 if (result > 0) {
770 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
771 errno = result;
772 result = -1;
773 }
774 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
775 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
776 }
777}
778
779
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000780Semaphore* OS::CreateSemaphore(int count) {
781 return new LinuxSemaphore(count);
782}
783
ager@chromium.org381abbb2009-02-25 13:23:22 +0000784
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000785#ifdef ENABLE_LOGGING_AND_PROFILING
786
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000787#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
788// Android runs a fairly new Linux kernel, so signal info is there,
789// but the C library doesn't have the structs defined.
790
791struct sigcontext {
792 uint32_t trap_no;
793 uint32_t error_code;
794 uint32_t oldmask;
795 uint32_t gregs[16];
796 uint32_t arm_cpsr;
797 uint32_t fault_address;
798};
799typedef uint32_t __sigset_t;
800typedef struct sigcontext mcontext_t;
801typedef struct ucontext {
802 uint32_t uc_flags;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000803 struct ucontext* uc_link;
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000804 stack_t uc_stack;
805 mcontext_t uc_mcontext;
806 __sigset_t uc_sigmask;
807} ucontext_t;
808enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
809
810#endif
811
812
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000813static int GetThreadID() {
814 // Glibc doesn't provide a wrapper for gettid(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000815#if defined(ANDROID)
816 return syscall(__NR_gettid);
817#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000818 return syscall(SYS_gettid);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000819#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000820}
821
822
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000823static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.org5c838252010-02-19 08:53:10 +0000824#ifndef V8_HOST_ARCH_MIPS
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000825 USE(info);
826 if (signal != SIGPROF) return;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000827 Isolate* isolate = Isolate::UncheckedCurrent();
828 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
829 // We require a fully initialized and entered isolate.
830 return;
831 }
832 Sampler* sampler = isolate->logger()->sampler();
833 if (sampler == NULL || !sampler->IsActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000834
lrn@chromium.org25156de2010-04-06 13:10:27 +0000835 TickSample sample_obj;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000836 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
ager@chromium.org357bf652010-04-12 11:30:10 +0000837 if (sample == NULL) sample = &sample_obj;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000838
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000839 // Extracting the sample from the context is extremely machine dependent.
840 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
841 mcontext_t& mcontext = ucontext->uc_mcontext;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000842 sample->state = isolate->current_vm_state();
ager@chromium.org9085a012009-05-11 19:22:57 +0000843#if V8_HOST_ARCH_IA32
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000844 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
845 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
846 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000847#elif V8_HOST_ARCH_X64
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000848 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
849 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
850 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000851#elif V8_HOST_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000852// An undefined macro evaluates to 0, so this applies to Android's Bionic also.
853#if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000854 sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
855 sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
856 sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000857#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000858 sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
859 sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
860 sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000861#endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000862#elif V8_HOST_ARCH_MIPS
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000863 // Implement this on MIPS.
864 UNIMPLEMENTED();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000865#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000866 sampler->SampleStack(sample);
867 sampler->Tick(sample);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000868#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000869}
870
871
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000872class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000873 public:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000874 PlatformData() : vm_tid_(GetThreadID()) {}
875
876 int vm_tid() const { return vm_tid_; }
877
878 private:
879 const int vm_tid_;
880};
881
882
883class SignalSender : public Thread {
884 public:
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000885 enum SleepInterval {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000886 HALF_INTERVAL,
887 FULL_INTERVAL
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000888 };
889
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000890 explicit SignalSender(int interval)
891 : Thread(NULL, "SignalSender"),
lrn@chromium.org303ada72010-10-27 09:33:13 +0000892 vm_tgid_(getpid()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000893 interval_(interval) {}
894
895 static void AddActiveSampler(Sampler* sampler) {
896 ScopedLock lock(mutex_);
897 SamplerRegistry::AddActiveSampler(sampler);
898 if (instance_ == NULL) {
899 // Install a signal handler.
900 struct sigaction sa;
901 sa.sa_sigaction = ProfilerSignalHandler;
902 sigemptyset(&sa.sa_mask);
903 sa.sa_flags = SA_RESTART | SA_SIGINFO;
904 signal_handler_installed_ =
905 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
906
907 // Start a thread that sends SIGPROF signal to VM threads.
908 instance_ = new SignalSender(sampler->interval());
909 instance_->Start();
910 } else {
911 ASSERT(instance_->interval_ == sampler->interval());
912 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000913 }
914
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000915 static void RemoveActiveSampler(Sampler* sampler) {
916 ScopedLock lock(mutex_);
917 SamplerRegistry::RemoveActiveSampler(sampler);
918 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
919 RuntimeProfiler::WakeUpRuntimeProfilerThreadBeforeShutdown();
920 instance_->Join();
921 delete instance_;
922 instance_ = NULL;
923
924 // Restore the old signal handler.
925 if (signal_handler_installed_) {
926 sigaction(SIGPROF, &old_signal_handler_, 0);
927 signal_handler_installed_ = false;
928 }
929 }
930 }
931
932 // Implement Thread::Run().
933 virtual void Run() {
934 SamplerRegistry::State state;
935 while ((state = SamplerRegistry::GetState()) !=
936 SamplerRegistry::HAS_NO_SAMPLERS) {
937 bool cpu_profiling_enabled =
938 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
939 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
940 // When CPU profiling is enabled both JavaScript and C++ code is
941 // profiled. We must not suspend.
942 if (!cpu_profiling_enabled) {
943 if (rate_limiter_.SuspendIfNecessary()) continue;
944 }
945 if (cpu_profiling_enabled && runtime_profiler_enabled) {
946 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
947 return;
948 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000949 Sleep(HALF_INTERVAL);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000950 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
951 return;
952 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000953 Sleep(HALF_INTERVAL);
954 } else {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000955 if (cpu_profiling_enabled) {
956 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
957 this)) {
958 return;
959 }
960 }
961 if (runtime_profiler_enabled) {
962 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
963 NULL)) {
964 return;
965 }
966 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000967 Sleep(FULL_INTERVAL);
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +0000968 }
lrn@chromium.org303ada72010-10-27 09:33:13 +0000969 }
970 }
971
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000972 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
973 if (!sampler->IsProfiling()) return;
974 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
975 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
976 }
977
978 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
979 if (!sampler->isolate()->IsInitialized()) return;
980 sampler->isolate()->runtime_profiler()->NotifyTick();
981 }
982
983 void SendProfilingSignal(int tid) {
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000984 if (!signal_handler_installed_) return;
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000985 // Glibc doesn't provide a wrapper for tgkill(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000986#if defined(ANDROID)
987 syscall(__NR_tgkill, vm_tgid_, tid, SIGPROF);
988#else
989 syscall(SYS_tgkill, vm_tgid_, tid, SIGPROF);
990#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000991 }
992
993 void Sleep(SleepInterval full_or_half) {
994 // Convert ms to us and subtract 100 us to compensate delays
995 // occuring during signal delivery.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000996 useconds_t interval = interval_ * 1000 - 100;
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000997 if (full_or_half == HALF_INTERVAL) interval /= 2;
998 int result = usleep(interval);
999#ifdef DEBUG
1000 if (result != 0 && errno != EINTR) {
1001 fprintf(stderr,
1002 "SignalSender usleep error; interval = %u, errno = %d\n",
1003 interval,
1004 errno);
1005 ASSERT(result == 0 || errno == EINTR);
1006 }
1007#endif
1008 USE(result);
1009 }
1010
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001011 const int vm_tgid_;
1012 const int interval_;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001013 RuntimeProfilerRateLimiter rate_limiter_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001014
1015 // Protects the process wide state below.
1016 static Mutex* mutex_;
1017 static SignalSender* instance_;
1018 static bool signal_handler_installed_;
1019 static struct sigaction old_signal_handler_;
1020
1021 DISALLOW_COPY_AND_ASSIGN(SignalSender);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001022};
1023
1024
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001025Mutex* SignalSender::mutex_ = OS::CreateMutex();
1026SignalSender* SignalSender::instance_ = NULL;
1027struct sigaction SignalSender::old_signal_handler_;
1028bool SignalSender::signal_handler_installed_ = false;
lrn@chromium.org303ada72010-10-27 09:33:13 +00001029
1030
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001031Sampler::Sampler(Isolate* isolate, int interval)
1032 : isolate_(isolate),
1033 interval_(interval),
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001034 profiling_(false),
ager@chromium.orgbeb25712010-11-29 08:02:25 +00001035 active_(false),
1036 samples_taken_(0) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001037 data_ = new PlatformData;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001038}
1039
1040
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001041Sampler::~Sampler() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001042 ASSERT(!IsActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001043 delete data_;
1044}
1045
1046
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001047void Sampler::Start() {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001048 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001049 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001050 SignalSender::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001051}
1052
1053
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001054void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001055 ASSERT(IsActive());
1056 SignalSender::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001057 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001058}
1059
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001060#endif // ENABLE_LOGGING_AND_PROFILING
1061
1062} } // namespace v8::internal