[V8] uclibc: __GLIBC__ might be defined on uclibc builds
[profile/ivi/qtjsbackend.git] / src / 3rdparty / v8 / src / platform-linux.cc
1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 // Platform specific code for Linux goes here. For the POSIX comaptible parts
29 // the implementation is in platform-posix.cc.
30
31 #include <pthread.h>
32 #include <semaphore.h>
33 #include <signal.h>
34 #include <sys/prctl.h>
35 #include <sys/time.h>
36 #include <sys/resource.h>
37 #include <sys/syscall.h>
38 #include <sys/types.h>
39 #include <stdlib.h>
40
41 // Ubuntu Dapper requires memory pages to be marked as
42 // executable. Otherwise, OS raises an exception when executing code
43 // in that page.
44 #include <sys/types.h>  // mmap & munmap
45 #include <sys/mman.h>   // mmap & munmap
46 #include <sys/stat.h>   // open
47 #include <fcntl.h>      // open
48 #include <unistd.h>     // sysconf
49 #if defined(__GLIBC__) && !defined(__UCLIBC__)
50 #include <execinfo.h>   // backtrace, backtrace_symbols
51 #endif  // def __GLIBC__
52 #include <strings.h>    // index
53 #include <errno.h>
54 #include <stdarg.h>
55
56 #undef MAP_TYPE
57
58 #include "v8.h"
59
60 #include "platform.h"
61 #include "v8threads.h"
62 #include "vm-state-inl.h"
63
64
65 namespace v8 {
66 namespace internal {
67
68 // 0 is never a valid thread id on Linux since tids and pids share a
69 // name space and pid 0 is reserved (see man 2 kill).
70 static const pthread_t kNoThread = (pthread_t) 0;
71
72
73 double ceiling(double x) {
74   return ceil(x);
75 }
76
77
78 static Mutex* limit_mutex = NULL;
79
80
81 void OS::Setup() {
82   // Seed the random number generator. We preserve microsecond resolution.
83   uint64_t seed = Ticks() ^ (getpid() << 16);
84   srandom(static_cast<unsigned int>(seed));
85   limit_mutex = CreateMutex();
86
87 #ifdef __arm__
88   // When running on ARM hardware check that the EABI used by V8 and
89   // by the C code is the same.
90   bool hard_float = OS::ArmUsingHardFloat();
91   if (hard_float) {
92 #if !USE_EABI_HARDFLOAT
93     PrintF("ERROR: Binary compiled with -mfloat-abi=hard but without "
94            "-DUSE_EABI_HARDFLOAT\n");
95     exit(1);
96 #endif
97   } else {
98 #if USE_EABI_HARDFLOAT
99     PrintF("ERROR: Binary not compiled with -mfloat-abi=hard but with "
100            "-DUSE_EABI_HARDFLOAT\n");
101     exit(1);
102 #endif
103   }
104 #endif
105 }
106
107
108 uint64_t OS::CpuFeaturesImpliedByPlatform() {
109   return 0;  // Linux runs on anything.
110 }
111
112
113 #ifdef __arm__
114 static bool CPUInfoContainsString(const char * search_string) {
115   const char* file_name = "/proc/cpuinfo";
116   // This is written as a straight shot one pass parser
117   // and not using STL string and ifstream because,
118   // on Linux, it's reading from a (non-mmap-able)
119   // character special device.
120   FILE* f = NULL;
121   const char* what = search_string;
122
123   if (NULL == (f = fopen(file_name, "r")))
124     return false;
125
126   int k;
127   while (EOF != (k = fgetc(f))) {
128     if (k == *what) {
129       ++what;
130       while ((*what != '\0') && (*what == fgetc(f))) {
131         ++what;
132       }
133       if (*what == '\0') {
134         fclose(f);
135         return true;
136       } else {
137         what = search_string;
138       }
139     }
140   }
141   fclose(f);
142
143   // Did not find string in the proc file.
144   return false;
145 }
146
147
148 bool OS::ArmCpuHasFeature(CpuFeature feature) {
149   const char* search_string = NULL;
150   // Simple detection of VFP at runtime for Linux.
151   // It is based on /proc/cpuinfo, which reveals hardware configuration
152   // to user-space applications.  According to ARM (mid 2009), no similar
153   // facility is universally available on the ARM architectures,
154   // so it's up to individual OSes to provide such.
155   switch (feature) {
156     case VFP3:
157       search_string = "vfpv3";
158       break;
159     case ARMv7:
160       search_string = "ARMv7";
161       break;
162     default:
163       UNREACHABLE();
164   }
165
166   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")) {
177       return true;
178     }
179   }
180
181   return false;
182 }
183
184
185 // Simple helper function to detect whether the C code is compiled with
186 // option -mfloat-abi=hard. The register d0 is loaded with 1.0 and the register
187 // pair r0, r1 is loaded with 0.0. If -mfloat-abi=hard is pased to GCC then
188 // calling this will return 1.0 and otherwise 0.0.
189 static void ArmUsingHardFloatHelper() {
190   asm("mov r0, #0");
191 #if defined(__VFP_FP__) && !defined(__SOFTFP__)
192   // Load 0x3ff00000 into r1 using instructions available in both ARM
193   // and Thumb mode.
194   asm("mov r1, #3");
195   asm("mov r2, #255");
196   asm("lsl r1, r1, #8");
197   asm("orr r1, r1, r2");
198   asm("lsl r1, r1, #20");
199   // For vmov d0, r0, r1 use ARM mode.
200 #ifdef __thumb__
201   asm volatile(
202     "@   Enter ARM Mode  \n\t"
203     "    adr r3, 1f      \n\t"
204     "    bx  r3          \n\t"
205     "    .ALIGN 4        \n\t"
206     "    .ARM            \n"
207     "1:  vmov d0, r0, r1 \n\t"
208     "@   Enter THUMB Mode\n\t"
209     "    adr r3, 2f+1    \n\t"
210     "    bx  r3          \n\t"
211     "    .THUMB          \n"
212     "2:                  \n\t");
213 #else
214   asm("vmov d0, r0, r1");
215 #endif  // __thumb__
216 #endif  // defined(__VFP_FP__) && !defined(__SOFTFP__)
217   asm("mov r1, #0");
218 }
219
220
221 bool OS::ArmUsingHardFloat() {
222   // Cast helper function from returning void to returning double.
223   typedef double (*F)();
224   F f = FUNCTION_CAST<F>(FUNCTION_ADDR(ArmUsingHardFloatHelper));
225   return f() == 1.0;
226 }
227 #endif  // def __arm__
228
229
230 #ifdef __mips__
231 bool OS::MipsCpuHasFeature(CpuFeature feature) {
232   const char* search_string = NULL;
233   const char* file_name = "/proc/cpuinfo";
234   // Simple detection of FPU at runtime for Linux.
235   // It is based on /proc/cpuinfo, which reveals hardware configuration
236   // to user-space applications.  According to MIPS (early 2010), no similar
237   // facility is universally available on the MIPS architectures,
238   // so it's up to individual OSes to provide such.
239   //
240   // This is written as a straight shot one pass parser
241   // and not using STL string and ifstream because,
242   // on Linux, it's reading from a (non-mmap-able)
243   // character special device.
244
245   switch (feature) {
246     case FPU:
247       search_string = "FPU";
248       break;
249     default:
250       UNREACHABLE();
251   }
252
253   FILE* f = NULL;
254   const char* what = search_string;
255
256   if (NULL == (f = fopen(file_name, "r")))
257     return false;
258
259   int k;
260   while (EOF != (k = fgetc(f))) {
261     if (k == *what) {
262       ++what;
263       while ((*what != '\0') && (*what == fgetc(f))) {
264         ++what;
265       }
266       if (*what == '\0') {
267         fclose(f);
268         return true;
269       } else {
270         what = search_string;
271       }
272     }
273   }
274   fclose(f);
275
276   // Did not find string in the proc file.
277   return false;
278 }
279 #endif  // def __mips__
280
281
282 int OS::ActivationFrameAlignment() {
283 #ifdef V8_TARGET_ARCH_ARM
284   // On EABI ARM targets this is required for fp correctness in the
285   // runtime system.
286   return 8;
287 #elif V8_TARGET_ARCH_MIPS
288   return 8;
289 #endif
290   // With gcc 4.4 the tree vectorization optimizer can generate code
291   // that requires 16 byte alignment such as movdqa on x86.
292   return 16;
293 }
294
295
296 void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) {
297 #if (defined(V8_TARGET_ARCH_ARM) && defined(__arm__)) || \
298     (defined(V8_TARGET_ARCH_MIPS) && defined(__mips__))
299   // Only use on ARM or MIPS hardware.
300   MemoryBarrier();
301 #else
302   __asm__ __volatile__("" : : : "memory");
303   // An x86 store acts as a release barrier.
304 #endif
305   *ptr = value;
306 }
307
308
309 const char* OS::LocalTimezone(double time) {
310   if (isnan(time)) return "";
311   time_t tv = static_cast<time_t>(floor(time/msPerSecond));
312   struct tm* t = localtime(&tv);
313   if (NULL == t) return "";
314   return t->tm_zone;
315 }
316
317
318 double OS::LocalTimeOffset() {
319   time_t tv = time(NULL);
320   struct tm* t = localtime(&tv);
321   // tm_gmtoff includes any daylight savings offset, so subtract it.
322   return static_cast<double>(t->tm_gmtoff * msPerSecond -
323                              (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
324 }
325
326
327 // We keep the lowest and highest addresses mapped as a quick way of
328 // determining that pointers are outside the heap (used mostly in assertions
329 // and verification).  The estimate is conservative, ie, not all addresses in
330 // 'allocated' space are actually allocated to our heap.  The range is
331 // [lowest, highest), inclusive on the low and and exclusive on the high end.
332 static void* lowest_ever_allocated = reinterpret_cast<void*>(-1);
333 static void* highest_ever_allocated = reinterpret_cast<void*>(0);
334
335
336 static void UpdateAllocatedSpaceLimits(void* address, int size) {
337   ASSERT(limit_mutex != NULL);
338   ScopedLock lock(limit_mutex);
339
340   lowest_ever_allocated = Min(lowest_ever_allocated, address);
341   highest_ever_allocated =
342       Max(highest_ever_allocated,
343           reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size));
344 }
345
346
347 bool OS::IsOutsideAllocatedSpace(void* address) {
348   return address < lowest_ever_allocated || address >= highest_ever_allocated;
349 }
350
351
352 size_t OS::AllocateAlignment() {
353   return sysconf(_SC_PAGESIZE);
354 }
355
356
357 void* OS::Allocate(const size_t requested,
358                    size_t* allocated,
359                    bool is_executable) {
360   const size_t msize = RoundUp(requested, AllocateAlignment());
361   int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
362   void* addr = OS::GetRandomMmapAddr();
363   void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
364   if (mbase == MAP_FAILED) {
365     LOG(i::Isolate::Current(),
366         StringEvent("OS::Allocate", "mmap failed"));
367     return NULL;
368   }
369   *allocated = msize;
370   UpdateAllocatedSpaceLimits(mbase, msize);
371   return mbase;
372 }
373
374
375 void OS::Free(void* address, const size_t size) {
376   // TODO(1240712): munmap has a return value which is ignored here.
377   int result = munmap(address, size);
378   USE(result);
379   ASSERT(result == 0);
380 }
381
382
383 void OS::Sleep(int milliseconds) {
384   unsigned int ms = static_cast<unsigned int>(milliseconds);
385   usleep(1000 * ms);
386 }
387
388
389 void OS::Abort() {
390   // Redirect to std abort to signal abnormal program termination.
391   abort();
392 }
393
394
395 void OS::DebugBreak() {
396 // TODO(lrn): Introduce processor define for runtime system (!= V8_ARCH_x,
397 //  which is the architecture of generated code).
398 #if (defined(__arm__) || defined(__thumb__))
399 # if defined(CAN_USE_ARMV5_INSTRUCTIONS)
400   asm("bkpt 0");
401 # endif
402 #elif defined(__mips__)
403   asm("break");
404 #else
405   asm("int $3");
406 #endif
407 }
408
409
410 class PosixMemoryMappedFile : public OS::MemoryMappedFile {
411  public:
412   PosixMemoryMappedFile(FILE* file, void* memory, int size)
413     : file_(file), memory_(memory), size_(size) { }
414   virtual ~PosixMemoryMappedFile();
415   virtual void* memory() { return memory_; }
416   virtual int size() { return size_; }
417  private:
418   FILE* file_;
419   void* memory_;
420   int size_;
421 };
422
423
424 OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
425   FILE* file = fopen(name, "r+");
426   if (file == NULL) return NULL;
427
428   fseek(file, 0, SEEK_END);
429   int size = ftell(file);
430
431   void* memory =
432       mmap(OS::GetRandomMmapAddr(),
433            size,
434            PROT_READ | PROT_WRITE,
435            MAP_SHARED,
436            fileno(file),
437            0);
438   return new PosixMemoryMappedFile(file, memory, size);
439 }
440
441
442 OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
443     void* initial) {
444   FILE* file = fopen(name, "w+");
445   if (file == NULL) return NULL;
446   int result = fwrite(initial, size, 1, file);
447   if (result < 1) {
448     fclose(file);
449     return NULL;
450   }
451   void* memory =
452       mmap(OS::GetRandomMmapAddr(),
453            size,
454            PROT_READ | PROT_WRITE,
455            MAP_SHARED,
456            fileno(file),
457            0);
458   return new PosixMemoryMappedFile(file, memory, size);
459 }
460
461
462 PosixMemoryMappedFile::~PosixMemoryMappedFile() {
463   if (memory_) OS::Free(memory_, size_);
464   fclose(file_);
465 }
466
467
468 void OS::LogSharedLibraryAddresses() {
469   // This function assumes that the layout of the file is as follows:
470   // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
471   // If we encounter an unexpected situation we abort scanning further entries.
472   FILE* fp = fopen("/proc/self/maps", "r");
473   if (fp == NULL) return;
474
475   // Allocate enough room to be able to store a full file name.
476   const int kLibNameLen = FILENAME_MAX + 1;
477   char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
478
479   i::Isolate* isolate = ISOLATE;
480   // This loop will terminate once the scanning hits an EOF.
481   while (true) {
482     uintptr_t start, end;
483     char attr_r, attr_w, attr_x, attr_p;
484     // Parse the addresses and permission bits at the beginning of the line.
485     if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
486     if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break;
487
488     int c;
489     if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
490       // Found a read-only executable entry. Skip characters until we reach
491       // the beginning of the filename or the end of the line.
492       do {
493         c = getc(fp);
494       } while ((c != EOF) && (c != '\n') && (c != '/'));
495       if (c == EOF) break;  // EOF: Was unexpected, just exit.
496
497       // Process the filename if found.
498       if (c == '/') {
499         ungetc(c, fp);  // Push the '/' back into the stream to be read below.
500
501         // Read to the end of the line. Exit if the read fails.
502         if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
503
504         // Drop the newline character read by fgets. We do not need to check
505         // for a zero-length string because we know that we at least read the
506         // '/' character.
507         lib_name[strlen(lib_name) - 1] = '\0';
508       } else {
509         // No library name found, just record the raw address range.
510         snprintf(lib_name, kLibNameLen,
511                  "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
512       }
513       LOG(isolate, SharedLibraryEvent(lib_name, start, end));
514     } else {
515       // Entry not describing executable data. Skip to end of line to setup
516       // reading the next entry.
517       do {
518         c = getc(fp);
519       } while ((c != EOF) && (c != '\n'));
520       if (c == EOF) break;
521     }
522   }
523   free(lib_name);
524   fclose(fp);
525 }
526
527
528 static const char kGCFakeMmap[] = "/tmp/__v8_gc__";
529
530
531 void OS::SignalCodeMovingGC() {
532   // Support for ll_prof.py.
533   //
534   // The Linux profiler built into the kernel logs all mmap's with
535   // PROT_EXEC so that analysis tools can properly attribute ticks. We
536   // do a mmap with a name known by ll_prof.py and immediately munmap
537   // it. This injects a GC marker into the stream of events generated
538   // by the kernel and allows us to synchronize V8 code log and the
539   // kernel log.
540   int size = sysconf(_SC_PAGESIZE);
541   FILE* f = fopen(kGCFakeMmap, "w+");
542   void* addr = mmap(OS::GetRandomMmapAddr(),
543                     size,
544                     PROT_READ | PROT_EXEC,
545                     MAP_PRIVATE,
546                     fileno(f),
547                     0);
548   ASSERT(addr != MAP_FAILED);
549   OS::Free(addr, size);
550   fclose(f);
551 }
552
553
554 int OS::StackWalk(Vector<OS::StackFrame> frames) {
555   // backtrace is a glibc extension.
556 #if defined(__GLIBC__) && !defined(__UCLIBC__)
557   int frames_size = frames.length();
558   ScopedVector<void*> addresses(frames_size);
559
560   int frames_count = backtrace(addresses.start(), frames_size);
561
562   char** symbols = backtrace_symbols(addresses.start(), frames_count);
563   if (symbols == NULL) {
564     return kStackWalkError;
565   }
566
567   for (int i = 0; i < frames_count; i++) {
568     frames[i].address = addresses[i];
569     // Format a text representation of the frame based on the information
570     // available.
571     SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen),
572              "%s",
573              symbols[i]);
574     // Make sure line termination is in place.
575     frames[i].text[kStackWalkMaxTextLen - 1] = '\0';
576   }
577
578   free(symbols);
579
580   return frames_count;
581 #else  // ndef __GLIBC__
582   return 0;
583 #endif  // ndef __GLIBC__
584 }
585
586
587 // Constants used for mmap.
588 static const int kMmapFd = -1;
589 static const int kMmapFdOffset = 0;
590
591 VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
592
593 VirtualMemory::VirtualMemory(size_t size) {
594   address_ = ReserveRegion(size);
595   size_ = size;
596 }
597
598
599 VirtualMemory::VirtualMemory(size_t size, size_t alignment)
600     : address_(NULL), size_(0) {
601   ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
602   size_t request_size = RoundUp(size + alignment,
603                                 static_cast<intptr_t>(OS::AllocateAlignment()));
604   void* reservation = mmap(OS::GetRandomMmapAddr(),
605                            request_size,
606                            PROT_NONE,
607                            MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
608                            kMmapFd,
609                            kMmapFdOffset);
610   if (reservation == MAP_FAILED) return;
611
612   Address base = static_cast<Address>(reservation);
613   Address aligned_base = RoundUp(base, alignment);
614   ASSERT_LE(base, aligned_base);
615
616   // Unmap extra memory reserved before and after the desired block.
617   if (aligned_base != base) {
618     size_t prefix_size = static_cast<size_t>(aligned_base - base);
619     OS::Free(base, prefix_size);
620     request_size -= prefix_size;
621   }
622
623   size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
624   ASSERT_LE(aligned_size, request_size);
625
626   if (aligned_size != request_size) {
627     size_t suffix_size = request_size - aligned_size;
628     OS::Free(aligned_base + aligned_size, suffix_size);
629     request_size -= suffix_size;
630   }
631
632   ASSERT(aligned_size == request_size);
633
634   address_ = static_cast<void*>(aligned_base);
635   size_ = aligned_size;
636 }
637
638
639 VirtualMemory::~VirtualMemory() {
640   if (IsReserved()) {
641     bool result = ReleaseRegion(address(), size());
642     ASSERT(result);
643     USE(result);
644   }
645 }
646
647
648 bool VirtualMemory::IsReserved() {
649   return address_ != NULL;
650 }
651
652
653 void VirtualMemory::Reset() {
654   address_ = NULL;
655   size_ = 0;
656 }
657
658
659 bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
660   return CommitRegion(address, size, is_executable);
661 }
662
663
664 bool VirtualMemory::Uncommit(void* address, size_t size) {
665   return UncommitRegion(address, size);
666 }
667
668
669 void* VirtualMemory::ReserveRegion(size_t size) {
670   void* result = mmap(OS::GetRandomMmapAddr(),
671                       size,
672                       PROT_NONE,
673                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
674                       kMmapFd,
675                       kMmapFdOffset);
676
677   if (result == MAP_FAILED) return NULL;
678
679   return result;
680 }
681
682
683 bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
684   int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
685   if (MAP_FAILED == mmap(base,
686                          size,
687                          prot,
688                          MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
689                          kMmapFd,
690                          kMmapFdOffset)) {
691     return false;
692   }
693
694   UpdateAllocatedSpaceLimits(base, size);
695   return true;
696 }
697
698
699 bool VirtualMemory::UncommitRegion(void* base, size_t size) {
700   return mmap(base,
701               size,
702               PROT_NONE,
703               MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED,
704               kMmapFd,
705               kMmapFdOffset) != MAP_FAILED;
706 }
707
708
709 bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
710   return munmap(base, size) == 0;
711 }
712
713
714 class Thread::PlatformData : public Malloced {
715  public:
716   PlatformData() : thread_(kNoThread) {}
717
718   pthread_t thread_;  // Thread handle for pthread.
719 };
720
721 Thread::Thread(const Options& options)
722     : data_(new PlatformData()),
723       stack_size_(options.stack_size) {
724   set_name(options.name);
725 }
726
727
728 Thread::Thread(const char* name)
729     : data_(new PlatformData()),
730       stack_size_(0) {
731   set_name(name);
732 }
733
734
735 Thread::~Thread() {
736   delete data_;
737 }
738
739
740 static void* ThreadEntry(void* arg) {
741   Thread* thread = reinterpret_cast<Thread*>(arg);
742   // This is also initialized by the first argument to pthread_create() but we
743   // don't know which thread will run first (the original thread or the new
744   // one) so we initialize it here too.
745 #ifdef PR_SET_NAME
746   prctl(PR_SET_NAME,
747         reinterpret_cast<unsigned long>(thread->name()),  // NOLINT
748         0, 0, 0);
749 #endif
750   thread->data()->thread_ = pthread_self();
751   ASSERT(thread->data()->thread_ != kNoThread);
752   thread->Run();
753   return NULL;
754 }
755
756
757 void Thread::set_name(const char* name) {
758   strncpy(name_, name, sizeof(name_));
759   name_[sizeof(name_) - 1] = '\0';
760 }
761
762
763 void Thread::Start() {
764   pthread_attr_t* attr_ptr = NULL;
765   pthread_attr_t attr;
766   if (stack_size_ > 0) {
767     pthread_attr_init(&attr);
768     pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_));
769     attr_ptr = &attr;
770   }
771   pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this);
772   ASSERT(data_->thread_ != kNoThread);
773 }
774
775
776 void Thread::Join() {
777   pthread_join(data_->thread_, NULL);
778 }
779
780
781 Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
782   pthread_key_t key;
783   int result = pthread_key_create(&key, NULL);
784   USE(result);
785   ASSERT(result == 0);
786   return static_cast<LocalStorageKey>(key);
787 }
788
789
790 void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
791   pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
792   int result = pthread_key_delete(pthread_key);
793   USE(result);
794   ASSERT(result == 0);
795 }
796
797
798 void* Thread::GetThreadLocal(LocalStorageKey key) {
799   pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
800   return pthread_getspecific(pthread_key);
801 }
802
803
804 void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
805   pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
806   pthread_setspecific(pthread_key, value);
807 }
808
809
810 void Thread::YieldCPU() {
811   sched_yield();
812 }
813
814
815 class LinuxMutex : public Mutex {
816  public:
817   LinuxMutex() {
818     pthread_mutexattr_t attrs;
819     int result = pthread_mutexattr_init(&attrs);
820     ASSERT(result == 0);
821     result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
822     ASSERT(result == 0);
823     result = pthread_mutex_init(&mutex_, &attrs);
824     ASSERT(result == 0);
825     USE(result);
826   }
827
828   virtual ~LinuxMutex() { pthread_mutex_destroy(&mutex_); }
829
830   virtual int Lock() {
831     int result = pthread_mutex_lock(&mutex_);
832     return result;
833   }
834
835   virtual int Unlock() {
836     int result = pthread_mutex_unlock(&mutex_);
837     return result;
838   }
839
840   virtual bool TryLock() {
841     int result = pthread_mutex_trylock(&mutex_);
842     // Return false if the lock is busy and locking failed.
843     if (result == EBUSY) {
844       return false;
845     }
846     ASSERT(result == 0);  // Verify no other errors.
847     return true;
848   }
849
850  private:
851   pthread_mutex_t mutex_;   // Pthread mutex for POSIX platforms.
852 };
853
854
855 Mutex* OS::CreateMutex() {
856   return new LinuxMutex();
857 }
858
859
860 class LinuxSemaphore : public Semaphore {
861  public:
862   explicit LinuxSemaphore(int count) {  sem_init(&sem_, 0, count); }
863   virtual ~LinuxSemaphore() { sem_destroy(&sem_); }
864
865   virtual void Wait();
866   virtual bool Wait(int timeout);
867   virtual void Signal() { sem_post(&sem_); }
868  private:
869   sem_t sem_;
870 };
871
872
873 void LinuxSemaphore::Wait() {
874   while (true) {
875     int result = sem_wait(&sem_);
876     if (result == 0) return;  // Successfully got semaphore.
877     CHECK(result == -1 && errno == EINTR);  // Signal caused spurious wakeup.
878   }
879 }
880
881
882 #ifndef TIMEVAL_TO_TIMESPEC
883 #define TIMEVAL_TO_TIMESPEC(tv, ts) do {                            \
884     (ts)->tv_sec = (tv)->tv_sec;                                    \
885     (ts)->tv_nsec = (tv)->tv_usec * 1000;                           \
886 } while (false)
887 #endif
888
889
890 bool LinuxSemaphore::Wait(int timeout) {
891   const long kOneSecondMicros = 1000000;  // NOLINT
892
893   // Split timeout into second and nanosecond parts.
894   struct timeval delta;
895   delta.tv_usec = timeout % kOneSecondMicros;
896   delta.tv_sec = timeout / kOneSecondMicros;
897
898   struct timeval current_time;
899   // Get the current time.
900   if (gettimeofday(&current_time, NULL) == -1) {
901     return false;
902   }
903
904   // Calculate time for end of timeout.
905   struct timeval end_time;
906   timeradd(&current_time, &delta, &end_time);
907
908   struct timespec ts;
909   TIMEVAL_TO_TIMESPEC(&end_time, &ts);
910   // Wait for semaphore signalled or timeout.
911   while (true) {
912     int result = sem_timedwait(&sem_, &ts);
913     if (result == 0) return true;  // Successfully got semaphore.
914     if (result > 0) {
915       // For glibc prior to 2.3.4 sem_timedwait returns the error instead of -1.
916       errno = result;
917       result = -1;
918     }
919     if (result == -1 && errno == ETIMEDOUT) return false;  // Timeout.
920     CHECK(result == -1 && errno == EINTR);  // Signal caused spurious wakeup.
921   }
922 }
923
924
925 Semaphore* OS::CreateSemaphore(int count) {
926   return new LinuxSemaphore(count);
927 }
928
929
930 #if !defined(__GLIBC__) && (defined(__arm__) || defined(__thumb__))
931 // Android runs a fairly new Linux kernel, so signal info is there,
932 // but the C library doesn't have the structs defined.
933
934 struct sigcontext {
935   uint32_t trap_no;
936   uint32_t error_code;
937   uint32_t oldmask;
938   uint32_t gregs[16];
939   uint32_t arm_cpsr;
940   uint32_t fault_address;
941 };
942 typedef uint32_t __sigset_t;
943 typedef struct sigcontext mcontext_t;
944 typedef struct ucontext {
945   uint32_t uc_flags;
946   struct ucontext* uc_link;
947   stack_t uc_stack;
948   mcontext_t uc_mcontext;
949   __sigset_t uc_sigmask;
950 } ucontext_t;
951 enum ArmRegisters {R15 = 15, R13 = 13, R11 = 11};
952
953 #endif
954
955
956 static int GetThreadID() {
957   // Glibc doesn't provide a wrapper for gettid(2).
958 #if defined(ANDROID)
959   return syscall(__NR_gettid);
960 #else
961   return syscall(SYS_gettid);
962 #endif
963 }
964
965
966 static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
967 #ifndef V8_HOST_ARCH_MIPS
968   USE(info);
969   if (signal != SIGPROF) return;
970   Isolate* isolate = Isolate::UncheckedCurrent();
971   if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) {
972     // We require a fully initialized and entered isolate.
973     return;
974   }
975   if (v8::Locker::IsActive() &&
976       !isolate->thread_manager()->IsLockedByCurrentThread()) {
977     return;
978   }
979
980   Sampler* sampler = isolate->logger()->sampler();
981   if (sampler == NULL || !sampler->IsActive()) return;
982
983   TickSample sample_obj;
984   TickSample* sample = CpuProfiler::TickSampleEvent(isolate);
985   if (sample == NULL) sample = &sample_obj;
986
987   // Extracting the sample from the context is extremely machine dependent.
988   ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
989   mcontext_t& mcontext = ucontext->uc_mcontext;
990   sample->state = isolate->current_vm_state();
991 #if V8_HOST_ARCH_IA32
992   sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_EIP]);
993   sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_ESP]);
994   sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_EBP]);
995 #elif V8_HOST_ARCH_X64
996   sample->pc = reinterpret_cast<Address>(mcontext.gregs[REG_RIP]);
997   sample->sp = reinterpret_cast<Address>(mcontext.gregs[REG_RSP]);
998   sample->fp = reinterpret_cast<Address>(mcontext.gregs[REG_RBP]);
999 #elif V8_HOST_ARCH_ARM
1000 // An undefined macro evaluates to 0, so this applies to Android's Bionic also.
1001 #if (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 3))
1002   sample->pc = reinterpret_cast<Address>(mcontext.gregs[R15]);
1003   sample->sp = reinterpret_cast<Address>(mcontext.gregs[R13]);
1004   sample->fp = reinterpret_cast<Address>(mcontext.gregs[R11]);
1005 #else
1006   sample->pc = reinterpret_cast<Address>(mcontext.arm_pc);
1007   sample->sp = reinterpret_cast<Address>(mcontext.arm_sp);
1008   sample->fp = reinterpret_cast<Address>(mcontext.arm_fp);
1009 #endif
1010 #elif V8_HOST_ARCH_MIPS
1011   sample.pc = reinterpret_cast<Address>(mcontext.pc);
1012   sample.sp = reinterpret_cast<Address>(mcontext.gregs[29]);
1013   sample.fp = reinterpret_cast<Address>(mcontext.gregs[30]);
1014 #endif
1015   sampler->SampleStack(sample);
1016   sampler->Tick(sample);
1017 #endif
1018 }
1019
1020
1021 class Sampler::PlatformData : public Malloced {
1022  public:
1023   PlatformData() : vm_tid_(GetThreadID()) {}
1024
1025   int vm_tid() const { return vm_tid_; }
1026
1027  private:
1028   const int vm_tid_;
1029 };
1030
1031
1032 class SignalSender : public Thread {
1033  public:
1034   enum SleepInterval {
1035     HALF_INTERVAL,
1036     FULL_INTERVAL
1037   };
1038
1039   explicit SignalSender(int interval)
1040       : Thread("SignalSender"),
1041         vm_tgid_(getpid()),
1042         interval_(interval) {}
1043
1044   static void InstallSignalHandler() {
1045     struct sigaction sa;
1046     sa.sa_sigaction = ProfilerSignalHandler;
1047     sigemptyset(&sa.sa_mask);
1048     sa.sa_flags = SA_RESTART | SA_SIGINFO;
1049     signal_handler_installed_ =
1050         (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0);
1051   }
1052
1053   static void RestoreSignalHandler() {
1054     if (signal_handler_installed_) {
1055       sigaction(SIGPROF, &old_signal_handler_, 0);
1056       signal_handler_installed_ = false;
1057     }
1058   }
1059
1060   static void AddActiveSampler(Sampler* sampler) {
1061     ScopedLock lock(mutex_);
1062     SamplerRegistry::AddActiveSampler(sampler);
1063     if (instance_ == NULL) {
1064       // Start a thread that will send SIGPROF signal to VM threads,
1065       // when CPU profiling will be enabled.
1066       instance_ = new SignalSender(sampler->interval());
1067       instance_->Start();
1068     } else {
1069       ASSERT(instance_->interval_ == sampler->interval());
1070     }
1071   }
1072
1073   static void RemoveActiveSampler(Sampler* sampler) {
1074     ScopedLock lock(mutex_);
1075     SamplerRegistry::RemoveActiveSampler(sampler);
1076     if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) {
1077       RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_);
1078       delete instance_;
1079       instance_ = NULL;
1080       RestoreSignalHandler();
1081     }
1082   }
1083
1084   // Implement Thread::Run().
1085   virtual void Run() {
1086     SamplerRegistry::State state;
1087     while ((state = SamplerRegistry::GetState()) !=
1088            SamplerRegistry::HAS_NO_SAMPLERS) {
1089       bool cpu_profiling_enabled =
1090           (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS);
1091       bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled();
1092       if (cpu_profiling_enabled && !signal_handler_installed_) {
1093         InstallSignalHandler();
1094       } else if (!cpu_profiling_enabled && signal_handler_installed_) {
1095         RestoreSignalHandler();
1096       }
1097       // When CPU profiling is enabled both JavaScript and C++ code is
1098       // profiled. We must not suspend.
1099       if (!cpu_profiling_enabled) {
1100         if (rate_limiter_.SuspendIfNecessary()) continue;
1101       }
1102       if (cpu_profiling_enabled && runtime_profiler_enabled) {
1103         if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) {
1104           return;
1105         }
1106         Sleep(HALF_INTERVAL);
1107         if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) {
1108           return;
1109         }
1110         Sleep(HALF_INTERVAL);
1111       } else {
1112         if (cpu_profiling_enabled) {
1113           if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile,
1114                                                       this)) {
1115             return;
1116           }
1117         }
1118         if (runtime_profiler_enabled) {
1119           if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile,
1120                                                       NULL)) {
1121             return;
1122           }
1123         }
1124         Sleep(FULL_INTERVAL);
1125       }
1126     }
1127   }
1128
1129   static void DoCpuProfile(Sampler* sampler, void* raw_sender) {
1130     if (!sampler->IsProfiling()) return;
1131     SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender);
1132     sender->SendProfilingSignal(sampler->platform_data()->vm_tid());
1133   }
1134
1135   static void DoRuntimeProfile(Sampler* sampler, void* ignored) {
1136     if (!sampler->isolate()->IsInitialized()) return;
1137     sampler->isolate()->runtime_profiler()->NotifyTick();
1138   }
1139
1140   void SendProfilingSignal(int tid) {
1141     if (!signal_handler_installed_) return;
1142     // Glibc doesn't provide a wrapper for tgkill(2).
1143 #if defined(ANDROID)
1144     syscall(__NR_tgkill, vm_tgid_, tid, SIGPROF);
1145 #else
1146     syscall(SYS_tgkill, vm_tgid_, tid, SIGPROF);
1147 #endif
1148   }
1149
1150   void Sleep(SleepInterval full_or_half) {
1151     // Convert ms to us and subtract 100 us to compensate delays
1152     // occuring during signal delivery.
1153     useconds_t interval = interval_ * 1000 - 100;
1154     if (full_or_half == HALF_INTERVAL) interval /= 2;
1155     int result = usleep(interval);
1156 #ifdef DEBUG
1157     if (result != 0 && errno != EINTR) {
1158       fprintf(stderr,
1159               "SignalSender usleep error; interval = %u, errno = %d\n",
1160               interval,
1161               errno);
1162       ASSERT(result == 0 || errno == EINTR);
1163     }
1164 #endif
1165     USE(result);
1166   }
1167
1168   const int vm_tgid_;
1169   const int interval_;
1170   RuntimeProfilerRateLimiter rate_limiter_;
1171
1172   // Protects the process wide state below.
1173   static Mutex* mutex_;
1174   static SignalSender* instance_;
1175   static bool signal_handler_installed_;
1176   static struct sigaction old_signal_handler_;
1177
1178   DISALLOW_COPY_AND_ASSIGN(SignalSender);
1179 };
1180
1181
1182 Mutex* SignalSender::mutex_ = OS::CreateMutex();
1183 SignalSender* SignalSender::instance_ = NULL;
1184 struct sigaction SignalSender::old_signal_handler_;
1185 bool SignalSender::signal_handler_installed_ = false;
1186
1187
1188 Sampler::Sampler(Isolate* isolate, int interval)
1189     : isolate_(isolate),
1190       interval_(interval),
1191       profiling_(false),
1192       active_(false),
1193       samples_taken_(0) {
1194   data_ = new PlatformData;
1195 }
1196
1197
1198 Sampler::~Sampler() {
1199   ASSERT(!IsActive());
1200   delete data_;
1201 }
1202
1203
1204 void Sampler::Start() {
1205   ASSERT(!IsActive());
1206   SetActive(true);
1207   SignalSender::AddActiveSampler(this);
1208 }
1209
1210
1211 void Sampler::Stop() {
1212   ASSERT(IsActive());
1213   SignalSender::RemoveActiveSampler(this);
1214   SetActive(false);
1215 }
1216
1217
1218 } }  // namespace v8::internal