blob: b152dae9a61ec7ecbf4dd7762cbd6c236ba82c58 [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() {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000133 return 0; // Linux runs on anything.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000134}
135
136
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000137#ifdef __arm__
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000138static bool CPUInfoContainsString(const char * search_string) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000139 const char* file_name = "/proc/cpuinfo";
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000140 // This is written as a straight shot one pass parser
141 // and not using STL string and ifstream because,
142 // on Linux, it's reading from a (non-mmap-able)
143 // character special device.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000144 FILE* f = NULL;
145 const char* what = search_string;
146
147 if (NULL == (f = fopen(file_name, "r")))
148 return false;
149
150 int k;
151 while (EOF != (k = fgetc(f))) {
152 if (k == *what) {
153 ++what;
154 while ((*what != '\0') && (*what == fgetc(f))) {
155 ++what;
156 }
157 if (*what == '\0') {
158 fclose(f);
159 return true;
160 } else {
161 what = search_string;
162 }
163 }
164 }
165 fclose(f);
166
167 // Did not find string in the proc file.
168 return false;
169}
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000170
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000171
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000172bool OS::ArmCpuHasFeature(CpuFeature feature) {
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000173 const char* search_string = NULL;
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000174 // Simple detection of VFP at runtime for Linux.
175 // It is based on /proc/cpuinfo, which reveals hardware configuration
176 // to user-space applications. According to ARM (mid 2009), no similar
177 // facility is universally available on the ARM architectures,
178 // so it's up to individual OSes to provide such.
179 switch (feature) {
180 case VFP3:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000181 search_string = "vfpv3";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000182 break;
183 case ARMv7:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000184 search_string = "ARMv7";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000185 break;
186 default:
187 UNREACHABLE();
188 }
189
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000190 if (CPUInfoContainsString(search_string)) {
191 return true;
192 }
193
194 if (feature == VFP3) {
195 // Some old kernels will report vfp not vfpv3. Here we make a last attempt
196 // to detect vfpv3 by checking for vfp *and* neon, since neon is only
197 // available on architectures with vfpv3.
198 // Checking neon on its own is not enough as it is possible to have neon
199 // without vfp.
200 if (CPUInfoContainsString("vfp") && CPUInfoContainsString("neon")) {
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000201 return true;
202 }
203 }
204
205 return false;
206}
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000207
208
209// Simple helper function to detect whether the C code is compiled with
210// option -mfloat-abi=hard. The register d0 is loaded with 1.0 and the register
211// pair r0, r1 is loaded with 0.0. If -mfloat-abi=hard is pased to GCC then
212// calling this will return 1.0 and otherwise 0.0.
213static void ArmUsingHardFloatHelper() {
214 asm("mov r0, #0");
215#if defined(__VFP_FP__) && !defined(__SOFTFP__)
216 // Load 0x3ff00000 into r1 using instructions available in both ARM
217 // and Thumb mode.
218 asm("mov r1, #3");
219 asm("mov r2, #255");
220 asm("lsl r1, r1, #8");
221 asm("orr r1, r1, r2");
lrn@chromium.org1c092762011-05-09 09:42:16 +0000222 asm("lsl r1, r1, #20");
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000223 // For vmov d0, r0, r1 use ARM mode.
224#ifdef __thumb__
225 asm volatile(
226 "@ Enter ARM Mode \n\t"
227 " adr r3, 1f \n\t"
228 " bx r3 \n\t"
229 " .ALIGN 4 \n\t"
230 " .ARM \n"
231 "1: vmov d0, r0, r1 \n\t"
232 "@ Enter THUMB Mode\n\t"
233 " adr r3, 2f+1 \n\t"
234 " bx r3 \n\t"
235 " .THUMB \n"
236 "2: \n\t");
237#else
238 asm("vmov d0, r0, r1");
239#endif // __thumb__
240#endif // defined(__VFP_FP__) && !defined(__SOFTFP__)
241 asm("mov r1, #0");
242}
243
244
245bool OS::ArmUsingHardFloat() {
246 // Cast helper function from returning void to returning double.
247 typedef double (*F)();
248 F f = FUNCTION_CAST<F>(FUNCTION_ADDR(ArmUsingHardFloatHelper));
249 return f() == 1.0;
250}
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000251#endif // def __arm__
252
253
lrn@chromium.org7516f052011-03-30 08:52:27 +0000254#ifdef __mips__
255bool OS::MipsCpuHasFeature(CpuFeature feature) {
256 const char* search_string = NULL;
257 const char* file_name = "/proc/cpuinfo";
258 // Simple detection of FPU at runtime for Linux.
259 // It is based on /proc/cpuinfo, which reveals hardware configuration
260 // to user-space applications. According to MIPS (early 2010), no similar
261 // facility is universally available on the MIPS architectures,
262 // so it's up to individual OSes to provide such.
263 //
264 // This is written as a straight shot one pass parser
265 // and not using STL string and ifstream because,
266 // on Linux, it's reading from a (non-mmap-able)
267 // character special device.
268
269 switch (feature) {
270 case FPU:
271 search_string = "FPU";
272 break;
273 default:
274 UNREACHABLE();
275 }
276
277 FILE* f = NULL;
278 const char* what = search_string;
279
280 if (NULL == (f = fopen(file_name, "r")))
281 return false;
282
283 int k;
284 while (EOF != (k = fgetc(f))) {
285 if (k == *what) {
286 ++what;
287 while ((*what != '\0') && (*what == fgetc(f))) {
288 ++what;
289 }
290 if (*what == '\0') {
291 fclose(f);
292 return true;
293 } else {
294 what = search_string;
295 }
296 }
297 }
298 fclose(f);
299
300 // Did not find string in the proc file.
301 return false;
302}
303#endif // def __mips__
304
305
ager@chromium.org236ad962008-09-25 09:45:57 +0000306int OS::ActivationFrameAlignment() {
ager@chromium.orge2902be2009-06-08 12:21:35 +0000307#ifdef V8_TARGET_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000308 // On EABI ARM targets this is required for fp correctness in the
309 // runtime system.
ager@chromium.org3a6061e2009-03-12 14:24:36 +0000310 return 8;
ager@chromium.org5c838252010-02-19 08:53:10 +0000311#elif V8_TARGET_ARCH_MIPS
312 return 8;
313#endif
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000314 // With gcc 4.4 the tree vectorization optimizer can generate code
ager@chromium.orge2902be2009-06-08 12:21:35 +0000315 // that requires 16 byte alignment such as movdqa on x86.
316 return 16;
ager@chromium.org236ad962008-09-25 09:45:57 +0000317}
318
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000319
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000320void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
lrn@chromium.org7516f052011-03-30 08:52:27 +0000321#if (defined(V8_TARGET_ARCH_ARM) && defined(__arm__)) || \
322 (defined(V8_TARGET_ARCH_MIPS) && defined(__mips__))
323 // Only use on ARM or MIPS hardware.
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000324 MemoryBarrier();
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000325#else
326 __asm__ __volatile__("" : : : "memory");
327 // An x86 store acts as a release barrier.
328#endif
329 *ptr = value;
330}
331
332
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000333const char* OS::LocalTimezone(double time) {
334 if (isnan(time)) return "";
335 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
336 struct tm* t = localtime(&tv);
337 if (NULL == t) return "";
338 return t->tm_zone;
339}
340
341
342double OS::LocalTimeOffset() {
343 time_t tv = time(NULL);
344 struct tm* t = localtime(&tv);
345 // tm_gmtoff includes any daylight savings offset, so subtract it.
346 return static_cast<double>(t->tm_gmtoff * msPerSecond -
347 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
348}
349
350
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000351// We keep the lowest and highest addresses mapped as a quick way of
352// determining that pointers are outside the heap (used mostly in assertions
353// and verification). The estimate is conservative, ie, not all addresses in
354// 'allocated' space are actually allocated to our heap. The range is
355// [lowest, highest), inclusive on the low and and exclusive on the high end.
356static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
357static void* highest_ever_allocated = reinterpret_cast<void*>(0);
358
359
360static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000361 ASSERT(limit_mutex != NULL);
362 ScopedLock lock(limit_mutex);
363
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000364 lowest_ever_allocated = Min(lowest_ever_allocated, address);
365 highest_ever_allocated =
366 Max(highest_ever_allocated,
367 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
368}
369
370
371bool OS::IsOutsideAllocatedSpace(void* address) {
372 return address < lowest_ever_allocated || address >= highest_ever_allocated;
373}
374
375
376size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000377 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000378}
379
380
kasper.lund7276f142008-07-30 08:49:36 +0000381void* OS::Allocate(const size_t requested,
382 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000383 bool is_executable) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000384 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000385 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
ricow@chromium.org9fa09672011-07-25 11:05:35 +0000386 void* addr = GetRandomMmapAddr();
387 void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000388 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000389 LOG(i::Isolate::Current(),
390 StringEvent("OS::Allocate", "mmap failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000391 return NULL;
392 }
393 *allocated = msize;
394 UpdateAllocatedSpaceLimits(mbase, msize);
395 return mbase;
396}
397
398
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000399void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000400 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000401 int result = munmap(address, size);
402 USE(result);
403 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000404}
405
406
407void OS::Sleep(int milliseconds) {
408 unsigned int ms = static_cast<unsigned int>(milliseconds);
409 usleep(1000 * ms);
410}
411
412
413void OS::Abort() {
414 // Redirect to std abort to signal abnormal program termination.
415 abort();
416}
417
418
kasper.lund7276f142008-07-30 08:49:36 +0000419void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000420// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
421// which is the architecture of generated code).
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000422#if (defined(__arm__) || defined(__thumb__))
423# if defined(CAN_USE_ARMV5_INSTRUCTIONS)
kasper.lund7276f142008-07-30 08:49:36 +0000424 asm("bkpt 0");
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000425# endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000426#elif defined(__mips__)
427 asm("break");
kasper.lund7276f142008-07-30 08:49:36 +0000428#else
429 asm("int $3");
430#endif
431}
432
433
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000434class PosixMemoryMappedFile : public OS::MemoryMappedFile {
435 public:
436 PosixMemoryMappedFile(FILE* file, void* memory, int size)
437 : file_(file), memory_(memory), size_(size) { }
438 virtual ~PosixMemoryMappedFile();
439 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000440 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000441 private:
442 FILE* file_;
443 void* memory_;
444 int size_;
445};
446
447
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000448OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000449 FILE* file = fopen(name, "r+");
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000450 if (file == NULL) return NULL;
451
452 fseek(file, 0, SEEK_END);
453 int size = ftell(file);
454
455 void* memory =
456 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
457 return new PosixMemoryMappedFile(file, memory, size);
458}
459
460
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
462 void* initial) {
463 FILE* file = fopen(name, "w+");
464 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000465 int result = fwrite(initial, size, 1, file);
466 if (result < 1) {
467 fclose(file);
468 return NULL;
469 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000470 void* memory =
471 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
472 return new PosixMemoryMappedFile(file, memory, size);
473}
474
475
476PosixMemoryMappedFile::~PosixMemoryMappedFile() {
477 if (memory_) munmap(memory_, size_);
478 fclose(file_);
479}
480
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000481
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482void OS::LogSharedLibraryAddresses() {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000483 // This function assumes that the layout of the file is as follows:
484 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
485 // If we encounter an unexpected situation we abort scanning further entries.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000486 FILE* fp = fopen("/proc/self/maps", "r");
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000487 if (fp == NULL) return;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000488
489 // Allocate enough room to be able to store a full file name.
490 const int kLibNameLen = FILENAME_MAX + 1;
491 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
492
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000493 i::Isolate* isolate = ISOLATE;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000494 // This loop will terminate once the scanning hits an EOF.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000495 while (true) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000496 uintptr_t start, end;
497 char attr_r, attr_w, attr_x, attr_p;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000498 // Parse the addresses and permission bits at the beginning of the line.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000499 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
500 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 +0000501
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000502 int c;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000503 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
504 // Found a read-only executable entry. Skip characters until we reach
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000505 // the beginning of the filename or the end of the line.
506 do {
507 c = getc(fp);
508 } while ((c != EOF) && (c != '\n') && (c != '/'));
509 if (c == EOF) break; // EOF: Was unexpected, just exit.
510
511 // Process the filename if found.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000512 if (c == '/') {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000513 ungetc(c, fp); // Push the '/' back into the stream to be read below.
514
515 // Read to the end of the line. Exit if the read fails.
516 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
517
518 // Drop the newline character read by fgets. We do not need to check
519 // for a zero-length string because we know that we at least read the
520 // '/' character.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000521 lib_name[strlen(lib_name) - 1] = '\0';
522 } else {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000523 // No library name found, just record the raw address range.
524 snprintf(lib_name, kLibNameLen,
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000525 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
526 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000527 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000528 } else {
529 // Entry not describing executable data. Skip to end of line to setup
530 // reading the next entry.
531 do {
532 c = getc(fp);
533 } while ((c != EOF) && (c != '\n'));
534 if (c == EOF) break;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000535 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000536 }
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000537 free(lib_name);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000538 fclose(fp);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000539}
540
541
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000542static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
543
544
545void OS::SignalCodeMovingGC() {
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000546 // Support for ll_prof.py.
547 //
548 // The Linux profiler built into the kernel logs all mmap's with
549 // PROT_EXEC so that analysis tools can properly attribute ticks. We
550 // do a mmap with a name known by ll_prof.py and immediately munmap
551 // it. This injects a GC marker into the stream of events generated
552 // by the kernel and allows us to synchronize V8 code log and the
553 // kernel log.
554 int size = sysconf(_SC_PAGESIZE);
555 FILE* f = fopen(kGCFakeMmap, "w+");
556 void* addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE,
557 fileno(f), 0);
558 ASSERT(addr != MAP_FAILED);
559 munmap(addr, size);
560 fclose(f);
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000561}
562
563
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000564int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000565 // backtrace is a glibc extension.
566#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000567 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000568 ScopedVector<void*> addresses(frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000569
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000570 int frames_count = backtrace(addresses.start(), frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000571
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000572 char** symbols = backtrace_symbols(addresses.start(), frames_count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000573 if (symbols == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000574 return kStackWalkError;
575 }
576
577 for (int i = 0; i < frames_count; i++) {
578 frames[i].address = addresses[i];
579 // Format a text representation of the frame based on the information
580 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000581 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
582 "%s",
583 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000584 // Make sure line termination is in place.
585 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
586 }
587
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000588 free(symbols);
589
590 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000591#else // ndef __GLIBC__
592 return 0;
593#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594}
595
596
597// Constants used for mmap.
598static const int kMmapFd = -1;
599static const int kMmapFdOffset = 0;
600
601
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000602VirtualMemory::VirtualMemory(size_t size) {
ricow@chromium.org9fa09672011-07-25 11:05:35 +0000603 address_ = mmap(GetRandomMmapAddr(), size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
605 kMmapFd, kMmapFdOffset);
606 size_ = size;
607}
608
609
610VirtualMemory::~VirtualMemory() {
611 if (IsReserved()) {
612 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
613 }
614}
615
616
617bool VirtualMemory::IsReserved() {
618 return address_ != MAP_FAILED;
619}
620
621
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000622bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
623 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000624 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
626 kMmapFd, kMmapFdOffset)) {
627 return false;
628 }
629
630 UpdateAllocatedSpaceLimits(address, size);
631 return true;
632}
633
634
635bool VirtualMemory::Uncommit(void* address, size_t size) {
636 return mmap(address, size, PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000637 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000638 kMmapFd, kMmapFdOffset) != MAP_FAILED;
639}
640
641
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000642class Thread::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000643 public:
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000644 PlatformData() : thread_(kNoThread) {}
ager@chromium.org41826e72009-03-30 13:30:57 +0000645
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000646 pthread_t thread_; // Thread handle for pthread.
647};
648
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000649Thread::Thread(const Options& options)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000650 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000651 stack_size_(options.stack_size) {
652 set_name(options.name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000653}
654
655
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000656Thread::Thread(const char* name)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000657 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000658 stack_size_(0) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000659 set_name(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000660}
661
662
663Thread::~Thread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000664 delete data_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000665}
666
667
668static void* ThreadEntry(void* arg) {
669 Thread* thread = reinterpret_cast<Thread*>(arg);
670 // This is also initialized by the first argument to pthread_create() but we
671 // don't know which thread will run first (the original thread or the new
672 // one) so we initialize it here too.
danno@chromium.orgb6451162011-08-17 14:33:23 +0000673#ifdef PR_SET_NAME
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000674 prctl(PR_SET_NAME,
675 reinterpret_cast<unsigned long>(thread->name()), // NOLINT
676 0, 0, 0);
danno@chromium.orgb6451162011-08-17 14:33:23 +0000677#endif
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000678 thread->data()->thread_ = pthread_self();
679 ASSERT(thread->data()->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000680 thread->Run();
681 return NULL;
682}
683
684
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000685void Thread::set_name(const char* name) {
686 strncpy(name_, name, sizeof(name_));
687 name_[sizeof(name_) - 1] = '\0';
688}
689
690
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000691void Thread::Start() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000692 pthread_attr_t* attr_ptr = NULL;
693 pthread_attr_t attr;
694 if (stack_size_ > 0) {
695 pthread_attr_init(&attr);
696 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
697 attr_ptr = &attr;
698 }
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000699 pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
700 ASSERT(data_->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000701}
702
703
704void Thread::Join() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000705 pthread_join(data_->thread_, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000706}
707
708
709Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
710 pthread_key_t key;
711 int result = pthread_key_create(&key, NULL);
712 USE(result);
713 ASSERT(result == 0);
714 return static_cast<LocalStorageKey>(key);
715}
716
717
718void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
719 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
720 int result = pthread_key_delete(pthread_key);
721 USE(result);
722 ASSERT(result == 0);
723}
724
725
726void* Thread::GetThreadLocal(LocalStorageKey key) {
727 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
728 return pthread_getspecific(pthread_key);
729}
730
731
732void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
733 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
734 pthread_setspecific(pthread_key, value);
735}
736
737
738void Thread::YieldCPU() {
739 sched_yield();
740}
741
742
743class LinuxMutex : public Mutex {
744 public:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000745 LinuxMutex() {
746 pthread_mutexattr_t attrs;
747 int result = pthread_mutexattr_init(&attrs);
748 ASSERT(result == 0);
749 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
750 ASSERT(result == 0);
751 result = pthread_mutex_init(&mutex_, &attrs);
752 ASSERT(result == 0);
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000753 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000754 }
755
756 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
757
758 virtual int Lock() {
759 int result = pthread_mutex_lock(&mutex_);
760 return result;
761 }
762
763 virtual int Unlock() {
764 int result = pthread_mutex_unlock(&mutex_);
765 return result;
766 }
767
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000768 virtual bool TryLock() {
769 int result = pthread_mutex_trylock(&mutex_);
770 // Return false if the lock is busy and locking failed.
771 if (result == EBUSY) {
772 return false;
773 }
774 ASSERT(result == 0); // Verify no other errors.
775 return true;
776 }
777
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000778 private:
779 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
780};
781
782
783Mutex* OS::CreateMutex() {
784 return new LinuxMutex();
785}
786
787
788class LinuxSemaphore : public Semaphore {
789 public:
790 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
791 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
792
kasper.lund7276f142008-07-30 08:49:36 +0000793 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000794 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000795 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000796 private:
797 sem_t sem_;
798};
799
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000800
kasper.lund7276f142008-07-30 08:49:36 +0000801void LinuxSemaphore::Wait() {
802 while (true) {
803 int result = sem_wait(&sem_);
804 if (result == 0) return; // Successfully got semaphore.
805 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
806 }
807}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000808
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000809
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000810#ifndef TIMEVAL_TO_TIMESPEC
811#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
812 (ts)->tv_sec = (tv)->tv_sec; \
813 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
814} while (false)
815#endif
816
817
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000818bool LinuxSemaphore::Wait(int timeout) {
819 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000820
821 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000822 struct timeval delta;
823 delta.tv_usec = timeout % kOneSecondMicros;
824 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000825
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000826 struct timeval current_time;
827 // Get the current time.
828 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000829 return false;
830 }
831
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000832 // Calculate time for end of timeout.
833 struct timeval end_time;
834 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000835
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000836 struct timespec ts;
837 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000838 // Wait for semaphore signalled or timeout.
839 while (true) {
840 int result = sem_timedwait(&sem_, &ts);
841 if (result == 0) return true; // Successfully got semaphore.
842 if (result > 0) {
843 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
844 errno = result;
845 result = -1;
846 }
847 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
848 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
849 }
850}
851
852
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000853Semaphore* OS::CreateSemaphore(int count) {
854 return new LinuxSemaphore(count);
855}
856
ager@chromium.org381abbb2009-02-25 13:23:22 +0000857
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000858#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
859// Android runs a fairly new Linux kernel, so signal info is there,
860// but the C library doesn't have the structs defined.
861
862struct sigcontext {
863 uint32_t trap_no;
864 uint32_t error_code;
865 uint32_t oldmask;
866 uint32_t gregs[16];
867 uint32_t arm_cpsr;
868 uint32_t fault_address;
869};
870typedef uint32_t __sigset_t;
871typedef struct sigcontext mcontext_t;
872typedef struct ucontext {
873 uint32_t uc_flags;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000874 struct ucontext* uc_link;
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000875 stack_t uc_stack;
876 mcontext_t uc_mcontext;
877 __sigset_t uc_sigmask;
878} ucontext_t;
879enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
880
881#endif
882
883
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000884static int GetThreadID() {
885 // Glibc doesn't provide a wrapper for gettid(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000886#if defined(ANDROID)
887 return syscall(__NR_gettid);
888#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000889 return syscall(SYS_gettid);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000890#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000891}
892
893
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000894static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.org5c838252010-02-19 08:53:10 +0000895#ifndef V8_HOST_ARCH_MIPS
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000896 USE(info);
897 if (signal != SIGPROF) return;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000898 Isolate* isolate = Isolate::UncheckedCurrent();
899 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
900 // We require a fully initialized and entered isolate.
901 return;
902 }
vitalyr@chromium.org0ec56d62011-04-15 22:22:08 +0000903 if (v8::Locker::IsActive() &&
904 !isolate->thread_manager()->IsLockedByCurrentThread()) {
905 return;
906 }
907
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000908 Sampler* sampler = isolate->logger()->sampler();
909 if (sampler == NULL || !sampler->IsActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000910
lrn@chromium.org25156de2010-04-06 13:10:27 +0000911 TickSample sample_obj;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000912 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
ager@chromium.org357bf652010-04-12 11:30:10 +0000913 if (sample == NULL) sample = &sample_obj;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000914
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000915 // Extracting the sample from the context is extremely machine dependent.
916 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
917 mcontext_t& mcontext = ucontext->uc_mcontext;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000918 sample->state = isolate->current_vm_state();
ager@chromium.org9085a012009-05-11 19:22:57 +0000919#if V8_HOST_ARCH_IA32
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000920 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
921 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
922 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000923#elif V8_HOST_ARCH_X64
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000924 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
925 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
926 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000927#elif V8_HOST_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000928// An undefined macro evaluates to 0, so this applies to Android's Bionic also.
929#if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000930 sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
931 sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
932 sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000933#else
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000934 sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
935 sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
936 sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000937#endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000938#elif V8_HOST_ARCH_MIPS
lrn@chromium.org7516f052011-03-30 08:52:27 +0000939 sample.pc = reinterpret_cast<Address>(mcontext.pc);
940 sample.sp = reinterpret_cast<Address>(mcontext.gregs[29]);
941 sample.fp = reinterpret_cast<Address>(mcontext.gregs[30]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000942#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000943 sampler->SampleStack(sample);
944 sampler->Tick(sample);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000945#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000946}
947
948
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000949class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950 public:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000951 PlatformData() : vm_tid_(GetThreadID()) {}
952
953 int vm_tid() const { return vm_tid_; }
954
955 private:
956 const int vm_tid_;
957};
958
959
960class SignalSender : public Thread {
961 public:
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000962 enum SleepInterval {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000963 HALF_INTERVAL,
964 FULL_INTERVAL
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000965 };
966
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000967 explicit SignalSender(int interval)
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000968 : Thread("SignalSender"),
lrn@chromium.org303ada72010-10-27 09:33:13 +0000969 vm_tgid_(getpid()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000970 interval_(interval) {}
971
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +0000972 static void InstallSignalHandler() {
973 struct sigaction sa;
974 sa.sa_sigaction = ProfilerSignalHandler;
975 sigemptyset(&sa.sa_mask);
976 sa.sa_flags = SA_RESTART | SA_SIGINFO;
977 signal_handler_installed_ =
978 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
979 }
980
981 static void RestoreSignalHandler() {
982 if (signal_handler_installed_) {
983 sigaction(SIGPROF, &old_signal_handler_, 0);
984 signal_handler_installed_ = false;
985 }
986 }
987
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000988 static void AddActiveSampler(Sampler* sampler) {
989 ScopedLock lock(mutex_);
990 SamplerRegistry::AddActiveSampler(sampler);
991 if (instance_ == NULL) {
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +0000992 // Start a thread that will send SIGPROF signal to VM threads,
993 // when CPU profiling will be enabled.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000994 instance_ = new SignalSender(sampler->interval());
995 instance_->Start();
996 } else {
997 ASSERT(instance_->interval_ == sampler->interval());
998 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000999 }
1000
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001001 static void RemoveActiveSampler(Sampler* sampler) {
1002 ScopedLock lock(mutex_);
1003 SamplerRegistry::RemoveActiveSampler(sampler);
1004 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00001005 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001006 delete instance_;
1007 instance_ = NULL;
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +00001008 RestoreSignalHandler();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001009 }
1010 }
1011
1012 // Implement Thread::Run().
1013 virtual void Run() {
1014 SamplerRegistry::State state;
1015 while ((state = SamplerRegistry::GetState()) !=
1016 SamplerRegistry::HAS_NO_SAMPLERS) {
1017 bool cpu_profiling_enabled =
1018 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1019 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
erik.corry@gmail.comd6076d92011-06-06 09:39:18 +00001020 if (cpu_profiling_enabled && !signal_handler_installed_) {
1021 InstallSignalHandler();
1022 } else if (!cpu_profiling_enabled && signal_handler_installed_) {
1023 RestoreSignalHandler();
1024 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001025 // When CPU profiling is enabled both JavaScript and C++ code is
1026 // profiled. We must not suspend.
1027 if (!cpu_profiling_enabled) {
1028 if (rate_limiter_.SuspendIfNecessary()) continue;
1029 }
1030 if (cpu_profiling_enabled && runtime_profiler_enabled) {
1031 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1032 return;
1033 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001034 Sleep(HALF_INTERVAL);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001035 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1036 return;
1037 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001038 Sleep(HALF_INTERVAL);
1039 } else {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001040 if (cpu_profiling_enabled) {
1041 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
1042 this)) {
1043 return;
1044 }
1045 }
1046 if (runtime_profiler_enabled) {
1047 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
1048 NULL)) {
1049 return;
1050 }
1051 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001052 Sleep(FULL_INTERVAL);
whesse@chromium.orgf0ac72d2010-11-08 12:47:26 +00001053 }
lrn@chromium.org303ada72010-10-27 09:33:13 +00001054 }
1055 }
1056
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001057 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
1058 if (!sampler->IsProfiling()) return;
1059 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
1060 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
1061 }
1062
1063 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1064 if (!sampler->isolate()->IsInitialized()) return;
1065 sampler->isolate()->runtime_profiler()->NotifyTick();
1066 }
1067
1068 void SendProfilingSignal(int tid) {
karlklose@chromium.org8f806e82011-03-07 14:06:08 +00001069 if (!signal_handler_installed_) return;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001070 // Glibc doesn't provide a wrapper for tgkill(2).
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001071#if defined(ANDROID)
1072 syscall(__NR_tgkill, vm_tgid_, tid, SIGPROF);
1073#else
1074 syscall(SYS_tgkill, vm_tgid_, tid, SIGPROF);
1075#endif
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001076 }
1077
1078 void Sleep(SleepInterval full_or_half) {
1079 // Convert ms to us and subtract 100 us to compensate delays
1080 // occuring during signal delivery.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001081 useconds_t interval = interval_ * 1000 - 100;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001082 if (full_or_half == HALF_INTERVAL) interval /= 2;
1083 int result = usleep(interval);
1084#ifdef DEBUG
1085 if (result != 0 && errno != EINTR) {
1086 fprintf(stderr,
1087 "SignalSender usleep error; interval = %u, errno = %d\n",
1088 interval,
1089 errno);
1090 ASSERT(result == 0 || errno == EINTR);
1091 }
1092#endif
1093 USE(result);
1094 }
1095
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001096 const int vm_tgid_;
1097 const int interval_;
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001098 RuntimeProfilerRateLimiter rate_limiter_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001099
1100 // Protects the process wide state below.
1101 static Mutex* mutex_;
1102 static SignalSender* instance_;
1103 static bool signal_handler_installed_;
1104 static struct sigaction old_signal_handler_;
1105
1106 DISALLOW_COPY_AND_ASSIGN(SignalSender);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001107};
1108
1109
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001110Mutex* SignalSender::mutex_ = OS::CreateMutex();
1111SignalSender* SignalSender::instance_ = NULL;
1112struct sigaction SignalSender::old_signal_handler_;
1113bool SignalSender::signal_handler_installed_ = false;
lrn@chromium.org303ada72010-10-27 09:33:13 +00001114
1115
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001116Sampler::Sampler(Isolate* isolate, int interval)
1117 : isolate_(isolate),
1118 interval_(interval),
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001119 profiling_(false),
ager@chromium.orgbeb25712010-11-29 08:02:25 +00001120 active_(false),
1121 samples_taken_(0) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001122 data_ = new PlatformData;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001123}
1124
1125
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001126Sampler::~Sampler() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001127 ASSERT(!IsActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001128 delete data_;
1129}
1130
1131
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001132void Sampler::Start() {
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001133 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001134 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001135 SignalSender::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001136}
1137
1138
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001139void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001140 ASSERT(IsActive());
1141 SignalSender::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +00001142 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001143}
1144
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001145
1146} } // namespace v8::internal