blob: 88b28c572d89c5b6cc765b9c0d3ab897b74e0402 [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,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000237 bool is_executable) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000238 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000239 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000240 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
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000251void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252 // TODO(1240712): munmap has a return value which is ignored here.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000253 munmap(address, size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254}
255
256
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000257#ifdef ENABLE_HEAP_PROTECTION
258
259void OS::Protect(void* address, size_t size) {
260 // TODO(1240712): mprotect has a return value which is ignored here.
261 mprotect(address, size, PROT_READ);
262}
263
264
265void OS::Unprotect(void* address, size_t size, bool is_executable) {
266 // TODO(1240712): mprotect has a return value which is ignored here.
267 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
268 mprotect(address, size, prot);
269}
270
271#endif
272
273
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000274void OS::Sleep(int milliseconds) {
275 unsigned int ms = static_cast<unsigned int>(milliseconds);
276 usleep(1000 * ms);
277}
278
279
280void OS::Abort() {
281 // Redirect to std abort to signal abnormal program termination.
282 abort();
283}
284
285
kasper.lund7276f142008-07-30 08:49:36 +0000286void OS::DebugBreak() {
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000287#if defined(__arm__) || defined(__thumb__)
kasper.lund7276f142008-07-30 08:49:36 +0000288 asm("bkpt 0");
289#else
290 asm("int $3");
291#endif
292}
293
294
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000295class PosixMemoryMappedFile : public OS::MemoryMappedFile {
296 public:
297 PosixMemoryMappedFile(FILE* file, void* memory, int size)
298 : file_(file), memory_(memory), size_(size) { }
299 virtual ~PosixMemoryMappedFile();
300 virtual void* memory() { return memory_; }
301 private:
302 FILE* file_;
303 void* memory_;
304 int size_;
305};
306
307
308OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
309 void* initial) {
310 FILE* file = fopen(name, "w+");
311 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000312 int result = fwrite(initial, size, 1, file);
313 if (result < 1) {
314 fclose(file);
315 return NULL;
316 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000317 void* memory =
318 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
319 return new PosixMemoryMappedFile(file, memory, size);
320}
321
322
323PosixMemoryMappedFile::~PosixMemoryMappedFile() {
324 if (memory_) munmap(memory_, size_);
325 fclose(file_);
326}
327
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000328
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000329#ifdef ENABLE_LOGGING_AND_PROFILING
330static unsigned StringToLong(char* buffer) {
331 return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
332}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333#endif
334
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000335
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336void OS::LogSharedLibraryAddresses() {
337#ifdef ENABLE_LOGGING_AND_PROFILING
338 static const int MAP_LENGTH = 1024;
339 int fd = open("/proc/self/maps", O_RDONLY);
340 if (fd < 0) return;
341 while (true) {
342 char addr_buffer[11];
343 addr_buffer[0] = '0';
344 addr_buffer[1] = 'x';
345 addr_buffer[10] = 0;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000346 int result = read(fd, addr_buffer + 2, 8);
347 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000348 unsigned start = StringToLong(addr_buffer);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000349 result = read(fd, addr_buffer + 2, 1);
350 if (result < 1) break;
351 if (addr_buffer[2] != '-') break;
352 result = read(fd, addr_buffer + 2, 8);
353 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000354 unsigned end = StringToLong(addr_buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 char buffer[MAP_LENGTH];
356 int bytes_read = -1;
357 do {
358 bytes_read++;
ager@chromium.orgc27e4e72008-09-04 13:52:27 +0000359 if (bytes_read >= MAP_LENGTH - 1)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000361 result = read(fd, buffer + bytes_read, 1);
362 if (result < 1) break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000363 } while (buffer[bytes_read] != '\n');
364 buffer[bytes_read] = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000365 // Ignore mappings that are not executable.
366 if (buffer[3] != 'x') continue;
ager@chromium.org236ad962008-09-25 09:45:57 +0000367 char* start_of_path = index(buffer, '/');
368 // There may be no filename in this line. Skip to next.
369 if (start_of_path == NULL) continue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000370 buffer[bytes_read] = 0;
ager@chromium.org236ad962008-09-25 09:45:57 +0000371 LOG(SharedLibraryEvent(start_of_path, start, end));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000372 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000373 close(fd);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000374#endif
375}
376
377
378int OS::StackWalk(OS::StackFrame* frames, int frames_size) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000379 // backtrace is a glibc extension.
380#ifdef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000381 void** addresses = NewArray<void*>(frames_size);
382
383 int frames_count = backtrace(addresses, frames_size);
384
385 char** symbols;
386 symbols = backtrace_symbols(addresses, frames_count);
387 if (symbols == NULL) {
388 DeleteArray(addresses);
389 return kStackWalkError;
390 }
391
392 for (int i = 0; i < frames_count; i++) {
393 frames[i].address = addresses[i];
394 // Format a text representation of the frame based on the information
395 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000396 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
397 "%s",
398 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000399 // Make sure line termination is in place.
400 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
401 }
402
403 DeleteArray(addresses);
404 free(symbols);
405
406 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000407#else // ndef __GLIBC__
408 return 0;
409#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410}
411
412
413// Constants used for mmap.
414static const int kMmapFd = -1;
415static const int kMmapFdOffset = 0;
416
417
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000418VirtualMemory::VirtualMemory(size_t size) {
419 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
421 kMmapFd, kMmapFdOffset);
422 size_ = size;
423}
424
425
426VirtualMemory::~VirtualMemory() {
427 if (IsReserved()) {
428 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
429 }
430}
431
432
433bool VirtualMemory::IsReserved() {
434 return address_ != MAP_FAILED;
435}
436
437
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000438bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
439 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000440 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000441 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
442 kMmapFd, kMmapFdOffset)) {
443 return false;
444 }
445
446 UpdateAllocatedSpaceLimits(address, size);
447 return true;
448}
449
450
451bool VirtualMemory::Uncommit(void* address, size_t size) {
452 return mmap(address, size, PROT_NONE,
453 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
454 kMmapFd, kMmapFdOffset) != MAP_FAILED;
455}
456
457
458class ThreadHandle::PlatformData : public Malloced {
459 public:
460 explicit PlatformData(ThreadHandle::Kind kind) {
461 Initialize(kind);
462 }
463
464 void Initialize(ThreadHandle::Kind kind) {
465 switch (kind) {
466 case ThreadHandle::SELF: thread_ = pthread_self(); break;
467 case ThreadHandle::INVALID: thread_ = kNoThread; break;
468 }
469 }
470 pthread_t thread_; // Thread handle for pthread.
471};
472
473
474ThreadHandle::ThreadHandle(Kind kind) {
475 data_ = new PlatformData(kind);
476}
477
478
479void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
480 data_->Initialize(kind);
481}
482
483
484ThreadHandle::~ThreadHandle() {
485 delete data_;
486}
487
488
489bool ThreadHandle::IsSelf() const {
490 return pthread_equal(data_->thread_, pthread_self());
491}
492
493
494bool ThreadHandle::IsValid() const {
495 return data_->thread_ != kNoThread;
496}
497
498
499Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
500}
501
502
503Thread::~Thread() {
504}
505
506
507static void* ThreadEntry(void* arg) {
508 Thread* thread = reinterpret_cast<Thread*>(arg);
509 // This is also initialized by the first argument to pthread_create() but we
510 // don't know which thread will run first (the original thread or the new
511 // one) so we initialize it here too.
512 thread->thread_handle_data()->thread_ = pthread_self();
513 ASSERT(thread->IsValid());
514 thread->Run();
515 return NULL;
516}
517
518
519void Thread::Start() {
520 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
521 ASSERT(IsValid());
522}
523
524
525void Thread::Join() {
526 pthread_join(thread_handle_data()->thread_, NULL);
527}
528
529
530Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
531 pthread_key_t key;
532 int result = pthread_key_create(&key, NULL);
533 USE(result);
534 ASSERT(result == 0);
535 return static_cast<LocalStorageKey>(key);
536}
537
538
539void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
540 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
541 int result = pthread_key_delete(pthread_key);
542 USE(result);
543 ASSERT(result == 0);
544}
545
546
547void* Thread::GetThreadLocal(LocalStorageKey key) {
548 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
549 return pthread_getspecific(pthread_key);
550}
551
552
553void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
554 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
555 pthread_setspecific(pthread_key, value);
556}
557
558
559void Thread::YieldCPU() {
560 sched_yield();
561}
562
563
564class LinuxMutex : public Mutex {
565 public:
566
567 LinuxMutex() {
568 pthread_mutexattr_t attrs;
569 int result = pthread_mutexattr_init(&attrs);
570 ASSERT(result == 0);
571 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
572 ASSERT(result == 0);
573 result = pthread_mutex_init(&mutex_, &attrs);
574 ASSERT(result == 0);
575 }
576
577 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
578
579 virtual int Lock() {
580 int result = pthread_mutex_lock(&mutex_);
581 return result;
582 }
583
584 virtual int Unlock() {
585 int result = pthread_mutex_unlock(&mutex_);
586 return result;
587 }
588
589 private:
590 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
591};
592
593
594Mutex* OS::CreateMutex() {
595 return new LinuxMutex();
596}
597
598
599class LinuxSemaphore : public Semaphore {
600 public:
601 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
602 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
603
kasper.lund7276f142008-07-30 08:49:36 +0000604 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000605 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000606 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607 private:
608 sem_t sem_;
609};
610
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000611
kasper.lund7276f142008-07-30 08:49:36 +0000612void LinuxSemaphore::Wait() {
613 while (true) {
614 int result = sem_wait(&sem_);
615 if (result == 0) return; // Successfully got semaphore.
616 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
617 }
618}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000619
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000620
621bool LinuxSemaphore::Wait(int timeout) {
622 const long kOneSecondMicros = 1000000; // NOLINT
623 const long kOneSecondNanos = 1000000000; // NOLINT
624
625 // Split timeout into second and nanosecond parts.
626 long nanos = (timeout % kOneSecondMicros) * 1000; // NOLINT
627 time_t secs = timeout / kOneSecondMicros;
628
629 // Get the current realtime clock.
630 struct timespec ts;
631 if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
632 return false;
633 }
634
635 // Calculate real time for end of timeout.
636 ts.tv_nsec += nanos;
637 if (ts.tv_nsec >= kOneSecondNanos) {
638 ts.tv_nsec -= kOneSecondNanos;
639 ts.tv_nsec++;
640 }
641 ts.tv_sec += secs;
642
643 // Wait for semaphore signalled or timeout.
644 while (true) {
645 int result = sem_timedwait(&sem_, &ts);
646 if (result == 0) return true; // Successfully got semaphore.
647 if (result > 0) {
648 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
649 errno = result;
650 result = -1;
651 }
652 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
653 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
654 }
655}
656
657
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000658Semaphore* OS::CreateSemaphore(int count) {
659 return new LinuxSemaphore(count);
660}
661
ager@chromium.org381abbb2009-02-25 13:23:22 +0000662
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000663#ifdef ENABLE_LOGGING_AND_PROFILING
664
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000665static Sampler* active_sampler_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000666
667static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000668 // Ucontext is a glibc extension - no profiling on Android at the moment.
669#ifdef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000670 USE(info);
671 if (signal != SIGPROF) return;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000672 if (active_sampler_ == NULL) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000673
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000674 TickSample sample;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000675
676 // If profiling, we extract the current pc and sp.
677 if (active_sampler_->IsProfiling()) {
678 // Extracting the sample from the context is extremely machine dependent.
679 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
680 mcontext_t& mcontext = ucontext->uc_mcontext;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000681#if defined (__arm__) || defined(__thumb__)
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000682 sample.pc = mcontext.gregs[R15];
683 sample.sp = mcontext.gregs[R13];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000684 sample.fp = mcontext.gregs[R11];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000685#else
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000686 sample.pc = mcontext.gregs[REG_EIP];
687 sample.sp = mcontext.gregs[REG_ESP];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000688 sample.fp = mcontext.gregs[REG_EBP];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000689#endif
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000690 }
691
692 // We always sample the VM state.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000693 sample.state = Logger::state();
694
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000695 active_sampler_->Tick(&sample);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000696#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697}
698
699
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000700class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000701 public:
702 PlatformData() {
703 signal_handler_installed_ = false;
704 }
705
706 bool signal_handler_installed_;
707 struct sigaction old_signal_handler_;
708 struct itimerval old_timer_value_;
709};
710
711
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000712Sampler::Sampler(int interval, bool profiling)
713 : interval_(interval), profiling_(profiling), active_(false) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000714 data_ = new PlatformData();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000715}
716
717
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000718Sampler::~Sampler() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000719 delete data_;
720}
721
722
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000723void Sampler::Start() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000724 // There can only be one active sampler at the time on POSIX
725 // platforms.
726 if (active_sampler_ != NULL) return;
727
728 // Request profiling signals.
729 struct sigaction sa;
730 sa.sa_sigaction = ProfilerSignalHandler;
731 sigemptyset(&sa.sa_mask);
732 sa.sa_flags = SA_SIGINFO;
733 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
734 data_->signal_handler_installed_ = true;
735
736 // Set the itimer to generate a tick for each interval.
737 itimerval itimer;
738 itimer.it_interval.tv_sec = interval_ / 1000;
739 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
740 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
741 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
742 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
743
744 // Set this sampler as the active sampler.
745 active_sampler_ = this;
746 active_ = true;
747}
748
749
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000750void Sampler::Stop() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000751 // Restore old signal handler
752 if (data_->signal_handler_installed_) {
753 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
754 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
755 data_->signal_handler_installed_ = false;
756 }
757
758 // This sampler is no longer the active sampler.
759 active_sampler_ = NULL;
760 active_ = false;
761}
762
763#endif // ENABLE_LOGGING_AND_PROFILING
764
765} } // namespace v8::internal