blob: c01c0d24b5a16a20dacc7fa3dae750e0764847f1 [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
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>
34#include <sys/time.h>
35#include <sys/resource.h>
ager@chromium.org381abbb2009-02-25 13:23:22 +000036#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
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000045#include <fcntl.h> // open
46#include <unistd.h> // sysconf
47#ifdef __GLIBC__
ager@chromium.org236ad962008-09-25 09:45:57 +000048#include <execinfo.h> // backtrace, backtrace_symbols
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000049#endif // def __GLIBC__
ager@chromium.org236ad962008-09-25 09:45:57 +000050#include <strings.h> // index
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051#include <errno.h>
52#include <stdarg.h>
53
54#undef MAP_TYPE
55
56#include "v8.h"
57
58#include "platform.h"
ager@chromium.orga1645e22009-09-09 19:27:10 +000059#include "top.h"
60#include "v8threads.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000061
62
kasperl@chromium.org71affb52009-05-26 05:44:31 +000063namespace v8 {
64namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065
66// 0 is never a valid thread id on Linux since tids and pids share a
67// name space and pid 0 is reserved (see man 2 kill).
68static const pthread_t kNoThread = (pthread_t) 0;
69
70
71double ceiling(double x) {
72 return ceil(x);
73}
74
75
76void OS::Setup() {
77 // Seed the random number generator.
ager@chromium.org9258b6b2008-09-11 09:11:10 +000078 // Convert the current time to a 64-bit integer first, before converting it
79 // to an unsigned. Going directly can cause an overflow and the seed to be
80 // set to all ones. The seed will be identical for different instances that
81 // call this setup code within the same millisecond.
82 uint64_t seed = static_cast<uint64_t>(TimeCurrentMillis());
83 srandom(static_cast<unsigned int>(seed));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000084}
85
86
ager@chromium.orgc4c92722009-11-18 14:12:51 +000087uint64_t OS::CpuFeaturesImpliedByPlatform() {
88#if (defined(__VFP_FP__) && !defined(__SOFTFP__))
89 // Here gcc is telling us that we are on an ARM and gcc is assuming that we
90 // have VFP3 instructions. If gcc can assume it then so can we.
91 return 1u << VFP3;
ager@chromium.org5c838252010-02-19 08:53:10 +000092#elif CAN_USE_ARMV7_INSTRUCTIONS
93 return 1u << ARMv7;
ager@chromium.orgc4c92722009-11-18 14:12:51 +000094#else
95 return 0; // Linux runs on anything.
96#endif
97}
98
99
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000100#ifdef __arm__
101bool OS::ArmCpuHasFeature(CpuFeature feature) {
102 const char* search_string = NULL;
103 const char* file_name = "/proc/cpuinfo";
104 // Simple detection of VFP at runtime for Linux.
105 // It is based on /proc/cpuinfo, which reveals hardware configuration
106 // to user-space applications. According to ARM (mid 2009), no similar
107 // facility is universally available on the ARM architectures,
108 // so it's up to individual OSes to provide such.
109 //
110 // This is written as a straight shot one pass parser
111 // and not using STL string and ifstream because,
112 // on Linux, it's reading from a (non-mmap-able)
113 // character special device.
114 switch (feature) {
115 case VFP3:
116 search_string = "vfp";
117 break;
ager@chromium.org5c838252010-02-19 08:53:10 +0000118 case ARMv7:
119 search_string = "ARMv7";
120 break;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000121 default:
122 UNREACHABLE();
123 }
124
125 FILE* f = NULL;
126 const char* what = search_string;
127
128 if (NULL == (f = fopen(file_name, "r")))
129 return false;
130
131 int k;
132 while (EOF != (k = fgetc(f))) {
133 if (k == *what) {
134 ++what;
135 while ((*what != '\0') && (*what == fgetc(f))) {
136 ++what;
137 }
138 if (*what == '\0') {
139 fclose(f);
140 return true;
141 } else {
142 what = search_string;
143 }
144 }
145 }
146 fclose(f);
147
148 // Did not find string in the proc file.
149 return false;
150}
151#endif // def __arm__
152
153
ager@chromium.org236ad962008-09-25 09:45:57 +0000154int OS::ActivationFrameAlignment() {
ager@chromium.orge2902be2009-06-08 12:21:35 +0000155#ifdef V8_TARGET_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000156 // On EABI ARM targets this is required for fp correctness in the
157 // runtime system.
ager@chromium.org3a6061e2009-03-12 14:24:36 +0000158 return 8;
ager@chromium.org5c838252010-02-19 08:53:10 +0000159#elif V8_TARGET_ARCH_MIPS
160 return 8;
161#endif
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000162 // With gcc 4.4 the tree vectorization optimizer can generate code
ager@chromium.orge2902be2009-06-08 12:21:35 +0000163 // that requires 16 byte alignment such as movdqa on x86.
164 return 16;
ager@chromium.org236ad962008-09-25 09:45:57 +0000165}
166
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000167
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000168#ifdef V8_TARGET_ARCH_ARM
169// 0xffff0fa0 is the hard coded address of a function provided by
170// the kernel which implements a memory barrier. On older
171// ARM architecture revisions (pre-v6) this may be implemented using
172// a syscall. This address is stable, and in active use (hard coded)
173// by at least glibc-2.7 and the Android C library.
174typedef void (*LinuxKernelMemoryBarrierFunc)(void);
175LinuxKernelMemoryBarrierFunc pLinuxKernelMemoryBarrier __attribute__((weak)) =
176 (LinuxKernelMemoryBarrierFunc) 0xffff0fa0;
177#endif
178
179void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
ricow@chromium.org30ce4112010-05-31 10:38:25 +0000180#if defined(V8_TARGET_ARCH_ARM) && defined(__arm__)
181 // Only use on ARM hardware.
kmillikin@chromium.org9155e252010-05-26 13:27:57 +0000182 pLinuxKernelMemoryBarrier();
183#else
184 __asm__ __volatile__("" : : : "memory");
185 // An x86 store acts as a release barrier.
186#endif
187 *ptr = value;
188}
189
190
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000191const char* OS::LocalTimezone(double time) {
192 if (isnan(time)) return "";
193 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
194 struct tm* t = localtime(&tv);
195 if (NULL == t) return "";
196 return t->tm_zone;
197}
198
199
200double OS::LocalTimeOffset() {
201 time_t tv = time(NULL);
202 struct tm* t = localtime(&tv);
203 // tm_gmtoff includes any daylight savings offset, so subtract it.
204 return static_cast<double>(t->tm_gmtoff * msPerSecond -
205 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
206}
207
208
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000209// We keep the lowest and highest addresses mapped as a quick way of
210// determining that pointers are outside the heap (used mostly in assertions
211// and verification). The estimate is conservative, ie, not all addresses in
212// 'allocated' space are actually allocated to our heap. The range is
213// [lowest, highest), inclusive on the low and and exclusive on the high end.
214static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
215static void* highest_ever_allocated = reinterpret_cast<void*>(0);
216
217
218static void UpdateAllocatedSpaceLimits(void* address, int size) {
219 lowest_ever_allocated = Min(lowest_ever_allocated, address);
220 highest_ever_allocated =
221 Max(highest_ever_allocated,
222 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
223}
224
225
226bool OS::IsOutsideAllocatedSpace(void* address) {
227 return address < lowest_ever_allocated || address >= highest_ever_allocated;
228}
229
230
231size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000232 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233}
234
235
kasper.lund7276f142008-07-30 08:49:36 +0000236void* OS::Allocate(const size_t requested,
237 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000238 bool is_executable) {
sgjesse@chromium.orgc3a01972010-08-04 09:46:24 +0000239 // TODO(805): Port randomization of allocated executable memory to Linux.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000240 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000241 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000242 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000243 if (mbase == MAP_FAILED) {
244 LOG(StringEvent("OS::Allocate", "mmap failed"));
245 return NULL;
246 }
247 *allocated = msize;
248 UpdateAllocatedSpaceLimits(mbase, msize);
249 return mbase;
250}
251
252
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000253void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000255 int result = munmap(address, size);
256 USE(result);
257 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000258}
259
260
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000261#ifdef ENABLE_HEAP_PROTECTION
262
263void OS::Protect(void* address, size_t size) {
264 // TODO(1240712): mprotect has a return value which is ignored here.
265 mprotect(address, size, PROT_READ);
266}
267
268
269void OS::Unprotect(void* address, size_t size, bool is_executable) {
270 // TODO(1240712): mprotect has a return value which is ignored here.
271 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
272 mprotect(address, size, prot);
273}
274
275#endif
276
277
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000278void OS::Sleep(int milliseconds) {
279 unsigned int ms = static_cast<unsigned int>(milliseconds);
280 usleep(1000 * ms);
281}
282
283
284void OS::Abort() {
285 // Redirect to std abort to signal abnormal program termination.
286 abort();
287}
288
289
kasper.lund7276f142008-07-30 08:49:36 +0000290void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000291// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
292// which is the architecture of generated code).
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000293#if (defined(__arm__) || defined(__thumb__))
294# if defined(CAN_USE_ARMV5_INSTRUCTIONS)
kasper.lund7276f142008-07-30 08:49:36 +0000295 asm("bkpt 0");
ager@chromium.orgea4f62e2010-08-16 16:28:43 +0000296# endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000297#elif defined(__mips__)
298 asm("break");
kasper.lund7276f142008-07-30 08:49:36 +0000299#else
300 asm("int $3");
301#endif
302}
303
304
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000305class PosixMemoryMappedFile : public OS::MemoryMappedFile {
306 public:
307 PosixMemoryMappedFile(FILE* file, void* memory, int size)
308 : file_(file), memory_(memory), size_(size) { }
309 virtual ~PosixMemoryMappedFile();
310 virtual void* memory() { return memory_; }
311 private:
312 FILE* file_;
313 void* memory_;
314 int size_;
315};
316
317
318OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
319 void* initial) {
320 FILE* file = fopen(name, "w+");
321 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000322 int result = fwrite(initial, size, 1, file);
323 if (result < 1) {
324 fclose(file);
325 return NULL;
326 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000327 void* memory =
328 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
329 return new PosixMemoryMappedFile(file, memory, size);
330}
331
332
333PosixMemoryMappedFile::~PosixMemoryMappedFile() {
334 if (memory_) munmap(memory_, size_);
335 fclose(file_);
336}
337
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339void OS::LogSharedLibraryAddresses() {
340#ifdef ENABLE_LOGGING_AND_PROFILING
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000341 // This function assumes that the layout of the file is as follows:
342 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
343 // If we encounter an unexpected situation we abort scanning further entries.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000344 FILE* fp = fopen("/proc/self/maps", "r");
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000345 if (fp == NULL) return;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000346
347 // Allocate enough room to be able to store a full file name.
348 const int kLibNameLen = FILENAME_MAX + 1;
349 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
350
351 // This loop will terminate once the scanning hits an EOF.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000352 while (true) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000353 uintptr_t start, end;
354 char attr_r, attr_w, attr_x, attr_p;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000355 // Parse the addresses and permission bits at the beginning of the line.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000356 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
357 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 +0000358
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000359 int c;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000360 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
361 // Found a read-only executable entry. Skip characters until we reach
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000362 // the beginning of the filename or the end of the line.
363 do {
364 c = getc(fp);
365 } while ((c != EOF) && (c != '\n') && (c != '/'));
366 if (c == EOF) break; // EOF: Was unexpected, just exit.
367
368 // Process the filename if found.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000369 if (c == '/') {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000370 ungetc(c, fp); // Push the '/' back into the stream to be read below.
371
372 // Read to the end of the line. Exit if the read fails.
373 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
374
375 // Drop the newline character read by fgets. We do not need to check
376 // for a zero-length string because we know that we at least read the
377 // '/' character.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000378 lib_name[strlen(lib_name) - 1] = '\0';
379 } else {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000380 // No library name found, just record the raw address range.
381 snprintf(lib_name, kLibNameLen,
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000382 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
383 }
384 LOG(SharedLibraryEvent(lib_name, start, end));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000385 } else {
386 // Entry not describing executable data. Skip to end of line to setup
387 // reading the next entry.
388 do {
389 c = getc(fp);
390 } while ((c != EOF) && (c != '\n'));
391 if (c == EOF) break;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000392 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393 }
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000394 free(lib_name);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000395 fclose(fp);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000396#endif
397}
398
399
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000400static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
401
402
403void OS::SignalCodeMovingGC() {
404#ifdef ENABLE_LOGGING_AND_PROFILING
405 // Support for ll_prof.py.
406 //
407 // The Linux profiler built into the kernel logs all mmap's with
408 // PROT_EXEC so that analysis tools can properly attribute ticks. We
409 // do a mmap with a name known by ll_prof.py and immediately munmap
410 // it. This injects a GC marker into the stream of events generated
411 // by the kernel and allows us to synchronize V8 code log and the
412 // kernel log.
413 int size = sysconf(_SC_PAGESIZE);
414 FILE* f = fopen(kGCFakeMmap, "w+");
415 void* addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE,
416 fileno(f), 0);
417 ASSERT(addr != MAP_FAILED);
418 munmap(addr, size);
419 fclose(f);
420#endif
421}
422
423
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000424int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000425 // backtrace is a glibc extension.
426#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000427 int frames_size = frames.length();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000428 ScopedVector<void*> addresses(frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000429
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000430 int frames_count = backtrace(addresses.start(), frames_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000431
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000432 char** symbols = backtrace_symbols(addresses.start(), frames_count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000433 if (symbols == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000434 return kStackWalkError;
435 }
436
437 for (int i = 0; i < frames_count; i++) {
438 frames[i].address = addresses[i];
439 // Format a text representation of the frame based on the information
440 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000441 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
442 "%s",
443 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000444 // Make sure line termination is in place.
445 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
446 }
447
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000448 free(symbols);
449
450 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000451#else // ndef __GLIBC__
452 return 0;
453#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000454}
455
456
457// Constants used for mmap.
458static const int kMmapFd = -1;
459static const int kMmapFdOffset = 0;
460
461
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000462VirtualMemory::VirtualMemory(size_t size) {
463 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000464 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
465 kMmapFd, kMmapFdOffset);
466 size_ = size;
467}
468
469
470VirtualMemory::~VirtualMemory() {
471 if (IsReserved()) {
472 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
473 }
474}
475
476
477bool VirtualMemory::IsReserved() {
478 return address_ != MAP_FAILED;
479}
480
481
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000482bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
483 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000484 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000485 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
486 kMmapFd, kMmapFdOffset)) {
487 return false;
488 }
489
490 UpdateAllocatedSpaceLimits(address, size);
491 return true;
492}
493
494
495bool VirtualMemory::Uncommit(void* address, size_t size) {
496 return mmap(address, size, PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000497 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000498 kMmapFd, kMmapFdOffset) != MAP_FAILED;
499}
500
501
502class ThreadHandle::PlatformData : public Malloced {
503 public:
504 explicit PlatformData(ThreadHandle::Kind kind) {
505 Initialize(kind);
506 }
507
508 void Initialize(ThreadHandle::Kind kind) {
509 switch (kind) {
510 case ThreadHandle::SELF: thread_ = pthread_self(); break;
511 case ThreadHandle::INVALID: thread_ = kNoThread; break;
512 }
513 }
ager@chromium.org41826e72009-03-30 13:30:57 +0000514
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000515 pthread_t thread_; // Thread handle for pthread.
516};
517
518
519ThreadHandle::ThreadHandle(Kind kind) {
520 data_ = new PlatformData(kind);
521}
522
523
524void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
525 data_->Initialize(kind);
526}
527
528
529ThreadHandle::~ThreadHandle() {
530 delete data_;
531}
532
533
534bool ThreadHandle::IsSelf() const {
535 return pthread_equal(data_->thread_, pthread_self());
536}
537
538
539bool ThreadHandle::IsValid() const {
540 return data_->thread_ != kNoThread;
541}
542
543
544Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
545}
546
547
548Thread::~Thread() {
549}
550
551
552static void* ThreadEntry(void* arg) {
553 Thread* thread = reinterpret_cast<Thread*>(arg);
554 // This is also initialized by the first argument to pthread_create() but we
555 // don't know which thread will run first (the original thread or the new
556 // one) so we initialize it here too.
557 thread->thread_handle_data()->thread_ = pthread_self();
558 ASSERT(thread->IsValid());
559 thread->Run();
560 return NULL;
561}
562
563
564void Thread::Start() {
565 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
566 ASSERT(IsValid());
567}
568
569
570void Thread::Join() {
571 pthread_join(thread_handle_data()->thread_, NULL);
572}
573
574
575Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
576 pthread_key_t key;
577 int result = pthread_key_create(&key, NULL);
578 USE(result);
579 ASSERT(result == 0);
580 return static_cast<LocalStorageKey>(key);
581}
582
583
584void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
585 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
586 int result = pthread_key_delete(pthread_key);
587 USE(result);
588 ASSERT(result == 0);
589}
590
591
592void* Thread::GetThreadLocal(LocalStorageKey key) {
593 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
594 return pthread_getspecific(pthread_key);
595}
596
597
598void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
599 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
600 pthread_setspecific(pthread_key, value);
601}
602
603
604void Thread::YieldCPU() {
605 sched_yield();
606}
607
608
609class LinuxMutex : public Mutex {
610 public:
611
612 LinuxMutex() {
613 pthread_mutexattr_t attrs;
614 int result = pthread_mutexattr_init(&attrs);
615 ASSERT(result == 0);
616 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
617 ASSERT(result == 0);
618 result = pthread_mutex_init(&mutex_, &attrs);
619 ASSERT(result == 0);
620 }
621
622 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
623
624 virtual int Lock() {
625 int result = pthread_mutex_lock(&mutex_);
626 return result;
627 }
628
629 virtual int Unlock() {
630 int result = pthread_mutex_unlock(&mutex_);
631 return result;
632 }
633
634 private:
635 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
636};
637
638
639Mutex* OS::CreateMutex() {
640 return new LinuxMutex();
641}
642
643
644class LinuxSemaphore : public Semaphore {
645 public:
646 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
647 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
648
kasper.lund7276f142008-07-30 08:49:36 +0000649 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000650 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000651 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000652 private:
653 sem_t sem_;
654};
655
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000656
kasper.lund7276f142008-07-30 08:49:36 +0000657void LinuxSemaphore::Wait() {
658 while (true) {
659 int result = sem_wait(&sem_);
660 if (result == 0) return; // Successfully got semaphore.
661 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
662 }
663}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000664
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000665
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000666#ifndef TIMEVAL_TO_TIMESPEC
667#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
668 (ts)->tv_sec = (tv)->tv_sec; \
669 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
670} while (false)
671#endif
672
673
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000674bool LinuxSemaphore::Wait(int timeout) {
675 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000676
677 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000678 struct timeval delta;
679 delta.tv_usec = timeout % kOneSecondMicros;
680 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000681
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000682 struct timeval current_time;
683 // Get the current time.
684 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000685 return false;
686 }
687
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000688 // Calculate time for end of timeout.
689 struct timeval end_time;
690 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000691
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000692 struct timespec ts;
693 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000694 // Wait for semaphore signalled or timeout.
695 while (true) {
696 int result = sem_timedwait(&sem_, &ts);
697 if (result == 0) return true; // Successfully got semaphore.
698 if (result > 0) {
699 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
700 errno = result;
701 result = -1;
702 }
703 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
704 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
705 }
706}
707
708
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000709Semaphore* OS::CreateSemaphore(int count) {
710 return new LinuxSemaphore(count);
711}
712
ager@chromium.org381abbb2009-02-25 13:23:22 +0000713
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000714#ifdef ENABLE_LOGGING_AND_PROFILING
715
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000716static Sampler* active_sampler_ = NULL;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000717static pthread_t vm_thread_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000718
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000719
720#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
721// Android runs a fairly new Linux kernel, so signal info is there,
722// but the C library doesn't have the structs defined.
723
724struct sigcontext {
725 uint32_t trap_no;
726 uint32_t error_code;
727 uint32_t oldmask;
728 uint32_t gregs[16];
729 uint32_t arm_cpsr;
730 uint32_t fault_address;
731};
732typedef uint32_t __sigset_t;
733typedef struct sigcontext mcontext_t;
734typedef struct ucontext {
735 uint32_t uc_flags;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000736 struct ucontext* uc_link;
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000737 stack_t uc_stack;
738 mcontext_t uc_mcontext;
739 __sigset_t uc_sigmask;
740} ucontext_t;
741enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
742
743#endif
744
745
ager@chromium.orga1645e22009-09-09 19:27:10 +0000746// A function that determines if a signal handler is called in the context
747// of a VM thread.
748//
749// The problem is that SIGPROF signal can be delivered to an arbitrary thread
750// (see http://code.google.com/p/google-perftools/issues/detail?id=106#c2)
751// So, if the signal is being handled in the context of a non-VM thread,
752// it means that the VM thread is running, and trying to sample its stack can
753// cause a crash.
754static inline bool IsVmThread() {
755 // In the case of a single VM thread, this check is enough.
756 if (pthread_equal(pthread_self(), vm_thread_)) return true;
757 // If there are multiple threads that use VM, they must have a thread id
758 // stored in TLS. To verify that the thread is really executing VM,
759 // we check Top's data. Having that ThreadManager::RestoreThread first
760 // restores ThreadLocalTop from TLS, and only then erases the TLS value,
761 // reading Top::thread_id() should not be affected by races.
762 if (ThreadManager::HasId() && !ThreadManager::IsArchived() &&
763 ThreadManager::CurrentId() == Top::thread_id()) {
764 return true;
765 }
766 return false;
767}
768
769
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000770static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.org5c838252010-02-19 08:53:10 +0000771#ifndef V8_HOST_ARCH_MIPS
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000772 USE(info);
773 if (signal != SIGPROF) return;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000774 if (active_sampler_ == NULL) return;
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000775 if (!IsVmThread()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000776
lrn@chromium.org25156de2010-04-06 13:10:27 +0000777 TickSample sample_obj;
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000778 TickSample* sample = CpuProfiler::TickSampleEvent();
ager@chromium.org357bf652010-04-12 11:30:10 +0000779 if (sample == NULL) sample = &sample_obj;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000780
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000781 // We always sample the VM state.
ager@chromium.org357bf652010-04-12 11:30:10 +0000782 sample->state = VMState::current_state();
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000783
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000784 // If profiling, we extract the current pc and sp.
785 if (active_sampler_->IsProfiling()) {
786 // Extracting the sample from the context is extremely machine dependent.
787 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
788 mcontext_t& mcontext = ucontext->uc_mcontext;
ager@chromium.org9085a012009-05-11 19:22:57 +0000789#if V8_HOST_ARCH_IA32
ager@chromium.org357bf652010-04-12 11:30:10 +0000790 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
791 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
792 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000793#elif V8_HOST_ARCH_X64
ager@chromium.org357bf652010-04-12 11:30:10 +0000794 sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
795 sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
796 sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000797#elif V8_HOST_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000798// An undefined macro evaluates to 0, so this applies to Android's Bionic also.
799#if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
ager@chromium.org357bf652010-04-12 11:30:10 +0000800 sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
801 sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
802 sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000803#else
ager@chromium.org357bf652010-04-12 11:30:10 +0000804 sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
805 sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
806 sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000807#endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000808#elif V8_HOST_ARCH_MIPS
809 // Implement this on MIPS.
ager@chromium.org357bf652010-04-12 11:30:10 +0000810 UNIMPLEMENTED();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000811#endif
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000812 active_sampler_->SampleStack(sample);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000813 }
ager@chromium.org357bf652010-04-12 11:30:10 +0000814
lrn@chromium.org25156de2010-04-06 13:10:27 +0000815 active_sampler_->Tick(sample);
816#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817}
818
819
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000820class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000821 public:
822 PlatformData() {
823 signal_handler_installed_ = false;
824 }
825
826 bool signal_handler_installed_;
827 struct sigaction old_signal_handler_;
828 struct itimerval old_timer_value_;
829};
830
831
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000832Sampler::Sampler(int interval, bool profiling)
whesse@chromium.org4a5224e2010-10-20 12:37:07 +0000833 : interval_(interval),
834 profiling_(profiling),
835 synchronous_(profiling),
836 active_(false) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000837 data_ = new PlatformData();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838}
839
840
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000841Sampler::~Sampler() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000842 delete data_;
843}
844
845
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000846void Sampler::Start() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000847 // There can only be one active sampler at the time on POSIX
848 // platforms.
849 if (active_sampler_ != NULL) return;
850
ager@chromium.orga1645e22009-09-09 19:27:10 +0000851 vm_thread_ = pthread_self();
852
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000853 // Request profiling signals.
854 struct sigaction sa;
855 sa.sa_sigaction = ProfilerSignalHandler;
856 sigemptyset(&sa.sa_mask);
857 sa.sa_flags = SA_SIGINFO;
858 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
859 data_->signal_handler_installed_ = true;
860
861 // Set the itimer to generate a tick for each interval.
862 itimerval itimer;
863 itimer.it_interval.tv_sec = interval_ / 1000;
864 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
865 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
866 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
867 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
868
869 // Set this sampler as the active sampler.
870 active_sampler_ = this;
871 active_ = true;
872}
873
874
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000875void Sampler::Stop() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000876 // Restore old signal handler
877 if (data_->signal_handler_installed_) {
878 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
879 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
880 data_->signal_handler_installed_ = false;
881 }
882
883 // This sampler is no longer the active sampler.
884 active_sampler_ = NULL;
885 active_ = false;
886}
887
ager@chromium.orga1645e22009-09-09 19:27:10 +0000888
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000889#endif // ENABLE_LOGGING_AND_PROFILING
890
891} } // namespace v8::internal