platform-solaris.cc revision 3fb3ca8c7ca439d408449a395897395c0faae8d1
1// Copyright 2011 the V8 project authors. All rights reserved.
2// 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()
38#include <ucontext.h>  // walkstack(), getcontext()
39#include <dlfcn.h>     // dladdr
40#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
48#include <sys/regset.h>
49
50
51#undef MAP_TYPE
52
53#include "v8.h"
54
55#include "platform.h"
56#include "vm-state-inl.h"
57
58
59// 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
77namespace 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
91static Mutex* limit_mutex = NULL;
92void 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));
100  limit_mutex = CreateMutex();
101}
102
103
104uint64_t OS::CpuFeaturesImpliedByPlatform() {
105  return 0;  // Solaris runs on a lot of things.
106}
107
108
109int OS::ActivationFrameAlignment() {
110  // GCC generates code that requires 16 byte alignment such as movdqa.
111  return Max(STACK_ALIGN, 16);
112}
113
114
115void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
116  __asm__ __volatile__("" : : : "memory");
117  *ptr = value;
118}
119
120
121const 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) {
150  ASSERT(limit_mutex != NULL);
151  ScopedLock lock(limit_mutex);
152
153  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) {
178    LOG(ISOLATE, StringEvent("OS::Allocate", "mmap failed"));
179    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
195void 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_; }
218  virtual int size() { return size_; }
219 private:
220  FILE* file_;
221  void* memory_;
222  int size_;
223};
224
225
226OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
227  FILE* file = fopen(name, "r+");
228  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
239OS::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
264void OS::SignalCodeMovingGC() {
265}
266
267
268struct 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
306int OS::StackWalk(Vector<OS::StackFrame> frames) {
307  ucontext_t ctx;
308  struct StackWalker walker = { frames, 0 };
309
310  if (getcontext(&ctx) < 0) return kStackWalkError;
311
312  if (!walkcontext(&ctx, StackWalkCallback, &walker)) {
313    return kStackWalkError;
314  }
315
316  return walker.index;
317}
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
365class Thread::PlatformData : public Malloced {
366 public:
367  PlatformData() : thread_(kNoThread) {  }
368
369  pthread_t thread_;  // Thread handle for pthread.
370};
371
372Thread::Thread(const Options& options)
373    : data_(new PlatformData()),
374      stack_size_(options.stack_size) {
375  set_name(options.name);
376}
377
378
379Thread::Thread(const char* name)
380    : data_(new PlatformData()),
381      stack_size_(0) {
382  set_name(name);
383}
384
385
386Thread::~Thread() {
387  delete data_;
388}
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.
396  thread->data()->thread_ = pthread_self();
397  ASSERT(thread->data()->thread_ != kNoThread);
398  thread->Run();
399  return NULL;
400}
401
402
403void Thread::set_name(const char* name) {
404  strncpy(name_, name, sizeof(name_));
405  name_[sizeof(name_) - 1] = '\0';
406}
407
408
409void Thread::Start() {
410  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  }
417  pthread_create(&data_->thread_, NULL, ThreadEntry, this);
418  ASSERT(data_->thread_ != kNoThread);
419}
420
421
422void Thread::Join() {
423  pthread_join(data_->thread_, NULL);
424}
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
477  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
487 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
575static pthread_t GetThreadID() {
576  return pthread_self();
577}
578
579static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
580  USE(info);
581  if (signal != SIGPROF) return;
582  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;
594
595  TickSample sample_obj;
596  TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
597  if (sample == NULL) sample = &sample_obj;
598
599  // 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;
602  sample->state = isolate->current_vm_state();
603
604  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
608  sampler->SampleStack(sample);
609  sampler->Tick(sample);
610}
611
612class Sampler::PlatformData : public Malloced {
613 public:
614  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:
625  enum SleepInterval {
626    HALF_INTERVAL,
627    FULL_INTERVAL
628  };
629
630  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);
641  }
642
643  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) {
667      RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
668      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        }
697        Sleep(HALF_INTERVAL);
698        if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
699          return;
700        }
701        Sleep(HALF_INTERVAL);
702      } else {
703        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        }
715        Sleep(FULL_INTERVAL);
716      }
717    }
718  }
719
720  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) {
732    if (!signal_handler_installed_) return;
733    pthread_kill(tid, SIGPROF);
734  }
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.
739    useconds_t interval = interval_ * 1000 - 100;
740    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
754  const int interval_;
755  RuntimeProfilerRateLimiter rate_limiter_;
756
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);
764};
765
766Mutex* SignalSender::mutex_ = OS::CreateMutex();
767SignalSender* SignalSender::instance_ = NULL;
768struct sigaction SignalSender::old_signal_handler_;
769bool SignalSender::signal_handler_installed_ = false;
770
771
772Sampler::Sampler(Isolate* isolate, int interval)
773    : isolate_(isolate),
774      interval_(interval),
775      profiling_(false),
776      active_(false),
777      samples_taken_(0) {
778  data_ = new PlatformData;
779}
780
781
782Sampler::~Sampler() {
783  ASSERT(!IsActive());
784  delete data_;
785}
786
787
788void Sampler::Start() {
789  ASSERT(!IsActive());
790  SetActive(true);
791  SignalSender::AddActiveSampler(this);
792}
793
794
795void Sampler::Stop() {
796  ASSERT(IsActive());
797  SignalSender::RemoveActiveSampler(this);
798  SetActive(false);
799}
800
801} }  // namespace v8::internal
802