blob: f1cac0969fee4b91caa6b5b43dac179ed8d0bdba [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
84int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
85 struct rusage usage;
86
87 if (getrusage(RUSAGE_SELF, &usage) < 0) return -1;
88 *secs = usage.ru_utime.tv_sec;
89 *usecs = usage.ru_utime.tv_usec;
90 return 0;
91}
92
93
94double OS::TimeCurrentMillis() {
95 struct timeval tv;
96 if (gettimeofday(&tv, NULL) < 0) return 0.0;
97 return (static_cast<double>(tv.tv_sec) * 1000) +
98 (static_cast<double>(tv.tv_usec) / 1000);
99}
100
101
102int64_t OS::Ticks() {
103 // Linux's gettimeofday has microsecond resolution.
104 struct timeval tv;
105 if (gettimeofday(&tv, NULL) < 0)
106 return 0;
107 return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
108}
109
110
111char* OS::LocalTimezone(double time) {
112 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
113 struct tm* t = localtime(&tv);
114 return const_cast<char*>(t->tm_zone);
115}
116
117
118double OS::DaylightSavingsOffset(double time) {
119 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
120 struct tm* t = localtime(&tv);
kasper.lund7276f142008-07-30 08:49:36 +0000121 return t->tm_isdst > 0 ? 3600 * msPerSecond : 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000122}
123
124
125double OS::LocalTimeOffset() {
kasper.lund7276f142008-07-30 08:49:36 +0000126 time_t tv = time(NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000127 struct tm* t = localtime(&tv);
kasper.lund7276f142008-07-30 08:49:36 +0000128 // tm_gmtoff includes any daylight savings offset, so subtract it.
129 return static_cast<double>(t->tm_gmtoff * msPerSecond -
130 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000131}
132
133
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000134FILE* OS::FOpen(const char* path, const char* mode) {
135 return fopen(path, mode);
136}
137
138
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139void OS::Print(const char* format, ...) {
140 va_list args;
141 va_start(args, format);
142 VPrint(format, args);
143 va_end(args);
144}
145
146
147void OS::VPrint(const char* format, va_list args) {
148 vprintf(format, args);
149}
150
151
152void OS::PrintError(const char* format, ...) {
153 va_list args;
154 va_start(args, format);
155 VPrintError(format, args);
156 va_end(args);
157}
158
159
160void OS::VPrintError(const char* format, va_list args) {
161 vfprintf(stderr, format, args);
162}
163
164
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000165int OS::SNPrintF(Vector<char> str, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000166 va_list args;
167 va_start(args, format);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000168 int result = VSNPrintF(str, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000169 va_end(args);
170 return result;
171}
172
173
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000174int OS::VSNPrintF(Vector<char> str,
175 const char* format,
176 va_list args) {
177 int n = vsnprintf(str.start(), str.length(), format, args);
178 if (n < 0 || n >= str.length()) {
179 str[str.length() - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000180 return -1;
181 } else {
182 return n;
183 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000184}
185
186
ager@chromium.org381abbb2009-02-25 13:23:22 +0000187char* OS::StrChr(char* str, int c) {
188 return strchr(str, c);
189}
190
191
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000192void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
193 strncpy(dest.start(), src, n);
194}
195
196
ager@chromium.org236ad962008-09-25 09:45:57 +0000197double OS::nan_value() {
198 return NAN;
199}
200
201
202int OS::ActivationFrameAlignment() {
ager@chromium.org3a6061e2009-03-12 14:24:36 +0000203 // Floating point code runs faster if the stack is 8-byte aligned.
204 return 8;
ager@chromium.org236ad962008-09-25 09:45:57 +0000205}
206
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000207
208// We keep the lowest and highest addresses mapped as a quick way of
209// determining that pointers are outside the heap (used mostly in assertions
210// and verification). The estimate is conservative, ie, not all addresses in
211// 'allocated' space are actually allocated to our heap. The range is
212// [lowest, highest), inclusive on the low and and exclusive on the high end.
213static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
214static void* highest_ever_allocated = reinterpret_cast<void*>(0);
215
216
217static void UpdateAllocatedSpaceLimits(void* address, int size) {
218 lowest_ever_allocated = Min(lowest_ever_allocated, address);
219 highest_ever_allocated =
220 Max(highest_ever_allocated,
221 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
222}
223
224
225bool OS::IsOutsideAllocatedSpace(void* address) {
226 return address < lowest_ever_allocated || address >= highest_ever_allocated;
227}
228
229
230size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000231 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000232}
233
234
kasper.lund7276f142008-07-30 08:49:36 +0000235void* OS::Allocate(const size_t requested,
236 size_t* allocated,
237 bool executable) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000238 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasper.lund7276f142008-07-30 08:49:36 +0000239 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
240 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000241 if (mbase == MAP_FAILED) {
242 LOG(StringEvent("OS::Allocate", "mmap failed"));
243 return NULL;
244 }
245 *allocated = msize;
246 UpdateAllocatedSpaceLimits(mbase, msize);
247 return mbase;
248}
249
250
251void OS::Free(void* buf, const size_t length) {
252 // TODO(1240712): munmap has a return value which is ignored here.
253 munmap(buf, length);
254}
255
256
257void OS::Sleep(int milliseconds) {
258 unsigned int ms = static_cast<unsigned int>(milliseconds);
259 usleep(1000 * ms);
260}
261
262
263void OS::Abort() {
264 // Redirect to std abort to signal abnormal program termination.
265 abort();
266}
267
268
kasper.lund7276f142008-07-30 08:49:36 +0000269void OS::DebugBreak() {
270#if defined (__arm__) || defined(__thumb__)
271 asm("bkpt 0");
272#else
273 asm("int $3");
274#endif
275}
276
277
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000278class PosixMemoryMappedFile : public OS::MemoryMappedFile {
279 public:
280 PosixMemoryMappedFile(FILE* file, void* memory, int size)
281 : file_(file), memory_(memory), size_(size) { }
282 virtual ~PosixMemoryMappedFile();
283 virtual void* memory() { return memory_; }
284 private:
285 FILE* file_;
286 void* memory_;
287 int size_;
288};
289
290
291OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
292 void* initial) {
293 FILE* file = fopen(name, "w+");
294 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000295 int result = fwrite(initial, size, 1, file);
296 if (result < 1) {
297 fclose(file);
298 return NULL;
299 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000300 void* memory =
301 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
302 return new PosixMemoryMappedFile(file, memory, size);
303}
304
305
306PosixMemoryMappedFile::~PosixMemoryMappedFile() {
307 if (memory_) munmap(memory_, size_);
308 fclose(file_);
309}
310
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000311
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000312#ifdef ENABLE_LOGGING_AND_PROFILING
313static unsigned StringToLong(char* buffer) {
314 return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
315}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000316#endif
317
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000318
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000319void OS::LogSharedLibraryAddresses() {
320#ifdef ENABLE_LOGGING_AND_PROFILING
321 static const int MAP_LENGTH = 1024;
322 int fd = open("/proc/self/maps", O_RDONLY);
323 if (fd < 0) return;
324 while (true) {
325 char addr_buffer[11];
326 addr_buffer[0] = '0';
327 addr_buffer[1] = 'x';
328 addr_buffer[10] = 0;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000329 int result = read(fd, addr_buffer + 2, 8);
330 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000331 unsigned start = StringToLong(addr_buffer);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000332 result = read(fd, addr_buffer + 2, 1);
333 if (result < 1) break;
334 if (addr_buffer[2] != '-') break;
335 result = read(fd, addr_buffer + 2, 8);
336 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000337 unsigned end = StringToLong(addr_buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338 char buffer[MAP_LENGTH];
339 int bytes_read = -1;
340 do {
341 bytes_read++;
ager@chromium.orgc27e4e72008-09-04 13:52:27 +0000342 if (bytes_read >= MAP_LENGTH - 1)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000344 result = read(fd, buffer + bytes_read, 1);
345 if (result < 1) break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000346 } while (buffer[bytes_read] != '\n');
347 buffer[bytes_read] = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000348 // Ignore mappings that are not executable.
349 if (buffer[3] != 'x') continue;
ager@chromium.org236ad962008-09-25 09:45:57 +0000350 char* start_of_path = index(buffer, '/');
351 // There may be no filename in this line. Skip to next.
352 if (start_of_path == NULL) continue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000353 buffer[bytes_read] = 0;
ager@chromium.org236ad962008-09-25 09:45:57 +0000354 LOG(SharedLibraryEvent(start_of_path, start, end));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000356 close(fd);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000357#endif
358}
359
360
361int OS::StackWalk(OS::StackFrame* frames, int frames_size) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000362 // backtrace is a glibc extension.
363#ifdef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000364 void** addresses = NewArray<void*>(frames_size);
365
366 int frames_count = backtrace(addresses, frames_size);
367
368 char** symbols;
369 symbols = backtrace_symbols(addresses, frames_count);
370 if (symbols == NULL) {
371 DeleteArray(addresses);
372 return kStackWalkError;
373 }
374
375 for (int i = 0; i < frames_count; i++) {
376 frames[i].address = addresses[i];
377 // Format a text representation of the frame based on the information
378 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000379 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
380 "%s",
381 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000382 // Make sure line termination is in place.
383 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
384 }
385
386 DeleteArray(addresses);
387 free(symbols);
388
389 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000390#else // ndef __GLIBC__
391 return 0;
392#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393}
394
395
396// Constants used for mmap.
397static const int kMmapFd = -1;
398static const int kMmapFdOffset = 0;
399
400
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000401VirtualMemory::VirtualMemory(size_t size) {
402 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000403 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
404 kMmapFd, kMmapFdOffset);
405 size_ = size;
406}
407
408
409VirtualMemory::~VirtualMemory() {
410 if (IsReserved()) {
411 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
412 }
413}
414
415
416bool VirtualMemory::IsReserved() {
417 return address_ != MAP_FAILED;
418}
419
420
kasper.lund7276f142008-07-30 08:49:36 +0000421bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
422 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
423 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000424 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
425 kMmapFd, kMmapFdOffset)) {
426 return false;
427 }
428
429 UpdateAllocatedSpaceLimits(address, size);
430 return true;
431}
432
433
434bool VirtualMemory::Uncommit(void* address, size_t size) {
435 return mmap(address, size, PROT_NONE,
436 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
437 kMmapFd, kMmapFdOffset) != MAP_FAILED;
438}
439
440
441class ThreadHandle::PlatformData : public Malloced {
442 public:
443 explicit PlatformData(ThreadHandle::Kind kind) {
444 Initialize(kind);
445 }
446
447 void Initialize(ThreadHandle::Kind kind) {
448 switch (kind) {
449 case ThreadHandle::SELF: thread_ = pthread_self(); break;
450 case ThreadHandle::INVALID: thread_ = kNoThread; break;
451 }
452 }
453 pthread_t thread_; // Thread handle for pthread.
454};
455
456
457ThreadHandle::ThreadHandle(Kind kind) {
458 data_ = new PlatformData(kind);
459}
460
461
462void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
463 data_->Initialize(kind);
464}
465
466
467ThreadHandle::~ThreadHandle() {
468 delete data_;
469}
470
471
472bool ThreadHandle::IsSelf() const {
473 return pthread_equal(data_->thread_, pthread_self());
474}
475
476
477bool ThreadHandle::IsValid() const {
478 return data_->thread_ != kNoThread;
479}
480
481
482Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
483}
484
485
486Thread::~Thread() {
487}
488
489
490static void* ThreadEntry(void* arg) {
491 Thread* thread = reinterpret_cast<Thread*>(arg);
492 // This is also initialized by the first argument to pthread_create() but we
493 // don't know which thread will run first (the original thread or the new
494 // one) so we initialize it here too.
495 thread->thread_handle_data()->thread_ = pthread_self();
496 ASSERT(thread->IsValid());
497 thread->Run();
498 return NULL;
499}
500
501
502void Thread::Start() {
503 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
504 ASSERT(IsValid());
505}
506
507
508void Thread::Join() {
509 pthread_join(thread_handle_data()->thread_, NULL);
510}
511
512
513Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
514 pthread_key_t key;
515 int result = pthread_key_create(&key, NULL);
516 USE(result);
517 ASSERT(result == 0);
518 return static_cast<LocalStorageKey>(key);
519}
520
521
522void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
523 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
524 int result = pthread_key_delete(pthread_key);
525 USE(result);
526 ASSERT(result == 0);
527}
528
529
530void* Thread::GetThreadLocal(LocalStorageKey key) {
531 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
532 return pthread_getspecific(pthread_key);
533}
534
535
536void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
537 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
538 pthread_setspecific(pthread_key, value);
539}
540
541
542void Thread::YieldCPU() {
543 sched_yield();
544}
545
546
547class LinuxMutex : public Mutex {
548 public:
549
550 LinuxMutex() {
551 pthread_mutexattr_t attrs;
552 int result = pthread_mutexattr_init(&attrs);
553 ASSERT(result == 0);
554 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
555 ASSERT(result == 0);
556 result = pthread_mutex_init(&mutex_, &attrs);
557 ASSERT(result == 0);
558 }
559
560 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
561
562 virtual int Lock() {
563 int result = pthread_mutex_lock(&mutex_);
564 return result;
565 }
566
567 virtual int Unlock() {
568 int result = pthread_mutex_unlock(&mutex_);
569 return result;
570 }
571
572 private:
573 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
574};
575
576
577Mutex* OS::CreateMutex() {
578 return new LinuxMutex();
579}
580
581
582class LinuxSemaphore : public Semaphore {
583 public:
584 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
585 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
586
kasper.lund7276f142008-07-30 08:49:36 +0000587 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000588 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000590 private:
591 sem_t sem_;
592};
593
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000594
kasper.lund7276f142008-07-30 08:49:36 +0000595void LinuxSemaphore::Wait() {
596 while (true) {
597 int result = sem_wait(&sem_);
598 if (result == 0) return; // Successfully got semaphore.
599 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
600 }
601}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000603
604bool LinuxSemaphore::Wait(int timeout) {
605 const long kOneSecondMicros = 1000000; // NOLINT
606 const long kOneSecondNanos = 1000000000; // NOLINT
607
608 // Split timeout into second and nanosecond parts.
609 long nanos = (timeout % kOneSecondMicros) * 1000; // NOLINT
610 time_t secs = timeout / kOneSecondMicros;
611
612 // Get the current realtime clock.
613 struct timespec ts;
614 if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
615 return false;
616 }
617
618 // Calculate real time for end of timeout.
619 ts.tv_nsec += nanos;
620 if (ts.tv_nsec >= kOneSecondNanos) {
621 ts.tv_nsec -= kOneSecondNanos;
622 ts.tv_nsec++;
623 }
624 ts.tv_sec += secs;
625
626 // Wait for semaphore signalled or timeout.
627 while (true) {
628 int result = sem_timedwait(&sem_, &ts);
629 if (result == 0) return true; // Successfully got semaphore.
630 if (result > 0) {
631 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
632 errno = result;
633 result = -1;
634 }
635 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
636 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
637 }
638}
639
640
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000641Semaphore* OS::CreateSemaphore(int count) {
642 return new LinuxSemaphore(count);
643}
644
ager@chromium.org381abbb2009-02-25 13:23:22 +0000645
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000646#ifdef ENABLE_LOGGING_AND_PROFILING
647
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000648static Sampler* active_sampler_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000649
650static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000651 // Ucontext is a glibc extension - no profiling on Android at the moment.
652#ifdef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000653 USE(info);
654 if (signal != SIGPROF) return;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000655 if (active_sampler_ == NULL) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000656
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000657 TickSample sample;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000658
659 // If profiling, we extract the current pc and sp.
660 if (active_sampler_->IsProfiling()) {
661 // Extracting the sample from the context is extremely machine dependent.
662 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
663 mcontext_t& mcontext = ucontext->uc_mcontext;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000664#if defined (__arm__) || defined(__thumb__)
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000665 sample.pc = mcontext.gregs[R15];
666 sample.sp = mcontext.gregs[R13];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000667 sample.fp = mcontext.gregs[R11];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000668#else
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000669 sample.pc = mcontext.gregs[REG_EIP];
670 sample.sp = mcontext.gregs[REG_ESP];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000671 sample.fp = mcontext.gregs[REG_EBP];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000672#endif
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000673 }
674
675 // We always sample the VM state.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000676 sample.state = Logger::state();
677
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000678 active_sampler_->Tick(&sample);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000679#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000680}
681
682
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000683class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000684 public:
685 PlatformData() {
686 signal_handler_installed_ = false;
687 }
688
689 bool signal_handler_installed_;
690 struct sigaction old_signal_handler_;
691 struct itimerval old_timer_value_;
692};
693
694
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000695Sampler::Sampler(int interval, bool profiling)
696 : interval_(interval), profiling_(profiling), active_(false) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697 data_ = new PlatformData();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000698}
699
700
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000701Sampler::~Sampler() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000702 delete data_;
703}
704
705
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000706void Sampler::Start() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000707 // There can only be one active sampler at the time on POSIX
708 // platforms.
709 if (active_sampler_ != NULL) return;
710
711 // Request profiling signals.
712 struct sigaction sa;
713 sa.sa_sigaction = ProfilerSignalHandler;
714 sigemptyset(&sa.sa_mask);
715 sa.sa_flags = SA_SIGINFO;
716 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
717 data_->signal_handler_installed_ = true;
718
719 // Set the itimer to generate a tick for each interval.
720 itimerval itimer;
721 itimer.it_interval.tv_sec = interval_ / 1000;
722 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
723 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
724 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
725 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
726
727 // Set this sampler as the active sampler.
728 active_sampler_ = this;
729 active_ = true;
730}
731
732
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000733void Sampler::Stop() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000734 // Restore old signal handler
735 if (data_->signal_handler_installed_) {
736 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
737 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
738 data_->signal_handler_installed_ = false;
739 }
740
741 // This sampler is no longer the active sampler.
742 active_sampler_ = NULL;
743 active_ = false;
744}
745
746#endif // ENABLE_LOGGING_AND_PROFILING
747
748} } // namespace v8::internal