blob: e044dbccadaae0b7e534c3ae8f4910a8fcecd609 [file] [log] [blame]
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001// Copyright 2012 the V8 project authors. All rights reserved.
Leon Clarked91b9f72010-01-27 17:25:45 +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
28// Platform specific code for Solaris 10 goes here. For the POSIX comaptible
29// parts the implementation is in platform-posix.cc.
30
31#ifdef __sparc
32# error "V8 does not support the SPARC CPU architecture."
33#endif
34
35#include <sys/stack.h> // for stack alignment
36#include <unistd.h> // getpagesize(), usleep()
37#include <sys/mman.h> // mmap()
Leon Clarkef7060e22010-06-03 12:02:55 +010038#include <ucontext.h> // walkstack(), getcontext()
39#include <dlfcn.h> // dladdr
Leon Clarked91b9f72010-01-27 17:25:45 +000040#include <pthread.h>
41#include <sched.h> // for sched_yield
42#include <semaphore.h>
43#include <time.h>
44#include <sys/time.h> // gettimeofday(), timeradd()
45#include <errno.h>
46#include <ieeefp.h> // finite()
47#include <signal.h> // sigemptyset(), etc
Steve Block44f0eee2011-05-26 01:26:41 +010048#include <sys/regset.h>
Leon Clarked91b9f72010-01-27 17:25:45 +000049
50
51#undef MAP_TYPE
52
53#include "v8.h"
54
Ben Murdoch3ef787d2012-04-12 10:51:47 +010055#include "platform-posix.h"
Leon Clarked91b9f72010-01-27 17:25:45 +000056#include "platform.h"
Ben Murdoch3ef787d2012-04-12 10:51:47 +010057#include "v8threads.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010058#include "vm-state-inl.h"
Leon Clarked91b9f72010-01-27 17:25:45 +000059
60
Leon Clarkef7060e22010-06-03 12:02:55 +010061// It seems there is a bug in some Solaris distributions (experienced in
62// SunOS 5.10 Generic_141445-09) which make it difficult or impossible to
63// access signbit() despite the availability of other C99 math functions.
64#ifndef signbit
65// Test sign - usually defined in math.h
66int signbit(double x) {
67 // We need to take care of the special case of both positive and negative
68 // versions of zero.
69 if (x == 0) {
70 return fpclass(x) & FP_NZERO;
71 } else {
72 // This won't detect negative NaN but that should be okay since we don't
73 // assume that behavior.
74 return x < 0;
75 }
76}
77#endif // signbit
78
Leon Clarked91b9f72010-01-27 17:25:45 +000079namespace v8 {
80namespace internal {
81
82
83// 0 is never a valid thread id on Solaris since the main thread is 1 and
84// subsequent have their ids incremented from there
85static const pthread_t kNoThread = (pthread_t) 0;
86
87
88double ceiling(double x) {
89 return ceil(x);
90}
91
92
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000093static Mutex* limit_mutex = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010094void OS::SetUp() {
Leon Clarked91b9f72010-01-27 17:25:45 +000095 // Seed the random number generator.
96 // Convert the current time to a 64-bit integer first, before converting it
97 // to an unsigned. Going directly will cause an overflow and the seed to be
98 // set to all ones. The seed will be identical for different instances that
99 // call this setup code within the same millisecond.
100 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
101 srandom(static_cast<unsigned int>(seed));
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000102 limit_mutex = CreateMutex();
Leon Clarked91b9f72010-01-27 17:25:45 +0000103}
104
105
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100106void OS::PostSetUp() {
107 // Math functions depend on CPU features therefore they are initialized after
108 // CPU.
109 MathSetup();
110}
111
112
Leon Clarked91b9f72010-01-27 17:25:45 +0000113uint64_t OS::CpuFeaturesImpliedByPlatform() {
114 return 0; // Solaris runs on a lot of things.
115}
116
117
118int OS::ActivationFrameAlignment() {
Ben Murdoch7d3e7fc2011-07-12 16:37:06 +0100119 // GCC generates code that requires 16 byte alignment such as movdqa.
120 return Max(STACK_ALIGN, 16);
Leon Clarked91b9f72010-01-27 17:25:45 +0000121}
122
123
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100124void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
125 __asm__ __volatile__("" : : : "memory");
126 *ptr = value;
127}
128
129
Leon Clarked91b9f72010-01-27 17:25:45 +0000130const char* OS::LocalTimezone(double time) {
131 if (isnan(time)) return "";
132 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
133 struct tm* t = localtime(&tv);
134 if (NULL == t) return "";
135 return tzname[0]; // The location of the timezone string on Solaris.
136}
137
138
139double OS::LocalTimeOffset() {
140 // On Solaris, struct tm does not contain a tm_gmtoff field.
141 time_t utc = time(NULL);
142 ASSERT(utc != -1);
143 struct tm* loc = localtime(&utc);
144 ASSERT(loc != NULL);
145 return static_cast<double>((mktime(loc) - utc) * msPerSecond);
146}
147
148
149// We keep the lowest and highest addresses mapped as a quick way of
150// determining that pointers are outside the heap (used mostly in assertions
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100151// and verification). The estimate is conservative, i.e., not all addresses in
Leon Clarked91b9f72010-01-27 17:25:45 +0000152// 'allocated' space are actually allocated to our heap. The range is
153// [lowest, highest), inclusive on the low and and exclusive on the high end.
154static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
155static void* highest_ever_allocated = reinterpret_cast<void*>(0);
156
157
158static void UpdateAllocatedSpaceLimits(void* address, int size) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000159 ASSERT(limit_mutex != NULL);
160 ScopedLock lock(limit_mutex);
161
Leon Clarked91b9f72010-01-27 17:25:45 +0000162 lowest_ever_allocated = Min(lowest_ever_allocated, address);
163 highest_ever_allocated =
164 Max(highest_ever_allocated,
165 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
166}
167
168
169bool OS::IsOutsideAllocatedSpace(void* address) {
170 return address < lowest_ever_allocated || address >= highest_ever_allocated;
171}
172
173
174size_t OS::AllocateAlignment() {
175 return static_cast<size_t>(getpagesize());
176}
177
178
179void* OS::Allocate(const size_t requested,
180 size_t* allocated,
181 bool is_executable) {
182 const size_t msize = RoundUp(requested, getpagesize());
183 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
184 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
185
186 if (mbase == MAP_FAILED) {
Steve Block44f0eee2011-05-26 01:26:41 +0100187 LOG(ISOLATE, StringEvent("OS::Allocate", "mmap failed"));
Leon Clarked91b9f72010-01-27 17:25:45 +0000188 return NULL;
189 }
190 *allocated = msize;
191 UpdateAllocatedSpaceLimits(mbase, msize);
192 return mbase;
193}
194
195
196void OS::Free(void* address, const size_t size) {
197 // TODO(1240712): munmap has a return value which is ignored here.
198 int result = munmap(address, size);
199 USE(result);
200 ASSERT(result == 0);
201}
202
203
Leon Clarked91b9f72010-01-27 17:25:45 +0000204void OS::Sleep(int milliseconds) {
205 useconds_t ms = static_cast<useconds_t>(milliseconds);
206 usleep(1000 * ms);
207}
208
209
210void OS::Abort() {
211 // Redirect to std abort to signal abnormal program termination.
212 abort();
213}
214
215
216void OS::DebugBreak() {
217 asm("int $3");
218}
219
220
221class PosixMemoryMappedFile : public OS::MemoryMappedFile {
222 public:
223 PosixMemoryMappedFile(FILE* file, void* memory, int size)
224 : file_(file), memory_(memory), size_(size) { }
225 virtual ~PosixMemoryMappedFile();
226 virtual void* memory() { return memory_; }
Steve Block1e0659c2011-05-24 12:43:12 +0100227 virtual int size() { return size_; }
Leon Clarked91b9f72010-01-27 17:25:45 +0000228 private:
229 FILE* file_;
230 void* memory_;
231 int size_;
232};
233
234
Steve Block1e0659c2011-05-24 12:43:12 +0100235OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100236 FILE* file = fopen(name, "r+");
Steve Block1e0659c2011-05-24 12:43:12 +0100237 if (file == NULL) return NULL;
238
239 fseek(file, 0, SEEK_END);
240 int size = ftell(file);
241
242 void* memory =
243 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
244 return new PosixMemoryMappedFile(file, memory, size);
245}
246
247
Leon Clarked91b9f72010-01-27 17:25:45 +0000248OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
249 void* initial) {
250 FILE* file = fopen(name, "w+");
251 if (file == NULL) return NULL;
252 int result = fwrite(initial, size, 1, file);
253 if (result < 1) {
254 fclose(file);
255 return NULL;
256 }
257 void* memory =
258 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
259 return new PosixMemoryMappedFile(file, memory, size);
260}
261
262
263PosixMemoryMappedFile::~PosixMemoryMappedFile() {
264 if (memory_) munmap(memory_, size_);
265 fclose(file_);
266}
267
268
269void OS::LogSharedLibraryAddresses() {
270}
271
272
Ben Murdochf87a2032010-10-22 12:50:53 +0100273void OS::SignalCodeMovingGC() {
274}
275
276
Leon Clarkef7060e22010-06-03 12:02:55 +0100277struct StackWalker {
278 Vector<OS::StackFrame>& frames;
279 int index;
280};
281
282
283static int StackWalkCallback(uintptr_t pc, int signo, void* data) {
284 struct StackWalker* walker = static_cast<struct StackWalker*>(data);
285 Dl_info info;
286
287 int i = walker->index;
288
289 walker->frames[i].address = reinterpret_cast<void*>(pc);
290
291 // Make sure line termination is in place.
292 walker->frames[i].text[OS::kStackWalkMaxTextLen - 1] = '\0';
293
294 Vector<char> text = MutableCStrVector(walker->frames[i].text,
295 OS::kStackWalkMaxTextLen);
296
297 if (dladdr(reinterpret_cast<void*>(pc), &info) == 0) {
298 OS::SNPrintF(text, "[0x%p]", pc);
299 } else if ((info.dli_fname != NULL && info.dli_sname != NULL)) {
300 // We have symbol info.
301 OS::SNPrintF(text, "%s'%s+0x%x", info.dli_fname, info.dli_sname, pc);
302 } else {
303 // No local symbol info.
304 OS::SNPrintF(text,
305 "%s'0x%p [0x%p]",
306 info.dli_fname,
307 pc - reinterpret_cast<uintptr_t>(info.dli_fbase),
308 pc);
309 }
310 walker->index++;
311 return 0;
312}
313
314
Leon Clarked91b9f72010-01-27 17:25:45 +0000315int OS::StackWalk(Vector<OS::StackFrame> frames) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100316 ucontext_t ctx;
317 struct StackWalker walker = { frames, 0 };
Leon Clarked91b9f72010-01-27 17:25:45 +0000318
Leon Clarkef7060e22010-06-03 12:02:55 +0100319 if (getcontext(&ctx) < 0) return kStackWalkError;
Leon Clarked91b9f72010-01-27 17:25:45 +0000320
Leon Clarkef7060e22010-06-03 12:02:55 +0100321 if (!walkcontext(&ctx, StackWalkCallback, &walker)) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000322 return kStackWalkError;
323 }
324
Leon Clarkef7060e22010-06-03 12:02:55 +0100325 return walker.index;
Leon Clarked91b9f72010-01-27 17:25:45 +0000326}
327
328
329// Constants used for mmap.
330static const int kMmapFd = -1;
331static const int kMmapFdOffset = 0;
332
333
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100334VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
335
Leon Clarked91b9f72010-01-27 17:25:45 +0000336VirtualMemory::VirtualMemory(size_t size) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100337 address_ = ReserveRegion(size);
Leon Clarked91b9f72010-01-27 17:25:45 +0000338 size_ = size;
339}
340
341
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100342VirtualMemory::VirtualMemory(size_t size, size_t alignment)
343 : address_(NULL), size_(0) {
344 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
345 size_t request_size = RoundUp(size + alignment,
346 static_cast<intptr_t>(OS::AllocateAlignment()));
347 void* reservation = mmap(OS::GetRandomMmapAddr(),
348 request_size,
349 PROT_NONE,
350 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
351 kMmapFd,
352 kMmapFdOffset);
353 if (reservation == MAP_FAILED) return;
354
355 Address base = static_cast<Address>(reservation);
356 Address aligned_base = RoundUp(base, alignment);
357 ASSERT_LE(base, aligned_base);
358
359 // Unmap extra memory reserved before and after the desired block.
360 if (aligned_base != base) {
361 size_t prefix_size = static_cast<size_t>(aligned_base - base);
362 OS::Free(base, prefix_size);
363 request_size -= prefix_size;
364 }
365
366 size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
367 ASSERT_LE(aligned_size, request_size);
368
369 if (aligned_size != request_size) {
370 size_t suffix_size = request_size - aligned_size;
371 OS::Free(aligned_base + aligned_size, suffix_size);
372 request_size -= suffix_size;
373 }
374
375 ASSERT(aligned_size == request_size);
376
377 address_ = static_cast<void*>(aligned_base);
378 size_ = aligned_size;
379}
380
381
Leon Clarked91b9f72010-01-27 17:25:45 +0000382VirtualMemory::~VirtualMemory() {
383 if (IsReserved()) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100384 bool result = ReleaseRegion(address(), size());
385 ASSERT(result);
386 USE(result);
Leon Clarked91b9f72010-01-27 17:25:45 +0000387 }
388}
389
390
391bool VirtualMemory::IsReserved() {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100392 return address_ != NULL;
Ben Murdochc7cc0282012-03-05 14:35:55 +0000393}
394
395
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100396void VirtualMemory::Reset() {
397 address_ = NULL;
398 size_ = 0;
399}
Ben Murdochc7cc0282012-03-05 14:35:55 +0000400
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100401
402bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
403 return CommitRegion(address, size, is_executable);
Ben Murdochc7cc0282012-03-05 14:35:55 +0000404}
405
406
407bool VirtualMemory::Uncommit(void* address, size_t size) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100408 return UncommitRegion(address, size);
409}
410
411
412bool VirtualMemory::Guard(void* address) {
413 OS::Guard(address, OS::CommitPageSize());
414 return true;
415}
416
417
418void* VirtualMemory::ReserveRegion(size_t size) {
419 void* result = mmap(OS::GetRandomMmapAddr(),
420 size,
421 PROT_NONE,
422 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
423 kMmapFd,
424 kMmapFdOffset);
425
426 if (result == MAP_FAILED) return NULL;
427
428 return result;
429}
430
431
432bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
433 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
434 if (MAP_FAILED == mmap(base,
435 size,
436 prot,
437 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
438 kMmapFd,
439 kMmapFdOffset)) {
440 return false;
441 }
442
443 UpdateAllocatedSpaceLimits(base, size);
444 return true;
445}
446
447
448bool VirtualMemory::UncommitRegion(void* base, size_t size) {
449 return mmap(base,
450 size,
451 PROT_NONE,
452 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
453 kMmapFd,
454 kMmapFdOffset) != MAP_FAILED;
455}
456
457
458bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
459 return munmap(base, size) == 0;
Leon Clarked91b9f72010-01-27 17:25:45 +0000460}
461
462
Ben Murdoch8b112d22011-06-08 16:22:53 +0100463class Thread::PlatformData : public Malloced {
Leon Clarked91b9f72010-01-27 17:25:45 +0000464 public:
Ben Murdoch8b112d22011-06-08 16:22:53 +0100465 PlatformData() : thread_(kNoThread) { }
Leon Clarked91b9f72010-01-27 17:25:45 +0000466
467 pthread_t thread_; // Thread handle for pthread.
468};
469
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100470
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000471Thread::Thread(const Options& options)
Ben Murdoch8b112d22011-06-08 16:22:53 +0100472 : data_(new PlatformData()),
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100473 stack_size_(options.stack_size()) {
474 set_name(options.name());
Leon Clarked91b9f72010-01-27 17:25:45 +0000475}
476
477
478Thread::~Thread() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100479 delete data_;
Leon Clarked91b9f72010-01-27 17:25:45 +0000480}
481
482
483static void* ThreadEntry(void* arg) {
484 Thread* thread = reinterpret_cast<Thread*>(arg);
485 // This is also initialized by the first argument to pthread_create() but we
486 // don't know which thread will run first (the original thread or the new
487 // one) so we initialize it here too.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100488 thread->data()->thread_ = pthread_self();
489 ASSERT(thread->data()->thread_ != kNoThread);
Leon Clarked91b9f72010-01-27 17:25:45 +0000490 thread->Run();
491 return NULL;
492}
493
494
Steve Block9fac8402011-05-12 15:51:54 +0100495void Thread::set_name(const char* name) {
496 strncpy(name_, name, sizeof(name_));
497 name_[sizeof(name_) - 1] = '\0';
498}
499
500
Leon Clarked91b9f72010-01-27 17:25:45 +0000501void Thread::Start() {
Steve Block44f0eee2011-05-26 01:26:41 +0100502 pthread_attr_t* attr_ptr = NULL;
503 pthread_attr_t attr;
504 if (stack_size_ > 0) {
505 pthread_attr_init(&attr);
506 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
507 attr_ptr = &attr;
508 }
Ben Murdoch8b112d22011-06-08 16:22:53 +0100509 pthread_create(&data_->thread_, NULL, ThreadEntry, this);
510 ASSERT(data_->thread_ != kNoThread);
Leon Clarked91b9f72010-01-27 17:25:45 +0000511}
512
513
514void Thread::Join() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100515 pthread_join(data_->thread_, NULL);
Leon Clarked91b9f72010-01-27 17:25:45 +0000516}
517
518
519Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
520 pthread_key_t key;
521 int result = pthread_key_create(&key, NULL);
522 USE(result);
523 ASSERT(result == 0);
524 return static_cast<LocalStorageKey>(key);
525}
526
527
528void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
529 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
530 int result = pthread_key_delete(pthread_key);
531 USE(result);
532 ASSERT(result == 0);
533}
534
535
536void* Thread::GetThreadLocal(LocalStorageKey key) {
537 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
538 return pthread_getspecific(pthread_key);
539}
540
541
542void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
543 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
544 pthread_setspecific(pthread_key, value);
545}
546
547
548void Thread::YieldCPU() {
549 sched_yield();
550}
551
552
553class SolarisMutex : public Mutex {
554 public:
Leon Clarked91b9f72010-01-27 17:25:45 +0000555 SolarisMutex() {
556 pthread_mutexattr_t attr;
557 pthread_mutexattr_init(&attr);
558 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
559 pthread_mutex_init(&mutex_, &attr);
560 }
561
562 ~SolarisMutex() { pthread_mutex_destroy(&mutex_); }
563
564 int Lock() { return pthread_mutex_lock(&mutex_); }
565
566 int Unlock() { return pthread_mutex_unlock(&mutex_); }
567
Ben Murdochb8e0da22011-05-16 14:20:40 +0100568 virtual bool TryLock() {
569 int result = pthread_mutex_trylock(&mutex_);
570 // Return false if the lock is busy and locking failed.
571 if (result == EBUSY) {
572 return false;
573 }
574 ASSERT(result == 0); // Verify no other errors.
575 return true;
576 }
577
Leon Clarked91b9f72010-01-27 17:25:45 +0000578 private:
579 pthread_mutex_t mutex_;
580};
581
582
583Mutex* OS::CreateMutex() {
584 return new SolarisMutex();
585}
586
587
588class SolarisSemaphore : public Semaphore {
589 public:
590 explicit SolarisSemaphore(int count) { sem_init(&sem_, 0, count); }
591 virtual ~SolarisSemaphore() { sem_destroy(&sem_); }
592
593 virtual void Wait();
594 virtual bool Wait(int timeout);
595 virtual void Signal() { sem_post(&sem_); }
596 private:
597 sem_t sem_;
598};
599
600
601void SolarisSemaphore::Wait() {
602 while (true) {
603 int result = sem_wait(&sem_);
604 if (result == 0) return; // Successfully got semaphore.
605 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
606 }
607}
608
609
610#ifndef TIMEVAL_TO_TIMESPEC
611#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
612 (ts)->tv_sec = (tv)->tv_sec; \
613 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
614} while (false)
615#endif
616
617
618#ifndef timeradd
619#define timeradd(a, b, result) \
620 do { \
621 (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
622 (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
623 if ((result)->tv_usec >= 1000000) { \
624 ++(result)->tv_sec; \
625 (result)->tv_usec -= 1000000; \
626 } \
627 } while (0)
628#endif
629
630
631bool SolarisSemaphore::Wait(int timeout) {
632 const long kOneSecondMicros = 1000000; // NOLINT
633
634 // Split timeout into second and nanosecond parts.
635 struct timeval delta;
636 delta.tv_usec = timeout % kOneSecondMicros;
637 delta.tv_sec = timeout / kOneSecondMicros;
638
639 struct timeval current_time;
640 // Get the current time.
641 if (gettimeofday(&current_time, NULL) == -1) {
642 return false;
643 }
644
645 // Calculate time for end of timeout.
646 struct timeval end_time;
647 timeradd(&current_time, &delta, &end_time);
648
649 struct timespec ts;
650 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
651 // Wait for semaphore signalled or timeout.
652 while (true) {
653 int result = sem_timedwait(&sem_, &ts);
654 if (result == 0) return true; // Successfully got semaphore.
655 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
656 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
657 }
658}
659
660
661Semaphore* OS::CreateSemaphore(int count) {
662 return new SolarisSemaphore(count);
663}
664
665
Steve Block44f0eee2011-05-26 01:26:41 +0100666static pthread_t GetThreadID() {
667 return pthread_self();
668}
669
Leon Clarked91b9f72010-01-27 17:25:45 +0000670static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
671 USE(info);
672 if (signal != SIGPROF) return;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000673 Isolate* isolate = Isolate::UncheckedCurrent();
674 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
675 // We require a fully initialized and entered isolate.
676 return;
677 }
678 if (v8::Locker::IsActive() &&
679 !isolate->thread_manager()->IsLockedByCurrentThread()) {
680 return;
681 }
682
683 Sampler* sampler = isolate->logger()->sampler();
684 if (sampler == NULL || !sampler->IsActive()) return;
Leon Clarked91b9f72010-01-27 17:25:45 +0000685
Ben Murdochb8e0da22011-05-16 14:20:40 +0100686 TickSample sample_obj;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000687 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
Ben Murdochb8e0da22011-05-16 14:20:40 +0100688 if (sample == NULL) sample = &sample_obj;
Leon Clarked91b9f72010-01-27 17:25:45 +0000689
Ben Murdochb8e0da22011-05-16 14:20:40 +0100690 // Extracting the sample from the context is extremely machine dependent.
691 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
692 mcontext_t& mcontext = ucontext->uc_mcontext;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000693 sample->state = isolate->current_vm_state();
Leon Clarked91b9f72010-01-27 17:25:45 +0000694
Steve Block44f0eee2011-05-26 01:26:41 +0100695 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_PC]);
696 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_SP]);
697 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_FP]);
698
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000699 sampler->SampleStack(sample);
700 sampler->Tick(sample);
Leon Clarked91b9f72010-01-27 17:25:45 +0000701}
702
Leon Clarked91b9f72010-01-27 17:25:45 +0000703class Sampler::PlatformData : public Malloced {
704 public:
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000705 PlatformData() : vm_tid_(GetThreadID()) {}
706
707 pthread_t vm_tid() const { return vm_tid_; }
708
709 private:
710 pthread_t vm_tid_;
711};
712
713
714class SignalSender : public Thread {
715 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100716 enum SleepInterval {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000717 HALF_INTERVAL,
718 FULL_INTERVAL
Steve Block44f0eee2011-05-26 01:26:41 +0100719 };
720
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100721 static const int kSignalSenderStackSize = 64 * KB;
722
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000723 explicit SignalSender(int interval)
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100724 : Thread(Thread::Options("SignalSender", kSignalSenderStackSize)),
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000725 interval_(interval) {}
726
727 static void InstallSignalHandler() {
728 struct sigaction sa;
729 sa.sa_sigaction = ProfilerSignalHandler;
730 sigemptyset(&sa.sa_mask);
731 sa.sa_flags = SA_RESTART | SA_SIGINFO;
732 signal_handler_installed_ =
733 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
Leon Clarked91b9f72010-01-27 17:25:45 +0000734 }
735
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000736 static void RestoreSignalHandler() {
737 if (signal_handler_installed_) {
738 sigaction(SIGPROF, &old_signal_handler_, 0);
739 signal_handler_installed_ = false;
740 }
741 }
742
743 static void AddActiveSampler(Sampler* sampler) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100744 ScopedLock lock(mutex_.Pointer());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000745 SamplerRegistry::AddActiveSampler(sampler);
746 if (instance_ == NULL) {
747 // Start a thread that will send SIGPROF signal to VM threads,
748 // when CPU profiling will be enabled.
749 instance_ = new SignalSender(sampler->interval());
750 instance_->Start();
751 } else {
752 ASSERT(instance_->interval_ == sampler->interval());
753 }
754 }
755
756 static void RemoveActiveSampler(Sampler* sampler) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100757 ScopedLock lock(mutex_.Pointer());
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000758 SamplerRegistry::RemoveActiveSampler(sampler);
759 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
760 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
761 delete instance_;
762 instance_ = NULL;
763 RestoreSignalHandler();
764 }
765 }
766
767 // Implement Thread::Run().
768 virtual void Run() {
769 SamplerRegistry::State state;
770 while ((state = SamplerRegistry::GetState()) !=
771 SamplerRegistry::HAS_NO_SAMPLERS) {
772 bool cpu_profiling_enabled =
773 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
774 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
775 if (cpu_profiling_enabled && !signal_handler_installed_) {
776 InstallSignalHandler();
777 } else if (!cpu_profiling_enabled && signal_handler_installed_) {
778 RestoreSignalHandler();
779 }
780
781 // When CPU profiling is enabled both JavaScript and C++ code is
782 // profiled. We must not suspend.
783 if (!cpu_profiling_enabled) {
784 if (rate_limiter_.SuspendIfNecessary()) continue;
785 }
786 if (cpu_profiling_enabled && runtime_profiler_enabled) {
787 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
788 return;
789 }
Steve Block44f0eee2011-05-26 01:26:41 +0100790 Sleep(HALF_INTERVAL);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000791 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
792 return;
793 }
Steve Block44f0eee2011-05-26 01:26:41 +0100794 Sleep(HALF_INTERVAL);
795 } else {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000796 if (cpu_profiling_enabled) {
797 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
798 this)) {
799 return;
800 }
801 }
802 if (runtime_profiler_enabled) {
803 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
804 NULL)) {
805 return;
806 }
807 }
Steve Block44f0eee2011-05-26 01:26:41 +0100808 Sleep(FULL_INTERVAL);
809 }
810 }
811 }
812
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000813 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
814 if (!sampler->IsProfiling()) return;
815 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
816 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
817 }
818
819 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
820 if (!sampler->isolate()->IsInitialized()) return;
821 sampler->isolate()->runtime_profiler()->NotifyTick();
822 }
823
824 void SendProfilingSignal(pthread_t tid) {
Steve Block44f0eee2011-05-26 01:26:41 +0100825 if (!signal_handler_installed_) return;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000826 pthread_kill(tid, SIGPROF);
Steve Block44f0eee2011-05-26 01:26:41 +0100827 }
828
829 void Sleep(SleepInterval full_or_half) {
830 // Convert ms to us and subtract 100 us to compensate delays
831 // occuring during signal delivery.
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000832 useconds_t interval = interval_ * 1000 - 100;
Steve Block44f0eee2011-05-26 01:26:41 +0100833 if (full_or_half == HALF_INTERVAL) interval /= 2;
834 int result = usleep(interval);
835#ifdef DEBUG
836 if (result != 0 && errno != EINTR) {
837 fprintf(stderr,
838 "SignalSender usleep error; interval = %u, errno = %d\n",
839 interval,
840 errno);
841 ASSERT(result == 0 || errno == EINTR);
842 }
843#endif
844 USE(result);
845 }
846
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000847 const int interval_;
Steve Block44f0eee2011-05-26 01:26:41 +0100848 RuntimeProfilerRateLimiter rate_limiter_;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000849
850 // Protects the process wide state below.
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100851 static LazyMutex mutex_;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000852 static SignalSender* instance_;
853 static bool signal_handler_installed_;
854 static struct sigaction old_signal_handler_;
855
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100856 private:
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000857 DISALLOW_COPY_AND_ASSIGN(SignalSender);
Leon Clarked91b9f72010-01-27 17:25:45 +0000858};
859
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100860LazyMutex SignalSender::mutex_ = LAZY_MUTEX_INITIALIZER;
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000861SignalSender* SignalSender::instance_ = NULL;
862struct sigaction SignalSender::old_signal_handler_;
863bool SignalSender::signal_handler_installed_ = false;
Steve Block44f0eee2011-05-26 01:26:41 +0100864
865
866Sampler::Sampler(Isolate* isolate, int interval)
867 : isolate_(isolate),
868 interval_(interval),
Ben Murdochb0fe1622011-05-05 13:52:32 +0100869 profiling_(false),
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800870 active_(false),
871 samples_taken_(0) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000872 data_ = new PlatformData;
Leon Clarked91b9f72010-01-27 17:25:45 +0000873}
874
875
876Sampler::~Sampler() {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000877 ASSERT(!IsActive());
Leon Clarked91b9f72010-01-27 17:25:45 +0000878 delete data_;
879}
880
881
882void Sampler::Start() {
Steve Block44f0eee2011-05-26 01:26:41 +0100883 ASSERT(!IsActive());
Steve Block44f0eee2011-05-26 01:26:41 +0100884 SetActive(true);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000885 SignalSender::AddActiveSampler(this);
Leon Clarked91b9f72010-01-27 17:25:45 +0000886}
887
888
889void Sampler::Stop() {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000890 ASSERT(IsActive());
891 SignalSender::RemoveActiveSampler(this);
Steve Block44f0eee2011-05-26 01:26:41 +0100892 SetActive(false);
Leon Clarked91b9f72010-01-27 17:25:45 +0000893}
894
Leon Clarked91b9f72010-01-27 17:25:45 +0000895} } // namespace v8::internal