blob: f1812ff20513a937b0b1f13e00698cb5009e219d [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
ager@chromium.orge2902be2009-06-08 12:21:35 +0000162 // With gcc 4.4 the tree vectorization optimiser can generate code
163 // 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
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000168const char* OS::LocalTimezone(double time) {
169 if (isnan(time)) return "";
170 time_t tv = static_cast<time_t>(floor(time/msPerSecond));
171 struct tm* t = localtime(&tv);
172 if (NULL == t) return "";
173 return t->tm_zone;
174}
175
176
177double OS::LocalTimeOffset() {
178 time_t tv = time(NULL);
179 struct tm* t = localtime(&tv);
180 // tm_gmtoff includes any daylight savings offset, so subtract it.
181 return static_cast<double>(t->tm_gmtoff * msPerSecond -
182 (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
183}
184
185
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000186// We keep the lowest and highest addresses mapped as a quick way of
187// determining that pointers are outside the heap (used mostly in assertions
188// and verification). The estimate is conservative, ie, not all addresses in
189// 'allocated' space are actually allocated to our heap. The range is
190// [lowest, highest), inclusive on the low and and exclusive on the high end.
191static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
192static void* highest_ever_allocated = reinterpret_cast<void*>(0);
193
194
195static void UpdateAllocatedSpaceLimits(void* address, int size) {
196 lowest_ever_allocated = Min(lowest_ever_allocated, address);
197 highest_ever_allocated =
198 Max(highest_ever_allocated,
199 reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
200}
201
202
203bool OS::IsOutsideAllocatedSpace(void* address) {
204 return address < lowest_ever_allocated || address >= highest_ever_allocated;
205}
206
207
208size_t OS::AllocateAlignment() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000209 return sysconf(_SC_PAGESIZE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000210}
211
212
kasper.lund7276f142008-07-30 08:49:36 +0000213void* OS::Allocate(const size_t requested,
214 size_t* allocated,
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000215 bool is_executable) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000216 const size_t msize = RoundUp(requested, sysconf(_SC_PAGESIZE));
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000217 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000218 void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000219 if (mbase == MAP_FAILED) {
220 LOG(StringEvent("OS::Allocate", "mmap failed"));
221 return NULL;
222 }
223 *allocated = msize;
224 UpdateAllocatedSpaceLimits(mbase, msize);
225 return mbase;
226}
227
228
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000229void OS::Free(void* address, const size_t size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000230 // TODO(1240712): munmap has a return value which is ignored here.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000231 int result = munmap(address, size);
232 USE(result);
233 ASSERT(result == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000234}
235
236
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000237#ifdef ENABLE_HEAP_PROTECTION
238
239void OS::Protect(void* address, size_t size) {
240 // TODO(1240712): mprotect has a return value which is ignored here.
241 mprotect(address, size, PROT_READ);
242}
243
244
245void OS::Unprotect(void* address, size_t size, bool is_executable) {
246 // TODO(1240712): mprotect has a return value which is ignored here.
247 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
248 mprotect(address, size, prot);
249}
250
251#endif
252
253
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254void OS::Sleep(int milliseconds) {
255 unsigned int ms = static_cast<unsigned int>(milliseconds);
256 usleep(1000 * ms);
257}
258
259
260void OS::Abort() {
261 // Redirect to std abort to signal abnormal program termination.
262 abort();
263}
264
265
kasper.lund7276f142008-07-30 08:49:36 +0000266void OS::DebugBreak() {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000267// TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
268// which is the architecture of generated code).
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000269#if defined(__arm__) || defined(__thumb__)
kasper.lund7276f142008-07-30 08:49:36 +0000270 asm("bkpt 0");
ager@chromium.org5c838252010-02-19 08:53:10 +0000271#elif defined(__mips__)
272 asm("break");
kasper.lund7276f142008-07-30 08:49:36 +0000273#else
274 asm("int $3");
275#endif
276}
277
278
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000279class PosixMemoryMappedFile : public OS::MemoryMappedFile {
280 public:
281 PosixMemoryMappedFile(FILE* file, void* memory, int size)
282 : file_(file), memory_(memory), size_(size) { }
283 virtual ~PosixMemoryMappedFile();
284 virtual void* memory() { return memory_; }
285 private:
286 FILE* file_;
287 void* memory_;
288 int size_;
289};
290
291
292OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
293 void* initial) {
294 FILE* file = fopen(name, "w+");
295 if (file == NULL) return NULL;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000296 int result = fwrite(initial, size, 1, file);
297 if (result < 1) {
298 fclose(file);
299 return NULL;
300 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000301 void* memory =
302 mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
303 return new PosixMemoryMappedFile(file, memory, size);
304}
305
306
307PosixMemoryMappedFile::~PosixMemoryMappedFile() {
308 if (memory_) munmap(memory_, size_);
309 fclose(file_);
310}
311
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000312
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000313void OS::LogSharedLibraryAddresses() {
314#ifdef ENABLE_LOGGING_AND_PROFILING
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000315 // This function assumes that the layout of the file is as follows:
316 // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
317 // If we encounter an unexpected situation we abort scanning further entries.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000318 FILE* fp = fopen("/proc/self/maps", "r");
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000319 if (fp == NULL) return;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000320
321 // Allocate enough room to be able to store a full file name.
322 const int kLibNameLen = FILENAME_MAX + 1;
323 char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
324
325 // This loop will terminate once the scanning hits an EOF.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000326 while (true) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000327 uintptr_t start, end;
328 char attr_r, attr_w, attr_x, attr_p;
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000329 // Parse the addresses and permission bits at the beginning of the line.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000330 if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
331 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 +0000332
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000333 int c;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000334 if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
335 // Found a read-only executable entry. Skip characters until we reach
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000336 // the beginning of the filename or the end of the line.
337 do {
338 c = getc(fp);
339 } while ((c != EOF) && (c != '\n') && (c != '/'));
340 if (c == EOF) break; // EOF: Was unexpected, just exit.
341
342 // Process the filename if found.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000343 if (c == '/') {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000344 ungetc(c, fp); // Push the '/' back into the stream to be read below.
345
346 // Read to the end of the line. Exit if the read fails.
347 if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
348
349 // Drop the newline character read by fgets. We do not need to check
350 // for a zero-length string because we know that we at least read the
351 // '/' character.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000352 lib_name[strlen(lib_name) - 1] = '\0';
353 } else {
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000354 // No library name found, just record the raw address range.
355 snprintf(lib_name, kLibNameLen,
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000356 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
357 }
358 LOG(SharedLibraryEvent(lib_name, start, end));
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000359 } else {
360 // Entry not describing executable data. Skip to end of line to setup
361 // reading the next entry.
362 do {
363 c = getc(fp);
364 } while ((c != EOF) && (c != '\n'));
365 if (c == EOF) break;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000366 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000367 }
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000368 free(lib_name);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000369 fclose(fp);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000370#endif
371}
372
373
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000374int OS::StackWalk(Vector<OS::StackFrame> frames) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000375 // backtrace is a glibc extension.
376#ifdef __GLIBC__
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000377 int frames_size = frames.length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000378 void** addresses = NewArray<void*>(frames_size);
379
380 int frames_count = backtrace(addresses, frames_size);
381
382 char** symbols;
383 symbols = backtrace_symbols(addresses, frames_count);
384 if (symbols == NULL) {
385 DeleteArray(addresses);
386 return kStackWalkError;
387 }
388
389 for (int i = 0; i < frames_count; i++) {
390 frames[i].address = addresses[i];
391 // Format a text representation of the frame based on the information
392 // available.
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000393 SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
394 "%s",
395 symbols[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000396 // Make sure line termination is in place.
397 frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
398 }
399
400 DeleteArray(addresses);
401 free(symbols);
402
403 return frames_count;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000404#else // ndef __GLIBC__
405 return 0;
406#endif // ndef __GLIBC__
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000407}
408
409
410// Constants used for mmap.
411static const int kMmapFd = -1;
412static const int kMmapFdOffset = 0;
413
414
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000415VirtualMemory::VirtualMemory(size_t size) {
416 address_ = mmap(NULL, size, PROT_NONE,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000417 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
418 kMmapFd, kMmapFdOffset);
419 size_ = size;
420}
421
422
423VirtualMemory::~VirtualMemory() {
424 if (IsReserved()) {
425 if (0 == munmap(address(), size())) address_ = MAP_FAILED;
426 }
427}
428
429
430bool VirtualMemory::IsReserved() {
431 return address_ != MAP_FAILED;
432}
433
434
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000435bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
436 int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
kasper.lund7276f142008-07-30 08:49:36 +0000437 if (MAP_FAILED == mmap(address, size, prot,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000438 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
439 kMmapFd, kMmapFdOffset)) {
440 return false;
441 }
442
443 UpdateAllocatedSpaceLimits(address, size);
444 return true;
445}
446
447
448bool VirtualMemory::Uncommit(void* address, size_t size) {
449 return mmap(address, size, PROT_NONE,
ager@chromium.orga1645e22009-09-09 19:27:10 +0000450 MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000451 kMmapFd, kMmapFdOffset) != MAP_FAILED;
452}
453
454
455class ThreadHandle::PlatformData : public Malloced {
456 public:
457 explicit PlatformData(ThreadHandle::Kind kind) {
458 Initialize(kind);
459 }
460
461 void Initialize(ThreadHandle::Kind kind) {
462 switch (kind) {
463 case ThreadHandle::SELF: thread_ = pthread_self(); break;
464 case ThreadHandle::INVALID: thread_ = kNoThread; break;
465 }
466 }
ager@chromium.org41826e72009-03-30 13:30:57 +0000467
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468 pthread_t thread_; // Thread handle for pthread.
469};
470
471
472ThreadHandle::ThreadHandle(Kind kind) {
473 data_ = new PlatformData(kind);
474}
475
476
477void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
478 data_->Initialize(kind);
479}
480
481
482ThreadHandle::~ThreadHandle() {
483 delete data_;
484}
485
486
487bool ThreadHandle::IsSelf() const {
488 return pthread_equal(data_->thread_, pthread_self());
489}
490
491
492bool ThreadHandle::IsValid() const {
493 return data_->thread_ != kNoThread;
494}
495
496
497Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
498}
499
500
501Thread::~Thread() {
502}
503
504
505static void* ThreadEntry(void* arg) {
506 Thread* thread = reinterpret_cast<Thread*>(arg);
507 // This is also initialized by the first argument to pthread_create() but we
508 // don't know which thread will run first (the original thread or the new
509 // one) so we initialize it here too.
510 thread->thread_handle_data()->thread_ = pthread_self();
511 ASSERT(thread->IsValid());
512 thread->Run();
513 return NULL;
514}
515
516
517void Thread::Start() {
518 pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
519 ASSERT(IsValid());
520}
521
522
523void Thread::Join() {
524 pthread_join(thread_handle_data()->thread_, NULL);
525}
526
527
528Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
529 pthread_key_t key;
530 int result = pthread_key_create(&key, NULL);
531 USE(result);
532 ASSERT(result == 0);
533 return static_cast<LocalStorageKey>(key);
534}
535
536
537void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
538 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
539 int result = pthread_key_delete(pthread_key);
540 USE(result);
541 ASSERT(result == 0);
542}
543
544
545void* Thread::GetThreadLocal(LocalStorageKey key) {
546 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
547 return pthread_getspecific(pthread_key);
548}
549
550
551void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
552 pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
553 pthread_setspecific(pthread_key, value);
554}
555
556
557void Thread::YieldCPU() {
558 sched_yield();
559}
560
561
562class LinuxMutex : public Mutex {
563 public:
564
565 LinuxMutex() {
566 pthread_mutexattr_t attrs;
567 int result = pthread_mutexattr_init(&attrs);
568 ASSERT(result == 0);
569 result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
570 ASSERT(result == 0);
571 result = pthread_mutex_init(&mutex_, &attrs);
572 ASSERT(result == 0);
573 }
574
575 virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
576
577 virtual int Lock() {
578 int result = pthread_mutex_lock(&mutex_);
579 return result;
580 }
581
582 virtual int Unlock() {
583 int result = pthread_mutex_unlock(&mutex_);
584 return result;
585 }
586
587 private:
588 pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms.
589};
590
591
592Mutex* OS::CreateMutex() {
593 return new LinuxMutex();
594}
595
596
597class LinuxSemaphore : public Semaphore {
598 public:
599 explicit LinuxSemaphore(int count) { sem_init(&sem_, 0, count); }
600 virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
601
kasper.lund7276f142008-07-30 08:49:36 +0000602 virtual void Wait();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000603 virtual bool Wait(int timeout);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604 virtual void Signal() { sem_post(&sem_); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000605 private:
606 sem_t sem_;
607};
608
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000609
kasper.lund7276f142008-07-30 08:49:36 +0000610void LinuxSemaphore::Wait() {
611 while (true) {
612 int result = sem_wait(&sem_);
613 if (result == 0) return; // Successfully got semaphore.
614 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
615 }
616}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000617
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000618
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000619#ifndef TIMEVAL_TO_TIMESPEC
620#define TIMEVAL_TO_TIMESPEC(tv, ts) do { \
621 (ts)->tv_sec = (tv)->tv_sec; \
622 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
623} while (false)
624#endif
625
626
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000627bool LinuxSemaphore::Wait(int timeout) {
628 const long kOneSecondMicros = 1000000; // NOLINT
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000629
630 // Split timeout into second and nanosecond parts.
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000631 struct timeval delta;
632 delta.tv_usec = timeout % kOneSecondMicros;
633 delta.tv_sec = timeout / kOneSecondMicros;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000634
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000635 struct timeval current_time;
636 // Get the current time.
637 if (gettimeofday(&current_time, NULL) == -1) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000638 return false;
639 }
640
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000641 // Calculate time for end of timeout.
642 struct timeval end_time;
643 timeradd(&current_time, &delta, &end_time);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000644
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000645 struct timespec ts;
646 TIMEVAL_TO_TIMESPEC(&end_time, &ts);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000647 // Wait for semaphore signalled or timeout.
648 while (true) {
649 int result = sem_timedwait(&sem_, &ts);
650 if (result == 0) return true; // Successfully got semaphore.
651 if (result > 0) {
652 // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
653 errno = result;
654 result = -1;
655 }
656 if (result == -1 && errno == ETIMEDOUT) return false; // Timeout.
657 CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup.
658 }
659}
660
661
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000662Semaphore* OS::CreateSemaphore(int count) {
663 return new LinuxSemaphore(count);
664}
665
ager@chromium.org381abbb2009-02-25 13:23:22 +0000666
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000667#ifdef ENABLE_LOGGING_AND_PROFILING
668
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000669static Sampler* active_sampler_ = NULL;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000670static pthread_t vm_thread_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000671
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000672
673#if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
674// Android runs a fairly new Linux kernel, so signal info is there,
675// but the C library doesn't have the structs defined.
676
677struct sigcontext {
678 uint32_t trap_no;
679 uint32_t error_code;
680 uint32_t oldmask;
681 uint32_t gregs[16];
682 uint32_t arm_cpsr;
683 uint32_t fault_address;
684};
685typedef uint32_t __sigset_t;
686typedef struct sigcontext mcontext_t;
687typedef struct ucontext {
688 uint32_t uc_flags;
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000689 struct ucontext* uc_link;
kasperl@chromium.orgacae3782009-04-11 09:17:08 +0000690 stack_t uc_stack;
691 mcontext_t uc_mcontext;
692 __sigset_t uc_sigmask;
693} ucontext_t;
694enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
695
696#endif
697
698
ager@chromium.orga1645e22009-09-09 19:27:10 +0000699// A function that determines if a signal handler is called in the context
700// of a VM thread.
701//
702// The problem is that SIGPROF signal can be delivered to an arbitrary thread
703// (see http://code.google.com/p/google-perftools/issues/detail?id=106#c2)
704// So, if the signal is being handled in the context of a non-VM thread,
705// it means that the VM thread is running, and trying to sample its stack can
706// cause a crash.
707static inline bool IsVmThread() {
708 // In the case of a single VM thread, this check is enough.
709 if (pthread_equal(pthread_self(), vm_thread_)) return true;
710 // If there are multiple threads that use VM, they must have a thread id
711 // stored in TLS. To verify that the thread is really executing VM,
712 // we check Top's data. Having that ThreadManager::RestoreThread first
713 // restores ThreadLocalTop from TLS, and only then erases the TLS value,
714 // reading Top::thread_id() should not be affected by races.
715 if (ThreadManager::HasId() && !ThreadManager::IsArchived() &&
716 ThreadManager::CurrentId() == Top::thread_id()) {
717 return true;
718 }
719 return false;
720}
721
722
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000723static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
ager@chromium.org5c838252010-02-19 08:53:10 +0000724#ifndef V8_HOST_ARCH_MIPS
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000725 USE(info);
726 if (signal != SIGPROF) return;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000727 if (active_sampler_ == NULL) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000728
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000729 TickSample sample;
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000730
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000731 // We always sample the VM state.
732 sample.state = Logger::state();
733
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000734 // If profiling, we extract the current pc and sp.
735 if (active_sampler_->IsProfiling()) {
736 // Extracting the sample from the context is extremely machine dependent.
737 ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
738 mcontext_t& mcontext = ucontext->uc_mcontext;
ager@chromium.org9085a012009-05-11 19:22:57 +0000739#if V8_HOST_ARCH_IA32
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000740 sample.pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
741 sample.sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
742 sample.fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000743#elif V8_HOST_ARCH_X64
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000744 sample.pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
745 sample.sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
746 sample.fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
ager@chromium.org9085a012009-05-11 19:22:57 +0000747#elif V8_HOST_ARCH_ARM
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000748// An undefined macro evaluates to 0, so this applies to Android's Bionic also.
749#if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000750 sample.pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
751 sample.sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
752 sample.fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000753#else
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000754 sample.pc = reinterpret_cast<Address>(mcontext.arm_pc);
755 sample.sp = reinterpret_cast<Address>(mcontext.arm_sp);
756 sample.fp = reinterpret_cast<Address>(mcontext.arm_fp);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000757#endif
ager@chromium.org5c838252010-02-19 08:53:10 +0000758#elif V8_HOST_ARCH_MIPS
759 // Implement this on MIPS.
760 UNIMPLEMENTED();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000761#endif
ager@chromium.orga1645e22009-09-09 19:27:10 +0000762 if (IsVmThread())
763 active_sampler_->SampleStack(&sample);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000764 }
765
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 active_sampler_->Tick(&sample);
ager@chromium.org5c838252010-02-19 08:53:10 +0000767#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000768}
769
770
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000771class Sampler::PlatformData : public Malloced {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000772 public:
773 PlatformData() {
774 signal_handler_installed_ = false;
775 }
776
777 bool signal_handler_installed_;
778 struct sigaction old_signal_handler_;
779 struct itimerval old_timer_value_;
780};
781
782
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000783Sampler::Sampler(int interval, bool profiling)
784 : interval_(interval), profiling_(profiling), active_(false) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000785 data_ = new PlatformData();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000786}
787
788
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000789Sampler::~Sampler() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000790 delete data_;
791}
792
793
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000794void Sampler::Start() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000795 // There can only be one active sampler at the time on POSIX
796 // platforms.
797 if (active_sampler_ != NULL) return;
798
ager@chromium.orga1645e22009-09-09 19:27:10 +0000799 vm_thread_ = pthread_self();
800
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000801 // Request profiling signals.
802 struct sigaction sa;
803 sa.sa_sigaction = ProfilerSignalHandler;
804 sigemptyset(&sa.sa_mask);
805 sa.sa_flags = SA_SIGINFO;
806 if (sigaction(SIGPROF, &sa, &data_->old_signal_handler_) != 0) return;
807 data_->signal_handler_installed_ = true;
808
809 // Set the itimer to generate a tick for each interval.
810 itimerval itimer;
811 itimer.it_interval.tv_sec = interval_ / 1000;
812 itimer.it_interval.tv_usec = (interval_ % 1000) * 1000;
813 itimer.it_value.tv_sec = itimer.it_interval.tv_sec;
814 itimer.it_value.tv_usec = itimer.it_interval.tv_usec;
815 setitimer(ITIMER_PROF, &itimer, &data_->old_timer_value_);
816
817 // Set this sampler as the active sampler.
818 active_sampler_ = this;
819 active_ = true;
820}
821
822
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000823void Sampler::Stop() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000824 // Restore old signal handler
825 if (data_->signal_handler_installed_) {
826 setitimer(ITIMER_PROF, &data_->old_timer_value_, NULL);
827 sigaction(SIGPROF, &data_->old_signal_handler_, 0);
828 data_->signal_handler_installed_ = false;
829 }
830
831 // This sampler is no longer the active sampler.
832 active_sampler_ = NULL;
833 active_ = false;
834}
835
ager@chromium.orga1645e22009-09-09 19:27:10 +0000836
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000837#endif // ENABLE_LOGGING_AND_PROFILING
838
839} } // namespace v8::internal