blob: c18049fec70c3552549a516de7ad12b35c568ab5 [file] [log] [blame]
ager@chromium.orga74f0da2008-12-03 16:05:52 +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
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000028// Platform specific code for FreeBSD goes here. For the POSIX comaptible parts
29// the implementation is in platform-posix.cc.
ager@chromium.orga74f0da2008-12-03 16:05:52 +000030
31#include <pthread.h>
32#include <semaphore.h>
33#include <signal.h>
34#include <sys/time.h>
35#include <sys/resource.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000036#include <sys/types.h>
ager@chromium.orga74f0da2008-12-03 16:05:52 +000037#include <sys/ucontext.h>
38#include <stdlib.h>
39
40#include <sys/types.h> // mmap & munmap
41#include <sys/mman.h> // mmap & munmap
42#include <sys/stat.h> // open
43#include <sys/fcntl.h> // open
44#include <unistd.h> // getpagesize
45#include <execinfo.h> // backtrace, backtrace_symbols
46#include <strings.h> // index
47#include <errno.h>
48#include <stdarg.h>
49#include <limits.h>
50
51#undef MAP_TYPE
52
53#include "v8.h"
54
55#include "platform.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000056#include "vm-state-inl.h"
ager@chromium.orga74f0da2008-12-03 16:05:52 +000057
58
kasperl@chromium.org71affb52009-05-26 05:44:31 +000059namespace v8 {
60namespace internal {
ager@chromium.orga74f0da2008-12-03 16:05:52 +000061
62// 0 is never a valid thread id on FreeBSD since tids and pids share a
63// name space and pid 0 is used to kill the group (see man 2 kill).
64static const pthread_t kNoThread = (pthread_t) 0;
65
66
67double ceiling(double x) {
68 // Correct as on OS X
69 if (-1.0 < x && x < 0.0) {
70 return -0.0;
71 } else {
72 return ceil(x);
73 }
74}
75
76
77void OS::Setup() {
78 // Seed the random number generator.
79 // Convert the current time to a 64-bit integer first, before converting it
80 // to an unsigned. Going directly can cause an overflow and the seed to be
81 // set to all ones. The seed will be identical for different instances that
82 // call this setup code within the same millisecond.
83 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
84 srandom(static_cast<unsigned int>(seed));
85}
86
87
ricow@chromium.org30ce4112010-05-31 10:38:25 +000088void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
89 __asm__ __volatile__("" : : : "memory");
90 *ptr = value;
91}
92
93
ager@chromium.orgc4c92722009-11-18 14:12:51 +000094uint64_t OS::CpuFeaturesImpliedByPlatform() {
95 return 0; // FreeBSD runs on anything.
96}
97
98
ager@chromium.orga74f0da2008-12-03 16:05:52 +000099int OS::ActivationFrameAlignment() {
100 // 16 byte alignment on FreeBSD
101 return 16;
102}
103
104
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000105const char* OS::LocalTimezone(double time) {
106 if (isnan(time)) return "";
107 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
108 struct tm* t = localtime(&tv);
109 if (NULL == t) return "";
110 return t->tm_zone;
111}
112
113
114double OS::LocalTimeOffset() {
115 time_t tv = time(NULL);
116 struct tm* t = localtime(&tv);
117 // tm_gmtoff includes any daylight savings offset, so subtract it.
118 return static_cast<double>(t->tm_gmtoff * msPerSecond -
119 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
120}
121
122
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000123// We keep the lowest and highest addresses mapped as a quick way of
124// determining that pointers are outside the heap (used mostly in assertions
125// and verification). The estimate is conservative, ie, not all addresses in
126// 'allocated' space are actually allocated to our heap. The range is
127// [lowest, highest), inclusive on the low and and exclusive on the high end.
128static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
129static void* highest_ever_allocated = reinterpret_cast<void*>(0);
130
131
132static void UpdateAllocatedSpaceLimits(void* address, int size) {
133 lowest_ever_allocated = Min(lowest_ever_allocated, address);
134 highest_ever_allocated =
135 Max(highest_ever_allocated,
136 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
137}
138
139
140bool OS::IsOutsideAllocatedSpace(void* address) {
141 return address < lowest_ever_allocated || address >= highest_ever_allocated;
142}
143
144
145size_t OS::AllocateAlignment() {
146 return getpagesize();
147}
148
149
150void* OS::Allocate(const size_t requested,
151 size_t* allocated,
152 bool executable) {
153 const size_t msize = RoundUp(requested, getpagesize());
154 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
155 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
156
157 if (mbase == MAP_FAILED) {
158 LOG(StringEvent("OS::Allocate", "mmap failed"));
159 return NULL;
160 }
161 *allocated = msize;
162 UpdateAllocatedSpaceLimits(mbase, msize);
163 return mbase;
164}
165
166
167void OS::Free(void* buf, const size_t length) {
168 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000169 int result = munmap(buf, length);
170 USE(result);
171 ASSERT(result == 0);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000172}
173
174
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000175#ifdef ENABLE_HEAP_PROTECTION
176
177void OS::Protect(void* address, size_t size) {
178 UNIMPLEMENTED();
179}
180
181
182void OS::Unprotect(void* address, size_t size, bool is_executable) {
183 UNIMPLEMENTED();
184}
185
186#endif
187
188
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000189void OS::Sleep(int milliseconds) {
190 unsigned int ms = static_cast<unsigned int>(milliseconds);
191 usleep(1000 * ms);
192}
193
194
195void OS::Abort() {
196 // Redirect to std abort to signal abnormal program termination.
197 abort();
198}
199
200
201void OS::DebugBreak() {
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000202#if (defined(__arm__) || defined(__thumb__))
203# if defined(CAN_USE_ARMV5_INSTRUCTIONS)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000204 asm("bkpt 0");
ricow@chromium.org0b9f8502010-08-18 07:45:01 +0000205# endif
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000206#else
207 asm("int $3");
208#endif
209}
210
211
212class PosixMemoryMappedFile : public OS::MemoryMappedFile {
213 public:
214 PosixMemoryMappedFile(FILE* file, void* memory, int size)
215 : file_(file), memory_(memory), size_(size) { }
216 virtual ~PosixMemoryMappedFile();
217 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000218 virtual int size() { return size_; }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000219 private:
220 FILE* file_;
221 void* memory_;
222 int size_;
223};
224
225
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000226OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
227 FILE* file = fopen(name, "w+");
228 if (file == NULL) return NULL;
229
230 fseek(file, 0, SEEK_END);
231 int size = ftell(file);
232
233 void* memory =
234 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
235 return new PosixMemoryMappedFile(file, memory, size);
236}
237
238
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000239OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
240 void* initial) {
241 FILE* file = fopen(name, "w+");
242 if (file == NULL) return NULL;
243 int result = fwrite(initial, size, 1, file);
244 if (result < 1) {
245 fclose(file);
246 return NULL;
247 }
248 void* memory =
249 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
250 return new PosixMemoryMappedFile(file, memory, size);
251}
252
253
254PosixMemoryMappedFile::~PosixMemoryMappedFile() {
255 if (memory_) munmap(memory_, size_);
256 fclose(file_);
257}
258
259
260#ifdef ENABLE_LOGGING_AND_PROFILING
261static unsigned StringToLong(char* buffer) {
262 return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
263}
264#endif
265
266
267void OS::LogSharedLibraryAddresses() {
268#ifdef ENABLE_LOGGING_AND_PROFILING
269 static const int MAP_LENGTH = 1024;
270 int fd = open("/proc/self/maps", O_RDONLY);
271 if (fd < 0) return;
272 while (true) {
273 char addr_buffer[11];
274 addr_buffer[0] = '0';
275 addr_buffer[1] = 'x';
276 addr_buffer[10] = 0;
277 int result = read(fd, addr_buffer + 2, 8);
278 if (result < 8) break;
279 unsigned start = StringToLong(addr_buffer);
280 result = read(fd, addr_buffer + 2, 1);
281 if (result < 1) break;
282 if (addr_buffer[2] != '-') break;
283 result = read(fd, addr_buffer + 2, 8);
284 if (result < 8) break;
285 unsigned end = StringToLong(addr_buffer);
286 char buffer[MAP_LENGTH];
287 int bytes_read = -1;
288 do {
289 bytes_read++;
290 if (bytes_read >= MAP_LENGTH - 1)
291 break;
292 result = read(fd, buffer + bytes_read, 1);
293 if (result < 1) break;
294 } while (buffer[bytes_read] != '\n');
295 buffer[bytes_read] = 0;
296 // Ignore mappings that are not executable.
297 if (buffer[3] != 'x') continue;
298 char* start_of_path = index(buffer, '/');
299 // There may be no filename in this line. Skip to next.
300 if (start_of_path == NULL) continue;
301 buffer[bytes_read] = 0;
302 LOG(SharedLibraryEvent(start_of_path, start, end));
303 }
304 close(fd);
305#endif
306}
307
308
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000309void OS::SignalCodeMovingGC() {
310}
311
312
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000313int OS::StackWalk(Vector<OS::StackFrame> frames) {
314 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000315 ScopedVector<void*> addresses(frames_size);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000316
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000317 int frames_count = backtrace(addresses.start(), frames_size);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000318
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000319 char** symbols = backtrace_symbols(addresses.start(), frames_count);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000320 if (symbols == NULL) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000321 return kStackWalkError;
322 }
323
324 for (int i = 0; i < frames_count; i++) {
325 frames[i].address = addresses[i];
326 // Format a text representation of the frame based on the information
327 // available.
328 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
329 "%s",
330 symbols[i]);
331 // Make sure line termination is in place.
332 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
333 }
334
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000335 free(symbols);
336
337 return frames_count;
338}
339
340
341// Constants used for mmap.
342static const int kMmapFd = -1;
343static const int kMmapFdOffset = 0;
344
345
346VirtualMemory::VirtualMemory(size_t size) {
347 address_ = mmap(NULL, size, PROT_NONE,
348 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
349 kMmapFd, kMmapFdOffset);
350 size_ = size;
351}
352
353
354VirtualMemory::~VirtualMemory() {
355 if (IsReserved()) {
356 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
357 }
358}
359
360
361bool VirtualMemory::IsReserved() {
362 return address_ != MAP_FAILED;
363}
364
365
366bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
367 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
368 if (MAP_FAILED == mmap(address, size, prot,
369 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
370 kMmapFd, kMmapFdOffset)) {
371 return false;
372 }
373
374 UpdateAllocatedSpaceLimits(address, size);
375 return true;
376}
377
378
379bool VirtualMemory::Uncommit(void* address, size_t size) {
380 return mmap(address, size, PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000381 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000382 kMmapFd, kMmapFdOffset) != MAP_FAILED;
383}
384
385
386class ThreadHandle::PlatformData : public Malloced {
387 public:
388 explicit PlatformData(ThreadHandle::Kind kind) {
389 Initialize(kind);
390 }
391
392 void Initialize(ThreadHandle::Kind kind) {
393 switch (kind) {
394 case ThreadHandle::SELF: thread_ = pthread_self(); break;
395 case ThreadHandle::INVALID: thread_ = kNoThread; break;
396 }
397 }
398 pthread_t thread_; // Thread handle for pthread.
399};
400
401
402ThreadHandle::ThreadHandle(Kind kind) {
403 data_ = new PlatformData(kind);
404}
405
406
407void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
408 data_->Initialize(kind);
409}
410
411
412ThreadHandle::~ThreadHandle() {
413 delete data_;
414}
415
416
417bool ThreadHandle::IsSelf() const {
418 return pthread_equal(data_->thread_, pthread_self());
419}
420
421
422bool ThreadHandle::IsValid() const {
423 return data_->thread_ != kNoThread;
424}
425
426
427Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000428 set_name("v8:<unknown>");
429}
430
431
432Thread::Thread(const char* name) : ThreadHandle(ThreadHandle::INVALID) {
ager@chromium.org0ee099b2011-01-25 14:06:47 +0000433 set_name(name);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000434}
435
436
437Thread::~Thread() {
438}
439
440
441static void* ThreadEntry(void* arg) {
442 Thread* thread = reinterpret_cast<Thread*>(arg);
443 // This is also initialized by the first argument to pthread_create() but we
444 // don't know which thread will run first (the original thread or the new
445 // one) so we initialize it here too.
446 thread->thread_handle_data()->thread_ = pthread_self();
447 ASSERT(thread->IsValid());
448 thread->Run();
449 return NULL;
450}
451
452
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000453void Thread::set_name(const char* name) {
454 strncpy(name_, name, sizeof(name_));
455 name_[sizeof(name_) - 1] = '\0';
456}
457
458
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000459void Thread::Start() {
460 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
461 ASSERT(IsValid());
462}
463
464
465void Thread::Join() {
466 pthread_join(thread_handle_data()->thread_, NULL);
467}
468
469
470Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
471 pthread_key_t key;
472 int result = pthread_key_create(&key, NULL);
473 USE(result);
474 ASSERT(result == 0);
475 return static_cast<LocalStorageKey>(key);
476}
477
478
479void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
480 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
481 int result = pthread_key_delete(pthread_key);
482 USE(result);
483 ASSERT(result == 0);
484}
485
486
487void* Thread::GetThreadLocal(LocalStorageKey key) {
488 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
489 return pthread_getspecific(pthread_key);
490}
491
492
493void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
494 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
495 pthread_setspecific(pthread_key, value);
496}
497
498
499void Thread::YieldCPU() {
500 sched_yield();
501}
502
503
504class FreeBSDMutex : public Mutex {
505 public:
506
507 FreeBSDMutex() {
508 pthread_mutexattr_t attrs;
509 int result = pthread_mutexattr_init(&attrs);
510 ASSERT(result == 0);
511 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
512 ASSERT(result == 0);
513 result = pthread_mutex_init(&mutex_, &attrs);
514 ASSERT(result == 0);
515 }
516
517 virtual ~FreeBSDMutex() { pthread_mutex_destroy(&mutex_); }
518
519 virtual int Lock() {
520 int result = pthread_mutex_lock(&mutex_);
521 return result;
522 }
523
524 virtual int Unlock() {
525 int result = pthread_mutex_unlock(&mutex_);
526 return result;
527 }
528
529 private:
530 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
531};
532
533
534Mutex* OS::CreateMutex() {
535 return new FreeBSDMutex();
536}
537
538
539class FreeBSDSemaphore : public Semaphore {
540 public:
541 explicit FreeBSDSemaphore(int count) { sem_init(&sem_, 0, count); }
542 virtual ~FreeBSDSemaphore() { sem_destroy(&sem_); }
543
544 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000545 virtual bool Wait(int timeout);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000546 virtual void Signal() { sem_post(&sem_); }
547 private:
548 sem_t sem_;
549};
550
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000551
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000552void FreeBSDSemaphore::Wait() {
553 while (true) {
554 int result = sem_wait(&sem_);
555 if (result == 0) return; // Successfully got semaphore.
556 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
557 }
558}
559
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000560
561bool FreeBSDSemaphore::Wait(int timeout) {
562 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000563
564 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000565 struct timeval delta;
566 delta.tv_usec = timeout % kOneSecondMicros;
567 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000568
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000569 struct timeval current_time;
570 // Get the current time.
571 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000572 return false;
573 }
574
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000575 // Calculate time for end of timeout.
576 struct timeval end_time;
577 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000578
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000579 struct timespec ts;
580 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000581 while (true) {
582 int result = sem_timedwait(&sem_, &ts);
583 if (result == 0) return true; // Successfully got semaphore.
584 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
585 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
586 }
587}
588
589
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000590Semaphore* OS::CreateSemaphore(int count) {
591 return new FreeBSDSemaphore(count);
592}
593
ager@chromium.org381abbb2009-02-25 13:23:22 +0000594
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000595#ifdef ENABLE_LOGGING_AND_PROFILING
596
597static Sampler* active_sampler_ = NULL;
598
599static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
600 USE(info);
601 if (signal != SIGPROF) return;
602 if (active_sampler_ == NULL) return;
603
604 TickSample sample;
605
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000606 // We always sample the VM state.
ager@chromium.org357bf652010-04-12 11:30:10 +0000607 sample.state = VMState::current_state();
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000608
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000609 // If profiling, we extract the current pc and sp.
610 if (active_sampler_->IsProfiling()) {
611 // Extracting the sample from the context is extremely machine dependent.
612 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
613 mcontext_t& mcontext = ucontext->uc_mcontext;
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +0000614#if V8_HOST_ARCH_IA32
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000615 sample.pc = reinterpret_cast<Address>(mcontext.mc_eip);
616 sample.sp = reinterpret_cast<Address>(mcontext.mc_esp);
617 sample.fp = reinterpret_cast<Address>(mcontext.mc_ebp);
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +0000618#elif V8_HOST_ARCH_X64
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000619 sample.pc = reinterpret_cast<Address>(mcontext.mc_rip);
620 sample.sp = reinterpret_cast<Address>(mcontext.mc_rsp);
621 sample.fp = reinterpret_cast<Address>(mcontext.mc_rbp);
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +0000622#elif V8_HOST_ARCH_ARM
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000623 sample.pc = reinterpret_cast<Address>(mcontext.mc_r15);
624 sample.sp = reinterpret_cast<Address>(mcontext.mc_r13);
625 sample.fp = reinterpret_cast<Address>(mcontext.mc_r11);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000626#endif
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000627 active_sampler_->SampleStack(&sample);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000628 }
629
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000630 active_sampler_->Tick(&sample);
631}
632
633
634class Sampler::PlatformData : public Malloced {
635 public:
636 PlatformData() {
637 signal_handler_installed_ = false;
638 }
639
640 bool signal_handler_installed_;
641 struct sigaction old_signal_handler_;
642 struct itimerval old_timer_value_;
643};
644
645
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000646Sampler::Sampler(int interval)
lrn@chromium.org303ada72010-10-27 09:33:13 +0000647 : interval_(interval),
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000648 profiling_(false),
ager@chromium.orgbeb25712010-11-29 08:02:25 +0000649 active_(false),
650 samples_taken_(0) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000651 data_ = new PlatformData();
652}
653
654
655Sampler::~Sampler() {
656 delete data_;
657}
658
659
660void Sampler::Start() {
661 // There can only be one active sampler at the time on POSIX
662 // platforms.
663 if (active_sampler_ != NULL) return;
664
665 // Request profiling signals.
666 struct sigaction sa;
667 sa.sa_sigaction = ProfilerSignalHandler;
668 sigemptyset(&sa.sa_mask);
669 sa.sa_flags = SA_SIGINFO;
670 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
671 data_->signal_handler_installed_ = true;
672
673 // Set the itimer to generate a tick for each interval.
674 itimerval itimer;
675 itimer.it_interval.tv_sec = interval_ / 1000;
676 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
677 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
678 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
679 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
680
681 // Set this sampler as the active sampler.
682 active_sampler_ = this;
683 active_ = true;
684}
685
686
687void Sampler::Stop() {
688 // Restore old signal handler
689 if (data_->signal_handler_installed_) {
690 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
691 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
692 data_->signal_handler_installed_ = false;
693 }
694
695 // This sampler is no longer the active sampler.
696 active_sampler_ = NULL;
697 active_ = false;
698}
699
700#endif // ENABLE_LOGGING_AND_PROFILING
701
702} } // namespace v8::internal