blob: 89abf398c4bda02f3717254372833fd56d210d99 [file] [log] [blame]
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +00001// Copyright 2012 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000028// Platform specific code for MacOS goes here. For the POSIX comaptible parts
29// the implementation is in platform-posix.cc.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000030
lrn@chromium.org5d00b602011-01-05 09:51:43 +000031#include <dlfcn.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000032#include <unistd.h>
33#include <sys/mman.h>
34#include <mach/mach_init.h>
kasperl@chromium.orge959c182009-07-27 08:59:04 +000035#include <mach-o/dyld.h>
36#include <mach-o/getsect.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037
38#include <AvailabilityMacros.h>
39
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000040#include <pthread.h>
41#include <semaphore.h>
42#include <signal.h>
kmillikin@chromium.org9155e252010-05-26 13:27:57 +000043#include <libkern/OSAtomic.h>
kasperl@chromium.org2abc4502009-07-02 07:00:29 +000044#include <mach/mach.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045#include <mach/semaphore.h>
46#include <mach/task.h>
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +000047#include <mach/vm_statistics.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000048#include <sys/time.h>
49#include <sys/resource.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000050#include <sys/types.h>
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +000051#include <sys/sysctl.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000052#include <stdarg.h>
53#include <stdlib.h>
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +000054#include <string.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000055#include <errno.h>
56
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057#undef MAP_TYPE
58
59#include "v8.h"
60
61#include "platform.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000062#include "vm-state-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063
ager@chromium.org5aa501c2009-06-23 07:57:28 +000064// 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
kasperl@chromium.org71affb52009-05-26 05:44:31 +000075namespace v8 {
76namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000077
ulan@chromium.org2efb9002012-01-19 15:36:35 +000078// 0 is never a valid thread id on MacOSX since a pthread_t is
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000079// 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
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000093static Mutex* limit_mutex = NULL;
94
95
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +000096void OS::SetUp() {
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +000097 // Seed the random number generator. We preserve microsecond resolution.
98 uint64_t seed = Ticks() ^ (getpid() << 16);
ager@chromium.org9258b6b2008-09-11 09:11:10 +000099 srandom(static_cast<unsigned int>(seed));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000100 limit_mutex = CreateMutex();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000101}
102
103
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000104// We keep the lowest and highest addresses mapped as a quick way of
105// determining that pointers are outside the heap (used mostly in assertions
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000106// and verification). The estimate is conservative, i.e., not all addresses in
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000107// 'allocated' space are actually allocated to our heap. The range is
108// [lowest, highest), inclusive on the low and and exclusive on the high end.
109static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
110static void* highest_ever_allocated = reinterpret_cast<void*>(0);
111
112
113static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000114 ASSERT(limit_mutex != NULL);
115 ScopedLock lock(limit_mutex);
116
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 lowest_ever_allocated = Min(lowest_ever_allocated, address);
118 highest_ever_allocated =
119 Max(highest_ever_allocated,
120 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
121}
122
123
124bool OS::IsOutsideAllocatedSpace(void* address) {
125 return address < lowest_ever_allocated || address >= highest_ever_allocated;
126}
127
128
129size_t OS::AllocateAlignment() {
kasper.lund7276f142008-07-30 08:49:36 +0000130 return getpagesize();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000131}
132
133
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +0000134// Constants used for mmap.
135// kMmapFd is used to pass vm_alloc flags to tag the region with the user
136// defined tag 255 This helps identify V8-allocated regions in memory analysis
137// tools like vmmap(1).
138static const int kMmapFd = VM_MAKE_TAG(255);
139static const off_t kMmapFdOffset = 0;
140
141
kasper.lund7276f142008-07-30 08:49:36 +0000142void* OS::Allocate(const size_t requested,
143 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000144 bool is_executable) {
kasper.lund7276f142008-07-30 08:49:36 +0000145 const size_t msize = RoundUp(requested, getpagesize());
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000146 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000147 void* mbase = mmap(OS::GetRandomMmapAddr(),
148 msize,
149 prot,
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +0000150 MAP_PRIVATE | MAP_ANON,
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000151 kMmapFd,
152 kMmapFdOffset);
kasper.lund7276f142008-07-30 08:49:36 +0000153 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000154 LOG(Isolate::Current(), StringEvent("OS::Allocate", "mmap failed"));
kasper.lund7276f142008-07-30 08:49:36 +0000155 return NULL;
156 }
157 *allocated = msize;
158 UpdateAllocatedSpaceLimits(mbase, msize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000159 return mbase;
160}
161
162
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000163void OS::Free(void* address, const size_t size) {
kasper.lund7276f142008-07-30 08:49:36 +0000164 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000165 int result = munmap(address, size);
166 USE(result);
167 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000168}
169
170
ager@chromium.org32912102009-01-16 10:38:43 +0000171void OS::Sleep(int milliseconds) {
172 usleep(1000 * milliseconds);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000173}
174
175
176void OS::Abort() {
177 // Redirect to std abort to signal abnormal program termination
178 abort();
179}
180
181
kasper.lund7276f142008-07-30 08:49:36 +0000182void OS::DebugBreak() {
183 asm("int $3");
184}
185
186
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000187class PosixMemoryMappedFile : public OS::MemoryMappedFile {
188 public:
189 PosixMemoryMappedFile(FILE* file, void* memory, int size)
190 : file_(file), memory_(memory), size_(size) { }
191 virtual ~PosixMemoryMappedFile();
192 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000193 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000194 private:
195 FILE* file_;
196 void* memory_;
197 int size_;
198};
199
200
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000201OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000202 FILE* file = fopen(name, "r+");
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000203 if (file == NULL) return NULL;
204
205 fseek(file, 0, SEEK_END);
206 int size = ftell(file);
207
208 void* memory =
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000209 mmap(OS::GetRandomMmapAddr(),
210 size,
211 PROT_READ | PROT_WRITE,
212 MAP_SHARED,
213 fileno(file),
214 0);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000215 return new PosixMemoryMappedFile(file, memory, size);
216}
217
218
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000219OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
220 void* initial) {
221 FILE* file = fopen(name, "w+");
222 if (file == NULL) return NULL;
lrn@chromium.org303ada72010-10-27 09:33:13 +0000223 int result = fwrite(initial, size, 1, file);
224 if (result < 1) {
225 fclose(file);
226 return NULL;
227 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228 void* memory =
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000229 mmap(OS::GetRandomMmapAddr(),
230 size,
231 PROT_READ | PROT_WRITE,
232 MAP_SHARED,
233 fileno(file),
234 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000235 return new PosixMemoryMappedFile(file, memory, size);
236}
237
238
239PosixMemoryMappedFile::~PosixMemoryMappedFile() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000240 if (memory_) OS::Free(memory_, size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000241 fclose(file_);
242}
243
244
245void OS::LogSharedLibraryAddresses() {
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000246 unsigned int images_count = _dyld_image_count();
247 for (unsigned int i = 0; i < images_count; ++i) {
248 const mach_header* header = _dyld_get_image_header(i);
249 if (header == NULL) continue;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000250#if V8_HOST_ARCH_X64
251 uint64_t size;
252 char* code_ptr = getsectdatafromheader_64(
253 reinterpret_cast<const mach_header_64*>(header),
254 SEG_TEXT,
255 SECT_TEXT,
256 &size);
257#else
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000258 unsigned int size;
259 char* code_ptr = getsectdatafromheader(header, SEG_TEXT, SECT_TEXT, &size);
ager@chromium.orga1645e22009-09-09 19:27:10 +0000260#endif
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000261 if (code_ptr == NULL) continue;
262 const uintptr_t slide = _dyld_get_image_vmaddr_slide(i);
263 const uintptr_t start = reinterpret_cast<uintptr_t>(code_ptr) + slide;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000264 LOG(Isolate::Current(),
265 SharedLibraryEvent(_dyld_get_image_name(i), start, start + size));
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000266 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000267}
268
269
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000270void OS::SignalCodeMovingGC() {
271}
272
273
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000274uint64_t OS::CpuFeaturesImpliedByPlatform() {
275 // MacOSX requires all these to install so we can assume they are present.
276 // These constants are defined by the CPUid instructions.
277 const uint64_t one = 1;
278 return (one << SSE2) | (one << CMOV) | (one << RDTSC) | (one << CPUID);
279}
280
281
ager@chromium.org236ad962008-09-25 09:45:57 +0000282int OS::ActivationFrameAlignment() {
283 // OS X activation frames must be 16 byte-aligned; see "Mac OS X ABI
284 // Function Call Guide".
285 return 16;
286}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000287
288
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000289void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
290 OSMemoryBarrier();
291 *ptr = value;
292}
293
294
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000295const char* OS::LocalTimezone(double time) {
296 if (isnan(time)) return "";
297 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
298 struct tm* t = localtime(&tv);
299 if (NULL == t) return "";
300 return t->tm_zone;
301}
302
303
304double OS::LocalTimeOffset() {
305 time_t tv = time(NULL);
306 struct tm* t = localtime(&tv);
307 // tm_gmtoff includes any daylight savings offset, so subtract it.
308 return static_cast<double>(t->tm_gmtoff * msPerSecond -
309 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
310}
311
312
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000313int OS::StackWalk(Vector<StackFrame> frames) {
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000314 // If weak link to execinfo lib has failed, ie because we are on 10.4, abort.
315 if (backtrace == NULL)
316 return 0;
317
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000318 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000319 ScopedVector<void*> addresses(frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000320
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000321 int frames_count = backtrace(addresses.start(), frames_size);
322
323 char** symbols = backtrace_symbols(addresses.start(), frames_count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324 if (symbols == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000325 return kStackWalkError;
326 }
327
328 for (int i = 0; i < frames_count; i++) {
329 frames[i].address = addresses[i];
330 // Format a text representation of the frame based on the information
331 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000332 SNPrintF(MutableCStrVector(frames[i].text,
333 kStackWalkMaxTextLen),
334 "%s",
335 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336 // Make sure line termination is in place.
337 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
338 }
339
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000340 free(symbols);
341
342 return frames_count;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343}
344
345
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000346VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000347
348
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000349VirtualMemory::VirtualMemory(size_t size)
350 : address_(ReserveRegion(size)), size_(size) { }
351
352
353VirtualMemory::VirtualMemory(size_t size, size_t alignment)
354 : address_(NULL), size_(0) {
355 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
356 size_t request_size = RoundUp(size + alignment,
357 static_cast<intptr_t>(OS::AllocateAlignment()));
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000358 void* reservation = mmap(OS::GetRandomMmapAddr(),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000359 request_size,
360 PROT_NONE,
361 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
362 kMmapFd,
363 kMmapFdOffset);
364 if (reservation == MAP_FAILED) return;
365
366 Address base = static_cast<Address>(reservation);
367 Address aligned_base = RoundUp(base, alignment);
368 ASSERT_LE(base, aligned_base);
369
370 // Unmap extra memory reserved before and after the desired block.
371 if (aligned_base != base) {
372 size_t prefix_size = static_cast<size_t>(aligned_base - base);
373 OS::Free(base, prefix_size);
374 request_size -= prefix_size;
375 }
376
377 size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
378 ASSERT_LE(aligned_size, request_size);
379
380 if (aligned_size != request_size) {
381 size_t suffix_size = request_size - aligned_size;
382 OS::Free(aligned_base + aligned_size, suffix_size);
383 request_size -= suffix_size;
384 }
385
386 ASSERT(aligned_size == request_size);
387
388 address_ = static_cast<void*>(aligned_base);
389 size_ = aligned_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000390}
391
392
393VirtualMemory::~VirtualMemory() {
394 if (IsReserved()) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000395 bool result = ReleaseRegion(address(), size());
396 ASSERT(result);
397 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000398 }
399}
400
401
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000402void VirtualMemory::Reset() {
403 address_ = NULL;
404 size_ = 0;
405}
406
407
408void* VirtualMemory::ReserveRegion(size_t size) {
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000409 void* result = mmap(OS::GetRandomMmapAddr(),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000410 size,
411 PROT_NONE,
412 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
413 kMmapFd,
414 kMmapFdOffset);
415
416 if (result == MAP_FAILED) return NULL;
417
418 return result;
419}
420
421
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000422bool VirtualMemory::IsReserved() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000423 return address_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000424}
425
426
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000427bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000428 return CommitRegion(address, size, is_executable);
429}
430
431
yangguo@chromium.orgab30bb82012-02-24 14:41:46 +0000432bool VirtualMemory::Guard(void* address) {
433 OS::Guard(address, OS::CommitPageSize());
434 return true;
435}
436
437
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000438bool VirtualMemory::CommitRegion(void* address,
439 size_t size,
440 bool is_executable) {
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000441 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000442 if (MAP_FAILED == mmap(address,
443 size,
444 prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000445 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000446 kMmapFd,
447 kMmapFdOffset)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000448 return false;
449 }
450
451 UpdateAllocatedSpaceLimits(address, size);
452 return true;
453}
454
455
456bool VirtualMemory::Uncommit(void* address, size_t size) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000457 return UncommitRegion(address, size);
458}
459
460
461bool VirtualMemory::UncommitRegion(void* address, size_t size) {
462 return mmap(address,
463 size,
464 PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000465 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000466 kMmapFd,
467 kMmapFdOffset) != MAP_FAILED;
468}
469
470
471bool VirtualMemory::ReleaseRegion(void* address, size_t size) {
472 return munmap(address, size) == 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473}
474
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000475
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000476class Thread::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000477 public:
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000478 PlatformData() : thread_(kNoThread) {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000479 pthread_t thread_; // Thread handle for pthread.
480};
481
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000482
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000483Thread::Thread(const Options& options)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000484 : data_(new PlatformData),
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000485 stack_size_(options.stack_size()) {
486 set_name(options.name());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000487}
488
489
490Thread::~Thread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000491 delete data_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492}
493
494
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000495static void SetThreadName(const char* name) {
496 // pthread_setname_np is only available in 10.6 or later, so test
497 // for it at runtime.
498 int (*dynamic_pthread_setname_np)(const char*);
499 *reinterpret_cast<void**>(&dynamic_pthread_setname_np) =
500 dlsym(RTLD_DEFAULT, "pthread_setname_np");
501 if (!dynamic_pthread_setname_np)
502 return;
503
504 // Mac OS X does not expose the length limit of the name, so hardcode it.
505 static const int kMaxNameLength = 63;
506 USE(kMaxNameLength);
507 ASSERT(Thread::kMaxThreadNameLength <= kMaxNameLength);
508 dynamic_pthread_setname_np(name);
509}
510
511
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000512static void* ThreadEntry(void* arg) {
513 Thread* thread = reinterpret_cast<Thread*>(arg);
514 // This is also initialized by the first argument to pthread_create() but we
515 // don't know which thread will run first (the original thread or the new
516 // one) so we initialize it here too.
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000517 thread->data()->thread_ = pthread_self();
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000518 SetThreadName(thread->name());
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000519 ASSERT(thread->data()->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 thread->Run();
521 return NULL;
522}
523
524
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000525void Thread::set_name(const char* name) {
526 strncpy(name_, name, sizeof(name_));
527 name_[sizeof(name_) - 1] = '\0';
528}
529
530
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000531void Thread::Start() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000532 pthread_attr_t* attr_ptr = NULL;
533 pthread_attr_t attr;
534 if (stack_size_ > 0) {
535 pthread_attr_init(&attr);
536 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
537 attr_ptr = &attr;
538 }
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000539 pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
540 ASSERT(data_->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000541}
542
543
544void Thread::Join() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000545 pthread_join(data_->thread_, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000546}
547
548
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000549#ifdef V8_FAST_TLS_SUPPORTED
550
551static Atomic32 tls_base_offset_initialized = 0;
552intptr_t kMacTlsBaseOffset = 0;
553
554// It's safe to do the initialization more that once, but it has to be
555// done at least once.
556static void InitializeTlsBaseOffset() {
557 const size_t kBufferSize = 128;
558 char buffer[kBufferSize];
559 size_t buffer_size = kBufferSize;
560 int ctl_name[] = { CTL_KERN , KERN_OSRELEASE };
561 if (sysctl(ctl_name, 2, buffer, &buffer_size, NULL, 0) != 0) {
562 V8_Fatal(__FILE__, __LINE__, "V8 failed to get kernel version");
563 }
564 // The buffer now contains a string of the form XX.YY.ZZ, where
565 // XX is the major kernel version component.
566 // Make sure the buffer is 0-terminated.
567 buffer[kBufferSize - 1] = '\0';
568 char* period_pos = strchr(buffer, '.');
569 *period_pos = '\0';
570 int kernel_version_major =
571 static_cast<int>(strtol(buffer, NULL, 10)); // NOLINT
572 // The constants below are taken from pthreads.s from the XNU kernel
573 // sources archive at www.opensource.apple.com.
574 if (kernel_version_major < 11) {
575 // 8.x.x (Tiger), 9.x.x (Leopard), 10.x.x (Snow Leopard) have the
576 // same offsets.
577#if defined(V8_HOST_ARCH_IA32)
578 kMacTlsBaseOffset = 0x48;
579#else
580 kMacTlsBaseOffset = 0x60;
581#endif
582 } else {
583 // 11.x.x (Lion) changed the offset.
584 kMacTlsBaseOffset = 0;
585 }
586
587 Release_Store(&tls_base_offset_initialized, 1);
588}
589
590static void CheckFastTls(Thread::LocalStorageKey key) {
591 void* expected = reinterpret_cast<void*>(0x1234CAFE);
592 Thread::SetThreadLocal(key, expected);
593 void* actual = Thread::GetExistingThreadLocal(key);
594 if (expected != actual) {
595 V8_Fatal(__FILE__, __LINE__,
596 "V8 failed to initialize fast TLS on current kernel");
597 }
598 Thread::SetThreadLocal(key, NULL);
599}
600
601#endif // V8_FAST_TLS_SUPPORTED
602
603
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000605#ifdef V8_FAST_TLS_SUPPORTED
606 bool check_fast_tls = false;
607 if (tls_base_offset_initialized == 0) {
608 check_fast_tls = true;
609 InitializeTlsBaseOffset();
610 }
611#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000612 pthread_key_t key;
613 int result = pthread_key_create(&key, NULL);
614 USE(result);
615 ASSERT(result == 0);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000616 LocalStorageKey typed_key = static_cast<LocalStorageKey>(key);
617#ifdef V8_FAST_TLS_SUPPORTED
618 // If we just initialized fast TLS support, make sure it works.
619 if (check_fast_tls) CheckFastTls(typed_key);
620#endif
621 return typed_key;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000622}
623
624
625void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
626 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
627 int result = pthread_key_delete(pthread_key);
628 USE(result);
629 ASSERT(result == 0);
630}
631
632
633void* Thread::GetThreadLocal(LocalStorageKey key) {
634 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
635 return pthread_getspecific(pthread_key);
636}
637
638
639void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
640 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
641 pthread_setspecific(pthread_key, value);
642}
643
644
645void Thread::YieldCPU() {
646 sched_yield();
647}
648
649
650class MacOSMutex : public Mutex {
651 public:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000652 MacOSMutex() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000653 pthread_mutexattr_t attr;
654 pthread_mutexattr_init(&attr);
655 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000656 pthread_mutex_init(&mutex_, &attr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000657 }
658
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000659 virtual ~MacOSMutex() { pthread_mutex_destroy(&mutex_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000660
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000661 virtual int Lock() { return pthread_mutex_lock(&mutex_); }
662 virtual int Unlock() { return pthread_mutex_unlock(&mutex_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000663
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000664 virtual bool TryLock() {
665 int result = pthread_mutex_trylock(&mutex_);
666 // Return false if the lock is busy and locking failed.
667 if (result == EBUSY) {
668 return false;
669 }
670 ASSERT(result == 0); // Verify no other errors.
671 return true;
672 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000673
674 private:
675 pthread_mutex_t mutex_;
676};
677
678
679Mutex* OS::CreateMutex() {
680 return new MacOSMutex();
681}
682
683
684class MacOSSemaphore : public Semaphore {
685 public:
686 explicit MacOSSemaphore(int count) {
687 semaphore_create(mach_task_self(), &semaphore_, SYNC_POLICY_FIFO, count);
688 }
689
690 ~MacOSSemaphore() {
691 semaphore_destroy(mach_task_self(), semaphore_);
692 }
693
kasper.lund7276f142008-07-30 08:49:36 +0000694 // The MacOS mach semaphore documentation claims it does not have spurious
695 // wakeups, the way pthreads semaphores do. So the code from the linux
696 // platform is not needed here.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697 void Wait() { semaphore_wait(semaphore_); }
698
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000699 bool Wait(int timeout);
700
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000701 void Signal() { semaphore_signal(semaphore_); }
702
703 private:
704 semaphore_t semaphore_;
705};
706
707
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000708bool MacOSSemaphore::Wait(int timeout) {
709 mach_timespec_t ts;
710 ts.tv_sec = timeout / 1000000;
711 ts.tv_nsec = (timeout % 1000000) * 1000;
712 return semaphore_timedwait(semaphore_, ts) != KERN_OPERATION_TIMED_OUT;
713}
714
715
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000716Semaphore* OS::CreateSemaphore(int count) {
717 return new MacOSSemaphore(count);
718}
719
ager@chromium.org381abbb2009-02-25 13:23:22 +0000720
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000721class Sampler::PlatformData : public Malloced {
722 public:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000723 PlatformData() : profiled_thread_(mach_thread_self()) {}
724
725 ~PlatformData() {
726 // Deallocate Mach port for thread.
727 mach_port_deallocate(mach_task_self(), profiled_thread_);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000728 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000729
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000730 thread_act_t profiled_thread() { return profiled_thread_; }
731
732 private:
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000733 // Note: for profiled_thread_ Mach primitives are used instead of PThread's
734 // because the latter doesn't provide thread manipulation primitives required.
735 // For details, consult "Mac OS X Internals" book, Section 7.3.
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000736 thread_act_t profiled_thread_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000737};
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000738
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000739
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000740class SamplerThread : public Thread {
741 public:
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +0000742 static const int kSamplerThreadStackSize = 64 * KB;
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000743
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000744 explicit SamplerThread(int interval)
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000745 : Thread(Thread::Options("SamplerThread", kSamplerThreadStackSize)),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000746 interval_(interval) {}
747
748 static void AddActiveSampler(Sampler* sampler) {
749 ScopedLock lock(mutex_);
750 SamplerRegistry::AddActiveSampler(sampler);
751 if (instance_ == NULL) {
752 instance_ = new SamplerThread(sampler->interval());
753 instance_->Start();
754 } else {
755 ASSERT(instance_->interval_ == sampler->interval());
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000756 }
757 }
758
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000759 static void RemoveActiveSampler(Sampler* sampler) {
760 ScopedLock lock(mutex_);
761 SamplerRegistry::RemoveActiveSampler(sampler);
762 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000763 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000764 delete instance_;
765 instance_ = NULL;
766 }
767 }
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000768
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000769 // Implement Thread::Run().
770 virtual void Run() {
771 SamplerRegistry::State state;
772 while ((state = SamplerRegistry::GetState()) !=
773 SamplerRegistry::HAS_NO_SAMPLERS) {
774 bool cpu_profiling_enabled =
775 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
776 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
777 // When CPU profiling is enabled both JavaScript and C++ code is
778 // profiled. We must not suspend.
779 if (!cpu_profiling_enabled) {
780 if (rate_limiter_.SuspendIfNecessary()) continue;
781 }
782 if (cpu_profiling_enabled) {
783 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
784 return;
785 }
786 }
787 if (runtime_profiler_enabled) {
788 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
789 return;
790 }
791 }
792 OS::Sleep(interval_);
793 }
794 }
795
796 static void DoCpuProfile(Sampler* sampler, void* raw_sampler_thread) {
797 if (!sampler->isolate()->IsInitialized()) return;
798 if (!sampler->IsProfiling()) return;
799 SamplerThread* sampler_thread =
800 reinterpret_cast<SamplerThread*>(raw_sampler_thread);
801 sampler_thread->SampleContext(sampler);
802 }
803
804 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
805 if (!sampler->isolate()->IsInitialized()) return;
806 sampler->isolate()->runtime_profiler()->NotifyTick();
807 }
808
809 void SampleContext(Sampler* sampler) {
810 thread_act_t profiled_thread = sampler->platform_data()->profiled_thread();
811 TickSample sample_obj;
812 TickSample* sample = CpuProfiler::TickSampleEvent(sampler->isolate());
813 if (sample == NULL) sample = &sample_obj;
814
815 if (KERN_SUCCESS != thread_suspend(profiled_thread)) return;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000816
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000817#if V8_HOST_ARCH_X64
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000818 thread_state_flavor_t flavor = x86_THREAD_STATE64;
819 x86_thread_state64_t state;
820 mach_msg_type_number_t count = x86_THREAD_STATE64_COUNT;
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000821#if __DARWIN_UNIX03
822#define REGISTER_FIELD(name) __r ## name
823#else
824#define REGISTER_FIELD(name) r ## name
825#endif // __DARWIN_UNIX03
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000826#elif V8_HOST_ARCH_IA32
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000827 thread_state_flavor_t flavor = i386_THREAD_STATE;
828 i386_thread_state_t state;
829 mach_msg_type_number_t count = i386_THREAD_STATE_COUNT;
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000830#if __DARWIN_UNIX03
831#define REGISTER_FIELD(name) __e ## name
832#else
833#define REGISTER_FIELD(name) e ## name
834#endif // __DARWIN_UNIX03
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000835#else
836#error Unsupported Mac OS X host architecture.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000837#endif // V8_HOST_ARCH
838
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000839 if (thread_get_state(profiled_thread,
840 flavor,
841 reinterpret_cast<natural_t*>(&state),
842 &count) == KERN_SUCCESS) {
843 sample->state = sampler->isolate()->current_vm_state();
844 sample->pc = reinterpret_cast<Address>(state.REGISTER_FIELD(ip));
845 sample->sp = reinterpret_cast<Address>(state.REGISTER_FIELD(sp));
846 sample->fp = reinterpret_cast<Address>(state.REGISTER_FIELD(bp));
847 sampler->SampleStack(sample);
848 sampler->Tick(sample);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000849 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000850 thread_resume(profiled_thread);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000851 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000852
853 const int interval_;
854 RuntimeProfilerRateLimiter rate_limiter_;
855
856 // Protects the process wide state below.
857 static Mutex* mutex_;
858 static SamplerThread* instance_;
859
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +0000860 private:
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000861 DISALLOW_COPY_AND_ASSIGN(SamplerThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000862};
863
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000864#undef REGISTER_FIELD
865
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000866
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000867Mutex* SamplerThread::mutex_ = OS::CreateMutex();
868SamplerThread* SamplerThread::instance_ = NULL;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000869
870
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000871Sampler::Sampler(Isolate* isolate, int interval)
872 : isolate_(isolate),
873 interval_(interval),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000874 profiling_(false),
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000875 active_(false),
876 samples_taken_(0) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000877 data_ = new PlatformData;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878}
879
880
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000881Sampler::~Sampler() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000882 ASSERT(!IsActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000883 delete data_;
884}
885
886
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000887void Sampler::Start() {
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000888 ASSERT(!IsActive());
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000889 SetActive(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000890 SamplerThread::AddActiveSampler(this);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000891}
892
893
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000894void Sampler::Stop() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000895 ASSERT(IsActive());
896 SamplerThread::RemoveActiveSampler(this);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000897 SetActive(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898}
899
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900
901} } // namespace v8::internal