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
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 // def __GLIBC__
52 #include <strings.h> // index
61 #include "v8threads.h"
62 #include "vm-state-inl.h"
68 // 0 is never a valid thread id on Linux since tids and pids share a
69 // name space and pid 0 is reserved (see man 2 kill).
70 static const pthread_t kNoThread = (pthread_t) 0;
73 double ceiling(double x) {
78 static Mutex* limit_mutex = NULL;
82 // Seed the random number generator. We preserve microsecond resolution.
83 uint64_t seed = Ticks() ^ (getpid() << 16);
84 srandom(static_cast<unsigned int>(seed));
85 limit_mutex = CreateMutex();
88 // When running on ARM hardware check that the EABI used by V8 and
89 // by the C code is the same.
90 bool hard_float = OS::ArmUsingHardFloat();
92 #if !USE_EABI_HARDFLOAT
93 PrintF("ERROR: Binary compiled with -mfloat-abi=hard but without "
94 "-DUSE_EABI_HARDFLOAT\n");
98 #if USE_EABI_HARDFLOAT
99 PrintF("ERROR: Binary not compiled with -mfloat-abi=hard but with "
100 "-DUSE_EABI_HARDFLOAT\n");
108 uint64_t OS::CpuFeaturesImpliedByPlatform() {
109 return 0; // Linux runs on anything.
114 static bool CPUInfoContainsString(const char * search_string) {
115 const char* file_name = "/proc/cpuinfo";
116 // This is written as a straight shot one pass parser
117 // and not using STL string and ifstream because,
118 // on Linux, it's reading from a (non-mmap-able)
119 // character special device.
121 const char* what = search_string;
123 if (NULL == (f = fopen(file_name, "r")))
127 while (EOF != (k = fgetc(f))) {
130 while ((*what != '\0') && (*what == fgetc(f))) {
137 what = search_string;
143 // Did not find string in the proc file.
148 bool OS::ArmCpuHasFeature(CpuFeature feature) {
149 const char* search_string = NULL;
150 // Simple detection of VFP at runtime for Linux.
151 // It is based on /proc/cpuinfo, which reveals hardware configuration
152 // to user-space applications. According to ARM (mid 2009), no similar
153 // facility is universally available on the ARM architectures,
154 // so it's up to individual OSes to provide such.
157 search_string = "vfpv3";
160 search_string = "ARMv7";
166 if (CPUInfoContainsString(search_string)) {
170 if (feature == VFP3) {
171 // Some old kernels will report vfp not vfpv3. Here we make a last attempt
172 // to detect vfpv3 by checking for vfp *and* neon, since neon is only
173 // available on architectures with vfpv3.
174 // Checking neon on its own is not enough as it is possible to have neon
176 if (CPUInfoContainsString("vfp") && CPUInfoContainsString("neon")) {
185 // Simple helper function to detect whether the C code is compiled with
186 // option -mfloat-abi=hard. The register d0 is loaded with 1.0 and the register
187 // pair r0, r1 is loaded with 0.0. If -mfloat-abi=hard is pased to GCC then
188 // calling this will return 1.0 and otherwise 0.0.
189 static void ArmUsingHardFloatHelper() {
191 #if defined(__VFP_FP__) && !defined(__SOFTFP__)
192 // Load 0x3ff00000 into r1 using instructions available in both ARM
196 asm("lsl r1, r1, #8");
197 asm("orr r1, r1, r2");
198 asm("lsl r1, r1, #20");
199 // For vmov d0, r0, r1 use ARM mode.
202 "@ Enter ARM Mode \n\t"
207 "1: vmov d0, r0, r1 \n\t"
208 "@ Enter THUMB Mode\n\t"
214 asm("vmov d0, r0, r1");
216 #endif // defined(__VFP_FP__) && !defined(__SOFTFP__)
221 bool OS::ArmUsingHardFloat() {
222 // Cast helper function from returning void to returning double.
223 typedef double (*F)();
224 F f = FUNCTION_CAST<F>(FUNCTION_ADDR(ArmUsingHardFloatHelper));
227 #endif // def __arm__
231 bool OS::MipsCpuHasFeature(CpuFeature feature) {
232 const char* search_string = NULL;
233 const char* file_name = "/proc/cpuinfo";
234 // Simple detection of FPU at runtime for Linux.
235 // It is based on /proc/cpuinfo, which reveals hardware configuration
236 // to user-space applications. According to MIPS (early 2010), no similar
237 // facility is universally available on the MIPS architectures,
238 // so it's up to individual OSes to provide such.
240 // This is written as a straight shot one pass parser
241 // and not using STL string and ifstream because,
242 // on Linux, it's reading from a (non-mmap-able)
243 // character special device.
247 search_string = "FPU";
254 const char* what = search_string;
256 if (NULL == (f = fopen(file_name, "r")))
260 while (EOF != (k = fgetc(f))) {
263 while ((*what != '\0') && (*what == fgetc(f))) {
270 what = search_string;
276 // Did not find string in the proc file.
279 #endif // def __mips__
282 int OS::ActivationFrameAlignment() {
283 #ifdef V8_TARGET_ARCH_ARM
284 // On EABI ARM targets this is required for fp correctness in the
287 #elif V8_TARGET_ARCH_MIPS
290 // With gcc 4.4 the tree vectorization optimizer can generate code
291 // that requires 16 byte alignment such as movdqa on x86.
296 void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
297 #if (defined(V8_TARGET_ARCH_ARM) && defined(__arm__)) || \
298 (defined(V8_TARGET_ARCH_MIPS) && defined(__mips__))
299 // Only use on ARM or MIPS hardware.
302 __asm__ __volatile__("" : : : "memory");
303 // An x86 store acts as a release barrier.
309 const char* OS::LocalTimezone(double time) {
310 if (isnan(time)) return "";
311 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
312 struct tm* t = localtime(&tv);
313 if (NULL == t) return "";
318 double OS::LocalTimeOffset() {
319 time_t tv = time(NULL);
320 struct tm* t = localtime(&tv);
321 // tm_gmtoff includes any daylight savings offset, so subtract it.
322 return static_cast<double>(t->tm_gmtoff * msPerSecond -
323 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
327 // We keep the lowest and highest addresses mapped as a quick way of
328 // determining that pointers are outside the heap (used mostly in assertions
329 // and verification). The estimate is conservative, ie, not all addresses in
330 // 'allocated' space are actually allocated to our heap. The range is
331 // [lowest, highest), inclusive on the low and and exclusive on the high end.
332 static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
333 static void* highest_ever_allocated = reinterpret_cast<void*>(0);
336 static void UpdateAllocatedSpaceLimits(void* address, int size) {
337 ASSERT(limit_mutex != NULL);
338 ScopedLock lock(limit_mutex);
340 lowest_ever_allocated = Min(lowest_ever_allocated, address);
341 highest_ever_allocated =
342 Max(highest_ever_allocated,
343 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
347 bool OS::IsOutsideAllocatedSpace(void* address) {
348 return address < lowest_ever_allocated || address >= highest_ever_allocated;
352 size_t OS::AllocateAlignment() {
353 return sysconf(_SC_PAGESIZE);
357 void* OS::Allocate(const size_t requested,
359 bool is_executable) {
360 const size_t msize = RoundUp(requested, AllocateAlignment());
361 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
362 void* addr = OS::GetRandomMmapAddr();
363 void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
364 if (mbase == MAP_FAILED) {
365 LOG(i::Isolate::Current(),
366 StringEvent("OS::Allocate", "mmap failed"));
370 UpdateAllocatedSpaceLimits(mbase, msize);
375 void OS::Free(void* address, const size_t size) {
376 // TODO(1240712): munmap has a return value which is ignored here.
377 int result = munmap(address, size);
383 void OS::Sleep(int milliseconds) {
384 unsigned int ms = static_cast<unsigned int>(milliseconds);
390 // Redirect to std abort to signal abnormal program termination.
395 void OS::DebugBreak() {
396 // TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
397 // which is the architecture of generated code).
398 #if (defined(__arm__) || defined(__thumb__))
399 # if defined(CAN_USE_ARMV5_INSTRUCTIONS)
402 #elif defined(__mips__)
410 class PosixMemoryMappedFile : public OS::MemoryMappedFile {
412 PosixMemoryMappedFile(FILE* file, void* memory, int size)
413 : file_(file), memory_(memory), size_(size) { }
414 virtual ~PosixMemoryMappedFile();
415 virtual void* memory() { return memory_; }
416 virtual int size() { return size_; }
424 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
425 FILE* file = fopen(name, "r+");
426 if (file == NULL) return NULL;
428 fseek(file, 0, SEEK_END);
429 int size = ftell(file);
432 mmap(OS::GetRandomMmapAddr(),
434 PROT_READ | PROT_WRITE,
438 return new PosixMemoryMappedFile(file, memory, size);
442 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
444 FILE* file = fopen(name, "w+");
445 if (file == NULL) return NULL;
446 int result = fwrite(initial, size, 1, file);
452 mmap(OS::GetRandomMmapAddr(),
454 PROT_READ | PROT_WRITE,
458 return new PosixMemoryMappedFile(file, memory, size);
462 PosixMemoryMappedFile::~PosixMemoryMappedFile() {
463 if (memory_) OS::Free(memory_, size_);
468 void OS::LogSharedLibraryAddresses() {
469 // This function assumes that the layout of the file is as follows:
470 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
471 // If we encounter an unexpected situation we abort scanning further entries.
472 FILE* fp = fopen("/proc/self/maps", "r");
473 if (fp == NULL) return;
475 // Allocate enough room to be able to store a full file name.
476 const int kLibNameLen = FILENAME_MAX + 1;
477 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
479 i::Isolate* isolate = ISOLATE;
480 // This loop will terminate once the scanning hits an EOF.
482 uintptr_t start, end;
483 char attr_r, attr_w, attr_x, attr_p;
484 // Parse the addresses and permission bits at the beginning of the line.
485 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
486 if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break;
489 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
490 // Found a read-only executable entry. Skip characters until we reach
491 // the beginning of the filename or the end of the line.
494 } while ((c != EOF) && (c != '\n') && (c != '/'));
495 if (c == EOF) break; // EOF: Was unexpected, just exit.
497 // Process the filename if found.
499 ungetc(c, fp); // Push the '/' back into the stream to be read below.
501 // Read to the end of the line. Exit if the read fails.
502 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
504 // Drop the newline character read by fgets. We do not need to check
505 // for a zero-length string because we know that we at least read the
507 lib_name[strlen(lib_name) - 1] = '\0';
509 // No library name found, just record the raw address range.
510 snprintf(lib_name, kLibNameLen,
511 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
513 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
515 // Entry not describing executable data. Skip to end of line to setup
516 // reading the next entry.
519 } while ((c != EOF) && (c != '\n'));
528 static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
531 void OS::SignalCodeMovingGC() {
532 // Support for ll_prof.py.
534 // The Linux profiler built into the kernel logs all mmap's with
535 // PROT_EXEC so that analysis tools can properly attribute ticks. We
536 // do a mmap with a name known by ll_prof.py and immediately munmap
537 // it. This injects a GC marker into the stream of events generated
538 // by the kernel and allows us to synchronize V8 code log and the
540 int size = sysconf(_SC_PAGESIZE);
541 FILE* f = fopen(kGCFakeMmap, "w+");
542 void* addr = mmap(OS::GetRandomMmapAddr(),
544 PROT_READ | PROT_EXEC,
548 ASSERT(addr != MAP_FAILED);
549 OS::Free(addr, size);
554 int OS::StackWalk(Vector<OS::StackFrame> frames) {
555 // backtrace is a glibc extension.
556 #if defined(__GLIBC__) && !defined(__UCLIBC__)
557 int frames_size = frames.length();
558 ScopedVector<void*> addresses(frames_size);
560 int frames_count = backtrace(addresses.start(), frames_size);
562 char** symbols = backtrace_symbols(addresses.start(), frames_count);
563 if (symbols == NULL) {
564 return kStackWalkError;
567 for (int i = 0; i < frames_count; i++) {
568 frames[i].address = addresses[i];
569 // Format a text representation of the frame based on the information
571 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
574 // Make sure line termination is in place.
575 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
581 #else // ndef __GLIBC__
583 #endif // ndef __GLIBC__
587 // Constants used for mmap.
588 static const int kMmapFd = -1;
589 static const int kMmapFdOffset = 0;
591 VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
593 VirtualMemory::VirtualMemory(size_t size) {
594 address_ = ReserveRegion(size);
599 VirtualMemory::VirtualMemory(size_t size, size_t alignment)
600 : address_(NULL), size_(0) {
601 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
602 size_t request_size = RoundUp(size + alignment,
603 static_cast<intptr_t>(OS::AllocateAlignment()));
604 void* reservation = mmap(OS::GetRandomMmapAddr(),
607 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
610 if (reservation == MAP_FAILED) return;
612 Address base = static_cast<Address>(reservation);
613 Address aligned_base = RoundUp(base, alignment);
614 ASSERT_LE(base, aligned_base);
616 // Unmap extra memory reserved before and after the desired block.
617 if (aligned_base != base) {
618 size_t prefix_size = static_cast<size_t>(aligned_base - base);
619 OS::Free(base, prefix_size);
620 request_size -= prefix_size;
623 size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
624 ASSERT_LE(aligned_size, request_size);
626 if (aligned_size != request_size) {
627 size_t suffix_size = request_size - aligned_size;
628 OS::Free(aligned_base + aligned_size, suffix_size);
629 request_size -= suffix_size;
632 ASSERT(aligned_size == request_size);
634 address_ = static_cast<void*>(aligned_base);
635 size_ = aligned_size;
639 VirtualMemory::~VirtualMemory() {
641 bool result = ReleaseRegion(address(), size());
648 bool VirtualMemory::IsReserved() {
649 return address_ != NULL;
653 void VirtualMemory::Reset() {
659 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
660 return CommitRegion(address, size, is_executable);
664 bool VirtualMemory::Uncommit(void* address, size_t size) {
665 return UncommitRegion(address, size);
669 void* VirtualMemory::ReserveRegion(size_t size) {
670 void* result = mmap(OS::GetRandomMmapAddr(),
673 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
677 if (result == MAP_FAILED) return NULL;
683 bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
684 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
685 if (MAP_FAILED == mmap(base,
688 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
694 UpdateAllocatedSpaceLimits(base, size);
699 bool VirtualMemory::UncommitRegion(void* base, size_t size) {
703 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
705 kMmapFdOffset) != MAP_FAILED;
709 bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
710 return munmap(base, size) == 0;
714 class Thread::PlatformData : public Malloced {
716 PlatformData() : thread_(kNoThread) {}
718 pthread_t thread_; // Thread handle for pthread.
721 Thread::Thread(const Options& options)
722 : data_(new PlatformData()),
723 stack_size_(options.stack_size) {
724 set_name(options.name);
728 Thread::Thread(const char* name)
729 : data_(new PlatformData()),
740 static void* ThreadEntry(void* arg) {
741 Thread* thread = reinterpret_cast<Thread*>(arg);
742 // This is also initialized by the first argument to pthread_create() but we
743 // don't know which thread will run first (the original thread or the new
744 // one) so we initialize it here too.
747 reinterpret_cast<unsigned long>(thread->name()), // NOLINT
750 thread->data()->thread_ = pthread_self();
751 ASSERT(thread->data()->thread_ != kNoThread);
757 void Thread::set_name(const char* name) {
758 strncpy(name_, name, sizeof(name_));
759 name_[sizeof(name_) - 1] = '\0';
763 void Thread::Start() {
764 pthread_attr_t* attr_ptr = NULL;
766 if (stack_size_ > 0) {
767 pthread_attr_init(&attr);
768 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
771 pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
772 ASSERT(data_->thread_ != kNoThread);
776 void Thread::Join() {
777 pthread_join(data_->thread_, NULL);
781 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
783 int result = pthread_key_create(&key, NULL);
786 return static_cast<LocalStorageKey>(key);
790 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
791 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
792 int result = pthread_key_delete(pthread_key);
798 void* Thread::GetThreadLocal(LocalStorageKey key) {
799 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
800 return pthread_getspecific(pthread_key);
804 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
805 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
806 pthread_setspecific(pthread_key, value);
810 void Thread::YieldCPU() {
815 class LinuxMutex : public Mutex {
818 pthread_mutexattr_t attrs;
819 int result = pthread_mutexattr_init(&attrs);
821 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
823 result = pthread_mutex_init(&mutex_, &attrs);
828 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
831 int result = pthread_mutex_lock(&mutex_);
835 virtual int Unlock() {
836 int result = pthread_mutex_unlock(&mutex_);
840 virtual bool TryLock() {
841 int result = pthread_mutex_trylock(&mutex_);
842 // Return false if the lock is busy and locking failed.
843 if (result == EBUSY) {
846 ASSERT(result == 0); // Verify no other errors.
851 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
855 Mutex* OS::CreateMutex() {
856 return new LinuxMutex();
860 class LinuxSemaphore : public Semaphore {
862 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
863 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
866 virtual bool Wait(int timeout);
867 virtual void Signal() { sem_post(&sem_); }
873 void LinuxSemaphore::Wait() {
875 int result = sem_wait(&sem_);
876 if (result == 0) return; // Successfully got semaphore.
877 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
882 #ifndef TIMEVAL_TO_TIMESPEC
883 #define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
884 (ts)->tv_sec = (tv)->tv_sec; \
885 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
890 bool LinuxSemaphore::Wait(int timeout) {
891 const long kOneSecondMicros = 1000000; // NOLINT
893 // Split timeout into second and nanosecond parts.
894 struct timeval delta;
895 delta.tv_usec = timeout % kOneSecondMicros;
896 delta.tv_sec = timeout / kOneSecondMicros;
898 struct timeval current_time;
899 // Get the current time.
900 if (gettimeofday(¤t_time, NULL) == -1) {
904 // Calculate time for end of timeout.
905 struct timeval end_time;
906 timeradd(¤t_time, &delta, &end_time);
909 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
910 // Wait for semaphore signalled or timeout.
912 int result = sem_timedwait(&sem_, &ts);
913 if (result == 0) return true; // Successfully got semaphore.
915 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
919 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
920 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
925 Semaphore* OS::CreateSemaphore(int count) {
926 return new LinuxSemaphore(count);
930 #if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
931 // Android runs a fairly new Linux kernel, so signal info is there,
932 // but the C library doesn't have the structs defined.
940 uint32_t fault_address;
942 typedef uint32_t __sigset_t;
943 typedef struct sigcontext mcontext_t;
944 typedef struct ucontext {
946 struct ucontext* uc_link;
948 mcontext_t uc_mcontext;
949 __sigset_t uc_sigmask;
951 enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
956 static int GetThreadID() {
957 // Glibc doesn't provide a wrapper for gettid(2).
959 return syscall(__NR_gettid);
961 return syscall(SYS_gettid);
966 static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
967 #ifndef V8_HOST_ARCH_MIPS
969 if (signal != SIGPROF) return;
970 Isolate* isolate = Isolate::UncheckedCurrent();
971 if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
972 // We require a fully initialized and entered isolate.
975 if (v8::Locker::IsActive() &&
976 !isolate->thread_manager()->IsLockedByCurrentThread()) {
980 Sampler* sampler = isolate->logger()->sampler();
981 if (sampler == NULL || !sampler->IsActive()) return;
983 TickSample sample_obj;
984 TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
985 if (sample == NULL) sample = &sample_obj;
987 // Extracting the sample from the context is extremely machine dependent.
988 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
989 mcontext_t& mcontext = ucontext->uc_mcontext;
990 sample->state = isolate->current_vm_state();
991 #if V8_HOST_ARCH_IA32
992 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
993 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
994 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
995 #elif V8_HOST_ARCH_X64
996 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
997 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
998 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
999 #elif V8_HOST_ARCH_ARM
1000 // An undefined macro evaluates to 0, so this applies to Android's Bionic also.
1001 #if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
1002 sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
1003 sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
1004 sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
1006 sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
1007 sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
1008 sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
1010 #elif V8_HOST_ARCH_MIPS
1011 sample.pc = reinterpret_cast<Address>(mcontext.pc);
1012 sample.sp = reinterpret_cast<Address>(mcontext.gregs[29]);
1013 sample.fp = reinterpret_cast<Address>(mcontext.gregs[30]);
1015 sampler->SampleStack(sample);
1016 sampler->Tick(sample);
1021 class Sampler::PlatformData : public Malloced {
1023 PlatformData() : vm_tid_(GetThreadID()) {}
1025 int vm_tid() const { return vm_tid_; }
1032 class SignalSender : public Thread {
1034 enum SleepInterval {
1039 explicit SignalSender(int interval)
1040 : Thread("SignalSender"),
1042 interval_(interval) {}
1044 static void InstallSignalHandler() {
1045 struct sigaction sa;
1046 sa.sa_sigaction = ProfilerSignalHandler;
1047 sigemptyset(&sa.sa_mask);
1048 sa.sa_flags = SA_RESTART | SA_SIGINFO;
1049 signal_handler_installed_ =
1050 (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
1053 static void RestoreSignalHandler() {
1054 if (signal_handler_installed_) {
1055 sigaction(SIGPROF, &old_signal_handler_, 0);
1056 signal_handler_installed_ = false;
1060 static void AddActiveSampler(Sampler* sampler) {
1061 ScopedLock lock(mutex_);
1062 SamplerRegistry::AddActiveSampler(sampler);
1063 if (instance_ == NULL) {
1064 // Start a thread that will send SIGPROF signal to VM threads,
1065 // when CPU profiling will be enabled.
1066 instance_ = new SignalSender(sampler->interval());
1069 ASSERT(instance_->interval_ == sampler->interval());
1073 static void RemoveActiveSampler(Sampler* sampler) {
1074 ScopedLock lock(mutex_);
1075 SamplerRegistry::RemoveActiveSampler(sampler);
1076 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
1077 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
1080 RestoreSignalHandler();
1084 // Implement Thread::Run().
1085 virtual void Run() {
1086 SamplerRegistry::State state;
1087 while ((state = SamplerRegistry::GetState()) !=
1088 SamplerRegistry::HAS_NO_SAMPLERS) {
1089 bool cpu_profiling_enabled =
1090 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1091 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
1092 if (cpu_profiling_enabled && !signal_handler_installed_) {
1093 InstallSignalHandler();
1094 } else if (!cpu_profiling_enabled && signal_handler_installed_) {
1095 RestoreSignalHandler();
1097 // When CPU profiling is enabled both JavaScript and C++ code is
1098 // profiled. We must not suspend.
1099 if (!cpu_profiling_enabled) {
1100 if (rate_limiter_.SuspendIfNecessary()) continue;
1102 if (cpu_profiling_enabled && runtime_profiler_enabled) {
1103 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1106 Sleep(HALF_INTERVAL);
1107 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1110 Sleep(HALF_INTERVAL);
1112 if (cpu_profiling_enabled) {
1113 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
1118 if (runtime_profiler_enabled) {
1119 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
1124 Sleep(FULL_INTERVAL);
1129 static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
1130 if (!sampler->IsProfiling()) return;
1131 SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
1132 sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
1135 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1136 if (!sampler->isolate()->IsInitialized()) return;
1137 sampler->isolate()->runtime_profiler()->NotifyTick();
1140 void SendProfilingSignal(int tid) {
1141 if (!signal_handler_installed_) return;
1142 // Glibc doesn't provide a wrapper for tgkill(2).
1143 #if defined(ANDROID)
1144 syscall(__NR_tgkill, vm_tgid_, tid, SIGPROF);
1146 syscall(SYS_tgkill, vm_tgid_, tid, SIGPROF);
1150 void Sleep(SleepInterval full_or_half) {
1151 // Convert ms to us and subtract 100 us to compensate delays
1152 // occuring during signal delivery.
1153 useconds_t interval = interval_ * 1000 - 100;
1154 if (full_or_half == HALF_INTERVAL) interval /= 2;
1155 int result = usleep(interval);
1157 if (result != 0 && errno != EINTR) {
1159 "SignalSender usleep error; interval = %u, errno = %d\n",
1162 ASSERT(result == 0 || errno == EINTR);
1169 const int interval_;
1170 RuntimeProfilerRateLimiter rate_limiter_;
1172 // Protects the process wide state below.
1173 static Mutex* mutex_;
1174 static SignalSender* instance_;
1175 static bool signal_handler_installed_;
1176 static struct sigaction old_signal_handler_;
1178 DISALLOW_COPY_AND_ASSIGN(SignalSender);
1182 Mutex* SignalSender::mutex_ = OS::CreateMutex();
1183 SignalSender* SignalSender::instance_ = NULL;
1184 struct sigaction SignalSender::old_signal_handler_;
1185 bool SignalSender::signal_handler_installed_ = false;
1188 Sampler::Sampler(Isolate* isolate, int interval)
1189 : isolate_(isolate),
1190 interval_(interval),
1194 data_ = new PlatformData;
1198 Sampler::~Sampler() {
1199 ASSERT(!IsActive());
1204 void Sampler::Start() {
1205 ASSERT(!IsActive());
1207 SignalSender::AddActiveSampler(this);
1211 void Sampler::Stop() {
1213 SignalSender::RemoveActiveSampler(this);
1218 } } // namespace v8::internal