blob: 970c41864fc3dfb9d15aeab78f388555056b1544 [file] [log] [blame]
Ben Murdoch7d3e7fc2011-07-12 16:37:06 +01001// Copyright 2011 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
55#include "platform.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010056#include "vm-state-inl.h"
Leon Clarked91b9f72010-01-27 17:25:45 +000057
58
Leon Clarkef7060e22010-06-03 12:02:55 +010059// 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
Leon Clarked91b9f72010-01-27 17:25:45 +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
91void OS::Setup() {
92 // Seed the random number generator.
93 // Convert the current time to a 64-bit integer first, before converting it
94 // to an unsigned. Going directly will cause an overflow and the seed to be
95 // set to all ones. The seed will be identical for different instances that
96 // call this setup code within the same millisecond.
97 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
98 srandom(static_cast<unsigned int>(seed));
99}
100
101
102uint64_t OS::CpuFeaturesImpliedByPlatform() {
103 return 0; // Solaris runs on a lot of things.
104}
105
106
107int OS::ActivationFrameAlignment() {
Ben Murdoch7d3e7fc2011-07-12 16:37:06 +0100108 // GCC generates code that requires 16 byte alignment such as movdqa.
109 return Max(STACK_ALIGN, 16);
Leon Clarked91b9f72010-01-27 17:25:45 +0000110}
111
112
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100113void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
114 __asm__ __volatile__("" : : : "memory");
115 *ptr = value;
116}
117
118
Leon Clarked91b9f72010-01-27 17:25:45 +0000119const char* OS::LocalTimezone(double time) {
120 if (isnan(time)) return "";
121 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
122 struct tm* t = localtime(&tv);
123 if (NULL == t) return "";
124 return tzname[0]; // The location of the timezone string on Solaris.
125}
126
127
128double OS::LocalTimeOffset() {
129 // On Solaris, struct tm does not contain a tm_gmtoff field.
130 time_t utc = time(NULL);
131 ASSERT(utc != -1);
132 struct tm* loc = localtime(&utc);
133 ASSERT(loc != NULL);
134 return static_cast<double>((mktime(loc) - utc) * msPerSecond);
135}
136
137
138// We keep the lowest and highest addresses mapped as a quick way of
139// determining that pointers are outside the heap (used mostly in assertions
140// and verification). The estimate is conservative, ie, not all addresses in
141// 'allocated' space are actually allocated to our heap. The range is
142// [lowest, highest), inclusive on the low and and exclusive on the high end.
143static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
144static void* highest_ever_allocated = reinterpret_cast<void*>(0);
145
146
147static void UpdateAllocatedSpaceLimits(void* address, int size) {
148 lowest_ever_allocated = Min(lowest_ever_allocated, address);
149 highest_ever_allocated =
150 Max(highest_ever_allocated,
151 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
152}
153
154
155bool OS::IsOutsideAllocatedSpace(void* address) {
156 return address < lowest_ever_allocated || address >= highest_ever_allocated;
157}
158
159
160size_t OS::AllocateAlignment() {
161 return static_cast<size_t>(getpagesize());
162}
163
164
165void* OS::Allocate(const size_t requested,
166 size_t* allocated,
167 bool is_executable) {
168 const size_t msize = RoundUp(requested, getpagesize());
169 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
170 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
171
172 if (mbase == MAP_FAILED) {
Steve Block44f0eee2011-05-26 01:26:41 +0100173 LOG(ISOLATE, StringEvent("OS::Allocate", "mmap failed"));
Leon Clarked91b9f72010-01-27 17:25:45 +0000174 return NULL;
175 }
176 *allocated = msize;
177 UpdateAllocatedSpaceLimits(mbase, msize);
178 return mbase;
179}
180
181
182void OS::Free(void* address, const size_t size) {
183 // TODO(1240712): munmap has a return value which is ignored here.
184 int result = munmap(address, size);
185 USE(result);
186 ASSERT(result == 0);
187}
188
189
190#ifdef ENABLE_HEAP_PROTECTION
191
192void OS::Protect(void* address, size_t size) {
193 // TODO(1240712): mprotect has a return value which is ignored here.
194 mprotect(address, size, PROT_READ);
195}
196
197
198void OS::Unprotect(void* address, size_t size, bool is_executable) {
199 // TODO(1240712): mprotect has a return value which is ignored here.
200 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
201 mprotect(address, size, prot);
202}
203
204#endif
205
206
207void OS::Sleep(int milliseconds) {
208 useconds_t ms = static_cast<useconds_t>(milliseconds);
209 usleep(1000 * ms);
210}
211
212
213void OS::Abort() {
214 // Redirect to std abort to signal abnormal program termination.
215 abort();
216}
217
218
219void OS::DebugBreak() {
220 asm("int $3");
221}
222
223
224class PosixMemoryMappedFile : public OS::MemoryMappedFile {
225 public:
226 PosixMemoryMappedFile(FILE* file, void* memory, int size)
227 : file_(file), memory_(memory), size_(size) { }
228 virtual ~PosixMemoryMappedFile();
229 virtual void* memory() { return memory_; }
Steve Block1e0659c2011-05-24 12:43:12 +0100230 virtual int size() { return size_; }
Leon Clarked91b9f72010-01-27 17:25:45 +0000231 private:
232 FILE* file_;
233 void* memory_;
234 int size_;
235};
236
237
Steve Block1e0659c2011-05-24 12:43:12 +0100238OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100239 FILE* file = fopen(name, "r+");
Steve Block1e0659c2011-05-24 12:43:12 +0100240 if (file == NULL) return NULL;
241
242 fseek(file, 0, SEEK_END);
243 int size = ftell(file);
244
245 void* memory =
246 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
247 return new PosixMemoryMappedFile(file, memory, size);
248}
249
250
Leon Clarked91b9f72010-01-27 17:25:45 +0000251OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
252 void* initial) {
253 FILE* file = fopen(name, "w+");
254 if (file == NULL) return NULL;
255 int result = fwrite(initial, size, 1, file);
256 if (result < 1) {
257 fclose(file);
258 return NULL;
259 }
260 void* memory =
261 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
262 return new PosixMemoryMappedFile(file, memory, size);
263}
264
265
266PosixMemoryMappedFile::~PosixMemoryMappedFile() {
267 if (memory_) munmap(memory_, size_);
268 fclose(file_);
269}
270
271
272void OS::LogSharedLibraryAddresses() {
273}
274
275
Ben Murdochf87a2032010-10-22 12:50:53 +0100276void OS::SignalCodeMovingGC() {
277}
278
279
Leon Clarkef7060e22010-06-03 12:02:55 +0100280struct StackWalker {
281 Vector<OS::StackFrame>& frames;
282 int index;
283};
284
285
286static int StackWalkCallback(uintptr_t pc, int signo, void* data) {
287 struct StackWalker* walker = static_cast<struct StackWalker*>(data);
288 Dl_info info;
289
290 int i = walker->index;
291
292 walker->frames[i].address = reinterpret_cast<void*>(pc);
293
294 // Make sure line termination is in place.
295 walker->frames[i].text[OS::kStackWalkMaxTextLen - 1] = '\0';
296
297 Vector<char> text = MutableCStrVector(walker->frames[i].text,
298 OS::kStackWalkMaxTextLen);
299
300 if (dladdr(reinterpret_cast<void*>(pc), &info) == 0) {
301 OS::SNPrintF(text, "[0x%p]", pc);
302 } else if ((info.dli_fname != NULL && info.dli_sname != NULL)) {
303 // We have symbol info.
304 OS::SNPrintF(text, "%s'%s+0x%x", info.dli_fname, info.dli_sname, pc);
305 } else {
306 // No local symbol info.
307 OS::SNPrintF(text,
308 "%s'0x%p [0x%p]",
309 info.dli_fname,
310 pc - reinterpret_cast<uintptr_t>(info.dli_fbase),
311 pc);
312 }
313 walker->index++;
314 return 0;
315}
316
317
Leon Clarked91b9f72010-01-27 17:25:45 +0000318int OS::StackWalk(Vector<OS::StackFrame> frames) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100319 ucontext_t ctx;
320 struct StackWalker walker = { frames, 0 };
Leon Clarked91b9f72010-01-27 17:25:45 +0000321
Leon Clarkef7060e22010-06-03 12:02:55 +0100322 if (getcontext(&ctx) < 0) return kStackWalkError;
Leon Clarked91b9f72010-01-27 17:25:45 +0000323
Leon Clarkef7060e22010-06-03 12:02:55 +0100324 if (!walkcontext(&ctx, StackWalkCallback, &walker)) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000325 return kStackWalkError;
326 }
327
Leon Clarkef7060e22010-06-03 12:02:55 +0100328 return walker.index;
Leon Clarked91b9f72010-01-27 17:25:45 +0000329}
330
331
332// Constants used for mmap.
333static const int kMmapFd = -1;
334static const int kMmapFdOffset = 0;
335
336
337VirtualMemory::VirtualMemory(size_t size) {
338 address_ = mmap(NULL, size, PROT_NONE,
339 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
340 kMmapFd, kMmapFdOffset);
341 size_ = size;
342}
343
344
345VirtualMemory::~VirtualMemory() {
346 if (IsReserved()) {
347 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
348 }
349}
350
351
352bool VirtualMemory::IsReserved() {
353 return address_ != MAP_FAILED;
354}
355
356
357bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
358 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
359 if (MAP_FAILED == mmap(address, size, prot,
360 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
361 kMmapFd, kMmapFdOffset)) {
362 return false;
363 }
364
365 UpdateAllocatedSpaceLimits(address, size);
366 return true;
367}
368
369
370bool VirtualMemory::Uncommit(void* address, size_t size) {
371 return mmap(address, size, PROT_NONE,
372 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
373 kMmapFd, kMmapFdOffset) != MAP_FAILED;
374}
375
376
Ben Murdoch8b112d22011-06-08 16:22:53 +0100377class Thread::PlatformData : public Malloced {
Leon Clarked91b9f72010-01-27 17:25:45 +0000378 public:
Ben Murdoch8b112d22011-06-08 16:22:53 +0100379 PlatformData() : thread_(kNoThread) { }
Leon Clarked91b9f72010-01-27 17:25:45 +0000380
381 pthread_t thread_; // Thread handle for pthread.
382};
383
Steve Block44f0eee2011-05-26 01:26:41 +0100384Thread::Thread(Isolate* isolate, const Options& options)
Ben Murdoch8b112d22011-06-08 16:22:53 +0100385 : data_(new PlatformData()),
Steve Block44f0eee2011-05-26 01:26:41 +0100386 isolate_(isolate),
387 stack_size_(options.stack_size) {
388 set_name(options.name);
Steve Block9fac8402011-05-12 15:51:54 +0100389}
390
391
Steve Block44f0eee2011-05-26 01:26:41 +0100392Thread::Thread(Isolate* isolate, const char* name)
Ben Murdoch8b112d22011-06-08 16:22:53 +0100393 : data_(new PlatformData()),
Steve Block44f0eee2011-05-26 01:26:41 +0100394 isolate_(isolate),
395 stack_size_(0) {
Steve Block9fac8402011-05-12 15:51:54 +0100396 set_name(name);
Leon Clarked91b9f72010-01-27 17:25:45 +0000397}
398
399
400Thread::~Thread() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100401 delete data_;
Leon Clarked91b9f72010-01-27 17:25:45 +0000402}
403
404
405static void* ThreadEntry(void* arg) {
406 Thread* thread = reinterpret_cast<Thread*>(arg);
407 // This is also initialized by the first argument to pthread_create() but we
408 // don't know which thread will run first (the original thread or the new
409 // one) so we initialize it here too.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100410 thread->data()->thread_ = pthread_self();
411 ASSERT(thread->data()->thread_ != kNoThread);
Steve Block44f0eee2011-05-26 01:26:41 +0100412 Thread::SetThreadLocal(Isolate::isolate_key(), thread->isolate());
Leon Clarked91b9f72010-01-27 17:25:45 +0000413 thread->Run();
414 return NULL;
415}
416
417
Steve Block9fac8402011-05-12 15:51:54 +0100418void Thread::set_name(const char* name) {
419 strncpy(name_, name, sizeof(name_));
420 name_[sizeof(name_) - 1] = '\0';
421}
422
423
Leon Clarked91b9f72010-01-27 17:25:45 +0000424void Thread::Start() {
Steve Block44f0eee2011-05-26 01:26:41 +0100425 pthread_attr_t* attr_ptr = NULL;
426 pthread_attr_t attr;
427 if (stack_size_ > 0) {
428 pthread_attr_init(&attr);
429 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
430 attr_ptr = &attr;
431 }
Ben Murdoch8b112d22011-06-08 16:22:53 +0100432 pthread_create(&data_->thread_, NULL, ThreadEntry, this);
433 ASSERT(data_->thread_ != kNoThread);
Leon Clarked91b9f72010-01-27 17:25:45 +0000434}
435
436
437void Thread::Join() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100438 pthread_join(data_->thread_, NULL);
Leon Clarked91b9f72010-01-27 17:25:45 +0000439}
440
441
442Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
443 pthread_key_t key;
444 int result = pthread_key_create(&key, NULL);
445 USE(result);
446 ASSERT(result == 0);
447 return static_cast<LocalStorageKey>(key);
448}
449
450
451void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
452 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
453 int result = pthread_key_delete(pthread_key);
454 USE(result);
455 ASSERT(result == 0);
456}
457
458
459void* Thread::GetThreadLocal(LocalStorageKey key) {
460 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
461 return pthread_getspecific(pthread_key);
462}
463
464
465void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
466 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
467 pthread_setspecific(pthread_key, value);
468}
469
470
471void Thread::YieldCPU() {
472 sched_yield();
473}
474
475
476class SolarisMutex : public Mutex {
477 public:
478
479 SolarisMutex() {
480 pthread_mutexattr_t attr;
481 pthread_mutexattr_init(&attr);
482 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
483 pthread_mutex_init(&mutex_, &attr);
484 }
485
486 ~SolarisMutex() { pthread_mutex_destroy(&mutex_); }
487
488 int Lock() { return pthread_mutex_lock(&mutex_); }
489
490 int Unlock() { return pthread_mutex_unlock(&mutex_); }
491
Ben Murdochb8e0da22011-05-16 14:20:40 +0100492 virtual bool TryLock() {
493 int result = pthread_mutex_trylock(&mutex_);
494 // Return false if the lock is busy and locking failed.
495 if (result == EBUSY) {
496 return false;
497 }
498 ASSERT(result == 0); // Verify no other errors.
499 return true;
500 }
501
Leon Clarked91b9f72010-01-27 17:25:45 +0000502 private:
503 pthread_mutex_t mutex_;
504};
505
506
507Mutex* OS::CreateMutex() {
508 return new SolarisMutex();
509}
510
511
512class SolarisSemaphore : public Semaphore {
513 public:
514 explicit SolarisSemaphore(int count) { sem_init(&sem_, 0, count); }
515 virtual ~SolarisSemaphore() { sem_destroy(&sem_); }
516
517 virtual void Wait();
518 virtual bool Wait(int timeout);
519 virtual void Signal() { sem_post(&sem_); }
520 private:
521 sem_t sem_;
522};
523
524
525void SolarisSemaphore::Wait() {
526 while (true) {
527 int result = sem_wait(&sem_);
528 if (result == 0) return; // Successfully got semaphore.
529 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
530 }
531}
532
533
534#ifndef TIMEVAL_TO_TIMESPEC
535#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
536 (ts)->tv_sec = (tv)->tv_sec; \
537 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
538} while (false)
539#endif
540
541
542#ifndef timeradd
543#define timeradd(a, b, result) \
544 do { \
545 (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
546 (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
547 if ((result)->tv_usec >= 1000000) { \
548 ++(result)->tv_sec; \
549 (result)->tv_usec -= 1000000; \
550 } \
551 } while (0)
552#endif
553
554
555bool SolarisSemaphore::Wait(int timeout) {
556 const long kOneSecondMicros = 1000000; // NOLINT
557
558 // Split timeout into second and nanosecond parts.
559 struct timeval delta;
560 delta.tv_usec = timeout % kOneSecondMicros;
561 delta.tv_sec = timeout / kOneSecondMicros;
562
563 struct timeval current_time;
564 // Get the current time.
565 if (gettimeofday(&current_time, NULL) == -1) {
566 return false;
567 }
568
569 // Calculate time for end of timeout.
570 struct timeval end_time;
571 timeradd(&current_time, &delta, &end_time);
572
573 struct timespec ts;
574 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
575 // Wait for semaphore signalled or timeout.
576 while (true) {
577 int result = sem_timedwait(&sem_, &ts);
578 if (result == 0) return true; // Successfully got semaphore.
579 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
580 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
581 }
582}
583
584
585Semaphore* OS::CreateSemaphore(int count) {
586 return new SolarisSemaphore(count);
587}
588
589
590#ifdef ENABLE_LOGGING_AND_PROFILING
591
592static Sampler* active_sampler_ = NULL;
Ben Murdochb8e0da22011-05-16 14:20:40 +0100593static pthread_t vm_tid_ = 0;
594
Leon Clarked91b9f72010-01-27 17:25:45 +0000595
Steve Block44f0eee2011-05-26 01:26:41 +0100596static pthread_t GetThreadID() {
597 return pthread_self();
598}
599
600
Leon Clarked91b9f72010-01-27 17:25:45 +0000601static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
602 USE(info);
603 if (signal != SIGPROF) return;
Ben Murdochb8e0da22011-05-16 14:20:40 +0100604 if (active_sampler_ == NULL || !active_sampler_->IsActive()) return;
Steve Block44f0eee2011-05-26 01:26:41 +0100605 if (vm_tid_ != GetThreadID()) return;
Leon Clarked91b9f72010-01-27 17:25:45 +0000606
Ben Murdochb8e0da22011-05-16 14:20:40 +0100607 TickSample sample_obj;
608 TickSample* sample = CpuProfiler::TickSampleEvent();
609 if (sample == NULL) sample = &sample_obj;
Leon Clarked91b9f72010-01-27 17:25:45 +0000610
Ben Murdochb8e0da22011-05-16 14:20:40 +0100611 // Extracting the sample from the context is extremely machine dependent.
612 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
613 mcontext_t& mcontext = ucontext->uc_mcontext;
614 sample->state = Top::current_vm_state();
Leon Clarked91b9f72010-01-27 17:25:45 +0000615
Steve Block44f0eee2011-05-26 01:26:41 +0100616 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_PC]);
617 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_SP]);
618 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_FP]);
619
Ben Murdochb8e0da22011-05-16 14:20:40 +0100620 active_sampler_->SampleStack(sample);
621 active_sampler_->Tick(sample);
Leon Clarked91b9f72010-01-27 17:25:45 +0000622}
623
624
625class Sampler::PlatformData : public Malloced {
626 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100627 enum SleepInterval {
628 FULL_INTERVAL,
629 HALF_INTERVAL
630 };
631
632 explicit PlatformData(Sampler* sampler)
633 : sampler_(sampler),
634 signal_handler_installed_(false),
635 vm_tgid_(getpid()),
636 signal_sender_launched_(false) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000637 }
638
Steve Block44f0eee2011-05-26 01:26:41 +0100639 void SignalSender() {
640 while (sampler_->IsActive()) {
641 if (rate_limiter_.SuspendIfNecessary()) continue;
642 if (sampler_->IsProfiling() && RuntimeProfiler::IsEnabled()) {
643 SendProfilingSignal();
644 Sleep(HALF_INTERVAL);
645 RuntimeProfiler::NotifyTick();
646 Sleep(HALF_INTERVAL);
647 } else {
648 if (sampler_->IsProfiling()) SendProfilingSignal();
649 if (RuntimeProfiler::IsEnabled()) RuntimeProfiler::NotifyTick();
650 Sleep(FULL_INTERVAL);
651 }
652 }
653 }
654
655 void SendProfilingSignal() {
656 if (!signal_handler_installed_) return;
657 pthread_kill(vm_tid_, SIGPROF);
658 }
659
660 void Sleep(SleepInterval full_or_half) {
661 // Convert ms to us and subtract 100 us to compensate delays
662 // occuring during signal delivery.
663 useconds_t interval = sampler_->interval_ * 1000 - 100;
664 if (full_or_half == HALF_INTERVAL) interval /= 2;
665 int result = usleep(interval);
666#ifdef DEBUG
667 if (result != 0 && errno != EINTR) {
668 fprintf(stderr,
669 "SignalSender usleep error; interval = %u, errno = %d\n",
670 interval,
671 errno);
672 ASSERT(result == 0 || errno == EINTR);
673 }
674#endif
675 USE(result);
676 }
677
678 Sampler* sampler_;
Leon Clarked91b9f72010-01-27 17:25:45 +0000679 bool signal_handler_installed_;
680 struct sigaction old_signal_handler_;
Steve Block44f0eee2011-05-26 01:26:41 +0100681 int vm_tgid_;
682 bool signal_sender_launched_;
683 pthread_t signal_sender_thread_;
684 RuntimeProfilerRateLimiter rate_limiter_;
Leon Clarked91b9f72010-01-27 17:25:45 +0000685};
686
687
Steve Block44f0eee2011-05-26 01:26:41 +0100688static void* SenderEntry(void* arg) {
689 Sampler::PlatformData* data =
690 reinterpret_cast<Sampler::PlatformData*>(arg);
691 data->SignalSender();
692 return 0;
693}
694
695
696Sampler::Sampler(Isolate* isolate, int interval)
697 : isolate_(isolate),
698 interval_(interval),
Ben Murdochb0fe1622011-05-05 13:52:32 +0100699 profiling_(false),
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800700 active_(false),
701 samples_taken_(0) {
Steve Block44f0eee2011-05-26 01:26:41 +0100702 data_ = new PlatformData(this);
Leon Clarked91b9f72010-01-27 17:25:45 +0000703}
704
705
706Sampler::~Sampler() {
Steve Block44f0eee2011-05-26 01:26:41 +0100707 ASSERT(!data_->signal_sender_launched_);
Leon Clarked91b9f72010-01-27 17:25:45 +0000708 delete data_;
709}
710
711
712void Sampler::Start() {
713 // There can only be one active sampler at the time on POSIX
714 // platforms.
Steve Block44f0eee2011-05-26 01:26:41 +0100715 ASSERT(!IsActive());
716 vm_tid_ = GetThreadID();
Leon Clarked91b9f72010-01-27 17:25:45 +0000717
718 // Request profiling signals.
719 struct sigaction sa;
720 sa.sa_sigaction = ProfilerSignalHandler;
721 sigemptyset(&sa.sa_mask);
Steve Block44f0eee2011-05-26 01:26:41 +0100722 sa.sa_flags = SA_RESTART | SA_SIGINFO;
723 data_->signal_handler_installed_ =
724 sigaction(SIGPROF, &sa, &data_->old_signal_handler_) == 0;
Leon Clarked91b9f72010-01-27 17:25:45 +0000725
Steve Block44f0eee2011-05-26 01:26:41 +0100726 // Start a thread that sends SIGPROF signal to VM thread.
727 // Sending the signal ourselves instead of relying on itimer provides
728 // much better accuracy.
729 SetActive(true);
730 if (pthread_create(
731 &data_->signal_sender_thread_, NULL, SenderEntry, data_) == 0) {
732 data_->signal_sender_launched_ = true;
733 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000734
735 // Set this sampler as the active sampler.
736 active_sampler_ = this;
Leon Clarked91b9f72010-01-27 17:25:45 +0000737}
738
739
740void Sampler::Stop() {
Steve Block44f0eee2011-05-26 01:26:41 +0100741 SetActive(false);
742
743 // Wait for signal sender termination (it will exit after setting
744 // active_ to false).
745 if (data_->signal_sender_launched_) {
746 Top::WakeUpRuntimeProfilerThreadBeforeShutdown();
747 pthread_join(data_->signal_sender_thread_, NULL);
748 data_->signal_sender_launched_ = false;
749 }
750
Leon Clarked91b9f72010-01-27 17:25:45 +0000751 // Restore old signal handler
752 if (data_->signal_handler_installed_) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000753 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
754 data_->signal_handler_installed_ = false;
755 }
756
757 // This sampler is no longer the active sampler.
758 active_sampler_ = NULL;
Leon Clarked91b9f72010-01-27 17:25:45 +0000759}
760
761#endif // ENABLE_LOGGING_AND_PROFILING
762
763} } // namespace v8::internal