blob: 82208f1a3deac69142d0b489a957a187ff0572c7 [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"
56
57
58namespace v8 { namespace internal {
59
60// 0 is never a valid thread id on FreeBSD since tids and pids share a
61// name space and pid 0 is used to kill the group (see man 2 kill).
62static const pthread_t kNoThread = (pthread_t) 0;
63
64
65double ceiling(double x) {
66 // Correct as on OS X
67 if (-1.0 < x && x < 0.0) {
68 return -0.0;
69 } else {
70 return ceil(x);
71 }
72}
73
74
75void OS::Setup() {
76 // Seed the random number generator.
77 // Convert the current time to a 64-bit integer first, before converting it
78 // to an unsigned. Going directly can cause an overflow and the seed to be
79 // set to all ones. The seed will be identical for different instances that
80 // call this setup code within the same millisecond.
81 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
82 srandom(static_cast<unsigned int>(seed));
83}
84
85
ager@chromium.orga74f0da2008-12-03 16:05:52 +000086double OS::nan_value() {
87 return NAN;
88}
89
90
91int OS::ActivationFrameAlignment() {
92 // 16 byte alignment on FreeBSD
93 return 16;
94}
95
96
97// We keep the lowest and highest addresses mapped as a quick way of
98// determining that pointers are outside the heap (used mostly in assertions
99// and verification). The estimate is conservative, ie, not all addresses in
100// 'allocated' space are actually allocated to our heap. The range is
101// [lowest, highest), inclusive on the low and and exclusive on the high end.
102static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
103static void* highest_ever_allocated = reinterpret_cast<void*>(0);
104
105
106static void UpdateAllocatedSpaceLimits(void* address, int size) {
107 lowest_ever_allocated = Min(lowest_ever_allocated, address);
108 highest_ever_allocated =
109 Max(highest_ever_allocated,
110 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
111}
112
113
114bool OS::IsOutsideAllocatedSpace(void* address) {
115 return address < lowest_ever_allocated || address >= highest_ever_allocated;
116}
117
118
119size_t OS::AllocateAlignment() {
120 return getpagesize();
121}
122
123
124void* OS::Allocate(const size_t requested,
125 size_t* allocated,
126 bool executable) {
127 const size_t msize = RoundUp(requested, getpagesize());
128 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
129 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
130
131 if (mbase == MAP_FAILED) {
132 LOG(StringEvent("OS::Allocate", "mmap failed"));
133 return NULL;
134 }
135 *allocated = msize;
136 UpdateAllocatedSpaceLimits(mbase, msize);
137 return mbase;
138}
139
140
141void OS::Free(void* buf, const size_t length) {
142 // TODO(1240712): munmap has a return value which is ignored here.
143 munmap(buf, length);
144}
145
146
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000147#ifdef ENABLE_HEAP_PROTECTION
148
149void OS::Protect(void* address, size_t size) {
150 UNIMPLEMENTED();
151}
152
153
154void OS::Unprotect(void* address, size_t size, bool is_executable) {
155 UNIMPLEMENTED();
156}
157
158#endif
159
160
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000161void OS::Sleep(int milliseconds) {
162 unsigned int ms = static_cast<unsigned int>(milliseconds);
163 usleep(1000 * ms);
164}
165
166
167void OS::Abort() {
168 // Redirect to std abort to signal abnormal program termination.
169 abort();
170}
171
172
173void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000174#if defined(__arm__) || defined(__thumb__)
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000175 asm("bkpt 0");
176#else
177 asm("int $3");
178#endif
179}
180
181
182class PosixMemoryMappedFile : public OS::MemoryMappedFile {
183 public:
184 PosixMemoryMappedFile(FILE* file, void* memory, int size)
185 : file_(file), memory_(memory), size_(size) { }
186 virtual ~PosixMemoryMappedFile();
187 virtual void* memory() { return memory_; }
188 private:
189 FILE* file_;
190 void* memory_;
191 int size_;
192};
193
194
195OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
196 void* initial) {
197 FILE* file = fopen(name, "w+");
198 if (file == NULL) return NULL;
199 int result = fwrite(initial, size, 1, file);
200 if (result < 1) {
201 fclose(file);
202 return NULL;
203 }
204 void* memory =
205 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
206 return new PosixMemoryMappedFile(file, memory, size);
207}
208
209
210PosixMemoryMappedFile::~PosixMemoryMappedFile() {
211 if (memory_) munmap(memory_, size_);
212 fclose(file_);
213}
214
215
216#ifdef ENABLE_LOGGING_AND_PROFILING
217static unsigned StringToLong(char* buffer) {
218 return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
219}
220#endif
221
222
223void OS::LogSharedLibraryAddresses() {
224#ifdef ENABLE_LOGGING_AND_PROFILING
225 static const int MAP_LENGTH = 1024;
226 int fd = open("/proc/self/maps", O_RDONLY);
227 if (fd < 0) return;
228 while (true) {
229 char addr_buffer[11];
230 addr_buffer[0] = '0';
231 addr_buffer[1] = 'x';
232 addr_buffer[10] = 0;
233 int result = read(fd, addr_buffer + 2, 8);
234 if (result < 8) break;
235 unsigned start = StringToLong(addr_buffer);
236 result = read(fd, addr_buffer + 2, 1);
237 if (result < 1) break;
238 if (addr_buffer[2] != '-') break;
239 result = read(fd, addr_buffer + 2, 8);
240 if (result < 8) break;
241 unsigned end = StringToLong(addr_buffer);
242 char buffer[MAP_LENGTH];
243 int bytes_read = -1;
244 do {
245 bytes_read++;
246 if (bytes_read >= MAP_LENGTH - 1)
247 break;
248 result = read(fd, buffer + bytes_read, 1);
249 if (result < 1) break;
250 } while (buffer[bytes_read] != '\n');
251 buffer[bytes_read] = 0;
252 // Ignore mappings that are not executable.
253 if (buffer[3] != 'x') continue;
254 char* start_of_path = index(buffer, '/');
255 // There may be no filename in this line. Skip to next.
256 if (start_of_path == NULL) continue;
257 buffer[bytes_read] = 0;
258 LOG(SharedLibraryEvent(start_of_path, start, end));
259 }
260 close(fd);
261#endif
262}
263
264
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000265int OS::StackWalk(Vector<OS::StackFrame> frames) {
266 int frames_size = frames.length();
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000267 void** addresses = NewArray<void*>(frames_size);
268
269 int frames_count = backtrace(addresses, frames_size);
270
271 char** symbols;
272 symbols = backtrace_symbols(addresses, frames_count);
273 if (symbols == NULL) {
274 DeleteArray(addresses);
275 return kStackWalkError;
276 }
277
278 for (int i = 0; i < frames_count; i++) {
279 frames[i].address = addresses[i];
280 // Format a text representation of the frame based on the information
281 // available.
282 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
283 "%s",
284 symbols[i]);
285 // Make sure line termination is in place.
286 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
287 }
288
289 DeleteArray(addresses);
290 free(symbols);
291
292 return frames_count;
293}
294
295
296// Constants used for mmap.
297static const int kMmapFd = -1;
298static const int kMmapFdOffset = 0;
299
300
301VirtualMemory::VirtualMemory(size_t size) {
302 address_ = mmap(NULL, size, PROT_NONE,
303 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
304 kMmapFd, kMmapFdOffset);
305 size_ = size;
306}
307
308
309VirtualMemory::~VirtualMemory() {
310 if (IsReserved()) {
311 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
312 }
313}
314
315
316bool VirtualMemory::IsReserved() {
317 return address_ != MAP_FAILED;
318}
319
320
321bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
322 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
323 if (MAP_FAILED == mmap(address, size, prot,
324 MAP_PRIVATE | MAP_ANON | MAP_FIXED,
325 kMmapFd, kMmapFdOffset)) {
326 return false;
327 }
328
329 UpdateAllocatedSpaceLimits(address, size);
330 return true;
331}
332
333
334bool VirtualMemory::Uncommit(void* address, size_t size) {
335 return mmap(address, size, PROT_NONE,
336 MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
337 kMmapFd, kMmapFdOffset) != MAP_FAILED;
338}
339
340
341class ThreadHandle::PlatformData : public Malloced {
342 public:
343 explicit PlatformData(ThreadHandle::Kind kind) {
344 Initialize(kind);
345 }
346
347 void Initialize(ThreadHandle::Kind kind) {
348 switch (kind) {
349 case ThreadHandle::SELF: thread_ = pthread_self(); break;
350 case ThreadHandle::INVALID: thread_ = kNoThread; break;
351 }
352 }
353 pthread_t thread_; // Thread handle for pthread.
354};
355
356
357ThreadHandle::ThreadHandle(Kind kind) {
358 data_ = new PlatformData(kind);
359}
360
361
362void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
363 data_->Initialize(kind);
364}
365
366
367ThreadHandle::~ThreadHandle() {
368 delete data_;
369}
370
371
372bool ThreadHandle::IsSelf() const {
373 return pthread_equal(data_->thread_, pthread_self());
374}
375
376
377bool ThreadHandle::IsValid() const {
378 return data_->thread_ != kNoThread;
379}
380
381
382Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
383}
384
385
386Thread::~Thread() {
387}
388
389
390static void* ThreadEntry(void* arg) {
391 Thread* thread = reinterpret_cast<Thread*>(arg);
392 // This is also initialized by the first argument to pthread_create() but we
393 // don't know which thread will run first (the original thread or the new
394 // one) so we initialize it here too.
395 thread->thread_handle_data()->thread_ = pthread_self();
396 ASSERT(thread->IsValid());
397 thread->Run();
398 return NULL;
399}
400
401
402void Thread::Start() {
403 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
404 ASSERT(IsValid());
405}
406
407
408void Thread::Join() {
409 pthread_join(thread_handle_data()->thread_, NULL);
410}
411
412
413Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
414 pthread_key_t key;
415 int result = pthread_key_create(&key, NULL);
416 USE(result);
417 ASSERT(result == 0);
418 return static_cast<LocalStorageKey>(key);
419}
420
421
422void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
423 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
424 int result = pthread_key_delete(pthread_key);
425 USE(result);
426 ASSERT(result == 0);
427}
428
429
430void* Thread::GetThreadLocal(LocalStorageKey key) {
431 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
432 return pthread_getspecific(pthread_key);
433}
434
435
436void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
437 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
438 pthread_setspecific(pthread_key, value);
439}
440
441
442void Thread::YieldCPU() {
443 sched_yield();
444}
445
446
447class FreeBSDMutex : public Mutex {
448 public:
449
450 FreeBSDMutex() {
451 pthread_mutexattr_t attrs;
452 int result = pthread_mutexattr_init(&attrs);
453 ASSERT(result == 0);
454 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
455 ASSERT(result == 0);
456 result = pthread_mutex_init(&mutex_, &attrs);
457 ASSERT(result == 0);
458 }
459
460 virtual ~FreeBSDMutex() { pthread_mutex_destroy(&mutex_); }
461
462 virtual int Lock() {
463 int result = pthread_mutex_lock(&mutex_);
464 return result;
465 }
466
467 virtual int Unlock() {
468 int result = pthread_mutex_unlock(&mutex_);
469 return result;
470 }
471
472 private:
473 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
474};
475
476
477Mutex* OS::CreateMutex() {
478 return new FreeBSDMutex();
479}
480
481
482class FreeBSDSemaphore : public Semaphore {
483 public:
484 explicit FreeBSDSemaphore(int count) { sem_init(&sem_, 0, count); }
485 virtual ~FreeBSDSemaphore() { sem_destroy(&sem_); }
486
487 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000488 virtual bool Wait(int timeout);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000489 virtual void Signal() { sem_post(&sem_); }
490 private:
491 sem_t sem_;
492};
493
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000494
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000495void FreeBSDSemaphore::Wait() {
496 while (true) {
497 int result = sem_wait(&sem_);
498 if (result == 0) return; // Successfully got semaphore.
499 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
500 }
501}
502
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000503
504bool FreeBSDSemaphore::Wait(int timeout) {
505 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000506
507 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000508 struct timeval delta;
509 delta.tv_usec = timeout % kOneSecondMicros;
510 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000511
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000512 struct timeval current_time;
513 // Get the current time.
514 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000515 return false;
516 }
517
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000518 // Calculate time for end of timeout.
519 struct timeval end_time;
520 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000521
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000522 struct timespec ts;
523 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000524 while (true) {
525 int result = sem_timedwait(&sem_, &ts);
526 if (result == 0) return true; // Successfully got semaphore.
527 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
528 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
529 }
530}
531
532
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000533Semaphore* OS::CreateSemaphore(int count) {
534 return new FreeBSDSemaphore(count);
535}
536
ager@chromium.org381abbb2009-02-25 13:23:22 +0000537
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000538#ifdef ENABLE_LOGGING_AND_PROFILING
539
540static Sampler* active_sampler_ = NULL;
541
542static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
543 USE(info);
544 if (signal != SIGPROF) return;
545 if (active_sampler_ == NULL) return;
546
547 TickSample sample;
548
549 // If profiling, we extract the current pc and sp.
550 if (active_sampler_->IsProfiling()) {
551 // Extracting the sample from the context is extremely machine dependent.
552 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
553 mcontext_t& mcontext = ucontext->uc_mcontext;
554#if defined (__arm__) || defined(__thumb__)
555 sample.pc = mcontext.mc_r15;
556 sample.sp = mcontext.mc_r13;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000557 sample.fp = mcontext.mc_r11;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000558#else
559 sample.pc = mcontext.mc_eip;
560 sample.sp = mcontext.mc_esp;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000561 sample.fp = mcontext.mc_ebp;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000562#endif
563 }
564
565 // We always sample the VM state.
566 sample.state = Logger::state();
567
568 active_sampler_->Tick(&sample);
569}
570
571
572class Sampler::PlatformData : public Malloced {
573 public:
574 PlatformData() {
575 signal_handler_installed_ = false;
576 }
577
578 bool signal_handler_installed_;
579 struct sigaction old_signal_handler_;
580 struct itimerval old_timer_value_;
581};
582
583
584Sampler::Sampler(int interval, bool profiling)
585 : interval_(interval), profiling_(profiling), active_(false) {
586 data_ = new PlatformData();
587}
588
589
590Sampler::~Sampler() {
591 delete data_;
592}
593
594
595void Sampler::Start() {
596 // There can only be one active sampler at the time on POSIX
597 // platforms.
598 if (active_sampler_ != NULL) return;
599
600 // Request profiling signals.
601 struct sigaction sa;
602 sa.sa_sigaction = ProfilerSignalHandler;
603 sigemptyset(&sa.sa_mask);
604 sa.sa_flags = SA_SIGINFO;
605 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
606 data_->signal_handler_installed_ = true;
607
608 // Set the itimer to generate a tick for each interval.
609 itimerval itimer;
610 itimer.it_interval.tv_sec = interval_ / 1000;
611 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
612 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
613 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
614 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
615
616 // Set this sampler as the active sampler.
617 active_sampler_ = this;
618 active_ = true;
619}
620
621
622void Sampler::Stop() {
623 // Restore old signal handler
624 if (data_->signal_handler_installed_) {
625 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
626 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
627 data_->signal_handler_installed_ = false;
628 }
629
630 // This sampler is no longer the active sampler.
631 active_sampler_ = NULL;
632 active_ = false;
633}
634
635#endif // ENABLE_LOGGING_AND_PROFILING
636
637} } // namespace v8::internal