1 // Copyright 2012 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
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.
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.
28 // Platform specific code for POSIX goes here. This is not a platform on its
29 // own but contains the parts which are the same across POSIX platforms Linux,
30 // Mac OS, FreeBSD and OpenBSD.
32 #include "platform-posix.h"
39 #include <sys/socket.h>
40 #include <sys/resource.h>
42 #include <sys/types.h>
45 #include <arpa/inet.h>
46 #include <netinet/in.h>
51 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
53 #include <android/log.h>
65 // Maximum size of the virtual memory. 0 means there is no artificial
68 intptr_t OS::MaxVirtualMemory() {
70 int result = getrlimit(RLIMIT_DATA, &limit);
71 if (result != 0) return 0;
72 return limit.rlim_cur;
76 intptr_t OS::CommitPageSize() {
77 static intptr_t page_size = getpagesize();
83 // Get rid of writable permission on code allocations.
84 void OS::ProtectCode(void* address, const size_t size) {
85 mprotect(address, size, PROT_READ | PROT_EXEC);
89 // Create guard pages.
90 void OS::Guard(void* address, const size_t size) {
91 mprotect(address, size, PROT_NONE);
96 void* OS::GetRandomMmapAddr() {
97 Isolate* isolate = Isolate::UncheckedCurrent();
98 // Note that the current isolate isn't set up in a call path via
99 // CpuFeatures::Probe. We don't care about randomization in this case because
100 // the code page is immediately freed.
101 if (isolate != NULL) {
102 #ifdef V8_TARGET_ARCH_X64
103 uint64_t rnd1 = V8::RandomPrivate(isolate);
104 uint64_t rnd2 = V8::RandomPrivate(isolate);
105 uint64_t raw_addr = (rnd1 << 32) ^ rnd2;
106 // Currently available CPUs have 48 bits of virtual addressing. Truncate
107 // the hint address to 46 bits to give the kernel a fighting chance of
108 // fulfilling our placement request.
109 raw_addr &= V8_UINT64_C(0x3ffffffff000);
111 uint32_t raw_addr = V8::RandomPrivate(isolate);
112 // The range 0x20000000 - 0x60000000 is relatively unpopulated across a
113 // variety of ASLR modes (PAE kernel, NX compat mode, etc) and on macos
115 raw_addr &= 0x3ffff000;
116 raw_addr += 0x20000000;
118 return reinterpret_cast<void*>(raw_addr);
124 // ----------------------------------------------------------------------------
127 double modulo(double x, double y) {
132 #define UNARY_MATH_FUNCTION(name, generator) \
133 static UnaryMathFunction fast_##name##_function = NULL; \
134 void init_fast_##name##_function() { \
135 fast_##name##_function = generator; \
137 double fast_##name(double x) { \
138 return (*fast_##name##_function)(x); \
141 UNARY_MATH_FUNCTION(sin, CreateTranscendentalFunction(TranscendentalCache::SIN))
142 UNARY_MATH_FUNCTION(cos, CreateTranscendentalFunction(TranscendentalCache::COS))
143 UNARY_MATH_FUNCTION(tan, CreateTranscendentalFunction(TranscendentalCache::TAN))
144 UNARY_MATH_FUNCTION(log, CreateTranscendentalFunction(TranscendentalCache::LOG))
145 UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
150 double OS::nan_value() {
151 // NAN from math.h is defined in C99 and not in POSIX.
156 // ----------------------------------------------------------------------------
157 // POSIX date/time support.
160 int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
163 if (getrusage(RUSAGE_SELF, &usage) < 0) return -1;
164 *secs = usage.ru_utime.tv_sec;
165 *usecs = usage.ru_utime.tv_usec;
170 double OS::TimeCurrentMillis() {
172 if (gettimeofday(&tv, NULL) < 0) return 0.0;
173 return (static_cast<double>(tv.tv_sec) * 1000) +
174 (static_cast<double>(tv.tv_usec) / 1000);
178 int64_t OS::Ticks() {
179 // gettimeofday has microsecond resolution.
181 if (gettimeofday(&tv, NULL) < 0)
183 return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
187 double OS::DaylightSavingsOffset(double time) {
188 if (isnan(time)) return nan_value();
189 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
190 struct tm* t = localtime(&tv);
191 if (NULL == t) return nan_value();
192 return t->tm_isdst > 0 ? 3600 * msPerSecond : 0;
196 int OS::GetLastError() {
201 // ----------------------------------------------------------------------------
202 // POSIX stdio support.
205 FILE* OS::FOpen(const char* path, const char* mode) {
206 FILE* file = fopen(path, mode);
207 if (file == NULL) return NULL;
208 struct stat file_stat;
209 if (fstat(fileno(file), &file_stat) != 0) return NULL;
210 bool is_regular_file = ((file_stat.st_mode & S_IFREG) != 0);
211 if (is_regular_file) return file;
217 bool OS::Remove(const char* path) {
218 return (remove(path) == 0);
222 FILE* OS::OpenTemporaryFile() {
227 const char* const OS::LogFileOpenMode = "w";
230 void OS::Print(const char* format, ...) {
232 va_start(args, format);
233 VPrint(format, args);
238 void OS::VPrint(const char* format, va_list args) {
239 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
240 __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
242 vprintf(format, args);
247 void OS::FPrint(FILE* out, const char* format, ...) {
249 va_start(args, format);
250 VFPrint(out, format, args);
255 void OS::VFPrint(FILE* out, const char* format, va_list args) {
256 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
257 __android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, format, args);
259 vfprintf(out, format, args);
264 void OS::PrintError(const char* format, ...) {
266 va_start(args, format);
267 VPrintError(format, args);
272 void OS::VPrintError(const char* format, va_list args) {
273 #if defined(ANDROID) && !defined(V8_ANDROID_LOG_STDOUT)
274 __android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, format, args);
276 vfprintf(stderr, format, args);
281 int OS::SNPrintF(Vector<char> str, const char* format, ...) {
283 va_start(args, format);
284 int result = VSNPrintF(str, format, args);
290 int OS::VSNPrintF(Vector<char> str,
293 int n = vsnprintf(str.start(), str.length(), format, args);
294 if (n < 0 || n >= str.length()) {
295 // If the length is zero, the assignment fails.
296 if (str.length() > 0)
297 str[str.length() - 1] = '\0';
305 #if defined(V8_TARGET_ARCH_IA32)
306 static OS::MemCopyFunction memcopy_function = NULL;
307 // Defined in codegen-ia32.cc.
308 OS::MemCopyFunction CreateMemCopyFunction();
310 // Copy memory area to disjoint memory area.
311 void OS::MemCopy(void* dest, const void* src, size_t size) {
312 // Note: here we rely on dependent reads being ordered. This is true
313 // on all architectures we currently support.
314 (*memcopy_function)(dest, src, size);
316 CHECK_EQ(0, memcmp(dest, src, size));
319 #endif // V8_TARGET_ARCH_IA32
322 void POSIXPostSetUp() {
323 #if defined(V8_TARGET_ARCH_IA32)
324 memcopy_function = CreateMemCopyFunction();
326 init_fast_sin_function();
327 init_fast_cos_function();
328 init_fast_tan_function();
329 init_fast_log_function();
330 init_fast_sqrt_function();
333 // ----------------------------------------------------------------------------
334 // POSIX string support.
337 char* OS::StrChr(char* str, int c) {
338 return strchr(str, c);
342 void OS::StrNCpy(Vector<char> dest, const char* src, size_t n) {
343 strncpy(dest.start(), src, n);
347 // ----------------------------------------------------------------------------
348 // POSIX socket support.
351 class POSIXSocket : public Socket {
353 explicit POSIXSocket() {
354 // Create the socket.
355 socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
357 // Allow rapid reuse.
358 static const int kOn = 1;
359 int ret = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
365 explicit POSIXSocket(int socket): socket_(socket) { }
366 virtual ~POSIXSocket() { Shutdown(); }
368 // Server initialization.
369 bool Bind(const int port);
370 bool Listen(int backlog) const;
371 Socket* Accept() const;
373 // Client initialization.
374 bool Connect(const char* host, const char* port);
376 // Shutdown socket for both read and write.
379 // Data Transimission
380 int Send(const char* data, int len) const;
381 int Receive(char* data, int len) const;
383 bool SetReuseAddress(bool reuse_address);
385 bool IsValid() const { return socket_ != -1; }
392 bool POSIXSocket::Bind(const int port) {
398 memset(&addr, 0, sizeof(addr));
399 addr.sin_family = AF_INET;
400 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
401 addr.sin_port = htons(port);
402 int status = bind(socket_,
403 BitCast<struct sockaddr *>(&addr),
409 bool POSIXSocket::Listen(int backlog) const {
414 int status = listen(socket_, backlog);
419 Socket* POSIXSocket::Accept() const {
426 socket = accept(socket_, NULL, NULL);
427 } while (socket == -1 && errno == EINTR);
432 return new POSIXSocket(socket);
437 bool POSIXSocket::Connect(const char* host, const char* port) {
442 // Lookup host and port.
443 struct addrinfo *result = NULL;
444 struct addrinfo hints;
445 memset(&hints, 0, sizeof(addrinfo));
446 hints.ai_family = AF_INET;
447 hints.ai_socktype = SOCK_STREAM;
448 hints.ai_protocol = IPPROTO_TCP;
449 int status = getaddrinfo(host, port, &hints, &result);
456 status = connect(socket_, result->ai_addr, result->ai_addrlen);
457 } while (status == -1 && errno == EINTR);
458 freeaddrinfo(result);
463 bool POSIXSocket::Shutdown() {
465 // Shutdown socket for both read and write.
466 int status = shutdown(socket_, SHUT_RDWR);
475 int POSIXSocket::Send(const char* data, int len) const {
476 if (len <= 0) return 0;
478 while (written < len) {
479 int status = send(socket_, data + written, len - written, 0);
482 } else if (status > 0) {
484 } else if (errno != EINTR) {
492 int POSIXSocket::Receive(char* data, int len) const {
493 if (len <= 0) return 0;
496 status = recv(socket_, data, len, 0);
497 } while (status == -1 && errno == EINTR);
498 return (status < 0) ? 0 : status;
502 bool POSIXSocket::SetReuseAddress(bool reuse_address) {
503 int on = reuse_address ? 1 : 0;
504 int status = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
509 bool Socket::SetUp() {
510 // Nothing to do on POSIX.
515 int Socket::LastError() {
520 uint16_t Socket::HToN(uint16_t value) {
525 uint16_t Socket::NToH(uint16_t value) {
530 uint32_t Socket::HToN(uint32_t value) {
535 uint32_t Socket::NToH(uint32_t value) {
540 Socket* OS::CreateSocket() {
541 return new POSIXSocket();
545 } } // namespace v8::internal