blob: ff5d83b6603d9b8d1597d504e884f23ef065a4d0 [file] [log] [blame]
Leon Clarked91b9f72010-01-27 17:25:45 +00001// Copyright 2006-2009 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 Solaris 10 goes here. For the POSIX comaptible
29// parts the implementation is in platform-posix.cc.
30
31#ifdef __sparc
32# error "V8 does not support the SPARC CPU architecture."
33#endif
34
35#include <sys/stack.h> // for stack alignment
36#include <unistd.h> // getpagesize(), usleep()
37#include <sys/mman.h> // mmap()
Leon Clarkef7060e22010-06-03 12:02:55 +010038#include <ucontext.h> // walkstack(), getcontext()
39#include <dlfcn.h> // dladdr
Leon Clarked91b9f72010-01-27 17:25:45 +000040#include <pthread.h>
41#include <sched.h> // for sched_yield
42#include <semaphore.h>
43#include <time.h>
44#include <sys/time.h> // gettimeofday(), timeradd()
45#include <errno.h>
46#include <ieeefp.h> // finite()
47#include <signal.h> // sigemptyset(), etc
48
49
50#undef MAP_TYPE
51
52#include "v8.h"
53
54#include "platform.h"
55
56
Leon Clarkef7060e22010-06-03 12:02:55 +010057// It seems there is a bug in some Solaris distributions (experienced in
58// SunOS 5.10 Generic_141445-09) which make it difficult or impossible to
59// access signbit() despite the availability of other C99 math functions.
60#ifndef signbit
61// Test sign - usually defined in math.h
62int signbit(double x) {
63 // We need to take care of the special case of both positive and negative
64 // versions of zero.
65 if (x == 0) {
66 return fpclass(x) & FP_NZERO;
67 } else {
68 // This won't detect negative NaN but that should be okay since we don't
69 // assume that behavior.
70 return x < 0;
71 }
72}
73#endif // signbit
74
Leon Clarked91b9f72010-01-27 17:25:45 +000075namespace v8 {
76namespace internal {
77
78
79// 0 is never a valid thread id on Solaris since the main thread is 1 and
80// subsequent have their ids incremented from there
81static const pthread_t kNoThread = (pthread_t) 0;
82
83
84double ceiling(double x) {
85 return ceil(x);
86}
87
88
89void OS::Setup() {
90 // Seed the random number generator.
91 // Convert the current time to a 64-bit integer first, before converting it
92 // to an unsigned. Going directly will cause an overflow and the seed to be
93 // set to all ones. The seed will be identical for different instances that
94 // call this setup code within the same millisecond.
95 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
96 srandom(static_cast<unsigned int>(seed));
97}
98
99
100uint64_t OS::CpuFeaturesImpliedByPlatform() {
101 return 0; // Solaris runs on a lot of things.
102}
103
104
105int OS::ActivationFrameAlignment() {
106 return STACK_ALIGN;
107}
108
109
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100110void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
111 __asm__ __volatile__("" : : : "memory");
112 *ptr = value;
113}
114
115
Leon Clarked91b9f72010-01-27 17:25:45 +0000116const char* OS::LocalTimezone(double time) {
117 if (isnan(time)) return "";
118 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
119 struct tm* t = localtime(&tv);
120 if (NULL == t) return "";
121 return tzname[0]; // The location of the timezone string on Solaris.
122}
123
124
125double OS::LocalTimeOffset() {
126 // On Solaris, struct tm does not contain a tm_gmtoff field.
127 time_t utc = time(NULL);
128 ASSERT(utc != -1);
129 struct tm* loc = localtime(&utc);
130 ASSERT(loc != NULL);
131 return static_cast<double>((mktime(loc) - utc) * msPerSecond);
132}
133
134
135// We keep the lowest and highest addresses mapped as a quick way of
136// determining that pointers are outside the heap (used mostly in assertions
137// and verification). The estimate is conservative, ie, not all addresses in
138// 'allocated' space are actually allocated to our heap. The range is
139// [lowest, highest), inclusive on the low and and exclusive on the high end.
140static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
141static void* highest_ever_allocated = reinterpret_cast<void*>(0);
142
143
144static void UpdateAllocatedSpaceLimits(void* address, int size) {
145 lowest_ever_allocated = Min(lowest_ever_allocated, address);
146 highest_ever_allocated =
147 Max(highest_ever_allocated,
148 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
149}
150
151
152bool OS::IsOutsideAllocatedSpace(void* address) {
153 return address < lowest_ever_allocated || address >= highest_ever_allocated;
154}
155
156
157size_t OS::AllocateAlignment() {
158 return static_cast<size_t>(getpagesize());
159}
160
161
162void* OS::Allocate(const size_t requested,
163 size_t* allocated,
164 bool is_executable) {
165 const size_t msize = RoundUp(requested, getpagesize());
166 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
167 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
168
169 if (mbase == MAP_FAILED) {
170 LOG(StringEvent("OS::Allocate", "mmap failed"));
171 return NULL;
172 }
173 *allocated = msize;
174 UpdateAllocatedSpaceLimits(mbase, msize);
175 return mbase;
176}
177
178
179void OS::Free(void* address, const size_t size) {
180 // TODO(1240712): munmap has a return value which is ignored here.
181 int result = munmap(address, size);
182 USE(result);
183 ASSERT(result == 0);
184}
185
186
187#ifdef ENABLE_HEAP_PROTECTION
188
189void OS::Protect(void* address, size_t size) {
190 // TODO(1240712): mprotect has a return value which is ignored here.
191 mprotect(address, size, PROT_READ);
192}
193
194
195void OS::Unprotect(void* address, size_t size, bool is_executable) {
196 // TODO(1240712): mprotect has a return value which is ignored here.
197 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
198 mprotect(address, size, prot);
199}
200
201#endif
202
203
204void OS::Sleep(int milliseconds) {
205 useconds_t ms = static_cast<useconds_t>(milliseconds);
206 usleep(1000 * ms);
207}
208
209
210void OS::Abort() {
211 // Redirect to std abort to signal abnormal program termination.
212 abort();
213}
214
215
216void OS::DebugBreak() {
217 asm("int $3");
218}
219
220
221class PosixMemoryMappedFile : public OS::MemoryMappedFile {
222 public:
223 PosixMemoryMappedFile(FILE* file, void* memory, int size)
224 : file_(file), memory_(memory), size_(size) { }
225 virtual ~PosixMemoryMappedFile();
226 virtual void* memory() { return memory_; }
227 private:
228 FILE* file_;
229 void* memory_;
230 int size_;
231};
232
233
234OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
235 void* initial) {
236 FILE* file = fopen(name, "w+");
237 if (file == NULL) return NULL;
238 int result = fwrite(initial, size, 1, file);
239 if (result < 1) {
240 fclose(file);
241 return NULL;
242 }
243 void* memory =
244 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
245 return new PosixMemoryMappedFile(file, memory, size);
246}
247
248
249PosixMemoryMappedFile::~PosixMemoryMappedFile() {
250 if (memory_) munmap(memory_, size_);
251 fclose(file_);
252}
253
254
255void OS::LogSharedLibraryAddresses() {
256}
257
258
Ben Murdochf87a2032010-10-22 12:50:53 +0100259void OS::SignalCodeMovingGC() {
260}
261
262
Leon Clarkef7060e22010-06-03 12:02:55 +0100263struct StackWalker {
264 Vector<OS::StackFrame>& frames;
265 int index;
266};
267
268
269static int StackWalkCallback(uintptr_t pc, int signo, void* data) {
270 struct StackWalker* walker = static_cast<struct StackWalker*>(data);
271 Dl_info info;
272
273 int i = walker->index;
274
275 walker->frames[i].address = reinterpret_cast<void*>(pc);
276
277 // Make sure line termination is in place.
278 walker->frames[i].text[OS::kStackWalkMaxTextLen - 1] = '\0';
279
280 Vector<char> text = MutableCStrVector(walker->frames[i].text,
281 OS::kStackWalkMaxTextLen);
282
283 if (dladdr(reinterpret_cast<void*>(pc), &info) == 0) {
284 OS::SNPrintF(text, "[0x%p]", pc);
285 } else if ((info.dli_fname != NULL && info.dli_sname != NULL)) {
286 // We have symbol info.
287 OS::SNPrintF(text, "%s'%s+0x%x", info.dli_fname, info.dli_sname, pc);
288 } else {
289 // No local symbol info.
290 OS::SNPrintF(text,
291 "%s'0x%p [0x%p]",
292 info.dli_fname,
293 pc - reinterpret_cast<uintptr_t>(info.dli_fbase),
294 pc);
295 }
296 walker->index++;
297 return 0;
298}
299
300
Leon Clarked91b9f72010-01-27 17:25:45 +0000301int OS::StackWalk(Vector<OS::StackFrame> frames) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100302 ucontext_t ctx;
303 struct StackWalker walker = { frames, 0 };
Leon Clarked91b9f72010-01-27 17:25:45 +0000304
Leon Clarkef7060e22010-06-03 12:02:55 +0100305 if (getcontext(&ctx) < 0) return kStackWalkError;
Leon Clarked91b9f72010-01-27 17:25:45 +0000306
Leon Clarkef7060e22010-06-03 12:02:55 +0100307 if (!walkcontext(&ctx, StackWalkCallback, &walker)) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000308 return kStackWalkError;
309 }
310
Leon Clarkef7060e22010-06-03 12:02:55 +0100311 return walker.index;
Leon Clarked91b9f72010-01-27 17:25:45 +0000312}
313
314
315// Constants used for mmap.
316static const int kMmapFd = -1;
317static const int kMmapFdOffset = 0;
318
319
320VirtualMemory::VirtualMemory(size_t size) {
321 address_ = mmap(NULL, size, PROT_NONE,
322 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
323 kMmapFd, kMmapFdOffset);
324 size_ = size;
325}
326
327
328VirtualMemory::~VirtualMemory() {
329 if (IsReserved()) {
330 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
331 }
332}
333
334
335bool VirtualMemory::IsReserved() {
336 return address_ != MAP_FAILED;
337}
338
339
340bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
341 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
342 if (MAP_FAILED == mmap(address, size, prot,
343 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
344 kMmapFd, kMmapFdOffset)) {
345 return false;
346 }
347
348 UpdateAllocatedSpaceLimits(address, size);
349 return true;
350}
351
352
353bool VirtualMemory::Uncommit(void* address, size_t size) {
354 return mmap(address, size, PROT_NONE,
355 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
356 kMmapFd, kMmapFdOffset) != MAP_FAILED;
357}
358
359
360class ThreadHandle::PlatformData : public Malloced {
361 public:
362 explicit PlatformData(ThreadHandle::Kind kind) {
363 Initialize(kind);
364 }
365
366 void Initialize(ThreadHandle::Kind kind) {
367 switch (kind) {
368 case ThreadHandle::SELF: thread_ = pthread_self(); break;
369 case ThreadHandle::INVALID: thread_ = kNoThread; break;
370 }
371 }
372
373 pthread_t thread_; // Thread handle for pthread.
374};
375
376
377ThreadHandle::ThreadHandle(Kind kind) {
378 data_ = new PlatformData(kind);
379}
380
381
382void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
383 data_->Initialize(kind);
384}
385
386
387ThreadHandle::~ThreadHandle() {
388 delete data_;
389}
390
391
392bool ThreadHandle::IsSelf() const {
393 return pthread_equal(data_->thread_, pthread_self());
394}
395
396
397bool ThreadHandle::IsValid() const {
398 return data_->thread_ != kNoThread;
399}
400
401
402Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
403}
404
405
406Thread::~Thread() {
407}
408
409
410static void* ThreadEntry(void* arg) {
411 Thread* thread = reinterpret_cast<Thread*>(arg);
412 // This is also initialized by the first argument to pthread_create() but we
413 // don't know which thread will run first (the original thread or the new
414 // one) so we initialize it here too.
415 thread->thread_handle_data()->thread_ = pthread_self();
416 ASSERT(thread->IsValid());
417 thread->Run();
418 return NULL;
419}
420
421
422void Thread::Start() {
423 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
424 ASSERT(IsValid());
425}
426
427
428void Thread::Join() {
429 pthread_join(thread_handle_data()->thread_, NULL);
430}
431
432
433Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
434 pthread_key_t key;
435 int result = pthread_key_create(&key, NULL);
436 USE(result);
437 ASSERT(result == 0);
438 return static_cast<LocalStorageKey>(key);
439}
440
441
442void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
443 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
444 int result = pthread_key_delete(pthread_key);
445 USE(result);
446 ASSERT(result == 0);
447}
448
449
450void* Thread::GetThreadLocal(LocalStorageKey key) {
451 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
452 return pthread_getspecific(pthread_key);
453}
454
455
456void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
457 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
458 pthread_setspecific(pthread_key, value);
459}
460
461
462void Thread::YieldCPU() {
463 sched_yield();
464}
465
466
467class SolarisMutex : public Mutex {
468 public:
469
470 SolarisMutex() {
471 pthread_mutexattr_t attr;
472 pthread_mutexattr_init(&attr);
473 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
474 pthread_mutex_init(&mutex_, &attr);
475 }
476
477 ~SolarisMutex() { pthread_mutex_destroy(&mutex_); }
478
479 int Lock() { return pthread_mutex_lock(&mutex_); }
480
481 int Unlock() { return pthread_mutex_unlock(&mutex_); }
482
483 private:
484 pthread_mutex_t mutex_;
485};
486
487
488Mutex* OS::CreateMutex() {
489 return new SolarisMutex();
490}
491
492
493class SolarisSemaphore : public Semaphore {
494 public:
495 explicit SolarisSemaphore(int count) { sem_init(&sem_, 0, count); }
496 virtual ~SolarisSemaphore() { sem_destroy(&sem_); }
497
498 virtual void Wait();
499 virtual bool Wait(int timeout);
500 virtual void Signal() { sem_post(&sem_); }
501 private:
502 sem_t sem_;
503};
504
505
506void SolarisSemaphore::Wait() {
507 while (true) {
508 int result = sem_wait(&sem_);
509 if (result == 0) return; // Successfully got semaphore.
510 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
511 }
512}
513
514
515#ifndef TIMEVAL_TO_TIMESPEC
516#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
517 (ts)->tv_sec = (tv)->tv_sec; \
518 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
519} while (false)
520#endif
521
522
523#ifndef timeradd
524#define timeradd(a, b, result) \
525 do { \
526 (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
527 (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
528 if ((result)->tv_usec >= 1000000) { \
529 ++(result)->tv_sec; \
530 (result)->tv_usec -= 1000000; \
531 } \
532 } while (0)
533#endif
534
535
536bool SolarisSemaphore::Wait(int timeout) {
537 const long kOneSecondMicros = 1000000; // NOLINT
538
539 // Split timeout into second and nanosecond parts.
540 struct timeval delta;
541 delta.tv_usec = timeout % kOneSecondMicros;
542 delta.tv_sec = timeout / kOneSecondMicros;
543
544 struct timeval current_time;
545 // Get the current time.
546 if (gettimeofday(&current_time, NULL) == -1) {
547 return false;
548 }
549
550 // Calculate time for end of timeout.
551 struct timeval end_time;
552 timeradd(&current_time, &delta, &end_time);
553
554 struct timespec ts;
555 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
556 // Wait for semaphore signalled or timeout.
557 while (true) {
558 int result = sem_timedwait(&sem_, &ts);
559 if (result == 0) return true; // Successfully got semaphore.
560 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
561 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
562 }
563}
564
565
566Semaphore* OS::CreateSemaphore(int count) {
567 return new SolarisSemaphore(count);
568}
569
570
571#ifdef ENABLE_LOGGING_AND_PROFILING
572
573static Sampler* active_sampler_ = NULL;
574
575static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
576 USE(info);
577 if (signal != SIGPROF) return;
578 if (active_sampler_ == NULL) return;
579
580 TickSample sample;
581 sample.pc = 0;
582 sample.sp = 0;
583 sample.fp = 0;
584
585 // We always sample the VM state.
Steve Block6ded16b2010-05-10 14:33:55 +0100586 sample.state = VMState::current_state();
Leon Clarked91b9f72010-01-27 17:25:45 +0000587
588 active_sampler_->Tick(&sample);
589}
590
591
592class Sampler::PlatformData : public Malloced {
593 public:
594 PlatformData() {
595 signal_handler_installed_ = false;
596 }
597
598 bool signal_handler_installed_;
599 struct sigaction old_signal_handler_;
600 struct itimerval old_timer_value_;
601};
602
603
604Sampler::Sampler(int interval, bool profiling)
Ben Murdochf87a2032010-10-22 12:50:53 +0100605 : interval_(interval),
606 profiling_(profiling),
607 synchronous_(profiling),
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800608 active_(false),
609 samples_taken_(0) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000610 data_ = new PlatformData();
611}
612
613
614Sampler::~Sampler() {
615 delete data_;
616}
617
618
619void Sampler::Start() {
620 // There can only be one active sampler at the time on POSIX
621 // platforms.
622 if (active_sampler_ != NULL) return;
623
624 // Request profiling signals.
625 struct sigaction sa;
626 sa.sa_sigaction = ProfilerSignalHandler;
627 sigemptyset(&sa.sa_mask);
628 sa.sa_flags = SA_SIGINFO;
629 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
630 data_->signal_handler_installed_ = true;
631
632 // Set the itimer to generate a tick for each interval.
633 itimerval itimer;
634 itimer.it_interval.tv_sec = interval_ / 1000;
635 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
636 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
637 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
638 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
639
640 // Set this sampler as the active sampler.
641 active_sampler_ = this;
642 active_ = true;
643}
644
645
646void Sampler::Stop() {
647 // Restore old signal handler
648 if (data_->signal_handler_installed_) {
649 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
650 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
651 data_->signal_handler_installed_ = false;
652 }
653
654 // This sampler is no longer the active sampler.
655 active_sampler_ = NULL;
656 active_ = false;
657}
658
659#endif // ENABLE_LOGGING_AND_PROFILING
660
661} } // namespace v8::internal