1 // Copyright 2012 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
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.
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.
28 // Platform specific code for Linux goes here. For the POSIX comaptible parts
29 // the implementation is in platform-posix.cc.
32 #include <semaphore.h>
34 #include <sys/prctl.h>
36 #include <sys/resource.h>
37 #include <sys/syscall.h>
38 #include <sys/types.h>
41 // Ubuntu Dapper requires memory pages to be marked as
42 // executable. Otherwise, OS raises an exception when executing code
44 #include <sys/types.h> // mmap & munmap
45 #include <sys/mman.h> // mmap & munmap
46 #include <sys/stat.h> // open
47 #include <fcntl.h> // open
48 #include <unistd.h> // sysconf
49 #if defined(__GLIBC__) && !defined(__UCLIBC__)
50 #include <execinfo.h> // backtrace, backtrace_symbols
51 #endif // defined(__GLIBC__) && !defined(__UCLIBC__)
52 #include <strings.h> // index
60 #include "platform-posix.h"
62 #include "v8threads.h"
63 #include "vm-state-inl.h"
69 // 0 is never a valid thread id on Linux since tids and pids share a
70 // name space and pid 0 is reserved (see man 2 kill).
71 static const pthread_t kNoThread = (pthread_t) 0;
74 double ceiling(double x) {
79 static Mutex* limit_mutex = NULL;
82 void OS::PostSetUp() {
87 uint64_t OS::CpuFeaturesImpliedByPlatform() {
88 return 0; // Linux runs on anything.
93 static bool CPUInfoContainsString(const char * search_string) {
94 const char* file_name = "/proc/cpuinfo";
95 // This is written as a straight shot one pass parser
96 // and not using STL string and ifstream because,
97 // on Linux, it's reading from a (non-mmap-able)
98 // character special device.
100 const char* what = search_string;
102 if (NULL == (f = fopen(file_name, "r")))
106 while (EOF != (k = fgetc(f))) {
109 while ((*what != '\0') && (*what == fgetc(f))) {
116 what = search_string;
122 // Did not find string in the proc file.
127 bool OS::ArmCpuHasFeature(CpuFeature feature) {
128 const char* search_string = NULL;
129 // Simple detection of VFP at runtime for Linux.
130 // It is based on /proc/cpuinfo, which reveals hardware configuration
131 // to user-space applications. According to ARM (mid 2009), no similar
132 // facility is universally available on the ARM architectures,
133 // so it's up to individual OSes to provide such.
136 search_string = "vfpv3";
139 search_string = "ARMv7";
145 if (CPUInfoContainsString(search_string)) {
149 if (feature == VFP3) {
150 // Some old kernels will report vfp not vfpv3. Here we make a last attempt
151 // to detect vfpv3 by checking for vfp *and* neon, since neon is only
152 // available on architectures with vfpv3.
153 // Checking neon on its own is not enough as it is possible to have neon
155 if (CPUInfoContainsString("vfp") && CPUInfoContainsString("neon")) {
164 // Simple helper function to detect whether the C code is compiled with
165 // option -mfloat-abi=hard. The register d0 is loaded with 1.0 and the register
166 // pair r0, r1 is loaded with 0.0. If -mfloat-abi=hard is pased to GCC then
167 // calling this will return 1.0 and otherwise 0.0.
168 static void ArmUsingHardFloatHelper() {
169 asm("mov r0, #0":::"r0");
170 #if defined(__VFP_FP__) && !defined(__SOFTFP__)
171 // Load 0x3ff00000 into r1 using instructions available in both ARM
173 asm("mov r1, #3":::"r1");
174 asm("mov r2, #255":::"r2");
175 asm("lsl r1, r1, #8":::"r1");
176 asm("orr r1, r1, r2":::"r1");
177 asm("lsl r1, r1, #20":::"r1");
178 // For vmov d0, r0, r1 use ARM mode.
181 "@ Enter ARM Mode \n\t"
186 "1: vmov d0, r0, r1 \n\t"
187 "@ Enter THUMB Mode\n\t"
193 asm("vmov d0, r0, r1");
195 #endif // defined(__VFP_FP__) && !defined(__SOFTFP__)
196 asm("mov r1, #0":::"r1");
200 bool OS::ArmUsingHardFloat() {
201 // Cast helper function from returning void to returning double.
202 typedef double (*F)();
203 F f = FUNCTION_CAST<F>(FUNCTION_ADDR(ArmUsingHardFloatHelper));
206 #endif // def __arm__
210 bool OS::MipsCpuHasFeature(CpuFeature feature) {
211 const char* search_string = NULL;
212 const char* file_name = "/proc/cpuinfo";
213 // Simple detection of FPU at runtime for Linux.
214 // It is based on /proc/cpuinfo, which reveals hardware configuration
215 // to user-space applications. According to MIPS (early 2010), no similar
216 // facility is universally available on the MIPS architectures,
217 // so it's up to individual OSes to provide such.
219 // This is written as a straight shot one pass parser
220 // and not using STL string and ifstream because,
221 // on Linux, it's reading from a (non-mmap-able)
222 // character special device.
226 search_string = "FPU";
233 const char* what = search_string;
235 if (NULL == (f = fopen(file_name, "r")))
239 while (EOF != (k = fgetc(f))) {
242 while ((*what != '\0') && (*what == fgetc(f))) {
249 what = search_string;
255 // Did not find string in the proc file.
258 #endif // def __mips__
261 int OS::ActivationFrameAlignment() {
262 #ifdef V8_TARGET_ARCH_ARM
263 // On EABI ARM targets this is required for fp correctness in the
266 #elif V8_TARGET_ARCH_MIPS
269 // With gcc 4.4 the tree vectorization optimizer can generate code
270 // that requires 16 byte alignment such as movdqa on x86.
275 void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
276 #if (defined(V8_TARGET_ARCH_ARM) && defined(__arm__)) || \
277 (defined(V8_TARGET_ARCH_MIPS) && defined(__mips__))
278 // Only use on ARM or MIPS hardware.
281 __asm__ __volatile__("" : : : "memory");
282 // An x86 store acts as a release barrier.
288 const char* OS::LocalTimezone(double time) {
289 if (isnan(time)) return "";
290 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
291 struct tm* t = localtime(&tv);
292 if (NULL == t) return "";
297 double OS::LocalTimeOffset() {
298 time_t tv = time(NULL);
299 struct tm* t = localtime(&tv);
300 // tm_gmtoff includes any daylight savings offset, so subtract it.
301 return static_cast<double>(t->tm_gmtoff * msPerSecond -
302 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
306 // We keep the lowest and highest addresses mapped as a quick way of
307 // determining that pointers are outside the heap (used mostly in assertions
308 // and verification). The estimate is conservative, i.e., not all addresses in
309 // 'allocated' space are actually allocated to our heap. The range is
310 // [lowest, highest), inclusive on the low and and exclusive on the high end.
311 static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
312 static void* highest_ever_allocated = reinterpret_cast<void*>(0);
315 static void UpdateAllocatedSpaceLimits(void* address, int size) {
316 ASSERT(limit_mutex != NULL);
317 ScopedLock lock(limit_mutex);
319 lowest_ever_allocated = Min(lowest_ever_allocated, address);
320 highest_ever_allocated =
321 Max(highest_ever_allocated,
322 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
326 bool OS::IsOutsideAllocatedSpace(void* address) {
327 return address < lowest_ever_allocated || address >= highest_ever_allocated;
331 size_t OS::AllocateAlignment() {
332 return sysconf(_SC_PAGESIZE);
336 void* OS::Allocate(const size_t requested,
338 bool is_executable) {
339 const size_t msize = RoundUp(requested, AllocateAlignment());
340 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
341 void* addr = OS::GetRandomMmapAddr();
342 void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
343 if (mbase == MAP_FAILED) {
344 LOG(i::Isolate::Current(),
345 StringEvent("OS::Allocate", "mmap failed"));
349 UpdateAllocatedSpaceLimits(mbase, msize);
354 void OS::Free(void* address, const size_t size) {
355 // TODO(1240712): munmap has a return value which is ignored here.
356 int result = munmap(address, size);
362 void OS::Sleep(int milliseconds) {
363 unsigned int ms = static_cast<unsigned int>(milliseconds);
369 // Redirect to std abort to signal abnormal program termination.
370 if (FLAG_break_on_abort) {
377 void OS::DebugBreak() {
378 // TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
379 // which is the architecture of generated code).
380 #if (defined(__arm__) || defined(__thumb__))
381 # if defined(CAN_USE_ARMV5_INSTRUCTIONS)
384 #elif defined(__mips__)
392 class PosixMemoryMappedFile : public OS::MemoryMappedFile {
394 PosixMemoryMappedFile(FILE* file, void* memory, int size)
395 : file_(file), memory_(memory), size_(size) { }
396 virtual ~PosixMemoryMappedFile();
397 virtual void* memory() { return memory_; }
398 virtual int size() { return size_; }
406 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
407 FILE* file = fopen(name, "r+");
408 if (file == NULL) return NULL;
410 fseek(file, 0, SEEK_END);
411 int size = ftell(file);
414 mmap(OS::GetRandomMmapAddr(),
416 PROT_READ | PROT_WRITE,
420 return new PosixMemoryMappedFile(file, memory, size);
424 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
426 FILE* file = fopen(name, "w+");
427 if (file == NULL) return NULL;
428 int result = fwrite(initial, size, 1, file);
434 mmap(OS::GetRandomMmapAddr(),
436 PROT_READ | PROT_WRITE,
440 return new PosixMemoryMappedFile(file, memory, size);
444 PosixMemoryMappedFile::~PosixMemoryMappedFile() {
445 if (memory_) OS::Free(memory_, size_);
450 void OS::LogSharedLibraryAddresses() {
451 // This function assumes that the layout of the file is as follows:
452 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
453 // If we encounter an unexpected situation we abort scanning further entries.
454 FILE* fp = fopen("/proc/self/maps", "r");
455 if (fp == NULL) return;
457 // Allocate enough room to be able to store a full file name.
458 const int kLibNameLen = FILENAME_MAX + 1;
459 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
461 i::Isolate* isolate = ISOLATE;
462 // This loop will terminate once the scanning hits an EOF.
464 uintptr_t start, end;
465 char attr_r, attr_w, attr_x, attr_p;
466 // Parse the addresses and permission bits at the beginning of the line.
467 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
468 if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break;
471 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
472 // Found a read-only executable entry. Skip characters until we reach
473 // the beginning of the filename or the end of the line.
476 } while ((c != EOF) && (c != '\n') && (c != '/'));
477 if (c == EOF) break; // EOF: Was unexpected, just exit.
479 // Process the filename if found.
481 ungetc(c, fp); // Push the '/' back into the stream to be read below.
483 // Read to the end of the line. Exit if the read fails.
484 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
486 // Drop the newline character read by fgets. We do not need to check
487 // for a zero-length string because we know that we at least read the
489 lib_name[strlen(lib_name) - 1] = '\0';
491 // No library name found, just record the raw address range.
492 snprintf(lib_name, kLibNameLen,
493 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
495 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
497 // Entry not describing executable data. Skip to end of line to set up
498 // reading the next entry.
501 } while ((c != EOF) && (c != '\n'));
510 static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
513 void OS::SignalCodeMovingGC() {
514 // Support for ll_prof.py.
516 // The Linux profiler built into the kernel logs all mmap's with
517 // PROT_EXEC so that analysis tools can properly attribute ticks. We
518 // do a mmap with a name known by ll_prof.py and immediately munmap
519 // it. This injects a GC marker into the stream of events generated
520 // by the kernel and allows us to synchronize V8 code log and the
522 int size = sysconf(_SC_PAGESIZE);
523 FILE* f = fopen(kGCFakeMmap, "w+");
524 void* addr = mmap(OS::GetRandomMmapAddr(),
526 PROT_READ | PROT_EXEC,
530 ASSERT(addr != MAP_FAILED);
531 OS::Free(addr, size);
536 int OS::StackWalk(Vector<OS::StackFrame> frames) {
537 // backtrace is a glibc extension.
538 #if defined(__GLIBC__) && !defined(__UCLIBC__)
539 int frames_size = frames.length();
540 ScopedVector<void*> addresses(frames_size);
542 int frames_count = backtrace(addresses.start(), frames_size);
544 char** symbols = backtrace_symbols(addresses.start(), frames_count);
545 if (symbols == NULL) {
546 return kStackWalkError;
549 for (int i = 0; i < frames_count; i++) {
550 frames[i].address = addresses[i];
551 // Format a text representation of the frame based on the information
553 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
556 // Make sure line termination is in place.
557 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
563 #else // defined(__GLIBC__) && !defined(__UCLIBC__)
565 #endif // defined(__GLIBC__) && !defined(__UCLIBC__)
569 // Constants used for mmap.
570 static const int kMmapFd = -1;
571 static const int kMmapFdOffset = 0;
573 VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
575 VirtualMemory::VirtualMemory(size_t size) {
576 address_ = ReserveRegion(size);
581 VirtualMemory::VirtualMemory(size_t size, size_t alignment)
582 : address_(NULL), size_(0) {
583 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
584 size_t request_size = RoundUp(size + alignment,
585 static_cast<intptr_t>(OS::AllocateAlignment()));
586 void* reservation = mmap(OS::GetRandomMmapAddr(),
589 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
592 if (reservation == MAP_FAILED) return;
594 Address base = static_cast<Address>(reservation);
595 Address aligned_base = RoundUp(base, alignment);
596 ASSERT_LE(base, aligned_base);
598 // Unmap extra memory reserved before and after the desired block.
599 if (aligned_base != base) {
600 size_t prefix_size = static_cast<size_t>(aligned_base - base);
601 OS::Free(base, prefix_size);
602 request_size -= prefix_size;
605 size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
606 ASSERT_LE(aligned_size, request_size);
608 if (aligned_size != request_size) {
609 size_t suffix_size = request_size - aligned_size;
610 OS::Free(aligned_base + aligned_size, suffix_size);
611 request_size -= suffix_size;
614 ASSERT(aligned_size == request_size);
616 address_ = static_cast<void*>(aligned_base);
617 size_ = aligned_size;
621 VirtualMemory::~VirtualMemory() {
623 bool result = ReleaseRegion(address(), size());
630 bool VirtualMemory::IsReserved() {
631 return address_ != NULL;
635 void VirtualMemory::Reset() {
641 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
642 return CommitRegion(address, size, is_executable);
646 bool VirtualMemory::Uncommit(void* address, size_t size) {
647 return UncommitRegion(address, size);
651 bool VirtualMemory::Guard(void* address) {
652 OS::Guard(address, OS::CommitPageSize());
657 void* VirtualMemory::ReserveRegion(size_t size) {
658 void* result = mmap(OS::GetRandomMmapAddr(),
661 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
665 if (result == MAP_FAILED) return NULL;
671 bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
672 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
673 if (MAP_FAILED == mmap(base,
676 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
682 UpdateAllocatedSpaceLimits(base, size);
687 bool VirtualMemory::UncommitRegion(void* base, size_t size) {
691 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
693 kMmapFdOffset) != MAP_FAILED;
697 bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
698 return munmap(base, size) == 0;
702 class Thread::PlatformData : public Malloced {
704 PlatformData() : thread_(kNoThread) {}
706 pthread_t thread_; // Thread handle for pthread.
709 Thread::Thread(const Options& options)
710 : data_(new PlatformData()),
711 stack_size_(options.stack_size()) {
712 set_name(options.name());
721 static void* ThreadEntry(void* arg) {
722 Thread* thread = reinterpret_cast<Thread*>(arg);
723 // This is also initialized by the first argument to pthread_create() but we
724 // don't know which thread will run first (the original thread or the new
725 // one) so we initialize it here too.
728 reinterpret_cast<unsigned long>(thread->name()), // NOLINT
731 thread->data()->thread_ = pthread_self();
732 ASSERT(thread->data()->thread_ != kNoThread);
738 void Thread::set_name(const char* name) {
739 strncpy(name_, name, sizeof(name_));
740 name_[sizeof(name_) - 1] = '\0';
744 void Thread::Start() {
745 pthread_attr_t* attr_ptr = NULL;
747 if (stack_size_ > 0) {
748 pthread_attr_init(&attr);
749 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
752 int result = pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
754 ASSERT(data_->thread_ != kNoThread);
758 void Thread::Join() {
759 pthread_join(data_->thread_, NULL);
763 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
765 int result = pthread_key_create(&key, NULL);
768 return static_cast<LocalStorageKey>(key);
772 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
773 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
774 int result = pthread_key_delete(pthread_key);
780 void* Thread::GetThreadLocal(LocalStorageKey key) {
781 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
782 return pthread_getspecific(pthread_key);
786 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
787 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
788 pthread_setspecific(pthread_key, value);
792 void Thread::YieldCPU() {
797 class LinuxMutex : public Mutex {
800 pthread_mutexattr_t attrs;
801 int result = pthread_mutexattr_init(&attrs);
803 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
805 result = pthread_mutex_init(&mutex_, &attrs);
810 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
813 int result = pthread_mutex_lock(&mutex_);
817 virtual int Unlock() {
818 int result = pthread_mutex_unlock(&mutex_);
822 virtual bool TryLock() {
823 int result = pthread_mutex_trylock(&mutex_);
824 // Return false if the lock is busy and locking failed.
825 if (result == EBUSY) {
828 ASSERT(result == 0); // Verify no other errors.
833 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
837 Mutex* OS::CreateMutex() {
838 return new LinuxMutex();
842 class LinuxSemaphore : public Semaphore {
844 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
845 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
848 virtual bool Wait(int timeout);
849 virtual void Signal() { sem_post(&sem_); }
855 void LinuxSemaphore::Wait() {
857 int result = sem_wait(&sem_);
858 if (result == 0) return; // Successfully got semaphore.
859 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
864 #ifndef TIMEVAL_TO_TIMESPEC
865 #define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
866 (ts)->tv_sec = (tv)->tv_sec; \
867 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
872 bool LinuxSemaphore::Wait(int timeout) {
873 const long kOneSecondMicros = 1000000; // NOLINT
875 // Split timeout into second and nanosecond parts.
876 struct timeval delta;
877 delta.tv_usec = timeout % kOneSecondMicros;
878 delta.tv_sec = timeout / kOneSecondMicros;
880 struct timeval current_time;
881 // Get the current time.
882 if (gettimeofday(¤t_time, NULL) == -1) {
886 // Calculate time for end of timeout.
887 struct timeval end_time;
888 timeradd(¤t_time, &delta, &end_time);
891 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
892 // Wait for semaphore signalled or timeout.
894 int result = sem_timedwait(&sem_, &ts);
895 if (result == 0) return true; // Successfully got semaphore.
897 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
901 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
902 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
907 Semaphore* OS::CreateSemaphore(int count) {
908 return new LinuxSemaphore(count);
912 #if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
913 // Android runs a fairly new Linux kernel, so signal info is there,
914 // but the C library doesn't have the structs defined.
922 uint32_t fault_address;
924 typedef uint32_t __sigset_t;
925 typedef struct sigcontext mcontext_t;
926 typedef struct ucontext {
928 struct ucontext* uc_link;
930 mcontext_t uc_mcontext;
931 __sigset_t uc_sigmask;
933 enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
935 #elif !defined(__GLIBC__) && defined(__mips__)
936 // MIPS version of sigcontext, for Android bionic.
957 typedef uint32_t __sigset_t;
958 typedef struct sigcontext mcontext_t;
959 typedef struct ucontext {
961 struct ucontext* uc_link;
963 mcontext_t uc_mcontext;
964 __sigset_t uc_sigmask;
967 #elif !defined(__GLIBC__) && defined(__i386__)
968 // x86 version for Android.
976 typedef uint32_t __sigset_t;
977 typedef struct sigcontext mcontext_t;
978 typedef struct ucontext {
980 struct ucontext* uc_link;
982 mcontext_t uc_mcontext;
983 __sigset_t uc_sigmask;
985 enum { REG_EBP = 6, REG_ESP = 7, REG_EIP = 14 };
989 static int GetThreadID() {
990 // Glibc doesn't provide a wrapper for gettid(2).
992 return syscall(__NR_gettid);
994 return syscall(SYS_gettid);
999 static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
1001 if (signal != SIGPROF) return;
1002 Isolate* isolate = Isolate::UncheckedCurrent();
1003 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
1004 // We require a fully initialized and entered isolate.
1007 if (v8::Locker::IsActive() &&
1008 !isolate->thread_manager()->IsLockedByCurrentThread()) {
1012 Sampler* sampler = isolate->logger()->sampler();
1013 if (sampler == NULL || !sampler->IsActive()) return;
1015 TickSample sample_obj;
1016 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
1017 if (sample == NULL) sample = &sample_obj;
1019 // Extracting the sample from the context is extremely machine dependent.
1020 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
1021 mcontext_t& mcontext = ucontext->uc_mcontext;
1022 sample->state = isolate->current_vm_state();
1023 #if V8_HOST_ARCH_IA32
1024 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
1025 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
1026 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
1027 #elif V8_HOST_ARCH_X64
1028 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
1029 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
1030 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
1031 #elif V8_HOST_ARCH_ARM
1032 // An undefined macro evaluates to 0, so this applies to Android's Bionic also.
1033 #if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
1034 sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
1035 sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
1036 sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
1038 sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
1039 sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
1040 sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
1041 #endif // (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
1042 #elif V8_HOST_ARCH_MIPS
1043 sample->pc = reinterpret_cast<Address>(mcontext.pc);
1044 sample->sp = reinterpret_cast<Address>(mcontext.gregs[29]);
1045 sample->fp = reinterpret_cast<Address>(mcontext.gregs[30]);
1046 #endif // V8_HOST_ARCH_*
1047 sampler->SampleStack(sample);
1048 sampler->Tick(sample);
1052 class Sampler::PlatformData : public Malloced {
1054 PlatformData() : vm_tid_(GetThreadID()) {}
1056 int vm_tid() const { return vm_tid_; }
1063 class SignalSender : public Thread {
1065 enum SleepInterval {
1070 static const int kSignalSenderStackSize = 64 * KB;
1072 explicit SignalSender(int interval)
1073 : Thread(Thread::Options("SignalSender", kSignalSenderStackSize)),
1075 interval_(interval) {}
1077 static void SetUp() { if (!mutex_) mutex_ = OS::CreateMutex(); }
1078 static void TearDown() { delete mutex_; }
1080 static void InstallSignalHandler() {
1081 struct sigaction sa;
1082 sa.sa_sigaction = ProfilerSignalHandler;
1083 sigemptyset(&sa.sa_mask);
1084 sa.sa_flags = SA_RESTART | SA_SIGINFO;
1085 signal_handler_installed_ =
1086 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
1089 static void RestoreSignalHandler() {
1090 if (signal_handler_installed_) {
1091 sigaction(SIGPROF, &old_signal_handler_, 0);
1092 signal_handler_installed_ = false;
1096 static void AddActiveSampler(Sampler* sampler) {
1097 ScopedLock lock(mutex_);
1098 SamplerRegistry::AddActiveSampler(sampler);
1099 if (instance_ == NULL) {
1100 // Start a thread that will send SIGPROF signal to VM threads,
1101 // when CPU profiling will be enabled.
1102 instance_ = new SignalSender(sampler->interval());
1105 ASSERT(instance_->interval_ == sampler->interval());
1109 static void RemoveActiveSampler(Sampler* sampler) {
1110 ScopedLock lock(mutex_);
1111 SamplerRegistry::RemoveActiveSampler(sampler);
1112 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
1113 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
1116 RestoreSignalHandler();
1120 // Implement Thread::Run().
1121 virtual void Run() {
1122 SamplerRegistry::State state;
1123 while ((state = SamplerRegistry::GetState()) !=
1124 SamplerRegistry::HAS_NO_SAMPLERS) {
1125 bool cpu_profiling_enabled =
1126 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1127 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
1128 if (cpu_profiling_enabled && !signal_handler_installed_) {
1129 InstallSignalHandler();
1130 } else if (!cpu_profiling_enabled && signal_handler_installed_) {
1131 RestoreSignalHandler();
1133 // When CPU profiling is enabled both JavaScript and C++ code is
1134 // profiled. We must not suspend.
1135 if (!cpu_profiling_enabled) {
1136 if (rate_limiter_.SuspendIfNecessary()) continue;
1138 if (cpu_profiling_enabled && runtime_profiler_enabled) {
1139 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1142 Sleep(HALF_INTERVAL);
1143 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1146 Sleep(HALF_INTERVAL);
1148 if (cpu_profiling_enabled) {
1149 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
1154 if (runtime_profiler_enabled) {
1155 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
1160 Sleep(FULL_INTERVAL);
1165 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
1166 if (!sampler->IsProfiling()) return;
1167 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
1168 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
1171 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1172 if (!sampler->isolate()->IsInitialized()) return;
1173 sampler->isolate()->runtime_profiler()->NotifyTick();
1176 void SendProfilingSignal(int tid) {
1177 if (!signal_handler_installed_) return;
1178 // Glibc doesn't provide a wrapper for tgkill(2).
1179 #if defined(ANDROID)
1180 syscall(__NR_tgkill, vm_tgid_, tid, SIGPROF);
1182 syscall(SYS_tgkill, vm_tgid_, tid, SIGPROF);
1186 void Sleep(SleepInterval full_or_half) {
1187 // Convert ms to us and subtract 100 us to compensate delays
1188 // occuring during signal delivery.
1189 useconds_t interval = interval_ * 1000 - 100;
1190 if (full_or_half == HALF_INTERVAL) interval /= 2;
1191 #if defined(ANDROID)
1194 int result = usleep(interval);
1196 if (result != 0 && errno != EINTR) {
1198 "SignalSender usleep error; interval = %u, errno = %d\n",
1201 ASSERT(result == 0 || errno == EINTR);
1209 const int interval_;
1210 RuntimeProfilerRateLimiter rate_limiter_;
1212 // Protects the process wide state below.
1213 static Mutex* mutex_;
1214 static SignalSender* instance_;
1215 static bool signal_handler_installed_;
1216 static struct sigaction old_signal_handler_;
1219 DISALLOW_COPY_AND_ASSIGN(SignalSender);
1223 Mutex* SignalSender::mutex_ = NULL;
1224 SignalSender* SignalSender::instance_ = NULL;
1225 struct sigaction SignalSender::old_signal_handler_;
1226 bool SignalSender::signal_handler_installed_ = false;
1230 // Seed the random number generator. We preserve microsecond resolution.
1231 uint64_t seed = Ticks() ^ (getpid() << 16);
1232 srandom(static_cast<unsigned int>(seed));
1233 limit_mutex = CreateMutex();
1236 // When running on ARM hardware check that the EABI used by V8 and
1237 // by the C code is the same.
1238 bool hard_float = OS::ArmUsingHardFloat();
1240 #if !USE_EABI_HARDFLOAT
1241 PrintF("ERROR: Binary compiled with -mfloat-abi=hard but without "
1242 "-DUSE_EABI_HARDFLOAT\n");
1246 #if USE_EABI_HARDFLOAT
1247 PrintF("ERROR: Binary not compiled with -mfloat-abi=hard but with "
1248 "-DUSE_EABI_HARDFLOAT\n");
1253 SignalSender::SetUp();
1257 void OS::TearDown() {
1258 SignalSender::TearDown();
1263 Sampler::Sampler(Isolate* isolate, int interval)
1264 : isolate_(isolate),
1265 interval_(interval),
1269 data_ = new PlatformData;
1273 Sampler::~Sampler() {
1274 ASSERT(!IsActive());
1279 void Sampler::Start() {
1280 ASSERT(!IsActive());
1282 SignalSender::AddActiveSampler(this);
1286 void Sampler::Stop() {
1288 SignalSender::RemoveActiveSampler(this);
1293 } } // namespace v8::internal