blob: c735cebfcf593acce35b2427008063241be0fd1b [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
61namespace v8 { namespace internal {
62
63// 0 is never a valid thread id on Linux since tids and pids share a
64// name space and pid 0 is reserved (see man 2 kill).
65static const pthread_t kNoThread = (pthread_t) 0;
66
67
68double ceiling(double x) {
69 return ceil(x);
70}
71
72
73void OS::Setup() {
74 // Seed the random number generator.
ager@chromium.org9258b6b2008-09-11 09:11:10 +000075 // Convert the current time to a 64-bit integer first, before converting it
76 // to an unsigned. Going directly can cause an overflow and the seed to be
77 // set to all ones. The seed will be identical for different instances that
78 // call this setup code within the same millisecond.
79 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
80 srandom(static_cast<unsigned int>(seed));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081}
82
83
ager@chromium.org236ad962008-09-25 09:45:57 +000084double OS::nan_value() {
85 return NAN;
86}
87
88
89int OS::ActivationFrameAlignment() {
ager@chromium.org3a6061e2009-03-12 14:24:36 +000090 // Floating point code runs faster if the stack is 8-byte aligned.
91 return 8;
ager@chromium.org236ad962008-09-25 09:45:57 +000092}
93
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000094
95// We keep the lowest and highest addresses mapped as a quick way of
96// determining that pointers are outside the heap (used mostly in assertions
97// and verification). The estimate is conservative, ie, not all addresses in
98// 'allocated' space are actually allocated to our heap. The range is
99// [lowest, highest), inclusive on the low and and exclusive on the high end.
100static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
101static void* highest_ever_allocated = reinterpret_cast<void*>(0);
102
103
104static void UpdateAllocatedSpaceLimits(void* address, int size) {
105 lowest_ever_allocated = Min(lowest_ever_allocated, address);
106 highest_ever_allocated =
107 Max(highest_ever_allocated,
108 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
109}
110
111
112bool OS::IsOutsideAllocatedSpace(void* address) {
113 return address < lowest_ever_allocated || address >= highest_ever_allocated;
114}
115
116
117size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000118 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000119}
120
121
kasper.lund7276f142008-07-30 08:49:36 +0000122void* OS::Allocate(const size_t requested,
123 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000124 bool is_executable) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000125 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000126 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000127 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000128 if (mbase == MAP_FAILED) {
129 LOG(StringEvent("OS::Allocate", "mmap failed"));
130 return NULL;
131 }
132 *allocated = msize;
133 UpdateAllocatedSpaceLimits(mbase, msize);
134 return mbase;
135}
136
137
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000138void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139 // TODO(1240712): munmap has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000140 munmap(address, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000141}
142
143
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000144#ifdef ENABLE_HEAP_PROTECTION
145
146void OS::Protect(void* address, size_t size) {
147 // TODO(1240712): mprotect has a return value which is ignored here.
148 mprotect(address, size, PROT_READ);
149}
150
151
152void OS::Unprotect(void* address, size_t size, bool is_executable) {
153 // TODO(1240712): mprotect has a return value which is ignored here.
154 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
155 mprotect(address, size, prot);
156}
157
158#endif
159
160
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000161void OS::Sleep(int milliseconds) {
162 unsigned int ms = static_cast<unsigned int>(milliseconds);
163 usleep(1000 * ms);
164}
165
166
167void OS::Abort() {
168 // Redirect to std abort to signal abnormal program termination.
169 abort();
170}
171
172
kasper.lund7276f142008-07-30 08:49:36 +0000173void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000174// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
175// which is the architecture of generated code).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000176#if defined(__arm__) || defined(__thumb__)
kasper.lund7276f142008-07-30 08:49:36 +0000177 asm("bkpt 0");
178#else
179 asm("int $3");
180#endif
181}
182
183
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000184class PosixMemoryMappedFile : public OS::MemoryMappedFile {
185 public:
186 PosixMemoryMappedFile(FILE* file, void* memory, int size)
187 : file_(file), memory_(memory), size_(size) { }
188 virtual ~PosixMemoryMappedFile();
189 virtual void* memory() { return memory_; }
190 private:
191 FILE* file_;
192 void* memory_;
193 int size_;
194};
195
196
197OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
198 void* initial) {
199 FILE* file = fopen(name, "w+");
200 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000201 int result = fwrite(initial, size, 1, file);
202 if (result < 1) {
203 fclose(file);
204 return NULL;
205 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206 void* memory =
207 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
208 return new PosixMemoryMappedFile(file, memory, size);
209}
210
211
212PosixMemoryMappedFile::~PosixMemoryMappedFile() {
213 if (memory_) munmap(memory_, size_);
214 fclose(file_);
215}
216
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000217
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000218#ifdef ENABLE_LOGGING_AND_PROFILING
219static unsigned StringToLong(char* buffer) {
220 return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
221}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000222#endif
223
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000224
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000225void OS::LogSharedLibraryAddresses() {
226#ifdef ENABLE_LOGGING_AND_PROFILING
227 static const int MAP_LENGTH = 1024;
228 int fd = open("/proc/self/maps", O_RDONLY);
229 if (fd < 0) return;
230 while (true) {
231 char addr_buffer[11];
232 addr_buffer[0] = '0';
233 addr_buffer[1] = 'x';
234 addr_buffer[10] = 0;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000235 int result = read(fd, addr_buffer + 2, 8);
236 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000237 unsigned start = StringToLong(addr_buffer);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000238 result = read(fd, addr_buffer + 2, 1);
239 if (result < 1) break;
240 if (addr_buffer[2] != '-') break;
241 result = read(fd, addr_buffer + 2, 8);
242 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000243 unsigned end = StringToLong(addr_buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000244 char buffer[MAP_LENGTH];
245 int bytes_read = -1;
246 do {
247 bytes_read++;
ager@chromium.orgc27e4e72008-09-04 13:52:27 +0000248 if (bytes_read >= MAP_LENGTH - 1)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000249 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000250 result = read(fd, buffer + bytes_read, 1);
251 if (result < 1) break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252 } while (buffer[bytes_read] != '\n');
253 buffer[bytes_read] = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254 // Ignore mappings that are not executable.
255 if (buffer[3] != 'x') continue;
ager@chromium.org236ad962008-09-25 09:45:57 +0000256 char* start_of_path = index(buffer, '/');
257 // There may be no filename in this line. Skip to next.
258 if (start_of_path == NULL) continue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000259 buffer[bytes_read] = 0;
ager@chromium.org236ad962008-09-25 09:45:57 +0000260 LOG(SharedLibraryEvent(start_of_path, start, end));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000261 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000262 close(fd);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000263#endif
264}
265
266
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000267int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000268 // backtrace is a glibc extension.
269#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000270 int frames_size = frames.length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000271 void** addresses = NewArray<void*>(frames_size);
272
273 int frames_count = backtrace(addresses, frames_size);
274
275 char** symbols;
276 symbols = backtrace_symbols(addresses, frames_count);
277 if (symbols == NULL) {
278 DeleteArray(addresses);
279 return kStackWalkError;
280 }
281
282 for (int i = 0; i < frames_count; i++) {
283 frames[i].address = addresses[i];
284 // Format a text representation of the frame based on the information
285 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000286 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
287 "%s",
288 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000289 // Make sure line termination is in place.
290 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
291 }
292
293 DeleteArray(addresses);
294 free(symbols);
295
296 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000297#else // ndef __GLIBC__
298 return 0;
299#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000300}
301
302
303// Constants used for mmap.
304static const int kMmapFd = -1;
305static const int kMmapFdOffset = 0;
306
307
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000308VirtualMemory::VirtualMemory(size_t size) {
309 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000310 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
311 kMmapFd, kMmapFdOffset);
312 size_ = size;
313}
314
315
316VirtualMemory::~VirtualMemory() {
317 if (IsReserved()) {
318 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
319 }
320}
321
322
323bool VirtualMemory::IsReserved() {
324 return address_ != MAP_FAILED;
325}
326
327
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000328bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
329 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000330 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000331 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
332 kMmapFd, kMmapFdOffset)) {
333 return false;
334 }
335
336 UpdateAllocatedSpaceLimits(address, size);
337 return true;
338}
339
340
341bool VirtualMemory::Uncommit(void* address, size_t size) {
342 return mmap(address, size, PROT_NONE,
343 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
344 kMmapFd, kMmapFdOffset) != MAP_FAILED;
345}
346
347
348class ThreadHandle::PlatformData : public Malloced {
349 public:
350 explicit PlatformData(ThreadHandle::Kind kind) {
351 Initialize(kind);
352 }
353
354 void Initialize(ThreadHandle::Kind kind) {
355 switch (kind) {
356 case ThreadHandle::SELF: thread_ = pthread_self(); break;
357 case ThreadHandle::INVALID: thread_ = kNoThread; break;
358 }
359 }
ager@chromium.org41826e72009-03-30 13:30:57 +0000360
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000361 pthread_t thread_; // Thread handle for pthread.
362};
363
364
365ThreadHandle::ThreadHandle(Kind kind) {
366 data_ = new PlatformData(kind);
367}
368
369
370void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
371 data_->Initialize(kind);
372}
373
374
375ThreadHandle::~ThreadHandle() {
376 delete data_;
377}
378
379
380bool ThreadHandle::IsSelf() const {
381 return pthread_equal(data_->thread_, pthread_self());
382}
383
384
385bool ThreadHandle::IsValid() const {
386 return data_->thread_ != kNoThread;
387}
388
389
390Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
391}
392
393
394Thread::~Thread() {
395}
396
397
398static void* ThreadEntry(void* arg) {
399 Thread* thread = reinterpret_cast<Thread*>(arg);
400 // This is also initialized by the first argument to pthread_create() but we
401 // don't know which thread will run first (the original thread or the new
402 // one) so we initialize it here too.
403 thread->thread_handle_data()->thread_ = pthread_self();
404 ASSERT(thread->IsValid());
405 thread->Run();
406 return NULL;
407}
408
409
410void Thread::Start() {
411 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
412 ASSERT(IsValid());
413}
414
415
416void Thread::Join() {
417 pthread_join(thread_handle_data()->thread_, NULL);
418}
419
420
421Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
422 pthread_key_t key;
423 int result = pthread_key_create(&key, NULL);
424 USE(result);
425 ASSERT(result == 0);
426 return static_cast<LocalStorageKey>(key);
427}
428
429
430void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
431 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
432 int result = pthread_key_delete(pthread_key);
433 USE(result);
434 ASSERT(result == 0);
435}
436
437
438void* Thread::GetThreadLocal(LocalStorageKey key) {
439 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
440 return pthread_getspecific(pthread_key);
441}
442
443
444void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
445 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
446 pthread_setspecific(pthread_key, value);
447}
448
449
450void Thread::YieldCPU() {
451 sched_yield();
452}
453
454
455class LinuxMutex : public Mutex {
456 public:
457
458 LinuxMutex() {
459 pthread_mutexattr_t attrs;
460 int result = pthread_mutexattr_init(&attrs);
461 ASSERT(result == 0);
462 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
463 ASSERT(result == 0);
464 result = pthread_mutex_init(&mutex_, &attrs);
465 ASSERT(result == 0);
466 }
467
468 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
469
470 virtual int Lock() {
471 int result = pthread_mutex_lock(&mutex_);
472 return result;
473 }
474
475 virtual int Unlock() {
476 int result = pthread_mutex_unlock(&mutex_);
477 return result;
478 }
479
480 private:
481 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
482};
483
484
485Mutex* OS::CreateMutex() {
486 return new LinuxMutex();
487}
488
489
490class LinuxSemaphore : public Semaphore {
491 public:
492 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
493 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
494
kasper.lund7276f142008-07-30 08:49:36 +0000495 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000496 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000497 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000498 private:
499 sem_t sem_;
500};
501
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000502
kasper.lund7276f142008-07-30 08:49:36 +0000503void LinuxSemaphore::Wait() {
504 while (true) {
505 int result = sem_wait(&sem_);
506 if (result == 0) return; // Successfully got semaphore.
507 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
508 }
509}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000510
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000511
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000512#ifndef TIMEVAL_TO_TIMESPEC
513#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
514 (ts)->tv_sec = (tv)->tv_sec; \
515 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
516} while (false)
517#endif
518
519
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000520bool LinuxSemaphore::Wait(int timeout) {
521 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000522
523 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000524 struct timeval delta;
525 delta.tv_usec = timeout % kOneSecondMicros;
526 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000527
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000528 struct timeval current_time;
529 // Get the current time.
530 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000531 return false;
532 }
533
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000534 // Calculate time for end of timeout.
535 struct timeval end_time;
536 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000537
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000538 struct timespec ts;
539 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000540 // Wait for semaphore signalled or timeout.
541 while (true) {
542 int result = sem_timedwait(&sem_, &ts);
543 if (result == 0) return true; // Successfully got semaphore.
544 if (result > 0) {
545 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
546 errno = result;
547 result = -1;
548 }
549 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
550 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
551 }
552}
553
554
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555Semaphore* OS::CreateSemaphore(int count) {
556 return new LinuxSemaphore(count);
557}
558
ager@chromium.org381abbb2009-02-25 13:23:22 +0000559
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000560#ifdef ENABLE_LOGGING_AND_PROFILING
561
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000562static Sampler* active_sampler_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000564
565#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
566// Android runs a fairly new Linux kernel, so signal info is there,
567// but the C library doesn't have the structs defined.
568
569struct sigcontext {
570 uint32_t trap_no;
571 uint32_t error_code;
572 uint32_t oldmask;
573 uint32_t gregs[16];
574 uint32_t arm_cpsr;
575 uint32_t fault_address;
576};
577typedef uint32_t __sigset_t;
578typedef struct sigcontext mcontext_t;
579typedef struct ucontext {
580 uint32_t uc_flags;
581 struct ucontext *uc_link;
582 stack_t uc_stack;
583 mcontext_t uc_mcontext;
584 __sigset_t uc_sigmask;
585} ucontext_t;
586enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
587
588#endif
589
590
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000591static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
592 USE(info);
593 if (signal != SIGPROF) return;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000594 if (active_sampler_ == NULL) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000595
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000596 TickSample sample;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000597
598 // If profiling, we extract the current pc and sp.
599 if (active_sampler_->IsProfiling()) {
600 // Extracting the sample from the context is extremely machine dependent.
601 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
602 mcontext_t& mcontext = ucontext->uc_mcontext;
ager@chromium.org5ec48922009-05-05 07:25:34 +0000603#if defined(__arm__) || defined(__thumb__)
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000604 sample.pc = mcontext.gregs[R15];
605 sample.sp = mcontext.gregs[R13];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000606 sample.fp = mcontext.gregs[R11];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607#else
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000608 sample.pc = mcontext.gregs[REG_EIP];
609 sample.sp = mcontext.gregs[REG_ESP];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000610 sample.fp = mcontext.gregs[REG_EBP];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611#endif
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000612 }
613
614 // We always sample the VM state.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000615 sample.state = Logger::state();
616
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000617 active_sampler_->Tick(&sample);
618}
619
620
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000621class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000622 public:
623 PlatformData() {
624 signal_handler_installed_ = false;
625 }
626
627 bool signal_handler_installed_;
628 struct sigaction old_signal_handler_;
629 struct itimerval old_timer_value_;
630};
631
632
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000633Sampler::Sampler(int interval, bool profiling)
634 : interval_(interval), profiling_(profiling), active_(false) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000635 data_ = new PlatformData();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000636}
637
638
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000639Sampler::~Sampler() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000640 delete data_;
641}
642
643
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000644void Sampler::Start() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000645 // There can only be one active sampler at the time on POSIX
646 // platforms.
647 if (active_sampler_ != NULL) return;
648
649 // Request profiling signals.
650 struct sigaction sa;
651 sa.sa_sigaction = ProfilerSignalHandler;
652 sigemptyset(&sa.sa_mask);
653 sa.sa_flags = SA_SIGINFO;
654 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
655 data_->signal_handler_installed_ = true;
656
657 // Set the itimer to generate a tick for each interval.
658 itimerval itimer;
659 itimer.it_interval.tv_sec = interval_ / 1000;
660 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
661 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
662 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
663 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
664
665 // Set this sampler as the active sampler.
666 active_sampler_ = this;
667 active_ = true;
668}
669
670
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000671void Sampler::Stop() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000672 // Restore old signal handler
673 if (data_->signal_handler_installed_) {
674 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
675 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
676 data_->signal_handler_installed_ = false;
677 }
678
679 // This sampler is no longer the active sampler.
680 active_sampler_ = NULL;
681 active_ = false;
682}
683
684#endif // ENABLE_LOGGING_AND_PROFILING
685
686} } // namespace v8::internal