blob: 1e79f102f53ed13752c142af27a69f7fbccc5b60 [file] [log] [blame]
vegorov@chromium.org3cf47312011-06-29 13:20:01 +00001// Copyright 2011 the V8 project authors. All rights reserved.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +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()
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000038#include <ucontext.h> // walkstack(), getcontext()
39#include <dlfcn.h> // dladdr
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +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
whesse@chromium.orgb08986c2011-03-14 16:13:42 +000048#include <sys/regset.h>
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000049
50
51#undef MAP_TYPE
52
53#include "v8.h"
54
55#include "platform.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000056#include "vm-state-inl.h"
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000057
58
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000059// It seems there is a bug in some Solaris distributions (experienced in
60// SunOS 5.10 Generic_141445-09) which make it difficult or impossible to
61// access signbit() despite the availability of other C99 math functions.
62#ifndef signbit
63// Test sign - usually defined in math.h
64int signbit(double x) {
65 // We need to take care of the special case of both positive and negative
66 // versions of zero.
67 if (x == 0) {
68 return fpclass(x) & FP_NZERO;
69 } else {
70 // This won't detect negative NaN but that should be okay since we don't
71 // assume that behavior.
72 return x < 0;
73 }
74}
75#endif // signbit
76
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000077namespace v8 {
78namespace internal {
79
80
81// 0 is never a valid thread id on Solaris since the main thread is 1 and
82// subsequent have their ids incremented from there
83static const pthread_t kNoThread = (pthread_t) 0;
84
85
86double ceiling(double x) {
87 return ceil(x);
88}
89
90
ricow@chromium.org4f693d62011-07-04 14:01:31 +000091static Mutex* limit_mutex = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000092void OS::Setup() {
93 // Seed the random number generator.
94 // Convert the current time to a 64-bit integer first, before converting it
95 // to an unsigned. Going directly will cause an overflow and the seed to be
96 // set to all ones. The seed will be identical for different instances that
97 // call this setup code within the same millisecond.
98 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
99 srandom(static_cast<unsigned int>(seed));
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000100 limit_mutex = CreateMutex();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000101}
102
103
104uint64_t OS::CpuFeaturesImpliedByPlatform() {
105 return 0; // Solaris runs on a lot of things.
106}
107
108
109int OS::ActivationFrameAlignment() {
vegorov@chromium.org3cf47312011-06-29 13:20:01 +0000110 // GCC generates code that requires 16 byte alignment such as movdqa.
111 return Max(STACK_ALIGN, 16);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000112}
113
114
ricow@chromium.org30ce4112010-05-31 10:38:25 +0000115void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
116 __asm__ __volatile__("" : : : "memory");
117 *ptr = value;
118}
119
120
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000121const char* OS::LocalTimezone(double time) {
122 if (isnan(time)) return "";
123 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
124 struct tm* t = localtime(&tv);
125 if (NULL == t) return "";
126 return tzname[0]; // The location of the timezone string on Solaris.
127}
128
129
130double OS::LocalTimeOffset() {
131 // On Solaris, struct tm does not contain a tm_gmtoff field.
132 time_t utc = time(NULL);
133 ASSERT(utc != -1);
134 struct tm* loc = localtime(&utc);
135 ASSERT(loc != NULL);
136 return static_cast<double>((mktime(loc) - utc) * msPerSecond);
137}
138
139
140// We keep the lowest and highest addresses mapped as a quick way of
141// determining that pointers are outside the heap (used mostly in assertions
142// and verification). The estimate is conservative, ie, not all addresses in
143// 'allocated' space are actually allocated to our heap. The range is
144// [lowest, highest), inclusive on the low and and exclusive on the high end.
145static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
146static void* highest_ever_allocated = reinterpret_cast<void*>(0);
147
148
149static void UpdateAllocatedSpaceLimits(void* address, int size) {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000150 ASSERT(limit_mutex != NULL);
151 ScopedLock lock(limit_mutex);
152
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000153 lowest_ever_allocated = Min(lowest_ever_allocated, address);
154 highest_ever_allocated =
155 Max(highest_ever_allocated,
156 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
157}
158
159
160bool OS::IsOutsideAllocatedSpace(void* address) {
161 return address < lowest_ever_allocated || address >= highest_ever_allocated;
162}
163
164
165size_t OS::AllocateAlignment() {
166 return static_cast<size_t>(getpagesize());
167}
168
169
170void* OS::Allocate(const size_t requested,
171 size_t* allocated,
172 bool is_executable) {
173 const size_t msize = RoundUp(requested, getpagesize());
174 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
175 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
176
177 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000178 LOG(ISOLATE, StringEvent("OS::Allocate", "mmap failed"));
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000179 return NULL;
180 }
181 *allocated = msize;
182 UpdateAllocatedSpaceLimits(mbase, msize);
183 return mbase;
184}
185
186
187void OS::Free(void* address, const size_t size) {
188 // TODO(1240712): munmap has a return value which is ignored here.
189 int result = munmap(address, size);
190 USE(result);
191 ASSERT(result == 0);
192}
193
194
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000195void OS::Sleep(int milliseconds) {
196 useconds_t ms = static_cast<useconds_t>(milliseconds);
197 usleep(1000 * ms);
198}
199
200
201void OS::Abort() {
202 // Redirect to std abort to signal abnormal program termination.
203 abort();
204}
205
206
207void OS::DebugBreak() {
208 asm("int $3");
209}
210
211
212class PosixMemoryMappedFile : public OS::MemoryMappedFile {
213 public:
214 PosixMemoryMappedFile(FILE* file, void* memory, int size)
215 : file_(file), memory_(memory), size_(size) { }
216 virtual ~PosixMemoryMappedFile();
217 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000218 virtual int size() { return size_; }
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000219 private:
220 FILE* file_;
221 void* memory_;
222 int size_;
223};
224
225
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000226OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000227 FILE* file = fopen(name, "r+");
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000228 if (file == NULL) return NULL;
229
230 fseek(file, 0, SEEK_END);
231 int size = ftell(file);
232
233 void* memory =
234 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
235 return new PosixMemoryMappedFile(file, memory, size);
236}
237
238
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000239OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
240 void* initial) {
241 FILE* file = fopen(name, "w+");
242 if (file == NULL) return NULL;
243 int result = fwrite(initial, size, 1, file);
244 if (result < 1) {
245 fclose(file);
246 return NULL;
247 }
248 void* memory =
249 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
250 return new PosixMemoryMappedFile(file, memory, size);
251}
252
253
254PosixMemoryMappedFile::~PosixMemoryMappedFile() {
255 if (memory_) munmap(memory_, size_);
256 fclose(file_);
257}
258
259
260void OS::LogSharedLibraryAddresses() {
261}
262
263
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000264void OS::SignalCodeMovingGC() {
265}
266
267
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000268struct StackWalker {
269 Vector<OS::StackFrame>& frames;
270 int index;
271};
272
273
274static int StackWalkCallback(uintptr_t pc, int signo, void* data) {
275 struct StackWalker* walker = static_cast<struct StackWalker*>(data);
276 Dl_info info;
277
278 int i = walker->index;
279
280 walker->frames[i].address = reinterpret_cast<void*>(pc);
281
282 // Make sure line termination is in place.
283 walker->frames[i].text[OS::kStackWalkMaxTextLen - 1] = '\0';
284
285 Vector<char> text = MutableCStrVector(walker->frames[i].text,
286 OS::kStackWalkMaxTextLen);
287
288 if (dladdr(reinterpret_cast<void*>(pc), &info) == 0) {
289 OS::SNPrintF(text, "[0x%p]", pc);
290 } else if ((info.dli_fname != NULL && info.dli_sname != NULL)) {
291 // We have symbol info.
292 OS::SNPrintF(text, "%s'%s+0x%x", info.dli_fname, info.dli_sname, pc);
293 } else {
294 // No local symbol info.
295 OS::SNPrintF(text,
296 "%s'0x%p [0x%p]",
297 info.dli_fname,
298 pc - reinterpret_cast<uintptr_t>(info.dli_fbase),
299 pc);
300 }
301 walker->index++;
302 return 0;
303}
304
305
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000306int OS::StackWalk(Vector<OS::StackFrame> frames) {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000307 ucontext_t ctx;
308 struct StackWalker walker = { frames, 0 };
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000309
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000310 if (getcontext(&ctx) < 0) return kStackWalkError;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000311
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000312 if (!walkcontext(&ctx, StackWalkCallback, &walker)) {
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000313 return kStackWalkError;
314 }
315
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000316 return walker.index;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000317}
318
319
320// Constants used for mmap.
321static const int kMmapFd = -1;
322static const int kMmapFdOffset = 0;
323
324
325VirtualMemory::VirtualMemory(size_t size) {
326 address_ = mmap(NULL, size, PROT_NONE,
327 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
328 kMmapFd, kMmapFdOffset);
329 size_ = size;
330}
331
332
333VirtualMemory::~VirtualMemory() {
334 if (IsReserved()) {
335 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
336 }
337}
338
339
340bool VirtualMemory::IsReserved() {
341 return address_ != MAP_FAILED;
342}
343
344
345bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
346 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
347 if (MAP_FAILED == mmap(address, size, prot,
348 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
349 kMmapFd, kMmapFdOffset)) {
350 return false;
351 }
352
353 UpdateAllocatedSpaceLimits(address, size);
354 return true;
355}
356
357
358bool VirtualMemory::Uncommit(void* address, size_t size) {
359 return mmap(address, size, PROT_NONE,
360 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
361 kMmapFd, kMmapFdOffset) != MAP_FAILED;
362}
363
364
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000365class Thread::PlatformData : public Malloced {
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000366 public:
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000367 PlatformData() : thread_(kNoThread) { }
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000368
369 pthread_t thread_; // Thread handle for pthread.
370};
371
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000372Thread::Thread(const Options& options)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000373 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000374 stack_size_(options.stack_size) {
375 set_name(options.name);
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000376}
377
378
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000379Thread::Thread(const char* name)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000380 : data_(new PlatformData()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000381 stack_size_(0) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000382 set_name(name);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000383}
384
385
386Thread::~Thread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000387 delete data_;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000388}
389
390
391static void* ThreadEntry(void* arg) {
392 Thread* thread = reinterpret_cast<Thread*>(arg);
393 // This is also initialized by the first argument to pthread_create() but we
394 // don't know which thread will run first (the original thread or the new
395 // one) so we initialize it here too.
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000396 thread->data()->thread_ = pthread_self();
397 ASSERT(thread->data()->thread_ != kNoThread);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000398 thread->Run();
399 return NULL;
400}
401
402
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000403void Thread::set_name(const char* name) {
404 strncpy(name_, name, sizeof(name_));
405 name_[sizeof(name_) - 1] = '\0';
406}
407
408
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000409void Thread::Start() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000410 pthread_attr_t* attr_ptr = NULL;
411 pthread_attr_t attr;
412 if (stack_size_ > 0) {
413 pthread_attr_init(&attr);
414 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
415 attr_ptr = &attr;
416 }
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000417 pthread_create(&data_->thread_, NULL, ThreadEntry, this);
418 ASSERT(data_->thread_ != kNoThread);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000419}
420
421
422void Thread::Join() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000423 pthread_join(data_->thread_, NULL);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000424}
425
426
427Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
428 pthread_key_t key;
429 int result = pthread_key_create(&key, NULL);
430 USE(result);
431 ASSERT(result == 0);
432 return static_cast<LocalStorageKey>(key);
433}
434
435
436void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
437 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
438 int result = pthread_key_delete(pthread_key);
439 USE(result);
440 ASSERT(result == 0);
441}
442
443
444void* Thread::GetThreadLocal(LocalStorageKey key) {
445 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
446 return pthread_getspecific(pthread_key);
447}
448
449
450void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
451 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
452 pthread_setspecific(pthread_key, value);
453}
454
455
456void Thread::YieldCPU() {
457 sched_yield();
458}
459
460
461class SolarisMutex : public Mutex {
462 public:
463
464 SolarisMutex() {
465 pthread_mutexattr_t attr;
466 pthread_mutexattr_init(&attr);
467 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
468 pthread_mutex_init(&mutex_, &attr);
469 }
470
471 ~SolarisMutex() { pthread_mutex_destroy(&mutex_); }
472
473 int Lock() { return pthread_mutex_lock(&mutex_); }
474
475 int Unlock() { return pthread_mutex_unlock(&mutex_); }
476
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000477 virtual bool TryLock() {
478 int result = pthread_mutex_trylock(&mutex_);
479 // Return false if the lock is busy and locking failed.
480 if (result == EBUSY) {
481 return false;
482 }
483 ASSERT(result == 0); // Verify no other errors.
484 return true;
485 }
486
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000487 private:
488 pthread_mutex_t mutex_;
489};
490
491
492Mutex* OS::CreateMutex() {
493 return new SolarisMutex();
494}
495
496
497class SolarisSemaphore : public Semaphore {
498 public:
499 explicit SolarisSemaphore(int count) { sem_init(&sem_, 0, count); }
500 virtual ~SolarisSemaphore() { sem_destroy(&sem_); }
501
502 virtual void Wait();
503 virtual bool Wait(int timeout);
504 virtual void Signal() { sem_post(&sem_); }
505 private:
506 sem_t sem_;
507};
508
509
510void SolarisSemaphore::Wait() {
511 while (true) {
512 int result = sem_wait(&sem_);
513 if (result == 0) return; // Successfully got semaphore.
514 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
515 }
516}
517
518
519#ifndef TIMEVAL_TO_TIMESPEC
520#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
521 (ts)->tv_sec = (tv)->tv_sec; \
522 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
523} while (false)
524#endif
525
526
527#ifndef timeradd
528#define timeradd(a, b, result) \
529 do { \
530 (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
531 (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
532 if ((result)->tv_usec >= 1000000) { \
533 ++(result)->tv_sec; \
534 (result)->tv_usec -= 1000000; \
535 } \
536 } while (0)
537#endif
538
539
540bool SolarisSemaphore::Wait(int timeout) {
541 const long kOneSecondMicros = 1000000; // NOLINT
542
543 // Split timeout into second and nanosecond parts.
544 struct timeval delta;
545 delta.tv_usec = timeout % kOneSecondMicros;
546 delta.tv_sec = timeout / kOneSecondMicros;
547
548 struct timeval current_time;
549 // Get the current time.
550 if (gettimeofday(&current_time, NULL) == -1) {
551 return false;
552 }
553
554 // Calculate time for end of timeout.
555 struct timeval end_time;
556 timeradd(&current_time, &delta, &end_time);
557
558 struct timespec ts;
559 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
560 // Wait for semaphore signalled or timeout.
561 while (true) {
562 int result = sem_timedwait(&sem_, &ts);
563 if (result == 0) return true; // Successfully got semaphore.
564 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
565 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
566 }
567}
568
569
570Semaphore* OS::CreateSemaphore(int count) {
571 return new SolarisSemaphore(count);
572}
573
574
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000575static pthread_t GetThreadID() {
576 return pthread_self();
577}
578
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000579static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
580 USE(info);
581 if (signal != SIGPROF) return;
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000582 Isolate* isolate = Isolate::UncheckedCurrent();
583 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
584 // We require a fully initialized and entered isolate.
585 return;
586 }
587 if (v8::Locker::IsActive() &&
588 !isolate->thread_manager()->IsLockedByCurrentThread()) {
589 return;
590 }
591
592 Sampler* sampler = isolate->logger()->sampler();
593 if (sampler == NULL || !sampler->IsActive()) return;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000594
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000595 TickSample sample_obj;
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000596 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000597 if (sample == NULL) sample = &sample_obj;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000598
sgjesse@chromium.orgc6c57182011-01-17 12:24:25 +0000599 // Extracting the sample from the context is extremely machine dependent.
600 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
601 mcontext_t& mcontext = ucontext->uc_mcontext;
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000602 sample->state = isolate->current_vm_state();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000603
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000604 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_PC]);
605 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_SP]);
606 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_FP]);
607
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000608 sampler->SampleStack(sample);
609 sampler->Tick(sample);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000610}
611
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000612class Sampler::PlatformData : public Malloced {
613 public:
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000614 PlatformData() : vm_tid_(GetThreadID()) {}
615
616 pthread_t vm_tid() const { return vm_tid_; }
617
618 private:
619 pthread_t vm_tid_;
620};
621
622
623class SignalSender : public Thread {
624 public:
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000625 enum SleepInterval {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000626 HALF_INTERVAL,
627 FULL_INTERVAL
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000628 };
629
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000630 explicit SignalSender(int interval)
631 : Thread("SignalSender"),
632 interval_(interval) {}
633
634 static void InstallSignalHandler() {
635 struct sigaction sa;
636 sa.sa_sigaction = ProfilerSignalHandler;
637 sigemptyset(&sa.sa_mask);
638 sa.sa_flags = SA_RESTART | SA_SIGINFO;
639 signal_handler_installed_ =
640 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000641 }
642
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000643 static void RestoreSignalHandler() {
644 if (signal_handler_installed_) {
645 sigaction(SIGPROF, &old_signal_handler_, 0);
646 signal_handler_installed_ = false;
647 }
648 }
649
650 static void AddActiveSampler(Sampler* sampler) {
651 ScopedLock lock(mutex_);
652 SamplerRegistry::AddActiveSampler(sampler);
653 if (instance_ == NULL) {
654 // Start a thread that will send SIGPROF signal to VM threads,
655 // when CPU profiling will be enabled.
656 instance_ = new SignalSender(sampler->interval());
657 instance_->Start();
658 } else {
659 ASSERT(instance_->interval_ == sampler->interval());
660 }
661 }
662
663 static void RemoveActiveSampler(Sampler* sampler) {
664 ScopedLock lock(mutex_);
665 SamplerRegistry::RemoveActiveSampler(sampler);
666 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000667 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000668 delete instance_;
669 instance_ = NULL;
670 RestoreSignalHandler();
671 }
672 }
673
674 // Implement Thread::Run().
675 virtual void Run() {
676 SamplerRegistry::State state;
677 while ((state = SamplerRegistry::GetState()) !=
678 SamplerRegistry::HAS_NO_SAMPLERS) {
679 bool cpu_profiling_enabled =
680 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
681 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
682 if (cpu_profiling_enabled && !signal_handler_installed_) {
683 InstallSignalHandler();
684 } else if (!cpu_profiling_enabled && signal_handler_installed_) {
685 RestoreSignalHandler();
686 }
687
688 // When CPU profiling is enabled both JavaScript and C++ code is
689 // profiled. We must not suspend.
690 if (!cpu_profiling_enabled) {
691 if (rate_limiter_.SuspendIfNecessary()) continue;
692 }
693 if (cpu_profiling_enabled && runtime_profiler_enabled) {
694 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
695 return;
696 }
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000697 Sleep(HALF_INTERVAL);
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000698 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
699 return;
700 }
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000701 Sleep(HALF_INTERVAL);
702 } else {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000703 if (cpu_profiling_enabled) {
704 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
705 this)) {
706 return;
707 }
708 }
709 if (runtime_profiler_enabled) {
710 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
711 NULL)) {
712 return;
713 }
714 }
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000715 Sleep(FULL_INTERVAL);
716 }
717 }
718 }
719
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000720 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
721 if (!sampler->IsProfiling()) return;
722 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
723 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
724 }
725
726 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
727 if (!sampler->isolate()->IsInitialized()) return;
728 sampler->isolate()->runtime_profiler()->NotifyTick();
729 }
730
731 void SendProfilingSignal(pthread_t tid) {
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000732 if (!signal_handler_installed_) return;
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000733 pthread_kill(tid, SIGPROF);
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000734 }
735
736 void Sleep(SleepInterval full_or_half) {
737 // Convert ms to us and subtract 100 us to compensate delays
738 // occuring during signal delivery.
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000739 useconds_t interval = interval_ * 1000 - 100;
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000740 if (full_or_half == HALF_INTERVAL) interval /= 2;
741 int result = usleep(interval);
742#ifdef DEBUG
743 if (result != 0 && errno != EINTR) {
744 fprintf(stderr,
745 "SignalSender usleep error; interval = %u, errno = %d\n",
746 interval,
747 errno);
748 ASSERT(result == 0 || errno == EINTR);
749 }
750#endif
751 USE(result);
752 }
753
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000754 const int interval_;
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000755 RuntimeProfilerRateLimiter rate_limiter_;
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000756
757 // Protects the process wide state below.
758 static Mutex* mutex_;
759 static SignalSender* instance_;
760 static bool signal_handler_installed_;
761 static struct sigaction old_signal_handler_;
762
763 DISALLOW_COPY_AND_ASSIGN(SignalSender);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000764};
765
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000766Mutex* SignalSender::mutex_ = OS::CreateMutex();
767SignalSender* SignalSender::instance_ = NULL;
768struct sigaction SignalSender::old_signal_handler_;
769bool SignalSender::signal_handler_installed_ = false;
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000770
771
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000772Sampler::Sampler(Isolate* isolate, int interval)
773 : isolate_(isolate),
774 interval_(interval),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000775 profiling_(false),
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000776 active_(false),
777 samples_taken_(0) {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000778 data_ = new PlatformData;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000779}
780
781
782Sampler::~Sampler() {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000783 ASSERT(!IsActive());
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000784 delete data_;
785}
786
787
788void Sampler::Start() {
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000789 ASSERT(!IsActive());
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000790 SetActive(true);
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000791 SignalSender::AddActiveSampler(this);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000792}
793
794
795void Sampler::Stop() {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000796 ASSERT(IsActive());
797 SignalSender::RemoveActiveSampler(this);
whesse@chromium.orgb08986c2011-03-14 16:13:42 +0000798 SetActive(false);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000799}
800
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000801} } // namespace v8::internal