blob: db6c80ed5df1e22cbdbd0e9d40f7e88e3b3885fd [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
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();
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +000090
91#ifdef __arm__
92 // When running on ARM hardware check that the EABI used by V8 and
93 // by the C code is the same.
94 bool hard_float = OS::ArmUsingHardFloat();
95 if (hard_float) {
96#if !USE_EABI_HARDFLOAT
97 PrintF("ERROR: Binary compiled with -mfloat-abi=hard but without "
98 "-DUSE_EABI_HARDFLOAT\n");
99 exit(1);
100#endif
101 } else {
102#if USE_EABI_HARDFLOAT
103 PrintF("ERROR: Binary not compiled with -mfloat-abi=hard but with "
104 "-DUSE_EABI_HARDFLOAT\n");
105 exit(1);
106#endif
107 }
108#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000109}
110
111
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000112uint64_t OS::CpuFeaturesImpliedByPlatform() {
113#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000114 // Here gcc is telling us that we are on an ARM and gcc is assuming
115 // that we have VFP3 instructions. If gcc can assume it then so can
116 // we. VFPv3 implies ARMv7, see ARM DDI 0406B, page A1-6.
117 return 1u << VFP3 | 1u << ARMv7;
ager@chromium.org5c838252010-02-19 08:53:10 +0000118#elif CAN_USE_ARMV7_INSTRUCTIONS
119 return 1u << ARMv7;
lrn@chromium.org7516f052011-03-30 08:52:27 +0000120#elif(defined(__mips_hard_float) && __mips_hard_float != 0)
121 // Here gcc is telling us that we are on an MIPS and gcc is assuming that we
122 // have FPU instructions. If gcc can assume it then so can we.
123 return 1u << FPU;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000124#else
125 return 0; // Linux runs on anything.
126#endif
127}
128
129
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000130#ifdef __arm__
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000131static bool CPUInfoContainsString(const char * search_string) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000132 const char* file_name = "/proc/cpuinfo";
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000133 // This is written as a straight shot one pass parser
134 // and not using STL string and ifstream because,
135 // on Linux, it's reading from a (non-mmap-able)
136 // character special device.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000137 FILE* f = NULL;
138 const char* what = search_string;
139
140 if (NULL == (f = fopen(file_name, "r")))
141 return false;
142
143 int k;
144 while (EOF != (k = fgetc(f))) {
145 if (k == *what) {
146 ++what;
147 while ((*what != '\0') && (*what == fgetc(f))) {
148 ++what;
149 }
150 if (*what == '\0') {
151 fclose(f);
152 return true;
153 } else {
154 what = search_string;
155 }
156 }
157 }
158 fclose(f);
159
160 // Did not find string in the proc file.
161 return false;
162}
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000163
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000164
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000165bool OS::ArmCpuHasFeature(CpuFeature feature) {
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000166 const char* search_string = NULL;
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000167 // Simple detection of VFP at runtime for Linux.
168 // It is based on /proc/cpuinfo, which reveals hardware configuration
169 // to user-space applications. According to ARM (mid 2009), no similar
170 // facility is universally available on the ARM architectures,
171 // so it's up to individual OSes to provide such.
172 switch (feature) {
173 case VFP3:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000174 search_string = "vfpv3";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000175 break;
176 case ARMv7:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000177 search_string = "ARMv7";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000178 break;
179 default:
180 UNREACHABLE();
181 }
182
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000183 if (CPUInfoContainsString(search_string)) {
184 return true;
185 }
186
187 if (feature == VFP3) {
188 // Some old kernels will report vfp not vfpv3. Here we make a last attempt
189 // to detect vfpv3 by checking for vfp *and* neon, since neon is only
190 // available on architectures with vfpv3.
191 // Checking neon on its own is not enough as it is possible to have neon
192 // without vfp.
193 if (CPUInfoContainsString("vfp") && CPUInfoContainsString("neon")) {
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000194 return true;
195 }
196 }
197
198 return false;
199}
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000200
201
202// Simple helper function to detect whether the C code is compiled with
203// option -mfloat-abi=hard. The register d0 is loaded with 1.0 and the register
204// pair r0, r1 is loaded with 0.0. If -mfloat-abi=hard is pased to GCC then
205// calling this will return 1.0 and otherwise 0.0.
206static void ArmUsingHardFloatHelper() {
207 asm("mov r0, #0");
208#if defined(__VFP_FP__) && !defined(__SOFTFP__)
209 // Load 0x3ff00000 into r1 using instructions available in both ARM
210 // and Thumb mode.
211 asm("mov r1, #3");
212 asm("mov r2, #255");
213 asm("lsl r1, r1, #8");
214 asm("orr r1, r1, r2");
215 asm("lsl r1, r1, #16");
216 // For vmov d0, r0, r1 use ARM mode.
217#ifdef __thumb__
218 asm volatile(
219 "@ Enter ARM Mode \n\t"
220 " adr r3, 1f \n\t"
221 " bx r3 \n\t"
222 " .ALIGN 4 \n\t"
223 " .ARM \n"
224 "1: vmov d0, r0, r1 \n\t"
225 "@ Enter THUMB Mode\n\t"
226 " adr r3, 2f+1 \n\t"
227 " bx r3 \n\t"
228 " .THUMB \n"
229 "2: \n\t");
230#else
231 asm("vmov d0, r0, r1");
232#endif // __thumb__
233#endif // defined(__VFP_FP__) && !defined(__SOFTFP__)
234 asm("mov r1, #0");
235}
236
237
238bool OS::ArmUsingHardFloat() {
239 // Cast helper function from returning void to returning double.
240 typedef double (*F)();
241 F f = FUNCTION_CAST<F>(FUNCTION_ADDR(ArmUsingHardFloatHelper));
242 return f() == 1.0;
243}
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000244#endif // def __arm__
245
246
lrn@chromium.org7516f052011-03-30 08:52:27 +0000247#ifdef __mips__
248bool OS::MipsCpuHasFeature(CpuFeature feature) {
249 const char* search_string = NULL;
250 const char* file_name = "/proc/cpuinfo";
251 // Simple detection of FPU at runtime for Linux.
252 // It is based on /proc/cpuinfo, which reveals hardware configuration
253 // to user-space applications. According to MIPS (early 2010), no similar
254 // facility is universally available on the MIPS architectures,
255 // so it's up to individual OSes to provide such.
256 //
257 // This is written as a straight shot one pass parser
258 // and not using STL string and ifstream because,
259 // on Linux, it's reading from a (non-mmap-able)
260 // character special device.
261
262 switch (feature) {
263 case FPU:
264 search_string = "FPU";
265 break;
266 default:
267 UNREACHABLE();
268 }
269
270 FILE* f = NULL;
271 const char* what = search_string;
272
273 if (NULL == (f = fopen(file_name, "r")))
274 return false;
275
276 int k;
277 while (EOF != (k = fgetc(f))) {
278 if (k == *what) {
279 ++what;
280 while ((*what != '\0') && (*what == fgetc(f))) {
281 ++what;
282 }
283 if (*what == '\0') {
284 fclose(f);
285 return true;
286 } else {
287 what = search_string;
288 }
289 }
290 }
291 fclose(f);
292
293 // Did not find string in the proc file.
294 return false;
295}
296#endif // def __mips__
297
298
ager@chromium.org236ad962008-09-25 09:45:57 +0000299int OS::ActivationFrameAlignment() {
ager@chromium.orge2902be2009-06-08 12:21:35 +0000300#ifdef V8_TARGET_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000301 // On EABI ARM targets this is required for fp correctness in the
302 // runtime system.
ager@chromium.org3a6061e2009-03-12 14:24:36 +0000303 return 8;
ager@chromium.org5c838252010-02-19 08:53:10 +0000304#elif V8_TARGET_ARCH_MIPS
305 return 8;
306#endif
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000307 // With gcc 4.4 the tree vectorization optimizer can generate code
ager@chromium.orge2902be2009-06-08 12:21:35 +0000308 // that requires 16 byte alignment such as movdqa on x86.
309 return 16;
ager@chromium.org236ad962008-09-25 09:45:57 +0000310}
311
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000312
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000313void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
lrn@chromium.org7516f052011-03-30 08:52:27 +0000314#if (defined(V8_TARGET_ARCH_ARM) && defined(__arm__)) || \
315 (defined(V8_TARGET_ARCH_MIPS) && defined(__mips__))
316 // Only use on ARM or MIPS hardware.
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000317 MemoryBarrier();
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000318#else
319 __asm__ __volatile__("" : : : "memory");
320 // An x86 store acts as a release barrier.
321#endif
322 *ptr = value;
323}
324
325
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000326const char* OS::LocalTimezone(double time) {
327 if (isnan(time)) return "";
328 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
329 struct tm* t = localtime(&tv);
330 if (NULL == t) return "";
331 return t->tm_zone;
332}
333
334
335double OS::LocalTimeOffset() {
336 time_t tv = time(NULL);
337 struct tm* t = localtime(&tv);
338 // tm_gmtoff includes any daylight savings offset, so subtract it.
339 return static_cast<double>(t->tm_gmtoff * msPerSecond -
340 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
341}
342
343
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000344// We keep the lowest and highest addresses mapped as a quick way of
345// determining that pointers are outside the heap (used mostly in assertions
346// and verification). The estimate is conservative, ie, not all addresses in
347// 'allocated' space are actually allocated to our heap. The range is
348// [lowest, highest), inclusive on the low and and exclusive on the high end.
349static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
350static void* highest_ever_allocated = reinterpret_cast<void*>(0);
351
352
353static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000354 ASSERT(limit_mutex != NULL);
355 ScopedLock lock(limit_mutex);
356
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000357 lowest_ever_allocated = Min(lowest_ever_allocated, address);
358 highest_ever_allocated =
359 Max(highest_ever_allocated,
360 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
361}
362
363
364bool OS::IsOutsideAllocatedSpace(void* address) {
365 return address < lowest_ever_allocated || address >= highest_ever_allocated;
366}
367
368
369size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000370 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000371}
372
373
kasper.lund7276f142008-07-30 08:49:36 +0000374void* OS::Allocate(const size_t requested,
375 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000376 bool is_executable) {
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000377 // TODO(805): Port randomization of allocated executable memory to Linux.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000378 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000379 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000380 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000381 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000382 LOG(i::Isolate::Current(),
383 StringEvent("OS::Allocate", "mmap failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000384 return NULL;
385 }
386 *allocated = msize;
387 UpdateAllocatedSpaceLimits(mbase, msize);
388 return mbase;
389}
390
391
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000392void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000394 int result = munmap(address, size);
395 USE(result);
396 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000397}
398
399
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000400#ifdef ENABLE_HEAP_PROTECTION
401
402void OS::Protect(void* address, size_t size) {
403 // TODO(1240712): mprotect has a return value which is ignored here.
404 mprotect(address, size, PROT_READ);
405}
406
407
408void OS::Unprotect(void* address, size_t size, bool is_executable) {
409 // TODO(1240712): mprotect has a return value which is ignored here.
410 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
411 mprotect(address, size, prot);
412}
413
414#endif
415
416
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000417void OS::Sleep(int milliseconds) {
418 unsigned int ms = static_cast<unsigned int>(milliseconds);
419 usleep(1000 * ms);
420}
421
422
423void OS::Abort() {
424 // Redirect to std abort to signal abnormal program termination.
425 abort();
426}
427
428
kasper.lund7276f142008-07-30 08:49:36 +0000429void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000430// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
431// which is the architecture of generated code).
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000432#if (defined(__arm__) || defined(__thumb__))
433# if defined(CAN_USE_ARMV5_INSTRUCTIONS)
kasper.lund7276f142008-07-30 08:49:36 +0000434 asm("bkpt 0");
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000435# endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000436#elif defined(__mips__)
437 asm("break");
kasper.lund7276f142008-07-30 08:49:36 +0000438#else
439 asm("int $3");
440#endif
441}
442
443
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000444class PosixMemoryMappedFile : public OS::MemoryMappedFile {
445 public:
446 PosixMemoryMappedFile(FILE* file, void* memory, int size)
447 : file_(file), memory_(memory), size_(size) { }
448 virtual ~PosixMemoryMappedFile();
449 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000450 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000451 private:
452 FILE* file_;
453 void* memory_;
454 int size_;
455};
456
457
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000458OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000459 FILE* file = fopen(name, "r+");
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000460 if (file == NULL) return NULL;
461
462 fseek(file, 0, SEEK_END);
463 int size = ftell(file);
464
465 void* memory =
466 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
467 return new PosixMemoryMappedFile(file, memory, size);
468}
469
470
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
472 void* initial) {
473 FILE* file = fopen(name, "w+");
474 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000475 int result = fwrite(initial, size, 1, file);
476 if (result < 1) {
477 fclose(file);
478 return NULL;
479 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480 void* memory =
481 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
482 return new PosixMemoryMappedFile(file, memory, size);
483}
484
485
486PosixMemoryMappedFile::~PosixMemoryMappedFile() {
487 if (memory_) munmap(memory_, size_);
488 fclose(file_);
489}
490
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000491
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492void OS::LogSharedLibraryAddresses() {
493#ifdef ENABLE_LOGGING_AND_PROFILING
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000494 // This function assumes that the layout of the file is as follows:
495 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
496 // If we encounter an unexpected situation we abort scanning further entries.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000497 FILE* fp = fopen("/proc/self/maps", "r");
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000498 if (fp == NULL) return;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000499
500 // Allocate enough room to be able to store a full file name.
501 const int kLibNameLen = FILENAME_MAX + 1;
502 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
503
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000504 i::Isolate* isolate = ISOLATE;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000505 // This loop will terminate once the scanning hits an EOF.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000506 while (true) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000507 uintptr_t start, end;
508 char attr_r, attr_w, attr_x, attr_p;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000509 // Parse the addresses and permission bits at the beginning of the line.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000510 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
511 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 +0000512
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000513 int c;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000514 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
515 // Found a read-only executable entry. Skip characters until we reach
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000516 // the beginning of the filename or the end of the line.
517 do {
518 c = getc(fp);
519 } while ((c != EOF) && (c != '\n') && (c != '/'));
520 if (c == EOF) break; // EOF: Was unexpected, just exit.
521
522 // Process the filename if found.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000523 if (c == '/') {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000524 ungetc(c, fp); // Push the '/' back into the stream to be read below.
525
526 // Read to the end of the line. Exit if the read fails.
527 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
528
529 // Drop the newline character read by fgets. We do not need to check
530 // for a zero-length string because we know that we at least read the
531 // '/' character.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000532 lib_name[strlen(lib_name) - 1] = '\0';
533 } else {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000534 // No library name found, just record the raw address range.
535 snprintf(lib_name, kLibNameLen,
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000536 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
537 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000538 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000539 } else {
540 // Entry not describing executable data. Skip to end of line to setup
541 // reading the next entry.
542 do {
543 c = getc(fp);
544 } while ((c != EOF) && (c != '\n'));
545 if (c == EOF) break;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000546 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000547 }
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000548 free(lib_name);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000549 fclose(fp);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000550#endif
551}
552
553
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000554static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
555
556
557void OS::SignalCodeMovingGC() {
558#ifdef ENABLE_LOGGING_AND_PROFILING
559 // Support for ll_prof.py.
560 //
561 // The Linux profiler built into the kernel logs all mmap's with
562 // PROT_EXEC so that analysis tools can properly attribute ticks. We
563 // do a mmap with a name known by ll_prof.py and immediately munmap
564 // it. This injects a GC marker into the stream of events generated
565 // by the kernel and allows us to synchronize V8 code log and the
566 // kernel log.
567 int size = sysconf(_SC_PAGESIZE);
568 FILE* f = fopen(kGCFakeMmap, "w+");
569 void* addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE,
570 fileno(f), 0);
571 ASSERT(addr != MAP_FAILED);
572 munmap(addr, size);
573 fclose(f);
574#endif
575}
576
577
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000578int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000579 // backtrace is a glibc extension.
580#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000581 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000582 ScopedVector<void*> addresses(frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000583
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000584 int frames_count = backtrace(addresses.start(), frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000586 char** symbols = backtrace_symbols(addresses.start(), frames_count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000587 if (symbols == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000588 return kStackWalkError;
589 }
590
591 for (int i = 0; i < frames_count; i++) {
592 frames[i].address = addresses[i];
593 // Format a text representation of the frame based on the information
594 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000595 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
596 "%s",
597 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598 // Make sure line termination is in place.
599 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
600 }
601
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602 free(symbols);
603
604 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000605#else // ndef __GLIBC__
606 return 0;
607#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000608}
609
610
611// Constants used for mmap.
612static const int kMmapFd = -1;
613static const int kMmapFdOffset = 0;
614
615
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000616VirtualMemory::VirtualMemory(size_t size) {
617 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000618 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
619 kMmapFd, kMmapFdOffset);
620 size_ = size;
621}
622
623
624VirtualMemory::~VirtualMemory() {
625 if (IsReserved()) {
626 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
627 }
628}
629
630
631bool VirtualMemory::IsReserved() {
632 return address_ != MAP_FAILED;
633}
634
635
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000636bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
637 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000638 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000639 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
640 kMmapFd, kMmapFdOffset)) {
641 return false;
642 }
643
644 UpdateAllocatedSpaceLimits(address, size);
645 return true;
646}
647
648
649bool VirtualMemory::Uncommit(void* address, size_t size) {
650 return mmap(address, size, PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000651 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000652 kMmapFd, kMmapFdOffset) != MAP_FAILED;
653}
654
655
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000656class Thread::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000657 public:
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000658 PlatformData() : thread_(kNoThread) {}
ager@chromium.org41826e72009-03-30 13:30:57 +0000659
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000660 pthread_t thread_; // Thread handle for pthread.
661};
662
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000663Thread::Thread(Isolate* isolate, const Options& options)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000664 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000665 isolate_(isolate),
666 stack_size_(options.stack_size) {
667 set_name(options.name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000668}
669
670
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000671Thread::Thread(Isolate* isolate, const char* name)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000672 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000673 isolate_(isolate),
674 stack_size_(0) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000675 set_name(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000676}
677
678
679Thread::~Thread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000680 delete data_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000681}
682
683
684static void* ThreadEntry(void* arg) {
685 Thread* thread = reinterpret_cast<Thread*>(arg);
686 // This is also initialized by the first argument to pthread_create() but we
687 // don't know which thread will run first (the original thread or the new
688 // one) so we initialize it here too.
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000689 prctl(PR_SET_NAME,
690 reinterpret_cast<unsigned long>(thread->name()), // NOLINT
691 0, 0, 0);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000692 thread->data()->thread_ = pthread_self();
693 ASSERT(thread->data()->thread_ != kNoThread);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000694 Thread::SetThreadLocal(Isolate::isolate_key(), thread->isolate());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000695 thread->Run();
696 return NULL;
697}
698
699
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000700void Thread::set_name(const char* name) {
701 strncpy(name_, name, sizeof(name_));
702 name_[sizeof(name_) - 1] = '\0';
703}
704
705
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000706void Thread::Start() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000707 pthread_attr_t* attr_ptr = NULL;
708 pthread_attr_t attr;
709 if (stack_size_ > 0) {
710 pthread_attr_init(&attr);
711 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
712 attr_ptr = &attr;
713 }
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000714 pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
715 ASSERT(data_->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000716}
717
718
719void Thread::Join() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000720 pthread_join(data_->thread_, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000721}
722
723
724Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
725 pthread_key_t key;
726 int result = pthread_key_create(&key, NULL);
727 USE(result);
728 ASSERT(result == 0);
729 return static_cast<LocalStorageKey>(key);
730}
731
732
733void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
734 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
735 int result = pthread_key_delete(pthread_key);
736 USE(result);
737 ASSERT(result == 0);
738}
739
740
741void* Thread::GetThreadLocal(LocalStorageKey key) {
742 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
743 return pthread_getspecific(pthread_key);
744}
745
746
747void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
748 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
749 pthread_setspecific(pthread_key, value);
750}
751
752
753void Thread::YieldCPU() {
754 sched_yield();
755}
756
757
758class LinuxMutex : public Mutex {
759 public:
760
761 LinuxMutex() {
762 pthread_mutexattr_t attrs;
763 int result = pthread_mutexattr_init(&attrs);
764 ASSERT(result == 0);
765 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
766 ASSERT(result == 0);
767 result = pthread_mutex_init(&mutex_, &attrs);
768 ASSERT(result == 0);
769 }
770
771 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
772
773 virtual int Lock() {
774 int result = pthread_mutex_lock(&mutex_);
775 return result;
776 }
777
778 virtual int Unlock() {
779 int result = pthread_mutex_unlock(&mutex_);
780 return result;
781 }
782
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000783 virtual bool TryLock() {
784 int result = pthread_mutex_trylock(&mutex_);
785 // Return false if the lock is busy and locking failed.
786 if (result == EBUSY) {
787 return false;
788 }
789 ASSERT(result == 0); // Verify no other errors.
790 return true;
791 }
792
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000793 private:
794 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
795};
796
797
798Mutex* OS::CreateMutex() {
799 return new LinuxMutex();
800}
801
802
803class LinuxSemaphore : public Semaphore {
804 public:
805 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
806 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
807
kasper.lund7276f142008-07-30 08:49:36 +0000808 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000809 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000810 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000811 private:
812 sem_t sem_;
813};
814
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000815
kasper.lund7276f142008-07-30 08:49:36 +0000816void LinuxSemaphore::Wait() {
817 while (true) {
818 int result = sem_wait(&sem_);
819 if (result == 0) return; // Successfully got semaphore.
820 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
821 }
822}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000823
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000824
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000825#ifndef TIMEVAL_TO_TIMESPEC
826#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
827 (ts)->tv_sec = (tv)->tv_sec; \
828 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
829} while (false)
830#endif
831
832
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000833bool LinuxSemaphore::Wait(int timeout) {
834 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000835
836 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000837 struct timeval delta;
838 delta.tv_usec = timeout % kOneSecondMicros;
839 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000840
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000841 struct timeval current_time;
842 // Get the current time.
843 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000844 return false;
845 }
846
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000847 // Calculate time for end of timeout.
848 struct timeval end_time;
849 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000850
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000851 struct timespec ts;
852 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000853 // Wait for semaphore signalled or timeout.
854 while (true) {
855 int result = sem_timedwait(&sem_, &ts);
856 if (result == 0) return true; // Successfully got semaphore.
857 if (result > 0) {
858 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
859 errno = result;
860 result = -1;
861 }
862 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
863 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
864 }
865}
866
867
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000868Semaphore* OS::CreateSemaphore(int count) {
869 return new LinuxSemaphore(count);
870}
871
ager@chromium.org381abbb2009-02-25 13:23:22 +0000872
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000873#ifdef ENABLE_LOGGING_AND_PROFILING
874
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000875#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
876// Android runs a fairly new Linux kernel, so signal info is there,
877// but the C library doesn't have the structs defined.
878
879struct sigcontext {
880 uint32_t trap_no;
881 uint32_t error_code;
882 uint32_t oldmask;
883 uint32_t gregs[16];
884 uint32_t arm_cpsr;
885 uint32_t fault_address;
886};
887typedef uint32_t __sigset_t;
888typedef struct sigcontext mcontext_t;
889typedef struct ucontext {
890 uint32_t uc_flags;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000891 struct ucontext* uc_link;
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000892 stack_t uc_stack;
893 mcontext_t uc_mcontext;
894 __sigset_t uc_sigmask;
895} ucontext_t;
896enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
897
898#endif
899
900
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000901static int GetThreadID() {
902 // Glibc doesn't provide a wrapper for gettid(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000903#if defined(ANDROID)
904 return syscall(__NR_gettid);
905#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000906 return syscall(SYS_gettid);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000907#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000908}
909
910
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000911static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.org5c838252010-02-19 08:53:10 +0000912#ifndef V8_HOST_ARCH_MIPS
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000913 USE(info);
914 if (signal != SIGPROF) return;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000915 Isolate* isolate = Isolate::UncheckedCurrent();
916 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
917 // We require a fully initialized and entered isolate.
918 return;
919 }
vitalyr@chromium.org0ec56d62011-04-15 22:22:08 +0000920 if (v8::Locker::IsActive() &&
921 !isolate->thread_manager()->IsLockedByCurrentThread()) {
922 return;
923 }
924
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000925 Sampler* sampler = isolate->logger()->sampler();
926 if (sampler == NULL || !sampler->IsActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000927
lrn@chromium.org25156de2010-04-06 13:10:27 +0000928 TickSample sample_obj;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000929 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
ager@chromium.org357bf652010-04-12 11:30:10 +0000930 if (sample == NULL) sample = &sample_obj;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000931
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000932 // Extracting the sample from the context is extremely machine dependent.
933 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
934 mcontext_t& mcontext = ucontext->uc_mcontext;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000935 sample->state = isolate->current_vm_state();
ager@chromium.org9085a012009-05-11 19:22:57 +0000936#if V8_HOST_ARCH_IA32
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000937 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
938 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
939 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000940#elif V8_HOST_ARCH_X64
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000941 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
942 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
943 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000944#elif V8_HOST_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000945// An undefined macro evaluates to 0, so this applies to Android's Bionic also.
946#if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000947 sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
948 sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
949 sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000950#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000951 sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
952 sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
953 sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000954#endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000955#elif V8_HOST_ARCH_MIPS
lrn@chromium.org7516f052011-03-30 08:52:27 +0000956 sample.pc = reinterpret_cast<Address>(mcontext.pc);
957 sample.sp = reinterpret_cast<Address>(mcontext.gregs[29]);
958 sample.fp = reinterpret_cast<Address>(mcontext.gregs[30]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000959#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000960 sampler->SampleStack(sample);
961 sampler->Tick(sample);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000962#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000963}
964
965
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000966class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000967 public:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000968 PlatformData() : vm_tid_(GetThreadID()) {}
969
970 int vm_tid() const { return vm_tid_; }
971
972 private:
973 const int vm_tid_;
974};
975
976
977class SignalSender : public Thread {
978 public:
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000979 enum SleepInterval {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000980 HALF_INTERVAL,
981 FULL_INTERVAL
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000982 };
983
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000984 explicit SignalSender(int interval)
985 : Thread(NULL, "SignalSender"),
lrn@chromium.org303ada72010-10-27 09:33:13 +0000986 vm_tgid_(getpid()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000987 interval_(interval) {}
988
989 static void AddActiveSampler(Sampler* sampler) {
990 ScopedLock lock(mutex_);
991 SamplerRegistry::AddActiveSampler(sampler);
992 if (instance_ == NULL) {
993 // Install a signal handler.
994 struct sigaction sa;
995 sa.sa_sigaction = ProfilerSignalHandler;
996 sigemptyset(&sa.sa_mask);
997 sa.sa_flags = SA_RESTART | SA_SIGINFO;
998 signal_handler_installed_ =
999 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
1000
1001 // Start a thread that sends SIGPROF signal to VM threads.
1002 instance_ = new SignalSender(sampler->interval());
1003 instance_->Start();
1004 } else {
1005 ASSERT(instance_->interval_ == sampler->interval());
1006 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001007 }
1008
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001009 static void RemoveActiveSampler(Sampler* sampler) {
1010 ScopedLock lock(mutex_);
1011 SamplerRegistry::RemoveActiveSampler(sampler);
1012 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
1013 RuntimeProfiler::WakeUpRuntimeProfilerThreadBeforeShutdown();
1014 instance_->Join();
1015 delete instance_;
1016 instance_ = NULL;
1017
1018 // Restore the old signal handler.
1019 if (signal_handler_installed_) {
1020 sigaction(SIGPROF, &old_signal_handler_, 0);
1021 signal_handler_installed_ = false;
1022 }
1023 }
1024 }
1025
1026 // Implement Thread::Run().
1027 virtual void Run() {
1028 SamplerRegistry::State state;
1029 while ((state = SamplerRegistry::GetState()) !=
1030 SamplerRegistry::HAS_NO_SAMPLERS) {
1031 bool cpu_profiling_enabled =
1032 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1033 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
1034 // When CPU profiling is enabled both JavaScript and C++ code is
1035 // profiled. We must not suspend.
1036 if (!cpu_profiling_enabled) {
1037 if (rate_limiter_.SuspendIfNecessary()) continue;
1038 }
1039 if (cpu_profiling_enabled && runtime_profiler_enabled) {
1040 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1041 return;
1042 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001043 Sleep(HALF_INTERVAL);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001044 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1045 return;
1046 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001047 Sleep(HALF_INTERVAL);
1048 } else {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001049 if (cpu_profiling_enabled) {
1050 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
1051 this)) {
1052 return;
1053 }
1054 }
1055 if (runtime_profiler_enabled) {
1056 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
1057 NULL)) {
1058 return;
1059 }
1060 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001061 Sleep(FULL_INTERVAL);
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +00001062 }
lrn@chromium.org303ada72010-10-27 09:33:13 +00001063 }
1064 }
1065
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001066 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
1067 if (!sampler->IsProfiling()) return;
1068 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
1069 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
1070 }
1071
1072 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1073 if (!sampler->isolate()->IsInitialized()) return;
1074 sampler->isolate()->runtime_profiler()->NotifyTick();
1075 }
1076
1077 void SendProfilingSignal(int tid) {
karlklose@chromium.org8f806e82011-03-07 14:06:08 +00001078 if (!signal_handler_installed_) return;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001079 // Glibc doesn't provide a wrapper for tgkill(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001080#if defined(ANDROID)
1081 syscall(__NR_tgkill, vm_tgid_, tid, SIGPROF);
1082#else
1083 syscall(SYS_tgkill, vm_tgid_, tid, SIGPROF);
1084#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001085 }
1086
1087 void Sleep(SleepInterval full_or_half) {
1088 // Convert ms to us and subtract 100 us to compensate delays
1089 // occuring during signal delivery.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001090 useconds_t interval = interval_ * 1000 - 100;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001091 if (full_or_half == HALF_INTERVAL) interval /= 2;
1092 int result = usleep(interval);
1093#ifdef DEBUG
1094 if (result != 0 && errno != EINTR) {
1095 fprintf(stderr,
1096 "SignalSender usleep error; interval = %u, errno = %d\n",
1097 interval,
1098 errno);
1099 ASSERT(result == 0 || errno == EINTR);
1100 }
1101#endif
1102 USE(result);
1103 }
1104
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001105 const int vm_tgid_;
1106 const int interval_;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001107 RuntimeProfilerRateLimiter rate_limiter_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001108
1109 // Protects the process wide state below.
1110 static Mutex* mutex_;
1111 static SignalSender* instance_;
1112 static bool signal_handler_installed_;
1113 static struct sigaction old_signal_handler_;
1114
1115 DISALLOW_COPY_AND_ASSIGN(SignalSender);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001116};
1117
1118
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001119Mutex* SignalSender::mutex_ = OS::CreateMutex();
1120SignalSender* SignalSender::instance_ = NULL;
1121struct sigaction SignalSender::old_signal_handler_;
1122bool SignalSender::signal_handler_installed_ = false;
lrn@chromium.org303ada72010-10-27 09:33:13 +00001123
1124
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001125Sampler::Sampler(Isolate* isolate, int interval)
1126 : isolate_(isolate),
1127 interval_(interval),
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001128 profiling_(false),
ager@chromium.orgbeb25712010-11-29 08:02:25 +00001129 active_(false),
1130 samples_taken_(0) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001131 data_ = new PlatformData;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001132}
1133
1134
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001135Sampler::~Sampler() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001136 ASSERT(!IsActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001137 delete data_;
1138}
1139
1140
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001141void Sampler::Start() {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001142 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001143 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001144 SignalSender::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001145}
1146
1147
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001148void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001149 ASSERT(IsActive());
1150 SignalSender::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001151 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001152}
1153
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001154#endif // ENABLE_LOGGING_AND_PROFILING
1155
1156} } // namespace v8::internal