blob: 1b07f4d315e73d9e74a4511c71a823be6aa3453e [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000028// Platform specific code for Linux goes here. For the POSIX comaptible parts
29// the implementation is in platform-posix.cc.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000030
31#include <pthread.h>
32#include <semaphore.h>
33#include <signal.h>
34#include <sys/time.h>
35#include <sys/resource.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000036#include <sys/types.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include <stdlib.h>
38
39// Ubuntu Dapper requires memory pages to be marked as
40// executable. Otherwise, OS raises an exception when executing code
41// in that page.
42#include <sys/types.h> // mmap & munmap
ager@chromium.org236ad962008-09-25 09:45:57 +000043#include <sys/mman.h> // mmap & munmap
44#include <sys/stat.h> // open
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000045#include <fcntl.h> // open
46#include <unistd.h> // sysconf
47#ifdef __GLIBC__
ager@chromium.org236ad962008-09-25 09:45:57 +000048#include <execinfo.h> // backtrace, backtrace_symbols
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000049#endif // def __GLIBC__
ager@chromium.org236ad962008-09-25 09:45:57 +000050#include <strings.h> // index
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051#include <errno.h>
52#include <stdarg.h>
53
54#undef MAP_TYPE
55
56#include "v8.h"
57
58#include "platform.h"
59
60
kasperl@chromium.org71affb52009-05-26 05:44:31 +000061namespace v8 {
62namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063
64// 0 is never a valid thread id on Linux since tids and pids share a
65// name space and pid 0 is reserved (see man 2 kill).
66static const pthread_t kNoThread = (pthread_t) 0;
67
68
69double ceiling(double x) {
70 return ceil(x);
71}
72
73
74void OS::Setup() {
75 // Seed the random number generator.
ager@chromium.org9258b6b2008-09-11 09:11:10 +000076 // Convert the current time to a 64-bit integer first, before converting it
77 // to an unsigned. Going directly can cause an overflow and the seed to be
78 // set to all ones. The seed will be identical for different instances that
79 // call this setup code within the same millisecond.
80 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
81 srandom(static_cast<unsigned int>(seed));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000082}
83
84
ager@chromium.org236ad962008-09-25 09:45:57 +000085double OS::nan_value() {
86 return NAN;
87}
88
89
90int OS::ActivationFrameAlignment() {
ager@chromium.org3a6061e2009-03-12 14:24:36 +000091 // Floating point code runs faster if the stack is 8-byte aligned.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +000092 // On EABI ARM targets this is required for fp correctness in the
93 // runtime system.
ager@chromium.org3a6061e2009-03-12 14:24:36 +000094 return 8;
ager@chromium.org236ad962008-09-25 09:45:57 +000095}
96
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000097
98// We keep the lowest and highest addresses mapped as a quick way of
99// determining that pointers are outside the heap (used mostly in assertions
100// and verification). The estimate is conservative, ie, not all addresses in
101// 'allocated' space are actually allocated to our heap. The range is
102// [lowest, highest), inclusive on the low and and exclusive on the high end.
103static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
104static void* highest_ever_allocated = reinterpret_cast<void*>(0);
105
106
107static void UpdateAllocatedSpaceLimits(void* address, int size) {
108 lowest_ever_allocated = Min(lowest_ever_allocated, address);
109 highest_ever_allocated =
110 Max(highest_ever_allocated,
111 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
112}
113
114
115bool OS::IsOutsideAllocatedSpace(void* address) {
116 return address < lowest_ever_allocated || address >= highest_ever_allocated;
117}
118
119
120size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000121 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000122}
123
124
kasper.lund7276f142008-07-30 08:49:36 +0000125void* OS::Allocate(const size_t requested,
126 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000127 bool is_executable) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000128 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000129 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000130 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000131 if (mbase == MAP_FAILED) {
132 LOG(StringEvent("OS::Allocate", "mmap failed"));
133 return NULL;
134 }
135 *allocated = msize;
136 UpdateAllocatedSpaceLimits(mbase, msize);
137 return mbase;
138}
139
140
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000141void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000142 // TODO(1240712): munmap has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000143 munmap(address, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000144}
145
146
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000147#ifdef ENABLE_HEAP_PROTECTION
148
149void OS::Protect(void* address, size_t size) {
150 // TODO(1240712): mprotect has a return value which is ignored here.
151 mprotect(address, size, PROT_READ);
152}
153
154
155void OS::Unprotect(void* address, size_t size, bool is_executable) {
156 // TODO(1240712): mprotect has a return value which is ignored here.
157 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
158 mprotect(address, size, prot);
159}
160
161#endif
162
163
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000164void OS::Sleep(int milliseconds) {
165 unsigned int ms = static_cast<unsigned int>(milliseconds);
166 usleep(1000 * ms);
167}
168
169
170void OS::Abort() {
171 // Redirect to std abort to signal abnormal program termination.
172 abort();
173}
174
175
kasper.lund7276f142008-07-30 08:49:36 +0000176void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000177// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
178// which is the architecture of generated code).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000179#if defined(__arm__) || defined(__thumb__)
kasper.lund7276f142008-07-30 08:49:36 +0000180 asm("bkpt 0");
181#else
182 asm("int $3");
183#endif
184}
185
186
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000187class PosixMemoryMappedFile : public OS::MemoryMappedFile {
188 public:
189 PosixMemoryMappedFile(FILE* file, void* memory, int size)
190 : file_(file), memory_(memory), size_(size) { }
191 virtual ~PosixMemoryMappedFile();
192 virtual void* memory() { return memory_; }
193 private:
194 FILE* file_;
195 void* memory_;
196 int size_;
197};
198
199
200OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
201 void* initial) {
202 FILE* file = fopen(name, "w+");
203 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000204 int result = fwrite(initial, size, 1, file);
205 if (result < 1) {
206 fclose(file);
207 return NULL;
208 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000209 void* memory =
210 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
211 return new PosixMemoryMappedFile(file, memory, size);
212}
213
214
215PosixMemoryMappedFile::~PosixMemoryMappedFile() {
216 if (memory_) munmap(memory_, size_);
217 fclose(file_);
218}
219
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000220
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000221#ifdef ENABLE_LOGGING_AND_PROFILING
222static unsigned StringToLong(char* buffer) {
223 return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
224}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000225#endif
226
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000227
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228void OS::LogSharedLibraryAddresses() {
229#ifdef ENABLE_LOGGING_AND_PROFILING
230 static const int MAP_LENGTH = 1024;
231 int fd = open("/proc/self/maps", O_RDONLY);
232 if (fd < 0) return;
233 while (true) {
234 char addr_buffer[11];
235 addr_buffer[0] = '0';
236 addr_buffer[1] = 'x';
237 addr_buffer[10] = 0;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000238 int result = read(fd, addr_buffer + 2, 8);
239 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000240 unsigned start = StringToLong(addr_buffer);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000241 result = read(fd, addr_buffer + 2, 1);
242 if (result < 1) break;
243 if (addr_buffer[2] != '-') break;
244 result = read(fd, addr_buffer + 2, 8);
245 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000246 unsigned end = StringToLong(addr_buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000247 char buffer[MAP_LENGTH];
248 int bytes_read = -1;
249 do {
250 bytes_read++;
ager@chromium.orgc27e4e72008-09-04 13:52:27 +0000251 if (bytes_read >= MAP_LENGTH - 1)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000253 result = read(fd, buffer + bytes_read, 1);
254 if (result < 1) break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000255 } while (buffer[bytes_read] != '\n');
256 buffer[bytes_read] = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000257 // Ignore mappings that are not executable.
258 if (buffer[3] != 'x') continue;
ager@chromium.org236ad962008-09-25 09:45:57 +0000259 char* start_of_path = index(buffer, '/');
260 // There may be no filename in this line. Skip to next.
261 if (start_of_path == NULL) continue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000262 buffer[bytes_read] = 0;
ager@chromium.org236ad962008-09-25 09:45:57 +0000263 LOG(SharedLibraryEvent(start_of_path, start, end));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000264 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000265 close(fd);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000266#endif
267}
268
269
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000270int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000271 // backtrace is a glibc extension.
272#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000273 int frames_size = frames.length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000274 void** addresses = NewArray<void*>(frames_size);
275
276 int frames_count = backtrace(addresses, frames_size);
277
278 char** symbols;
279 symbols = backtrace_symbols(addresses, frames_count);
280 if (symbols == NULL) {
281 DeleteArray(addresses);
282 return kStackWalkError;
283 }
284
285 for (int i = 0; i < frames_count; i++) {
286 frames[i].address = addresses[i];
287 // Format a text representation of the frame based on the information
288 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000289 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
290 "%s",
291 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000292 // Make sure line termination is in place.
293 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
294 }
295
296 DeleteArray(addresses);
297 free(symbols);
298
299 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000300#else // ndef __GLIBC__
301 return 0;
302#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000303}
304
305
306// Constants used for mmap.
307static const int kMmapFd = -1;
308static const int kMmapFdOffset = 0;
309
310
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000311VirtualMemory::VirtualMemory(size_t size) {
312 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000313 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
314 kMmapFd, kMmapFdOffset);
315 size_ = size;
316}
317
318
319VirtualMemory::~VirtualMemory() {
320 if (IsReserved()) {
321 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
322 }
323}
324
325
326bool VirtualMemory::IsReserved() {
327 return address_ != MAP_FAILED;
328}
329
330
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000331bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
332 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000333 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
335 kMmapFd, kMmapFdOffset)) {
336 return false;
337 }
338
339 UpdateAllocatedSpaceLimits(address, size);
340 return true;
341}
342
343
344bool VirtualMemory::Uncommit(void* address, size_t size) {
345 return mmap(address, size, PROT_NONE,
346 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
347 kMmapFd, kMmapFdOffset) != MAP_FAILED;
348}
349
350
351class ThreadHandle::PlatformData : public Malloced {
352 public:
353 explicit PlatformData(ThreadHandle::Kind kind) {
354 Initialize(kind);
355 }
356
357 void Initialize(ThreadHandle::Kind kind) {
358 switch (kind) {
359 case ThreadHandle::SELF: thread_ = pthread_self(); break;
360 case ThreadHandle::INVALID: thread_ = kNoThread; break;
361 }
362 }
ager@chromium.org41826e72009-03-30 13:30:57 +0000363
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000364 pthread_t thread_; // Thread handle for pthread.
365};
366
367
368ThreadHandle::ThreadHandle(Kind kind) {
369 data_ = new PlatformData(kind);
370}
371
372
373void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
374 data_->Initialize(kind);
375}
376
377
378ThreadHandle::~ThreadHandle() {
379 delete data_;
380}
381
382
383bool ThreadHandle::IsSelf() const {
384 return pthread_equal(data_->thread_, pthread_self());
385}
386
387
388bool ThreadHandle::IsValid() const {
389 return data_->thread_ != kNoThread;
390}
391
392
393Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
394}
395
396
397Thread::~Thread() {
398}
399
400
401static void* ThreadEntry(void* arg) {
402 Thread* thread = reinterpret_cast<Thread*>(arg);
403 // This is also initialized by the first argument to pthread_create() but we
404 // don't know which thread will run first (the original thread or the new
405 // one) so we initialize it here too.
406 thread->thread_handle_data()->thread_ = pthread_self();
407 ASSERT(thread->IsValid());
408 thread->Run();
409 return NULL;
410}
411
412
413void Thread::Start() {
414 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
415 ASSERT(IsValid());
416}
417
418
419void Thread::Join() {
420 pthread_join(thread_handle_data()->thread_, NULL);
421}
422
423
424Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
425 pthread_key_t key;
426 int result = pthread_key_create(&key, NULL);
427 USE(result);
428 ASSERT(result == 0);
429 return static_cast<LocalStorageKey>(key);
430}
431
432
433void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
434 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
435 int result = pthread_key_delete(pthread_key);
436 USE(result);
437 ASSERT(result == 0);
438}
439
440
441void* Thread::GetThreadLocal(LocalStorageKey key) {
442 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
443 return pthread_getspecific(pthread_key);
444}
445
446
447void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
448 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
449 pthread_setspecific(pthread_key, value);
450}
451
452
453void Thread::YieldCPU() {
454 sched_yield();
455}
456
457
458class LinuxMutex : public Mutex {
459 public:
460
461 LinuxMutex() {
462 pthread_mutexattr_t attrs;
463 int result = pthread_mutexattr_init(&attrs);
464 ASSERT(result == 0);
465 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
466 ASSERT(result == 0);
467 result = pthread_mutex_init(&mutex_, &attrs);
468 ASSERT(result == 0);
469 }
470
471 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
472
473 virtual int Lock() {
474 int result = pthread_mutex_lock(&mutex_);
475 return result;
476 }
477
478 virtual int Unlock() {
479 int result = pthread_mutex_unlock(&mutex_);
480 return result;
481 }
482
483 private:
484 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
485};
486
487
488Mutex* OS::CreateMutex() {
489 return new LinuxMutex();
490}
491
492
493class LinuxSemaphore : public Semaphore {
494 public:
495 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
496 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
497
kasper.lund7276f142008-07-30 08:49:36 +0000498 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000499 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000501 private:
502 sem_t sem_;
503};
504
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000505
kasper.lund7276f142008-07-30 08:49:36 +0000506void LinuxSemaphore::Wait() {
507 while (true) {
508 int result = sem_wait(&sem_);
509 if (result == 0) return; // Successfully got semaphore.
510 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
511 }
512}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000513
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000514
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000515#ifndef TIMEVAL_TO_TIMESPEC
516#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
517 (ts)->tv_sec = (tv)->tv_sec; \
518 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
519} while (false)
520#endif
521
522
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000523bool LinuxSemaphore::Wait(int timeout) {
524 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000525
526 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000527 struct timeval delta;
528 delta.tv_usec = timeout % kOneSecondMicros;
529 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000530
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000531 struct timeval current_time;
532 // Get the current time.
533 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000534 return false;
535 }
536
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000537 // Calculate time for end of timeout.
538 struct timeval end_time;
539 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000540
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000541 struct timespec ts;
542 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000543 // Wait for semaphore signalled or timeout.
544 while (true) {
545 int result = sem_timedwait(&sem_, &ts);
546 if (result == 0) return true; // Successfully got semaphore.
547 if (result > 0) {
548 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
549 errno = result;
550 result = -1;
551 }
552 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
553 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
554 }
555}
556
557
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000558Semaphore* OS::CreateSemaphore(int count) {
559 return new LinuxSemaphore(count);
560}
561
ager@chromium.org381abbb2009-02-25 13:23:22 +0000562
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563#ifdef ENABLE_LOGGING_AND_PROFILING
564
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000565static Sampler* active_sampler_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000567
568#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
569// Android runs a fairly new Linux kernel, so signal info is there,
570// but the C library doesn't have the structs defined.
571
572struct sigcontext {
573 uint32_t trap_no;
574 uint32_t error_code;
575 uint32_t oldmask;
576 uint32_t gregs[16];
577 uint32_t arm_cpsr;
578 uint32_t fault_address;
579};
580typedef uint32_t __sigset_t;
581typedef struct sigcontext mcontext_t;
582typedef struct ucontext {
583 uint32_t uc_flags;
584 struct ucontext *uc_link;
585 stack_t uc_stack;
586 mcontext_t uc_mcontext;
587 __sigset_t uc_sigmask;
588} ucontext_t;
589enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
590
591#endif
592
593
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
595 USE(info);
596 if (signal != SIGPROF) return;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000597 if (active_sampler_ == NULL) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000599 TickSample sample;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000600
601 // If profiling, we extract the current pc and sp.
602 if (active_sampler_->IsProfiling()) {
603 // Extracting the sample from the context is extremely machine dependent.
604 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
605 mcontext_t& mcontext = ucontext->uc_mcontext;
ager@chromium.org9085a012009-05-11 19:22:57 +0000606#if V8_HOST_ARCH_IA32
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000607 sample.pc = mcontext.gregs[REG_EIP];
608 sample.sp = mcontext.gregs[REG_ESP];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000609 sample.fp = mcontext.gregs[REG_EBP];
ager@chromium.org9085a012009-05-11 19:22:57 +0000610#elif V8_HOST_ARCH_X64
611 sample.pc = mcontext.gregs[REG_RIP];
612 sample.sp = mcontext.gregs[REG_RSP];
613 sample.fp = mcontext.gregs[REG_RBP];
614#elif V8_HOST_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000615// An undefined macro evaluates to 0, so this applies to Android's Bionic also.
616#if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
ager@chromium.org9085a012009-05-11 19:22:57 +0000617 sample.pc = mcontext.gregs[R15];
618 sample.sp = mcontext.gregs[R13];
619 sample.fp = mcontext.gregs[R11];
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000620#else
621 sample.pc = mcontext.arm_pc;
622 sample.sp = mcontext.arm_sp;
623 sample.fp = mcontext.arm_fp;
624#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625#endif
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000626 }
627
628 // We always sample the VM state.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000629 sample.state = Logger::state();
630
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000631 active_sampler_->Tick(&sample);
632}
633
634
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000635class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000636 public:
637 PlatformData() {
638 signal_handler_installed_ = false;
639 }
640
641 bool signal_handler_installed_;
642 struct sigaction old_signal_handler_;
643 struct itimerval old_timer_value_;
644};
645
646
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000647Sampler::Sampler(int interval, bool profiling)
648 : interval_(interval), profiling_(profiling), active_(false) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000649 data_ = new PlatformData();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000650}
651
652
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000653Sampler::~Sampler() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000654 delete data_;
655}
656
657
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000658void Sampler::Start() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000659 // There can only be one active sampler at the time on POSIX
660 // platforms.
661 if (active_sampler_ != NULL) return;
662
663 // Request profiling signals.
664 struct sigaction sa;
665 sa.sa_sigaction = ProfilerSignalHandler;
666 sigemptyset(&sa.sa_mask);
667 sa.sa_flags = SA_SIGINFO;
668 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
669 data_->signal_handler_installed_ = true;
670
671 // Set the itimer to generate a tick for each interval.
672 itimerval itimer;
673 itimer.it_interval.tv_sec = interval_ / 1000;
674 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
675 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
676 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
677 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
678
679 // Set this sampler as the active sampler.
680 active_sampler_ = this;
681 active_ = true;
682}
683
684
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000685void Sampler::Stop() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000686 // Restore old signal handler
687 if (data_->signal_handler_installed_) {
688 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
689 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
690 data_->signal_handler_installed_ = false;
691 }
692
693 // This sampler is no longer the active sampler.
694 active_sampler_ = NULL;
695 active_ = false;
696}
697
698#endif // ENABLE_LOGGING_AND_PROFILING
699
700} } // namespace v8::internal