blob: 38f7c678344acfd380bb21c4e6099d8d7d35bb16 [file] [log] [blame]
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001// Copyright 2012 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
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000028// Platform specific code for Linux goes here. For the POSIX comaptible parts
29// the implementation is in platform-posix.cc.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000030
31#include <pthread.h>
32#include <semaphore.h>
33#include <signal.h>
lrn@chromium.org5d00b602011-01-05 09:51:43 +000034#include <sys/prctl.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include <sys/time.h>
36#include <sys/resource.h>
lrn@chromium.org303ada72010-10-27 09:33:13 +000037#include <sys/syscall.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000038#include <sys/types.h>
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000039#include <stdlib.h>
40
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +000041#if defined(__GLIBC__) && !defined(__UCLIBC__)
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +000042#include <execinfo.h>
43#include <cxxabi.h>
44#endif
45
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000046// Ubuntu Dapper requires memory pages to be marked as
47// executable. Otherwise, OS raises an exception when executing code
48// in that page.
49#include <sys/types.h> // mmap & munmap
ager@chromium.org236ad962008-09-25 09:45:57 +000050#include <sys/mman.h> // mmap & munmap
51#include <sys/stat.h> // open
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000052#include <fcntl.h> // open
53#include <unistd.h> // sysconf
ager@chromium.org236ad962008-09-25 09:45:57 +000054#include <strings.h> // index
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000055#include <errno.h>
56#include <stdarg.h>
57
mstarzinger@chromium.org471f2f12012-08-10 14:46:33 +000058// GLibc on ARM defines mcontext_t has a typedef for 'struct sigcontext'.
59// Old versions of the C library <signal.h> didn't define the type.
60#if defined(__ANDROID__) && !defined(__BIONIC_HAVE_UCONTEXT_T) && \
61 defined(__arm__) && !defined(__BIONIC_HAVE_STRUCT_SIGCONTEXT)
62#include <asm/sigcontext.h>
63#endif
64
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065#undef MAP_TYPE
66
67#include "v8.h"
68
danno@chromium.org8c0a43f2012-04-03 08:37:53 +000069#include "platform-posix.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000070#include "platform.h"
ager@chromium.orga1645e22009-09-09 19:27:10 +000071#include "v8threads.h"
kasperl@chromium.orga5551262010-12-07 12:49:48 +000072#include "vm-state-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073
74
kasperl@chromium.org71affb52009-05-26 05:44:31 +000075namespace v8 {
76namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000077
78// 0 is never a valid thread id on Linux since tids and pids share a
79// name space and pid 0 is reserved (see man 2 kill).
80static const pthread_t kNoThread = (pthread_t) 0;
81
82
83double ceiling(double x) {
84 return ceil(x);
85}
86
87
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000088static Mutex* limit_mutex = NULL;
89
90
danno@chromium.org8c0a43f2012-04-03 08:37:53 +000091void OS::PostSetUp() {
fschneider@chromium.org7d10be52012-04-10 12:30:14 +000092 POSIXPostSetUp();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +000093}
94
95
ager@chromium.orgc4c92722009-11-18 14:12:51 +000096uint64_t OS::CpuFeaturesImpliedByPlatform() {
ager@chromium.orgc4c92722009-11-18 14:12:51 +000097 return 0; // Linux runs on anything.
ager@chromium.orgc4c92722009-11-18 14:12:51 +000098}
99
100
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000101#ifdef __arm__
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000102static bool CPUInfoContainsString(const char * search_string) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000103 const char* file_name = "/proc/cpuinfo";
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000104 // This is written as a straight shot one pass parser
105 // and not using STL string and ifstream because,
106 // on Linux, it's reading from a (non-mmap-able)
107 // character special device.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000108 FILE* f = NULL;
109 const char* what = search_string;
110
mstarzinger@chromium.orgf705b502013-04-04 11:38:09 +0000111 if (NULL == (f = fopen(file_name, "r"))) {
112 OS::PrintError("Failed to open /proc/cpuinfo\n");
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000113 return false;
mstarzinger@chromium.orgf705b502013-04-04 11:38:09 +0000114 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000115
116 int k;
117 while (EOF != (k = fgetc(f))) {
118 if (k == *what) {
119 ++what;
120 while ((*what != '\0') && (*what == fgetc(f))) {
121 ++what;
122 }
123 if (*what == '\0') {
124 fclose(f);
125 return true;
126 } else {
127 what = search_string;
128 }
129 }
130 }
131 fclose(f);
132
133 // Did not find string in the proc file.
134 return false;
135}
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000136
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000137
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000138bool OS::ArmCpuHasFeature(CpuFeature feature) {
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000139 const char* search_string = NULL;
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000140 // Simple detection of VFP at runtime for Linux.
141 // It is based on /proc/cpuinfo, which reveals hardware configuration
142 // to user-space applications. According to ARM (mid 2009), no similar
143 // facility is universally available on the ARM architectures,
144 // so it's up to individual OSes to provide such.
145 switch (feature) {
146 case VFP3:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000147 search_string = "vfpv3";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000148 break;
149 case ARMv7:
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000150 search_string = "ARMv7";
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000151 break;
verwaest@chromium.org33e09c82012-10-10 17:07:22 +0000152 case SUDIV:
153 search_string = "idiva";
154 break;
yangguo@chromium.org003650e2013-01-24 16:31:08 +0000155 case VFP32DREGS:
156 // This case is handled specially below.
157 break;
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000158 default:
159 UNREACHABLE();
160 }
161
yangguo@chromium.org003650e2013-01-24 16:31:08 +0000162 if (feature == VFP32DREGS) {
163 return ArmCpuHasFeature(VFP3) && !CPUInfoContainsString("d16");
164 }
165
ager@chromium.org5f0c45f2010-12-17 08:51:21 +0000166 if (CPUInfoContainsString(search_string)) {
167 return true;
168 }
169
170 if (feature == VFP3) {
171 // Some old kernels will report vfp not vfpv3. Here we make a last attempt
172 // to detect vfpv3 by checking for vfp *and* neon, since neon is only
173 // available on architectures with vfpv3.
174 // Checking neon on its own is not enough as it is possible to have neon
175 // without vfp.
176 if (CPUInfoContainsString("vfp") && CPUInfoContainsString("neon")) {
lrn@chromium.orgfa943b72010-11-03 08:14:36 +0000177 return true;
178 }
179 }
180
181 return false;
182}
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000183
184
rossberg@chromium.org89e18f52012-10-22 13:09:53 +0000185CpuImplementer OS::GetCpuImplementer() {
186 static bool use_cached_value = false;
187 static CpuImplementer cached_value = UNKNOWN_IMPLEMENTER;
188 if (use_cached_value) {
189 return cached_value;
190 }
191 if (CPUInfoContainsString("CPU implementer\t: 0x41")) {
192 cached_value = ARM_IMPLEMENTER;
193 } else if (CPUInfoContainsString("CPU implementer\t: 0x51")) {
194 cached_value = QUALCOMM_IMPLEMENTER;
195 } else {
196 cached_value = UNKNOWN_IMPLEMENTER;
197 }
198 use_cached_value = true;
199 return cached_value;
200}
201
202
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000203bool OS::ArmUsingHardFloat() {
yangguo@chromium.orgc74d6742012-06-29 15:15:45 +0000204 // GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify
205 // the Floating Point ABI used (PCS stands for Procedure Call Standard).
206 // We use these as well as a couple of other defines to statically determine
207 // what FP ABI used.
208 // GCC versions 4.4 and below don't support hard-fp.
209 // GCC versions 4.5 may support hard-fp without defining __ARM_PCS or
210 // __ARM_PCS_VFP.
211
212#define GCC_VERSION (__GNUC__ * 10000 \
213 + __GNUC_MINOR__ * 100 \
214 + __GNUC_PATCHLEVEL__)
215#if GCC_VERSION >= 40600
216#if defined(__ARM_PCS_VFP)
217 return true;
218#else
219 return false;
220#endif
221
222#elif GCC_VERSION < 40500
223 return false;
224
225#else
226#if defined(__ARM_PCS_VFP)
227 return true;
228#elif defined(__ARM_PCS) || defined(__SOFTFP) || !defined(__VFP_FP__)
229 return false;
230#else
231#error "Your version of GCC does not report the FP ABI compiled for." \
232 "Please report it on this issue" \
233 "http://code.google.com/p/v8/issues/detail?id=2140"
234
235#endif
236#endif
237#undef GCC_VERSION
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000238}
yangguo@chromium.orgc74d6742012-06-29 15:15:45 +0000239
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000240#endif // def __arm__
241
242
lrn@chromium.org7516f052011-03-30 08:52:27 +0000243#ifdef __mips__
244bool OS::MipsCpuHasFeature(CpuFeature feature) {
245 const char* search_string = NULL;
246 const char* file_name = "/proc/cpuinfo";
247 // Simple detection of FPU at runtime for Linux.
248 // It is based on /proc/cpuinfo, which reveals hardware configuration
249 // to user-space applications. According to MIPS (early 2010), no similar
250 // facility is universally available on the MIPS architectures,
251 // so it's up to individual OSes to provide such.
252 //
253 // This is written as a straight shot one pass parser
254 // and not using STL string and ifstream because,
255 // on Linux, it's reading from a (non-mmap-able)
256 // character special device.
257
258 switch (feature) {
259 case FPU:
260 search_string = "FPU";
261 break;
262 default:
263 UNREACHABLE();
264 }
265
266 FILE* f = NULL;
267 const char* what = search_string;
268
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000269 if (NULL == (f = fopen(file_name, "r"))) {
270 OS::PrintError("Failed to open /proc/cpuinfo\n");
lrn@chromium.org7516f052011-03-30 08:52:27 +0000271 return false;
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000272 }
lrn@chromium.org7516f052011-03-30 08:52:27 +0000273
274 int k;
275 while (EOF != (k = fgetc(f))) {
276 if (k == *what) {
277 ++what;
278 while ((*what != '\0') && (*what == fgetc(f))) {
279 ++what;
280 }
281 if (*what == '\0') {
282 fclose(f);
283 return true;
284 } else {
285 what = search_string;
286 }
287 }
288 }
289 fclose(f);
290
291 // Did not find string in the proc file.
292 return false;
293}
294#endif // def __mips__
295
296
ager@chromium.org236ad962008-09-25 09:45:57 +0000297int OS::ActivationFrameAlignment() {
ager@chromium.orge2902be2009-06-08 12:21:35 +0000298#ifdef V8_TARGET_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000299 // On EABI ARM targets this is required for fp correctness in the
300 // runtime system.
ager@chromium.org3a6061e2009-03-12 14:24:36 +0000301 return 8;
ager@chromium.org5c838252010-02-19 08:53:10 +0000302#elif V8_TARGET_ARCH_MIPS
303 return 8;
304#endif
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000305 // With gcc 4.4 the tree vectorization optimizer can generate code
ager@chromium.orge2902be2009-06-08 12:21:35 +0000306 // that requires 16 byte alignment such as movdqa on x86.
307 return 16;
ager@chromium.org236ad962008-09-25 09:45:57 +0000308}
309
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000310
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000311void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
lrn@chromium.org7516f052011-03-30 08:52:27 +0000312#if (defined(V8_TARGET_ARCH_ARM) && defined(__arm__)) || \
313 (defined(V8_TARGET_ARCH_MIPS) && defined(__mips__))
314 // Only use on ARM or MIPS hardware.
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000315 MemoryBarrier();
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000316#else
317 __asm__ __volatile__("" : : : "memory");
318 // An x86 store acts as a release barrier.
319#endif
320 *ptr = value;
321}
322
323
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000324const char* OS::LocalTimezone(double time) {
325 if (isnan(time)) return "";
326 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
327 struct tm* t = localtime(&tv);
328 if (NULL == t) return "";
329 return t->tm_zone;
330}
331
332
333double OS::LocalTimeOffset() {
334 time_t tv = time(NULL);
335 struct tm* t = localtime(&tv);
336 // tm_gmtoff includes any daylight savings offset, so subtract it.
337 return static_cast<double>(t->tm_gmtoff * msPerSecond -
338 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
339}
340
341
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342// We keep the lowest and highest addresses mapped as a quick way of
343// determining that pointers are outside the heap (used mostly in assertions
ulan@chromium.org2efb9002012-01-19 15:36:35 +0000344// and verification). The estimate is conservative, i.e., not all addresses in
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000345// 'allocated' space are actually allocated to our heap. The range is
346// [lowest, highest), inclusive on the low and and exclusive on the high end.
347static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
348static void* highest_ever_allocated = reinterpret_cast<void*>(0);
349
350
351static void UpdateAllocatedSpaceLimits(void* address, int size) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000352 ASSERT(limit_mutex != NULL);
353 ScopedLock lock(limit_mutex);
354
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 lowest_ever_allocated = Min(lowest_ever_allocated, address);
356 highest_ever_allocated =
357 Max(highest_ever_allocated,
358 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
359}
360
361
362bool OS::IsOutsideAllocatedSpace(void* address) {
363 return address < lowest_ever_allocated || address >= highest_ever_allocated;
364}
365
366
367size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000368 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000369}
370
371
kasper.lund7276f142008-07-30 08:49:36 +0000372void* OS::Allocate(const size_t requested,
373 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000374 bool is_executable) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000375 const size_t msize = RoundUp(requested, AllocateAlignment());
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000376 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000377 void* addr = OS::GetRandomMmapAddr();
ricow@chromium.org9fa09672011-07-25 11:05:35 +0000378 void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379 if (mbase == MAP_FAILED) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000380 LOG(i::Isolate::Current(),
381 StringEvent("OS::Allocate", "mmap failed"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000382 return NULL;
383 }
384 *allocated = msize;
385 UpdateAllocatedSpaceLimits(mbase, msize);
386 return mbase;
387}
388
389
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000390void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000391 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000392 int result = munmap(address, size);
393 USE(result);
394 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000395}
396
397
398void OS::Sleep(int milliseconds) {
399 unsigned int ms = static_cast<unsigned int>(milliseconds);
400 usleep(1000 * ms);
401}
402
403
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +0000404int OS::NumberOfCores() {
405 return sysconf(_SC_NPROCESSORS_ONLN);
406}
407
408
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000409void OS::Abort() {
410 // Redirect to std abort to signal abnormal program termination.
rossberg@chromium.org2c067b12012-03-19 11:01:52 +0000411 if (FLAG_break_on_abort) {
412 DebugBreak();
413 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000414 abort();
415}
416
417
kasper.lund7276f142008-07-30 08:49:36 +0000418void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000419// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
420// which is the architecture of generated code).
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000421#if (defined(__arm__) || defined(__thumb__))
422# if defined(CAN_USE_ARMV5_INSTRUCTIONS)
kasper.lund7276f142008-07-30 08:49:36 +0000423 asm("bkpt 0");
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000424# endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000425#elif defined(__mips__)
426 asm("break");
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000427#elif defined(__native_client__)
428 asm("hlt");
kasper.lund7276f142008-07-30 08:49:36 +0000429#else
430 asm("int $3");
431#endif
432}
433
434
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000435void OS::DumpBacktrace() {
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000436#if defined(__GLIBC__) && !defined(__UCLIBC__)
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000437 void* trace[100];
438 int size = backtrace(trace, ARRAY_SIZE(trace));
439 char** symbols = backtrace_symbols(trace, size);
440 fprintf(stderr, "\n==== C stack trace ===============================\n\n");
441 if (size == 0) {
442 fprintf(stderr, "(empty)\n");
443 } else if (symbols == NULL) {
444 fprintf(stderr, "(no symbols)\n");
445 } else {
446 for (int i = 1; i < size; ++i) {
447 fprintf(stderr, "%2d: ", i);
448 char mangled[201];
449 if (sscanf(symbols[i], "%*[^(]%*[(]%200[^)+]", mangled) == 1) { // NOLINT
450 int status;
451 size_t length;
452 char* demangled = abi::__cxa_demangle(mangled, NULL, &length, &status);
453 fprintf(stderr, "%s\n", demangled ? demangled : mangled);
454 free(demangled);
455 } else {
456 fprintf(stderr, "??\n");
457 }
458 }
459 }
460 fflush(stderr);
461 free(symbols);
462#endif
463}
464
465
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000466class PosixMemoryMappedFile : public OS::MemoryMappedFile {
467 public:
468 PosixMemoryMappedFile(FILE* file, void* memory, int size)
469 : file_(file), memory_(memory), size_(size) { }
470 virtual ~PosixMemoryMappedFile();
471 virtual void* memory() { return memory_; }
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000472 virtual int size() { return size_; }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473 private:
474 FILE* file_;
475 void* memory_;
476 int size_;
477};
478
479
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000480OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
fschneider@chromium.org3a5fd782011-02-24 10:10:44 +0000481 FILE* file = fopen(name, "r+");
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000482 if (file == NULL) return NULL;
483
484 fseek(file, 0, SEEK_END);
485 int size = ftell(file);
486
487 void* memory =
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000488 mmap(OS::GetRandomMmapAddr(),
489 size,
490 PROT_READ | PROT_WRITE,
491 MAP_SHARED,
492 fileno(file),
493 0);
vegorov@chromium.org0a4e9012011-01-24 12:33:13 +0000494 return new PosixMemoryMappedFile(file, memory, size);
495}
496
497
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000498OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
499 void* initial) {
500 FILE* file = fopen(name, "w+");
501 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000502 int result = fwrite(initial, size, 1, file);
503 if (result < 1) {
504 fclose(file);
505 return NULL;
506 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507 void* memory =
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000508 mmap(OS::GetRandomMmapAddr(),
509 size,
510 PROT_READ | PROT_WRITE,
511 MAP_SHARED,
512 fileno(file),
513 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514 return new PosixMemoryMappedFile(file, memory, size);
515}
516
517
518PosixMemoryMappedFile::~PosixMemoryMappedFile() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000519 if (memory_) OS::Free(memory_, size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 fclose(file_);
521}
522
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000523
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000524void OS::LogSharedLibraryAddresses() {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000525 // This function assumes that the layout of the file is as follows:
526 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
527 // If we encounter an unexpected situation we abort scanning further entries.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000528 FILE* fp = fopen("/proc/self/maps", "r");
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000529 if (fp == NULL) return;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000530
531 // Allocate enough room to be able to store a full file name.
532 const int kLibNameLen = FILENAME_MAX + 1;
533 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
534
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000535 i::Isolate* isolate = ISOLATE;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000536 // This loop will terminate once the scanning hits an EOF.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000537 while (true) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000538 uintptr_t start, end;
539 char attr_r, attr_w, attr_x, attr_p;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000540 // Parse the addresses and permission bits at the beginning of the line.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000541 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
542 if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000543
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000544 int c;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000545 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
546 // Found a read-only executable entry. Skip characters until we reach
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000547 // the beginning of the filename or the end of the line.
548 do {
549 c = getc(fp);
yangguo@chromium.org46a2a512013-01-18 16:29:40 +0000550 } while ((c != EOF) && (c != '\n') && (c != '/') && (c != '['));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000551 if (c == EOF) break; // EOF: Was unexpected, just exit.
552
553 // Process the filename if found.
yangguo@chromium.org46a2a512013-01-18 16:29:40 +0000554 if ((c == '/') || (c == '[')) {
555 // Push the '/' or '[' back into the stream to be read below.
556 ungetc(c, fp);
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000557
558 // Read to the end of the line. Exit if the read fails.
559 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
560
561 // Drop the newline character read by fgets. We do not need to check
562 // for a zero-length string because we know that we at least read the
yangguo@chromium.org46a2a512013-01-18 16:29:40 +0000563 // '/' or '[' character.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000564 lib_name[strlen(lib_name) - 1] = '\0';
565 } else {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000566 // No library name found, just record the raw address range.
567 snprintf(lib_name, kLibNameLen,
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000568 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
569 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000570 LOG(isolate, SharedLibraryEvent(lib_name, start, end));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000571 } else {
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000572 // Entry not describing executable data. Skip to end of line to set up
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000573 // reading the next entry.
574 do {
575 c = getc(fp);
576 } while ((c != EOF) && (c != '\n'));
577 if (c == EOF) break;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000578 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579 }
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000580 free(lib_name);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000581 fclose(fp);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000582}
583
584
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000585void OS::SignalCodeMovingGC() {
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000586 // Support for ll_prof.py.
587 //
588 // The Linux profiler built into the kernel logs all mmap's with
589 // PROT_EXEC so that analysis tools can properly attribute ticks. We
590 // do a mmap with a name known by ll_prof.py and immediately munmap
591 // it. This injects a GC marker into the stream of events generated
592 // by the kernel and allows us to synchronize V8 code log and the
593 // kernel log.
594 int size = sysconf(_SC_PAGESIZE);
mstarzinger@chromium.orgde886792012-09-11 13:22:37 +0000595 FILE* f = fopen(FLAG_gc_fake_mmap, "w+");
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000596 void* addr = mmap(OS::GetRandomMmapAddr(),
597 size,
598 PROT_READ | PROT_EXEC,
599 MAP_PRIVATE,
600 fileno(f),
601 0);
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000602 ASSERT(addr != MAP_FAILED);
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000603 OS::Free(addr, size);
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000604 fclose(f);
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000605}
606
607
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000608int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000609 // backtrace is a glibc extension.
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000610#if defined(__GLIBC__) && !defined(__UCLIBC__)
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000611 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000612 ScopedVector<void*> addresses(frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000613
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000614 int frames_count = backtrace(addresses.start(), frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000615
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000616 char** symbols = backtrace_symbols(addresses.start(), frames_count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000617 if (symbols == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000618 return kStackWalkError;
619 }
620
621 for (int i = 0; i < frames_count; i++) {
622 frames[i].address = addresses[i];
623 // Format a text representation of the frame based on the information
624 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000625 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
626 "%s",
627 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000628 // Make sure line termination is in place.
629 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
630 }
631
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000632 free(symbols);
633
634 return frames_count;
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000635#else // defined(__GLIBC__) && !defined(__UCLIBC__)
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000636 return 0;
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000637#endif // defined(__GLIBC__) && !defined(__UCLIBC__)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000638}
639
640
641// Constants used for mmap.
642static const int kMmapFd = -1;
643static const int kMmapFdOffset = 0;
644
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000645
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000646VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000647
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000648
649VirtualMemory::VirtualMemory(size_t size)
650 : address_(ReserveRegion(size)), size_(size) { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000651
652
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000653VirtualMemory::VirtualMemory(size_t size, size_t alignment)
654 : address_(NULL), size_(0) {
655 ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
656 size_t request_size = RoundUp(size + alignment,
657 static_cast<intptr_t>(OS::AllocateAlignment()));
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000658 void* reservation = mmap(OS::GetRandomMmapAddr(),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000659 request_size,
660 PROT_NONE,
661 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
662 kMmapFd,
663 kMmapFdOffset);
664 if (reservation == MAP_FAILED) return;
665
666 Address base = static_cast<Address>(reservation);
667 Address aligned_base = RoundUp(base, alignment);
668 ASSERT_LE(base, aligned_base);
669
670 // Unmap extra memory reserved before and after the desired block.
671 if (aligned_base != base) {
672 size_t prefix_size = static_cast<size_t>(aligned_base - base);
673 OS::Free(base, prefix_size);
674 request_size -= prefix_size;
675 }
676
677 size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
678 ASSERT_LE(aligned_size, request_size);
679
680 if (aligned_size != request_size) {
681 size_t suffix_size = request_size - aligned_size;
682 OS::Free(aligned_base + aligned_size, suffix_size);
683 request_size -= suffix_size;
684 }
685
686 ASSERT(aligned_size == request_size);
687
688 address_ = static_cast<void*>(aligned_base);
689 size_ = aligned_size;
690}
691
692
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000693VirtualMemory::~VirtualMemory() {
694 if (IsReserved()) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000695 bool result = ReleaseRegion(address(), size());
696 ASSERT(result);
697 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000698 }
699}
700
701
702bool VirtualMemory::IsReserved() {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000703 return address_ != NULL;
704}
705
706
707void VirtualMemory::Reset() {
708 address_ = NULL;
709 size_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000710}
711
712
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000713bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000714 return CommitRegion(address, size, is_executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000715}
716
717
718bool VirtualMemory::Uncommit(void* address, size_t size) {
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000719 return UncommitRegion(address, size);
720}
721
722
yangguo@chromium.orgab30bb82012-02-24 14:41:46 +0000723bool VirtualMemory::Guard(void* address) {
724 OS::Guard(address, OS::CommitPageSize());
725 return true;
726}
727
728
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000729void* VirtualMemory::ReserveRegion(size_t size) {
rossberg@chromium.orgb4b2aa62011-10-13 09:49:59 +0000730 void* result = mmap(OS::GetRandomMmapAddr(),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000731 size,
732 PROT_NONE,
733 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
734 kMmapFd,
735 kMmapFdOffset);
736
737 if (result == MAP_FAILED) return NULL;
738
739 return result;
740}
741
742
743bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
744 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
745 if (MAP_FAILED == mmap(base,
746 size,
747 prot,
748 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
749 kMmapFd,
750 kMmapFdOffset)) {
751 return false;
752 }
753
754 UpdateAllocatedSpaceLimits(base, size);
755 return true;
756}
757
758
759bool VirtualMemory::UncommitRegion(void* base, size_t size) {
760 return mmap(base,
761 size,
762 PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000763 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +0000764 kMmapFd,
765 kMmapFdOffset) != MAP_FAILED;
766}
767
768
769bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
770 return munmap(base, size) == 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000771}
772
773
danno@chromium.org72204d52012-10-31 10:02:10 +0000774bool VirtualMemory::HasLazyCommits() {
775 return true;
776}
777
778
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000779class Thread::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000780 public:
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000781 PlatformData() : thread_(kNoThread) {}
ager@chromium.org41826e72009-03-30 13:30:57 +0000782
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000783 pthread_t thread_; // Thread handle for pthread.
784};
785
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000786Thread::Thread(const Options& options)
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000787 : data_(new PlatformData()),
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000788 stack_size_(options.stack_size()),
789 start_semaphore_(NULL) {
yangguo@chromium.org659ceec2012-01-26 07:37:54 +0000790 set_name(options.name());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000791}
792
793
794Thread::~Thread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000795 delete data_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000796}
797
798
799static void* ThreadEntry(void* arg) {
800 Thread* thread = reinterpret_cast<Thread*>(arg);
801 // This is also initialized by the first argument to pthread_create() but we
802 // don't know which thread will run first (the original thread or the new
803 // one) so we initialize it here too.
danno@chromium.orgb6451162011-08-17 14:33:23 +0000804#ifdef PR_SET_NAME
karlklose@chromium.org8f806e82011-03-07 14:06:08 +0000805 prctl(PR_SET_NAME,
806 reinterpret_cast<unsigned long>(thread->name()), // NOLINT
807 0, 0, 0);
danno@chromium.orgb6451162011-08-17 14:33:23 +0000808#endif
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000809 thread->data()->thread_ = pthread_self();
810 ASSERT(thread->data()->thread_ != kNoThread);
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000811 thread->NotifyStartedAndRun();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000812 return NULL;
813}
814
815
lrn@chromium.org5d00b602011-01-05 09:51:43 +0000816void Thread::set_name(const char* name) {
817 strncpy(name_, name, sizeof(name_));
818 name_[sizeof(name_) - 1] = '\0';
819}
820
821
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000822void Thread::Start() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000823 pthread_attr_t* attr_ptr = NULL;
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000824#if defined(__native_client__)
825 // use default stack size.
826#else
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000827 pthread_attr_t attr;
828 if (stack_size_ > 0) {
829 pthread_attr_init(&attr);
830 pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
831 attr_ptr = &attr;
832 }
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +0000833#endif
danno@chromium.orgc612e022011-11-10 11:38:15 +0000834 int result = pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
835 CHECK_EQ(0, result);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000836 ASSERT(data_->thread_ != kNoThread);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000837}
838
839
840void Thread::Join() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000841 pthread_join(data_->thread_, NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000842}
843
844
845Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
846 pthread_key_t key;
847 int result = pthread_key_create(&key, NULL);
848 USE(result);
849 ASSERT(result == 0);
850 return static_cast<LocalStorageKey>(key);
851}
852
853
854void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
855 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
856 int result = pthread_key_delete(pthread_key);
857 USE(result);
858 ASSERT(result == 0);
859}
860
861
862void* Thread::GetThreadLocal(LocalStorageKey key) {
863 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
864 return pthread_getspecific(pthread_key);
865}
866
867
868void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
869 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
870 pthread_setspecific(pthread_key, value);
871}
872
873
874void Thread::YieldCPU() {
875 sched_yield();
876}
877
878
879class LinuxMutex : public Mutex {
880 public:
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000881 LinuxMutex() {
882 pthread_mutexattr_t attrs;
883 int result = pthread_mutexattr_init(&attrs);
884 ASSERT(result == 0);
885 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
886 ASSERT(result == 0);
887 result = pthread_mutex_init(&mutex_, &attrs);
888 ASSERT(result == 0);
rossberg@chromium.org717967f2011-07-20 13:44:42 +0000889 USE(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000890 }
891
892 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
893
894 virtual int Lock() {
895 int result = pthread_mutex_lock(&mutex_);
896 return result;
897 }
898
899 virtual int Unlock() {
900 int result = pthread_mutex_unlock(&mutex_);
901 return result;
902 }
903
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000904 virtual bool TryLock() {
905 int result = pthread_mutex_trylock(&mutex_);
906 // Return false if the lock is busy and locking failed.
907 if (result == EBUSY) {
908 return false;
909 }
910 ASSERT(result == 0); // Verify no other errors.
911 return true;
912 }
913
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000914 private:
915 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
916};
917
918
919Mutex* OS::CreateMutex() {
920 return new LinuxMutex();
921}
922
923
924class LinuxSemaphore : public Semaphore {
925 public:
926 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
927 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
928
kasper.lund7276f142008-07-30 08:49:36 +0000929 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000930 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000931 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000932 private:
933 sem_t sem_;
934};
935
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000936
kasper.lund7276f142008-07-30 08:49:36 +0000937void LinuxSemaphore::Wait() {
938 while (true) {
939 int result = sem_wait(&sem_);
940 if (result == 0) return; // Successfully got semaphore.
941 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
942 }
943}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000944
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000945
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000946#ifndef TIMEVAL_TO_TIMESPEC
947#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
948 (ts)->tv_sec = (tv)->tv_sec; \
949 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
950} while (false)
951#endif
952
953
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000954bool LinuxSemaphore::Wait(int timeout) {
955 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000956
957 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000958 struct timeval delta;
959 delta.tv_usec = timeout % kOneSecondMicros;
960 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000961
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000962 struct timeval current_time;
963 // Get the current time.
964 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000965 return false;
966 }
967
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000968 // Calculate time for end of timeout.
969 struct timeval end_time;
970 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000971
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000972 struct timespec ts;
973 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000974 // Wait for semaphore signalled or timeout.
975 while (true) {
976 int result = sem_timedwait(&sem_, &ts);
977 if (result == 0) return true; // Successfully got semaphore.
978 if (result > 0) {
979 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
980 errno = result;
981 result = -1;
982 }
983 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
984 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
985 }
986}
987
988
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000989Semaphore* OS::CreateSemaphore(int count) {
990 return new LinuxSemaphore(count);
991}
992
ager@chromium.org381abbb2009-02-25 13:23:22 +0000993
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000994void OS::SetUp() {
995 // Seed the random number generator. We preserve microsecond resolution.
996 uint64_t seed = Ticks() ^ (getpid() << 16);
997 srandom(static_cast<unsigned int>(seed));
998 limit_mutex = CreateMutex();
fschneider@chromium.org7d10be52012-04-10 12:30:14 +0000999}
1000
1001
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00001002void OS::TearDown() {
erik.corry@gmail.comed49e962012-04-17 11:57:53 +00001003 delete limit_mutex;
1004}
1005
1006
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001007} } // namespace v8::internal