blob: 79134da35255b529e95920fc6542116fe9402dba [file] [log] [blame]
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +00001// Copyright 2012 the V8 project authors. All rights reserved.
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +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
28// Platform specific code for Cygwin goes here. For the POSIX comaptible parts
29// the implementation is in platform-posix.cc.
30
31#include <errno.h>
32#include <pthread.h>
33#include <semaphore.h>
34#include <stdarg.h>
35#include <strings.h> // index
36#include <sys/time.h>
37#include <sys/mman.h> // mmap & munmap
38#include <unistd.h> // sysconf
39
40#undef MAP_TYPE
41
42#include "v8.h"
43
44#include "platform.h"
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +000045#include "v8threads.h"
46#include "vm-state-inl.h"
47#include "win32-headers.h"
48
49namespace v8 {
50namespace internal {
51
52// 0 is never a valid thread id
53static const pthread_t kNoThread = (pthread_t) 0;
54
55
56double ceiling(double x) {
57 return ceil(x);
58}
59
60
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +000061static Mutex* limit_mutex = NULL;
62
63
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +000064void OS::SetUp() {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +000065 // Seed the random number generator.
66 // Convert the current time to a 64-bit integer first, before converting it
67 // to an unsigned. Going directly can cause an overflow and the seed to be
68 // set to all ones. The seed will be identical for different instances that
69 // call this setup code within the same millisecond.
70 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
71 srandom(static_cast<unsigned int>(seed));
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +000072 limit_mutex = CreateMutex();
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +000073}
74
75
76uint64_t OS::CpuFeaturesImpliedByPlatform() {
77 return 0; // Nothing special about Cygwin.
78}
79
80
81int OS::ActivationFrameAlignment() {
82 // With gcc 4.4 the tree vectorization optimizer can generate code
83 // that requires 16 byte alignment such as movdqa on x86.
84 return 16;
85}
86
87
88void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
89 __asm__ __volatile__("" : : : "memory");
90 // An x86 store acts as a release barrier.
91 *ptr = value;
92}
93
94const char* OS::LocalTimezone(double time) {
95 if (isnan(time)) return "";
96 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
97 struct tm* t = localtime(&tv);
98 if (NULL == t) return "";
99 return tzname[0]; // The location of the timezone string on Cygwin.
100}
101
102
103double OS::LocalTimeOffset() {
104 // On Cygwin, struct tm does not contain a tm_gmtoff field.
105 time_t utc = time(NULL);
106 ASSERT(utc != -1);
107 struct tm* loc = localtime(&utc);
108 ASSERT(loc != NULL);
109 // time - localtime includes any daylight savings offset, so subtract it.
110 return static_cast<double>((mktime(loc) - utc) * msPerSecond -
111 (loc->tm_isdst > 0 ? 3600 * msPerSecond : 0));
112}
113
114
115// We keep the lowest and highest addresses mapped as a quick way of
116// determining that pointers are outside the heap (used mostly in assertions
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000117// and verification). The estimate is conservative, i.e., not all addresses in
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000118// 'allocated' space are actually allocated to our heap. The range is
119// [lowest, highest), inclusive on the low and and exclusive on the high end.
120static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
121static void* highest_ever_allocated = reinterpret_cast<void*>(0);
122
123
124static void UpdateAllocatedSpaceLimits(void* address, int size) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000125 ASSERT(limit_mutex != NULL);
126 ScopedLock lock(limit_mutex);
127
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000128 lowest_ever_allocated = Min(lowest_ever_allocated, address);
129 highest_ever_allocated =
130 Max(highest_ever_allocated,
131 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
132}
133
134
135bool OS::IsOutsideAllocatedSpace(void* address) {
136 return address < lowest_ever_allocated || address >= highest_ever_allocated;
137}
138
139
140size_t OS::AllocateAlignment() {
141 return sysconf(_SC_PAGESIZE);
142}
143
144
145void* OS::Allocate(const size_t requested,
146 size_t* allocated,
147 bool is_executable) {
148 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
149 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
150 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
151 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000152 LOG(ISOLATE, StringEvent("OS::Allocate", "mmap failed"));
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000153 return NULL;
154 }
155 *allocated = msize;
156 UpdateAllocatedSpaceLimits(mbase, msize);
157 return mbase;
158}
159
160
161void OS::Free(void* address, const size_t size) {
162 // TODO(1240712): munmap has a return value which is ignored here.
163 int result = munmap(address, size);
164 USE(result);
165 ASSERT(result == 0);
166}
167
168
lrn@chromium.orgd4e9e222011-08-03 12:01:58 +0000169void OS::ProtectCode(void* address, const size_t size) {
170 DWORD old_protect;
171 VirtualProtect(address, size, PAGE_EXECUTE_READ, &old_protect);
172}
173
174
175void OS::Guard(void* address, const size_t size) {
176 DWORD oldprotect;
177 VirtualProtect(address, size, PAGE_READONLY | PAGE_GUARD, &oldprotect);
178}
179
180
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000181void OS::Sleep(int milliseconds) {
182 unsigned int ms = static_cast<unsigned int>(milliseconds);
183 usleep(1000 * ms);
184}
185
186
187void OS::Abort() {
188 // Redirect to std abort to signal abnormal program termination.
189 abort();
190}
191
192
193void OS::DebugBreak() {
194 asm("int $3");
195}
196
197
198class PosixMemoryMappedFile : public OS::MemoryMappedFile {
199 public:
200 PosixMemoryMappedFile(FILE* file, void* memory, int size)
201 : file_(file), memory_(memory), size_(size) { }
202 virtual ~PosixMemoryMappedFile();
203 virtual void* memory() { return memory_; }
204 virtual int size() { return size_; }
205 private:
206 FILE* file_;
207 void* memory_;
208 int size_;
209};
210
211
212OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
213 FILE* file = fopen(name, "r+");
214 if (file == NULL) return NULL;
215
216 fseek(file, 0, SEEK_END);
217 int size = ftell(file);
218
219 void* memory =
220 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
221 return new PosixMemoryMappedFile(file, memory, size);
222}
223
224
225OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
226 void* initial) {
227 FILE* file = fopen(name, "w+");
228 if (file == NULL) return NULL;
229 int result = fwrite(initial, size, 1, file);
230 if (result < 1) {
231 fclose(file);
232 return NULL;
233 }
234 void* memory =
235 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
236 return new PosixMemoryMappedFile(file, memory, size);
237}
238
239
240PosixMemoryMappedFile::~PosixMemoryMappedFile() {
241 if (memory_) munmap(memory_, size_);
242 fclose(file_);
243}
244
245
246void OS::LogSharedLibraryAddresses() {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000247 // This function assumes that the layout of the file is as follows:
248 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
249 // If we encounter an unexpected situation we abort scanning further entries.
250 FILE* fp = fopen("/proc/self/maps", "r");
251 if (fp == NULL) return;
252
253 // Allocate enough room to be able to store a full file name.
254 const int kLibNameLen = FILENAME_MAX + 1;
255 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
256
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000257 i::Isolate* isolate = ISOLATE;
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000258 // This loop will terminate once the scanning hits an EOF.
259 while (true) {
260 uintptr_t start, end;
261 char attr_r, attr_w, attr_x, attr_p;
262 // Parse the addresses and permission bits at the beginning of the line.
263 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
264 if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break;
265
266 int c;
267 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
268 // Found a read-only executable entry. Skip characters until we reach
269 // the beginning of the filename or the end of the line.
270 do {
271 c = getc(fp);
272 } while ((c != EOF) && (c != '\n') && (c != '/'));
273 if (c == EOF) break; // EOF: Was unexpected, just exit.
274
275 // Process the filename if found.
276 if (c == '/') {
277 ungetc(c, fp); // Push the '/' back into the stream to be read below.
278
279 // Read to the end of the line. Exit if the read fails.
280 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
281
282 // Drop the newline character read by fgets. We do not need to check
283 // for a zero-length string because we know that we at least read the
284 // '/' character.
285 lib_name[strlen(lib_name) - 1] = '\0';
286 } else {
287 // No library name found, just record the raw address range.
288 snprintf(lib_name, kLibNameLen,
289 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
290 }
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000291 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000292 } else {
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000293 // Entry not describing executable data. Skip to end of line to set up
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000294 // reading the next entry.
295 do {
296 c = getc(fp);
297 } while ((c != EOF) && (c != '\n'));
298 if (c == EOF) break;
299 }
300 }
301 free(lib_name);
302 fclose(fp);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000303}
304
305
306void OS::SignalCodeMovingGC() {
307 // Nothing to do on Cygwin.
308}
309
310
311int OS::StackWalk(Vector<OS::StackFrame> frames) {
312 // Not supported on Cygwin.
313 return 0;
314}
315
316
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000317// The VirtualMemory implementation is taken from platform-win32.cc.
318// The mmap-based virtual memory implementation as it is used on most posix
319// platforms does not work well because Cygwin does not support MAP_FIXED.
320// This causes VirtualMemory::Commit to not always commit the memory region
321// specified.
322
323bool VirtualMemory::IsReserved() {
324 return address_ != NULL;
325}
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000326
327
328VirtualMemory::VirtualMemory(size_t size) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000329 address_ = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000330 size_ = size;
331}
332
333
334VirtualMemory::~VirtualMemory() {
335 if (IsReserved()) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000336 if (0 == VirtualFree(address(), 0, MEM_RELEASE)) address_ = NULL;
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000337 }
338}
339
340
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000341bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000342 int prot = is_executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
343 if (NULL == VirtualAlloc(address, size, MEM_COMMIT, prot)) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000344 return false;
345 }
346
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000347 UpdateAllocatedSpaceLimits(address, static_cast<int>(size));
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000348 return true;
349}
350
351
352bool VirtualMemory::Uncommit(void* address, size_t size) {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000353 ASSERT(IsReserved());
354 return VirtualFree(address, size, MEM_DECOMMIT) != false;
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000355}
356
357
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000358class Thread::PlatformData : public Malloced {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000359 public:
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000360 PlatformData() : thread_(kNoThread) {}
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000361 pthread_t thread_; // Thread handle for pthread.
362};
363
364
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000365
366
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000367Thread::Thread(const Options& options)
jkummerow@chromium.orgf7a58842012-02-21 10:08:21 +0000368 : data_(new PlatformData()),
369 stack_size_(options.stack_size()) {
370 set_name(options.name());
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000371}
372
373
374Thread::~Thread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000375 delete data_;
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000376}
377
378
379static void* ThreadEntry(void* arg) {
380 Thread* thread = reinterpret_cast<Thread*>(arg);
381 // This is also initialized by the first argument to pthread_create() but we
382 // don't know which thread will run first (the original thread or the new
383 // one) so we initialize it here too.
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000384 thread->data()->thread_ = pthread_self();
385 ASSERT(thread->data()->thread_ != kNoThread);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000386 thread->Run();
387 return NULL;
388}
389
390
391void Thread::set_name(const char* name) {
392 strncpy(name_, name, sizeof(name_));
393 name_[sizeof(name_) - 1] = '\0';
394}
395
396
397void Thread::Start() {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000398 pthread_attr_t* attr_ptr = NULL;
399 pthread_attr_t attr;
400 if (stack_size_ > 0) {
401 pthread_attr_init(&attr);
402 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
403 attr_ptr = &attr;
404 }
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000405 pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
406 ASSERT(data_->thread_ != kNoThread);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000407}
408
409
410void Thread::Join() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000411 pthread_join(data_->thread_, NULL);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000412}
413
414
415static inline Thread::LocalStorageKey PthreadKeyToLocalKey(
416 pthread_key_t pthread_key) {
417 // We need to cast pthread_key_t to Thread::LocalStorageKey in two steps
418 // because pthread_key_t is a pointer type on Cygwin. This will probably not
419 // work on 64-bit platforms, but Cygwin doesn't support 64-bit anyway.
420 STATIC_ASSERT(sizeof(Thread::LocalStorageKey) == sizeof(pthread_key_t));
421 intptr_t ptr_key = reinterpret_cast<intptr_t>(pthread_key);
422 return static_cast<Thread::LocalStorageKey>(ptr_key);
423}
424
425
426static inline pthread_key_t LocalKeyToPthreadKey(
427 Thread::LocalStorageKey local_key) {
428 STATIC_ASSERT(sizeof(Thread::LocalStorageKey) == sizeof(pthread_key_t));
429 intptr_t ptr_key = static_cast<intptr_t>(local_key);
430 return reinterpret_cast<pthread_key_t>(ptr_key);
431}
432
433
434Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
435 pthread_key_t key;
436 int result = pthread_key_create(&key, NULL);
437 USE(result);
438 ASSERT(result == 0);
439 return PthreadKeyToLocalKey(key);
440}
441
442
443void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
444 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
445 int result = pthread_key_delete(pthread_key);
446 USE(result);
447 ASSERT(result == 0);
448}
449
450
451void* Thread::GetThreadLocal(LocalStorageKey key) {
452 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
453 return pthread_getspecific(pthread_key);
454}
455
456
457void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
458 pthread_key_t pthread_key = LocalKeyToPthreadKey(key);
459 pthread_setspecific(pthread_key, value);
460}
461
462
463void Thread::YieldCPU() {
464 sched_yield();
465}
466
467
468class CygwinMutex : public Mutex {
469 public:
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000470 CygwinMutex() {
471 pthread_mutexattr_t attrs;
472 memset(&attrs, 0, sizeof(attrs));
473
474 int result = pthread_mutexattr_init(&attrs);
475 ASSERT(result == 0);
476 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
477 ASSERT(result == 0);
478 result = pthread_mutex_init(&mutex_, &attrs);
479 ASSERT(result == 0);
480 }
481
482 virtual ~CygwinMutex() { pthread_mutex_destroy(&mutex_); }
483
484 virtual int Lock() {
485 int result = pthread_mutex_lock(&mutex_);
486 return result;
487 }
488
489 virtual int Unlock() {
490 int result = pthread_mutex_unlock(&mutex_);
491 return result;
492 }
493
494 virtual bool TryLock() {
495 int result = pthread_mutex_trylock(&mutex_);
496 // Return false if the lock is busy and locking failed.
497 if (result == EBUSY) {
498 return false;
499 }
500 ASSERT(result == 0); // Verify no other errors.
501 return true;
502 }
503
504 private:
505 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
506};
507
508
509Mutex* OS::CreateMutex() {
510 return new CygwinMutex();
511}
512
513
514class CygwinSemaphore : public Semaphore {
515 public:
516 explicit CygwinSemaphore(int count) { sem_init(&sem_, 0, count); }
517 virtual ~CygwinSemaphore() { sem_destroy(&sem_); }
518
519 virtual void Wait();
520 virtual bool Wait(int timeout);
521 virtual void Signal() { sem_post(&sem_); }
522 private:
523 sem_t sem_;
524};
525
526
527void CygwinSemaphore::Wait() {
528 while (true) {
529 int result = sem_wait(&sem_);
530 if (result == 0) return; // Successfully got semaphore.
531 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
532 }
533}
534
535
536#ifndef TIMEVAL_TO_TIMESPEC
537#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
538 (ts)->tv_sec = (tv)->tv_sec; \
539 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
540} while (false)
541#endif
542
543
544bool CygwinSemaphore::Wait(int timeout) {
545 const long kOneSecondMicros = 1000000; // NOLINT
546
547 // Split timeout into second and nanosecond parts.
548 struct timeval delta;
549 delta.tv_usec = timeout % kOneSecondMicros;
550 delta.tv_sec = timeout / kOneSecondMicros;
551
552 struct timeval current_time;
553 // Get the current time.
554 if (gettimeofday(&current_time, NULL) == -1) {
555 return false;
556 }
557
558 // Calculate time for end of timeout.
559 struct timeval end_time;
560 timeradd(&current_time, &delta, &end_time);
561
562 struct timespec ts;
563 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
564 // Wait for semaphore signalled or timeout.
565 while (true) {
566 int result = sem_timedwait(&sem_, &ts);
567 if (result == 0) return true; // Successfully got semaphore.
568 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
569 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
570 }
571}
572
573
574Semaphore* OS::CreateSemaphore(int count) {
575 return new CygwinSemaphore(count);
576}
577
578
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000579// ----------------------------------------------------------------------------
580// Cygwin profiler support.
581//
582// On Cygwin we use the same sampler implementation as on win32.
583
584class Sampler::PlatformData : public Malloced {
585 public:
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000586 // Get a handle to the calling thread. This is the thread that we are
587 // going to profile. We need to make a copy of the handle because we are
588 // going to use it in the sampler thread. Using GetThreadHandle() will
589 // not work in this case. We're using OpenThread because DuplicateHandle
590 // for some reason doesn't work in Chrome's sandbox.
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000591 PlatformData() : profiled_thread_(OpenThread(THREAD_GET_CONTEXT |
592 THREAD_SUSPEND_RESUME |
593 THREAD_QUERY_INFORMATION,
594 false,
595 GetCurrentThreadId())) {}
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000596
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000597 ~PlatformData() {
598 if (profiled_thread_ != NULL) {
599 CloseHandle(profiled_thread_);
600 profiled_thread_ = NULL;
601 }
602 }
603
604 HANDLE profiled_thread() { return profiled_thread_; }
605
606 private:
607 HANDLE profiled_thread_;
608};
609
610
611class SamplerThread : public Thread {
612 public:
jkummerow@chromium.orgf7a58842012-02-21 10:08:21 +0000613 static const int kSamplerThreadStackSize = 64 * KB;
614
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000615 explicit SamplerThread(int interval)
jkummerow@chromium.orgf7a58842012-02-21 10:08:21 +0000616 : Thread(Thread::Options("SamplerThread", kSamplerThreadStackSize)),
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000617 interval_(interval) {}
618
619 static void AddActiveSampler(Sampler* sampler) {
620 ScopedLock lock(mutex_);
621 SamplerRegistry::AddActiveSampler(sampler);
622 if (instance_ == NULL) {
623 instance_ = new SamplerThread(sampler->interval());
624 instance_->Start();
625 } else {
626 ASSERT(instance_->interval_ == sampler->interval());
627 }
628 }
629
630 static void RemoveActiveSampler(Sampler* sampler) {
631 ScopedLock lock(mutex_);
632 SamplerRegistry::RemoveActiveSampler(sampler);
633 if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +0000634 RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000635 delete instance_;
636 instance_ = NULL;
637 }
638 }
639
640 // Implement Thread::Run().
641 virtual void Run() {
642 SamplerRegistry::State state;
643 while ((state = SamplerRegistry::GetState()) !=
644 SamplerRegistry::HAS_NO_SAMPLERS) {
645 bool cpu_profiling_enabled =
646 (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
647 bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
648 // When CPU profiling is enabled both JavaScript and C++ code is
649 // profiled. We must not suspend.
650 if (!cpu_profiling_enabled) {
651 if (rate_limiter_.SuspendIfNecessary()) continue;
652 }
653 if (cpu_profiling_enabled) {
654 if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
655 return;
656 }
657 }
658 if (runtime_profiler_enabled) {
659 if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
660 return;
661 }
662 }
663 OS::Sleep(interval_);
664 }
665 }
666
667 static void DoCpuProfile(Sampler* sampler, void* raw_sampler_thread) {
668 if (!sampler->isolate()->IsInitialized()) return;
669 if (!sampler->IsProfiling()) return;
670 SamplerThread* sampler_thread =
671 reinterpret_cast<SamplerThread*>(raw_sampler_thread);
672 sampler_thread->SampleContext(sampler);
673 }
674
675 static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
676 if (!sampler->isolate()->IsInitialized()) return;
677 sampler->isolate()->runtime_profiler()->NotifyTick();
678 }
679
680 void SampleContext(Sampler* sampler) {
681 HANDLE profiled_thread = sampler->platform_data()->profiled_thread();
682 if (profiled_thread == NULL) return;
683
684 // Context used for sampling the register state of the profiled thread.
685 CONTEXT context;
686 memset(&context, 0, sizeof(context));
687
688 TickSample sample_obj;
689 TickSample* sample = CpuProfiler::TickSampleEvent(sampler->isolate());
690 if (sample == NULL) sample = &sample_obj;
691
692 static const DWORD kSuspendFailed = static_cast<DWORD>(-1);
693 if (SuspendThread(profiled_thread) == kSuspendFailed) return;
694 sample->state = sampler->isolate()->current_vm_state();
695
696 context.ContextFlags = CONTEXT_FULL;
697 if (GetThreadContext(profiled_thread, &context) != 0) {
698#if V8_HOST_ARCH_X64
699 sample->pc = reinterpret_cast<Address>(context.Rip);
700 sample->sp = reinterpret_cast<Address>(context.Rsp);
701 sample->fp = reinterpret_cast<Address>(context.Rbp);
702#else
703 sample->pc = reinterpret_cast<Address>(context.Eip);
704 sample->sp = reinterpret_cast<Address>(context.Esp);
705 sample->fp = reinterpret_cast<Address>(context.Ebp);
706#endif
707 sampler->SampleStack(sample);
708 sampler->Tick(sample);
709 }
710 ResumeThread(profiled_thread);
711 }
712
713 const int interval_;
714 RuntimeProfilerRateLimiter rate_limiter_;
715
716 // Protects the process wide state below.
717 static Mutex* mutex_;
718 static SamplerThread* instance_;
719
jkummerow@chromium.org05ed9dd2012-01-23 14:42:48 +0000720 private:
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000721 DISALLOW_COPY_AND_ASSIGN(SamplerThread);
722};
723
724
725Mutex* SamplerThread::mutex_ = OS::CreateMutex();
726SamplerThread* SamplerThread::instance_ = NULL;
727
728
729Sampler::Sampler(Isolate* isolate, int interval)
730 : isolate_(isolate),
731 interval_(interval),
732 profiling_(false),
733 active_(false),
734 samples_taken_(0) {
735 data_ = new PlatformData;
736}
737
738
739Sampler::~Sampler() {
740 ASSERT(!IsActive());
741 delete data_;
742}
743
744
745void Sampler::Start() {
746 ASSERT(!IsActive());
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000747 SetActive(true);
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000748 SamplerThread::AddActiveSampler(this);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000749}
750
751
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000752void Sampler::Stop() {
kmillikin@chromium.orgc36ce6e2011-04-04 08:25:31 +0000753 ASSERT(IsActive());
754 SamplerThread::RemoveActiveSampler(this);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000755 SetActive(false);
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000756}
757
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000758
759} } // namespace v8::internal