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