12 #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__OpenBSD__) 13 #include <pthread_np.h> 23 #include <sys/types.h> 24 #if defined(__APPLE__) || defined(__DragonFly__) || defined(__FreeBSD__) || \ 25 defined(__NetBSD__) || defined(__OpenBSD__) 26 #include <sys/sysctl.h> 29 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT) 31 #include <android/log.h> 37 #include "src/base/platform/platform-posix.h" 39 #include "src/base/lazy-instance.h" 40 #include "src/base/macros.h" 41 #include "src/base/platform/platform.h" 42 #include "src/base/platform/time.h" 43 #include "src/base/utils/random-number-generator.h" 45 #ifdef V8_FAST_TLS_SUPPORTED 46 #include "src/base/atomicops.h" 54 #include <sys/prctl.h> 57 #if defined(V8_OS_FUCHSIA) 58 #include <zircon/process.h> 60 #include <sys/resource.h> 63 #if !defined(_AIX) && !defined(V8_OS_FUCHSIA) 64 #include <sys/syscall.h> 67 #if V8_OS_FREEBSD || V8_OS_MACOSX || V8_OS_OPENBSD || V8_OS_SOLARIS 68 #define MAP_ANONYMOUS MAP_ANON 71 #if defined(V8_OS_SOLARIS) 72 #if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE > 2) || defined(__EXTENSIONS__) 73 extern "C" int madvise(caddr_t,
size_t,
int);
75 extern int madvise(caddr_t,
size_t,
int);
80 #define MADV_FREE MADV_DONTNEED 89 const pthread_t kNoThread =
static_cast<pthread_t
>(0);
91 bool g_hard_abort =
false;
93 const char* g_gc_fake_mmap =
nullptr;
95 static LazyInstance<RandomNumberGenerator>::type
96 platform_random_number_generator = LAZY_INSTANCE_INITIALIZER;
97 static LazyMutex rng_mutex = LAZY_MUTEX_INITIALIZER;
104 const int kMmapFd = VM_MAKE_TAG(255);
105 #else // !V8_OS_MACOSX 106 const int kMmapFd = -1;
107 #endif // !V8_OS_MACOSX 109 const int kMmapFdOffset = 0;
111 int GetProtectionFromMemoryPermission(OS::MemoryPermission access) {
113 case OS::MemoryPermission::kNoAccess:
115 case OS::MemoryPermission::kRead:
117 case OS::MemoryPermission::kReadWrite:
118 return PROT_READ | PROT_WRITE;
119 case OS::MemoryPermission::kReadWriteExecute:
120 return PROT_READ | PROT_WRITE | PROT_EXEC;
121 case OS::MemoryPermission::kReadExecute:
122 return PROT_READ | PROT_EXEC;
127 int GetFlagsForMemoryPermission(OS::MemoryPermission access) {
128 int flags = MAP_PRIVATE | MAP_ANONYMOUS;
129 if (access == OS::MemoryPermission::kNoAccess) {
130 #if !V8_OS_AIX && !V8_OS_FREEBSD && !V8_OS_QNX 131 flags |= MAP_NORESERVE;
132 #endif // !V8_OS_AIX && !V8_OS_FREEBSD && !V8_OS_QNX 140 void* Allocate(
void* address,
size_t size, OS::MemoryPermission access) {
141 int prot = GetProtectionFromMemoryPermission(access);
142 int flags = GetFlagsForMemoryPermission(access);
143 void* result = mmap(address, size, prot, flags, kMmapFd, kMmapFdOffset);
144 if (result == MAP_FAILED)
return nullptr;
148 #endif // !V8_OS_FUCHSIA 152 void OS::Initialize(
bool hard_abort,
const char*
const gc_fake_mmap) {
153 g_hard_abort = hard_abort;
154 g_gc_fake_mmap = gc_fake_mmap;
157 int OS::ActivationFrameAlignment() {
158 #if V8_TARGET_ARCH_ARM 162 #elif V8_TARGET_ARCH_MIPS 164 #elif V8_TARGET_ARCH_S390 177 size_t OS::AllocatePageSize() {
178 return static_cast<size_t>(sysconf(_SC_PAGESIZE));
182 size_t OS::CommitPageSize() {
183 static size_t page_size = getpagesize();
188 void OS::SetRandomMmapSeed(
int64_t seed) {
190 MutexGuard guard(rng_mutex.Pointer());
191 platform_random_number_generator.Pointer()->SetSeed(seed);
196 void* OS::GetRandomMmapAddr() {
199 MutexGuard guard(rng_mutex.Pointer());
200 platform_random_number_generator.Pointer()->NextBytes(&raw_addr,
203 #if defined(V8_USE_ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \ 204 defined(THREAD_SANITIZER) || defined(LEAK_SANITIZER) 209 raw_addr &= 0x007fffff0000ULL;
210 raw_addr += 0x7e8000000000ULL;
212 #if V8_TARGET_ARCH_X64 216 raw_addr &= uint64_t{0x3FFFFFFFF000};
217 #elif V8_TARGET_ARCH_PPC64 221 raw_addr &= uint64_t{0x3FFFF000};
223 raw_addr += uint64_t{0x400000000000};
224 #elif V8_TARGET_BIG_ENDIAN 226 raw_addr &= uint64_t{0x03FFFFFFF000};
229 raw_addr &= uint64_t{0x3FFFFFFF0000};
231 #elif V8_TARGET_ARCH_S390X 235 raw_addr &= uint64_t{0xFFFFFFF000};
236 #elif V8_TARGET_ARCH_S390 239 raw_addr &= 0x1FFFF000;
240 #elif V8_TARGET_ARCH_MIPS64 243 raw_addr &= uint64_t{0xFFFFFF0000};
245 raw_addr &= 0x3FFFF000;
257 raw_addr += 0x80000000;
261 raw_addr += 0x90000000;
266 raw_addr += 0x20000000;
270 return reinterpret_cast<void*
>(raw_addr);
274 #if !V8_OS_CYGWIN && !V8_OS_FUCHSIA 276 void* OS::Allocate(
void* address,
size_t size,
size_t alignment,
277 MemoryPermission access) {
278 size_t page_size = AllocatePageSize();
279 DCHECK_EQ(0, size % page_size);
280 DCHECK_EQ(0, alignment % page_size);
281 address = AlignedAddress(address, alignment);
283 size_t request_size = size + (alignment - page_size);
284 request_size = RoundUp(request_size, OS::AllocatePageSize());
285 void* result = base::Allocate(address, request_size, access);
286 if (result ==
nullptr)
return nullptr;
289 uint8_t* base =
static_cast<uint8_t*
>(result);
290 uint8_t* aligned_base =
reinterpret_cast<uint8_t*
>(
291 RoundUp(reinterpret_cast<uintptr_t>(base), alignment));
292 if (aligned_base != base) {
293 DCHECK_LT(base, aligned_base);
294 size_t prefix_size =
static_cast<size_t>(aligned_base - base);
295 CHECK(Free(base, prefix_size));
296 request_size -= prefix_size;
299 if (size != request_size) {
300 DCHECK_LT(size, request_size);
301 size_t suffix_size = request_size - size;
302 CHECK(Free(aligned_base + size, suffix_size));
303 request_size -= suffix_size;
306 DCHECK_EQ(size, request_size);
307 return static_cast<void*
>(aligned_base);
311 bool OS::Free(
void* address,
const size_t size) {
312 DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % AllocatePageSize());
313 DCHECK_EQ(0, size % AllocatePageSize());
314 return munmap(address, size) == 0;
318 bool OS::Release(
void* address,
size_t size) {
319 DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
320 DCHECK_EQ(0, size % CommitPageSize());
321 return munmap(address, size) == 0;
325 bool OS::SetPermissions(
void* address,
size_t size, MemoryPermission access) {
326 DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
327 DCHECK_EQ(0, size % CommitPageSize());
329 int prot = GetProtectionFromMemoryPermission(access);
330 int ret = mprotect(address, size, prot);
331 if (ret == 0 && access == OS::MemoryPermission::kNoAccess) {
333 USE(DiscardSystemPages(address, size));
342 #if defined(OS_MACOSX) 343 if (access != OS::MemoryPermission::kNoAccess)
344 madvise(address, size, MADV_FREE_REUSE);
350 bool OS::DiscardSystemPages(
void* address,
size_t size) {
351 DCHECK_EQ(0, reinterpret_cast<uintptr_t>(address) % CommitPageSize());
352 DCHECK_EQ(0, size % CommitPageSize());
353 #if defined(OS_MACOSX) 357 int ret = madvise(address, size, MADV_FREE_REUSABLE);
358 #elif defined(_AIX) || defined(V8_OS_SOLARIS) 359 int ret = madvise(reinterpret_cast<caddr_t>(address), size, MADV_FREE);
361 int ret = madvise(address, size, MADV_FREE);
363 if (ret != 0 && errno == ENOSYS)
365 if (ret != 0 && errno == EINVAL) {
369 #if defined(_AIX) || defined(V8_OS_SOLARIS) 370 ret = madvise(reinterpret_cast<caddr_t>(address), size, MADV_DONTNEED);
372 ret = madvise(address, size, MADV_DONTNEED);
379 bool OS::HasLazyCommits() {
380 #if V8_OS_AIX || V8_OS_LINUX || V8_OS_MACOSX 387 #endif // !V8_OS_CYGWIN && !V8_OS_FUCHSIA 389 const char* OS::GetGCFakeMMapFile() {
390 return g_gc_fake_mmap;
394 void OS::Sleep(TimeDelta interval) {
395 usleep(static_cast<useconds_t>(interval.InMicroseconds()));
401 V8_IMMEDIATE_CRASH();
408 void OS::DebugBreak() {
411 #elif V8_HOST_ARCH_ARM64 413 #elif V8_HOST_ARCH_MIPS 415 #elif V8_HOST_ARCH_MIPS64 417 #elif V8_HOST_ARCH_PPC 419 #elif V8_HOST_ARCH_IA32 421 #elif V8_HOST_ARCH_X64 423 #elif V8_HOST_ARCH_S390 425 asm volatile(
".word 0x0001");
427 #error Unsupported host architecture. 435 : file_(file), memory_(memory), size_(size) {}
437 void* memory()
const final {
return memory_; }
438 size_t size()
const final {
return size_; }
449 if (FILE* file = fopen(name,
"r+")) {
450 if (fseek(file, 0, SEEK_END) == 0) {
451 long size = ftell(file);
454 mmap(OS::GetRandomMmapAddr(), size, PROT_READ | PROT_WRITE,
455 MAP_SHARED, fileno(file), 0);
456 if (memory != MAP_FAILED) {
468 OS::MemoryMappedFile* OS::MemoryMappedFile::create(
const char* name,
469 size_t size,
void* initial) {
470 if (FILE* file = fopen(name,
"w+")) {
471 size_t result = fwrite(initial, 1, size, file);
472 if (result == size && !ferror(file)) {
473 void* memory = mmap(OS::GetRandomMmapAddr(), result,
474 PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
475 if (memory != MAP_FAILED) {
476 return new PosixMemoryMappedFile(file, memory, result);
485 PosixMemoryMappedFile::~PosixMemoryMappedFile() {
486 if (memory_) CHECK(OS::Free(memory_, RoundUp(size_, OS::AllocatePageSize())));
491 int OS::GetCurrentProcessId() {
492 return static_cast<int>(getpid());
496 int OS::GetCurrentThreadId() {
497 #if V8_OS_MACOSX || (V8_OS_ANDROID && defined(__APPLE__)) 498 return static_cast<int>(pthread_mach_thread_np(pthread_self()));
500 return static_cast<int>(syscall(__NR_gettid));
502 return static_cast<int>(gettid());
504 return static_cast<int>(thread_self());
506 return static_cast<int>(zx_thread_self());
508 return static_cast<int>(pthread_self());
510 return static_cast<int>(
reinterpret_cast<intptr_t
>(pthread_self()));
514 void OS::ExitProcess(
int exit_code) {
526 #if !defined(V8_OS_FUCHSIA) 530 if (getrusage(RUSAGE_SELF, &usage) < 0)
return -1;
531 *secs =
static_cast<uint32_t>(usage.ru_utime.tv_sec);
532 *usecs =
static_cast<uint32_t>(usage.ru_utime.tv_usec);
537 double OS::TimeCurrentMillis() {
538 return Time::Now().ToJsTime();
541 double PosixTimezoneCache::DaylightSavingsOffset(
double time) {
542 if (std::isnan(time))
return std::numeric_limits<double>::quiet_NaN();
543 time_t tv =
static_cast<time_t
>(std::floor(time/msPerSecond));
545 struct tm* t = localtime_r(&tv, &tm);
546 if (
nullptr == t)
return std::numeric_limits<double>::quiet_NaN();
547 return t->tm_isdst > 0 ? 3600 * msPerSecond : 0;
551 int OS::GetLastError() {
560 FILE* OS::FOpen(
const char* path,
const char* mode) {
561 FILE* file = fopen(path, mode);
562 if (file ==
nullptr)
return nullptr;
563 struct stat file_stat;
564 if (fstat(fileno(file), &file_stat) != 0) {
568 bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
569 if (is_regular_file)
return file;
575 bool OS::Remove(
const char* path) {
576 return (
remove(path) == 0);
579 char OS::DirectorySeparator() {
return '/'; }
581 bool OS::isDirectorySeparator(
const char ch) {
582 return ch == DirectorySeparator();
586 FILE* OS::OpenTemporaryFile() {
591 const char*
const OS::LogFileOpenMode =
"w";
594 void OS::Print(
const char* format, ...) {
596 va_start(args, format);
597 VPrint(format, args);
602 void OS::VPrint(
const char* format, va_list args) {
603 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT) 604 __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
606 vprintf(format, args);
611 void OS::FPrint(FILE* out,
const char* format, ...) {
613 va_start(args, format);
614 VFPrint(out, format, args);
619 void OS::VFPrint(FILE* out,
const char* format, va_list args) {
620 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT) 621 __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
623 vfprintf(out, format, args);
628 void OS::PrintError(
const char* format, ...) {
630 va_start(args, format);
631 VPrintError(format, args);
636 void OS::VPrintError(
const char* format, va_list args) {
637 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT) 638 __android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, format, args);
640 vfprintf(stderr, format, args);
645 int OS::SNPrintF(
char* str,
int length,
const char* format, ...) {
647 va_start(args, format);
648 int result = VSNPrintF(str, length, format, args);
654 int OS::VSNPrintF(
char* str,
658 int n = vsnprintf(str, length, format, args);
659 if (n < 0 || n >= length) {
662 str[length - 1] =
'\0';
674 char* OS::StrChr(
char* str,
int c) {
675 return strchr(str, c);
679 void OS::StrNCpy(
char* dest,
int length,
const char* src,
size_t n) {
680 strncpy(dest, src, n);
693 Mutex thread_creation_mutex_;
696 Thread::Thread(
const Options& options)
698 stack_size_(options.stack_size()),
699 start_semaphore_(nullptr) {
700 if (stack_size_ > 0 && static_cast<size_t>(stack_size_) < PTHREAD_STACK_MIN) {
701 stack_size_ = PTHREAD_STACK_MIN;
703 set_name(options.name());
712 static void SetThreadName(
const char* name) {
713 #if V8_OS_DRAGONFLYBSD || V8_OS_FREEBSD || V8_OS_OPENBSD 714 pthread_set_name_np(pthread_self(), name);
716 STATIC_ASSERT(Thread::kMaxThreadNameLength <= PTHREAD_MAX_NAMELEN_NP);
717 pthread_setname_np(pthread_self(),
"%s", name);
721 int (*dynamic_pthread_setname_np)(
const char*);
722 *
reinterpret_cast<void**
>(&dynamic_pthread_setname_np) =
723 dlsym(RTLD_DEFAULT,
"pthread_setname_np");
724 if (dynamic_pthread_setname_np ==
nullptr)
return;
727 static const int kMaxNameLength = 63;
728 STATIC_ASSERT(Thread::kMaxThreadNameLength <= kMaxNameLength);
729 dynamic_pthread_setname_np(name);
730 #elif defined(PR_SET_NAME) 732 reinterpret_cast<unsigned long>(name),
738 static void* ThreadEntry(
void* arg) {
739 Thread* thread =
reinterpret_cast<Thread*
>(arg);
743 { MutexGuard lock_guard(&thread->data()->thread_creation_mutex_); }
744 SetThreadName(thread->name());
745 DCHECK_NE(thread->data()->thread_, kNoThread);
746 thread->NotifyStartedAndRun();
751 void Thread::set_name(
const char* name) {
752 strncpy(name_, name,
sizeof(name_));
753 name_[
sizeof(name_) - 1] =
'\0';
757 void Thread::Start() {
760 memset(&attr, 0,
sizeof(attr));
761 result = pthread_attr_init(&attr);
762 DCHECK_EQ(0, result);
763 size_t stack_size = stack_size_;
764 if (stack_size == 0) {
767 stack_size = 1 * 1024 * 1024;
770 stack_size = 2 * 1024 * 1024;
773 if (stack_size > 0) {
774 result = pthread_attr_setstacksize(&attr, stack_size);
775 DCHECK_EQ(0, result);
778 MutexGuard lock_guard(&data_->thread_creation_mutex_);
779 result = pthread_create(&data_->thread_, &attr, ThreadEntry,
this);
781 DCHECK_EQ(0, result);
782 result = pthread_attr_destroy(&attr);
783 DCHECK_EQ(0, result);
784 DCHECK_NE(data_->thread_, kNoThread);
788 void Thread::Join() { pthread_join(data_->thread_,
nullptr); }
790 static Thread::LocalStorageKey PthreadKeyToLocalKey(pthread_key_t pthread_key) {
795 STATIC_ASSERT(
sizeof(Thread::LocalStorageKey) ==
sizeof(pthread_key_t));
796 intptr_t ptr_key =
reinterpret_cast<intptr_t
>(pthread_key);
797 return static_cast<Thread::LocalStorageKey
>(ptr_key);
799 return static_cast<Thread::LocalStorageKey
>(pthread_key);
804 static pthread_key_t LocalKeyToPthreadKey(Thread::LocalStorageKey local_key) {
806 STATIC_ASSERT(
sizeof(Thread::LocalStorageKey) ==
sizeof(pthread_key_t));
807 intptr_t ptr_key =
static_cast<intptr_t
>(local_key);
808 return reinterpret_cast<pthread_key_t
>(ptr_key);
810 return static_cast<pthread_key_t
>(local_key);
815 #ifdef V8_FAST_TLS_SUPPORTED 817 static Atomic32 tls_base_offset_initialized = 0;
818 intptr_t kMacTlsBaseOffset = 0;
822 static void InitializeTlsBaseOffset() {
823 const size_t kBufferSize = 128;
824 char buffer[kBufferSize];
825 size_t buffer_size = kBufferSize;
826 int ctl_name[] = { CTL_KERN , KERN_OSRELEASE };
827 if (sysctl(ctl_name, 2, buffer, &buffer_size,
nullptr, 0) != 0) {
828 FATAL(
"V8 failed to get kernel version");
833 buffer[kBufferSize - 1] =
'\0';
834 char* period_pos = strchr(buffer,
'.');
836 int kernel_version_major =
837 static_cast<int>(strtol(buffer,
nullptr, 10));
840 if (kernel_version_major < 11) {
843 #if V8_HOST_ARCH_IA32 844 kMacTlsBaseOffset = 0x48;
846 kMacTlsBaseOffset = 0x60;
850 kMacTlsBaseOffset = 0;
853 Release_Store(&tls_base_offset_initialized, 1);
857 static void CheckFastTls(Thread::LocalStorageKey key) {
858 void* expected =
reinterpret_cast<void*
>(0x1234CAFE);
859 Thread::SetThreadLocal(key, expected);
860 void* actual = Thread::GetExistingThreadLocal(key);
861 if (expected != actual) {
862 FATAL(
"V8 failed to initialize fast TLS on current kernel");
864 Thread::SetThreadLocal(key,
nullptr);
867 #endif // V8_FAST_TLS_SUPPORTED 870 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
871 #ifdef V8_FAST_TLS_SUPPORTED 872 bool check_fast_tls =
false;
873 if (tls_base_offset_initialized == 0) {
874 check_fast_tls =
true;
875 InitializeTlsBaseOffset();
879 int result = pthread_key_create(&key,
nullptr);
880 DCHECK_EQ(0, result);
882 LocalStorageKey local_key = PthreadKeyToLocalKey(key);
883 #ifdef V8_FAST_TLS_SUPPORTED 885 if (check_fast_tls) CheckFastTls(local_key);
891 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
892 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
893 int result = pthread_key_delete(pthread_key);
894 DCHECK_EQ(0, result);
899 void* Thread::GetThreadLocal(LocalStorageKey key) {
900 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
901 return pthread_getspecific(pthread_key);
905 void Thread::SetThreadLocal(LocalStorageKey key,
void* value) {
906 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
907 int result = pthread_setspecific(pthread_key, value);
908 DCHECK_EQ(0, result);