blob: c001f51b69f9eb3e510eb2862d0777fe0b422ea7 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +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 Linux goes here
29
30#include <pthread.h>
31#include <semaphore.h>
32#include <signal.h>
33#include <sys/time.h>
34#include <sys/resource.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000035#include <sys/socket.h>
36#include <sys/types.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include <stdlib.h>
38
39// Ubuntu Dapper requires memory pages to be marked as
40// executable. Otherwise, OS raises an exception when executing code
41// in that page.
42#include <sys/types.h> // mmap & munmap
ager@chromium.org236ad962008-09-25 09:45:57 +000043#include <sys/mman.h> // mmap & munmap
44#include <sys/stat.h> // open
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045#include <sys/fcntl.h> // open
ager@chromium.org236ad962008-09-25 09:45:57 +000046#include <unistd.h> // getpagesize
47#include <execinfo.h> // backtrace, backtrace_symbols
48#include <strings.h> // index
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000049#include <errno.h>
50#include <stdarg.h>
51
ager@chromium.org381abbb2009-02-25 13:23:22 +000052#include <arpa/inet.h>
53#include <netinet/in.h>
54#include <netdb.h>
55
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000056#undef MAP_TYPE
57
58#include "v8.h"
59
60#include "platform.h"
61
62
63namespace v8 { namespace internal {
64
65// 0 is never a valid thread id on Linux since tids and pids share a
66// name space and pid 0 is reserved (see man 2 kill).
67static const pthread_t kNoThread = (pthread_t) 0;
68
69
70double ceiling(double x) {
71 return ceil(x);
72}
73
74
75void OS::Setup() {
76 // Seed the random number generator.
ager@chromium.org9258b6b2008-09-11 09:11:10 +000077 // 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));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000083}
84
85
86int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
87 struct rusage usage;
88
89 if (getrusage(RUSAGE_SELF, &usage) < 0) return -1;
90 *secs = usage.ru_utime.tv_sec;
91 *usecs = usage.ru_utime.tv_usec;
92 return 0;
93}
94
95
96double OS::TimeCurrentMillis() {
97 struct timeval tv;
98 if (gettimeofday(&tv, NULL) < 0) return 0.0;
99 return (static_cast<double>(tv.tv_sec) * 1000) +
100 (static_cast<double>(tv.tv_usec) / 1000);
101}
102
103
104int64_t OS::Ticks() {
105 // Linux's gettimeofday has microsecond resolution.
106 struct timeval tv;
107 if (gettimeofday(&tv, NULL) < 0)
108 return 0;
109 return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
110}
111
112
113char* OS::LocalTimezone(double time) {
114 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
115 struct tm* t = localtime(&tv);
116 return const_cast<char*>(t->tm_zone);
117}
118
119
120double OS::DaylightSavingsOffset(double time) {
121 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
122 struct tm* t = localtime(&tv);
kasper.lund7276f142008-07-30 08:49:36 +0000123 return t->tm_isdst > 0 ? 3600 * msPerSecond : 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000124}
125
126
127double OS::LocalTimeOffset() {
kasper.lund7276f142008-07-30 08:49:36 +0000128 time_t tv = time(NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000129 struct tm* t = localtime(&tv);
kasper.lund7276f142008-07-30 08:49:36 +0000130 // tm_gmtoff includes any daylight savings offset, so subtract it.
131 return static_cast<double>(t->tm_gmtoff * msPerSecond -
132 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000133}
134
135
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000136FILE* OS::FOpen(const char* path, const char* mode) {
137 return fopen(path, mode);
138}
139
140
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000141void OS::Print(const char* format, ...) {
142 va_list args;
143 va_start(args, format);
144 VPrint(format, args);
145 va_end(args);
146}
147
148
149void OS::VPrint(const char* format, va_list args) {
150 vprintf(format, args);
151}
152
153
154void OS::PrintError(const char* format, ...) {
155 va_list args;
156 va_start(args, format);
157 VPrintError(format, args);
158 va_end(args);
159}
160
161
162void OS::VPrintError(const char* format, va_list args) {
163 vfprintf(stderr, format, args);
164}
165
166
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000167int OS::SNPrintF(Vector<char> str, const char* format, ...) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000168 va_list args;
169 va_start(args, format);
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000170 int result = VSNPrintF(str, format, args);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000171 va_end(args);
172 return result;
173}
174
175
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000176int OS::VSNPrintF(Vector<char> str,
177 const char* format,
178 va_list args) {
179 int n = vsnprintf(str.start(), str.length(), format, args);
180 if (n < 0 || n >= str.length()) {
181 str[str.length() - 1] = '\0';
kasper.lund7276f142008-07-30 08:49:36 +0000182 return -1;
183 } else {
184 return n;
185 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000186}
187
188
ager@chromium.org381abbb2009-02-25 13:23:22 +0000189char* OS::StrChr(char* str, int c) {
190 return strchr(str, c);
191}
192
193
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000194void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
195 strncpy(dest.start(), src, n);
196}
197
198
ager@chromium.org8bb60582008-12-11 12:02:20 +0000199char* OS::StrDup(const char* str) {
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000200 return strdup(str);
201}
202
203
ager@chromium.org8bb60582008-12-11 12:02:20 +0000204char* OS::StrNDup(const char* str, size_t n) {
205 return strndup(str, n);
206}
207
208
ager@chromium.org236ad962008-09-25 09:45:57 +0000209double OS::nan_value() {
210 return NAN;
211}
212
213
214int OS::ActivationFrameAlignment() {
215 // No constraint on Linux.
216 return 0;
217}
218
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000219
220// We keep the lowest and highest addresses mapped as a quick way of
221// determining that pointers are outside the heap (used mostly in assertions
222// and verification). The estimate is conservative, ie, not all addresses in
223// 'allocated' space are actually allocated to our heap. The range is
224// [lowest, highest), inclusive on the low and and exclusive on the high end.
225static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
226static void* highest_ever_allocated = reinterpret_cast<void*>(0);
227
228
229static void UpdateAllocatedSpaceLimits(void* address, int size) {
230 lowest_ever_allocated = Min(lowest_ever_allocated, address);
231 highest_ever_allocated =
232 Max(highest_ever_allocated,
233 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
234}
235
236
237bool OS::IsOutsideAllocatedSpace(void* address) {
238 return address < lowest_ever_allocated || address >= highest_ever_allocated;
239}
240
241
242size_t OS::AllocateAlignment() {
243 return getpagesize();
244}
245
246
kasper.lund7276f142008-07-30 08:49:36 +0000247void* OS::Allocate(const size_t requested,
248 size_t* allocated,
249 bool executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000250 const size_t msize = RoundUp(requested, getpagesize());
kasper.lund7276f142008-07-30 08:49:36 +0000251 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
252 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000253 if (mbase == MAP_FAILED) {
254 LOG(StringEvent("OS::Allocate", "mmap failed"));
255 return NULL;
256 }
257 *allocated = msize;
258 UpdateAllocatedSpaceLimits(mbase, msize);
259 return mbase;
260}
261
262
263void OS::Free(void* buf, const size_t length) {
264 // TODO(1240712): munmap has a return value which is ignored here.
265 munmap(buf, length);
266}
267
268
269void OS::Sleep(int milliseconds) {
270 unsigned int ms = static_cast<unsigned int>(milliseconds);
271 usleep(1000 * ms);
272}
273
274
275void OS::Abort() {
276 // Redirect to std abort to signal abnormal program termination.
277 abort();
278}
279
280
kasper.lund7276f142008-07-30 08:49:36 +0000281void OS::DebugBreak() {
282#if defined (__arm__) || defined(__thumb__)
283 asm("bkpt 0");
284#else
285 asm("int $3");
286#endif
287}
288
289
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290class PosixMemoryMappedFile : public OS::MemoryMappedFile {
291 public:
292 PosixMemoryMappedFile(FILE* file, void* memory, int size)
293 : file_(file), memory_(memory), size_(size) { }
294 virtual ~PosixMemoryMappedFile();
295 virtual void* memory() { return memory_; }
296 private:
297 FILE* file_;
298 void* memory_;
299 int size_;
300};
301
302
303OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
304 void* initial) {
305 FILE* file = fopen(name, "w+");
306 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000307 int result = fwrite(initial, size, 1, file);
308 if (result < 1) {
309 fclose(file);
310 return NULL;
311 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000312 void* memory =
313 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
314 return new PosixMemoryMappedFile(file, memory, size);
315}
316
317
318PosixMemoryMappedFile::~PosixMemoryMappedFile() {
319 if (memory_) munmap(memory_, size_);
320 fclose(file_);
321}
322
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000323
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000324#ifdef ENABLE_LOGGING_AND_PROFILING
325static unsigned StringToLong(char* buffer) {
326 return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
327}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000328#endif
329
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000330
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000331void OS::LogSharedLibraryAddresses() {
332#ifdef ENABLE_LOGGING_AND_PROFILING
333 static const int MAP_LENGTH = 1024;
334 int fd = open("/proc/self/maps", O_RDONLY);
335 if (fd < 0) return;
336 while (true) {
337 char addr_buffer[11];
338 addr_buffer[0] = '0';
339 addr_buffer[1] = 'x';
340 addr_buffer[10] = 0;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000341 int result = read(fd, addr_buffer + 2, 8);
342 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000343 unsigned start = StringToLong(addr_buffer);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000344 result = read(fd, addr_buffer + 2, 1);
345 if (result < 1) break;
346 if (addr_buffer[2] != '-') break;
347 result = read(fd, addr_buffer + 2, 8);
348 if (result < 8) break;
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000349 unsigned end = StringToLong(addr_buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000350 char buffer[MAP_LENGTH];
351 int bytes_read = -1;
352 do {
353 bytes_read++;
ager@chromium.orgc27e4e72008-09-04 13:52:27 +0000354 if (bytes_read >= MAP_LENGTH - 1)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000356 result = read(fd, buffer + bytes_read, 1);
357 if (result < 1) break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000358 } while (buffer[bytes_read] != '\n');
359 buffer[bytes_read] = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360 // Ignore mappings that are not executable.
361 if (buffer[3] != 'x') continue;
ager@chromium.org236ad962008-09-25 09:45:57 +0000362 char* start_of_path = index(buffer, '/');
363 // There may be no filename in this line. Skip to next.
364 if (start_of_path == NULL) continue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000365 buffer[bytes_read] = 0;
ager@chromium.org236ad962008-09-25 09:45:57 +0000366 LOG(SharedLibraryEvent(start_of_path, start, end));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000367 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000368 close(fd);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000369#endif
370}
371
372
373int OS::StackWalk(OS::StackFrame* frames, int frames_size) {
374 void** addresses = NewArray<void*>(frames_size);
375
376 int frames_count = backtrace(addresses, frames_size);
377
378 char** symbols;
379 symbols = backtrace_symbols(addresses, frames_count);
380 if (symbols == NULL) {
381 DeleteArray(addresses);
382 return kStackWalkError;
383 }
384
385 for (int i = 0; i < frames_count; i++) {
386 frames[i].address = addresses[i];
387 // Format a text representation of the frame based on the information
388 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000389 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
390 "%s",
391 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000392 // Make sure line termination is in place.
393 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
394 }
395
396 DeleteArray(addresses);
397 free(symbols);
398
399 return frames_count;
400}
401
402
403// Constants used for mmap.
404static const int kMmapFd = -1;
405static const int kMmapFdOffset = 0;
406
407
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000408VirtualMemory::VirtualMemory(size_t size) {
409 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
411 kMmapFd, kMmapFdOffset);
412 size_ = size;
413}
414
415
416VirtualMemory::~VirtualMemory() {
417 if (IsReserved()) {
418 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
419 }
420}
421
422
423bool VirtualMemory::IsReserved() {
424 return address_ != MAP_FAILED;
425}
426
427
kasper.lund7276f142008-07-30 08:49:36 +0000428bool VirtualMemory::Commit(void* address, size_t size, bool executable) {
429 int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
430 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000431 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
432 kMmapFd, kMmapFdOffset)) {
433 return false;
434 }
435
436 UpdateAllocatedSpaceLimits(address, size);
437 return true;
438}
439
440
441bool VirtualMemory::Uncommit(void* address, size_t size) {
442 return mmap(address, size, PROT_NONE,
443 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
444 kMmapFd, kMmapFdOffset) != MAP_FAILED;
445}
446
447
448class ThreadHandle::PlatformData : public Malloced {
449 public:
450 explicit PlatformData(ThreadHandle::Kind kind) {
451 Initialize(kind);
452 }
453
454 void Initialize(ThreadHandle::Kind kind) {
455 switch (kind) {
456 case ThreadHandle::SELF: thread_ = pthread_self(); break;
457 case ThreadHandle::INVALID: thread_ = kNoThread; break;
458 }
459 }
460 pthread_t thread_; // Thread handle for pthread.
461};
462
463
464ThreadHandle::ThreadHandle(Kind kind) {
465 data_ = new PlatformData(kind);
466}
467
468
469void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
470 data_->Initialize(kind);
471}
472
473
474ThreadHandle::~ThreadHandle() {
475 delete data_;
476}
477
478
479bool ThreadHandle::IsSelf() const {
480 return pthread_equal(data_->thread_, pthread_self());
481}
482
483
484bool ThreadHandle::IsValid() const {
485 return data_->thread_ != kNoThread;
486}
487
488
489Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
490}
491
492
493Thread::~Thread() {
494}
495
496
497static void* ThreadEntry(void* arg) {
498 Thread* thread = reinterpret_cast<Thread*>(arg);
499 // This is also initialized by the first argument to pthread_create() but we
500 // don't know which thread will run first (the original thread or the new
501 // one) so we initialize it here too.
502 thread->thread_handle_data()->thread_ = pthread_self();
503 ASSERT(thread->IsValid());
504 thread->Run();
505 return NULL;
506}
507
508
509void Thread::Start() {
510 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
511 ASSERT(IsValid());
512}
513
514
515void Thread::Join() {
516 pthread_join(thread_handle_data()->thread_, NULL);
517}
518
519
520Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
521 pthread_key_t key;
522 int result = pthread_key_create(&key, NULL);
523 USE(result);
524 ASSERT(result == 0);
525 return static_cast<LocalStorageKey>(key);
526}
527
528
529void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
530 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
531 int result = pthread_key_delete(pthread_key);
532 USE(result);
533 ASSERT(result == 0);
534}
535
536
537void* Thread::GetThreadLocal(LocalStorageKey key) {
538 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
539 return pthread_getspecific(pthread_key);
540}
541
542
543void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
544 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
545 pthread_setspecific(pthread_key, value);
546}
547
548
549void Thread::YieldCPU() {
550 sched_yield();
551}
552
553
554class LinuxMutex : public Mutex {
555 public:
556
557 LinuxMutex() {
558 pthread_mutexattr_t attrs;
559 int result = pthread_mutexattr_init(&attrs);
560 ASSERT(result == 0);
561 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
562 ASSERT(result == 0);
563 result = pthread_mutex_init(&mutex_, &attrs);
564 ASSERT(result == 0);
565 }
566
567 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
568
569 virtual int Lock() {
570 int result = pthread_mutex_lock(&mutex_);
571 return result;
572 }
573
574 virtual int Unlock() {
575 int result = pthread_mutex_unlock(&mutex_);
576 return result;
577 }
578
579 private:
580 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
581};
582
583
584Mutex* OS::CreateMutex() {
585 return new LinuxMutex();
586}
587
588
589class LinuxSemaphore : public Semaphore {
590 public:
591 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
592 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
593
kasper.lund7276f142008-07-30 08:49:36 +0000594 virtual void Wait();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000595 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000596 private:
597 sem_t sem_;
598};
599
kasper.lund7276f142008-07-30 08:49:36 +0000600void LinuxSemaphore::Wait() {
601 while (true) {
602 int result = sem_wait(&sem_);
603 if (result == 0) return; // Successfully got semaphore.
604 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
605 }
606}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607
608Semaphore* OS::CreateSemaphore(int count) {
609 return new LinuxSemaphore(count);
610}
611
ager@chromium.org381abbb2009-02-25 13:23:22 +0000612
613// ----------------------------------------------------------------------------
614// Linux socket support.
615//
616
617class LinuxSocket : public Socket {
618 public:
619 explicit LinuxSocket() {
620 // Create the socket.
621 socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
622 }
623 explicit LinuxSocket(int socket): socket_(socket) { }
624
625
626 virtual ~LinuxSocket() {
627 if (IsValid()) {
628 // Close socket.
629 close(socket_);
630 }
631 }
632
633 // Server initialization.
634 bool Bind(const int port);
635 bool Listen(int backlog) const;
636 Socket* Accept() const;
637
638 // Client initialization.
639 bool Connect(const char* host, const char* port);
640
641 // Data Transimission
642 int Send(const char* data, int len) const;
643 bool SendAll(const char* data, int len) const;
644 int Receive(char* data, int len) const;
645
646 bool IsValid() const { return socket_ != -1; }
647
648 private:
649 int socket_;
650};
651
652
653bool LinuxSocket::Bind(const int port) {
654 if (!IsValid()) {
655 return false;
656 }
657
658 sockaddr_in addr;
659 memset(&addr, 0, sizeof(addr));
660 addr.sin_family = AF_INET;
661 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
662 addr.sin_port = htons(port);
663 int status = bind(socket_,
664 reinterpret_cast<struct sockaddr *>(&addr),
665 sizeof(addr));
666 return status == 0;
667}
668
669
670bool LinuxSocket::Listen(int backlog) const {
671 if (!IsValid()) {
672 return false;
673 }
674
675 int status = listen(socket_, backlog);
676 return status == 0;
677}
678
679
680Socket* LinuxSocket::Accept() const {
681 if (!IsValid()) {
682 return NULL;
683 }
684
685 int socket = accept(socket_, NULL, NULL);
686 if (socket == -1) {
687 return NULL;
688 } else {
689 return new LinuxSocket(socket);
690 }
691}
692
693
694bool LinuxSocket::Connect(const char* host, const char* port) {
695 if (!IsValid()) {
696 return false;
697 }
698
699 // Lookup host and port.
700 struct addrinfo *result = NULL;
701 struct addrinfo hints;
702 memset(&hints, 0, sizeof(addrinfo));
703 hints.ai_family = AF_INET;
704 hints.ai_socktype = SOCK_STREAM;
705 hints.ai_protocol = IPPROTO_TCP;
706 int status = getaddrinfo(host, port, &hints, &result);
707 if (status != 0) {
708 return false;
709 }
710
711 // Connect.
712 status = connect(socket_, result->ai_addr, result->ai_addrlen);
713 return status == 0;
714}
715
716
717int LinuxSocket::Send(const char* data, int len) const {
718 int status = send(socket_, data, len, 0);
719 return status;
720}
721
722
723bool LinuxSocket::SendAll(const char* data, int len) const {
724 int sent_len = 0;
725 while (sent_len < len) {
726 int status = Send(data, len);
727 if (status <= 0) {
728 return false;
729 }
730 sent_len += status;
731 }
732 return true;
733}
734
735
736int LinuxSocket::Receive(char* data, int len) const {
737 int status = recv(socket_, data, len, 0);
738 return status;
739}
740
741
742bool Socket::Setup() {
743 // Nothing to do on Linux.
744 return true;
745}
746
747
748int Socket::LastError() {
749 return errno;
750}
751
752
753uint16_t Socket::HToN(uint16_t value) {
754 return htons(value);
755}
756
757
758uint16_t Socket::NToH(uint16_t value) {
759 return ntohs(value);
760}
761
762
763uint32_t Socket::HToN(uint32_t value) {
764 return htonl(value);
765}
766
767
768uint32_t Socket::NToH(uint32_t value) {
769 return ntohl(value);
770}
771
772
773Socket* OS::CreateSocket() {
774 return new LinuxSocket();
775}
776
777
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000778#ifdef ENABLE_LOGGING_AND_PROFILING
779
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000780static Sampler* active_sampler_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000781
782static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
783 USE(info);
784 if (signal != SIGPROF) return;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000785 if (active_sampler_ == NULL) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000786
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000787 TickSample sample;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000788
789 // If profiling, we extract the current pc and sp.
790 if (active_sampler_->IsProfiling()) {
791 // Extracting the sample from the context is extremely machine dependent.
792 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
793 mcontext_t& mcontext = ucontext->uc_mcontext;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000794#if defined (__arm__) || defined(__thumb__)
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000795 sample.pc = mcontext.gregs[R15];
796 sample.sp = mcontext.gregs[R13];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000797 sample.fp = mcontext.gregs[R11];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000798#else
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000799 sample.pc = mcontext.gregs[REG_EIP];
800 sample.sp = mcontext.gregs[REG_ESP];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000801 sample.fp = mcontext.gregs[REG_EBP];
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000802#endif
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000803 }
804
805 // We always sample the VM state.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000806 sample.state = Logger::state();
807
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000808 active_sampler_->Tick(&sample);
809}
810
811
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000812class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000813 public:
814 PlatformData() {
815 signal_handler_installed_ = false;
816 }
817
818 bool signal_handler_installed_;
819 struct sigaction old_signal_handler_;
820 struct itimerval old_timer_value_;
821};
822
823
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000824Sampler::Sampler(int interval, bool profiling)
825 : interval_(interval), profiling_(profiling), active_(false) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826 data_ = new PlatformData();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000827}
828
829
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000830Sampler::~Sampler() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000831 delete data_;
832}
833
834
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000835void Sampler::Start() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836 // There can only be one active sampler at the time on POSIX
837 // platforms.
838 if (active_sampler_ != NULL) return;
839
840 // Request profiling signals.
841 struct sigaction sa;
842 sa.sa_sigaction = ProfilerSignalHandler;
843 sigemptyset(&sa.sa_mask);
844 sa.sa_flags = SA_SIGINFO;
845 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
846 data_->signal_handler_installed_ = true;
847
848 // Set the itimer to generate a tick for each interval.
849 itimerval itimer;
850 itimer.it_interval.tv_sec = interval_ / 1000;
851 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
852 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
853 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
854 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
855
856 // Set this sampler as the active sampler.
857 active_sampler_ = this;
858 active_ = true;
859}
860
861
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000862void Sampler::Stop() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 // Restore old signal handler
864 if (data_->signal_handler_installed_) {
865 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
866 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
867 data_->signal_handler_installed_ = false;
868 }
869
870 // This sampler is no longer the active sampler.
871 active_sampler_ = NULL;
872 active_ = false;
873}
874
875#endif // ENABLE_LOGGING_AND_PROFILING
876
877} } // namespace v8::internal