platform-solaris.cc revision 85b71799222b55eb5dd74ea26efe0c64ab655c8c
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  SolarisMutex() {
464    pthread_mutexattr_t attr;
465    pthread_mutexattr_init(&attr);
466    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
467    pthread_mutex_init(&mutex_, &attr);
468  }
469
470  ~SolarisMutex() { pthread_mutex_destroy(&mutex_); }
471
472  int Lock() { return pthread_mutex_lock(&mutex_); }
473
474  int Unlock() { return pthread_mutex_unlock(&mutex_); }
475
476  virtual bool TryLock() {
477    int result = pthread_mutex_trylock(&mutex_);
478    // Return false if the lock is busy and locking failed.
479    if (result == EBUSY) {
480      return false;
481    }
482    ASSERT(result == 0);  // Verify no other errors.
483    return true;
484  }
485
486 private:
487  pthread_mutex_t mutex_;
488};
489
490
491Mutex* OS::CreateMutex() {
492  return new SolarisMutex();
493}
494
495
496class SolarisSemaphore : public Semaphore {
497 public:
498  explicit SolarisSemaphore(int count) {  sem_init(&sem_, 0, count); }
499  virtual ~SolarisSemaphore() { sem_destroy(&sem_); }
500
501  virtual void Wait();
502  virtual bool Wait(int timeout);
503  virtual void Signal() { sem_post(&sem_); }
504 private:
505  sem_t sem_;
506};
507
508
509void SolarisSemaphore::Wait() {
510  while (true) {
511    int result = sem_wait(&sem_);
512    if (result == 0) return;  // Successfully got semaphore.
513    CHECK(result == -1 && errno == EINTR);  // Signal caused spurious wakeup.
514  }
515}
516
517
518#ifndef TIMEVAL_TO_TIMESPEC
519#define TIMEVAL_TO_TIMESPEC(tv, ts) do {                            \
520    (ts)->tv_sec = (tv)->tv_sec;                                    \
521    (ts)->tv_nsec = (tv)->tv_usec * 1000;                           \
522} while (false)
523#endif
524
525
526#ifndef timeradd
527#define timeradd(a, b, result) \
528  do { \
529    (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
530    (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
531    if ((result)->tv_usec >= 1000000) { \
532      ++(result)->tv_sec; \
533      (result)->tv_usec -= 1000000; \
534    } \
535  } while (0)
536#endif
537
538
539bool SolarisSemaphore::Wait(int timeout) {
540  const long kOneSecondMicros = 1000000;  // NOLINT
541
542  // Split timeout into second and nanosecond parts.
543  struct timeval delta;
544  delta.tv_usec = timeout % kOneSecondMicros;
545  delta.tv_sec = timeout / kOneSecondMicros;
546
547  struct timeval current_time;
548  // Get the current time.
549  if (gettimeofday(&current_time, NULL) == -1) {
550    return false;
551  }
552
553  // Calculate time for end of timeout.
554  struct timeval end_time;
555  timeradd(&current_time, &delta, &end_time);
556
557  struct timespec ts;
558  TIMEVAL_TO_TIMESPEC(&end_time, &ts);
559  // Wait for semaphore signalled or timeout.
560  while (true) {
561    int result = sem_timedwait(&sem_, &ts);
562    if (result == 0) return true;  // Successfully got semaphore.
563    if (result == -1 && errno == ETIMEDOUT) return false;  // Timeout.
564    CHECK(result == -1 && errno == EINTR);  // Signal caused spurious wakeup.
565  }
566}
567
568
569Semaphore* OS::CreateSemaphore(int count) {
570  return new SolarisSemaphore(count);
571}
572
573
574static pthread_t GetThreadID() {
575  return pthread_self();
576}
577
578static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
579  USE(info);
580  if (signal != SIGPROF) return;
581  Isolate* isolate = Isolate::UncheckedCurrent();
582  if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
583    // We require a fully initialized and entered isolate.
584    return;
585  }
586  if (v8::Locker::IsActive() &&
587      !isolate->thread_manager()->IsLockedByCurrentThread()) {
588    return;
589  }
590
591  Sampler* sampler = isolate->logger()->sampler();
592  if (sampler == NULL || !sampler->IsActive()) return;
593
594  TickSample sample_obj;
595  TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
596  if (sample == NULL) sample = &sample_obj;
597
598  // Extracting the sample from the context is extremely machine dependent.
599  ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
600  mcontext_t& mcontext = ucontext->uc_mcontext;
601  sample->state = isolate->current_vm_state();
602
603  sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_PC]);
604  sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_SP]);
605  sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_FP]);
606
607  sampler->SampleStack(sample);
608  sampler->Tick(sample);
609}
610
611class Sampler::PlatformData : public Malloced {
612 public:
613  PlatformData() : vm_tid_(GetThreadID()) {}
614
615  pthread_t vm_tid() const { return vm_tid_; }
616
617 private:
618  pthread_t vm_tid_;
619};
620
621
622class SignalSender : public Thread {
623 public:
624  enum SleepInterval {
625    HALF_INTERVAL,
626    FULL_INTERVAL
627  };
628
629  explicit SignalSender(int interval)
630      : Thread("SignalSender"),
631        interval_(interval) {}
632
633  static void InstallSignalHandler() {
634    struct sigaction sa;
635    sa.sa_sigaction = ProfilerSignalHandler;
636    sigemptyset(&sa.sa_mask);
637    sa.sa_flags = SA_RESTART | SA_SIGINFO;
638    signal_handler_installed_ =
639        (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
640  }
641
642  static void RestoreSignalHandler() {
643    if (signal_handler_installed_) {
644      sigaction(SIGPROF, &old_signal_handler_, 0);
645      signal_handler_installed_ = false;
646    }
647  }
648
649  static void AddActiveSampler(Sampler* sampler) {
650    ScopedLock lock(mutex_);
651    SamplerRegistry::AddActiveSampler(sampler);
652    if (instance_ == NULL) {
653      // Start a thread that will send SIGPROF signal to VM threads,
654      // when CPU profiling will be enabled.
655      instance_ = new SignalSender(sampler->interval());
656      instance_->Start();
657    } else {
658      ASSERT(instance_->interval_ == sampler->interval());
659    }
660  }
661
662  static void RemoveActiveSampler(Sampler* sampler) {
663    ScopedLock lock(mutex_);
664    SamplerRegistry::RemoveActiveSampler(sampler);
665    if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
666      RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
667      delete instance_;
668      instance_ = NULL;
669      RestoreSignalHandler();
670    }
671  }
672
673  // Implement Thread::Run().
674  virtual void Run() {
675    SamplerRegistry::State state;
676    while ((state = SamplerRegistry::GetState()) !=
677           SamplerRegistry::HAS_NO_SAMPLERS) {
678      bool cpu_profiling_enabled =
679          (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
680      bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
681      if (cpu_profiling_enabled && !signal_handler_installed_) {
682        InstallSignalHandler();
683      } else if (!cpu_profiling_enabled && signal_handler_installed_) {
684        RestoreSignalHandler();
685      }
686
687      // When CPU profiling is enabled both JavaScript and C++ code is
688      // profiled. We must not suspend.
689      if (!cpu_profiling_enabled) {
690        if (rate_limiter_.SuspendIfNecessary()) continue;
691      }
692      if (cpu_profiling_enabled && runtime_profiler_enabled) {
693        if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
694          return;
695        }
696        Sleep(HALF_INTERVAL);
697        if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
698          return;
699        }
700        Sleep(HALF_INTERVAL);
701      } else {
702        if (cpu_profiling_enabled) {
703          if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
704                                                      this)) {
705            return;
706          }
707        }
708        if (runtime_profiler_enabled) {
709          if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
710                                                      NULL)) {
711            return;
712          }
713        }
714        Sleep(FULL_INTERVAL);
715      }
716    }
717  }
718
719  static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
720    if (!sampler->IsProfiling()) return;
721    SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
722    sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
723  }
724
725  static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
726    if (!sampler->isolate()->IsInitialized()) return;
727    sampler->isolate()->runtime_profiler()->NotifyTick();
728  }
729
730  void SendProfilingSignal(pthread_t tid) {
731    if (!signal_handler_installed_) return;
732    pthread_kill(tid, SIGPROF);
733  }
734
735  void Sleep(SleepInterval full_or_half) {
736    // Convert ms to us and subtract 100 us to compensate delays
737    // occuring during signal delivery.
738    useconds_t interval = interval_ * 1000 - 100;
739    if (full_or_half == HALF_INTERVAL) interval /= 2;
740    int result = usleep(interval);
741#ifdef DEBUG
742    if (result != 0 && errno != EINTR) {
743      fprintf(stderr,
744              "SignalSender usleep error; interval = %u, errno = %d\n",
745              interval,
746              errno);
747      ASSERT(result == 0 || errno == EINTR);
748    }
749#endif
750    USE(result);
751  }
752
753  const int interval_;
754  RuntimeProfilerRateLimiter rate_limiter_;
755
756  // Protects the process wide state below.
757  static Mutex* mutex_;
758  static SignalSender* instance_;
759  static bool signal_handler_installed_;
760  static struct sigaction old_signal_handler_;
761
762  DISALLOW_COPY_AND_ASSIGN(SignalSender);
763};
764
765Mutex* SignalSender::mutex_ = OS::CreateMutex();
766SignalSender* SignalSender::instance_ = NULL;
767struct sigaction SignalSender::old_signal_handler_;
768bool SignalSender::signal_handler_installed_ = false;
769
770
771Sampler::Sampler(Isolate* isolate, int interval)
772    : isolate_(isolate),
773      interval_(interval),
774      profiling_(false),
775      active_(false),
776      samples_taken_(0) {
777  data_ = new PlatformData;
778}
779
780
781Sampler::~Sampler() {
782  ASSERT(!IsActive());
783  delete data_;
784}
785
786
787void Sampler::Start() {
788  ASSERT(!IsActive());
789  SetActive(true);
790  SignalSender::AddActiveSampler(this);
791}
792
793
794void Sampler::Stop() {
795  ASSERT(IsActive());
796  SignalSender::RemoveActiveSampler(this);
797  SetActive(false);
798}
799
800} }  // namespace v8::internal
801