blob: 37330be82ba3b16146be383ba451e560c5accc32 [file] [log] [blame]
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +00001// Copyright 2011 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
ricow@chromium.org9fa09672011-07-25 11:05:35 +000081static void* GetRandomMmapAddr() {
82 Isolate* isolate = Isolate::UncheckedCurrent();
83 // Note that the current isolate isn't set up in a call path via
84 // CpuFeatures::Probe. We don't care about randomization in this case because
85 // the code page is immediately freed.
86 if (isolate != NULL) {
87#ifdef V8_TARGET_ARCH_X64
88 uint64_t rnd1 = V8::RandomPrivate(isolate);
89 uint64_t rnd2 = V8::RandomPrivate(isolate);
90 uint64_t raw_addr = (rnd1 << 32) ^ rnd2;
91 raw_addr &= V8_UINT64_C(0x3ffffffff000);
92#else
93 uint32_t raw_addr = V8::RandomPrivate(isolate);
94 // The range 0x20000000 - 0x60000000 is relatively unpopulated across a
95 // variety of ASLR modes (PAE kernel, NX compat mode, etc).
96 raw_addr &= 0x3ffff000;
97 raw_addr += 0x20000000;
98#endif
99 return reinterpret_cast<void*>(raw_addr);
100 }
101 return NULL;
102}
103
104
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000105void OS::Setup() {
ricow@chromium.org9fa09672011-07-25 11:05:35 +0000106 // Seed the random number generator. We preserve microsecond resolution.
107 uint64_t seed = Ticks() ^ (getpid() << 16);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000108 srandom(static_cast<unsigned int>(seed));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000109 limit_mutex = CreateMutex();
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000110
111#ifdef __arm__
112 // When running on ARM hardware check that the EABI used by V8 and
113 // by the C code is the same.
114 bool hard_float = OS::ArmUsingHardFloat();
115 if (hard_float) {
116#if !USE_EABI_HARDFLOAT
117 PrintF("ERROR: Binary compiled with -mfloat-abi=hard but without "
118 "-DUSE_EABI_HARDFLOAT\n");
119 exit(1);
120#endif
121 } else {
122#if USE_EABI_HARDFLOAT
123 PrintF("ERROR: Binary not compiled with -mfloat-abi=hard but with "
124 "-DUSE_EABI_HARDFLOAT\n");
125 exit(1);
126#endif
127 }
128#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000129}
130
131
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000132uint64_t OS::CpuFeaturesImpliedByPlatform() {
fschneider@chromium.orgfb144a02011-05-04 12:43:48 +0000133#if(defined(__mips_hard_float) && __mips_hard_float != 0)
lrn@chromium.org7516f052011-03-30 08:52:27 +0000134 // Here gcc is telling us that we are on an MIPS and gcc is assuming that we
135 // have FPU instructions. If gcc can assume it then so can we.
136 return 1u << FPU;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000137#else
138 return 0; // Linux runs on anything.
139#endif
140}
141
142
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000143#ifdef __arm__
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000144static bool CPUInfoContainsString(const char * search_string) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000145 const char* file_name = "/proc/cpuinfo";
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000146 // This is written as a straight shot one pass parser
147 // and not using STL string and ifstream because,
148 // on Linux, it's reading from a (non-mmap-able)
149 // character special device.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000150 FILE* f = NULL;
151 const char* what = search_string;
152
153 if (NULL == (f = fopen(file_name, "r")))
154 return false;
155
156 int k;
157 while (EOF != (k = fgetc(f))) {
158 if (k == *what) {
159 ++what;
160 while ((*what != '\0') && (*what == fgetc(f))) {
161 ++what;
162 }
163 if (*what == '\0') {
164 fclose(f);
165 return true;
166 } else {
167 what = search_string;
168 }
169 }
170 }
171 fclose(f);
172
173 // Did not find string in the proc file.
174 return false;
175}
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000176
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000177
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000178bool OS::ArmCpuHasFeature(CpuFeature feature) {
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000179 const char* search_string = NULL;
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000180 // Simple detection of VFP at runtime for Linux.
181 // It is based on /proc/cpuinfo, which reveals hardware configuration
182 // to user-space applications. According to ARM (mid 2009), no similar
183 // facility is universally available on the ARM architectures,
184 // so it's up to individual OSes to provide such.
185 switch (feature) {
186 case VFP3:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000187 search_string = "vfpv3";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000188 break;
189 case ARMv7:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000190 search_string = "ARMv7";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000191 break;
192 default:
193 UNREACHABLE();
194 }
195
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000196 if (CPUInfoContainsString(search_string)) {
197 return true;
198 }
199
200 if (feature == VFP3) {
201 // Some old kernels will report vfp not vfpv3. Here we make a last attempt
202 // to detect vfpv3 by checking for vfp *and* neon, since neon is only
203 // available on architectures with vfpv3.
204 // Checking neon on its own is not enough as it is possible to have neon
205 // without vfp.
206 if (CPUInfoContainsString("vfp") && CPUInfoContainsString("neon")) {
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000207 return true;
208 }
209 }
210
211 return false;
212}
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000213
214
215// Simple helper function to detect whether the C code is compiled with
216// option -mfloat-abi=hard. The register d0 is loaded with 1.0 and the register
217// pair r0, r1 is loaded with 0.0. If -mfloat-abi=hard is pased to GCC then
218// calling this will return 1.0 and otherwise 0.0.
219static void ArmUsingHardFloatHelper() {
220 asm("mov r0, #0");
221#if defined(__VFP_FP__) && !defined(__SOFTFP__)
222 // Load 0x3ff00000 into r1 using instructions available in both ARM
223 // and Thumb mode.
224 asm("mov r1, #3");
225 asm("mov r2, #255");
226 asm("lsl r1, r1, #8");
227 asm("orr r1, r1, r2");
lrn@chromium.org1c092762011-05-09 09:42:16 +0000228 asm("lsl r1, r1, #20");
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000229 // For vmov d0, r0, r1 use ARM mode.
230#ifdef __thumb__
231 asm volatile(
232 "@ Enter ARM Mode \n\t"
233 " adr r3, 1f \n\t"
234 " bx r3 \n\t"
235 " .ALIGN 4 \n\t"
236 " .ARM \n"
237 "1: vmov d0, r0, r1 \n\t"
238 "@ Enter THUMB Mode\n\t"
239 " adr r3, 2f+1 \n\t"
240 " bx r3 \n\t"
241 " .THUMB \n"
242 "2: \n\t");
243#else
244 asm("vmov d0, r0, r1");
245#endif // __thumb__
246#endif // defined(__VFP_FP__) && !defined(__SOFTFP__)
247 asm("mov r1, #0");
248}
249
250
251bool OS::ArmUsingHardFloat() {
252 // Cast helper function from returning void to returning double.
253 typedef double (*F)();
254 F f = FUNCTION_CAST<F>(FUNCTION_ADDR(ArmUsingHardFloatHelper));
255 return f() == 1.0;
256}
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000257#endif // def __arm__
258
259
lrn@chromium.org7516f052011-03-30 08:52:27 +0000260#ifdef __mips__
261bool OS::MipsCpuHasFeature(CpuFeature feature) {
262 const char* search_string = NULL;
263 const char* file_name = "/proc/cpuinfo";
264 // Simple detection of FPU at runtime for Linux.
265 // It is based on /proc/cpuinfo, which reveals hardware configuration
266 // to user-space applications. According to MIPS (early 2010), no similar
267 // facility is universally available on the MIPS architectures,
268 // so it's up to individual OSes to provide such.
269 //
270 // This is written as a straight shot one pass parser
271 // and not using STL string and ifstream because,
272 // on Linux, it's reading from a (non-mmap-able)
273 // character special device.
274
275 switch (feature) {
276 case FPU:
277 search_string = "FPU";
278 break;
279 default:
280 UNREACHABLE();
281 }
282
283 FILE* f = NULL;
284 const char* what = search_string;
285
286 if (NULL == (f = fopen(file_name, "r")))
287 return false;
288
289 int k;
290 while (EOF != (k = fgetc(f))) {
291 if (k == *what) {
292 ++what;
293 while ((*what != '\0') && (*what == fgetc(f))) {
294 ++what;
295 }
296 if (*what == '\0') {
297 fclose(f);
298 return true;
299 } else {
300 what = search_string;
301 }
302 }
303 }
304 fclose(f);
305
306 // Did not find string in the proc file.
307 return false;
308}
309#endif // def __mips__
310
311
ager@chromium.org236ad962008-09-25 09:45:57 +0000312int OS::ActivationFrameAlignment() {
ager@chromium.orge2902be2009-06-08 12:21:35 +0000313#ifdef V8_TARGET_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000314 // On EABI ARM targets this is required for fp correctness in the
315 // runtime system.
ager@chromium.org3a6061e2009-03-12 14:24:36 +0000316 return 8;
ager@chromium.org5c838252010-02-19 08:53:10 +0000317#elif V8_TARGET_ARCH_MIPS
318 return 8;
319#endif
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000320 // With gcc 4.4 the tree vectorization optimizer can generate code
ager@chromium.orge2902be2009-06-08 12:21:35 +0000321 // that requires 16 byte alignment such as movdqa on x86.
322 return 16;
ager@chromium.org236ad962008-09-25 09:45:57 +0000323}
324
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000325
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000326void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
lrn@chromium.org7516f052011-03-30 08:52:27 +0000327#if (defined(V8_TARGET_ARCH_ARM) && defined(__arm__)) || \
328 (defined(V8_TARGET_ARCH_MIPS) && defined(__mips__))
329 // Only use on ARM or MIPS hardware.
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000330 MemoryBarrier();
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000331#else
332 __asm__ __volatile__("" : : : "memory");
333 // An x86 store acts as a release barrier.
334#endif
335 *ptr = value;
336}
337
338
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000339const char* OS::LocalTimezone(double time) {
340 if (isnan(time)) return "";
341 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
342 struct tm* t = localtime(&tv);
343 if (NULL == t) return "";
344 return t->tm_zone;
345}
346
347
348double OS::LocalTimeOffset() {
349 time_t tv = time(NULL);
350 struct tm* t = localtime(&tv);
351 // tm_gmtoff includes any daylight savings offset, so subtract it.
352 return static_cast<double>(t->tm_gmtoff * msPerSecond -
353 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
354}
355
356
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000357// We keep the lowest and highest addresses mapped as a quick way of
358// determining that pointers are outside the heap (used mostly in assertions
359// and verification). The estimate is conservative, ie, not all addresses in
360// 'allocated' space are actually allocated to our heap. The range is
361// [lowest, highest), inclusive on the low and and exclusive on the high end.
362static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
363static void* highest_ever_allocated = reinterpret_cast<void*>(0);
364
365
366static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000367 ASSERT(limit_mutex != NULL);
368 ScopedLock lock(limit_mutex);
369
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000370 lowest_ever_allocated = Min(lowest_ever_allocated, address);
371 highest_ever_allocated =
372 Max(highest_ever_allocated,
373 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
374}
375
376
377bool OS::IsOutsideAllocatedSpace(void* address) {
378 return address < lowest_ever_allocated || address >= highest_ever_allocated;
379}
380
381
382size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000383 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000384}
385
386
kasper.lund7276f142008-07-30 08:49:36 +0000387void* OS::Allocate(const size_t requested,
388 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000389 bool is_executable) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000390 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000391 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
ricow@chromium.org9fa09672011-07-25 11:05:35 +0000392 void* addr = GetRandomMmapAddr();
393 void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000394 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000395 LOG(i::Isolate::Current(),
396 StringEvent("OS::Allocate", "mmap failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000397 return NULL;
398 }
399 *allocated = msize;
400 UpdateAllocatedSpaceLimits(mbase, msize);
401 return mbase;
402}
403
404
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000405void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000406 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000407 int result = munmap(address, size);
408 USE(result);
409 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410}
411
412
413void OS::Sleep(int milliseconds) {
414 unsigned int ms = static_cast<unsigned int>(milliseconds);
415 usleep(1000 * ms);
416}
417
418
419void OS::Abort() {
420 // Redirect to std abort to signal abnormal program termination.
421 abort();
422}
423
424
kasper.lund7276f142008-07-30 08:49:36 +0000425void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000426// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
427// which is the architecture of generated code).
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000428#if (defined(__arm__) || defined(__thumb__))
429# if defined(CAN_USE_ARMV5_INSTRUCTIONS)
kasper.lund7276f142008-07-30 08:49:36 +0000430 asm("bkpt 0");
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000431# endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000432#elif defined(__mips__)
433 asm("break");
kasper.lund7276f142008-07-30 08:49:36 +0000434#else
435 asm("int $3");
436#endif
437}
438
439
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000440class PosixMemoryMappedFile : public OS::MemoryMappedFile {
441 public:
442 PosixMemoryMappedFile(FILE* file, void* memory, int size)
443 : file_(file), memory_(memory), size_(size) { }
444 virtual ~PosixMemoryMappedFile();
445 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000446 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000447 private:
448 FILE* file_;
449 void* memory_;
450 int size_;
451};
452
453
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000454OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000455 FILE* file = fopen(name, "r+");
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000456 if (file == NULL) return NULL;
457
458 fseek(file, 0, SEEK_END);
459 int size = ftell(file);
460
461 void* memory =
462 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
463 return new PosixMemoryMappedFile(file, memory, size);
464}
465
466
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000467OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
468 void* initial) {
469 FILE* file = fopen(name, "w+");
470 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000471 int result = fwrite(initial, size, 1, file);
472 if (result < 1) {
473 fclose(file);
474 return NULL;
475 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000476 void* memory =
477 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
478 return new PosixMemoryMappedFile(file, memory, size);
479}
480
481
482PosixMemoryMappedFile::~PosixMemoryMappedFile() {
483 if (memory_) munmap(memory_, size_);
484 fclose(file_);
485}
486
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000487
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000488void OS::LogSharedLibraryAddresses() {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000489 // This function assumes that the layout of the file is as follows:
490 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
491 // If we encounter an unexpected situation we abort scanning further entries.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000492 FILE* fp = fopen("/proc/self/maps", "r");
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000493 if (fp == NULL) return;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000494
495 // Allocate enough room to be able to store a full file name.
496 const int kLibNameLen = FILENAME_MAX + 1;
497 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
498
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000499 i::Isolate* isolate = ISOLATE;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000500 // This loop will terminate once the scanning hits an EOF.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000501 while (true) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000502 uintptr_t start, end;
503 char attr_r, attr_w, attr_x, attr_p;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000504 // Parse the addresses and permission bits at the beginning of the line.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000505 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
506 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 +0000507
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000508 int c;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000509 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
510 // Found a read-only executable entry. Skip characters until we reach
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000511 // the beginning of the filename or the end of the line.
512 do {
513 c = getc(fp);
514 } while ((c != EOF) && (c != '\n') && (c != '/'));
515 if (c == EOF) break; // EOF: Was unexpected, just exit.
516
517 // Process the filename if found.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000518 if (c == '/') {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000519 ungetc(c, fp); // Push the '/' back into the stream to be read below.
520
521 // Read to the end of the line. Exit if the read fails.
522 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
523
524 // Drop the newline character read by fgets. We do not need to check
525 // for a zero-length string because we know that we at least read the
526 // '/' character.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000527 lib_name[strlen(lib_name) - 1] = '\0';
528 } else {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000529 // No library name found, just record the raw address range.
530 snprintf(lib_name, kLibNameLen,
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000531 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
532 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000533 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000534 } else {
535 // Entry not describing executable data. Skip to end of line to setup
536 // reading the next entry.
537 do {
538 c = getc(fp);
539 } while ((c != EOF) && (c != '\n'));
540 if (c == EOF) break;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000541 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000542 }
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000543 free(lib_name);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000544 fclose(fp);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000545}
546
547
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000548static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
549
550
551void OS::SignalCodeMovingGC() {
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000552 // Support for ll_prof.py.
553 //
554 // The Linux profiler built into the kernel logs all mmap's with
555 // PROT_EXEC so that analysis tools can properly attribute ticks. We
556 // do a mmap with a name known by ll_prof.py and immediately munmap
557 // it. This injects a GC marker into the stream of events generated
558 // by the kernel and allows us to synchronize V8 code log and the
559 // kernel log.
560 int size = sysconf(_SC_PAGESIZE);
561 FILE* f = fopen(kGCFakeMmap, "w+");
562 void* addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE,
563 fileno(f), 0);
564 ASSERT(addr != MAP_FAILED);
565 munmap(addr, size);
566 fclose(f);
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000567}
568
569
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000570int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000571 // backtrace is a glibc extension.
572#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000573 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000574 ScopedVector<void*> addresses(frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000575
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000576 int frames_count = backtrace(addresses.start(), frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000577
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000578 char** symbols = backtrace_symbols(addresses.start(), frames_count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579 if (symbols == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000580 return kStackWalkError;
581 }
582
583 for (int i = 0; i < frames_count; i++) {
584 frames[i].address = addresses[i];
585 // Format a text representation of the frame based on the information
586 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000587 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
588 "%s",
589 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000590 // Make sure line termination is in place.
591 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
592 }
593
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594 free(symbols);
595
596 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000597#else // ndef __GLIBC__
598 return 0;
599#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000600}
601
602
603// Constants used for mmap.
604static const int kMmapFd = -1;
605static const int kMmapFdOffset = 0;
606
607
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000608VirtualMemory::VirtualMemory(size_t size) {
ricow@chromium.org9fa09672011-07-25 11:05:35 +0000609 address_ = mmap(GetRandomMmapAddr(), size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000610 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
611 kMmapFd, kMmapFdOffset);
612 size_ = size;
613}
614
615
616VirtualMemory::~VirtualMemory() {
617 if (IsReserved()) {
618 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
619 }
620}
621
622
623bool VirtualMemory::IsReserved() {
624 return address_ != MAP_FAILED;
625}
626
627
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000628bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
629 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000630 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000631 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
632 kMmapFd, kMmapFdOffset)) {
633 return false;
634 }
635
636 UpdateAllocatedSpaceLimits(address, size);
637 return true;
638}
639
640
641bool VirtualMemory::Uncommit(void* address, size_t size) {
642 return mmap(address, size, PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000643 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000644 kMmapFd, kMmapFdOffset) != MAP_FAILED;
645}
646
647
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000648class Thread::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000649 public:
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000650 PlatformData() : thread_(kNoThread) {}
ager@chromium.org41826e72009-03-30 13:30:57 +0000651
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000652 pthread_t thread_; // Thread handle for pthread.
653};
654
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000655Thread::Thread(const Options& options)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000656 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000657 stack_size_(options.stack_size) {
658 set_name(options.name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000659}
660
661
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000662Thread::Thread(const char* name)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000663 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000664 stack_size_(0) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000665 set_name(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000666}
667
668
669Thread::~Thread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000670 delete data_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000671}
672
673
674static void* ThreadEntry(void* arg) {
675 Thread* thread = reinterpret_cast<Thread*>(arg);
676 // This is also initialized by the first argument to pthread_create() but we
677 // don't know which thread will run first (the original thread or the new
678 // one) so we initialize it here too.
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000679 prctl(PR_SET_NAME,
680 reinterpret_cast<unsigned long>(thread->name()), // NOLINT
681 0, 0, 0);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000682 thread->data()->thread_ = pthread_self();
683 ASSERT(thread->data()->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000684 thread->Run();
685 return NULL;
686}
687
688
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000689void Thread::set_name(const char* name) {
690 strncpy(name_, name, sizeof(name_));
691 name_[sizeof(name_) - 1] = '\0';
692}
693
694
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000695void Thread::Start() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000696 pthread_attr_t* attr_ptr = NULL;
697 pthread_attr_t attr;
698 if (stack_size_ > 0) {
699 pthread_attr_init(&attr);
700 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
701 attr_ptr = &attr;
702 }
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000703 pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
704 ASSERT(data_->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000705}
706
707
708void Thread::Join() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000709 pthread_join(data_->thread_, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000710}
711
712
713Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
714 pthread_key_t key;
715 int result = pthread_key_create(&key, NULL);
716 USE(result);
717 ASSERT(result == 0);
718 return static_cast<LocalStorageKey>(key);
719}
720
721
722void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
723 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
724 int result = pthread_key_delete(pthread_key);
725 USE(result);
726 ASSERT(result == 0);
727}
728
729
730void* Thread::GetThreadLocal(LocalStorageKey key) {
731 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
732 return pthread_getspecific(pthread_key);
733}
734
735
736void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
737 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
738 pthread_setspecific(pthread_key, value);
739}
740
741
742void Thread::YieldCPU() {
743 sched_yield();
744}
745
746
747class LinuxMutex : public Mutex {
748 public:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000749 LinuxMutex() {
750 pthread_mutexattr_t attrs;
751 int result = pthread_mutexattr_init(&attrs);
752 ASSERT(result == 0);
753 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
754 ASSERT(result == 0);
755 result = pthread_mutex_init(&mutex_, &attrs);
756 ASSERT(result == 0);
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000757 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000758 }
759
760 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
761
762 virtual int Lock() {
763 int result = pthread_mutex_lock(&mutex_);
764 return result;
765 }
766
767 virtual int Unlock() {
768 int result = pthread_mutex_unlock(&mutex_);
769 return result;
770 }
771
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000772 virtual bool TryLock() {
773 int result = pthread_mutex_trylock(&mutex_);
774 // Return false if the lock is busy and locking failed.
775 if (result == EBUSY) {
776 return false;
777 }
778 ASSERT(result == 0); // Verify no other errors.
779 return true;
780 }
781
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000782 private:
783 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
784};
785
786
787Mutex* OS::CreateMutex() {
788 return new LinuxMutex();
789}
790
791
792class LinuxSemaphore : public Semaphore {
793 public:
794 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
795 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
796
kasper.lund7276f142008-07-30 08:49:36 +0000797 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000798 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000799 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000800 private:
801 sem_t sem_;
802};
803
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000804
kasper.lund7276f142008-07-30 08:49:36 +0000805void LinuxSemaphore::Wait() {
806 while (true) {
807 int result = sem_wait(&sem_);
808 if (result == 0) return; // Successfully got semaphore.
809 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
810 }
811}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000812
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000813
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000814#ifndef TIMEVAL_TO_TIMESPEC
815#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
816 (ts)->tv_sec = (tv)->tv_sec; \
817 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
818} while (false)
819#endif
820
821
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000822bool LinuxSemaphore::Wait(int timeout) {
823 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000824
825 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000826 struct timeval delta;
827 delta.tv_usec = timeout % kOneSecondMicros;
828 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000829
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000830 struct timeval current_time;
831 // Get the current time.
832 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000833 return false;
834 }
835
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000836 // Calculate time for end of timeout.
837 struct timeval end_time;
838 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000839
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000840 struct timespec ts;
841 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000842 // Wait for semaphore signalled or timeout.
843 while (true) {
844 int result = sem_timedwait(&sem_, &ts);
845 if (result == 0) return true; // Successfully got semaphore.
846 if (result > 0) {
847 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
848 errno = result;
849 result = -1;
850 }
851 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
852 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
853 }
854}
855
856
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000857Semaphore* OS::CreateSemaphore(int count) {
858 return new LinuxSemaphore(count);
859}
860
ager@chromium.org381abbb2009-02-25 13:23:22 +0000861
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000862#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
863// Android runs a fairly new Linux kernel, so signal info is there,
864// but the C library doesn't have the structs defined.
865
866struct sigcontext {
867 uint32_t trap_no;
868 uint32_t error_code;
869 uint32_t oldmask;
870 uint32_t gregs[16];
871 uint32_t arm_cpsr;
872 uint32_t fault_address;
873};
874typedef uint32_t __sigset_t;
875typedef struct sigcontext mcontext_t;
876typedef struct ucontext {
877 uint32_t uc_flags;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000878 struct ucontext* uc_link;
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000879 stack_t uc_stack;
880 mcontext_t uc_mcontext;
881 __sigset_t uc_sigmask;
882} ucontext_t;
883enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
884
885#endif
886
887
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000888static int GetThreadID() {
889 // Glibc doesn't provide a wrapper for gettid(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000890#if defined(ANDROID)
891 return syscall(__NR_gettid);
892#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000893 return syscall(SYS_gettid);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000894#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000895}
896
897
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.org5c838252010-02-19 08:53:10 +0000899#ifndef V8_HOST_ARCH_MIPS
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900 USE(info);
901 if (signal != SIGPROF) return;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000902 Isolate* isolate = Isolate::UncheckedCurrent();
903 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
904 // We require a fully initialized and entered isolate.
905 return;
906 }
vitalyr@chromium.org0ec56d62011-04-15 22:22:08 +0000907 if (v8::Locker::IsActive() &&
908 !isolate->thread_manager()->IsLockedByCurrentThread()) {
909 return;
910 }
911
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000912 Sampler* sampler = isolate->logger()->sampler();
913 if (sampler == NULL || !sampler->IsActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000914
lrn@chromium.org25156de2010-04-06 13:10:27 +0000915 TickSample sample_obj;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000916 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
ager@chromium.org357bf652010-04-12 11:30:10 +0000917 if (sample == NULL) sample = &sample_obj;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000918
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000919 // Extracting the sample from the context is extremely machine dependent.
920 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
921 mcontext_t& mcontext = ucontext->uc_mcontext;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000922 sample->state = isolate->current_vm_state();
ager@chromium.org9085a012009-05-11 19:22:57 +0000923#if V8_HOST_ARCH_IA32
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000924 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
925 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
926 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000927#elif V8_HOST_ARCH_X64
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000928 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
929 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
930 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000931#elif V8_HOST_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000932// An undefined macro evaluates to 0, so this applies to Android's Bionic also.
933#if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000934 sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
935 sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
936 sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000937#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000938 sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
939 sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
940 sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000941#endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000942#elif V8_HOST_ARCH_MIPS
lrn@chromium.org7516f052011-03-30 08:52:27 +0000943 sample.pc = reinterpret_cast<Address>(mcontext.pc);
944 sample.sp = reinterpret_cast<Address>(mcontext.gregs[29]);
945 sample.fp = reinterpret_cast<Address>(mcontext.gregs[30]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000946#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000947 sampler->SampleStack(sample);
948 sampler->Tick(sample);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000949#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950}
951
952
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000953class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000954 public:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000955 PlatformData() : vm_tid_(GetThreadID()) {}
956
957 int vm_tid() const { return vm_tid_; }
958
959 private:
960 const int vm_tid_;
961};
962
963
964class SignalSender : public Thread {
965 public:
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000966 enum SleepInterval {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000967 HALF_INTERVAL,
968 FULL_INTERVAL
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000969 };
970
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000971 explicit SignalSender(int interval)
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000972 : Thread("SignalSender"),
lrn@chromium.org303ada72010-10-27 09:33:13 +0000973 vm_tgid_(getpid()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000974 interval_(interval) {}
975
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +0000976 static void InstallSignalHandler() {
977 struct sigaction sa;
978 sa.sa_sigaction = ProfilerSignalHandler;
979 sigemptyset(&sa.sa_mask);
980 sa.sa_flags = SA_RESTART | SA_SIGINFO;
981 signal_handler_installed_ =
982 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
983 }
984
985 static void RestoreSignalHandler() {
986 if (signal_handler_installed_) {
987 sigaction(SIGPROF, &old_signal_handler_, 0);
988 signal_handler_installed_ = false;
989 }
990 }
991
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000992 static void AddActiveSampler(Sampler* sampler) {
993 ScopedLock lock(mutex_);
994 SamplerRegistry::AddActiveSampler(sampler);
995 if (instance_ == NULL) {
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +0000996 // Start a thread that will send SIGPROF signal to VM threads,
997 // when CPU profiling will be enabled.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000998 instance_ = new SignalSender(sampler->interval());
999 instance_->Start();
1000 } else {
1001 ASSERT(instance_->interval_ == sampler->interval());
1002 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001003 }
1004
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001005 static void RemoveActiveSampler(Sampler* sampler) {
1006 ScopedLock lock(mutex_);
1007 SamplerRegistry::RemoveActiveSampler(sampler);
1008 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00001009 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001010 delete instance_;
1011 instance_ = NULL;
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +00001012 RestoreSignalHandler();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001013 }
1014 }
1015
1016 // Implement Thread::Run().
1017 virtual void Run() {
1018 SamplerRegistry::State state;
1019 while ((state = SamplerRegistry::GetState()) !=
1020 SamplerRegistry::HAS_NO_SAMPLERS) {
1021 bool cpu_profiling_enabled =
1022 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1023 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +00001024 if (cpu_profiling_enabled && !signal_handler_installed_) {
1025 InstallSignalHandler();
1026 } else if (!cpu_profiling_enabled && signal_handler_installed_) {
1027 RestoreSignalHandler();
1028 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001029 // When CPU profiling is enabled both JavaScript and C++ code is
1030 // profiled. We must not suspend.
1031 if (!cpu_profiling_enabled) {
1032 if (rate_limiter_.SuspendIfNecessary()) continue;
1033 }
1034 if (cpu_profiling_enabled && runtime_profiler_enabled) {
1035 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1036 return;
1037 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001038 Sleep(HALF_INTERVAL);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001039 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1040 return;
1041 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001042 Sleep(HALF_INTERVAL);
1043 } else {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001044 if (cpu_profiling_enabled) {
1045 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
1046 this)) {
1047 return;
1048 }
1049 }
1050 if (runtime_profiler_enabled) {
1051 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
1052 NULL)) {
1053 return;
1054 }
1055 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001056 Sleep(FULL_INTERVAL);
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +00001057 }
lrn@chromium.org303ada72010-10-27 09:33:13 +00001058 }
1059 }
1060
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001061 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
1062 if (!sampler->IsProfiling()) return;
1063 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
1064 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
1065 }
1066
1067 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1068 if (!sampler->isolate()->IsInitialized()) return;
1069 sampler->isolate()->runtime_profiler()->NotifyTick();
1070 }
1071
1072 void SendProfilingSignal(int tid) {
karlklose@chromium.org8f806e82011-03-07 14:06:08 +00001073 if (!signal_handler_installed_) return;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001074 // Glibc doesn't provide a wrapper for tgkill(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001075#if defined(ANDROID)
1076 syscall(__NR_tgkill, vm_tgid_, tid, SIGPROF);
1077#else
1078 syscall(SYS_tgkill, vm_tgid_, tid, SIGPROF);
1079#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001080 }
1081
1082 void Sleep(SleepInterval full_or_half) {
1083 // Convert ms to us and subtract 100 us to compensate delays
1084 // occuring during signal delivery.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001085 useconds_t interval = interval_ * 1000 - 100;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001086 if (full_or_half == HALF_INTERVAL) interval /= 2;
1087 int result = usleep(interval);
1088#ifdef DEBUG
1089 if (result != 0 && errno != EINTR) {
1090 fprintf(stderr,
1091 "SignalSender usleep error; interval = %u, errno = %d\n",
1092 interval,
1093 errno);
1094 ASSERT(result == 0 || errno == EINTR);
1095 }
1096#endif
1097 USE(result);
1098 }
1099
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001100 const int vm_tgid_;
1101 const int interval_;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001102 RuntimeProfilerRateLimiter rate_limiter_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001103
1104 // Protects the process wide state below.
1105 static Mutex* mutex_;
1106 static SignalSender* instance_;
1107 static bool signal_handler_installed_;
1108 static struct sigaction old_signal_handler_;
1109
1110 DISALLOW_COPY_AND_ASSIGN(SignalSender);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001111};
1112
1113
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001114Mutex* SignalSender::mutex_ = OS::CreateMutex();
1115SignalSender* SignalSender::instance_ = NULL;
1116struct sigaction SignalSender::old_signal_handler_;
1117bool SignalSender::signal_handler_installed_ = false;
lrn@chromium.org303ada72010-10-27 09:33:13 +00001118
1119
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001120Sampler::Sampler(Isolate* isolate, int interval)
1121 : isolate_(isolate),
1122 interval_(interval),
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001123 profiling_(false),
ager@chromium.orgbeb25712010-11-29 08:02:25 +00001124 active_(false),
1125 samples_taken_(0) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001126 data_ = new PlatformData;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001127}
1128
1129
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001130Sampler::~Sampler() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001131 ASSERT(!IsActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001132 delete data_;
1133}
1134
1135
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001136void Sampler::Start() {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001137 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001138 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001139 SignalSender::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001140}
1141
1142
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001143void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001144 ASSERT(IsActive());
1145 SignalSender::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001146 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001147}
1148
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001149
1150} } // namespace v8::internal