1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Platform-specific code for POSIX goes here. This is not a platform on its
6 // own, but contains the parts which are the same across the POSIX platforms
7 // Linux, MacOS, FreeBSD, OpenBSD, NetBSD and QNX.
12 #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__OpenBSD__)
13 #include <pthread_np.h> // for pthread_set_name_np
15 #include <sched.h> // for sched_yield
21 #include <sys/resource.h>
24 #include <sys/types.h>
25 #if defined(__APPLE__) || defined(__DragonFly__) || defined(__FreeBSD__) || \
26 defined(__NetBSD__) || defined(__OpenBSD__)
27 #include <sys/sysctl.h> // NOLINT, for sysctl
32 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
34 #include <android/log.h> // NOLINT
40 #include "src/base/lazy-instance.h"
41 #include "src/base/macros.h"
42 #include "src/base/platform/platform.h"
43 #include "src/base/platform/time.h"
44 #include "src/base/utils/random-number-generator.h"
46 #ifdef V8_FAST_TLS_SUPPORTED
47 #include "src/base/atomicops.h"
55 #include <sys/prctl.h> // NOLINT, for prctl
59 #include <sys/syscall.h>
67 // 0 is never a valid thread id.
68 const pthread_t kNoThread = (pthread_t) 0;
70 bool g_hard_abort = false;
72 const char* g_gc_fake_mmap = NULL;
77 int OS::ActivationFrameAlignment() {
78 #if V8_TARGET_ARCH_ARM
79 // On EABI ARM targets this is required for fp correctness in the
82 #elif V8_TARGET_ARCH_MIPS
85 // Otherwise we just assume 16 byte alignment, i.e.:
86 // - With gcc 4.4 the tree vectorization optimizer can generate code
87 // that requires 16 byte alignment such as movdqa on x86.
88 // - Mac OS X and Solaris (64-bit) activation frames must be 16 byte-aligned;
89 // see "Mac OS X ABI Function Call Guide"
95 intptr_t OS::CommitPageSize() {
96 static intptr_t page_size = getpagesize();
101 void OS::Free(void* address, const size_t size) {
102 // TODO(1240712): munmap has a return value which is ignored here.
103 int result = munmap(address, size);
109 // Get rid of writable permission on code allocations.
110 void OS::ProtectCode(void* address, const size_t size) {
113 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
115 // The Native Client port of V8 uses an interpreter, so
116 // code pages don't need PROT_EXEC.
117 mprotect(address, size, PROT_READ);
119 mprotect(address, size, PROT_READ | PROT_EXEC);
124 // Create guard pages.
125 void OS::Guard(void* address, const size_t size) {
128 VirtualProtect(address, size, PAGE_NOACCESS, &oldprotect);
130 mprotect(address, size, PROT_NONE);
135 static LazyInstance<RandomNumberGenerator>::type
136 platform_random_number_generator = LAZY_INSTANCE_INITIALIZER;
139 void OS::Initialize(int64_t random_seed, bool hard_abort,
140 const char* const gc_fake_mmap) {
142 platform_random_number_generator.Pointer()->SetSeed(random_seed);
144 g_hard_abort = hard_abort;
145 g_gc_fake_mmap = gc_fake_mmap;
149 const char* OS::GetGCFakeMMapFile() {
150 return g_gc_fake_mmap;
154 void* OS::GetRandomMmapAddr() {
156 // TODO(bradchen): restore randomization once Native Client gets
157 // smarter about using mmap address hints.
158 // See http://code.google.com/p/nativeclient/issues/3341
161 #if defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
162 defined(THREAD_SANITIZER)
163 // Dynamic tools do not support custom mmap addresses.
167 platform_random_number_generator.Pointer()->NextBytes(&raw_addr,
169 #if V8_TARGET_ARCH_X64
170 // Currently available CPUs have 48 bits of virtual addressing. Truncate
171 // the hint address to 46 bits to give the kernel a fighting chance of
172 // fulfilling our placement request.
173 raw_addr &= V8_UINT64_C(0x3ffffffff000);
175 raw_addr &= 0x3ffff000;
178 // For our Solaris/illumos mmap hint, we pick a random address in the bottom
179 // half of the top half of the address space (that is, the third quarter).
180 // Because we do not MAP_FIXED, this will be treated only as a hint -- the
181 // system will not fail to mmap() because something else happens to already
182 // be mapped at our random address. We deliberately set the hint high enough
183 // to get well above the system's break (that is, the heap); Solaris and
184 // illumos will try the hint and if that fails allocate as if there were
185 // no hint at all. The high hint prevents the break from getting hemmed in
186 // at low values, ceding half of the address space to the system heap.
187 raw_addr += 0x80000000;
189 // The range 0x20000000 - 0x60000000 is relatively unpopulated across a
190 // variety of ASLR modes (PAE kernel, NX compat mode, etc) and on macos
192 raw_addr += 0x20000000;
195 return reinterpret_cast<void*>(raw_addr);
199 size_t OS::AllocateAlignment() {
200 return static_cast<size_t>(sysconf(_SC_PAGESIZE));
204 void OS::Sleep(int milliseconds) {
205 useconds_t ms = static_cast<useconds_t>(milliseconds);
212 V8_IMMEDIATE_CRASH();
214 // Redirect to std abort to signal abnormal program termination.
219 void OS::DebugBreak() {
222 #elif V8_HOST_ARCH_ARM64
224 #elif V8_HOST_ARCH_MIPS
226 #elif V8_HOST_ARCH_MIPS64
228 #elif V8_HOST_ARCH_IA32
234 #elif V8_HOST_ARCH_X64
237 #error Unsupported host architecture.
242 // ----------------------------------------------------------------------------
245 double OS::nan_value() {
246 // NAN from math.h is defined in C99 and not in POSIX.
251 int OS::GetCurrentProcessId() {
252 return static_cast<int>(getpid());
256 int OS::GetCurrentThreadId() {
257 #if V8_OS_MACOSX || (V8_OS_ANDROID && defined(__APPLE__))
258 return static_cast<int>(pthread_mach_thread_np(pthread_self()));
260 return static_cast<int>(syscall(__NR_gettid));
262 return static_cast<int>(gettid());
264 return static_cast<int>(reinterpret_cast<intptr_t>(pthread_self()));
269 // ----------------------------------------------------------------------------
270 // POSIX date/time support.
273 int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
275 // Optionally used in Logger::ResourceEvent.
280 if (getrusage(RUSAGE_SELF, &usage) < 0) return -1;
281 *secs = usage.ru_utime.tv_sec;
282 *usecs = usage.ru_utime.tv_usec;
288 double OS::TimeCurrentMillis() {
289 return Time::Now().ToJsTime();
293 class TimezoneCache {};
296 TimezoneCache* OS::CreateTimezoneCache() {
301 void OS::DisposeTimezoneCache(TimezoneCache* cache) {
302 DCHECK(cache == NULL);
306 void OS::ClearTimezoneCache(TimezoneCache* cache) {
307 DCHECK(cache == NULL);
311 double OS::DaylightSavingsOffset(double time, TimezoneCache*) {
312 if (std::isnan(time)) return nan_value();
313 time_t tv = static_cast<time_t>(std::floor(time/msPerSecond));
314 struct tm* t = localtime(&tv);
315 if (NULL == t) return nan_value();
316 return t->tm_isdst > 0 ? 3600 * msPerSecond : 0;
320 int OS::GetLastError() {
325 // ----------------------------------------------------------------------------
326 // POSIX stdio support.
329 FILE* OS::FOpen(const char* path, const char* mode) {
330 FILE* file = fopen(path, mode);
331 if (file == NULL) return NULL;
332 struct stat file_stat;
333 if (fstat(fileno(file), &file_stat) != 0) return NULL;
334 bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
335 if (is_regular_file) return file;
341 bool OS::Remove(const char* path) {
342 return (remove(path) == 0);
346 FILE* OS::OpenTemporaryFile() {
351 const char* const OS::LogFileOpenMode = "w";
354 void OS::Print(const char* format, ...) {
356 va_start(args, format);
357 VPrint(format, args);
362 void OS::VPrint(const char* format, va_list args) {
363 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
364 __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
366 vprintf(format, args);
371 void OS::FPrint(FILE* out, const char* format, ...) {
373 va_start(args, format);
374 VFPrint(out, format, args);
379 void OS::VFPrint(FILE* out, const char* format, va_list args) {
380 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
381 __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
383 vfprintf(out, format, args);
388 void OS::PrintError(const char* format, ...) {
390 va_start(args, format);
391 VPrintError(format, args);
396 void OS::VPrintError(const char* format, va_list args) {
397 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
398 __android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, format, args);
400 vfprintf(stderr, format, args);
405 int OS::SNPrintF(char* str, int length, const char* format, ...) {
407 va_start(args, format);
408 int result = VSNPrintF(str, length, format, args);
414 int OS::VSNPrintF(char* str,
418 int n = vsnprintf(str, length, format, args);
419 if (n < 0 || n >= length) {
420 // If the length is zero, the assignment fails.
422 str[length - 1] = '\0';
430 // ----------------------------------------------------------------------------
431 // POSIX string support.
434 char* OS::StrChr(char* str, int c) {
435 return strchr(str, c);
439 void OS::StrNCpy(char* dest, int length, const char* src, size_t n) {
440 strncpy(dest, src, n);
444 // ----------------------------------------------------------------------------
445 // POSIX thread support.
448 class Thread::PlatformData {
450 PlatformData() : thread_(kNoThread) {}
451 pthread_t thread_; // Thread handle for pthread.
452 // Synchronizes thread creation
453 Mutex thread_creation_mutex_;
456 Thread::Thread(const Options& options)
457 : data_(new PlatformData),
458 stack_size_(options.stack_size()),
459 start_semaphore_(NULL) {
460 if (stack_size_ > 0 && static_cast<size_t>(stack_size_) < PTHREAD_STACK_MIN) {
461 stack_size_ = PTHREAD_STACK_MIN;
463 set_name(options.name());
472 static void SetThreadName(const char* name) {
473 #if V8_OS_DRAGONFLYBSD || V8_OS_FREEBSD || V8_OS_OPENBSD
474 pthread_set_name_np(pthread_self(), name);
476 STATIC_ASSERT(Thread::kMaxThreadNameLength <= PTHREAD_MAX_NAMELEN_NP);
477 pthread_setname_np(pthread_self(), "%s", name);
479 // pthread_setname_np is only available in 10.6 or later, so test
480 // for it at runtime.
481 int (*dynamic_pthread_setname_np)(const char*);
482 *reinterpret_cast<void**>(&dynamic_pthread_setname_np) =
483 dlsym(RTLD_DEFAULT, "pthread_setname_np");
484 if (dynamic_pthread_setname_np == NULL)
487 // Mac OS X does not expose the length limit of the name, so hardcode it.
488 static const int kMaxNameLength = 63;
489 STATIC_ASSERT(Thread::kMaxThreadNameLength <= kMaxNameLength);
490 dynamic_pthread_setname_np(name);
491 #elif defined(PR_SET_NAME)
493 reinterpret_cast<unsigned long>(name), // NOLINT
499 static void* ThreadEntry(void* arg) {
500 Thread* thread = reinterpret_cast<Thread*>(arg);
501 // We take the lock here to make sure that pthread_create finished first since
502 // we don't know which thread will run first (the original thread or the new
504 { LockGuard<Mutex> lock_guard(&thread->data()->thread_creation_mutex_); }
505 SetThreadName(thread->name());
506 DCHECK(thread->data()->thread_ != kNoThread);
507 thread->NotifyStartedAndRun();
512 void Thread::set_name(const char* name) {
513 strncpy(name_, name, sizeof(name_));
514 name_[sizeof(name_) - 1] = '\0';
518 void Thread::Start() {
521 memset(&attr, 0, sizeof(attr));
522 result = pthread_attr_init(&attr);
523 DCHECK_EQ(0, result);
524 // Native client uses default stack size.
526 if (stack_size_ > 0) {
527 result = pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
528 DCHECK_EQ(0, result);
532 LockGuard<Mutex> lock_guard(&data_->thread_creation_mutex_);
533 result = pthread_create(&data_->thread_, &attr, ThreadEntry, this);
535 DCHECK_EQ(0, result);
536 result = pthread_attr_destroy(&attr);
537 DCHECK_EQ(0, result);
538 DCHECK(data_->thread_ != kNoThread);
543 void Thread::Join() {
544 pthread_join(data_->thread_, NULL);
548 void Thread::YieldCPU() {
549 int result = sched_yield();
550 DCHECK_EQ(0, result);
555 static Thread::LocalStorageKey PthreadKeyToLocalKey(pthread_key_t pthread_key) {
557 // We need to cast pthread_key_t to Thread::LocalStorageKey in two steps
558 // because pthread_key_t is a pointer type on Cygwin. This will probably not
559 // work on 64-bit platforms, but Cygwin doesn't support 64-bit anyway.
560 STATIC_ASSERT(sizeof(Thread::LocalStorageKey) == sizeof(pthread_key_t));
561 intptr_t ptr_key = reinterpret_cast<intptr_t>(pthread_key);
562 return static_cast<Thread::LocalStorageKey>(ptr_key);
564 return static_cast<Thread::LocalStorageKey>(pthread_key);
569 static pthread_key_t LocalKeyToPthreadKey(Thread::LocalStorageKey local_key) {
571 STATIC_ASSERT(sizeof(Thread::LocalStorageKey) == sizeof(pthread_key_t));
572 intptr_t ptr_key = static_cast<intptr_t>(local_key);
573 return reinterpret_cast<pthread_key_t>(ptr_key);
575 return static_cast<pthread_key_t>(local_key);
580 #ifdef V8_FAST_TLS_SUPPORTED
582 static Atomic32 tls_base_offset_initialized = 0;
583 intptr_t kMacTlsBaseOffset = 0;
585 // It's safe to do the initialization more that once, but it has to be
586 // done at least once.
587 static void InitializeTlsBaseOffset() {
588 const size_t kBufferSize = 128;
589 char buffer[kBufferSize];
590 size_t buffer_size = kBufferSize;
591 int ctl_name[] = { CTL_KERN , KERN_OSRELEASE };
592 if (sysctl(ctl_name, 2, buffer, &buffer_size, NULL, 0) != 0) {
593 V8_Fatal(__FILE__, __LINE__, "V8 failed to get kernel version");
595 // The buffer now contains a string of the form XX.YY.ZZ, where
596 // XX is the major kernel version component.
597 // Make sure the buffer is 0-terminated.
598 buffer[kBufferSize - 1] = '\0';
599 char* period_pos = strchr(buffer, '.');
601 int kernel_version_major =
602 static_cast<int>(strtol(buffer, NULL, 10)); // NOLINT
603 // The constants below are taken from pthreads.s from the XNU kernel
604 // sources archive at www.opensource.apple.com.
605 if (kernel_version_major < 11) {
606 // 8.x.x (Tiger), 9.x.x (Leopard), 10.x.x (Snow Leopard) have the
608 #if V8_HOST_ARCH_IA32
609 kMacTlsBaseOffset = 0x48;
611 kMacTlsBaseOffset = 0x60;
614 // 11.x.x (Lion) changed the offset.
615 kMacTlsBaseOffset = 0;
618 Release_Store(&tls_base_offset_initialized, 1);
622 static void CheckFastTls(Thread::LocalStorageKey key) {
623 void* expected = reinterpret_cast<void*>(0x1234CAFE);
624 Thread::SetThreadLocal(key, expected);
625 void* actual = Thread::GetExistingThreadLocal(key);
626 if (expected != actual) {
627 V8_Fatal(__FILE__, __LINE__,
628 "V8 failed to initialize fast TLS on current kernel");
630 Thread::SetThreadLocal(key, NULL);
633 #endif // V8_FAST_TLS_SUPPORTED
636 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
637 #ifdef V8_FAST_TLS_SUPPORTED
638 bool check_fast_tls = false;
639 if (tls_base_offset_initialized == 0) {
640 check_fast_tls = true;
641 InitializeTlsBaseOffset();
645 int result = pthread_key_create(&key, NULL);
646 DCHECK_EQ(0, result);
648 LocalStorageKey local_key = PthreadKeyToLocalKey(key);
649 #ifdef V8_FAST_TLS_SUPPORTED
650 // If we just initialized fast TLS support, make sure it works.
651 if (check_fast_tls) CheckFastTls(local_key);
657 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
658 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
659 int result = pthread_key_delete(pthread_key);
660 DCHECK_EQ(0, result);
665 void* Thread::GetThreadLocal(LocalStorageKey key) {
666 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
667 return pthread_getspecific(pthread_key);
671 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
672 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
673 int result = pthread_setspecific(pthread_key, value);
674 DCHECK_EQ(0, result);
679 } } // namespace v8::base