[go: nahoru, domu]

blob: 6be941a08ba934bf1228deb4f442fb5bcee085c4 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 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
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28// Platform specific code for MacOS goes here. For the POSIX comaptible parts
29// the implementation is in platform-posix.cc.
30
Steve Block9fac8402011-05-12 15:51:54 +010031#include <dlfcn.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000032#include <unistd.h>
33#include <sys/mman.h>
34#include <mach/mach_init.h>
35#include <mach-o/dyld.h>
36#include <mach-o/getsect.h>
37
38#include <AvailabilityMacros.h>
39
40#include <pthread.h>
41#include <semaphore.h>
42#include <signal.h>
Leon Clarkef7060e22010-06-03 12:02:55 +010043#include <libkern/OSAtomic.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000044#include <mach/mach.h>
45#include <mach/semaphore.h>
46#include <mach/task.h>
47#include <mach/vm_statistics.h>
48#include <sys/time.h>
49#include <sys/resource.h>
50#include <sys/types.h>
Ben Murdoch8b112d22011-06-08 16:22:53 +010051#include <sys/sysctl.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000052#include <stdarg.h>
53#include <stdlib.h>
Ben Murdoch8b112d22011-06-08 16:22:53 +010054#include <string.h>
Steve Blocka7e24c12009-10-30 11:49:00 +000055#include <errno.h>
56
57#undef MAP_TYPE
58
59#include "v8.h"
60
61#include "platform.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010062#include "vm-state-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000063
64// Manually define these here as weak imports, rather than including execinfo.h.
65// This lets us launch on 10.4 which does not have these calls.
66extern "C" {
67 extern int backtrace(void**, int) __attribute__((weak_import));
68 extern char** backtrace_symbols(void* const*, int)
69 __attribute__((weak_import));
70 extern void backtrace_symbols_fd(void* const*, int, int)
71 __attribute__((weak_import));
72}
73
74
75namespace v8 {
76namespace internal {
77
78// 0 is never a valid thread id on MacOSX since a ptread_t is
79// a pointer.
80static const pthread_t kNoThread = (pthread_t) 0;
81
82
83double ceiling(double x) {
84 // Correct Mac OS X Leopard 'ceil' behavior.
85 if (-1.0 < x && x < 0.0) {
86 return -0.0;
87 } else {
88 return ceil(x);
89 }
90}
91
92
Steve Block44f0eee2011-05-26 01:26:41 +010093static Mutex* limit_mutex = NULL;
94
95
Steve Blocka7e24c12009-10-30 11:49:00 +000096void OS::Setup() {
97 // Seed the random number generator.
98 // Convert the current time to a 64-bit integer first, before converting it
99 // to an unsigned. Going directly will cause an overflow and the seed to be
100 // set to all ones. The seed will be identical for different instances that
101 // call this setup code within the same millisecond.
102 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
103 srandom(static_cast<unsigned int>(seed));
Steve Block44f0eee2011-05-26 01:26:41 +0100104 limit_mutex = CreateMutex();
Steve Blocka7e24c12009-10-30 11:49:00 +0000105}
106
107
108// We keep the lowest and highest addresses mapped as a quick way of
109// determining that pointers are outside the heap (used mostly in assertions
110// and verification). The estimate is conservative, ie, not all addresses in
111// 'allocated' space are actually allocated to our heap. The range is
112// [lowest, highest), inclusive on the low and and exclusive on the high end.
113static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
114static void* highest_ever_allocated = reinterpret_cast<void*>(0);
115
116
117static void UpdateAllocatedSpaceLimits(void* address, int size) {
Steve Block44f0eee2011-05-26 01:26:41 +0100118 ASSERT(limit_mutex != NULL);
119 ScopedLock lock(limit_mutex);
120
Steve Blocka7e24c12009-10-30 11:49:00 +0000121 lowest_ever_allocated = Min(lowest_ever_allocated, address);
122 highest_ever_allocated =
123 Max(highest_ever_allocated,
124 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
125}
126
127
128bool OS::IsOutsideAllocatedSpace(void* address) {
129 return address < lowest_ever_allocated || address >= highest_ever_allocated;
130}
131
132
133size_t OS::AllocateAlignment() {
134 return getpagesize();
135}
136
137
138// Constants used for mmap.
139// kMmapFd is used to pass vm_alloc flags to tag the region with the user
140// defined tag 255 This helps identify V8-allocated regions in memory analysis
141// tools like vmmap(1).
142static const int kMmapFd = VM_MAKE_TAG(255);
143static const off_t kMmapFdOffset = 0;
144
145
146void* OS::Allocate(const size_t requested,
147 size_t* allocated,
148 bool is_executable) {
149 const size_t msize = RoundUp(requested, getpagesize());
150 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
151 void* mbase = mmap(NULL, msize, prot,
152 MAP_PRIVATE | MAP_ANON,
153 kMmapFd, kMmapFdOffset);
154 if (mbase == MAP_FAILED) {
Steve Block44f0eee2011-05-26 01:26:41 +0100155 LOG(Isolate::Current(), StringEvent("OS::Allocate", "mmap failed"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000156 return NULL;
157 }
158 *allocated = msize;
159 UpdateAllocatedSpaceLimits(mbase, msize);
160 return mbase;
161}
162
163
164void OS::Free(void* address, const size_t size) {
165 // TODO(1240712): munmap has a return value which is ignored here.
166 int result = munmap(address, size);
167 USE(result);
168 ASSERT(result == 0);
169}
170
171
Steve Blocka7e24c12009-10-30 11:49:00 +0000172void OS::Sleep(int milliseconds) {
173 usleep(1000 * milliseconds);
174}
175
176
177void OS::Abort() {
178 // Redirect to std abort to signal abnormal program termination
179 abort();
180}
181
182
183void OS::DebugBreak() {
184 asm("int $3");
185}
186
187
188class PosixMemoryMappedFile : public OS::MemoryMappedFile {
189 public:
190 PosixMemoryMappedFile(FILE* file, void* memory, int size)
191 : file_(file), memory_(memory), size_(size) { }
192 virtual ~PosixMemoryMappedFile();
193 virtual void* memory() { return memory_; }
Steve Block1e0659c2011-05-24 12:43:12 +0100194 virtual int size() { return size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000195 private:
196 FILE* file_;
197 void* memory_;
198 int size_;
199};
200
201
Steve Block1e0659c2011-05-24 12:43:12 +0100202OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100203 FILE* file = fopen(name, "r+");
Steve Block1e0659c2011-05-24 12:43:12 +0100204 if (file == NULL) return NULL;
205
206 fseek(file, 0, SEEK_END);
207 int size = ftell(file);
208
209 void* memory =
210 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
211 return new PosixMemoryMappedFile(file, memory, size);
212}
213
214
Steve Blocka7e24c12009-10-30 11:49:00 +0000215OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
216 void* initial) {
217 FILE* file = fopen(name, "w+");
218 if (file == NULL) return NULL;
John Reck59135872010-11-02 12:39:01 -0700219 int result = fwrite(initial, size, 1, file);
220 if (result < 1) {
221 fclose(file);
222 return NULL;
223 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000224 void* memory =
225 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
226 return new PosixMemoryMappedFile(file, memory, size);
227}
228
229
230PosixMemoryMappedFile::~PosixMemoryMappedFile() {
231 if (memory_) munmap(memory_, size_);
232 fclose(file_);
233}
234
235
236void OS::LogSharedLibraryAddresses() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000237 unsigned int images_count = _dyld_image_count();
238 for (unsigned int i = 0; i < images_count; ++i) {
239 const mach_header* header = _dyld_get_image_header(i);
240 if (header == NULL) continue;
241#if V8_HOST_ARCH_X64
242 uint64_t size;
243 char* code_ptr = getsectdatafromheader_64(
244 reinterpret_cast<const mach_header_64*>(header),
245 SEG_TEXT,
246 SECT_TEXT,
247 &size);
248#else
249 unsigned int size;
250 char* code_ptr = getsectdatafromheader(header, SEG_TEXT, SECT_TEXT, &size);
251#endif
252 if (code_ptr == NULL) continue;
253 const uintptr_t slide = _dyld_get_image_vmaddr_slide(i);
254 const uintptr_t start = reinterpret_cast<uintptr_t>(code_ptr) + slide;
Steve Block44f0eee2011-05-26 01:26:41 +0100255 LOG(Isolate::Current(),
256 SharedLibraryEvent(_dyld_get_image_name(i), start, start + size));
Steve Blocka7e24c12009-10-30 11:49:00 +0000257 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000258}
259
260
Ben Murdochf87a2032010-10-22 12:50:53 +0100261void OS::SignalCodeMovingGC() {
262}
263
264
Steve Blockd0582a62009-12-15 09:54:21 +0000265uint64_t OS::CpuFeaturesImpliedByPlatform() {
266 // MacOSX requires all these to install so we can assume they are present.
267 // These constants are defined by the CPUid instructions.
268 const uint64_t one = 1;
269 return (one << SSE2) | (one << CMOV) | (one << RDTSC) | (one << CPUID);
Steve Blocka7e24c12009-10-30 11:49:00 +0000270}
271
272
273int OS::ActivationFrameAlignment() {
274 // OS X activation frames must be 16 byte-aligned; see "Mac OS X ABI
275 // Function Call Guide".
276 return 16;
277}
278
279
Leon Clarkef7060e22010-06-03 12:02:55 +0100280void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
281 OSMemoryBarrier();
282 *ptr = value;
283}
284
285
Leon Clarked91b9f72010-01-27 17:25:45 +0000286const char* OS::LocalTimezone(double time) {
287 if (isnan(time)) return "";
288 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
289 struct tm* t = localtime(&tv);
290 if (NULL == t) return "";
291 return t->tm_zone;
292}
293
294
295double OS::LocalTimeOffset() {
296 time_t tv = time(NULL);
297 struct tm* t = localtime(&tv);
298 // tm_gmtoff includes any daylight savings offset, so subtract it.
299 return static_cast<double>(t->tm_gmtoff * msPerSecond -
300 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
301}
302
303
Steve Blocka7e24c12009-10-30 11:49:00 +0000304int OS::StackWalk(Vector<StackFrame> frames) {
305 // If weak link to execinfo lib has failed, ie because we are on 10.4, abort.
306 if (backtrace == NULL)
307 return 0;
308
309 int frames_size = frames.length();
Kristian Monsen25f61362010-05-21 11:50:48 +0100310 ScopedVector<void*> addresses(frames_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000311
Kristian Monsen25f61362010-05-21 11:50:48 +0100312 int frames_count = backtrace(addresses.start(), frames_size);
313
314 char** symbols = backtrace_symbols(addresses.start(), frames_count);
Steve Blocka7e24c12009-10-30 11:49:00 +0000315 if (symbols == NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000316 return kStackWalkError;
317 }
318
319 for (int i = 0; i < frames_count; i++) {
320 frames[i].address = addresses[i];
321 // Format a text representation of the frame based on the information
322 // available.
323 SNPrintF(MutableCStrVector(frames[i].text,
324 kStackWalkMaxTextLen),
325 "%s",
326 symbols[i]);
327 // Make sure line termination is in place.
328 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
329 }
330
Steve Blocka7e24c12009-10-30 11:49:00 +0000331 free(symbols);
332
333 return frames_count;
334}
335
336
337
338
339VirtualMemory::VirtualMemory(size_t size) {
340 address_ = mmap(NULL, size, PROT_NONE,
341 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
342 kMmapFd, kMmapFdOffset);
343 size_ = size;
344}
345
346
347VirtualMemory::~VirtualMemory() {
348 if (IsReserved()) {
349 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
350 }
351}
352
353
354bool VirtualMemory::IsReserved() {
355 return address_ != MAP_FAILED;
356}
357
358
359bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
360 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
361 if (MAP_FAILED == mmap(address, size, prot,
362 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
363 kMmapFd, kMmapFdOffset)) {
364 return false;
365 }
366
367 UpdateAllocatedSpaceLimits(address, size);
368 return true;
369}
370
371
372bool VirtualMemory::Uncommit(void* address, size_t size) {
373 return mmap(address, size, PROT_NONE,
374 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
375 kMmapFd, kMmapFdOffset) != MAP_FAILED;
376}
377
378
Ben Murdoch8b112d22011-06-08 16:22:53 +0100379class Thread::PlatformData : public Malloced {
Steve Blocka7e24c12009-10-30 11:49:00 +0000380 public:
Ben Murdoch8b112d22011-06-08 16:22:53 +0100381 PlatformData() : thread_(kNoThread) {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000382 pthread_t thread_; // Thread handle for pthread.
383};
384
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000385Thread::Thread(const Options& options)
Ben Murdoch8b112d22011-06-08 16:22:53 +0100386 : data_(new PlatformData),
Steve Block44f0eee2011-05-26 01:26:41 +0100387 stack_size_(options.stack_size) {
388 set_name(options.name);
Steve Block9fac8402011-05-12 15:51:54 +0100389}
390
391
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000392Thread::Thread(const char* name)
Ben Murdoch8b112d22011-06-08 16:22:53 +0100393 : data_(new PlatformData),
Steve Block44f0eee2011-05-26 01:26:41 +0100394 stack_size_(0) {
Steve Block9fac8402011-05-12 15:51:54 +0100395 set_name(name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000396}
397
398
399Thread::~Thread() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100400 delete data_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000401}
402
403
Steve Block9fac8402011-05-12 15:51:54 +0100404static void SetThreadName(const char* name) {
405 // pthread_setname_np is only available in 10.6 or later, so test
406 // for it at runtime.
407 int (*dynamic_pthread_setname_np)(const char*);
408 *reinterpret_cast<void**>(&dynamic_pthread_setname_np) =
409 dlsym(RTLD_DEFAULT, "pthread_setname_np");
410 if (!dynamic_pthread_setname_np)
411 return;
412
413 // Mac OS X does not expose the length limit of the name, so hardcode it.
414 static const int kMaxNameLength = 63;
415 USE(kMaxNameLength);
416 ASSERT(Thread::kMaxThreadNameLength <= kMaxNameLength);
417 dynamic_pthread_setname_np(name);
418}
419
420
Steve Blocka7e24c12009-10-30 11:49:00 +0000421static void* ThreadEntry(void* arg) {
422 Thread* thread = reinterpret_cast<Thread*>(arg);
423 // This is also initialized by the first argument to pthread_create() but we
424 // don't know which thread will run first (the original thread or the new
425 // one) so we initialize it here too.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100426 thread->data()->thread_ = pthread_self();
Steve Block9fac8402011-05-12 15:51:54 +0100427 SetThreadName(thread->name());
Ben Murdoch8b112d22011-06-08 16:22:53 +0100428 ASSERT(thread->data()->thread_ != kNoThread);
Steve Blocka7e24c12009-10-30 11:49:00 +0000429 thread->Run();
430 return NULL;
431}
432
433
Steve Block9fac8402011-05-12 15:51:54 +0100434void Thread::set_name(const char* name) {
435 strncpy(name_, name, sizeof(name_));
436 name_[sizeof(name_) - 1] = '\0';
437}
438
439
Steve Blocka7e24c12009-10-30 11:49:00 +0000440void Thread::Start() {
Steve Block44f0eee2011-05-26 01:26:41 +0100441 pthread_attr_t* attr_ptr = NULL;
442 pthread_attr_t attr;
443 if (stack_size_ > 0) {
444 pthread_attr_init(&attr);
445 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
446 attr_ptr = &attr;
447 }
Ben Murdoch8b112d22011-06-08 16:22:53 +0100448 pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
449 ASSERT(data_->thread_ != kNoThread);
Steve Blocka7e24c12009-10-30 11:49:00 +0000450}
451
452
453void Thread::Join() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100454 pthread_join(data_->thread_, NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000455}
456
457
Ben Murdoch8b112d22011-06-08 16:22:53 +0100458#ifdef V8_FAST_TLS_SUPPORTED
459
460static Atomic32 tls_base_offset_initialized = 0;
461intptr_t kMacTlsBaseOffset = 0;
462
463// It's safe to do the initialization more that once, but it has to be
464// done at least once.
465static void InitializeTlsBaseOffset() {
466 const size_t kBufferSize = 128;
467 char buffer[kBufferSize];
468 size_t buffer_size = kBufferSize;
469 int ctl_name[] = { CTL_KERN , KERN_OSRELEASE };
470 if (sysctl(ctl_name, 2, buffer, &buffer_size, NULL, 0) != 0) {
471 V8_Fatal(__FILE__, __LINE__, "V8 failed to get kernel version");
472 }
473 // The buffer now contains a string of the form XX.YY.ZZ, where
474 // XX is the major kernel version component.
475 // Make sure the buffer is 0-terminated.
476 buffer[kBufferSize - 1] = '\0';
477 char* period_pos = strchr(buffer, '.');
478 *period_pos = '\0';
479 int kernel_version_major =
480 static_cast<int>(strtol(buffer, NULL, 10)); // NOLINT
481 // The constants below are taken from pthreads.s from the XNU kernel
482 // sources archive at www.opensource.apple.com.
483 if (kernel_version_major < 11) {
484 // 8.x.x (Tiger), 9.x.x (Leopard), 10.x.x (Snow Leopard) have the
485 // same offsets.
486#if defined(V8_HOST_ARCH_IA32)
487 kMacTlsBaseOffset = 0x48;
488#else
489 kMacTlsBaseOffset = 0x60;
490#endif
491 } else {
492 // 11.x.x (Lion) changed the offset.
493 kMacTlsBaseOffset = 0;
494 }
495
496 Release_Store(&tls_base_offset_initialized, 1);
497}
498
499static void CheckFastTls(Thread::LocalStorageKey key) {
500 void* expected = reinterpret_cast<void*>(0x1234CAFE);
501 Thread::SetThreadLocal(key, expected);
502 void* actual = Thread::GetExistingThreadLocal(key);
503 if (expected != actual) {
504 V8_Fatal(__FILE__, __LINE__,
505 "V8 failed to initialize fast TLS on current kernel");
506 }
507 Thread::SetThreadLocal(key, NULL);
508}
509
510#endif // V8_FAST_TLS_SUPPORTED
511
512
Steve Blocka7e24c12009-10-30 11:49:00 +0000513Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100514#ifdef V8_FAST_TLS_SUPPORTED
515 bool check_fast_tls = false;
516 if (tls_base_offset_initialized == 0) {
517 check_fast_tls = true;
518 InitializeTlsBaseOffset();
519 }
520#endif
Steve Blocka7e24c12009-10-30 11:49:00 +0000521 pthread_key_t key;
522 int result = pthread_key_create(&key, NULL);
523 USE(result);
524 ASSERT(result == 0);
Ben Murdoch8b112d22011-06-08 16:22:53 +0100525 LocalStorageKey typed_key = static_cast<LocalStorageKey>(key);
526#ifdef V8_FAST_TLS_SUPPORTED
527 // If we just initialized fast TLS support, make sure it works.
528 if (check_fast_tls) CheckFastTls(typed_key);
529#endif
530 return typed_key;
Steve Blocka7e24c12009-10-30 11:49:00 +0000531}
532
533
534void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
535 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
536 int result = pthread_key_delete(pthread_key);
537 USE(result);
538 ASSERT(result == 0);
539}
540
541
542void* Thread::GetThreadLocal(LocalStorageKey key) {
543 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
544 return pthread_getspecific(pthread_key);
545}
546
547
548void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
549 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
550 pthread_setspecific(pthread_key, value);
551}
552
553
554void Thread::YieldCPU() {
555 sched_yield();
556}
557
558
559class MacOSMutex : public Mutex {
560 public:
Steve Blocka7e24c12009-10-30 11:49:00 +0000561 MacOSMutex() {
562 pthread_mutexattr_t attr;
563 pthread_mutexattr_init(&attr);
564 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
565 pthread_mutex_init(&mutex_, &attr);
566 }
567
Ben Murdochb0fe1622011-05-05 13:52:32 +0100568 virtual ~MacOSMutex() { pthread_mutex_destroy(&mutex_); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000569
Ben Murdochb0fe1622011-05-05 13:52:32 +0100570 virtual int Lock() { return pthread_mutex_lock(&mutex_); }
571 virtual int Unlock() { return pthread_mutex_unlock(&mutex_); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000572
Ben Murdochb0fe1622011-05-05 13:52:32 +0100573 virtual bool TryLock() {
574 int result = pthread_mutex_trylock(&mutex_);
575 // Return false if the lock is busy and locking failed.
576 if (result == EBUSY) {
577 return false;
578 }
579 ASSERT(result == 0); // Verify no other errors.
580 return true;
581 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000582
583 private:
584 pthread_mutex_t mutex_;
585};
586
587
588Mutex* OS::CreateMutex() {
589 return new MacOSMutex();
590}
591
592
593class MacOSSemaphore : public Semaphore {
594 public:
595 explicit MacOSSemaphore(int count) {
596 semaphore_create(mach_task_self(), &semaphore_, SYNC_POLICY_FIFO, count);
597 }
598
599 ~MacOSSemaphore() {
600 semaphore_destroy(mach_task_self(), semaphore_);
601 }
602
603 // The MacOS mach semaphore documentation claims it does not have spurious
604 // wakeups, the way pthreads semaphores do. So the code from the linux
605 // platform is not needed here.
606 void Wait() { semaphore_wait(semaphore_); }
607
608 bool Wait(int timeout);
609
610 void Signal() { semaphore_signal(semaphore_); }
611
612 private:
613 semaphore_t semaphore_;
614};
615
616
617bool MacOSSemaphore::Wait(int timeout) {
618 mach_timespec_t ts;
619 ts.tv_sec = timeout / 1000000;
620 ts.tv_nsec = (timeout % 1000000) * 1000;
621 return semaphore_timedwait(semaphore_, ts) != KERN_OPERATION_TIMED_OUT;
622}
623
624
625Semaphore* OS::CreateSemaphore(int count) {
626 return new MacOSSemaphore(count);
627}
628
629
Steve Blocka7e24c12009-10-30 11:49:00 +0000630class Sampler::PlatformData : public Malloced {
631 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100632 PlatformData() : profiled_thread_(mach_thread_self()) {}
633
634 ~PlatformData() {
635 // Deallocate Mach port for thread.
636 mach_port_deallocate(mach_task_self(), profiled_thread_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000637 }
638
Steve Block44f0eee2011-05-26 01:26:41 +0100639 thread_act_t profiled_thread() { return profiled_thread_; }
640
641 private:
Steve Blocka7e24c12009-10-30 11:49:00 +0000642 // Note: for profiled_thread_ Mach primitives are used instead of PThread's
643 // because the latter doesn't provide thread manipulation primitives required.
644 // For details, consult "Mac OS X Internals" book, Section 7.3.
Steve Blocka7e24c12009-10-30 11:49:00 +0000645 thread_act_t profiled_thread_;
Steve Block44f0eee2011-05-26 01:26:41 +0100646};
Steve Blocka7e24c12009-10-30 11:49:00 +0000647
Steve Block44f0eee2011-05-26 01:26:41 +0100648class SamplerThread : public Thread {
649 public:
650 explicit SamplerThread(int interval)
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000651 : Thread("SamplerThread"),
Steve Block44f0eee2011-05-26 01:26:41 +0100652 interval_(interval) {}
653
654 static void AddActiveSampler(Sampler* sampler) {
655 ScopedLock lock(mutex_);
656 SamplerRegistry::AddActiveSampler(sampler);
657 if (instance_ == NULL) {
658 instance_ = new SamplerThread(sampler->interval());
659 instance_->Start();
660 } else {
661 ASSERT(instance_->interval_ == sampler->interval());
Ben Murdochb0fe1622011-05-05 13:52:32 +0100662 }
663 }
664
Steve Block44f0eee2011-05-26 01:26:41 +0100665 static void RemoveActiveSampler(Sampler* sampler) {
666 ScopedLock lock(mutex_);
667 SamplerRegistry::RemoveActiveSampler(sampler);
668 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
Ben Murdoch3fb3ca82011-12-02 17:19:32 +0000669 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
Steve Block44f0eee2011-05-26 01:26:41 +0100670 delete instance_;
671 instance_ = NULL;
672 }
673 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000674
Steve Block44f0eee2011-05-26 01:26:41 +0100675 // Implement Thread::Run().
676 virtual void Run() {
677 SamplerRegistry::State state;
678 while ((state = SamplerRegistry::GetState()) !=
679 SamplerRegistry::HAS_NO_SAMPLERS) {
680 bool cpu_profiling_enabled =
681 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
682 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
683 // When CPU profiling is enabled both JavaScript and C++ code is
684 // profiled. We must not suspend.
685 if (!cpu_profiling_enabled) {
686 if (rate_limiter_.SuspendIfNecessary()) continue;
687 }
688 if (cpu_profiling_enabled) {
689 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
690 return;
691 }
692 }
693 if (runtime_profiler_enabled) {
694 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
695 return;
696 }
697 }
698 OS::Sleep(interval_);
699 }
700 }
701
702 static void DoCpuProfile(Sampler* sampler, void* raw_sampler_thread) {
703 if (!sampler->isolate()->IsInitialized()) return;
704 if (!sampler->IsProfiling()) return;
705 SamplerThread* sampler_thread =
706 reinterpret_cast<SamplerThread*>(raw_sampler_thread);
707 sampler_thread->SampleContext(sampler);
708 }
709
710 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
711 if (!sampler->isolate()->IsInitialized()) return;
712 sampler->isolate()->runtime_profiler()->NotifyTick();
713 }
714
715 void SampleContext(Sampler* sampler) {
716 thread_act_t profiled_thread = sampler->platform_data()->profiled_thread();
717 TickSample sample_obj;
718 TickSample* sample = CpuProfiler::TickSampleEvent(sampler->isolate());
719 if (sample == NULL) sample = &sample_obj;
720
721 if (KERN_SUCCESS != thread_suspend(profiled_thread)) return;
Ben Murdochf87a2032010-10-22 12:50:53 +0100722
Steve Blocka7e24c12009-10-30 11:49:00 +0000723#if V8_HOST_ARCH_X64
Steve Block44f0eee2011-05-26 01:26:41 +0100724 thread_state_flavor_t flavor = x86_THREAD_STATE64;
725 x86_thread_state64_t state;
726 mach_msg_type_number_t count = x86_THREAD_STATE64_COUNT;
Steve Blocka7e24c12009-10-30 11:49:00 +0000727#if __DARWIN_UNIX03
728#define REGISTER_FIELD(name) __r ## name
729#else
730#define REGISTER_FIELD(name) r ## name
731#endif // __DARWIN_UNIX03
732#elif V8_HOST_ARCH_IA32
Steve Block44f0eee2011-05-26 01:26:41 +0100733 thread_state_flavor_t flavor = i386_THREAD_STATE;
734 i386_thread_state_t state;
735 mach_msg_type_number_t count = i386_THREAD_STATE_COUNT;
Steve Blocka7e24c12009-10-30 11:49:00 +0000736#if __DARWIN_UNIX03
737#define REGISTER_FIELD(name) __e ## name
738#else
739#define REGISTER_FIELD(name) e ## name
740#endif // __DARWIN_UNIX03
741#else
742#error Unsupported Mac OS X host architecture.
743#endif // V8_HOST_ARCH
744
Steve Block44f0eee2011-05-26 01:26:41 +0100745 if (thread_get_state(profiled_thread,
746 flavor,
747 reinterpret_cast<natural_t*>(&state),
748 &count) == KERN_SUCCESS) {
749 sample->state = sampler->isolate()->current_vm_state();
750 sample->pc = reinterpret_cast<Address>(state.REGISTER_FIELD(ip));
751 sample->sp = reinterpret_cast<Address>(state.REGISTER_FIELD(sp));
752 sample->fp = reinterpret_cast<Address>(state.REGISTER_FIELD(bp));
753 sampler->SampleStack(sample);
754 sampler->Tick(sample);
Steve Blocka7e24c12009-10-30 11:49:00 +0000755 }
Steve Block44f0eee2011-05-26 01:26:41 +0100756 thread_resume(profiled_thread);
Steve Blocka7e24c12009-10-30 11:49:00 +0000757 }
Steve Block44f0eee2011-05-26 01:26:41 +0100758
759 const int interval_;
760 RuntimeProfilerRateLimiter rate_limiter_;
761
762 // Protects the process wide state below.
763 static Mutex* mutex_;
764 static SamplerThread* instance_;
765
766 DISALLOW_COPY_AND_ASSIGN(SamplerThread);
Steve Blocka7e24c12009-10-30 11:49:00 +0000767};
768
769#undef REGISTER_FIELD
770
771
Steve Block44f0eee2011-05-26 01:26:41 +0100772Mutex* SamplerThread::mutex_ = OS::CreateMutex();
773SamplerThread* SamplerThread::instance_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000774
775
Steve Block44f0eee2011-05-26 01:26:41 +0100776Sampler::Sampler(Isolate* isolate, int interval)
777 : isolate_(isolate),
778 interval_(interval),
Ben Murdochb0fe1622011-05-05 13:52:32 +0100779 profiling_(false),
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800780 active_(false),
781 samples_taken_(0) {
Steve Block44f0eee2011-05-26 01:26:41 +0100782 data_ = new PlatformData;
Steve Blocka7e24c12009-10-30 11:49:00 +0000783}
784
785
786Sampler::~Sampler() {
Steve Block44f0eee2011-05-26 01:26:41 +0100787 ASSERT(!IsActive());
Steve Blocka7e24c12009-10-30 11:49:00 +0000788 delete data_;
789}
790
791
792void Sampler::Start() {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100793 ASSERT(!IsActive());
Ben Murdochb0fe1622011-05-05 13:52:32 +0100794 SetActive(true);
Steve Block44f0eee2011-05-26 01:26:41 +0100795 SamplerThread::AddActiveSampler(this);
Steve Blocka7e24c12009-10-30 11:49:00 +0000796}
797
798
799void Sampler::Stop() {
Steve Block44f0eee2011-05-26 01:26:41 +0100800 ASSERT(IsActive());
801 SamplerThread::RemoveActiveSampler(this);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100802 SetActive(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000803}
804
Steve Blocka7e24c12009-10-30 11:49:00 +0000805
806} } // namespace v8::internal